Language

Errors, retries and timeouts#

Catch a failed call, tell what kind of failure it was, and decide what your code does next.

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;
  }
}
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 ""))
use tokedex::{Error, Router, RouterError, wire};
 
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    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(())
}
code
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 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.

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 and a cancellation end the call at once.
  • When no attempt succeeds, you get the error of the failure, such as RateLimitErrorRouterError::Provider.
  • Through a gateway, the gateway does this on its side; see Run through a 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.

Set a timeout#

const response = await router.responses.create(
  { model: 'openai/gpt-6-luna', input: 'Summarise the plot of Hamlet.' },
  { timeoutMs: 30_000 },
);
response = router.responses.create(
    model="openai/gpt-6-luna", input="Summarise the plot of Hamlet.", timeout_ms=30_000
)
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 runToolsrun_tools run. A streamToolsstream_tools run starts the timeout at your first read.

On timeout, an embedded Router raises a NetworkError with subkind Timeout. Through a gateway, the SDK raises a DOMException named TimeoutError.

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

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#

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 },
);
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)
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.

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.

An embedded Router raises a NetworkError with subkind Abort. Through a gateway, cancelling with CancelToken raises asyncio.CancelledError.

Cancellation raises a network error with subkind Abort in both modes.

Gateway errors#

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.

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().

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 onResponseHeaderson_response_headers receives. Retry only the codes that Errors and limits 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.

Through a gateway, a stream error raises GatewayHttpError.

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.

Through a gateway, a stream error is a RouterError, as it is for a call.

Router refusals#

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

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

  • 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 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 has the full guidelines.

Next: Run through a gateway, Routes and failover or Observability.