Metadata-Version: 2.5
Name: tokedex
Version: 0.1.2rc2
Summary: Tokedex Python SDK for routing requests to language models across providers.
Author-email: Artificial Analysis <tokedex@artificialanalysis.ai>
License-Expression: MIT
License-File: LICENSE
Keywords: ai,failover,llm,router,streaming,tokedex
Requires-Python: >=3.11
Requires-Dist: cryptography>=42
Requires-Dist: httpx2<3,>=2.16.2
Requires-Dist: jsonschema>=4.23
Requires-Dist: pydantic>=2.11
Requires-Dist: typing-extensions>=4.6
Provides-Extra: all
Requires-Dist: opentelemetry-api>=1.27; extra == 'all'
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.27; extra == 'all'
Requires-Dist: opentelemetry-sdk>=1.27; extra == 'all'
Provides-Extra: telemetry
Requires-Dist: opentelemetry-api>=1.27; extra == 'telemetry'
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.27; extra == 'telemetry'
Requires-Dist: opentelemetry-sdk>=1.27; extra == 'telemetry'
Description-Content-Type: text/markdown

# 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

```bash
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:

```bash
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.

```python
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.

```bash
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](https://tokedex.artificialanalysis.ai/sdk/generate-text) 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](https://tokedex.artificialanalysis.ai/sdk/streaming).
- **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](https://tokedex.artificialanalysis.ai/sdk/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.

```python
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.

```python
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](https://tokedex.artificialanalysis.ai/sdk/gateway) 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](https://pydantic.dev/docs/httpx2/get-started/migration/).

## 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`.

```python
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.

```python
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](https://tokedex.artificialanalysis.ai/sdk/batch)
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](https://tokedex.artificialanalysis.ai/sdk/provider-keys) 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`.

```python
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](https://tokedex.artificialanalysis.ai/sdk/routes-and-failover)
covers fallback routes and when the router retries.

## SDK examples

Runnable examples are in [`examples/`](./examples); see
[`examples/README.md`](./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](./examples/08_telemetry.py) 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:

```python
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](https://tokedex.artificialanalysis.ai/sdk/observability) covers
the SDK's telemetry sink.
