Language
Client

Errors, limits and request IDs#

Read the gateway's error code to decide whether to retry, wait or fix the request.

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');
}
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")
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');
}
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")
code
429 rate_limited retry

For Rust, choose Tokedex SDK in the bar above: its Rust client takes the same address and key.

Shell
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" }]
  }'
code
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}}}
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');
}
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")
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<dyn std::error::Error>> {
    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(())
}
code
429 rate_limited retry
code
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. A request that succeeds calls a provider and can incur charges.

Branch on the error code#

The code is in error.code. Several causes share one status, such as 403, so branch on the code rather than the status.

The code is in the body's error.code, the body being error.errorerror.body. The status and the Anthropic error.type, such as rate_limit_error, are shared by several causes, so branch on the code.

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.

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#

CodeStatusRetry?
rate_limited429Yes, after retry-after seconds
provider_unavailable, invalid_upstream_response, provider_timeout503, 502, 504Yes, with backoff
limits_unavailable, continuation_unavailable503Yes, with backoff
budget_exceeded402Not until the budget resets
provider_not_served422No: name a provider from the error's providers in x-tokedex-provider, or drop the header (Choose a provider)
Every other code4xx, 5xxNo: 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.

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 maxRetriesmax_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 maxRetriesmax_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.

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:

code
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 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.

The SDK reads it with router.limits.retrieve()router.limits().retrieve(); see Run through a gateway.

Errors inside a stream#

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.

code
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.

code
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.

On OpenAI Chat Completions and OpenAI Responses, the OpenAI SDK raises OpenAI.APIErroropenai.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.

Iterating the stream raises Anthropic.APIErroranthropic.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.

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.

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.

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#

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'));
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"))
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'));
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"))
Shell
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\"." }]
  }'
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' } },
);
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"},
    )
use std::sync::Arc;
 
use tokedex::{GatewayOptions, RequestOptions, Router, wire};
 
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    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(())
}
code
f556d214-dcf3-4c31-8bb2-412e1d4085a7
code
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.

code
f556d214-dcf3-4c31-8bb2-412e1d4085a7
code
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.

On an error, the client holds it in requestIDrequest_id.

Request headerDoes
x-tokedex-trajectory-idGroups requests that share the value, such as one conversation or agent run, into one session
x-tokedex-tagsLabels the request with comma-separated tags you can search and filter by
x-tokedex-project-nameNames the project the request belongs to
x-tokedex-trace-text: trueKeeps the prompt and response text in the trace, when an admin has turned text capture on
x-tokedex-trace: falseLeaves 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 shows what it holds.

Next: Budgets or Find and inspect a request.