For agents#

Tokedex is a token router that calls OpenAI, Anthropic, Google, xAI and other providers through OpenAI Responses, OpenAI Chat Completions, Anthropic Messages or Gemini GenerateContent, with retries and failover. Use the SDK when you can change the application's code, or run the gateway when clients that use those APIs need shared provider access. Manage a running gateway from a shell or script with the CLI, tdx.

Machine assets#

AssetContents
/llms.txtAn index of the docs, with a link to each page's Markdown
/llms-full.txtEvery page's Markdown in reading order, in one file
/<path>.mdThe Markdown of any page: append .md to its path, as in /gateway/quickstart.md. A section index is at <section>.md, as in /gateway.md.
/errors.jsonEvery error ID with its cause, fix and whether it is retried
/catalog.jsonProviders and models: key variables, capabilities, and each model's Artificial Analysis price and quality
/language-support.jsonWhat each SDK language supports
tdx schema --jsonEvery CLI command with its flags, constraints, output fields and exit codes, from the installed CLI
tdx guideThis page, built into the CLI and read without a network; tdx guide gateway, tdx guide sdk or tdx guide llms prints one part

Quickstart — SDK#

Install the SDK as the SDK quickstart describes, and set OPENAI_API_KEY. Call models through the Router object: router.responses takes OpenAI Responses requests and router.chat.completions takes OpenAI Chat Completions requests, each with that API's own fields. The sample makes two calls, prints hello twice and can incur charges.

import { Router } from '@tokedex/sdk';
 
// The Router reads the key from OPENAI_API_KEY.
const router = new Router();
 
const response = await router.responses.create({
  model: 'openai/gpt-6-luna',
  input: 'Reply with exactly the word "hello".',
});
for (const item of response.output) {
  if (item.type !== 'message') continue;
  for (const part of item.content) if (part.type === 'output_text') console.log(part.text);
}
 
const completion = await router.chat.completions.create({
  model: 'openai/gpt-6-luna',
  messages: [{ role: 'user', content: 'Reply with exactly the word "hello".' }],
});
console.log(completion.choices[0]?.message.content);
from tokedex import Router
 
# The Router reads the key from OPENAI_API_KEY.
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)
use tokedex::{Router, wire};
 
// The Router reads the key from OPENAI_API_KEY.
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let router = Router::builder().build()?;
    let prompt = r#"Reply with exactly the word "hello"."#;
 
    let response = router.responses().create(wire::ResponsesRequest::new("openai/gpt-6-luna", prompt)).await?;
    println!("{}", response.output_text());
 
    let request = wire::ChatCompletionsRequest::new("openai/gpt-6-luna", vec![wire::Message::user(prompt)]);
    let completion = router.chat().completions().create(request).await?;
    if let Some(wire::Content::Text(text)) = &completion.choices[0].message.content {
        println!("{text}");
    }
    Ok(())
}

The same object speaks Anthropic Messages (router.messages) and Gemini GenerateContent (router.generateContent). router.models.list() lists the model IDs you can call and the API each speaks. new Router({ baseUrl, apiKey }) sends the same calls through a Tokedex gateway. The SDK overview lists everything else the Router does.

Quickstart — gateway#

Note:

Tip: To create keys and do other administration from a shell or script, use the CLI, as Quickstart — CLI shows.

Start the gateway, create an API key, then send a request. Docker Compose runs the published gateway image. The Gateway quickstart covers Docker, npm and the first request in the dashboard, and Deploy to production covers Kubernetes.

Shell
# 1. Start the gateway.
git clone https://github.com/ArtificialAnalysis/Tokedex.git
cd Tokedex
docker compose up --no-build

The gateway prints its master key in the log and saves it in /home/node/.tokedex/master-key in the gateway-data volume. With -d, read the key with docker compose logs gateway.

To run with Node instead, use npm or pnpm from the repository root:

Shell
npm install && npm start
Shell
pnpm install && pnpm start

Node prints the master key in an interactive terminal and saves it in ~/.tokedex/master-key.

Shell
# 2. With the master key in TOKEDEX_MASTER_KEY, create an API key. The response
# shows the new key once, in `token`.
export TOKEDEX_API_KEY="$(curl -s http://127.0.0.1:4000/control/v1/inference-keys \
  -H "Authorization: Bearer $TOKEDEX_MASTER_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name":"agent","allowedModels":null}' \
  | sed -n 's/.*"token":"\([^"]*\)".*/\1/p')"
Shell
# 3. List the model IDs the key can call.
curl -s http://127.0.0.1:4000/v1/models -H "Authorization: Bearer $TOKEDEX_API_KEY"
Shell
# 4. Replace <model-id> with an `id` whose `client_dialect_id` is
# `openai.chat-completions`. This calls a provider and can incur charges.
curl -s http://127.0.0.1:4000/v1/chat/completions \
  -H "Authorization: Bearer $TOKEDEX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"<model-id>","messages":[{"role":"user","content":"Reply with exactly the word \"hello\"."}]}'

"allowedModels":null lets the key call every model its workspace allows. The master key works on /control and the dashboard, never on /v1.

Quickstart — CLI#

Manage a running gateway with the CLI, tdx: API keys, budgets, people, workspaces, spend and traces. A person at a terminal signs in with tdx auth login and approves a code in the browser. An agent uses an admin key instead, because that sign-in waits for a person to approve it, and tdx auth login refuses to start it with no terminal. Create the key in the dashboard under API keys → Admin keys or with the master key, as Give a script an admin key shows.

  1. Install the CLI with npm install --global @tokedex/cli. See the CLI quickstart for requirements.
Shell
# 2. Point it at the gateway with an admin key, for this shell only, and check who it is.
export TOKEDEX_HOST='http://127.0.0.1:4000'
export TOKEDEX_TOKEN='<your-admin-key>'
tdx auth status
Shell
# 3. List every command, then read one command's flags and output fields as JSON.
tdx schema --json
tdx api-keys create --help --json
Shell
# 4. Preview a write, then make it. The new API key goes only to a new owner-only file.
tdx api-keys create --name agent --all-models --dry-run
tdx api-keys create --name agent --all-models --token-file ./agent.key

Every command prints {"schemaVersion": "tokedex.cli.v1", "command": …, "data": …} on stdout, or {"error": {"code": …, "hint": …, "fix": …}} on stderr with an exit code from 1 to 7. Exit code 1 can mean a write was applied before a later step failed, so read the current state before you repeat a write. The CLI never prints a credential: tdx api-keys create writes a new key only to a new --token-file, or makes a --secretless offer, and tdx api masks secret fields. Scripts and agents covers output, exit codes and credentials, and the Command reference lists every command.

Check a setup#

  • SDK. The SDK sample above prints hello twice.
  • Gateway. Repeat the request with curl -si and look for the x-tokedex-provider and x-tokedex-model response headers, which name the provider and model that served the request. The request also appears in the dashboard under Observability.
  • CLI. tdx doctor checks the connection and the credential, and exits with 1 if either fails.

What works per language#

  • Stable
  • Partial
  • Stub
  • n/a
language-support.json
SurfaceTypeScriptRustPython
Router object: Responses, Chat Completions, Messages, GenerateContent, models and BatchCalls any built-in model by model ID with each API's own request and response fields, directly or through a gateway. Python has a synchronous Router and an AsyncRouter. Typed output comes from responses.parse with a schema in each language.StableStableStable
Your own routes: createRouter with chat, stream and structuredRoutes you list in order of preference, with retries, failover, hooks and sinks.StableStableStable
Tool runsrunTools with a Router, and the core run function, return every step, the full conversation, combined usage and the reason the run ended. Python and Rust name it run_tools.StableStableStable
OpenTelemetry HTTP export helpercreateOtelHttpDrain from @tokedex/gateway in TypeScript, create_otel_http_drain from tokedex.telemetry in Python and from tokedex::telemetry in Rust.StableStableStable
Gateway route embedded in a Next.js appTypeScript only.Stablen/an/a
Runnable numbered examplesEach language has examples for the Router, your own routes and streamed tool runs. Python and Rust add a Batch example. TypeScript adds a Next.js gateway route and an observability agent.StableStableStable

When something breaks#

Look up the error ID in /errors.json. Each error has a stable ID, such as Provider.RateLimit or the gateway's RateLimited, with its cause and fix. The SDK retries network failures, rate limits and server errors on the same route, and moves to the next route on other errors.

When several providers serve a model, a request tries them in the model's provider order (cheapest first by default) and moves to the next on a rate limit, an outage or a timeout; a follow-up turn of a conversation retries each provider before it moves to the next. If one provider keeps failing, send x-tokedex-provider-order (the SDKs' providerOrder) to try others first, or x-tokedex-provider (providers) to allow only some; see Choose a provider.