Choose a model#
See every model your keys let you call, on which API, and how much each one can read.
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);
}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)use tokedex::Router;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
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(())
}openai/gpt-6-luna anthropic.messages 1050000
openai/gpt-6-luna openai.chat-completions 1050000
openai/gpt-6-luna openai.responses 1050000It needs OPENAI_API_KEY. Listing sends nothing to a provider, so it costs nothing.
Model row fields#
router.models.list()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_windowandmax_input_tokens: how many tokens the model reads, when known.native_batch: the 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 valuesproviderscan name.
The list holds the built-in models and routers whose provider has a key, then your 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.
APIs for each model#
client_dialect_id | Call it on |
|---|---|
openai.responses | router.responsesrouter.responses() |
openai.chat-completions | router.chat.completionsrouter.chat().completions() |
anthropic.messages | router.messagesrouter.messages() |
google.generate-content | router.generateContentrouter.generate_contentrouter.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 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#
const response = await router.responses.create({
model: 'aa/fastest',
input: 'Name the capital of France in one word.',
});response = router.responses.create(
model="aa/fastest", input="Name the capital of France in one word."
)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. Routers and fallback 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#
const completion = await router.chat.completions.create(
{ model: '<model-id>', messages: [{ role: 'user', content: 'Reply with exactly the word "hello".' }] },
{ providerOrder: ['<provider-id>', '<other-provider-id>'], onServed: (served) => console.log('served by', served.provider) },
);
console.log(completion.choices[0]?.message.content);completion = router.chat.completions.create(
model="<model-id>",
messages=[{"role": "user", "content": 'Reply with exactly the word "hello".'}],
provider_order=["<provider-id>", "<other-provider-id>"],
on_served=lambda served: print("served by", served.provider),
)
print(completion.choices[0].message.content)use tokedex::{RequestOptions, wire};
let ordered = router.with_options(
RequestOptions::default()
.provider_order(["<provider-id>", "<other-provider-id>"])
.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("<model-id>", 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: { '<model-id>': ['<provider-id>'] } in its options|provider_order={"<model-id>": ["<provider-id>"]} when you create it|Router::builder().provider_order("<model-id>", ["<provider-id>"])]]. 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
BadRequestnamingx-tokedex-provider-order, before anything is sent; take IDs from the model'sprovider_ids. - Option and header. A call may also send the
x-tokedex-provider-orderheader. 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).
- 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 set as [[
timeoutMs|timeout_ms|RequestOptions::timeout]], it also moves on at once when the wait is longer than the time left. [[AsignalfromAbortSignal.timeout(ms)cannot tell the Router how long is left, so settimeoutMsinstead.|Acanceltoken sets no time limit, so settimeout_msas well.|A cancellation token sets no time limit, so settimeoutas well.]]
Pin a provider#
When several providers serve a model, the Router tries them in the model's provider order. 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. onServedon_served hears which provider served, once, before the result or the first stream event. router.models.retrieve(id)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.
import { ProviderNotServedError, Router } from '@tokedex/sdk';
const router = new Router();
const detail = await router.models.retrieve('<model-id>');
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: ['<provider-id>'], 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);
}from tokedex import ProviderNotServedError, Router
with Router() as router:
detail = router.models.retrieve("<model-id>")
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=["<provider-id>"],
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)use tokedex::{Error, RequestOptions, Router, wire};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let router = Router::builder().build()?;
let detail = router.models().retrieve("<model-id>").await?;
println!("{:?} {:?}", detail.model.provider_ids, detail.routing.map(|routing| routing.strategy));
let pinned = router.with_options(
RequestOptions::default()
.providers(["<provider-id>"])
.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 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.
Check what a model accepts#
- Length.
context_windowandmax_input_tokensgive 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 withContextWindowExceeded. - 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.
The refusal is a GatewayError with kind CapabilityUnsupported.
The refusal raises FidelityError from tokedex.core.ir, whose issues name the input, such as input.image.
The refusal is tokedex::Error::Router holding RouterError::FidelityError, whose issues name the input, such as input.image.
Read the whole model list response#
const discovery = await router.models.discover();
console.log(discovery.data.length, discovery.models.length);discovery = router.models.discover()
print(len(discovery.data), len(discovery.models))let discovery = router.models().discover().await?;
println!("{} {}", discovery.data.len(), discovery.models.len());data holds the rows that router.models.list()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()router.models().list(), and use models only to configure a coding agent, because models leaves your custom models out.
Next: Translation between APIs, Provider keys or Custom models.