
# 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<dyn std::error::Error>> {
    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 <provider> <upstream-model>
```

**Anthropic SDK**

```text
aa/cheapest <provider> <upstream-model>
```

**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: <provider>
x-tokedex-model: <upstream-model>
x-tokedex-deployment: <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<dyn std::error::Error>> {
    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
<provider> <upstream-model>
aa/cheapest
```

**Rust · Tokedex SDK**

```text
Some("<provider>") Some("<upstream-model>")
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: <provider-id>" \
  -d '{
    "model": "<model-id>",
    "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: '<model-id>', messages: [{ role: 'user', content: 'Reply with exactly the word "hello".' }] },
  { headers: { 'x-tokedex-provider': '<provider-id>' } },
).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="<model-id>",
    messages=[{"role": "user", "content": 'Reply with exactly the word "hello".'}],
    extra_headers={"x-tokedex-provider": "<provider-id>"},
)
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: '<model-id>', max_tokens: 64, messages: [{ role: 'user', content: 'Reply with exactly the word "hello".' }] },
  { headers: { 'x-tokedex-provider': '<provider-id>' } },
).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="<model-id>",
    max_tokens=64,
    messages=[{"role": "user", "content": 'Reply with exactly the word "hello".'}],
    extra_headers={"x-tokedex-provider": "<provider-id>"},
)
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: '<model-id>', messages: [{ role: 'user', content: 'Reply with exactly the word "hello".' }] },
    { providers: ['<provider-id>'], 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="<model-id>",
            messages=[{"role": "user", "content": 'Reply with exactly the word "hello".'}],
            providers=["<provider-id>"],
            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<dyn std::error::Error>> {
    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(["<provider-id>"])
            .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("<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 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: <provider-id>, <other-provider-id>
```

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