Metadata-Version: 2.5
Name: atmorouter
Version: 0.1.0
Summary: Small Python client for the AtmoRouter OpenAI-compatible API (sync + async, streaming, model pricing helpers).
Project-URL: Homepage, https://atmorouter.dev
Project-URL: Documentation, https://atmorouter.dev/docs
Project-URL: Source, https://github.com/atmorouterdev/atmorouter-python
Project-URL: Issues, https://github.com/atmorouterdev/atmorouter-python/issues
Author-email: AtmoRouter <admin@atmorouter.dev>
License-Expression: MIT
License-File: LICENSE
Keywords: api-client,atmorouter,chat-completions,llm,openai
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: httpx<1,>=0.24
Provides-Extra: dev
Requires-Dist: build; extra == 'dev'
Requires-Dist: openai>=1; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.21; extra == 'dev'
Requires-Dist: pytest>=7; extra == 'dev'
Requires-Dist: twine; extra == 'dev'
Description-Content-Type: text/markdown

# atmorouter

Small Python client for the [AtmoRouter](https://atmorouter.dev) OpenAI-compatible API. Sync and async, built on `httpx`, with streaming and cost helpers.

- Base URL: `https://atmorouter.dev/v1`
- Docs: https://atmorouter.dev/docs
- Source: https://github.com/atmorouterdev/atmorouter-python
- License: MIT
- Python 3.9+

## Install

```bash
pip install atmorouter
```

The only runtime dependency is `httpx`. Get an API key at https://atmorouter.dev and export it:

```bash
export ATMOROUTER_API_KEY="your-key"
```

The key can also be passed as `AtmoRouter(api_key="your-key")`. The base URL can be overridden with `base_url=` or the `ATMOROUTER_BASE_URL` environment variable.

## Quickstart

```python
from atmorouter import AtmoRouter

client = AtmoRouter()  # reads ATMOROUTER_API_KEY
r = client.chat.completions.create(
    model="zai/glm-5.4",
    messages=[{"role": "user", "content": "Say hello in one short sentence."}],
    max_tokens=200,
)
print(r["choices"][0]["message"]["content"])
print("cost (USD):", r.get("atmorouter_cost"))
```

`create` returns the parsed JSON response as a dict. When the API sends an `X-Atmorouter-Cost` header, its value is added to the dict as `atmorouter_cost` (USD). That is the amount actually charged for the request.

Named parameters: `model`, `messages`, `stream`, `temperature`, `max_tokens`, `top_p`, `stop`, `tools`, `tool_choice`, `response_format`. Any other keyword argument is passed through in the request body; `None` values are dropped.

Both clients work as context managers (`with AtmoRouter() as client:` / `async with AsyncAtmoRouter() as client:`), or call `close()` / `aclose()` yourself.

## Streaming

Pass `stream=True` to get an iterator of SSE chunks (dicts). The request sets `stream_options.include_usage`, so the final chunk carries `usage`, including `usage["cost"]` in USD.

```python
from atmorouter import AtmoRouter

client = AtmoRouter()
for chunk in client.chat.completions.create(
    model="zai/glm-5.4",
    messages=[{"role": "user", "content": "Count from 1 to 5."}],
    max_tokens=300,
    stream=True,
):
    if chunk.get("choices"):
        print(chunk["choices"][0]["delta"].get("content") or "", end="", flush=True)
    elif chunk.get("usage"):
        print("\ncost (USD):", chunk["usage"].get("cost"))
```

The stream closes itself when the iterator finishes; it also supports `with stream:` / `async with stream:`. The async client returns `AsyncStream` with the same behaviour (`async for chunk in ...`).

## Async

```python
import asyncio
from atmorouter import AsyncAtmoRouter

async def main() -> None:
    async with AsyncAtmoRouter() as client:
        r = await client.chat.completions.create(
            model="grok/grok-4.6",
            messages=[{"role": "user", "content": "Name one prime number."}],
            max_tokens=200,
        )
        print(r["choices"][0]["message"]["content"])

asyncio.run(main())
```

`AsyncAtmoRouter` has the same surface as `AtmoRouter`: `chat.completions.create(...)`, `list_models()`, `get_model()`.

## Models and cost estimates

`list_models()` returns the live catalog from `GET /v1/models`. Each entry carries a `pricing` object in USD per 1M tokens (`input`, `output`, and optionally `cached_input`). `estimate_cost` computes an estimate from those rates.

```python
from atmorouter import AtmoRouter, estimate_cost

with AtmoRouter() as client:
    models = client.list_models()
    for m in models:
        if m["id"] in ("zai/glm-5.4", "ds/deepseek-flash", "grok/grok-4.6"):
            c = estimate_cost(m, input_tokens=2000, output_tokens=500)
            print(f'{m["id"]}: ~${c:.6f} for 2000 in / 500 out')
```

`estimate_cost(model, input_tokens, output_tokens, cached_input_tokens=0)` returns USD, or `None` if the model entry has no pricing. `cached_input_tokens` is the portion of `input_tokens` billed at the cached rate.

The estimate is only a quick calculation from the listed rates. The amount actually charged is what the API reports: `atmorouter_cost` on a non-streaming response, or `usage.cost` on the final chunk of a stream.

`get_model(model_id)` returns a single catalog entry by id, or `None`.

## Errors and retries

All exceptions subclass `AtmoRouterError`:

| Class | Raised when |
|---|---|
| `APIConnectionError` | No HTTP response (network error, timeout) |
| `APIStatusError` | Base class for the below; has `status_code`, `body`, `request_id` |
| `AuthenticationError` | 401 or 403 |
| `RateLimitError` | 429 |
| `BadRequestError` | other 4xx |
| `InternalServerError` | 5xx |

Requests are retried automatically (default `max_retries=2`) on connection errors and on status 408, 409, 429, 500, 502, 503, 504. Backoff is exponential (0.5 s, 1 s, ...) capped at 8 s, or the server's `Retry-After` header capped at 30 s. Set `max_retries=0` to disable.

```python
from atmorouter import AtmoRouter, RateLimitError

client = AtmoRouter(timeout=120.0, max_retries=3)
try:
    r = client.chat.completions.create(model="zai/glm-5.4", messages=[{"role": "user", "content": "Hi"}])
except RateLimitError as e:
    print(e.status_code, e.message, e.request_id)
```

Default timeout is 600 s. `default_headers=` adds headers to every request; `http_client=` supplies your own `httpx.Client` / `httpx.AsyncClient`.

## Use with the official openai package

The API is OpenAI-compatible, so the official `openai` package works by pointing `base_url` at AtmoRouter:

```python
import os
from openai import OpenAI

client = OpenAI(base_url="https://atmorouter.dev/v1", api_key=os.environ["ATMOROUTER_API_KEY"])
r = client.chat.completions.create(
    model="zai/glm-5.4",
    messages=[{"role": "user", "content": "Say hi."}],
    max_tokens=200,
)
print(r.choices[0].message.content)
```

`openai` is not a dependency of this package; install it separately (`pip install openai`).

## Examples

Runnable scripts live in [`examples/`](https://github.com/atmorouterdev/atmorouter-python): `chat.py`, `stream.py`, `async_chat.py`, `models_and_cost.py`, `with_openai_package.py`.
