
# Routers and fallback

Create a model ID of your own that sends each request to one of the models you list, and moves to the next when a provider fails.

**Dashboard**

1. Open **Models & Routing → Routing** and choose **+ New router**.
2. Enter the **Model ID** clients will send, such as `<router-id>`.
3. Under **How should it choose?**, pick a strategy, such as **In order**.
4. Under **Models**, add at least two models whose provider has a key. With **In order**, set the order with the arrows.
5. Check **Works with** for shared API formats, then check the pick preview. Models on the same API can still handle requests or responses differently, such as how they represent tool calls. If the preview says the models do not share a projection contract, swap or remove a model before creating the router.
6. Under **If a model fails**, choose **Change** to pick which failures fall back and set **Most attempts per request**.
7. Check **How a request flows**, then choose **Create router**.

The router appears under **Your routers**, and clients in every workspace can call its ID at once. If the form says the router is saved but clients can't call it yet, choose **Create router** again.

**HTTP API**

A router takes two requests: one creates it under an internal ID, and one gives it the model ID clients send. Each model is named by its route for each client API, the `groupId` of its rows in `sources` from `GET /control/compiled/addresses`, such as `openai-gpt-6-luna-chat` for `openai/gpt-6-luna` on OpenAI Chat Completions.

```bash
curl -sS -X PUT "$TOKEDEX_URL/control/compiled/model-groups/coding-fallback" \
  -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "strategy": { "reviewed": { "modelGroupStrategyId": "model-group.ordered.v1", "modelGroupStrategyVersion": "2.0.0" } },
    "members": [
      { "sourceGroupIds": { "openai.chat-completions": "openai-gpt-6-luna-chat", "openai.responses": "openai-gpt-6-luna-responses" } },
      { "sourceGroupIds": { "openai.chat-completions": "openai-chat-claude-haiku-5-5", "openai.responses": "openai-responses-claude-haiku-5-5" } }
    ],
    "maxRequestNativeAttempts": 2,
    "fallbackEligibleFailureClasses": ["rate-limited", "provider-unavailable", "timeout", "transport-error"],
    "enabled": true,
    "listed": true
  }'
```

The gateway answers `201` and saves the router without a callable ID. To check whether the draft can serve its shared APIs, send the same body to `POST /control/compiled/model-groups/preview`. If `addressProblem` says the models do not share a projection contract, their request or response handling differs on that client API. Use compatible routes on that API, or give the router an ID only on compatible APIs.

Give the router a model ID on each compatible client API:

```bash
curl -sS -X PATCH "$TOKEDEX_URL/control/compiled/addresses" \
  -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "changes": [
      { "clientDialectId": "openai.chat-completions", "address": "<router-id>", "entry": { "target": { "modelGroupId": "coding-fallback" }, "replaces": null } },
      { "clientDialectId": "openai.responses", "address": "<router-id>", "entry": { "target": { "modelGroupId": "coding-fallback" }, "replaces": null } }
    ]
  }'
```

Both answer with the whole routing table, where the router now lists its model IDs:

```json
{ "modelGroupId": "coding-fallback", "origin": "operator", "enabled": true, "listed": true,
  "addresses": [{ "clientDialectId": "openai.chat-completions", "address": "<router-id>" }, { "clientDialectId": "openai.responses", "address": "<router-id>" }] }
```

You need: an admin key with the `admin` or `operator` preset in `TOKEDEX_ADMIN_KEY`, and `export TOKEDEX_URL='http://127.0.0.1:4000'`.

A router cannot contain another router.

## See which model answered

Send a request to the router with `-i`. It calls a provider and can incur charges.

```bash
curl -sS -i "$TOKEDEX_BASE_URL/chat/completions" \
  -H "Authorization: Bearer $TOKEDEX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "<router-id>",
    "messages": [{ "role": "user", "content": "Reply with exactly the word \"hello\"." }]
  }'
```

When the first model's provider was rate limited, the second answered:

```text
HTTP/1.1 200 OK
x-tokedex-provider: anthropic
x-tokedex-model: anthropic/claude-haiku-5.5
x-tokedex-strategy: model-group.ordered.v1
```

The headers name the model that answered after any fallback, and the body's `model` stays the ID you sent. The key needs access to the router ID. In **Observability**, the request shows the router as its **Model alias**.

## Set a model's provider routing

A model served by several providers sends each request to the first connected provider in its order, and the next one takes it when a provider fails. Each client API of the model has its own order. The default order is the catalogue's: cheapest list price first, then the model maker's own provider, then provider ID. In an order you set, the providers you list come first and any you leave out follow in the default order. You set or reset the order of each client API separately, and it applies in every workspace; a client API with one provider has no order to set.

A request that sends its own [`x-tokedex-provider-order`](/gateway/models#prefer-providers) header tries the providers it names first, in its order, and the rest in this order, so set your order for what most of your traffic needs. A follow-up turn of a conversation, such as one carrying a tool result, tries each provider up to three times, a short wait apart, before it moves to the next: the provider keeps its prompt cache for the conversation, which makes the turn cheaper and faster.

**Dashboard**

Open the model in **Models & Routing**. Under **Provider routing**, each client API with more than one provider lists its providers in the order a request tries them, with each one's catalogue list price. The list is labelled **Default: cheapest, then first-party, then A–Z**, or **Custom · set by an operator** once an order is set.

To reorder a client API's providers where they are listed:

1. Drag a provider by its handle to its new place in the list. The list's label changes to **Custom · set by an operator**, or back to the default's label if the new order is the default.
2. Choose **Save**, or **Cancel** to put the saved order back. Only the client APIs whose order changed are saved.

From the keyboard, focus a provider's handle, press Space or Enter to pick it up, move it with the up and down arrow keys, and press Space or Enter to drop it. Escape puts it back where it was.

To reorder them in the editor, which also resets an order:

1. Choose **Change provider routing**. A model whose client APIs each have one provider does not show it.
2. In a client API's list, drag a provider by its handle, or move it up or down with its arrows. The list's label changes to **Custom · set by an operator**.
3. To return one client API to the default order, choose **Reset to default** under its list.
4. Choose **Save**. Only the client APIs whose order changed are saved.

On a touch screen, where dragging may not work, use the editor's arrows.

Providers without a key are skipped until they have one. A client API that now has one provider can keep an order saved from when it had more, which would apply again if a provider returns. **Provider routing** and the editor name each such client API, with a **Reset to default** that removes its order: under **Provider routing** at once, and in the editor when you choose **Save**, with any order you changed there. Until a dragged order is saved or cancelled, **Save** and **Cancel** take the place of **Change provider routing** and these resets.

**HTTP API**

Send `PATCH /control/compiled/source-edits/<group-id>` for each client API whose order you set, with the `groupId` of the model's row for that API in `sources` from `GET /control/compiled/addresses`. The gateway refuses an order for a route with one provider with `400`:

```bash
curl -sS -X PATCH "$TOKEDEX_URL/control/compiled/source-edits/<group-id>" \
  -H "Authorization: Bearer $TOKEDEX_MASTER_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "routing": { "providerOrder": ["<provider-id>", "<other-provider-id>"] } }'
```

`{ "routing": null }` restores the default order on that route. The gateway refuses an order naming a provider that does not serve the route with `400`.

Read the model's `routing` for the API you edited with `GET /v1/models/<model-id>?client_dialect_id=openai.responses`. URL-encode the full model ID, including its slash. Use the `client_dialect_id` from the model list and authenticate with a bearer API key.

`set_by` is `operator` for your order and `catalogue` for the default. `order` lists the route's ready providers in member order, filtered by the API key's provider access. A particular request can narrow the order further through its capabilities or provider options.

With the CLI, `tdx models providers list` lists the routes, and [`tdx models providers show --id <group-id>`](/cli/reference/models#tdx-models-providers-show) prints a route's order, who set it and each provider's list price. [`tdx models providers edit`](/cli/reference/models#tdx-models-providers-edit) sets an order with one `--provider-order` per provider, first tried first, or restores the default with `--default-order`:

```bash
tdx models providers edit --id <group-id> --provider-order <provider-id> --provider-order <other-provider-id>
tdx models providers edit --id <group-id> --default-order
```

On the gateway's own machine, the admin command saves the same order in the gateway's store without going through the server. It takes the providers as one comma-separated list:

```bash
tokedex-gateway source-edits order --id <group-id> --provider-order <provider-id>,<other-provider-id>
```

`--default-order` in place of `--provider-order` restores the default order. By default the command refuses to save while a running gateway holds the store. Add `--dry-run` to print the change without saving it.

## Strategies

| Strategy | Picks | `modelGroupStrategyId` | Needs | Use it when |
| --- | --- | --- | --- | --- |
| **In order** | The first model, then the next down the list | `model-group.ordered.v1` | Nothing extra | Start here: you choose the main model and its backups, so what answers stays predictable |
| **Cheapest** | The model with the lowest catalogue price | `model-group.cost.v1` | A catalogue price for each model | The models are interchangeable for the task |
| **Highest quality** | The model with the highest Artificial Analysis Intelligence Index | `model-group.quality.v1` | An Intelligence Index for each model | The answer matters more than its price |
| **Custom** | The models that pass your conditions, in the order you rank them by | None: name it in `strategy.operator` | The facts its conditions and ranking read | One condition is not enough, such as the cheapest model above an Intelligence Index floor |

With every strategy, the next model in line answers when the pick fails. A model missing what its strategy needs is never picked. With **Highest quality**, or a custom strategy that reads a benchmark, choose in each model's **Ranked at** list the variant, such as the reasoning effort, your requests run at.

A custom strategy keeps the models that pass its conditions on benchmark scores and prices, then ranks them; [Combine conditions in a custom strategy](#combine-conditions-in-a-custom-strategy) builds one. The router uses the variant you chose for each model, skips models missing a required measurement and keeps your model order when values tie.

If you limit providers on the router, its strategy or an individual model, a provider must meet all three sets of limits to be eligible. Only eligible providers contribute to the model's price. A strategy that blends input and output token prices needs the same input rate and the same output rate across those providers. Cached-input rates do not affect that calculation.

The same limits apply to the first request, retries, fallback, continuations and Batch jobs. If no provider qualifies, the router can refuse the request before contacting one.

## Combine conditions in a custom strategy

A custom strategy keeps only the models that pass its conditions, then ranks them. The built-in `aa/cheapest-40-intelligence` keeps every connected model with an Artificial Analysis Intelligence Index of at least 40 and ranks them by cost per task, cheapest first. This strategy, `cheapest-40-intelligence`, applies the same conditions to the models you list in your own router, and you can change the floor or the ranking. Save it as `strategy.json`:

```json
{
  "language": "strategy-tree.v1",
  "strategy": {
    "pipeline": [
      { "filter": { "intelligence": { ">=": 40 } } },
      { "sort": [{ "cost-per-task": "asc" }] }
    ]
  },
  "facts": {
    "intelligence": { "metric": "aa-intelligence-index.v5" },
    "cost-per-task": { "metric": "aa-intelligence-index.v5" }
  },
  "maximumNativeAttempts": 3,
  "fallbackEligibleFailureClasses": ["rate-limited", "provider-unavailable", "timeout", "transport-error", "context-length-exceeded"]
}
```

| Fact | Means | Range |
| --- | --- | --- |
| `intelligence` | Artificial Analysis Intelligence Index | 0 to 100 |
| `cost-per-task` | Published cost of one Intelligence Index task, in US dollars | 0 to 10,000 |
| `time-per-task` | Published time for one Intelligence Index task, in seconds | 0 to 86,400 |
| `price` | Catalogue price in US dollars per million tokens, input and output blended by the weights you set | 0 to 1,000,000 |

`pipeline` holds up to eight steps. A `filter` compares one fact with `>=`, `<=`, `>` or `<`, and `and` joins several, such as `{ "and": [{ "intelligence": { ">=": 40 } }, { "price": { "<=": 5 } }] }`. One `sort`, last, ranks by one to four facts, `asc` or `desc`. Declare in `facts` each fact the pipeline reads and no others: `intelligence`, `cost-per-task` and `time-per-task` take `{ "metric": "aa-intelligence-index.v5" }`, and `price` takes `{ "source": "token-blend", "priceBlend": { "inputWeight": 3, "outputWeight": 1 } }`. To rank by token price instead, sort by `price`. A router that uses the strategy can make at most `maximumNativeAttempts` attempts, and falls back only on failures from `fallbackEligibleFailureClasses`.

**Dashboard**

The dashboard lists custom strategies but cannot save or change one. Save `strategy.json` under the ID `cheapest-40-intelligence` with the request this page shows for the HTTP API, or with `tdx models routers strategies set` (see the [command reference](/cli/reference/models#tdx-models-routers-strategies-set) in the CLI docs). Then:

1. Open **Models & Routing → Routing** and choose **+ New router**.
2. Enter the **Model ID** clients will send, such as `<router-id>`.
3. Under **How should it choose?**, choose **Custom strategy**, then pick `cheapest-40-intelligence` under **Custom strategy to use**.
4. Under **Models**, add the models it chooses among, and set each one's **Ranked at** to the variant your requests run at, such as **high**.
5. Check **How a request flows**, then choose **Create router**.

Under **Custom strategies**, **See how it ranked** on `cheapest-40-intelligence` shows each model's place and why the others were left out, such as an Intelligence Index under 40.

**HTTP API**

```bash
curl -sS -X PUT "$TOKEDEX_URL/control/compiled/model-group-strategies/cheapest-40-intelligence" \
  -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" \
  -H "Content-Type: application/json" \
  --data-binary @strategy.json
```

The gateway answers `201`, or `200` when it replaces the strategy. A router names it in `strategy.operator`, and each model sets `rankingVariantId`, the variant your requests run at:

```bash
curl -sS -X PUT "$TOKEDEX_URL/control/compiled/model-groups/smart-and-cheap" \
  -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "strategy": { "operator": "cheapest-40-intelligence" },
    "members": [
      { "sourceGroupIds": { "openai.chat-completions": "openai-gpt-6-1-sol-chat", "openai.responses": "openai-gpt-6-1-sol-responses" }, "rankingVariantId": "high" },
      { "sourceGroupIds": { "openai.chat-completions": "openai-gpt-6-1-terra-chat", "openai.responses": "openai-gpt-6-1-terra-responses" }, "rankingVariantId": "high" },
      { "sourceGroupIds": { "openai.chat-completions": "openai-chat-claude-sonnet-5-5", "openai.responses": "openai-responses-claude-sonnet-5-5" }, "rankingVariantId": "high" },
      { "sourceGroupIds": { "openai.chat-completions": "openai-gpt-6-luna-chat", "openai.responses": "openai-gpt-6-luna-responses" }, "rankingVariantId": "high" }
    ],
    "maxRequestNativeAttempts": 3,
    "fallbackEligibleFailureClasses": ["rate-limited", "provider-unavailable", "timeout", "transport-error"],
    "enabled": true,
    "listed": true
  }'
```

Give it a model ID with the `PATCH /control/compiled/addresses` request at the top of this page. A router can make no more attempts than its strategy's `maximumNativeAttempts`, and fall back on no failure its strategy leaves out. To see how the strategy ranks the router's models:

```bash
curl -sS "$TOKEDEX_URL/control/compiled/model-group-strategies/cheapest-40-intelligence/explain?model-group=smart-and-cheap" \
  -H "Authorization: Bearer $TOKEDEX_ADMIN_KEY"
```

The cheapest model that passes ranks first, and a model under the floor is left out with its score:

```json
[{ "id": "smart-and-cheap", "available": true, "explanation": {
  "strategy": { "source": "operator", "id": "cheapest-40-intelligence", "digest": "sha256:<digest>" },
  "members": [
    { "model": "<model>", "outcome": "ranked", "position": 2, "metrics": { "cost-per-task": 0.590985 } },
    { "model": "<model>", "outcome": "ranked", "position": 1, "metrics": { "cost-per-task": 0.25928 } },
    { "model": "<model>", "outcome": "ranked", "position": 3, "metrics": { "cost-per-task": 1.636129 } },
    { "model": "<model>", "outcome": "excluded", "reason": "filter", "rule": "/strategy/pipeline/0/filter/intelligence", "test": { "intelligence": { ">=": 40 } }, "actual": 21.4 }
  ] } }]
```

`members` keeps the order you listed. With these four models, `openai/gpt-6.1-terra` ranks first, then `openai/gpt-6.1-sol` and `anthropic/claude-sonnet-5.5`, and `openai/gpt-6-luna`, at an Intelligence Index of 21.4, is left out. The scores and costs change as the catalogue does.

A request to the router names the strategy beside the model that answered:

```text
HTTP/1.1 200 OK
x-tokedex-strategy: cheapest-40-intelligence
x-tokedex-strategy-evidence: metadata@sha256:<digest>
```

`x-tokedex-strategy-evidence` names the benchmark and price data the ranking read.

The gateway refuses a strategy it cannot read with `400` `invalid_model_group_strategy` and lists each problem. It also refuses a router that no model qualifies for, and a strategy change that would leave a router using it with none. If a later catalogue leaves no model qualifying, the router stops answering and clients get `404` `model_not_found`: lower the floor or add models.

## Failures that fall back

**Dashboard**

A new router falls back on rate limits, timeouts, provider outages and connection errors. You can add **Prompt too long**; add it when your models have different context windows, so a long prompt moves to one that can take it. Any other error goes straight back to the client.

**HTTP API**

`fallbackEligibleFailureClasses` lists any of `rate-limited`, `timeout`, `provider-unavailable`, `transport-error` and `context-length-exceeded` (a prompt too long for the model). Add `context-length-exceeded` when your models have different context windows, so a long prompt moves to one that can take it. Any other error goes straight back to the client.

List models from more than one provider, so an outage or rate limit at one leaves another to answer.

The most attempts per request count the first try, from 1 to 16, so `1` turns fallback off. Start with one attempt per model; lower it when clients would rather fail fast, since each attempt adds the time the failed one took. Fallback reaches only models that support the features the request uses, such as tools, and a stream moves to the next model only before it sends any output.

For a self-contained text request, the router tries providers of the same model whose context windows fit the estimated input and requested output first. It keeps the configured order within each set. If any eligible provider has an unknown window, or the request uses media, stored context, a pinned continuation or token counting, the configured order applies.

**Prompt too long** triggers fallback when the provider returns HTTP 400 and identifies a context overflow. If the provider says that `max_tokens` is invalid, the router ends the request with that error.

## Built-in routers

| Model ID | Chooses |
| --- | --- |
| `aa/most-intelligent` | Eligible models by Intelligence Index, highest first |
| `aa/cheapest` | Eligible models by benchmarked cost per task, cheapest first |
| `aa/fastest` | Eligible models by benchmarked time per task, fastest first |
| `aa/cheapest-50-intelligence` | Eligible models with an Intelligence Index of at least 50, by benchmarked cost per task, cheapest first |
| `aa/cheapest-40-intelligence` | The same, at an Intelligence Index of at least 40 |
| `aa/cheapest-30-intelligence` | The same, at an Intelligence Index of at least 30 |

These routes use only providers you have connected. IDs that start with `aa/` are reserved. Give an application a router of its own when it must keep the same candidate list across releases.

**Dashboard**

Under **Built-in routers**, you can hide one from the model list or turn it off, then **Save changes**; you cannot change it. See [Your own model server](/gateway/custom-models#serve-a-model-under-your-own-id) to serve a model under an ID you choose.

**HTTP API**

`PATCH /control/compiled/model-group-edits/<id>` with `{ "enabled": false }` turns one off, and `{ "listed": false }` hides it, where `<id>` is its internal ID, such as `aa-intelligence` for `aa/most-intelligent`.

## Change or delete a router

**Dashboard**

Under **Your routers**, **Edit** opens the same form, and **Delete** removes the router and its ID. The **In /v1/models** and **Enabled** switches hide it from the model list or turn it off once you choose **Save changes** in the bar that appears. **See how it ranked** shows which models a strategy ranked or left out, and why. To give a router a different ID, create a new one.

**HTTP API**

Send the whole body again to the same `PUT` path; the gateway answers `200`. To delete it, first release each model ID with `"entry": null` in a `PATCH /control/compiled/addresses` change, then send `DELETE` to `/control/compiled/model-groups/<id>`. A router that still has a model ID is refused with `400`.

To give a router a different ID, add the new ID with a `PATCH /control/compiled/addresses` change and release the old one with `"entry": null`, in the same request.

Clients that call a deleted or turned-off router's ID get `404` `model_not_found`.

Next: [Find a model](/gateway/models), [Model access and limits](/gateway/model-access-and-limits) or [Prices](/gateway/spend-and-usage#prices).
