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
uv run ruff check && uv run pyright

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="gpt-6-luna",
        input='Reply with exactly the word "hello".',
    )
    print(response.output_text)

    completion = router.chat.completions.create(
        model="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 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/cost, is a router model: 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="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 httpx.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.

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="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="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

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. Upstream broadcast and trace-metadata helpers are also available.

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.0.1.dev15

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.0.1.dev15
File Size Uploaded Provenance Actions
tokedex-0.0.1.dev15.tar.gz 780.0 kB Without provenance Details for tokedex-0.0.1.dev15.tar.gz

Built distribution (wheel)

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

Total release size: 1.7 MB

Release files / tokedex-0.0.1.dev15.tar.gz

Download URL tokedex-0.0.1.dev15.tar.gz
Size 780.0 kB
Tags Source
SHA-256 checksum
How to use checksums
f5ef7076b3b974c4376cdfa05f23c25dd9f1f79c8082ec06cea952b4caf8daea
BLAKE2b-256 checksum
How to use checksums
53a5213d4084e384096ae02ab0c74636dcb265df8d19488b26e64446fdd82ced
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":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / tokedex-0.0.1.dev15-py3-none-any.whl

Download URL tokedex-0.0.1.dev15-py3-none-any.whl
Size 936.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
829fcbcefde4f365ca5b24da737f1452295b2256e2edf4795c7924afaaaad453
BLAKE2b-256 checksum
How to use checksums
f50dfa9bdd1b569416530600bcccef6d4729ed5571c29982bfb78fc354a0b62e
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":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for tokedex 0.0.1.dev15

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