# Tokedex — full documentation > Tokedex is a multi-provider token router: call any provider's models with the API your code already uses, directly or through a self-hosted gateway. > Concatenated Markdown of every page, in reading order, from https://tokedex.artificialanalysis.ai. --- # Tokedex Tokedex is an open-source token router by [Artificial Analysis](https://artificialanalysis.ai). Route, observe and budget requests to language models from your apps, coding agents and team across every provider. - **Provider knowledge.** Each model's price, limits and capabilities, and routing by Artificial Analysis benchmarks. - **Observability, spend and budgets.** For one person, a team or an enterprise. - **Open source.** Run the gateway as a container in your cloud, or use the SDK in your code. ## Gateway A self-hosted server between your applications and the providers. It holds the provider credentials, and clients call it with API keys you issue. - Works with the Tokedex SDK, any OpenAI or Anthropic client, and coding agents such as Claude Code, Codex and Cursor. - Gives each team a workspace with its own API keys, roles and budgets. - Records a trace of every request, with its model, tokens, latency and cost. Run the published Docker image on your machine, then call the gateway with an API key you create in its dashboard: ```bash git clone https://github.com/ArtificialAnalysis/Tokedex.git cd Tokedex docker compose up --no-build ``` Then follow the [Gateway quickstart](/gateway/quickstart), read the [Gateway overview](/gateway), or manage it from a terminal with the [CLI](/cli). ## SDK A library that calls the providers from your own process, with provider keys read from your environment. - For TypeScript, Python and Rust. - The same code runs through a gateway when you change the line that creates the Router. - Build a router from your own routes, with hooks and sinks. Start with the [SDK quickstart](/sdk/quickstart), or read the [SDK overview](/sdk). ## Start with your job - [Connect an app](/gateway/connect-your-app): keep your OpenAI or Anthropic client and point it at the gateway. - [Connect a coding agent](/gateway/coding-agents): set up Claude Code, Codex, Cursor and others from the dashboard. - [Manage keys and budgets](/gateway/api-keys): issue API keys, invite people and cap what each team spends. - [Deploy to production](/gateway/deploy): run the gateway on Kubernetes with the Helm chart. ## What it does - **[One interface to use any model in any agent](/gateway/coding-agents).** Use OpenAI Chat Completions, OpenAI Responses or Anthropic's Messages API with any model. Use your agent, whether a custom agent or Claude Code, with any model. You can now use GPT-6.2 Astra or Gemini 4 Neon in Claude Code. - **[Routing on Artificial Analysis benchmarks](/gateway/router#built-in-routers).** Use Artificial Analysis intelligence, speed and cost benchmarks to automatically pick the best model for your constraints, such as the cheapest model scoring 50+ on the Intelligence Index. - **[Observability so you can measure and improve your agents](/gateway/requests-and-sessions).** Track and inspect traces to debug and improve your agents, with no data sent to a third party. - **[Cost controls and team management](/gateway/people-and-workspaces).** Set spend budgets and alerts, scope API keys, enable SSO and organise teams into workspaces. - **[Retries and fallback](/sdk/routes-and-failover).** Increase availability with smart retries and fallback models to ensure your agents don't go down. - **[SDKs for Python, TypeScript and Rust](/sdk).** Call models from your own code with streaming, structured output and tool calling, directly or through your gateway. Plain HTTP and curl work too. ## Contribute Tokedex does not accept pull requests, so an issue is the way to suggest a change. - [Open an issue](https://github.com/ArtificialAnalysis/Tokedex/issues/new): report a bug, request a feature or point out a problem in the docs. - [Read the contributing guide](https://github.com/ArtificialAnalysis/Tokedex/blob/main/CONTRIBUTING.md): see what to include so an issue can be acted on. - [Report a vulnerability](https://github.com/ArtificialAnalysis/Tokedex/blob/main/SECURITY.md): report a security problem privately, as the security policy describes. --- # Gateway overview The gateway is a server you run between your apps and model providers such as OpenAI, Anthropic and Google, with a dashboard to manage who calls which model and what it costs. An app keeps its client and changes three values: the base URL, the API key and the model ID. ```ts import OpenAI from 'openai'; const client = new OpenAI({ baseURL: 'http://127.0.0.1:4000/v1', // the gateway, in place of the provider apiKey: process.env['TOKEDEX_API_KEY'], // a gateway API key, in place of the provider's }); const completion = await client.chat.completions.create({ model: 'openai/gpt-6-luna', // a model the key can call, from any connected provider messages: [{ role: 'user', content: 'Reply with exactly the word "hello".' }], }); console.log(completion.choices[0]?.message.content); ``` ```text hello ``` The same client calls models from other providers too, such as `anthropic/claude-haiku-5.5` from Anthropic. The gateway serves OpenAI Chat Completions, OpenAI Responses, Anthropic Messages and Gemini GenerateContent, so the OpenAI SDK, the Anthropic SDK, curl and coding agents such as Claude Code and Codex all connect the same way. ## Gateway features - **One place for provider keys.** Your apps never hold a provider's key. See [Provider credentials](/gateway/provider-credentials). - **A key for each app or person,** limited to the models it needs, so a leaked key is revoked without stopping anything else. See [API keys](/gateway/api-keys). - **Budgets** that refuse requests once a key, a person, a workspace or a model has spent its limit. See [Budgets](/gateway/budgets). - **Routing,** with routers that choose among several models and fall back when one fails. See [Routers and fallback](/gateway/router). - **A trace of every request,** with its tokens, cost, latency and the provider that answered. See [Find and inspect a request](/gateway/requests-and-sessions). ## Paths by role Everyone starts with the [Gateway quickstart](/gateway/quickstart): the gateway on your machine and a first request in a few minutes. Connect one provider and send that request before you invite anyone: the Quick start card says why a request fails and what one costs, so you find a provider problem before others depend on the gateway. Then follow the path for your job. - **You call models from an app or a coding agent.** [Connect your app](/gateway/connect-your-app), [Connect a coding agent](/gateway/coding-agents), [Find a model](/gateway/models), then [Errors, limits and request IDs](/gateway/errors-and-limits). Look up endpoints, headers and request fields in the [API reference](/gateway/api-reference). - **You manage access and spend in the dashboard.** [People and workspaces](/gateway/people-and-workspaces), [Provider credentials](/gateway/provider-credentials), [API keys](/gateway/api-keys), [Budgets](/gateway/budgets), then [Spend and usage](/gateway/spend-and-usage). To do the same from a terminal or a script, use the [CLI](/cli). - **You run the gateway for others.** [Deploy to production](/gateway/deploy), [HTTPS and reverse proxies](/gateway/https), [Single sign-on](/gateway/single-sign-on), then [Backup and restore](/gateway/backup-restore). Once people have accounts, keep the master key for recovery only, since it has full access. --- # Gateway quickstart Start the gateway on your machine, send it a first request and see the request's tokens and cost, in a few minutes. **Docker** ```bash git clone https://github.com/ArtificialAnalysis/Tokedex.git cd Tokedex docker compose up --no-build ``` ```text gateway-1 | Gateway is ready. Sign in with this master key: gateway-1 | gateway-1 | gateway-1 | gateway-1 | Find it as /home/node/.tokedex/master-key. Follow the Quick start on Home after signing in. ``` You need: Docker with Compose, and an API key from a model provider, such as OpenAI, Anthropic or Google. Docker pulls the published image on the first start. Keep the container logs private because they contain the master key. **npm** ```bash git clone https://github.com/ArtificialAnalysis/Tokedex.git cd Tokedex npm install npm start ``` ```text ● Gateway is up Dashboard http://127.0.0.1:4000/ API http://127.0.0.1:4000/v1 Control http://127.0.0.1:4000/control Master key Saved as ~/.tokedex/master-key. Sign in with it, then follow the Quick start on Home. ``` You need a supported Node.js LTS release (see `engines` in [`package.json`](https://github.com/ArtificialAnalysis/Tokedex/blob/main/package.json)) and an API key from a model provider, such as OpenAI, Anthropic or Google. `npm start` builds the gateway and its dashboard first, which takes a few minutes. With pnpm, `pnpm install` and `pnpm start` do the same. ## Sign in 1. Open `http://127.0.0.1:4000` in a browser on the same machine. 2. Paste the master key and choose **Continue with master key**. The dashboard opens on **Home**. The master key has full access, so keep it private. To sign in with a password from now on, choose **Create account** in the **Using master key** banner. Do it before you invite anyone, and keep the master key for recovery after that, so the key that can do everything stays out of daily use. ## Send your first request Follow the **Quick start** card at the top of **Home**: 1. Under **Connect a model provider**, choose your provider, paste its API key and choose **Save key**. The card says the provider is connected. 2. Under **Make your first request**, choose **Create API key**. The card's command now holds a new API key, shown this once. 3. Choose **Copy command** and run it in a terminal. ```bash curl http://127.0.0.1:4000/v1/chat/completions \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{"model":"openai/gpt-6-luna","messages":[{"role":"user","content":"Say hello in one short sentence."}]}' ``` ```json {"id":"chatcmpl-…","object":"chat.completion","model":"openai/gpt-6-luna","choices":[{"index":0,"message":{"role":"assistant","content":"Hello there!"},"finish_reason":"stop"}],"usage":{"prompt_tokens":14,"completion_tokens":2,"total_tokens":16}} ``` The card fills in a model that your provider serves, such as `openai/gpt-6-luna` for OpenAI. The request calls your provider and can incur charges. ## See what it cost The Quick start card shows what the request cost. Once the request is served, the card reads **You're set up**, and **See its trace and cost** shows what the request used: ```text Your first request used 16 tokens (14 in, 2 out), costing <$0.0001. ``` ![The Quick start card on Home with all three steps completed, showing the tokens and cost of the first request](/images/dashboard/home-quick-start.png) Choose **Open its trace →** to open the request in **Observability**, with the provider and model that answered and its **Estimated cost**. If the request is refused or fails, the card says why and how to fix it. ## Check that the gateway is running ```bash curl -sS http://127.0.0.1:4000/readyz ``` ```json {"ok":true,"release":{"environment":"local"},"service":"tokedex"} ``` The check needs no key. ## State and the master key **Docker** The gateway keeps its state, the master key and the provider keys you save in the `gateway-data` volume. `docker compose down` keeps the volume. To choose your own master key, set `TOKEDEX_MASTER_KEY` to at least 32 characters in a `.env` file in the repository root before the first start. To back up the volume and rehearse a restore, choose **Docker** under **Run with**. [Backup and restore](/gateway/backup-restore) > **Important:** Stop the gateway with `docker compose down`, without `-v`. Deleting the volume deletes your accounts, API keys and saved provider keys, and the gateway starts again as a new installation. **npm** The gateway keeps its state and the master key in `~/.tokedex`. To back it up, stop the gateway and archive that directory with your `.env` if you made one. Keep the archive in private, encrypted storage because it contains credentials. To upgrade, take a backup, check out the new release, then run `npm install` and `npm start`. The gateway keeps using `~/.tokedex`. If the new release fails, use the backup to restore the release you ran and its state. To choose your own master key, set `TOKEDEX_MASTER_KEY` to at least 32 characters in a `.env` file in the repository root before the first start. `.env.example` lists the other settings. The gateway answers only on its own machine. Before anyone else uses it, serve it over [HTTPS](/gateway/https). To run it in production, see [Deploy to production](/gateway/deploy). Next: [Connect your app](/gateway/connect-your-app), [Provider credentials](/gateway/provider-credentials) or [Observability](/gateway/requests-and-sessions). --- # Connect your app Keep the client your app already uses and change three values, its base URL, its API key and the model ID, to send its requests through the gateway. **OpenAI SDK** ```ts import OpenAI from 'openai'; const client = new OpenAI({ baseURL: process.env['TOKEDEX_BASE_URL'], apiKey: process.env['TOKEDEX_API_KEY'], }); const completion = await client.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 import os from openai import OpenAI client = OpenAI(base_url=os.environ["TOKEDEX_BASE_URL"], api_key=os.environ["TOKEDEX_API_KEY"]) completion = client.chat.completions.create( model="openai/gpt-6-luna", messages=[{"role": "user", "content": 'Reply with exactly the word "hello".'}], ) print(completion.choices[0].message.content) ``` ```text hello ``` **Anthropic SDK** ```ts import Anthropic from '@anthropic-ai/sdk'; const client = new Anthropic({ baseURL: process.env['TOKEDEX_URL'], apiKey: process.env['TOKEDEX_API_KEY'], }); const message = await client.messages .stream({ model: 'openai/gpt-6-luna', // Anthropic's SDK requires max_tokens, and streaming once it is this large. max_tokens: 128000, messages: [{ role: 'user', content: 'Reply with exactly the word "hello".' }], }) .finalMessage(); for (const block of message.content) if (block.type === 'text') console.log(block.text); ``` ```python import os from anthropic import Anthropic client = Anthropic(base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"]) with client.messages.stream( model="openai/gpt-6-luna", # Anthropic's SDK requires max_tokens, and streaming once it is this large. max_tokens=128000, messages=[{"role": "user", "content": 'Reply with exactly the word "hello".'}], ) as stream: message = stream.get_final_message() for block in message.content: if block.type == "text": print(block.text) ``` ```text hello ``` **Rust · OpenAI SDK, Anthropic SDK** For Rust, choose **Tokedex SDK** in the bar above: its Rust client takes the same address and key. **curl** ```bash curl -sS "$TOKEDEX_BASE_URL/chat/completions" \ -H "Authorization: Bearer $TOKEDEX_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-6-luna", "messages": [{ "role": "user", "content": "Reply with exactly the word \"hello\"." }] }' ``` ```json { "object": "chat.completion", "model": "openai/gpt-6-luna", "choices": [{ "index": 0, "message": { "role": "assistant", "content": "hello" }, "finish_reason": "stop" }], "usage": { "prompt_tokens": 14, "completion_tokens": 2, "total_tokens": 16 } } ``` **Tokedex SDK** ```ts import { Router } from '@tokedex/sdk'; const router = new Router({ baseUrl: process.env['TOKEDEX_URL']!, apiKey: process.env['TOKEDEX_API_KEY']!, }); 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 import os from tokedex import Router with Router(base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"]) as router: 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::{GatewayOptions, Router, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::new(GatewayOptions::new(std::env::var("TOKEDEX_URL")?, std::env::var("TOKEDEX_API_KEY")?))?; let messages = vec![wire::Message::user(r#"Reply with exactly the word "hello"."#)]; let request = wire::ChatCompletionsRequest::new("openai/gpt-6-luna", messages); let completion = router.chat().completions().create(request).await?; if let Some(wire::Content::Text(text)) = &completion.choices[0].message.content { println!("{text}"); } Ok(()) } ``` ```text hello ``` You need: the gateway's address and an API key (`tokedex_ik_…`) that can call `openai/gpt-6-luna`. An admin can give you one, or you can [create one](/gateway/api-keys) under **API keys**. For an application, use a workspace key rather than your personal key, because a personal key stops working when its holder leaves the workspace. Each request calls a provider and can incur charges. ## Values to change **OpenAI SDK, curl** ```bash export TOKEDEX_BASE_URL='http://127.0.0.1:4000/v1' export TOKEDEX_API_KEY='' ``` **Anthropic SDK, Tokedex SDK** ```bash export TOKEDEX_URL='http://127.0.0.1:4000' export TOKEDEX_API_KEY='' ``` | Value | Set it to | | --- | --- | | Base URL | The gateway's address followed by (Anthropic SDK, Tokedex SDK: without) `/v1`, such as `https://gateway.example.com/v1` (Anthropic SDK, Tokedex SDK: `https://gateway.example.com`) | | API key | Your API key, in place of the provider's key | | Model ID | A model ID your key can call, such as `openai/gpt-6-luna` | `127.0.0.1` reaches the gateway only from its own machine. A client in a container or on another computer needs an address it can reach. Keep the key in your app's secret store, never in browser code or source files, because anyone who reads it can call models on your key until it is revoked. The same client calls other providers' models too: with `anthropic/claude-haiku-5.5` as the model ID, if your key can call it, the gateway sends the request to Anthropic. **OpenAI SDK** The client adds `/chat/completions` to the base URL and sends the key as `Authorization: Bearer`. The same client calls OpenAI Responses at `client.responses.create`. **Anthropic SDK** The client adds `/v1/messages` to the base URL and sends the key in `x-api-key`. The gateway accepts `anthropic-version: 2023-06-01`, the version the client sends. **curl** Send the key as `Authorization: Bearer`. The same key calls OpenAI Responses at `$TOKEDEX_BASE_URL/responses`, and Anthropic Messages at `$TOKEDEX_BASE_URL/messages`, where `x-api-key` carries it too. **Tokedex SDK** The SDK adds each API's path to the address, such as `/v1/chat/completions`, and sends the key as `Authorization: Bearer`. The same Router calls OpenAI Responses, Anthropic Messages and Gemini GenerateContent too; see [Run through a gateway](/sdk/gateway). [API reference](/gateway/api-reference) lists each API's endpoints, the headers the gateway reads and returns, and what it does with each request field. ## List the models your key can call **OpenAI SDK** ```ts import OpenAI from 'openai'; const client = new OpenAI({ baseURL: process.env['TOKEDEX_BASE_URL'], apiKey: process.env['TOKEDEX_API_KEY'] }); for await (const model of client.models.list()) { if ('client_dialect_id' in model && model.client_dialect_id === 'openai.chat-completions') console.log(model.id); } ``` ```python import os from openai import OpenAI client = OpenAI(base_url=os.environ["TOKEDEX_BASE_URL"], api_key=os.environ["TOKEDEX_API_KEY"]) for model in client.models.list(): if getattr(model, "client_dialect_id", None) == "openai.chat-completions": print(model.id) ``` **Anthropic SDK** ```ts import Anthropic from '@anthropic-ai/sdk'; const client = new Anthropic({ baseURL: process.env['TOKEDEX_URL'], apiKey: process.env['TOKEDEX_API_KEY'] }); for await (const model of client.models.list()) { if ('client_dialect_id' in model && model.client_dialect_id === 'anthropic.messages') console.log(model.id); } ``` ```python import os from anthropic import Anthropic client = Anthropic(base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"]) for model in client.models.list(): if getattr(model, "client_dialect_id", None) == "anthropic.messages": print(model.id) ``` **curl** ```bash curl -sS "$TOKEDEX_BASE_URL/models" \ -H "Authorization: Bearer $TOKEDEX_API_KEY" ``` ```json { "object": "list", "data": [ … { "id": "openai/gpt-6-luna", "object": "model", "client_dialect_id": "openai.chat-completions", "context_window": 1050000, … }, { "id": "openai/gpt-6-luna", "object": "model", "client_dialect_id": "openai.responses", "context_window": 1050000, … }, … ], "models": […] } ``` **Tokedex SDK** ```ts import { Router } from '@tokedex/sdk'; const router = new Router({ baseUrl: process.env['TOKEDEX_URL']!, apiKey: process.env['TOKEDEX_API_KEY']! }); for (const model of await router.models.list()) { if (model.client_dialect_id === 'openai.chat-completions') console.log(model.id); } ``` ```python import os from tokedex import Router with Router(base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"]) as router: for model in router.models.list(): if model.client_dialect_id == "openai.chat-completions": print(model.id) ``` ```rust use tokedex::{GatewayOptions, Router}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::new(GatewayOptions::new(std::env::var("TOKEDEX_URL")?, std::env::var("TOKEDEX_API_KEY")?))?; for model in router.models().list().await? { if model.client_dialect_id == "openai.chat-completions" { println!("{}", model.id); } } Ok(()) } ``` **OpenAI SDK, Anthropic SDK, Tokedex SDK** ```text … openai/gpt-6.1-sol openai/gpt-6.1-terra openai/gpt-6-luna … ``` The list holds each model ID once for every client API that serves it, and `client_dialect_id` names the API; a model ID can be served on one client API and not another. Use an ID listed with `openai.chat-completions` (Anthropic SDK: `anthropic.messages`). An empty list means no provider is connected yet, or your key can call no model. Listing sends nothing to a provider, so check a model ID here with the key your app will use before you deploy it. ## Stream a response **OpenAI SDK** ```ts import OpenAI from 'openai'; const client = new OpenAI({ baseURL: process.env['TOKEDEX_BASE_URL'], apiKey: process.env['TOKEDEX_API_KEY'] }); const stream = await client.chat.completions.create({ model: 'openai/gpt-6-luna', messages: [{ role: 'user', content: 'Reply with exactly the word "hello".' }], stream: true, }); for await (const chunk of stream) process.stdout.write(chunk.choices[0]?.delta.content ?? ''); console.log(); ``` ```python import os from openai import OpenAI client = OpenAI(base_url=os.environ["TOKEDEX_BASE_URL"], api_key=os.environ["TOKEDEX_API_KEY"]) stream = client.chat.completions.create( model="openai/gpt-6-luna", messages=[{"role": "user", "content": 'Reply with exactly the word "hello".'}], stream=True, ) for chunk in stream: for choice in chunk.choices: print(choice.delta.content or "", end="", flush=True) print() ``` **Anthropic SDK** ```ts import Anthropic from '@anthropic-ai/sdk'; const client = new Anthropic({ baseURL: process.env['TOKEDEX_URL'], apiKey: process.env['TOKEDEX_API_KEY'] }); const stream = client.messages.stream({ model: 'openai/gpt-6-luna', max_tokens: 128000, messages: [{ role: 'user', content: 'Reply with exactly the word "hello".' }], }); stream.on('text', (text: string) => process.stdout.write(text)); await stream.finalMessage(); console.log(); ``` ```python import os from anthropic import Anthropic client = Anthropic(base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"]) with client.messages.stream( model="openai/gpt-6-luna", max_tokens=128000, messages=[{"role": "user", "content": 'Reply with exactly the word "hello".'}], ) as stream: for text in stream.text_stream: print(text, end="", flush=True) print() ``` **curl** ```bash curl -sS -N "$TOKEDEX_BASE_URL/chat/completions" \ -H "Authorization: Bearer $TOKEDEX_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-6-luna", "stream": true, "messages": [{ "role": "user", "content": "Reply with exactly the word \"hello\"." }] }' ``` ```text data: {"object":"chat.completion.chunk","model":"openai/gpt-6-luna","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]} data: {"object":"chat.completion.chunk","model":"openai/gpt-6-luna","choices":[{"index":0,"delta":{"content":"hello"},"finish_reason":null}]} data: {"object":"chat.completion.chunk","model":"openai/gpt-6-luna","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]} data: {"object":"chat.completion.chunk","model":"openai/gpt-6-luna","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":2,"total_tokens":16}} data: [DONE] ``` `-N` prints each event as it arrives. The stream ends with a `usage` chunk and `data: [DONE]`. **Tokedex SDK** ```ts import { Router } from '@tokedex/sdk'; const router = new Router({ baseUrl: process.env['TOKEDEX_URL']!, apiKey: process.env['TOKEDEX_API_KEY']! }); for await (const chunk of router.chat.completions.stream({ model: 'openai/gpt-6-luna', messages: [{ role: 'user', content: 'Reply with exactly the word "hello".' }], })) { process.stdout.write(chunk.choices[0]?.delta.content ?? ''); } console.log(); ``` ```python import os from tokedex import Router with Router(base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"]) as router: with router.chat.completions.stream( model="openai/gpt-6-luna", messages=[{"role": "user", "content": 'Reply with exactly the word "hello".'}], ) as chunks: for chunk in chunks: for choice in chunk.choices: print(choice.delta.content or "", end="", flush=True) print() ``` ```rust use tokedex::{GatewayOptions, Router, StreamExt, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::new(GatewayOptions::new(std::env::var("TOKEDEX_URL")?, std::env::var("TOKEDEX_API_KEY")?))?; let messages = vec![wire::Message::user(r#"Reply with exactly the word "hello"."#)]; let mut chunks = router.chat().completions().stream(wire::ChatCompletionsRequest::new("openai/gpt-6-luna", messages)); while let Some(chunk) = chunks.next().await { for choice in chunk?.choices { if let wire::Presence::Value(text) = choice.delta.content { print!("{text}"); } } } println!(); Ok(()) } ``` **OpenAI SDK, Anthropic SDK, Tokedex SDK** ```text hello ``` **OpenAI SDK** The last chunk carries `usage` and no choices. A streamed request can fail after it starts, so handle an error inside the stream as well as an error status. ## Errors **OpenAI SDK** ```ts import OpenAI from 'openai'; const client = new OpenAI({ baseURL: process.env['TOKEDEX_BASE_URL'], apiKey: process.env['TOKEDEX_API_KEY'] }); try { await client.chat.completions.create({ model: 'unknown/no-such-model', messages: [{ role: 'user', content: 'Hello' }] }); } catch (error) { if (!(error instanceof OpenAI.APIError)) throw error; console.log(error.status, error.code); } ``` ```python import os import openai client = openai.OpenAI(base_url=os.environ["TOKEDEX_BASE_URL"], api_key=os.environ["TOKEDEX_API_KEY"]) try: client.chat.completions.create(model="unknown/no-such-model", messages=[{"role": "user", "content": "Hello"}]) except openai.APIStatusError as error: print(error.status_code, error.code) ``` ```text 404 model_not_found ``` The client raises an `APIError` (Python: `APIStatusError`) with the HTTP status in `status` (Python: `status_code`) and the gateway's error code in `code`. Branch on `code`. **Anthropic SDK** ```ts import Anthropic from '@anthropic-ai/sdk'; const client = new Anthropic({ baseURL: process.env['TOKEDEX_URL'], apiKey: process.env['TOKEDEX_API_KEY'] }); try { await client.messages .stream({ model: 'unknown/no-such-model', max_tokens: 128000, messages: [{ role: 'user', content: 'Hello' }] }) .finalMessage(); } catch (error) { if (!(error instanceof Anthropic.APIError)) throw error; const body = error.error as { error?: { code?: string } } | undefined; console.log(error.status, body?.error?.code); } ``` ```python import os import anthropic client = anthropic.Anthropic(base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"]) try: with client.messages.stream( model="unknown/no-such-model", max_tokens=128000, messages=[{"role": "user", "content": "Hello"}] ) as stream: stream.get_final_message() except anthropic.APIStatusError as error: print(error.status_code, error.body["error"]["code"]) ``` ```text 404 model_not_found ``` The client raises an `APIError` (Python: `APIStatusError`) subclass that follows the status, such as `NotFoundError` for `404`. The body is `{"type":"error","error":{"code":"model_not_found","type":"not_found_error","message":"…"}}`. Branch on `error.code` in the body. **curl** ```bash curl -sS -i "$TOKEDEX_BASE_URL/chat/completions" \ -H "Authorization: Bearer $TOKEDEX_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "unknown/no-such-model", "messages": [{ "role": "user", "content": "Hello" }] }' ``` ```text HTTP/1.1 404 Not Found content-type: application/json {"error":{"code":"model_not_found","message":"model is not available on this gateway","type":"invalid_request_error"}} ``` Branch on `error.code`. Anthropic Messages wraps the same fields as `{"type":"error","error":{…}}`, so `error.code` holds the code there too. **Tokedex SDK** ```ts import { GatewayHttpError, Router } from '@tokedex/sdk'; const router = new Router({ baseUrl: process.env['TOKEDEX_URL']!, apiKey: process.env['TOKEDEX_API_KEY']! }); try { await router.chat.completions.create({ model: 'unknown/no-such-model', messages: [{ role: 'user', content: 'Hello' }] }); } catch (error) { if (!(error instanceof GatewayHttpError)) throw error; console.log(error.status, error.code); } ``` ```python import os import httpx2 from tokedex import Router with Router(base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"]) as router: try: router.chat.completions.create(model="unknown/no-such-model", messages=[{"role": "user", "content": "Hello"}]) except httpx2.HTTPStatusError as error: print(error.response.status_code, error.response.json()["error"]["code"]) ``` ```rust use tokedex::{Error, GatewayOptions, Router, RouterError, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::new(GatewayOptions::new(std::env::var("TOKEDEX_URL")?, std::env::var("TOKEDEX_API_KEY")?))?; let request = wire::ChatCompletionsRequest::new("unknown/no-such-model", vec![wire::Message::user("Hello")]); match router.chat().completions().create(request).await { Err(Error::Router(error)) => { if let RouterError::Provider { status_code, provider_code, .. } = *error { println!("{status_code:?} {provider_code:?}"); } } Err(error) => return Err(error.into()), Ok(_) => {} } Ok(()) } ``` **TypeScript, Python · Tokedex SDK** ```text 404 model_not_found ``` **Rust · Tokedex SDK** ```text Some(404) Some("model_not_found") ``` **TypeScript · Tokedex SDK** The Router throws a `GatewayHttpError`, with the HTTP status in `status` and the gateway's error code in `code`. Branch on `code`. **Python · Tokedex SDK** The Router raises `httpx2.HTTPStatusError`. The status is in `error.response.status_code`, and the gateway's error code in the body's `error.code`. Branch on the code. **Rust · Tokedex SDK** The Router returns `Error::Router` holding a `RouterError::Provider`, with the HTTP status in `status_code` and the gateway's error code in `provider_code`. Branch on `provider_code`. The code names the cause where one status has several: | Status | Code | Means | | --- | --- | --- | | `401` | `invalid_api_key` | The key is wrong or revoked | | `402` | `budget_exceeded` | A budget that applies to the key has run out | | `403` | `permission_denied`, `key_expired`, `key_disabled`, `key_suspended` | The key may not make this request, or cannot be used | | `404` | `model_not_found` | The gateway does not serve this model ID | | `429` | `rate_limited` | A rate limit applies; retry later | | `502`, `503` | `provider_unavailable` and others | The provider failed or could not be reached | A retry sends another provider request and can incur another charge. Retry only `429` and the `5xx` codes that [Errors, limits and request IDs](/gateway/errors-and-limits#retryable-errors) marks retryable: a `401`, `402`, `403` or `404` fails the same way until the key, the budget or the request changes. Next: [Connect a coding agent](/gateway/coding-agents), [Errors, limits and request IDs](/gateway/errors-and-limits) or [Run through a gateway](/sdk/gateway) in the SDK docs. --- # Connect a coding agent Point your coding agent at the gateway with the setup the dashboard writes, so each of its requests is traced and costed. 1. On **Home**, under **Connect your coding agent**, choose your agent, such as **Claude Code**. 2. Under **Gateway key**, choose **Create API key**, then **Copy key line**, and add the line to your shell profile. Or export a key you have as `TOKEDEX_API_KEY`. 3. Under **Model**, choose a model, such as `anthropic/claude-haiku-5.5`. 4. Choose **Copy setup prompt** and paste the prompt into a coding agent on this computer. It sets up yours. 5. In a new session of your agent, ask it to run `printf gateway-ok`. It reports `gateway-ok`. ![The Connect Claude Code panel, with a model chosen and the setup prompt to copy](/images/dashboard/connect-coding-agent.png) You need: the agent, and an API key that can call the model or a role that can create one. Each request the agent sends can incur provider charges. ## Supported agents Claude Code, Codex, Copilot, Cursor, OpenCode, Pi, Grok Build, Kimi Code, Mistral Vibe, DeepSeek Harness, Mirror and Cline. **Model** lists the compatible models your key can call with the selected agent. If the panel says there is no supported setup, choose another agent, such as Pi or OpenCode. For Claude Code, choose a model Anthropic serves. An OpenAI model can stop Claude Code when it [compacts its context](#claude-code-compaction-on-openai-models). A key made on **Home** is your Quick start key: it calls every model you may use and never expires. Keep it for your own computer. For an agent anywhere else, such as a shared machine, create a key from the **Coding agent** template under **API keys**: it expires after 30 days and has a $50 monthly budget, so a key left behind stops on its own and its spend is capped. For another API key, open the key in **API keys** and choose its **Connect** tab, where the last five agents are under **More tools**. Export your saved copy of that key as `TOKEDEX_API_KEY`. ## Setup prompt The setup prompt has the agent read the key from `TOKEDEX_API_KEY` without printing it; the key is never in the prompt. Where there is a desktop app, it asks whether to set up the CLI, the app or both. It merges its settings into the agent's configuration, keeping your others, then checks the key: ```bash export TOKEDEX_URL='http://127.0.0.1:4000' curl -sS -o /dev/null -w '%{http_code}\n' "$TOKEDEX_URL/v1/models" \ -H "Authorization: Bearer $TOKEDEX_API_KEY" ``` ```text 200 ``` A `200` proves only the key, so finish with the `printf gateway-ok` check. To set the agent up by hand, expand **Manual instructions**, with tabs for the **CLI** and the **Desktop app**. A command or configuration holds the key only right after you create it. Otherwise it reads `TOKEDEX_API_KEY` or says ``, which you replace. ## See the agent's requests In **Observability**, the newest request names your key and model. Every agent but Cursor, Mirror and the Cline CLI tags its requests `agent:`; under **Sessions**, a Claude Code, Codex or OpenCode session shows `agent:claude-code`, `agent:codex` or `agent:opencode` under **Tags**. Give each computer you run an agent on its own key. Observability and the spend report then show each one's requests and spend apart, and revoking one key stops one computer only. ## Troubleshoot Claude Code - **401.** `ANTHROPIC_AUTH_TOKEN` must hold your API key and `ANTHROPIC_API_KEY` must be empty, in your shell and any saved environment. In the CLI, `/status` shows the gateway as the base URL. - **422 "the reasoning control $.reasoning.budgetTokens is not supported by this model".** Use the hyphenated model ID, such as `anthropic/claude-opus-4-7` rather than `anthropic/claude-opus-4.7`. Claude Code recognizes Claude Opus 4.6, 4.7 and 4.8 and Sonnet 4.6 only by their hyphenated names. With the dotted ID it sends a manual thinking budget, which these models refuse. - **The desktop app rejects the model.** Choose a Claude model under **Model**. Auto mode also needs a classifier model that the profile lists and the key can call. - **You want your Claude account back.** Sign out of third-party inference, choose **Sign in with Claude.ai** and relaunch. ### Claude Code compaction on OpenAI models When its context fills during a tool loop, Claude Code asks the model for a text-only summary while a tool call is still pending. An OpenAI model can answer with another tool call instead, and Claude Code stops with "summarization produced empty response". This can happen on any model ID that an OpenAI model serves, including `openai/gpt-6-luna` and routers that can choose an OpenAI model. To avoid it, choose a model that Anthropic serves, such as `anthropic/claude-haiku-5.5`. ## Troubleshoot Codex - **An earlier configuration.** In `config.toml` and any active profile, replace the whole `[model_providers.tokedex]` table and its child tables, and remove `model_catalog_json` and `model_instructions_file` overrides. Restart Codex. - **No key.** Start the CLI where `TOKEDEX_API_KEY` is set. For the desktop app, fully quit it; on macOS run `launchctl setenv TOKEDEX_API_KEY "$TOKEDEX_API_KEY"` and `open -a Codex`, again after each macOS sign-out; on Windows, add the variable in **Edit environment variables for your account**. - **The app's picker lacks the model.** Codex uses the one in `config.toml`. ## Switch providers in a session For **Codex**, apply the generated setup for the new model before you resume. On a best-effort route, the gateway replays compatible namespaced tool calls and their results using prefixed names. The current tool list determines which tools the new model can call. When you switch **Kimi Code** from OpenAI Responses to Anthropic Messages, start a new session on the new model. Carry forward a text summary of your work and any results the new session needs. A resumed session can send the old provider's signed thinking as Anthropic thinking, which Anthropic rejects with `Invalid signature`. ## Troubleshoot other agents - In the **Cursor editor**, open **Settings → Models → API Keys**. Turn on **Use OpenAI API Key**, enable **Override OpenAI Base URL**, then add the exact model ID from the dashboard. This setup requires a public HTTPS gateway address and a signed-in editor. Use one of the other agents for a loopback-only gateway. [Cursor editor setup](https://forum.cursor.com/t/how-to-adjust-settings-for-custom-added-models/173253/21) · [HTTPS and reverse proxies](/gateway/https) - To resume **Cline**, open a terminal and run `cline --id ` for an interactive session. Use a fresh session for headless `--json` commands, which cannot currently resume by ID. [Cline CLI reference](https://docs.cline.bot/cli/cli-reference) - **Copilot** needs a model with a thinking effort on Chat Completions. In VS Code, keep the `apiKey` VS Code wrote, and restart VS Code if the model is missing. - **OpenCode** needs OpenCode 2 (`@opencode/cli`), **Mistral Vibe** 3.1.2 or later, and **DeepSeek Harness** Node.js 24.9 or newer. - **A snippet says ``.** The key can call no model on that API. Put a model ID from [Find a model](/gateway/models) in its place. Next: [API keys](/gateway/api-keys), [Find and inspect a request](/gateway/requests-and-sessions) or [Errors, limits and request IDs](/gateway/errors-and-limits). --- # Find a model List the model IDs your API key can call on the API your client speaks, with the context window of each. **OpenAI SDK** ```ts import OpenAI from 'openai'; const client = new OpenAI({ baseURL: process.env['TOKEDEX_BASE_URL'], apiKey: process.env['TOKEDEX_API_KEY'] }); for await (const model of client.models.list()) { const row = model as typeof model & { client_dialect_id?: string; context_window?: number }; if (row.client_dialect_id === 'openai.chat-completions') console.log(row.id, row.context_window); } ``` ```python import os from openai import OpenAI client = OpenAI(base_url=os.environ["TOKEDEX_BASE_URL"], api_key=os.environ["TOKEDEX_API_KEY"]) for model in client.models.list(): if getattr(model, "client_dialect_id", None) == "openai.chat-completions": print(model.id, getattr(model, "context_window", None)) ``` **Anthropic SDK** ```ts import Anthropic from '@anthropic-ai/sdk'; const client = new Anthropic({ baseURL: process.env['TOKEDEX_URL'], apiKey: process.env['TOKEDEX_API_KEY'] }); for await (const model of client.models.list()) { const row = model as typeof model & { client_dialect_id?: string; context_window?: number }; if (row.client_dialect_id === 'anthropic.messages') console.log(row.id, row.context_window); } ``` ```python import os from anthropic import Anthropic client = Anthropic(base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"]) for model in client.models.list(): if getattr(model, "client_dialect_id", None) == "anthropic.messages": print(model.id, getattr(model, "context_window", None)) ``` **curl** ```bash curl -sS "$TOKEDEX_BASE_URL/models" \ -H "Authorization: Bearer $TOKEDEX_API_KEY" ``` ```json { "object": "list", "data": [ { "id": "openai/gpt-6-luna", "object": "model", "created": 0, "owned_by": "tokedex", "client_dialect_id": "openai.chat-completions", "native_batch": [{ "operation": "chat.completions", "status": "supported", "available": false, "unavailableReason": "managed-key-unavailable" }], "context_window": 1050000, "max_input_tokens": 1050000 }, … ], "models": […] } ``` **Tokedex SDK** ```ts import { Router } from '@tokedex/sdk'; const router = new Router({ baseUrl: process.env['TOKEDEX_URL']!, apiKey: process.env['TOKEDEX_API_KEY']! }); for (const model of await router.models.list()) { if (model.client_dialect_id === 'openai.chat-completions') console.log(model.id, model.context_window); } ``` ```python import os from tokedex import Router with Router(base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"]) as router: for model in router.models.list(): if model.client_dialect_id == "openai.chat-completions": print(model.id, model.context_window) ``` ```rust use tokedex::{GatewayOptions, Router}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::new(GatewayOptions::new(std::env::var("TOKEDEX_URL")?, std::env::var("TOKEDEX_API_KEY")?))?; for model in router.models().list().await? { if model.client_dialect_id == "openai.chat-completions" { println!("{} {:?}", model.id, model.context_window); } } Ok(()) } ``` **Rust · OpenAI SDK, Anthropic SDK** For Rust, choose **Tokedex SDK** in the bar above: its Rust client takes the same address and key. **OpenAI SDK, Anthropic SDK** ```text … anthropic/claude-haiku-5.5 1000000 openai/gpt-6-luna 1050000 … ``` **TypeScript, Python · Tokedex SDK** ```text … anthropic/claude-haiku-5.5 1000000 openai/gpt-6-luna 1050000 … ``` **Rust · Tokedex SDK** ```text … anthropic/claude-haiku-5.5 Some(1000000) openai/gpt-6-luna Some(1050000) … ``` You need: the gateway's address and an API key; see [Connect your app](/gateway/connect-your-app). Listing sends nothing to a provider and costs nothing. ## Model row fields Each model ID has one row for every client API that serves it. Use `client.models.retrieve(id)` in the OpenAI or Anthropic SDK to read a listed model. For a direct request to `GET /v1/models/{id}`, URL-encode the full ID, including any slash. With a bearer API key, add `?client_dialect_id=openai.responses` to read one specific API's row and routing. Use the dialect ID from its list row. An unavailable row returns `404`. With no selector, a bearer request prefers OpenAI Chat Completions, then OpenAI Responses, then the first available row. | Field | Means | | --- | --- | | `id` | The model ID to send in `model` | | `client_dialect_id` | The client API: `openai.chat-completions`, `openai.responses`, `anthropic.messages` or `google.generate-content` | | `context_window` | The most tokens one request can hold; `max_input_tokens` is the same | | `native_batch` | Whether a Batch job can run the model | | `trust` | `unreviewed` on a model from your organisation's own model server | Send a model ID only on an API that lists it, here `openai.chat-completions` (Anthropic SDK: `anthropic.messages`). Some models are served on one API only. A model served from your organisation's own model server is listed only to a key that names it, and has no `context_window`. ## Routers A router is a model ID that chooses a model for each request. You send it like any other ID, and its `context_window` is the smallest of its models'. The built-in ones start with `aa/` and choose only among connected providers: - `aa/most-intelligent` ranks eligible models by Artificial Analysis Intelligence Index, `aa/cheapest` by benchmarked cost per task, and `aa/fastest` by benchmarked time per task. Send a fixed model ID when you need the same model every time, such as for an evaluation or a prompt tuned to one model. [Routers and fallback](/gateway/router) explains fallback and how your organisation adds its own router. ## Find the model that answered **OpenAI SDK** ```ts import OpenAI from 'openai'; const client = new OpenAI({ baseURL: process.env['TOKEDEX_BASE_URL'], apiKey: process.env['TOKEDEX_API_KEY'] }); const { data: completion, response } = await client.chat.completions .create({ model: 'aa/cheapest', messages: [{ role: 'user', content: 'Reply with exactly the word "hello".' }] }) .withResponse(); console.log(completion.model, response.headers.get('x-tokedex-provider'), response.headers.get('x-tokedex-model')); ``` ```python import os from openai import OpenAI client = OpenAI(base_url=os.environ["TOKEDEX_BASE_URL"], api_key=os.environ["TOKEDEX_API_KEY"]) raw = client.chat.completions.with_raw_response.create( model="aa/cheapest", messages=[{"role": "user", "content": 'Reply with exactly the word "hello".'}], ) print(raw.parse().model, raw.headers.get("x-tokedex-provider"), raw.headers.get("x-tokedex-model")) ``` **Anthropic SDK** ```ts import Anthropic from '@anthropic-ai/sdk'; const client = new Anthropic({ baseURL: process.env['TOKEDEX_URL'], apiKey: process.env['TOKEDEX_API_KEY'] }); const { data: messageStream, response } = await client.messages .stream({ model: 'aa/cheapest', max_tokens: 128000, messages: [{ role: 'user', content: 'Reply with exactly the word "hello".' }] }) .withResponse(); const message = await messageStream.finalMessage(); console.log(message.model, response.headers.get('x-tokedex-provider'), response.headers.get('x-tokedex-model')); ``` ```python import os from anthropic import Anthropic client = Anthropic(base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"]) with client.messages.stream( model="aa/cheapest", max_tokens=128000, messages=[{"role": "user", "content": 'Reply with exactly the word "hello".'}], ) as stream: message = stream.get_final_message() print(message.model, stream.response.headers.get("x-tokedex-provider"), stream.response.headers.get("x-tokedex-model")) ``` **OpenAI SDK** ```text aa/cheapest ``` **Anthropic SDK** ```text aa/cheapest ``` **curl** ```bash curl -sS -D - -o /dev/null "$TOKEDEX_BASE_URL/chat/completions" \ -H "Authorization: Bearer $TOKEDEX_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "aa/cheapest", "messages": [{ "role": "user", "content": "Reply with exactly the word \"hello\"." }] }' ``` ```text HTTP/1.1 200 OK x-tokedex-provider: x-tokedex-model: x-tokedex-deployment: x-tokedex-strategy: model-group.cost-per-task.v1 x-request-id: 68078326-… ``` **Tokedex SDK** ```ts import { Router } from '@tokedex/sdk'; const router = new Router({ baseUrl: process.env['TOKEDEX_URL']!, apiKey: process.env['TOKEDEX_API_KEY']!, onResponseHeaders: (headers) => console.log(headers['x-tokedex-provider'], headers['x-tokedex-model']), }); const completion = await router.chat.completions.create({ model: 'aa/cheapest', messages: [{ role: 'user', content: 'Reply with exactly the word "hello".' }], }); console.log(completion.model); ``` ```python import os from collections.abc import Mapping from tokedex import Router def show(headers: Mapping[str, str]) -> None: print(headers.get("x-tokedex-provider"), headers.get("x-tokedex-model")) with Router(base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"], on_response_headers=show) as router: completion = router.chat.completions.create( model="aa/cheapest", messages=[{"role": "user", "content": 'Reply with exactly the word "hello".'}], ) print(completion.model) ``` ```rust use std::sync::Arc; use tokedex::{GatewayOptions, Router, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let mut options = GatewayOptions::new(std::env::var("TOKEDEX_URL")?, std::env::var("TOKEDEX_API_KEY")?); options.on_response_headers = Some(Arc::new(|headers| { println!("{:?} {:?}", headers.get("x-tokedex-provider"), headers.get("x-tokedex-model")); })); let router = Router::new(options)?; let messages = vec![wire::Message::user(r#"Reply with exactly the word "hello"."#)]; let completion = router.chat().completions().create(wire::ChatCompletionsRequest::new("aa/cheapest", messages)).await?; println!("{}", completion.model); Ok(()) } ``` **TypeScript, Python · Tokedex SDK** ```text aa/cheapest ``` **Rust · Tokedex SDK** ```text Some("") Some("") aa/cheapest ``` The request calls a provider and can incur charges. `x-tokedex-provider` names the provider that answered, after any fallback, and `x-tokedex-model` its name for the model; the reply's `model` stays the ID you sent. Every successful response has both headers. When a model from your organisation's own model server answers, `x-tokedex-trust` is `unreviewed`. Behind a router, the model that answers can change between requests and between client APIs, so log `x-tokedex-provider` and `x-tokedex-model` beside any result you compare or debug later. ## Choose a provider When several providers serve a model on one client API, the gateway tries them in the model's provider order: by default cheapest list price first, or the order an operator [sets](/gateway/router#set-a-models-provider-routing). A request can instead name the providers allowed to serve it in the `x-tokedex-provider` header, separated by commas. Only those are tried, in the request's provider order: the model's order, with any that [`x-tokedex-provider-order`](#prefer-providers) names moved first. The order of the IDs in `x-tokedex-provider` does not rank them. When none of them can serve the request, the gateway refuses it with `422` `provider_not_served` rather than sending it elsewhere, and the error's `providers` lists the providers that can. **curl** ```bash curl -sS -i "$TOKEDEX_BASE_URL/chat/completions" \ -H "Authorization: Bearer $TOKEDEX_API_KEY" \ -H "Content-Type: application/json" \ -H "x-tokedex-provider: " \ -d '{ "model": "", "messages": [{ "role": "user", "content": "Reply with exactly the word \"hello\"." }] }' ``` **OpenAI SDK** ```ts import OpenAI from 'openai'; const client = new OpenAI({ baseURL: process.env['TOKEDEX_BASE_URL'], apiKey: process.env['TOKEDEX_API_KEY'] }); const { data: completion, response } = await client.chat.completions.create( { model: '', messages: [{ role: 'user', content: 'Reply with exactly the word "hello".' }] }, { headers: { 'x-tokedex-provider': '' } }, ).withResponse(); console.log(response.headers.get('x-tokedex-provider'), completion.choices[0]?.message.content); ``` ```python import os from openai import OpenAI client = OpenAI(base_url=os.environ["TOKEDEX_BASE_URL"], api_key=os.environ["TOKEDEX_API_KEY"]) raw = client.chat.completions.with_raw_response.create( model="", messages=[{"role": "user", "content": 'Reply with exactly the word "hello".'}], extra_headers={"x-tokedex-provider": ""}, ) print(raw.headers.get("x-tokedex-provider"), raw.parse().choices[0].message.content) ``` **Anthropic SDK** ```ts import Anthropic from '@anthropic-ai/sdk'; const client = new Anthropic({ baseURL: process.env['TOKEDEX_URL'], apiKey: process.env['TOKEDEX_API_KEY'] }); const { data: message, response } = await client.messages.create( { model: '', max_tokens: 64, messages: [{ role: 'user', content: 'Reply with exactly the word "hello".' }] }, { headers: { 'x-tokedex-provider': '' } }, ).withResponse(); console.log(response.headers.get('x-tokedex-provider'), message.content); ``` ```python import os from anthropic import Anthropic client = Anthropic(base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"]) raw = client.messages.with_raw_response.create( model="", max_tokens=64, messages=[{"role": "user", "content": 'Reply with exactly the word "hello".'}], extra_headers={"x-tokedex-provider": ""}, ) print(raw.headers.get("x-tokedex-provider"), raw.parse().content) ``` **Tokedex SDK** The Tokedex SDKs take the providers as a `providers` option and tell `onServed` which provider served, before the result or the first event. A call that also sets the header allows only the providers both name. ```ts import { ProviderNotServedError, Router } from '@tokedex/sdk'; const router = new Router({ baseUrl: process.env['TOKEDEX_URL']!, apiKey: process.env['TOKEDEX_API_KEY']! }); try { const completion = await router.chat.completions.create( { model: '', messages: [{ role: 'user', content: 'Reply with exactly the word "hello".' }] }, { providers: [''], onServed: (served) => console.log(served.provider, served.upstreamModel) }, ); console.log(completion.choices[0]?.message.content); } catch (error) { if (!(error instanceof ProviderNotServedError)) throw error; console.log('Providers that can serve it:', error.providers); } ``` ```python import os from tokedex import ProviderNotServedError, Router with Router(base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"]) as router: try: completion = router.chat.completions.create( model="", messages=[{"role": "user", "content": 'Reply with exactly the word "hello".'}], providers=[""], on_served=lambda served: print(served.provider, served.upstream_model), ) print(completion.choices[0].message.content) except ProviderNotServedError as error: print("Providers that can serve it:", error.providers) ``` ```rust use tokedex::{Error, GatewayOptions, RequestOptions, Router, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::new(GatewayOptions::new(std::env::var("TOKEDEX_URL")?, std::env::var("TOKEDEX_API_KEY")?))?; let pinned = router.with_options( RequestOptions::default() .providers([""]) .on_served(|served| println!("{} {}", served.provider, served.upstream_model)), ); let messages = vec![wire::Message::user(r#"Reply with exactly the word "hello"."#)]; match pinned.chat().completions().create(wire::ChatCompletionsRequest::new("", messages)).await { Ok(completion) => println!("{:?}", completion.choices.first().map(|choice| &choice.message.content)), Err(Error::ProviderNotServed(refused)) => println!("Providers that can serve it: {:?}", refused.providers), Err(error) => return Err(error.into()), } Ok(()) } ``` The request calls a provider and can incur charges. Every response names the provider that served it in its own `x-tokedex-provider` header. An ID that names no provider is refused with `400` `invalid_request`. A follow-up turn that carries state only the provider that answered accepts, such as a stored response (`previous_response_id`), signed reasoning or signed tool calls, stays with that provider; a pin that leaves that provider out is refused with `422`, and `providers` names it. Any other follow-up turn follows the provider order, retrying each provider before it moves to the next. The pin applies the same way to token counting, Batch jobs and routers: a router picks only among its models that a named provider serves. Open a model in **Models & Routing**. **Use a specific provider** shows the header with the model's provider IDs, and **Try it in the Playground** opens a request pinned to the first connected one. In the Playground, the **Provider** field sets the header, and the response says which provider served it. ### Prefer providers ```http x-tokedex-provider-order: , ``` To prefer providers without excluding the others, send `x-tokedex-provider-order` instead. The providers it names are tried first, in its order, and the rest follow in the model's order; it beats an order an operator set. Use it when one provider answers your prompts better or faster, and keep `x-tokedex-provider` for a request that must never reach another provider. - **A preference.** A named provider that does not serve the model, or has no credentials, is skipped without an error. - **Refusals.** An ID that names no provider, or a value that is not provider IDs separated by commas, gets `400` `invalid_request` naming the header. - **Where it applies.** The four client APIs, token counting and `POST /v1/batches`. With `x-tokedex-provider` as well, the pin chooses the providers and the order ranks them. - **Routers.** On a [router](/gateway/router), the order ranks the providers of each model the router tries. It never changes which models the router picks or the order it tries them in. - **Follow-up turns.** A follow-up turn that stays with the provider that answered, such as one continuing a stored response, ignores the order. The Tokedex SDKs send it from a call option or from a per-model Router setting; see [Order the providers](/sdk/models#order-the-providers). ## Missing or refused models | What you see | Why | | --- | --- | | Listed only for another API | The model is served there only | | `404` `model_not_found` | The ID is misspelled, not served on this API, turned off, or its provider has no credentials | | `403` `permission_denied` | Your key, workspace or organisation does not allow the model or its provider. A key limited to some models gets this for every other ID, misspelled ones included. | | `422` `unsupported` | The model or API cannot serve part of the request, such as a tool or an image | | Not listed, yet it answers | The model is hidden from the list | | An empty list | No provider is connected, or your key can call no model | An admin fixes these in [Model access and limits](/gateway/model-access-and-limits), [API keys](/gateway/api-keys) or [Provider credentials](/gateway/provider-credentials). ## Check feature support Support depends on the client API and the model. The model list gives each model's client API, context window and Batch support, but not the features it accepts. To find out, try the request in the dashboard's **Playground**: start with plain text, then add streaming, tools, structured output, reasoning or images one at a time, so a refusal points at one feature. When a model cannot take a request exactly as sent, the gateway approximates it where the model allows that, and reports what it changed; otherwise it refuses with `422` `unsupported`. Approximating is the default, `best_effort`. Send `x-tokedex-fidelity-policy: strict` to get the refusal instead. Send `strict` when your code depends on the feature, such as structured output it parses, so a model that cannot honour it fails with `422` instead of dropping or approximating it; use `best_effort` when an approximate answer is still useful. These response headers report what happened: | Header | Holds | | --- | --- | | `x-tokedex-fidelity-policy` | The policy the gateway applied | | `x-tokedex-fidelity-v1` | Sent when you ask for `best_effort` or the gateway changed the request: a JSON report in which `fidelity` is `native` when the model received the request as sent, and each entry in `degradations` names a field the gateway dropped or approximated | Next: [Errors, limits and request IDs](/gateway/errors-and-limits) or [Routers and fallback](/gateway/router). --- # Errors, limits and request IDs Read the gateway's error code to decide whether to retry, wait or fix the request. **OpenAI SDK** ```ts import OpenAI from 'openai'; const client = new OpenAI({ baseURL: process.env['TOKEDEX_BASE_URL'], apiKey: process.env['TOKEDEX_API_KEY'], maxRetries: 0 }); const RETRY = ['rate_limited', 'provider_unavailable', 'provider_timeout', 'invalid_upstream_response', 'limits_unavailable', 'continuation_unavailable']; try { await client.chat.completions.create({ model: 'openai/gpt-6-luna', messages: [{ role: 'user', content: 'Hello' }] }); } catch (error) { if (!(error instanceof OpenAI.APIError)) throw error; console.log(error.status, error.code, RETRY.includes(error.code ?? '') ? 'retry' : 'do not retry'); } ``` ```python import os import openai client = openai.OpenAI(base_url=os.environ["TOKEDEX_BASE_URL"], api_key=os.environ["TOKEDEX_API_KEY"], max_retries=0) RETRY = {"rate_limited", "provider_unavailable", "provider_timeout", "invalid_upstream_response", "limits_unavailable", "continuation_unavailable"} try: client.chat.completions.create(model="openai/gpt-6-luna", messages=[{"role": "user", "content": "Hello"}]) except openai.APIStatusError as error: print(error.status_code, error.code, "retry" if error.code in RETRY else "do not retry") ``` **Anthropic SDK** ```ts import Anthropic from '@anthropic-ai/sdk'; const client = new Anthropic({ baseURL: process.env['TOKEDEX_URL'], apiKey: process.env['TOKEDEX_API_KEY'], maxRetries: 0 }); const RETRY = ['rate_limited', 'provider_unavailable', 'provider_timeout', 'invalid_upstream_response', 'limits_unavailable', 'continuation_unavailable']; try { await client.messages .stream({ model: 'openai/gpt-6-luna', max_tokens: 128000, messages: [{ role: 'user', content: 'Hello' }] }) .finalMessage(); } catch (error) { if (!(error instanceof Anthropic.APIError)) throw error; const code = (error.error as { error?: { code?: string } } | undefined)?.error?.code ?? ''; console.log(error.status, code, RETRY.includes(code) ? 'retry' : 'do not retry'); } ``` ```python import os import anthropic client = anthropic.Anthropic(base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"], max_retries=0) RETRY = {"rate_limited", "provider_unavailable", "provider_timeout", "invalid_upstream_response", "limits_unavailable", "continuation_unavailable"} try: with client.messages.stream( model="openai/gpt-6-luna", max_tokens=128000, messages=[{"role": "user", "content": "Hello"}] ) as stream: stream.get_final_message() except anthropic.APIStatusError as error: code = error.body["error"]["code"] print(error.status_code, code, "retry" if code in RETRY else "do not retry") ``` **OpenAI SDK, Anthropic SDK** ```text 429 rate_limited retry ``` **Rust · OpenAI SDK, Anthropic SDK** For Rust, choose **Tokedex SDK** in the bar above: its Rust client takes the same address and key. **curl** ```bash curl -sS -i "$TOKEDEX_BASE_URL/chat/completions" \ -H "Authorization: Bearer $TOKEDEX_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-6-luna", "messages": [{ "role": "user", "content": "Hello" }] }' ``` ```text HTTP/1.1 429 Too Many Requests retry-after: 60 retry-after-ms: 59963 x-request-id: da0663a0-… {"error":{"code":"rate_limited","message":"rate limit exceeded: 1 requests per minute for this key; retry in 60 s","type":"rate_limit_error","limit":{"scope":"key","retry_after_ms":59963}}} ``` **Tokedex SDK** ```ts import { GatewayHttpError, Router } from '@tokedex/sdk'; const router = new Router({ baseUrl: process.env['TOKEDEX_URL']!, apiKey: process.env['TOKEDEX_API_KEY']! }); const RETRY = ['rate_limited', 'provider_unavailable', 'provider_timeout', 'invalid_upstream_response', 'limits_unavailable', 'continuation_unavailable']; try { await router.chat.completions.create({ model: 'openai/gpt-6-luna', messages: [{ role: 'user', content: 'Hello' }] }); } catch (error) { if (!(error instanceof GatewayHttpError)) throw error; console.log(error.status, error.code, RETRY.includes(String(error.code)) ? 'retry' : 'do not retry'); } ``` ```python import os import httpx2 from tokedex import Router RETRY = {"rate_limited", "provider_unavailable", "provider_timeout", "invalid_upstream_response", "limits_unavailable", "continuation_unavailable"} with Router(base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"]) as router: try: router.chat.completions.create(model="openai/gpt-6-luna", messages=[{"role": "user", "content": "Hello"}]) except httpx2.HTTPStatusError as error: code = error.response.json()["error"]["code"] print(error.response.status_code, code, "retry" if code in RETRY else "do not retry") ``` ```rust use tokedex::{Error, GatewayOptions, Router, RouterError, wire}; const RETRY: [&str; 6] = ["rate_limited", "provider_unavailable", "provider_timeout", "invalid_upstream_response", "limits_unavailable", "continuation_unavailable"]; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::new(GatewayOptions::new(std::env::var("TOKEDEX_URL")?, std::env::var("TOKEDEX_API_KEY")?))?; let request = wire::ChatCompletionsRequest::new("openai/gpt-6-luna", vec![wire::Message::user("Hello")]); if let Err(Error::Router(error)) = router.chat().completions().create(request).await { if let RouterError::Provider { status_code, provider_code, .. } = *error { let code = provider_code.unwrap_or_default(); println!("{status_code:?} {code} {}", if RETRY.contains(&code.as_str()) { "retry" } else { "do not retry" }); } } Ok(()) } ``` **TypeScript, Python · Tokedex SDK** ```text 429 rate_limited retry ``` **Rust · Tokedex SDK** ```text Some(429) rate_limited retry ``` This output comes from a key over its limit of one request a minute. You need: an API key that can call `openai/gpt-6-luna`, set up as in [Connect your app](/gateway/connect-your-app). A request that succeeds calls a provider and can incur charges. ## Branch on the error code **OpenAI SDK** The code is in `error.code`. Several causes share one status, such as `403`, so branch on the code rather than the status. **Anthropic SDK** The code is in the body's `error.code`, the body being `error.error` (Python: `error.body`). The status and the Anthropic `error.type`, such as `rate_limit_error`, are shared by several causes, so branch on the code. **curl** Branch on `error.code`. On Anthropic Messages the body is `{"type":"error","error":{…}}` with the same `error.code`. The status is shared by several causes, such as `403`. **Tokedex SDK** The code is in [[`code`|the body's `error.code`|`provider_code`]]. Several causes share one status, such as `403`, so branch on the code. ## Retryable errors | Code | Status | Retry? | | --- | --- | --- | | `rate_limited` | `429` | Yes, after `retry-after` seconds | | `provider_unavailable`, `invalid_upstream_response`, `provider_timeout` | `503`, `502`, `504` | Yes, with backoff | | `limits_unavailable`, `continuation_unavailable` | `503` | Yes, with backoff | | `budget_exceeded` | `402` | Not until the budget resets | | `provider_not_served` | `422` | No: name a provider from the error's `providers` in `x-tokedex-provider`, or drop the header ([Choose a provider](/gateway/models#choose-a-provider)) | | Every other code | `4xx`, `5xx` | No: change the request, the key or the gateway's setup | The gateway already retries for you before it answers: it moves to the model's next provider after a rate limit, an outage or a timeout, and, for a model that several providers serve, tries the same provider again first on a follow-up turn of a conversation. A retry is a new provider request and can incur another charge. Set a client timeout long enough for your longest response; a timed-out request that the client retries is a new provider request. Cap the attempts, and stop on any code not marked Yes, so a lasting failure does not become repeated charges. **OpenAI SDK, Anthropic SDK** The client retries a timeout, a connection error, `408`, `409`, `429` and `5xx` twice on its own, waiting as `retry-after` says, unless you set `maxRetries` (Python, Rust: `max_retries`). A `402` carries `x-should-retry: false`, so the client does not retry it. Keep one layer of retries: rely on the client's, or set `maxRetries` (Python, Rust: `max_retries`) to `0`, as the first example does, when you write your own loop. Two layers multiply the attempts, and each attempt can be charged. **Tokedex SDK** The Router does not retry an error the gateway sends back; the gateway does its own retrying and fallback before it answers. Retry `rate_limited` yourself after `retry-after`, and the other codes marked Yes with backoff, since the Router hands them straight to you. ## Rate limits Each replica counts a key's requests separately. A key limited to 60 requests a minute can reach 120 requests a minute when traffic is spread evenly across two replicas. A replica that reaches the key's limit returns `429` `rate_limited` with `error.limit.scope` set to `key`. `retry-after` gives the wait in seconds, and `retry-after-ms` gives it in milliseconds. While a budget applies, each replica also caps concurrent requests. The defaults are 32 running requests per key and 256 for each other budget scope that applies, such as the workspace. A request over either cap gets `429` with `retry-after: 1`, and `error.limit.scope` names the scope. Rate-limit headers on a successful response report the counter on the replica that handled it: ```text x-tokedex-ratelimit-limit: 1 x-tokedex-ratelimit-remaining: 0 x-tokedex-ratelimit-reset-ms: 60000 ``` Slow down as `x-tokedex-ratelimit-remaining` nears `0`. Apply a shared limit in your clients if you need one rate limit across replicas. A provider can rate-limit the gateway too. That `429` has no `error.limit`, and `retry-after` only when the provider sent one. ## Budget refusals The gateway refuses the request with `402` before it reaches a provider, with `x-should-retry: false`: ```json { "error": { "code": "budget_exceeded", "message": "budget exceeded: this request could cost more than the key budget for today (UTC) has left; lower max_tokens or shorten the input, or wait: it resets at 2026-11-21T00:00:00.000Z", "type": "insufficient_quota", "limit": { "scope": "key", "window": "day", "resets_at": "2026-11-21T00:00:00.000Z", "limit_usd": "0.000010", "spent_usd": "0.000009" } } } ``` A refusal by a workspace, organisation or model budget leaves out `limit_usd` and `spent_usd`. Try again after `error.limit.resets_at`, or lower `max_tokens` when the message says the request could cost more than is left. Anthropic Messages sends the same fields with `error.type` `billing_error`. The tightest of the key's and its holder's own budgets is reported on each success in `x-tokedex-budget-remaining-usd` and the other `x-tokedex-budget-*` headers; [Budgets](/gateway/budgets#when-a-budget-is-used-up) explains them. To see where your key stands before a request is refused, send `GET /v1/limits` with the key. It returns every budget and rate limit that reaches the key, with a budget's amounts where the gateway discloses them. The rate counters are for the replica that answers. Check it before a long batch job, so the job does not stop halfway on a spent budget. **Tokedex SDK** The SDK reads it with `router.limits.retrieve()` (Rust: `router.limits().retrieve()`); see [Run through a gateway](/sdk/gateway#read-your-keys-budgets-and-rate-limits). ## Errors inside a stream **curl** The status is already `200`, so the error arrives as an event and the text sent before it stays. On OpenAI Chat Completions the failed stream ends like this. ```text data: {"object":"chat.completion.chunk","model":"openai/gpt-6-luna","choices":[{"index":0,"delta":{"content":"Hel"},"finish_reason":null}]} data: {"error":{"code":"provider_unavailable","message":"upstream unavailable","type":"api_error"}} data: [DONE] ``` On OpenAI Responses a failure after partial output ends the stream with `response.failed`. ```text event: response.output_text.delta data: {"type":"response.output_text.delta","sequence_number":4,"output_index":0,"item_id":"msg_example","content_index":0,"delta":"Hel"} event: response.failed data: {"type":"response.failed","sequence_number":5,"response":{"id":"resp_example","object":"response","created_at":1795219200,"model":"openai/gpt-6-luna","status":"failed","output":[],"usage":null},"error":{"code":"stream_error","message":"stream failed: internal error","type":"api_error"}} ``` Treat `response.failed` as a failure and read `error.code` from the event data. On Anthropic Messages, check `event: error` and read `error.code` from its data. **OpenAI SDK** On OpenAI Chat Completions and OpenAI Responses, the OpenAI SDK raises `OpenAI.APIError` (Python: `openai.APIError`) when it reads an event with an `error` object. Catch the exception around the whole loop and read its `code`. If you read OpenAI Responses events directly, treat `response.failed` as a failure even after partial output and read `error.code` from the event data. **Anthropic SDK** Iterating the stream raises `Anthropic.APIError` (Python: `anthropic.APIStatusError`) with the same body as above, and the text sent before it stays. Catch it around the loop as well as around the call. **TypeScript · Tokedex SDK** Iterating the stream throws `GatewayHttpError` with the code in `code` and `status` `200`, the status the stream started with. The text sent before it stays. **Python · Tokedex SDK** An error event raises `httpx2.HTTPStatusError` with `status_code` `200`. Read the failing event and its code from `error.response.json()`. If the stream closes before its terminal event, iteration raises `ValueError`. Catch both around the whole loop. The text sent before the error stays. **Rust · Tokedex SDK** Reading the stream returns `Error::Router` holding the same `RouterError::Provider` as a call. The text sent before it stays. A reverse proxy in front of the gateway must not buffer streamed responses, or a stream reaches your client in one piece. ## Make a request easy to find **OpenAI SDK** ```ts import OpenAI from 'openai'; const client = new OpenAI({ baseURL: process.env['TOKEDEX_BASE_URL'], apiKey: process.env['TOKEDEX_API_KEY'], defaultHeaders: { 'x-tokedex-project-name': 'storefront' }, }); const { response } = await client.chat.completions .create( { model: 'openai/gpt-6-luna', messages: [{ role: 'user', content: 'Reply with exactly the word "hello".' }] }, { headers: { 'x-tokedex-trajectory-id': 'order-4821', 'x-tokedex-tags': 'checkout,eval' } }, ) .withResponse(); console.log(response.headers.get('x-request-id')); ``` ```python import os from openai import OpenAI client = OpenAI( base_url=os.environ["TOKEDEX_BASE_URL"], api_key=os.environ["TOKEDEX_API_KEY"], default_headers={"x-tokedex-project-name": "storefront"}, ) raw = client.chat.completions.with_raw_response.create( model="openai/gpt-6-luna", messages=[{"role": "user", "content": 'Reply with exactly the word "hello".'}], extra_headers={"x-tokedex-trajectory-id": "order-4821", "x-tokedex-tags": "checkout,eval"}, ) print(raw.headers.get("x-request-id")) ``` **Anthropic SDK** ```ts import Anthropic from '@anthropic-ai/sdk'; const client = new Anthropic({ baseURL: process.env['TOKEDEX_URL'], apiKey: process.env['TOKEDEX_API_KEY'], defaultHeaders: { 'x-tokedex-project-name': 'storefront' }, }); const { data: messageStream, response } = await client.messages .stream( { model: 'openai/gpt-6-luna', max_tokens: 128000, messages: [{ role: 'user', content: 'Reply with exactly the word "hello".' }] }, { headers: { 'x-tokedex-trajectory-id': 'order-4821', 'x-tokedex-tags': 'checkout,eval' } }, ) .withResponse(); await messageStream.finalMessage(); console.log(response.headers.get('request-id')); ``` ```python import os from anthropic import Anthropic client = Anthropic( base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"], default_headers={"x-tokedex-project-name": "storefront"}, ) with client.messages.stream( model="openai/gpt-6-luna", max_tokens=128000, messages=[{"role": "user", "content": 'Reply with exactly the word "hello".'}], extra_headers={"x-tokedex-trajectory-id": "order-4821", "x-tokedex-tags": "checkout,eval"}, ) as stream: stream.get_final_message() print(stream.response.headers.get("request-id")) ``` **curl** ```bash curl -sS -D - -o /dev/null "$TOKEDEX_BASE_URL/chat/completions" \ -H "Authorization: Bearer $TOKEDEX_API_KEY" \ -H "Content-Type: application/json" \ -H "x-tokedex-trajectory-id: order-4821" \ -H "x-tokedex-tags: checkout,eval" \ -H "x-tokedex-project-name: storefront" \ -d '{ "model": "openai/gpt-6-luna", "messages": [{ "role": "user", "content": "Reply with exactly the word \"hello\"." }] }' ``` **Tokedex SDK** ```ts import { Router } from '@tokedex/sdk'; const router = new Router({ baseUrl: process.env['TOKEDEX_URL']!, apiKey: process.env['TOKEDEX_API_KEY']!, headers: { 'x-tokedex-project-name': 'storefront' }, onResponseHeaders: (headers) => console.log(headers['x-request-id']), }); await router.chat.completions.create( { model: 'openai/gpt-6-luna', messages: [{ role: 'user', content: 'Reply with exactly the word "hello".' }] }, { headers: { 'x-tokedex-trajectory-id': 'order-4821', 'x-tokedex-tags': 'checkout,eval' } }, ); ``` ```python import os from collections.abc import Mapping from tokedex import Router def log_request_id(headers: Mapping[str, str]) -> None: print(headers.get("x-request-id")) with Router( base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"], default_headers={"x-tokedex-project-name": "storefront"}, on_response_headers=log_request_id, ) as router: router.chat.completions.create( model="openai/gpt-6-luna", messages=[{"role": "user", "content": 'Reply with exactly the word "hello".'}], extra_headers={"x-tokedex-trajectory-id": "order-4821", "x-tokedex-tags": "checkout,eval"}, ) ``` ```rust use std::sync::Arc; use tokedex::{GatewayOptions, RequestOptions, Router, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let mut options = GatewayOptions::new(std::env::var("TOKEDEX_URL")?, std::env::var("TOKEDEX_API_KEY")?); options.headers.insert("x-tokedex-project-name".into(), "storefront".into()); options.on_response_headers = Some(Arc::new(|headers| println!("{:?}", headers.get("x-request-id")))); let router = Router::new(options)?; let session = router.with_options(RequestOptions::default().headers([ ("x-tokedex-trajectory-id".to_string(), "order-4821".to_string()), ("x-tokedex-tags".to_string(), "checkout,eval".to_string()), ])); let messages = vec![wire::Message::user(r#"Reply with exactly the word "hello"."#)]; session.chat().completions().create(wire::ChatCompletionsRequest::new("openai/gpt-6-luna", messages)).await?; Ok(()) } ``` **OpenAI SDK, Anthropic SDK** ```text f556d214-dcf3-4c31-8bb2-412e1d4085a7 ``` **curl** ```text HTTP/1.1 200 OK … x-tokedex-request-id: f556d214-… x-request-id: f556d214-… request-id: f556d214-… ``` The ID is in the `x-request-id` response header. **TypeScript, Python · Tokedex SDK** ```text f556d214-dcf3-4c31-8bb2-412e1d4085a7 ``` **Rust · Tokedex SDK** ```text Some("f556d214-dcf3-4c31-8bb2-412e1d4085a7") ``` Log the request ID with your own error: every response carries it, errors included, as `x-request-id`, `request-id` and `x-tokedex-request-id`. The gateway makes it and ignores one you send. **OpenAI SDK, Anthropic SDK** On an error, the client holds it in `requestID` (Python, Rust: `request_id`). | Request header | Does | | --- | --- | | `x-tokedex-trajectory-id` | Groups requests that share the value, such as one conversation or agent run, into one session | | `x-tokedex-tags` | Labels the request with comma-separated tags you can search and filter by | | `x-tokedex-project-name` | Names the project the request belongs to | | `x-tokedex-trace-text: true` | Keeps the prompt and response text in the trace, when an admin has turned [text capture](/gateway/recording-and-retention) on | | `x-tokedex-trace: false` | Leaves the request out of the traces | Set `x-tokedex-project-name` once for each application and `x-tokedex-trajectory-id` for each conversation or agent run, as the examples do, so a failing run opens as one session. To look a request up, paste its ID, or your session ID, into **Search requests or paste an ID…** under **Observability → Requests** and choose **Open request**; [Find and inspect a request](/gateway/requests-and-sessions) shows what it holds. Next: [Budgets](/gateway/budgets) or [Find and inspect a request](/gateway/requests-and-sessions). --- # API reference Look up what the gateway serves on your API: its endpoints, where your API key goes, the headers it reads and returns, and what it does with each request field. **OpenAI Responses** | Method and path | Does | | --- | --- | | `POST /v1/responses` | Creates a response | With `"stream": true`, the reply is server-sent events, each an `event:` line naming the type and a `data:` line, from `response.created` to `response.completed`, `response.incomplete` or `response.failed`, with no `[DONE]` line. Retrieving, deleting or cancelling a stored response, listing its input items, counting input tokens and compacting return `404`. **OpenAI Chat Completions** | Method and path | Does | | --- | --- | | `POST /v1/chat/completions` | Creates a completion | With `"stream": true`, the reply is `data:` lines, each a `chat.completion.chunk`, ending with `data: [DONE]`. The stored-completion endpoints, such as `GET /v1/chat/completions/{completion_id}`, return `404`. **Anthropic Messages** | Method and path | Does | | --- | --- | | `POST /v1/messages` | Creates a message | | `POST /v1/messages/count_tokens` | Counts the input tokens of the same body and headers without generating, and returns `{"input_tokens": }`. It takes a request from the key's rate limit and spends no budget | With `"stream": true`, the reply is server-sent events, each an `event:` line naming the type and a `data:` line, from `message_start` to `message_stop`. `/v1/messages/batches` returns `404`. **Gemini GenerateContent** | Method and path | Does | | --- | --- | | `POST /v1/models/{model}:generateContent` | Generates a response from the model the path names | | `POST /v1/models/{model}:streamGenerateContent?alt=sse` | Streams it as `data:` lines, each a `GenerateContentResponse` | | `POST /v1/models/{model}:countTokens` | Counts the input tokens of `{"contents": […]}`, or of a whole `{"generateContentRequest": {…}}`, without generating, and returns `{"totalTokens": }`. It takes a request from the key's rate limit and spends no budget | | `GET /v1/models`, `GET /v1/models/{model}` with `x-goog-api-key` | Lists the Gemini models your key can call, or one of them, as Gemini API `Model`s, all on one page. Without that header, `GET /v1/models` is the OpenAI-format list every API shares | | `POST /upload/v1beta/files` with `x-goog-api-key` | Starts a resumable upload, as the SDK's `files.upload()` does, and answers with the gateway's own upload URL for the bytes. It is the one `v1beta` path served, because the SDK always uploads there | | `GET /v1/files`, `GET /v1/files/{file}`, `DELETE /v1/files/{file}` with `x-goog-api-key` | Lists, reads or deletes the files your key uploaded, as Gemini API `File`s. Another key's file returns `404`. Without that header, `/v1/files` is not served | The paths take no other query string: a `key` parameter, or a stream request without `alt=sse`, returns `404`, as do other model methods such as `:embedContent`, in Google's envelope. In the Google Gen AI SDK, set the base URL to the gateway's address and the API version to `v1`. The gateway serves Gemini only under Google's stable `v1`: a `/v1beta` path, which the SDK uses by default, returns `404` in Google's envelope with a message naming that setting. Context caches, embeddings and batches are not served. An upload goes to Google under the gateway's own Google key, in the SDK's own chunks, each no larger than the gateway's request limit. Google keeps a file for 48 hours; each key's files count against limits the operator sets with `TOKEDEX_FILES_MAX_FILES_PER_KEY` and `TOKEDEX_FILES_MAX_BYTES_PER_KEY`, and an upload past them returns `413`. Every Files call takes a request from the key's rate limit and spends no budget. A prompt may name in `fileData.fileUri` only a file your key uploaded through the gateway: any other URI on Google's API host returns `403`, and such a prompt is served only by a model on that Google key. The gateway ties files and unfinished uploads to the Google API key that opened them. After changing that key, upload again even if both keys belong to the same Google Cloud project. If the original key is restored, its unexpired files and uploads become available again. Files and uploads recorded before the gateway started tracking the Google key also need to be uploaded again. Use the exact public model ID from discovery in `{model}`, such as `google/gemini-3.5-flash-lite`. The slash may be literal, as Google's SDK sends it, or encoded once as uppercase `%2F`, as the Tokedex SDK sends it. The same rule applies to model lookups. The gateway decodes once and matches the installed ID exactly: it does not infer a maker, retain retired bare IDs as aliases, or change case. Double or mixed encoding, empty or extra components, and dot-segment model components are rejected. Explicitly installed custom model atoms remain addressable; these public URL rules do not rename provider-native wire models. You need: an API key (`tokedex_ik_…`), with `TOKEDEX_BASE_URL` (Anthropic Messages, Gemini GenerateContent: `TOKEDEX_URL`) and `TOKEDEX_API_KEY` set as in [Connect your app](/gateway/connect-your-app#values-to-change). A request that reaches a model calls a provider and can incur charges. ## Choose an API Use the API your client or agent already speaks: OpenAI Responses, OpenAI Chat Completions and Anthropic Messages each reach most models of every connected provider, so a new provider never needs a new API. Gemini GenerateContent serves Google's Gemini and Gemma models. Only OpenAI Responses keeps a conversation for you to continue with `previous_response_id`, and only Anthropic Messages and Gemini GenerateContent count input tokens. ## Shared endpoints | Method and path | Does | Key | | --- | --- | --- | | `GET /v1/models` | Lists the model IDs your key can call, once for each client API that serves them; see [Find a model](/gateway/models) | `Authorization: Bearer` or `x-api-key` | | `GET /v1/limits` | Returns every budget and rate limit that reaches your key; see [Budget refusals](/gateway/errors-and-limits#budget-refusals) | `Authorization: Bearer` or `x-api-key` | | `POST /v1/keys/report-compromised` | Revokes a leaked API key or admin key, sent as `{"token": ""}`. It answers `202` to every well-formed report, so the reply never says whether the key was live | None | | `GET /healthz`, `GET /readyz`, `GET /version` | Say that the gateway is running, whether it is ready, and which release it runs. `/readyz` answers `503` while a store it needs does not answer | None | | `GET /api/hello` | Answers `200` with no body; Claude Code checks it before its first request | None | | `POST /v1/batches`, `GET /v1/batches/{id}`, `POST /v1/batches/{id}/cancel`, `GET /v1/batches/{id}/results` | Batch jobs, which only a gateway started from a configuration file runs, with one of that file's virtual keys or its master key. On any other gateway an API key gets `403`. See [Batch jobs](/sdk/batch) in the SDK docs | `Authorization: Bearer` | A gateway started from a configuration file takes that file's virtual keys and master key on every path that takes a key, and has no admin keys, key states, budgets, rate limits, `/v1/limits` or `report-compromised`. The rest of this page describes a gateway started without one. ## Authentication **OpenAI Responses, OpenAI Chat Completions** Send your API key as `Authorization: Bearer`. These paths do not read `x-api-key`, so a key sent only there gets `401`. **OpenAI Responses** ```bash curl -sS "$TOKEDEX_BASE_URL/responses" \ -H "Authorization: Bearer $TOKEDEX_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-6-luna", "input": [{ "role": "user", "content": "Reply with exactly the word \"hello\"." }] }' ``` **OpenAI Chat Completions** ```bash curl -sS "$TOKEDEX_BASE_URL/chat/completions" \ -H "Authorization: Bearer $TOKEDEX_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-6-luna", "messages": [{ "role": "user", "content": "Reply with exactly the word \"hello\"." }] }' ``` **OpenAI Responses, OpenAI Chat Completions** Sent without the header, the same request gets `401`: ```json {"error":{"code":"invalid_api_key","message":"authentication failed","type":"invalid_request_error"}} ``` **Anthropic Messages** Send your API key in `x-api-key`, as the Anthropic SDK does, or as `Authorization: Bearer`. If you send both, they must hold the same key, or the request gets `401`. ```bash curl -sS "$TOKEDEX_URL/v1/messages" \ -H "x-api-key: $TOKEDEX_API_KEY" \ -H "anthropic-version: 2023-06-01" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-6-luna", "messages": [{ "role": "user", "content": "Reply with exactly the word \"hello\"." }] }' ``` Sent without a key, the same request gets `401`: ```json {"type":"error","error":{"code":"invalid_api_key","type":"authentication_error","message":"authentication failed"}} ``` **Gemini GenerateContent** Send your API key in `x-goog-api-key`, as the Google Gen AI SDK does, and no `Authorization` header: a request that carries both gets `401`. ```bash curl -sS "$TOKEDEX_URL/v1/models/google/gemini-3.5-flash-lite:generateContent" \ -H "x-goog-api-key: $TOKEDEX_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "contents": [{ "role": "user", "parts": [{ "text": "Reply with exactly the word \"hello\"." }] }] }' ``` Sent without the header, the same request gets `401`: ```json {"error":{"code":401,"status":"UNAUTHENTICATED","message":"authentication failed"}} ``` The gateway checks the key before it reads the body. A missing, unknown or revoked key gets `401` `invalid_api_key`, and so do the master key and admin keys, which do not call models: [create an API key](/gateway/api-keys). A disabled, expired or suspended key gets `403` with its own code. The gateway calls providers with its own provider credentials and never forwards your key. ## Request headers | Header | Does | | --- | --- | | `x-tokedex-fidelity-policy` | `strict` refuses with `422` a request the model cannot take exactly; `best_effort` lets the gateway drop or approximate what the model cannot take. Left out or empty, `best_effort` applies, and each approximation is reported in `x-tokedex-fidelity-v1`. Another value returns `400`. See [Check feature support](/gateway/models#check-feature-support) | | `x-tokedex-provider` | Comma-separated provider IDs allowed to serve the request; `422` `provider_not_served` when none of them can. See [Choose a provider](/gateway/models#choose-a-provider) | | `x-tokedex-provider-order` | Comma-separated provider IDs the request tries first, in that order; the model's other providers follow. A blank or malformed value, or an ID that names no provider, returns `400`. See [Prefer providers](/gateway/models#prefer-providers) | | `x-tokedex-trajectory-id`, `x-tokedex-tags`, `x-tokedex-project-name`, `x-tokedex-trace-text`, `x-tokedex-trace` | Group, label and record the request; see [Make a request easy to find](/gateway/errors-and-limits#make-a-request-easy-to-find) | | `x-request-id` | Ignored: the gateway makes each request's ID itself | **Anthropic Messages** Anthropic Messages also reads these: | Header | Does | | --- | --- | | `anthropic-version` | Optional. `2023-06-01` is the only value accepted; another returns `400` | | `anthropic-beta` | Up to 16 comma-separated values of up to 64 characters each, or `400`. The gateway sends them on to a model it reaches over Anthropic's own API. Another model drops them and reports it in `x-tokedex-fidelity-v1`, or refuses with `422`, as the fidelity policy decides | ## Response headers | Header | Sent on | Holds | | --- | --- | --- | | `x-request-id`, `request-id`, `x-tokedex-request-id` | Every response except from `report-compromised`, errors included | The request's ID, the same in all three | | `x-tokedex-provider`, `x-tokedex-model` | Success | The provider that answered, after any fallback, and its name for the model | | `x-tokedex-deployment`, `x-tokedex-strategy` | Most successes | The deployment that served and the routing strategy that chose it | | `x-tokedex-fidelity-policy` | Success | The fidelity policy the gateway applied | | `x-tokedex-fidelity-v1` | Success, when you asked for `best_effort` or the gateway changed the request | A JSON report of what it dropped or approximated | | `x-tokedex-trust` | Success from a model on [your own model server](/gateway/custom-models) | `unreviewed` | | `x-tokedex-ratelimit-limit`, `x-tokedex-ratelimit-remaining`, `x-tokedex-ratelimit-reset-ms` | Success, when the key has a rate limit | The key's requests-a-minute limit, remaining requests, and milliseconds until the limit is full again on the replica that answered | | `x-tokedex-budget-remaining-usd` and the other `x-tokedex-budget-*` headers | Success, when a budget applies | The tightest of the key's and its holder's own budgets; see [Budgets](/gateway/budgets#when-a-budget-is-used-up) | | `retry-after`, `retry-after-ms` | `429` | The wait in seconds and in milliseconds. A provider's `429` carries `retry-after` only when the provider sent one | | `x-should-retry` | `402`, and `403` `price_unavailable` | `false`, so the OpenAI and Anthropic SDKs do not retry it | **Anthropic Messages** A `count_tokens` response carries the request ID headers and `x-tokedex-fidelity-policy`, and `x-tokedex-token-count: estimated` when the count is the gateway's estimate rather than the provider's. **Gemini GenerateContent** A `countTokens` response carries the request ID headers and `x-tokedex-fidelity-policy`, and `x-tokedex-token-count: estimated` when the count is the gateway's estimate rather than the provider's. ## Request fields The gateway sends the request to the model that serves it, translated where that provider's API differs. A field the model cannot take gets `422` `unsupported`, naming the field, or, where the fidelity policy allows, is dropped or approximated and reported in `x-tokedex-fidelity-v1`. Where a table below says a value returns `400`, the gateway refuses it itself with `invalid_request`, usually naming the field. **OpenAI Responses, OpenAI Chat Completions, Anthropic Messages** `model` is required. It names a model your key can call on your API: a provider's model such as `openai/gpt-6-luna` (Gemini GenerateContent: `google/gemini-3.5-flash-lite`), a [router](/gateway/router), or a model from [your own model server](/gateway/custom-models), which only a key that names it can call. The reply's `model` is the ID you sent. **Gemini GenerateContent** The path names the model: one your key can call, as the Google SDK's `models.list()` shows, and `GET /v1/models` with `Authorization: Bearer` lists for `google.generate-content`. An ID this API does not serve returns `404` `model_not_found`, and one your key may not call returns `403` `permission_denied`; [Find a model](/gateway/models#missing-or-refused-models) says why each happens. A `task_type` field is accepted only as `"general"`, which changes nothing; another value returns `400`. The body must be JSON, or it gets `400` `invalid_json`, and at most 12,000,000 bytes, inline files and images counted after base64 encoding, or it gets `413` `request_too_large`. The operator changes the limit with `TOKEDEX_MAX_REQUEST_BYTES`, and a [reverse proxy](/gateway/https#proxy-settings) in front needs one at least as large. **OpenAI Responses** | Field | What the gateway does | | --- | --- | | `input` | A string or an array of input items | | `stream` | `true` streams the response | | `stream_options` | Takes `include_obfuscation` and `include_usage`; another key returns `400` | | `store` | Left out or `true`, the gateway keeps the response for 24 hours by default, so `previous_response_id` can continue it. `false` keeps nothing | | `previous_response_id` | Continues a response the gateway kept. Send the same API key and model ID: an ID that is missing, expired or another key's returns `404` `previous_response_not_found`, as does one kept before the gateway's model configuration changed or, on a gateway without Postgres or Redis, before it restarted. A model that cannot continue a response returns `400` `previous_response_unsupported` | | `background` | `true` returns `400` | | `text` | Its `format` is `text`, `json_object`, `json_schema` with `name` and `schema` and optionally `description` and `strict`, `grammar` with `syntax` (`lark` or `regex`) and `definition`, or `python`; another key returns `400` | | `top_logprobs` | A number asks for log probabilities; `null` asks for none; another value returns `400` | | The other fields of the OpenAI Responses API, such as `instructions`, `tools`, `tool_choice`, `reasoning`, `include` and `max_output_tokens` | Sent to the model | A field of the wrong type, such as a string in `temperature`, returns `400`, except a `stream`, `tools` or `instructions` of the wrong type, which the gateway ignores. The operator sets how long responses are kept with `TOKEDEX_CONTINUATION_TTL_SECONDS`. **OpenAI Chat Completions** | Field | What the gateway does | | --- | --- | | `messages` | Required, with at least one message. Roles are `system`, `developer`, `user`, `assistant` and `tool`, and `developer` is read as `system`; another role returns `400` | | User message `content` | A string, or `text`, `image_url`, `file` and `input_audio` parts; another part type returns `400` | | `stream` | `true` streams the completion | | `stream_options` | Takes only `include_usage`, a boolean; another key returns `400` | | `max_completion_tokens`, `max_tokens` | When you send both, `max_completion_tokens` applies | | `temperature`, `top_p`, `seed`, `logprobs`, `parallel_tool_calls` | Sent to the model | | `top_logprobs` | Sent to the model with `logprobs: true`; without it, dropped | | `stop` | A string or an array of strings; anything else returns `400` | | `tools` | `function` and `custom` tools; another type returns `400` | | `tool_choice` | `auto`, `none`, `required`, or one named function or custom tool; another form returns `400` | | `response_format` | `text`, `json_object`, or `json_schema` with a `json_schema.schema`; another type returns `400` | | `reasoning_effort` | `none`, `minimal`, `low`, `medium`, `high`, `xhigh` or `max`; another value returns `400` | | Any other field, such as `n`, `user`, `store`, `metadata`, `presence_penalty`, `frequency_penalty`, `logit_bias` or `service_tier` | Returns `400`, naming the fields | The gateway ignores a value of the wrong type in `temperature`, `top_p`, `seed`, `max_completion_tokens`, `max_tokens`, `logprobs`, `top_logprobs` and `parallel_tool_calls`. It also ignores `target_provider`, and the `snippy` object with `enabled: false` that Copilot sends. **Anthropic Messages** | Field | What the gateway does | | --- | --- | | `messages` | Required, with at least one message. Roles are `user`, `assistant` and `system`; another role returns `400` | | `max_tokens` | Optional. Left out, an Anthropic model gets its maximum output | | `stream` | `true` streams the message; a value that is not a boolean returns `400` | | `temperature`, `top_p` | Numbers; anything else returns `400` | | `stop_sequences` | An array of strings; anything else returns `400` | | `tools` | Client tools, with `name`, `input_schema`, `description`, `strict` and `cache_control`. A tool with a `type`, such as Anthropic's web search, returns `400` | | `system`, `tool_choice`, `thinking`, `output_config`, `metadata`, `context_management` | Sent to the model. A key inside them that the gateway does not know returns `400` | | Any other field, such as `top_k` or `service_tier` | Sent unchanged to a model the gateway reaches over Anthropic's own API. Another model returns `400` | **Gemini GenerateContent** | Field | What the gateway does | | --- | --- | | `contents` | The conversation, with roles `user` and `model` | | `systemInstruction` | `{"parts": […]}` with text parts only, plus an optional `role`, which is ignored; another part type returns `400` | | Parts | `text`, `inlineData` and `fileData`, the last two with an optional `mediaResolution` and, on a video, `videoMetadata`. A `model` turn may also hold the `executableCode`, `codeExecutionResult`, `toolCall` and `toolResponse` Parts a built-in tool returned, which go back to Gemini as they came | | `generationConfig` | Takes `temperature`, `topP`, `topK`, `seed`, `presencePenalty`, `frequencyPenalty`, `maxOutputTokens`, `stopSequences`, `candidateCount`, `thinkingConfig`, `responseLogprobs`, `logprobs`, `mediaResolution` and `enableEnhancedCivicAnswers`, all sent to Gemini as given. `logprobs` without `responseLogprobs: true`, or another key, returns `400`. `presencePenalty`, `frequencyPenalty` and `responseLogprobs: true` return `422` before Gemini is called on a model that refuses them, which every Gemini and Gemma model in the catalogue does; the error names the fields to remove | | Structured output | `responseMimeType` with `responseJsonSchema` or `responseSchema`, sent as given, so `text/x.enum` works too. A schema without `responseMimeType`, or both schemas, returns `400` | | `responseModalities` | `["TEXT"]` only: the gateway returns text, so another modality returns `400` | | `safetySettings` | Sent to Gemini as given, each with `category` and `threshold` | | `tools` | `functionDeclarations`, and Google's built-in tools `googleSearch` (with an optional `timeRangeFilter`), `urlContext`, `codeExecution` and `googleMaps` (with an optional `enableWidget`), each sent to Gemini as given, after the functions. A model not granted a built-in tool returns `422`; another built-in tool, or a field Gemini refuses such as `excludeDomains`, returns `400`. Gemini's grounding, URL-context and code-execution results come back as Gemini returns them | | `toolConfig` | `functionCallingConfig` with `mode` `AUTO`, `NONE` or `ANY`, and with `ANY` any number of `allowedFunctionNames`; `VALIDATED`, or names with another mode, returns `400`. With a built-in tool, also `retrievalConfig`, the location Maps and Search ground on, and `includeServerSideToolInvocations`, which Gemini needs before it takes built-in tools beside functions | | `model`, `stream` | Return `400`: the path names the model and whether to stream | | Any other field, such as `cachedContent` or `serviceTier` | Returns `400` | ## Errors **OpenAI Responses** Errors use OpenAI's envelope, `{"error": {"code", "message", "type"}}`. Inside a stream, an error is an `event: error` whose data holds `code`, `message` and `param`. **OpenAI Chat Completions** Errors use OpenAI's envelope, `{"error": {"code", "message", "type"}}`. Inside a stream, an error is a `data: {"error": {…}}` line followed by `data: [DONE]`. **Anthropic Messages** Errors use Anthropic's envelope, `{"type": "error", "error": {"code", "type", "message"}}`, with the gateway's code in `error.code`. Inside a stream, an error is an `event: error` with the same body. **Gemini GenerateContent** Errors use Google's envelope, `{"error": {"code", "status", "message"}}`, where `code` is the HTTP status. A refusal for the key's state or one of its limits adds a `details` entry of type `google.rpc.ErrorInfo`, whose `reason` is the gateway's code in capitals, such as `RATE_LIMITED`. Other refusals carry none of the gateway codes this page names: read the HTTP status and `error.status`. Inside a stream, an error is a `data:` line with the same body. A path the gateway does not serve gets `404` before your key is checked: the OpenAI envelope with code `not_found` on a `POST`, and a plain-text body on other methods. An error before the first streamed event returns its own status and a JSON body. [Errors, limits and request IDs](/gateway/errors-and-limits) lists the codes and says which to retry. ## Recommendations - **Send `x-tokedex-fidelity-policy: strict` when your code depends on a field,** such as structured output it parses, so a model that cannot honour it fails with `422` instead of dropping it. - **Check each model ID in `GET /v1/models` with your app's key before you deploy,** since an ID can be served on one API and not another, and listing sends nothing to a provider. - **Log `x-request-id` (Anthropic Messages: `request-id`) with your own errors,** since every response carries it, errors included, and **Observability** finds the request by it. **OpenAI Responses** - **Send `store: false` when your client keeps its own history or makes a one-off request.** To continue a turn with client-managed history, send the earlier inputs and response `output` items in `input`. Kept responses count against your key's storage, and once it is full the gateway refuses requests that would keep one with `503` `continuation_capacity`. **Anthropic Messages** - **Count a large prompt with `count_tokens` and compare it with the model's `context_window` before you send it,** since a count generates nothing and spends no budget. **Gemini GenerateContent** - **Count a large prompt with `countTokens` and compare it with the model's `inputTokenLimit` before you send it,** since a count generates nothing and spends no budget. Next: [Connect your app](/gateway/connect-your-app), [Find a model](/gateway/models) or [Errors, limits and request IDs](/gateway/errors-and-limits). --- # People and workspaces Invite a teammate into a workspace with the role they need, and keep each team's or project's keys, limits and spend apart. **Dashboard** 1. Choose **Invite teammate** on **Home** or **Members**. 2. Optionally, enter **Their email (optional)**, so nobody else can use the link. 3. Under **Where they will work**, choose a workspace, and under **What they can do**, choose a role. **Developer** is the default. 4. Choose when **Their access ends** and how long the **Link works for**: **1 day**, **3 days** (the default) or **7 days**. Give a contractor an end date, so their access stops on its own. 5. Choose **Create invite link**, then **Copy link**, and send it privately. The person opens the link and chooses a password, or signs in with your identity provider. They then appear on **Members** with their role. You need: an organisation Owner or Admin account, or a Workspace admin account to invite into your workspace. Before anyone has an account, **Invite teammate** first asks you to create your own, and you become the Owner. **The whole organisation** appears under **Where they will work** once the gateway has teammates. **HTTP API** ```bash curl -sS "$TOKEDEX_URL/control/v1/invites" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "email": "ana@example.com", "target": { "workspaceId": "", "role": "developer" } }' ``` The gateway answers `201` with the link, shown this once: ```json { "object": "invite", "id": "inv_01M7V8NW…", "email": "ana@example.com", "targetLabel": "Developer of Research", "status": "pending", "expiresAt": "2026-11-23T01:21:03.798Z", "url": "http://127.0.0.1:4000/#invite=tokedex_iv_…", "shownOnce": "This link is shown once and works once. Send it over a channel you trust." } ``` Send `url` to the person privately. They open it and choose a password, or sign in with your identity provider. You need: an admin key with the `admin` preset in `TOKEDEX_ADMIN_KEY`, and `export TOKEDEX_URL='http://127.0.0.1:4000'`. `email` is optional and binds the link to that address. A workspace role's `role` is `admin`, `developer` or `viewer`; for an organisation role, send `"target": { "role": "viewer" }` or `"member"`. `target.accessEndsAt`, an ISO time, ends the workspace role then; set it for a contractor, so their access stops on its own. `expiresInHours` sets how long the link works, from 1 to 168; the default is 72. `GET /control/v1/invites/targets` lists the targets you can invite to. Inviting someone as Owner, Admin or Workspace admin needs a signed-in dashboard session, and answers `session_required` to an admin key. Invites work once the gateway has its first Owner account, which is created in the dashboard; until then the gateway answers `409` `first_account_required`. The link works once. The gateway sends no email, and a person who already has an account cannot accept an invite: change their access instead. An invite that gives administrative access names the person's email address and works for at most a day. With the gateway at a local address such as `127.0.0.1`, an invite link opens only on that machine until the gateway has a public address; see [HTTPS and reverse proxies](/gateway/https). ## Roles An organisation role applies to every workspace. Give a workspace role when someone needs one workspace only. | Role | Scope | What it allows | | --- | --- | --- | | Owner | Organisation | Everything, including sign-in settings | | Admin | Organisation | Everything except sign-in settings, and Workspace admin of every workspace | | Viewer | Organisation | Reads every workspace, key, budget, report and the audit log; spends nothing without a workspace role | | Member | Organisation | Signs in; everything else, the **Playground** included, comes from workspace roles | | Workspace admin | Workspace | The workspace's people, keys, admin keys and limits, and budgets on its people and models | | Developer | Workspace | Their own keys in the workspace, within its limits | | Workspace viewer | Workspace | Reads the workspace's keys, limits, budgets, spend and usage | Give each person the narrowest role that covers their work: Developer to build with models, Workspace viewer to read spend, Workspace admin to run a team's workspace. Keep organisation Owner and Admin to the few people who run the gateway, because those roles reach every workspace. Roles can also come from identity-provider groups; see [Single sign-on](/gateway/single-sign-on). ## Create a workspace Creating a workspace needs an organisation Owner or Admin. **Dashboard** ![The Workspaces page listing the Default, Platform and Research workspaces](/images/dashboard/workspaces.png) 1. Choose **New workspace** on **Workspaces**. 2. Under **What it is for**, choose **Project**, **Team**, **App**, **Environment** or **Sandbox**, which fills in suggested settings. 3. Enter a **Name**. 4. Check **Models can call**, **Monthly budget (USD, optional)**, **Longest a key lives (days, optional)** and **Create a key for 's app**, then choose **Create workspace**. The workspace appears on **Workspaces**, and a key you asked for is shown this once. A **Sandbox** starts with a $20 monthly budget, 7-day keys and only the models under $1 per million input tokens, so use one for experiments: a forgotten key there expires soon and spends little. To rename a workspace, edit **Name** in its **Settings** and choose **Save**. **HTTP API** ```bash curl -sS "$TOKEDEX_URL/control/v1/workspaces" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "Research", "purpose": "team" }' ``` ```json { "object": "workspace", "id": "ws_01M7V8K7…", "slug": "research", "name": "Research", "purpose": "team", "status": "active" } ``` `purpose` is optional: `project`, `team`, `app`, `environment` or `sandbox`. It sets no limits. Keep `id` to [create keys](/gateway/api-keys) and invite people into the workspace. To rename it, send `{ "name": "…" }` with `PATCH /control/v1/workspaces/`. Every installation has a **Default** workspace. A workspace's slug comes from its first name and never changes, even when you rename it. Create a workspace for each team, project or environment whose spend you want to see and cap on its own, such as production apart from testing, since keys, limits, budgets and spend belong to one workspace. ## Pages that follow the workspace Each workspace has its own keys, people, limits, budgets and spend. Providers, models and prices are shared by every workspace. **Dashboard** The selector at the top of the sidebar sets the workspace the dashboard shows, and the page's address keeps it, so a link or a reload opens the same one. | Pages | Show | | --- | --- | | **Home**, **Observability**, **Usage**, **Spend & budgets**, **API keys**, **Playground**, **Alerts**, **Settings** | The chosen workspace | | **Providers**, **Models & Routing**, **Pricing** | Every workspace; **Providers** and **Models & Routing** also mark what the chosen one can use | | **Workspaces**, **Members**, **Audit log** | The organisation | The selector lists the workspaces your roles reach. Organisation Owners and Admins can also choose **All workspaces** for totals and organisation-wide settings. With more than eight workspaces, type part of a name to find one. **HTTP API** A route about one workspace names it, in its path or as `workspaceId`; without one, a list covers every workspace the key can read. ## Change someone's access **Dashboard** 1. Open **Members**, choose **All workspaces** above the list, and choose the person. 2. On **Access**, set their **Org role**, change or **Remove** a workspace role, or choose **Add to a workspace…**. 3. Choose **Save access**. A Workspace admin chooses their workspace above the list instead, opens the person and changes their role there. To stop someone for now, open **Danger zone** and choose **Disable**: their sessions end and their keys stop working until you choose **Enable**. **Offboard…** removes their access for good after you review their keys. Disable first when you are unsure, because **Enable** undoes it. **HTTP API** Find the person's `id` with `GET /control/v1/users`, then send the roles they should hold: ```bash curl -sS -X PUT "$TOKEDEX_URL/control/v1/users//role-assignments" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "places": [{ "workspaceId": "" }], "assignments": [ { "role": "workspace_developer", "scope": { "workspaceId": "" }, "expiresAt": "2027-01-31T00:00:00Z" } ] }' ``` ```json { "object": "user", "assignments": [ { "role": "workspace_developer", "scope": { "workspaceId": "ws_01M7V8K7…" }, "expiresAt": "2027-01-31T00:00:00.000Z" }, { "role": "workspace_viewer", "scope": { "workspaceId": "ws_default" }, "expiresAt": null } ] } ``` `places` names the workspaces whose roles you are setting, and the person keeps their roles elsewhere. Always send it: without it, the list replaces every role you can manage, the person's other workspaces and organisation role included. Workspace roles are `workspace_admin`, `workspace_developer` and `workspace_viewer`, with a `scope`; organisation roles are `owner`, `admin`, `viewer` and `member`, without one. `POST /control/v1/users//disable` stops the person and their keys until `…/enable`. Giving or changing an Owner, Admin or Workspace admin role, and disabling a person who holds one, need a signed-in dashboard session, and answer `session_required` to an admin key. When a workspace role ends, the person's personal keys in that workspace stop with it. Workspace keys keep working, so run applications on workspace keys and a person's departure never stops one. Disabling or offboarding a person needs an organisation Owner or Admin. ## Pause or archive a workspace Pausing and archiving a workspace need an organisation Owner or Admin. You can pause **Default** but not archive it. **Dashboard** Choose the workspace and open **Settings**. At the bottom, choose **Pause **, give a reason under **Why (optional)** and choose **Review the pause**. Check the keys that stop, then choose **Pause **; **Resume** undoes it. To archive, revoke its API keys first, choose **Archive…**, check who loses access and choose **Archive **. To restore it, switch **Workspaces** to **Archived**, open it and choose **Restore**. **HTTP API** ```bash curl -sS -X POST "$TOKEDEX_URL/control/v1/workspaces//pause" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "reason": "Quarterly review" }' ``` The gateway first answers `409` `review_required` with the keys that stop under `review.keysSuspended`. Send the same body with `"acknowledge": ""` to apply it. `…/resume` and `…/restore` work the same way. `…/archive` is reviewed too, listing the people who lose access, the admin keys revoked and the invites cancelled; it answers `409` `workspace_not_empty` while live API keys remain. | Action | What happens | To undo | Use it when | | --- | --- | --- | --- | | Pause | The workspace's API keys stop working, and no key is created or rotated there. Nothing is deleted. | Resume: access returns as it was | Spend must stop for now, such as during a review | | Archive | Revoke its live API keys first. People lose their roles there, pending invites are cancelled and its admin keys are revoked. Its history and spend stay. | Restore: it returns without its people or admin keys | The team or project is finished | Next: [API keys](/gateway/api-keys), [Model access and limits](/gateway/model-access-and-limits) or [Budgets](/gateway/budgets). --- # API keys Give each app, service or person their own API key, so you can see what each one spends and stop one without touching the others. **Dashboard** 1. Choose the key's workspace at the top of the sidebar, open **API keys** and choose **Create key**. 2. Under **Start from**, choose **Coding agent**, **Production service**, **Contractor** or **Choose everything myself**. A template fills in the fields that follow. 3. Enter a **Name**, and under **Who it belongs to**, choose **You (personal)** or **Workspace key**. 4. Under **Models this key can call**, keep **All permitted models** or choose **Only the models I choose**. **Advanced** holds the expiry, the request limit and the budget. 5. Choose **Create key**. 6. In **Save your new key**, choose **Copy key** and store it, then choose **Done**. ![The API keys page listing four active keys with their workspace, models and expiry](/images/dashboard/api-keys.png) The key is shown this once, with setup snippets for **curl**, the SDKs and coding agents, and now appears in the list. Start an application's key from **Production service**, a workspace key with a default limit of 600 requests a minute per replica. **Coding agent** keys expire after 30 days with $500 a month. **Contractor** keys expire after 30 days with $500 in total. A **Coding agent** key is your own, so it needs your own account. Signed in with the master key, choose **Create account** beside it first. A template you can't start from says why under its name. You need: an organisation Owner or Admin account, or a Workspace admin or Developer account in the workspace. **HTTP API** ```bash curl -sS "$TOKEDEX_URL/control/v1/inference-keys" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "support-bot-prod", "owner": { "kind": "service", "workspaceId": "" }, "allowedModels": null, "expiresIn": "90d" }' ``` The gateway answers `201`. Store `token` now: it is shown this once. ```json { "object": "inference_key", "id": "01M7V8WE…", "name": "support-bot-prod", "status": "active", "owner": { "kind": "service", "userId": null, "workspaceId": "ws_01M7V8K7…" }, "allowedModels": null, "expiresAt": "2027-02-18T01:24:38.931Z", "token": "tokedex_ik_01M7V8WE…" } ``` You need: an admin key with the `key-manager` or `admin` preset in `TOKEDEX_ADMIN_KEY`, and `export TOKEDEX_URL='http://127.0.0.1:4000'`. `allowedModels` is required: a list of model IDs, or `null` for every model the workspace allows. `expiresIn` is `1d`, `7d`, `30d`, `90d`, `1y` or `never`, the default. Without `owner`, the key lands in **Default**. `limits: { "rpm": 60 }` sets a limit of 60 requests a minute per replica. A new key is shortened to fit the workspace's limits. Only an organisation Owner or Admin can give a key its own budget. See [Budgets](/gateway/budgets) and [Rate limits](/gateway/errors-and-limits#rate-limits). ## Personal and workspace keys A personal key suits your editor, coding agent or experiments, and stops working when its holder leaves the workspace. A workspace key suits an application, a shared service or automation, and keeps working when people leave. **Dashboard** Only the holder ever sees a personal key's secret. To give someone one, an administrator offers it from **Account → Personal keys → Create a key**, under **Who holds it**, with **Offer it to a person**. The person opens the key under **Account → Personal keys** and chooses **Pick up the key**. **HTTP API** Only the holder sees a personal key's secret, so an admin key offers one instead: send `"owner": { "kind": "personal", "userId": "", "workspaceId": "" }` with `"secretless": true`. The key is created with `"status": "awaiting_pickup"` and `"token": null`, and the person picks it up under **Account → Personal keys** in the dashboard. ## Find a key **Dashboard** On **API keys**, filter by status, **Unused 30 days**, **Expiring in 7 days**, **Outside the policy** (expiring later than the workspace now allows) or holder. To find the key behind a value in a log, paste it into **Paste a key to find it**. Disable keys under **Unused 30 days**, so fewer secrets can leak, and revoke them once nobody asks for them back. **HTTP API** ```bash curl -sS "$TOKEDEX_URL/control/v1/inference-keys?workspaceId=&limit=20" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" ``` ```json { "object": "list", "data": [{ "id": "01M7V8WE…", "name": "support-bot-prod", "status": "active", "lastUsedAt": null, "expiresAt": "2027-02-18T01:24:38.931Z" }], "page": { "next": null, "hasMore": false, "limit": 20 } } ``` A key's secret is never listed. Filter with `status`, `q` (part of a name, or the start of a key ID), `idle=30d`, `expiring=7d` or `outsideLimits=true`, and pass `page.next` as `cursor` for the next page. A key's ID is the part of its token after `tokedex_ik_`, up to the next `_`. ## Rotate a key **Dashboard** 1. Open the key from **API keys**, or your own from **Account → Personal keys**, and choose **Rotate**. 2. Under **Keep the current secret working for**, choose **End it now**, **1 hour**, **24 hours** (the default) or **7 days**, then choose **Rotate**. 3. Copy the new key and update every client that uses it. 4. Once **Secrets** on the **Overview** tab shows nothing uses the old secret, choose **End grace now**. **HTTP API** ```bash curl -sS -X POST "$TOKEDEX_URL/control/v1/inference-keys//rotate" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "grace": "24h" }' ``` The response holds the new key in `token`, and the old secret under `secrets` with `"state": "grace"` until its `notAfter`. `grace` is `now`, `1h`, `24h` (the default) or `7d`. Once nothing uses the old secret, end it with `POST …//secrets//retire`. The key keeps its ID, budget and history. Only a personal key's holder can rotate it. Rotate a key when someone who has seen its secret leaves, with a grace period so clients move over before the old secret stops. On a gateway with Postgres replicas, the replica that handles the change applies it immediately. The others pick it up on their next poll, every two seconds by default (`TOKEDEX_CONFIG_POLL_INTERVAL_MS`). Until then, another replica can refuse the new secret or still accept a secret you ended, even after **End it now** or **End grace now**. If you lose the rotation response before saving the secret, inspect the key's generation on the replica that handled the rotation. If you can only read through the load balancer, wait at least one configured polling interval before checking because another replica can still show the previous generation. The new secret is available only in the rotation response. Once you confirm the change, rotate again after any active grace period ends, or end that grace period during the new rotation. ## Disable or revoke a key **Dashboard** Open the key and choose **Disable** to refuse it until you choose **Enable**, or **Revoke** to stop it for good. **Delete permanently** then removes its record. **HTTP API** ```bash curl -sS -X POST "$TOKEDEX_URL/control/v1/inference-keys//revoke" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "reason": "compromised" }' ``` The response is the key with `"status": "revoked"`. `POST …/disable` and `…/enable` work the same way, without a body. `DELETE /control/v1/inference-keys/` removes a revoked key's record and returns `"deleted": true`. A disabled key gets `403` `key_disabled`, and a revoked one `401` `invalid_api_key`. Revoking ends a budget set on that key alone; its usage and spend history stay. Revoke a key that may have leaked, then create a replacement. A disabled or revoked key can still work on another replica until its next [configuration poll](#rotate-a-key). A restored backup brings keys back as they were. [Backup and restore](/gateway/backup-restore) ## Give a script an admin key An admin key (`tokedex_mk_…`) calls the management endpoints, not models. **Dashboard** 1. Choose the workspace the script manages, or **All workspaces** for the whole gateway, and open **API keys → Admin keys**. 2. Choose **Create admin key**, enter a **Name**, choose what it can do and when it expires, and choose **Create key**. 3. Copy the key, which is shown this once. Creating an admin key asks you to confirm it's you when your sign-in is not recent. For a script that acts as you, create a personal access token under **Account → Access tokens** instead. It lasts at most 90 days. `tdx auth login` creates one for the CLI when you approve its code in the browser, as the [CLI quickstart](/cli/quickstart) shows. **HTTP API** ```bash curl -sS "$TOKEDEX_URL/control/v1/management-keys" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "research-ci", "preset": "workspace-key-manager", "owner": { "kind": "service", "workspaceId": "" }, "scope": { "workspaceIds": [""] }, "expiresIn": "90d" }' ``` ```json { "object": "management_key", "id": "01M7VBF0…", "name": "research-ci", "preset": "workspace-key-manager", "status": "active", "expiresAt": "2027-02-18T02:09:43.473Z", "adjustments": null, "token": "tokedex_mk_01M7VBF0…" } ``` The key reaches only that workspace. For one that manages the whole gateway, leave out `owner` and `scope` and choose a preset such as `key-manager`. This needs the `admin` preset, or `workspace-admin` for its own workspace. `GET /control/v1/permissions` lists every preset with its permissions, and `grants` names permissions directly in place of `preset`. Personal access tokens are created only by their owner: in the dashboard, or by approving `tdx auth login` in it. Before any admin key exists, create the first one with the master key, and keep it in `TOKEDEX_ADMIN_KEY`. The token is shown once: ```bash export TOKEDEX_ADMIN_KEY="$(curl -sS "$TOKEDEX_URL/control/v1/management-keys" \ -H "Authorization: Bearer $TOKEDEX_MASTER_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "ci-admin", "preset": "admin", "expiresIn": "90d" }' \ | jq -r .token)" ``` | Preset | Can | | --- | --- | | `admin` | Everything an admin key can do | | `key-manager` | Create and manage API keys; read their budgets, spend and usage | | `viewer` | Read keys, budgets, spend and usage | | `auditor` | Every read, the audit log included, except captured prompts and responses | | `finance` | Read spend, usage, budgets, prices and workspaces | | `operator` | Manage models and gateway settings; read usage and traces | | `credential-admin` | Manage provider credentials | | `workspace-admin`, `workspace-key-manager`, `workspace-viewer` | Administer, manage the keys of, or read the workspaces in `scope.workspaceIds` | Give a script the smallest preset that works, scoped to its workspace where it can be, and an expiry, so a leaked admin key can do little for long. A script that creates keys in one workspace needs `workspace-key-manager`, and across the gateway `key-manager`; a spend export needs `finance`. The [CLI](/cli) reads an admin key from `TOKEDEX_TOKEN`, as [Scripts and agents](/cli/scripts-and-agents#choose-how-to-pass-credentials) in the CLI docs shows. An admin key works only while the person who created or last rotated it is active and still holds everything it can do. Rotate it to keep it working when they leave. An admin key a workspace owns lives 90 days unless you choose, at most a year, and never longer than the admin key that created it. The response's `adjustments` names any change; a gateway-wide admin key has no such cap. ## Recommendations - **Give each application its own key.** A leaked key is then revoked without stopping the others, and spend is reported per key. - **Limit a key to the models it needs.** A leaked key then reaches only those. - **Give each key a budget,** either its own or the workspace's default per API key, to limit a runaway client's spend. Next: [Connect your app](/gateway/connect-your-app), [Budgets](/gateway/budgets) or [Model access and limits](/gateway/model-access-and-limits). --- # Model access and limits Choose which workspaces can call a model or a provider, and how long their keys live and how fast they call. **Dashboard** 1. On **Models & Routing**, choose **Manage access** beside the model. For a provider, choose it beside the provider on **Providers**. 2. Choose **Selected workspaces** and tick the workspaces that keep it. 3. Choose **Save**. The review lists the keys that lose the model. 4. Choose **Save access**. The model is refused at once in the workspaces you left out, and **Models & Routing** marks it **Restricted** there. You need: an organisation Owner or Admin account. **HTTP API** ```bash curl -sS -X PUT "$TOKEDEX_URL/control/v1/policy/model-access" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "modelId": "openai/gpt-6-luna", "workspaces": [""] }' ``` A change that takes access away first answers `409` with the keys that lose the model: ```json { "error": { "code": "review_required", "message": "this change reduces access: review it, then send its digest as acknowledge", "review": { "changes": [{ "op": "+", "path": "modelAccess.openai/gpt-6-luna", "before": null, "after": ["platform"] }], "keysLosingModels": [{ "keyId": "01M7V8Z2…", "name": "research-app", "workspaceId": "ws_01M7V8K7…", "restricted": ["openai/gpt-6-luna"] }], "digest": "sha256:4cb690b0…" } } } ``` Send the same body with `"acknowledge": ""` to apply it. The gateway answers `200` with every restricted model and the workspaces that keep it: ```json { "object": "list", "data": [{ "modelId": "openai/gpt-6-luna", "workspaces": [{ "id": "ws_01M7V8S8…", "slug": "platform", "name": "Platform" }] }] } ``` You need: an admin key with the `admin` preset in `TOKEDEX_ADMIN_KEY`, and `export TOKEDEX_URL='http://127.0.0.1:4000'`. `"workspaces": "all"` gives the model back to every workspace, with no review. `PUT /control/v1/policy/provider-access` takes `providerId`, such as `anthropic`, in place of `modelId`. Every workspace can call every model the gateway serves, including models added later, until you restrict it. A workspace created later starts without a restricted model or provider. Restrict each workspace to the models and providers it needs, so a key that leaks there cannot reach the rest. ## Workspaces left out | You restrict | In the workspaces left out | | --- | --- | | A model | Keys are refused the model, and it leaves their model list. A [router](/gateway/router) is its own model ID: restrict the router itself. | | A provider | The gateway never calls the provider for those keys. A model that other connected providers serve routes to them; one that only this provider serves is refused. A conversation that continues a response from the provider stops. A custom model on the provider's own API is turned off with it. | A key there that asks for the model is refused with `403` before the gateway calls a provider: ```json {"error":{"code":"permission_denied","message":"permission denied","type":"invalid_request_error"}} ``` ## Limit one workspace's models **Dashboard** 1. Choose the workspace at the top of the sidebar and open **Settings**. 2. Under **Model access**, choose **Only listed models** and pick them. 3. Choose **Save model access**, then **Apply changes** in the review. New models stay off in the workspace until you list them. **Everything the organization connects** lifts the list. Use **Only listed models** where each new model should be reviewed first, such as production, and keep the other where a team should get new models as you connect them. To change the organisation's own limits for one workspace, use **Policy as a file** under **Settings** with **All workspaces**: download the policy as YAML, edit a copy, plan it and apply it. **HTTP API** ```bash curl -sS -X PUT "$TOKEDEX_URL/control/v1/workspaces//guardrail" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "guardrail": { "models": ["openai/gpt-6-luna", "anthropic/claude-haiku-5.5"] } }' ``` `guardrail` replaces the organisation's limits for the workspace, and the change is reviewed like any that reduces access. `GET /control/v1/workspaces//availability` then lists every model with its `status` there: `available`, `restricted`, `not_listed`, `provider_off`, `needs_provider_key` or `workspace_paused`. Applying a policy file is dashboard only. `GET /control/v1/policy/export` downloads the policy as YAML. An organisation Owner or Admin sets the list. A Workspace admin can narrow it further with the workspace's own list, never widen it. ## Limit key lifetime and rate **Dashboard** 1. Choose the workspace and open **Settings**. Its policies card is named after it, such as **Research's policies**. 2. Enter **Longest a key lives (days)** and **Requests a minute per key**. 3. Choose **Save**. Lowering a limit opens **Review before applying**; choose **Apply changes**. For every workspace at once, choose **All workspaces** and open **Settings**. **Organization policy** holds the same limits, the models and providers every workspace may use, and the **Maximum allowed per-key default (USD)**. While you are the gateway's only user, **Key defaults & limits** takes the place of **Organization policy**. **HTTP API** ```bash curl -sS -X PUT "$TOKEDEX_URL/control/v1/workspaces//rules" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "rules": { "maxKeyLifetimeDays": 30, "keyRpmMax": 120 } }' ``` `rules` replaces the workspace's own policy, so send every field you want to keep; `models` and `providers` lists go in it too. It needs the `admin` or `workspace-admin` preset. The organisation's policy for every workspace takes the same fields as `"policy"` on `PUT /control/v1/policy`, with `"keyBudgetMax": { "window": "month", "limit": "100" }` to cap the default budget per API key, and needs the `admin` preset. The tightest of the organisation's policy, its limits for each workspace and the workspace's own policy wins. A new key is shortened to fit. Existing keys keep their expiry unless you shorten them in the review. Each replica counts requests for each key separately and returns `429` `rate_limited` when it reaches the key's limit. See [Rate limits](/gateway/errors-and-limits#rate-limits). Set the request limit above what your busiest key needs per replica at its peak, so normal traffic stays within the limit. The dashboard's **Production service** key template gives 600 requests a minute per replica. Set the longest lifetime to how often you can replace keys, since every new key must be replaced within it. ## Review before a change applies A change that takes access away, such as restricting a model, lowering a limit or pausing a workspace, is reviewed first. Others apply at once. **Dashboard** The review lists **What changes**, **Providers turned off**, **Keys that lose access**, **Limits that go down** and the keys that won't meet the new policy. To shorten keys a shorter lifetime leaves outside it, tick **Shorten their expiry to fit**. Then choose its button, such as **Apply changes**. If the settings changed meanwhile, it refreshes first. Read **Keys that lose access** before you apply, and tell those keys' owners: their next request is refused. **HTTP API** The first request answers `409` `review_required` with `review`: `changes`, `providersNarrowed`, `keysLosingModels`, `keysSuspended`, `limitsLowered`, `budgetsLowered` and `nonCompliant` keys. To shorten keys that no longer fit, add `"remediation": { "clampExpiryDays": 7 }` (1, 7 or 30, the days a key that is already over the limit keeps) and read `review.remediationEffects`. Send the same body with `"acknowledge": ""`. If anything it depends on changed since, the gateway refuses the digest; request the review again. Read `keysLosingModels` and `keysSuspended` before you send the digest, and tell those keys' owners: their next request is refused. ## The Models & Routing page **Models & Routing** lists every model ID the gateway serves. It is shared by all workspaces and shows how the chosen workspace sees each one. **Dashboard** - Filter by **Enabled**, **Needs attention** or **Disabled**; by **Available in **, **Restricted in **, **Provider turned off** or **Needs a provider key**; or with **Search models**, **API format** and **Provider**. - **Routes to** names what requests go to; **Setup status** reads **Needs attention** when an API route is not available, such as for want of a provider key. - **In ** reads **Available**, **Restricted**, **Not on its list**, **Provider off**, **Needs a provider key** or **Workspace paused**, beside **Price per 1M tokens** and **Workspace access**. - Choose a model ID for **Model details**: **Copy model ID**, its price there, **Routing by API format**, and on each route **Open in Playground** and **Technical details & Batch support**. ![The Models page listing the models the gateway serves](/images/dashboard/models.png) **HTTP API** `GET /control/v1/workspaces//availability` gives the same view of one workspace. The models an API key can call are on [Find a model](/gateway/models). ## Hide a model from the model list Each model has two settings that apply in every workspace: whether it accepts requests, and whether it appears in the model list. A hidden model still accepts requests, within each workspace's and key's access, so hide a model to steer people to another without breaking apps that call it, and stop it accepting requests only when it must stop everywhere. A router that chooses among several models has its own **In /v1/models** and **Enabled** switches; see [Routers and fallback](/gateway/router). **Dashboard** 1. On **Models & Routing**, open the model. Under **Access & discovery**, clear **Show in model list**, or **Accept requests** to refuse it everywhere. 2. In the **Unsaved changes** bar, choose **Save changes**, or **Discard changes**. **HTTP API** Both settings are changed in the dashboard only, under **Access & discovery** on a model. Next: [Budgets](/gateway/budgets), [API keys](/gateway/api-keys) or [People and workspaces](/gateway/people-and-workspaces). --- # Budgets Set a budget in US dollars and choose whether the gateway refuses new requests or only alerts when spend reaches the limit. **Dashboard** 1. Choose a workspace at the top of the sidebar, or **All workspaces** to cap a person or a model everywhere. 2. Open **Spend & budgets** and choose **+ Set budget**. 3. Under **What to cap**, choose **A key**, **A person** or **A model**, then pick one. 4. Enter the **Limit (USD)** and choose **a day**, **a week**, **a month** or **in total**. 5. Under **When it is used up**, keep **Refuse new requests**, or choose **Only alert** for a production service whose outage would cost more than the overspend. 6. Choose **Alert at** and **Who is told**, check the summary, then choose **Set budget**. The budget appears under **Budgets that apply here**. ![The Spend & budgets page showing spend against a monthly budget and spend per day by key](/images/dashboard/spend-budgets.png) You need: an organisation Owner or Admin account, or a Workspace admin account for a person or a model in your workspace. **HTTP API** ```bash curl -sS "$TOKEDEX_URL/control/v1/budgets" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "target": { "kind": "key", "id": "" }, "window": "month", "limit": "50" }' ``` The gateway answers `201` with the budget, its spend so far and when it resets: ```json { "object": "budget", "id": "bud_01M7V…", "target": { "kind": "key", "id": "01M7V…" }, "window": "month", "limit": { "amount": "50.000000", "currency": "USD" }, "onLimit": "refuse", "alertThresholds": [50, 75, 90, 100], "progress": { "spent": { "amount": "0.000000", "currency": "USD" }, "state": "ok", "resetsAt": "2026-12-01T00:00:00.000Z" } } ``` You need: an admin key with the `admin` preset in `TOKEDEX_ADMIN_KEY`, and `export TOKEDEX_URL='http://127.0.0.1:4000'`. `target.kind` is `key`, `user` (a person, by user ID) or `model` (a model ID). A person's or a model's budget holds in every workspace unless you add `"within": { "kind": "workspace", "id": "" }`. `window` is `day`, `week`, `month` or `total`. `"onLimit": "alert"` lets requests continue; use it for a production service whose outage would cost more than the overspend. `alertThresholds` sets the alert percentages. ## Budget types The gateway checks every budget that applies before it contacts a provider. If any of those budgets is spent and set to refuse new requests, the request stops there. | Budget | Counts | Who sets it | | --- | --- | --- | | Key | One API key | Organisation Owner or Admin | | Person | A person's own keys, in one workspace or all | Organisation Owner or Admin; a Workspace admin, in their workspace | | Model | Requests that name the model ID, in one workspace or all | The same as a person's | | Workspace | Everything spent in the workspace | Organisation Owner or Admin | | Organisation | Everything spent in every workspace | Organisation Owner or Admin | | Default per API key | Each key in a workspace or the organisation without its own budget for that period | Organisation Owner or Admin; a Workspace admin can set or lower their workspace's | The **Playground** also has a fixed allowance of $1 a day per person. Start with a monthly budget on each workspace, set above your largest expected month, and lower it once you have a month of spend. The spend report counts the same calendar months. Then set a default per API key to limit the impact of a runaway key. For a period, prefer a day (HTTP API: `day`) for a key that runs unattended, such as a scheduled job or an autonomous agent loop, so a runaway loop is caught within a day, and in total (HTTP API: `total`) for a fixed allowance, such as a contractor's. **HTTP API** An admin key needs `budgets.manage` for key, person and model budgets, and `workspaces.manage` for the others. The `admin` preset holds both. A `workspace-admin` key can also set or lower its workspace's `keyBudgetDefault` on `PUT /control/v1/workspaces//rules`. ## Cap a workspace or the organisation **Dashboard** 1. Choose the workspace, or **All workspaces** for the organisation, and open **Settings**. 2. Enter the amount in the workspace's monthly budget, such as **Default's monthly budget (USD)**, or **Organization budget (USD)**. **Default budget per API key (USD)** is beside it. 3. Choose **Save**. Adding or lowering a budget opens **Review before applying**; choose **Apply changes**. A workspace's budget is monthly in **Settings**. Set another period over HTTP. **HTTP API** ```bash curl -sS -X PUT "$TOKEDEX_URL/control/v1/workspaces//guardrail" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "budget": { "window": "month", "limit": "500" } }' ``` Adding or lowering a budget first answers `409` with the change to review: ```json { "error": { "code": "review_required", "message": "this change reduces access: review it, then send its digest as acknowledge", "review": { "budgetsLowered": [{ "path": "workspaces.default.budget", "before": null, "after": { "window": "month", "limit": "500.00" } }], "digest": "sha256:921cdd79…" } } } ``` Send the same body again with `"acknowledge": ""` to apply it. The organisation's budget takes the same body on `PUT /control/v1/policy`, and `keyBudgetDefault` sets the default per API key on either route. ## Change or remove a budget **Dashboard** On **Spend & budgets**, choose **Edit** on the budget's row, make the change and choose **Save budget**, or choose **Remove budget** and confirm. For a workspace's or the organisation's budget, edit or clear the amount in **Settings** and choose **Save**. **HTTP API** Find the budget's `id` with `GET /control/v1/budgets`, filtered by `targetKind`, `targetId`, `window` or `workspaceId`, then change it: ```bash curl -sS -X PATCH "$TOKEDEX_URL/control/v1/budgets/" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "limit": "80" }' ``` Or delete it, which returns `"deleted": true`: ```bash curl -sS -X DELETE "$TOKEDEX_URL/control/v1/budgets/" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" ``` To remove a workspace's or the organisation's budget, send `"budget": null` to its route, with no review. The spend a budget counted stays when you change or remove it. To change a budget's period or target, remove it and set a new one. ## When a budget is used up Once the gateway sees that a budget set to refuse new requests is spent, it returns `402` before contacting a provider: ```json { "error": { "code": "budget_exceeded", "message": "budget exceeded: the key budget for today (UTC) is spent ($1.000000 of $1.000000); it resets at 2026-11-21T00:00:00.000Z", "type": "insufficient_quota", "limit": { "scope": "key", "window": "day", "resets_at": "2026-11-21T00:00:00.000Z", "limit_usd": "1.000000", "spent_usd": "1.000000" } } } ``` A refusal by a workspace, organisation or model budget leaves out the amounts. For a key or person budget whose amounts the caller can see, the gateway also checks the cost of the requested maximum output at the cheapest eligible price. If that cost exceeds the amount left, the gateway refuses the request. The gateway checks settled spend before each request and charges calls as they finish. Three concurrent requests costing $1 each can all pass a $1 workspace budget check and settle at $3. A replica can also keep admitting requests until it sees spend recorded by other replicas. Use lower request concurrency and output limits with small budgets to reduce the possible overrun. While a budget applies, a model with no known price is refused with `403` `price_unavailable` until an organisation Owner or Admin sets its price in **Pricing**. Set missing prices before you add a budget, so requests to those models keep working. Calls a model made with no price, under no budget that refuses it, can be [priced later](/gateway/spend-and-usage#price-calls-made-with-no-price): their cost then counts in the budget periods they were made in. **HTTP API** `"unknownPrice": "allow"` on a key, person or model budget lets models with no known price through it. A successful response reports the tightest of the key's and its holder's own budgets as it stood when the gateway accepted the request. The reset timestamp is for that same period. ```text x-tokedex-budget-remaining-usd: 0.500000 x-tokedex-budget-limit-usd: 1.000000 x-tokedex-budget-scope: key x-tokedex-budget-window: day x-tokedex-budget-reset: 2026-11-21T00:00:00.000Z ``` The scope is `key`, `member` (a person in one workspace) or `user` (a person in all). Workspace, organisation and model budgets never appear here. A budget set to **Only alert** never refuses and never appears in the response headers. ## Budget resets Daily budgets reset at midnight UTC, weekly ones on Monday and monthly ones on the 1st, also at midnight UTC. A budget in total never resets and counts from when you set it; the others count everything spent in the current period, including before you set them. The gateway counts each request's cost in the UTC period when it accepted the request, even if the request finishes after the reset. > **Important:** Check the period's spend so far before you set a day, week or month budget. A limit below it refuses requests at once. Next: [Budget alerts](/gateway/budget-alerts), [Read the spend report](/gateway/spend-and-usage#read-the-spend-report) or [People and workspaces](/gateway/people-and-workspaces). --- # Budget alerts Get an alert each time spend crosses one of a budget's thresholds, in the dashboard and, if you set it up, by email or in Slack. **Dashboard** 1. Choose a workspace at the top of the sidebar, or **All workspaces** for every workspace you can see. 2. Open **Alerts**. The badge on its icon counts your unread alerts, and, for an organisation Owner or Admin, each model serving calls with no price. 3. On the **Inbox** tab, choose **Unread** or **All**. A model serving calls with no price is listed above the alerts, with **Set price**, until a price covers it; see [Price calls made with no price](/gateway/spend-and-usage#price-calls-made-with-no-price). It is not sent by email or to Slack. 4. On an alert, choose **View spend** to open what spent on **Spend & budgets**, or **Mark read**. **Mark all read** clears the list. You need: an account that can see the budget, such as an organisation Owner or Admin, or a Workspace admin. Connections and their deliveries need an organisation Owner or Admin. Changing a connection can ask you to confirm it's you. **HTTP API** ```bash curl -sS "$TOKEDEX_URL/control/v1/alerts" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" ``` ```json { "object": "list", "data": [ { "object": "spend_alert", "id": "alr_01M7V92A…", "read": false, "crossed": [50, 100], "percent": 158, "exhausted": true, "spent": { "amount": "0.000158", "currency": "USD" }, "budget": { "id": "bud_01M7V91X…", "window": "month", "limit": { "amount": "0.000100", "currency": "USD" }, "thresholds": [50, 100] }, "affected": { "kind": "key", "id": "01M7V8Z2…", "name": "research-app", "workspace": { "id": "ws_01M7V8K7…", "name": "Research" } } } ] } ``` Each alert names the budget, the thresholds crossed and what was spent; `exhausted` is `true` once the budget is used up. Add `?workspaceId=` for one workspace's alerts. You need: an admin key that can read budgets, such as one with the `viewer` or `finance` preset, in `TOKEDEX_ADMIN_KEY`, and `export TOKEDEX_URL='http://127.0.0.1:4000'`. `GET /control/v1/alerts/unread-count` returns `count`. To mark alerts read, send `{ "all": true }` or `{ "alertIds": [""] }` to `POST /control/v1/alerts/read`; read state belongs to each person or key. An alert only warns: the budget itself decides what happens once it is used up. To set one, see [Budgets](/gateway/budgets). ## Alert thresholds A budget's thresholds are percentages of its limit, chosen under **Alert at** when you set it. A budget set with **+ Set budget** starts with 80% and 100%; one set elsewhere alerts at 50%, 75%, 90% and 100%. A budget with no thresholds raises no alerts, and the **Playground**'s daily allowance raises none. On a budget that refuses requests, the default, add an earlier threshold, such as 50%, so whoever is told has time to act before requests are refused. 80% and 100% are enough for a budget set to **Only alert**. - Each threshold alerts once per period, or once in all for a budget in total. Spend that passes several at once raises one alert that lists them. - A raised limit alerts again only past what was already reported: a used-up $10 daily budget raised to $20 alerts next at $15 (75%). A lowered limit alerts on the thresholds it newly crosses. - The gateway checks budgets every 15 seconds. Spend that settles just after a period ends can raise that period's alerts for about an hour. - Calls [priced after they were made](/gateway/spend-and-usage#price-calls-made-with-no-price) add their cost to the periods they were made in. In the current period that cost counts toward its thresholds; a period that has ended alerts no more. ## Alert visibility You see an alert only when you can see both its budget's limit and what was spent. | Role | Alerts they see | | --- | --- | | Organisation Owner, Admin or Viewer | Every alert | | Workspace admin or Workspace viewer | In their workspaces: the workspace's and models' budgets, and every key's and person's | | Developer | In their workspaces: the workspace's and models' budgets, their own keys' and their own | The people a budget tells, chosen under **Who is told** on the budget, see its alerts unread; anyone else who can see it finds them under **All**, already read. Connections send alerts whoever a budget tells. Tell the people who can act, such as someone who can raise the limit or the key's holder, since only they see the alert unread. The gateway keeps alerts for 180 days. An alert older than 30 days counts as read. ## Send alerts by email Email needs an SMTP server in the gateway's environment, which whoever runs the gateway sets. Until then, **Create email connection** is unavailable. | Variable | Value | | --- | --- | | `TOKEDEX_SMTP_URL` | The server, as `smtp://[:@][:]`, or `smtps://…` for TLS from the first byte. Percent-encode the user name and password. | | `TOKEDEX_SMTP_HOST`, `TOKEDEX_SMTP_PORT`, `TOKEDEX_SMTP_USER`, `TOKEDEX_SMTP_PASSWORD` | The same server in parts, in place of `TOKEDEX_SMTP_URL`, never with it. The user and password go together. The port defaults to `587`. | | `TOKEDEX_SMTP_FROM` | The sender, as `alerts@example.com` or `Spend Alerts `. Required with a server. | | `TOKEDEX_SMTP_TLS` | `starttls`, which fails if the server cannot upgrade; `implicit`; or `none`, which allows a user and password only to a loopback host. Defaults to `implicit` for `smtps://` or port 465, otherwise `starttls`. | On Kubernetes, set them under `extraEnv` in the Helm chart's values, taking the password, or a URL that holds one, from a Secret as [Deploy to production](/gateway/deploy) shows for provider keys. For a local gateway, set them in the repository's `.env` file. Restart the gateway after a change: a malformed value, a server without a sender, or a `TOKEDEX_SMTP_*` setting without a server stops it from starting. To try email without a mail server, use Mailpit, which catches every message and shows it at `http://127.0.0.1:8025`: add `COMPOSE_PROFILES=mail`, `TOKEDEX_SMTP_URL=smtp://mailpit:1025`, `TOKEDEX_SMTP_TLS=none` and `TOKEDEX_SMTP_FROM=alerts@example.com` to `.env` and run `docker compose up -d`. For a gateway started with `npm start`, use `smtp://127.0.0.1:1025`, run `docker compose --profile mail up -d mailpit` and restart the gateway. A gateway has at most 10 connections. **HTTP API** Connections, test sends and deliveries are managed only from a signed-in dashboard session, by an organisation Owner or Admin: their routes answer `session_required` to an admin key. **Dashboard** 1. Open **Alerts → Delivery** and choose **Create email connection**. 2. Enter a **Name**, and choose which alerts it sends under **Send alerts at**, **About** and **Also send alerts from per-key default budgets**. 3. Under **People**, choose people on the gateway. Each gets only the alerts they could see in their own inbox. 4. Under **Other addresses**, enter outside addresses, one per line. Each gets every alert the connection sends. 5. Choose **Create email connection**, then **Send test**. The connection appears under **Connections** and sends alerts raised from then on, one copy per address. Prefer **People** to **Other addresses** where you can, because each person then gets only what they may see on the gateway. ## Post alerts to Slack **Dashboard** 1. Open **Alerts → Delivery**, choose **Create Slack connection**, then **Webhook URL**. 2. Choose **Create a Slack app ↗**. In the form Slack fills in, create and install the app and pick the channel. 3. Copy the webhook URL from the app's **Incoming Webhooks** and paste it under **Slack webhook URL**. 4. Enter a **Name** after the channel, such as `#finance-alerts`: Slack does not say where a webhook posts. 5. Choose which alerts it sends, then **Create Slack connection** and **Send test**. The test message appears in the channel. Everyone there reads every alert the connection sends, whatever they can see on the gateway, but no secret or prompt text, so post to a channel limited to people who may see spend. Anyone with the webhook URL can post to the channel, so the gateway never shows it again. To pick the channel in Slack instead, choose **Slack app**, which needs the gateway's public `https` address. If deliveries read "Gave up: Slack no longer accepts this webhook", choose **Reconnect** on the connection's card and pick the channel again. Where **Reconnect** does not show, **Edit** the connection and paste a new webhook URL. **HTTP API** Slack connections are made only in the dashboard, by an organisation Owner or Admin. ## Test a connection **Dashboard** Choose **Send test** on the connection's card. Each recipient, or the Slack channel, gets a message marked as a test. A connection takes one test every 30 seconds across all replicas, or another at once after a change. ## Check deliveries **Dashboard** **Edit → Recent deliveries** shows what a connection sent, and **Sent to** on an alert in the inbox shows where it went. A failed send is retried for up to 10 tries or 24 hours and reads **Retrying** meanwhile. Slack can specify a minimum wait before the next attempt. If the delivery expires first, the gateway gives up. | You see | What to do | | --- | --- | | Gave up: Slack no longer accepts this webhook | [Reconnect the Slack connection](#post-alerts-to-slack) | | The mail server refused it, or was unavailable | Ask whoever runs the gateway to check its mail settings | | Skipped: the person may no longer see this alert | Nothing: their access changed after the alert was raised | | Cancelled: the connection is turned off, or was deleted | Select **Send alerts through this connection** under **Edit**; later alerts are sent, cancelled ones are not | The **Audit log** records every connection change and test send. Next: [Budgets](/gateway/budgets) or [Spend and usage](/gateway/spend-and-usage). --- # Spend and usage See what each workspace, key, person or model spent this month, and which models, providers and keys account for your traffic. **Dashboard** 1. Choose a workspace at the top of the sidebar, or **All workspaces** for every workspace. 2. Open **Spend & budgets** and choose the month. 3. Group the rows by **Key**, **Person** or **Model**, or by workspace with **All workspaces**. 4. Choose **Export CSV** to download the report. The page shows what was spent this month, the change from last month, what the month is on pace for and the spend per day, with a row for each key, person or model and the budgets that apply below. You need: a role that can read spend, such as an organisation Owner, Admin or Viewer, or a Workspace admin or Workspace viewer. **HTTP API** ```bash curl -sS "$TOKEDEX_URL/control/v1/workspaces//spend-report?groupBy=key&period=2026-11" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" ``` ```json { "object": "spend_report", "period": "2026-11", "groupBy": "key", "data": [ { "kind": "line", "name": "research-app", "keyId": "01M7V8Z2…", "calls": 66, "inputTokens": 924, "outputTokens": 132, "costUsd": "0.000158", "previousCostUsd": null, "daily": ["0.000000", "…", "0.000158"] } ], "total": { "calls": 66, "costUsd": "0.000158" }, "projectedCostUsd": "0.000249", "coverage": { "calls": 66, "pricedCalls": 66, "unpricedCalls": 0, "estimatedCalls": 0 } } ``` You need: an admin key that can read spend, such as one with the `finance` or `viewer` preset, in `TOKEDEX_ADMIN_KEY`, and `export TOKEDEX_URL='http://127.0.0.1:4000'`. `groupBy` is `key` (the default), `person` or `model`. `period` is a month as `YYYY-MM`, the current one by default. `GET /control/v1/workspaces/spend-report` reports every workspace you can read, grouped by `workspace` by default. Add `format=csv` for a CSV file. ## Choose a view | To find out | Open | | --- | --- | | What a workspace, key, person or model spent in a month, against its budget | **Spend & budgets** | | Which models, providers, keys or tags account for calls, tokens and cost over a time range | **Usage** | | What a model costs, or to set its price | **Pricing**, and [Prices](#prices) below | | Why one request failed or what a session cost | [Find and inspect a request](/gateway/requests-and-sessions) | | Who changed gateway configuration or access | **Audit log** | Start with the spend report for what a month cost and how it compares with budgets, then use **Usage** to find which model, provider, tag or project drove it. Report totals from the spend report, because **Usage** leaves out requests the gateway did not record or no longer keeps. ## Read the spend report Months are calendar months in UTC. Every grouping adds up to the same total; spend the rows do not cover, such as **Playground** keys or removed keys, is one row of its own. The spend report goes back 13 months, so export each month's report as CSV if you need it longer. Group by key first, since each application has its own key, and by model when you are deciding whether a cheaper model would serve. A Developer's spend report and usage cover their own keys. Organisation totals, and each workspace's spend beside its budget, need a role that reads every workspace: organisation Owner, Admin or Viewer. When some costs are unknown or estimated, the report says how many calls have a known cost. A call to a model with no price counts as $0 until someone [sets one](#prices), and a call that ends without a usage report, such as a cancelled request, is charged a conservative estimate. Check that count before you rely on a total, and set a price for each model that has none, since its calls otherwise count as nothing. **HTTP API** `coverage` counts the calls with no price in `unpricedCalls` and the estimated ones in `estimatedCalls`. Amounts are the gateway's calculation from reported usage and its prices, so reconcile them with your provider's invoice. The report reads the gateway's spend records, which are kept apart from traces, so it stays complete when request recording is off. ## Prices A price belongs to one provider's model, in US dollars per million tokens. It is the catalogue price that ships with the gateway release, which changes only when you upgrade; a price set on this gateway, which wins over the catalogue's; or the price of [your own model server](/gateway/custom-models), set with it. **Dashboard** 1. Open **Pricing**, find the model and provider, and choose **Set price** on its row. 2. Enter **Input ($ per 1M tokens)** and **Output ($ per 1M tokens)**. Under **Prompt caching (optional)**, enter **Cache read**, **Cache write** and **Cache write, 1 hour** where the provider prices them apart; the drawer starts with the model's current rates. Add a **Note (optional)** such as where the price comes from. 3. Choose **Save price**. **Price from** on the row now reads **Your price**, and the rates apply from the next request. **Mark as free** makes the model's calls cost nothing, for a model you do not pay per token for, and **Use the default** goes back to the catalogue price. Each needs an organisation Owner or Admin. **HTTP API** Pricing overrides use the provider's native model ID, not the public `maker/model` selector sent to inference endpoints. The provider and native model together identify the price being overridden. ```bash curl -sS "$TOKEDEX_URL/control/v1/pricing/overrides" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "provider": "openai", "model": "gpt-6-luna", "price": { "input": "0.08", "output": "0.40" }, "note": "Negotiated rate" }' ``` The gateway answers `201` with the `price_override`, and the rates apply from the next request. `price` also takes `cachedInput` (a cache read), `cacheWrite` and `cacheWriteLong` (a cache write kept for an hour). This needs an admin key with the `admin` preset. Send `"free": true` in place of `price` to make the model's calls cost nothing, for a model you do not pay per token for. `DELETE /control/v1/pricing/overrides/openai:gpt-6-luna` goes back to the catalogue price, and `GET /control/v1/pricing` lists each model's `price` and its `source`: `catalogue`, `override`, `deployment`, or `null` when no price is known. Your price replaces the whole catalogue price: a cache read or write rate you leave out is charged at the input rate (an hour-long write at the cache write rate), and tool-call rates you leave out are no longer charged. Spend already recorded keeps the price it was charged at, except calls made with no price: you can [price those](#price-calls-made-with-no-price) once their model has one. Set a price only where your rate differs from the catalogue's, such as a negotiated rate, since it drops the rates you leave out, and record its source in the note so others can check it. After an upgrade, check your prices against the new catalogue, because yours keeps winning when the catalogue's changes. When you add a [model from a provider](/gateway/custom-models#a-model-a-catalogue-provider-serves), set rates or mark it free. The price declared on that model takes precedence over an override for its provider model ID. While a budget that refuses unknown prices (the default) applies to a key, the key's requests to a model with no price are refused with `403` `price_unavailable` until you set a price or mark it free. **Dashboard** A banner on **Pricing** says how many models have no price. ## Price calls made with no price A model with no price can serve keys whose budgets permit unpriced calls. This includes existing models from a provider that have no price. The gateway records their usage with no cost. Once a price covers the model, apply it to those calls to add their cost to the day, week and month they were made. Budgets, spend reports and traces count that cost. - A call is priced once. A call that already had a price keeps it, and a later price change moves nothing already priced. - A call that ended without a usage report is priced from its estimate, and counts as estimated. - Calls with no price are kept for 400 days, as long as the daily spend they land in. - A budget whose period has ended does not alert again for cost added to it. Spend added to the current period counts toward its thresholds as usual. **Dashboard** **Alerts** lists each model that is serving calls with no price, and the sidebar's Alerts count includes them, for an Owner or Admin. Each stays until a price covers the model. 1. Open **Pricing**. **Calls with no price** lists each model's calls, tokens, and first and last call. 2. Choose **Set price** on its row, enter the rates, and keep **Also price the earlier calls with no price** ticked. The drawer uses the rate for one-hour cache writes when the usage records them. Cache writes without a recorded duration use the ordinary cache write rate. 3. Choose **Save price**. The page says how many calls were priced and what they added to spend. A model that already has a price, set after its calls were made, shows **Price these calls** instead. It says what they will cost before it charges them. The details of a [model from a provider](/gateway/custom-models#a-model-a-catalogue-provider-serves) also count its calls with no price, and setting its own price there can charge them too. **HTTP API** `GET /control/v1/pricing/unpriced` lists the calls by provider model ID, with `calls`, `usage`, `firstSeenAt`, `lastSeenAt`, the gateway `models` that served them, and the `price` that covers them now, or `null`. In `usage`, `cacheCreationLongInputTokens` counts the subset of `cacheCreationInputTokens` known to have a cache duration of at least one hour. Add `?since=` to list only later calls. Send `"applyToUnpriced": true` with an override to price the model's calls with it: ```bash curl -sS "$TOKEDEX_URL/control/v1/pricing/overrides" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "provider": "fireworks", "model": "accounts/fireworks/models/new-model", "price": { "input": "0.60", "output": "2.50" }, "applyToUnpriced": true }' ``` The reply adds `repriced`: the `calls` priced, the `estimatedCalls` among them, the `unpricedCalls` still with no price, the `cost` added and the `workspaceIds` it was added to. To use an existing price, send `{ "provider", "model" }` to `POST /control/v1/pricing/unpriced/reprice`, with `"dryRun": true` to preview the charge. Both preview and apply return `400` when earlier unpriced calls exist and no price covers any of them. Once all calls are priced, both return zero calls and zero cost. Each needs an admin key with the `admin` preset, and each pricing is an audited `price_override.reprice` change. With the CLI: `tdx pricing unpriced list [--since 30d]`, `tdx pricing unpriced price --provider --model [--preview]`, and `--apply-to-unpriced` on `tdx pricing overrides set` and `edit`. ## Explore usage **Dashboard** 1. Open **Usage** and choose a time range, from **1 hour** to **All time**. 2. Group by **Model alias**, **Model**, **Provider**, **Key**, **Tag**, **Project**, **Person** or **Workspace**. 3. Choose a row to see its calls, tokens and cost, and open its requests. **Refresh** shows a request you just sent, and **Export** downloads the table. **Refused** counts the requests the gateway refused in the range, or in the last 30 days with **All time**. **HTTP API** ```bash curl -sS "$TOKEDEX_URL/observability/v1/usage?groupBy=model&since=2026-11-01T00:00:00Z" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" ``` ```json { "object": "list", "data": [{ "name": "openai/gpt-6-luna", "calls": 66, "inputTokens": 924, "cachedInputTokens": 0, "outputTokens": 132, "reasoningOutputTokens": 0, "totalTokens": 1056, "costUsd": 0.0001584 }], "groupBy": "model", "summary": { "calls": 66, "totalTokens": 1056, "costUsd": 0.0001584 } } ``` This needs an admin key that can read usage, such as one with the `viewer`, `finance` or `operator` preset. `groupBy` is required: `model`, `provider`, `key`, `agent`, `tag`, `project`, `user` or `workspace`. `since` and `until` take ISO times; `workspaceId`, `keyId`, `model`, `provider` and `tag` filter the rows, and `format=csv` returns a CSV file. Input tokens include cached input and cache writes, and output tokens include reasoning tokens, so do not add those columns together. ## Spend and usage differences **Usage** covers the requests the gateway recorded and still keeps, over any time range. The spend report counts every priced call by calendar month, whether or not it was recorded. For monthly accounting and budgets, use the spend report. What the gateway records, and for how long, is on [What the gateway records](/gateway/recording-and-retention). Next: [Budgets](/gateway/budgets), [Budget alerts](/gateway/budget-alerts) or [Your own model server](/gateway/custom-models). --- # Provider credentials Save each provider's API key on the gateway once, and every workspace can call that provider's models with the API keys you issue. **Dashboard** 1. Open **Providers** and choose **+ Add key**, or **Add key** on the provider's row. 2. Under **Provider**, select the provider. Choose a **Configuration method** when the provider offers a choice. 3. Enter the credential and any required settings, then choose **Save key**. The provider's row reads **Stored in the gateway** and, for the selected workspace, **Connected**. ![The Providers page with OpenAI, Anthropic and Google connected](/images/dashboard/providers.png) You need: an organisation Owner or Admin account, and an API key from the provider. **HTTP API** The path names the credential. `jq` reads the provider key from the environment, and curl reads the admin header from a pipe. This keeps both keys out of process arguments. ```bash jq -n '{ value: env.OPENAI_API_KEY }' \ | curl -sS -X PUT "$TOKEDEX_URL/control/keys/OPENAI_API_KEY" \ -H @<(printf 'Authorization: Bearer %s\n' "$TOKEDEX_ADMIN_KEY") \ -H "Content-Type: application/json" \ --data-binary @- ``` ```json {"name":"OPENAI_API_KEY","set":true} ``` You need: Bash, curl, [jq](https://jqlang.org), an exported `OPENAI_API_KEY`, an admin key with the `credential-admin` or `admin` preset in `TOKEDEX_ADMIN_KEY`, and `export TOKEDEX_URL='http://127.0.0.1:4000'`. The replica that saves a key uses it at once. Other replicas pick it up by polling the shared configuration. Saving a key needs no restart. ## Credential names **Dashboard** The **Env-var name** column on **Providers** names each provider's credentials and settings, such as `GEMINI_API_KEY` for Google. Providers that share a key share a row. Public settings such as a region show their values in the table. **HTTP API** `GET /control/keys` lists provider bindings and their sources. A public setting includes its `setting.label` and `setting.value`. The response hides credential values. This example shows two entries with `providerInfo` omitted. ```bash curl -sS "$TOKEDEX_URL/control/keys" \ -H @<(printf 'Authorization: Bearer %s\n' "$TOKEDEX_ADMIN_KEY") ``` ```json [ { "name": "ANTHROPIC_API_KEY", "source": "unset", "providers": ["anthropic"] }, { "name": "OPENAI_API_KEY", "source": "store", "providers": ["openai"] } ] ``` ## Check which providers are connected **Dashboard** Connected providers come first. Each binding reads **Stored in the gateway**, **From the environment** or **Not configured**. The selected workspace's column reads **Connected**, **Not configured** or **Turned off in Default**, with how many of the provider's models its keys can call. Other roles see each provider and whether it is connected in the selected workspace, without credential names. **HTTP API** Each entry's `source` is `store` (saved on the gateway), `environment` (read from the gateway's environment) or `unset` (no key, so its models cannot be called). Credentials are shared by every workspace. To turn a provider off in some workspaces, see [Model access and limits](/gateway/model-access-and-limits). ## Supply a key through the environment Prefer saving keys on the gateway: a saved key needs no restart and is backed up, encrypted, with the gateway's state. Use the environment when your own secret store must hold the key. Set the variable named for the credential, such as `OPENAI_API_KEY`, in the gateway's environment and restart the gateway. Google's key is also read from `GOOGLE_AI_API_KEY`. A key saved on the gateway wins over the environment variable of the same name, so keep each credential in one place: a changed variable has no effect while a saved key exists. To use the environment value, remove the saved key. ## Amazon Bedrock Bedrock accepts a key pair or a Bedrock API key. Supply a region with either method. - **Key pair:** `AWS_BEDROCK_ACCESS_KEY_ID` and `AWS_BEDROCK_SECRET_ACCESS_KEY`, plus `AWS_BEDROCK_SESSION_TOKEN` for temporary credentials. The gateway signs each request with them. - **Bedrock API key:** `AWS_BEDROCK_API_KEY`. AWS gives a new API key as `AWS_BEARER_TOKEN_BEDROCK`; paste that value under `AWS_BEDROCK_API_KEY`. Set `AWS_BEDROCK_REGION` to the region of the key. With the CLI, save it in the same command as the API key. This example reads the credential from `AWS_BEARER_TOKEN_BEDROCK` in your shell. ```bash tdx providers keys set --name AWS_BEDROCK_API_KEY \ --value-env AWS_BEARER_TOKEN_BEDROCK --setting AWS_BEDROCK_REGION=us-west-2 ``` When both halves of the key pair are set, the gateway signs with them, even if the API key is set too. When the pair is incomplete, it sends the API key. If a stored half of the pair can't be read, the request fails rather than falling back to the API key, which may belong to another AWS account or role. The gateway never reads `AWS_BEARER_TOKEN_BEDROCK` or the other `AWS_*` names that AWS tools read, so a key meant for those tools never reaches Bedrock through the gateway. ## Replace or remove a key 1. Create a new key at the provider. 2. Save it under the same credential name, as above. 3. If you run several replicas, wait for each to pick up the new key from the shared configuration. 4. Send a small request through each replica to check the provider connection. If the provider reports usage by key, confirm that it reports those requests under the new key. These requests can incur charges. 5. Revoke the old key at the provider. Your API keys keep working throughout, so replace a provider key as soon as it may have leaked. For a key that comes from the environment, change the variable and restart the gateway instead. **Dashboard** To remove a saved key, choose **Remove** on its row. The provider's models stop unless the environment holds the same variable. **HTTP API** To remove a saved key, send `DELETE` to the same path. The gateway answers `{"removed":"OPENAI_API_KEY"}`. The provider's models stop unless the environment holds the same variable. ## Give one provider several keys Add a pool for a backup key or for workspaces with keys of their own. See the continuation and Batch rules below. Set `TOKEDEX_PROVIDER_KEY_POOLS_FILE` to a file that lists them, or, for a gateway started from a configuration file with `--config`, put the same object under `providerKeyPools` in that file. The file names environment variables, never keys. ```yaml slots: - slot: OPENAI_API_KEY strategy: fill-first entries: - id: primary label: Primary enabled: true availability: global healthGeneration: 0 secret: environment: OPENAI_KEY_PRIMARY - id: backup label: Backup enabled: true availability: global healthGeneration: 0 secret: environment: OPENAI_KEY_BACKUP workspaces: - id: ws_default ``` | Field | Meaning | | --- | --- | | `strategy` | `fill-first`, the default, uses the entries in order. `rotate` starts one entry later for each request. | | `id` | A stable name for the entry. Never reuse one. | | `availability` | `global`, or a list of workspace IDs that may use the entry. | | `healthGeneration` | Raise it when you replace an entry's key or enable the entry again. | | `tags` | Optional labels. They do not affect which key is used, and no report shows them. | | `workspaces` | Every workspace whose requests may use the pool, by ID. `ws_default` is the Default workspace's ID; a workspace's name is not its ID. `providerKeyFallback: global` lets a workspace with entries of its own also use the global ones. | Start with `fill-first` to use the first eligible key and skip keys that are cooling down. After a retryable credential failure, the gateway can try another key in the same request if the model and API have another attempt available. A later request can use the backup while the first key cools. Choose `rotate` to spread requests across equal keys. Set every named variable, then restart the gateway after each edit. The gateway refuses to start on an unknown field in the pool file, a named variable that is not set, or a variable name that starts with `TOKEDEX_` or `AA_ROUTER_`. Each request's log line and exported trace name the entries it tried. A request from a workspace that the pool file does not list is refused with `403` for that provider. While a pool exists, the gateway ignores the key saved for that credential, and with any global entry, its environment variable too. It says so once at startup. A credential with more than one key, counting disabled entries and the environment variable, cannot run Batch jobs or use named fallback. [Provider-hosted custom models](/gateway/custom-models#serve-one-model-id-through-several-providers) can continue a stored conversation on the credential that served it. Catalogue models require a single credential for stored conversations. A credential tied to a provider account takes exactly one global entry. ## Stored key encryption The gateway encrypts each saved key and never shows it again. The encryption key is the file `credential-kek.json`, in `kek/` on the Helm chart's volume claim and in `~/.tokedex/auth/` for a local gateway, or a key in AWS KMS. In production, keep the encryption key in AWS KMS, or back the file up with the gateway's state but apart from the database backups, so one stolen backup cannot open stored keys. Without the file, a restored gateway cannot read its stored keys and you enter them again. Keys that come only from the environment are not in that backup, so keep them in your own secret store. See [Backup and restore](/gateway/backup-restore). Next: [Routers and fallback](/gateway/router), [Your own model server](/gateway/custom-models) or [API keys](/gateway/api-keys). --- # Routers and fallback Create a model ID of your own that sends each request to one of the models you list, and moves to the next when a provider fails. **Dashboard** 1. Open **Models & Routing → Routing** and choose **+ New router**. 2. Enter the **Model ID** clients will send, such as ``. 3. Under **How should it choose?**, pick a strategy, such as **In order**. 4. Under **Models**, add at least two models whose provider has a key. With **In order**, set the order with the arrows. 5. Check **Works with** for shared API formats, then check the pick preview. Models on the same API can still handle requests or responses differently, such as how they represent tool calls. If the preview says the models do not share a projection contract, swap or remove a model before creating the router. 6. Under **If a model fails**, choose **Change** to pick which failures fall back and set **Most attempts per request**. 7. Check **How a request flows**, then choose **Create router**. The router appears under **Your routers**, and clients in every workspace can call its ID at once. If the form says the router is saved but clients can't call it yet, choose **Create router** again. **HTTP API** A router takes two requests: one creates it under an internal ID, and one gives it the model ID clients send. Each model is named by its route for each client API, the `groupId` of its rows in `sources` from `GET /control/compiled/addresses`, such as `openai-gpt-6-luna-chat` for `openai/gpt-6-luna` on OpenAI Chat Completions. ```bash curl -sS -X PUT "$TOKEDEX_URL/control/compiled/model-groups/coding-fallback" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "strategy": { "reviewed": { "modelGroupStrategyId": "model-group.ordered.v1", "modelGroupStrategyVersion": "2.0.0" } }, "members": [ { "sourceGroupIds": { "openai.chat-completions": "openai-gpt-6-luna-chat", "openai.responses": "openai-gpt-6-luna-responses" } }, { "sourceGroupIds": { "openai.chat-completions": "openai-chat-claude-haiku-5-5", "openai.responses": "openai-responses-claude-haiku-5-5" } } ], "maxRequestNativeAttempts": 2, "fallbackEligibleFailureClasses": ["rate-limited", "provider-unavailable", "timeout", "transport-error"], "enabled": true, "listed": true }' ``` The gateway answers `201` and saves the router without a callable ID. To check whether the draft can serve its shared APIs, send the same body to `POST /control/compiled/model-groups/preview`. If `addressProblem` says the models do not share a projection contract, their request or response handling differs on that client API. Use compatible routes on that API, or give the router an ID only on compatible APIs. Give the router a model ID on each compatible client API: ```bash curl -sS -X PATCH "$TOKEDEX_URL/control/compiled/addresses" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "changes": [ { "clientDialectId": "openai.chat-completions", "address": "", "entry": { "target": { "modelGroupId": "coding-fallback" }, "replaces": null } }, { "clientDialectId": "openai.responses", "address": "", "entry": { "target": { "modelGroupId": "coding-fallback" }, "replaces": null } } ] }' ``` Both answer with the whole routing table, where the router now lists its model IDs: ```json { "modelGroupId": "coding-fallback", "origin": "operator", "enabled": true, "listed": true, "addresses": [{ "clientDialectId": "openai.chat-completions", "address": "" }, { "clientDialectId": "openai.responses", "address": "" }] } ``` You need: an admin key with the `admin` or `operator` preset in `TOKEDEX_ADMIN_KEY`, and `export TOKEDEX_URL='http://127.0.0.1:4000'`. A router cannot contain another router. ## See which model answered Send a request to the router with `-i`. It calls a provider and can incur charges. ```bash curl -sS -i "$TOKEDEX_BASE_URL/chat/completions" \ -H "Authorization: Bearer $TOKEDEX_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "", "messages": [{ "role": "user", "content": "Reply with exactly the word \"hello\"." }] }' ``` When the first model's provider was rate limited, the second answered: ```text HTTP/1.1 200 OK x-tokedex-provider: anthropic x-tokedex-model: anthropic/claude-haiku-5.5 x-tokedex-strategy: model-group.ordered.v1 ``` The headers name the model that answered after any fallback, and the body's `model` stays the ID you sent. The key needs access to the router ID. In **Observability**, the request shows the router as its **Model alias**. ## Set a model's provider routing A model served by several providers sends each request to the first connected provider in its order, and the next one takes it when a provider fails. Each client API of the model has its own order. The default order is the catalogue's: cheapest list price first, then the model maker's own provider, then provider ID. In an order you set, the providers you list come first and any you leave out follow in the default order. You set or reset the order of each client API separately, and it applies in every workspace; a client API with one provider has no order to set. A request that sends its own [`x-tokedex-provider-order`](/gateway/models#prefer-providers) header tries the providers it names first, in its order, and the rest in this order, so set your order for what most of your traffic needs. A follow-up turn of a conversation, such as one carrying a tool result, tries each provider up to three times, a short wait apart, before it moves to the next: the provider keeps its prompt cache for the conversation, which makes the turn cheaper and faster. **Dashboard** Open the model in **Models & Routing**. Under **Provider routing**, each client API with more than one provider lists its providers in the order a request tries them, with each one's catalogue list price. The list is labelled **Default: cheapest, then first-party, then A–Z**, or **Custom · set by an operator** once an order is set. To reorder a client API's providers where they are listed: 1. Drag a provider by its handle to its new place in the list. The list's label changes to **Custom · set by an operator**, or back to the default's label if the new order is the default. 2. Choose **Save**, or **Cancel** to put the saved order back. Only the client APIs whose order changed are saved. From the keyboard, focus a provider's handle, press Space or Enter to pick it up, move it with the up and down arrow keys, and press Space or Enter to drop it. Escape puts it back where it was. To reorder them in the editor, which also resets an order: 1. Choose **Change provider routing**. A model whose client APIs each have one provider does not show it. 2. In a client API's list, drag a provider by its handle, or move it up or down with its arrows. The list's label changes to **Custom · set by an operator**. 3. To return one client API to the default order, choose **Reset to default** under its list. 4. Choose **Save**. Only the client APIs whose order changed are saved. On a touch screen, where dragging may not work, use the editor's arrows. Providers without a key are skipped until they have one. A client API that now has one provider can keep an order saved from when it had more, which would apply again if a provider returns. **Provider routing** and the editor name each such client API, with a **Reset to default** that removes its order: under **Provider routing** at once, and in the editor when you choose **Save**, with any order you changed there. Until a dragged order is saved or cancelled, **Save** and **Cancel** take the place of **Change provider routing** and these resets. **HTTP API** Send `PATCH /control/compiled/source-edits/` for each client API whose order you set, with the `groupId` of the model's row for that API in `sources` from `GET /control/compiled/addresses`. The gateway refuses an order for a route with one provider with `400`: ```bash curl -sS -X PATCH "$TOKEDEX_URL/control/compiled/source-edits/" \ -H "Authorization: Bearer $TOKEDEX_MASTER_KEY" \ -H "Content-Type: application/json" \ -d '{ "routing": { "providerOrder": ["", ""] } }' ``` `{ "routing": null }` restores the default order on that route. The gateway refuses an order naming a provider that does not serve the route with `400`. Read the model's `routing` for the API you edited with `GET /v1/models/?client_dialect_id=openai.responses`. URL-encode the full model ID, including its slash. Use the `client_dialect_id` from the model list and authenticate with a bearer API key. `set_by` is `operator` for your order and `catalogue` for the default. `order` lists the route's ready providers in member order, filtered by the API key's provider access. A particular request can narrow the order further through its capabilities or provider options. With the CLI, `tdx models providers list` lists the routes, and [`tdx models providers show --id `](/cli/reference/models#tdx-models-providers-show) prints a route's order, who set it and each provider's list price. [`tdx models providers edit`](/cli/reference/models#tdx-models-providers-edit) sets an order with one `--provider-order` per provider, first tried first, or restores the default with `--default-order`: ```bash tdx models providers edit --id --provider-order --provider-order tdx models providers edit --id --default-order ``` On the gateway's own machine, the admin command saves the same order in the gateway's store without going through the server. It takes the providers as one comma-separated list: ```bash tokedex-gateway source-edits order --id --provider-order , ``` `--default-order` in place of `--provider-order` restores the default order. By default the command refuses to save while a running gateway holds the store. Add `--dry-run` to print the change without saving it. ## Strategies | Strategy | Picks | `modelGroupStrategyId` | Needs | Use it when | | --- | --- | --- | --- | --- | | **In order** | The first model, then the next down the list | `model-group.ordered.v1` | Nothing extra | Start here: you choose the main model and its backups, so what answers stays predictable | | **Cheapest** | The model with the lowest catalogue price | `model-group.cost.v1` | A catalogue price for each model | The models are interchangeable for the task | | **Highest quality** | The model with the highest Artificial Analysis Intelligence Index | `model-group.quality.v1` | An Intelligence Index for each model | The answer matters more than its price | | **Custom** | The models that pass your conditions, in the order you rank them by | None: name it in `strategy.operator` | The facts its conditions and ranking read | One condition is not enough, such as the cheapest model above an Intelligence Index floor | With every strategy, the next model in line answers when the pick fails. A model missing what its strategy needs is never picked. With **Highest quality**, or a custom strategy that reads a benchmark, choose in each model's **Ranked at** list the variant, such as the reasoning effort, your requests run at. A custom strategy keeps the models that pass its conditions on benchmark scores and prices, then ranks them; [Combine conditions in a custom strategy](#combine-conditions-in-a-custom-strategy) builds one. The router uses the variant you chose for each model, skips models missing a required measurement and keeps your model order when values tie. If you limit providers on the router, its strategy or an individual model, a provider must meet all three sets of limits to be eligible. Only eligible providers contribute to the model's price. A strategy that blends input and output token prices needs the same input rate and the same output rate across those providers. Cached-input rates do not affect that calculation. The same limits apply to the first request, retries, fallback, continuations and Batch jobs. If no provider qualifies, the router can refuse the request before contacting one. ## Combine conditions in a custom strategy A custom strategy keeps only the models that pass its conditions, then ranks them. The built-in `aa/cheapest-40-intelligence` keeps every connected model with an Artificial Analysis Intelligence Index of at least 40 and ranks them by cost per task, cheapest first. This strategy, `cheapest-40-intelligence`, applies the same conditions to the models you list in your own router, and you can change the floor or the ranking. Save it as `strategy.json`: ```json { "language": "strategy-tree.v1", "strategy": { "pipeline": [ { "filter": { "intelligence": { ">=": 40 } } }, { "sort": [{ "cost-per-task": "asc" }] } ] }, "facts": { "intelligence": { "metric": "aa-intelligence-index.v5" }, "cost-per-task": { "metric": "aa-intelligence-index.v5" } }, "maximumNativeAttempts": 3, "fallbackEligibleFailureClasses": ["rate-limited", "provider-unavailable", "timeout", "transport-error", "context-length-exceeded"] } ``` | Fact | Means | Range | | --- | --- | --- | | `intelligence` | Artificial Analysis Intelligence Index | 0 to 100 | | `cost-per-task` | Published cost of one Intelligence Index task, in US dollars | 0 to 10,000 | | `time-per-task` | Published time for one Intelligence Index task, in seconds | 0 to 86,400 | | `price` | Catalogue price in US dollars per million tokens, input and output blended by the weights you set | 0 to 1,000,000 | `pipeline` holds up to eight steps. A `filter` compares one fact with `>=`, `<=`, `>` or `<`, and `and` joins several, such as `{ "and": [{ "intelligence": { ">=": 40 } }, { "price": { "<=": 5 } }] }`. One `sort`, last, ranks by one to four facts, `asc` or `desc`. Declare in `facts` each fact the pipeline reads and no others: `intelligence`, `cost-per-task` and `time-per-task` take `{ "metric": "aa-intelligence-index.v5" }`, and `price` takes `{ "source": "token-blend", "priceBlend": { "inputWeight": 3, "outputWeight": 1 } }`. To rank by token price instead, sort by `price`. A router that uses the strategy can make at most `maximumNativeAttempts` attempts, and falls back only on failures from `fallbackEligibleFailureClasses`. **Dashboard** The dashboard lists custom strategies but cannot save or change one. Save `strategy.json` under the ID `cheapest-40-intelligence` with the request this page shows for the HTTP API, or with `tdx models routers strategies set` (see the [command reference](/cli/reference/models#tdx-models-routers-strategies-set) in the CLI docs). Then: 1. Open **Models & Routing → Routing** and choose **+ New router**. 2. Enter the **Model ID** clients will send, such as ``. 3. Under **How should it choose?**, choose **Custom strategy**, then pick `cheapest-40-intelligence` under **Custom strategy to use**. 4. Under **Models**, add the models it chooses among, and set each one's **Ranked at** to the variant your requests run at, such as **high**. 5. Check **How a request flows**, then choose **Create router**. Under **Custom strategies**, **See how it ranked** on `cheapest-40-intelligence` shows each model's place and why the others were left out, such as an Intelligence Index under 40. **HTTP API** ```bash curl -sS -X PUT "$TOKEDEX_URL/control/compiled/model-group-strategies/cheapest-40-intelligence" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" \ -H "Content-Type: application/json" \ --data-binary @strategy.json ``` The gateway answers `201`, or `200` when it replaces the strategy. A router names it in `strategy.operator`, and each model sets `rankingVariantId`, the variant your requests run at: ```bash curl -sS -X PUT "$TOKEDEX_URL/control/compiled/model-groups/smart-and-cheap" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "strategy": { "operator": "cheapest-40-intelligence" }, "members": [ { "sourceGroupIds": { "openai.chat-completions": "openai-gpt-6-1-sol-chat", "openai.responses": "openai-gpt-6-1-sol-responses" }, "rankingVariantId": "high" }, { "sourceGroupIds": { "openai.chat-completions": "openai-gpt-6-1-terra-chat", "openai.responses": "openai-gpt-6-1-terra-responses" }, "rankingVariantId": "high" }, { "sourceGroupIds": { "openai.chat-completions": "openai-chat-claude-sonnet-5-5", "openai.responses": "openai-responses-claude-sonnet-5-5" }, "rankingVariantId": "high" }, { "sourceGroupIds": { "openai.chat-completions": "openai-gpt-6-luna-chat", "openai.responses": "openai-gpt-6-luna-responses" }, "rankingVariantId": "high" } ], "maxRequestNativeAttempts": 3, "fallbackEligibleFailureClasses": ["rate-limited", "provider-unavailable", "timeout", "transport-error"], "enabled": true, "listed": true }' ``` Give it a model ID with the `PATCH /control/compiled/addresses` request at the top of this page. A router can make no more attempts than its strategy's `maximumNativeAttempts`, and fall back on no failure its strategy leaves out. To see how the strategy ranks the router's models: ```bash curl -sS "$TOKEDEX_URL/control/compiled/model-group-strategies/cheapest-40-intelligence/explain?model-group=smart-and-cheap" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" ``` The cheapest model that passes ranks first, and a model under the floor is left out with its score: ```json [{ "id": "smart-and-cheap", "available": true, "explanation": { "strategy": { "source": "operator", "id": "cheapest-40-intelligence", "digest": "sha256:" }, "members": [ { "model": "", "outcome": "ranked", "position": 2, "metrics": { "cost-per-task": 0.590985 } }, { "model": "", "outcome": "ranked", "position": 1, "metrics": { "cost-per-task": 0.25928 } }, { "model": "", "outcome": "ranked", "position": 3, "metrics": { "cost-per-task": 1.636129 } }, { "model": "", "outcome": "excluded", "reason": "filter", "rule": "/strategy/pipeline/0/filter/intelligence", "test": { "intelligence": { ">=": 40 } }, "actual": 21.4 } ] } }] ``` `members` keeps the order you listed. With these four models, `openai/gpt-6.1-terra` ranks first, then `openai/gpt-6.1-sol` and `anthropic/claude-sonnet-5.5`, and `openai/gpt-6-luna`, at an Intelligence Index of 21.4, is left out. The scores and costs change as the catalogue does. A request to the router names the strategy beside the model that answered: ```text HTTP/1.1 200 OK x-tokedex-strategy: cheapest-40-intelligence x-tokedex-strategy-evidence: metadata@sha256: ``` `x-tokedex-strategy-evidence` names the benchmark and price data the ranking read. The gateway refuses a strategy it cannot read with `400` `invalid_model_group_strategy` and lists each problem. It also refuses a router that no model qualifies for, and a strategy change that would leave a router using it with none. If a later catalogue leaves no model qualifying, the router stops answering and clients get `404` `model_not_found`: lower the floor or add models. ## Failures that fall back **Dashboard** A new router falls back on rate limits, timeouts, provider outages and connection errors. You can add **Prompt too long**; add it when your models have different context windows, so a long prompt moves to one that can take it. Any other error goes straight back to the client. **HTTP API** `fallbackEligibleFailureClasses` lists any of `rate-limited`, `timeout`, `provider-unavailable`, `transport-error` and `context-length-exceeded` (a prompt too long for the model). Add `context-length-exceeded` when your models have different context windows, so a long prompt moves to one that can take it. Any other error goes straight back to the client. List models from more than one provider, so an outage or rate limit at one leaves another to answer. The most attempts per request count the first try, from 1 to 16, so `1` turns fallback off. Start with one attempt per model; lower it when clients would rather fail fast, since each attempt adds the time the failed one took. Fallback reaches only models that support the features the request uses, such as tools, and a stream moves to the next model only before it sends any output. For a self-contained text request, the router tries providers of the same model whose context windows fit the estimated input and requested output first. It keeps the configured order within each set. If any eligible provider has an unknown window, or the request uses media, stored context, a pinned continuation or token counting, the configured order applies. **Prompt too long** triggers fallback when the provider returns HTTP 400 and identifies a context overflow. If the provider says that `max_tokens` is invalid, the router ends the request with that error. ## Built-in routers | Model ID | Chooses | | --- | --- | | `aa/most-intelligent` | Eligible models by Intelligence Index, highest first | | `aa/cheapest` | Eligible models by benchmarked cost per task, cheapest first | | `aa/fastest` | Eligible models by benchmarked time per task, fastest first | | `aa/cheapest-50-intelligence` | Eligible models with an Intelligence Index of at least 50, by benchmarked cost per task, cheapest first | | `aa/cheapest-40-intelligence` | The same, at an Intelligence Index of at least 40 | | `aa/cheapest-30-intelligence` | The same, at an Intelligence Index of at least 30 | These routes use only providers you have connected. IDs that start with `aa/` are reserved. Give an application a router of its own when it must keep the same candidate list across releases. **Dashboard** Under **Built-in routers**, you can hide one from the model list or turn it off, then **Save changes**; you cannot change it. See [Your own model server](/gateway/custom-models#serve-a-model-under-your-own-id) to serve a model under an ID you choose. **HTTP API** `PATCH /control/compiled/model-group-edits/` with `{ "enabled": false }` turns one off, and `{ "listed": false }` hides it, where `` is its internal ID, such as `aa-intelligence` for `aa/most-intelligent`. ## Change or delete a router **Dashboard** Under **Your routers**, **Edit** opens the same form, and **Delete** removes the router and its ID. The **In /v1/models** and **Enabled** switches hide it from the model list or turn it off once you choose **Save changes** in the bar that appears. **See how it ranked** shows which models a strategy ranked or left out, and why. To give a router a different ID, create a new one. **HTTP API** Send the whole body again to the same `PUT` path; the gateway answers `200`. To delete it, first release each model ID with `"entry": null` in a `PATCH /control/compiled/addresses` change, then send `DELETE` to `/control/compiled/model-groups/`. A router that still has a model ID is refused with `400`. To give a router a different ID, add the new ID with a `PATCH /control/compiled/addresses` change and release the old one with `"entry": null`, in the same request. Clients that call a deleted or turned-off router's ID get `404` `model_not_found`. Next: [Find a model](/gateway/models), [Model access and limits](/gateway/model-access-and-limits) or [Prices](/gateway/spend-and-usage#prices). --- # Your own model server Serve a model from your own OpenAI Chat Completions, OpenAI Responses or Anthropic Messages server through the gateway, under a model ID you choose. **Dashboard** 1. Open **Models & Routing** and choose **+ Add model → Connect your own server**. 2. Fill in **Public model ID**, **Native protocol**, **Base URL**, **Upstream model id** and **Credential**, as described below. 3. Under **Price**, choose **Input and output rates** or **Free**, then choose **Connect server**. The model appears on **Models & Routing** as pending. Saving calls nothing and serves nothing until the model passes its test. **HTTP API** ```bash curl -sS "$TOKEDEX_URL/control/compiled/custom-models" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "publicModelId": "", "baseUrl": "http://127.0.0.1:8000", "upstreamModelId": "", "protocol": "openai.chat-completions", "credential": { "environment": "AA_OPERATOR_KEY_LLAMA" }, "price": { "input": "0.10", "output": "0.20" }, "listed": true }' ``` The gateway answers `201` with the model, pending its test: ```json { "publicModelId": "", "protocol": "openai.chat-completions", "price": { "input": "0.10", "output": "0.20" }, "revision": "sha256:1a2460015b3c…", "qualificationEstimateUsd": "0.001871600", "qualification": { "status": "pending" } } ``` You need: an admin key with the `admin` preset in `TOKEDEX_ADMIN_KEY`, and `export TOKEDEX_URL='http://127.0.0.1:4000'`. Saving calls nothing and serves nothing until the model passes its test, which runs from the dashboard, or from `tdx models custom qualify` with a person's approval in the dashboard. | Field | Enter | | --- | --- | | Model ID | The model ID clients send. It cannot start with `aa/`. | | Protocol | The API your server speaks. Clients call the model on that API only. | | Base URL | Your server's base URL, without a trailing `/v1`. | | Upstream model ID | The model ID your server expects. | | Credential | None, an environment variable, a key stored on **Providers**, or a [key pool](#give-your-server-several-keys). The gateway sends it as a bearer token, or as `x-api-key` on Messages. | | Price | Input and output US dollars per million tokens, with optional cache read and cache write rates, or free. Required when you add the model. | Protect your server with a key and give the gateway that key as the credential, so the server answers only callers that hold it. Enter a price that reflects what the server costs you, so spend and budgets count its use; a free model never counts toward a budget. On any API but its own, a model on your own server answers `404` `model_not_found`. On Responses, clients send the whole history each time. On Messages, send text and function tools for the conversation. A custom model has one server and no provider order, so it ignores a well-formed `x-tokedex-provider-order` header. Set reasoning on the request. Chat Completions forwards `reasoning_effort`. Responses forwards `reasoning.effort`, `reasoning.summary` and `reasoning.context`. Messages forwards `output_config.effort` and `thinking`, including adaptive, disabled and manual thinking with a token budget. Your server decides which of those controls the model accepts. To reach a server on a private network or over plain `http`, such as `localhost`, start the gateway with `TOKEDEX_ALLOW_PRIVATE_NETWORK_ORIGINS=true`. Leave it off unless a custom model needs it, since it lets a custom model point the gateway's requests at your private network. **Dashboard** The form's fields are **Public model ID**, **Native protocol** (**Chat Completions**, **Responses (stateless)** or **Messages**), **Base URL**, **Upstream model id**, **Credential** with its **Credential name**, **Price** and **Show in model list**. On Messages, also set **Maximum output tokens**, the ceiling used when a request sends none. For **Environment variable** or **Stored key (Providers page)**, the **Credential name** must start with `AA_OPERATOR_KEY_`; store such a key on **Providers** by choosing **Custom key…**, see [Provider credentials](/gateway/provider-credentials). A model saved earlier with a connected provider's key keeps that key. To add a model a connected provider serves, use [**Add a model from a provider**](#a-model-a-catalogue-provider-serves) instead. **HTTP API** Set `protocol` to `openai.chat-completions`, `openai.responses` or `anthropic.messages`. On Messages, also send `"messages": { "apiVersion": "2023-06-01", "maxOutputTokens": }`, the ceiling used when a request sends none. Omit `credential` for an unauthenticated server. Use `{ "environment": "" }` for an environment variable, `{ "custody": "" }` for a stored key, or a [key pool](#give-your-server-several-keys). Environment and stored credential names start with `AA_OPERATOR_KEY_`. [Provider credentials](/gateway/provider-credentials) Set `price` to `{ "input", "output" }`, with optional `cachedInput`, `cacheWrite` and `cacheWriteLong`, or `{ "free": true }`. A cache rate left out is charged at the input rate and an hour-long write at the cache write rate. `listed` puts the model in `GET /v1/models`. ## Give your server several keys In store mode, add a dedicated pool to the deployment file named by `TOKEDEX_PROVIDER_KEY_POOLS_FILE`. Use the full base URL, including any path prefix, and the native protocol of the model's server. Give each entry its own `AA_OPERATOR_KEY_` environment variable and supply its value to the gateway. This example shares both keys with the Default workspace. ```yaml slots: [] customPools: - id: model-server baseUrl: https://models.example.com protocol: openai.chat-completions entries: - id: model-primary label: Primary enabled: true availability: global healthGeneration: 0 secret: environment: AA_OPERATOR_KEY_MODEL_PRIMARY - id: model-backup label: Backup enabled: true availability: global healthGeneration: 0 secret: environment: AA_OPERATOR_KEY_MODEL_BACKUP workspaces: - id: ws_default ``` Use `slots: []` when the file has only dedicated pools. A pool uses `fill-first` by default or `rotate` when configured. Entries can name specific workspaces. Increase the entry's `healthGeneration` when replacing its key or enabling it again, then restart the gateway to apply changes. [Set key availability and fallback](/gateway/provider-credentials#give-one-provider-several-keys) **Dashboard** For a dedicated pool, choose **Configured key pool** under **Credential**, then select its ID under **Key pool**. To borrow a catalogue provider's key or pool, choose **Catalogue provider key or pool** and enter the provider's exact reviewed API base URL and protocol. **HTTP API** Send `"credential": { "pool": "model-server" }` in the model declaration. To borrow a catalogue provider's key or pool, send `"credential": { "provider": "" }` with the provider's exact reviewed API base URL and protocol. Use `tdx models custom pools` to list dedicated pools and `tdx models custom create --body-file ./custom-model.json` to send the declaration from the CLI. Qualify the model with an eligible key in the workspace you charge. The test stays on that key and within the cap you approve. A fresh request can try one backup key after a retryable failure. Changing pool entries keeps a qualified endpoint enabled. If a continuation's original key changes or becomes unavailable, the gateway refuses it before calling the server. ## A model a catalogue provider serves When a connected provider serves a model the catalogue does not list yet, add it by provider instead of base URL. The gateway calls the provider's own API with the provider key it already holds, and serves the model under that provider, so provider access, key limits and pins apply as they do to the provider's catalogue models. **Dashboard** 1. Open **Models & Routing** and choose **+ Add model → Add a model from a provider**. 2. Choose the **Provider**, and enter the **Provider model ID** (the provider's own ID for the model) and the **Gateway model ID** (the ID clients send). If the provider offers several APIs, choose the **Provider API**. 3. Tick **Images** or **Files** if the model takes them. 4. Under **Price**, choose **Input and output rates** or **Free**, then choose **Add model**. Providers a model can't be added from yet are listed with the reason, such as a provider key that isn't connected. **HTTP API** ```bash curl -sS "$TOKEDEX_URL/control/compiled/custom-models" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "publicModelId": "team/new-model", "provider": "fireworks", "upstreamModelId": "accounts/fireworks/models/new-model", "price": { "input": "0.60", "output": "2.50" } }' ``` Use `"price": { "free": true }` to register a model as free. With the CLI, pass both rates or use `--free`. ```bash tdx models custom create --provider fireworks \ --provider-model accounts/fireworks/models/new-model --id team/new-model \ --price-input 0.60 --price-output 2.50 ``` Run `tdx models custom providers` to list providers and their APIs. See the [CLI reference](/cli/reference/models#tdx-models-custom-create) for cache rates, API selection and other options. - The provider API determines which client APIs can call the model. Most providers serve OpenAI Responses, OpenAI Chat Completions and Anthropic Messages. Bedrock Converse serves OpenAI Responses. Vertex AI and Google AI Studio models using GenerateContent also serve native Gemini GenerateContent calls. [Gateway API reference](/gateway/api-reference) - The gateway translates calls made on a different supported API. It reports omissions in `x-tokedex-fidelity-v1` and drops a field only when every catalogue model on that provider API may drop it. A call that requires a loss and sends `x-tokedex-fidelity-policy: strict` receives `422`. [Check feature support](/gateway/models#check-feature-support) - Set reasoning on the client request. The provider's API determines which controls the gateway can send. These can include named effort, Responses summaries and context, Messages adaptive thinking or token budgets, and Gemini `thinkingBudget` and `includeThoughts`. If the route offers effort but cannot send the requested level, the gateway returns `422` with the available levels. The provider can still reject a forwarded control. - It serves as soon as you register it, without a qualification test. - Include `protocol` when the provider offers more than one API. `inputs: ["image", "file"]` lets images or files through. - A call to a provider’s Messages API needs an output limit. For a model without a reviewed or configured limit, set `max_tokens` on Anthropic Messages, `max_completion_tokens` (or `max_tokens`) on OpenAI Chat Completions, or `max_output_tokens` on OpenAI Responses. - Any key whose model scope admits the ID can call it, not only keys that name it. - A model the catalogue already serves on that provider is refused. Bedrock, Vertex AI, Azure, Google AI Studio, Cloudflare Workers AI and Databricks use the credentials and account settings you configure for the provider. The provider picker shows which APIs are ready. [Connect provider credentials](/gateway/provider-credentials) - Keep a price on a priced model when you edit it. A price on the model takes precedence over a [price override](/gateway/spend-and-usage#prices) for that provider model ID. - Existing unpriced models continue serving where the budget permits unpriced calls. Use **Set price** or a `PUT` with `price` to price one. You can also apply that price to earlier calls. [Price calls made with no price](/gateway/spend-and-usage#price-calls-made-with-no-price) ## Serve one model ID through several providers Add one declaration per provider with the same gateway model ID. Give each new member rates or mark it free. Each client API tries the providers that can serve it in provider order. A provider pin limits the request to the providers it names. Pricing and usage follow the provider and provider model ID that served the request. [Set provider order](/gateway/router#set-a-models-provider-routing) In best-effort mode, each provider can apply its reviewed translations. The response reports the serving provider's losses in `x-tokedex-fidelity-v1`. Strict mode uses providers that can serve the request without loss. **Dashboard** Open the shared model and use **Add provider** to add a member. Choose a provider to edit its model, price or status. Use the model's discovery setting to show or hide the shared ID. **HTTP API** Send another declaration to `POST /control/compiled/custom-models` with the same `publicModelId` and a different `provider`. Pass `?provider=` on a member update or removal. Use `PATCH /control/compiled/custom-models/` with `listed` and `expectedListed` to change discovery visibility for the model. With the CLI, run `tdx models custom list` to see the providers. Use `--provider` on `tdx models custom edit` or `tdx models custom remove` to select one. Use `tdx models custom visibility` to show or hide the shared ID. Authorised clients can call an unlisted model by ID. With a provider key pool, a fresh request can try a second eligible key on a retryable credential failure. A custom route with a pool has a two-attempt budget shared by key retries and provider failover. The preferred provider can spend both attempts. A continuation uses the exact provider deployment and credential that served the earlier turn. If that credential is unavailable, the continuation fails before the gateway calls a provider. [Set up a provider key pool](/gateway/provider-credentials#give-one-provider-several-keys) ## Test and enable a custom model **HTTP API** The test needs a person signed in to the dashboard: no admin, API or master key can run it. Run it from the dashboard, or with [`tdx models custom qualify`](/cli/reference/models#tdx-models-custom-qualify), which opens a device approval in the dashboard for a person to accept when no fresh approval exists. 1. On **Models & Routing**, open the model and choose **Edit custom model**, then **Test and enable / status**. 2. Choose **This run's total cap in USD** and the **Workspace charged for this run**. Pick a cap at or above the expected cost the drawer shows: the gateway checks its estimate against the cap before the first call, and refuses the run when the cap is lower. 3. Tick the approval and choose **Approve and qualify**. The gateway sends at most four calls to your server, checking a conversation's history, streaming and a function-tool round trip. When they pass, the drawer reads **Passed. This exact revision is enabled.** and the model serves at once. When one fails, it names the check, and the model stays off. ## Keys that can call a custom model Only a key whose model list names the model can call it: [create one](/gateway/api-keys) with **Only the models I choose** and select it. A key with **All permitted models** is refused with `403` `permission_denied`. ```bash curl -sS -i "$TOKEDEX_BASE_URL/chat/completions" \ -H "Authorization: Bearer $TOKEDEX_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "", "messages": [{ "role": "user", "content": "Reply with exactly the word \"hello\"." }] }' ``` ```text HTTP/1.1 200 OK x-tokedex-provider: operator x-tokedex-model: x-tokedex-trust: unreviewed ``` The request calls your server, and costs what its price says. A workspace can turn custom models off with the provider they belong to; see [Model access and limits](/gateway/model-access-and-limits). ## Change or remove a custom model **Dashboard** Open the model's details and choose **Edit custom model**, change it in **Edit server model** and choose **Save pending changes**, or choose **Delete custom model** and confirm. For a model from a provider, choose **Edit model**, change it and choose **Save changes**, or **Delete model**. **HTTP API** Send `PUT /control/compiled/custom-models/` with `{ "revision": "", "declaration": { … } }`: the current `revision` from `GET /control/compiled/custom-models`, and the whole declaration as you created it. To remove the model, send `DELETE` to the same path. Saving any change to a model on your own server takes it out of service until it passes the test again, so make changes when few clients call the model, and test at once. A model from a provider keeps serving: the next request uses the change. ## Serve a model under your own ID Point a model ID you choose at a catalogue model or a router, so clients keep sending the same ID while you change what answers it. To serve a custom model under an alias, use a router with that custom model as a member. **Dashboard** 1. On **Models & Routing**, choose **+ Add model → Create a model alias**. 2. Enter the **Public model ID** and select what it routes to for each API format. 3. Choose **Review**, then **Confirm**. To change an ID later, open its details and use **Change routing** or **Rename** beside the API format; both show the same review. **HTTP API** Each change names a client API, the model ID, and the route it points at, the `groupId` of a row in `sources` from `GET /control/compiled/addresses`: ```bash curl -sS -X PATCH "$TOKEDEX_URL/control/compiled/addresses" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" \ -H "Content-Type: application/json" \ -d '{ "changes": [ { "clientDialectId": "openai.chat-completions", "address": "", "entry": { "target": { "sourceGroupId": "openai-gpt-6-luna-chat" }, "replaces": null } } ] }' ``` The answer lists the new model ID among `addresses`. Send the same change with `"entry": null` to remove it, or with `{ "modelGroupId": "" }` as the target to point it at a router. Renaming a model ID stops the old ID on that API. Update your clients and any API key limited to the old ID first. Next: [API keys](/gateway/api-keys), [Routers and fallback](/gateway/router) or [Prices](/gateway/spend-and-usage#prices). --- # Find and inspect a request Look a request up by its request ID and see who sent it, which provider and model answered, what it cost and what went wrong. **Dashboard** 1. Open **Observability**. 2. On the **Requests** tab, paste the request ID, or the whole error message that holds it, into **Search requests**. 3. Press Enter, or choose **Open request**. The request opens in a drawer, with its provider, model, status, key, finish reason, tokens and **Estimated cost**. ![A request open in Observability, showing its provider, model, status, cost and tokens](/images/dashboard/trace.png) You need: an account that can see the key's requests. An organisation Owner, Admin or Viewer sees every request, a Workspace admin or Workspace viewer those of their workspace, and a Developer those of their own keys. Give someone who only investigates requests a Viewer or Workspace viewer role, which reads without changing anything. **HTTP API** ```bash curl -sS "$TOKEDEX_URL/observability/v1/calls?requestId=" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" ``` ```json { "data": [{ "id": "0c570d31-d4fa-463b-ab14-626096b51c5e", "trajectoryId": "0c570d31-d4fa-463b-ab14-626096b51c5e", "provider": "anthropic", "model": "anthropic/claude-haiku-5.5", "status": "ok", "durationMs": 9, "costUsd": 0.0000024, "error": null, "keyId": "01M7V8SE8TMJ773PVSMM5ZANGJ", "workspaceId": "ws_default" }] } ``` You need: an admin key with the `admin` or `operator` preset in `TOKEDEX_ADMIN_KEY`, and `export TOKEDEX_URL='http://127.0.0.1:4000'`. A key with only `usage.read`, such as the `viewer` preset, also reads requests; give a script that only reads requests that preset, the smallest that works. The request ID is in every response's `x-request-id` header, and the OpenAI and Anthropic SDKs show it on an error as `request_id`. [Errors, limits and request IDs](/gateway/errors-and-limits#make-a-request-easy-to-find) shows callers how to send it to you. Ask the caller for the request ID first: one search finds the request by it, and search never matches prompt text. ## Request details **Dashboard** | Tab | Shows | | --- | --- | | **Summary** | The number of requests, cost, response time, tool calls and tokens, with a breakdown by model | | **Requests** | Each request's provider, model, status, key, finish reason, tokens and error | | **Timeline** | When each request started and how long it took | | **Raw** | The stored record as JSON | A request sent to a router shows the model that answered, with the router ID as its **Model alias**. A request's text shows only if the gateway captured it; otherwise it reads **Text not captured**. See [What the gateway records](/gateway/recording-and-retention). **HTTP API** For everything the gateway stored, request the whole trace by the `trajectoryId`: ```bash curl -sS "$TOKEDEX_URL/observability/v1/traces/" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" ``` It holds the totals, every request in `calls`, with its tokens, cost, finish reason and error, and the gateway's routing steps in `events`. `title` is the model ID the caller sent. A request's `request` and `response` text appear only if the gateway captured them; see [What the gateway records](/gateway/recording-and-retention). The failed attempts before a router's fallback are not listed; the request shows the model that answered. ## Failed requests **Dashboard** A request the gateway refused, or that failed at the provider with an authentication, rate-limit or server error, shows **What to do**: what the error means and a button to each page where you can fix it. Choose **Errors only** to list only failed requests. **HTTP API** A failed request has `status` `error` and an `error` object with its code and type. `GET /observability/v1/traces?status=error` lists failed requests. For what each error code means to a caller, see [Errors, limits and request IDs](/gateway/errors-and-limits). ## Follow a whole session A session groups the requests of one run, such as a coding agent's task. Claude Code, Codex, OpenCode and goose send a session ID themselves. So does any client that sends LiteLLM's `x-litellm-session-id`, Helicone's `helicone-session-id` or a plain `x-session-id` header, and any client can send the `x-tokedex-trajectory-id` header. Have your own agents and batch jobs send it, so a failed request is found with the run it belongs to. A session belongs to the key that sent it. **Dashboard** Open the **Sessions** tab and choose a session. The same tabs cover all its requests. In **Playground**, **View trace in Observability** opens the run as a session. **HTTP API** Search for the session ID the client sent, then request that trace: ```bash curl -sS "$TOKEDEX_URL/observability/v1/traces?search=nightly-eval-42" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" ``` ```json { "data": [{ "id": "ses_cdbaf2bcf3be0c38bb1e2ec4bb5c04d6", "title": "openai/gpt-6-luna", "callCount": 2 }] } ``` ## List recent requests **Dashboard** **Requests** lists every request you can see, newest first. Narrow it with the time range, the provider list and **Errors only**, or search by model, provider, project or tag. **Export** downloads what is listed; export requests you must keep longer than the gateway keeps traces, since it deletes the oldest. ![The Observability page listing requests with their model, key, tokens, duration and cost](/images/dashboard/observability.png) **HTTP API** `GET /observability/v1/traces` lists traces newest first. Filter with `since` and `until` (ISO times), `status`, `provider`, `model`, `tag`, `project`, `keyId`, `workspaceId` and `search`, and page with `limit` and the `cursor` from `page.next`. Search matches IDs, models, providers, projects, tags and session IDs, never prompt or response text. ## A request cannot be found **Dashboard** The page says **No request** with the ID, and lists the reasons: **HTTP API** An empty `data` list means the gateway has no record of it, for one of these reasons: - it is older than the gateway keeps; see [What the gateway records](/gateway/recording-and-retention#trace-retention); - it was sent with `x-tokedex-trace: false`, or while recording was off; - it was sent a moment ago and is still being written; - it was sent in another workspace, or with a key whose requests you cannot see; - another replica served it, and the replicas share no database. To find every request in one place, give several replicas a shared database, as [Deploy to production](/gateway/deploy) does. Next: [What the gateway records](/gateway/recording-and-retention), [Spend and usage](/gateway/spend-and-usage) or [Export traces with OpenTelemetry](/gateway/export-traces). --- # What the gateway records Check what the gateway records and how long it keeps it, then change that with a few settings. ```bash curl -sS "$TOKEDEX_URL/observability/v1/status" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" ``` ```json { "object": "observability_status", "apiVersion": "v1", "state": "ok", "enabled": true, "captureText": true, "traces": 4, "spans": 5, "oldestStartedAt": "2026-11-20T01:23:06.891Z", "newestStartedAt": "2026-11-20T01:28:45.067Z", "storageBytes": 102400, "retention": { "maxAgeSeconds": 2592000, "maxBytes": 536870912, "maxTraces": null, "lastPrunedAt": "2026-11-20T01:30:30.967Z" }, "ingest": { "queueDepth": 0, "queueCapacity": 4096, "droppedEvents": 0, "degraded": false, "lastErrorAt": null } } ``` You need: an admin key with the `admin`, `operator` or `viewer` preset in `TOKEDEX_ADMIN_KEY`, and `export TOKEDEX_URL='http://127.0.0.1:4000'`. Changing a setting below needs access to the gateway's environment. ## Data recorded for each request | Data | Recorded | | --- | --- | | Model, provider, key, workspace, timings, token counts, cost, error codes, tool names, tags and session | Always, unless recording is off | | Prompt, response, tool-argument, tool-result and provider error-message text | Only when the gateway allows text capture and the request asks for it | Recording is on by default, and each record is a trace in [**Observability**](/gateway/requests-and-sessions). Spend is recorded separately, so budgets and the [spend report](/gateway/spend-and-usage) stay complete whatever you set here. ## Turn text capture on Set `TOKEDEX_OBSERVABILITY_TEXT_CAPTURE=true` in the gateway's environment and restart it. Then the text of each request that sends this header is captured: ```text x-tokedex-trace-text: true ``` Capture applies to later requests. A trace without text reads **Text not captured**. Turn capture on only while you debug, and have only the client you are debugging send the header: captured text can be read by every organisation Owner and Admin, and by admin keys with the `admin` or `operator` preset, goes to your [export destinations](/gateway/export-traces#prompt-and-response-text) and stays in your backups. Callers set the header as [Errors, limits and request IDs](/gateway/errors-and-limits#make-a-request-easy-to-find) shows. ## Trace retention | Variable | Keeps | Default | | --- | --- | --- | | `TOKEDEX_OBSERVABILITY_MAX_AGE_SECONDS` | Traces up to this age | `2592000` (30 days) | | `TOKEDEX_OBSERVABILITY_MAX_BYTES` | The trace store up to this size | `536870912` (512 MiB) | | `TOKEDEX_OBSERVABILITY_MAX_TRACES` | Up to this many traces | No limit | Set the age to the longest you need to look back on requests, within what your privacy policy allows, and keep a size limit so traces cannot fill the disk or database that also holds spend. The gateway deletes the oldest traces at a limit, and lowering a limit deletes the traces beyond it, so export what you need first. Traces are kept in `~/.tokedex/observability.sqlite`, or `TOKEDEX_OBSERVABILITY_STORE_PATH`; with a shared Postgres database, in the database. With several replicas and no shared database, each replica records only the requests it served. On Kubernetes, set variables under `extraEnv` in the Helm chart's values; for a local gateway started with `npm start`, in the `.env` file in the repository root. Restart the gateway after a change. ## Turn recording off or on Prefer keeping recording on with text capture off: the metadata alone finds a failed request, and a request that must leave no record can send `x-tokedex-trace: false`. Set `TOKEDEX_OBSERVABILITY` to `0`, `false`, `no` or `off` and restart: nothing is recorded or [exported](/gateway/export-traces) from then on. `1`, `true`, `yes` or `on` turns it back on. Any other value turns recording off, with a warning at startup. While it is off, an organisation Owner or Admin can also choose **Enable observability** on **Observability**, or send `PUT /control/observability` with `{"enabled": true}`, then restart. A set `TOKEDEX_OBSERVABILITY` wins. ## Keep content private - **Leave a request out.** A request that sends `x-tokedex-trace: false` is not recorded or exported at all, metadata included. It takes effect once a request has authenticated; a request refused before that is recorded as the gateway's setting says. No header turns recording on when the gateway has it off. - **Restrict who reads traces.** Tool names, tags and key names can identify a workflow without any text. Organisation Owners, Admins and Viewers read every trace. - **Restrict who reads logs.** Logs are separate from traces. A failed request's log line keeps up to 2 KiB of the provider's error body, which can repeat prompt text whatever you set here. - **Plan for the store.** Include it in your [backups](/gateway/backup-restore) and privacy reviews. The gateway masks the key that authenticated the request in the traces it records and exports. Keep other credentials out of captured text. If an earlier trace contains a key, revoke it and follow your retention policy for the trace and any copies at export destinations. ## Check that recording works A request succeeds whether or not its trace is stored, so check the status above, and have your monitoring alert when it is not `ok`. Its `state` is: - `ok`: the gateway is recording. - `degraded`: the gateway is dropping trace events, so some traces are incomplete. - `disabled`: recording is off. With `configEnabled: true`, the store is not running: restart the gateway, then check its startup log, store path or database, permissions and disk space. Two endpoints that need no key report the gateway itself: ```bash curl -sS "$TOKEDEX_URL/readyz" ``` ```json {"ok":true,"release":{"environment":"local"},"service":"tokedex"} ``` `/healthz` says the process is running. `/readyz` also tests Postgres and Redis, when used, within one second; when one fails, it answers `503` with its name in `unavailable`. A gateway that cannot write spend refuses keys under a budget, so watch your database and disk. ## Audit log The **Audit log** records who changed the gateway's configuration and access, such as keys, provider credentials, models, prices and workspaces, and each attempt to authenticate to manage it. It records no model requests. Organisation Owners, Admins and Viewers see it in the sidebar. The audit log keeps 30 days of changes. With a shared Postgres database, set `TOKEDEX_CONTROL_JOURNAL_MAX_AGE_SECONDS` to change the age limit and `TOKEDEX_CONTROL_JOURNAL_MAX_EVENTS` to cap the number of events. The gateway checks both limits at startup and every minute, even when nobody makes changes. An age limit under a minute shortens the sweep interval to that limit, down to one second. Include the audit log in your backups and export anything you need before lowering a limit. Without Postgres, the audit log also stops at 256 MiB. Next: [Find and inspect a request](/gateway/requests-and-sessions), [Export traces with OpenTelemetry](/gateway/export-traces) or [Backup and restore](/gateway/backup-restore). --- # Export traces with OpenTelemetry Send a span for every request the gateway serves to any OTLP/HTTP collector, alongside the traces in **Observability**. Set the collector's address in the gateway's environment and restart the gateway: ```bash TOKEDEX_OTEL_EXPORTER_OTLP_ENDPOINT='https://collector.example.com' TOKEDEX_OTEL_EXPORTER_OTLP_HEADERS='Authorization=Bearer ' ``` After the next request, the collector receives a span on `/v1/traces`, trimmed here: ```json { "resource": { "attributes": [{ "key": "service.name", "value": { "stringValue": "tokedex-gateway" } }] }, "spans": [{ "name": "llm openai/gpt-6-luna", "status": { "code": 1 }, "attributes": [ { "key": "gen_ai.request.model", "value": { "stringValue": "openai/gpt-6-luna" } }, { "key": "gen_ai.usage.input_tokens", "value": { "intValue": "14" } }, { "key": "tokedex.request.id", "value": { "stringValue": "d3c36880-a8a6-431e-80bd-f0ea4639d403" } }, { "key": "tokedex.cost.usd", "value": { "doubleValue": 1.92e-06 } } ] }] } ``` You need: access to the gateway's environment and permission to restart it, and a collector or service that accepts OTLP/HTTP traces. On Kubernetes, set the variables under `extraEnv` in the Helm chart's values, with collector tokens and service keys read from a Secret, as [Deploy to production](/gateway/deploy#supply-provider-credentials) shows for provider keys; for a local gateway started with `npm start`, in the `.env` file in the repository root. ## Collector settings | Variable | Value | | --- | --- | | `TOKEDEX_OTEL_EXPORTER_OTLP_ENDPOINT` | The collector's address. The gateway adds `/v1/traces` unless the address already ends with it. | | `TOKEDEX_OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` | Used in place of the address above. The gateway also adds `/v1/traces` to it unless it already ends with it, so a collector at another path cannot be reached. | | `TOKEDEX_OTEL_EXPORTER_OTLP_HEADERS` | Headers sent with each export, as comma-separated `name=value` pairs | | `TOKEDEX_OTEL_SERVICE_NAME` | The `service.name` on each span. Default `tokedex-gateway`. | The standard `OTEL_EXPORTER_OTLP_ENDPOINT`, `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` and `OTEL_EXPORTER_OTLP_HEADERS` work too. The gateway uses the first one set of `TOKEDEX_OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`, `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`, `TOKEDEX_OTEL_EXPORTER_OTLP_ENDPOINT` and `OTEL_EXPORTER_OTLP_ENDPOINT`. For headers, the `TOKEDEX_` name wins. ## Send traces to a named service List the services in `TOKEDEX_OTEL_DRAINS`, separated by commas, and set each one's variables. The gateway skips a listed service whose required variables are missing. ```bash TOKEDEX_OTEL_DRAINS='braintrust' BRAINTRUST_API_KEY='' ``` | Service | `TOKEDEX_OTEL_DRAINS` | Required | Optional | | --- | --- | --- | --- | | Braintrust | `braintrust` | `BRAINTRUST_API_KEY` | `BRAINTRUST_PROJECT_NAME` (default `tokedex`) | | Arize | `arize` | `ARIZE_API_KEY`, `ARIZE_SPACE_ID` | `ARIZE_PROJECT_NAME` (default `tokedex`) | | SigNoz Cloud | `signoz` | `SIGNOZ_INGESTION_KEY` | `TOKEDEX_SIGNOZ_REGION`: `us`, `eu` or `in` | | Self-hosted SigNoz | `signoz` | `TOKEDEX_SIGNOZ_OTLP_ENDPOINT`, a full `/v1/traces` URL | | | LangSmith | `langsmith` | `LANGSMITH_API_KEY` | `LANGSMITH_PROJECT` | | Langfuse | `langfuse` | `LANGFUSE_PUBLIC_KEY`, `LANGFUSE_SECRET_KEY` | `LANGFUSE_BASE_URL` | | Weights & Biases Weave | `weave` | `WANDB_API_KEY`, `WANDB_ENTITY`, `WANDB_PROJECT` | `WEAVE_BASE_URL` | | Galileo | `galileo` | `GALILEO_API_KEY`, `GALILEO_PROJECT` | `GALILEO_LOG_STREAM` (default `default`) | | Datadog | `datadog` | `DD_API_KEY` | `DD_SITE` | | Honeycomb | `honeycomb` | `HONEYCOMB_API_KEY` | `HONEYCOMB_DATASET`, `HONEYCOMB_REGION=eu` | | New Relic | `new-relic` | `NEW_RELIC_LICENSE_KEY` | `NEW_RELIC_REGION`: `eu` or `fedramp` | Use a named service when yours is listed: you set only its key, and the gateway builds its address and headers. Use the collector settings for any other destination, or for an OpenTelemetry Collector of your own that forwards spans onward. A named service and a collector can be used together: the gateway sends each span to every destination. ## Span contents Each span is named `llm /`, for the provider and model that answered. It carries OpenTelemetry GenAI attributes, such as `gen_ai.request.model` (the model ID the caller sent) and `gen_ai.usage.input_tokens`, and `tokedex.*` attributes for the request ID, session, key identifier, workspace, tags, tokens, duration, finish reason and cost. Its events record the gateway's routing steps. A request that falls back sends one span for each attempt, with the same `tokedex.request.id`. A failed attempt has status code `2` and its `error.type`, such as `RateLimit`. ## Prompt and response text Text is exported only for a request whose text the gateway captures: `TOKEDEX_OBSERVABILITY_TEXT_CAPTURE=true` in the gateway's environment, and `x-tokedex-trace-text: true` on the request. The request and response then appear in the span's `gen_ai.input.messages` and `gen_ai.output.messages` attributes, and a failed request's span carries the provider's error message. The gateway masks the key that authenticated the request before exporting the trace. See [Keep content private](/gateway/recording-and-retention#keep-content-private). Each of the two attributes is a JSON string in the OpenTelemetry GenAI message format: a list of messages, each with a `role` and typed `parts`, such as `text`, `reasoning`, `tool_call` and `tool_call_response`. A system prompt is the first input message, with the role `system`. The same text is also in the span's events, under `tokedex.event.data_json`. SigNoz never receives text. Before you turn text capture on, check that every other destination may hold prompt and response text, since each one receives it. ## Data that is not exported Export follows recording. When recording is off (`TOKEDEX_OBSERVABILITY=0`), or a request sends `x-tokedex-trace: false`, nothing is exported for it. ## Check that export works 1. Restart the gateway with the variables set. 2. Send a request through the gateway. It calls a provider and can incur charges. 3. Find a span named `llm /` in your collector or service. If none arrives, read the gateway's log. A failed export logs `OTLP drain "" export failed — span dropped`, with the HTTP status or error. The gateway waits at most 10 seconds for each export and keeps at most 64 in flight to each destination, so a slow collector loses spans, never delays requests. Keep recording on as the complete record, and use the export for analysis that can tolerate a lost span. ## Receive traces at the gateway Set `TOKEDEX_OBSERVABILITY_INGEST_TOKEN` and restart, and the gateway stores the OTLP/HTTP JSON spans that the SDK or another exporter sends to `POST /observability/v1/traces`, so calls made without the gateway appear in **Observability**. ```bash curl -sS "$TOKEDEX_URL/observability/v1/traces" \ -H "Authorization: Bearer $TOKEDEX_INGEST_TOKEN" \ -H "Content-Type: application/json" \ --data-binary @spans.json ``` ```json {"object":"observability_ingest","spans":1,"accepted":1} ``` The token can only write spans: it reads nothing, and no other key is accepted on this route. Generate a long random value, give it only to the exporters that send spans, and keep it out of logs. The token is 1 to 512 visible ASCII characters, without commas, and the route exists only while recording is on. Next: [What the gateway records](/gateway/recording-and-retention) or [Find and inspect a request](/gateway/requests-and-sessions). --- # Deploy to production Run the gateway where your team can rely on it, and check that it is ready before anyone uses it. From the root of a clone of the repository, with the Secrets and the values file from the sections below: ```bash helm upgrade --install tokedex ./helm/tokedex \ --namespace tokedex \ -f release-values.yaml \ --wait --timeout 10m helm test tokedex --namespace tokedex curl -sS https://gateway.example.com/readyz ``` ```json {"ok":true,"release":{"environment":"local"},"service":"tokedex"} ``` `helm test` passes when the gateway reports ready inside the cluster. You need: Kubernetes 1.32 or later, `kubectl`, Helm 3.17 or later or Helm 4, a managed Postgres database and a role that owns it, a managed Redis endpoint, a StorageClass that provides `ReadWriteMany`, and an ingress controller with a TLS certificate for the gateway's hostname. To try the gateway on your own computer first, follow the [Gateway quickstart](/gateway/quickstart). ## Create the gateway's keys The release reads four keys from a Secret you create. Generate them once and keep them for the life of the installation. ```bash kubectl create namespace tokedex { printf 'TOKEDEX_MASTER_KEY=%s\n' "$(openssl rand -hex 32)" printf 'TOKEDEX_FINGERPRINT_KEY=%s\n' "$(openssl rand -hex 32)" printf 'TOKEDEX_VERIFIER_ROOT=%s\n' "$(openssl rand -hex 32)" printf 'TOKEDEX_PASSWORD_PEPPER=%s\n' "$(openssl rand -hex 32)" } | kubectl -n tokedex create secret generic tokedex-keys --from-env-file=/dev/stdin ``` Copy the values into your secret manager: a restore needs them. Name the Secret in `release-values.yaml`, which each section below adds to; keep it outside the chart directory. ```yaml secrets: existingSecret: tokedex-keys ``` The master key signs in to the dashboard. The other three must be the same on [every replica](#run-several-replicas). ## Pin the image Pin the release you run. The `tokedex/gateway` image runs on AMD64 and ARM64; `0.1.1` is the current release. ```yaml image: repository: tokedex/gateway tag: "0.1.1" ``` `image.digest` pins an immutable build and takes precedence over `image.tag`; set it in production, so every Pod, restore and rehearsal runs the build you tested. For a private registry, set `image.repository` to your mirror and list its pull Secrets in `imagePullSecrets`. To move to another release, see [Upgrades and migrations](/gateway/upgrades). ## Supply provider credentials Save them in the dashboard after you sign in, as [Provider credentials](/gateway/provider-credentials) shows, or pass them in the gateway's environment under the provider's own variable, such as `OPENAI_API_KEY`. Keep environment credentials in their own Secret, and pass each one as an entry of the `extraEnv` list in `release-values.yaml`: ```bash printf 'OPENAI_API_KEY=%s\n' "$OPENAI_API_KEY" \ | kubectl -n tokedex create secret generic tokedex-providers --from-env-file=/dev/stdin ``` ```yaml extraEnv: - name: OPENAI_API_KEY valueFrom: secretKeyRef: name: tokedex-providers key: OPENAI_API_KEY ``` ## Connect Postgres and Redis The gateway keeps its state in managed Postgres and Redis, which several replicas share. Put each connection string in a Secret under the key `url`, with the password percent-encoded and your provider's TLS parameters; use `rediss://` for Redis over TLS. ```bash kubectl -n tokedex create secret generic tokedex-postgres \ --from-literal=url='postgresql://tokedex:@:5432/tokedex' kubectl -n tokedex create secret generic tokedex-redis \ --from-literal=url='rediss://:@:6379' ``` Several replicas also need a `ReadWriteMany` volume claim, which holds spend not yet written to Postgres and the key that encrypts stored provider credentials. ```yaml postgresql: mode: external external: secretName: tokedex-postgres redis: mode: external external: secretName: tokedex-redis replicaCount: 3 persistence: accessMode: ReadWriteMany storageClass: podDisruptionBudget: enabled: true minAvailable: 1 ``` The gateway creates its database schema at first start. Choose the stores before the first install: a bound claim's access mode and StorageClass are fixed, and a later change of store copies no data. Helm uninstall keeps the gateway's volume claim. The chart can also run Postgres and Redis inside the cluster (`mode: bundled`). For failover, TLS to the stores and managed backups, use managed services; keep bundled stores for a trial or staging cluster. Every value is in the [Helm chart guide](https://github.com/ArtificialAnalysis/tokedex/blob/main/helm/tokedex/README.md). ## Redis requirements The Redis endpoint needs: - `maxmemory-policy noeviction`, since every key the gateway writes is live state: an evicted cooldown sends traffic back to a provider key that was cooling. - Persistence on, so a Redis restart keeps stored conversations. - A standalone endpoint that runs scripts and answers before the gateway starts. ## Run several replicas Every replica must share: - Postgres, Redis and the `ReadWriteMany` claim. - The verifier root, which checks every key and session; the fingerprint key, which identifies callers in the audit log; and the password pepper. All three are in `tokedex-keys`. - The key that encrypts stored provider credentials, on the claim. To keep it in AWS KMS instead, set `custody.mode: kms` and `custody.kmsKeyId`, and pass `TOKEDEX_KEK_KMS_REGION` and AWS credentials with `extraEnv`. Revoking KMS access blocks future unwraps. A running replica can still use provider credentials it has already decrypted. To stop that use, revoke the provider credential at the provider or stop every replica that loaded it. To scale on CPU in place of `replicaCount`, which needs the Kubernetes resource metrics API: ```yaml autoscaling: enabled: true minReplicas: 3 maxReplicas: 10 ``` A rollout replaces Pods one at a time. Keep `podDisruptionBudget.minAvailable` below the smallest replica count, and spread replicas across nodes with `topologySpreadConstraints`, as the [Helm chart guide](https://github.com/ArtificialAnalysis/tokedex/blob/main/helm/tokedex/README.md) shows, so a rollout or a lost node leaves one serving. Without the `ReadWriteMany` claim and Postgres, the chart runs one replica and stops the old Pod before it starts the new one, so a rollout briefly stops serving. Once the first install has created the schema, set `postgresql.migrationMode: check`, so an upgrade never migrates the database under a replica of the earlier release; see [Upgrades and migrations](/gateway/upgrades#database-migrations). ## Serve the gateway over HTTPS Set the public URL and the ingress to the same hostname. The chart refuses a `publicUrl` other than `https://` followed by `ingress.host`. ```yaml publicUrl: https://gateway.example.com ingress: enabled: true className: host: gateway.example.com tlsSecretName: gateway-tls ``` [HTTPS and reverse proxies](/gateway/https) creates the TLS Secret, sets your controller's limits and timeouts, and names the proxies the gateway trusts. ## Check the release 1. Check that every gateway Pod is `Running` and ready, and that the log names both stores: ```bash kubectl -n tokedex get pods \ -l app.kubernetes.io/instance=tokedex,app.kubernetes.io/component=gateway kubectl -n tokedex logs deployment/tokedex | grep 'State backends' ``` ```text State backends (postgres+redis): ``` 2. Open `https://gateway.example.com` and sign in with the master key, read from the Secret: ```bash kubectl -n tokedex get secret tokedex-keys \ -o jsonpath='{.data.TOKEDEX_MASTER_KEY}' | base64 -d ``` Before the ingress is ready, run `kubectl -n tokedex port-forward svc/tokedex 4000:4000` and check `http://127.0.0.1:4000/readyz`. The dashboard answers only at the public URL, or at `127.0.0.1` while `publicUrl` is unset. `/readyz` needs no key. It answers `503` and names the store in `unavailable` while Postgres or Redis does not answer. ## Hardening in the Helm chart - The gateway runs as user and group 1000, never root, with a read-only root filesystem. - Every Linux capability is dropped, privilege escalation is off, and the seccomp profile is `RuntimeDefault`. - No service account token or service links are mounted. - While `networkPolicy.bundledBackends` is `true`, the default, NetworkPolicies admit only the gateway and its migration Job to a bundled Postgres or Redis. Your cluster's network plugin must enforce them. A claim you bring with `persistence.existingClaim` must be writable by user 1000. The chart sets `fsGroup: 1000`, which grants that on storage that honours it; the gateway need not own the claim's root. ## Outbound hosts The gateway calls your Postgres and Redis endpoints, your providers' API hosts, your identity provider, your SMTP server, and, for Slack alerts, `slack.com` and Slack's webhook hosts. Requests to Slack go out directly, never through a proxy set in the gateway's environment. ## Recommendations - **Keep the key-encryption key in AWS KMS, or back it up apart from the database.** One stolen backup then cannot open the stored provider credentials. - **Restrict the dashboard to your network.** Clients need only `/v1`, and the dashboard is an administrative console. - **Test a restore before anyone relies on the gateway.** A [backup](/gateway/backup-restore) you have not restored may lack a part, such as a Secret. Next: [HTTPS and reverse proxies](/gateway/https), [Single sign-on](/gateway/single-sign-on) or [Backup and restore](/gateway/backup-restore). --- # HTTPS and reverse proxies Serve the gateway and its dashboard at an `https://` address, with sign-in and streamed responses working through your proxy. Store the certificate in a TLS Secret, add the public URL and the ingress to your values file, then apply it: ```bash kubectl -n tokedex create secret tls gateway-tls \ --cert=gateway.crt --key=gateway.key ``` ```yaml publicUrl: https://gateway.example.com ingress: enabled: true className: host: gateway.example.com tlsSecretName: gateway-tls annotations: {} ``` ```bash helm upgrade --install tokedex ./helm/tokedex \ --namespace tokedex \ -f release-values.yaml \ --wait --timeout 10m curl -sS https://gateway.example.com/readyz ``` ```json {"ok":true,"release":{"environment":"local"},"service":"tokedex"} ``` You need: the release and `release-values.yaml` from [Deploy to production](/gateway/deploy), an ingress controller in the cluster, and a certificate and key for the hostname. A certificate manager that writes the same Secret works too, and is the better choice because it renews the certificate before it expires. ## Public URL The public URL is the origin browsers use, including the scheme, host and any port, such as `https://gateway.example.com`. Serve the dashboard and sign-in at the root of that hostname. The gateway accepts the configured `Host`. It also accepts `localhost`, `127.0.0.1` and `[::1]` on any port when you leave the public URL unset or when either the public URL or the gateway's listen address is loopback. Other hosts get `421`. A public URL with a path stops the gateway at start-up and prints this error. ```text TOKEDEX_PUBLIC_URL must be the http(s) origin browsers use to reach this gateway, such as https://gateway.example.com: it has a path, query or fragment ``` Invitation links, single sign-on redirect URIs and Slack's Redirect URL are built on it. Settle the final hostname before you set up single sign-on or Slack alerts, so neither needs redoing. If you change it, update the redirect URI at your identity provider and add the new Redirect URL that **Alerts → Delivery** shows to your [Slack app](/gateway/budget-alerts#post-alerts-to-slack). ## Proxy settings Any reverse proxy in front of the gateway needs these settings. Set them in `ingress.annotations`, in your controller's own annotation names. | Setting | Value | | --- | --- | | Request body size limit | At least 12,000,000 bytes, the gateway's own limit | | Response buffering | Off, so streamed responses arrive as the model writes them | | Read and send timeouts | 300 seconds or more, for requests that stay silent that long | | `Host` header | Passed to the gateway unchanged, so the gateway can compare it with the public URL | | `X-Forwarded-For` header | The client's address, written by the proxy. The first proxy replaces any value the client sent. | The gateway reads the public host from `Host` only. `X-Forwarded-Host` and `X-Forwarded-Proto` have no effect. In an NGINX that runs outside the cluster, a server block sets them like this. Point `proxy_pass` at the address where NGINX reaches the gateway's Service; the example uses `127.0.0.1:4000`. ```nginx server { listen 443 ssl; server_name gateway.example.com; ssl_certificate /etc/nginx/tls/gateway.crt; ssl_certificate_key /etc/nginx/tls/gateway.key; client_max_body_size 12000000; location / { proxy_pass http://127.0.0.1:4000; proxy_http_version 1.1; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header Connection ""; proxy_buffering off; proxy_cache off; proxy_read_timeout 300s; proxy_send_timeout 300s; } } ``` NGINX's default body limit of 1 MiB refuses a larger request with `413`. If you list gateway replicas directly in an NGINX `upstream` block, set a short upstream connection timeout such as `proxy_connect_timeout 1s`. NGINX can then try a healthy replica sooner if it cannot connect to the first one. Keep the read and send timeouts for established connections as shown above. Leave the `Origin`, `Cookie` and `Authorization` headers unchanged. If you raise the gateway's body limit with `TOKEDEX_MAX_REQUEST_BYTES`, raise the proxy's to match. Keep the query string of `/alerts/slack/` out of your access logs: Slack returns there with a single-use code. Restrict who can reach the dashboard, `/control` and `/observability` with your network, a VPN or an authenticating proxy, since they administer the gateway. Clients need only `/v1`, Gemini GenerateContent included, and `/api/hello`, which Claude Code checks. ## Trusted proxies The gateway limits sign-in attempts for each client address. It reads that address from `X-Forwarded-For` only on a connection from a proxy listed in `TOKEDEX_TRUSTED_PROXIES`, as IP addresses or CIDR ranges separated by commas or spaces. List the addresses your ingress controller's Pods connect from, or the address an outside proxy's connections arrive from, as an entry of the `extraEnv` list in `release-values.yaml`, and apply the values again: ```yaml extraEnv: - name: TOKEDEX_TRUSTED_PROXIES value: "" ``` List only proxies you operate, since a listed proxy can report any address. Behind a chain of proxies, list each one and have each append to `X-Forwarded-For`; the gateway takes the right-most address that is not a trusted proxy. While the setting is unset, the gateway turns this limit off for connections from private and loopback addresses, and logs a warning at the first sign-in. > **Important:** Set `TOKEDEX_TRUSTED_PROXIES` behind an ingress. Its Pods connect from private addresses, so while the setting is unset, nothing limits sign-in attempts from any client. ## Check sign-in and streaming 1. Open `https://gateway.example.com` and sign in. 2. Create an [API key](/gateway/api-keys). It saves without an error, so cookies and headers pass through. 3. Open **Account → Sessions**. **From** shows the client's network, not the proxy's. 4. Send a streamed request from **Playground** in the dashboard. The reply appears as the model writes it. The request calls your provider and can incur charges. Sign-in with a password or single sign-on needs `https`. Over plain HTTP from another machine it reports **Passwords are only accepted over https**. `TOKEDEX_ALLOW_HTTP_SIGN_IN=1` allows it anyway and sends passwords unencrypted, so fix HTTPS instead of setting it on a gateway that other machines reach. Next: [Single sign-on](/gateway/single-sign-on), [Deploy to production](/gateway/deploy) or [Troubleshooting](/gateway/troubleshooting). --- # Single sign-on Let people sign in to the dashboard through your OpenID Connect (OIDC) identity provider, with roles from their groups. Describe the identity provider in a file, such as `oidc.yaml`: ```yaml providers: - id: company displayName: Company SSO issuer: https://login.example.com/oauth2/default clientId: clientSecretEnv: TOKEDEX_OIDC_COMPANY_SECRET allowedEmailDomains: [example.com] jit: true roleMapping: orgRoles: admin: [tokedex-admins] member: [engineering] ``` Keep the file and the client secret in one Secret. Save the client secret in a file named `client-secret`, with no trailing newline: ```bash kubectl -n tokedex create secret generic tokedex-oidc \ --from-file=oidc.yaml \ --from-file=client-secret ``` Merge these into `release-values.yaml`, adding the entries to any `extraEnv`, `extraVolumes` or `extraVolumeMounts` list it already has, and run the `helm upgrade` from [Deploy to production](/gateway/deploy). Every replica restarts with the file mounted. The gateway reads the file only at start-up, and refuses to start on an unknown field or an unset secret. After every change to the file or the secret, run `kubectl -n tokedex rollout restart deployment/tokedex`. ```yaml extraEnv: - name: TOKEDEX_OIDC_PROVIDERS_FILE value: /etc/tokedex/oidc/oidc.yaml - name: TOKEDEX_OIDC_COMPANY_SECRET valueFrom: secretKeyRef: name: tokedex-oidc key: client-secret extraVolumes: - name: oidc secret: secretName: tokedex-oidc items: - key: oidc.yaml path: oidc.yaml extraVolumeMounts: - name: oidc mountPath: /etc/tokedex/oidc readOnly: true ``` Open **Members → Sign-in** and choose **Check**. **Identity providers** lists **Company SSO**, and the row reads **ok** once the gateway reaches the identity provider. You need: a gateway served over [HTTPS](/gateway/https) with its public URL set, an application at your identity provider, and an organisation Owner account with emergency sign-in, for when the identity provider is down. Single sign-on stays off until the public URL is set; the gateway logs a warning at start-up. ## Register an OIDC application Register an OIDC application at your identity provider with the redirect URI `https://gateway.example.com/auth/v1/oidc/company/callback`. Use the `id` from your provider file in place of `company`, with up to 32 lowercase letters, digits and hyphens. Copy the issuer URL and client ID into the file. Supply the client secret through the Kubernetes Secret above and set `clientSecretEnv` to the name of the environment variable that holds it. Use the issuer exactly as the provider's tokens carry it. For Microsoft Entra ID, use your tenant's issuer: the gateway refuses the multi-tenant ones. ## Provider file settings - `allowedEmailDomains` admits only those addresses. List your own domains, so only your organisation's addresses get accounts. - `jit: true` creates an account at a person's first sign-in. Without it, people need an invitation or a linked account. - `roleMapping.orgRoles` gives each organisation role to the groups listed, and a person gets the highest one: here `engineering` signs in as a Member and `tokedex-admins` as an Admin. - `clientSecretEnv` names the variable that holds the client secret, which must start with `TOKEDEX_OIDC_`. Mapping groups to Owner needs `allowSuperRole: true` in `roleMapping`. Leave it off and make Owners by hand, so a change to a group at the identity provider cannot hand out full control. Google's ID tokens carry no groups. With Google, invite people instead of mapping groups. Every field and sign-in rule is in the [single sign-on reference](https://github.com/ArtificialAnalysis/tokedex/blob/main/docs/user-management/README.md#5-single-sign-on). ## Test sign-in 1. Sign in as an organisation Owner or Admin and open **Members → Sign-in**. 2. Choose **Test sign-in** and sign in as someone who should get access. The result shows the claims the gateway read and the roles it would assign. Nothing is created. 3. Repeat as someone who must be refused. 4. Ask a real user to choose **Continue with Company SSO** on the sign-in page, then check their roles in **Members**. From a deployment script, check it with the master key or an admin key with the `auditor` preset. The gateway contacts the identity provider; nobody signs in. ```bash curl -sS -X POST "$TOKEDEX_URL/control/v1/sso-providers/company/check" \ -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" ``` ```json { "object": "sso_provider", "id": "company", "displayName": "Company SSO", "redirectUri": "https://gateway.example.com/auth/v1/oidc/company/callback", "enabled": true, "discovery": { "state": "ok", "checkedAt": 1795137738974 } } ``` `discovery.state` is `failing`, with a `reason`, when the gateway cannot reach the provider. ## Map groups to workspace roles Select the workspace and open **Settings**. Under **Identity-provider groups**, enter a group, choose its role, then choose **Add group**. Choose **Save groups** to open **Review group changes**. Review the changes and choose **Save groups** in the dialog to apply them. The gateway applies group changes at a person's next sign-in, and never removes the last Owner. To end someone's access at once, open them in **Members** and choose **Disable**; do this as well as removing them at the identity provider, since an open session outlasts a group change. ## Link an existing account If you already have an account, sign in with your password before using SSO for the first time. Open **Account → Profile & sign-in** and choose **Connect Company SSO**. Linking removes your password unless your account has emergency sign-in. With `jit: true`, signing in through SSO before linking can create a separate account if the address on your existing account is unverified, as with a password invitation. If the identity provider verifies an email address that an existing account already holds as verified, the gateway refuses the new sign-in with `sso_account_exists` until you link the identity. ## Require single sign-on Require it only once **Test sign-in** admits and refuses the right people, and at least one Owner, better two, has emergency sign-in and has signed in with its password. Otherwise only the master key signs in while the identity provider is down, and the gateway warns you of that. 1. Sign in as an organisation Owner and open **Members → Sign-in**. 2. Under **Sign-in settings**, select **Require single sign-on** and choose **Save**. From then on, a password signs in only an account with emergency sign-in, and the master key still signs in. Open sessions continue: **Sign everyone out** ends them and revokes every personal access token. Choose it when sessions opened with a password must end now, and warn people first, since their tokens stop too. Next: [People and workspaces](/gateway/people-and-workspaces), [Recover dashboard access](/gateway/recover-access) or [HTTPS and reverse proxies](/gateway/https). --- # Backup and restore Take one backup that brings back the whole gateway: its people, keys, settings, spend and the provider credentials it holds. **Docker** Use the local-storage commands for the Docker image quickstart or `compose.yaml`. Use the Postgres and Redis commands for `compose.self-host.yaml`. Block new client traffic, wait for requests to finish, and keep the backup on private, encrypted storage. ### Back up local storage ```bash umask 077 container=tokedex-gateway volume=$(docker inspect --format '{{range .Mounts}}{{if and (eq .Type "volume") (eq .Destination "/home/node/.tokedex")}}{{.Name}}{{end}}{{end}}' "$container") test -n "$volume" && mkdir tokedex-backup && docker inspect --format '{{.Image}}' "$container" > tokedex-backup/image-id && docker stop "$container" && docker run --rm --network none -v "$volume:/source:ro" alpine:3.20 \ tar -czf - -C /source . > tokedex-backup/state.tgz && docker start "$container" ``` Use this for a gateway with local storage started by the [Docker image quickstart](https://hub.docker.com/r/tokedex/gateway) or [Docker Compose quickstart](/gateway/quickstart). With Compose, run `docker compose ps --all -q gateway` from the project directory and use that container ID for `container`. The command discovers the actual volume name, including any Compose project prefix. The gateway restarts when the archive succeeds. If the backup fails after the container stops, run `docker start "$container"` to bring it back, then retry with a fresh backup directory. ### Back up Postgres and Redis Run from the Compose project directory with your usual environment. These commands stop every gateway replica, dump Postgres, and stop Redis before archiving its append-only files and the gateway volumes. ```bash ( set -eu umask 077 shared() { docker compose -f compose.self-host.yaml "$@"; } gateway=$(shared ps -q gateway | head -n 1) test -n "$gateway" project=$(docker inspect -f '{{index .Config.Labels "com.docker.compose.project"}}' "$gateway") mkdir tokedex-shared-backup docker inspect -f '{{.Image}}' "$gateway" > tokedex-shared-backup/image-id shared stop gateway shared exec -T postgres sh -ec 'pg_dump -Fc -U "$POSTGRES_USER" -d "$POSTGRES_DB"' \ > tokedex-shared-backup/postgres.dump shared exec -T redis redis-cli SAVE shared stop redis for name in state-data kek-data auth-data spend-unwritten redis-data; do volume="${project}_${name}" docker volume inspect "$volume" > /dev/null docker run --rm --network none -v "$volume:/source:ro" alpine:3.20 \ tar -czf - -C /source . > "tokedex-shared-backup/$name.tgz" done shared start --wait redis gateway ) ``` Use the same Compose project options you normally pass to `docker compose`. If a step fails while the services are stopped, restart them with `docker compose -f compose.self-host.yaml start --wait redis gateway`, then retry with a fresh backup directory. **Kubernetes** ```bash umask 077 helm upgrade tokedex ./helm/tokedex -n tokedex -f release-values.yaml \ --set replicaCount=0 --set autoscaling.enabled=false --wait --timeout 10m kubectl -n tokedex wait --for=delete pod --timeout=10m \ -l app.kubernetes.io/instance=tokedex,app.kubernetes.io/component=gateway # Take an on-demand snapshot of your managed Postgres now. # Take a Redis snapshot now if you need stored conversations to survive. kubectl -n tokedex apply -f volume-pod.yaml kubectl -n tokedex wait --for=condition=Ready pod/tokedex-volume --timeout=5m kubectl -n tokedex exec tokedex-volume -- tar -czf - -C /state . > tokedex-data.tgz kubectl -n tokedex delete pod tokedex-volume helm upgrade tokedex ./helm/tokedex -n tokedex -f release-values.yaml --wait --timeout 10m ``` `volume-pod.yaml` mounts the gateway's volume claim in a Pod that runs as root, so the archive keeps each file's owner and mode; a namespace that enforces the `restricted` Pod Security Standard refuses it. Set `image` to the image your release runs: ```yaml apiVersion: v1 kind: Pod metadata: name: tokedex-volume spec: restartPolicy: Never containers: - name: shell image: tokedex/gateway:0.1.1 command: ["sleep", "3600"] securityContext: runAsUser: 0 volumeMounts: - name: state mountPath: /state volumes: - name: state persistentVolumeClaim: claimName: tokedex-data ``` You need: `kubectl` and `helm` access to the release, here `tokedex` in the namespace `tokedex` with the values it runs in `release-values.yaml`, a maintenance window, and private, encrypted storage: the archive holds the key that decrypts stored provider credentials. Block client traffic first. ## Backup contents **Docker** With local storage, the volume holds accounts, API keys, gateway settings, the master key, stored provider credentials and their encryption key, spend, and traces. Conversations stored in local memory end when the gateway stops. With `compose.self-host.yaml`, take the Postgres dump and all five volume archives together. | State | Where it lives | | --- | --- | | Accounts, API keys, gateway settings, encrypted provider credentials, spend, traces and audit log | Postgres | | Master key and other gateway state files | `state-data` | | Key that decrypts stored provider credentials | `kek-data` | | Password pepper when supplied by a file | `auth-data` | | Spend waiting to be written to the ledger | `spend-unwritten` | | Stored OpenAI Responses conversations and provider key cooldowns | `redis-data` | For either backup, keep the original launch settings, including the Compose `.env` and any deployment overrides. Keep the original values of externally supplied credentials and keys in your secret store. **Kubernetes** Back up the database, volume claim and Secrets together. Include a Redis snapshot from the same maintenance window if you need to keep stored conversations. Turn on your managed Postgres's automated backups and point-in-time recovery. | State | Where it lives | | --- | --- | | People, workspaces, API keys, settings, budgets, spend, traces and the audit log | Postgres; on the claim for a release without Postgres | | Master key | `TOKEDEX_MASTER_KEY` in the gateway Secret, with a copy at `master-key` on the claim | | Verifier root and fingerprint key | The gateway Secret; on the claim for a release without Postgres | | Password pepper | `TOKEDEX_PASSWORD_PEPPER` in the gateway Secret; on the claim if the Secret has no such key | | Key that encrypts stored provider credentials | `kek/credential-kek.json` on the claim, or your KMS key with `custody.mode: kms` | | Spend not yet written to the database | `state/spend-unwritten` on the claim | | Stored OpenAI Responses conversations and provider key cooldowns | Redis | The claim is `tokedex-data` unless you set `persistence.existingClaim`. With every backup, record the chart revision, your values file, the image digest and every Secret the release names. ## Restore into a clean place **Docker** ### Restore local storage ```bash docker volume create tokedex-data-restore && docker run --rm -i --network none -v tokedex-data-restore:/state alpine:3.20 \ sh -c 'test -z "$(ls -A /state)" && tar -xzpf - -C /state' \ < tokedex-backup/state.tgz && docker run -d --name tokedex-gateway-restore \ -p 127.0.0.1:4001:4000 \ -v tokedex-data-restore:/home/node/.tokedex \ "$(cat tokedex-backup/image-id)" ``` Use a new volume so the restore can run beside the original gateway. If the recorded image is absent from this host, use the same image version from your original launch settings. Reapply externally supplied gateway settings and credentials from the same backup when you start it. ### Restore Postgres and Redis Use the same gateway image and Compose file that took the backup. Load your original Compose settings and credentials from the backup and your secret store. Use a new project name and a free loopback port so you can rehearse beside the original gateway. ```bash ( set -eu project=tokedex-restore backup=tokedex-shared-backup restore() { docker compose -p "$project" -f compose.self-host.yaml "$@"; } test -z "$(restore ps --all -q)" test -z "$(docker volume ls -q --filter "label=com.docker.compose.project=$project")" docker image tag "$(cat "$backup/image-id")" "$project-gateway" for name in state-data kek-data auth-data spend-unwritten redis-data; do volume="${project}_${name}" docker volume create --label "com.docker.compose.project=$project" \ --label "com.docker.compose.volume=$name" "$volume" > /dev/null docker run --rm -i --network none -v "$volume:/state" alpine:3.20 \ sh -ec 'test -z "$(ls -A /state)" && tar -xzpf - -C /state' < "$backup/$name.tgz" done restore up --wait postgres redis restore exec -T postgres sh -ec ' pg_restore --single-transaction --no-owner --no-acl -U "$POSTGRES_USER" -d "$POSTGRES_DB" ' < "$backup/postgres.dump" TOKEDEX_GATEWAY_PORTS=4001 TOKEDEX_PUBLIC_URL=http://127.0.0.1:4001 \ TOKEDEX_DATABASE_MIGRATE=check TOKEDEX_SPEND_ALERTS_DELIVERY_INTERVAL_MS=0 \ restore up --no-build --wait gateway ) ``` The new gateway listens on port `4001`, checks the restored schema, and keeps alert delivery off during the rehearsal. Use a fresh project if you need to start the restore again. **Kubernetes** Restore every part from the same backup, with the gateway version that took it, and keep clients away until the checks below pass. Restore beside the running release, never over it, so it stays your way back if the restore fails. [Upgrade](/gateway/upgrades) afterwards: an earlier version cannot always read state a later one wrote. 1. Restore Postgres into a new instance. For stored conversations, restore Redis into a new instance from its matching snapshot. Start with empty Redis if you can discard those conversations and provider key cooldowns. 2. Create the namespace `tokedex-restore` and its Secrets from your secret manager. Keep the original gateway Secret values, including `TOKEDEX_MASTER_KEY`, `TOKEDEX_FINGERPRINT_KEY`, `TOKEDEX_VERIFIER_ROOT` and `TOKEDEX_PASSWORD_PEPPER` if set. Point the Postgres and Redis Secrets at the new instances. 3. In a copy of `release-values.yaml` named `restore-values.yaml`, set `publicUrl` and `ingress.host` to a restore address such as `gateway-restore.example.com`, and `ingress.tlsSecretName` to a TLS Secret for that hostname in `tokedex-restore`, as [HTTPS and reverse proxies](/gateway/https) shows. Install with no replicas: ```bash helm upgrade --install tokedex ./helm/tokedex -n tokedex-restore -f restore-values.yaml \ --set replicaCount=0 --set autoscaling.enabled=false --set postgresql.migrationMode=check ``` 4. Copy the archive into the new, empty claim: ```bash kubectl -n tokedex-restore apply -f volume-pod.yaml kubectl -n tokedex-restore wait --for=condition=Ready pod/tokedex-volume --timeout=5m kubectl -n tokedex-restore exec -i tokedex-volume -- tar -xzpf - -C /state < tokedex-data.tgz kubectl -n tokedex-restore delete pod tokedex-volume ``` 5. Start the gateway: ```bash helm upgrade tokedex ./helm/tokedex -n tokedex-restore -f restore-values.yaml \ --set postgresql.migrationMode=check --wait --timeout 10m ``` With `migrationMode: check`, a gateway whose schema does not match its image refuses to start and names the pending migrations. A release without Postgres skips the database restore and both `migrationMode` settings. To serve clients, set the production address back and run `helm upgrade` again. With KMS custody, the restored release needs access to the original KMS key. ## Check the restore **Docker** ```bash export TOKEDEX_URL='http://127.0.0.1:4001' curl -fsS "$TOKEDEX_URL/readyz" ``` **Kubernetes** ```bash export TOKEDEX_URL='https://gateway-restore.example.com' curl -fsS "$TOKEDEX_URL/readyz" ``` ```json {"ok":true,"release":{"environment":"local"},"service":"tokedex"} ``` **Kubernetes** Check the `State backends` line from `kubectl -n tokedex-restore logs deployment/tokedex` to confirm which stores the gateway uses. Startup fails if it cannot decrypt a stored provider credential. List models with an API key that existed at the backup. `200` shows the restored key verifies. If you get `401`, check that the key was active at the time of the backup and that you restored the matching verifier root. ```bash curl -sS -o /dev/null -w '%{http_code}\n' "$TOKEDEX_URL/v1/models" \ -H "Authorization: Bearer $TOKEDEX_API_KEY" ``` ```text 200 ``` Sign in as an Owner and review **Workspaces**, **Members**, **API keys**, **Providers** and **Audit log**. Repeat every revocation and administrative change made since the backup before you let clients back in. > **Important:** An old backup brings back sessions, API keys and permissions revoked since it was taken, and rewinds spend and budget counters. ## Recommendations **Docker** - **Back up before every upgrade.** Restore the archive into a new volume if you need to go back to the earlier gateway version. - **Keep the archive in private, encrypted storage.** It holds the keys that sign in as the owner and decrypt stored provider credentials. - **Rehearse a restore before an upgrade.** Check that the restored gateway accepts an original API key and has the state you expect. **Kubernetes** - **Back up before every upgrade and after each change the database does not hold.** That is when you first store a provider credential and whenever you change the gateway's Secrets. A restore is the only way back from an upgrade, and those two changes are not in a database backup. - **Rehearse a restore on a schedule and before each upgrade.** You find a missing part, such as a Secret, before you need it. - **Keep the archive apart from the database snapshots.** It holds the key that decrypts the stored provider credentials, so a leaked database snapshot alone cannot open them. Next: [Upgrades and migrations](/gateway/upgrades), [Recover dashboard access](/gateway/recover-access) or [Troubleshooting](/gateway/troubleshooting). --- # Upgrades and migrations Move the gateway to a new release with its data intact, and check it before clients return. ```bash helm upgrade tokedex ./helm/tokedex -n tokedex -f release-values.yaml \ --set replicaCount=0 --set autoscaling.enabled=false --wait --timeout 10m && kubectl -n tokedex wait --for=delete pod --timeout=10m \ -l app.kubernetes.io/instance=tokedex,app.kubernetes.io/component=gateway ``` After both commands succeed, take a [complete backup](/gateway/backup-restore). The next commands run the migration and start the new release. ```bash ( set -o pipefail for action in apply check; do migration=$(helm template tokedex ./helm/tokedex -n tokedex -f next-values.yaml \ --set replicaCount=0 --set autoscaling.enabled=false --set "migrationJob.action=$action" \ --show-only templates/migration-job.yaml | kubectl -n tokedex create -f - -o name) || exit 1 deadline=$((SECONDS + 600)) while :; do conditions=$(kubectl -n tokedex get "$migration" --request-timeout=10s \ -o jsonpath='{range .status.conditions[?(@.status=="True")]}{.type}{" "}{end}') || exit 1 if [[ " $conditions " == *" Failed "* ]] || (( SECONDS >= deadline )); then kubectl -n tokedex logs "$migration" || true exit 1 fi [[ " $conditions " == *" Complete "* ]] && break sleep 2 done kubectl -n tokedex logs "$migration" || exit 1 done helm upgrade tokedex ./helm/tokedex -n tokedex -f next-values.yaml --wait --timeout 10m || exit 1 helm test tokedex -n tokedex ) ``` The second Job's log ends with no migration pending: ```json { "schemaVersion": "tokedex-gateway.admin.v1", "command": "migrate", "data": { "migrations": { "mode": "check", "applied": ["0001_state_tables", "…", "alerts/0003_model_budgets"], "pending": [] }, "preview": null } } ``` `release-values.yaml` holds the running release's values and `next-values.yaml` a copy with the new `image.tag`. Run the commands from the new release's chart. The script starts the new release after both Jobs succeed. It stops and prints the Job log as soon as Kubernetes marks a Job `Failed`, or after ten minutes without completion. Keep the gateway stopped after a failure. Keep the release name, namespace, Secret references and claim unchanged in `next-values.yaml`. You need: `kubectl`, Helm 3.17 or later, whose built-in Kubernetes version meets the chart's minimum, a release with Postgres and `postgresql.migrationMode: check` in `next-values.yaml`, a maintenance window, and a [complete backup](/gateway/backup-restore) taken with the release you run now. ## Prepare an upgrade 1. Read what the new release changes. 2. Rehearse on a backup [restored into a clean place](/gateway/backup-restore#restore-into-a-clean-place): upgrade it, then test the client APIs and features your applications use, including a streamed response and a follow-up turn. 3. Block new client traffic before you stop the gateway. Time the migration Job in your rehearsal, so you know how long a maintenance window to book. Pin `image.digest` in `next-values.yaml` as well as the tag, so production runs the exact build you rehearsed. ## Database migrations `postgresql.migrationMode` decides what a starting gateway does with pending migrations: `auto`, the default, applies them, and `check` refuses to start while one is pending. With several replicas, use `check` and apply migrations as a step, so no replica of the earlier release runs against a migrated database. Keep `check` in your values after the upgrade, so the next one is a deliberate step too. The migration Job needs Postgres, `replicaCount: 0` and autoscaling off; the chart refuses to render it otherwise. With `auto` and one replica on a `ReadWriteOnce` claim, `helm upgrade` with `next-values.yaml` is the whole upgrade: the chart stops the old Pod, and the new one applies the migrations as it starts. A release without Postgres keeps its state on the claim and runs no migration command. Run `helm upgrade` with `next-values.yaml`, then `helm test`. ## What happens to the model catalogue Each release carries its own model catalogue. When the new release starts on a store that holds an earlier catalogue, it reviews the change, the same review `catalogue preview` prints, and adopts the new catalogue if nothing in the review stops it. It saves the replaced catalogue as a backup in the same write, and records a report that the dashboard and `catalogue status` show until you acknowledge it. The report lists the models added and removed, price changes, routers whose members or ranking changed, and behaviour the release retired. The gateway stops, not ready, and asks for your review when the change would: - turn off one of your aliases, custom routers or other saved entries, including an alias whose source the new catalogue turns off; - turn off one of your custom models: the new catalogue now serves a model with that ID, or no longer offers the provider API and key the custom model uses; - take a member custom model from one of your custom routers; - take a model, or one of its client APIs, from an API key whose model list names that model, counting only the key's allowed providers when it has them; - leave a built-in router without members, or with a plan that does not resolve. It also stops when it cannot compare the stored catalogue with its own, or cannot read the API keys' model lists. A model that the new catalogue removes and that no key's model list names does not stop the upgrade; the review lists it. A key limited only to providers, with no model list, does not stop it either; the review lists each model such a key would lose. The startup log and `catalogue status` give one reason for each stop. To recover, follow [Recover a failed upgrade](#recover-a-failed-upgrade). To review every catalogue upgrade yourself, set `catalogue.upgrade: review` in the Helm chart, or `TOKEDEX_CATALOGUE_UPGRADE=review`. The gateway then stops on each upgrade, even one its review allows, until you run `catalogue apply`. It also stops on a stored catalogue it cannot read, until you run `catalogue rebuild`, instead of rebuilding it as `auto` does. The default is `auto`. In your rehearsal, and again after the upgrade, check the catalogue state. The command is read-only and calls no provider. ```bash kubectl -n tokedex exec deployment/tokedex -- node /app/dist/cli.js catalogue status --json ``` `data.status.reports` lists the upgrade reports, each with its `verdict`, `reasons` and the `backup` that holds the replaced catalogue. `data.status.disabled` lists the entries that are off, and is `[]` when there are none. Repair or remove each entry in **Models & Routing**. ### Go back after an adopted upgrade An adopted catalogue is written to the store, and the earlier release does not start on it. The replaced catalogue is kept next to it as `.replaced-`, and the upgrade report's `backup` field names it. To go back to the earlier release when the new one applied no database migration, stop the gateway, put the replaced catalogue back, and start the earlier image. If the new release applied a migration, restore the pre-upgrade backup instead. An earlier release that starts on the adopted store refuses to start. A release that adopts catalogue upgrades says in that refusal that a newer release upgraded the store, and names the kept catalogue. Releases from before automatic adoption only say the stored authority is "unrecognized or incompatible", so when you go back to one of them, this section is the guidance. `catalogue restore` puts the kept catalogue back. It takes two values from `catalogue status --json`: the report's `backup`, and `catalogueHash`, the SHA-256 of the catalogue stored now. A release that adopts catalogue upgrades prints the complete command in its refusal; with a release from before automatic adoption, run it with the new release. Stop every gateway on the store first. On a shared Postgres store that means every replica of every deployment that uses it: the command cannot detect a running gateway. Run the command with the release that is installed now, then start the earlier image. The `backup` value is a path such as `/home/node/.tokedex/catalogue.json.replaced-0123456789abcdef` on a file store, or a document name such as `gateway.catalogue.replaced-0123456789abcdef` on Postgres. The command refuses, and changes nothing, if the backup is not a file or document this store saved or its bytes do not match its name, if the stored catalogue changed since you read `catalogueHash`, or if the backup is already the stored catalogue. A backup's name holds a digest of its bytes: the command checks the bytes against the name, which shows they were not changed, not who wrote them. It restores an `unreadable-` backup only when the running release can read it. It keeps the catalogue it replaces as another `replaced-` backup, so you can undo the restore the same way. **With Helm**, keep the current chart and the values the release runs now: the earlier chart's schema may not accept `catalogue.upgrade`, and the earlier image ignores it. Only the image changes. `helm history tokedex -n tokedex` lists the revisions, and `helm get values tokedex -n tokedex --revision ` shows the earlier `image.tag` and `image.digest`. Set both: the chart uses the digest whenever one is set, and ignores the tag. If your values turn on `autoscaling`, the autoscaler starts the gateway again during these steps, so the commands keep it off; turn it back on once the earlier release runs. ```bash values=release-values.yaml helm upgrade tokedex ./helm/tokedex -n tokedex -f "$values" --set autoscaling.enabled=false --wait --timeout 10m kubectl -n tokedex scale deployment/tokedex --replicas=0 kubectl -n tokedex wait pod -l app.kubernetes.io/name=tokedex,app.kubernetes.io/instance=tokedex,app.kubernetes.io/component=gateway --for=delete --timeout=5m kubectl -n tokedex patch deployment tokedex --type json -p '[ {"op": "add", "path": "/spec/template/spec/containers/0/command", "value": ["sleep", "infinity"]}, {"op": "remove", "path": "/spec/template/spec/containers/0/startupProbe"}, {"op": "remove", "path": "/spec/template/spec/containers/0/readinessProbe"}, {"op": "remove", "path": "/spec/template/spec/containers/0/livenessProbe"} ]' kubectl -n tokedex scale deployment/tokedex --replicas=1 kubectl -n tokedex rollout status deployment/tokedex --timeout=5m kubectl -n tokedex exec -i deployment/tokedex -- node /app/dist/cli.js catalogue status --json kubectl -n tokedex exec -i deployment/tokedex -- node /app/dist/cli.js \ catalogue restore --backup '' --acknowledge kubectl -n tokedex scale deployment/tokedex --replicas=0 kubectl -n tokedex wait pod -l app.kubernetes.io/name=tokedex,app.kubernetes.io/instance=tokedex,app.kubernetes.io/component=gateway --for=delete --timeout=5m kubectl -n tokedex patch deployment tokedex --type json \ -p '[{"op": "remove", "path": "/spec/template/spec/containers/0/command"}]' helm upgrade tokedex ./helm/tokedex -n tokedex -f "$values" --set autoscaling.enabled=false \ --set image.tag= --set image.digest= --wait --timeout 10m ``` The gateway stays at zero Pods from the restore until `helm upgrade` starts the earlier image: removing the `sleep` command while a Pod runs would start the new release, which adopts its catalogue again. For the same reason, do not run the `helm upgrade` from [Run a gateway command while the gateway is stopped](/gateway/recover-access#run-a-gateway-command-while-the-gateway-is-stopped) unchanged: it starts the new release. Put the earlier `image.tag` and `image.digest` in your values file afterwards, so the next `helm upgrade` does not start the new release either. **With Docker Compose**, run the command with the current image, then start the earlier one: ```bash docker compose stop gateway docker compose run --rm --no-deps gateway catalogue status --json docker compose run --rm --no-deps gateway catalogue restore --backup '' --acknowledge TOKEDEX_GATEWAY_IMAGE=tokedex/gateway: docker compose up -d gateway ``` Set `TOKEDEX_GATEWAY_IMAGE` to the earlier image wherever you keep it, so the gateway does not start the new release on its next restart. Your settings, keys and users stay as they are, including changes made after the upgrade. Start the earlier image, not the new one: with `catalogue.upgrade: auto` the new release adopts its catalogue again as it starts. ## Check the upgraded gateway ```bash curl -sS https://gateway.example.com/readyz kubectl -n tokedex logs deployment/tokedex | grep 'State backends' kubectl -n tokedex get deployment tokedex -o jsonpath='{.spec.template.spec.containers[0].image}' ``` ```json {"ok":true,"release":{"environment":"local"},"service":"tokedex"} ``` 1. Check that the gateway is ready and that the `State backends` line names the storage you expect. 2. Sign in as an Owner and check **Workspaces**, **API keys**, **Providers** and **Models & Routing**, and that **Usage** and **Observability** still show earlier activity. 3. Send one request through each client API your applications use. It calls your provider and can incur charges. 4. Let clients back in. Then make the new values the running values, so every later `helm upgrade` keeps the new image: ```bash mv next-values.yaml release-values.yaml ``` ## Recover a failed upgrade If the startup log says catalogue recovery is required, inference and administration are unavailable. Keep clients blocked and keep the logs of the failed run. Remove the master key and other secrets before sharing diagnostics. 1. Check catalogue status (read-only). Set `values=next-values.yaml` and open the maintenance container. [Run a gateway command while the gateway is stopped](/gateway/recover-access#run-a-gateway-command-while-the-gateway-is-stopped) ```bash kubectl -n tokedex exec deployment/tokedex -- node /app/dist/cli.js catalogue status --json ``` 2. If the startup log says the upgrade needs review, read its reasons, then preview the change (read-only). ```bash kubectl -n tokedex exec deployment/tokedex -- node /app/dist/cli.js catalogue preview ``` 3. Choose how to recover. - **Apply if preview succeeds and you accept the change (writes catalogue state).** Review the proposed catalogue, router plan and entries the upgrade will disable. When a detailed comparison is unavailable, the model and key change lists are `null`. Run the write command in the maintenance container with the gateway stopped. Replace `` with the exact value from preview. ```bash kubectl -n tokedex exec deployment/tokedex -- node /app/dist/cli.js catalogue apply --acknowledge '' ``` - **Decline the change** by running the earlier release instead. The new release changes nothing until you apply. - **Rebuild only when this gateway cannot read the stored catalogue (writes catalogue state).** The startup log or `catalogue status` then says the catalogue is out of sync and prints a rebuild command; a readable catalogue is replaced only through preview and apply. Run the write command in the maintenance container with the gateway stopped. Copy the full rebuild command from the startup log or from the status JSON's `data.status.message`. It already contains the SHA-256 of the stored catalogue bytes, labelled **File digest for rebuild** in Details. The catalogue revision is listed separately. ```bash kubectl -n tokedex exec deployment/tokedex -- node /app/dist/cli.js catalogue rebuild --acknowledge '' ``` Rebuild keeps operator settings, keys and users. It backs up the old catalogue and its reports, then replaces the old catalogue routing, detached plan and catalogue overrides with the installed catalogue. Saved operator overrides stay in the operator store. If rebuild fails, stop and keep the status JSON and masked error for support. Remove credentials before sharing them. 4. Start the repaired gateway and check it before unblocking clients. For other failures, deploy a corrected release or restore the pre-upgrade backup with the release and Secrets it was taken with. An earlier release cannot always read state that a later one wrote, so a restore is the way back. Keep the pre-upgrade backup until you are sure you will not need to go back. Never delete the gateway's claim to clear an upgrade error: it holds keys nothing else can rebuild. > **Warning:** `helm rollback` changes Kubernetes resources only. It leaves the database migrated and the new catalogue in the store, and an earlier release must not run against them. Restore the whole backup, or, when no migration ran, [put the replaced catalogue back](#go-back-after-an-adopted-upgrade) first. Next: [Backup and restore](/gateway/backup-restore), [Troubleshooting](/gateway/troubleshooting) or [Recover dashboard access](/gateway/recover-access). --- # Recover dashboard access Find the heading that matches what you see, and get back in without losing people, keys or settings. **Kubernetes** The master key is in the gateway Secret: ```bash kubectl -n tokedex get secret tokedex-keys \ -o jsonpath='{.data.TOKEDEX_MASTER_KEY}' | base64 -d ``` **Docker** The gateway the [quickstart](/gateway/quickstart) starts keeps its master key in the `master-key` file of its `gateway-data` volume, and prints it in the start-up log. From the clone you started it in: ```bash docker compose exec gateway cat /home/node/.tokedex/master-key ``` You need: access to the gateway's release and its Secrets (Docker: clone and its volume). Take a [backup](/gateway/backup-restore) before you change stored state. ## The dashboard refuses the address The browser shows **This gateway does not answer to that address** (HTTP 421): the dashboard answers only at the gateway's public URL, or at `localhost` while none is set. **Kubernetes** Set `publicUrl` in `release-values.yaml` to the URL you open, such as `https://gateway.example.com`, and `ingress.host` to its hostname, then run `helm upgrade`. **Docker** Open `http://127.0.0.1:4000` on the machine that runs the gateway. If you set `TOKEDEX_PUBLIC_URL` in your shell or in `.env`, the dashboard answers only at that URL: set it to the URL you open, or remove it, then run `docker compose up -d`. Behind a proxy, pass the browser's `Host` header unchanged; see [HTTPS and reverse proxies](/gateway/https). ## A person cannot sign in | Problem | Fix | | --- | --- | | Forgotten password | An administrator, or the master key, opens the person in **Members** and chooses **Danger zone → Create reset link**. The link works once, for an hour. | | Identity provider outage | On the sign-in page, choose **Emergency sign-in with a password** if the account has emergency sign-in, or **Use the master key**. | | No Owner can sign in | Sign in with the master key. In **Members**, enable a disabled Owner and create a reset link. If no one holds the Owner role, choose **Create account** in the **Using master key** banner. | Once anyone has an account, a master-key session ends after 15 minutes idle or one hour in all. ## The master key is lost or mismatched If the master key is lost or refused, set a new one with every replica stopped: a gateway refuses a new key while another runs. **Kubernetes** The key that signs in is the `TOKEDEX_MASTER_KEY` the gateway last started with. ```bash helm upgrade tokedex ./helm/tokedex -n tokedex -f release-values.yaml \ --set replicaCount=0 --set autoscaling.enabled=false --wait --timeout 10m kubectl -n tokedex wait --for=delete pod --timeout=10m \ -l app.kubernetes.io/instance=tokedex,app.kubernetes.io/component=gateway new_master_key=$(openssl rand -hex 32) kubectl -n tokedex patch secret tokedex-keys --type merge \ -p "{\"stringData\":{\"TOKEDEX_MASTER_KEY\":\"$new_master_key\"}}" helm upgrade tokedex ./helm/tokedex -n tokedex -f release-values.yaml \ --set replicaCount=1 --set autoscaling.enabled=false \ --set podDisruptionBudget.enabled=false --wait --timeout 10m helm upgrade tokedex ./helm/tokedex -n tokedex -f release-values.yaml --wait --timeout 10m ``` One replica takes the new key first, then the release returns to its own replica count and disruption budget. **Docker** Start the gateway once with a new key in `TOKEDEX_MASTER_KEY`, then read it from the volume: ```bash TOKEDEX_MASTER_KEY="$(openssl rand -hex 32)" docker compose up -d --wait docker compose exec gateway cat /home/node/.tokedex/master-key ``` The gateway saves the new key in place of the old one, and later starts use it. If `.env` sets `TOKEDEX_MASTER_KEY`, put the new key there instead and run `docker compose up -d`. The start-up log reads: ```text gateway: TOKEDEX_MASTER_KEY changed, so it is now the master key. The previous key no longer signs in. ``` The **Audit log** records the change. Store the new key wherever you keep the old one before you sign out, since the old one no longer works. A master key needs at least 32 characters, and no access-key prefix such as `tokedex_ik_`. ## A password pepper is missing or wrong The pepper keys every stored password. **Kubernetes** It is `TOKEDEX_PASSWORD_PEPPER` in the gateway Secret or, when the Secret has no such key, `auth/password-pepper.key` on the claim. **Docker** It is `auth/password-pepper.key` in the `gateway-data` volume. When it is missing or wrong, the gateway refuses to start with an error that names the pepper, or one replica answers password sign-ins with `503 pepper_mismatch`. Restore it from the backup that matches the state, the same on every replica. If it is lost for good, make a new pepper under the next version, `2:` and 64 hex characters: ```bash new_pepper="2:$(openssl rand -hex 32)" ``` **Kubernetes** Write it to `TOKEDEX_PASSWORD_PEPPER` in the gateway Secret with every replica stopped, then start them, as for the master key. **Docker** Write it to the pepper file with the gateway stopped, then start the gateway: ```bash docker compose stop gateway printf '%s\n' "$new_pepper" | docker compose run --rm --no-deps -T --entrypoint sh gateway \ -c 'umask 077 && cat > /home/node/.tokedex/auth/password-pepper.key' docker compose start gateway ``` A new value under the lost version is refused. Every password then stops working: create a reset link for each person. ## Rotate the password pepper Keep the old pepper and add a new one under a higher version. **Kubernetes** Set `TOKEDEX_PASSWORD_PEPPER` in the gateway Secret to the old value and the new one, as `1:,2:`, and restart every replica: ```bash kubectl -n tokedex rollout restart deployment/tokedex ``` Until the restart finishes, a password set on a restarted replica can fail on one that has not restarted yet. **Docker** With the gateway stopped, rewrite `auth/password-pepper.key` in the volume as two lines, `1:` and `2:`. A file that holds one bare key holds version 1. New passwords use the highest version, and each person moves to it at their next sign-in. Remove the old entry only once nobody's password still uses it: a password under a version the gateway no longer holds stops working. ## A verifier root or key-encryption key is lost Restore both from the same backup as the state. **Kubernetes** With Postgres, the verifier root is `TOKEDEX_VERIFIER_ROOT` in the gateway Secret; without, it is `auth/verifier-root.key` on the claim. The key-encryption key is `kek/credential-kek.json` on the claim, or your KMS key. **Docker** Both are files in the `gateway-data` volume: `auth/verifier-root.key` and `auth/credential-kek.json`. - **Verifier root lost:** a gateway whose verifier root is a file starts with a new one. Every API key and admin key then answers `401 invalid_api_key`, and the log reports that the master key changed. If it is lost for good, create the keys again. - **Key-encryption key lost:** the gateway refuses to start with `Failed to open the stored credential ""`. If it is lost for good, enter that credential again while the gateway is stopped, and repeat for each name the error gives. **Kubernetes** With Postgres, a Secret without `TOKEDEX_VERIFIER_ROOT` leaves the Pod in `CreateContainerConfigError`; a different value acts as a new root. Enter a credential with [Run a gateway command while the gateway is stopped](#run-a-gateway-command-while-the-gateway-is-stopped), with this command in place of `catalogue status`: ```bash kubectl -n tokedex exec -i deployment/tokedex -- \ node /app/dist/cli.js keys set --name OPENAI_API_KEY --value-stdin < openai-key.txt ``` **Docker** ```bash docker compose stop gateway docker compose run --rm --no-deps -T gateway \ keys set --name OPENAI_API_KEY --value-stdin < openai-key.txt docker compose start gateway ``` ## Catalogue or configuration is unreadable | The gateway | Fix | | --- | --- | | Starts and logs a `catalogue_rebuilt` event | Nothing: it replaced a damaged model catalogue with its own and kept the damaged copy, named in `backup`. | | Refuses to start: the catalogues are out of sync | Keep the gateway stopped and follow the startup log's [catalogue recovery instructions](/gateway/upgrades#recover-a-failed-upgrade). If a newer release wrote the stored catalogue, upgrade to that release or restore a backup. | | Refuses to start: `invalid configuration document` | Restore the gateway's configuration from your backup. | ## Run a gateway command while the gateway is stopped **Kubernetes** Swap the gateway process for `sleep`, run the command, then undo the swap and put the release back. Set `values` to the values file the release last ran. ```bash values=release-values.yaml kubectl -n tokedex patch deployment tokedex --type json -p '[ {"op": "add", "path": "/spec/template/spec/containers/0/command", "value": ["sleep", "infinity"]}, {"op": "remove", "path": "/spec/template/spec/containers/0/startupProbe"}, {"op": "remove", "path": "/spec/template/spec/containers/0/readinessProbe"}, {"op": "remove", "path": "/spec/template/spec/containers/0/livenessProbe"} ]' kubectl -n tokedex scale deployment/tokedex --replicas=1 kubectl -n tokedex rollout status deployment/tokedex --timeout=5m kubectl -n tokedex exec -i deployment/tokedex -- node /app/dist/cli.js catalogue status kubectl -n tokedex scale deployment/tokedex --replicas=0 kubectl -n tokedex wait pod -l app.kubernetes.io/name=tokedex,app.kubernetes.io/instance=tokedex,app.kubernetes.io/component=gateway --for=delete --timeout=5m kubectl -n tokedex patch deployment tokedex --type json \ -p '[{"op": "remove", "path": "/spec/template/spec/containers/0/command"}]' helm upgrade tokedex ./helm/tokedex -n tokedex -f "$values" --wait --timeout 10m ``` Scale to zero before you undo the swap, so the gateway starts only when `helm upgrade` starts it, with the image in `$values`. Undo the swap before `helm upgrade`: the chart never sets `command`, so Helm leaves it in place. If your values turn on `autoscaling`, first run `helm upgrade` with `--set autoscaling.enabled=false`, or the autoscaler starts the gateway again. Replace `catalogue status` with the command you need. **Docker** ```bash docker compose stop gateway docker compose run --rm --no-deps gateway catalogue status docker compose start gateway ``` Replace `catalogue status` with the command you need. Commands that change state refuse while a gateway runs on the same state. ## Recommendations - **Keep copies of the password pepper, verifier root and key-encryption key with your backups.** A restored copy keeps passwords, API keys and stored provider credentials working; a new one stops them. - **Keep at least two Owners, and give one emergency sign-in.** An absent Owner then needs no master key, and someone can sign in while the identity provider is down. - **Rotate the password pepper instead of replacing it.** A rotation keeps every password working; a replacement stops them all. Next: [Troubleshooting](/gateway/troubleshooting), [Backup and restore](/gateway/backup-restore) or [Single sign-on](/gateway/single-sign-on). --- # Troubleshooting Find what is wrong with a running gateway from its status and its start-up log. Read both before you change anything: most failures name their cause there, and each section below goes from that cause to its fix. **Kubernetes** ```bash kubectl -n tokedex get pods -l app.kubernetes.io/instance=tokedex,app.kubernetes.io/component=gateway kubectl -n tokedex logs deployment/tokedex kubectl -n tokedex port-forward svc/tokedex 4000:4000 & curl -sS http://127.0.0.1:4000/readyz ``` **Docker** ```bash docker compose ps -a docker compose logs gateway curl -sS http://127.0.0.1:4000/readyz ``` ```json {"ok":true,"release":{"environment":"local"},"service":"tokedex"} ``` **Kubernetes** You need: `kubectl` access to the release, here `tokedex` in the namespace `tokedex`. For an error a request returns, see [Errors, limits and request IDs](/gateway/errors-and-limits). **Docker** Run these commands from the clone you used in the [Gateway quickstart](/gateway/quickstart). For an error a request returns, see [Errors, limits and request IDs](/gateway/errors-and-limits). ## The gateway is not ready **Kubernetes** The Pods are `Running` but not ready, and `/readyz` answers `503` with what the gateway cannot reach: ```json {"ok":false,"release":{"environment":"local"},"service":"tokedex","unavailable":["redis"]} ``` | `unavailable` lists | Fix | | --- | --- | | `postgres` or `redis` | Check that the store is up and reachable from the cluster. Redis needs persistence on and the `noeviction` memory policy. | | `catalogue_out_of_sync` | This replica cannot load the catalogue another stored, usually because it runs an earlier release. Finish the [upgrade](/gateway/upgrades). | It becomes ready once the store answers, without a restart, so fix the store rather than restarting Pods. A Pod not ready within five minutes of starting is restarted. **Docker** `docker compose ps` shows `(health: starting)` or `(unhealthy)`. A gateway on its own volume is ready as soon as it listens, so read the start-up log, as in [The gateway keeps restarting](#the-gateway-keeps-restarting). ## The gateway keeps restarting **Kubernetes** The Pod shows `Error` or `CrashLoopBackOff`. Read the run that failed with `kubectl -n tokedex logs --previous`, before you delete the Pod: a replacement Pod's log no longer holds the failure. **Docker** `docker compose ps -a` shows the gateway as `Restarting`, or `Exited` once Docker has given up after three restarts. Read `docker compose logs gateway`. The log ends with `gateway: startup failed` and the reason: | Reason in the log | Fix | | --- | --- | | A database connection error, such as `password authentication failed` | Correct the connection string and restart: the gateway reads secrets only at start. | | `the database schema is behind this gateway: pending migration(s) …` | Apply the migrations, as in [Upgrades and migrations](/gateway/upgrades#database-migrations). | | `a running gateway owns this store` | Another gateway runs on the same state. Stop every replica, then start them together. | | The master key, the password pepper, `Failed to open the stored credential`, or `invalid configuration document` | Follow [Recover dashboard access](/gateway/recover-access). | | `the unwritten spend in … could not be written to the spend ledger` | Check the database connection, and keep the files in `state/spend-unwritten`: they hold spend not yet counted. | Stop every replica before you run a gateway command on the same state: a command that changes state refuses while a gateway runs on it. [Recover dashboard access](/gateway/recover-access#run-a-gateway-command-while-the-gateway-is-stopped) shows how to run one. ## The dashboard will not open Check first that the gateway is ready. Then: - **You are on another computer.** The gateway answers other computers only at its public URL, through the ingress (Docker: The quickstart's gateway answers only on the machine that runs it). To serve other computers, [deploy it](/gateway/deploy) and serve it over [HTTPS](/gateway/https). - **The browser shows "This gateway does not answer to that address" (HTTP 421).** Set the public URL to the address you open; see [The dashboard refuses the address](/gateway/recover-access#the-dashboard-refuses-the-address). - **The page opens but sign-in fails.** See [A person cannot sign in](/gateway/recover-access#a-person-cannot-sign-in), or [Single sign-on](/gateway/single-sign-on) for an identity provider. ## No models appear **Playground** and `GET /v1/models` list only models the API key can call. 1. Open **Providers**. A provider that reads **Not configured** needs a credential; see [Provider credentials](/gateway/provider-credentials). 2. Open the model in **Models & Routing**. **Routing by API format** must list your client API, with **Accept requests** and **Show in model list** selected. 3. Check that the key and its workspace may call the model; see [Model access and limits](/gateway/model-access-and-limits). 4. In **Playground**, choose **Refresh models** after you change the key or a credential. ## Traces or prompt text are missing - **A request is not in Observability.** Check first that recording reports `ok`, as [Check that recording works](/gateway/recording-and-retention#check-that-recording-works) shows, then the time range and the workspace chosen in the sidebar. A request sent with `x-tokedex-trace: false` is not recorded. - **The page reads "Observability store disabled".** Choose **Enable observability**, then restart the gateway. - **A trace reads "Text not captured".** Text capture is off on the gateway, or the request did not opt in; see [What the gateway records](/gateway/recording-and-retention). ## A restored or upgraded gateway will not start Keep clients away, read the reason in the start-up log and save a copy, since a catalogue fix needs the command it prints. Then check that: - The gateway runs the release that took the backup. Restore first, then upgrade. - Every part of the backup is back, with the secrets the gateway had. - No migration is pending, and the stored catalogue is in sync; see [Recover a failed upgrade](/gateway/upgrades#recover-a-failed-upgrade). Never delete the claim (Docker: volume) to get past an error: it holds keys nothing else can rebuild. ## Report a problem [Open an issue on GitHub](https://github.com/ArtificialAnalysis/tokedex/issues/new) to report a bug, request a feature or point out a problem in these docs. In the dashboard, **Open an issue on GitHub** under **Help** in the sidebar starts one with the release and browser details filled in. Tokedex does not accept pull requests, so an issue is also the way to suggest a change; [Contributing](https://github.com/ArtificialAnalysis/tokedex/blob/main/CONTRIBUTING.md) has the full guidelines. Include the image tag (Docker: commit of your clone), the client API, a minimal request, the HTTP status, the error body, the `x-request-id` response header and the start-up log. Remove keys, provider credentials and sensitive text first: issues are public, and the start-up log can print the master key. Report a security problem privately, as [SECURITY.md](https://github.com/ArtificialAnalysis/tokedex/blob/main/SECURITY.md) describes. Next: [Recover dashboard access](/gateway/recover-access), [Errors, limits and request IDs](/gateway/errors-and-limits) or [Upgrades and migrations](/gateway/upgrades). --- # SDK overview Write a request once, in the API you already use, and send it to a model from any provider by changing its model ID. **OpenAI Responses** ```ts import { Router } from '@tokedex/sdk'; const router = new Router(); const response = await router.responses.create({ model: 'openai/gpt-6-luna', input: 'Name the capital of France in one word.', }); 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); } ``` ```python from tokedex import Router with Router() as router: response = router.responses.create( model="openai/gpt-6-luna", input="Name the capital of France in one word." ) print(response.output_text) ``` ```rust use tokedex::{Router, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let request = wire::ResponsesRequest::new("openai/gpt-6-luna", "Name the capital of France in one word."); let response = router.responses().create(request).await?; println!("{}", response.output_text()); Ok(()) } ``` **OpenAI Chat Completions** ```ts import { Router } from '@tokedex/sdk'; const router = new Router(); const completion = await router.chat.completions.create({ model: 'openai/gpt-6-luna', messages: [{ role: 'user', content: 'Name the capital of France in one word.' }], }); console.log(completion.choices[0]?.message.content); ``` ```python from tokedex import Router with Router() as router: completion = router.chat.completions.create( model="openai/gpt-6-luna", messages=[{"role": "user", "content": "Name the capital of France in one word."}], ) print(completion.choices[0].message.content) ``` ```rust use tokedex::{Router, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let messages = vec![wire::Message::user("Name the capital of France in one word.")]; let request = wire::ChatCompletionsRequest::new("openai/gpt-6-luna", messages); let completion = router.chat().completions().create(request).await?; if let Some(wire::Content::Text(text)) = &completion.choices[0].message.content { println!("{text}"); } Ok(()) } ``` **Anthropic Messages** ```ts import { Router } from '@tokedex/sdk'; const router = new Router(); const message = await router.messages.create({ model: 'openai/gpt-6-luna', messages: [{ role: 'user', content: 'Name the capital of France in one word.' }], }); for (const block of message.content) if (block.type === 'text') console.log(block.text); ``` ```python from tokedex import Router with Router() as router: message = router.messages.create( model="openai/gpt-6-luna", messages=[{"role": "user", "content": "Name the capital of France in one word."}], ) print("".join(block.text for block in message.content if block.type == "text")) ``` ```rust use tokedex::{Router, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let messages = vec![wire::Message::user("Name the capital of France in one word.")]; let request = wire::MessagesRequest::new("openai/gpt-6-luna", messages); let message = router.messages().create(request).await?; for block in &message.content { if let wire::ContentBlock::Text { text, .. } = block { println!("{text}"); } } Ok(()) } ``` ```text Paris ``` The model is OpenAI's, and the request and the reply are in your API. It needs `OPENAI_API_KEY` in your environment, and the call is billed by OpenAI. **TypeScript** Run it with `npx tsx hello.ts`. ## Behind the sample The Router sent the request to OpenAI and gave you the reply in your API. `openai/gpt-6-luna` works the same in all three APIs, so the API you write in never decides the model. Your code reads every model's answer from the same fields and never sees a provider's format. To call another provider's model, change `model`: with `anthropic/claude-haiku-5.5`, the same request goes to Anthropic. Most models are served on OpenAI Responses, OpenAI Chat Completions and Anthropic Messages. A few are served on one API only; `router.models.list()` (Rust: `router.models().list()`) returns one row for each model and API it serves. The same Router also speaks a fourth API, Gemini GenerateContent, for Google's Gemini and Gemma models; see [Generate text](/sdk/generate-text). Keep the API your code already uses, since most models are served on all three and nothing needs porting. For new code, start with OpenAI Responses: it is the only API with the typed `parse` (Rust: `parse()`) helper and with conversation turns the Router stores for you. Choose Gemini GenerateContent only for code that calls Google's models alone, because it serves no other provider's. ## Run the same code through a gateway ```ts const router = new Router({ baseUrl: 'http://127.0.0.1:4000', apiKey: process.env.TOKEDEX_API_KEY! }); ``` ```python import os from tokedex import Router with Router(base_url="http://127.0.0.1:4000", api_key=os.environ["TOKEDEX_API_KEY"]) as router: ... # The same calls as before. ``` ```rust use tokedex::{GatewayOptions, Router}; let router = Router::new(GatewayOptions::new("http://127.0.0.1:4000", std::env::var("TOKEDEX_API_KEY")?))?; ``` Change the line that creates the Router and keep every other line. The gateway then holds the provider credentials, so your process needs only a Tokedex API key, and each call appears in the gateway's dashboard under **Observability** and **Usage**. Through a gateway, you can call the models that gateway serves, and its administrator chooses them. [Run through a gateway](/sdk/gateway) covers headers and errors. Move to a gateway once more than one application or person calls models on the same provider accounts: each then holds only its own API key, and you see every call in one dashboard. ## Other Router features | To | Call | Guide | |---|---|---| | Stream the reply as it is written | `.stream(…)` on the same resource | [Stream a reply](/sdk/streaming) | | Get a typed, validated value | `router.responses.parse` (Rust: `router.responses().parse`) | [Structured output](/sdk/structured-output) | | Send images and files | Image and file parts in the request | [Images and files](/sdk/images-and-files) | | Continue a conversation | The API's own history fields | [Conversations](/sdk/conversations) | | Run a job at Batch prices | `router.batches.create` (Rust: `router.batches().create`) | [Batch jobs](/sdk/batch) | | See which models and APIs you can call | `router.models.list()` (Rust: `router.models().list()`) | [Choose a model](/sdk/models) | To choose each provider and account yourself, or to add hooks and sinks, build your own router with the core package; see [Routes and failover](/sdk/routes-and-failover). ## Install the SDK Run `npm install @tokedex/sdk` (Python: `uv add tokedex`; Rust: `cargo add tokedex`), or follow the [SDK quickstart](/sdk/quickstart). **Rust** The samples also need Tokio: `cargo add tokio --features macros,rt-multi-thread`. Next: [SDK quickstart](/sdk/quickstart), [Generate text](/sdk/generate-text) or [Run through a gateway](/sdk/gateway). --- # SDK quickstart Install the SDK, set one key and get your first reply from a model, in about five minutes. ## Install the SDK **TypeScript** Use a supported Node.js LTS release (see `engines` in [`package.json`](https://github.com/ArtificialAnalysis/Tokedex/blob/main/typescript/package.json)) and an ESM project, with `"type": "module"` in `package.json`. In your project directory, add the SDK: ```ts npm install @tokedex/sdk npm install --save-dev tsx ``` ```python uv add tokedex ``` ```rust cargo add tokedex cargo add tokio --features macros,rt-multi-thread ``` **Python** It needs Python 3.11 or later and [uv](https://docs.astral.sh/uv/). **Rust** It needs Rust 1.88 or later. ## Set a provider key **OpenAI Responses, OpenAI Chat Completions, Anthropic Messages** ```bash export OPENAI_API_KEY='' ``` **Gemini GenerateContent** ```bash export GEMINI_API_KEY='' ``` The Router reads each provider's key from the environment when a call needs it. [Provider keys](/sdk/provider-keys) lists every provider's variable. > **Tip:** Keep provider keys in the environment, never in your source code. Your program then holds no secret, and a key cannot reach version control with it. ## Write a first program **OpenAI Responses** ```ts import { Router } from '@tokedex/sdk'; 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); } ``` ```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) ``` ```rust use tokedex::{Router, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let request = wire::ResponsesRequest::new("openai/gpt-6-luna", r#"Reply with exactly the word "hello"."#); let response = router.responses().create(request).await?; println!("{}", response.output_text()); Ok(()) } ``` **OpenAI Chat Completions** ```ts import { Router } from '@tokedex/sdk'; const router = new Router(); 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 with Router() as router: 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}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let messages = vec![wire::Message::user(r#"Reply with exactly the word "hello"."#)]; let request = wire::ChatCompletionsRequest::new("openai/gpt-6-luna", messages); let completion = router.chat().completions().create(request).await?; if let Some(wire::Content::Text(text)) = &completion.choices[0].message.content { println!("{text}"); } Ok(()) } ``` **Anthropic Messages** ```ts import { Router } from '@tokedex/sdk'; const router = new Router(); const message = await router.messages.create({ model: 'openai/gpt-6-luna', messages: [{ role: 'user', content: 'Reply with exactly the word "hello".' }], }); for (const block of message.content) if (block.type === 'text') console.log(block.text); ``` ```python from tokedex import Router with Router() as router: message = router.messages.create( model="openai/gpt-6-luna", messages=[{"role": "user", "content": 'Reply with exactly the word "hello".'}], ) for block in message.content: if block.type == "text": print(block.text) ``` ```rust use tokedex::{Router, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let messages = vec![wire::Message::user(r#"Reply with exactly the word "hello"."#)]; let request = wire::MessagesRequest::new("openai/gpt-6-luna", messages); let message = router.messages().create(request).await?; for block in &message.content { if let wire::ContentBlock::Text { text, .. } = block { println!("{text}"); } } Ok(()) } ``` **Gemini GenerateContent** ```ts import { Router } from '@tokedex/sdk'; const router = new Router(); const response = await router.generateContent.create({ model: 'google/gemini-3.5-flash-lite', contents: [{ role: 'user', parts: [{ text: 'Reply with exactly the word "hello".' }] }], }); for (const part of response.candidates?.[0]?.content?.parts ?? []) { if ('text' in part && !part.thought) console.log(part.text); } ``` ```python from tokedex import Router from tokedex.sdk.wire import GeminiTextPart with Router() as router: response = router.generate_content.create( model="google/gemini-3.5-flash-lite", contents=[{"role": "user", "parts": [{"text": 'Reply with exactly the word "hello".'}]}], ) for candidate in response.candidates or []: if candidate.content is None: continue for part in candidate.content.parts: if isinstance(part, GeminiTextPart) and not part.thought: print(part.text) ``` ```rust use serde_json::json; use tokedex::{Router, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let request: wire::GeminiRequest = serde_json::from_value(json!({ "contents": [{ "role": "user", "parts": [{ "text": "Reply with exactly the word \"hello\"." }] }], }))?; let response = router.generate_content().create("google/gemini-3.5-flash-lite", request).await?; for candidate in response.candidates.unwrap_or_default() { for part in candidate.content.map(|content| content.parts).unwrap_or_default() { if part["thought"].as_bool() != Some(true) && let Some(text) = part["text"].as_str() { println!("{text}"); } } } Ok(()) } ``` Save it as `hello.ts` (Python: `hello.py`; Rust: `src/main.rs`). It sends one your API request and prints the reply's text. In a larger program, create one Router when the program starts and reuse it for every call, so its connections are reused rather than opened for each call. **OpenAI Responses** The Router also holds the conversation turns it stores, which a new Router cannot find. **Rust · Gemini GenerateContent** Add `cargo add serde_json` to write the request as JSON. ## Run the program ```ts npx tsx hello.ts ``` ```python uv run python hello.py ``` ```rust cargo run ``` ```text hello ``` The call uses your OpenAI (Gemini GenerateContent: Google) account and can incur charges. ## Call the Router from async code **TypeScript, Rust** Every call is already asynchronous: you `await` it. **Python** Use `AsyncRouter` in an `async with` block and `await` each call. It takes the same arguments as `Router`, and every other line stays the same. Avoid `Router` in async code: each of its calls blocks the thread until the reply arrives, which stalls your event loop. Next: [SDK overview](/sdk), [Generate text](/sdk/generate-text) or [Run through a gateway](/sdk/gateway). --- # Generate text Send a prompt with instructions and settings in the API your code already uses, and read the model's answer. **OpenAI Responses** ```ts import { Router } from '@tokedex/sdk'; const router = new Router(); const response = await router.responses.create({ model: 'openai/gpt-6-luna', instructions: 'Answer with a number only.', input: 'What is 2 + 2?', }); 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); } ``` ```python from tokedex import Router with Router() as router: response = router.responses.create( model="openai/gpt-6-luna", instructions="Answer with a number only.", input="What is 2 + 2?", ) print(response.output_text) ``` ```rust use tokedex::{Router, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let mut request = wire::ResponsesRequest::new("openai/gpt-6-luna", "What is 2 + 2?"); request.instructions = wire::Presence::Value("Answer with a number only.".into()); let response = router.responses().create(request).await?; println!("{}", response.output_text()); Ok(()) } ``` **OpenAI Chat Completions** ```ts import { Router } from '@tokedex/sdk'; const router = new Router(); const completion = await router.chat.completions.create({ model: 'openai/gpt-6-luna', messages: [ { role: 'system', content: 'Answer with a number only.' }, { role: 'user', content: 'What is 2 + 2?' }, ], }); console.log(completion.choices[0]?.message.content); ``` ```python from tokedex import Router with Router() as router: completion = router.chat.completions.create( model="openai/gpt-6-luna", messages=[ {"role": "system", "content": "Answer with a number only."}, {"role": "user", "content": "What is 2 + 2?"}, ], ) print(completion.choices[0].message.content) ``` ```rust use tokedex::{Router, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let system = wire::Message { role: "system".into(), content: Some("Answer with a number only.".into()), fields: Default::default(), }; let messages = vec![system, wire::Message::user("What is 2 + 2?")]; let request = wire::ChatCompletionsRequest::new("openai/gpt-6-luna", messages); let completion = router.chat().completions().create(request).await?; if let Some(wire::Content::Text(text)) = &completion.choices[0].message.content { println!("{text}"); } Ok(()) } ``` **Anthropic Messages** ```ts import { Router } from '@tokedex/sdk'; const router = new Router(); const message = await router.messages.create({ model: 'openai/gpt-6-luna', system: 'Answer with a number only.', messages: [{ role: 'user', content: 'What is 2 + 2?' }], }); for (const block of message.content) if (block.type === 'text') console.log(block.text); ``` ```python from tokedex import Router with Router() as router: message = router.messages.create( model="openai/gpt-6-luna", system="Answer with a number only.", messages=[{"role": "user", "content": "What is 2 + 2?"}], ) for block in message.content: if block.type == "text": print(block.text) ``` ```rust use tokedex::{Router, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let messages = vec![wire::Message::user("What is 2 + 2?")]; let mut request = wire::MessagesRequest::new("openai/gpt-6-luna", messages); request.system = wire::Presence::Value("Answer with a number only.".into()); let message = router.messages().create(request).await?; for block in &message.content { if let wire::ContentBlock::Text { text, .. } = block { println!("{text}"); } } Ok(()) } ``` **Gemini GenerateContent** ```ts import { Router } from '@tokedex/sdk'; const router = new Router(); const response = await router.generateContent.create({ model: 'google/gemini-3.5-flash-lite', systemInstruction: { parts: [{ text: 'Answer with a number only.' }] }, contents: [{ role: 'user', parts: [{ text: 'What is 2 + 2?' }] }], }); for (const part of response.candidates?.[0]?.content?.parts ?? []) if ('text' in part) console.log(part.text); ``` ```python from tokedex import Router with Router() as router: response = router.generate_content.create( model="google/gemini-3.5-flash-lite", system_instruction={"parts": [{"text": "Answer with a number only."}]}, contents=[{"role": "user", "parts": [{"text": "What is 2 + 2?"}]}], ) for candidate in response.candidates or []: print("".join(getattr(part, "text", "") for part in candidate.content.parts)) ``` ```rust use serde_json::json; use tokedex::{Router, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let request: wire::GeminiRequest = serde_json::from_value(json!({ "systemInstruction": { "parts": [{ "text": "Answer with a number only." }] }, "contents": [{ "role": "user", "parts": [{ "text": "What is 2 + 2?" }] }], }))?; let response = router.generate_content().create("google/gemini-3.5-flash-lite", request).await?; for candidate in response.candidates.unwrap_or_default() { for part in candidate.content.map(|content| content.parts).unwrap_or_default() { println!("{}", part["text"].as_str().unwrap_or_default()); } } Ok(()) } ``` ```text 4 ``` It needs `OPENAI_API_KEY` (Gemini GenerateContent: `GEMINI_API_KEY`), and the call is billed by OpenAI (Gemini GenerateContent: Google). Any other model takes the same request: change `model`. Most models are served on OpenAI Responses, OpenAI Chat Completions and Anthropic Messages; Gemini GenerateContent takes Google's Gemini and Gemma models only. See [Choose a model](/sdk/models). **Rust · Gemini GenerateContent** Add `cargo add serde_json` to write the request as JSON. **Gemini GenerateContent** Gemini model names and custom aliases occupy one URL path segment. They can contain ASCII letters, digits, dots, underscores and hyphens. For a function without an argument schema, omit `parameters` or pass `null`. When supplied, `parametersJsonSchema` must be an object. Native Gemini responses preserve explicit nulls in optional candidate metadata such as `finishMessage` and `safetyRatings`. If a provider supplies a value of the wrong type, the gateway returns HTTP 502 and the embedded SDK raises a provider error. Write against GenerateContent only when your code calls Google's models alone. If you may move to another provider's model later, prefer one of the other three APIs, so that the move is a change of `model` and not a rewrite. **Python** Use `Router` in a `with` block, or call `close()` when you are done, to release its connections. ## Read the reply The text is in `output` (OpenAI Chat Completions: `choices[0].message.content`; Anthropic Messages: `content`; Gemini GenerateContent: `candidates[0].content.parts`), the token counts in `usage` (Gemini GenerateContent: `usageMetadata`), and why the model stopped in `status` (OpenAI Chat Completions: `choices[0].finish_reason`; Anthropic Messages: `stop_reason`; Gemini GenerateContent: `candidates[0].finishReason`). Every field has the name and shape that your API gives it, in every language and whichever provider served the model. **TypeScript · OpenAI Responses** The text sits in the `output_text` parts of each `message` item, as the sample reads it. **Python, Rust · OpenAI Responses** `output_text` (Python, Rust: `output_text()`) joins the `output_text` parts of every `message` item for you. ## Give the model instructions The opening sample sets them in `instructions` (OpenAI Chat Completions: a system message; Anthropic Messages: `system`; Gemini GenerateContent: `systemInstruction`). Every provider receives them as its own system prompt. **OpenAI Chat Completions, Anthropic Messages** Keep all your instructions in `instructions` (OpenAI Chat Completions: the first system message; Anthropic Messages: `system`; Gemini GenerateContent: `systemInstruction`): a system message after the first turn reaches some providers as text in the next user turn; see [Translation between APIs](/sdk/translation). ## Set length, temperature and reasoning Length, temperature and reasoning are request fields, next to the prompt, with your API's own names: - Most output tokens: `max_output_tokens` (OpenAI Chat Completions: `max_completion_tokens`; Anthropic Messages: `max_tokens`; Gemini GenerateContent: `generationConfig.maxOutputTokens`). - Temperature: `temperature` (Gemini GenerateContent: `generationConfig.temperature`). - Reasoning effort: `reasoning.effort` (OpenAI Chat Completions: `reasoning_effort`; Anthropic Messages: `output_config.effort`; Gemini GenerateContent: `generationConfig.thinkingConfig`). Which values a model accepts depends on the model; see [Choose a model](/sdk/models). Leave out a field you do not mean to send. A field set to `null` (Python, Rust: `None`) can still be refused by a model that does not support it. Leave out `max_output_tokens` (OpenAI Chat Completions: `max_completion_tokens`; Anthropic Messages: `max_tokens`; Gemini GenerateContent: `generationConfig.maxOutputTokens`) and the model's own output limit applies. If you set one, leave room for reasoning: a reasoning model's thinking counts against the same limit, so a small one can end the reply before it starts. Either way, check why the model stopped before you use the text. A reply that reaches the limit ends mid-answer, and the field that says why the model stopped holds `incomplete` (OpenAI Chat Completions: `length`; Anthropic Messages: `max_tokens`; Gemini GenerateContent: `MAX_TOKENS`). **OpenAI Responses** The Router refuses `background: true`. To run work later, use [Batch jobs](/sdk/batch). Settings for the call itself, such as a timeout, are call options; see [Errors, retries and timeouts](/sdk/errors-and-retries). **Anthropic Messages** Send Anthropic headers, such as `anthropic-beta`, in the `headers` (Python: `extra_headers`; Rust: `RequestOptions::headers`) call option. ## Count tokens before sending ```ts const count = await router.messages.countTokens({ model: 'openai/gpt-6-luna', messages: [{ role: 'user', content: 'What is 2 + 2?' }], }); console.log(count.input_tokens, count.estimated); ``` ```python count = router.messages.count_tokens( model="openai/gpt-6-luna", messages=[{"role": "user", "content": "What is 2 + 2?"}] ) print(count.input_tokens, count.estimated) ``` ```rust use tokedex::wire; let request = wire::MessagesRequest::new("openai/gpt-6-luna", vec![wire::Message::user("What is 2 + 2?")]); let count = router.messages().count_tokens(request).await?; println!("{} {}", count.input_tokens, count.estimated); ``` Counting is an Anthropic Messages call, and it works for any model that Messages serves. It generates nothing. `estimated` is true when the Router uses its own estimate because the provider has no counter or its counter is temporarily unavailable, such as when it returns a rate limit. A provider authentication error still fails the count. Count a long prompt before you send it, to check that it fits the model's context window, since a prompt that does not fit fails the call with `ContextWindowExceeded`. Leave room below the limit when `estimated` is true, because the number is then approximate. ## Request and response types **TypeScript** `@tokedex/sdk` exports the request type `ResponseRequest` (OpenAI Chat Completions: `ChatCompletionRequest`; Anthropic Messages: `MessageRequest`; Gemini GenerateContent: `GeminiRequest`), the reply type `ResponseObject` (OpenAI Chat Completions: `ChatCompletion`; Anthropic Messages: `MessageResponse`; Gemini GenerateContent: `GeminiResponse`) and the stream event type `ResponseStreamEvent` (OpenAI Chat Completions: `ChatCompletionChunk`; Anthropic Messages: `MessageStreamEvent`; Gemini GenerateContent: `GeminiResponse`). **Python** A request is the method's keyword arguments. `tokedex.sdk.wire` holds the reply type `Response` (OpenAI Chat Completions: `ChatCompletion`; Anthropic Messages: `Message`; Gemini GenerateContent: `GeminiResponse`), the stream event type `ResponseStreamEvent` (OpenAI Chat Completions: `ChatCompletionChunk`; Anthropic Messages: `MessageStreamEvent`; Gemini GenerateContent: `GeminiResponse`) and typed request parts, such as `ResponseInputMessage` (OpenAI Chat Completions: `ChatMessageParam`; Anthropic Messages: `MessageParam`; Gemini GenerateContent: `GeminiContent`). **Rust** `tokedex::wire` holds the request type `ResponsesRequest` (OpenAI Chat Completions: `ChatCompletionsRequest`; Anthropic Messages: `MessagesRequest`; Gemini GenerateContent: `GeminiRequest`), the reply type `Response` (OpenAI Chat Completions: `ChatCompletion`; Anthropic Messages: `MessagesResponse`; Gemini GenerateContent: `GeminiResponse`) and the stream event type `ResponseEvent` (OpenAI Chat Completions: `ChatChunk`; Anthropic Messages: `MessagesEvent`; Gemini GenerateContent: `GeminiResponse`). Next: [Stream a reply](/sdk/streaming), [Conversations](/sdk/conversations) or [Structured output](/sdk/structured-output). --- # Stream a reply Print the model's answer as it is written, in your API's own stream events. **OpenAI Responses** ```ts import { Router } from '@tokedex/sdk'; const router = new Router(); for await (const event of router.responses.stream({ model: 'openai/gpt-6-luna', input: 'Count from 1 to 5.' })) { if (event.type === 'response.output_text.delta') process.stdout.write(event.delta); } console.log(); ``` ```python from tokedex import Router with Router() as router: with router.responses.stream(model="openai/gpt-6-luna", input="Count from 1 to 5.") as events: for event in events: if event.type == "response.output_text.delta": print(event.delta, end="", flush=True) print() ``` ```rust use tokedex::{Router, StreamExt, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let mut events = router.responses().stream(wire::ResponsesRequest::new("openai/gpt-6-luna", "Count from 1 to 5.")); while let Some(event) = events.next().await { let event = event?; if event.kind == "response.output_text.delta" { print!("{}", event.delta.unwrap_or_default()); } } println!(); Ok(()) } ``` **OpenAI Chat Completions** ```ts import { Router } from '@tokedex/sdk'; const router = new Router(); for await (const chunk of router.chat.completions.stream({ model: 'openai/gpt-6-luna', messages: [{ role: 'user', content: 'Count from 1 to 5.' }], })) { process.stdout.write(chunk.choices[0]?.delta.content ?? ''); } console.log(); ``` ```python from tokedex import Router with Router() as router: with router.chat.completions.stream( model="openai/gpt-6-luna", messages=[{"role": "user", "content": "Count from 1 to 5."}] ) as chunks: for chunk in chunks: for choice in chunk.choices: print(choice.delta.content or "", end="", flush=True) print() ``` ```rust use tokedex::{Router, StreamExt, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let request = wire::ChatCompletionsRequest::new("openai/gpt-6-luna", vec![wire::Message::user("Count from 1 to 5.")]); let mut chunks = router.chat().completions().stream(request); while let Some(chunk) = chunks.next().await { for choice in chunk?.choices { if let wire::Presence::Value(text) = choice.delta.content { print!("{text}"); } } } println!(); Ok(()) } ``` **Anthropic Messages** ```ts import { Router } from '@tokedex/sdk'; const router = new Router(); for await (const event of router.messages.stream({ model: 'openai/gpt-6-luna', messages: [{ role: 'user', content: 'Count from 1 to 5.' }], })) { if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') process.stdout.write(event.delta.text); } console.log(); ``` ```python from tokedex import Router with Router() as router: with router.messages.stream( model="openai/gpt-6-luna", messages=[{"role": "user", "content": "Count from 1 to 5."}], ) as events: for event in events: if event.type == "content_block_delta" and event.delta.type == "text_delta": print(event.delta.text, end="", flush=True) print() ``` ```rust use tokedex::{Router, StreamExt, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let messages = vec![wire::Message::user("Count from 1 to 5.")]; let mut events = router.messages().stream(wire::MessagesRequest::new("openai/gpt-6-luna", messages)); while let Some(event) = events.next().await { let event = event?; if event.kind == "content_block_delta" { print!("{}", event.fields["delta"]["text"].as_str().unwrap_or_default()); } } println!(); Ok(()) } ``` **Gemini GenerateContent** ```ts import { Router } from '@tokedex/sdk'; const router = new Router(); for await (const chunk of router.generateContent.stream({ model: 'google/gemini-3.5-flash-lite', contents: [{ role: 'user', parts: [{ text: 'Count from 1 to 5.' }] }], })) { for (const part of chunk.candidates?.[0]?.content?.parts ?? []) if ('text' in part) process.stdout.write(part.text); } console.log(); ``` ```python from tokedex import Router with Router() as router: with router.generate_content.stream( model="google/gemini-3.5-flash-lite", contents=[{"role": "user", "parts": [{"text": "Count from 1 to 5."}]}], ) as chunks: for chunk in chunks: for candidate in chunk.candidates or []: parts = candidate.content.parts if candidate.content else [] print("".join(getattr(part, "text", "") for part in parts), end="", flush=True) print() ``` ```rust use serde_json::json; use tokedex::{Router, StreamExt, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let request: wire::GeminiRequest = serde_json::from_value(json!({ "contents": [{ "role": "user", "parts": [{ "text": "Count from 1 to 5." }] }], }))?; let mut chunks = router.generate_content().stream("google/gemini-3.5-flash-lite", request); while let Some(chunk) = chunks.next().await { for candidate in chunk?.candidates.unwrap_or_default() { for part in candidate.content.map(|content| content.parts).unwrap_or_default() { print!("{}", part["text"].as_str().unwrap_or_default()); } } } println!(); Ok(()) } ``` ```text 1, 2, 3, 4, 5 ``` It needs `OPENAI_API_KEY` (Gemini GenerateContent: `GEMINI_API_KEY`), and the call is billed by OpenAI (Gemini GenerateContent: Google). `stream` takes the same request as `create`. Streams work the same through a gateway; see [Run through a gateway](/sdk/gateway). Stream when a person reads the reply as it is written. For work nobody watches, call `create`: until its reply arrives, a failed attempt can still move to another provider, while a stream stays with its provider after the first event (see [Stream failures](#stream-failures)). **Rust · Gemini GenerateContent** Add `cargo add serde_json` to write the request as JSON. **Python** With an `AsyncRouter`, open the stream with `async with` and read it with `async for`. **OpenAI Responses** `router.responses.parse` (Rust: `router.responses().parse`) does not stream. ## Text events Text arrives in `response.output_text.delta` (OpenAI Chat Completions: `choices[0].delta.content`; Anthropic Messages: `content_block_delta`; Gemini GenerateContent: `candidates[0].content.parts`), and `response.completed` (OpenAI Chat Completions: `finish_reason`; Anthropic Messages: `message_delta`; Gemini GenerateContent: `finishReason`) marks the end of the reply. Other events carry reasoning and tool calls as they arrive. The events are your API's own, whichever provider serves the model. To stream a tool loop, use `streamTools` (Python, Rust: `stream_tools`). **Rust · Anthropic Messages** A Messages event is generic: read its type in `kind` and the rest in `fields`. ## Streaming with create **TypeScript, Python · OpenAI Responses, OpenAI Chat Completions, Anthropic Messages** `create` with `stream: true` (Python, Rust: `stream=True`) returns the same stream as `stream`, so code written for your API's own client keeps working. **TypeScript · OpenAI Responses, OpenAI Chat Completions, Anthropic Messages** Await the call, then iterate over what it returns. **TypeScript, Python · Gemini GenerateContent** GenerateContent chooses streaming by method, so call `stream`, not `create`. **Rust** In Rust, call `stream`; `create` does not stream. A request that sets `stream` to anything else fails. ## Stop a stream early Stop reading, and the Router closes the provider's connection. **TypeScript** `break` out of the `for await` loop. **Python** `break` out of the loop, or leave the `with` block. A stream opened outside a `with` block needs `close()`, so prefer the `with` block: it closes the connection even when your code raises. **Rust** Drop the stream, for example by breaking out of the loop. ## Stream failures Until the first event reaches you, a failed call can still move to another provider that serves the model, or to the next model of a [router ID such as `aa/fastest`](/sdk/models#routers). After that, the stream stays with its provider, and an error ends your loop: `the loop throws` (Python: `the loop raises`; Rust: `the stream yields an Err`). > **Tip:** Treat text you collect from a stream as a draft until the end event arrives. If the loop ends with an error, discard the partial reply or mark it as cut off, and send the whole request again when you need the complete answer, because a stream does not resume. ## Cancel a stream or set a timeout ```ts const controller = new AbortController(); // controller.abort() stops the stream const options = { signal: controller.signal, timeoutMs: 30_000 }; ``` ```python from tokedex.core.provider import CancelToken cancel = CancelToken() # cancel.abort() stops the stream ``` ```rust use std::time::Duration; use tokedex::{CancellationToken, RequestOptions}; let cancel = CancellationToken::new(); // cancel.cancel() stops the stream let options = RequestOptions::default().timeout(Duration::from_secs(30)).cancel(cancel.clone()); let limited = router.with_options(options); ``` **TypeScript** Pass `options` as the second argument of `stream`. **Python** Pass `cancel=cancel` and `timeout_ms=30_000` to `stream`, next to the request fields. **Rust** Stream from `limited` the way you stream from `router`. The timeout covers retries, failover and every read. Size it for your longest complete reply so the stream has time to finish. The errors from a timeout or cancellation depend on how the Router connects. See [Set a timeout](/sdk/errors-and-retries#set-a-timeout) and [Cancel a call](/sdk/errors-and-retries#cancel-a-call). Next: [Conversations](/sdk/conversations) or [Errors, retries and timeouts](/sdk/errors-and-retries). --- # Structured output Describe the value you want as a type, and get it back from the model filled in and checked. **OpenAI Responses** ```ts import { Router } from '@tokedex/sdk'; import { z } from 'zod'; const Country = z.object({ capital: z.string(), currency: z.string() }); const router = new Router(); const response = await router.responses.parse({ model: 'openai/gpt-6-luna', input: 'What is the capital of France, and its currency code?', textFormat: Country, }); const country = response.outputParsed; if (country !== null) console.log(country.capital, country.currency); ``` ```python from pydantic import BaseModel from tokedex import Router class Country(BaseModel): capital: str currency: str with Router() as router: response = router.responses.parse( model="openai/gpt-6-luna", input="What is the capital of France, and its currency code?", text_format=Country, ) country = response.output_parsed if country is not None: print(country.capital, country.currency) ``` ```rust use schemars::JsonSchema; use serde::Deserialize; use tokedex::{Router, wire}; #[derive(Deserialize, JsonSchema)] struct Country { capital: String, currency: String, } #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let request = wire::ResponsesRequest::new( "openai/gpt-6-luna", "What is the capital of France, and its currency code?", ); let response = router.responses().parse::(request).await?; if let Some(country) = response.output_parsed { println!("{} {}", country.capital, country.currency); } Ok(()) } ``` **Gemini GenerateContent** ```ts import { Router } from '@tokedex/sdk'; import { z } from 'zod'; const Country = z.object({ capital: z.string(), currency: z.string() }); const router = new Router(); const response = await router.responses.parse({ model: 'google/gemini-3.5-flash-lite', input: 'What is the capital of France, and its currency code?', textFormat: Country, }); const country = response.outputParsed; if (country !== null) console.log(country.capital, country.currency); ``` ```python from pydantic import BaseModel from tokedex import Router class Country(BaseModel): capital: str currency: str with Router() as router: response = router.responses.parse( model="google/gemini-3.5-flash-lite", input="What is the capital of France, and its currency code?", text_format=Country, ) country = response.output_parsed if country is not None: print(country.capital, country.currency) ``` ```rust use schemars::JsonSchema; use serde::Deserialize; use tokedex::{Router, wire}; #[derive(Deserialize, JsonSchema)] struct Country { capital: String, currency: String, } #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let request = wire::ResponsesRequest::new( "google/gemini-3.5-flash-lite", "What is the capital of France, and its currency code?", ); let response = router.responses().parse::(request).await?; if let Some(country) = response.output_parsed { println!("{} {}", country.capital, country.currency); } Ok(()) } ``` **OpenAI Chat Completions** ```ts import { Router } from '@tokedex/sdk'; import { z } from 'zod'; const Country = z.object({ capital: z.string(), currency: z.string() }); const router = new Router(); const completion = await router.chat.completions.create({ model: 'openai/gpt-6-luna', messages: [{ role: 'user', content: 'What is the capital of France, and its currency code?' }], response_format: { type: 'json_schema', json_schema: { name: 'country', strict: true, schema: { type: 'object', properties: { capital: { type: 'string' }, currency: { type: 'string' } }, required: ['capital', 'currency'], additionalProperties: false, }, }, }, }); const country = Country.parse(JSON.parse(completion.choices[0]?.message.content ?? '')); console.log(country.capital, country.currency); ``` ```python from pydantic import BaseModel from tokedex import Router class Country(BaseModel): capital: str currency: str with Router() as router: completion = router.chat.completions.create( model="openai/gpt-6-luna", messages=[ {"role": "user", "content": "What is the capital of France, and its currency code?"} ], response_format={ "type": "json_schema", "json_schema": { "name": "country", "strict": True, "schema": { "type": "object", "properties": {"capital": {"type": "string"}, "currency": {"type": "string"}}, "required": ["capital", "currency"], "additionalProperties": False, }, }, }, ) country = Country.model_validate_json(completion.choices[0].message.content or "") print(country.capital, country.currency) ``` ```rust use serde::Deserialize; use serde_json::json; use tokedex::{Router, wire}; #[derive(Deserialize)] struct Country { capital: String, currency: String, } #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let request: wire::ChatCompletionsRequest = serde_json::from_value(json!({ "model": "openai/gpt-6-luna", "messages": [{ "role": "user", "content": "What is the capital of France, and its currency code?" }], "response_format": { "type": "json_schema", "json_schema": { "name": "country", "strict": true, "schema": { "type": "object", "properties": { "capital": { "type": "string" }, "currency": { "type": "string" } }, "required": ["capital", "currency"], "additionalProperties": false, }, }, }, }))?; let completion = router.chat().completions().create(request).await?; if let Some(wire::Content::Text(text)) = &completion.choices[0].message.content { let country: Country = serde_json::from_str(text)?; println!("{} {}", country.capital, country.currency); } Ok(()) } ``` **Anthropic Messages** ```ts import { Router } from '@tokedex/sdk'; import { z } from 'zod'; const Country = z.object({ capital: z.string(), currency: z.string() }); const router = new Router(); const message = await router.messages.create({ model: 'openai/gpt-6-luna', messages: [{ role: 'user', content: 'What is the capital of France, and its currency code?' }], output_config: { format: { type: 'json_schema', schema: { type: 'object', properties: { capital: { type: 'string' }, currency: { type: 'string' } }, required: ['capital', 'currency'], additionalProperties: false, }, }, }, }); const text = message.content.flatMap((block) => (block.type === 'text' ? [block.text] : [])).join(''); const country = Country.parse(JSON.parse(text)); console.log(country.capital, country.currency); ``` ```python from pydantic import BaseModel from tokedex import Router class Country(BaseModel): capital: str currency: str with Router() as router: message = router.messages.create( model="openai/gpt-6-luna", messages=[ {"role": "user", "content": "What is the capital of France, and its currency code?"} ], output_config={ "format": { "type": "json_schema", "schema": { "type": "object", "properties": {"capital": {"type": "string"}, "currency": {"type": "string"}}, "required": ["capital", "currency"], "additionalProperties": False, }, } }, ) text = "".join(block.text for block in message.content if block.type == "text") country = Country.model_validate_json(text) print(country.capital, country.currency) ``` ```rust use serde::Deserialize; use serde_json::json; use tokedex::{Router, wire}; #[derive(Deserialize)] struct Country { capital: String, currency: String, } #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let request: wire::MessagesRequest = serde_json::from_value(json!({ "model": "openai/gpt-6-luna", "messages": [{ "role": "user", "content": "What is the capital of France, and its currency code?" }], "output_config": { "format": { "type": "json_schema", "schema": { "type": "object", "properties": { "capital": { "type": "string" }, "currency": { "type": "string" } }, "required": ["capital", "currency"], "additionalProperties": false, }, }, }, }))?; let message = router.messages().create(request).await?; let text: String = message .content .iter() .filter_map(|block| match block { wire::ContentBlock::Text { text, .. } => Some(text.as_str()), _ => None, }) .collect(); let country: Country = serde_json::from_str(&text)?; println!("{} {}", country.capital, country.currency); Ok(()) } ``` ```text Paris EUR ``` It needs `OPENAI_API_KEY` (Gemini GenerateContent: `GEMINI_API_KEY`), and the call is billed by OpenAI (Gemini GenerateContent: Google). **TypeScript** Install Zod 4 with `npm install zod@4`. **Python** The SDK installs pydantic. **Rust** Add `cargo add schemars@0.8 serde --features serde/derive` (OpenAI Chat Completions, Anthropic Messages: `cargo add serde serde_json --features serde/derive`). **Gemini GenerateContent** GenerateContent's own fields, `responseMimeType` with `responseJsonSchema` or an OpenAPI `responseSchema`, ask the model for matching JSON, but leave your code to check it. The typed helper, which writes the schema from your type and checks the reply in one call, is on OpenAI Responses. So call the Gemini model there, as here, and `parse` (Rust: `parse()`) does the rest. **OpenAI Chat Completions, Anthropic Messages** The API's own schema field asks the model for matching JSON, and your code checks it. The typed helper, which does both in one call, is on OpenAI Responses. If you can choose the API for this call, use that helper, because it writes the schema from your type, so the two cannot drift apart. Otherwise keep a check like the one in the sample on every reply: the Router returns the text as the model wrote it. **OpenAI Responses, Gemini GenerateContent** The schema must be an object that strict JSON Schema can express. Every field is required, so make a field that can be empty nullable. A map of arbitrary keys, a field of any type and a recursive type are refused before anything is sent. Run each new type once while you develop, so a refused schema shows up then, at no cost. `parse` (Rust: `parse()`) does not stream, and it sets `text.format` itself, so a request that also sets `text.format` fails. **Python · OpenAI Responses, Gemini GenerateContent** ```python from pydantic import BaseModel class Answer(BaseModel): comment: str | None ``` Use `Answer` as `text_format` to require `comment` and allow it to be `None`. Adding `= None` makes the field optional, so `parse()` rejects the schema before sending a request. **Rust · OpenAI Responses, Gemini GenerateContent** For a required nullable field such as `comment: Option`, add `#[schemars(schema_with = "tokedex::nullable_schema::")]`. This keeps the field in the schema and allows a JSON `null` value. **OpenAI Chat Completions** With `strict: true`, list every property in `required` and set `additionalProperties` to `false`. **Anthropic Messages** The schema's top-level `type` must be `object`, and `output_config.format` takes only `json_schema`. ## Replies with nothing to parse **OpenAI Responses, Gemini GenerateContent** `outputParsed` (Python, Rust: `output_parsed`) is `null` (Python, Rust: `None`) when the model refused, answered only with tool calls, or stopped early, for example at `max_output_tokens`. The refusal or the calls are in `output`, and a reply that stopped early has the status `incomplete`. Handle `null` (Python, Rust: `None`) as an expected outcome, and give `max_output_tokens` room for the whole object, because JSON cut off at the limit has nothing to parse. **Rust · OpenAI Responses, Gemini GenerateContent** The whole reply is in `response.response`. **OpenAI Chat Completions** Parse `content` only when `finish_reason` is `stop`: `length` means the JSON was cut off, and `tool_calls` means the model asked for a tool instead. When the model refuses, `content` is `null` (Python, Rust: `None`) and `message.refusal` says why. After a `length`, raise `max_completion_tokens` before you send again, since a retry under the same limit can be cut off the same way. **Anthropic Messages** Parse the text only when `stop_reason` is `end_turn`: `max_tokens` means the JSON was cut off, and `tool_use` means the model asked for a tool instead. After a `max_tokens`, raise `max_tokens` in the request before you send again, since a retry under the same limit can be cut off the same way. ## Replies that do not match the schema **OpenAI Responses, Gemini GenerateContent** ```ts import { StructuredOutputError } from '@tokedex/sdk'; const Country = z.object({ capital: z.string(), currency: z.string() }); try { await router.responses.parse({ model: 'openai/gpt-6-luna', input: 'Describe France.', textFormat: Country }); } catch (error) { if (!(error instanceof StructuredOutputError)) throw error; console.error(error.message); } ``` ```python from pydantic import BaseModel, ValidationError class Country(BaseModel): capital: str currency: str try: router.responses.parse(model="openai/gpt-6-luna", input="Describe France.", text_format=Country) except ValidationError as error: print(error) ``` ```rust use schemars::JsonSchema; use serde::Deserialize; use tokedex::{Error, wire}; #[derive(Deserialize, JsonSchema)] struct Country { capital: String, currency: String, } let request = wire::ResponsesRequest::new("openai/gpt-6-luna", "Describe France."); match router.responses().parse::(request).await { Err(Error::StructuredOutput(error)) => eprintln!("{error}"), other => println!("{}", other?.response.status), } ``` **OpenAI Responses, Gemini GenerateContent** If the reply is invalid JSON or fails schema validation, the call raises `StructuredOutputError` (Python: `ValidationError`; Rust: `Error::StructuredOutput`) without sending another request. Provider and network failures still follow the Router's [retry and fallback policy](/sdk/errors-and-retries#retries-and-provider-fallback). If you retry a validation failure yourself, cap the attempts because each can incur another charge. **OpenAI Chat Completions, Anthropic Messages** The check in the opening sample fails on invalid JSON at `JSON.parse` (Python: `model_validate_json`; Rust: `serde_json::from_str`) and on a schema mismatch at `Country.parse` (Python: `model_validate_json`; Rust: `serde_json::from_str`). Your check runs after the Router returns the reply, so validation failures do not trigger another request. The Router's [retry and fallback policy](/sdk/errors-and-retries#retries-and-provider-fallback) applies to provider and network failures before you receive the reply. If you retry a validation failure yourself, cap the attempts because each can incur another charge. ## Use a model from another provider **OpenAI Responses, Gemini GenerateContent** ```ts const Country = z.object({ capital: z.string(), currency: z.string() }); const response = await router.responses.parse({ model: 'anthropic/claude-haiku-5.5', input: 'What is the capital of France, and its currency code?', textFormat: Country, }); ``` ```python from pydantic import BaseModel class Country(BaseModel): capital: str currency: str response = router.responses.parse( model="anthropic/claude-haiku-5.5", input="What is the capital of France, and its currency code?", text_format=Country, ) ``` ```rust use schemars::JsonSchema; use serde::Deserialize; use tokedex::wire; #[derive(Deserialize, JsonSchema)] struct Country { capital: String, currency: String, } let request = wire::ResponsesRequest::new( "anthropic/claude-haiku-5.5", "What is the capital of France, and its currency code?", ); let response = router.responses().parse::(request).await?; ``` Change the model ID and nothing else. The Router asks Anthropic for JSON that matches the schema in Anthropic's own terms, and `parse` (Rust: `parse()`) checks the answer as before. A [custom model](/sdk/custom-models) works with `parse` (Rust: `parse()`) only when you declare it with the OpenAI Responses protocol. Through a gateway, `parse` (Rust: `parse()`) works the same: the gateway receives an ordinary Responses request, and the SDK checks the reply. See [Run through a gateway](/sdk/gateway). **OpenAI Chat Completions, Anthropic Messages** Change `model` in the opening sample to `anthropic/claude-haiku-5.5` (Anthropic Messages: `google/gemini-3.5-flash-lite`) and nothing else. The Router passes your schema to Anthropic (Anthropic Messages: Google) in that provider's own structured-output field, and your check runs as before. Next: [Generate text](/sdk/generate-text). --- # Images and files Send an image or a file with your prompt and ask the model about it, in your API's own image and file fields. **OpenAI Responses** ```ts import { Router } from '@tokedex/sdk'; const router = new Router(); const response = await router.responses.create({ model: 'openai/gpt-6-luna', input: [ { type: 'message', role: 'user', content: [ { type: 'input_image', image_url: 'https://example.com/chart.png' }, { type: 'input_text', text: 'What does this chart show? Answer in one sentence.' }, ], }, ], }); const text = response.output .flatMap((item) => (item.type === 'message' ? item.content : [])) .flatMap((part) => (part.type === 'output_text' ? [part.text] : [])) .join(''); console.log(text); ``` ```python from tokedex import Router with Router() as router: response = router.responses.create( model="openai/gpt-6-luna", input=[ { "type": "message", "role": "user", "content": [ {"type": "input_image", "image_url": "https://example.com/chart.png"}, { "type": "input_text", "text": "What does this chart show? Answer in one sentence.", }, ], } ], ) print(response.output_text) ``` ```rust use serde_json::json; use tokedex::{Router, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let request: wire::ResponsesRequest = serde_json::from_value(json!({ "model": "openai/gpt-6-luna", "input": [{ "type": "message", "role": "user", "content": [ { "type": "input_image", "image_url": "https://example.com/chart.png" }, { "type": "input_text", "text": "What does this chart show? Answer in one sentence." }, ], }], }))?; let response = router.responses().create(request).await?; println!("{}", response.output_text()); Ok(()) } ``` **OpenAI Chat Completions** ```ts import { Router } from '@tokedex/sdk'; const router = new Router(); const completion = await router.chat.completions.create({ model: 'openai/gpt-6-luna', messages: [ { role: 'user', content: [ { type: 'image_url', image_url: { url: 'https://example.com/chart.png' } }, { type: 'text', text: 'What does this chart show? Answer in one sentence.' }, ], }, ], }); console.log(completion.choices[0]?.message.content); ``` ```python from tokedex import Router with Router() as router: completion = router.chat.completions.create( model="openai/gpt-6-luna", messages=[ { "role": "user", "content": [ {"type": "image_url", "image_url": {"url": "https://example.com/chart.png"}}, {"type": "text", "text": "What does this chart show? Answer in one sentence."}, ], } ], ) print(completion.choices[0].message.content) ``` ```rust use serde_json::json; use tokedex::{Router, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let request: wire::ChatCompletionsRequest = serde_json::from_value(json!({ "model": "openai/gpt-6-luna", "messages": [{ "role": "user", "content": [ { "type": "image_url", "image_url": { "url": "https://example.com/chart.png" } }, { "type": "text", "text": "What does this chart show? Answer in one sentence." }, ], }], }))?; let completion = router.chat().completions().create(request).await?; if let Some(wire::Content::Text(text)) = &completion.choices[0].message.content { println!("{text}"); } Ok(()) } ``` **Anthropic Messages** ```ts import { Router } from '@tokedex/sdk'; const router = new Router(); const message = await router.messages.create({ model: 'openai/gpt-6-luna', messages: [ { role: 'user', content: [ { type: 'image', source: { type: 'url', url: 'https://example.com/chart.png' } }, { type: 'text', text: 'What does this chart show? Answer in one sentence.' }, ], }, ], }); const text = message.content.flatMap((block) => (block.type === 'text' ? [block.text] : [])).join(''); console.log(text); ``` ```python from tokedex import Router with Router() as router: message = router.messages.create( model="openai/gpt-6-luna", messages=[ { "role": "user", "content": [ {"type": "image", "source": {"type": "url", "url": "https://example.com/chart.png"}}, {"type": "text", "text": "What does this chart show? Answer in one sentence."}, ], } ], ) print("".join(block.text for block in message.content if block.type == "text")) ``` ```rust use serde_json::json; use tokedex::{Router, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let request: wire::MessagesRequest = serde_json::from_value(json!({ "model": "openai/gpt-6-luna", "messages": [{ "role": "user", "content": [ { "type": "image", "source": { "type": "url", "url": "https://example.com/chart.png" } }, { "type": "text", "text": "What does this chart show? Answer in one sentence." }, ], }], }))?; let message = router.messages().create(request).await?; for block in &message.content { if let wire::ContentBlock::Text { text, .. } = block { println!("{text}"); } } Ok(()) } ``` **Gemini GenerateContent** ```ts import { Router } from '@tokedex/sdk'; const router = new Router(); const result = await router.generateContent.create({ model: 'google/gemini-3.5-flash-lite', contents: [ { role: 'user', parts: [ { fileData: { mimeType: 'image/png', fileUri: 'https://example.com/chart.png' } }, { text: 'What does this chart show? Answer in one sentence.' }, ], }, ], }); for (const part of result.candidates?.[0]?.content?.parts ?? []) { if ('text' in part) console.log(part.text); } ``` ```python from tokedex import Router with Router() as router: result = router.generate_content.create( model="google/gemini-3.5-flash-lite", contents=[ { "role": "user", "parts": [ {"fileData": {"mimeType": "image/png", "fileUri": "https://example.com/chart.png"}}, {"text": "What does this chart show? Answer in one sentence."}, ], } ], ) print("".join(getattr(part, "text", "") for part in result.candidates[0].content.parts)) ``` ```rust use serde_json::json; use tokedex::{Router, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let request: wire::GeminiRequest = serde_json::from_value(json!({ "contents": [{ "role": "user", "parts": [ { "fileData": { "mimeType": "image/png", "fileUri": "https://example.com/chart.png" } }, { "text": "What does this chart show? Answer in one sentence." }, ], }], }))?; let result = router.generate_content().create("google/gemini-3.5-flash-lite", request).await?; let candidates = result.candidates.unwrap_or_default(); if let Some(content) = candidates.first().and_then(|candidate| candidate.content.as_ref()) { for part in &content.parts { if let Some(text) = part["text"].as_str() { println!("{text}"); } } } Ok(()) } ``` ```text The chart shows sales rising each quarter. ``` **TypeScript · OpenAI Responses, OpenAI Chat Completions, Anthropic Messages** It needs `OPENAI_API_KEY`, and the call is billed by OpenAI. Run it with `npx tsx images.ts`. **Python · OpenAI Responses, OpenAI Chat Completions, Anthropic Messages** It needs `OPENAI_API_KEY`, and the call is billed by OpenAI. **Rust · OpenAI Responses, OpenAI Chat Completions, Anthropic Messages** It needs `OPENAI_API_KEY`, and the call is billed by OpenAI. Add `cargo add serde_json` to write the request as JSON. **TypeScript · Gemini GenerateContent** It needs `GEMINI_API_KEY`, and the call is billed by Google. Run it with `npx tsx images.ts`. **Python · Gemini GenerateContent** It needs `GEMINI_API_KEY`, and the call is billed by Google. **Rust · Gemini GenerateContent** It needs `GEMINI_API_KEY`, and the call is billed by Google. Add `cargo add serde_json` to write the request as JSON. **OpenAI Responses** The image goes in an `input_image` part next to your question. `image_url` takes a URL or a base64 data URL. **OpenAI Chat Completions** The message's `content` becomes a list of parts: an `image_url` part and a `text` part with your question. **Anthropic Messages** The image goes in an `image` block whose `source` is a URL, base64 data or a file ID. **Gemini GenerateContent** The image goes in a `fileData` part with its `mimeType` next to a `text` part. Google reads the `fileUri` itself. ## Send an image from a local file **OpenAI Responses, OpenAI Chat Completions** Encode the file as base64 and send it as a data URL, `data:;base64,`, in the same field as a URL. ```ts import { readFile } from 'node:fs/promises'; const chart = `data:image/png;base64,${(await readFile('chart.png')).toString('base64')}`; const completion = await router.chat.completions.create({ model: 'openai/gpt-6-luna', messages: [ { role: 'user', content: [ { type: 'image_url', image_url: { url: chart } }, { type: 'text', text: 'Describe this image in one sentence.' }, ], }, ], }); ``` ```python import base64 from pathlib import Path chart = "data:image/png;base64," + base64.b64encode(Path("chart.png").read_bytes()).decode() completion = router.chat.completions.create( model="openai/gpt-6-luna", messages=[ { "role": "user", "content": [ {"type": "image_url", "image_url": {"url": chart}}, {"type": "text", "text": "Describe this image in one sentence."}, ], } ], ) ``` ```rust use base64::Engine; use serde_json::json; use tokedex::wire; let data = base64::engine::general_purpose::STANDARD.encode(std::fs::read("chart.png")?); let request: wire::ChatCompletionsRequest = serde_json::from_value(json!({ "model": "openai/gpt-6-luna", "messages": [{ "role": "user", "content": [ { "type": "image_url", "image_url": { "url": format!("data:image/png;base64,{data}") } }, { "type": "text", "text": "Describe this image in one sentence." }, ], }], }))?; let completion = router.chat().completions().create(request).await?; ``` **OpenAI Responses** This is the Chat Completions form; on your API, put the same data URL in `input_image`'s `image_url`. **Anthropic Messages** ```ts import { readFile } from 'node:fs/promises'; const message = await router.messages.create({ model: 'openai/gpt-6-luna', messages: [ { role: 'user', content: [ { type: 'image', source: { type: 'base64', media_type: 'image/png', data: (await readFile('chart.png')).toString('base64') }, }, { type: 'text', text: 'Describe this image in one sentence.' }, ], }, ], }); ``` ```python import base64 from pathlib import Path data = base64.b64encode(Path("chart.png").read_bytes()).decode() message = router.messages.create( model="openai/gpt-6-luna", messages=[ { "role": "user", "content": [ {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": data}}, {"type": "text", "text": "Describe this image in one sentence."}, ], } ], ) ``` ```rust use base64::Engine; use serde_json::json; use tokedex::wire; let data = base64::engine::general_purpose::STANDARD.encode(std::fs::read("chart.png")?); let request: wire::MessagesRequest = serde_json::from_value(json!({ "model": "openai/gpt-6-luna", "messages": [{ "role": "user", "content": [ { "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": data } }, { "type": "text", "text": "Describe this image in one sentence." }, ], }], }))?; let message = router.messages().create(request).await?; ``` Send plain base64 in `data`, without a `data:` prefix, and the file's type in `media_type`. **Gemini GenerateContent** ```ts import { readFile } from 'node:fs/promises'; const result = await router.generateContent.create({ model: 'google/gemini-3.5-flash-lite', contents: [ { role: 'user', parts: [ { inlineData: { mimeType: 'image/png', data: (await readFile('chart.png')).toString('base64') } }, { text: 'Describe this image in one sentence.' }, ], }, ], }); ``` ```python import base64 from pathlib import Path data = base64.b64encode(Path("chart.png").read_bytes()).decode() result = router.generate_content.create( model="google/gemini-3.5-flash-lite", contents=[ { "role": "user", "parts": [ {"inlineData": {"mimeType": "image/png", "data": data}}, {"text": "Describe this image in one sentence."}, ], } ], ) ``` ```rust use base64::Engine; use serde_json::json; use tokedex::wire; let data = base64::engine::general_purpose::STANDARD.encode(std::fs::read("chart.png")?); let request: wire::GeminiRequest = serde_json::from_value(json!({ "contents": [{ "role": "user", "parts": [ { "inlineData": { "mimeType": "image/png", "data": data } }, { "text": "Describe this image in one sentence." }, ], }], }))?; let result = router.generate_content().create("google/gemini-3.5-flash-lite", request).await?; ``` An `inlineData` part takes plain base64 in `data`, without a `data:` prefix, and the file's type in `mimeType`. **Rust** Add `cargo add base64` to encode the file. ## Send a PDF or another file **OpenAI Responses** ```ts const response = await router.responses.create({ model: 'openai/gpt-6-luna', input: [ { type: 'message', role: 'user', content: [ { type: 'input_file', file_url: 'https://example.com/report.pdf' }, { type: 'input_text', text: 'Summarise this report in three bullet points.' }, ], }, ], }); ``` ```python response = router.responses.create( model="openai/gpt-6-luna", input=[ { "type": "message", "role": "user", "content": [ {"type": "input_file", "file_url": "https://example.com/report.pdf"}, {"type": "input_text", "text": "Summarise this report in three bullet points."}, ], } ], ) ``` ```rust use serde_json::json; use tokedex::wire; let request: wire::ResponsesRequest = serde_json::from_value(json!({ "model": "openai/gpt-6-luna", "input": [{ "type": "message", "role": "user", "content": [ { "type": "input_file", "file_url": "https://example.com/report.pdf" }, { "type": "input_text", "text": "Summarise this report in three bullet points." }, ], }], }))?; let response = router.responses().create(request).await?; ``` An `input_file` part takes the file by URL in `file_url`. For a local file, send a base64 data URL, such as `data:application/pdf;base64,…`, in `file_data`, with the file's name in `filename` so the model knows what it reads. **OpenAI Chat Completions** ```ts import { readFile } from 'node:fs/promises'; const report = `data:application/pdf;base64,${(await readFile('report.pdf')).toString('base64')}`; const completion = await router.chat.completions.create({ model: 'openai/gpt-6-luna', messages: [ { role: 'user', content: [ { type: 'file', file: { file_data: report, filename: 'report.pdf' } }, { type: 'text', text: 'Summarise this report in three bullet points.' }, ], }, ], }); ``` ```python import base64 from pathlib import Path report = "data:application/pdf;base64," + base64.b64encode(Path("report.pdf").read_bytes()).decode() completion = router.chat.completions.create( model="openai/gpt-6-luna", messages=[ { "role": "user", "content": [ {"type": "file", "file": {"file_data": report, "filename": "report.pdf"}}, {"type": "text", "text": "Summarise this report in three bullet points."}, ], } ], ) ``` ```rust use base64::Engine; use serde_json::json; use tokedex::wire; let data = base64::engine::general_purpose::STANDARD.encode(std::fs::read("report.pdf")?); let request: wire::ChatCompletionsRequest = serde_json::from_value(json!({ "model": "openai/gpt-6-luna", "messages": [{ "role": "user", "content": [ { "type": "file", "file": { "file_data": format!("data:application/pdf;base64,{data}"), "filename": "report.pdf" } }, { "type": "text", "text": "Summarise this report in three bullet points." }, ], }], }))?; let completion = router.chat().completions().create(request).await?; ``` A `file` part takes the file as a base64 data URL in `file_data`. Give it a `filename`, so the model knows what it reads. Chat Completions has no URL field for a file. Download the file yourself, or use OpenAI Responses or Anthropic Messages. **Anthropic Messages** ```ts const message = await router.messages.create({ model: 'openai/gpt-6-luna', messages: [ { role: 'user', content: [ { type: 'document', source: { type: 'url', url: 'https://example.com/report.pdf' } }, { type: 'text', text: 'Summarise this report in three bullet points.' }, ], }, ], }); ``` ```python message = router.messages.create( model="openai/gpt-6-luna", messages=[ { "role": "user", "content": [ {"type": "document", "source": {"type": "url", "url": "https://example.com/report.pdf"}}, {"type": "text", "text": "Summarise this report in three bullet points."}, ], } ], ) ``` ```rust use serde_json::json; use tokedex::wire; let request: wire::MessagesRequest = serde_json::from_value(json!({ "model": "openai/gpt-6-luna", "messages": [{ "role": "user", "content": [ { "type": "document", "source": { "type": "url", "url": "https://example.com/report.pdf" } }, { "type": "text", "text": "Summarise this report in three bullet points." }, ], }], }))?; let message = router.messages().create(request).await?; ``` A PDF goes in a `document` block, whose `source` takes the same three forms as an image's. **Gemini GenerateContent** ```ts const result = await router.generateContent.create({ model: 'google/gemini-3.5-flash-lite', contents: [ { role: 'user', parts: [ { fileData: { mimeType: 'application/pdf', fileUri: 'https://example.com/report.pdf' } }, { text: 'Summarise this report in three bullet points.' }, ], }, ], }); ``` ```python result = router.generate_content.create( model="google/gemini-3.5-flash-lite", contents=[ { "role": "user", "parts": [ {"fileData": {"mimeType": "application/pdf", "fileUri": "https://example.com/report.pdf"}}, {"text": "Summarise this report in three bullet points."}, ], } ], ) ``` ```rust use serde_json::json; use tokedex::wire; let request: wire::GeminiRequest = serde_json::from_value(json!({ "contents": [{ "role": "user", "parts": [ { "fileData": { "mimeType": "application/pdf", "fileUri": "https://example.com/report.pdf" } }, { "text": "Summarise this report in three bullet points." }, ], }], }))?; let result = router.generate_content().create("google/gemini-3.5-flash-lite", request).await?; ``` A file takes the same parts as an image, with the file's own `mimeType`: `fileData` by URL, or `inlineData` for a local file. ## Send a file the provider already stores **OpenAI Responses** ```ts const response = await router.responses.create({ model: 'openai/gpt-6-luna', input: [ { type: 'message', role: 'user', content: [ { type: 'input_file', file_id: 'file-abc123' }, { type: 'input_text', text: 'Summarise this report in three bullet points.' }, ], }, ], }); ``` ```python response = router.responses.create( model="openai/gpt-6-luna", input=[ { "type": "message", "role": "user", "content": [ {"type": "input_file", "file_id": "file-abc123"}, {"type": "input_text", "text": "Summarise this report in three bullet points."}, ], } ], ) ``` ```rust use serde_json::json; use tokedex::wire; let request: wire::ResponsesRequest = serde_json::from_value(json!({ "model": "openai/gpt-6-luna", "input": [{ "type": "message", "role": "user", "content": [ { "type": "input_file", "file_id": "file-abc123" }, { "type": "input_text", "text": "Summarise this report in three bullet points." }, ], }], }))?; let response = router.responses().create(request).await?; ``` `input_image` takes `file_id` the same way. **OpenAI Chat Completions** ```ts const completion = await router.chat.completions.create({ model: 'openai/gpt-6-luna', messages: [ { role: 'user', content: [ { type: 'file', file: { file_id: 'file-abc123' } }, { type: 'text', text: 'Summarise this report in three bullet points.' }, ], }, ], }); ``` ```python completion = router.chat.completions.create( model="openai/gpt-6-luna", messages=[ { "role": "user", "content": [ {"type": "file", "file": {"file_id": "file-abc123"}}, {"type": "text", "text": "Summarise this report in three bullet points."}, ], } ], ) ``` ```rust use serde_json::json; use tokedex::wire; let request: wire::ChatCompletionsRequest = serde_json::from_value(json!({ "model": "openai/gpt-6-luna", "messages": [{ "role": "user", "content": [ { "type": "file", "file": { "file_id": "file-abc123" } }, { "type": "text", "text": "Summarise this report in three bullet points." }, ], }], }))?; let completion = router.chat().completions().create(request).await?; ``` The Router reads the ID as an OpenAI file. **Anthropic Messages** ```ts const message = await router.messages.create({ model: 'anthropic/claude-haiku-5.5', messages: [ { role: 'user', content: [ { type: 'document', source: { type: 'file', file_id: 'file_abc123' } }, { type: 'text', text: 'Summarise this report in three bullet points.' }, ], }, ], }); ``` ```python message = router.messages.create( model="anthropic/claude-haiku-5.5", messages=[ { "role": "user", "content": [ {"type": "document", "source": {"type": "file", "file_id": "file_abc123"}}, {"type": "text", "text": "Summarise this report in three bullet points."}, ], } ], ) ``` ```rust use serde_json::json; use tokedex::wire; let request: wire::MessagesRequest = serde_json::from_value(json!({ "model": "anthropic/claude-haiku-5.5", "messages": [{ "role": "user", "content": [ { "type": "document", "source": { "type": "file", "file_id": "file_abc123" } }, { "type": "text", "text": "Summarise this report in three bullet points." }, ], }], }))?; let message = router.messages().create(request).await?; ``` The Router reads the ID as an Anthropic file, so the model here is Anthropic's. **OpenAI Responses, OpenAI Chat Completions, Anthropic Messages** Send the ID the provider issued when you uploaded the file. The Router sends the call only to that provider and the one account whose key can read the file, with no fallback to another. A file ID fails before anything is sent when the model reaches no account that can read it, or more than one. Use a file ID only for a file you upload once and send in many requests to that provider. For anything else, send a URL or the data, so that a failed attempt can still move to another provider or account. **Gemini GenerateContent** Put the URI that Google's Files API returned in `fileUri`, with the file's `mimeType`, as in the last section. Upload the file with the key the Router uses, `GEMINI_API_KEY`, so Google lets the call read it. ## URLs the Router downloads **OpenAI Responses, OpenAI Chat Completions, Anthropic Messages** Some providers read an image or a PDF only as data inside the request. When the model you call is served by one of them, the Router downloads each `https` URL from your process and sends the bytes instead. It connects only to public addresses, follows at most five redirects, gives up after 30 seconds, and reads at most 16 URLs per request and 12 MB per file. A URL it cannot read fails the call with a `DocumentInputError` (Rust: `RouterError::DocumentInput`) before the provider is called. Send a file on a private network or behind a sign-in as data, not as a URL. The Router connects only to public addresses, so such a URL fails whenever the model's provider needs the bytes. **Gemini GenerateContent** On GenerateContent the Router never downloads a URL: Google reads each `fileUri` itself, and the Router passes it on unchanged. On the other three APIs, the Router downloads a URL for a provider that reads images and PDFs only as data inside the request. So send a file that only your own network can reach as `inlineData`, not as a `fileUri`: Google, not your process, has to read the URI. **Python, Rust** The files the Router downloads for one request may total 12 MB. **TypeScript** The files the Router downloads for one request may total 16 MiB. To send those downloads through your own network code, pass `documentFetch` when you create the Router. It must connect only to public addresses and must not follow redirects itself. **Python** To send those downloads through your own network code, pass an `httpx2` transport as `fetch_document` when you create the Router. **Rust** To send those downloads through your own network code, pass your transport to the builder's `document_transport`. ## Check whether a model accepts an image or a file Send the request. A model that cannot take an image or a file refuses it before anything is sent, so nothing is billed. **TypeScript** The refusal is a `GatewayError` with `kind` `CapabilityUnsupported`. **Python** The refusal is a `FidelityError`, from `tokedex.core.ir`, that names the image or file part. **Rust** The refusal is `RouterError::FidelityError` inside `tokedex::Error::Router`, and it names the image or file part. Before you move a feature that sends images or files to a new model, send it one such request, so you learn before release whether the model takes the input. A refusal costs nothing. A [router](/gateway/router#built-in-routers) tries only the models that accept the input, so call one when any capable model will do. `router.models.list()` (Rust: `router.models().list()`) does not say which inputs a model takes. [Custom models](/sdk/custom-models) take text and function tools only, so they refuse every image and file. Next: [Structured output](/sdk/structured-output), [Choose a model](/sdk/models) or [Errors, retries and timeouts](/sdk/errors-and-retries). --- # Conversations Ask a follow-up question that the model answers with the earlier turns in mind. **OpenAI Responses** ```ts import { Router } from '@tokedex/sdk'; const router = new Router(); const first = await router.responses.create({ model: 'openai/gpt-6-luna', input: 'My name is Ada.' }); const second = await router.responses.create({ model: 'openai/gpt-6-luna', previous_response_id: first.id, input: 'What is my name?', }); for (const item of second.output) { if (item.type !== 'message') continue; for (const part of item.content) if (part.type === 'output_text') console.log(part.text); } ``` ```python from tokedex import Router with Router() as router: first = router.responses.create(model="openai/gpt-6-luna", input="My name is Ada.") second = router.responses.create( model="openai/gpt-6-luna", previous_response_id=first.id, input="What is my name?" ) print(second.output_text) ``` ```rust use tokedex::{Router, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let first = router.responses().create(wire::ResponsesRequest::new("openai/gpt-6-luna", "My name is Ada.")).await?; let mut next = wire::ResponsesRequest::new("openai/gpt-6-luna", "What is my name?"); next.previous_response_id = wire::Presence::Value(first.id); let second = router.responses().create(next).await?; println!("{}", second.output_text()); Ok(()) } ``` **OpenAI Chat Completions** ```ts import { Router, type ChatCompletionRequest } from '@tokedex/sdk'; const router = new Router(); const history: ChatCompletionRequest['messages'] = [{ role: 'user', content: 'My name is Ada.' }]; const first = await router.chat.completions.create({ model: 'openai/gpt-6-luna', messages: history }); const second = await router.chat.completions.create({ model: 'openai/gpt-6-luna', messages: [...history, first.choices[0]!.message, { role: 'user', content: 'What is my name?' }], }); console.log(second.choices[0]?.message.content); ``` ```python from typing import Any from tokedex import Router with Router() as router: history: list[Any] = [{"role": "user", "content": "My name is Ada."}] first = router.chat.completions.create(model="openai/gpt-6-luna", messages=history) history.append(first.choices[0].message.model_dump(exclude_none=True)) history.append({"role": "user", "content": "What is my name?"}) second = router.chat.completions.create(model="openai/gpt-6-luna", messages=history) print(second.choices[0].message.content) ``` ```rust use tokedex::{Router, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let mut history = vec![wire::Message::user("My name is Ada.")]; let first = router.chat().completions().create(wire::ChatCompletionsRequest::new("openai/gpt-6-luna", history.clone())).await?; history.push(first.choices[0].message.clone()); history.push(wire::Message::user("What is my name?")); let second = router.chat().completions().create(wire::ChatCompletionsRequest::new("openai/gpt-6-luna", history)).await?; if let Some(wire::Content::Text(text)) = &second.choices[0].message.content { println!("{text}"); } Ok(()) } ``` **Anthropic Messages** ```ts import { Router, type MessageRequest } from '@tokedex/sdk'; const router = new Router(); const history: MessageRequest['messages'] = [{ role: 'user', content: 'My name is Ada.' }]; const first = await router.messages.create({ model: 'openai/gpt-6-luna', messages: history }); const second = await router.messages.create({ model: 'openai/gpt-6-luna', messages: [...history, { role: 'assistant', content: first.content }, { role: 'user', content: 'What is my name?' }], }); for (const block of second.content) if (block.type === 'text') console.log(block.text); ``` ```python from typing import Any from tokedex import Router with Router() as router: history: list[Any] = [{"role": "user", "content": "My name is Ada."}] first = router.messages.create(model="openai/gpt-6-luna", messages=history) reply = [block.model_dump(exclude_none=True) for block in first.content] history.append({"role": "assistant", "content": reply}) history.append({"role": "user", "content": "What is my name?"}) second = router.messages.create(model="openai/gpt-6-luna", messages=history) print("".join(block.text for block in second.content if block.type == "text")) ``` ```rust use tokedex::{Router, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let ask = |history: Vec| wire::MessagesRequest::new("openai/gpt-6-luna", history); let mut history = vec![wire::Message::user("My name is Ada.")]; let first = router.messages().create(ask(history.clone())).await?; history.push(wire::Message::assistant(wire::Content::Blocks(first.content))); history.push(wire::Message::user("What is my name?")); let second = router.messages().create(ask(history)).await?; for block in &second.content { if let wire::ContentBlock::Text { text, .. } = block { println!("{text}"); } } Ok(()) } ``` **Gemini GenerateContent** ```ts import { Router, type GeminiRequest } from '@tokedex/sdk'; const router = new Router(); const model = 'google/gemini-3.5-flash-lite'; const history: GeminiRequest['contents'] = [{ role: 'user', parts: [{ text: 'My name is Ada.' }] }]; const first = await router.generateContent.create({ model, contents: history }); const reply = first.candidates?.[0]?.content; const second = await router.generateContent.create({ model, contents: [...history, ...(reply ? [reply] : []), { role: 'user', parts: [{ text: 'What is my name?' }] }], }); for (const part of second.candidates?.[0]?.content?.parts ?? []) if ('text' in part) console.log(part.text); ``` ```python from typing import Any from tokedex import Router with Router() as router: history: list[Any] = [{"role": "user", "parts": [{"text": "My name is Ada."}]}] first = router.generate_content.create(model="google/gemini-3.5-flash-lite", contents=history) history.append(first.model_dump(exclude_none=True)["candidates"][0]["content"]) history.append({"role": "user", "parts": [{"text": "What is my name?"}]}) second = router.generate_content.create(model="google/gemini-3.5-flash-lite", contents=history) for candidate in second.candidates or []: print("".join(getattr(part, "text", "") for part in candidate.content.parts)) ``` ```rust use serde_json::{Value, json}; use tokedex::{Router, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let model = "google/gemini-3.5-flash-lite"; let ask = |history: &[Value]| serde_json::from_value::(json!({ "contents": history })); let mut history = vec![json!({ "role": "user", "parts": [{ "text": "My name is Ada." }] })]; let first = router.generate_content().create(model, ask(&history)?).await?; history.push(serde_json::to_value(&first)?["candidates"][0]["content"].clone()); history.push(json!({ "role": "user", "parts": [{ "text": "What is my name?" }] })); let second = serde_json::to_value(router.generate_content().create(model, ask(&history)?).await?)?; for part in second["candidates"][0]["content"]["parts"].as_array().into_iter().flatten() { println!("{}", part["text"].as_str().unwrap_or_default()); } Ok(()) } ``` ```text Your name is Ada. ``` It needs `OPENAI_API_KEY` (Gemini GenerateContent: `GEMINI_API_KEY`), and each call is billed by OpenAI (Gemini GenerateContent: Google). **OpenAI Responses** The Router stored the first turn, so the second request sends only the new input and the first reply's `id` as `previous_response_id`. **OpenAI Chat Completions, Anthropic Messages, Gemini GenerateContent** your API keeps nothing between calls, so the second request carries the whole conversation: the first message, the model's reply and the new question. Send each reply back as it arrived. Some providers put state the next call needs into the reply, such as Gemini's thought signatures. **Rust · Gemini GenerateContent** Add `cargo add serde_json` to write the request as JSON. ## Conversation lifetime **OpenAI Responses** You can continue a turn for 24 hours, unless its request set `store: false`. The Router keeps its record of each turn in memory, so the turns end with the process; set `ttlMs` (Python, Rust: `ttl_ms`) in the continuation options below to change the 24 hours. A turn continues only on the same model and the same provider account. A missing, expired or foreign turn fails with a `GatewayError` of kind `PreviousResponseNotFound`. Create one Router and reuse it for every turn: by default each Router keeps its stored turns in its own memory, so a new Router cannot find them. A restart ends every conversation too; when conversations must survive restarts, run through a gateway or give the Router the shared stores below. To keep the history yourself instead, set `store: false` and send the earlier turns, including each reply's `output` items, in `input`. Do this when a conversation must move to another model, or outlive the process without the shared stores below, since a stored turn continues only on its own model and, by default, only in memory. **OpenAI Chat Completions, Anthropic Messages, Gemini GenerateContent** A conversation lasts as long as you keep the history. The Router stores nothing for your API, so save each turn where your application keeps its data and send it all with every request. If you want the Router to keep the turns for you, write against OpenAI Responses instead: it is the only API whose turns the Router stores. Because every request carries the whole conversation, the prompt grows with each turn. [Count the tokens](/sdk/generate-text#count-tokens-before-sending) of a long conversation before you send it, so it does not outgrow the model's context window. `runTools` (Python, Rust: `run_tools`) keeps nothing between calls: pass the conversation in its messages. ## Share a conversation between processes **TypeScript · OpenAI Responses** Give every Router the same shared stores in `continuation`: a `store`, a `leaseStore` and an `ownerKey`, backed by your own database. Routers with the same owner key continue each other's turns. The `store` implements `ReservableResponseContinuationStore` from `@tokedex/engine` (`get`, `put` and `reserveWrite`), and the lease store implements `ContinuationLeaseStore` from `@tokedex/sdk` (`put`, `resolve` and `consume`). **Python · OpenAI Responses** Give every Router the same shared stores in `continuation`: a `store`, a `lease_store` and an `owner_key`, backed by your own database. Routers with the same owner key continue each other's turns. The `store` implements `ReservableResponseContinuationStore` from `tokedex.engine` (`get`, `reserve`, `renew`, `release` and `commit`), and the lease store implements `ContinuationLeaseStore` from `tokedex.core.ir` (`put`, `resolve` and `consume`). **Rust · OpenAI Responses** Give every Router the same shared stores with `Router::builder().continuation(…)`: a `store`, a `lease_store` and an `owner_key`, backed by your own database. Routers with the same owner key continue each other's turns. The `store` implements `tokedex::router::ResponseContinuationStore` (`get`, `reserve`, `renew`, `release` and `put`), and the lease store implements `tokedex_core::continuation::ContinuationLeaseStore` (`put`, `resolve` and `consume`). **OpenAI Chat Completions, Anthropic Messages, Gemini GenerateContent** Load the history from your own database in any process and send it. The Router needs nothing else. **OpenAI Responses** The default in-memory store holds up to 4,096 turns per owner, subject to a 64 MiB per-owner byte limit. Each stored turn, including replay history and routing metadata, must fit in 1,500,000 UTF-8 bytes. A request can fit and still exceed this limit once the provider has answered. In gateway mode this returns HTTP 413 with code `continuation_too_large`. When a shared store does not answer, or the call outlives its hold on the stored turn, the call fails with the kind `ServiceUnavailable` (Python: `Unavailable`; Rust: `Conflict`). Python and Rust fail with `Conflict` when another call is continuing the same turn. Send the request again. ## Through a gateway **OpenAI Responses** The gateway stores the turns instead of your process, so any process with the same API key can continue them. See [Run through a gateway](/sdk/gateway). When several processes must share conversations, start with a gateway before you build shared stores of your own, because it gives you that sharing with no store code. **OpenAI Chat Completions, Anthropic Messages, Gemini GenerateContent** Nothing changes: you still send the whole history with each request. See [Run through a gateway](/sdk/gateway). Next: [Stream a reply](/sdk/streaming) or [Run through a gateway](/sdk/gateway). --- # Batch jobs Run many independent requests as one job on the provider's own Batch API, for work that does not need an answer right away. **OpenAI Responses** ```ts import { Router } from '@tokedex/sdk'; const router = new Router(); const job = await router.batches.create({ model: 'openai/gpt-6-luna', operation: 'responses', items: [ { customId: 'france', body: { input: 'Name the capital of France in one word.' } }, { customId: 'japan', body: { input: 'Name the capital of Japan in one word.' } }, ], }); // Store job.id: it is the only way back to this job. console.log(job.native.status); ``` ```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="france", body={"input": "Name the capital of France in one word."}), BatchItem(custom_id="japan", body={"input": "Name the capital of Japan in one word."}), ], ) # Store job.id: it is the only way back to this job. print(job.native.get("status")) ``` ```rust use serde_json::json; use tokedex::{BatchItem, BatchOperation, BatchSubmission, Router}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let submission = BatchSubmission { model: "openai/gpt-6-luna".into(), operation: BatchOperation::Responses, items: vec![ BatchItem { custom_id: "france".into(), body: json!({ "input": "Name the capital of France in one word." }) }, BatchItem { custom_id: "japan".into(), body: json!({ "input": "Name the capital of Japan in one word." }) }, ], client_dialect_id: None, }; let job = router.batches().create(&submission, Default::default()).await?; // Store job.id: it is the only way back to this job. println!("{}", job.native.get("status").and_then(|status| status.as_str()).unwrap_or_default()); Ok(()) } ``` ```text validating ``` **OpenAI Chat Completions** ```ts import { Router } from '@tokedex/sdk'; const router = new Router(); const job = await router.batches.create({ model: 'openai/gpt-6-luna', operation: 'chat.completions', items: [ { customId: 'france', body: { messages: [{ role: 'user', content: 'Name the capital of France in one word.' }] } }, { customId: 'japan', body: { messages: [{ role: 'user', content: 'Name the capital of Japan in one word.' }] } }, ], }); // Store job.id: it is the only way back to this job. console.log(job.native.status); ``` ```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="chat.completions", items=[ BatchItem( custom_id=country, body={"messages": [{"role": "user", "content": f"Name the capital of {name} in one word."}]}, ) for country, name in [("france", "France"), ("japan", "Japan")] ], ) # Store job.id: it is the only way back to this job. print(job.native.get("status")) ``` ```rust use serde_json::json; use tokedex::{BatchItem, BatchOperation, BatchSubmission, Router}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let ask = |country: &str| json!({ "messages": [{ "role": "user", "content": format!("Name the capital of {country} in one word.") }] }); let submission = BatchSubmission { model: "openai/gpt-6-luna".into(), operation: BatchOperation::ChatCompletions, items: vec![ BatchItem { custom_id: "france".into(), body: ask("France") }, BatchItem { custom_id: "japan".into(), body: ask("Japan") }, ], client_dialect_id: None, }; let job = router.batches().create(&submission, Default::default()).await?; // Store job.id: it is the only way back to this job. println!("{}", job.native.get("status").and_then(|status| status.as_str()).unwrap_or_default()); Ok(()) } ``` ```text validating ``` **Anthropic Messages** ```ts import { Router } from '@tokedex/sdk'; const router = new Router(); const ask = (country: string) => ({ // Anthropic's Batch API requires max_tokens on every item. max_tokens: 128000, messages: [{ role: 'user', content: `Name the capital of ${country} in one word.` }], }); const job = await router.batches.create({ model: 'anthropic/claude-haiku-5.5', operation: 'messages', items: [ { customId: 'france', body: ask('France') }, { customId: 'japan', body: ask('Japan') }, ], }); // Store job.id: it is the only way back to this job. console.log(job.native.processing_status); ``` ```python from tokedex import Router from tokedex.sdk.batch import BatchItem with Router() as router: job = router.batches.create( model="anthropic/claude-haiku-5.5", operation="messages", items=[ BatchItem( custom_id=country, body={ # Anthropic's Batch API requires max_tokens on every item. "max_tokens": 128000, "messages": [{"role": "user", "content": f"Name the capital of {name} in one word."}], }, ) for country, name in [("france", "France"), ("japan", "Japan")] ], ) # Store job.id: it is the only way back to this job. print(job.native.get("processing_status")) ``` ```rust use serde_json::json; use tokedex::{BatchItem, BatchOperation, BatchSubmission, Router}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let ask = |country: &str| json!({ // Anthropic's Batch API requires max_tokens on every item. "max_tokens": 128000, "messages": [{ "role": "user", "content": format!("Name the capital of {country} in one word.") }], }); let submission = BatchSubmission { model: "anthropic/claude-haiku-5.5".into(), operation: BatchOperation::Messages, items: vec![ BatchItem { custom_id: "france".into(), body: ask("France") }, BatchItem { custom_id: "japan".into(), body: ask("Japan") }, ], client_dialect_id: None, }; let job = router.batches().create(&submission, Default::default()).await?; // Store job.id: it is the only way back to this job. let status = job.native.get("processing_status").and_then(|status| status.as_str()); println!("{}", status.unwrap_or_default()); Ok(()) } ``` ```text in_progress ``` **Gemini GenerateContent** ```ts import { Router } from '@tokedex/sdk'; const router = new Router(); const ask = (country: string) => ({ contents: [{ role: 'user', parts: [{ text: `Name the capital of ${country} in one word.` }] }], }); const job = await router.batches.create({ model: 'google/gemini-3.5-flash-lite', operation: 'generateContent', items: [ { customId: 'france', body: ask('France') }, { customId: 'japan', body: ask('Japan') }, ], }); // Store job.id: it is the only way back to this job. console.log((job.native.metadata as { state?: string } | undefined)?.state); ``` ```python from tokedex import Router from tokedex.sdk.batch import BatchItem with Router() as router: job = router.batches.create( model="google/gemini-3.5-flash-lite", operation="generateContent", items=[ BatchItem( custom_id=country, body={ "contents": [ {"role": "user", "parts": [{"text": f"Name the capital of {name} in one word."}]} ] }, ) for country, name in [("france", "France"), ("japan", "Japan")] ], ) # Store job.id: it is the only way back to this job. metadata = job.native.get("metadata") print(metadata.get("state") if isinstance(metadata, dict) else None) ``` ```rust use serde_json::json; use tokedex::{BatchItem, BatchOperation, BatchSubmission, Router}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let ask = |country: &str| json!({ "contents": [{ "role": "user", "parts": [{ "text": format!("Name the capital of {country} in one word.") }] }], }); let submission = BatchSubmission { model: "google/gemini-3.5-flash-lite".into(), operation: BatchOperation::GenerateContent, items: vec![ BatchItem { custom_id: "france".into(), body: ask("France") }, BatchItem { custom_id: "japan".into(), body: ask("Japan") }, ], client_dialect_id: None, }; let job = router.batches().create(&submission, Default::default()).await?; // Store job.id: it is the only way back to this job. let state = job.native.get("metadata").and_then(|metadata| metadata["state"].as_str()); println!("{}", state.unwrap_or_default()); Ok(()) } ``` ```text BATCH_STATE_PENDING ``` **OpenAI Responses, OpenAI Chat Completions** It needs `OPENAI_API_KEY`. The job runs at OpenAI and is billed at its Batch prices. **Anthropic Messages** It needs `ANTHROPIC_API_KEY`. The job runs at Anthropic and is billed at its Batch prices. **Gemini GenerateContent** It needs `GEMINI_API_KEY`. The job runs at Google and is billed at its Batch prices. **Rust** Add `cargo add serde_json` to write each body as JSON. Each item has a unique `customId` (Python, Rust: `custom_id`) and a `body` in the format `operation` names, without `model`. `job.native` is the provider's own reply, so its fields differ between providers. Every item must be an independent, non-streaming request. If submission returns `502` with `batch_provider_error`, the provider may have accepted the job before the reply was lost. Check the provider's console or Batch API and resubmit only after you confirm the first job was never created. Submitting twice can create two jobs, each billed at the provider's Batch prices. The model's provider decides `operation`: a job runs on that provider's own Batch API, untranslated. So `openai/gpt-6-luna` (Anthropic Messages: `anthropic/claude-haiku-5.5`; Gemini GenerateContent: `google/gemini-3.5-flash-lite`) takes your API items here, whichever API the rest of your code uses. Use a Batch job for many requests whose answers can wait. Keep ordinary calls when someone waits for the answer or a request needs an earlier reply, because Batch items cannot stream or continue a conversation. Save the job ID somewhere durable as soon as the job is created: no call lists your jobs, so the ID is the only way back to one. **Anthropic Messages** Give Anthropic items custom IDs of letters, digits, `_` and `-`, at most 64 characters, or the whole job is refused before it is sent. A job can be pinned to providers, as a single call can ([Pin a provider](/sdk/models#pin-a-provider)): pass `providers` in [[the second argument of router.batches.create|options=BatchCallOptions(providers=[...]) to router.batches.create|the BatchCallOptions of router.batches().create]]. The job is submitted only to a named provider. When none of them can run it, nothing is submitted and the call fails with [[`ProviderNotServedError`|`ProviderNotServedError`|`BatchClientError::ProviderNotServed`]], whose `providers` lists the ones that can. An embedded Router uses its default `providers` list for Batch creation unless the request supplies its own list. A job can prefer providers too ([Order the providers](/sdk/models#order-the-providers)): pass [[`providerOrder`|`provider_order`|`provider_order`]] in the same options, and the job is submitted to the first named provider that can run it. Without one, the Router's order for the model applies. Batch submissions are never retried in place. ## List models that run Batch jobs ```ts for (const model of await router.models.list()) { for (const batch of model.native_batch ?? []) { if (batch.available) console.log(model.id, model.client_dialect_id, batch.operation); } } ``` ```python for model in router.models.list(): for batch in model.native_batch: if batch.available: print(model.id, model.client_dialect_id, batch.operation) ``` ```rust for model in router.models().list().await? { for batch in model.native_batch.unwrap_or_default() { if batch.available { println!("{} {} {:?}", model.id, model.client_dialect_id, batch.operation); } } } ``` Check `native_batch` before submitting a model's first job. It lists each `operation` and its reviewed `status` (`supported`, `unsupported` or `unverified`). The SDK and gateway use the catalogue to select the endpoint for that operation. Listing models makes no provider request. A supported operation is `available` when your setup can submit it. If it is unavailable, read `unavailableReason` (Python, Rust: `unavailable_reason`). For `credentials-unavailable`, set the provider's key. For `batch-configuration-unavailable`, check for a matching endpoint and any required [Batch settings](#provider-batch-settings). For other reasons, choose another model. The gateway also checks your key's Batch access. The provider can still refuse a job if your provider account lacks Batch access. When a model lists the `operation` only on another API's row, pass that row's `client_dialect_id` as `clientDialectId` (Python, Rust: `client_dialect_id`). ## Check a job ```ts const current = await router.batches.retrieve(''); console.log(current.native); ``` ```python current = router.batches.retrieve("") print(current.native) ``` ```rust let current = router.batches().retrieve("", Default::default()).await?; println!("{:?}", current.native); ``` Pass the ID you stored, and repeat until the provider has finished. **OpenAI Responses, OpenAI Chat Completions** OpenAI has finished when `status` is `completed`, `failed`, `expired` or `cancelled`. **Anthropic Messages** Anthropic has finished when `processing_status` is `ended`. **Gemini GenerateContent** Google has finished when `done` is `true`. ## Read the results ```ts const result = await router.batches.results(''); if (result.kind === 'file') console.log(await result.response.text()); else if (result.kind === 'inline') console.log(result.data); else console.log(result.urls); ``` ```python from tokedex.sdk.batch import BatchFileResult, BatchInlineResult result = router.batches.results("") if isinstance(result, BatchFileResult): for line in result.response.iter_lines(): print(line) elif isinstance(result, BatchInlineResult): print(result.data) else: print(result.urls) ``` ```rust use tokedex::{BatchResult, StreamExt}; match router.batches().results("", Default::default()).await? { BatchResult::File { mut response } => { while let Some(chunk) = response.body.next().await { print!("{}", String::from_utf8_lossy(&chunk?)); } } BatchResult::Inline { data } => println!("{data}"), BatchResult::Downloads { urls } => println!("{urls:?}"), } ``` The results come in the provider's form: a JSON Lines file to read to the end, inline records, or signed download links. For the error file, pass `{ file: 'errors' }` (Python: `file="errors"`; Rust: `BatchResultOptions { file: Some(BatchFile::Errors), .. }`). Providers delete results on their own schedule, so read them early. TypeScript exposes native Batch integers outside the safe `number` range as `bigint` in job metadata and inline results. Pass a `bigint` in an item body to send an exact JSON integer, for example `9007199254740993n` in a tool argument. The gateway preserves the integer digits in its HTTP response. Rust's default JSON representation keeps integers from `i64::MIN` through `u64::MAX` exact. For wider integer tokens in Batch requests or results, enable the `arbitrary-precision` feature of `tokedex`. This activates `serde_json/arbitrary_precision` throughout the Rust dependency graph. In that mode, `serde_json` reserves the object key `$serde_json::private::Number` when it appears first in an object. **OpenAI Responses, OpenAI Chat Completions** An OpenAI job has an error file next to its output file, so read both, or items that failed go unnoticed. ## Cancel a job ```ts const cancelled = await router.batches.cancel(''); ``` ```python cancelled = router.batches.cancel("") ``` ```rust let cancelled = router.batches().cancel("", Default::default()).await?; ``` It returns the job with the provider's status in `native`. ## Reopen a job from another process The job ID is sealed with a receipt key, and only a Router with the same key and owner key opens it. The SDK creates the key on first use in a private file that every process you run as the same user shares: `$XDG_STATE_HOME/tokedex/batch-receipt.key`, `~/.local/state/tokedex/batch-receipt.key` on macOS and Linux, or `%LOCALAPPDATA%\tokedex\batch-receipt.key` on Windows. Back it up. ```ts import { Router } from '@tokedex/sdk'; const shared = new Router({ batch: { receiptSecret: process.env['BATCH_SECRET']!, ownerKey: 'team-a' }, }); ``` ```python import os from tokedex import Router shared = Router(batch_receipt_secret=os.environ["BATCH_SECRET"], batch_owner_key="team-a") ``` ```rust use tokedex::{Router, RouterOptions}; let shared = Router::new(RouterOptions { batch_receipt_secret: Some(std::env::var("BATCH_SECRET")?), batch_owner: Some("team-a".into()), ..Default::default() })?; ``` Across machines, or in containers without a persistent disk, give every process the same long random secret, here or in `TOKEDEX_BATCH_RECEIPT_SECRET`; the option wins over the variable, and both over the file. Set it before the first job, because a job ID opens only under the key that sealed it, and a later change strands earlier jobs. A job opens only under the owner key that submitted it, `embedded` by default. A job ID works for 30 days, under the same receipt key and owner key, and while the model's provider settings stay the same. [Through a gateway](/sdk/gateway), the same calls run on the gateway, which holds the provider keys and the receipt key. This needs a gateway started from a configuration file, which the Helm chart and the published image do not run. ## Provider Batch settings | Provider | Setting | Value | |---|---|---| | Fireworks | `batch.fireworksAccountId` (Python, Rust: `fireworks_account_id`) | The Fireworks account that owns the job's datasets | | Xiaomi | `batch.xiaomiBatchOrigin` (Python, Rust: `xiaomi_batch_origin`) | The regional Batch origin from your Xiaomi console | Set it when you create the Router, as with the receipt secret. ## Batch errors A failed call raises `BatchClientError` (Rust: `BatchClientError::Response`), with an HTTP-style `status` and a `code`: | `status` | `code` | Cause | |---|---|---| | `400` | `invalid_request` | The submission is invalid. | | `400` | `batch_unsupported` | No provider of the model takes Batch jobs for this request. | | `404` | `model_not_found` | The model is unknown, or its provider has no key. | | `404` | `batch_not_found` | The job ID is unknown or expired. | | `404` | `batch_file_unavailable` | That result file does not exist. | | `409` | `batch_results_unavailable` | The results are not ready. | | `501` | `batch_cancel_unavailable` | The provider cannot cancel jobs, such as Fireworks. | | `502` | `batch_provider_error` | The provider's reply was invalid, or the call failed another way. | Through a gateway, `status` and `code` are the gateway's own. Next: [Run through a gateway](/sdk/gateway), [Choose a model](/sdk/models) or [Errors, retries and timeouts](/sdk/errors-and-retries). --- # Choose a model See every model your keys let you call, on which API, and how much each one can read. ```ts import { Router } from '@tokedex/sdk'; const router = new Router(); const rows = await router.models.list(); for (const row of rows) { if (row.id === 'openai/gpt-6-luna') console.log(row.id, row.client_dialect_id, row.context_window); } ``` ```python from tokedex import Router with Router() as router: for row in router.models.list(): if row.id == "openai/gpt-6-luna": print(row.id, row.client_dialect_id, row.context_window) ``` ```rust use tokedex::Router; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; for row in router.models().list().await? { if row.id == "openai/gpt-6-luna" { println!("{} {} {}", row.id, row.client_dialect_id, row.context_window.unwrap_or_default()); } } Ok(()) } ``` ```text openai/gpt-6-luna anthropic.messages 1050000 openai/gpt-6-luna openai.chat-completions 1050000 openai/gpt-6-luna openai.responses 1050000 ``` It needs `OPENAI_API_KEY`. Listing sends nothing to a provider, so it costs nothing. ## Model row fields `router.models.list()` (Rust: `router.models().list()`) returns one row for each model and API you can call it on, so `openai/gpt-6-luna` has three. - `id`: the model ID to send. - `client_dialect_id`: the API the row is for. - `context_window` and `max_input_tokens`: how many tokens the model reads, when known. - `native_batch`: the [Batch](/sdk/batch) operations the model supports, and whether each is ready with your keys. - `provider_ids`: the providers the call can be served by now, the values [`providers`](#pin-a-provider) can name. The list holds the built-in models and [routers](#routers) whose provider has a key, then your [custom models](/sdk/custom-models). A custom model's row carries only `id`, `client_dialect_id` and `trust`, which is `unreviewed`. A custom model takes text and function tools only: one on your own server on the one API it speaks, and one from a provider on all three, the others translated to its provider's API. Through a gateway, the list shows the models that gateway serves, and its administrator chooses them; see [Run through a gateway](/sdk/gateway). ## APIs for each model | `client_dialect_id` | Call it on | |---|---| | `openai.responses` | `router.responses` (Rust: `router.responses()`) | | `openai.chat-completions` | `router.chat.completions` (Rust: `router.chat().completions()`) | | `anthropic.messages` | `router.messages` (Rust: `router.messages()`) | | `google.generate-content` | `router.generateContent` (Python: `router.generate_content`; Rust: `router.generate_content()`) | Most models have rows for OpenAI Responses, OpenAI Chat Completions and Anthropic Messages, whichever API their provider speaks: the Router translates the request and the reply, as [Translation between APIs](/sdk/translation) explains. A few are served on one API only. Gemini GenerateContent takes Google's Gemini and Gemma models. A call on an API the model has no row for fails with `NotFound`. ## Routers ```ts const response = await router.responses.create({ model: 'aa/fastest', input: 'Name the capital of France in one word.', }); ``` ```python response = router.responses.create( model="aa/fastest", input="Name the capital of France in one word." ) ``` ```rust use tokedex::wire; let request = wire::ResponsesRequest::new("aa/fastest", "Name the capital of France in one word."); let response = router.responses().create(request).await?; ``` A model ID that starts with `aa/` is a router: it chooses a model for each request. `aa/fastest` ranks eligible models by benchmarked time per task. It uses only the providers you have keys for, and the reply's `model` stays `aa/fastest`; to see which model answered, watch the call with an [observer](/sdk/observability). [Routers and fallback](/gateway/router#built-in-routers) lists each router and how it chooses. Use a model ID such as `openai/gpt-6-luna` when every answer must come from one model, as in an evaluation or a prompt tuned to that model. Use a router when any of its models will do and the call should survive one of them failing. Set keys for more of its providers to give it more models to move to. ## Order the providers ```ts const completion = await router.chat.completions.create( { model: '', messages: [{ role: 'user', content: 'Reply with exactly the word "hello".' }] }, { providerOrder: ['', ''], onServed: (served) => console.log('served by', served.provider) }, ); console.log(completion.choices[0]?.message.content); ``` ```python completion = router.chat.completions.create( model="", messages=[{"role": "user", "content": 'Reply with exactly the word "hello".'}], provider_order=["", ""], on_served=lambda served: print("served by", served.provider), ) print(completion.choices[0].message.content) ``` ```rust use tokedex::{RequestOptions, wire}; let ordered = router.with_options( RequestOptions::default() .provider_order(["", ""]) .on_served(|served| println!("served by {}", served.provider)), ); let messages = vec![wire::Message::user(r#"Reply with exactly the word "hello"."#)]; let completion = ordered.chat().completions().create(wire::ChatCompletionsRequest::new("", messages)).await?; println!("{:?}", completion.choices.first().map(|choice| &choice.message.content)); ``` When several providers serve a model, the Router tries them in the model's provider order, and moves to the next when one fails with a rate limit, an outage or a timeout. The catalogue orders them by list price, cheapest first, then the model maker's own provider, then provider ID; a gateway operator can set another order. `providerOrder` puts the providers you name first, in your order, and the rest follow in the model's order. It is a preference: a named provider that does not serve the model, or has no key, is skipped. Give the Router a default order for each model as [[`providerOrder: { '': [''] }` in its options|`provider_order={"": [""]}` when you create it|`Router::builder().provider_order("", [""])`]]. It applies to calls that name that exact model ID, and a call's own order replaces it. Start with the default order, which already prefers the cheapest provider, and set your own when a provider answers your prompts faster or better. - **Unknown IDs.** An ID that is not a provider here is refused with `BadRequest` naming `x-tokedex-provider-order`, before anything is sent; take IDs from the model's `provider_ids`. - **Option and header.** A call may also send the `x-tokedex-provider-order` header. If it names a different order from [[`providerOrder`|`provider_order`|`provider_order`]], the call is refused locally, so set one or the other. - **Follow-up turns.** A request that continues a conversation, such as one carrying an assistant turn or a tool result, tries the same provider up to three times, waiting briefly between tries, before it moves to the next. The provider then reuses its prompt cache for the conversation, which makes the turn cheaper and faster. A follow-up turn that carries state only that provider accepts never moves to another one, and ignores the order ([Pin a provider](#pin-a-provider)). - **Waits and timeouts.** A provider can ask for a longer wait before the next try. The Router waits up to 10 seconds, and moves to the next provider at once when asked for longer. With a [timeout](/sdk/errors-and-retries#set-a-timeout) set as [[`timeoutMs`|`timeout_ms`|`RequestOptions::timeout`]], it also moves on at once when the wait is longer than the time left. [[A `signal` from `AbortSignal.timeout(ms)` cannot tell the Router how long is left, so set `timeoutMs` instead.|A `cancel` token sets no time limit, so set `timeout_ms` as well.|A cancellation token sets no time limit, so set `timeout` as well.]] ## Pin a provider When several providers serve a model, the Router tries them in the model's [provider order](#order-the-providers). To choose instead, name the providers allowed to serve the call in `providers`. Only those are tried, in the call's provider order; the order you list them in `providers` does not rank them. When none of them can serve the call, it fails with `ProviderNotServedError`, whose `providers` lists the ones that can, and nothing is sent. `onServed` (Python, Rust: `on_served`) hears which provider served, once, before the result or the first stream event. `router.models.retrieve(id)` (Rust: `router.models().retrieve(id)`) lists a model's providers, each with its own model ID, context window, reasoning efforts and Batch support, and how it picks among them. For a particular client API's routing, use [[`router.models.retrieve(id, { clientDialectId: 'openai.responses' })`|`router.models.retrieve(id, client_dialect_id="openai.responses")`|`router.models().retrieve_for_dialect(id, "openai.responses")`]]. Take the dialect ID from the model's list row. An unavailable row returns a not-found error. ```ts import { ProviderNotServedError, Router } from '@tokedex/sdk'; const router = new Router(); const detail = await router.models.retrieve(''); console.log(detail.provider_ids, detail.routing?.strategy); try { const completion = await router.chat.completions.create( { model: detail.id, messages: [{ role: 'user', content: 'Reply with exactly the word "hello".' }] }, { providers: [''], onServed: (served) => console.log('served by', served.provider) }, ); console.log(completion.choices[0]?.message.content); } catch (error) { if (!(error instanceof ProviderNotServedError)) throw error; console.log('Providers that can serve it:', error.providers); } ``` ```python from tokedex import ProviderNotServedError, Router with Router() as router: detail = router.models.retrieve("") print(detail.provider_ids, detail.routing.strategy if detail.routing else None) try: completion = router.chat.completions.create( model=detail.id, messages=[{"role": "user", "content": 'Reply with exactly the word "hello".'}], providers=[""], on_served=lambda served: print("served by", served.provider), ) print(completion.choices[0].message.content) except ProviderNotServedError as error: print("Providers that can serve it:", error.providers) ``` ```rust use tokedex::{Error, RequestOptions, Router, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let detail = router.models().retrieve("").await?; println!("{:?} {:?}", detail.model.provider_ids, detail.routing.map(|routing| routing.strategy)); let pinned = router.with_options( RequestOptions::default() .providers([""]) .on_served(|served| println!("served by {}", served.provider)), ); let messages = vec![wire::Message::user(r#"Reply with exactly the word "hello"."#)]; match pinned.chat().completions().create(wire::ChatCompletionsRequest::new(detail.model.id, messages)).await { Ok(completion) => println!("{:?}", completion.choices.first().map(|choice| &choice.message.content)), Err(Error::ProviderNotServed(refused)) => println!("Providers that can serve it: {:?}", refused.providers), Err(error) => return Err(error.into()), } Ok(()) } ``` The pin applies the same way to streaming, token counting, tool runs and [Batch](/sdk/batch) jobs. A follow-up turn that carries state only the provider that answered accepts, such as a stored response, signed reasoning or signed tool calls, stays with that provider; a pin that leaves it out fails with `ProviderNotServedError` naming that provider. Any other follow-up turn follows the provider order, retrying each provider before it moves to the next. Through a gateway, `providers` travels as the `x-tokedex-provider` header, and a call that also sets that header is allowed only the providers both name; see [Choose a provider](/gateway/models#choose-a-provider). ## Check what a model accepts - **Length.** `context_window` and `max_input_tokens` give the most tokens the model reads. Check them before you send a long conversation, so you can shorten it yourself rather than have the provider fail the call with `ContextWindowExceeded`. - **Images and files.** The list does not say. Send the request: a model that cannot read the input refuses it before anything is sent, so nothing is charged. A router tries only its models that accept the input. See [Images and files](/sdk/images-and-files). **TypeScript** The refusal is a `GatewayError` with kind `CapabilityUnsupported`. **Python** The refusal raises `FidelityError` from `tokedex.core.ir`, whose `issues` name the input, such as `input.image`. **Rust** The refusal is `tokedex::Error::Router` holding `RouterError::FidelityError`, whose `issues` name the input, such as `input.image`. ## Read the whole model list response ```ts const discovery = await router.models.discover(); console.log(discovery.data.length, discovery.models.length); ``` ```python discovery = router.models.discover() print(len(discovery.data), len(discovery.models)) ``` ```rust let discovery = router.models().discover().await?; println!("{} {}", discovery.data.len(), discovery.models.len()); ``` `data` holds the rows that `router.models.list()` (Rust: `router.models().list()`) returns. `models` holds the same rows, except custom and unreviewed models, as profiles for coding agents such as Codex, with `context_window`, `max_context_window` and `auto_compact_token_limit` where they are known. Choose models in your own code from `data`, or from `router.models.list()` (Rust: `router.models().list()`), and use `models` only to configure a coding agent, because `models` leaves your custom models out. Next: [Translation between APIs](/sdk/translation), [Provider keys](/sdk/provider-keys) or [Custom models](/sdk/custom-models). --- # Translation between APIs Send a request in the API you use to a model whose provider speaks another, and choose what happens to a field that has no equivalent there. **OpenAI Responses** ```ts import { Router } from '@tokedex/sdk'; const router = new Router(); await router.responses.create( { model: 'google/gemini-3.5-flash-lite', input: 'Name the capital of France in one word.', prompt_cache_key: 'geography', }, { fidelity: 'best_effort', onFidelityDecision: (decision) => { for (const change of decision.degradations) console.log(change.path, change.code); }, }, ); ``` ```python from tokedex import Router from tokedex.core.ir import FidelityDecision def report(decision: FidelityDecision) -> None: for change in decision.degradations: print(change.path, change.code) with Router() as router: router.responses.create( model="google/gemini-3.5-flash-lite", input="Name the capital of France in one word.", prompt_cache_key="geography", fidelity="best_effort", on_fidelity_decision=report, ) ``` ```rust use std::sync::Arc; use serde_json::json; use tokedex::{FidelityDecision, FidelityPolicy, RequestOptions, Router, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?.with_options(RequestOptions { fidelity: Some(FidelityPolicy::BestEffort), on_fidelity_decision: Some(Arc::new(|decision: FidelityDecision| { for change in decision.degradations { println!("{} {}", change.path, change.code); } })), ..Default::default() }); let request: wire::ResponsesRequest = serde_json::from_value(json!({ "model": "google/gemini-3.5-flash-lite", "input": "Name the capital of France in one word.", "prompt_cache_key": "geography", }))?; router.responses().create(request).await?; Ok(()) } ``` ```text $.promptCache provider.degradation.google.prompt_cache_hint_omitted ``` It needs `GEMINI_API_KEY`, and the call is billed by Google. Google's API has no prompt cache key, so the Router left `prompt_cache_key` out, sent the rest and reported the change. **OpenAI Chat Completions** ```ts import { Router } from '@tokedex/sdk'; const router = new Router(); await router.chat.completions.create( { model: 'anthropic/claude-haiku-5.5', messages: [{ role: 'user', content: 'How many users signed up today?' }], tools: [{ type: 'custom', custom: { name: 'run_sql', description: 'Run one SQL query.' } }], }, { fidelity: 'best_effort', onFidelityDecision: (decision) => { for (const change of decision.degradations) console.log(change.path, change.code); }, }, ); ``` ```python from tokedex import Router from tokedex.core.ir import FidelityDecision def report(decision: FidelityDecision) -> None: for change in decision.degradations: print(change.path, change.code) with Router() as router: router.chat.completions.create( model="anthropic/claude-haiku-5.5", messages=[{"role": "user", "content": "How many users signed up today?"}], tools=[{"type": "custom", "custom": {"name": "run_sql", "description": "Run one SQL query."}}], fidelity="best_effort", on_fidelity_decision=report, ) ``` ```rust use std::sync::Arc; use serde_json::json; use tokedex::{FidelityDecision, FidelityPolicy, RequestOptions, Router, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?.with_options(RequestOptions { fidelity: Some(FidelityPolicy::BestEffort), on_fidelity_decision: Some(Arc::new(|decision: FidelityDecision| { for change in decision.degradations { println!("{} {}", change.path, change.code); } })), ..Default::default() }); let request: wire::ChatCompletionsRequest = serde_json::from_value(json!({ "model": "anthropic/claude-haiku-5.5", "messages": [{ "role": "user", "content": "How many users signed up today?" }], "tools": [{ "type": "custom", "custom": { "name": "run_sql", "description": "Run one SQL query." } }], }))?; router.chat().completions().create(request).await?; Ok(()) } ``` ```text $.tools provider.degradation.anthropic.custom_tool_as_string_function ``` It needs `ANTHROPIC_API_KEY`, and the call is billed by Anthropic. Anthropic Messages has no free-form custom tool, so the Router sent `run_sql` as a function that takes one string, and reported the change. **Anthropic Messages** ```ts import { Router } from '@tokedex/sdk'; const router = new Router(); await router.messages.create( { model: 'google/gemini-3.5-flash-lite', system: [{ type: 'text', text: 'Answer in one word.', cache_control: { type: 'ephemeral' } }], messages: [{ role: 'user', content: 'Name the capital of France.' }], }, { fidelity: 'best_effort', onFidelityDecision: (decision) => { for (const change of decision.degradations) console.log(change.path, change.code); }, }, ); ``` ```python from tokedex import Router from tokedex.core.ir import FidelityDecision def report(decision: FidelityDecision) -> None: for change in decision.degradations: print(change.path, change.code) with Router() as router: router.messages.create( model="google/gemini-3.5-flash-lite", system=[ {"type": "text", "text": "Answer in one word.", "cache_control": {"type": "ephemeral"}} ], messages=[{"role": "user", "content": "Name the capital of France."}], fidelity="best_effort", on_fidelity_decision=report, ) ``` ```rust use std::sync::Arc; use serde_json::json; use tokedex::{FidelityDecision, FidelityPolicy, RequestOptions, Router, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?.with_options(RequestOptions { fidelity: Some(FidelityPolicy::BestEffort), on_fidelity_decision: Some(Arc::new(|decision: FidelityDecision| { for change in decision.degradations { println!("{} {}", change.path, change.code); } })), ..Default::default() }); let request: wire::MessagesRequest = serde_json::from_value(json!({ "model": "google/gemini-3.5-flash-lite", "system": [{ "type": "text", "text": "Answer in one word.", "cache_control": { "type": "ephemeral" } }], "messages": [{ "role": "user", "content": "Name the capital of France." }], }))?; router.messages().create(request).await?; Ok(()) } ``` ```text $.promptCacheBreakpoint provider.degradation.google.cache_control_omitted ``` It needs `GEMINI_API_KEY`, and the call is billed by Google. Google's API has no cache breakpoint, so the Router left `cache_control` out, sent the rest and reported the change. **Rust** The samples also need `cargo add serde_json`. ## Requests and replies across APIs Your request is written in your API, and the model's provider may speak another API. The Router rewrites the request into the provider's API and rewrites the reply into your API, so your code reads every model's answer from the same fields. Most fields have an exact equivalent, so most requests arrive exactly as you wrote them. Gemini GenerateContent takes only Google's Gemini and Gemma models, which Google serves on that API, so nothing is translated there. ## Fields with no equivalent The fidelity policy decides what happens to a field with no equivalent: - **`strict`** refuses the call before anything is sent, so nothing is charged. - **`best_effort`** sends the call, drops or approximates only the fields it is allowed to change, and reports each change. A field that `best_effort` may not change refuses the call under either policy. Chat Completions and Messages keep the visible summary and answer when a Responses provider also returns encrypted reasoning. The gateway reports the omitted encrypted content in the `x-tokedex-fidelity-v1` response header. In a stream, look for the report on a Chat chunk with empty `choices`, a Messages `message_delta`, or the terminal error. If an embedded stream throws, read `responseProjectionReport` on the TypeScript error, `response_projection_report` on the Python exception, or `raw["x-tokedex-fidelity-v1"]` on the Rust provider error. If you send an assistant's `reasoning_content` back in Chat history, the selected route determines what the provider receives. Reviewed Chat hosts and xAI Responses routes can replay plain reasoning. Other reviewed cross-dialect routes retain the assistant's answer, omit its unsigned reasoning, and report `provider.degradation.chat.reasoning_echo_omitted` at `$.messages` under both fidelity policies. If an Anthropic response contains signed thinking, Chat returns the visible thinking and reports `provider.degradation.anthropic.thinking_signature_omitted` at `$.reasoning`. The gateway's buffered response header carries both observed omissions. A stream's opening header reports the history omission, and its terminal Chat chunk reports the omissions observed through completion. Start with `strict` while you build, so each field a model cannot carry shows up as a refusal that costs nothing. Allow `best_effort` for a call once you have read the changes it reports and your code works without those fields. Keep `strict` where a dropped field would make the answer wrong, not only different. ## Changes best_effort makes Each model has its own short list of changes on each API. For example, `best_effort` can: **OpenAI Responses** - leave out `prompt_cache_key` for a provider with no such field; - leave out a reasoning `summary` that the model cannot return; - send a custom tool to an Anthropic model as a function that takes one string. **OpenAI Chat Completions** - send a custom tool to an Anthropic model as a function that takes one string; - send `reasoning_effort` as `none` when `openai/gpt-6-luna` gets tools, since OpenAI Chat Completions takes its tools only without reasoning. **Anthropic Messages** - leave out `cache_control` breakpoints for a provider with no such field; - leave out a `thinking` budget for `openai/gpt-6-luna`, which takes an effort level rather than a budget, so OpenAI uses its default effort. It never changes a function tool, a tool call's arguments or result, or an ID. Under `best_effort`, pass `onFidelityDecision` (Python, Rust: `on_fidelity_decision`) as the opening sample does and log what it reports, so a dropped field shows in your logs and not only as a different answer. ## Set the policy ```ts const bestEffort = { fidelity: 'best_effort' } as const; const byHeader = { headers: { 'x-tokedex-fidelity-policy': 'best_effort' } }; ``` ```python best_effort = {"fidelity": "best_effort"} by_header = {"extra_headers": {"x-tokedex-fidelity-policy": "best_effort"}} ``` ```rust use tokedex::{FidelityPolicy, RequestOptions}; let best_effort = router.with_options(RequestOptions::default().fidelity(FidelityPolicy::BestEffort)); let by_header = router.with_options(RequestOptions::default().headers([( "x-tokedex-fidelity-policy".to_string(), "best_effort".to_string(), )])); ``` **TypeScript** Pass either object as the call's second argument. It applies to that call only. **Python** Pass either as keyword arguments to the call, such as `router.chat.completions.create(**best_effort, …)`. It applies to that call only. **Rust** `with_options` returns a Router whose calls all use the options. The header does the same as the option, and a gateway reads it too. If either one says `strict`, the call is strict. ## Default policy With no policy set, a call is `best_effort`: the model applies the approximations reviewed for it on your API and reports each one. Strict is yours to ask for. A model served natively on your API usually has nothing to approximate, so it takes each request exactly or refuses it under either policy. **TypeScript** A [router](/sdk/models#routers) that chooses among several models, such as `aa/fastest`, is `strict`. **Python, Rust** A [router](/sdk/models#routers) that chooses among several models, such as `aa/fastest`, uses the default of each model it tries. Set the policy on calls to such a router ID, so every attempt follows the same rule. The list of models does not show a model's default. To be certain which policy applies, set it yourself, so that moving a call to another model does not change what happens to a field. ## Refusal errors **OpenAI Responses** ```ts import { FidelityError } from '@tokedex/sdk'; try { await router.responses.create( { model: 'google/gemini-3.5-flash-lite', input: 'Name the capital of France.', prompt_cache_key: 'geography' }, { fidelity: 'strict' }, ); } catch (error) { if (!(error instanceof FidelityError)) throw error; for (const issue of error.issues) console.log(issue.path, issue.feature); } ``` ```python from tokedex.core.ir import FidelityError try: router.responses.create( model="google/gemini-3.5-flash-lite", input="Name the capital of France.", prompt_cache_key="geography", fidelity="strict", ) except FidelityError as error: for issue in error.issues: print(issue.path, issue.feature) ``` ```rust use serde_json::json; use tokedex::{Error, FidelityPolicy, RequestOptions, RouterError, wire}; let request: wire::ResponsesRequest = serde_json::from_value(json!({ "model": "google/gemini-3.5-flash-lite", "input": "Name the capital of France.", "prompt_cache_key": "geography", }))?; let strict = router.with_options(RequestOptions::default().fidelity(FidelityPolicy::Strict)); if let Err(Error::Router(error)) = strict.responses().create(request).await { if let RouterError::FidelityError(refusal) = *error { for issue in refusal.issues { println!("{} {}", issue.path, issue.feature); } } } ``` **OpenAI Chat Completions** ```ts import { FidelityError } from '@tokedex/sdk'; try { await router.chat.completions.create({ model: 'anthropic/claude-haiku-5.5', messages: [{ role: 'user', content: 'Name the capital of France.' }], seed: 7, }); } catch (error) { if (!(error instanceof FidelityError)) throw error; for (const issue of error.issues) console.log(issue.path, issue.feature); } ``` ```python from tokedex.core.ir import FidelityError try: router.chat.completions.create( model="anthropic/claude-haiku-5.5", messages=[{"role": "user", "content": "Name the capital of France."}], seed=7, ) except FidelityError as error: for issue in error.issues: print(issue.path, issue.feature) ``` ```rust use serde_json::json; use tokedex::{Error, RouterError, wire}; let request: wire::ChatCompletionsRequest = serde_json::from_value(json!({ "model": "anthropic/claude-haiku-5.5", "messages": [{ "role": "user", "content": "Name the capital of France." }], "seed": 7, }))?; if let Err(Error::Router(error)) = router.chat().completions().create(request).await { if let RouterError::FidelityError(refusal) = *error { for issue in refusal.issues { println!("{} {}", issue.path, issue.feature); } } } ``` Anthropic has no `seed`, and no policy lets the Router drop it, so this call is refused under either one. **Anthropic Messages** ```ts import { FidelityError } from '@tokedex/sdk'; try { await router.messages.create( { model: 'google/gemini-3.5-flash-lite', system: [{ type: 'text', text: 'Answer in one word.', cache_control: { type: 'ephemeral' } }], messages: [{ role: 'user', content: 'Name the capital of France.' }], }, { fidelity: 'strict' }, ); } catch (error) { if (!(error instanceof FidelityError)) throw error; for (const issue of error.issues) console.log(issue.path, issue.feature); } ``` ```python from tokedex.core.ir import FidelityError try: router.messages.create( model="google/gemini-3.5-flash-lite", system=[ {"type": "text", "text": "Answer in one word.", "cache_control": {"type": "ephemeral"}} ], messages=[{"role": "user", "content": "Name the capital of France."}], fidelity="strict", ) except FidelityError as error: for issue in error.issues: print(issue.path, issue.feature) ``` ```rust use serde_json::json; use tokedex::{Error, FidelityPolicy, RequestOptions, RouterError, wire}; let request: wire::MessagesRequest = serde_json::from_value(json!({ "model": "google/gemini-3.5-flash-lite", "system": [{ "type": "text", "text": "Answer in one word.", "cache_control": { "type": "ephemeral" } }], "messages": [{ "role": "user", "content": "Name the capital of France." }], }))?; let strict = router.with_options(RequestOptions::default().fidelity(FidelityPolicy::Strict)); if let Err(Error::Router(error)) = strict.messages().create(request).await { if let RouterError::FidelityError(refusal) = *error { for issue in refusal.issues { println!("{} {}", issue.path, issue.feature); } } } ``` The refusal is a `FidelityError`, raised before anything is sent. Each of its `issues` names a part of the request by its `path` and says which `feature` could not be carried. Remove or change that part, or allow `best_effort` when it may change it. Do not retry the same request: the refusal comes from the request, the model and the policy, so the same call is refused again. **TypeScript** A refusal of a change that `best_effort` would make, such as a custom tool, can raise an error with kind `UnsupportedRequest` instead of `FidelityError`; its message names the part of the request. Next: [Choose a model](/sdk/models) or [Errors, retries and timeouts](/sdk/errors-and-retries). --- # Custom models Add your own model server to the Router under a namespaced model ID you choose, and call it like any other model. These examples use the local namespace `local/`; `upstreamModel` (Python and Rust: `upstream_model`) keeps the server's native model ID separate from the public selector. **OpenAI Chat Completions** ```ts import { Router } from '@tokedex/sdk'; const router = new Router({ customModels: [ { model: 'local/llama', protocol: 'openai.chat-completions', baseUrl: 'http://localhost:11434', upstreamModel: 'llama3.2', }, ], }); const completion = await router.chat.completions.create({ model: 'local/llama', messages: [{ role: 'user', content: 'Name the capital of France in one word.' }], }); console.log(completion.choices[0]?.message.content); ``` ```python from tokedex import Router, RouterCustomModel local_llama = RouterCustomModel("local/llama", "http://localhost:11434", upstream_model="llama3.2") with Router(custom_models=[local_llama]) as router: completion = router.chat.completions.create( model="local/llama", messages=[{"role": "user", "content": "Name the capital of France in one word."}], ) print(completion.choices[0].message.content) ``` ```rust use tokedex::{Router, RouterCustomModel, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let mut local_llama = RouterCustomModel::new("local/llama", "http://localhost:11434"); local_llama.upstream_model = Some("llama3.2".into()); let router = Router::builder().custom_model(local_llama).build()?; let messages = vec![wire::Message::user("Name the capital of France in one word.")]; let request = wire::ChatCompletionsRequest::new("local/llama", messages); let completion = router.chat().completions().create(request).await?; if let Some(wire::Content::Text(text)) = &completion.choices[0].message.content { println!("{text}"); } Ok(()) } ``` ```text Paris ``` It needs [Ollama](https://ollama.com) running with `llama3.2` pulled. Nothing goes to a cloud provider, so nothing is billed. LM Studio and most other local servers speak OpenAI Chat Completions too; change `baseUrl` and the model. **OpenAI Responses** ```ts import { Router } from '@tokedex/sdk'; const router = new Router({ customModels: [{ model: 'local/model', upstreamModel: 'local-model', protocol: 'openai.responses', baseUrl: 'http://localhost:8000' }], }); const response = await router.responses.create({ model: 'local/model', input: 'Name the capital of France in one word.', }); const text = response.output .flatMap((item) => (item.type === 'message' ? item.content : [])) .flatMap((part) => (part.type === 'output_text' ? [part.text] : [])) .join(''); console.log(text); ``` ```python from tokedex import Router, RouterCustomModel local_model = RouterCustomModel("local/model", "http://localhost:8000", upstream_model="local-model", protocol="openai.responses") with Router(custom_models=[local_model]) as router: response = router.responses.create( model="local/model", input="Name the capital of France in one word." ) print(response.output_text) ``` ```rust use tokedex::{Router, RouterCustomModel, RouterCustomProtocol, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let mut local_model = RouterCustomModel::new("local/model", "http://localhost:8000") .with_protocol(RouterCustomProtocol::Responses); local_model.upstream_model = Some("local-model".into()); let router = Router::builder().custom_model(local_model).build()?; let request = wire::ResponsesRequest::new("local/model", "Name the capital of France in one word."); let response = router.responses().create(request).await?; println!("{}", response.output_text()); Ok(()) } ``` ```text Paris ``` It needs a server at `http://localhost:8000` that speaks OpenAI Responses. Nothing goes to a cloud provider, so nothing is billed. **Anthropic Messages** ```ts import { Router } from '@tokedex/sdk'; const router = new Router({ customModels: [ { model: 'local/model', protocol: 'anthropic.messages', baseUrl: 'http://localhost:8000', upstreamModel: 'local-model', messages: { apiVersion: '2023-06-01', maxOutputTokens: 16384 }, }, ], }); const message = await router.messages.create({ model: 'local/model', messages: [{ role: 'user', content: 'Name the capital of France in one word.' }], }); const text = message.content.flatMap((block) => (block.type === 'text' ? [block.text] : [])).join(''); console.log(text); ``` ```python from tokedex import Router, RouterCustomModel local_model = RouterCustomModel( "local/model", "http://localhost:8000", upstream_model="local-model", protocol="anthropic.messages", messages={"api_version": "2023-06-01", "max_output_tokens": 16384}, ) with Router(custom_models=[local_model]) as router: message = router.messages.create( model="local/model", messages=[{"role": "user", "content": "Name the capital of France in one word."}], ) print("".join(block.text for block in message.content if block.type == "text")) ``` ```rust use tokedex::{Router, RouterCustomModel, RouterCustomProtocol, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let mut local_model = RouterCustomModel::new("local/model", "http://localhost:8000").with_protocol( RouterCustomProtocol::Messages { api_version: "2023-06-01".into(), max_output_tokens: 16384 }, ); local_model.upstream_model = Some("local-model".into()); let router = Router::builder().custom_model(local_model).build()?; let messages = vec![wire::Message::user("Name the capital of France in one word.")]; let request = wire::MessagesRequest::new("local/model", messages); let message = router.messages().create(request).await?; for block in &message.content { if let wire::ContentBlock::Text { text, .. } = block { println!("{text}"); } } Ok(()) } ``` ```text Paris ``` It needs a server at `http://localhost:8000` that speaks Anthropic Messages. Nothing goes to a cloud provider, so nothing is billed. Through a gateway, the gateway's administrator adds model servers instead; see [Connect your own model server](/gateway/custom-models) in the gateway docs. ## Call an unlisted model from the SDK Pass the provider's model ID as `model` and name the providers you want to call. The embedded Router uses their reviewed APIs and API keys. This example uses `FIREWORKS_API_KEY` and calls Fireworks, which can incur charges. **Rust** The Rust examples for calling unlisted models and configuring provider-hosted models use the SDK from a [Tokedex source checkout](https://github.com/ArtificialAnalysis/Tokedex). From your Cargo project, add the SDK as a path dependency and replace `/path/to/Tokedex` with the path to your checkout. ```bash cargo add tokedex --path /path/to/Tokedex/rust/crates/tokedex ``` ```ts import { Router } from '@tokedex/sdk'; const router = new Router(); const completion = await router.chat.completions.create({ model: 'accounts/fireworks/routers/glm-5p3-fast', messages: [{ role: 'user', content: 'Reply with OK.' }], }, { providers: ['fireworks'] }); console.log(completion.choices[0]?.message.content); ``` ```python from tokedex import Router with Router() as router: completion = router.chat.completions.create( model="accounts/fireworks/routers/glm-5p3-fast", messages=[{"role": "user", "content": "Reply with OK."}], providers=["fireworks"], ) print(completion.choices[0].message.content) ``` ```rust use tokedex::{RequestOptions, Router, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let request = wire::ChatCompletionsRequest::new( "accounts/fireworks/routers/glm-5p3-fast", vec![wire::Message::user("Reply with OK.")], ); let pinned = router.with_options(RequestOptions::default().providers(["fireworks"])); let completion = pinned.chat().completions().create(request).await?; if let Some(wire::Content::Text(text)) = &completion.choices[0].message.content { println!("{text}"); } Ok(()) } ``` Set a default list with [[new Router({ providers: ['fireworks'] })|Router(providers=["fireworks"])|Router::builder().providers(["fireworks"]).build()?]]. A list on a call replaces the default. A provider pin header narrows the effective list when both are set. On a catalogue match, the list limits normal routing to those providers. IDs beginning with `aa/` are reserved for built-in routers. For an unlisted ID, the list gives the base order and each eligible provider receives the same model ID. Set `providerOrder` (Python: `provider_order`; Rust: `RequestOptions::provider_order`) to change that order within the list. The Router can try a second provider after a retryable failure, before it sends a response. The Router prefers the provider API that matches your request. If only one other reviewed API can serve it, the Router translates the request and reports any fidelity losses. A Chat Completions or Responses request without an output limit uses 4,096 tokens when it reaches Anthropic Messages. To serve an unlisted model through a gateway, have an administrator [add it in the gateway](/gateway/custom-models). ## A model a catalogue provider serves When a provider the catalogue knows serves a model the catalogue does not list yet, name the provider and its model ID instead of a server. The Router calls the provider's own API with the key it already reads for that provider, such as `FIREWORKS_API_KEY`, and serves the model under the provider's ID, so a provider pin names it. **Rust** Use the [Rust SDK from a source checkout](#call-an-unlisted-model-from-the-sdk) for `RouterCustomModel::on_provider`. ```ts import { Router } from '@tokedex/sdk'; const router = new Router({ customModels: [ { model: 'team/new-model', provider: 'fireworks', upstreamModel: 'accounts/fireworks/models/new-model' }, ], }); const completion = await router.chat.completions.create({ model: 'team/new-model', messages: [{ role: 'user', content: 'Name the capital of France in one word.' }], }); console.log(completion.choices[0]?.message.content); ``` ```python from tokedex import Router, RouterCustomModel new_model = RouterCustomModel( "team/new-model", provider="fireworks", upstream_model="accounts/fireworks/models/new-model" ) with Router(custom_models=[new_model]) as router: completion = router.chat.completions.create( model="team/new-model", messages=[{"role": "user", "content": "Name the capital of France in one word."}], ) print(completion.choices[0].message.content) ``` ```rust use tokedex::{Router, RouterCustomModel, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let new_model = RouterCustomModel::on_provider("team/new-model", "fireworks", "accounts/fireworks/models/new-model"); let router = Router::builder().custom_model(new_model).build()?; let messages = vec![wire::Message::user("Name the capital of France in one word.")]; let request = wire::ChatCompletionsRequest::new("team/new-model", messages); let completion = router.chat().completions().create(request).await?; if let Some(wire::Content::Text(text)) = &completion.choices[0].message.content { println!("{text}"); } Ok(()) } ``` - **Provider.** Use a reviewed provider API, including those for Bedrock, Vertex AI, Azure, Google AI Studio, Cloudflare Workers AI and Databricks. The Router uses the provider's credentials and account settings. [[The Router uses the provider's API when it has one, and asks for `protocol` when it has several.|The Router uses the provider's API when it has one, and asks for `protocol` when it has several.|The Router uses the provider's API when it has one, and asks for `with_protocol` when it has several.]] Construction fails for a provider that cannot serve the model, naming the available APIs. - **Model ID.** `upstreamModel` (Python: `upstream_model`; Rust: `the third argument`) is the provider's own ID. A model the catalogue already serves on that provider is refused: call it by its catalogue ID instead. - **Inputs.** It takes text and function tools. [[inputs: ['image']|inputs=("image",)|with_inputs([RouterCustomInput::Image])]] lets images or files through. - **Reasoning.** Set reasoning on the request as you would for a built-in model. The provider's API determines which controls the Router can send, including named effort, Responses summaries and context, Messages adaptive thinking and token budgets, or Gemini `thinkingBudget` and `includeThoughts`. If a route offers effort but cannot send the requested level, the Router reports the available levels before calling the provider. The provider can still reject a forwarded control. - **APIs.** Most providers serve OpenAI Responses, OpenAI Chat Completions and Anthropic Messages. Bedrock Converse serves OpenAI Responses. Vertex AI and Google AI Studio models using GenerateContent also serve Gemini GenerateContent. The Router translates between supported APIs and reports the provider's reviewed losses in best-effort mode. Strict mode requires a lossless route. - **Messages.** On a Messages provider, set `messages: { maxOutputTokens }` (Python: `messages={"api_version": …, "max_output_tokens": …}`; Rust: `RouterCustomProtocol::Messages { api_version, max_output_tokens }`). ## Serve one model ID through several providers **Rust** Use the [Rust SDK from a source checkout](#call-an-unlisted-model-from-the-sdk) to configure several providers for one model ID. ```ts import { Router } from '@tokedex/sdk'; const router = new Router({ customModels: [ { model: 'team/new-model', provider: 'fireworks', upstreamModel: 'accounts/fireworks/models/new-model', price: { input: '0.10', output: '0.30' } }, { model: 'team/new-model', provider: 'togetherai', upstreamModel: 'example/new-model' }, ], }); ``` ```python from tokedex import Router, RouterCustomModel primary = RouterCustomModel( "team/new-model", provider="fireworks", upstream_model="accounts/fireworks/models/new-model", price={"input": "0.10", "output": "0.30"}, ) backup = RouterCustomModel( "team/new-model", provider="togetherai", upstream_model="example/new-model" ) with Router(custom_models=[primary, backup]) as router: available_models = router.models.list() ``` ```rust use tokedex::{Router, RouterCustomModel, RouterCustomPrice}; #[tokio::main] async fn main() -> Result<(), Box> { let _router = Router::builder() .custom_model_with_price( RouterCustomModel::on_provider("team/new-model", "fireworks", "accounts/fireworks/models/new-model"), RouterCustomPrice::tokens("0.10", "0.30"), ) .custom_model(RouterCustomModel::on_provider("team/new-model", "togetherai", "example/new-model")) .build()?; Ok(()) } ``` Give every declaration the same model ID and listing setting. Name a different provider in each declaration. Each client API can use the providers that serve it, and model discovery lists the shared ID once per API. - **Price order.** The Router ranks priced providers by the input and output rates in US dollars per million tokens. Input counts three times as much as output. Use [[`price: { free: true }`|`price={"free": True}`|`RouterCustomPrice::Free`]] for a free provider. Unpriced providers follow priced ones, and provider ID breaks ties. - **Order and pins.** Set a preferred provider order on the Router or on the call. A provider pin limits the call to the named providers. [Order the providers](/sdk/models#order-the-providers) - **Fallback.** Before the response starts, a retryable failure can send the request to the next eligible provider. Each provider uses its own reviewed translations. A continuation returns to the provider that served the earlier turn. ## Server protocols | Server speaks | Protocol | Also give | |---|---|---| | OpenAI Chat Completions | `openai.chat-completions` | Nothing | | OpenAI Responses | `openai.responses` | Nothing | | Anthropic Messages | `anthropic.messages` | `messages: { apiVersion, maxOutputTokens }` (Python: `messages={"api_version": …, "max_output_tokens": …}`; Rust: `RouterCustomProtocol::Messages { api_version, max_output_tokens }`) | **TypeScript** Every custom model names its `protocol`. **Python** `protocol` defaults to `openai.chat-completions`. **Rust** `with_protocol` sets the protocol; without it, a custom model speaks OpenAI Chat Completions. Choose the protocol your server speaks natively, because the Router sends it requests in that protocol. Start with `openai.chat-completions`, which LM Studio, Ollama and most local servers speak. Choose `openai.responses` when your server speaks it and you want typed values from `router.responses.parse` (Rust: `router.responses().parse`), which needs that protocol. - Give the server's address with or without `/v1`, and `upstreamModel` (Python, Rust: `upstream_model`) when the server knows the model by another name. - An OpenAI Responses server receives every request with `store: false`. The Router keeps the conversation itself, so `previous_response_id` still works. - An Anthropic Messages server takes the API version `2023-06-01`. `max_output_tokens` is the most a call may ask for, and the default when a call sets none, so set it to the most your server can return. ## API for a custom model Call the model on the one API its server speaks: `router.chat.completions` (OpenAI Responses: `router.responses`; Anthropic Messages: `router.messages`) here. A call on any other API fails with `NotFound`, because the Router does not translate to your server. Set reasoning on the request using `reasoning_effort` (OpenAI Responses: `reasoning`; Anthropic Messages: `thinking`). Choose a named effort level. (OpenAI Responses: Set the effort, summary or context.; Anthropic Messages: Choose adaptive, disabled or manual thinking, or set the output effort.) Your server decides which of those controls the model accepts. **OpenAI Chat Completions, Anthropic Messages** To get a typed value with `router.responses.parse` (Rust: `router.responses().parse`), declare the model with the OpenAI Responses protocol; see [Structured output](/sdk/structured-output). ## Rules - **IDs.** An ID cannot be blank, start with `aa/` or match a built-in model ID. Reuse an ID only across different reviewed providers. Name the model for its role, such as `local-llama`, and give the server's own name in `upstreamModel` (Python, Rust: `upstream_model`), so you can swap the model on the server without changing your calls. - **Inputs.** A custom model takes text and function tools. A request with an image or a file fails before anything is sent. - **Listing.** `router.models.list()` (Rust: `router.models().list()`) lists custom models after the built-in ones, with `trust` set to `unreviewed`. Set `listed: false` (Python: `listed=False`; Rust: `listed = false`) to leave one out; you can still call it by ID. - **Keys.** Set `apiKey` (Python, Rust: `api_key`) if the server needs one. The Router sends it as `x-api-key` to an Anthropic Messages server and as a bearer token to the others, and sends no key when you set none. Read the key from the environment or a secret store, as you would a provider key, so it stays out of your source code. Next: [Choose a model](/sdk/models) or [Conversations](/sdk/conversations). --- # Provider keys Set a provider's key, and the Router can call every built-in model that provider runs. ```ts import { Router } from '@tokedex/sdk'; const router = new Router(); const ready = new Set((await router.models.list()).map((row) => row.id)); for (const model of ['openai/gpt-6-luna', 'anthropic/claude-haiku-5.5', 'google/gemini-3.5-flash-lite']) { console.log(`${model}: ${ready.has(model) ? 'ready' : 'no key'}`); } ``` ```python from tokedex import Router with Router() as router: ready = {row.id for row in router.models.list()} for model in ["openai/gpt-6-luna", "anthropic/claude-haiku-5.5", "google/gemini-3.5-flash-lite"]: print(f"{model}: {'ready' if model in ready else 'no key'}") ``` ```rust use std::collections::HashSet; use tokedex::Router; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let ready: HashSet = router.models().list().await?.into_iter().map(|row| row.id).collect(); for model in ["openai/gpt-6-luna", "anthropic/claude-haiku-5.5", "google/gemini-3.5-flash-lite"] { println!("{model}: {}", if ready.contains(model) { "ready" } else { "no key" }); } Ok(()) } ``` ```text openai/gpt-6-luna: ready anthropic/claude-haiku-5.5: ready google/gemini-3.5-flash-lite: no key ``` This output is from a shell with `OPENAI_API_KEY` and `ANTHROPIC_API_KEY` set. Listing models sends nothing to a provider, so it costs nothing. ## Provider key variables | Provider | Variable | |---|---| | Agnes AI | `AGNES_API_KEY` | | Alibaba Cloud Model Studio | `DASHSCOPE_API_KEY` | | Anthropic | `ANTHROPIC_API_KEY` | | Arcee | `ARCEE_API_KEY` | | Azure | `AZURE_API_KEY` and `AZURE_RESOURCE_NAME` | | Baseten | `BASETEN_API_KEY` | | Bitdeer | `BITDEER_API_KEY` | | Celeris | `CELERIS_API_KEY` | | Cerebras | `CEREBRAS_API_KEY` | | Cohere | `COHERE_API_KEY` | | CoreWeave | `COREWEAVE_API_KEY` | | Crusoe | `CRUSOE_API_KEY` | | DeepInfra | `DEEPINFRA_API_KEY` | | DeepSeek | `DEEPSEEK_API_KEY` | | DigitalOcean | `DIGITALOCEAN_API_KEY` | | Fireworks AI | `FIREWORKS_API_KEY` | | FriendliAI | `FRIENDLI_AI_API_KEY` | | GMI Cloud | `GMI_API_KEY` | | Google | `GEMINI_API_KEY` | | Google Vertex AI | `VERTEX_SERVICE_ACCOUNT_JSON` (a service-account key, as JSON) and `VERTEX_PROJECT` | | Groq | `GROQ_API_KEY` | | Hyperbolic | `HYPERBOLIC_API_KEY` | | Inco | `INCO_API_KEY` | | Liquid AI | `LIQUID_API_KEY` | | Makora | `MAKORA_API_KEY` | | Meta | `META_API_KEY` | | MiniMax | `MINIMAX_API_KEY` | | Moonshot AI | `MOONSHOT_API_KEY` | | Multiverse Computing | `COMPACTIFAI_API_KEY` | | Nebius | `NEBIUS_API_KEY` | | Novita | `NOVITA_API_KEY` | | OpenAI | `OPENAI_API_KEY` | | Parasail | `PARASAIL_API_KEY` | | Reka AI | `REKA_API_KEY` | | SambaNova | `SAMBANOVA_API_KEY` | | Sarvam AI | `SARVAM_API_KEY` | | SiliconFlow | `SILICONFLOW_API_KEY` | | StepFun | `STEPFUN_API_KEY` | | Tencent | `TENCENT_API_KEY` | | Thinking Machines | `TINKER_API_KEY` (Tinker's API is for testing your models; production inference access has a waitlist) | | Together | `TOGETHERAI_API_KEY` | | Upstage | `UPSTAGE_API_KEY` | | Wafer | `WAFER_API_KEY` | | xAI | `XAI_API_KEY` | | Xiaomi | `XIAOMI_API_KEY` | | Z.ai | `ZAI_API_KEY` | The Router reads a variable when a call needs it, so a key you set after creating the Router still counts. Start with these variables: you set keys where the program runs, and none appear in your code. A model that more than one provider runs needs a key for at least one of them; set keys for two or more when you depend on it, so the Router has another provider to move to when one fails. The Router reads Google's key from `GEMINI_API_KEY` only. Your own model servers take their key in the custom model's `apiKey` (Python, Rust: `api_key`); see [Custom models](/sdk/custom-models). ## Pass keys in code ```ts import { Router } from '@tokedex/sdk'; const fromRecord = new Router({ credentials: { OPENAI_API_KEY: process.env['TEAM_OPENAI_KEY'] }, }); const fromFunction = new Router({ credentials: (name) => (name === 'ANTHROPIC_API_KEY' ? process.env['TEAM_ANTHROPIC_KEY'] : undefined), }); ``` ```python import os from tokedex import Router from_mapping = Router(credentials={"OPENAI_API_KEY": os.environ["TEAM_OPENAI_KEY"]}) from_function = Router( credentials=lambda name: os.environ.get("TEAM_ANTHROPIC_KEY") if name == "ANTHROPIC_API_KEY" else None ) ``` ```rust use std::sync::Arc; use tokedex::Router; let router = Router::builder() .credentials(Arc::new(|name: &str| match name { "OPENAI_API_KEY" => std::env::var("TEAM_OPENAI_KEY").ok(), _ => None, })) .build()?; ``` `credentials` takes the variable names from the table. It replaces the environment: the Router then reads no variable you leave out. Use the function form to read keys from your own secret store, or whenever a key can change while the program runs: the Router calls it each time a call needs a key. **Rust** Rust takes the function form only. List every key the Router needs: a model none of whose providers is listed drops out of the model list, and calls to it fail. ## Missing keys A model whose provider has no key is left out of `router.models.list()` (Rust: `router.models().list()`), and a call to it fails before anything is sent. **TypeScript** The error's `kind` is `NotFound`. Check `kind` rather than the class: this error is not a `GatewayError`. **Python** The call raises `GatewayError` from `tokedex.engine`, with kind `NotFound`. **Rust** The call returns `tokedex::Error::Routing` holding a `GatewayError` with kind `GatewayErrorKind::NotFound`. A model ID the Router does not know fails the same way. Run a check like the opening sample when your program starts, so a missing key shows up there, at no cost, rather than at the first call that needs it. See [Errors, retries and timeouts](/sdk/errors-and-retries) for every Router error. ## Provider keys with a gateway A Router that [runs through a gateway](/sdk/gateway) needs none: it sends only your Tokedex API key, and the gateway holds the provider credentials. See [Provider credentials](/gateway/provider-credentials) in the gateway docs. Next: [Choose a model](/sdk/models), [Custom models](/sdk/custom-models) or [Run through a gateway](/sdk/gateway). --- # Run through a gateway Create the Router with a gateway's address and an API key, and every call you make goes through the gateway. **OpenAI Responses** ```ts import { Router } from '@tokedex/sdk'; const router = new Router({ baseUrl: process.env['TOKEDEX_URL']!, apiKey: process.env['TOKEDEX_API_KEY']! }); const response = await router.responses.create({ model: 'openai/gpt-6-luna', input: 'Name the capital of France in one word.', }); const text = response.output .flatMap((item) => (item.type === 'message' ? item.content : [])) .flatMap((part) => (part.type === 'output_text' ? [part.text] : [])) .join(''); console.log(text); ``` ```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="Name the capital of France in one word." ) print(response.output_text) ``` ```rust use tokedex::{GatewayOptions, Router, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::new(GatewayOptions::new(std::env::var("TOKEDEX_URL")?, std::env::var("TOKEDEX_API_KEY")?))?; let request = wire::ResponsesRequest::new("openai/gpt-6-luna", "Name the capital of France in one word."); let response = router.responses().create(request).await?; println!("{}", response.output_text()); Ok(()) } ``` **OpenAI Chat Completions** ```ts import { Router } from '@tokedex/sdk'; const router = new Router({ baseUrl: process.env['TOKEDEX_URL']!, apiKey: process.env['TOKEDEX_API_KEY']! }); const completion = await router.chat.completions.create({ model: 'openai/gpt-6-luna', messages: [{ role: 'user', content: 'Name the capital of France in one word.' }], }); console.log(completion.choices[0]?.message.content); ``` ```python import os from tokedex import Router with Router(base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"]) as router: completion = router.chat.completions.create( model="openai/gpt-6-luna", messages=[{"role": "user", "content": "Name the capital of France in one word."}], ) print(completion.choices[0].message.content) ``` ```rust use tokedex::{GatewayOptions, Router, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::new(GatewayOptions::new(std::env::var("TOKEDEX_URL")?, std::env::var("TOKEDEX_API_KEY")?))?; let messages = vec![wire::Message::user("Name the capital of France in one word.")]; let request = wire::ChatCompletionsRequest::new("openai/gpt-6-luna", messages); let completion = router.chat().completions().create(request).await?; if let Some(wire::Content::Text(text)) = &completion.choices[0].message.content { println!("{text}"); } Ok(()) } ``` **Anthropic Messages** ```ts import { Router } from '@tokedex/sdk'; const router = new Router({ baseUrl: process.env['TOKEDEX_URL']!, apiKey: process.env['TOKEDEX_API_KEY']! }); const message = await router.messages.create({ model: 'openai/gpt-6-luna', messages: [{ role: 'user', content: 'Name the capital of France in one word.' }], }); console.log(message.content.flatMap((block) => (block.type === 'text' ? [block.text] : [])).join('')); ``` ```python import os from tokedex import Router with Router(base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"]) as router: message = router.messages.create( model="openai/gpt-6-luna", messages=[{"role": "user", "content": "Name the capital of France in one word."}], ) print("".join(block.text for block in message.content if block.type == "text")) ``` ```rust use tokedex::{GatewayOptions, Router, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::new(GatewayOptions::new(std::env::var("TOKEDEX_URL")?, std::env::var("TOKEDEX_API_KEY")?))?; let messages = vec![wire::Message::user("Name the capital of France in one word.")]; let request = wire::MessagesRequest::new("openai/gpt-6-luna", messages); let message = router.messages().create(request).await?; for block in &message.content { if let wire::ContentBlock::Text { text, .. } = block { println!("{text}"); } } Ok(()) } ``` **Gemini GenerateContent** ```ts import { Router } from '@tokedex/sdk'; const router = new Router({ baseUrl: process.env['TOKEDEX_URL']!, apiKey: process.env['TOKEDEX_API_KEY']! }); const result = await router.generateContent.create({ model: 'google/gemini-3.5-flash-lite', contents: [{ role: 'user', parts: [{ text: 'Name the capital of France in one word.' }] }], }); for (const part of result.candidates?.[0]?.content?.parts ?? []) { if ('text' in part) console.log(part.text); } ``` ```python import os from tokedex import Router with Router(base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"]) as router: result = router.generate_content.create( model="google/gemini-3.5-flash-lite", contents=[{"role": "user", "parts": [{"text": "Name the capital of France in one word."}]}], ) print("".join(getattr(part, "text", "") for part in result.candidates[0].content.parts)) ``` ```rust use tokedex::{GatewayOptions, Router, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::new(GatewayOptions::new(std::env::var("TOKEDEX_URL")?, std::env::var("TOKEDEX_API_KEY")?))?; let request: wire::GeminiRequest = serde_json::from_value(serde_json::json!({ "contents": [{ "role": "user", "parts": [{ "text": "Name the capital of France in one word." }] }], }))?; let result = router.generate_content().create("google/gemini-3.5-flash-lite", request).await?; let candidates = result.candidates.unwrap_or_default(); if let Some(content) = candidates.first().and_then(|candidate| candidate.content.as_ref()) { println!("{}", content.parts[0]["text"].as_str().unwrap_or_default()); } Ok(()) } ``` ```text Paris ``` It needs a [running gateway](/gateway/quickstart) that serves the model, its address in `TOKEDEX_URL`, such as `http://127.0.0.1:4000`, and an [API key](/gateway/api-keys) in `TOKEDEX_API_KEY`. The call is billed to the gateway's provider accounts. You can call the models the gateway serves and your API key allows; `router.models.list()` (Rust: `router.models().list()`) lists them. Ask for an API key for each application, so its spend shows on its own and its key can be revoked without stopping the others. Only the line that creates the Router changes. Give the address without `/v1`, with any reverse-proxy path: the SDK adds `/v1/responses` (OpenAI Chat Completions: `/v1/chat/completions`; Anthropic Messages: `/v1/messages`; Gemini GenerateContent: `/v1/models/…`) itself. ## Work the gateway takes over - **Routing:** choosing the provider, retries, failover, and its own models, [routers](/gateway/router#built-in-routers) and custom models. - **Provider keys:** your process holds only the API key. - **Stored conversations:** OpenAI Responses turns, continued from `previous_response_id`. - **Limits and records:** your key's models, budgets and rate limits, and each call under **Observability** and **Usage** in its dashboard. Call providers directly while one program holds your provider keys. Move to a gateway when several applications or people need the same providers, or when you need budgets, rate limits or a record of every call, because the gateway holds the keys and applies limits per API key. [Batch jobs](/sdk/batch) run on a gateway only when it is started from a configuration file, which the Helm chart and the published image do not run. ### Request body size The self-hosted TypeScript gateway accepts up to 12,000,000 bytes per HTTP request by default. It counts the serialized body, including every item in a Batch and the base64 text of inline files. A larger request returns HTTP `413` (`request_too_large`) before any provider call. An SDK pointed at the gateway has the same limit as curl. To change the limit, set `TOKEDEX_MAX_REQUEST_BYTES` or configure `server.maxRequestBytes` and restart the gateway. The environment setting takes precedence. When the SDK calls providers directly, each provider's input limits apply. ## Send headers with a call ```ts const tagged = new Router({ baseUrl: process.env['TOKEDEX_URL']!, apiKey: process.env['TOKEDEX_API_KEY']!, headers: { 'x-tokedex-tags': 'eval' }, }); ``` ```python import os from tokedex import Router tagged = Router( base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"], default_headers={"x-tokedex-tags": "eval"}, ) ``` ```rust use tokedex::{GatewayOptions, Router}; let mut options = GatewayOptions::new(std::env::var("TOKEDEX_URL")?, std::env::var("TOKEDEX_API_KEY")?); options.headers.insert("x-tokedex-tags".into(), "eval".into()); let tagged = Router::new(options)?; ``` Headers set when you create the Router go with every call. A header in one call's options goes with that call and replaces the same header set for every call: **OpenAI Responses** ```ts await router.responses.create( { model: 'openai/gpt-6-luna', input: 'Name the capital of France in one word.' }, { headers: { 'x-tokedex-trajectory-id': 'nightly-eval-42' } }, ); ``` ```python router.responses.create( model="openai/gpt-6-luna", input="Name the capital of France in one word.", extra_headers={"x-tokedex-trajectory-id": "nightly-eval-42"}, ) ``` ```rust use tokedex::{RequestOptions, wire}; let session = router.with_options( RequestOptions::default().headers([("x-tokedex-trajectory-id".to_string(), "nightly-eval-42".to_string())]), ); let request = wire::ResponsesRequest::new("openai/gpt-6-luna", "Name the capital of France in one word."); session.responses().create(request).await?; ``` **OpenAI Chat Completions** ```ts await router.chat.completions.create( { model: 'openai/gpt-6-luna', messages: [{ role: 'user', content: 'Name the capital of France in one word.' }] }, { headers: { 'x-tokedex-trajectory-id': 'nightly-eval-42' } }, ); ``` ```python router.chat.completions.create( model="openai/gpt-6-luna", messages=[{"role": "user", "content": "Name the capital of France in one word."}], extra_headers={"x-tokedex-trajectory-id": "nightly-eval-42"}, ) ``` ```rust use tokedex::{RequestOptions, wire}; let session = router.with_options( RequestOptions::default().headers([("x-tokedex-trajectory-id".to_string(), "nightly-eval-42".to_string())]), ); let messages = vec![wire::Message::user("Name the capital of France in one word.")]; session.chat().completions().create(wire::ChatCompletionsRequest::new("openai/gpt-6-luna", messages)).await?; ``` **Anthropic Messages** ```ts await router.messages.create( { model: 'openai/gpt-6-luna', messages: [{ role: 'user', content: 'Name the capital of France in one word.' }] }, { headers: { 'x-tokedex-trajectory-id': 'nightly-eval-42' } }, ); ``` ```python router.messages.create( model="openai/gpt-6-luna", messages=[{"role": "user", "content": "Name the capital of France in one word."}], extra_headers={"x-tokedex-trajectory-id": "nightly-eval-42"}, ) ``` ```rust use tokedex::{RequestOptions, wire}; let session = router.with_options( RequestOptions::default().headers([("x-tokedex-trajectory-id".to_string(), "nightly-eval-42".to_string())]), ); let messages = vec![wire::Message::user("Name the capital of France in one word.")]; session.messages().create(wire::MessagesRequest::new("openai/gpt-6-luna", messages)).await?; ``` **Gemini GenerateContent** ```ts await router.generateContent.create( { model: 'google/gemini-3.5-flash-lite', contents: [{ role: 'user', parts: [{ text: 'Name the capital of France in one word.' }] }] }, { headers: { 'x-tokedex-trajectory-id': 'nightly-eval-42' } }, ); ``` ```python router.generate_content.create( model="google/gemini-3.5-flash-lite", contents=[{"role": "user", "parts": [{"text": "Name the capital of France in one word."}]}], extra_headers={"x-tokedex-trajectory-id": "nightly-eval-42"}, ) ``` ```rust use tokedex::{RequestOptions, wire}; let session = router.with_options( RequestOptions::default().headers([("x-tokedex-trajectory-id".to_string(), "nightly-eval-42".to_string())]), ); let request: wire::GeminiRequest = serde_json::from_value(serde_json::json!({ "contents": [{ "role": "user", "parts": [{ "text": "Name the capital of France in one word." }] }], }))?; session.generate_content().create("google/gemini-3.5-flash-lite", request).await?; ``` | Header | Effect | |---|---| | `x-tokedex-trace: false` | Leaves the call out of **Observability** | | `x-tokedex-trace-text: true` | Records its text, when the gateway allows it | | `x-tokedex-trajectory-id` | Groups calls into one session | | `x-tokedex-tags` | Tags the call for filtering | | `x-tokedex-project-id`, `x-tokedex-project-name` | Labels the call with a project | | `x-tokedex-fidelity-policy` | Sets the call's [fidelity policy](/sdk/translation) | | `x-tokedex-provider` | Names the providers allowed to serve the call, as the [`providers`](/sdk/models#pin-a-provider) option does; given both, only the providers both name | | `x-tokedex-provider-order` | Names the providers the call tries first, as the [[`providerOrder`|`provider_order`|`provider_order`]] [option](/sdk/models#order-the-providers) does; given both, they must name the same order. The Router sends its own per-model order as this header when a call names none | | `anthropic-version`, `anthropic-beta` | Anthropic protocol headers | Set a header that holds for the whole process, such as `x-tokedex-tags`, when you create the Router, and a value that changes, such as `x-tokedex-trajectory-id`, in each call, since a call's header replaces the Router's. The Router drops other headers, apart from session IDs that coding agents send, so none can replace your API key. See [What the gateway records](/gateway/recording-and-retention#keep-content-private). ## Read the response headers ```ts const observed = new Router({ baseUrl: process.env['TOKEDEX_URL']!, apiKey: process.env['TOKEDEX_API_KEY']!, onResponseHeaders: (headers) => console.log(headers['x-request-id'], headers['x-tokedex-provider']), }); ``` ```python import os from collections.abc import Mapping from tokedex import Router def log_headers(headers: Mapping[str, str]) -> None: print(headers.get("x-request-id"), headers.get("x-tokedex-provider")) observed = Router( base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"], on_response_headers=log_headers, ) ``` ```rust use std::sync::Arc; use tokedex::{GatewayOptions, Router}; let mut options = GatewayOptions::new(std::env::var("TOKEDEX_URL")?, std::env::var("TOKEDEX_API_KEY")?); options.on_response_headers = Some(Arc::new(|headers| { println!("{:?} {:?}", headers.get("x-request-id"), headers.get("x-tokedex-provider")); })); let observed = Router::new(options)?; ``` The callback runs as each response arrives, before its body, for streams and errors too, and receives the request ID that **Observability → Requests** finds, the provider and model that answered, what translation changed in `x-tokedex-fidelity-v1`, and your key's rate limit and budget. Their names are `x-request-id`, `x-tokedex-provider`, `x-tokedex-model`, `x-tokedex-fidelity-v1`, `x-tokedex-ratelimit-limit`, `x-tokedex-ratelimit-remaining`, `x-tokedex-ratelimit-reset-ms`, and `x-tokedex-budget-*` for budgets. ## Structured output and tool runs Both work through a gateway. `router.responses.parse` (Rust: `router.responses().parse`) is an OpenAI Responses call. `runTools` (Python, Rust: `run_tools`) and `streamTools` (Python, Rust: `stream_tools`) use the first of Chat Completions, Responses, Messages and GenerateContent that the gateway's model list shows for the model. ## Call a model the gateway does not list Each API's own calls reach an unlisted model by its ID. A tool run uses OpenAI Chat Completions for it unless you name the API: **OpenAI Responses** ```ts import { runTools } from '@tokedex/sdk'; const result = await runTools(router, 'What is the weather in Tokyo?', { model: 'openai/gpt-6-luna', tools: [getWeather], clientDialectId: 'openai.responses', }); ``` ```python from tokedex import run_tools result = run_tools( router, "What is the weather in Tokyo?", model="openai/gpt-6-luna", tools=[get_weather], client_dialect_id="openai.responses", ) ``` ```rust use tokedex::{ClientDialect, RunOptions, RunRequest, run_tools}; let request = RunRequest::new("openai/gpt-6-luna", "What is the weather in Tokyo?") .client_dialect_id(ClientDialect::Responses) .options(RunOptions { tools: vec![get_weather], ..Default::default() }); let result = run_tools(&router, request).await?; ``` **OpenAI Chat Completions** ```ts import { runTools } from '@tokedex/sdk'; const result = await runTools(router, 'What is the weather in Tokyo?', { model: 'openai/gpt-6-luna', tools: [getWeather], clientDialectId: 'openai.chat-completions', }); ``` ```python from tokedex import run_tools result = run_tools( router, "What is the weather in Tokyo?", model="openai/gpt-6-luna", tools=[get_weather], client_dialect_id="openai.chat-completions", ) ``` ```rust use tokedex::{ClientDialect, RunOptions, RunRequest, run_tools}; let request = RunRequest::new("openai/gpt-6-luna", "What is the weather in Tokyo?") .client_dialect_id(ClientDialect::ChatCompletions) .options(RunOptions { tools: vec![get_weather], ..Default::default() }); let result = run_tools(&router, request).await?; ``` **Anthropic Messages** ```ts import { runTools } from '@tokedex/sdk'; const result = await runTools(router, 'What is the weather in Tokyo?', { model: 'openai/gpt-6-luna', tools: [getWeather], clientDialectId: 'anthropic.messages', maxOutputTokens: 128000, }); ``` ```python from tokedex import run_tools result = run_tools( router, "What is the weather in Tokyo?", model="openai/gpt-6-luna", tools=[get_weather], client_dialect_id="anthropic.messages", max_output_tokens=128000, ) ``` ```rust use tokedex::{ClientDialect, RunOptions, RunRequest, run_tools}; let request = RunRequest::new("openai/gpt-6-luna", "What is the weather in Tokyo?") .client_dialect_id(ClientDialect::Messages) .options(RunOptions { tools: vec![get_weather], max_output_tokens: Some(128000), ..Default::default() }); let result = run_tools(&router, request).await?; ``` Anthropic Messages needs a maximum, and the SDK has no output ceiling for a model the gateway does not list, so set `maxOutputTokens` (Python, Rust: `max_output_tokens`). A reasoning model's thinking counts against it, so leave room. **Gemini GenerateContent** ```ts import { runTools } from '@tokedex/sdk'; const result = await runTools(router, 'What is the weather in Tokyo?', { model: 'google/gemini-3.5-flash-lite', tools: [getWeather], clientDialectId: 'google.generate-content', }); ``` ```python from tokedex import run_tools result = run_tools( router, "What is the weather in Tokyo?", model="google/gemini-3.5-flash-lite", tools=[get_weather], client_dialect_id="google.generate-content", ) ``` ```rust use tokedex::{ClientDialect, RunOptions, RunRequest, run_tools}; let request = RunRequest::new("google/gemini-3.5-flash-lite", "What is the weather in Tokyo?") .client_dialect_id(ClientDialect::Gemini) .options(RunOptions { tools: vec![get_weather], ..Default::default() }); let result = run_tools(&router, request).await?; ``` With `clientDialectId` (Python: `client_dialect_id`; Rust: `client_dialect_id()`) set, the run uses your API without reading the list. `getWeather` (Python, Rust: `get_weather`) is a tool you define with `tool`. ## Gateway Router options A gateway Router takes only the address, the key, headers, the response-header callback and your own `fetch` (Python: `http_client`; Rust: `transport`). **TypeScript, Python** Options for calling providers yourself, such as `credentials`, `customModels` (Python, Rust: `custom_models`), `observer` or the Batch settings, raise a `TypeError` when you pass them with a gateway address. A call's fidelity policy goes to the gateway, but a fidelity callback, `onFidelityDecision` (Python, Rust: `on_fidelity_decision`) or `admitFidelity` (Python, Rust: `admit_fidelity`), raises an error; read `x-tokedex-fidelity-v1` instead. ## Failed calls **TypeScript** An error status raises `GatewayHttpError`, with the status in `status`, the gateway's message in `message` and its error code in `code`, in a stream too. **Python** An error status raises `httpx2.HTTPStatusError`, with the status in `error.response.status_code`. An error inside a stream raises it too, with the failing event in `error.response.json()`. **Rust** An error status returns `tokedex::Error::Router` holding a `RouterError::Provider`, whose subkind follows the status, such as `RateLimit` for `429`. A `401` means the key is wrong or revoked, and a `404` that the gateway does not serve the model ID. Log `x-request-id` with each failed call, to find it under **Observability → Requests**. Retry only the codes [Errors and limits](/gateway/errors-and-limits#retryable-errors) marks as retryable, and a `429` only after `retry-after`, because the Router does not retry a gateway error and each retry is a new provider request. See [Errors, retries and timeouts](/sdk/errors-and-retries). ## Read your key's budgets and rate limits ```ts const limits = await router.limits.retrieve(); for (const budget of limits.budgets) console.log(budget.scope, budget.window, budget.remaining_usd); for (const rate of limits.rate_limits) console.log(rate.scope, rate.requests_per_minute, rate.remaining); ``` ```python limits = router.limits.retrieve() for budget in limits.budgets: print(budget.scope, budget.window, budget.remaining_usd) for rate in limits.rate_limits: print(rate.scope, rate.requests_per_minute, rate.remaining) ``` ```rust let limits = router.limits().retrieve().await?; for budget in &limits.budgets { println!("{} {} {:?}", budget.scope, budget.window, budget.remaining_usd); } for rate in &limits.rate_limits { println!("{} {} {}", rate.scope, rate.requests_per_minute, rate.remaining); } ``` The call reads `GET /v1/limits` for the budgets that apply to your API key and the rate counters on the replica that answers. A budget's amounts are there only when the gateway discloses them, which by default it does for the key's own budgets and its holder's. The call takes an API key. The master key gets a `403`. A Router that calls providers directly has no such limits, and the call fails with a `GatewayError` of kind `NotFound`. See [Budgets](/gateway/budgets) and [Rate limits](/gateway/errors-and-limits#rate-limits) in the gateway docs. Next: [Errors, retries and timeouts](/sdk/errors-and-retries), [Observability](/sdk/observability) or [Connect your app](/gateway/connect-your-app) in the gateway docs. --- # Errors, retries and timeouts Catch a failed call, tell what kind of failure it was, and decide what your code does next. ```ts import { Router, RouterError } from '@tokedex/sdk'; const router = new Router(); try { const response = await router.responses.create({ model: 'openai/gpt-6-luna', input: 'Name the capital of France in one word.', }); console.log(response.status); } catch (error) { if (error instanceof RouterError) { const subkind = 'subkind' in error.data ? `.${error.data.subkind}` : ''; console.log(`failed: ${error.data.kind}${subkind}`); } else if (error instanceof Error && 'kind' in error) { console.log(`refused: ${String(error.kind)}`); } else { throw error; } } ``` ```python from tokedex import Router from tokedex.core import RouterError from tokedex.engine import GatewayError with Router() as router: try: response = router.responses.create( model="openai/gpt-6-luna", input="Name the capital of France in one word." ) print(response.status) except GatewayError as error: print(f"refused: {error.kind}") except RouterError as error: subkind = getattr(error.data, "subkind", None) print(f"failed: {error.data.kind}" + (f".{subkind}" if subkind else "")) ``` ```rust use tokedex::{Error, Router, RouterError, wire}; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder().build()?; let request = wire::ResponsesRequest::new("openai/gpt-6-luna", "Name the capital of France in one word."); match router.responses().create(request).await { Ok(response) => println!("{}", response.status), Err(Error::Routing(refusal)) => println!("refused: {:?}", refusal.kind), Err(Error::Router(error)) => match *error { RouterError::Provider { subkind, .. } => println!("failed: Provider.{subkind:?}"), RouterError::Network { subkind, .. } => println!("failed: Network.{subkind:?}"), other => println!("failed: {other}"), }, Err(other) => return Err(other.into()), } Ok(()) } ``` ```text failed: Provider.RateLimit ``` That is what it prints when OpenAI answers with a rate limit. With no `OPENAI_API_KEY` set, it prints `refused: NotFound`, and when the call succeeds, `completed`, billed by OpenAI. - **Refused** means the Router did not send the call: the model is unknown, its key is missing, or the request asks for something the model cannot do. Nothing is billed. Most refusals carry a `kind`; [the list below](#router-refusals) has the rest. - **Failed** means the provider or the network failed and no other provider could take the call. The error is a `RouterError` whose kind and subkind, such as `Provider.RateLimit`, name what failed. A `Provider` failure is `Authentication`, `PermissionDenied`, `RateLimit`, `ContextWindowExceeded`, `BadRequest`, `ServerError`, `ServiceUnavailable`, `ContentRisk` or `SafetyBlocked`. A `Network` failure is `Timeout`, `Abort`, `ConnectionRefused`, `DnsFailure` or `Other`. Fix a refusal rather than retrying it: nothing was sent, and the same request is refused again. Retry a failure yourself only when it is `Provider.RateLimit`, `Provider.ServerError`, `Provider.ServiceUnavailable` or a `Network` failure other than `Abort` or a `Timeout` from your own timeout, and only after a wait: the Router has already tried every provider it could, and each retry is a new provider request. Fix the request or the key after any other failure. A failed tool raises its own error, and so does a reply that does not match your schema; see [Structured output](/sdk/structured-output). **TypeScript** In TypeScript, a missing provider key raises an error with `kind: 'NotFound'` that is not a `GatewayError`, so the sample checks `kind` rather than the class. ## Retries and provider fallback - A model can be served by several providers or provider accounts. When an attempt fails with a rate limit, a provider server error, a rejected provider key or a network failure, the Router moves to the next one that serves the model, up to the attempts the model allows. - A refusal, a [fidelity error](/sdk/translation) and a cancellation end the call at once. - When no attempt succeeds, you get the error of the failure, such as `RateLimitError` (Rust: `RouterError::Provider`). - Through a gateway, the gateway does this on its side; see [Run through a gateway](/sdk/gateway). - Retries and moving between providers apply to a Router that calls providers itself; a router you build from your own routes retries differently. See [Routes and failover](/sdk/routes-and-failover). ## Set a timeout ```ts const response = await router.responses.create( { model: 'openai/gpt-6-luna', input: 'Summarise the plot of Hamlet.' }, { timeoutMs: 30_000 }, ); ``` ```python response = router.responses.create( model="openai/gpt-6-luna", input="Summarise the plot of Hamlet.", timeout_ms=30_000 ) ``` ```rust use std::time::Duration; use tokedex::{RequestOptions, wire}; let patient = router.with_options(RequestOptions::default().timeout(Duration::from_secs(30))); let request = wire::ResponsesRequest::new("openai/gpt-6-luna", "Summarise the plot of Hamlet."); let response = patient.responses().create(request).await?; ``` The timeout covers the whole call, including every attempt, moving to another provider, a stream's reads, and every model call and tool of a `runTools` (Python, Rust: `run_tools`) run. A `streamTools` (Python, Rust: `stream_tools`) run starts the timeout at your first read. **TypeScript** On timeout, an embedded Router raises a `NetworkError` with subkind `Timeout`. Through a gateway, the SDK raises a `DOMException` named `TimeoutError`. **Python, Rust** On timeout, the Router raises a network error with subkind `Timeout` in both modes. The Router also plans with it. When a provider fails a [follow-up turn](/sdk/models#order-the-providers) and asks to be retried after a wait longer than the time left, the call moves to the next provider at once rather than wait. Through a gateway, the timeout ends the call on your side only; the gateway retries by its own rules. **TypeScript** Set the timeout with `timeoutMs` rather than a `signal` from `AbortSignal.timeout(ms)`. A signal ends the call when it fires, but the Router cannot tell from it when that will be, so a follow-up turn can start a wait that the signal then cuts short instead of moving to the next provider. You can pass a `signal` beside `timeoutMs` to cancel the call early. A `runTools` or `streamTools` run takes `timeoutMs` in its run options, beside `model` and `tools`, and its `signal` in its call options. Set a timeout on every call that a person or a job waits on, so a call that keeps moving between providers ends when you choose. Size it for the whole call, not one reply: a value that fits one reply can end a fallback, a long stream or a tool run early. ## Cancel a call ```ts const controller = new AbortController(); setTimeout(() => controller.abort(), 5_000); await router.responses.create( { model: 'openai/gpt-6-luna', input: 'Summarise the plot of Hamlet.' }, { signal: controller.signal }, ); ``` ```python import threading from tokedex.core import CancelToken cancel = CancelToken() threading.Timer(5, cancel.abort).start() router.responses.create(model="openai/gpt-6-luna", input="Summarise the plot of Hamlet.", cancel=cancel) ``` ```rust use tokedex::{CancellationToken, RequestOptions, wire}; let cancel = CancellationToken::new(); let trigger = cancel.clone(); tokio::spawn(async move { tokio::time::sleep(std::time::Duration::from_secs(5)).await; trigger.cancel(); }); let cancellable = router.with_options(RequestOptions::default().cancel(cancel)); let request = wire::ResponsesRequest::new("openai/gpt-6-luna", "Summarise the plot of Hamlet."); cancellable.responses().create(request).await?; ``` Cancel from anywhere in your program, here after five seconds. Cancellation ends the call immediately, including any retries or provider fallback. **TypeScript** An embedded Router raises a `NetworkError` with subkind `Abort`. Through a gateway, the SDK propagates the signal's reason. Calling `abort()` without a reason raises a `DOMException` named `AbortError`. **Python** An embedded Router raises a `NetworkError` with subkind `Abort`. Through a gateway, cancelling with `CancelToken` raises `asyncio.CancelledError`. **Rust** Cancellation raises a network error with subkind `Abort` in both modes. ## Gateway errors **TypeScript** When the gateway answers with an error, the call raises a `GatewayHttpError`, with the HTTP status in `status`, the gateway's message in `message`, its error code in `code` and the whole error object in `error`. **Python** When the gateway answers with an error, the call raises an `httpx2.HTTPStatusError`, with the status in `error.response.status_code` and the gateway's error object in `error.response.json()`. **Rust** A gateway error is `tokedex::Error::Router` holding a `RouterError::Provider`, whose subkind follows the status, such as `RateLimit` for `429`. Find the call under **Observability** by the request ID that `onResponseHeaders` (Python, Rust: `on_response_headers`) receives. Retry only the codes that [Errors and limits](/gateway/errors-and-limits#retryable-errors) marks as retryable, because the Router does not retry an error the gateway sends back. ## Stream failures Until the first event reaches your code, the Router can still move the call to another provider. After that, a failure is raised from your loop, so put the whole loop inside your error handling. A stream that closes before its API's final event fails too. **TypeScript** Through a gateway, a stream error raises `GatewayHttpError`. **Python** Through a gateway, an error event raises `httpx2.HTTPStatusError`, whose response holds the failing event. If the stream closes before its terminal event, iteration raises `ValueError`. Catch both around the whole loop. **Rust** Through a gateway, a stream error is a `RouterError`, as it is for a call. ## Router refusals **TypeScript** - An unknown model ID: `GatewayError` with kind `NotFound`. - A model whose provider has no key: an error with kind `NotFound` that is not a `GatewayError`. - An image or a file the model cannot take: `GatewayError` with kind `CapabilityUnsupported`. - `background: true`: `GatewayError` with kind `BadRequest`. - A field the model's API cannot carry under the call's fidelity policy: `FidelityError`, whose `issues` name each field. - A field with an invalid value: an error whose message names the field. It is a `TypeError` on `router.responses` and an `Error` named `WireParseError` on the other APIs, and neither is a `GatewayError`. - A `providers` pin that none of the named providers can serve: `ProviderNotServedError`, whose `providers` lists the ones that can. A malformed pin is a `TypeError`. **Python** - An unknown model ID, or a model whose provider has no key: `GatewayError`, from `tokedex.engine`, with kind `NotFound`. - `background=True`: `GatewayError` with kind `BadRequest`. - A field the model's API cannot carry under the call's fidelity policy, or an image or a file the model cannot take: `FidelityError`, from `tokedex.core.ir`, whose `issues` name each field. - A field with an invalid value: a `ValueError` that names the field. - A `providers` pin that none of the named providers can serve: `ProviderNotServedError`, whose `providers` lists the ones that can. A malformed pin is a `ValueError`. **Rust** - An unknown model ID, or a model whose provider has no key: `Error::Routing` holding a `GatewayError` with kind `NotFound`. - `background: true`: `Error::Routing` with kind `BadRequest`. - A field the model's API cannot carry under the call's fidelity policy, or an image or a file the model cannot take: `RouterError::FidelityError` inside `Error::Router`, whose `issues` name each field. - A `providers` pin that none of the named providers can serve: `Error::ProviderNotServed`, whose `providers` lists the ones that can. A malformed pin is `Error::Routing` with kind `BadRequest`. ## Report a problem [Open an issue on GitHub](https://github.com/ArtificialAnalysis/tokedex/issues/new) to report a bug, request a feature or point out a problem in these docs. Include the language, the SDK version, a short program that shows the problem and the error it raises. Remove keys and prompt text first: issues are public. Tokedex does not accept pull requests, so an issue is also the way to suggest a change. [Contributing](https://github.com/ArtificialAnalysis/tokedex/blob/main/CONTRIBUTING.md) has the full guidelines. Next: [Run through a gateway](/sdk/gateway), [Routes and failover](/sdk/routes-and-failover) or [Observability](/sdk/observability). --- # Observability Watch each call the Router makes: the provider and model it chose, each attempt, and how the call ended. ```ts import { Router } from '@tokedex/sdk'; const router = new Router({ observer: (event) => console.log(event.stage, event.providerName, event.model), }); for (const model of ['openai/gpt-6-luna', 'anthropic/claude-haiku-5.5']) { await router.responses.create({ model, input: 'Name the capital of France in one word.' }); } ``` ```python from typing import Any from tokedex import Router def show(event: Any) -> None: print(event["stage"], event["providerName"], event["model"]) with Router(observer=show) as router: for model in ["openai/gpt-6-luna", "anthropic/claude-haiku-5.5"]: router.responses.create(model=model, input="Name the capital of France in one word.") ``` ```rust use std::sync::Arc; use tokedex::{Router, wire}; use tokedex_core::observers::LifecycleEvent; #[tokio::main] async fn main() -> Result<(), Box> { let router = Router::builder() .observer(Arc::new(|event: &LifecycleEvent| { if let LifecycleEvent::Canonical { base, event } = event { println!("{:?} {} {}", event.stage, base.provider_name, base.model); } })) .build()?; for model in ["openai/gpt-6-luna", "anthropic/claude-haiku-5.5"] { let request = wire::ResponsesRequest::new(model, "Name the capital of France in one word."); router.responses().create(request).await?; } Ok(()) } ``` **TypeScript, Python** ```text route-select openai gpt-6-luna pre-submit openai gpt-6-luna completion openai gpt-6-luna route-select anthropic claude-haiku-5-5 pre-submit anthropic claude-haiku-5-5 completion anthropic claude-haiku-5-5 ``` **Rust** ```text RouteSelect openai gpt-6-luna PreSubmit openai gpt-6-luna Completion openai gpt-6-luna RouteSelect anthropic claude-haiku-5-5 PreSubmit anthropic claude-haiku-5-5 Completion anthropic claude-haiku-5-5 ``` **TypeScript** It needs `OPENAI_API_KEY` and `ANTHROPIC_API_KEY`, and each call is billed by its provider. Run it with `npx tsx observe.ts`. **Python** It needs `OPENAI_API_KEY` and `ANTHROPIC_API_KEY`, and each call is billed by its provider. Each event is a dictionary with the field names shown in TypeScript. **Rust** It needs `OPENAI_API_KEY` and `ANTHROPIC_API_KEY`, and each call is billed by its provider. Add `cargo add tokedex-core` for the event types. Every event from a Router is `LifecycleEvent::Canonical`, with the shared fields in `base`. The observer hears every call in the order it happens, whichever API the call uses. Use an observer with the `Router` object. With a router you build from your own routes, use an observer or the [telemetry sink](#use-the-sdks-telemetry-sink), since only such a router takes sinks. Use the gateway's dashboard when the Router [runs through a gateway](#through-a-gateway), which takes no observer. ## Observer stages | Stage | When | |---|---| | `route-select` | The Router has chosen a provider and model for an attempt | | `pre-submit` | The request is about to go to the provider | | `stream-start`, `chunk`, `stream-end` | A stream opens, delivers each event to your code, and closes | | `completion` | The call finished, with the result and its duration | | `error` | An attempt failed, with the error's kind and subkind and its duration | | `retry-attempt` | The Router is about to try the same provider again, with the error and the wait before the next try | When an attempt fails and the Router moves to another provider, an `error` event is followed by a new `route-select`. On a follow-up turn of a conversation, the Router can first try the same provider again ([Order the providers](/sdk/models#order-the-providers)): the `error` event is then followed by `retry-attempt`, whose `backoffMs` (Rust: `backoff_ms`) is the wait in milliseconds. The Router never answers from a cache, so it never sends `cache-lookup`. ## Event fields Every event names the `stage`, the `providerName` (Rust: `provider_name`), the `model`, the attempt number and a `requestId` (Rust: `request_id`) that stays the same for every event of one call. `pre-submit` carries the request, `completion` the result and `error` the error's data, so an observer sees prompts and response text. Keep it in your own process. **TypeScript** An observer runs synchronously and the Router never waits for it. An observer that throws does not affect the call. **Python, Rust** An observer runs synchronously, and one that fails does not affect the call. ## Send events to your own collector ```ts import { Router, type RouterLifecycleEvent } from '@tokedex/sdk'; const records: object[] = []; const recorded = new Router({ observer: (event: RouterLifecycleEvent) => { if (event.stage !== 'completion' && event.stage !== 'error') return; records.push({ requestId: event.requestId, provider: event.providerName, model: event.model, durationMs: event.durationMs, error: event.stage === 'error' ? event.error.kind : undefined, }); }, }); // On your own schedule, and once before your program exits: await fetch(process.env['COLLECTOR_URL']!, { method: 'POST', body: JSON.stringify(records.splice(0)) }); ``` ```python import os from typing import Any import httpx2 from tokedex import Router records: list[dict[str, Any]] = [] def record(event: Any) -> None: if event["stage"] in ("completion", "error"): records.append( { "requestId": event["requestId"], "provider": event["providerName"], "model": event["model"], "durationMs": event["durationMs"], "error": event["error"]["kind"] if event["stage"] == "error" else None, } ) recorded = Router(observer=record) # On your own schedule, and once before your program exits: httpx2.post(os.environ["COLLECTOR_URL"], json=records) records.clear() ``` ```rust use std::sync::{Arc, Mutex}; use serde_json::{Value, json}; use tokedex::Router; use tokedex_core::observers::{LifecycleEvent, LifecycleStage}; let records: Arc>> = Arc::default(); let sink = records.clone(); let recorded = Router::builder() .observer(Arc::new(move |event: &LifecycleEvent| { if let LifecycleEvent::Canonical { base, event } = event { if matches!(event.stage, LifecycleStage::Completion | LifecycleStage::Error) { sink.lock().unwrap().push(json!({ "requestId": base.request_id, "provider": base.provider_name, "model": base.model, "durationMs": event.duration_ms, "error": event.error.as_ref().map(|error| format!("{error:?}")), })); } } })) .build()?; // On your own schedule, send records.lock().unwrap().drain(..) to your collector. ``` Copy only the fields you want to keep, as here, so prompts and response text stay in your process, and send the records away from the call path, because the observer runs synchronously. ## Use the SDK's telemetry sink The telemetry sink attaches to a router you build yourself with the core package, from routes and provider clients you choose. It batches metadata about each call and posts it to your collector. ```ts import { chat, createRouter } from '@tokedex/core'; import { openai } from '@tokedex/openai'; import { flushTelemetry, tokedexTelemetry } from '@tokedex/sdk'; const telemetry = tokedexTelemetry({ endpoint: process.env['TOKEDEX_TELEMETRY_ENDPOINT']! }); const coreRouter = createRouter({ routes: [{ provider: openai(), model: 'gpt-6-luna' }], sinks: [telemetry.sink], }); await chat(coreRouter, { messages: [{ role: 'user', content: 'Name the capital of France in one word.' }] }); await flushTelemetry(telemetry); ``` ```python import os from tokedex.core import Route, chat, create_router from tokedex.providers.openai import openai from tokedex.telemetry import TokedexTelemetryOptions, flush_telemetry, tokedex_telemetry telemetry = tokedex_telemetry( TokedexTelemetryOptions(endpoint=os.environ["TOKEDEX_TELEMETRY_ENDPOINT"]) ) core_router = create_router( routes=[Route(provider=openai(), model="gpt-6-luna")], sinks=[telemetry.sink] ) await chat( core_router, {"messages": [{"role": "user", "content": "Name the capital of France in one word."}]}, ) await flush_telemetry(telemetry) ``` ```rust use std::sync::Arc; use tokedex::telemetry::{TokedexTelemetryOptions, flush_telemetry, tokedex_telemetry}; use tokedex_core::chat::{ChatCallOptions, chat}; use tokedex_core::router::{Route, RouterConfig, create_router}; use tokedex_core::types::{ChatRequest, Message}; use tokedex_openai::{OpenAiOptions, openai}; let telemetry = tokedex_telemetry( TokedexTelemetryOptions::new().endpoint(std::env::var("TOKEDEX_TELEMETRY_ENDPOINT")?), )?; let core_router = create_router(RouterConfig { routes: vec![Route { deployment_id: None, provider: Arc::new(openai(OpenAiOptions::default())?), model: "gpt-6-luna".into(), tags: None, }], sinks: vec![telemetry.sink()], ..Default::default() })?; let request = ChatRequest::builder() .model("gpt-6-luna") .messages(vec![Message::User { content: "Name the capital of France in one word.".into() }]) .build(); chat(&core_router, request, ChatCallOptions::default()).await?; flush_telemetry(&telemetry).await; ``` **TypeScript** It needs `npm install @tokedex/core @tokedex/openai`; `@tokedex/sdk` exports the telemetry functions. **Rust** It needs `cargo add tokedex-core tokedex-openai`; `tokedex` re-exports the telemetry crate as `tokedex::telemetry`. - **Options.** `endpoint`, your collector's URL, is required. `collectorToken` (Python, Rust: `collector_token`) goes to that URL only, as `Authorization: Bearer `. `maxBatch` (Python, Rust: `max_batch`) (default `50`) and `sampleRate` (Python, Rust: `sample_rate`) (default `1`) set the batch size and the share of calls sent. Keep `sampleRate` (Python, Rust: `sample_rate`) at `1` unless your collector cannot take every call, because a lower rate leaves calls out of every count you draw from it. - **What is sent.** Each batch is JSON with `sdk`, `schemaVersion`, `sentAt` and `events`: `request_start`, `response`, `error` and `retry_attempt`, with IDs, provider, model, timings, token usage and error kinds. No prompts, tool arguments or results, response text or error messages. - **Flushing.** The sink posts when it holds `maxBatch` (Python, Rust: `max_batch`) events and has no timer, so flush on an interval and before your program exits. A failed post is dropped and never affects a call. Flush in your shutdown handler as well, so a normal exit loses nothing; only a crash loses the events since the last flush. ## Through a gateway A Router that [runs through a gateway](/sdk/gateway) takes no observer: the gateway records each call, with its provider, model, token usage and errors, under **Observability** and **Usage** in its dashboard. Passing an observer with a gateway address fails. To find one of your calls there, read its request ID from `onResponseHeaders` (Python, Rust: `on_response_headers`), and tag or group calls with the `x-tokedex-tags` and `x-tokedex-trajectory-id` headers. To send the gateway's traces to your own collector, see [Export traces with OpenTelemetry](/gateway/export-traces). Next: [Errors, retries and timeouts](/sdk/errors-and-retries), [Run through a gateway](/sdk/gateway) or [Hooks and sinks](/sdk/hooks-and-sinks). --- # Routes and failover The `Router` object picks providers and fails over for you. Use the core package instead when you want to list your own providers and models, in your order of preference. Start with the `Router` object; it reaches your own servers as [custom models](/sdk/custom-models). Build your own routes when you need a fixed order of providers, a host that must take images, files or structured output, which a custom model refuses, or [hooks and sinks](/sdk/hooks-and-sinks), which only a router you build takes. ```ts import { chat, createRouter } from '@tokedex/core'; import { anthropic } from '@tokedex/anthropic'; import { openai } from '@tokedex/openai'; const router = createRouter({ routes: [ { provider: openai(), model: 'gpt-6-luna' }, { provider: anthropic(), model: 'claude-haiku-5-5' }, ], }); const res = await chat(router, 'Name the capital of France in one word.'); console.log(`${res.provider}: ${res.text}`); ``` ```python import asyncio from tokedex.core import Route, chat, create_router from tokedex.providers.anthropic import anthropic from tokedex.providers.openai import openai async def main() -> None: router = create_router( routes=[ Route(provider=openai(), model="gpt-6-luna"), Route(provider=anthropic(), model="claude-haiku-5-5"), ] ) res = await chat(router, "Name the capital of France in one word.") print(f"{res.provider}: {res.text}") asyncio.run(main()) ``` ```rust use std::sync::Arc; use tokedex_anthropic::{AnthropicOptions, anthropic}; use tokedex_core::chat::{ChatCallOptions, chat}; use tokedex_core::router::{Route, RouterConfig, create_router}; use tokedex_openai::{OpenAiOptions, openai}; #[tokio::main] async fn main() -> Result<(), Box> { let primary = Arc::new(openai(OpenAiOptions::default())?); let fallback = Arc::new(anthropic(AnthropicOptions::default())?); let router = create_router(RouterConfig { routes: vec![ Route { deployment_id: None, provider: primary, model: "gpt-6-luna".into(), tags: None }, Route { deployment_id: None, provider: fallback, model: "claude-haiku-5-5".into(), tags: None }, ], ..Default::default() })?; let res = chat(&router, "Name the capital of France in one word.", ChatCallOptions::default()).await?; println!("{}: {}", res.provider, res.text); Ok(()) } ``` ```text openai: Paris ``` It needs `OPENAI_API_KEY` and `ANTHROPIC_API_KEY`, and each call is billed by the provider that answers. When the OpenAI call fails, the same program prints `anthropic: Paris`. Each route's `model` is the provider's own model ID. ## Install the core package **TypeScript** Run `npm install @tokedex/core` and add a provider package for each provider you route to: `@tokedex/openai`, `@tokedex/anthropic`, `@tokedex/google`, `@tokedex/openai-compatible` or `@tokedex/local-llm`. **Python** `uv add tokedex` includes the core package, `tokedex.core`, and every provider client, in `tokedex.providers`. **Rust** Run `cargo add tokedex-core` and add a crate for each provider you route to: `tokedex-openai`, `tokedex-anthropic`, `tokedex-google`, `tokedex-openai-compatible` or `tokedex-local-llm`. The samples also need `cargo add tokio --features macros,rt-multi-thread`. ## Connect each provider | Provider | Client | From | Key | |---|---|---|---| | OpenAI | `openai` | `@tokedex/openai` (Python: `tokedex.providers.openai`; Rust: `tokedex-openai`) | `OPENAI_API_KEY` | | Anthropic | `anthropic` | `@tokedex/anthropic` (Python: `tokedex.providers.anthropic`; Rust: `tokedex-anthropic`) | `ANTHROPIC_API_KEY` | | Google | `google` | `@tokedex/google` (Python: `tokedex.providers.google`; Rust: `tokedex-google`) | `GEMINI_API_KEY`, `GOOGLE_AI_API_KEY` or `GOOGLE_API_KEY` | | xAI | `xai` | `@tokedex/openai-compatible` (Python: `tokedex.providers.openai_compatible`; Rust: `tokedex-openai-compatible`) | `XAI_API_KEY` | | Any host that speaks OpenAI Chat Completions | `openAiCompatible` (Python, Rust: `openai_compatible`) | `@tokedex/openai-compatible` (Python: `tokedex.providers.openai_compatible`; Rust: `tokedex-openai-compatible`) | The key you pass | | LM Studio, Ollama | `lmStudio, ollama` (Python, Rust: `lm_studio, ollama`) | `@tokedex/local-llm` (Python: `tokedex.providers.local`; Rust: `tokedex-local-llm`) | None | Each client reads its key from the variable when you pass none: ```ts import { lmStudio, ollama } from '@tokedex/local-llm'; import { openAiCompatible } from '@tokedex/openai-compatible'; const groq = openAiCompatible({ baseUrl: 'https://api.groq.com/openai', name: 'groq', apiKey: process.env['GROQ_API_KEY'] ?? '', capabilities: ['toolCalling'], }); const studio = lmStudio(); const local = ollama({ baseUrl: 'http://192.168.1.20:11434' }); ``` ```python import os from tokedex.providers.local import lm_studio, ollama from tokedex.providers.openai_compatible import openai_compatible groq = openai_compatible( base_url="https://api.groq.com/openai", name="groq", api_key=os.environ["GROQ_API_KEY"], capabilities=["toolCalling"], ) studio = lm_studio() local = ollama(base_url="http://192.168.1.20:11434") ``` ```rust use tokedex_core::capabilities::ProviderCapability; use tokedex_local_llm::{LmStudioOptions, OllamaOptions, lm_studio, ollama}; use tokedex_openai_compatible::{OpenAiCompatibleOptions, openai_compatible}; let mut options = OpenAiCompatibleOptions::new("https://api.groq.com/openai"); options.name = Some("groq".into()); options.api_key = Some(std::env::var("GROQ_API_KEY")?.into()); options.capabilities = Some(vec![ProviderCapability::Streaming, ProviderCapability::ToolCalling]); let groq = openai_compatible(options)?; let studio = lm_studio(LmStudioOptions::default())?; let mut ollama_options = OllamaOptions::default(); ollama_options.base_url = Some("http://192.168.1.20:11434".into()); let local = ollama(ollama_options)?; ``` An OpenAI-compatible client takes the host's address without `/v1`. It sends every request as it is until you list its `capabilities`; then it refuses tools, images, reasoning or structured output the list leaves out, so list only what the host supports. A client refuses a request that needs a capability it lacks, such as tools on a client without `toolCalling`, before sending it; the router then tries the next route. LM Studio is at `http://127.0.0.1:1234` and Ollama at `http://localhost:11434` unless you pass another address. ## Retries and failover | Error | The router | |---|---| | A rate limit, a server error, an unavailable service or a network failure | Retries the same route after a backoff | | Any other error, such as a bad key or a bad request | Moves to the next route at once | | Cancellation, a document it cannot read, or a provider reply it cannot parse | Fails the call at once | A call has three attempts. Each retry uses one, and moving to the next route does not. The backoff starts at 250 ms and doubles up to 8 seconds, with 25% jitter, unless the provider sends `Retry-After`. Set `retries` (Rust: `RouterConfig.retries`) to change them, such as `{ maxAttempts: 5 }` (Python: `RetryPolicy(max_attempts=5)`; Rust: `RetryPolicy { max_attempts: 5, ..RetryPolicy::DEFAULT }`). A [stream](/sdk/streaming) gets one attempt on each route, with no retries. Put the route you want to answer most calls first, and a route on another provider next, so a bad key or a missing capability on one provider does not stop the call. Outside a stream, routes do not cover a rate limit or an outage: those are retried on the same route, and when the attempts run out there the call fails without trying the next route. Raise the attempts only for work nobody waits on, since each retry waits longer than the last. When every route fails, the call raises `AllRoutesFailedError` (Rust: `RouterError::AllRoutesFailed`), whose `data.attempts` (Rust: `attempts`) lists each failure. When the attempts run out first, it raises the last route's error. ## See which route answered `res.provider` names the provider that answered and `res.model` the model. To see every attempt, add `consoleObserver()` (Python: `console_observer()`; Rust: `console_observer(ConsoleObserverOptions::default())`) to the router's `observers`. It writes a line to standard error at each stage, such as `route-select`, `error` and `completion`, naming the provider, model, attempt and request ID, and the error's kind when an attempt fails. The lines hold no prompts or response text, so you can keep them in your logs. ## Run tools and structured output on your routes ```ts const Country = z.object({ capital: z.string(), currency: z.string() }); const country = await structured(router, 'What is the capital of France, and its currency code?', { schema: Country, }); console.log(country.parsed.capital); const result = await run(router, 'What is the weather in Tokyo?', { tools: [getWeather] }); console.log(result.finalResponse.text); ``` ```python from pydantic import BaseModel from tokedex.core import run, structured class Country(BaseModel): capital: str currency: str country = await structured( router, "What is the capital of France, and its currency code?", schema=Country ) print(country.parsed.capital) result = await run(router, "What is the weather in Tokyo?", tools=[get_weather]) print(result.final_response.text) ``` ```rust use schemars::JsonSchema; use serde::Deserialize; use tokedex_core::chat::ChatCallOptions; use tokedex_core::run::{RunOptions, run}; use tokedex_core::structured::{StructuredOptions, structured}; #[derive(Deserialize, JsonSchema)] struct Country { capital: String, currency: String, } let country = structured::( &router, "What is the capital of France, and its currency code?", StructuredOptions::default(), ChatCallOptions::default(), ) .await?; println!("{}", country.parsed.capital); let options = RunOptions { tools: vec![get_weather], ..Default::default() }; let result = run(&router, "What is the weather in Tokyo?", options, ChatCallOptions::default()).await?; println!("{}", result.final_response.text); ``` `structured` asks for JSON that matches your type and returns it checked in `parsed`. `run` calls your tools until the model answers, like `runTools` (Python, Rust: `run_tools`) on the `Router` object. Both take any router from `createRouter` (Python, Rust: `create_router`), and `runStream` (Python, Rust: `run_stream`) streams a run's events. The provider-native model ID `gpt-6-luna` takes tools on OpenAI Chat Completions only with reasoning effort `none`, so set `reasoning: { effort: 'none' }` (Python: `reasoning=ReasoningConfig(effort="none")`; Rust: `reasoning: Some(ReasoningConfig { effort: Some(ReasoningEffort::None), ..Default::default() })`) in a run that uses it on these direct-provider routes. Calls through the SDK's catalogue `Router` or a gateway instead use the public ID `openai/gpt-6-luna`. Next: [Hooks and sinks](/sdk/hooks-and-sinks). --- # Hooks and sinks Change each call your router makes with a hook, or record it with a sink. Both belong to the core package's `createRouter` (Python, Rust: `create_router`); the `Router` object reports its calls to an [observer](/sdk/observability) instead. ```ts import { chat, createRouter } from '@tokedex/core'; import { openai } from '@tokedex/openai'; const router = createRouter({ routes: [{ provider: openai(), model: 'gpt-6-luna' }], hooks: { onPreSubmit: [ (req) => ({ ...req, messages: [{ role: 'system', content: 'Answer in one word.' }, ...req.messages] }), ], }, }); const res = await chat(router, 'What is the capital of France?'); console.log(res.text); ``` ```python import asyncio from tokedex.core import Hooks, Route, SystemMessage, chat, create_router from tokedex.providers.openai import openai def add_system_prompt(req, _ctx): system = SystemMessage(content="Answer in one word.") return req.model_copy(update={"messages": [system, *req.messages]}) async def main() -> None: router = create_router( routes=[Route(provider=openai(), model="gpt-6-luna")], hooks=Hooks(on_pre_submit=[add_system_prompt]), ) res = await chat(router, "What is the capital of France?") print(res.text) asyncio.run(main()) ``` ```rust use std::sync::Arc; use async_trait::async_trait; use tokedex_core::chat::{ChatCallOptions, chat}; use tokedex_core::errors::RouterError; use tokedex_core::hooks::{Hook, HookCtx}; use tokedex_core::router::{Route, RouterConfig, create_router}; use tokedex_core::types::{ChatRequest, Message}; use tokedex_openai::{OpenAiOptions, openai}; struct AddSystemPrompt; #[async_trait] impl Hook for AddSystemPrompt { async fn on_pre_submit(&self, mut req: ChatRequest, _ctx: &HookCtx) -> Result { let system = Message::System { content: "Answer in one word.".into(), prompt_cache_breakpoint: None }; req.messages.insert(0, system); Ok(req) } } #[tokio::main] async fn main() -> Result<(), Box> { let provider = Arc::new(openai(OpenAiOptions::default())?); let router = create_router(RouterConfig { routes: vec![Route { deployment_id: None, provider, model: "gpt-6-luna".into(), tags: None }], hooks: vec![Arc::new(AddSystemPrompt)], ..Default::default() })?; let res = chat(&router, "What is the capital of France?", ChatCallOptions::default()).await?; println!("{}", res.text); Ok(()) } ``` ```text Paris ``` It needs `OPENAI_API_KEY`, and the call is billed by OpenAI. Install the packages as in [Routes and failover](/sdk/routes-and-failover#install-the-core-package). **Rust** It also needs `cargo add async-trait`. ## Choose a hook or a sink A hook runs inside the call and can change it: the request, the route, the response or what happens after an error. A sink receives events about the call, such as its model, token usage and duration, and cannot change it. Use a hook to redact, rewrite, cache or recover; use a sink to log or measure. Prefer a sink for anything that only records, because it never receives prompts or response text, and a sink that fails logs a warning where a hook that fails ends the call. ## Hook stages | Stage | Runs | Can | |---|---|---| | `onRouteSelect` (Python, Rust: `on_route_select`) | Before each attempt | Choose a different route | | `onPreSubmit` (Python, Rust: `on_pre_submit`) | Before each attempt, once the route's model is set | Return a changed request | | `onCacheLookup` (Python, Rust: `on_cache_lookup`) | After `onPreSubmit` (Python, Rust: `on_pre_submit`) | Return a response, which skips the provider | | `onCompletion` (Python, Rust: `on_completion`) | After a successful attempt | Return a changed response | | `onError` (Python, Rust: `on_error`) | After a failed attempt | Answer, retry, or leave it to the router | | `onRetryAttempt` (Python, Rust: `on_retry_attempt`) | Before the router waits to retry | Observe the retry | | `onStreamStart` (Python, Rust: `on_stream_start`), `onStreamTransform` (Python, Rust: `on_stream_transform`) | When a stream starts | Set up stream state, or wrap the whole stream | | `onChunk` (Python, Rust: `on_chunk`) | For each streamed delta | Change, drop or split it | | `onStreamEnd` (Python, Rust: `on_stream_end`) | When a stream closes | Clean up | **TypeScript, Python** Each stage takes a list of functions, which run in order. **Rust** A hook implements the `Hook` trait's method for each stage it uses, and `hooks` takes a list of them, which run in order. Every attempt starts from the request you passed, so the system message above is added once however often the router retries. If a hook throws, the call fails, so catch errors inside a hook whose work the call can do without. `emptyResponsePatch()` (Python, Rust: `empty_response_patch()`) is a built-in `onPreSubmit` (Python, Rust: `on_pre_submit`) hook that fills blank messages for providers that reject them. ## Answer from a cache ```ts import type { ChatResponse } from '@tokedex/core'; const cache = new Map(); const keys = new Map(); const cached = createRouter({ routes: [{ provider, model: 'gpt-6-luna' }], hooks: { onCacheLookup: [ (req, ctx) => { const key = JSON.stringify(req.messages); const hit = cache.get(key); if (hit !== undefined) return hit; keys.set(ctx.requestId, key); return undefined; }, ], onCompletion: [ (res, ctx) => { const key = keys.get(ctx.requestId); if (key !== undefined) cache.set(key, res); keys.delete(ctx.requestId); return res; }, ], onError: [ (_error, _req, ctx) => { keys.delete(ctx.requestId); return undefined; }, ], }, }); ``` ```python import json from tokedex.core import ChatResponse, Hooks, Route, create_router cache: dict[str, ChatResponse] = {} keys: dict[str, str] = {} def lookup(req, ctx): key = json.dumps([m.model_dump(by_alias=True, mode="json") for m in req.messages]) hit = cache.get(key) if hit is not None: return hit keys[ctx.request_id] = key return None def store(res, ctx): key = keys.pop(ctx.request_id, None) if key is not None: cache[key] = res return res def forget(_error, _req, ctx): keys.pop(ctx.request_id, None) cached = create_router( routes=[Route(provider=provider, model="gpt-6-luna")], hooks=Hooks(on_cache_lookup=[lookup], on_completion=[store], on_error=[forget]), ) ``` ```rust use std::collections::HashMap; use std::sync::Mutex; use async_trait::async_trait; use tokedex_core::errors::RouterError; use tokedex_core::hooks::{Hook, HookCtx, OnErrorDecision}; use tokedex_core::types::{ChatRequest, ChatResponse}; #[derive(Default)] struct ResponseCache { entries: Mutex>, keys: Mutex>, } #[async_trait] impl Hook for ResponseCache { async fn on_cache_lookup(&self, req: &ChatRequest, ctx: &HookCtx) -> Result, RouterError> { let key = serde_json::to_string(&req.messages).unwrap_or_default(); if let Some(hit) = self.entries.lock().unwrap().get(&key).cloned() { return Ok(Some(hit)); } self.keys.lock().unwrap().insert(ctx.request_id.clone(), key); Ok(None) } async fn on_completion(&self, res: ChatResponse, ctx: &HookCtx) -> Result { if let Some(key) = self.keys.lock().unwrap().remove(&ctx.request_id) { self.entries.lock().unwrap().insert(key, res.clone()); } Ok(res) } async fn on_error(&self, _err: &RouterError, _req: &ChatRequest, ctx: &HookCtx) -> Result, RouterError> { self.keys.lock().unwrap().remove(&ctx.request_id); Ok(None) } } ``` A cache hit returns straight from `onCacheLookup` (Python, Rust: `on_cache_lookup`). On a miss, save the key by request ID so `onCompletion` (Python, Rust: `on_completion`) can store the provider response. The completion and error hooks both remove the temporary key. A retry looks up the cache again. > **Tip:** Build the key from every part of the request that changes the answer, not only the messages as here, so a call with other tools or settings does not get another call's response. Limit the cache's size too: this one grows with every new request. ## Decide what happens after an error ```ts const shortening = createRouter({ routes: [{ provider, model: 'gpt-6-luna' }], hooks: { onError: [ (err, req) => { if (err.kind === 'Provider' && err.subkind === 'ContextWindowExceeded') { return { action: 'retry', request: { ...req, messages: req.messages.slice(-1) } }; } return undefined; }, ], }, }); ``` ```python from tokedex.core import Hooks, Route, create_router from tokedex.core.hooks import RetryDecision def retry_shorter(err, req, _ctx): if err.kind == "Provider" and err.subkind == "ContextWindowExceeded": return RetryDecision(request=req.model_copy(update={"messages": req.messages[-1:]})) return None shortening = create_router( routes=[Route(provider=provider, model="gpt-6-luna")], hooks=Hooks(on_error=[retry_shorter]), ) ``` ```rust use async_trait::async_trait; use tokedex_core::errors::{ProviderErrorSubkind, RouterError}; use tokedex_core::hooks::{Hook, HookCtx, OnErrorDecision}; use tokedex_core::types::ChatRequest; struct RetryShorter; #[async_trait] impl Hook for RetryShorter { async fn on_error(&self, err: &RouterError, req: &ChatRequest, _ctx: &HookCtx) -> Result, RouterError> { if let RouterError::Provider { subkind: ProviderErrorSubkind::ContextWindowExceeded, .. } = err { let mut shorter = req.clone(); shorter.messages = req.messages.last().cloned().into_iter().collect(); return Ok(Some(OnErrorDecision::Retry { request: Some(Box::new(shorter)) })); } Ok(None) } } ``` When the conversation is too long for the model, this retries with only the latest message. Return a response to answer with it, a retry to try the same route again, which uses one of the call's attempts, or nothing to let the router [retry or fail over](/sdk/routes-and-failover#retries-and-failover). A cancelled call, a document the router cannot read and a provider reply it cannot parse skip `onError` (Python, Rust: `on_error`) and reach your code directly. ## Log every call ```ts import { LoggingSink } from '@tokedex/core'; const logged = createRouter({ routes: [{ provider, model: 'gpt-6-luna' }], sinks: [LoggingSink()] }); ``` ```python from tokedex.core import LoggingSink, Route, create_router logged = create_router(routes=[Route(provider=provider, model="gpt-6-luna")], sinks=[LoggingSink()]) ``` ```rust use std::sync::Arc; use tokedex_core::router::{Route, RouterConfig, create_router}; use tokedex_core::sinks::LoggingSink; let logged = create_router(RouterConfig { routes: vec![Route { deployment_id: None, provider, model: "gpt-6-luna".into(), tags: None }], sinks: vec![Arc::new(LoggingSink::new())], ..Default::default() })?; ``` ```json {"event":"response","requestId":"…","provider":"openai","model":"gpt-6-luna","durationMs":312,"finishReason":"stop","usage":{"inputTokens":9,"outputTokens":1,"totalTokens":10}} ``` **TypeScript, Python** Each event writes one JSON line like this to standard output. To send the lines elsewhere, pass `logger` (Python, Rust: `log`) to `LoggingSink`. **Rust** Each event writes one line like this with `tracing`, at the `info` level. To send the lines elsewhere, use `LoggingSink::with_logger`. To send each call's telemetry to a collector instead, see [Observability](/sdk/observability). ## Write your own sink ```ts import type { Sink } from '@tokedex/core'; const metricsSink: Sink = { onResponse: (event) => { metrics.histogram('model.tokens', event.usage?.totalTokens ?? 0, { provider: event.provider }); metrics.histogram('model.latency_ms', event.durationMs, { provider: event.provider }); }, onError: (event) => metrics.increment('model.errors', { provider: event.provider, kind: event.data.kind }), }; const measured = createRouter({ routes: [{ provider, model: 'gpt-6-luna' }], sinks: [metricsSink] }); ``` ```python from tokedex.core import Route, Sink, create_router class MetricsSink(Sink): def on_response(self, event) -> None: tokens = event.usage.total_tokens if event.usage else 0 print(f"tokens={tokens} latency_ms={event.duration_ms}") def on_error(self, event) -> None: print(f"error provider={event.provider} kind={event.data.kind}") measured = create_router(routes=[Route(provider=provider, model="gpt-6-luna")], sinks=[MetricsSink()]) ``` ```rust use std::sync::Arc; use async_trait::async_trait; use tokedex_core::errors::BoxError; use tokedex_core::router::{Route, RouterConfig, create_router}; use tokedex_core::sinks::{ErrorEvent, ResponseEvent, Sink}; struct MetricsSink; #[async_trait] impl Sink for MetricsSink { async fn on_response(&self, event: &ResponseEvent) -> Result<(), BoxError> { let tokens = event.usage.as_ref().map_or(0, |usage| usage.total_tokens); println!("tokens={tokens} latency_ms={}", event.duration_ms); Ok(()) } async fn on_error(&self, event: &ErrorEvent) -> Result<(), BoxError> { println!("error provider={}", event.provider); Ok(()) } } let measured = create_router(RouterConfig { routes: vec![Route { deployment_id: None, provider, model: "gpt-6-luna".into(), tags: None }], sinks: vec![Arc::new(MetricsSink)], ..Default::default() })?; ``` A sink implements only the methods it needs: `onRequestStart` (Python, Rust: `on_request_start`), `onResponse` (Python, Rust: `on_response`), `onError` (Python, Rust: `on_error`), `onRetryAttempt` (Python, Rust: `on_retry_attempt`), `onStreamStart` (Python, Rust: `on_stream_start`), `onStreamChunk` (Python, Rust: `on_stream_chunk`) and `onStreamEnd` (Python, Rust: `on_stream_end`). The call waits for each one, so keep them quick: record the values and send them on your own schedule. If one fails, the SDK logs a warning and the call goes on. ## Data a sink receives A sink receives metadata: the request ID, provider, model, timings, token usage, finish reason, and a summary of the request in counts and flags. It never receives prompts, messages, tool arguments or response text. An error event carries the provider's error message as sent, which can quote your request, so leave the message out of what a sink sends off your machine, as the metrics sink above does. Hooks, by contrast, receive the full request and response. Next: [Routes and failover](/sdk/routes-and-failover) or [Observability](/sdk/observability). --- # CLI overview `tdx` manages a running gateway from a terminal or a script: API keys, budgets, people, workspaces, models, spend, traces and the audit log. It calls the gateway's management endpoints as you, or with an admin key, and prints every result as versioned JSON, so the same commands serve a person, a CI job and a coding agent. ## Install and sign in You need a running gateway and an account on its dashboard. [Install the CLI](/cli/quickstart#install-the-cli), then sign in. ```bash tdx auth login --host http://127.0.0.1:4000 ``` ```text Open http://127.0.0.1:4000/cli-sign-in Enter this code in the browser: SFBB-ZWBT Only enter a code that your own terminal shows you. The code expires in 10 minutes. Opened your browser. Waiting for approval… (Ctrl-C to cancel) ``` Enter the code on the page that opens and choose **Approve**. `tdx auth login` then saves a personal access token that acts as you, with the gateway's address, in a profile only your user can read, so later commands need neither: ```bash tdx api-keys list ``` ```json { "schemaVersion": "tokedex.cli.v1", "command": "api-keys list", "data": { "keys": [ { "id": "01M83N53FRJSNFAN03N49RBKSZ", "name": "ci-deploy", "status": "active", "createdAt": "2026-11-23T07:33:00.561Z", "expiresAt": null } ], "hasMore": false, "nextCursor": null } } ``` The install also provides `tokedex` as a second command name. ## Command groups | Commands | What they do | Concepts | |---|---|---| | [`api-keys`](/cli/reference/api-keys) | Create, rotate, disable and revoke API keys | [API keys](/gateway/api-keys) | | [`budgets`](/cli/reference/budgets) | Create, change and remove budgets | [Budgets](/gateway/budgets) | | [`usage`](/cli/reference/usage), [`spend`](/cli/reference/spend) | Read usage reports and spend | [Spend and usage](/gateway/spend-and-usage) | | [`workspaces`](/cli/reference/workspaces), [`users`](/cli/reference/users), [`invites`](/cli/reference/invites) | Manage workspaces and their policy, people's roles, and invitations | [People and workspaces](/gateway/people-and-workspaces) | | [`providers`](/cli/reference/providers) | Set and remove provider credentials | [Provider credentials](/gateway/provider-credentials) | | [`models`](/cli/reference/models), [`pricing`](/cli/reference/pricing) | Turn models on and off, manage routers and aliases, and override prices | [Find a model](/gateway/models), [Routers and fallback](/gateway/router) | | [`observability`](/cli/reference/observability) | Read traces and calls | [Find and inspect a request](/gateway/requests-and-sessions) | | [`audit`](/cli/reference/audit) | Read and follow the audit log | [Audit log](/gateway/recording-and-retention#audit-log) | | [`alerts`](/cli/reference/alerts) | Read and mark spend alerts | [Budget alerts](/gateway/budget-alerts) | | [`auth`](/cli/reference/auth), [`doctor`](/cli/reference/doctor) | Sign in, sign out and check the connection | [CLI quickstart](/cli/quickstart) | | [`api`](/cli/reference/api) | Send any management request, with secrets masked in the reply | [Scripts and agents](/cli/scripts-and-agents) | Every command prints its own help, as in `tdx api-keys create --help`. The [Command reference](/cli/reference) has a page for each group, with every command's flags, output fields and examples. ## How the CLI connects - **Gateway address.** `tdx` reads it from `--host`, `TOKEDEX_HOST` or the saved profile. It requires HTTPS, except for `localhost`, `127.0.0.1` and `[::1]`. - **Credential.** It sends the token saved by `tdx auth login`, or `TOKEDEX_TOKEN` for one run, which suits [scripts and agents](/cli/scripts-and-agents#choose-how-to-pass-credentials). The token from browser sign-in lasts 30 days, and `tdx auth logout` revokes it. For a script, use an admin key with the smallest preset that covers the job, so a leaked key can do little. A master key works too, but it can do everything, so keep it for recovery. - **Permissions.** The gateway decides what the credential may do: a token from browser sign-in can do what your role lets you do, and an admin key what its preset covers. Anything else fails with `FORBIDDEN` and exit code 4. [Give a script an admin key](/gateway/api-keys#give-a-script-an-admin-key) lists the presets. A few tasks need a person in the dashboard itself, such as changing sign-in settings or alert destinations. The CLI refuses them with `SESSION_REQUIRED`, even after browser sign-in, so do them in the dashboard. Next: [CLI quickstart](/cli/quickstart), [Scripts and agents](/cli/scripts-and-agents) or the [Command reference](/cli/reference). --- # CLI quickstart Install `tdx`, sign in to your gateway and read its workspaces, in about five minutes. You need a supported Node.js LTS release (see `engines` in [`package.json`](https://github.com/ArtificialAnalysis/Tokedex/blob/main/typescript/package.json)), a running gateway and an account on its dashboard. The [Gateway quickstart](/gateway/quickstart) starts a gateway at `http://127.0.0.1:4000`. ## Install the CLI ```bash npm install --global @tokedex/cli tdx --version ``` ### Install from source To build the CLI from a checkout, use pnpm 10.34.9. Open your Tokedex checkout or clone the repository. ```bash git clone https://github.com/ArtificialAnalysis/Tokedex.git cd Tokedex ``` From the checkout, build and install the CLI. ```bash pnpm -C typescript install --frozen-lockfile pnpm -C typescript build:refs npm install --global --install-links ./typescript/packages/cli tdx --version ``` ## Sign in ```bash tdx auth login --host http://127.0.0.1:4000 ``` ```text Open http://127.0.0.1:4000/cli-sign-in Enter this code in the browser: SFBB-ZWBT Only enter a code that your own terminal shows you. The code expires in 10 minutes. Opened your browser. Waiting for approval… (Ctrl-C to cancel) ``` The page is on the gateway's public URL (`TOKEDEX_PUBLIC_URL`) when it has one, even if `--host` is another address for it, so signing in through your identity provider brings you back to it. The exception is a public URL and `--host` on this machine with different ports, such as a port-forward on another port: the page is then on `--host`, and you sign in there with your email and password. In the browser page that opens: 1. Sign in to the dashboard, if it asks. 2. Enter the code from your terminal and choose **Continue**. 3. Check the request: the CLI's name, the network it asked from and how long its token lasts. Choose **Approve**. If you signed in more than 10 minutes ago, confirm it's you first. The page says **Request approved. Return to your terminal to confirm that sign-in completed.** The terminal prints the saved profile when sign-in completes. ```json { "schemaVersion": "tokedex.cli.v1", "command": "auth login", "data": { "profile": { "name": "default", "origin": "http://127.0.0.1:4000" }, "principal": { "kind": "user", "id": "usr_01M83XDKHP308B8X1770RJZ9PQ", "name": "Ada Lovelace" }, "breakGlass": false, "expiresAt": "2026-12-23T09:59:27.105Z", "warning": null, "preview": null } } ``` `tdx auth login` saved a personal access token, with the gateway's address, in a file only your user can read under `~/.config/tokedex/`. The token can do what your role lets you do, except what only the dashboard does, and lasts 30 days; ask for less with `--expires-in 7d`. It is listed under **Account → Access tokens**, where you can revoke it. Approve only a code your own terminal shows you. Anyone who sends you a code and a link is asking for your access. On a machine without a browser, including SSH without a terminal, select browser sign-in explicitly. Replace the host with your gateway's address. ```bash tdx auth login --host https://gateway.example.com --method browser --no-browser ``` Open the printed address on a device that can reach the gateway and approve the code there. ## Check the connection ```bash tdx auth status --json=principal,expiresAt,source ``` ```json { "schemaVersion": "tokedex.cli.v1", "command": "auth status", "data": { "principal": { "kind": "user", "id": "usr_01M83XDKHP308B8X1770RJZ9PQ", "name": "Ada Lovelace" }, "expiresAt": "2026-12-23T09:59:27.105Z", "source": { "profile": "default", "profileSource": "default", "origin": "http://127.0.0.1:4000", "hostSource": "profile", "credential": "profile", "ephemeral": false, "browserSignIn": true } } } ``` `expiresAt` is when the token stops working; run `tdx auth login` again before then. `browserSignIn` shows the token came from browser sign-in, and plain `tdx auth status` also lists your `permissions`. ### Diagnose a proxy connection Run [`tdx doctor`](/cli/reference/doctor) when you connect through an HTTPS proxy. If it reports `TRANSPORT_FAILED`, test the proxy tunnel and TLS handshake against the same gateway URL. This health check needs no gateway credentials. ```bash export TOKEDEX_URL='https://gateway.example.com' curl --silent --show-error --output /dev/null \ --write-out 'Proxy CONNECT status %{http_connect}\n' "$TOKEDEX_URL/healthz" ``` | Result | What to check | | --- | --- | | Proxy CONNECT returns `407` | Check the credentials for your proxy. Set the proxy URL in `HTTPS_PROXY` or its lowercase equivalent. | | Proxy CONNECT returns `200` and curl reports a certificate trust error | Ask your network administrator for the trusted CA certificate. For `tdx`, set `NODE_EXTRA_CA_CERTS` to the path of its PEM file, then run `tdx doctor` again. | | Proxy CONNECT returns `000` and you expected a proxy | Check for a matching `NO_PROXY` entry and check the lowercase proxy variables. The CLI gives lowercase settings precedence. | If the connection passes and the login check reports `AUTHENTICATION_FAILED`, sign in to the gateway again. See the [CLI environment variables](/cli/reference#environment-variables). ## List workspaces ```bash tdx workspaces list --json --jq '.data.workspaces[] | {slug, name, status}' ``` ```json { "slug": "default", "name": "Default", "status": "active" } ``` It lists the workspaces your role lets you read, as the dashboard's workspace switcher does. Without `--jq`, the command prints every field of each workspace, wrapped in the same object as `auth status`. `--jq` runs your installed `jq` on that object. ## Connect another gateway Each profile holds one gateway. Sign in to another under a name, then pass that name to choose it: ```bash tdx auth login --host https://gateway.example.com --profile staging tdx workspaces list --profile staging ``` `tdx auth logout --profile staging` revokes that profile's token on the gateway and deletes the profile, so sign out of a machine you no longer use. A CI job or agent should not use your sign-in: give it an admin key through `TOKEDEX_TOKEN` and `TOKEDEX_HOST`, as [Scripts and agents](/cli/scripts-and-agents#choose-how-to-pass-credentials) describes. Next: [Scripts and agents](/cli/scripts-and-agents), the [Command reference](/cli/reference) or [API keys](/gateway/api-keys) in the gateway docs. --- # Scripts and agents Run `tdx` from CI jobs, scripts and coding agents: find its commands, read its output, and recover from errors without repeating a change. You need: `tdx` connected to your gateway, as in the [CLI quickstart](/cli/quickstart), and an admin key whose preset covers the commands you run. ## Discover commands ```bash tdx schema --json # every command, flag, output field and exit code tdx api-keys create --help --json # one command ``` A command's `--help --json` lists its flags, the rules between them, its output fields and its `operation`, which says whether it reads or writes and which gateway route it calls: ```json "operation": { "id": "api-keys.create", "effect": "write", "target": "http", "availability": "implemented", "http": { "kind": "fixed", "routes": ["POST /control/v1/inference-keys"] } } ``` Point an agent at `tdx schema --json` rather than a copied list of commands, so what it reads always matches the installed version. ## Read the output A command that succeeds prints one JSON object to stdout and exits with 0. `data` holds the result: ```bash tdx auth status --json=principal ``` ```json { "schemaVersion": "tokedex.cli.v1", "command": "auth status", "data": { "principal": { "kind": "management_key", "id": "01M83N4WA8WZ46MMMFY2HNK818", "name": "cli-quickstart" } } } ``` - **`schemaVersion`** names the output format. Check it before you read `data`, so a script stops rather than misreads a different format. - **`--json=`** keeps only the named fields of `data`, as `--json=principal` does above. - **`--jq ''`** runs your installed `jq` on the whole object, and needs `--json`: `tdx workspaces list --json --jq '.data.workspaces[].slug'`. - **`tdx audit stream`** prints one object per line as events arrive. Pipe it to `jq -c`; it refuses `--jq`. ## Handle errors A command that fails prints an error to stderr and exits with a code from 1 to 7. Branch on `code` and the exit code; `hint` and `fix` are written for a person. ```json {"error":{"code":"FORBIDDEN","hint":"The gateway denied this request.","fix":"Use an authorized credential. Session-only and step-up requirements cannot be bypassed by this CLI."}} ``` | Exit code | Meaning | What to do | |---|---|---| | 0 | Success | Read stdout | | 1 | An internal error, or a change the gateway applied before a later step failed | Read stdout and the error code before you run anything again | | 2 | Usage | Fix the command against its `--help --json` | | 3 | Authentication | Check `TOKEDEX_TOKEN`, `TOKEDEX_HOST` and the profile. A token from browser sign-in expires, so a person signs in again with `tdx auth login` | | 4 | Forbidden | Use an admin key whose preset covers the command | | 5 | Not found | Check the ID | | 6 | Conflict | Read the current state, then decide whether to try again | | 7 | Unavailable: the gateway, the network or `jq`, or a task that needs the dashboard (`SESSION_REQUIRED`) | Retry a read after a pause. Before you retry a write, read the state, since a timeout leaves the outcome unknown | ## Preview a write Add `--dry-run` to a command that changes something, to see the request without sending it: ```bash tdx api-keys create --name ci-deploy --all-models --dry-run ``` ```json { "schemaVersion": "tokedex.cli.v1", "command": "api-keys create", "data": { "preview": { "applied": false, "authoritative": false, "basis": "unavailable", "request": { "action": "create-inference-key", "name": "ci-deploy", "allowedModels": null, "secretless": false, "profile": "default", "origin": "http://127.0.0.1:4000" } } } } ``` `"applied": false` confirms nothing changed. Have an agent show this preview before it runs a write, so a person approves the exact request. The preview checks neither permissions nor current state, and a command that reads still calls the gateway, so check that `operation.effect` in its `--help --json` is not `read` before you rely on one. ## Check before you retry a write A write can succeed on the gateway and still exit with 1. Here the change applies, then the `--jq` filter fails: ```bash tdx api-keys disable --id 01M83N53FRJSNFAN03N49RBKSZ --json --jq '.data.key | error("unexpected shape")' ``` stdout has the unfiltered result, with the key's `"status": "disabled"`, and stderr has the error: ```json {"error":{"code":"CHANGE_APPLIED_JQ_FAILED","hint":"The command completed and its changes were applied, but jq output failed.","fix":"The unfiltered safe JSON outcome is on stdout. Inspect it before repeating any write; correct the filter separately."}} ``` The key is disabled anyway. `CHANGE_APPLIED_RESPONSE_INVALID`, `KEY_CREATED_DELIVERY_FAILED` and `KEY_ROTATED_DELIVERY_FAILED` also mean the change was made. After exit code 1, or a timed-out write, read the current state, such as `tdx api-keys list`, before you run the write again: repeating `api-keys create` makes a second key. A filter that `jq` cannot compile is refused with exit code 2 before anything is sent. If browser sign-in exits 7 with `SIGN_IN_DELIVERY_UNCONFIRMED`, the gateway may have issued a personal access token. Revoke any token issued by that attempt under **Account → Access tokens** before signing in again. ## Choose how to pass credentials | Source | Use it for | How it behaves | |---|---|---| | `TOKEDEX_TOKEN` holding an admin key, with `--host` or `TOKEDEX_HOST` | CI jobs and agents that run on their own | Read for one run and never written to disk | | A profile saved by browser sign-in, `tdx auth login` | A person at a terminal | A personal access token that acts as you for 30 days, kept in a file only your user can read under `~/.config/tokedex/`, and sent only to the address it was saved with | | A profile saved by `tdx auth login --method token` | A machine you run commands on yourself, with a key you minted | The token you supply, kept like the one above; `tdx auth logout` deletes the profile but leaves the key valid | `TOKEDEX_TOKEN` wins when both are present. In CI, pass the admin key from the job's secret store as `TOKEDEX_TOKEN`, so no copy outlives the job, and give each script its own key, so revoking one stops nothing else. Choose a profile with `--profile` or `TOKEDEX_PROFILE`; used with another address, it fails with `PROFILE_HOST_MISMATCH` and the key is not sent. Keep browser sign-in for yourself. Its token can do everything your role can, and it stops when you sign out everywhere or change your password, which breaks any job that depends on it. A coding agent you run in your own terminal uses your profile, so it acts as you; to give it less, pass it an admin key with a narrow preset through `TOKEDEX_TOKEN`. ## Issue an API key from a script `tdx api-keys create` never prints a new key. It writes the key to a new file that only your user can read: ```bash tdx api-keys create --name ci-deploy --all-models --token-file ./ci-deploy.key ``` ```json { "schemaVersion": "tokedex.cli.v1", "command": "api-keys create", "data": { "key": { "id": "01M83N53FRJSNFAN03N49RBKSZ", "name": "ci-deploy", "status": "active", "createdAt": "2026-11-23T07:33:00.561Z", "expiresAt": null }, "credential": { "delivered": true, "destination": "token-file" }, "preview": null } } ``` The file must not exist yet, so a run never overwrites a key. `tdx api-keys rotate --token-file` delivers a rotated key the same way, and `--secretless` with `--owner` offers someone a personal key that they pick up in the dashboard. `tdx api` masks secrets in every reply. Creating keys needs the `key-manager` preset, or `workspace-key-manager` in one workspace. Next: the [Command reference](/cli/reference), [API keys](/gateway/api-keys) or [Errors, limits and request IDs](/gateway/errors-and-limits) in the gateway docs. --- # Command reference Manage a running gateway through its management endpoints with a token, such as an admin key: API keys, budgets and spend, people, workspaces, models, observability and the audit log. Run any command with --help, or schema --json for every command at once. To administer a gateway's own store on its machine, without the server, see `tokedex-gateway --help`. Each page here is built from the same schema as `tdx --help`; `tdx --help --json` prints it as JSON. ## Command groups | Command | Description | Type | |---|---|---| | [tdx admin](/cli/reference/admin) | Inspect gateway administration capabilities. | Group | | [tdx alert-channels](/cli/reference/alert-channels) | Alert destinations and Slack setup (dashboard only). | Group | | [tdx alerts](/cli/reference/alerts) | Read and mark spend alerts in your inbox. | Group | | [tdx api](/cli/reference/api) | Send an admin HTTP request. | Read or write | | [tdx api-keys](/cli/reference/api-keys) | Manage API keys (tokedex_ik_). | Group | | [tdx audit](/cli/reference/audit) | Read and follow the audit log (the dashboard's Events tab). | Group | | [tdx auth](/cli/reference/auth) | Sign in with the browser or a token, and manage saved profiles. | Group | | [tdx budgets](/cli/reference/budgets) | Manage spend budgets. | Group | | [tdx completion](/cli/reference/completion) | Generate shell completion. | Local | | [tdx config](/cli/reference/config) | Inspect compiled gateway configuration. | Group | | [tdx doctor](/cli/reference/doctor) | Check connection, auth, catalogue and backend information. | Read | | [tdx guide](/cli/reference/guide) | Print bundled agent getting-started material. | Local | | [tdx identity-settings](/cli/reference/identity-settings) | Inspect sign-in and session settings. | Group | | [tdx invites](/cli/reference/invites) | Manage one-shot invitation links. | Group | | [tdx limits](/cli/reference/limits) | Read the calling API key's budgets and rate limits. | Read | | [tdx models](/cli/reference/models) | Models callers can request from this gateway. | Group | | [tdx observability](/cli/reference/observability) | Read inference traces and calls, the store status and its switch. | Group | | [tdx open](/cli/reference/open) | Print or open the logged-in host dashboard. | Write | | [tdx pricing](/cli/reference/pricing) | Inspect prices and manage price overrides. | Group | | [tdx profile](/cli/reference/profile) | Your own gateway account profile (not a local connection profile). | Group | | [tdx providers](/cli/reference/providers) | Manage provider credentials. | Group | | [tdx schema](/cli/reference/schema) | Print the command tree. | Local | | [tdx sessions](/cli/reference/sessions) | Inspect sessions; interactive revocation is unavailable. | Group | | [tdx spend](/cli/reference/spend) | Read spend counters and settlements. | Group | | [tdx sso-providers](/cli/reference/sso-providers) | Inspect SSO (OIDC sign-in) providers. | Group | | [tdx usage](/cli/reference/usage) | Read usage reports. | Group | | [tdx users](/cli/reference/users) | Manage people and their role assignments. | Group | | [tdx workspaces](/cli/reference/workspaces) | Manage workspaces, their policy and spend. | Group | ## Global flags Every command takes these flags. | Flag | Type | Default | Description | |---|---|---|---| | `-h`, `--help` | boolean | `false` | Show help; runs nothing. | | `--version` | boolean | `false` | Print the CLI version; reads no profile, credential or host. | | `--host` | url | | Gateway address: an HTTPS origin, or HTTP on localhost, 127.0.0.1 or [::1]. Also read from `TOKEDEX_HOST`. | | `--profile` | string | `default` | Profile: 1-64 lowercase ASCII letters, digits, dots, underscores or hyphens; start with a letter or digit. Also read from `TOKEDEX_PROFILE`. | | `--json` | field-list | | Print versioned JSON; optionally keep only these comma-separated fields of data. | | `--jq` | string | | Filter the masked JSON with your installed jq; requires --json. A command that is not a read checks that the filter compiles before it sends anything. A filter that fails after a write exits 1 with CHANGE_APPLIED_JQ_FAILED and the unfiltered JSON on stdout: the change was applied. Under --dry-run the same failure is PREVIEW_JQ_FAILED, with nothing applied. | | `--dry-run` | boolean | `false` | Show what a write would send without sending it; reads still run. | ## Environment variables | Variable | Description | |---|---| | `TOKEDEX_HOST` | Gateway address; --host takes precedence. | | `TOKEDEX_PROFILE` | Profile name; --profile takes precedence. | | `TOKEDEX_TOKEN` | Token for this run only, such as an admin key; requires --host or TOKEDEX_HOST; never printed, and saved only by auth login. | | `XDG_CONFIG_HOME` | Existing absolute directory whose tokedex/ folder holds saved profiles; unset, $HOME/.config is used (HOME must exist). | | `HTTP_PROXY` | Always honored for HTTP and as HTTPS fallback without Node proxy opt-in; lowercase http_proxy takes precedence. | | `HTTPS_PROXY` | Always honored for HTTPS regardless of NODE_USE_ENV_PROXY or NODE_OPTIONS; lowercase https_proxy takes precedence. | | `NO_PROXY` | Direct-host exclusions for CLI transport, independent of Node proxy opt-in; lowercase no_proxy takes precedence. | ## Exit codes | Code | Meaning | |---|---| | `0` | success | | `1` | internal | | `2` | usage | | `3` | authentication | | `4` | forbidden | | `5` | not found | | `6` | conflict | | `7` | unavailable | ## Output and errors A command that succeeds prints one JSON object to stdout, `{"schemaVersion": "tokedex.cli.v1", "command": …, "data": …}`, and exits 0. Help printed with `--help --json` uses `tokedex.cli-help.v1`. A command that fails prints `{"error": {"code": …, "hint": …, "fix": …}}` to stderr and exits with one of the codes above. [Scripts and agents](/cli/scripts-and-agents) shows how to read both. ## Shared behaviour Many commands behave the same way in these respects. Their sections link here instead of repeating the text. ### Masked read output Secrets in the output are masked, judged against the whole request and gateway reply, before --json selects fields or --jq runs; █ marks a masked value. Checked booleans, values the CLI sets itself and its source field (where present) print unmasked; source is only checked to exclude the token. A reply that exceeds the masking limits fails with OUTPUT_MASK_LIMIT (exit 7) and prints no values. ### Masked write output Secrets in the output are masked, judged against the whole request and gateway reply, before --json selects fields or --jq runs; █ marks a masked value. Checked booleans, values the CLI sets itself and its source field (where present) print unmasked; source is only checked to exclude the token. The request is masked on its own first; if it exceeds the masking limits, the command fails with OUTPUT_MASK_LIMIT (exit 7) and sends nothing. A --dry-run preview has no reply, so it is masked against the request and TOKEDEX_TOKEN (when set) only. If the gateway accepts a write but its reply exceeds the limits, the command exits 1 with its applied-but-invalid error and prints no values; a preview that exceeds them fails with OUTPUT_MASK_LIMIT (exit 7). ### Checked request values Values you pass are checked against TOKEDEX_TOKEN (when set) and the gateway's token prefixes; under --dry-run a token saved only in a profile cannot be compared, because the profile is not read. ### Values too long to print A value the CLI cannot print safely is withheld on its own and the rest of the reply still prints: text longer than 4096 characters, such as a tag, title, project, agent name or a client-chosen id, prints as [withheld: too long], and a trace, trajectory or request id containing a control character such as a TAB prints as [withheld: control character]. Masking still sees the full value. A withheld id cannot be looked up. A client can also send the marker text itself, which then reads the same as a withheld value. ### People and role commands Every value in the reply is masked before --json, --jq or any other output, and masking fails closed; a secret under an ordinary-looking name cannot be recognised. Under --dry-run a write shows its method, path and body with no diff, unchecked by the gateway, and sends no request, reads no credential or profile and writes no file. Invalid input is refused before anything happens. The gateway still decides permissions, which roles you may grant and which people an identity provider owns; changes to admin-level people need a dashboard session with a fresh sign-in, which this token-only CLI cannot provide. The CLI never escalates or retries. ### Invitation links The gateway reveals a raw invitation URL once. Reserve a NEW owner-only 0600 --token-file before minting; existing files are never overwritten. The file contains the complete invitation link, never stdout, JSON, jq, hints or previews. Alternatively --secretless explicitly discards that link locally: the gateway still mints it, and no secretless field is sent. Masked or malformed links are never reported as delivered. Delivery failure or an uncertain write requires private state inspection, never blind repetition; no credential fallback is printed. See [People and role commands](/cli/reference#people-and-role-commands). ### Workspace reads Uses auth status host-bound bearer rules; the gateway decides what this credential may read, and the CLI enforces no permission itself. --dry-run still performs this read. See [Masked read output](/cli/reference#masked-read-output). Key ids and names, an access review's key summaries, and budget, rate and lifetime settings in the gateway's own shapes print in clear unless they show too much of a token body. Other values the reply carries under key-like names (such as the source guardrail of a limit the guardrail sets, which masks key-preview adjustment reasons naming it) are learned as aliases, so matching public values may print as █ too. See [Checked request values](/cli/reference#checked-request-values). ### Workspace changes Uses auth status host-bound bearer rules; the gateway authorizes and validates every change, and the CLI enforces no permission itself. Only the options you supply are sent. Structured inputs are inline JSON options, never files or stdin, whose object keys must be the gateway's field names for that option: a layer's models, maxKeyLifetimeDays, keyRpmMax and keyBudgetMax, and a budget's window and limit. Invalid local input is refused before any profile, credential or gateway access. --dry-run sends no request and reads no profile, credential, stdin or file; it shows only a local preview of the requested method, path and body, without current state, review or gateway checks. One request, never retried. See [Masked write output](/cli/reference#masked-write-output). Outside a --dry-run preview, key ids and names, a review's key summaries, and budgets (`{"window": day, week, month or total, "limit": a USD amount}`) and rate and lifetime settings in the gateway's own shapes print in clear unless they show too much of a token body. Other values sent or returned under key-like names (such as a budget in any other shape, or the source guardrail of a limit the guardrail sets, which masks the review kind) are learned as aliases, so matching public values may print as █ too. A --dry-run preview shows --key-budget-default and a layer's keyBudgetMax, and any string a layer holds under a key-like name, as █; a layer's number and null limits usually print as sent, but a number sharing digits with a whole-number budget limit prints as █ (write limits with a decimal point). See [Checked request values](/cli/reference#checked-request-values). ### Catalogue reads Uses auth status host-bound bearer rules. The response shape is checked, then recursively masked like api output, so fields named like token, key, secret or credential (for example contextWindowTokens) are intentionally shown as █. Gateway error bodies are never displayed; --dry-run performs the same read. ### Catalogue changes Input, including any definition file, is validated before any profile or gateway access. --dry-run reads only an explicit definition file, sends no request, reads no profile or credential and creates nothing; it shows the masked requested method, path and body, unchecked by the gateway. A completed write prints the masked, shape-checked response; gateway error bodies are never displayed and nothing is retried. Ids and other public values are 1-512 characters without control or format characters, line separators or whitespace at either end; an --id is also never . or .., and is percent-encoded into the route. See [Checked request values](/cli/reference#checked-request-values). ### Catalogue republishing The gateway republishes the catalogue for this change, which can take several seconds on a large catalogue; the request deadline is 30 seconds, and a timeout means the outcome is unknown. ### Observability filters and output Filter values are at most 512 characters without control characters and are refused before any request if they contain the bearer or a registered gateway token prefix; they are never echoed. Only supplied filters are sent. Output is a validated projection under fixed names; anything unexpected in the reply fails with INVALID_RESPONSE. Values pass the same fail-closed masking as api, with aliases learned from the request and the whole raw reply, dropped fields included; masked values print as █. Key metadata in the gateway's own forms prints in clear as JSON fields: ULID key ids (keyId), key labels (master key, virtual key and 6 lowercase hex digits, or a key id), key fingerprints (key_ and 16 lowercase hex digits), key kinds, key display names (keyName), key directories as calls list describes, the key lists and counts of an access review in the gateway's exact summary shapes, whose entries are judged by their own field names, and key budget, rate and lifetime settings. Where a command offers --key-id, a ULID key id prints in its own request path; a key-like query parameter or name=value text anywhere else is secret. When the request, whole raw reply and output of one command together show more positions of a known or learned gateway token's random body than leave 128 bits unseen with its checksum known, 17 or more for tokedex_ik_, tokedex_mk_, tokedex_ss_, tokedex_iv_ and tokedex_rs_ tokens and 22 or more for tokedex_vk_ tokens, each position counted once and only in runs of 8 or more consecutive characters, also when spaces or other separators split a run, every value showing any of them prints as █, a key display name included. Pieces shorter than 8 characters are not counted, so this covers previews and accidental pastes, not a key deliberately split into short pieces. Any other string of 8 or more characters under a secret-like name, except an RFC 3339 timestamp or a gateway entity id, prints as █ wherever it appears; this over-masking is intentional. A cursor that masking would change is refused (INVALID_RESPONSE), because a masked cursor cannot be passed back. A reply too large to mask fails with OUTPUT_MASK_LIMIT (exit 7); retry with a smaller --limit. --dry-run still performs this read. ### Alert output Output values pass the same fail-closed masking as api, with aliases learned from the request and the whole reply; masked values print as █. A key alert's gateway key id, its drill-down link (/spend/?…&spendKey=\) and its fallback link (/api-keys/?…&key=\) print in clear when the link names that alert's own key; only these commands vouch for those links, so the same parameters anywhere else, such as in api output or in a link naming another key, are secret. Public values may still be over-masked: a key id that is not a gateway key id is treated as a secret, so it and its links print as █, and once such an alert is on the page, links sharing any query part of 8 or more characters with its drill-down link (such as the month or by=model) may print as █ too. Body positions of a known or learned gateway token are counted across the whole page, every alert and nextCursor included, so once the page shows too many of one token's positions every alert value showing any of them prints as █ and a nextCursor showing any of them is refused; each alert keeps its own work budget, so a large valid page lists whole. nextCursor is not masked but is refused if it echoes the bearer or a learned alias. A reply too large to mask (for list, retry with a smaller --limit) or too deep to mask, or one carrying a malformed cursor, a credential prefix in its cursor or a link that is not origin-relative, is refused. ### Audit event fields Each event is projected under fixed names: envelope ids, times, category, severity, source, node, scope, actor (kind, id, auth method; the credential id is withheld), correlation, resource, revisions, and data as an array of { field, value } from a fixed list of the gateway's data field names; unknown data fields and idempotency key hashes are withheld. ### Sign-in settings output Every reply value, including booleans, integers, sync and discovery.state, is masked; only the CLI constant source (always file) is added back afterwards. Values are masked under neutral CLI names and printed under the gateway's field names, so passwordLogin, minPasswordLength and allowLocalPasswordForSsoUsers are not erased by name and normally print real values; a number that echoes a secret elsewhere in the reply prints as █. --- # tdx admin Inspect gateway administration capabilities. Read what this gateway lets an operator edit. Every command also takes the [global flags](/cli/reference#global-flags) and reads the [environment variables](/cli/reference#environment-variables) that the command reference lists once. ## Commands | Command | Description | Type | |---|---|---| | [tdx admin capabilities](/cli/reference/admin#tdx-admin-capabilities) | Inspect what this gateway lets an operator edit. | Read | ## tdx admin capabilities Inspect what this gateway lets an operator edit. **Reads** Read the compiled admin capabilities document: alias (address), router (model group) and custom model support, strategy choices, failure classes, client dialects and the read-only custom model policy. The custom model policy's credential fields (credentialSources, credentialPrefix) are masked by the name-based masker. See [Catalogue reads](/cli/reference#catalogue-reads). ```bash # GET /control/compiled/capabilities tdx admin capabilities [flags] ``` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `capabilities` | masked-capabilities | Masked compiled-admin-capabilities.v1 document. | **Examples** Inspect editable capabilities: ```bash tdx admin capabilities --json ``` --- # tdx alert-channels Alert destinations and Slack setup (dashboard only). Alert channels, their delivery histories, the Slack app and Add to Slack are unavailable to this bearer-only CLI: every route is session-only: the gateway serves it only to an interactive dashboard sign-in holding install-wide settings.manage, spend.read and budgets.read, and most changes also need a recent sign-in (step-up). Each command refuses with SESSION_REQUIRED before any request or credential read, --dry-run included; use the gateway dashboard. Every command also takes the [global flags](/cli/reference#global-flags) and reads the [environment variables](/cli/reference#environment-variables) that the command reference lists once. ## Commands | Command | Description | Type | |---|---|---| | [tdx alert-channels list](/cli/reference/alert-channels#tdx-alert-channels-list) | List alert channels (dashboard only). | Dashboard only | | [tdx alert-channels view](/cli/reference/alert-channels#tdx-alert-channels-view) | Read an alert channel (dashboard only). | Dashboard only | | [tdx alert-channels create](/cli/reference/alert-channels#tdx-alert-channels-create) | Create an alert channel (dashboard only). | Dashboard only | | [tdx alert-channels edit](/cli/reference/alert-channels#tdx-alert-channels-edit) | Update an alert channel (dashboard only). | Dashboard only | | [tdx alert-channels remove](/cli/reference/alert-channels#tdx-alert-channels-remove) | Remove an alert channel (dashboard only). | Dashboard only | | [tdx alert-channels test](/cli/reference/alert-channels#tdx-alert-channels-test) | Send a test alert to a channel (dashboard only). | Dashboard only | | [tdx alert-channels deliveries](/cli/reference/alert-channels#tdx-alert-channels-deliveries) | Read a channel's delivery history (dashboard only). | Dashboard only | | [tdx alert-channels slack-app](/cli/reference/alert-channels#tdx-alert-channels-slack-app) | Manage the Slack app alert channels use (dashboard only). | Group | | [tdx alert-channels slack-app set](/cli/reference/alert-channels#tdx-alert-channels-slack-app-set) | Connect or replace the Slack app (dashboard only). | Dashboard only | | [tdx alert-channels slack-app remove](/cli/reference/alert-channels#tdx-alert-channels-slack-app-remove) | Disconnect the Slack app (dashboard only). | Dashboard only | | [tdx alert-channels slack-install](/cli/reference/alert-channels#tdx-alert-channels-slack-install) | Add a Slack channel through Add to Slack (dashboard only). | Group | | [tdx alert-channels slack-install start](/cli/reference/alert-channels#tdx-alert-channels-slack-install-start) | Start Add to Slack (dashboard only). | Dashboard only | | [tdx alert-channels slack-install complete](/cli/reference/alert-channels#tdx-alert-channels-slack-install-complete) | Complete Add to Slack (dashboard only). | Dashboard only | | [tdx alert-channels slack-install cancel](/cli/reference/alert-channels#tdx-alert-channels-slack-install-cancel) | Cancel Add to Slack (dashboard only). | Dashboard only | ## tdx alert-channels list List alert channels (dashboard only). **Dashboard only.** The gateway serves this only to a signed-in dashboard session, so the CLI refuses it with `SESSION_REQUIRED`. Unavailable to this bearer-only CLI: GET /control/v1/alert-channels is session-only: the gateway serves it only to an interactive dashboard sign-in holding install-wide settings.manage, spend.read and budgets.read, and most changes also need a recent sign-in (step-up). Use the gateway dashboard. --dry-run also refuses: there is no reachable change to preview. No request is sent and no credential, profile or file is read. Destinations and Slack secrets are never accepted as command input. ```bash # GET /control/v1/alert-channels tdx alert-channels list [flags] ``` ## tdx alert-channels view Read an alert channel (dashboard only). **Dashboard only.** The gateway serves this only to a signed-in dashboard session, so the CLI refuses it with `SESSION_REQUIRED`. Unavailable to this bearer-only CLI: GET /control/v1/alert-channels/:channelId is session-only: the gateway serves it only to an interactive dashboard sign-in holding install-wide settings.manage, spend.read and budgets.read, and most changes also need a recent sign-in (step-up). Use the gateway dashboard. --dry-run also refuses: there is no reachable change to preview. No request is sent and no credential, profile or file is read. Destinations and Slack secrets are never accepted as command input. ```bash # GET /control/v1/alert-channels/:channelId tdx alert-channels view --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | ## tdx alert-channels create Create an alert channel (dashboard only). **Dashboard only.** The gateway serves this only to a signed-in dashboard session, so the CLI refuses it with `SESSION_REQUIRED`. Unavailable to this bearer-only CLI: POST /control/v1/alert-channels is session-only: the gateway serves it only to an interactive dashboard sign-in holding install-wide settings.manage, spend.read and budgets.read, and most changes also need a recent sign-in (step-up). Use the gateway dashboard. --dry-run also refuses: there is no reachable change to preview. No request is sent and no credential, profile or file is read. Destinations and Slack secrets are never accepted as command input. ```bash # POST /control/v1/alert-channels tdx alert-channels create [flags] ``` ## tdx alert-channels edit Update an alert channel (dashboard only). **Dashboard only.** The gateway serves this only to a signed-in dashboard session, so the CLI refuses it with `SESSION_REQUIRED`. Unavailable to this bearer-only CLI: PATCH /control/v1/alert-channels/:channelId is session-only: the gateway serves it only to an interactive dashboard sign-in holding install-wide settings.manage, spend.read and budgets.read, and most changes also need a recent sign-in (step-up). Use the gateway dashboard. --dry-run also refuses: there is no reachable change to preview. No request is sent and no credential, profile or file is read. Destinations and Slack secrets are never accepted as command input. ```bash # PATCH /control/v1/alert-channels/:channelId tdx alert-channels edit --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | ## tdx alert-channels remove Remove an alert channel (dashboard only). **Dashboard only.** The gateway serves this only to a signed-in dashboard session, so the CLI refuses it with `SESSION_REQUIRED`. Unavailable to this bearer-only CLI: DELETE /control/v1/alert-channels/:channelId is session-only: the gateway serves it only to an interactive dashboard sign-in holding install-wide settings.manage, spend.read and budgets.read, and most changes also need a recent sign-in (step-up). Use the gateway dashboard. --dry-run also refuses: there is no reachable change to preview. No request is sent and no credential, profile or file is read. Destinations and Slack secrets are never accepted as command input. ```bash # DELETE /control/v1/alert-channels/:channelId tdx alert-channels remove --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | ## tdx alert-channels test Send a test alert to a channel (dashboard only). **Dashboard only.** The gateway serves this only to a signed-in dashboard session, so the CLI refuses it with `SESSION_REQUIRED`. Unavailable to this bearer-only CLI: POST /control/v1/alert-channels/:channelId/test is session-only: the gateway serves it only to an interactive dashboard sign-in holding install-wide settings.manage, spend.read and budgets.read, and most changes also need a recent sign-in (step-up). Use the gateway dashboard. --dry-run also refuses: there is no reachable change to preview. No request is sent and no credential, profile or file is read. Destinations and Slack secrets are never accepted as command input. ```bash # POST /control/v1/alert-channels/:channelId/test tdx alert-channels test --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | ## tdx alert-channels deliveries Read a channel's delivery history (dashboard only). **Dashboard only.** The gateway serves this only to a signed-in dashboard session, so the CLI refuses it with `SESSION_REQUIRED`. Unavailable to this bearer-only CLI: GET /control/v1/alert-channels/:channelId/deliveries is session-only: the gateway serves it only to an interactive dashboard sign-in holding install-wide settings.manage, spend.read and budgets.read, and most changes also need a recent sign-in (step-up). Use the gateway dashboard. --dry-run also refuses: there is no reachable change to preview. No request is sent and no credential, profile or file is read. Destinations and Slack secrets are never accepted as command input. ```bash # GET /control/v1/alert-channels/:channelId/deliveries tdx alert-channels deliveries --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | ## tdx alert-channels slack-app Manage the Slack app alert channels use (dashboard only). Unavailable to this bearer-only CLI: the Slack app routes are session-only: the gateway serves it only to an interactive dashboard sign-in holding install-wide settings.manage, spend.read and budgets.read, and most changes also need a recent sign-in (step-up). Use the gateway dashboard. ## tdx alert-channels slack-app set Connect or replace the Slack app (dashboard only). **Dashboard only.** The gateway serves this only to a signed-in dashboard session, so the CLI refuses it with `SESSION_REQUIRED`. Unavailable to this bearer-only CLI: PUT /control/v1/alert-slack/app is session-only: the gateway serves it only to an interactive dashboard sign-in holding install-wide settings.manage, spend.read and budgets.read, and most changes also need a recent sign-in (step-up). Use the gateway dashboard. --dry-run also refuses: there is no reachable change to preview. No request is sent and no credential, profile or file is read. Destinations and Slack secrets are never accepted as command input. ```bash # PUT /control/v1/alert-slack/app tdx alert-channels slack-app set [flags] ``` ## tdx alert-channels slack-app remove Disconnect the Slack app (dashboard only). **Dashboard only.** The gateway serves this only to a signed-in dashboard session, so the CLI refuses it with `SESSION_REQUIRED`. Unavailable to this bearer-only CLI: DELETE /control/v1/alert-slack/app is session-only: the gateway serves it only to an interactive dashboard sign-in holding install-wide settings.manage, spend.read and budgets.read, and most changes also need a recent sign-in (step-up). Use the gateway dashboard. --dry-run also refuses: there is no reachable change to preview. No request is sent and no credential, profile or file is read. Destinations and Slack secrets are never accepted as command input. ```bash # DELETE /control/v1/alert-slack/app tdx alert-channels slack-app remove [flags] ``` ## tdx alert-channels slack-install Add a Slack channel through Add to Slack (dashboard only). Unavailable to this bearer-only CLI: the Add to Slack routes are session-only: the gateway serves it only to an interactive dashboard sign-in holding install-wide settings.manage, spend.read and budgets.read, and most changes also need a recent sign-in (step-up). Use the gateway dashboard. ## tdx alert-channels slack-install start Start Add to Slack (dashboard only). **Dashboard only.** The gateway serves this only to a signed-in dashboard session, so the CLI refuses it with `SESSION_REQUIRED`. Unavailable to this bearer-only CLI: POST /control/v1/alert-slack/installs is session-only: the gateway serves it only to an interactive dashboard sign-in holding install-wide settings.manage, spend.read and budgets.read, and most changes also need a recent sign-in (step-up). Use the gateway dashboard. --dry-run also refuses: there is no reachable change to preview. No request is sent and no credential, profile or file is read. Destinations and Slack secrets are never accepted as command input. ```bash # POST /control/v1/alert-slack/installs tdx alert-channels slack-install start [flags] ``` ## tdx alert-channels slack-install complete Complete Add to Slack (dashboard only). **Dashboard only.** The gateway serves this only to a signed-in dashboard session, so the CLI refuses it with `SESSION_REQUIRED`. Unavailable to this bearer-only CLI: POST /control/v1/alert-slack/installs/complete is session-only: the gateway serves it only to an interactive dashboard sign-in holding install-wide settings.manage, spend.read and budgets.read, and most changes also need a recent sign-in (step-up). Use the gateway dashboard. --dry-run also refuses: there is no reachable change to preview. No request is sent and no credential, profile or file is read. Destinations and Slack secrets are never accepted as command input. ```bash # POST /control/v1/alert-slack/installs/complete tdx alert-channels slack-install complete [flags] ``` ## tdx alert-channels slack-install cancel Cancel Add to Slack (dashboard only). **Dashboard only.** The gateway serves this only to a signed-in dashboard session, so the CLI refuses it with `SESSION_REQUIRED`. Unavailable to this bearer-only CLI: POST /control/v1/alert-slack/installs/cancel is session-only: the gateway serves it only to an interactive dashboard sign-in holding install-wide settings.manage, spend.read and budgets.read, and most changes also need a recent sign-in (step-up). Use the gateway dashboard. --dry-run also refuses: there is no reachable change to preview. No request is sent and no credential, profile or file is read. Destinations and Slack secrets are never accepted as command input. ```bash # POST /control/v1/alert-slack/installs/cancel tdx alert-channels slack-install cancel [flags] ``` --- # tdx alerts Read and mark spend alerts in your inbox. Bearer reads of the spend-alert inbox: list, unread count and mark read. The routes require budgets.read, and the gateway further filters rows to what this credential may see. Alert settings and delivery histories are session-only and unavailable to this bearer-only CLI; use the dashboard. Every command also takes the [global flags](/cli/reference#global-flags) and reads the [environment variables](/cli/reference#environment-variables) that the command reference lists once. ## Commands | Command | Description | Type | |---|---|---| | [tdx alerts list](/cli/reference/alerts#tdx-alerts-list) | List spend alerts the gateway lets this credential see. | Read | | [tdx alerts unread-count](/cli/reference/alerts#tdx-alerts-unread-count) | Count unread spend alerts. | Read | | [tdx alerts mark-read](/cli/reference/alerts#tdx-alerts-mark-read) | Mark spend alerts read. | Write | | [tdx alerts settings](/cli/reference/alerts#tdx-alerts-settings) | Read alert settings (dashboard only). | Dashboard only | | [tdx alerts deliveries](/cli/reference/alerts#tdx-alerts-deliveries) | Read an alert's delivery history (dashboard only). | Dashboard only | ## tdx alerts list List spend alerts the gateway lets this credential see. **Reads** Read one gateway page of the spend alerts the gateway's alert visibility rules let this credential see, newest first. The route requires budgets.read, and the gateway further filters rows. An alert older than thirty days, or whose budget does not notify this reader, reads as read. Only the supplied --filter, --limit, --workspace-id and --cursor are sent. nextCursor, passed back as --cursor=\, continues the same walk; the gateway refuses a cursor issued for another filter, workspace or reader. No automatic paging. Read state is per reader and unchanged by reads. Budget targets and other unvalidated fields are withheld. --dry-run still performs this read. See [Alert output](/cli/reference#alert-output) and [Checked request values](/cli/reference#checked-request-values). ```bash # GET /control/v1/alerts tdx alerts list [flags] ``` **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--filter` | one of `all`, `unread` | | All or unread; omitted uses the gateway default. | | `--limit` | integer | | Page size; omitted uses the gateway default; the gateway enforces its range. | | `--workspace-id` | string | | Only alerts raised in this public workspace id. | | `--cursor` | string | | Opaque nextCursor from a previous page with the same --filter and --workspace-id; pass it as --cursor=\. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `alerts` | public-alert[] | Id, times, read state, thresholds, percent, spent, period, budget summary, affected scope and dashboard links. | | `nextCursor` | string\|null | Gateway continuation cursor; null on the final page. | ## tdx alerts unread-count Count unread spend alerts. **Reads** Read how many alerts the gateway lets this credential see are unread (the route requires budgets.read, and the gateway further filters rows); an alert older than thirty days, or whose budget does not notify this reader, is not counted. capped is true when the count is only a floor. Does not change read state. --dry-run still performs this read. See [Alert output](/cli/reference#alert-output) and [Checked request values](/cli/reference#checked-request-values). ```bash # GET /control/v1/alerts/unread-count tdx alerts unread-count [flags] ``` **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--workspace-id` | string | | Only alerts raised in this public workspace id. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `count` | integer | Unread alerts this credential may see. | | `capped` | boolean | Whether there may be more than count. | ## tdx alerts mark-read Mark spend alerts read. **Writes** Mark the named alerts, or with --all every unread alert the gateway lets this credential see, read for this reader only. The route requires budgets.read, and the gateway further filters rows. Alerts the reader cannot see and unknown ids are ignored alike, and an alert older than thirty days, or whose budget does not notify this reader, already reads as read and is not marked; marked counts newly marked alerts. One request per call: when more is true, repeat with --all --cursor=\ yourself; nothing is repeated automatically. Dry-run reads no profile or credential, sends no request and creates no files; the gateway has not checked its preview. See [Alert output](/cli/reference#alert-output) and [Checked request values](/cli/reference#checked-request-values). ```bash # POST /control/v1/alerts/read tdx alerts mark-read [flags] ``` **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public alert id; repeat for several; never a credential. Repeatable. | | `--all` | boolean | `false` | Mark every unread alert the gateway lets this credential see. | | `--workspace-id` | string | | With --all: only alerts raised in this public workspace id. | | `--cursor` | string | | With --all: nextCursor from a previous mark-read --all reply with the same --workspace-id; pass it as --cursor=\. | **Constraints** - Exactly one of `--id`, `--all` - `--workspace-id` requires `--all` - `--cursor` requires `--all` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `marked` | integer | Alerts newly marked read. | | `more` | boolean | With --all: unread alerts may remain past this call. | | `nextCursor` | string\|null | With --all: cursor for the next call; null when none. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | ## tdx alerts settings Read alert settings (dashboard only). **Dashboard only.** The gateway serves this only to a signed-in dashboard session, so the CLI refuses it with `SESSION_REQUIRED`. Unavailable to this bearer-only CLI: GET /control/v1/alert-settings is session-only: the gateway serves it only to an interactive dashboard sign-in holding install-wide settings.manage, spend.read and budgets.read, and most changes also need a recent sign-in (step-up). Use the gateway dashboard. --dry-run also refuses: there is no reachable change to preview. No request is sent and no credential, profile or file is read. Destinations and Slack secrets are never accepted as command input. ```bash # GET /control/v1/alert-settings tdx alerts settings [flags] ``` ## tdx alerts deliveries Read an alert's delivery history (dashboard only). **Dashboard only.** The gateway serves this only to a signed-in dashboard session, so the CLI refuses it with `SESSION_REQUIRED`. Unavailable to this bearer-only CLI: GET /control/v1/alerts/:alertId/deliveries is session-only: the gateway serves it only to an interactive dashboard sign-in holding install-wide settings.manage, spend.read and budgets.read, and most changes also need a recent sign-in (step-up). Use the gateway dashboard. --dry-run also refuses: there is no reachable change to preview. No request is sent and no credential, profile or file is read. Destinations and Slack secrets are never accepted as command input. ```bash # GET /control/v1/alerts/:alertId/deliveries tdx alerts deliveries --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | --- # tdx api Send an admin HTTP request. **Reads or writes, by method** · any management route Accepts origin-relative paths only; redirects and cross-origin requests are refused. Uses auth status host-bound bearer rules. Successful JSON bodies are printed after mandatory recursive masking, before selection/jq; █ marks masked fields or values. Names containing token, secret, password, key, credential, authorization or cookie are masked, including csrfToken and revealed tokens. Response-derived strings under those names, and response values learned from credential links, secret assignments and embedded JSON, become global echo aliases only at 8 characters or longer; shorter strings are masked in place but may remain visible under innocent names, preserving short public metadata such as live. Request-secret aliases, known bearers and recognized tokedex_\_ credentials retain no minimum; a response Bearer value is masked in place and becomes an echo alias only at 8 characters or longer. Numbers, booleans and null under secret names are masked in place, not collected as global echo strings, except that a non-negative integer or null under a token-count name such as contextWindowTokens is public. RFC 3339 timestamps and gateway entity ids (such as ws_ and a ULID) under secret names are masked in place but never become echo aliases. CLI source labels do not feed name-based echo collection; known bearer echoes are still scrubbed there. Strings containing secret markers, credential links (#reset/#invite and secret parameters), any tokedex_\_ credential, Bearer text, embedded secret JSON/assignments or known bearer echoes (even short values/property names) are replaced WHOLE, not partially reconstructed. Raw text and up to two tolerant percent-decoding rounds are checked independently; invalid sequences stay opaque and any ambiguous/failed decoding masks the whole string, including public literal percentages. Over-masking public values and key metadata is intentional; there is no off switch. Arbitrary unknown secrets under innocent names or beyond the inspected encodings cannot be inferred. Excessive depth, node/secret counts, masked-name collisions or masking work fail closed on the whole value with a fixed notice naming only the limit kind. Non-JSON/unreadable bodies are withheld with a notice, all response headers remain private, and gateway errors use safe mapped diagnostics. Revealing admin routes carry a credential-masked notice when output is masked. Inference-key creation points to api-keys create --token-file or --secretless; do not repeat an accepted write to recover a masked credential. GET/HEAD reject --input bodies. --dry-run reads explicit input files/stdin and shows the masked actual method/path/body without HTTP or saved-credential lookup; authentication and gateway acceptance remain unverified. ```bash tdx api [flags] ``` **Arguments** | Argument | Type | Description | |---|---|---| | `METHOD` | one of `GET`, `HEAD`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS` | Required. HTTP method; GET, HEAD and OPTIONS are non-mutating; only GET/HEAD are bodyless. | | `path` | string | Required. Origin-relative admin path, optionally with query parameters. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `-F`, `--field` | string | | Repeat key=value; booleans, null and safe integers are typed; @file or @- reads UTF-8 text; nested [key] and final [] arrays supported. Query parameters for GET/HEAD or with --input, otherwise JSON body. Repeatable. | | `--input` | path | | Read a JSON body from a regular file or - for stdin; UTF-8, at most 1 MiB; stdin limited to 3 seconds. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `request` | masked-request | Actual masked method/path; body included only in dry-run, otherwise withheld; █ marks masking. | | `response` | masked-response\|null | HTTP success status and masked JSON body, or withheld notice; no response headers. | | `source` | masked-bearer-source | Masked connection provenance; dry-run origin may be unobserved. | | `preview` | write-preview\|null | Preview of a request that is not sent, unchecked by the gateway; null after execution. | Every command also takes the [global flags](/cli/reference#global-flags) and reads the [environment variables](/cli/reference#environment-variables) that the command reference lists once. --- # tdx api-keys Manage API keys (tokedex_ik_). Create, list, view, disable, enable, rotate and revoke API keys. Issued and rotated tokens go only to a new owner-only --token-file, never stdout, JSON or jq. --owner maps the gateway owner object; another personal holder requires --secretless and gateway authorization. Session-only pickup is unavailable; use the dashboard as the holder. Dry-run creates no credential file. Every command also takes the [global flags](/cli/reference#global-flags) and reads the [environment variables](/cli/reference#environment-variables) that the command reference lists once. ## Commands | Command | Description | Type | |---|---|---| | [tdx api-keys list](/cli/reference/api-keys#tdx-api-keys-list) | List API keys. | Read | | [tdx api-keys view](/cli/reference/api-keys#tdx-api-keys-view) | Read an API key by public id. | Read | | [tdx api-keys create](/cli/reference/api-keys#tdx-api-keys-create) | Create an API key or a secretless offer. | Write | | [tdx api-keys edit](/cli/reference/api-keys#tdx-api-keys-edit) | Update an API key provider restriction. | Write | | [tdx api-keys enable](/cli/reference/api-keys#tdx-api-keys-enable) | Enable an API key. | Write | | [tdx api-keys disable](/cli/reference/api-keys#tdx-api-keys-disable) | Disable an API key. | Write | | [tdx api-keys rotate](/cli/reference/api-keys#tdx-api-keys-rotate) | Issue a new secret generation. | Write | | [tdx api-keys revoke](/cli/reference/api-keys#tdx-api-keys-revoke) | Revoke an API key. | Write | | [tdx api-keys pickup](/cli/reference/api-keys#tdx-api-keys-pickup) | Claim a secretless offer as its signed-in holder. | Not available yet | ## tdx api-keys list List API keys. **Reads** Read one gateway page of public key metadata. hasMore and nextCursor report truncation; tokens, grants, extensions and secret generations are withheld. See [Masked read output](/cli/reference#masked-read-output). Large pages can exceed these limits; tdx api GET /control/v1/inference-keys --field limit=20 --json reads a smaller page through the generic api command, masked by the same policy. ```bash # GET /control/v1/inference-keys tdx api-keys list [flags] ``` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `keys` | public-key[] | Key id, name, status, creation and expiry only. | | `hasMore` | boolean | Whether the gateway has another page. | | `nextCursor` | string\|null | Gateway continuation cursor; null on the final page. | ## tdx api-keys view Read an API key by public id. **Reads** Requires inference_keys.read. Read one key's public metadata: id, name, status, creation, expiry, allowed models and providers, and each secret generation's number and state (current, grace or retired). Tokens, verifiers, owners, grants, extensions and secret-generation timestamps are withheld. Reads are read-only and --dry-run still reads. See [Masked read output](/cli/reference#masked-read-output). ```bash # GET /control/v1/inference-keys/:keyId tdx api-keys view --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `key` | public-key-detail | Key id, name, status, creation, expiry, allowedModels and allowedProviders (null for no additional restriction) and generations (number and state only). | ## tdx api-keys create Create an API key or a secretless offer. **Writes** The gateway mints the credential only into a new --token-file (exclusive owner-only 0600 file; existing safe parent required), never stdout, JSON or jq. --owner sends the existing gateway owner object; when omitted the gateway defaults ownership. A personal key for another holder requires --secretless; gateway permissions and workspace policy still apply. Without --owner, user/PAT callers default to their own personal key, while master-key and admin-key callers default to unowned keys. Secretless offers require a personal owner; master-key and admin-key callers can name a personal owner with --owner. Pickup requires an interactive dashboard session and is unavailable to this bearer-only CLI. File preflight happens before POST; a committed mint with failed delivery is reported explicitly, never retried or printed as a fallback. Dry-run reads no secret files or profiles, makes no request and creates no files; the gateway has not checked the requested policy and may reject or adjust it. See [Checked request values](/cli/reference#checked-request-values) and [Masked write output](/cli/reference#masked-write-output). ```bash # POST /control/v1/inference-keys tdx api-keys create --name [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--name` | string | | Display name. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--allowed-model` | string | | Exact public model id from tdx models list; repeat for multiple ids. Repeatable. | | `--all-models` | boolean | `false` | Request every model allowed by workspace policy. | | `--allowed-provider` | string | | Exact catalogue provider id; repeat for multiple ids. Repeatable. | | `--all-providers` | boolean | `false` | Remove the additional key restriction; workspace provider policy still applies. | | `--description` | string | | Non-secret description. | | `--expires-at` | datetime | | Absolute ISO-8601 expiry; omitted uses gateway policy. | | `--secretless` | boolean | `false` | Create an offer without issuing a token. | | `--token-file` | path | | New owner-only token file; never overwrite an existing path. | | `--owner` | json | | Owner JSON: kind personal\|service\|none, userId and workspaceId strings or null; omitted ids become null. | **Constraints** - Exactly one of `--allowed-model`, `--all-models` - At most one of `--allowed-provider`, `--all-providers` - At most one of `--secretless`, `--token-file` - `--token-file` is required unless `--secretless` or `--dry-run` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `key` | public-key | Key id, name, status, creation and expiry only. | | `credential` | delivery-metadata | Delivery status and destination kind only; never a token or path. | | `preview` | write-preview | Requested changes, unchecked by the gateway; never credentials. | ## tdx api-keys edit Update an API key provider restriction. **Writes** Change only the additional provider restriction. All providers remains bounded by workspace policy. See [Masked write output](/cli/reference#masked-write-output). ```bash # PATCH /control/v1/inference-keys/:keyId tdx api-keys edit --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--allowed-provider` | string | | Exact catalogue provider id; repeat for multiple ids. Repeatable. | | `--all-providers` | boolean | `false` | Remove the additional key restriction; workspace provider policy still applies. | **Constraints** - Exactly one of `--allowed-provider`, `--all-providers` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `key` | public-key-detail\|null | Public key metadata and provider restriction; null during dry-run. | | `preview` | write-preview\|null | Requested changes only; null after execution. | ## tdx api-keys enable Enable an API key. **Writes** Requires inference_keys.manage. Enable a disabled key by public id; revoked keys stay refused with KEY_REVOKED and expired keys with CONFLICT (exit 6). No request body is sent. A key already in that state is answered unchanged. Dry-run reports the requested change only without reading secret files or profiles, sending requests or creating files. See [Checked request values](/cli/reference#checked-request-values) and [Masked write output](/cli/reference#masked-write-output). ```bash # POST /control/v1/inference-keys/:keyId/enable tdx api-keys enable --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `key` | public-key | Key id, name, status, creation and expiry only. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | ## tdx api-keys disable Disable an API key. **Writes** Requires inference_keys.manage. Disable by public id: the key stops authenticating within the gateway's propagation bound, and tdx api-keys enable reverses it. No request body is sent. A key already in that state is answered unchanged. Dry-run reports the requested change only without reading secret files or profiles, sending requests or creating files. See [Checked request values](/cli/reference#checked-request-values) and [Masked write output](/cli/reference#masked-write-output). ```bash # POST /control/v1/inference-keys/:keyId/disable tdx api-keys disable --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `key` | public-key | Key id, name, status, creation and expiry only. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | ## tdx api-keys rotate Issue a new secret generation. **Writes** Requires inference_keys.manage; a personal key can be rotated only by its holder (otherwise forbidden, exit 4). Issue a new secret generation by public id. The gateway reveals the new token once: it goes only to a new --token-file (exclusive owner-only 0600 file reserved before POST; existing safe parent required; existing files and symlinks are never overwritten), never stdout, JSON, jq, hints or fallbacks. --grace sets how long the previous secret keeps working; omitted, nothing is sent and the gateway default (24h) applies. While an earlier superseded secret is still in grace, the gateway refuses another rotation with ROTATION_IN_PROGRESS (exit 6) unless --end-previous-grace ends that grace now. A committed rotation whose delivery failed or could not be confirmed, including an accepted reply that could not be read, fails with KEY_ROTATED_DELIVERY_FAILED (exit 1) and no token: do not repeat it blindly. A timeout leaves the outcome unknown (REQUEST_TIMEOUT, exit 7): inspect the key with tdx api-keys view before rotating again. Dry-run reads no secret files or profiles, makes no request and creates no files. See [Checked request values](/cli/reference#checked-request-values) and [Masked write output](/cli/reference#masked-write-output). ```bash # POST /control/v1/inference-keys/:keyId/rotate tdx api-keys rotate --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--token-file` | path | | New owner-only token file; never overwrite an existing path. | | `--grace` | one of `now`, `1h`, `24h`, `7d` | | How long the previous secret keeps working; omitted uses the gateway default (24h). | | `--end-previous-grace` | boolean | `false` | End the grace of an earlier secret that is still in grace instead of being refused. | **Constraints** - `--token-file` is required unless `--dry-run` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `key` | public-key | Key id, name, status, creation and expiry only. | | `rotation` | rotation-metadata | New generation, previous generation and previous grace end (previousNotAfter); never a token. | | `credential` | delivery-metadata | Delivery status and destination kind only; never a token or path. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | ## tdx api-keys revoke Revoke an API key. **Writes** Revoke by public id using the gateway default operator reason. Dry-run reports requested revocation only without reading secret files or profiles, sending requests or creating files. See [Checked request values](/cli/reference#checked-request-values) and [Masked write output](/cli/reference#masked-write-output). ```bash # POST /control/v1/inference-keys/:keyId/revoke tdx api-keys revoke --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `key` | public-key | Key id, name, status, creation and expiry only. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | ## tdx api-keys pickup Claim a secretless offer as its signed-in holder. **Not available yet.** Running it exits 7 with `NOT_IMPLEMENTED`. Unavailable: pickup requires the holder's interactive dashboard session. This bearer-only CLI cannot call the session-only route; use the dashboard. No request or local credential read is performed. ```bash # POST /control/v1/inference-keys/:keyId/pickup tdx api-keys pickup --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--token-file` | path | | New owner-only token file; never overwrite an existing path. | --- # tdx audit Read and follow the audit log (the dashboard's Events tab). Read and follow the audit log (the dashboard's Events tab): the control-event journal, which records both audit and operational events of control-plane changes. list, show and stream require audit.read. status reads the journal, writer and queue status and requires install-wide status.read instead. Every command also takes the [global flags](/cli/reference#global-flags) and reads the [environment variables](/cli/reference#environment-variables) that the command reference lists once. ## Commands | Command | Description | Type | |---|---|---| | [tdx audit list](/cli/reference/audit#tdx-audit-list) | List control events, newest first. | Read | | [tdx audit show](/cli/reference/audit#tdx-audit-show) | Read one control event. | Read | | [tdx audit stream](/cli/reference/audit#tdx-audit-stream) | Follow control events as they are recorded. | Read | | [tdx audit status](/cli/reference/audit#tdx-audit-status) | Read control-plane journal, writer and queue status. | Read | ## tdx audit list List control events, newest first. **Reads** Read one page of the control-event journal. A cursor the journal no longer holds (pruned, or from a replaced journal) fails with CURSOR_EXPIRED (exit 6); restart without --cursor. earliest is the earliest retained cursor. Without filters, nextCursor and earliest also resume audit stream, and a stream cursor continues this list. A value longer than 4096 characters prints as [withheld: too long] on its own while the rest prints, and masking still sees it. A nextCursor or earliest longer than 2048 characters prints as [withheld: too long] while hasMore keeps the gateway's value; --cursor refuses the marker before any request. See [Audit event fields](/cli/reference#audit-event-fields) and [Observability filters and output](/cli/reference#observability-filters-and-output). ```bash # GET /control/v1/events tdx audit list [flags] ``` **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--since` | datetime | | Only events that occurred at or after this instant. | | `--until` | datetime | | Only events that occurred at or before this instant. | | `--category` | one of `audit`, `operational` | | Audit or operational. | | `--event-type` | string | | Event type; the gateway's lowercase name (a letter, then up to 127 lowercase letters, digits, dots or underscores). | | `--action` | string | | Audit action; the gateway's lowercase name (a letter, then up to 127 lowercase letters, digits, dots or underscores). | | `--outcome` | one of `committed`, `rejected`, `failed`, `partial`, `cancelled` | | Terminal outcome. | | `--resource-type` | string | | Resource type; the gateway's lowercase name (a letter, then up to 127 lowercase letters, digits, dots or underscores). | | `--resource-id` | string | | Resource id. | | `--operation-id` | string | | Operation id. | | `--workspace-id` | string | | Only events scoped to this public workspace id. | | `--limit` | integer | | Page size; the gateway clamps it to 1..200 and defaults to 50. | | `--cursor` | string | | Opaque nextCursor from a previous audit list page with the same filters; pass it as --cursor=\. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `events` | public-control-event[] | Projected control events. | | `hasMore` | boolean | Whether a further page exists. | | `nextCursor` | string\|null | Gateway continuation cursor; null on the final page. | | `earliest` | string\|null | Earliest retained cursor; null for an empty journal. | ## tdx audit show Read one control event. **Reads** Read one control event by its event id. A value longer than 4096 characters prints as [withheld: too long] on its own while the rest prints, and masking still sees it. See [Audit event fields](/cli/reference#audit-event-fields) and [Observability filters and output](/cli/reference#observability-filters-and-output). ```bash # GET /control/v1/events/:eventId tdx audit show --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Event id: 1-512 printable ASCII characters without whitespace; never a credential. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `event` | public-control-event | The projected control event. | ## tdx audit stream Follow control events as they are recorded. **Reads** Follow the journal over server-sent events and print one compact JSON line per event as it arrives, the same with or without --json; --json=\ selects event and cursor per line. --jq is refused before any request; pipe the lines to jq -c instead. Heartbeats are not printed and a partial frame is never printed. Connecting is limited to 3 seconds; afterwards there is no total deadline, only the idle timeout. Each frame is masked with the same policy as api, learning aliases from that frame only, unlike audit list, which learns them from the whole page: a secret learned from one frame is not masked when a later frame echoes it under an innocent name. Body positions of a known or learned gateway token are counted across the whole session: a value in a frame that would take a token past its limit prints as █, a value showing only positions already printed prints, and lines already printed are never masked after the fact. A token learned from a frame is counted from that frame on: positions of it printed in earlier frames, before the CLI could recognise it, are not counted and cannot be retracted. The bearer the CLI knows is counted from the first frame. A learned token stays tracked for the rest of the session; once the session tracks more than 1024 tokens the stream stops with OUTPUT_MASK_LIMIT (exit 7) rather than forget one. A frame that cannot be masked, or whose cursor masking would change, stops the stream with an error and is not printed, while earlier lines stay on stdout. A frame over 1 MiB fails with RESPONSE_TOO_LARGE. --max-events and the first SIGINT or SIGTERM stop with exit 0 and close the connection, even while a line waits for stdout; that pending line may then be left incomplete, so a reader that later drains the pipe can see a truncated last line, while every earlier line is complete. A second signal terminates by default. A consumer closing stdout is detected on the next event write, which then stops with exit 0 and closes the connection. Until an event is written, a stream whose consumer has closed ends only on the idle timeout (exit 7 STREAM_IDLE_TIMEOUT), a signal (exit 0) or the gateway ending the stream (exit 7 STREAM_CLOSED); heartbeats reset the idle timer, so --idle-timeout does not bound a heartbeat-only stream. Any other stdout write failure exits 1 with OUTPUT_WRITE_FAILED. The gateway ending the stream exits 7 STREAM_CLOSED; resume with --cursor set to the cursor of the last printed line. A cursor the journal no longer holds fails with CURSOR_EXPIRED (exit 6); restart without --cursor. A value longer than 4096 characters prints as [withheld: too long] on its own while the rest prints, and masking still sees it. See [Audit event fields](/cli/reference#audit-event-fields). --dry-run still performs this read. ```bash # GET /control/v1/events/stream tdx audit stream [flags] ``` **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--cursor` | string | | Resume after the event this cursor names: the cursor of a printed line, or a nextCursor or earliest from an audit list without filters; pass it as --cursor=\. Omitted: a bounded backfill of recent events, then live events. | | `--max-events` | integer | | Stop with exit 0 after printing this many events. | | `--idle-timeout` | integer | | Seconds without any bytes before stopping with STREAM_IDLE_TIMEOUT (exit 7); 1..3600, default 60. Heartbeats are bytes and reset it, so it does not bound a heartbeat-only stream. The gateway heartbeats every 15 seconds by default. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `event` | public-control-event | The projected control event. | | `cursor` | string | Stream cursor of this event; pass it to --cursor to resume after it. | Prints one JSON object per line as events arrive, so `--jq` is refused; pipe the lines to `jq -c` instead. ## tdx audit status Read control-plane journal, writer and queue status. **Reads** Requires install-wide status.read. Reads GET /control/v1/status: the audit journal mode, local journal health, whether privileged mutations are accepted, the unsafe-override flag, single-writer ownership, the retained journal range, queue health and configured exporters. The gateway's object and apiVersion are validated, not printed. Every printed value comes from one fail-closed masking pass over the request, the whole gateway reply (including fields the CLI drops) and the CLI's projection, before selection/jq; █ marks masked values. mode and local are printed as the CLI's own validated literals. A reply that cannot be masked within the fixed limits fails with OUTPUT_MASK_LIMIT (exit 7) and no values; a malformed reply fails with INVALID_RESPONSE (exit 7). --dry-run still performs this read. ```bash # GET /control/v1/status tdx audit status [flags] ``` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `mode` | string | Journal mode: local-required, local-best-effort or off. | | `local` | string | Local journal health: on, off or degraded. | | `mutationReady` | boolean | Whether privileged mutations are currently accepted. | | `unsafeOverride` | boolean | Whether audit is disabled by an unsafe operator override (mode off). | | `writer` | control-writer | Single-writer ownership: owned, conflict, owner node, replica and language ids, last heartbeat. | | `journal` | control-journal | Journal id, generation, retained sequence range, segments, bytes and oldest event age. | | `queues` | control-queues | Audit and operational queue depth and capacity, dropped operational events. | | `exporters` | control-exporter[] | Exporter id, sanitized origin, state, lag and queue depth. | **Examples** Read the masked public projection as versioned JSON: ```bash tdx audit status --json ``` Select declared output fields: ```bash tdx audit status --json=mode,mutationReady ``` **See also:** [tdx observability status](/cli/reference/observability#tdx-observability-status), [tdx doctor](/cli/reference/doctor) --- # tdx auth Sign in with the browser or a token, and manage saved profiles. login signs in with the browser, approving a code in the dashboard for a personal access token, or validates and saves a token you supply; profiles are host-bound and saved locally. status reads fresh public identity, permissions and expiry, preferring ephemeral TOKEDEX_TOKEN. logout removes the selected saved profile, revoking a token that browser sign-in issued for it. methods reads the gateway's public sign-in configuration and sends no credential. POSIX permissions are local protection, not encryption. Dashboard-only commands stay dashboard-only: a browser sign-in issues a token, never a dashboard session. Every command also takes the [global flags](/cli/reference#global-flags) and reads the [environment variables](/cli/reference#environment-variables) that the command reference lists once. ## Commands | Command | Description | Type | |---|---|---| | [tdx auth login](/cli/reference/auth#tdx-auth-login) | Sign in with the browser or save a token. | Write | | [tdx auth status](/cli/reference/auth#tdx-auth-status) | Inspect credential source and permissions without secrets. | Read | | [tdx auth logout](/cli/reference/auth#tdx-auth-logout) | Sign out: remove the saved profile and revoke a browser sign-in's token. | Write | | [tdx auth methods](/cli/reference/auth#tdx-auth-methods) | Read the public sign-in configuration. | Read | ## tdx auth login Sign in with the browser or save a token. **Writes a local profile** Browser sign-in (--method browser, the default when no token is supplied): prints a code, opens the gateway's /cli-sign-in page, and waits while you approve the code there from your own dashboard sign-in, confirming it's you if you signed in more than ten minutes ago. Only enter a code your own terminal shows you. The gateway then issues a personal access token that acts as you, with what you may do at each use and never more, minus the dashboard-only actions; it ends when it expires (--expires-in, default 30d, at most 90d), when you sign out everywhere or change your password, and when it is revoked under Account → Access tokens or by auth logout. Requires --host, TOKEDEX_HOST or the selected profile's saved origin, and refuses TOKEDEX_TOKEN, --value-file and --value-stdin. Without --method and with no terminal on stderr, nothing is started: pass --method browser or supply a token. The request expires after ten minutes. A denial or an expiry exits 3 (SIGN_IN_DENIED, SIGN_IN_EXPIRED). If the CLI cannot confirm token delivery, it exits 7 (SIGN_IN_DELIVERY_UNCONFIRMED) and keeps the profile as it was. Revoke any token issued by that sign-in under Account → Access tokens before trying again. The token is saved to the selected profile like a token login's, and signing in again into that profile revokes the token its previous browser sign-in issued. Token login (--method token): supply exactly one of --value-file, --value-stdin or TOKEDEX_TOKEN; existing credentials are never login inputs. File/stdin accept one UTF-8 token and at most one final newline (8194 bytes); stdin is limited to 3 seconds. Files must be owner-owned mode 0600 regular files with no symlinks or unsafe writable ancestors. Validate with GET /control/v1/me before saving or replacing the selected bearer profile. An explicit supplied token may intentionally rebind that profile to a new origin; the old saved credential survives a failed validation or a save that fails before it commits. TOKEDEX_TOKEN requires --host or TOKEDEX_HOST and never uses a saved profile origin. File/stdin host: --host, TOKEDEX_HOST, selected profile origin; profile: --profile, TOKEDEX_PROFILE, default. No remote default. XDG_CONFIG_HOME must already exist; it and its ancestors are never created. When unset, HOME must already exist; only HOME/.config (0700) and the profile files below it may be created. Missing required roots fail without creating a partial tree; create the root manually or set XDG_CONFIG_HOME to an existing directory. Profiles use owner-owned POSIX directory 0700 and files 0600 under the profile root, with exclusive nonsecret per-profile locks and atomic replacement. Every default-root write syncs HOME, then .config and the profile files before publication, even when .config already exists; nothing above HOME is synced. Explicit-root writes sync only from XDG_CONFIG_HOME down to the profile files, never its ancestors or a separate HOME. Required pre-publication sync failures refuse the write; post-publication failures report committed-but-uncertain durability, not rollback. Insecure existing state is refused, not repaired. Local protection is not encryption and does not protect against the same OS user or root; crash-abandoned locks require manual inspection. Master keys receive a break-glass warning, never an escalation fallback. --dry-run reads no saved profile, secret file or stdin, sends no request and creates nothing; it reports an unavailable basis, unchecked by the gateway, and may not show the saved origin. Dry-run requires no credential source; TOKEDEX_TOKEN, when set, is used only to mask the token preview. See [Masked read output](/cli/reference#masked-read-output). A masking failure saves no bearer profile. ```bash # POST /control/v1/cli-sign-in/start # POST /control/v1/cli-sign-in/redeem # GET /control/v1/me # POST /control/v1/me/revoke tdx auth login [flags] ``` **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--method` | one of `browser`, `token` | | Browser (the default when no token is supplied) or token. | | `--name` | string | | Browser sign-in: the token's name in Account → Access tokens (default: \ on \). | | `--expires-in` | one of `1d`, `7d`, `30d`, `90d` | | Browser sign-in: how long the token lasts (default 30d). | | `--no-browser` | boolean | `false` | Browser sign-in: print the sign-in page's address instead of opening it. | | `--value-file` | path | | Read a credential only from this file. | | `--value-stdin` | boolean | `false` | Read a credential from standard input. | **Constraints** - At most one of `--value-file`, `--value-stdin` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `profile` | public-profile | Selected name and canonical origin only; origin may be unobserved during dry-run. | | `principal` | public-principal\|null | Fresh validated kind, public id and name; null during dry-run. | | `breakGlass` | boolean\|null | Validated break-glass status; null during dry-run. | | `expiresAt` | string\|null | When the saved token expires; null when it never does, and during dry-run. | | `warning` | string\|null | A master-key break-glass warning, or a previous browser sign-in's token left unrevoked; never a credential. | | `preview` | write-preview\|null | Requested replacement only, with an unavailable basis; no secret input or saved profile is read. | **Examples** Sign in with the browser: ```bash tdx auth login --host https://gateway.example.test ``` Sign in from another machine's browser, for a week: ```bash tdx auth login --host https://gateway.example.test --no-browser --expires-in 7d ``` Validate and protect a redirected bearer token: ```bash tdx auth login --method token --host https://gateway.example.test --value-stdin --json ``` Preview the requested replacement without reading a saved profile or secret input: ```bash tdx auth login --method token --profile staging --dry-run --json ``` ## tdx auth status Inspect credential source and permissions without secrets. **Reads** Read fresh GET /control/v1/me using ephemeral TOKEDEX_TOKEN first, otherwise the selected protected bearer profile. Explicit invalid or refused environment input never falls back. TOKEDEX_TOKEN requires --host or TOKEDEX_HOST and never uses a saved profile origin. Stored-token host: --host, TOKEDEX_HOST, selected profile canonical origin; no remote default. Profile: --profile, TOKEDEX_PROFILE, default (an explicit default wins). A supplied host differing in scheme, name or port from the saved profile's is refused before its credential is sent. Environment bearers never persist implicitly. With an explicit or environment host and token, the saved profile is not opened. The credential's expiry (expiresAt) and whether browser sign-in issued it (source.browserSignIn) are reported; a browser sign-in issues a token, never a dashboard session. HTTPS is required except exact localhost, 127.0.0.1 or [::1] HTTP origins. Redirects and retries are refused; the whole request is limited to 3 seconds and the response to 1 MiB. Only public principal fields and permissions are returned, never grants, CSRF, tokens or cookies. This read still reaches the gateway with --dry-run and may record read usage; it does not preview writes. See [Masked read output](/cli/reference#masked-read-output). ```bash # GET /control/v1/me tdx auth status [flags] ``` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `principal` | public-principal | Route-derived kind, public id and display name only. | | `permissions` | string[] | Public permission names reported by the gateway. | | `installPermissions` | string[] | Public install-wide permission names reported by the gateway. | | `breakGlass` | boolean | Whether the gateway identifies this credential as break-glass. | | `expiresAt` | string\|null | When the token expires, as the gateway reports it; null when it never does. | | `source` | bearer-source | Canonical origin, profile label, resolution sources and whether browser sign-in issued the credential; never the credential. | **Examples** Inspect TOKEDEX_TOKEN without reading or saving a profile: ```bash tdx auth status --host https://gateway.example.test --json ``` Read fresh public fields with the saved profile when TOKEDEX_TOKEN is unset: ```bash tdx auth status --profile staging --json=principal,permissions ``` ## tdx auth logout Sign out: remove the saved profile and revoke a browser sign-in's token. **Writes a local profile** Remove only the named local bearer profile selected by --profile, TOKEDEX_PROFILE, default. TOKEDEX_TOKEN, including invalid input, never selects or changes the selected saved profile; when set, it is used only to mask output. A supplied --host or TOKEDEX_HOST must still match the saved canonical origin. A token that browser sign-in issued for this profile is revoked on the gateway first (POST /control/v1/me/revoke, with the token itself); the profile is removed even when the gateway does not confirm it, and a warning says the token stays valid until it expires or is revoked under Account → Access tokens. A token you supplied with token login is not revoked, since it may be in use elsewhere: logout only removes it from this machine. POSIX ownership, 0700 directory, 0600 regular file, no-symlink and exclusive-lock checks still apply; insecure state is not repaired. A missing profile fails explicitly. --dry-run reads no saved profile or secret files, creates no parents/locks/tempfiles and reports only requested local removal with unavailable basis, never remote revocation. Real logout masks its output with the saved token and TOKEDEX_TOKEN (when set); a mask-limit refusal (OUTPUT_MASK_LIMIT, exit 7) happens before removal and leaves the profile in place. ```bash # POST /control/v1/me/revoke tdx auth logout [flags] ``` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `profile` | public-profile | Selected name and canonical origin only; origin may be unobserved during dry-run. | | `removed` | boolean | Whether the selected local bearer profile was removed; false during dry-run. | | `remoteRevoked` | boolean | Whether the gateway revoked a token browser sign-in issued; false for a token login's token and during dry-run. | | `warning` | string\|null | Set when a browser sign-in's token could not be revoked on the gateway. | | `preview` | write-preview\|null | Requested local removal only; null after execution. | **Examples** Remove the selected saved profile, revoking a browser sign-in's token: ```bash tdx auth logout --profile staging --json ``` Preview the requested local removal without reading the saved profile: ```bash tdx auth logout --profile staging --dry-run --json ``` ## tdx auth methods Read the public sign-in configuration. **Reads** Reads the public GET /auth/v1/config, which needs no credential: the sign-in methods the gateway offers, whether single sign-on is required, whether this is a first run, browser session settings and the issued credential prefixes. No Authorization header or credential is sent. Host: --host, TOKEDEX_HOST, otherwise the selected local connection profile's saved origin; that profile's credential is used only to mask output, never sent. Without --host or TOKEDEX_HOST the selected profile's file-safety checks apply (an unsafe profile refuses with PROFILE_UNSAFE); --host or TOKEDEX_HOST skips any profile read. A 401 or 403 keeps its usual code and exit but says no credential was sent. Renamed for name safety: session.cookie is session.browserBound, session.csrfHeader is session.antiForgeryHeader and tokenPrefixes is issuedPrefixes. Every printed value comes from one fail-closed masking pass over the request, the whole gateway reply (including fields the CLI drops) and the CLI's projection, before selection/jq; █ marks masked values. Each method type (oidc, password or bearer) is printed as the CLI's own validated literal. A reply that cannot be masked within the fixed limits fails with OUTPUT_MASK_LIMIT (exit 7) and no values; a malformed reply fails with INVALID_RESPONSE (exit 7). --dry-run still performs this read. ```bash # GET /auth/v1/config tdx auth methods [flags] ``` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `methods` | auth-method[] | Type oidc with id and displayName; type password with breakGlassOnly and minLength; type bearer with accepts. | | `ssoRequired` | boolean | Whether single sign-on is required. | | `firstRun` | boolean | Whether no gateway account exists yet. | | `session` | auth-session | BrowserBound: sessions ride a browser cookie; antiForgeryHeader: the request header name the dashboard sends. | | `issuedPrefixes` | issued-prefixes | Public prefixes of issued inference and management credentials. | **Examples** Read the masked public projection as versioned JSON: ```bash tdx auth methods --host https://gateway.example.test --json ``` Select declared output fields: ```bash tdx auth methods --host https://gateway.example.test --json=methods,ssoRequired ``` **See also:** [tdx auth login](/cli/reference/auth#tdx-auth-login), [tdx profile show](/cli/reference/profile#tdx-profile-show) --- # tdx budgets Manage spend budgets. List, read, create, edit and remove budgets, list per-key default members and adjust counted spend. USD amounts are decimal strings in the gateway grammar and are never converted to numbers. Writes support --dry-run with no request, profile or credential read. Reads remain read-only with --dry-run. Every command also takes the [global flags](/cli/reference#global-flags) and reads the [environment variables](/cli/reference#environment-variables) that the command reference lists once. ## Commands | Command | Description | Type | |---|---|---| | [tdx budgets list](/cli/reference/budgets#tdx-budgets-list) | List budgets. | Read | | [tdx budgets view](/cli/reference/budgets#tdx-budgets-view) | Read a budget. | Read | | [tdx budgets create](/cli/reference/budgets#tdx-budgets-create) | Create a budget. | Write | | [tdx budgets edit](/cli/reference/budgets#tdx-budgets-edit) | Update a budget's limit, policy or note. | Write | | [tdx budgets remove](/cli/reference/budgets#tdx-budgets-remove) | Remove a budget. | Write | | [tdx budgets members](/cli/reference/budgets#tdx-budgets-members) | List the members of a per-key default budget. | Read | | [tdx budgets adjust](/cli/reference/budgets#tdx-budgets-adjust) | Correct a budget's counted spend. | Write | ## tdx budgets list List budgets. **Reads** Read every budget the gateway lets this bearer read (budgets.read); the gateway filters rows by scope and has no pagination, so the list is complete for this reader. Filters are sent as query parameters. Ledger metadata (mode, state, pending, lastSyncAt, rate-limit scope) is reported as the gateway gives it. Uses auth status host-bound bearer rules; --dry-run still reads. ```bash # GET /control/v1/budgets tdx budgets list [flags] ``` **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--target-kind` | one of `org`, `key`, `workspace`, `user`, `model`, `each` | | Only budgets with this target kind. | | `--target-id` | string | | Only budgets whose target names this id. | | `--window` | one of `day`, `week`, `month`, `total` | | Only budgets with this window. | | `--state` | one of `ok`, `warning`, `exceeded` | | Only budgets whose progress is in this state. | | `--workspace-id` | string | | Only budgets that bind requests made in this workspace; rows then say whether they are inherited. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `budgets` | public-budget[] | Gateway budget views, in gateway order. | | `ledger` | ledger-state | Spend ledger mode, state, pending count, lastSyncAt and rate-limit scope. | ## tdx budgets view Read a budget. **Reads** Read one budget and its progress in the current window. Money is {amount, currency: USD} as a decimal string, or null when this reader is not shown amounts. Uses auth status host-bound bearer rules; --dry-run still reads. ```bash # GET /control/v1/budgets/:budgetId tdx budgets view --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Budget id: bud_ followed by a 26-character Crockford ULID. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `budget` | public-budget\|null | Gateway budget view: id, target, window, limit Money, policy, note, counting, timestamps and progress; Money is {amount, currency: USD} or null when hidden; null during dry-run. | ## tdx budgets create Create a budget. **Writes** Create a key, person or model budget with budgets.manage over its target. Org, workspace and per-key default (each) budgets are policy, set by policy rather than here; the gateway refuses to write them through this command with a conflict (exit 6). The gateway decides scope and may refuse (403) or report a duplicate target and window (409). Target and window cannot change later. --limit is a USD decimal string sent exactly as written. Omitted policy fields take gateway defaults. Dry-run reads no profile or credential, sends no request and creates nothing; it reports requested values only. See [Checked request values](/cli/reference#checked-request-values). ```bash # POST /control/v1/budgets tdx budgets create --target-kind --target-id --window --limit [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--target-kind` | one of `key`, `user`, `model` | | What the budget binds: one key, person or model. | | `--target-id` | string | | Target id: the key id, user id or public model id (passed through). | | `--window` | one of `day`, `week`, `month`, `total` | | Calendar window (UTC) or total. | | `--limit` | usd | | USD decimal string in the gateway grammar: 0 or 1-9 integer digits without a leading zero, then optionally . and 1-9 digits; no sign, exponent or grouping; zero refused; sent exactly as written, never as a number. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--within-workspace` | string | | Confine a user or model budget to one workspace id. | | `--unknown-price` | one of `block`, `allow` | | Calls without a known price: block (gateway default) or allow. | | `--on-limit` | one of `refuse`, `alert` | | At the limit: refuse requests (gateway default) or alert only. | | `--alert-threshold` | integer | | Alert threshold percentage; repeat in ascending order (the gateway accepts whole percentages 1-100, at most eight, distinct). Repeatable. | | `--note` | string | | Operator note; amounts readers cannot see hide it too; refused locally if it could hide a credential: a percent sign, bare or written %25 (which decodes to %), or an escape that is not valid UTF-8; name: value or name=value where the name contains token, secret, password, key, credential, authorization or cookie; a #, ? or & directly before such a name, or before reset or invite, with or without =; #reset or #invite; Bearer text or a tokedex_ token. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `budget` | public-budget\|null | Gateway budget view: id, target, window, limit Money, policy, note, counting, timestamps and progress; Money is {amount, currency: USD} or null when hidden; null during dry-run. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | ## tdx budgets edit Update a budget's limit, policy or note. **Writes** PATCH only the named fields. Org, workspace and per-key default (each) budgets are policy, set by policy rather than here; the gateway refuses to write them through this command with a conflict (exit 6). Target and window cannot change (create a new budget instead). --alert-threshold replaces the whole list. An edit naming no field is refused locally as a usage error, before any request or dry-run preview; a change equal to current state is a gateway no-op. Dry-run reads no profile or credential and sends no request. See [Checked request values](/cli/reference#checked-request-values). ```bash # PATCH /control/v1/budgets/:budgetId tdx budgets edit --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Budget id: bud_ followed by a 26-character Crockford ULID. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--limit` | usd | | USD decimal string in the gateway grammar: 0 or 1-9 integer digits without a leading zero, then optionally . and 1-9 digits; no sign, exponent or grouping; zero refused; sent exactly as written, never as a number. | | `--unknown-price` | one of `block`, `allow` | | Calls without a known price: block (gateway default) or allow. | | `--on-limit` | one of `refuse`, `alert` | | At the limit: refuse requests (gateway default) or alert only. | | `--alert-threshold` | integer | | Alert threshold percentage; repeat in ascending order (the gateway accepts whole percentages 1-100, at most eight, distinct). Repeatable. | | `--note` | string | | Operator note; amounts readers cannot see hide it too; refused locally if it could hide a credential: a percent sign, bare or written %25 (which decodes to %), or an escape that is not valid UTF-8; name: value or name=value where the name contains token, secret, password, key, credential, authorization or cookie; a #, ? or & directly before such a name, or before reset or invite, with or without =; #reset or #invite; Bearer text or a tokedex_ token. | | `--clear-note` | boolean | `false` | Clear the note (sends note: null). | **Constraints** - At most one of `--note`, `--clear-note` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `budget` | public-budget\|null | Gateway budget view: id, target, window, limit Money, policy, note, counting, timestamps and progress; Money is {amount, currency: USD} or null when hidden; null during dry-run. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | ## tdx budgets remove Remove a budget. **Writes** Delete a budget with budgets.manage. Org, workspace and per-key default (each) budgets are policy, set by policy rather than here; the gateway refuses to write them through this command with a conflict (exit 6). Spend counters are facts and remain; a new budget on the scope sees them. Dry-run reads no profile or credential and sends no request. See [Checked request values](/cli/reference#checked-request-values). ```bash # DELETE /control/v1/budgets/:budgetId tdx budgets remove --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Budget id: bud_ followed by a 26-character Crockford ULID. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `removed` | budget-removal\|null | Removed budget id and deleted: true; null during dry-run. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | ## tdx budgets members List the members of a per-key default budget. **Reads** Members exist for only `each` (per-key default) budgets; the gateway refuses any other budget. It returns at most 200 members, biggest spenders in the current window first, with no cursor, so a longer membership is truncated at the gateway cap and the reply does not say so. Members outside the reader's spend.read are left out. Uses auth status host-bound bearer rules; --dry-run still reads. ```bash # GET /control/v1/budgets/:budgetId/members tdx budgets members --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Budget id: bud_ followed by a 26-character Crockford ULID. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `budgetId` | string | Budget id. | | `window` | string | Budget window. | | `windowStart` | string\|null | Current window start. | | `resetsAt` | string\|null | Current window end. | | `members` | budget-member[] | Scope, spent and remaining Money (null when hidden), state and call count. | ## tdx budgets adjust Correct a budget's counted spend. **Writes** Org, workspace and per-key default (each) budgets are policy, set by policy rather than here; the gateway refuses to write them through this command with a conflict (exit 6). Adjustments are install-wide only: the gateway requires budgets.manage on the install, so a workspace-scoped budget manager is refused (403). A positive amount adds counted spend; a negative amount credits spend back, lifting every budget on that scope, and can give back no more than the budget has counted (409). The reply's amount is signed. With --idempotency-key the gateway keys the settlement by it with the caller, budget and scope: repeating the same adjustment returns the original and applies nothing, and reusing the key for a different amount or reason is a 409 conflict. The CLI never generates a key and never retries; without one, a repeat after an unknown outcome may apply twice. Dry-run reads no profile or credential and sends no request. See [Checked request values](/cli/reference#checked-request-values). ```bash # POST /control/v1/budgets/:budgetId/adjustments tdx budgets adjust --id --amount --reason-code [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Budget id: bud_ followed by a 26-character Crockford ULID. | | `--amount` | signed-usd | | Signed USD decimal string: the --limit grammar with an optional leading -; zero refused; sent exactly as written. Write --amount -2.5 or --amount=-2.5. | | `--reason-code` | one of `correction`, `grant`, `refund` | | Why the counter is corrected. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--window-start` | datetime | | Window the adjustment is for, as progress.windowStart shows it; refused once that window has ended. | | `--idempotency-key` | string | | Idempotency-Key header: 1-255 printable ASCII characters without spaces; public de-duplication data, shown as given and never treated as a credential. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `adjustment` | budget-adjustment\|null | Settlement id, budget id, scope, window, signed Money amount (null when hidden) and reason; null during dry-run. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | --- # tdx completion Generate shell completion. **Runs locally** Generate a completion script from this command schema. JSON returns the script in data.script. ```bash tdx completion [flags] ``` **Arguments** | Argument | Type | Description | |---|---|---| | `shell` | one of `bash`, `zsh`, `fish` | Required. Completion shell. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `script` | string | Shell completion script. | Every command also takes the [global flags](/cli/reference#global-flags) and reads the [environment variables](/cli/reference#environment-variables) that the command reference lists once. --- # tdx config Inspect compiled gateway configuration. Read compiled gateway configuration (status.read). Provider credential binding names are never printed here; use tdx providers keys list. Every command also takes the [global flags](/cli/reference#global-flags) and reads the [environment variables](/cli/reference#environment-variables) that the command reference lists once. ## Commands | Command | Description | Type | |---|---|---| | [tdx config show](/cli/reference/config#tdx-config-show) | Read the compiled providers and routers. | Read | ## tdx config show Read the compiled providers and routers. **Reads** Requires install-wide status.read. Reads GET /control/status: the compiled providers and routers. Stored provider credential binding names are never printed, even when the gateway includes them for credentials.read; use tdx providers keys list for binding names. Those names remain in the masking context, so a printed id containing one prints as █. Every printed value comes from one fail-closed masking pass over the request, the whole gateway reply (including fields the CLI drops) and the CLI's projection, before selection/jq; █ marks masked values. A reply that cannot be masked within the fixed limits fails with OUTPUT_MASK_LIMIT (exit 7) and no values; a malformed reply fails with INVALID_RESPONSE (exit 7). --dry-run still performs this read. ```bash # GET /control/status tdx config show [flags] ``` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `providers` | compiled-provider[] | Compiled providers: groupId, clientDialectId, publicModelId, enabled and listed. | | `routers` | compiled-router[] | Compiled routers: modelGroupId and publicModelId. | **Examples** Read the masked public projection as versioned JSON: ```bash tdx config show --json ``` Select declared output fields: ```bash tdx config show --json=providers ``` **See also:** [tdx providers keys list](/cli/reference/providers#tdx-providers-keys-list), [tdx audit status](/cli/reference/audit#tdx-audit-status) --- # tdx doctor Check connection, auth, catalogue and backend information. **Reads** Read-only health, bearer login and gateway release identity checks. Catalogue version and backend details are explicitly unavailable: no authoritative version is exposed, and no provider/backend probes are made. Schema/config revisions are not catalogue versions. Uses auth status host-bound bearer rules. Once connection inputs resolve, the independent check report remains on stdout; exits 1 if connection or login fails, otherwise 0. Gateway-version unavailability alone is not fatal; inspect ok/available and error fields. Gateway version is release environment and optional commit, not a package version. --dry-run remains read-only and performs the same reads. The login section is masked with the full output-mask policy together with the whole gateway reply and request before selection/jq; █ marks masked values. Checked booleans, values the CLI sets itself and its source field (where present) print unmasked; source is only checked to exclude the token. A login reply that cannot be masked within the fixed limits reports login error OUTPUT_MASK_LIMIT and no values. ```bash # GET /healthz # GET /control/v1/me # GET /version tdx doctor [flags] ``` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `connection` | connection-check | Validated health result or safe error code. | | `login` | login-check | Projected bearer identity and permissions or safe error code. | | `gatewayVersion` | release-identity | Validated release environment and optional commit, or unavailable. | | `catalogueVersion` | unavailable-version | Explicitly unavailable; never substitutes schema/config revisions. | | `backend` | unavailable-check | Explicitly unavailable; no backend probes. | | `source` | bearer-source | Canonical origin, profile label and resolution sources; never the credential. | Every command also takes the [global flags](/cli/reference#global-flags) and reads the [environment variables](/cli/reference#environment-variables) that the command reference lists once. --- # tdx guide Print bundled agent getting-started material. **Runs locally** Print public agent documentation bundled from the docs site at CLI build time, with a live documentation link. No runtime fetch, credentials or local profiles. Default topic: for-agents. sdk and gateway select the corresponding quickstart; llms prints a compact navigation-derived machine index. JSON returns topic, url and content. ```bash tdx guide [topic] [flags] ``` **Arguments** | Argument | Type | Description | |---|---|---| | `topic` | one of `for-agents`, `sdk`, `gateway`, `llms` | Bundled documentation topic. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `topic` | string | Selected guide topic. | | `url` | string | Live documentation URL. | | `content` | string | Build-time public Markdown snapshot. | Every command also takes the [global flags](/cli/reference#global-flags) and reads the [environment variables](/cli/reference#environment-variables) that the command reference lists once. --- # tdx identity-settings Inspect sign-in and session settings. Sign-in and session settings. show works with a bearer holding install-wide identity.read; set and sign-out-everyone are dashboard-only (session-only with step-up). SSO providers are the OIDC identity providers people sign in through, in the separate sso-providers namespace, unrelated to the provider credentials that providers keys manages. Every command also takes the [global flags](/cli/reference#global-flags) and reads the [environment variables](/cli/reference#environment-variables) that the command reference lists once. ## Commands | Command | Description | Type | |---|---|---| | [tdx identity-settings show](/cli/reference/identity-settings#tdx-identity-settings-show) | Read identity settings. | Read | | [tdx identity-settings set](/cli/reference/identity-settings#tdx-identity-settings-set) | Change identity settings (dashboard only). | Dashboard only | | [tdx identity-settings sign-out-everyone](/cli/reference/identity-settings#tdx-identity-settings-sign-out-everyone) | Sign everyone out (dashboard only). | Dashboard only | ## tdx identity-settings show Read identity settings. **Reads** Requires install-wide identity.read. Read password login, single sign-on requirement, password length, session lifetimes, the sign-out epoch, whether SSO users may keep a local password, the number of configured SSO providers and the gateway's warnings. --dry-run still performs this read. See [Masked read output](/cli/reference#masked-read-output), [Sign-in settings output](/cli/reference#sign-in-settings-output) and [Checked request values](/cli/reference#checked-request-values). ```bash # GET /control/v1/identity-settings tdx identity-settings show [flags] ``` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `identitySettings` | public-identity-settings | PasswordLogin, ssoRequired, minPasswordLength, sessionIdleMinutes, sessionAbsoluteHours, sessionEpoch, allowLocalPasswordForSsoUsers, providers (configured SSO provider count) and warnings; every value masked under neutral names, so settings normally print real values. | ## tdx identity-settings set Change identity settings (dashboard only). **Dashboard only.** The gateway serves this only to a signed-in dashboard session, so the CLI refuses it with `SESSION_REQUIRED`. Unavailable to this bearer-only CLI: PUT /control/v1/identity-settings is session-only: the gateway serves it only to an interactive dashboard sign-in holding install-wide identity.manage, with a recent sign-in (step-up) every time. Use the gateway dashboard. --dry-run also refuses: there is no reachable change to preview. No request is sent and no credential, profile or file is read. ```bash # PUT /control/v1/identity-settings tdx identity-settings set [flags] ``` ## tdx identity-settings sign-out-everyone Sign everyone out (dashboard only). **Dashboard only.** The gateway serves this only to a signed-in dashboard session, so the CLI refuses it with `SESSION_REQUIRED`. Unavailable to this bearer-only CLI: POST /control/v1/identity-settings/sign-out-everyone is session-only: the gateway serves it only to an interactive dashboard sign-in holding install-wide identity.manage, with a recent sign-in (step-up) every time. It ends every session and signs the asking session back in. Use the gateway dashboard. --dry-run also refuses: there is no reachable change to preview. No request is sent and no credential, profile or file is read. ```bash # POST /control/v1/identity-settings/sign-out-everyone tdx identity-settings sign-out-everyone [flags] ``` --- # tdx invites Manage one-shot invitation links. See [Invitation links](/cli/reference#invitation-links). Every command also takes the [global flags](/cli/reference#global-flags) and reads the [environment variables](/cli/reference#environment-variables) that the command reference lists once. ## Commands | Command | Description | Type | |---|---|---| | [tdx invites list](/cli/reference/invites#tdx-invites-list) | List invitations. | Read | | [tdx invites create](/cli/reference/invites#tdx-invites-create) | Create an invitation. | Write | | [tdx invites regenerate](/cli/reference/invites#tdx-invites-regenerate) | Revoke and replace an invitation with a new link. | Write | | [tdx invites revoke](/cli/reference/invites#tdx-invites-revoke) | Revoke an invitation. | Write | ## tdx invites list List invitations. **Reads** Requires users.read. Read the gateway's bounded invitation list (at most 1000 stored rows); no pagination or completeness is inferred. See [People and role commands](/cli/reference#people-and-role-commands). ```bash # GET /control/v1/invites tdx invites list [flags] ``` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `invites` | masked-route-data | Gateway data after mandatory CLI masking; █ marks masked values. | | `notice` | string | Present instead of data when masking withholds the entire result. | ## tdx invites create Create an invitation. **Writes** Requires invites.create for the target. See [Invitation links](/cli/reference#invitation-links). ```bash # POST /control/v1/invites tdx invites create --target [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--target` | json | | Public target JSON: {role} or {workspaceId, role, accessEndsAt?}. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--email` | string | | Optional recipient address; required by the gateway for admin-grade targets. | | `--expires-in-hours` | integer | | Integer lifetime from 1 to 168 hours; admin-grade gateway limit is 24 hours. | | `--token-file` | path | | New owner-only token file; never overwrite an existing path. | | `--secretless` | boolean | `false` | Explicitly discard the minted invitation link without displaying it; not a gateway mint flag. | **Constraints** - At most one of `--token-file`, `--secretless` - `--token-file` is required unless `--secretless` or `--dry-run` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `invite` | masked-route-data | Gateway data after mandatory CLI masking; █ marks masked values. | | `delivery` | masked-route-data | Gateway data after mandatory CLI masking; █ marks masked values. | | `preview` | write-preview\|null | Requested method, path and body only, with no diff and unchecked by the gateway; null after execution. | | `notice` | string | Present instead of data when masking withholds the entire result. | ## tdx invites regenerate Revoke and replace an invitation with a new link. **Writes** Requires invites.create for the target. The gateway revokes the old invitation and creates a new one under the caller's authority; it does not inherit the old inviter's authority. See [Invitation links](/cli/reference#invitation-links). ```bash # POST /control/v1/invites/:inviteId/regenerate tdx invites regenerate --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--expires-in-hours` | integer | | Integer lifetime from 1 to 168 hours; admin-grade gateway limit is 24 hours. | | `--token-file` | path | | New owner-only token file; never overwrite an existing path. | | `--secretless` | boolean | `false` | Explicitly discard the minted invitation link without displaying it; not a gateway mint flag. | **Constraints** - At most one of `--token-file`, `--secretless` - `--token-file` is required unless `--secretless` or `--dry-run` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `invite` | masked-route-data | Gateway data after mandatory CLI masking; █ marks masked values. | | `delivery` | masked-route-data | Gateway data after mandatory CLI masking; █ marks masked values. | | `preview` | write-preview\|null | Requested method, path and body only, with no diff and unchecked by the gateway; null after execution. | | `notice` | string | Present instead of data when masking withholds the entire result. | ## tdx invites revoke Revoke an invitation. **Writes** Requires invites.create or users.manage for the target. See [People and role commands](/cli/reference#people-and-role-commands). ```bash # DELETE /control/v1/invites/:inviteId tdx invites revoke --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `invite` | masked-route-data | Gateway data after mandatory CLI masking; █ marks masked values. | | `preview` | write-preview\|null | Requested method, path and body only, with no diff and unchecked by the gateway; null after execution. | | `notice` | string | Present instead of data when masking withholds the entire result. | --- # tdx limits Read the calling API key's budgets and rate limits. **Reads** Read GET /v1/limits as the API key itself. It needs an explicit API key (tokedex_ik_, the family the gateway authenticates as inference) from exactly one of --key-file or --key-stdin; other token families are refused locally before any request. It never uses or sends the saved admin profile bearer or TOKEDEX_TOKEN, and never opens a saved profile. The host comes only from --host or TOKEDEX_HOST. The gateway serves this route only while user management is on (otherwise 404) and refuses non-inference principals (403). Amounts are decimal USD strings and appear only where the gateway discloses them. --dry-run still reads. ```bash # GET /v1/limits tdx limits [flags] ``` **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--key-file` | path | | Read the API key from this owner-only 0600 regular file; no symlinks. | | `--key-stdin` | boolean | `false` | Read the API key from redirected standard input (8194 bytes, 3 seconds). | **Constraints** - Exactly one of `--key-file`, `--key-stdin` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `keyId` | string | Public id of the calling key. | | `budgets` | key-budget[] | Scope, the public model id as model on a model budget, window, applies_via, resets_at, exhausted and disclosed limit_usd, spent_usd, remaining_usd strings. | | `rateLimits` | key-rate-limit[] | Scope, requests_per_minute, remaining and reset_ms. | Every command also takes the [global flags](/cli/reference#global-flags) and reads the [environment variables](/cli/reference#environment-variables) that the command reference lists once. --- # tdx models Models callers can request from this gateway. Models callers can request from this gateway: list them, toggle several at once, and manage who serves each one (providers), routers that pick between models, the aliases callers send, and custom models served from your own endpoint. Every command also takes the [global flags](/cli/reference#global-flags) and reads the [environment variables](/cli/reference#environment-variables) that the command reference lists once. ## Commands | Command | Description | Type | |---|---|---| | [tdx models list](/cli/reference/models#tdx-models-list) | List catalogue models. | Read | | [tdx models toggle](/cli/reference/models#tdx-models-toggle) | Enable, disable, list or unlist providers and routers together. | Write | | [tdx models providers](/cli/reference/models#tdx-models-providers) | Who serves a model on one client API. | Group | | [tdx models providers list](/cli/reference/models#tdx-models-providers-list) | List provider configurations. | Read | | [tdx models providers show](/cli/reference/models#tdx-models-providers-show) | Show the provider order of a provider configuration. | Read | | [tdx models providers enable](/cli/reference/models#tdx-models-providers-enable) | Enable a provider configuration. | Write | | [tdx models providers disable](/cli/reference/models#tdx-models-providers-disable) | Disable a provider configuration. | Write | | [tdx models providers edit](/cli/reference/models#tdx-models-providers-edit) | Edit enabled or listing state, or provider routing, of a provider configuration. | Write | | [tdx models providers edits](/cli/reference/models#tdx-models-providers-edits) | Manage stale provider configuration edits. | Group | | [tdx models providers edits remove](/cli/reference/models#tdx-models-providers-edits-remove) | Remove a saved provider configuration edit. | Write | | [tdx models routers](/cli/reference/models#tdx-models-routers) | Ids that pick one of several models per request. | Group | | [tdx models routers list](/cli/reference/models#tdx-models-routers-list) | List routers. | Read | | [tdx models routers set](/cli/reference/models#tdx-models-routers-set) | Create or replace an operator router. | Write | | [tdx models routers preview](/cli/reference/models#tdx-models-routers-preview) | Preview how an operator router would rank its members. | Read | | [tdx models routers remove](/cli/reference/models#tdx-models-routers-remove) | Remove an operator router. | Write | | [tdx models routers edit](/cli/reference/models#tdx-models-routers-edit) | Edit a reviewed router. | Write | | [tdx models routers edits](/cli/reference/models#tdx-models-routers-edits) | Manage stale reviewed router edits. | Group | | [tdx models routers edits remove](/cli/reference/models#tdx-models-routers-edits-remove) | Remove a saved reviewed router edit. | Write | | [tdx models routers strategies](/cli/reference/models#tdx-models-routers-strategies) | Ways a router can pick its model. | Group | | [tdx models routers strategies list](/cli/reference/models#tdx-models-routers-strategies-list) | List operator strategies. | Read | | [tdx models routers strategies explain](/cli/reference/models#tdx-models-routers-strategies-explain) | Explain an operator strategy. | Read | | [tdx models routers strategies set](/cli/reference/models#tdx-models-routers-strategies-set) | Create or replace an operator strategy. | Write | | [tdx models routers strategies remove](/cli/reference/models#tdx-models-routers-strategies-remove) | Remove an operator strategy. | Write | | [tdx models aliases](/cli/reference/models#tdx-models-aliases) | Model ids callers send, per client API. | Group | | [tdx models aliases list](/cli/reference/models#tdx-models-aliases-list) | List aliases. | Read | | [tdx models aliases set](/cli/reference/models#tdx-models-aliases-set) | Point an alias at a provider configuration or router. | Write | | [tdx models aliases remove](/cli/reference/models#tdx-models-aliases-remove) | Restore a reviewed default alias. | Write | | [tdx models aliases preview](/cli/reference/models#tdx-models-aliases-preview) | Preview how an alias change would reach provider configurations. | Read | | [tdx models custom](/cli/reference/models#tdx-models-custom) | Add models from a provider or your own server. | Group | | [tdx models custom providers](/cli/reference/models#tdx-models-custom-providers) | List the providers a model can be added from. | Read | | [tdx models custom pools](/cli/reference/models#tdx-models-custom-pools) | List configured pools for server models. | Read | | [tdx models custom list](/cli/reference/models#tdx-models-custom-list) | List custom model declarations. | Read | | [tdx models custom status](/cli/reference/models#tdx-models-custom-status) | Inspect runtime status of custom models. | Read | | [tdx models custom create](/cli/reference/models#tdx-models-custom-create) | Add a model from a provider, or from a file. | Write | | [tdx models custom edit](/cli/reference/models#tdx-models-custom-edit) | Replace one custom model declaration. | Write | | [tdx models custom visibility](/cli/reference/models#tdx-models-custom-visibility) | Show or hide a provider-hosted model in discovery. | Write | | [tdx models custom qualify](/cli/reference/models#tdx-models-custom-qualify) | Qualify a custom model with human approval. | Write | | [tdx models custom qualify cancel](/cli/reference/models#tdx-models-custom-qualify-cancel) | Cancel one exact accepted qualification run. | Write | | [tdx models custom remove](/cli/reference/models#tdx-models-custom-remove) | Remove a custom model declaration. | Write | ## tdx models list List catalogue models. **Reads** Read the public catalogue model list with client dialects and kinds. See [Catalogue reads](/cli/reference#catalogue-reads). ```bash # GET /control/v1/catalogue/models tdx models list [flags] ``` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `models` | masked-catalogue-model[] | Catalogue model id, client dialects and kind. | **Examples** List catalogue model ids: ```bash tdx models list --json=models ``` ## tdx models toggle Enable, disable, list or unlist providers and routers together. **Writes** Apply up to the gateway limit of toggle changes in one publication. Each change names its kind, its id, enabled and/or listed, and the expected current {enabled, listed}; kind group is a provider configuration (a catalogue Group) and kind modelGroup is a router. The gateway refuses stale expectations. The file must be a JSON object with a changes array. See [Catalogue changes](/cli/reference#catalogue-changes) and [Catalogue republishing](/cli/reference#catalogue-republishing). ```bash # PATCH /control/compiled/toggles tdx models toggle --body-file [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--body-file` | path | | Toggle changes file: `{"changes": [...]}`; regular file, or stdin with --body-file=-; UTF-8 JSON, at most 1 MiB. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `updated` | integer | Number of toggle changes applied. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | **Examples** Preview several toggles: ```bash tdx models toggle --body-file ./toggles.json --dry-run --json ``` ## tdx models providers Who serves a model on one client API. Who serves one model on one client API (a catalogue Group): turn it on or off, and list or unlist it. Ids are Group ids, called groupId in output. Provider credentials are managed separately with providers keys. ## tdx models providers list List provider configurations. **Reads** Read the compiled Group inventory: reviewed provider configurations, routers and unreviewed custom provider configurations. See [Catalogue reads](/cli/reference#catalogue-reads). ```bash # GET /control/v1/catalogue/groups tdx models providers list [flags] ``` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `providers` | masked-group[] | Reviewed provider configurations (catalogue Groups). | | `routers` | masked-model-group[] | Routers (ModelGroups) by client dialect. | | `unreviewed` | masked-group[] | Operator-declared custom provider configurations. | | `bindingsDigest` | string | Digest of the client dialect bindings. | **Examples** List provider configurations: ```bash tdx models providers list --json=providers ``` ## tdx models providers show Show the provider order of a provider configuration. **Reads** Read one compiled Group from the inventory and print the order it tries its providers in: each provider with whether it is ready here and its catalogue list price, the routing strategy, and who set the order (catalogue or operator). The catalogue's default order is the cheapest blended list price first, then the model's own (first-party) provider, then provider id A-Z; with an operator's order set, defaultOrder lists the default it replaced. A route serves one client API, so each of a model's API formats has its own order, including multi-provider custom models. Models providers list names the routes. A request's x-tokedex-provider-order header puts its providers first and wins over this order. See [Catalogue reads](/cli/reference#catalogue-reads). ```bash # GET /control/v1/catalogue/groups tdx models providers show --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `provider` | masked-provider-order | The groupId, publicModelId, clientDialectId, strategy, setBy, order [{providerId, providerName, ready, price}] and defaultOrder when an operator set the order. | **Examples** Show the order a provider configuration tries its providers in: ```bash tdx models providers show --id --json ``` ## tdx models providers enable Enable a provider configuration. **Writes** Send `{"enabled": true}` for one reviewed Group id. See [Catalogue changes](/cli/reference#catalogue-changes) and [Catalogue republishing](/cli/reference#catalogue-republishing). ```bash # PATCH /control/compiled/groups/:groupId tdx models providers enable --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `provider` | masked-group | The reviewed provider configuration (source Group) after the change. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | **Examples** Preview enabling a provider configuration: ```bash tdx models providers enable --id --dry-run --json ``` ## tdx models providers disable Disable a provider configuration. **Writes** Send `{"enabled": false}` for one reviewed Group id. See [Catalogue changes](/cli/reference#catalogue-changes) and [Catalogue republishing](/cli/reference#catalogue-republishing). ```bash # PATCH /control/compiled/groups/:groupId tdx models providers disable --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `provider` | masked-group | The reviewed provider configuration (source Group) after the change. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | **Examples** Preview disabling a provider configuration: ```bash tdx models providers disable --id --dry-run --json ``` ## tdx models providers edit Edit enabled or listing state, or provider routing, of a provider configuration. **Writes** Save a source edit with at least one of --enabled, --listed, --provider-order and --default-order. --provider-order sends requests to the first provider it names and moves to the next when one fails; providers it leaves out follow in the default order (cheapest, then first-party, then A-Z). --default-order removes that order. The order is set per API format: a Group serves one client API, so set it on each of a model's Groups you want ordered, and read it back with models providers show. Custom routes accept provider order, and models custom visibility controls their discovery setting. A route with one provider has no order to set, and the gateway refuses --provider-order for it. A request's x-tokedex-provider-order header puts its providers first and wins over this order. See [Catalogue changes](/cli/reference#catalogue-changes) and [Catalogue republishing](/cli/reference#catalogue-republishing). ```bash # PATCH /control/compiled/source-edits/:groupId tdx models providers edit --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--enabled` | one of `true`, `false` | | Enabled state. | | `--listed` | one of `true`, `false` | | Listing state. | | `--provider-order` | string | | Catalogue provider id to try next; repeat in order, first tried first. Repeatable. | | `--default-order` | boolean | `false` | Restore the default provider order. | **Constraints** - `--enabled` is required unless `--listed` or `--provider-order` or `--default-order` - At most one of `--provider-order`, `--default-order` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `view` | masked-addresses-view | Masked compiled aliases (addresses) view after the write. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | **Examples** Keep a provider configuration serving but unlisted: ```bash tdx models providers edit --id --listed false --json ``` Send requests to one provider first, then the others: ```bash tdx models providers edit --id --provider-order --json ``` Restore the default provider order: ```bash tdx models providers edit --id --default-order --json ``` ## tdx models providers edits Manage stale provider configuration edits. Remove saved provider configuration edits whose Group the catalogue no longer has. ## tdx models providers edits remove Remove a saved provider configuration edit. **Writes** Remove a saved source edit. The gateway removes an edit only when the catalogue no longer has its Group, and refuses one for an existing Group with a usage error; to change a live one, use models providers edit. See [Catalogue changes](/cli/reference#catalogue-changes) and [Catalogue republishing](/cli/reference#catalogue-republishing). ```bash # DELETE /control/compiled/source-edits/:groupId tdx models providers edits remove --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `view` | masked-addresses-view | Masked compiled aliases (addresses) view after the write. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | **Examples** Remove a stale provider configuration edit: ```bash tdx models providers edits remove --id --json ``` ## tdx models routers Ids that pick one of several models per request. A router is an id that picks one of several models for each request (called a ModelGroup in gateway output). Members are catalogue models; an operator router may also name declared custom models: one on your own server serves only on its own protocol, one from a provider on any client API. set creates or replaces an operator router; edit changes a reviewed one. ## tdx models routers list List routers. **Reads** There is no dedicated router read route; this reads the compiled aliases (addresses) view and prints only its routers (modelGroups in the gateway view). See [Catalogue reads](/cli/reference#catalogue-reads). ```bash # GET /control/compiled/addresses tdx models routers list [flags] ``` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `routers` | masked-model-group[] | Reviewed and operator routers (ModelGroups). | | `settings` | object | Saved operator router settings, including router and member provider selections. | **Examples** List reviewed and operator routers: ```bash tdx models routers list --json ``` ## tdx models routers set Create or replace an operator router. **Writes** Send the file's JSON object as the operator router (ModelGroup) definition; the gateway validates it. Each member is `{"sourceGroupIds": {"": ""}}` for a catalogue model or `{"customModel": ""}` for a declared custom model; keep at least one catalogue member. A custom member on your own server serves only on its custom model's protocol and only for keys that name that custom model; one from a provider serves on any client API, for any key whose model scope admits it, and a fact-ranked strategy leaves it out. Set providers on the router and/or each catalogue member to a list of provider ids for Selected providers; omit providers for All providers. A router with custom members takes no router providers. An empty list permits no provider. Router, member, key and workspace limits intersect. Use set again to edit these settings; list shows the saved settings. See [Catalogue changes](/cli/reference#catalogue-changes) and [Catalogue republishing](/cli/reference#catalogue-republishing). ```bash # PUT /control/compiled/model-groups/:modelGroupId tdx models routers set --id --body-file [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | | `--body-file` | path | | Router (ModelGroup) JSON object file; regular file, or stdin with --body-file=-; UTF-8 JSON, at most 1 MiB. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `view` | masked-addresses-view | Masked compiled aliases (addresses) view after the write. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | **Examples** Preview a router definition: ```bash tdx models routers set --id --body-file ./router.json --dry-run --json ``` ## tdx models routers preview Preview how an operator router would rank its members. **Reads** Ask the gateway to check a router definition as a set would and explain how its strategy orders the members, without saving or auditing it. This is a read, not a dry-run: it sends the request, including with --dry-run. The gateway derives it like a publication, which can take several seconds on a large catalogue, so the request deadline is 30 seconds; any failure, including a timeout or gateway 5xx, is reported as a failed read, never as an applied or possibly applied change. The file is validated before any profile or gateway access. See [Catalogue reads](/cli/reference#catalogue-reads). ```bash # POST /control/compiled/model-groups/preview tdx models routers preview --body-file [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--body-file` | path | | Router (ModelGroup) JSON object file; regular file, or stdin with --body-file=-; UTF-8 JSON, at most 1 MiB. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `members` | masked-member[] | Each catalogue member's model and ranking variants, in the order sent. | | `customMembers` | masked-member[] | Each custom model member: its position, the model id it ranks as, and whether it serves now with the reason when not. | | `explanation` | masked-explanation | Each member's position, or why the strategy leaves it out. | **Examples** Check a router before saving it: ```bash tdx models routers preview --body-file ./router.json --json ``` ## tdx models routers remove Remove an operator router. **Writes** Remove an operator router; the gateway refuses while an alias points at it. See [Catalogue changes](/cli/reference#catalogue-changes) and [Catalogue republishing](/cli/reference#catalogue-republishing). ```bash # DELETE /control/compiled/model-groups/:modelGroupId tdx models routers remove --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `view` | masked-addresses-view | Masked compiled aliases (addresses) view after the write. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | **Examples** Remove an operator router: ```bash tdx models routers remove --id --json ``` ## tdx models routers edit Edit a reviewed router. **Writes** Save an enabled or listing edit for a reviewed router, with at least one of --enabled and --listed. See [Catalogue changes](/cli/reference#catalogue-changes) and [Catalogue republishing](/cli/reference#catalogue-republishing). ```bash # PATCH /control/compiled/model-group-edits/:modelGroupId tdx models routers edit --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--enabled` | one of `true`, `false` | | Enabled state. | | `--listed` | one of `true`, `false` | | Listing state. | **Constraints** - `--enabled` is required unless `--listed` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `view` | masked-addresses-view | Masked compiled aliases (addresses) view after the write. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | **Examples** Disable a reviewed router: ```bash tdx models routers edit --id --enabled false --json ``` ## tdx models routers edits Manage stale reviewed router edits. Remove saved reviewed router edits whose ModelGroup the catalogue no longer has. ## tdx models routers edits remove Remove a saved reviewed router edit. **Writes** Remove a saved reviewed router edit. The gateway removes an edit only when the catalogue no longer has its ModelGroup, and refuses one for an existing ModelGroup with a usage error; to change a live one, use models routers edit. See [Catalogue changes](/cli/reference#catalogue-changes) and [Catalogue republishing](/cli/reference#catalogue-republishing). ```bash # DELETE /control/compiled/model-group-edits/:modelGroupId tdx models routers edits remove --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `view` | masked-addresses-view | Masked compiled aliases (addresses) view after the write. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | **Examples** Remove a stale router edit: ```bash tdx models routers edits remove --id --json ``` ## tdx models routers strategies Ways a router can pick its model. The ways a router can pick its model, shared by routers: list, explain, create, replace and remove operator strategies that order router members. ## tdx models routers strategies list List operator strategies. **Reads** Read the strategy language, its limits and saved operator definitions. See [Catalogue reads](/cli/reference#catalogue-reads). ```bash # GET /control/compiled/model-group-strategies tdx models routers strategies list [flags] ``` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `strategies` | masked-strategy-view | Masked strategy language, limits and definitions. | **Examples** List operator strategies: ```bash tdx models routers strategies list --json ``` ## tdx models routers strategies explain Explain an operator strategy. **Reads** Explain how a saved strategy orders the members of each router using it, or only --router. See [Catalogue reads](/cli/reference#catalogue-reads). ```bash # GET /control/compiled/model-group-strategies/:strategyId/explain tdx models routers strategies explain --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--router` | string | | Only explain this router (ModelGroup id). | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `explanations` | masked-explanation[] | Per router availability and member order. | **Examples** Explain one router: ```bash tdx models routers strategies explain --id --router --json ``` ## tdx models routers strategies set Create or replace an operator strategy. **Writes** Send the file's JSON object as the strategy definition; the gateway validates it. See [Catalogue changes](/cli/reference#catalogue-changes) and [Catalogue republishing](/cli/reference#catalogue-republishing). ```bash # PUT /control/compiled/model-group-strategies/:strategyId tdx models routers strategies set --id --body-file [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | | `--body-file` | path | | Strategy tree JSON object file; regular file, or stdin with --body-file=-; UTF-8 JSON, at most 1 MiB. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `strategies` | masked-strategy-view | Masked strategy language, limits and definitions. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | **Examples** Preview a strategy definition: ```bash tdx models routers strategies set --id --body-file ./strategy.json --dry-run --json ``` ## tdx models routers strategies remove Remove an operator strategy. **Writes** Remove a saved operator strategy. See [Catalogue changes](/cli/reference#catalogue-changes) and [Catalogue republishing](/cli/reference#catalogue-republishing). ```bash # DELETE /control/compiled/model-group-strategies/:strategyId tdx models routers strategies remove --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `strategies` | masked-strategy-view | Masked strategy language, limits and definitions. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | **Examples** Remove an operator strategy: ```bash tdx models routers strategies remove --id --json ``` ## tdx models aliases Model ids callers send, per client API. An alias is a model id callers send, and what it points at (a provider configuration or a router), per client API; it is not the id sent to the provider. The gateway calls these addresses. List, set, restore and preview them. ## tdx models aliases list List aliases. **Reads** Read the compiled addresses view: reviewed sources, saved intent, effective aliases, routers, problems and serving reach. See [Catalogue reads](/cli/reference#catalogue-reads). ```bash # GET /control/compiled/addresses tdx models aliases list [flags] ``` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `sources` | masked-source[] | Reviewed provider configurations (source Groups). | | `intent` | masked-intent | Saved operator intent. | | `aliases` | masked-address[] | Effective aliases (addresses) per client dialect. | | `routers` | masked-model-group[] | Reviewed and operator routers (ModelGroups). | | `problems` | string[] | Saved entries disabled by catalogue references. | | `serving` | masked-reach | How reviewed provider configurations are reached. | **Examples** List effective aliases and problems: ```bash tdx models aliases list --json=aliases,problems ``` ## tdx models aliases set Point an alias at a provider configuration or router. **Writes** Point an alias at exactly one of --group, --router or --release. --release clears the target and requires --replaces; a released alias cannot set --listed. See [Catalogue changes](/cli/reference#catalogue-changes) and [Catalogue republishing](/cli/reference#catalogue-republishing). ```bash # PATCH /control/compiled/addresses tdx models aliases set --client-dialect --address [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--client-dialect` | string | | Client API (client dialect) id. | | `--address` | string | | Alias: the model id callers send. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--group` | string | | Provider configuration (catalogue Group) id. | | `--router` | string | | Router (ModelGroup) id. | | `--release` | boolean | `false` | Release the alias. | | `--replaces` | string | | Reviewed holder id. | | `--listed` | one of `true`, `false` | | Listing state. | **Constraints** - Exactly one of `--group`, `--router`, `--release` - `--release` requires `--replaces` - At most one of `--release`, `--listed` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `view` | masked-addresses-view | Masked compiled aliases (addresses) view after the write. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | **Examples** Preview an alias: ```bash tdx models aliases set --client-dialect --address --group --dry-run --json ``` ## tdx models aliases remove Restore a reviewed default alias. **Writes** Remove the saved alias entry, restoring the reviewed default. See [Catalogue changes](/cli/reference#catalogue-changes) and [Catalogue republishing](/cli/reference#catalogue-republishing). ```bash # PATCH /control/compiled/addresses tdx models aliases remove --client-dialect --address [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--client-dialect` | string | | Client API (client dialect) id. | | `--address` | string | | Alias: the model id callers send. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `view` | masked-addresses-view | Masked compiled aliases (addresses) view after the write. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | **Examples** Restore a reviewed default: ```bash tdx models aliases remove --client-dialect --address --json ``` ## tdx models aliases preview Preview how an alias change would reach provider configurations. **Reads** Ask the gateway how reviewed provider configurations would be reached after one alias change, with exactly one of --group, --router, --release or --restore. The gateway derives the result without saving or auditing it. This is a read, not a dry-run: it sends the request, including with --dry-run. The gateway derives it like a publication, which can take several seconds on a large catalogue, so the request deadline is 30 seconds; any failure, including a timeout or gateway 5xx, is reported as a failed read, never as an applied or possibly applied change. --restore cannot set --replaces or --listed. Input is validated before any profile or gateway access. See [Catalogue reads](/cli/reference#catalogue-reads). ```bash # POST /control/compiled/addresses/preview tdx models aliases preview --client-dialect --address [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--client-dialect` | string | | Client API (client dialect) id. | | `--address` | string | | Alias: the model id callers send. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--group` | string | | Provider configuration (catalogue Group) id. | | `--router` | string | | Router (ModelGroup) id. | | `--release` | boolean | `false` | Release the alias. | | `--replaces` | string | | Reviewed holder id. | | `--listed` | one of `true`, `false` | | Listing state. | | `--restore` | boolean | `false` | Preview restoring the reviewed default. | **Constraints** - Exactly one of `--group`, `--router`, `--release`, `--restore` - `--release` requires `--replaces` - At most one of `--release`, `--listed` - At most one of `--restore`, `--listed` - At most one of `--restore`, `--replaces` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `memberOnly` | masked-reach[] | Provider configurations reached only as router members or fallbacks. | | `unaddressed` | string[] | Provider configurations no alias would reach. | **Examples** Preview reach before saving: ```bash tdx models aliases preview --client-dialect --address --router --json ``` ## tdx models custom Add models from a provider or your own server. Add, list, edit, qualify and remove custom models. One gateway model ID can contain a declaration for each of several providers. A declaration names the provider and its upstream model ID: it is served through the provider's own API and key, under the provider's id, as soon as it is saved, and its calls are recorded unpriced until it has a price. A model on your own server names its base URL and native protocol (Chat Completions, stateless Responses or conservative Messages); it is pending and not served until a qualification that a person approves, with spend consent, passes. upstreamModelId is sent unchanged. Aliases never point at a custom model, but an operator router may list one: on its own protocol for a model on your own server, on any client API for a model from a provider. Declarations name where the gateway reads a credential, never its value. ## tdx models custom providers List the providers a model can be added from. **Reads** Read every catalogue provider with the APIs a model added from it can use (protocols, empty when it can use none) and any reason the reviewed binding or credentials are unavailable. Requires catalogue.read and credentials.read. No credential names or values are returned. Without --workspace-id, workspace-dependent eligibility is provisional. No provider calls. ```bash # GET /control/compiled/custom-model-providers tdx models custom providers [flags] ``` **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--workspace-id` | string | | Optional final workspace scope for provider key eligibility. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `providers` | provider-choice[] | ProviderId, label, protocols, workspaceDependent and optional unavailableReason. | **Examples** List the providers a model can be added from: ```bash tdx models custom providers --json ``` ## tdx models custom pools List configured pools for server models. **Reads** List dedicated server pools configured on the gateway. Each choice shows its ID, origin, native protocol and availability. The full base URL and protocol must match the pool configuration when you select it in a model declaration. Requires catalogue.read and credentials.read. No provider calls. ```bash # GET /control/compiled/custom-model-pools tdx models custom pools [flags] ``` **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--workspace-id` | string | | Optional workspace for pool eligibility. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `pools` | custom-model-pool[] | Id, origin-only baseUrl, protocol, available and optional unavailableReason. | **Examples** List configured server pools: ```bash tdx models custom pools --json ``` ## tdx models custom list List custom model declarations. **Reads** Read operator custom model declarations; requires catalogue.read and credentials.read. Valid entries show publicModelId, origin-only baseUrl (no private path), upstreamModelId, protocol, optional messages and price, listed and upstreamAuth (environment, custody, provider, pool or none). A dedicated pool also shows its ID. A model from a provider also shows provider and optional inputs; a model on your own server shows its server-owned qualification. Credential names are not shown. Qualification status is pending, testing, failed or enabled; it is not the runtime serving status. Isolated malformed entries instead show publicModelId, entryIndex, entryRevision and problem {code,message}, without declaration fields. See [Catalogue reads](/cli/reference#catalogue-reads). ```bash # GET /control/compiled/custom-models tdx models custom list [flags] ``` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `customModels` | masked-custom-model-or-invalid-entry[] | Provider, protocol, revision, optional messages, price and qualification for each declaration, or the invalid declaration’s entry index, entry revision and problem. | **Examples** List custom model declarations: ```bash tdx models custom list --json ``` ## tdx models custom status Inspect runtime status of custom models. **Reads** Read each custom model's runtime status: serving or disabled, with an optional problem {code,message}. Pending, stale or invalid declarations are disabled; this is not qualification evidence or an activation command. See [Catalogue reads](/cli/reference#catalogue-reads). ```bash # GET /control/v1/catalogue/custom-models tdx models custom status [flags] ``` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `customModels` | masked-custom-model-status[] | PublicModelId, the provider if hosted, status (serving or disabled) and optional problem {code,message}. | **Examples** Inspect custom model status: ```bash tdx models custom status --json ``` ## tdx models custom create Add a model from a provider, or from a file. **Writes** With --provider, add a model a catalogue provider serves that the catalogue does not list: --provider-model is the provider's id for it and --id the id clients send. It is served through the provider's API and key, under the provider's id, as soon as it is saved; no test is needed. Create another provider declaration with its own price under the same gateway model ID to add a fallback. Client APIs use the provider's reviewed projections. The serving provider reports approved translation losses, and strict requests require a lossless route. --api picks the provider API where it has several. A call to a Messages provider needs an output limit on the request or a reviewed or configured limit. Set max_tokens on Messages, max_completion_tokens (or max_tokens) on Chat Completions, or max_output_tokens on Responses. Use --max-output-tokens to configure a default. Before saving, it reads models custom providers and stops, saying what to change, on an unknown or unavailable provider, a missing or unserved --api, or a misplaced --max-output-tokens. Give each hosted declaration an explicit price with --free or both --price-input and --price-output. With rates, you can add --price-cached-input, --price-cache-write and --price-cache-write-long. A model the catalogue already serves on that provider is refused, naming the catalogue model. With --body-file, the file is one declaration object: either the same model from a provider (`{"publicModelId", "provider", "upstreamModelId", "price"}` with optional protocol, messages `{"maxOutputTokens"}`, inputs ["image","file"] and listed), or a model on your own server: publicModelId, baseUrl, upstreamModelId and protocol (openai.chat-completions, openai.responses or anthropic.messages). A Messages server you run also requires messages `{"apiVersion": "2023-06-01", "maxOutputTokens": 16384}`. Set price to `{"input": "1", "output": "2"}` or `{"free": true}`. Input, output and optional cachedInput, cacheWrite and cacheWriteLong are nonnegative decimal strings in USD per million tokens with up to six decimal places. Choose explicit free if both input and output rates are zero. A new model on your own server also needs a price. A cache rate left out is charged at the input rate, an hour-long write at the cache write rate. The first declaration defaults to listed, and adding a provider inherits the model's listing if listed is omitted. Use models custom visibility to change it. Optional credential is one of `{"environment": NAME}`, `{"custody": NAME}`, `{"pool": ID}`, or `{"provider": ID}`. Use models custom pools for dedicated pool IDs. A provider credential uses the provider's key or pool at its exact reviewed API address. baseUrl must be http(s) without userinfo, query or fragment; other URL, credential and rate rules remain the gateway's. A model on your own server is pending, not served, until qualification passes; never submit qualification: it is server-owned. Replies show origin-only baseUrl, protocol, optional provider, inputs, messages and price, listed, upstreamAuth and qualification; dry-run stays offline and shows the requested declaration without server evidence. See [Catalogue changes](/cli/reference#catalogue-changes) and [Catalogue republishing](/cli/reference#catalogue-republishing). Example declaration: `{"publicModelId": "synthetic/endpoint", "baseUrl": "https://synthetic.invalid", "upstreamModelId": "synthetic-upstream", "protocol": "openai.chat-completions", "price": {"input": "1", "output": "2"}}`. ```bash # POST /control/compiled/custom-models tdx models custom create [flags] ``` **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--provider` | string | | Catalogue provider id from models custom providers: the model is served through its API and key. | | `--provider-model` | string | | The provider's own model id, sent to it unchanged. | | `--id` | string | | Gateway model id: the id clients send. | | `--api` | one of `chat-completions`, `responses`, `messages`, `gemini`, `bedrock-converse` | | The provider API to call when more than one is available. | | `--max-output-tokens` | integer | | Set a default output limit for calls to a Messages provider, from 1 to 1000000. | | `--inputs` | string | | Inputs beyond text and tools it accepts: image, file or image,file. | | `--price-input` | string | | Input USD per million tokens, a decimal string such as 0.60. | | `--price-output` | string | | Output USD per million tokens, a decimal string such as 2.50. | | `--price-cached-input` | string | | Cached input (a prompt-cache read) USD per million tokens; without it, charged at --price-input. | | `--price-cache-write` | string | | Prompt-cache write USD per million tokens; without it, charged at --price-input. | | `--price-cache-write-long` | string | | Hour-long prompt-cache write USD per million tokens; without it, charged at --price-cache-write. | | `--free` | boolean | `false` | Record its calls as free. | | `--unlisted` | boolean | `false` | Create an unlisted model. Added providers inherit visibility when omitted. | | `--body-file` | path | | Declaration file, in place of the flags above; regular file, or stdin with --body-file=-; UTF-8 JSON, at most 1 MiB. | **Constraints** - Exactly one of `--provider`, `--body-file` - `--provider-model` requires `--provider` - `--provider` requires `--provider-model` - `--id` requires `--provider` - `--provider` requires `--id` - `--api` requires `--provider` - `--max-output-tokens` requires `--provider` - `--inputs` requires `--provider` - `--unlisted` requires `--provider` - `--free` requires `--provider` - `--price-input` requires `--price-output` - `--price-output` requires `--price-input` - `--price-input` requires `--provider` - At most one of `--free`, `--price-input` - `--price-cached-input` requires `--price-input` - `--price-cache-write` requires `--price-input` - `--price-cache-write-long` requires `--price-input` - `--price-input` is required unless `--free` or `--body-file` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `customModel` | masked-custom-model | PublicModelId, optional provider, origin-only baseUrl, upstreamModelId, protocol, price, optional inputs and messages, listed, upstreamAuth and, on your own server, server-owned pending qualification. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | **Examples** Preview a model from a provider: ```bash tdx models custom create --provider --provider-model --id --price-input 1 --price-output 2 --dry-run --json ``` Preview a custom model declaration: ```bash tdx models custom create --body-file ./custom-model.json --dry-run --json ``` ## tdx models custom edit Replace one custom model declaration. **Writes** Edit one declaration selected by model ID and provider. Use models custom list to find the current revision. Include a price when editing a priced hosted model. An existing unpriced hosted model can keep its current pricing or receive a price. Use models custom visibility to change listing for a provider-hosted model. See [Catalogue changes](/cli/reference#catalogue-changes) and [Catalogue republishing](/cli/reference#catalogue-republishing). ```bash # PUT /control/compiled/custom-models/:publicModelId tdx models custom edit --id --revision --body-file [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | | `--revision` | string | | Current declaration revision from models custom list. | | `--body-file` | path | | Complete replacement declaration; regular file, or stdin with --body-file=-; UTF-8 JSON, at most 1 MiB. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--provider` | string | | Provider to edit when several serve the model. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `customModel` | masked-custom-model | The updated declaration. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | **Examples** Preview updating one provider: ```bash tdx models custom edit --id --provider --revision --body-file ./custom-model.json --dry-run --json ``` ## tdx models custom visibility Show or hide a provider-hosted model in discovery. **Writes** Update discovery visibility for all providers under one model ID. Authorized callers can invoke a hidden model by ID. See [Catalogue changes](/cli/reference#catalogue-changes) and [Catalogue republishing](/cli/reference#catalogue-republishing). ```bash # PATCH /control/compiled/custom-models/:publicModelId tdx models custom visibility --id --listed --expected-listed [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | | `--listed` | one of `true`, `false` | | New listing state. | | `--expected-listed` | one of `true`, `false` | | Current listing state from models custom list. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `customModel` | masked-custom-model-visibility | The model ID and its new listed state. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | **Examples** Hide a model from discovery: ```bash tdx models custom visibility --id --listed false --expected-listed true --json ``` ## tdx models custom qualify Qualify a custom model with human approval. **Writes** Requires explicit --consent. Opens dashboard device approval when no fresh human qualification session exists. Admin keys, API keys and master keys cannot substitute for browser human approval. Fresh approval lasts at most ten minutes and ends on browser session expiry/revocation. Fixed suite: at most four calls of 128 output tokens, on a temporary model-restricted API key with total budget equal to the explicit cap (0 \< capUsd \<= 0.10). Reports the exact accepted run, testing and then enabled or failed. Starts are never retried; inspect dashboard state after an ambiguous acknowledgement. Transport interruption is not cancellation. Dry-run stays offline. ```bash # POST /control/compiled/custom-models/:publicModelId/qualification tdx models custom qualify --cap-usd --workspace [flags] ``` **Arguments** | Argument | Type | Description | |---|---|---| | `publicModelId` | string | Required. Custom model public ID. | **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--cap-usd` | usd | | Explicit total budget: more than USD 0, at most USD 0.10. | | `--workspace` | string | | Workspace charged by the temporary restricted API key. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--provider` | string | | Provider to qualify when several serve the model. | | `--consent` | boolean | `false` | Approve at most four calls, each at most 128 output tokens, with total budget equal to cap-usd. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `publicModelId` | string | Requested model. | | `provider` | string | The qualified provider, when applicable. | | `runId` | string\|null | Exact accepted run ID. | | `status` | string | Testing, enabled or failed. | | `failure` | string\|null | Safe qualification failure category. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | ## tdx models custom qualify cancel Cancel one exact accepted qualification run. **Writes** Requires the human-approved qualification session and the exact accepted --run-id. Never cancels a guessed current run; transport abort is not cancellation. Dry-run sends nothing. ```bash # POST /control/compiled/custom-models/:publicModelId/qualification/cancel tdx models custom qualify cancel --run-id [flags] ``` **Arguments** | Argument | Type | Description | |---|---|---| | `publicModelId` | string | Required. Custom model public ID. | **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--run-id` | string | | Exact accepted qualification run ID. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--provider` | string | | Provider whose run to cancel. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `publicModelId` | string | Requested model. | | `provider` | string | The provider selected for cancellation, when given. | | `runId` | string | Exact cancellation target. | | `cancelled` | boolean | Gateway acknowledged cancellation. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | ## tdx models custom remove Remove a custom model declaration. **Writes** Remove one declaration by public model ID and provider if the model has several providers. See [Catalogue changes](/cli/reference#catalogue-changes) and [Catalogue republishing](/cli/reference#catalogue-republishing). ```bash # DELETE /control/compiled/custom-models/:publicModelId tdx models custom remove --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--provider` | string | | Provider to remove when several serve the model. | | `--revision` | string | | Require this current declaration revision. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `removed` | string | Removed public model id. | | `provider` | string | Provider selected for removal, when given. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | **Examples** Remove a custom model: ```bash tdx models custom remove --id --json ``` --- # tdx observability Read inference traces and calls, the store status and its switch. Read the gateway's inference observability store: traces (trajectories with their calls and timeline) and individual calls with their attribution. The attribution filters (--key-id, --user-id, --workspace-id, --request-id, and --sessions where offered) apply only with user management on; a gateway without it ignores parameters it does not know, so the reply is then unfiltered by them. status reads the store's state (install-wide status.read); set saves the observability switch for the next restart (install-wide settings.manage). Every command also takes the [global flags](/cli/reference#global-flags) and reads the [environment variables](/cli/reference#environment-variables) that the command reference lists once. ## Commands | Command | Description | Type | |---|---|---| | [tdx observability traces](/cli/reference/observability#tdx-observability-traces) | Read inference traces. | Group | | [tdx observability traces list](/cli/reference/observability#tdx-observability-traces-list) | List traces, newest first. | Read | | [tdx observability traces show](/cli/reference/observability#tdx-observability-traces-show) | Read one trace with its calls and timeline. | Read | | [tdx observability calls](/cli/reference/observability#tdx-observability-calls) | Read individual gateway calls. | Group | | [tdx observability calls list](/cli/reference/observability#tdx-observability-calls-list) | List calls, newest first. | Read | | [tdx observability status](/cli/reference/observability#tdx-observability-status) | Read embedded observability store status. | Read | | [tdx observability set](/cli/reference/observability#tdx-observability-set) | Save the observability switch for the next restart. | Write | ## tdx observability traces Read inference traces. Read inference traces from the gateway's observability store: list a page, or show one trace without its captured text. The attribution filters (--key-id, --user-id, --workspace-id, --request-id, and --sessions where offered) apply only with user management on; a gateway without it ignores parameters it does not know, so the reply is then unfiltered by them. ## tdx observability traces list List traces, newest first. **Reads** Read one gateway page of traces (trajectories) the gateway lets this credential see. No automatic paging: pass nextCursor back with the same filters. The attribution filters (--key-id, --user-id, --workspace-id, --request-id, and --sessions where offered) apply only with user management on; a gateway without it ignores parameters it does not know, so the reply is then unfiltered by them. A --key-id that is not a gateway key id (a ULID) is a secret request parameter: it prints as █, and so does any value that contains it or another &-separated part of the request path, such as model=\ after an earlier filter. See [Values too long to print](/cli/reference#values-too-long-to-print). A nextCursor longer than 2048 characters (the gateway puts the last row's id in it) prints as [withheld: too long] while hasMore keeps the gateway's value; --cursor refuses the marker before any request, so page past that row with narrower --since and --until filters. keyHash is withheld; with amounts hidden for this reader costUsd is null. See [Observability filters and output](/cli/reference#observability-filters-and-output). ```bash # GET /observability/v1/traces tdx observability traces list [flags] ``` **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--since` | datetime | | Only items starting at or after this instant. | | `--until` | datetime | | Only items starting at or before this instant. | | `--status` | string | | Status, such as ok or error. | | `--provider` | string | | Provider id, passed through as given. | | `--model` | string | | Model id, passed through as given. | | `--agent` | string | | Agent name. | | `--project` | string | | Project id. | | `--tag` | string | | Tag. | | `--search` | string | | Free-text search the gateway matches. | | `--key-id` | string | | Attribution: public API key id. | | `--user-id` | string | | Attribution: public user id. | | `--workspace-id` | string | | Attribution: public workspace id. | | `--request-id` | string | | Request id. | | `--sessions` | one of `grouped`, `sourced` | | Grouped or sourced sessions only. | | `--limit` | integer | | Page size; the gateway clamps it to 1..200 and defaults to 50. | | `--cursor` | string | | Opaque nextCursor from a previous observability traces list page with the same filters; pass it as --cursor=\. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `traces` | public-trace[] | Id, trace id, title, status, agent, project, endpoint, providers, key label, tags, times, counts, session source, client trajectory id, input, output, non-cached input, cached input, cache-creation input, reasoning output and total tokens, costUsd. | | `summary` | trace-summary | Trajectories, error trajectories, spans, unpriced calls (null when absent), input, output, non-cached input, cached input, cache-creation input, reasoning output and total tokens and costUsd over the whole filtered scope. | | `money` | 'raw'\|'hidden'\|null | How amounts read for this credential; null when the gateway does not say. | | `hasMore` | boolean | Whether a further page exists. | | `nextCursor` | string\|null | Gateway continuation cursor; null on the final page. | ## tdx observability traces show Read one trace with its calls and timeline. **Reads** Read one trace. Trace ids can be client-chosen, so the id is percent-encoded into the path. Captured text (span request and response, error messages and event data) is never printed: textWithheld says whether the reply carried any; it still feeds masking. keyHash is withheld. See [Values too long to print](/cli/reference#values-too-long-to-print) and [Observability filters and output](/cli/reference#observability-filters-and-output). ```bash # GET /observability/v1/traces/:id tdx observability traces show --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Trace id as the gateway reported it: 1-512 printable ASCII characters without whitespace; never a credential. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `trace` | public-trace-detail | The trace summary fields, captureText, calls (structured fields only) and events (id, request id, time, stage, provider, model). | | `textWithheld` | boolean | Whether the reply carried captured text the CLI did not print. | ## tdx observability calls Read individual gateway calls. Read individual calls (provider calls and gateway request outcomes) with attribution. Requires a gateway with user management on. ## tdx observability calls list List calls, newest first. **Reads** Read one gateway page of calls with their attribution and usage. The route exists only with user management on; without it the gateway answers 404 and this exits 5 NOT_FOUND. JSON only: the gateway's CSV export (format=csv) is not offered. The attribution filters (--key-id, --user-id, --workspace-id, --request-id, and --sessions where offered) apply only with user management on; a gateway without it ignores parameters it does not know, so the reply is then unfiltered by them. A --key-id that is not a gateway key id (a ULID) is a secret request parameter: it prints as █, and so does any value that contains it or another &-separated part of the request path, such as model=\ after an earlier filter. See [Values too long to print](/cli/reference#values-too-long-to-print). A nextCursor longer than 2048 characters (the gateway puts the last row's id in it) prints as [withheld: too long] while hasMore keeps the gateway's value; --cursor refuses the marker before any request, so page past that row with narrower --since and --until filters. Directory entries name the keys, people and workspaces the page refers to, as arrays of id, name and state. Gateway key ids (ULIDs) print in clear, in calls and in the directory, as do the directory's key names and states. If any directory key id is not a ULID, every key name and state there of 8 or more characters prints as █ wherever it appears; under an id that contains a secret-like word such as KEY, that entry's name and state of 8 or more characters print as █ wherever they appear. See [Observability filters and output](/cli/reference#observability-filters-and-output). ```bash # GET /observability/v1/calls tdx observability calls list [flags] ``` **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--kind` | one of `provider_call`, `gateway_request_outcome`, `all` | | Provider_call, gateway_request_outcome or all; omitted uses the gateway default (all). | | `--since` | datetime | | Only items starting at or after this instant. | | `--until` | datetime | | Only items starting at or before this instant. | | `--status` | string | | Status, such as ok or error. | | `--provider` | string | | Provider id, passed through as given. | | `--model` | string | | Model id, passed through as given. | | `--agent` | string | | Agent name. | | `--project` | string | | Project id. | | `--tag` | string | | Tag. | | `--search` | string | | Free-text search the gateway matches. | | `--key-id` | string | | Attribution: public API key id. | | `--user-id` | string | | Attribution: public user id. | | `--workspace-id` | string | | Attribution: public workspace id. | | `--request-id` | string | | Request id. | | `--limit` | integer | | Page size; the gateway clamps it to 1..200 and defaults to 50. | | `--cursor` | string | | Opaque nextCursor from a previous observability calls list page with the same filters; pass it as --cursor=\. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `calls` | public-call[] | Id, kind, status, structured error, trajectory id, times, endpoint, provider, model, finish reason, tags, key/user/workspace ids, principal kind, input, output, non-cached input, cached input, cache-creation input, reasoning output and total tokens, costUsd, usageReported, costReported. | | `summary` | call-summary | Calls, coverage, input, output, non-cached input, cached input, cache-creation input, reasoning output and total tokens, costUsd and refused (null when absent) over the whole filtered scope. | | `money` | 'raw'\|'hidden'\|null | How amounts read for this credential. | | `directory` | public-directory | Keys, users and workspaces: arrays of id, name and state. | | `hasMore` | boolean | Whether a further page exists. | | `nextCursor` | string\|null | Gateway continuation cursor; null on the final page. | ## tdx observability status Read embedded observability store status. **Reads** Requires install-wide status.read. Reads GET /observability/v1/status: the store state, whether the embedded store is live in this process (enabled), the resolved switch it will use at the next start (configEnabled; null when the gateway omits it for a live store), text capture, trace and span counts, retention and ingest health. Every printed value comes from one fail-closed masking pass over the request, the whole gateway reply (including fields the CLI drops) and the CLI's projection, before selection/jq; █ marks masked values. state is printed as the CLI's own validated literal. A reply that cannot be masked within the fixed limits fails with OUTPUT_MASK_LIMIT (exit 7) and no values; a malformed reply fails with INVALID_RESPONSE (exit 7). --dry-run still performs this read. ```bash # GET /observability/v1/status tdx observability status [flags] ``` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `state` | string | Store state: ok, degraded or disabled. | | `enabled` | boolean | Whether the embedded store is live in this gateway process. | | `configEnabled` | boolean\|null | While disabled: the resolved switch for the next start; null when a running store omits it. | | `captureText` | boolean | Whether raw text capture is on. | | `traces` | integer | Stored traces. | | `spans` | integer | Stored spans. | | `oldestStartedAt` | string\|null | Oldest stored trace start. | | `newestStartedAt` | string\|null | Newest stored trace start. | | `storageBytes` | integer\|null | Store size in bytes, when known. | | `retention` | store-retention | Maximum age, bytes and traces, and last prune time. | | `ingest` | store-ingest | Queue depth and capacity, dropped events, degraded flag and last error time. | **Examples** Read the masked public projection as versioned JSON: ```bash tdx observability status --json ``` Select declared output fields: ```bash tdx observability status --json=state,enabled,configEnabled ``` **See also:** [tdx observability set](/cli/reference/observability#tdx-observability-set), [tdx audit status](/cli/reference/audit#tdx-audit-status) ## tdx observability set Save the observability switch for the next restart. **Writes** Requires install-wide settings.manage. Sends PUT /control/observability with body exactly `{"enabled": }`. The gateway persists the saved switch and returns it. It applies at the gateway's next restart unless TOKEDEX_OBSERVABILITY (or its alias TOKEDEX_OBSERVABILITY_STORE) is set there, which overrides it. While the store is disabled, observability status shows the resolved next-start value as configEnabled; a running store does not report it. Dry-run reads no saved profile, sends no request and creates nothing; it requires no credential source, and TOKEDEX_TOKEN, when set, is used only to mask the preview. The gateway has not checked its preview. Before sending, the request is masked alone; if that hits the fixed limits the command fails with OUTPUT_MASK_LIMIT (exit 7) and nothing is sent. The printed value comes from one fail-closed masking pass over the request, the whole gateway reply and the projection; an accepted write whose reply is invalid or cannot be masked fails with CHANGE_APPLIED_RESPONSE_INVALID (exit 1) and no values. ```bash # PUT /control/observability tdx observability set --enabled [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--enabled` | one of `true`, `false` | | Save observability on (true) or off (false). | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `enabled` | boolean | The switch the gateway persisted. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | **Examples** Save observability on for the next restart: ```bash tdx observability set --enabled true --json ``` Preview turning it off without any read or request: ```bash tdx observability set --enabled false --dry-run --json ``` **See also:** [tdx observability status](/cli/reference/observability#tdx-observability-status) --- # tdx open Print or open the logged-in host dashboard. **Writes** Resolve the host with the same origin-bound bearer/profile rules as auth status; no remote default. Validate fresh GET /control/v1/me before printing or opening. Browser login is separate: no credential is placed in the URL or sent to the opener. Pages are fixed root-mounted static dashboard routes; default: index. --json and --no-browser only print. Linux without DISPLAY/WAYLAND_DISPLAY or a missing opener only prints. Otherwise use the system opener without a shell, forwarding only desktop environment variables, not credentials. --help does not resolve a connection. --dry-run resolves a URL without a request or browser launch. Classified non-read so jq preflight precedes any effects. ```bash # GET /control/v1/me tdx open [page] [flags] ``` **Arguments** | Argument | Type | Description | |---|---|---| | `page` | one of `index`, `api-keys`, `providers`, `users`, `usage`, `events`, `playground`, `account`, `workspaces` | Dashboard page. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--no-browser` | boolean | `false` | Only print the dashboard URL. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `url` | string | Canonical host dashboard URL without credentials. | | `opened` | boolean | Whether the system browser opener completed successfully. | Every command also takes the [global flags](/cli/reference#global-flags) and reads the [environment variables](/cli/reference#environment-variables) that the command reference lists once. --- # tdx pricing Inspect prices and manage price overrides. Read effective deployment prices and coverage, and manage operator price overrides. Every command also takes the [global flags](/cli/reference#global-flags) and reads the [environment variables](/cli/reference#environment-variables) that the command reference lists once. ## Commands | Command | Description | Type | |---|---|---| | [tdx pricing list](/cli/reference/pricing#tdx-pricing-list) | List deployment prices and overrides. | Read | | [tdx pricing overrides](/cli/reference/pricing#tdx-pricing-overrides) | Manage price overrides. | Group | | [tdx pricing overrides set](/cli/reference/pricing#tdx-pricing-overrides-set) | Set a price override for a provider model. | Write | | [tdx pricing overrides edit](/cli/reference/pricing#tdx-pricing-overrides-edit) | Replace a price override. | Write | | [tdx pricing overrides remove](/cli/reference/pricing#tdx-pricing-overrides-remove) | Remove a price override. | Write | | [tdx pricing unpriced](/cli/reference/pricing#tdx-pricing-unpriced) | Price calls made with no price. | Group | | [tdx pricing unpriced list](/cli/reference/pricing#tdx-pricing-unpriced-list) | List calls served with no price, by provider model. | Read | | [tdx pricing unpriced price](/cli/reference/pricing#tdx-pricing-unpriced-price) | Charge a provider model's calls with no price at the price covering it now. | Write | ## tdx pricing list List deployment prices and overrides. **Reads** Read effective deployment prices, coverage, this month's call counts, model reach and price overrides. See [Catalogue reads](/cli/reference#catalogue-reads). ```bash # GET /control/v1/pricing tdx pricing list [flags] ``` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `catalogueRevision` | string\|null | Catalogue price revision. | | `coverage` | masked-coverage | Priced and unpriced deployments. | | `month` | masked-month | This month's call counts. | | `deployments` | masked-price[] | Effective price per deployment. | | `models` | masked-reach[] | Deployments answering each model id. | | `overrides` | masked-override[] | Saved price overrides. | **Examples** Inspect price coverage and overrides: ```bash tdx pricing list --json=coverage,overrides ``` ## tdx pricing overrides Manage price overrides. Set, replace or remove a price override for one provider model, identified as provider:model. ## tdx pricing overrides set Set a price override for a provider model. **Writes** Send exactly one of a --price-file JSON object or --free, with an optional --note. With --apply-to-unpriced, the calls the provider model already served with no price are priced too, at this price, each in the day, week and month it was made; a call that had a price keeps it. See [Catalogue changes](/cli/reference#catalogue-changes). ```bash # POST /control/v1/pricing/overrides tdx pricing overrides set --provider --model [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--provider` | string | | Provider id from pricing list. | | `--model` | string | | Provider model id from pricing list. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--price-file` | path | | Price card JSON object file; regular file, or stdin with --price-file=-; at most 1 MiB. | | `--free` | boolean | `false` | Mark the model free instead of supplying a price. | | `--note` | string | | Non-secret note. | | `--apply-to-unpriced` | boolean | `false` | Also price the calls this provider model served with no price, at this price. | **Constraints** - Exactly one of `--price-file`, `--free` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `override` | masked-override | Saved price override. | | `repriced` | repriced\|null | With --apply-to-unpriced: calls priced, those priced from an estimate, calls still with no price, the cost added (null when hidden) and the workspaces charged. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | **Examples** Preview a price override: ```bash tdx pricing overrides set --provider --model --price-file ./price.json --dry-run --json ``` Set a price and charge it to the calls already made: ```bash tdx pricing overrides set --provider --model --price-file ./price.json --apply-to-unpriced --json ``` ## tdx pricing overrides edit Replace a price override. **Writes** Replace the price of an existing override with exactly one of --price-file or --free, with an optional --note. Omitting --note clears any saved note. See [Catalogue changes](/cli/reference#catalogue-changes). ```bash # PATCH /control/v1/pricing/overrides/:overrideId tdx pricing overrides edit --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Price override id (provider:model) from pricing list. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--price-file` | path | | Price card JSON object file; regular file, or stdin with --price-file=-; at most 1 MiB. | | `--free` | boolean | `false` | Mark the model free instead of supplying a price. | | `--note` | string | | Non-secret note. | | `--apply-to-unpriced` | boolean | `false` | Also price the calls this provider model served with no price, at this price. | **Constraints** - Exactly one of `--price-file`, `--free` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `override` | masked-override | Saved price override. | | `repriced` | repriced\|null | With --apply-to-unpriced: calls priced, those priced from an estimate, calls still with no price, the cost added (null when hidden) and the workspaces charged. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | **Examples** Mark an overridden model free: ```bash tdx pricing overrides edit --id --free --json ``` ## tdx pricing overrides remove Remove a price override. **Writes** Remove a price override, restoring the catalogue price. See [Catalogue changes](/cli/reference#catalogue-changes). ```bash # DELETE /control/v1/pricing/overrides/:overrideId tdx pricing overrides remove --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Price override id (provider:model) from pricing list. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `removed` | string | Removed price override id. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | **Examples** Remove a price override: ```bash tdx pricing overrides remove --id --json ``` ## tdx pricing unpriced Price calls made with no price. List the calls models served before they had a price, by provider model, and charge them once a price covers the model. ## tdx pricing unpriced list List calls served with no price, by provider model. **Reads** Read the calls the gateway recorded with no price, by provider and provider model ID: how many, their tokens, when they were made, the gateway model IDs that served them, and the price that covers them now, if any. Such calls are kept to be priced for retentionDays days. See [Catalogue reads](/cli/reference#catalogue-reads). ```bash # GET /control/v1/pricing/unpriced tdx pricing unpriced list [flags] ``` **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--since` | string | | Only calls made at or after this: an ISO time, or a number of days back such as 30d. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `retentionDays` | number | How long a call with no price is kept to be priced. | | `models` | masked-unpriced[] | Calls with no price per provider model: counts, tokens, first and last call, gateway model ids, the price covering them now, and uncoveredCalls, those no price covers yet. | **Examples** List the last 30 days of calls with no price: ```bash tdx pricing unpriced list --since 30d --json ``` ## tdx pricing unpriced price Charge a provider model's calls with no price at the price covering it now. **Writes** Charge the calls this provider model served with no price at the price that covers it now (its own, an override, or the catalogue's), each in the day, week and month it was made. A call is priced once; a call that had a price keeps it. With --preview the gateway says what that would charge and prices nothing. When no price covers the model yet the gateway refuses, and nothing is priced. See [Catalogue changes](/cli/reference#catalogue-changes). ```bash # POST /control/v1/pricing/unpriced/reprice tdx pricing unpriced price --provider --model [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--provider` | string | | Provider id from pricing unpriced list. | | `--model` | string | | Provider model id from pricing unpriced list. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--preview` | boolean | `false` | Say what pricing would charge, and price nothing. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `priced` | repriced | Whether it was a preview, calls priced, those priced from an estimate, calls still with no price, the cost added (null when hidden) and the workspaces charged. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | **Examples** See what pricing the calls would charge: ```bash tdx pricing unpriced price --provider --model --preview --json ``` --- # tdx profile Your own gateway account profile (not a local connection profile). Read your own gateway account profile and its linked identities with a bearer. This is your gateway account profile, not the local connection profile that the global --profile flag or TOKEDEX_PROFILE selects and auth login/logout manage; --profile only chooses which saved local credential is used for the read. Creating the first account, editing the profile and setting a local sign-in secret are session-only and refuse with SESSION_REQUIRED before any request or read; use the gateway dashboard. Every command also takes the [global flags](/cli/reference#global-flags) and reads the [environment variables](/cli/reference#environment-variables) that the command reference lists once. ## Commands | Command | Description | Type | |---|---|---| | [tdx profile show](/cli/reference/profile#tdx-profile-show) | Read your gateway account profile. | Read | | [tdx profile identities](/cli/reference/profile#tdx-profile-identities) | List single sign-on identities linked to your account. | Read | | [tdx profile create](/cli/reference/profile#tdx-profile-create) | Create the first gateway account (dashboard only). | Dashboard only | | [tdx profile edit](/cli/reference/profile#tdx-profile-edit) | Change your gateway account display name (dashboard only). | Dashboard only | | [tdx profile password](/cli/reference/profile#tdx-profile-password) | Set or change your local sign-in secret (dashboard only). | Dashboard only | ## tdx profile show Read your gateway account profile. **Reads** Reads GET /control/v1/profile for the credential in use; any authenticated principal may read its own. kind is master, management_key or user. master: accountsExist and breakGlass. management_key: id. user: id, the user view (as users show reads it), localSignInSet (the gateway's hasPassword: whether a local sign-in secret is set), localSignInAllowed (the gateway's mayHoldPassword), lastSsoSignInAt and stepUpUntil (null for a bearer, which has no sign-in session). Fields that do not apply to kind are null. This is your gateway account profile, not the local connection profile that the global --profile flag or TOKEDEX_PROFILE selects and auth login/logout manage; --profile only chooses which saved local credential is used for the read. Every printed value comes from one fail-closed masking pass over the request, the whole gateway reply (including fields the CLI drops) and the CLI's projection, before selection/jq; █ marks masked values. kind is printed as the CLI's own validated literal. A reply that cannot be masked within the fixed limits fails with OUTPUT_MASK_LIMIT (exit 7) and no values; a malformed reply fails with INVALID_RESPONSE (exit 7). --dry-run still performs this read. ```bash # GET /control/v1/profile tdx profile show [flags] ``` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `kind` | string | Master, management_key or user. | | `id` | string\|null | Admin key id or user id; null for master. | | `accountsExist` | boolean\|null | Master: whether any gateway account exists. | | `breakGlass` | boolean\|null | Master: whether this credential is break-glass. | | `user` | public-user\|null | User: id, names, email, status, origin, creator, manageability, role assignments, last sign-in and linked identities. | | `localSignInSet` | boolean\|null | User: whether a local sign-in secret is set. | | `localSignInAllowed` | boolean\|null | User: whether this account may hold a local sign-in secret. | | `lastSsoSignInAt` | string\|null | User: last single sign-on time. | | `stepUpUntil` | string\|null | User: end of the recent sign-in window; null without a session. | **Examples** Read the masked public projection as versioned JSON: ```bash tdx profile show --json ``` Select declared output fields: ```bash tdx profile show --json=kind,id ``` **See also:** [tdx profile identities](/cli/reference/profile#tdx-profile-identities) ## tdx profile identities List single sign-on identities linked to your account. **Reads** Reads GET /control/v1/profile/identities: the linked single sign-on identities of your own gateway account. Only a person has identities: a user principal, including a personal access token. The gateway refuses master keys and admin keys (FORBIDDEN, exit 4). This is your gateway account profile, not the local connection profile that the global --profile flag or TOKEDEX_PROFILE selects and auth login/logout manage; --profile only chooses which saved local credential is used for the read. Every printed value comes from one fail-closed masking pass over the request, the whole gateway reply (including fields the CLI drops) and the CLI's projection, before selection/jq; █ marks masked values. A reply that cannot be masked within the fixed limits fails with OUTPUT_MASK_LIMIT (exit 7) and no values; a malformed reply fails with INVALID_RESPONSE (exit 7). --dry-run still performs this read. ```bash # GET /control/v1/profile/identities tdx profile identities [flags] ``` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `identities` | linked-identity[] | Id, provider id and display name, issuer host, link time and whether the provider is authoritative. | **Examples** Read the masked public projection as versioned JSON: ```bash tdx profile identities --json ``` Select declared output fields: ```bash tdx profile identities --json=identities ``` **See also:** [tdx profile show](/cli/reference/profile#tdx-profile-show) ## tdx profile create Create the first gateway account (dashboard only). **Dashboard only.** The gateway serves this only to a signed-in dashboard session, so the CLI refuses it with `SESSION_REQUIRED`. Unavailable to this bearer-only CLI: POST /control/v1/profile is session-only: the gateway creates the first account only from the master key's own interactive dashboard session. Use the gateway dashboard. --dry-run also refuses: there is no reachable change to preview. No request is sent and no credential, profile or file is read. This is your gateway account profile, not the local connection profile that the global --profile flag or TOKEDEX_PROFILE selects and auth login/logout manage; --profile only chooses which saved local credential is used for the read. ```bash # POST /control/v1/profile tdx profile create [flags] ``` **See also:** [tdx profile show](/cli/reference/profile#tdx-profile-show), [tdx open](/cli/reference/open) ## tdx profile edit Change your gateway account display name (dashboard only). **Dashboard only.** The gateway serves this only to a signed-in dashboard session, so the CLI refuses it with `SESSION_REQUIRED`. Unavailable to this bearer-only CLI: PATCH /control/v1/profile is session-only: only a person's own interactive dashboard session may change their profile. Use the gateway dashboard. --dry-run also refuses: there is no reachable change to preview. No request is sent and no credential, profile or file is read. This is your gateway account profile, not the local connection profile that the global --profile flag or TOKEDEX_PROFILE selects and auth login/logout manage; --profile only chooses which saved local credential is used for the read. ```bash # PATCH /control/v1/profile tdx profile edit [flags] ``` **See also:** [tdx profile show](/cli/reference/profile#tdx-profile-show), [tdx open](/cli/reference/open) ## tdx profile password Set or change your local sign-in secret (dashboard only). **Dashboard only.** The gateway serves this only to a signed-in dashboard session, so the CLI refuses it with `SESSION_REQUIRED`. Unavailable to this bearer-only CLI: POST /control/v1/profile/password is session-only: only a person's own interactive dashboard session may set it, and secrets are never accepted as command input. Use the gateway dashboard. --dry-run also refuses: there is no reachable change to preview. No request is sent and no credential, profile or file is read. This is your gateway account profile, not the local connection profile that the global --profile flag or TOKEDEX_PROFILE selects and auth login/logout manage; --profile only chooses which saved local credential is used for the read. ```bash # POST /control/v1/profile/password tdx profile password [flags] ``` **See also:** [tdx profile show](/cli/reference/profile#tdx-profile-show), [tdx open](/cli/reference/open) --- # tdx providers Manage provider credentials. Manage the credentials the gateway uses to call providers. Every command also takes the [global flags](/cli/reference#global-flags) and reads the [environment variables](/cli/reference#environment-variables) that the command reference lists once. ## Commands | Command | Description | Type | |---|---|---| | [tdx providers keys](/cli/reference/providers#tdx-providers-keys) | Manage provider credential bindings. | Group | | [tdx providers keys list](/cli/reference/providers#tdx-providers-keys-list) | List provider credential binding names. | Read | | [tdx providers keys set](/cli/reference/providers#tdx-providers-keys-set) | Set a provider credential from a file or stdin. | Write | | [tdx providers keys remove](/cli/reference/providers#tdx-providers-keys-remove) | Remove a provider credential binding. | Write | ## tdx providers keys Manage provider credential bindings. List, set and remove the gateway's provider bindings by name. Provider credentials stay hidden. ## tdx providers keys list List provider credential binding names. **Reads** Read binding names, sources and public provider settings. Lists every value the compiled catalogue binds, as the init wizard asks for them: each provider's key, a companion its signing profile requires (an AWS access key id), a Bedrock API key it accepts instead, and each setting, set or not; each can be set by name with providers keys set. Credential values stay hidden. See [Masked read output](/cli/reference#masked-read-output). ```bash # GET /control/keys tdx providers keys list [flags] ``` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `bindings` | public-binding[] | Binding names, source kinds, what the catalogue binds each as (key, companion, bearer-token or slot) and optional public setting with label and value. | ## tdx providers keys set Set a provider credential from a file or stdin. **Writes** Read the credential from a protected owner-only file, bounded redirected stdin, or an explicitly named environment variable. Each credential is limited to 8192 UTF-8 bytes. A credential holds no whitespace unless it is one JSON object, such as a service-account key, which may hold whitespace inside but none around it. When using --setting or --field-env, the gateway validates the catalogue configuration and saves all supplied fields together. Only public settings can be supplied literally. Dry-run reads no credential inputs or profiles, sends no request and creates nothing; its requested preview is not authoritative. See [Checked request values](/cli/reference#checked-request-values) and [Masked write output](/cli/reference#masked-write-output). ```bash # PUT /control/keys/:name tdx providers keys set --name [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--name` | string | | Credential binding environment-variable name. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--value-file` | path | | Read a credential only from this file. | | `--value-stdin` | boolean | `false` | Read a credential from standard input. | | `--value-env` | string | | Read a credential from this explicitly named environment variable; never a literal value. | | `--setting` | string | | Set a public provider setting as BINDING=VALUE. Repeat for multiple settings. Repeatable. | | `--field-env` | string | | Read a companion credential as BINDING=VARIABLE from the named environment variable. Repeat for multiple companions. Repeatable. | **Constraints** - Exactly one of `--value-file`, `--value-stdin`, `--value-env` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `binding` | binding-outcome | Public binding name and set status only. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | **Examples** Save a Bedrock API key and its region together: ```bash tdx providers keys set --name AWS_BEDROCK_API_KEY --value-env BEDROCK_KEY --setting AWS_BEDROCK_REGION=us-west-2 ``` ## tdx providers keys remove Remove a provider credential binding. **Writes** Remove a stored binding by name. Ambient gateway environment credentials may still resolve; removal does not revoke a provider credential. Dry-run reads no secret files or profiles, makes no request and creates nothing; the gateway has not checked the preview. See [Checked request values](/cli/reference#checked-request-values) and [Masked write output](/cli/reference#masked-write-output). ```bash # DELETE /control/keys/:name tdx providers keys remove --name [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--name` | string | | Credential binding environment-variable name. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `removed` | string | Removed binding name, not a credential. | | `preview` | write-preview\|null | Requested change, unchecked by the gateway; null after execution. | --- # tdx schema Print the command tree. **Runs locally** Print the serializable command schema, including inherited global flags, help fields and the fixed exit-code registry. ```bash tdx schema [flags] ``` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `schema` | command-schema | Complete serializable command contract. | Every command also takes the [global flags](/cli/reference#global-flags) and reads the [environment variables](/cli/reference#environment-variables) that the command reference lists once. --- # tdx sessions Inspect sessions; interactive revocation is unavailable. List a named person's sessions with --user-id and install-wide users.read. Own-session listing and every revocation route require an interactive dashboard session and are unavailable in this bearer-only CLI; use the dashboard. Unavailable commands refuse before requests or profile reads; write dry-runs only preview the selected route. Every command also takes the [global flags](/cli/reference#global-flags) and reads the [environment variables](/cli/reference#environment-variables) that the command reference lists once. ## Commands | Command | Description | Type | |---|---|---| | [tdx sessions list](/cli/reference/sessions#tdx-sessions-list) | List a person's sessions, or explain own-session unavailability. | Read | | [tdx sessions revoke](/cli/reference/sessions#tdx-sessions-revoke) | Unavailable: session revocation requires an interactive session. | Not available yet | ## tdx sessions list List a person's sessions, or explain own-session unavailability. **Reads** With --user-id, GET /users/:userId/sessions is bearer-reachable with install-wide users.read. Without it, GET /sessions is session-only and unavailable; no request, authentication or profile read is attempted. Reads with --dry-run still perform the same authorized GET. See [People and role commands](/cli/reference#people-and-role-commands). ```bash # GET /control/v1/users/:userId/sessions tdx sessions list [flags] ``` **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--user-id` | string | | Person id; requires install-wide users.read. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `sessions` | masked-route-data | Gateway data after mandatory CLI masking; █ marks masked values. | | `notice` | string | Present instead of data when masking withholds the entire result. | ## tdx sessions revoke Unavailable: session revocation requires an interactive session. **Not available yet.** Running it exits 7 with `NOT_IMPLEMENTED`. All session revocation routes are session-only; another person's sessions also require install users.manage and step-up. This bearer-only CLI refuses without authentication, requests or profile reads. Use the dashboard. Dry-run shows the selected DELETE route only, without dispatch. See [People and role commands](/cli/reference#people-and-role-commands). ```bash # DELETE /control/v1/sessions # DELETE /control/v1/sessions/:sessionId # DELETE /control/v1/users/:userId/sessions # DELETE /control/v1/users/:userId/sessions/:sessionId tdx sessions revoke [flags] ``` **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--user-id` | string | | Person whose sessions would be revoked; omitted means your own. | | `--id` | string | | Public session id; never a credential. | | `--all` | boolean | `false` | All sessions of the person, or all your OTHER sessions when no user-id. | **Constraints** - Exactly one of `--id`, `--all` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `preview` | write-preview\|null | Requested method, path and body only, with no diff and unchecked by the gateway; null after execution. | | `notice` | string | Present instead of data when masking withholds the entire result. | --- # tdx spend Read spend counters and settlements. Read spend counters, series and settlements by exactly one selector. Read-only. Every command also takes the [global flags](/cli/reference#global-flags) and reads the [environment variables](/cli/reference#environment-variables) that the command reference lists once. ## Commands | Command | Description | Type | |---|---|---| | [tdx spend subject](/cli/reference/spend#tdx-spend-subject) | Read a scope's budgets, rate limits and spend. | Read | | [tdx spend series](/cli/reference/spend#tdx-spend-series) | Read a scope's spend per window. | Read | | [tdx spend settlements](/cli/reference/spend#tdx-spend-settlements) | Read recent settlements. | Read | ## tdx spend subject Read a scope's budgets, rate limits and spend. **Reads** Read the budgets binding one key, user, workspace or the org, the constraining one, rate limits, spend per window and ledger state. Requests are not subjects. Budgets set to --on-limit alert never bind, so budgets leaves them out; when any target exactly this subject, alertOnlyBudgets counts them and names the budgets list command that shows them, from one more read (GET /control/v1/budgets, budgets.read). Only budgets whose target is this key, user, workspace or the org count: not budgets on the rest of a key's chain, nor a user's budgets within a workspace. alertOnlyBudgets is null both when there are none and when that read is refused or fails; a null never means the subject read failed. Requires spend.read on the selected scope; the gateway refuses scopes outside the reader's reach (403) and shows amounts through its money view (null when hidden). Exactly one selector is enforced locally before any request. Uses auth status host-bound bearer rules; reads are read-only and --dry-run still reads. ```bash # GET /control/v1/spend/subject # GET /control/v1/budgets tdx spend subject [flags] ``` **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--key-id` | string | | Select one API key scope by public key id. | | `--user-id` | string | | Select one person scope by user id. | | `--workspace-id` | string | | Select one workspace scope by id. | | `--scope-kind` | one of `key`, `user`, `workspace`, `org` | | Select a scope by kind; key, user and workspace need --scope-id; org takes none. | | `--scope-id` | string | | Scope id for --scope-kind key, user or workspace. | **Constraints** - Exactly one of `--key-id`, `--user-id`, `--workspace-id`, `--scope-kind` - `--scope-id` requires `--scope-kind` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `subject` | spend-subject | Selected subject ids. | | `effective` | effective-budget\|null | Tightest visible budget. | | `budgets` | subject-budget[] | Visible binding budgets with Money limit, spent and remaining. | | `rateLimits` | rate-limit[] | Key rate limits with per-minute rate, burst and enforcement scope. | | `spend` | window-money | Money spent per window: day, week, month and total. | | `ledger` | ledger-state | Spend ledger state. | | `alertOnlyBudgets` | alert-only-budgets\|null | Count of alert-only budgets targeting exactly this subject (not its key chain or a workspace member scope) and the budgets list command that shows them; null when there are none, and also when they could not be read. | ## tdx spend series Read a scope's spend per window. **Reads** Read one point per window between --from and --to; the gateway refuses more than 400 points. Requests have no series. Requires spend.read on the selected scope; the gateway refuses scopes outside the reader's reach (403) and shows amounts through its money view (null when hidden). Exactly one selector is enforced locally before any request. Uses auth status host-bound bearer rules; reads are read-only and --dry-run still reads. ```bash # GET /control/v1/spend/series tdx spend series [flags] ``` **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--key-id` | string | | Select one API key scope by public key id. | | `--user-id` | string | | Select one person scope by user id. | | `--workspace-id` | string | | Select one workspace scope by id. | | `--scope-kind` | one of `key`, `user`, `workspace`, `org` | | Select a scope by kind; key, user and workspace need --scope-id; org takes none. | | `--scope-id` | string | | Scope id for --scope-kind key, user or workspace. | | `--window` | one of `day`, `week`, `month` | | Window size; the gateway default is day. | | `--from` | datetime | | Series start; the gateway default is 30 days before --to. | | `--to` | datetime | | Series end; the gateway default is now. | **Constraints** - Exactly one of `--key-id`, `--user-id`, `--workspace-id`, `--scope-kind` - `--scope-id` requires `--scope-kind` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `scope` | spend-scope | Selected scope. | | `window` | string | Window size. | | `points` | spend-point[] | Window start, spent Money, call and token counts. | ## tdx spend settlements Read recent settlements. **Reads** Read recent settlements of one scope or one request; a request id needs an install-wide reader. Requires spend.read on the selected scope; the gateway refuses scopes outside the reader's reach (403) and shows amounts through its money view (null when hidden). Exactly one selector is enforced locally before any request. Uses auth status host-bound bearer rules; reads are read-only and --dry-run still reads. ```bash # GET /control/v1/spend/settlements tdx spend settlements [flags] ``` **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--key-id` | string | | Select one API key scope by public key id. | | `--user-id` | string | | Select one person scope by user id. | | `--workspace-id` | string | | Select one workspace scope by id. | | `--scope-kind` | one of `key`, `user`, `workspace`, `org` | | Select a scope by kind; key, user and workspace need --scope-id; org takes none. | | `--scope-id` | string | | Scope id for --scope-kind key, user or workspace. | | `--request-id` | string | | Select one request's settlements; install-wide readers only. | | `--limit` | integer | | Positive integer; the gateway clamps it to 1-200 (default 50) and reports no truncation. | | `--since` | datetime | | Only settlements since this time. | **Constraints** - Exactly one of `--key-id`, `--user-id`, `--workspace-id`, `--scope-kind`, `--request-id` - `--scope-id` requires `--scope-kind` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `settlements` | settlement[] | Id, kind, request id, times, cost Money (null when hidden), pricing, provider, model, price source and usage. | --- # tdx sso-providers Inspect SSO (OIDC sign-in) providers. SSO providers are the OIDC identity providers people sign in through, configured in the file TOKEDEX_OIDC_PROVIDERS_FILE names; they are unrelated to the provider credentials that providers keys manages. list and check work with a bearer holding install-wide identity.read. test-result is dashboard-only: results belong to the dashboard session that ran the SSO test. SSO providers are configured in the SSO providers file (TOKEDEX_OIDC_PROVIDERS_FILE), not through this CLI. Every command also takes the [global flags](/cli/reference#global-flags) and reads the [environment variables](/cli/reference#environment-variables) that the command reference lists once. ## Commands | Command | Description | Type | |---|---|---| | [tdx sso-providers list](/cli/reference/sso-providers#tdx-sso-providers-list) | List SSO providers and their discovery status. | Read | | [tdx sso-providers check](/cli/reference/sso-providers#tdx-sso-providers-check) | Make the gateway rediscover an SSO provider now. | Write | | [tdx sso-providers test-result](/cli/reference/sso-providers#tdx-sso-providers-test-result) | Read an SSO test result (dashboard only). | Dashboard only | ## tdx sso-providers list List SSO providers and their discovery status. **Reads** Requires install-wide identity.read. Read every SSO provider the SSO providers file (TOKEDEX_OIDC_PROVIDERS_FILE) configures, with its discovery status. The client secret is never sent. --dry-run still performs this read. SSO providers are the OIDC identity providers people sign in through, configured in the file TOKEDEX_OIDC_PROVIDERS_FILE names; they are unrelated to the provider credentials that providers keys manages. discovery.reason is the gateway's free error text from its last identity-provider fetch, or why discovery is disabled: untrusted, and masked like any string; a reason that is empty, longer than 4096 UTF-16 code units, contains C0/DEL/C1 controls (U+0000–001F, U+007F–009F), bidi marks (U+061C, U+200E, U+200F), embeddings/overrides (U+202A–202E), isolates (U+2066–2069) or echoes the bearer prints as █ without refusing the reply in human and JSON output. Other provider text with those controls or bidi characters is invalid: list refuses it with INVALID_RESPONSE; check reports CHANGE_APPLIED_RESPONSE_INVALID after the gateway accepted the write. Printable neighbors and ordinary multilingual text remain valid. Public configuration names such as TOKEDEX_PUBLIC_URL remain visible; registered credential prefixes still trigger masking. See [Masked read output](/cli/reference#masked-read-output), [Sign-in settings output](/cli/reference#sign-in-settings-output) and [Checked request values](/cli/reference#checked-request-values). ```bash # GET /control/v1/sso-providers tdx sso-providers list [flags] ``` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `ssoProviders` | public-sso-provider[] | Each SSO provider's id, displayName, source, issuerHost, redirectUri, enabled, jit, authoritative, allowedEmailDomains, sync, trustedClaims and discovery (state, with checkedAt, retryAt and reason where the gateway sends them); never a client secret. | ## tdx sso-providers check Make the gateway rediscover an SSO provider now. **Writes** Requires install-wide identity.read. The gateway fetches this SSO provider's OIDC discovery document now, ignoring its retry backoff: an outbound request from the gateway to the identity provider, so this is classified as a write and jq filters are preflighted before dispatch. A completed failing discovery is reported in discovery, not as an error; an unknown id is not found. The gateway waits up to 5 seconds for the identity provider. This command allows a bounded 6-second whole request, including reading the reply, to leave time for that fetch and response overhead; ordinary reads retain their 3-second limit. If the deadline expires before response headers are received, check fails with REQUEST_TIMEOUT (exit 7, outcome unknown): the gateway may still record the result. If success headers were received but the reply body stalls past the deadline, check fails with CHANGE_APPLIED_RESPONSE_INVALID (exit 1): the gateway accepted the change, but its reply could not be read safely. In either case, inspect it afterwards with sso-providers list before repeating the check. No automatic retry is made. Dry-run reads no profile or credential, sends no request and creates no files; the gateway has not checked its preview. SSO providers are the OIDC identity providers people sign in through, configured in the file TOKEDEX_OIDC_PROVIDERS_FILE names; they are unrelated to the provider credentials that providers keys manages. discovery.reason is the gateway's free error text from its last identity-provider fetch, or why discovery is disabled: untrusted, and masked like any string; a reason that is empty, longer than 4096 UTF-16 code units, contains C0/DEL/C1 controls (U+0000–001F, U+007F–009F), bidi marks (U+061C, U+200E, U+200F), embeddings/overrides (U+202A–202E), isolates (U+2066–2069) or echoes the bearer prints as █ without refusing the reply in human and JSON output. Other provider text with those controls or bidi characters is invalid: list refuses it with INVALID_RESPONSE; check reports CHANGE_APPLIED_RESPONSE_INVALID after the gateway accepted the write. Printable neighbors and ordinary multilingual text remain valid. Public configuration names such as TOKEDEX_PUBLIC_URL remain visible; registered credential prefixes still trigger masking. See [Checked request values](/cli/reference#checked-request-values), [Masked write output](/cli/reference#masked-write-output) and [Sign-in settings output](/cli/reference#sign-in-settings-output). ```bash # POST /control/v1/sso-providers/:providerId/check tdx sso-providers check --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | SSO provider id from sso-providers list; never a credential. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `ssoProvider` | public-sso-provider | The checked SSO provider's id, displayName, source, issuerHost, redirectUri, enabled, jit, authoritative, allowedEmailDomains, sync, trustedClaims and discovery (state, with checkedAt, retryAt and reason where the gateway sends them); never a client secret. | | `preview` | write-preview\|null | Requested check, unchecked by the gateway; null after execution. | ## tdx sso-providers test-result Read an SSO test result (dashboard only). **Dashboard only.** The gateway serves this only to a signed-in dashboard session, so the CLI refuses it with `SESSION_REQUIRED`. Unavailable to this bearer-only CLI: GET /control/v1/sso-providers/test-results/:resultId is session-bound: a test result belongs to the interactive dashboard session that ran the SSO test. The route admits bearers with install-wide identity.read, but the gateway answers not found to every other caller, so a bearer can never read a result; this command is session-only. Use the gateway dashboard. --dry-run also refuses: there is no reachable change to preview. No request is sent and no credential, profile or file is read. ```bash # GET /control/v1/sso-providers/test-results/:resultId tdx sso-providers test-result --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | --- # tdx usage Read usage reports. Read observability usage rollups and series as JSON. CSV export is not supported by the CLI. Every command also takes the [global flags](/cli/reference#global-flags) and reads the [environment variables](/cli/reference#environment-variables) that the command reference lists once. ## Commands | Command | Description | Type | |---|---|---| | [tdx usage report](/cli/reference/usage#tdx-usage-report) | Read a usage rollup. | Read | | [tdx usage series](/cli/reference/usage#tdx-usage-series) | Read a usage time series. | Read | ## tdx usage report Read a usage rollup. **Reads** Read one grouped rollup over the filtered window. Requires usage.read; the gateway narrows rows to the reader's reach. CSV is not supported by the CLI: format is never sent, so the gateway replies in JSON. Token counts and costUsd are the gateway's numbers, unchanged. Calls and traces are out of scope. Very large replies, such as grouping by key on installs with many keys, may exceed the masker's safety limits and are refused rather than shown partially (OUTPUT_MASK_LIMIT); narrow --since/--until, filter or group more coarsely. Uses auth status host-bound bearer rules; reads are read-only and --dry-run still reads. ```bash # GET /observability/v1/usage tdx usage report --group-by [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--group-by` | one of `agent`, `model`, `provider`, `key`, `tag`, `project`, `user`, `workspace` | | Group rows by this dimension. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--since` | datetime | | Window start, ISO-8601 with a time zone. | | `--until` | datetime | | Window end, ISO-8601 with a time zone. | | `--status` | string | | Filter by status; passed through to the gateway; refused locally if it could hide a credential: a percent sign, bare or written %25 (which decodes to %), or an escape that is not valid UTF-8; name: value or name=value where the name contains token, secret, password, key, credential, authorization or cookie; a #, ? or & directly before such a name, or before reset or invite, with or without =; #reset or #invite; Bearer text or a tokedex_ token. | | `--provider` | string | | Filter by provider; passed through to the gateway; refused locally if it could hide a credential: a percent sign, bare or written %25 (which decodes to %), or an escape that is not valid UTF-8; name: value or name=value where the name contains token, secret, password, key, credential, authorization or cookie; a #, ? or & directly before such a name, or before reset or invite, with or without =; #reset or #invite; Bearer text or a tokedex_ token. | | `--model` | string | | Filter by model; passed through to the gateway; refused locally if it could hide a credential: a percent sign, bare or written %25 (which decodes to %), or an escape that is not valid UTF-8; name: value or name=value where the name contains token, secret, password, key, credential, authorization or cookie; a #, ? or & directly before such a name, or before reset or invite, with or without =; #reset or #invite; Bearer text or a tokedex_ token. | | `--agent` | string | | Filter by agent; passed through to the gateway; refused locally if it could hide a credential: a percent sign, bare or written %25 (which decodes to %), or an escape that is not valid UTF-8; name: value or name=value where the name contains token, secret, password, key, credential, authorization or cookie; a #, ? or & directly before such a name, or before reset or invite, with or without =; #reset or #invite; Bearer text or a tokedex_ token. | | `--project` | string | | Filter by project; passed through to the gateway; refused locally if it could hide a credential: a percent sign, bare or written %25 (which decodes to %), or an escape that is not valid UTF-8; name: value or name=value where the name contains token, secret, password, key, credential, authorization or cookie; a #, ? or & directly before such a name, or before reset or invite, with or without =; #reset or #invite; Bearer text or a tokedex_ token. | | `--tag` | string | | Filter by tag; passed through to the gateway; refused locally if it could hide a credential: a percent sign, bare or written %25 (which decodes to %), or an escape that is not valid UTF-8; name: value or name=value where the name contains token, secret, password, key, credential, authorization or cookie; a #, ? or & directly before such a name, or before reset or invite, with or without =; #reset or #invite; Bearer text or a tokedex_ token. | | `--search` | string | | Filter by search; passed through to the gateway; refused locally if it could hide a credential: a percent sign, bare or written %25 (which decodes to %), or an escape that is not valid UTF-8; name: value or name=value where the name contains token, secret, password, key, credential, authorization or cookie; a #, ? or & directly before such a name, or before reset or invite, with or without =; #reset or #invite; Bearer text or a tokedex_ token. | | `--key-id` | string | | Filter by API key id; needs user management on: a gateway without it ignores this filter on usage report, which the CLI then refuses, and serves no usage series. | | `--user-id` | string | | Filter by user id; needs user management on: a gateway without it ignores this filter on usage report, which the CLI then refuses, and serves no usage series. | | `--workspace-id` | string | | Filter by workspace id; needs user management on: a gateway without it ignores this filter on usage report, which the CLI then refuses, and serves no usage series. | | `--request-id` | string | | Filter by request id; needs user management on: a gateway without it ignores this filter on usage report, which the CLI then refuses, and serves no usage series. | | `--sessions` | one of `grouped`, `sourced` | | Session grouping filter; needs user management on: a gateway without it ignores this filter on usage report, which the CLI then refuses, and serves no usage series. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `rows` | usage-row[] | Grouped rows: name, calls, token totals, costUsd when shown, coverage. | | `page` | page | Gateway page metadata as reported. | | `groupBy` | string | Grouping dimension. | | `summary` | usage-summary | Totals over the whole filtered window. | | `window` | usage-window | Resolved since and until. | | `money` | raw\|hidden\|null | Gateway money mode: hidden withholds every costUsd; null when the gateway omits it (user management off). | | `directory` | attribution-directory\|null | Names and states of the keys, users and workspaces the rows name; null when omitted. | ## tdx usage series Read a usage time series. **Reads** Read bucketed usage; the gateway bounds the window per interval and groups series past the top N as __other__. Requires usage.read; the gateway narrows rows to the reader's reach. CSV is not supported by the CLI: format is never sent, so the gateway replies in JSON. Token counts and costUsd are the gateway's numbers, unchanged. Calls and traces are out of scope. Very large replies, such as grouping by key on installs with many keys, may exceed the masker's safety limits and are refused rather than shown partially (OUTPUT_MASK_LIMIT); narrow --since/--until, filter or group more coarsely. Uses auth status host-bound bearer rules; reads are read-only and --dry-run still reads. ```bash # GET /observability/v1/usage/series tdx usage series --interval --since [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--interval` | one of `minute`, `hour`, `day` | | UTC bucket size. | | `--since` | datetime | | Window start, ISO-8601 with a time zone. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--group-by` | one of `agent`, `model`, `provider`, `key`, `tag`, `project`, `user`, `workspace` | | Split series by this dimension. | | `--rank-by` | one of `calls`, `costUsd`, `totalTokens` | | Rank the top series by. | | `--top` | integer | | Positive integer number of series; the gateway clamps it to 20 and reports the value it used. | | `--until` | datetime | | Window end, ISO-8601 with a time zone. | | `--status` | string | | Filter by status; passed through to the gateway; refused locally if it could hide a credential: a percent sign, bare or written %25 (which decodes to %), or an escape that is not valid UTF-8; name: value or name=value where the name contains token, secret, password, key, credential, authorization or cookie; a #, ? or & directly before such a name, or before reset or invite, with or without =; #reset or #invite; Bearer text or a tokedex_ token. | | `--provider` | string | | Filter by provider; passed through to the gateway; refused locally if it could hide a credential: a percent sign, bare or written %25 (which decodes to %), or an escape that is not valid UTF-8; name: value or name=value where the name contains token, secret, password, key, credential, authorization or cookie; a #, ? or & directly before such a name, or before reset or invite, with or without =; #reset or #invite; Bearer text or a tokedex_ token. | | `--model` | string | | Filter by model; passed through to the gateway; refused locally if it could hide a credential: a percent sign, bare or written %25 (which decodes to %), or an escape that is not valid UTF-8; name: value or name=value where the name contains token, secret, password, key, credential, authorization or cookie; a #, ? or & directly before such a name, or before reset or invite, with or without =; #reset or #invite; Bearer text or a tokedex_ token. | | `--agent` | string | | Filter by agent; passed through to the gateway; refused locally if it could hide a credential: a percent sign, bare or written %25 (which decodes to %), or an escape that is not valid UTF-8; name: value or name=value where the name contains token, secret, password, key, credential, authorization or cookie; a #, ? or & directly before such a name, or before reset or invite, with or without =; #reset or #invite; Bearer text or a tokedex_ token. | | `--project` | string | | Filter by project; passed through to the gateway; refused locally if it could hide a credential: a percent sign, bare or written %25 (which decodes to %), or an escape that is not valid UTF-8; name: value or name=value where the name contains token, secret, password, key, credential, authorization or cookie; a #, ? or & directly before such a name, or before reset or invite, with or without =; #reset or #invite; Bearer text or a tokedex_ token. | | `--tag` | string | | Filter by tag; passed through to the gateway; refused locally if it could hide a credential: a percent sign, bare or written %25 (which decodes to %), or an escape that is not valid UTF-8; name: value or name=value where the name contains token, secret, password, key, credential, authorization or cookie; a #, ? or & directly before such a name, or before reset or invite, with or without =; #reset or #invite; Bearer text or a tokedex_ token. | | `--search` | string | | Filter by search; passed through to the gateway; refused locally if it could hide a credential: a percent sign, bare or written %25 (which decodes to %), or an escape that is not valid UTF-8; name: value or name=value where the name contains token, secret, password, key, credential, authorization or cookie; a #, ? or & directly before such a name, or before reset or invite, with or without =; #reset or #invite; Bearer text or a tokedex_ token. | | `--key-id` | string | | Filter by API key id; needs user management on: a gateway without it ignores this filter on usage report, which the CLI then refuses, and serves no usage series. | | `--user-id` | string | | Filter by user id; needs user management on: a gateway without it ignores this filter on usage report, which the CLI then refuses, and serves no usage series. | | `--workspace-id` | string | | Filter by workspace id; needs user management on: a gateway without it ignores this filter on usage report, which the CLI then refuses, and serves no usage series. | | `--request-id` | string | | Filter by request id; needs user management on: a gateway without it ignores this filter on usage report, which the CLI then refuses, and serves no usage series. | | `--sessions` | one of `grouped`, `sourced` | | Session grouping filter; needs user management on: a gateway without it ignores this filter on usage report, which the CLI then refuses, and serves no usage series. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `interval` | string | Bucket size. | | `window` | series-window | Floored since and exclusive until. | | `buckets` | string[] | Every bucket start in the window. | | `groupBy` | string\|null | Grouping dimension. | | `rankBy` | string | Ranking. | | `top` | integer | Series count the gateway used after clamping. | | `series` | usage-series[] | Per-group totals and sparse points. | | `summary` | usage-point | Window totals. | | `money` | raw\|hidden\|null | Gateway money mode: hidden withholds every costUsd; null when the gateway omits it (user management off). | | `directory` | attribution-directory\|null | Names and states of the keys, users and workspaces the rows name; null when omitted. | --- # tdx users Manage people and their role assignments. List, show, change a role in one place, disable and enable people. Removal is explicitly unavailable; there is no DELETE user route. See [People and role commands](/cli/reference#people-and-role-commands). Every command also takes the [global flags](/cli/reference#global-flags) and reads the [environment variables](/cli/reference#environment-variables) that the command reference lists once. ## Commands | Command | Description | Type | |---|---|---| | [tdx users list](/cli/reference/users#tdx-users-list) | List people. | Read | | [tdx users show](/cli/reference/users#tdx-users-show) | Read a person. | Read | | [tdx users enable](/cli/reference/users#tdx-users-enable) | Enable a person. | Write | | [tdx users disable](/cli/reference/users#tdx-users-disable) | Disable a person. | Write | | [tdx users role](/cli/reference/users#tdx-users-role) | Replace roles in one place with a role. | Write | | [tdx users remove](/cli/reference/users#tdx-users-remove) | Unavailable: offboarding requires an interactive session. | Not available yet | ## tdx users list List people. **Reads** Requires users.read. Read one gateway page; hasMore and nextCursor expose truncation without automatic pagination. See [People and role commands](/cli/reference#people-and-role-commands). ```bash # GET /control/v1/users tdx users list [flags] ``` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `users` | masked-route-data | Gateway data after mandatory CLI masking; █ marks masked values. | | `hasMore` | masked-route-data | Gateway data after mandatory CLI masking; █ marks masked values. | | `nextCursor` | masked-route-data | Gateway data after mandatory CLI masking; █ marks masked values. | | `notice` | string | Present instead of data when masking withholds the entire result. | ## tdx users show Read a person. **Reads** Requires users.read or self visibility (your own user). See [People and role commands](/cli/reference#people-and-role-commands). ```bash # GET /control/v1/users/:userId tdx users show --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `user` | masked-route-data | Gateway data after mandatory CLI masking; █ marks masked values. | | `notice` | string | Present instead of data when masking withholds the entire result. | ## tdx users enable Enable a person. **Writes** Requires install-wide users.manage. See [People and role commands](/cli/reference#people-and-role-commands). ```bash # POST /control/v1/users/:userId/enable tdx users enable --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `user` | masked-route-data | Gateway data after mandatory CLI masking; █ marks masked values. | | `preview` | write-preview\|null | Requested method, path and body only, with no diff and unchecked by the gateway; null after execution. | | `notice` | string | Present instead of data when masking withholds the entire result. | ## tdx users disable Disable a person. **Writes** Requires install-wide users.manage. See [People and role commands](/cli/reference#people-and-role-commands). ```bash # POST /control/v1/users/:userId/disable tdx users disable --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `user` | masked-route-data | Gateway data after mandatory CLI masking; █ marks masked values. | | `preview` | write-preview\|null | Requested method, path and body only, with no diff and unchecked by the gateway; null after execution. | | `notice` | string | Present instead of data when masking withholds the entire result. | ## tdx users role Replace roles in one place with a role. **Writes** Requires users.manage in the selected place. PUT sends one assignment and explicitly names its place (install scope by default, or --workspace-id). This replaces the caller-managed roles IN THAT PLACE, not roles elsewhere; IdP-managed roles and server subset/last-owner rules remain in force. No concurrency precondition or current-state diff is inferred. See [People and role commands](/cli/reference#people-and-role-commands). ```bash # PUT /control/v1/users/:userId/role-assignments tdx users role --id --role-id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | | `--role-id` | string | | Public role id from the gateway. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--workspace-id` | string | | Limit replacement to this workspace; omitted means install scope. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `user` | masked-route-data | Gateway data after mandatory CLI masking; █ marks masked values. | | `preview` | write-preview\|null | Requested method, path and body only, with no diff and unchecked by the gateway; null after execution. | | `notice` | string | Present instead of data when masking withholds the entire result. | ## tdx users remove Unavailable: offboarding requires an interactive session. **Not available yet.** Running it exits 7 with `NOT_IMPLEMENTED`. There is NO DELETE user route. Removal is terminal POST deprovision from a reviewed offboarding plan, session-only with step-up and possible one-shot credential transfers. This CLI cannot execute it. Use the dashboard; no request, authentication or profile read is attempted. Dry-run shows only the route with body null (the required reviewed decisions are unavailable), never a fake deletion. See [People and role commands](/cli/reference#people-and-role-commands). ```bash # GET /control/v1/users/:userId/offboarding # POST /control/v1/users/:userId/deprovision tdx users remove --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public resource id; never a credential. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `preview` | write-preview\|null | Requested method, path and body only, with no diff and unchecked by the gateway; null after execution. | | `notice` | string | Present instead of data when masking withholds the entire result. | --- # tdx workspaces Manage workspaces, their policy and spend. List, create, edit, pause, resume, archive and restore workspaces; set their guardrail, rules and budgets; preview key mints; read key provenance, availability, spend reports and key templates. The gateway authorizes every route. Pausing, archiving and other changes that reduce access need --acknowledge with the digest of the gateway's review for the same credential; each such command's help shows how to obtain it with the api command. IdP group bindings are session-only and unavailable to this bearer-only CLI. Every command also takes the [global flags](/cli/reference#global-flags) and reads the [environment variables](/cli/reference#environment-variables) that the command reference lists once. ## Commands | Command | Description | Type | |---|---|---| | [tdx workspaces list](/cli/reference/workspaces#tdx-workspaces-list) | List workspaces. | Read | | [tdx workspaces create](/cli/reference/workspaces#tdx-workspaces-create) | Create a workspace. | Write | | [tdx workspaces show](/cli/reference/workspaces#tdx-workspaces-show) | Read a workspace. | Read | | [tdx workspaces edit](/cli/reference/workspaces#tdx-workspaces-edit) | Rename or retag a workspace. | Write | | [tdx workspaces guardrail](/cli/reference/workspaces#tdx-workspaces-guardrail) | Set a workspace's guardrail and budgets. | Group | | [tdx workspaces guardrail set](/cli/reference/workspaces#tdx-workspaces-guardrail-set) | Replace a workspace's guardrail and budgets. | Write | | [tdx workspaces rules](/cli/reference/workspaces#tdx-workspaces-rules) | Set a workspace's own rules. | Group | | [tdx workspaces rules set](/cli/reference/workspaces#tdx-workspaces-rules-set) | Replace a workspace's rules. | Write | | [tdx workspaces pause](/cli/reference/workspaces#tdx-workspaces-pause) | Pause a workspace. | Write | | [tdx workspaces resume](/cli/reference/workspaces#tdx-workspaces-resume) | Resume a paused workspace. | Write | | [tdx workspaces archive](/cli/reference/workspaces#tdx-workspaces-archive) | Archive an empty workspace. | Write | | [tdx workspaces restore](/cli/reference/workspaces#tdx-workspaces-restore) | Restore an archived workspace. | Write | | [tdx workspaces idp-bindings](/cli/reference/workspaces#tdx-workspaces-idp-bindings) | Identity-provider group bindings (dashboard only). | Group | | [tdx workspaces idp-bindings set](/cli/reference/workspaces#tdx-workspaces-idp-bindings-set) | Replace a workspace's IdP group bindings (dashboard only). | Dashboard only | | [tdx workspaces key-preview](/cli/reference/workspaces#tdx-workspaces-key-preview) | Preview the API key a mint would create here. | Read | | [tdx workspaces keys](/cli/reference/workspaces#tdx-workspaces-keys) | Inspect a workspace's keys. | Group | | [tdx workspaces keys provenance](/cli/reference/workspaces#tdx-workspaces-keys-provenance) | Show who authorized a key and under which rules. | Read | | [tdx workspaces availability](/cli/reference/workspaces#tdx-workspaces-availability) | Show what a workspace's keys can call. | Read | | [tdx workspaces spend-report](/cli/reference/workspaces#tdx-workspaces-spend-report) | Report spend for every workspace or one. | Read | | [tdx workspaces templates](/cli/reference/workspaces#tdx-workspaces-templates) | List key templates. | Read | ## tdx workspaces list List workspaces. **Reads** Read the workspaces the gateway lets this credential see (workspaces.read), with this month's spend where it may read it. Only --status is sent. See [Workspace reads](/cli/reference#workspace-reads). ```bash # GET /control/v1/workspaces tdx workspaces list [flags] ``` **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--status` | string | | Status filter the gateway accepts, such as active, paused, archived or all; omitted lists every workspace that is not archived. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `workspaces` | public-workspace[] | Id, slug, name, purpose, tags, status, counts, model access summary and this month's spend summary. | **Examples** List every workspace, archived ones included: ```bash tdx workspaces list --status all --json ``` ## tdx workspaces create Create a workspace. **Writes** Create a workspace (install-wide workspaces.manage). The gateway's reply also suggests a first inference-key mint call; that suggestion is withheld, so mint the first key with api-keys create --owner. See [Workspace changes](/cli/reference#workspace-changes). ```bash # POST /control/v1/workspaces tdx workspaces create --name [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--name` | string | | Display name. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--slug` | string | | URL slug; omitted derives one from the name; slugs are never reused. | | `--purpose` | string | | Purpose the gateway accepts, such as project or team. | | `--tags` | json | | JSON array of tag strings. | | `--guardrail` | json | | Guardrail: JSON policy layer object (models, maxKeyLifetimeDays, keyRpmMax, keyBudgetMax), or null for none; the gateway validates it. | | `--rules` | json | | Workspace rules: JSON policy layer object (models, maxKeyLifetimeDays, keyRpmMax, keyBudgetMax), or null for none; the gateway validates it. | | `--budget` | json | | Workspace budget: JSON `{"window", "limit"}` with limit a USD decimal string, or null to remove it; the gateway validates it. | | `--key-budget-default` | json | | Per-key default budget for new keys: JSON `{"window", "limit"}`, or null to remove it; the gateway validates it. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `workspace` | public-workspace | Id, slug, name, purpose, tags, status and its reason, counts, model access summary, guardrail, rules, budgets and, where the credential may see them, IdP bindings. | | `preview` | write-preview\|null | Requested method, path and body, unchecked by the gateway; null after execution. | **Examples** Preview creating a workspace: ```bash tdx workspaces create --name Research --purpose project --dry-run --json ``` ## tdx workspaces show Read a workspace. **Reads** Read one workspace with its guardrail, rules, budgets and this month's spend. See [Workspace reads](/cli/reference#workspace-reads). ```bash # GET /control/v1/workspaces/:workspaceId tdx workspaces show --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public workspace id from workspaces list; never a credential. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `workspace` | public-workspace | Workspace view with guardrail, rules, budgets, IdP bindings where visible and this month's spend summary. | **Examples** Read one workspace: ```bash tdx workspaces show --id --json=workspace ``` ## tdx workspaces edit Rename or retag a workspace. **Writes** Change a workspace's name, purpose or tags (install-wide workspaces.manage); an archived workspace must be restored first. A workspace keeps the slug it was created with. See [Workspace changes](/cli/reference#workspace-changes). ```bash # PATCH /control/v1/workspaces/:workspaceId tdx workspaces edit --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public workspace id from workspaces list; never a credential. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--name` | string | | Display name. | | `--purpose` | string | | Purpose the gateway accepts. | | `--tags` | json | | JSON array of tag strings, replacing the current tags; [] clears them. | **Constraints** - `--name` is required unless `--purpose` or `--tags` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `workspace` | public-workspace | Id, slug, name, purpose, tags, status and its reason, counts, model access summary, guardrail, rules, budgets and, where the credential may see them, IdP bindings. | | `preview` | write-preview\|null | Requested method, path and body, unchecked by the gateway; null after execution. | **Examples** Rename a workspace: ```bash tdx workspaces edit --id --name Research --json ``` ## tdx workspaces guardrail Set a workspace's guardrail and budgets. Replace a workspace's guardrail layer and its budgets. A change that reduces access needs --acknowledge with the digest of the gateway's review for the same credential; see guardrail set --help. ## tdx workspaces guardrail set Replace a workspace's guardrail and budgets. **Writes** Replace the guardrail layer and set the workspace or per-key default budget (install-wide workspaces.manage); omitted parts stay unchanged. A guardrail may only tighten the organisation's policy. A change the gateway's review finds reduces access (such as a new or lower budget, a lower key limit or keys losing models) needs --acknowledge with the digest of the gateway's review of exactly this change, obtained with this same credential; without it the gateway refuses with REVIEW_REQUIRED, and with a digest that no longer matches with REVIEW_STALE (both exit 6); it applies nothing and this CLI shows no review. This command's --dry-run cannot show that review. To obtain the review and its digest, send the identical request with tdx api PUT '/control/v1/workspaces/\/guardrail?dryRun=true' --input \ (the JSON body this command would send, without acknowledge, under wire names such as keyBudgetDefault and remediation `{"clampExpiryDays": }`) --json, then rerun this command with the same options and --acknowledge \. Any other body, or a gateway change in between, makes the digest stale. If the digest in the api output prints as █, make the change in the gateway dashboard (a digest read there usually does not match this CLI's credential). Write budget limits with a decimal point, such as 5.00: a --dry-run preview masks text matching a whole-number limit such as 5. See [Workspace changes](/cli/reference#workspace-changes). ```bash # PUT /control/v1/workspaces/:workspaceId/guardrail tdx workspaces guardrail set --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public workspace id from workspaces list; never a credential. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--guardrail` | json | | Guardrail: JSON policy layer object (models, maxKeyLifetimeDays, keyRpmMax, keyBudgetMax), or null for none; the gateway validates it. | | `--budget` | json | | Workspace budget: JSON `{"window", "limit"}` with limit a USD decimal string, or null to remove it; the gateway validates it. | | `--key-budget-default` | json | | Per-key default budget for new keys: JSON `{"window", "limit"}`, or null to remove it; the gateway validates it. | | `--clamp-expiry-days` | integer | | Remediation: shorten the lifetimes of keys the change leaves outside the new limit to this many days; the gateway validates the value. | | `--acknowledge` | string | | Digest of the gateway's review of exactly this change, obtained with this same credential; the gateway validates it. | **Constraints** - `--guardrail` is required unless `--budget` or `--key-budget-default` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `workspace` | public-workspace | Id, slug, name, purpose, tags, status and its reason, counts, model access summary, guardrail, rules, budgets and, where the credential may see them, IdP bindings. | | `review` | public-review\|null | Kind, target, revision, whether acknowledgement was required, digest and change counts of the gateway's review; null when the gateway made no reviewed change. | | `preview` | write-preview\|null | Requested method, path and body, unchecked by the gateway; null after execution. | **Examples** Preview a workspace budget: ```bash tdx workspaces guardrail set --id --budget '{"window":"month","limit":"100.00"}' --dry-run --json ``` ## tdx workspaces rules Set a workspace's own rules. Replace a workspace's own rules layer. A change that reduces access needs --acknowledge with the digest of the gateway's review for the same credential; see rules set --help. ## tdx workspaces rules set Replace a workspace's rules. **Writes** Replace the workspace's own rules layer and per-key default budget (workspace_rules.manage in the workspace); omitted parts stay unchanged. Rules may only tighten the guardrail, and without install-wide workspaces.manage the per-key default may only be lowered. A change the gateway's review finds reduces access (such as a lower key limit or keys losing models) needs --acknowledge with the digest of the gateway's review of exactly this change, obtained with this same credential; without it the gateway refuses with REVIEW_REQUIRED, and with a digest that no longer matches with REVIEW_STALE (both exit 6); it applies nothing and this CLI shows no review. This command's --dry-run cannot show that review. To obtain the review and its digest, send the identical request with tdx api PUT '/control/v1/workspaces/\/rules?dryRun=true' --input \ (the JSON body this command would send, without acknowledge, under wire names such as keyBudgetDefault and remediation `{"clampExpiryDays": }`) --json, then rerun this command with the same options and --acknowledge \. Any other body, or a gateway change in between, makes the digest stale. If the digest in the api output prints as █, make the change in the gateway dashboard (a digest read there usually does not match this CLI's credential). Write budget limits with a decimal point, such as 5.00: a --dry-run preview masks text matching a whole-number limit such as 5. See [Workspace changes](/cli/reference#workspace-changes). ```bash # PUT /control/v1/workspaces/:workspaceId/rules tdx workspaces rules set --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public workspace id from workspaces list; never a credential. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--rules` | json | | Workspace rules: JSON policy layer object (models, maxKeyLifetimeDays, keyRpmMax, keyBudgetMax), or null for none; the gateway validates it. | | `--key-budget-default` | json | | Per-key default budget for new keys: JSON `{"window", "limit"}`, or null to remove it; the gateway validates it. | | `--clamp-expiry-days` | integer | | Remediation: shorten the lifetimes of keys the change leaves outside the new limit to this many days; the gateway validates the value. | | `--acknowledge` | string | | Digest of the gateway's review of exactly this change, obtained with this same credential; the gateway validates it. | **Constraints** - `--rules` is required unless `--key-budget-default` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `workspace` | public-workspace | Id, slug, name, purpose, tags, status and its reason, counts, model access summary, guardrail, rules, budgets and, where the credential may see them, IdP bindings. | | `review` | public-review\|null | Kind, target, revision, whether acknowledgement was required, digest and change counts of the gateway's review; null when the gateway made no reviewed change. | | `preview` | write-preview\|null | Requested method, path and body, unchecked by the gateway; null after execution. | **Examples** Preview workspace rules: ```bash tdx workspaces rules set --id --rules '{"maxKeyLifetimeDays":30}' --dry-run --json ``` ## tdx workspaces pause Pause a workspace. **Writes** Pause a workspace, suspending its API keys until it is resumed (install-wide workspaces.manage). Pausing an active workspace always needs --acknowledge with the digest of the gateway's review of exactly this change, obtained with this same credential; without it the gateway refuses with REVIEW_REQUIRED, and with a digest that no longer matches with REVIEW_STALE (both exit 6); it applies nothing and this CLI shows no review. This command's --dry-run cannot show that review. To obtain the review and its digest, send the identical request with tdx api POST '/control/v1/workspaces/\/pause?dryRun=true' [--field reason=\] --json, then rerun this command with the same options and --acknowledge \. Any other body, or a gateway change in between, makes the digest stale. If the digest in the api output prints as █, make the change in the gateway dashboard (a digest read there usually does not match this CLI's credential). The api command's --field sends a bare number, true, false or null as a typed value, so for such a reason use --input \ with the JSON body `{"reason": ""}`. Pausing a paused workspace changes nothing and returns review null. See [Workspace changes](/cli/reference#workspace-changes). ```bash # POST /control/v1/workspaces/:workspaceId/pause tdx workspaces pause --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public workspace id from workspaces list; never a credential. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--reason` | string | | Non-secret reason shown with the paused status. | | `--acknowledge` | string | | Digest of the gateway's review of exactly this change, obtained with this same credential; the gateway validates it. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `workspace` | public-workspace | Id, slug, name, purpose, tags, status and its reason, counts, model access summary, guardrail, rules, budgets and, where the credential may see them, IdP bindings. | | `review` | public-review\|null | Kind, target, revision, whether acknowledgement was required, digest and change counts of the gateway's review; null when the gateway made no reviewed change. | | `preview` | write-preview\|null | Requested method, path and body, unchecked by the gateway; null after execution. | **Examples** Preview the pause request: ```bash tdx workspaces pause --id --dry-run --json ``` ## tdx workspaces resume Resume a paused workspace. **Writes** Resume a paused workspace (install-wide workspaces.manage); resuming an active one changes nothing. Resuming never reduces access, so it needs no --acknowledge; the route accepts one while the workspace is paused, and the gateway refuses a digest that does not match its review with REVIEW_STALE (exit 6). See [Workspace changes](/cli/reference#workspace-changes). ```bash # POST /control/v1/workspaces/:workspaceId/resume tdx workspaces resume --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public workspace id from workspaces list; never a credential. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--acknowledge` | string | | Optional review digest; resuming never needs one, and the gateway refuses one that does not match its review. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `workspace` | public-workspace | Id, slug, name, purpose, tags, status and its reason, counts, model access summary, guardrail, rules, budgets and, where the credential may see them, IdP bindings. | | `preview` | write-preview\|null | Requested method, path and body, unchecked by the gateway; null after execution. | **Examples** Preview the resume request: ```bash tdx workspaces resume --id --dry-run --json ``` ## tdx workspaces archive Archive an empty workspace. **Writes** Archive a workspace that holds no API keys (install-wide workspaces.manage): its roles, IdP bindings, admin keys and pending invites are removed. Archiving an open workspace always needs --acknowledge with the digest of the gateway's review of exactly this change, obtained with this same credential; without it the gateway refuses with REVIEW_REQUIRED, and with a digest that no longer matches with REVIEW_STALE (both exit 6); it applies nothing and this CLI shows no review. This command's --dry-run cannot show that review. To obtain the review and its digest, send the identical request with tdx api POST '/control/v1/workspaces/\/archive?dryRun=true' --json, then rerun this command with the same options and --acknowledge \. Any other body, or a gateway change in between, makes the digest stale. If the digest in the api output prints as █, make the change in the gateway dashboard (a digest read there usually does not match this CLI's credential). Archiving an archived workspace changes nothing and returns review null. The Default workspace is never archived. See [Workspace changes](/cli/reference#workspace-changes). ```bash # POST /control/v1/workspaces/:workspaceId/archive tdx workspaces archive --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public workspace id from workspaces list; never a credential. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--acknowledge` | string | | Digest of the gateway's review of exactly this change, obtained with this same credential; the gateway validates it. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `workspace` | public-workspace | Id, slug, name, purpose, tags, status and its reason, counts, model access summary, guardrail, rules, budgets and, where the credential may see them, IdP bindings. | | `review` | public-review\|null | Kind, target, revision, whether acknowledgement was required, digest and change counts of the gateway's review; null when the gateway made no reviewed change. | | `preview` | write-preview\|null | Requested method, path and body, unchecked by the gateway; null after execution. | **Examples** Preview the archive request: ```bash tdx workspaces archive --id --dry-run --json ``` ## tdx workspaces restore Restore an archived workspace. **Writes** Restore an archived workspace, empty, with no roles, bindings or pending invites (install-wide workspaces.manage); restoring an open one changes nothing. See [Workspace changes](/cli/reference#workspace-changes). ```bash # POST /control/v1/workspaces/:workspaceId/restore tdx workspaces restore --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public workspace id from workspaces list; never a credential. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `workspace` | public-workspace | Id, slug, name, purpose, tags, status and its reason, counts, model access summary, guardrail, rules, budgets and, where the credential may see them, IdP bindings. | | `preview` | write-preview\|null | Requested method, path and body, unchecked by the gateway; null after execution. | **Examples** Preview the restore request: ```bash tdx workspaces restore --id --dry-run --json ``` ## tdx workspaces idp-bindings Identity-provider group bindings (dashboard only). Binding identity-provider groups to workspace roles is session-only with step-up; this bearer-only CLI refuses it with SESSION_REQUIRED before any request or credential read, --dry-run included. Use the gateway dashboard. ## tdx workspaces idp-bindings set Replace a workspace's IdP group bindings (dashboard only). **Dashboard only.** The gateway serves this only to a signed-in dashboard session, so the CLI refuses it with `SESSION_REQUIRED`. Unavailable to this bearer-only CLI: PUT /control/v1/workspaces/:workspaceId/idp-bindings is session-only: binding an identity-provider group hands a workspace role to everyone in it, so the gateway serves it only to an interactive dashboard sign-in holding idp_bindings.manage in the workspace, after a recent sign-in (step-up), never to a key. Use the gateway dashboard. --dry-run also refuses: there is no reachable change to preview. No request is sent and no credential, profile or file is read. ```bash # PUT /control/v1/workspaces/:workspaceId/idp-bindings tdx workspaces idp-bindings set --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public workspace id from workspaces list; never a credential. | ## tdx workspaces key-preview Preview the API key a mint would create here. **Reads** Ask the gateway whether an inference-key mint here would be allowed, authorized as that mint (inference_keys.manage where the key would land), and what it would mint after policy adjustments. The gateway saves nothing, mints nothing and issues no credential. This is a read, not a dry-run: it sends the request, including with --dry-run, and any failure is reported as a failed read. A refusal by policy is a successful answer with allowed false and the refusal. With neither --owner nor a workspace-kind --template-id the gateway previews a personal key, which only a person holds: a person's session or their own admin key can preview one, but the master key or a service or unowned admin key needs --owner workspace or a workspace-kind --template-id. See [Workspace reads](/cli/reference#workspace-reads). ```bash # POST /control/v1/workspaces/:workspaceId/key-preview tdx workspaces key-preview --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public workspace id from workspaces list; never a credential. | **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--template-id` | string | | Key template id or slug from workspaces templates. | | `--owner` | string | | Owner kind the gateway accepts, such as personal or workspace; personal needs a signed-in person. | | `--allowed-model` | string | | Model id from tdx models list; repeat for several; omitted allows every model the workspace allows. Repeatable. | | `--expires-in` | string | | Lifetime the gateway accepts, such as 30d or never; omitted uses the template's. | | `--rpm` | integer | | Requests per minute; the gateway validates it. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `allowed` | boolean | Whether the mint would be allowed. | | `refusal` | public-refusal\|null | Gateway refusal code, message and parameter when not allowed. | | `template` | public-template\|null | Template the preview applied. | | `draft` | public-key-draft\|null | Owner, allowed models, expiry, rpm and template id the mint would use. | | `adjustments` | public-adjustment[] | Field, before, after and reason for each policy adjustment. | | `holderAccessEndsAt` | string\|null | When a personal key holder's access ends. | **Examples** Check a workspace key mint: ```bash tdx workspaces key-preview --id --owner workspace --template-id --json ``` ## tdx workspaces keys Inspect a workspace's keys. Read the provenance of a key in a workspace. ## tdx workspaces keys provenance Show who authorized a key and under which rules. **Reads** Read who minted a key in this workspace, its template and the rule revisions it was minted under, and whether the policy changed since. The gateway shows only a key this credential may read. The key id itself is withheld from output. See [Workspace reads](/cli/reference#workspace-reads). ```bash # GET /control/v1/workspaces/:workspaceId/keys/:keyId/provenance tdx workspaces keys provenance --id --key-id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public workspace id from workspaces list; never a credential. | | `--key-id` | string | | Public key id; never a credential. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `provenance` | public-provenance | Name, creation, creator, authority, template, rule revisions and whether policy changed since. | **Examples** Read a key's provenance: ```bash tdx workspaces keys provenance --id --key-id --json ``` ## tdx workspaces availability Show what a workspace's keys can call. **Reads** Read every model the gateway serves with whether this workspace's keys can call it and why not, prices of callable models where the gateway has them, and each provider's status there. See [Workspace reads](/cli/reference#workspace-reads). ```bash # GET /control/v1/workspaces/:workspaceId/availability tdx workspaces availability --id [flags] ``` **Required flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public workspace id from workspaces list; never a credential. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `workspaceId` | string | Workspace id. | | `workspaceStatus` | string | Workspace status. | | `modelAccess` | public-model-access | Mode, listed models and the layer that set them. | | `models` | public-model-availability[] | Each model's kind, providers, status, restriction, providers off and prices. | | `providers` | public-provider-availability[] | Each provider's status and model counts. | **Examples** List what a workspace can call: ```bash tdx workspaces availability --id --json=models ``` ## tdx workspaces spend-report Report spend for every workspace or one. **Reads** Read one month's spend report (spend.read): without --id, GET /control/v1/workspaces/spend-report across the workspaces this credential may read (grouped by workspace by default); with --id, that workspace's report (grouped by key by default; a developer sees only their own keys). JSON only: the gateway's CSV download (format=csv) is not supported, because this CLI reads JSON replies only. Rows withhold the reply's keyId and keyName fields; for key groupings the row's group and name are the key's id and name. A key row's keyKind prints the kind the gateway reports, a workspace (service) key's included. See [Workspace reads](/cli/reference#workspace-reads). ```bash # GET /control/v1/workspaces/spend-report # GET /control/v1/workspaces/:workspaceId/spend-report tdx workspaces spend-report [flags] ``` **Optional flags** | Flag | Type | Default | Description | |---|---|---|---| | `--id` | string | | Public workspace id; omitted reports every workspace the credential may read. | | `--period` | string | | Month as YYYY-MM; omitted is the current month; the gateway validates the range. | | `--group-by` | string | | Grouping the gateway accepts, such as workspace, key, person or model; workspace is not accepted with --id. | | `--key-id` | string | | Public key id; the gateway accepts it only with --group-by model. | **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `period` | string | Reported month. | | `periodStart` | string | Month start. | | `periodEnd` | string | Month end. | | `current` | boolean | Whether the month is still running. | | `groupBy` | string | Grouping used. | | `modelIds` | string\|null | Which model ids rows name, when grouped by model. | | `days` | string[] | UTC days covered. | | `compare` | public-compare\|null | Comparison month and whether it is like for like. | | `rows` | public-spend-row[] | One row per group with calls, token counts, cost, previous cost and daily cost. | | `total` | public-spend-row | Total row. | | `projectedCostUsd` | string\|null | Projected month cost. | | `coverage` | public-coverage | Calls, priced, unpriced and estimated calls. | **Examples** Report one workspace's spend by model: ```bash tdx workspaces spend-report --id --group-by model --json=rows,total ``` ## tdx workspaces templates List key templates. **Reads** Read the key templates the gateway offers, with how many unrevoked keys this credential may see use each. See [Workspace reads](/cli/reference#workspace-reads). ```bash # GET /control/v1/templates tdx workspaces templates [flags] ``` **Output fields** (inside `data`) | Field | Type | Description | |---|---|---| | `templates` | public-template[] | Id, slug, name, description, kind, lifetime, budget, rpm and use count. | **Examples** List key templates: ```bash tdx workspaces templates --json ``` --- # 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 | | `/.md` | The Markdown of any page: append `.md` to its path, as in [`/gateway/quickstart.md`](/gateway/quickstart.md). A section index is at `
.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> { 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 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":"","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='' 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).