# Automatic routing

**Last updated:** 2026-11-25T02:41:33-03:00 (UTC-3)

An "auto" alias decides, for each request, which model serves it. A coding question goes to the coding model, math goes to the reasoning model, simple conversation goes to the cheap one, and an agent that keeps failing moves to a stronger model until it recovers. The client always calls the same alias, and you control the criteria. Flag: `auto_routing`.

There are three strategies:

| Strategy | How it decides | Extra cost |
| --- | --- | --- |
| Semantic (default) | Compares the user's last message with example phrases for each route, using embeddings | One embeddings call per request |
| `complexity` | Scores the text's complexity locally and picks a tier; optionally asks a classifier model | No call; about 0.15 ms for 2,000 characters. With a classifier, one chat call when it runs |
| `trajectory` | Reads what the agent's tools have been returning and moves the session one tier up or down; optionally asks a judge model about an undecided turn. Own flag: `tool_aware_routing` | No call; about 0.1 ms for a 50-message conversation ([measured](/docs/performance/trajectory-routing/)). With a judge, one chat call on an undecided turn |

Choose `semantic` when the topics are known in advance, `complexity` when the opening prompt says how hard the work is, and `trajectory` for coding agents and other tool loops, where the first prompt says little and the difficulty shows up during the run.

## Which APIs an auto alias serves

An auto alias serves Chat Completions (`/v1/chat/completions`), Messages (`/v1/messages`) and Responses (`/v1/responses`), the last two being what coding agents speak. It serves the capabilities it declares, and chat alone when it declares none:

```yaml
models:
  - id: agent
    capabilities: [chat, messages, responses]   # the surfaces this router answers on
    auto_route:
      strategy: complexity
      default: small
      tiers: {simple: small, complex: big}
  - id: small
    capabilities: [chat, messages, responses]   # every routed alias serves them too
    targets: [{provider: openai, model: gpt-4o-mini}]
  - id: big
    capabilities: [chat, messages, responses]
    targets: [{provider: openai, model: gpt-4o}]
```

- **Every routed alias serves every capability of the router.** The `default`, each route target and each tier alias must declare them all; otherwise the configuration is refused at boot and by the API, so a request is never routed to an alias that cannot answer it. A routed alias whose provider does not speak the dialect natively is translated, as it would be when called directly ([protocol translation](/docs/features/protocol-translation/)).
- **A surface the router does not declare** answers 422 `capability_unsupported`, before any helper call.
- **What the strategies read.** On each surface the router reads the same things: the text of the last user turn that has text (a turn made only of tool results is skipped), the assistant's tool calls and the tool results.
- **Stored Responses state is refused.** A request with `previous_response_id` or `conversation` answers 422 `stateful_route_unsupported`: that state lives at one provider under one model, the router cannot read it, and another tier could not continue it. Send the conversation in `input`, as coding agents do.
- **Everything else is the routed alias's.** Its rate limits, body limit, feature rights, retries, fallbacks, cache and prices apply; the router alias's own request rate limit is counted first.

## Semantic strategy

```yaml
models:
  - id: auto
    auto_route:
      embedding_model: embed      # alias with the embeddings capability
      default: general            # when no route passes the threshold
      max_input_chars: 2000       # optional
      routes:
        - name: code
          target: coder           # ordinary chat alias
          threshold: 0.55         # optional, 0.5 by default
          utterances:
            - write a python function
            - explain this stack trace
        - name: math
          target: mathy
          utterances: [solve this equation for x, what is the derivative of x squared]
```

| Key | Default | What it does |
| --- | --- | --- |
| `auto_route.strategy` | `semantic` | `semantic` compares embeddings with each route's examples; `complexity` scores the text locally; `trajectory` reads the agent's tool results (both below) |
| `auto_route.embedding_model` | required for `semantic` | Alias with the embeddings capability that embeds the examples and each prompt |
| `auto_route.default` | required | Alias that serves a prompt no route matches |
| `auto_route.max_input_chars` | `2000` | Longest prompt text, in characters, sent to the embedding or classifier model |
| `auto_route.routes[].name` | required | Route name, returned in `X-Gateway-Auto-Route` and recorded in the logs |
| `auto_route.routes[].target` | required | Ordinary chat alias that serves the prompts this route wins |
| `auto_route.routes[].description` | empty | Free text for the console |
| `auto_route.routes[].utterances` | required | Example prompts; each prompt is compared with them |
| `auto_route.routes[].threshold` | `0.5` | Minimum cosine similarity for the route to win; tune it per embedding model (see calibration) |

- **Access:** the key must be allowed to call `auto`. Only routes whose target the key can also call compete. With no allowed target, the response is 403.
- **Cost:** the embedding runs as the same key, with quota, ledger and RPM, and keeps the key's owner, so with identity ownership its spend is attributed to the same user or workload as the request it serves (the classifier call does the same). The examples are embedded once per version of the routes.
- **Team policy:** the key does not need the embedding alias in its own allowlist, but its team policy and organization ceiling must allow it, plus the `route:embeddings` scope, because the call sends the prompt to that provider. A team policy or organization that allows the `auto` alias without them is refused: at boot for the YAML, with 400 in the team policy editor, with 400 in the organization editor, and with 422 when an alias edit would open the gap against a stored policy. Without that check every request would silently go to `default`.
- **Response:** `X-Gateway-Auto-Route` carries the route name or `default`. The ledger and the logs record the chosen alias.
- **Embeddings model failure:** falls back to `default`, with no error for the client.
- **Calibration:** in the console, the model editor has **Test routing**. Through the API, `POST /api/v1/admin/auto-routes/test` with `{"model":"auto","text":"..."}` returns each route's score. With nomic-embed, off-topic prompts scored between 0.33 and 0.44 and on-topic ones between 0.50 and 0.71. With Amazon Titan Text Embeddings V2 on Bedrock the scale is much lower: off-topic prompts scored between 0.06 and 0.20 and on-topic ones between 0.21 and 0.37, so the 0.5 default routes nothing and a threshold near 0.2 leaves little margin; give each route more examples. A different model calls for different thresholds.
- **Scope:** Chat Completions, Messages and Responses, as declared in the alias's `capabilities` (above). Embeddings and every other operation on an `auto_route` alias respond 422.

## How much the router saved

Each routed request records the requested alias (`auto_route`), the most expensive candidate the key could use (`auto_route_baseline`), at the automatic price at that moment, and what the router chose and why (`auto_route_choice`, `auto_route_reason`). The **Auto-router usage** tab in the key detail compares the real cost with the baseline cost, per alias and per session, and shows the provider's prompt cache hit rate depending on whether the router kept, switched or went back to the model. Turns routed before the first price update after a restart have no baseline.

## Complexity strategy

With `strategy: complexity`, the alias scores the last message locally, without calling a model, and picks a tier.

```yaml
models:
  - id: smart
    auto_route:
      strategy: complexity
      default: small
      tiers: {simple: small, medium: mid, reasoning: big}   # complex missing → next most capable
      keyword_rules:
        - {keywords: [contrato, jurídico], tier: reasoning}
```

| Key | Default | What it does |
| --- | --- | --- |
| `auto_route.tiers` | required | Map of `simple`, `medium`, `complex` and `reasoning` to aliases; a missing tier uses the next more capable one |
| `auto_route.boundaries.simple_medium` | `0.15` | Score above which a prompt is at least `medium` |
| `auto_route.boundaries.medium_complex` | `0.35` | Score above which a prompt is at least `complex` |
| `auto_route.boundaries.complex_reasoning` | `0.60` | Score above which a prompt is `reasoning` |
| `auto_route.keyword_rules[].keywords` | required | Words or expressions; a prompt containing any of them goes straight to the rule's tier, before scoring |
| `auto_route.keyword_rules[].tier` | required | `simple`, `medium`, `complex` or `reasoning` |

- **Dimensions**, with the weights and the tier limits (0.15 / 0.35 / 0.60):
  - code (0.30);
  - reasoning (0.25);
  - technical terms (0.25);
  - length (0.10);
  - simple-question indicators (−0.05);
  - multiple steps;
  - many questions.

  The word lists cover English and Portuguese.
- **Whole words:** a single word counts only as a whole word ("api" does not match "capital"). Multi-word expressions match as a substring of the text.
- **Reasoning override:** two reasoning markers lead to the `reasoning` tier once the score passes the first limit.
- **Keyword rules:** `keyword_rules` decide before scoring.
- **Access:** a tier whose alias the key cannot call goes to `default`, never to a more capable tier.
- **Testing:** the endpoint and the console show the tier, the score and the signals.

## Classifier model

The local score reads keywords, so it can misjudge a short but hard question, or a long but routine one. A classifier model reads the request and names the tier instead. It can run on every request, or only where the local score is not confident, so you pay for it only on the traffic that needs it.

```yaml
models:
  - id: smart
    auto_route:
      strategy: complexity
      default: small
      tiers: {simple: small, medium: mid, complex: big, reasoning: deep}
      classifier:
        mode: local_first        # or model, near_boundary
        model: judge             # ordinary chat alias, ideally small and fast
        max_local_tier: simple   # local_first: the local score decides up to this tier
        timeout_ms: 3000         # optional, 3000 by default
        fallback: local          # optional: local (default) or default
```

| `mode` | When the classifier runs |
| --- | --- |
| `model` | On every request |
| `local_first` | When the local score lands above `max_local_tier` (`simple`, `medium` or `complex`) |
| `near_boundary` | When the score is within `boundary_margin` (0.05 by default, up to 0.5) of a tier limit, at any tier |

| Key | Default | What it does |
| --- | --- | --- |
| `auto_route.classifier.mode` | required | When the classifier runs: `model`, `local_first` or `near_boundary` (table above) |
| `auto_route.classifier.model` | required | Chat alias that names the tier |
| `auto_route.classifier.timeout_ms` | `3000` | Deadline of the classifier call; past it the local score (or `default`) decides |
| `auto_route.classifier.max_local_tier` | required for `local_first` | Highest tier the local score settles on its own |
| `auto_route.classifier.boundary_margin` | `0.05` | For `near_boundary`: distance from a tier limit, up to 0.5, within which the classifier decides |
| `auto_route.classifier.fallback` | `local` | What decides when the classifier fails: `local` (the scored tier) or `default` (the default alias) |

- **No evidence, no shortcut:** the local tier settles a request only when a keyword rule or a content dimension (code, reasoning, technical terms, simple-question indicators, multiple steps, many questions) fired. Length alone is not evidence: a short prompt such as `Solve for x: 3x^2 - 12x + 9 = 0` scores as `simple` only because it is short, so it goes to the classifier like a prompt where nothing fired.
- **Access and cost:** the classifier runs through the gateway as the calling key, restricted to the classifier alias, so quota, RPM and the ledger count it, with the request ID `<request_id>.classify`. The key does not need the classifier alias in its allowlist, but its team policy and organization ceiling must allow it, and a ceiling that allows the router without it is refused, as for the embedding alias.
- **What it sees:** a fixed rubric and the last user message, quoted and bounded by `max_input_chars`. The system prompt and earlier turns are not sent.
- **What counts as an answer:** only `{"tier": "<tier>"}` or the bare tier name. Anything else is a failure. No `response_format` is sent, so any chat model works.
- **Never widens access:** the chosen tier goes through the same check as a scored one. A tier the key cannot call goes to `default`. A prompt that asks the classifier for a higher tier can at most reach a tier the key may already use.
- **Failure:** a timeout, an error status or an unreadable answer falls back to the local score, or to `default` with `fallback: default`. A timeout or a 5xx also skips the classifier on that replica for 30 seconds; then one request tries it again. The chat request itself never fails because of the classifier.
- **Keyword rules** still decide first, without a call.
- **Testing:** the routing test shows whether the classifier decided (and its tier), was skipped because the local score was confident, or failed (and why). The test runs the classifier for real, so it is metered.

## Stall escalation

An agent working with a small model can get stuck calling the same tool with the same arguments. With `stall_escalation`, the router notices and sends the request one tier up.

```yaml
      stall_escalation:
        window: 6             # optional: tool calls to look at
        repeat_threshold: 3   # optional: repeats of the newest call that count as stuck
```

- The router looks at the assistant's tool calls in the request's own messages. It is stalled when the **newest** call, by name and arguments, appears `repeat_threshold` times among the last `window` calls. An agent that repeated a call and then moved on is not escalated.
- The request goes to the next **configured** tier above the one that would serve it, and only one tier. At the top, nothing changes.
- Nothing is stored: the next request is judged on its own messages, so the bump ends when the loop does.
- The decision carries the signal `stalled tool loop`. To see it in the routing test, send a conversation (`messages`) instead of a single prompt.
- It works the same on Chat Completions, Messages and Responses, and the `trajectory` strategy accepts the same block.

## Trajectory strategy

A coding agent sends its task once and then works for dozens of turns. What tells you whether the small model is coping is not that first prompt: it is what the tools return. With `strategy: trajectory` the router reads the newest tool results of each request and moves the session between the tiers:

- **up one tier** when the same failure comes back, on a critical error, right after the client compacted the conversation, or when the recent results are mostly failures;
- **down one tier** when the recent results are writes and passing checks;
- **to `default`** when nothing decides: no tool results yet, tools it does not know, a mixed picture.

Nothing is sent anywhere to decide this. The router reads the request it already has.

### Turn it on

```yaml
features:
  auto_routing: true
  tool_aware_routing: true        # off by default
  session_tracking: true          # optional: also records the session in the request log
models:
  - id: agent
    capabilities: [chat, messages, responses]
    auto_route:
      strategy: trajectory
      default: small              # where a session starts and where an undecided turn lands
      tiers: {simple: small, complex: big}
```

That is a complete configuration: every setting below has a default. `tiers` takes two to four of `simple`, `medium`, `complex` and `reasoning`, and `default` must be the alias of one of them, because "one tier up" is counted from it. With `tool_aware_routing` off, an alias with this strategy is refused at boot and by the API, and nothing else changes.

Have the client send a session identifier in `X-Gateway-Session-Id` (one value per agent run). Without it the router still works, but each request is judged alone and nothing is held (see Holds).

### What it reads

The router looks at the last `window` tool results, each with the call that produced it:

| It reads | Used for |
| --- | --- |
| The tool name | Its class: reads (`Read`, `Grep`, `Glob`, `LS`, web fetch and search), writes (`Edit`, `Write`, `MultiEdit`, `apply_patch`, the text editor tool) or planning (`TodoWrite`, `update_plan`, `Task`). The built-in list covers the common coding agents; add your own tools with `tool_classes` |
| The shell command inside a shell call (`Bash`, `shell`, `exec_command`, `local_shell`) | Whether it checks the work (`pytest`, `go test`, `npm test`, `cargo test`, `make` and `make test`, `npm run lint`, linters and compilers), writes (`sed -i`, `git commit`, `mv`, `rm`, any output redirected to a file) or reads (`ls`, `cat`, `grep`, `git diff`). `2>&1` and pipes are understood; a script or target whose name does not say it checks something (`make clean`, `npm run dev`) is left unclassified |
| The error flag | `is_error` of a Messages tool result, the exit code of a Responses shell output, a failed patch |
| The result text | Only where it is the tool's own verdict: the output of a shell command that is not a plain read (`exit code 1`, a traceback, a line starting with `FAILED` or `error:`), or any result that opens with `Error:`. A file the agent reads may contain the word "error" and is not a failure |

It does not read tool schemas or the `tools` array. Images and other non-text results cannot be read: a window with one is undecided.

### How it decides

1. **A hold is active** (below): the session stays where it is.
2. **Overrides, one tier up:** the newest result is a failure that already appears in the window, from the same call with the same message apart from numbers such as timings (`repeated_failure`; a test that now fails for another reason is progress, not a repeat), the newest result is a critical error such as a panic or out of memory (`critical_error`), the last user message carries one of your `compaction_markers` and no tool ran since, or `stall_escalation` is set and the agent repeats the same call.
3. **Otherwise the score.** Each failure in the window pushes up (a warning a little, an error more, a critical error most; a failure that a later passing check resolved counts half). Each write and each passing check pushes down. A full window of only looking around, with no write, no check and no failure, pushes up a little. The sum is squashed to a confidence between -1 and 1. At or above `confidence_threshold` the session goes one tier up; at or below its negative, one tier down.
4. **Inside the band** the turn is undecided: the judge decides if you configured one, else `default` serves.

So one failed test run alone changes nothing (confidence 0.46), and neither does a file that is not there while the agent looks around; the same failure twice escalates, two different failures in the window escalate through the score, and an edit followed by a passing run brings the session back.

**A turn sent twice counts once.** A client retry or a parallel request carries the same conversation as the request before it. The router recognizes it (same length, same newest tool call and result, same last user text), serves it as the first one was served, and does not move the tier or use a turn of a hold. The response says `repeat`.

Moves are one tier at a time, to the next **configured** tier. At the top or the bottom the session stays. An undecided turn outside a hold is served by `default`, and the session is back on the default's tier.

| Turn | Tool results so far | Served (tiers `simple: small`, `complex: big`) | Why |
| --- | --- | --- | --- |
| 1 | reads a file | `small` | no decision |
| 2 | + a failing test run | `small` | one failure is inside the band |
| 3 | + the same failure | `big` | repeated failure |
| 4 | + the same failure again | `big` | held |
| 5 | + an edit | `big` | held |
| 6 | + a passing test run | `small` | writes and a passing check |

### Holds

Every switch of model leaves the provider's prompt cache behind, because that cache is per model. A session that bounces between tiers on every noisy result can cost more than staying on the big model. Holds keep a session still:

- **After moving up**, the session stays on that tier for `hold.escalation_turns` requests (2 by default), whatever their history says, and the one after is scored again.
- **After coming down**, it stays on the cheaper tier for `hold.min_cheaper_turns` requests (0 by default) before a signal may take it up again.

A hold belongs to one session: the value of the session header, under one key, one team and one organization. The same session value sent by another key, another team or another organization is another session, and neither reads nor changes the first. The state is kept per replica, bounded by `hold.max_entries` and `hold.ttl`; with `shared_routing_state` on ([shared routing state](/docs/features/routing-and-admission/)) it is shared across replicas and survives restarts, through the same tables as routing affinity, where a row is a keyed digest and 32 bytes and names no session, key or model. A hold written on one replica reaches the others on their next sync (`routing_state.sync_interval`).

**Without the session header there are no holds**: the request is judged from the default tier on its own history, and the status page counts those requests so you can tell. A request with several values in the header, or a value that is not 1 to 256 visible ASCII characters, counts as having none.

### Settings

Every key is optional except `strategy`, `default` and `tiers`.

| Key | Default | What it does |
| --- | --- | --- |
| `auto_route.trajectory.window` | `3` | How many of the newest tool results are read, 1 to 20. A larger window remembers failures longer |
| `auto_route.trajectory.confidence_threshold` | `0.5` | How far from zero the score must be to move the tier, above 0 up to 1. Higher moves less often and leaves more turns to `default` or to the judge |
| `auto_route.trajectory.overrides.repeated_failure` | `true` | Go one tier up when the newest failing result repeats in the window. Set `false` to leave it to the score |
| `auto_route.trajectory.overrides.critical_error` | `true` | Go one tier up when the newest result is a critical error. Set `false` to leave it to the score |
| `auto_route.trajectory.overrides.compaction_markers` | empty (off) | Up to 16 strings of 8 to 200 characters that your client writes in the user message that replaces a compacted conversation, for example the opening words of its summary. On the request right after one, the tier goes up, since the model now works from a summary |
| `auto_route.trajectory.tool_classes.observe` | empty | Names of your tools that read state (search, list, fetch); up to 100 |
| `auto_route.trajectory.tool_classes.mutate` | empty | Names of your tools that change state (create, update, delete); a successful call counts like a write |
| `auto_route.trajectory.tool_classes.plan` | empty | Names of your tools that organize the work without touching state |
| `auto_route.trajectory.tool_classes.neutral` | empty | Names of tools to ignore, also when the built-in list knows them |
| `auto_route.trajectory.hold.escalation_turns` | `2` | Requests the session stays on the tier it moved up to, 0 to 50; `0` turns the hold off |
| `auto_route.trajectory.hold.min_cheaper_turns` | `0` | Requests the session stays on a cheaper tier after coming down, 0 to 50 |
| `auto_route.trajectory.hold.header` | `X-Gateway-Session-Id` | Request header that carries the session identifier: letters, digits and dashes, never a credential header |
| `auto_route.trajectory.hold.ttl` | `1h` | How long a session's state lives after its last request, `1m` to `24h` |
| `auto_route.trajectory.hold.max_entries` | `10000` | Sessions tracked per replica for this alias, 100 to 100000; past it the least recently used is dropped. All trajectory aliases together may ask for at most 200000 |
| `auto_route.classifier` | none | The judge for undecided turns (below): `mode: ambiguous`, `model`, `timeout_ms` |
| `auto_route.stall_escalation` | none | Same block as in `complexity`: a repeated tool call counts as an override |

Tool names in `tool_classes` match exactly, ignoring case, with or without an `mcp__server__` prefix (`update_inventory` also matches `mcp__warehouse__update_inventory`). A name may appear once across the four lists; a duplicate or an empty name is refused. A full example for a non-coding agent:

```yaml
    auto_route:
      strategy: trajectory
      default: mid
      tiers: {simple: small, medium: mid, complex: big}
      trajectory:
        window: 5
        tool_classes:
          observe: [kb_search, get_order]
          mutate: [update_inventory, refund_order]
        hold: {escalation_turns: 3, min_cheaper_turns: 1}
```

With these lists, three successful `update_inventory` calls take the session from `mid` down to `small`; without them the router does not know the tool and `mid` serves.

### Judge for undecided turns

By default an undecided turn goes to `default`, with no model call. You can have a small chat model decide those turns instead:

```yaml
      classifier:
        mode: ambiguous          # the only mode of this strategy
        model: judge             # ordinary chat alias, ideally small and fast
        timeout_ms: 3000         # optional
```

- **When it runs:** only on a request with tool results whose score is inside the band, outside a hold. A request without tool results, a decided turn and a held turn never call it.
- **What it sees:** the last user message, bounded by `max_input_chars`, and the kind and outcome of the recent tool results (for example `1. check: error`, `2. write: ok`). Tool output, tool arguments and tool names are never sent.
- **What its answer does:** it names a tier, and the session moves **one** tier towards it, or stays when the judge names the tier the session is on.
- **Failure:** a timeout, an error or an unreadable answer leaves the turn undecided, so `default` serves. The request never fails because of the judge.
- **Access and cost:** as for the complexity classifier, it runs as the calling key restricted to the judge alias, with request ID `<request_id>.classify`; the team policy and organization ceiling must allow the judge alias and the `route:chat` scope.

### Access

- A tier the key cannot call is served by `default`, never by that tier or another one, also under an override or a hold. The response says `tier_not_permitted`.
- With no permitted `default`, the response is 403.
- The conversation is client data: a client that invents failures can at most reach an alias its key may already call, and budgets, rate limits and the ledger count the request as usual.
- `tool_aware_routing` is a model-policy right of the team plan, like `auto_routing`.

### What the response and the telemetry say

| Where | What |
| --- | --- |
| `X-Gateway-Auto-Route` | The tier that served (`simple`, `medium`, `complex`, `reasoning`) or `default` |
| `X-Gateway-Auto-Route-Reason` | `signals` (the score), `override`, `hold`, `judge`, `default` (nothing decided), `repeat` (the same turn sent again) or `tier_not_permitted` |
| `X-Gateway-Auto-Route-Transition` | With a session: `first` (first routed request of the session), `kept` (same model as the previous request), `switched` (a model the session had not used) or `back` (a model it used earlier). `kept` is the only one where the provider's prompt cache can still be warm |
| Request log and request events | `auto_route_choice`, `auto_route_reason` and `auto_route_transition`, beside `auto_route` and `auto_route_baseline`; shown in the request journey |
| Request span | `gateway.auto_route.strategy`, `.tier` (`.route` for a semantic route name), `.reason`, `.baseline`, `.detail`, `.override`, `.direction`, `.transition`, `.confidence`, `.hold_remaining`, `.window_results` and `.stateless`, stored and exported over OTLP with the span |
| Metrics | Below |

None of them carries tool output, a tool argument, a tool name or the session value.

| Metric | Labels | What it counts |
| --- | --- | --- |
| `gateway_auto_route_decisions_total` | `alias`, `strategy`, `route`, `reason` | Decisions of every strategy |
| `gateway_auto_route_decision_duration_seconds` | `strategy` | Time of the decision (histogram); a strategy that calls a model includes the call |
| `gateway_auto_route_switches_total` | `alias`, `direction` (`up`, `down`) | Requests on which a session moved to another tier |
| `gateway_auto_route_cache_turns_total` | `alias`, `transition`, `cache` (`hit`, `miss`, `unreported`) | Answered trajectory requests by what they did to the prompt cache and whether the provider reported a cache read; `transition` is `unknown` without a session |
| `gateway_auto_route_tokens_total` | `alias`, `transition`, `kind` (`input`, `cached_input`, `output`) | Tokens of those requests |
| `gateway_auto_route_cost_usd_total` | `alias`, `transition`, `kind` (`actual`, `baseline`) | Estimated cost at the current automatic price: what was paid and what the most expensive candidate would have cost |
| `gateway_auto_route_sessions`, `gateway_auto_route_holds_active` | `alias` | Sessions tracked and sessions currently held, on this replica |
| `gateway_auto_route_stateless_total` | `alias` | Requests judged without a session, so without holds |

To see whether switching pays, compare the cache hit rate of `kept` with `switched` and `back`, and `actual` with `baseline`:

```promql
sum by (transition) (rate(gateway_auto_route_cache_turns_total{alias="agent",cache="hit"}[1h]))
  / sum by (transition) (rate(gateway_auto_route_cache_turns_total{alias="agent",cache!="unreported"}[1h]))
```

The **Auto-router usage** tab of a key shows the same comparison per session from the request log (see "How much the router saved"). If `back` and `switched` rarely hit the cache and the saving is small, raise `hold.escalation_turns` or `hold.min_cheaper_turns`, or raise `confidence_threshold`.

### Status and testing

- **Status:** Providers → Routing shows, per trajectory alias, the sessions tracked on the answering replica, how many stand on each tier, how many are held and how many requests came without a session. API: `GET /api/v1/admin/routing-status`, field `trajectory`.
- **Test a conversation:** in the model editor, **Test routing** takes a Chat Completions conversation as JSON. Through the API, `POST /api/v1/admin/auto-routes/test` with `{"model":"agent","messages":[...]}` returns the tier, the confidence, the signals (counts such as `errors ×2`, never tool names or output), the override or the reason nothing was decided. Add `"position":"complex","hold":1` to test a turn as a held session would see it. The test writes no session state; a judge, when it runs, is metered.

### Limits

- The rules are fixed and readable, not learned. Whether a routed pair gives the quality you need at a lower cost depends on your agents and models: measure it on your traffic with the metrics above before relying on it. The gateway publishes no saving figure for it.
- The state is advanced when the request is routed, so a turn that is then refused or fails at the provider still counted. Sending that same turn again does not count a second time.
- A canary shadow copy of a routed request goes to the alias that served the original; it is not decided again and counts no turn.
- Two replicas serving the same session between two syncs each see the hold as of the last sync; a hold can therefore last a request or two longer, never shorter than on one replica.
- Text heuristics are in English, like the tools' own output.

## Limits

- Chat Completions, Messages and Responses only, as the alias declares. Embeddings and other operations on an `auto_route` alias respond 422, and so does a Responses request with stored state.
- The router never promotes the key to a model it cannot use: a route or tier without permission falls back to `default`.

## See also

- [Cost, occupancy, tags and fallbacks](/docs/features/routing-strategies/).
- [Usage valuation](/docs/features/usage-valuation/): where the cost compared with the baseline comes from.

## Complete console policy editing

The existing model routing editor also exposes prompt-character limits (default 2,000, up to 20,000), semantic route descriptions (up to 500 UTF-8 bytes), complexity boundaries, keyword rules, classifier options and stall escalation. They use the same typed `auto_route` contract and model override transaction as YAML/API; this adds no routing strategy or automatic classifier/provider call. Existing helper aliases and caller permissions are still validated.

Complexity boundary defaults are `0.15`, `0.35` and `0.60`, strictly increasing. Keyword rules select the minimum tier when a configured word is present. One-per-line controls retain a typed newline while sending only nonempty entries, and rebuilding the strategy clears the previous strategy's draft boxes. Invalid snapshots are refused before publishing; explicit preview/testing retains its existing authorization and upstream-call behavior.


## Shared policy definitions

The automatic router retains its typed strategy, tier, reference and cross-field rules. Required aliases and examples belong to the routing policy. Thresholds keep their existing field-specific defaults; an omitted or zero semantic route threshold selects `0.5`. These policy values are not credentials or a universal routing default. Shared [parameter definitions](/docs/reference/parameter-registry/) describe consumed constraints without authorizing a helper model, changing the scoring formula or bypassing the team and organization ceilings. A form creation preset remains separate from the effective backend default.

Semantic route thresholds and near-boundary classifier margins must be finite numbers. YAML `NaN` and infinities are rejected, retaining the existing finite ranges and zero-to-default behavior.

The console accepts continuous finite threshold/margin/boundary values without rounding to an input step. Complexity boundaries must still increase strictly within `(0, 1]`. Raw zero remains available for existing default selectors: prompt characters, classifier timeout and stall window/repetition threshold. The backend still rejects invalid nonzero timeout ranges and inconsistent stall settings.
