Skip to main content

TokenRouter Python SDK

Official Python client for TokenRouter — the OpenAI-compatible AI gateway. Python 3.9+, one dependency (httpx).

pip install tokenrouter

Quickstart

from tokenrouter import TokenRouter

client = TokenRouter()  # reads TOKENROUTER_API_KEY (and TOKENROUTER_BASE_URL)

completion = client.chat.completions.create(
    model="auto",  # or "openai/gpt-5-mini", "claude-sonnet-4-5", "auto:cost", ...
    messages=[{"role": "user", "content": "Hello!"}],
)
print(completion.choices[0].message.content)
print(completion.usage.total_tokens)      # attribute access
print(completion["usage"]["total_tokens"])  # dict access
raw = completion.model_dump()             # plain dict

Migrating from the OpenAI SDK

TokenRouter speaks the OpenAI wire protocol, so migration is just changing the import and the key:

- from openai import OpenAI
- client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
+ from tokenrouter import TokenRouter
+ client = TokenRouter(api_key=os.environ["TOKENROUTER_API_KEY"])

Or keep using the openai package and just point it at the gateway:

from openai import OpenAI
client = OpenAI(
    api_key=os.environ["TOKENROUTER_API_KEY"],
    base_url="https://api.tokenrouter.io/v1",
)

Streaming

stream = client.chat.completions.create(
    model="auto",
    messages=[{"role": "user", "content": "Write a haiku."}],
    stream=True,
    stream_options={"include_usage": True},  # opt in to a final usage frame
)
for chunk in stream:
    if chunk.choices:
        print(chunk.choices[0].delta.get("content") or "", end="")
    if chunk.get("usage"):
        print("\nusage:", chunk.usage.model_dump())

Streams are context managers. If you might stop iterating early (break, return), use with so the HTTP connection is released deterministically (iterating to the end closes it either way):

with client.chat.completions.create(model="auto", messages=messages, stream=True) as stream:
    for chunk in stream:
        if should_stop(chunk):
            break

# async: async with await client.chat.completions.create(..., stream=True) as stream:

Async

from tokenrouter import AsyncTokenRouter

client = AsyncTokenRouter()

completion = await client.chat.completions.create(
    model="auto", messages=[{"role": "user", "content": "Hello!"}]
)

stream = await client.chat.completions.create(model="auto", messages=[...], stream=True)
async for chunk in stream:
    ...

Responses API

response = client.responses.create(
    model="auto",
    instructions="You are terse.",
    input="What is an AI gateway?",
)

# Streaming: an iterator of response.* events (ends when the connection closes)
for event in client.responses.create(model="auto", input="Hi", stream=True):
    if event.type == "response.output_text.delta":
        print(event.delta, end="")

TokenRouter's Responses API is stateless: previous_response_id and store=True are not supported.

Models and embeddings

models = client.models.list()  # includes 'auto', 'auto:cost|latency|quality|balanced'
embeddings = client.embeddings.create(
    model="openai/text-embedding-3-small",
    input="The quick brown fox",
)

Errors

All API errors are typed and carry status_code, code, and param:

Class Status Codes
AuthenticationError 401 invalid_api_key
PermissionError 403 model_not_allowed, subscription_inactive
NotFoundError 404 model_not_found
RateLimitError 429 rate_limit_exceeded, monthly_quota_exceeded (has retry_after)
BudgetExceededError 429 budget_exceeded (subclass of RateLimitError)
APIError any everything else, e.g. provider_key_missing, upstream_error
APIConnectionError / APITimeoutError — network failures / timeouts
from tokenrouter import RateLimitError

try:
    client.chat.completions.create(model="auto", messages=messages)
except RateLimitError as err:
    print(f"rate limited, retry in {err.retry_after}s")

Retries and configuration

Failed requests are retried twice by default with exponential backoff — on 429 (honouring Retry-After), 5xx, and network errors. Other 4xx are never retried, and a stream is never retried once it has started.

client = TokenRouter(
    api_key="tr_...",
    base_url="https://api.tokenrouter.io/v1",  # or TOKENROUTER_BASE_URL
    max_retries=2,   # 0 disables retries
    timeout=60.0,    # seconds, passed to httpx
)

Every request method also accepts per-call overrides:

client.chat.completions.create(
    model="auto",
    messages=messages,
    timeout=10.0,                          # seconds, this request only
    extra_headers={"X-Request-Tag": "cron"},
)

Development

uv sync
uv run pytest -q
TOKENROUTER_API_KEY=tr_... uv run python scripts/smoke.py

Metadata

Release files for tokenrouter 2.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for tokenrouter 2.0.0
File Size Uploaded Provenance Actions
tokenrouter-2.0.0.tar.gz 25.6 kB Without provenance Details for tokenrouter-2.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for tokenrouter 2.0.0
File Interpreter ABI Platform Actions
tokenrouter-2.0.0-py3-none-any.whl Python 3 none any Details for tokenrouter-2.0.0-py3-none-any.whl

Total release size: 41.5 kB

Release files / tokenrouter-2.0.0.tar.gz

Download URL tokenrouter-2.0.0.tar.gz
Size 25.6 kB
Tags Source
SHA-256 checksum
How to use checksums
31ae09d83ebb8bf0c08c26168c9d26e1ab2f729fa39e5a3df3589c8176d90674
BLAKE2b-256 checksum
How to use checksums
de124d3fccbd29b480d054d94d5557fad6bfb90fc2bcd74c3cde89a50491866d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.5

Release files / tokenrouter-2.0.0-py3-none-any.whl

Download URL tokenrouter-2.0.0-py3-none-any.whl
Size 15.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
fa05a33d0a3a1da5ab51198ca04f296a2f3f19db164f664dc77988ed539ccc02
BLAKE2b-256 checksum
How to use checksums
77ef949bb1f71a379e51f8828cafed10d95f778c042086222940239078a6815a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.5

Security for tokenrouter 2.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page