
# 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<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(())
}
```

```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: '<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);
```

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

```rust
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 `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('<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);
}
```

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

```rust
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](/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).
