
# 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

| Asset | Contents |
|---|---|
| [`/llms.txt`](/llms.txt) | An index of the docs, with a link to each page's Markdown |
| [`/llms-full.txt`](/llms-full.txt) | Every page's Markdown in reading order, in one file |
| `/<path>.md` | The Markdown of any page: append `.md` to its path, as in [`/gateway/quickstart.md`](/gateway/quickstart.md). A section index is at `<section>.md`, as in [`/gateway.md`](/gateway.md). |
| [`/errors.json`](/errors.json) | Every error ID with its cause, fix and whether it is retried |
| [`/catalog.json`](/catalog.json) | Providers and models: key variables, capabilities, and each model's Artificial Analysis price and quality |
| [`/language-support.json`](/language-support.json) | What each SDK language supports |
| `tdx schema --json` | Every CLI command with its flags, constraints, output fields and exit codes, from the installed CLI |
| `tdx guide` | This 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](/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.

```ts
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);
```

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

```rust
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](/sdk) lists everything else the `Router` does.

## Quickstart — gateway

> **Tip:** To create keys and do other administration from a shell or script, use the CLI, as [Quickstart — CLI](#quickstart--cli) shows.

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

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

```bash
npm install && npm start
```

```bash
pnpm install && pnpm start
```

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

```bash
# 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')"
```

```bash
# 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"
```

```bash
# 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](/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](/gateway/api-keys#give-a-script-an-admin-key) shows.

1. Install the CLI with `npm install --global @tokedex/cli`. See the [CLI quickstart](/cli/quickstart#install-the-cli) for requirements.

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

```bash
# 3. List every command, then read one command's flags and output fields as JSON.
tdx schema --json
tdx api-keys create --help --json
```

```bash
# 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](/cli/scripts-and-agents) covers output, exit codes and credentials, and the [Command reference](/cli/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

```support-matrix
Per-language support: ● stable · ◐ partial · ○ stub · — n/a. Machine-readable twin: /language-support.json
```

## When something breaks

Look up the error ID in [`/errors.json`](/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](/gateway/models#choose-a-provider).
