Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

Tokedex SDK for Python

The Tokedex SDK for Python calls OpenAI, Anthropic, Google, xAI and other providers through one Router object. It has two parts:

  • tokedex — Router and AsyncRouter, which speak OpenAI Responses, OpenAI Chat Completions, Anthropic Messages and Gemini GenerateContent, and run Batch jobs, with run_tools and stream_tools for tool loops. tokedex.sdk exports the same objects.
  • tokedex.core — create_router and the chat, stream, structured and run functions, for your own routes, hooks and sinks.

Requires Python 3.11 or later. The full documentation is at https://tokedex.artificialanalysis.ai.

Install

uv add tokedex          # or: pip install tokedex

Optional extras include telemetry (OpenTelemetry API/SDK/OTLP HTTP exporter) and all.

From a checkout of the monorepo:

cd python
uv sync --all-extras     # SDK + telemetry + dev tools
uv run pytest -n auto --dist loadfile
uv run ruff check && uv run pyright
uv run pytest tests/distribution   # build, install and check the wheel and sdist

Call a model with the Router

Each property of the Router speaks one API and takes that API's own request fields as keyword arguments: router.responses takes OpenAI Responses requests and router.chat.completions takes OpenAI Chat Completions requests. The Router reads provider keys, such as OPENAI_API_KEY, from the environment.

from tokedex import Router

with Router() as router:
    response = router.responses.create(
        model="openai/gpt-6-luna",
        input='Reply with exactly the word "hello".',
    )
    print(response.output_text)

    completion = router.chat.completions.create(
        model="openai/gpt-6-luna",
        messages=[{"role": "user", "content": 'Reply with exactly the word "hello".'}],
    )
    print(completion.choices[0].message.content)

Save it as hello.py and run it. The call uses your OpenAI account and can incur charges.

export OPENAI_API_KEY='<your-openai-api-key>'
uv run python hello.py

The program prints hello twice. Each reply has that API's own fields: output_text joins the text of a Responses reply, and a Chat Completions reply keeps its text in choices[0].message.content. The with block closes the Router's HTTP connections when it ends.

Use the other APIs

The same object serves the other APIs. Call models with the Router shows each call.

  • Anthropic Messages: router.messages.create(model=..., messages=...). router.messages.count_tokens(...) takes the same fields and returns input_tokens, with estimated set when the count is an estimate.
  • Gemini GenerateContent: router.generate_content.create(model=..., contents=...) takes the models router.models.list() lists with google.generate-content, such as google/gemini-3.5-flash-lite.
  • Streaming: .stream(...) on responses, chat.completions, messages and generate_content yields the API's own events. Use the stream in a with block so that stopping early closes the request. See Stream responses.
  • Structured output: router.responses.parse(model=..., input=..., text_format=Answer) returns the Responses reply with your Pydantic model in output_parsed, or None for a refusal or an incomplete answer. See Get structured output.
  • Tool runs: a request that declares tools returns the model's tool calls to your code. To run your tool functions automatically, run_tools(router, prompt, model=..., tools=[...]) calls the model, runs the tools it asks for and calls it again until it answers; stream_tools yields each step as it happens. Import both from tokedex.

List the models you can call

router.models.list() returns one row for each model and API your provider keys reach, with its context window and Batch support.

from tokedex import Router

with Router() as router:
    for model in router.models.list():
        print(model.id, model.client_dialect_id, model.context_window)

An ID that starts with aa/, such as aa/cheapest, is a router: it chooses a model for each request and falls back to the next one when a call fails.

Call a gateway with the same object

Pass a gateway's address and an API key, and the same calls go through the gateway. The gateway then holds the provider credentials, chooses the routes and stores conversations.

import os

from tokedex import Router

with Router(base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"]) as router:
    response = router.responses.create(model="openai/gpt-6-luna", input="Hello")
    print(response.output_text)

TOKEDEX_URL is the gateway address without /v1, such as http://127.0.0.1:4000. A gateway error raises httpx2.HTTPStatusError, in a stream too. AsyncRouter(base_url=..., api_key=...) does the same in async code. Call a gateway with the Router covers headers and response metadata.

In gateway mode, timeout_ms covers the whole call, including pauses between stream events, and overrides the HTTP client's own timeout for that call.

The SDK uses HTTPX2. When migrating an application that supplies http_client=, construct an httpx2.Client for Router or an httpx2.AsyncClient for AsyncRouter. The application owns the injected client and closes it. Update custom transports and exception handlers to import from httpx2 as well. TLS verification now uses the operating system's trust store by default. See the HTTPX2 migration guide.

Use the Router in async code

AsyncRouter has the same properties and methods as Router. Await each call, and open it with async with. Pass it to run_tools and await the result, or open stream_tools(...) with async with.

import asyncio

from tokedex import AsyncRouter


async def main() -> None:
    async with AsyncRouter() as router:
        response = await router.responses.create(model="openai/gpt-6-luna", input="Hello")
        print(response.output_text)


asyncio.run(main())

Run Batch jobs

router.batches submits a provider Batch job, then checks it, reads its results and cancels it. It works with provider keys alone and through a gateway.

from tokedex import Router
from tokedex.sdk.batch import BatchItem

with Router() as router:
    job = router.batches.create(
        model="openai/gpt-6-luna",
        operation="responses",
        items=[BatchItem(custom_id="first", body={"input": "Summarize this."})],
    )
    print(job.id, job.native.get("status"))

Keep job.id: router.batches.retrieve, results and cancel take it. Without a gateway, the first Batch call creates a key file, tokedex/batch-receipt.key in your state directory (XDG_STATE_HOME, ~/.local/state, or LOCALAPPDATA on Windows). Keep it to reopen jobs after a restart, or set TOKEDEX_BATCH_RECEIPT_SECRET to share one secret across hosts. Batch jobs covers polling and reading results.

Set provider keys

Python accepts plain strings and Pydantic SecretStr values for gateway keys, provider credentials, custom-model keys, and Batch receipt secrets. SDK options redact those values when printed. Credential mappings and resolvers are read when a call needs a key, so a running client can observe a rotation.

The Router reads each provider's key from the environment when it sends a request. Pass credentials={"OPENAI_API_KEY": ...}, keyed by the same names, to use other keys.

Provider Environment variable
OpenAI OPENAI_API_KEY
Anthropic ANTHROPIC_API_KEY
Google GEMINI_API_KEY
xAI XAI_API_KEY

The google() provider in tokedex.providers.google also reads GOOGLE_AI_API_KEY, then GOOGLE_API_KEY. Connect providers lists every provider and covers OpenAI-compatible providers, LM Studio and Ollama.

Build your own routes

To list your own providers and models in order of preference, or to add hooks and sinks, use create_router with the chat, stream, structured and run functions from tokedex.core. Provider clients are in tokedex.providers.

import asyncio
import os

from tokedex.core import Route, aclose_router, chat, create_router
from tokedex.providers.openai import openai


async def main() -> None:
    router = create_router(
        routes=[Route(provider=openai(api_key=os.environ["OPENAI_API_KEY"]), model="gpt-6-luna")]
    )
    try:
        response = await chat(router, 'Reply with exactly the word "hello".')
        print(response.text)
    finally:
        await aclose_router(router)


asyncio.run(main())

Route across providers with failover covers fallback routes and when the router retries.

SDK examples

Runnable examples are in examples/; see examples/README.md for the list.

Telemetry & observability

tokedex.telemetry provides a batching sink for privacy-bounded lifecycle events. Create it with tokedex_telemetry(TokedexTelemetryOptions(...)), pass its sink to create_router(), and call flush_telemetry() before shutdown. Configure an explicit collector endpoint and optional collector token. The offline telemetry example demonstrates this with an injected HTTP client.

The optional telemetry extra supplies OpenTelemetry SDK dependencies for managed span recorders.

Helpers in tokedex.telemetry build the headers and metadata a provider needs to forward traces to your collector:

from tokedex.telemetry import (
    create_otel_broadcast_headers,
    create_otel_trace_metadata,
)

headers = create_otel_broadcast_headers(
    header_prefix="X-Upstream",
    api_key="<your-collector-key>",
    collector_endpoint="https://collector.example/v1/traces",
    referer="https://gateway.example.com",
    title="Tokedex",
)
metadata = create_otel_trace_metadata(
    trace_id="trace-id",
    generation_name="gateway-call",
)

Set header_prefix to the prefix the provider expects. Send telemetry to your collector covers the SDK's telemetry sink.

Metadata

Release files for tokedex 0.1.1rc2

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

Source distribution (sdist)

Source distribution for tokedex 0.1.1rc2
File Size Uploaded Provenance Actions
tokedex-0.1.1rc2.tar.gz 857.6 kB Without provenance Details for tokedex-0.1.1rc2.tar.gz

Built distribution (wheel)

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

Total release size: 1.9 MB

Release files / tokedex-0.1.1rc2.tar.gz

Download URL tokedex-0.1.1rc2.tar.gz
Size 857.6 kB
Tags Source
SHA-256 checksum
How to use checksums
b6751b525d467ff1fbe9b6379a5279a2fb007d86248149692221dc094bc3f73e
BLAKE2b-256 checksum
How to use checksums
0c24064f149cb7e641a21826a06eefad15251a0037562060525bdb58a38dd7b2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / tokedex-0.1.1rc2-py3-none-any.whl

Download URL tokedex-0.1.1rc2-py3-none-any.whl
Size 1.0 MB
Tags Python 3
SHA-256 checksum
How to use checksums
5a951fb164a94882a2237ea656ec2e69829d8e429a48d5e83e67d0a16c85e2a4
BLAKE2b-256 checksum
How to use checksums
884adcb202ebc9bd9a70c2b078ba5b1eba863e02ee0ac01b8a7473eca8803010
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for tokedex 0.1.1rc2

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