11B.5 Model Selection and Routing
A production LLM feature rarely runs on one model. The support bot answers a password-reset question and a contract-review request through the same endpoint; the nightly summariser processes ten thousand documents that are 95% routine and 5% genuinely hard; the classifier sees a hundred languages and three user tiers. Sending everything to the frontier model is the simplest correct design and also the most expensive one; sending everything to the cheapest model is the most expensive mistake you can make, because the failures it produces cost more than the savings. Model selection is the decision of which model should serve which kind of work, made once, offline, from evidence. Routing is the machinery that makes that decision per request, at runtime, cheaply and observably. This lesson covers both: how to choose models per task from your own eval set, the full taxonomy of routing patterns (static, rule-based, cascades, classifiers, learned routers, provider and gateway routing, canaries), how to build and evaluate a router in llm_service/router.py, how to keep prompts portable across the models a router can pick, and how to govern model choice so that "which model is allowed to serve what" stays a reviewed, auditable decision rather than a config drift.
What you'll learn
- The difference between model selection (offline, per task) and model routing (online, per request), and why you need both
- How to decompose a workload into routable tasks, and how to read the quality–cost–latency frontier off your own eval set instead of a leaderboard
- Capability checks and hard constraints (modalities, tools, structured output, context, data policy, licences) as routing gates
- Version pinning vs aliases, deprecation calendars and migration playbooks as an operations routine
- Every routing pattern in production use, with code: static, rule-based, weighted/canary splits with sticky hashing, cascades that escalate on quality signals, embedding-kNN and LLM-as-router classifiers, learned routers (RouteLLM-style, vLLM Semantic Router), hosted routers (OpenRouter Auto, Azure model router, Amazon Bedrock prompt routing, Cloudflare), and gateway routing (LiteLLM, Portkey, Kong, Vercel)
- How to evaluate a router: oracle bound, regret, cost-at-equal-quality, per-slice analysis, and the leakage pitfalls that make routers look better than they are
- Prompt portability across routed models, and per-model prompt variants with versioning
- Governance: allow-lists, model inventory, deprecation tracking and per-route cost caps
What you don't need
- API keys. Every part of the routing layer runs with fakes and labelled tables; the provider-facing pieces are reference code you can run later against the free local stand-in from lesson 03.1, Part 12.
- A running observability platform. Decision logging is plain JSONL; dashboards and alerting are lesson 11A.1 and lesson 11A.2.
- Fine-tuning. Learned routers are covered at the level you need to evaluate and adopt them; training your own is out of scope.
- Retries, timeouts and circuit breakers. Those belong to lesson 03.8, lesson 03.11 and lesson 11C.3; this lesson assumes a client that already retries and falls back on errors, and adds the layer that decides which model to try in the first place and when a technically successful answer should be escalated anyway.
Setup
This lesson's code is pure Python 3.11+ standard library — no SDKs, no keys, no services. It slots into the module's running project, llm_service, alongside the provider_agnostic client from lesson 03.11 and the evalkit package from Module 10A. If you are starting the service fresh:
uv init llm-service --bare --python 3.13 && cd llm-service
uv add pydantic python-dotenv
# The provider clients come from lesson 03.11's provider_agnostic package;
# eval data comes from Module 10's evalkit. Both are plain packages you copy in.The .env file is only needed when you point the service at real providers later:
# .env (never commit this file)
OPENAI_API_KEY=...
ANTHROPIC_API_KEY=...
GEMINI_API_KEY=... # optional
OPENROUTER_API_KEY=... # optional gatewayWhat you must be able to do after this lesson#
- Explain the difference between model selection (offline, per task) and routing (online, per request)
- Decompose a workload into routable tasks and read the quality, cost and latency frontier per slice
- Gate a model into a route with capability and data-policy checks
- Implement a weighted split with a stable user hash for canary traffic
- Choose a routing pattern: static, rule-based, cascade or learned
- Evaluate a router with the oracle bound, regret and cost at equal quality, and avoid label leakage
- Treat a prompt version and a model version as one release unit and keep an allow-list
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
| "Should we just use the biggest model for everything?" | 1.3 The frontier from your eval set |
| "The cheap model is fine for 90% of traffic." | 1.2 Decomposing the workload |
| "Route by rules: images go to the vision model, long docs to the long-context one." | 2.4 Rule-based routing |
| "Start cheap, escalate if the answer looks wrong." | 2.9 Cascades |
| "Train a classifier to pick the model." | 2.10 Classifier routers |
"What is openrouter/auto?" |
2.11 Hosted and learned routers |
| "Our gateway already does fallbacks — isn't that routing?" | 2.2 What a router decides and 2.12 Gateway routing |
| "How do we A/B a new model without a big-bang switch?" | 2.5 A/B and canary routing |
| "Is the router actually saving money at equal quality?" | 4.1 Evaluating a router |
| "The prompt worked on Sonnet but broke on Haiku." | Part 5: Portability |
| "Who approves adding a new model to production?" | Part 6: Governance |
Part 1: Choosing the model for each task#
1.1 Selection is offline; routing is online#
Two decisions share the word "model choice", and confusing them is the most common planning mistake in LLM systems.
- Selection happens before launch and on a schedule: which models are candidates for each kind of work, evaluated on your data, pinned in configuration. Its outputs are a model inventory (6.3) and a set of routes — named lanes like
ticket_triage,contract_extract,chat_answer— each bound to an ordered chain of acceptable models. - Routing happens per request: given this request's signals, which route (or which model inside a cascade) serves it. Its outputs are a
RouteDecisionlogged with the request (3.6).
Lesson 02.9, Part 10 taught the selection framework — requirements, constraints, shortlist, evaluate on your data, pick primary plus fallback, operate. This lesson assumes that framework and goes deeper on the parts a production system adds: decomposing the workload into routable units, reading the quality–cost–latency frontier off an eval set, treating capabilities and data policy as hard gates, and running version and deprecation management as a routine. Lesson 02.9, 10.6 previewed routing and cascades; lesson 04.8, 2.4 gave the prompt pattern for an LLM-based router. Everything from here down is the production version.
1.2 Decomposing the workload into routable tasks#
A "task" in routing terms is a slice of traffic with a distinct quality bar, cost profile and latency budget. The first step of selection is drawing those boundaries. The useful decomposition axes:
| Axis | Example slices | Why it matters |
|---|---|---|
| Function | classify, extract, summarise, answer, draft, code-review, translate | Different capability mixes; a model good at extraction can be poor at chat |
| Difficulty | easy / medium / hard within one function | The whole point of cascades: most traffic is easy |
| Modality | text-only vs image/PDF/audio/video input | Capability gate; only some models accept media |
| Context size | short prompts vs 200k-token documents | Context window and long-context quality both vary |
| Language / locale | English vs Hindi/Tamil/other | Token cost and quality both differ per language (02.9, worked example) |
| User tier | free vs paid vs enterprise | Different SLOs and different willingness to pay for quality |
| Risk | reversible draft vs irreversible action (send email, post payment) | Escalation and human-review thresholds differ |
A useful output of this step is a route table: one row per routable slice, naming the alias it will use, the quality bar, and the constraints. This is also the input to the model inventory in 6.3.
| Route | Slice | Quality bar | Latency budget | Notes |
|---|---|---|---|---|
chat.fast |
FAQ, greetings, simple how-to | "correct and on-policy" | TTFT < 1.5 s | Highest volume; cache-friendly |
chat.smart |
policy questions, multi-step help | "complete and grounded" | TTFT < 3 s | Escalation target of chat.fast |
extract.invoice |
invoice → line items | schema-valid + totals correct | < 10 s | Structured output required |
summarize.long |
100k+ token docs | faithful, covers key points | < 60 s, async OK | Long-context model or map-reduce |
code.review |
PR review comments | catches real bugs, low noise | < 30 s | Frontier or strong reasoning tier |
1.3 The quality–cost–latency frontier from your eval set#
02.9, 7.6 established that leaderboards and benchmarks cannot pick your model: they measure someone else's data. Selection in production is a frontier problem: each candidate model produces a point (quality, cost_per_task, latency) measured on your eval set, and you pick the cheapest point that clears your quality bar with margin.
The mechanics, concretely:
- Fix the eval set first. The same
evalkitdataset (Module 10A, 10A.2) runs against every candidate. Scores must be comparable — same scorer, samerepeats, same decoding settings. - Measure all three axes per model. Quality from the eval; cost from
usage× your price table (03.7, Part 3); latency as p50/p95 of total time (and TTFT where streaming matters, 11A.2 owns the SLO framing). - Plot the frontier. A model is dominated if another is better on quality and cheaper (or equal quality at lower latency). Drop dominated models from the shortlist.
- Pick with margin, not at the edge. Choose the cheapest model whose quality is comfortably above the bar — provider behaviour drifts (02.9, 8.1 notes even pinned snapshots can shift), and a model sitting exactly at the threshold will fall below it.
Worked example (illustrative numbers — compute your own): a support feature with two candidate tiers, evaluated on 200 labelled tickets.
| Model | Quality (pass rate) | Cost/task | p95 latency |
|---|---|---|---|
fast tier (small model) |
0.86 | $0.0012 | 1.1 s |
smart tier (mid model) |
0.94 | $0.0060 | 2.8 s |
| frontier tier | 0.96 | $0.021 | 6.4 s |
Quality bar: 0.90. The frontier tier is dominated on cost for this bar (smart clears it at 3.5× less). Between the remaining two: if 80% of traffic is easy, a cascade that sends easy tickets to fast and escalates failures to smart lands near $0.80×0.0012 + $0.20×(0.0012+0.0060) ≈ $0.0024/task at ≈0.93 quality — beating either single model on the cost–quality plane. That arithmetic is exactly what 3.7 computes for real.
1.4 Capability checks as gates#
Before any quality or cost comparison, a candidate model must be able to do the job. Lesson 03.11, Part 7 built the capability registry for exactly this: models.yaml maps each route entry to provider, API, context window, output limits and a Capabilities record (tools, forced tool choice, structured output, images, documents, reasoning, stream usage, stop sequences, parallel tool switch, strict tools). check_capabilities(req, spec) raises before anything is sent rather than letting an adapter silently drop a feature the model doesn't support.
In selection, treat capabilities as gates, not preferences:
- A route that needs vision can only list models with
images: true; a route needing strict JSON can only liststructured_output: truemodels — and even then, each provider's subset of JSON Schema differs (03.4, Part 4). - A route needing forced tool choice must respect
forced_tool_choice: falseentries (Claude Sonnet/Opus 5.x return a 400 forany/toolchoice — 03.5, 3.3). - Context window is a gate on input size:
context_windowminus your system prompt, history andmax_output_tokensmust exceed the largest request the route will see — including the escalated retry inside a cascade. - Reasoning models need headroom in
max_output_tokensfor thinking tokens (02.8); a route tuned for 500-token answers can silently truncate on a reasoning model.
1.5 Hard constraints: data policy, residency and licences#
Some constraints eliminate candidates before quality is measured. 02.9, Part 9 owns the privacy overview; for routing, the operational consequences are sharper:
- The fallback must not violate the policy. If a route's data may only go to zero-data-retention endpoints, its fallback chain and its gateway's provider preferences must enforce
zdr: true/data_collection: "deny"too — an outage is exactly when a permissive fallback leaks data. 02.9, 10.5 says pick a different provider for resilience; the privacy corollary is pick a different provider that honours the same data terms. - Residency is per route, per provider, per endpoint. OpenRouter's in-region routing,
provider.only/ignore,order,quantizationsandmax_priceare request-level controls (02.9, 5.4); record which were used, because "we used OpenRouter" is not an answer to "where was the data processed". - Open-weight licences constrain use. Some community licences restrict commercial use or require attribution; check the licence for each self-hosted or hosted open model (02.9, 3.3, lesson 11C.6).
- Terms can forbid the pipeline. Distillation and training-on-outputs clauses matter if your router's "eval" or "judge" calls feed a fine-tune (02.9, 9.6).
Encode these as fields on the route definition (data_policy, regions, requires_zdr) and check them in the router itself — a rule that lives only in a wiki page will be violated by the first person in a hurry.
1.6 Versions: pinning, aliases and deprecation calendars#
02.9, Part 8 owns the mechanics — aliases vs snapshots, lifecycle stages, notice periods, and the seven pinning rules. What production adds:
- A route pins a snapshot, and the route's name is the alias. Your application says
model="chat.smart"; the route definition maps that toclaude-sonnet-5-5(a pinned snapshot on Anthropic, since 4.6-generation IDs are dateless-but-fixed) or to an ordered provider_agnostic alias chain (smart: [sol, sonnet]). Migration then means editing the route definition — one reviewed change — not hunting model IDs through code. - Deprecation is a scheduled migration, not an incident. Providers publish notice periods (OpenAI ≥6 months GA / ≥3 months specialised / ~2 weeks preview; Anthropic ≥60 days; Google ≥2 weeks preview; OpenRouter
expiration_datein the catalogue — 02.9, 8.2). The routine: a daily/weekly check of configured routes against the lifecycle APIs (the lifecycle-check script in 02.9, 8.3 is the pattern;provider_agnostic/refresh.pydoes the same for registry entries), an alert at a threshold (say 90 days), and a migration runbook per route. - The migration runbook is eval-gated. Candidate replacement → run the route's eval slice → compare quality, cost, latency → canary (2.5) → full cutover → keep the old route defined for rollback window → remove. 04.9, 4.3 is the prompt-side checklist; the model-side version adds price and latency deltas to the score sheet.
- Silent drift still happens on pinned snapshots (serving infrastructure, safety classifiers, API-version changes — 02.9, 8.1). Continuous quality monitoring (11A.2, 10A.9) is the detector; pinning only removes announced change.
1.7 The model inventory#
Selection produces an artefact that governance (Part 6) and incident response both need: the model inventory — one row per route × model pair actually allowed to serve production traffic:
| Field | Example | Why it's there |
|---|---|---|
| Route | extract.invoice |
which slice it serves |
| Model entry / snapshot | luna → gpt-6-luna |
what actually runs |
| Provider + API | openai / responses | failure-domain and capability context |
| Purpose | "primary", "fallback", "judge", "embedder" | judges and embedders are models too — they need the same lifecycle care |
| Data policy | zdr-required, no-retention, standard |
audit answer for compliance |
| Owner | team or person | who gets paged |
| Eval result | quality 0.94, cost $0.006, p95 2.8 s, evalset evals/v3 |
the evidence for keeping it |
| Status | active, canary, deprecated-pending, retired |
lifecycle state |
| Added / review-by | dates | forces periodic re-evaluation |
Keep it in version control next to the route config (it is configuration), and generate the route table views from it rather than maintaining two lists.
Part 2: The routing patterns#
2.1 Where the router sits#
A router is a decision layer between your application code and the model calls. It never generates text itself (except when the router is an LLM — see 2.10); it inspects the request and returns a decision: which route, which model, which provider hints, and why.
flowchart TB
req["Incoming request<br/>(feature, user, messages, files)"] --> app["Your application<br/>extracts RouteFeatures"]
app --> router{"Router<br/>rules · classifier · learned · gateway"}
router -->|"RouteDecision:<br/>alias + provider hints + reason"| sel["Model selection<br/>alias → ordered chain"]
sel --> client["LLMClient (03.11)<br/>retries, deadline, error fallback"]
client --> resp["Response + cost + attempts"]
resp --> log["Decision log (JSONL)<br/>decision ↔ outcome join"]
router -.->|"decision record"| logThree placement options, often combined:
- In your application (this lesson's
llm_service/router.py): full control, unit-testable with fakes, sees your auth context (user tier, tenant, feature). Costs you the engineering. - In a self-hosted gateway (LiteLLM proxy, Portkey gateway, vLLM Semantic Router): routing logic lives next to the provider keys; good when several services share models. Adds a hop and a config surface outside your codebase.
- In a hosted gateway/aggregator (OpenRouter, Cloudflare AI Gateway, Vercel AI Gateway, Azure model router, Bedrock prompt routing): zero infrastructure, but the decision logic is the vendor's and your visibility is whatever they log.
2.2 What a router decides, and when#
Every routing pattern answers the same five questions differently:
| Question | Options |
|---|---|
| When | Before the call (pre-routing), after a failed/weak first attempt (cascade), or both |
| Signal | Request metadata you already have (feature, tier), cheap request features (length, language, modality), a classifier model, a learned router, or the provider/gateway itself |
| Granularity | Per feature (static), per request (dynamic), per user (sticky), or per deployment (load balancing) |
| Failure domain | One provider, many providers, or "whoever is cheapest/right now" |
| Evaluability | Can you replay decisions offline and score them? (Rules and logged features: yes. Vendor black boxes: only through their logs.) |
A crucial distinction the industry blurs: error fallback ≠ routing. 03.11, Part 8 already gives you fallback chains — ordered models tried when the current one errors (Policy.fallback_on: rate limits, overload, timeouts, quota). That is reliability, owned by the client and deepened in lesson 11C.3. Routing decides which chain a request enters and whether a successful-but-weak answer should escalate anyway. The two compose: your router picks chat.smart's chain; the client walks the chain on errors; a cascade validator can still send the request to chat.frontier when the answer fails a quality check.
2.3 Static routing by task or feature#
The simplest pattern and the one you already have: each feature names its route. Request.model = "extract.invoice" and the registry/route table maps that to a pinned chain. No per-request logic at all.
# llm_service/routes.yaml (excerpt) — the route table from 1.2, as configuration
routes:
chat.fast: {alias: fast, data_policy: standard}
chat.smart: {alias: smart, data_policy: standard}
extract.invoice: {alias: vision-capable-fast, data_policy: no-pii-in-prompts}
summarize.long: {alias: longctx, data_policy: zdr-required}Static routing is correct whenever traffic slices are known before the request arrives — which is most of them, because your API endpoints already separate features. Its virtue is total evaluability: the routing "function" is a lookup table, so offline router evaluation (Part 4) is exact.
2.4 Rule-based routing#
When one feature's traffic mixes difficulties, rules inspect cheap request signals and pick a route per request. The signals, roughly in order of cost:
| Signal | Cost | Example rule |
|---|---|---|
| Caller-supplied metadata | free | user_tier == "enterprise" → chat.smart |
| Feature / endpoint | free | already static |
| Request shape | ~free | needs_tools, output_schema present, n_messages, approx token estimate |
| Media presence | ~free | has_images → vision-capable route |
| Language detection | cheap (offline library or heuristic) | non-English → multilingual-strong route |
| Content heuristics | cheap | "compare/contrast/analyse" keyword boost → harder tier (fragile — see failure gallery) |
Rules are ordered, first-match-wins, and total — every request must land somewhere. Keep them in code or config where they can be reviewed and unit-tested; a rule engine embedded in a prompt is a rule engine you can't test.
flowchart TD
f["RouteFeatures:<br/>tier, lang, tokens, media, tools"] --> r1{"enterprise tier?"}
r1 -->|yes| smart["chat.smart"]
r1 -->|no| r2{"has images/docs?"}
r2 -->|yes| vis["vision-capable route"]
r2 -->|no| r3{"approx tokens > 8k<br/>or needs tools?"}
r3 -->|yes| mid["chat.smart"]
r3 -->|no| r4{"language ≠ en?"}
r4 -->|yes| mid
r4 -->|no| fast["chat.fast"]2.5 A/B and canary routing#
Routing isn't only about cost tiers — it's how you release model and prompt changes. Three patterns:
- Percentage split (A/B): a stable hash of the user/session ID assigns each user to arm A or arm B, so a user sees one consistent behaviour while the population splits by weight. 04.10, Part 8 owns prompt-level A/B; the same mechanism routes models.
- Canary rollout: 1–5% of traffic (or one tenant, one feature flag cohort) gets the new model first; compare quality/cost/latency before widening. This is the release strategy 02.10, 19.3 promised to Module 11C and 11C.2 wires into CI.
- Shadow traffic: the new model answers real requests in parallel, results logged and compared but never shown. Zero user risk, full signal — at double cost for the shadowed slice, and with the caveat that two simultaneous calls can rate-limit you (11C.3 covers the resilience side).
Sticky assignment matters more than it looks: a user whose answers come from different models across turns gets inconsistent tone, and provider-side caches (03.7) only warm if the same prefix keeps hitting the same provider. Hash on a keyed user/session hash (03.10 owns hash_user), never the raw ID.
2.6 Cost-aware and latency-aware routing#
Two "aware" flavours sort within a route rather than across tasks:
- Cost-aware: among interchangeable endpoints serving the same model (OpenRouter's many hosts for an open-weight model; LiteLLM deployments; Azure regions), prefer the cheapest that meets a latency/quality floor. OpenRouter's
provider.sort: "price"or the:floorvariant does exactly this, including flex-tier endpoints (02.9, 5.4). The catch, verified in the 02.9 endpoint listing: the cheapest host often runs a quantized build —quantizations: ["fp8","bf16"]filters that out when quality matters. - Latency-aware: sort by throughput/TTFT instead — OpenRouter
provider.sort: "throughput"or:nitro, LiteLLMlatency-based-routing, Cloudflaresmartrouting. Use for interactive routes where TTFT dominates UX; the cost is paying priority-tier prices when a priority endpoint wins the sort.
Both are per-request hints passed to the gateway/provider, not app-level decisions — unless you run your own gateway, in which case they're routing strategies (2.12). Hedged requests (fire a second call when the first is slow) are a latency technique with a cost multiplier — lesson 11B.1 owns it; don't confuse it with routing.
2.7 Load balancing across keys, regions and deployments#
When one provider account is the bottleneck — rate limits, regional latency, a single deployment's capacity — you spread load:
- Across API keys / deployments of the same model: LiteLLM's router does this natively (each
model_listentry is a deployment;simple-shuffle,least-busy,usage-based-routing-v2spread across them). Multiple keys on one account can violate provider terms — check the provider's fair-use and rate-limit terms before key-sharding; orgs typically get multiple keys legitimately, but "10 keys to beat the rate limit" is a terms-of-service question, not just engineering. - Across regions: OpenAI data-residency endpoints, Anthropic
inference_geo, Gemini regional endpoints, OpenRouter region-pinned providers. Costs a residency premium (e.g. Anthropicinference_geo: "us"prices at 1.1×) — a routing cost, not just a latency one. - Across providers for the same open-weight model: the commodity case from 02.9, 5.4 — 40+ hosts serve DeepSeek V4.1 Flash at 5× price spread. Here load balancing and cost-aware routing are the same mechanism.
The discipline: pin quality-affecting choices. Quantization, provider version drift and prompt-cache warmth all vary per endpoint; if your eval was run on fp8 and production silently serves fp4, your frontier measurement is void. provider.quantizations, provider.order + allow_fallbacks: false, or registry entries per host are how you make the serving endpoint a reviewed decision.
2.8 Multi-provider active-active#
The end-state of the previous patterns: every route has ≥2 independent providers serving it, and traffic splits by health and cost rather than failover-only. This is what gateways sell as "high availability" and what your own router can do with weighted arms across providers.
The non-obvious requirements:
- Data policy must be uniform across arms. An active-active pair where arm B has weaker retention terms is a policy violation waiting for an outage — or worse, waiting for a cost-driven routing decision to quietly prefer B.
- Quality must be equal, not assumed. The same open-weight model on two hosts is not guaranteed identical (quantization, serving stack, prompt template handling). Re-run the route's eval slice per endpoint before weighting traffic toward the cheaper one.
- Sticky state matters. Multi-turn conversations, prompt caches and session memory all favour keeping a user on one arm; the sticky hashing from 2.5 is the mechanism.
- This is reliability, owned elsewhere. Circuit breakers, health probes, failover semantics and chaos testing are lesson 11C.3; this lesson's job is deciding the weights and membership of the active set.
2.9 Cascades: escalate on quality, not just errors#
The highest-leverage routing pattern for cost: try the cheap model first; escalate only when its answer fails a check. The check is the whole design.
flowchart LR
q["Request"] --> c1["cheap model<br/>(fast tier)"]
c1 --> v{"Validator:<br/>schema ok? finish ok?<br/>confidence? judge?"}
v -->|"pass"| out["Answer + log"]
v -->|"fail"| c2["stronger model<br/>(smart tier)"]
c2 --> v2{"Validator"}
v2 -->|"pass"| out
v2 -->|"fail"| c3["frontier / human review"]
c3 --> outWhat can a validator check? In increasing order of cost and reliability:
| Validator | What it proves | Cost | Failure mode |
|---|---|---|---|
finish_reason ∈ {stop, tool_calls} |
not truncated, not refused, not errored | free | weak signal — a stopped answer can still be wrong |
Schema validity (output_schema parsed) |
format contract held | free (already paid for) | catches format failures only |
| Business rules (totals sum, dates parse, enum membership) | domain invariants | cheap, deterministic | only catches what you thought to check |
| Self-consistency / logprobs confidence | model's own uncertainty | cheap-ish; logprobs availability varies by provider (02.5) | overconfident wrong answers pass |
| Self-grade ("rate your answer 1–5" in a second call) | the model's opinion of itself | one extra small call | models are bad at grading their own confident errors |
| Verifier / judge model | an independent check | a second model call (can itself be cheap-tier) | judge errors; judge cost adds up |
| Grounding check (answer must cite retrieved chunks) | the answer is anchored | cheap, deterministic where citations exist | only for RAG-shaped outputs |
Cascade economics. Let p be the fraction of requests the cheap model passes, c1/c2 the per-call costs, and assume a failed first attempt is billed anyway (it is — you paid for the tokens). Expected cost per request:
E[cost] = c1 + (1 - p) × c2 (+ retries/fallbacks inside each call, owned by 03.11/11C.3)With the 1.3 example numbers (c1 = $0.0012, c2 = $0.0060, p = 0.8): E[cost] ≈ $0.0012 + 0.2×$0.0060 = $0.0024. The cascade beats the always-smart route ($0.0060) only if p stays high — which is why p is a measured production metric (3.6, 4.3), not a one-time eval number. Every percentage point of p you lose costs (c2) × 0.01 per request; every point of quality the cheap model loses unnoticed costs trust.
Escalation triggers beyond validators: ContextTooLong (the input doesn't fit the cheap model's window — 03.11 deliberately does not auto-fallback on it because "that is a cascade, Module 11" (now Module 11B) — this is where you implement it), repeated identical tool calls (08A.14 owns agent-loop detection), and LENGTH truncation on structured output (raise max_output_tokens or escalate — a truncated JSON is a failed parse, and 03.4 owns the parse-side handling).
2.10 Classifier routers you build yourself#
Between rules and learned routers sits the classifier router: a small model (or an embedding + kNN) that looks at the request and predicts its difficulty/route. The ladder, cheapest first:
- Rules (2.4): zero marginal cost, brittle to anything not in the rule set.
- Embeddings + kNN: embed the request, find its nearest labelled examples, vote on the route. Needs an embedder you already run for RAG (Module 06) and a few hundred labelled "this was hard/easy" examples. Deterministic, inspectable (you can show the neighbours), cheap. Fails when difficulty isn't surface-similar to your examples.
- A small classifier model: fine-tuned or prompted small model mapping request → route label. More expressive than kNN; needs training data and its own eval.
- LLM-as-router: ask a cheap model "which tier?" with the 04.8, 2.4 prompt. One extra small call per request (~$0.0001); flexible; non-deterministic unless you constrain decoding (03.4 enum output makes it reliable); and it inherits the small model's blind spots.
Whatever the classifier, the discipline is the same: label the routes by downstream outcome, not intuition. "Hard" should mean "the cheap model failed the eval on inputs like this", which you discover by running both tiers over your eval set and joining results — exactly what the offline evaluator in 3.7 computes.
2.11 Hosted and learned routers#
You can also buy the classifier. As of November 2026, the landscape:
| Router | What it is | Status (Nov 2026) | Fit |
|---|---|---|---|
OpenRouter Auto (openrouter/auto, openrouter/auto-beta) |
Vendor router: first narrows the pool by your guardrails, zero-data-retention setting, capabilities, provider restrictions and allowed_models/excluded_models (wildcards such as anthropic/* work); then a fast decision model rates eleven aspects of the request (task type, difficulty, whether speed matters, vision, codebase knowledge...) in one call, and a routing policy weighs that rating against live prices, cache status and benchmark performance to pick both a model and a reasoning effort; cost_tier (low/medium/high; xhigh and max route as high) selects the policy; the plugin id is auto-router (auto-beta-router for the beta channel — settings sent under the wrong id are silently ignored) |
Active, flagship (docs checked November 2026) | Zero-effort baseline; black-box, driven by general benchmarks and prices, not your data |
| Azure AI Foundry model router | Trained selector model deployed in Foundry like any other model and called by its deployment name; modes Balanced (default; picks the cheapest model within ~1-2% of the best quality for the prompt) / Cost (~5-6% band) / Quality; optional model subset (new base models are not added to your subset automatically); built-in automatic failover (your subset is also the fallback set, so choose at least two models); ~37 models across OpenAI, Anthropic, xAI, Fireworks, DeepSeek and Meta (version 2025-11-18, updated in place) |
Active | If you're already on Foundry; strong defaults. Caveats from Microsoft's own page: the effective context window is that of the smallest underlying model (use a subset for long prompts), the routing decision is based on the text input only, and cache hits only happen when consecutive requests land on the same model |
| Amazon Bedrock Intelligent Prompt Routing | Routes within a model family (Nova, Claude, Llama) by predicted "response quality difference" vs a fallback anchor | Active; English prompts only | Cheap in-family tiering; narrow scope by design |
| Google Vertex AI Model Optimizer / Agent Platform model routing | Meta-endpoint that picks the Gemini model per request; ModelRoutingPreference = PRIORITIZE_QUALITY / BALANCED / PRIORITIZE_COST (REST GenerationConfig.routingConfig.autoMode; the Python SDK marks its RoutingConfig class deprecated in favour of ModelConfig — the API surfaces disagree, so check current docs) |
Active; Gemini-family only | If you're on Vertex; same in-family caveat as Bedrock |
| Cloudflare AI Gateway | Dynamic Routes (visual/JSON flow: conditional, percentage, model, rate-limit, budget nodes) + model aliases (preferred order or smart) + Auto Router (cloudflare/auto model name; check its docs page for the current stability label) |
Active | Edge-deployed, non-devs can edit routes; per-gateway scope |
| RouteLLM (LMSYS) | Open-source framework: trained routers (matrix-factorization, BERT, causal-LM) for strong-vs-weak binary routing with a cost threshold; OpenAI-compatible server | Apache-2.0, ~5.7k stars, effectively unmaintained (last commit ~Aug 2024) | Reference implementation to learn from; think twice before production dependence |
| vLLM Semantic Router | Open-source (vllm-sr 0.4.0, Apache-2.0), now positioned as a "decision layer for models and compute": YAML-configured signals → projections → decisions → algorithms → recipes (one model, a cascade, or a multi-model workflow); OpenAI- and Anthropic-compatible API on :8899, dashboard on :8700; signal families span heuristic detectors and learned classifiers (complexity, domain, language, jailbreak, PII, preference…) — check the docs for the current count |
Active, early (0.x) | Self-hosted "router as a service" aligned with the vLLM ecosystem; young and moving fast |
| Martian | Pioneer of learned routing | Shifted its emphasis to interpretability research; its router documentation page returned 404 on 12 November 2026 and no official shutdown announcement was found (verify before relying on it either way) | Historical interest only |
| Not Diamond | Learned router SaaS | Refocused on coding agents (its site now describes an "intelligent model router for coding agents"); Python SDK repo archived (last push Dec 2025) | Niche now |
| LiteLLM Router / Portkey | Not learned routers — configurable routing (strategies, fallbacks, load balancing) | Active, widely used | See 2.12 |
OpenRouter's Auto Router has siblings worth knowing (as of November 2026, from OpenRouter's routing docs): openrouter/auto-code runs on the same engine with a policy tuned for coding agents (it starts in a higher cost tier, weighs speed more heavily, penalises failures harder and prefers changing reasoning effort over switching model, so the prompt cache survives); openrouter/pareto-code is a much simpler benchmark-based picker (you set min_coding_score between 0 and 1, and it sends the request to the cheapest currently available coding model in that tier of an Artificial Analysis coding ranking, one model per request); and openrouter/free picks a random free model that supports the features the request needs. The Auto Router needs conversational input (messages or a message-list input), is available only in OpenRouter's global data region, and cannot be combined with another router model in the same request, so check the data-residency constraints of 1.5 before you route regulated traffic through it.
Two honest observations. First, the winners are gateways, not routers: routing became a feature of the proxy layer (OpenRouter, Cloudflare, LiteLLM, Portkey, Vercel) rather than a standalone product — Martian's move away from its router is a signal of the same trend. Second, no hosted router knows your eval set. They optimise for general benchmarks, live prices and generic quality predictions; your quality bar is yours. Treat hosted routers as a strong baseline to beat with your own evals, or as the mechanism when you have no routing engineering capacity — and always log which model actually served (response.model) so you can audit decisions after the fact.
OpenRouter's other routing surfaces. Auto Router is only one of them, and the provider already ships two mechanisms this lesson's patterns map onto directly. The models request field is OpenRouter's primary cross-model fallback: an ordered list of model IDs tried in turn when the first returns an error — context-length overflow, moderation refusal, rate limit or downtime (any error can trigger it) — with the request billed at whichever model actually serves and the response's model attribute reporting which one did. It's the hosted equivalent of your CascadeRouter's error path (2.2 — note it fires on errors, not on weak-but-successful answers, so it complements rather than replaces a quality cascade). The Anthropic Messages skin exposes the same mechanism as a fallbacks parameter (max 3 entries, model-only, can't be combined with models). Presets (@preset/{slug}) package a whole routing configuration — model or fallback array, provider preferences, system prompt, parameters, tools — as a named, versioned object referenced in place of re-sending config; useful when the routing policy belongs to whoever owns the OpenRouter workspace rather than to your code. 02.9, 5.4 covers models and provider options in depth.
2.12 Gateway routing: LiteLLM, Portkey and friends#
Self-hosted gateways give you routing-as-configuration without writing a router. Verified as of November 2026:
LiteLLM proxy (litellm 1.108.0) — the Router load-balances deployments of a model_name and fails over between model_names:
- Strategies:
simple-shuffle(default, recommended),least-busy,usage-based-routing-v2,latency-based-routing,cost-based-routing(the docs' lowest-cost pick, async-only), or a custom Python function. Per-model routing groups bind a set ofmodel_names to a strategy, each with its own strategy and args. - Session affinity pins every request of a conversation to the deployment that served its first — the gateway-level version of the sticky hashing in 2.5. A related cache-aware routing mode discovers Kubernetes pods and keeps a session on the pod holding its prompt-cache prefix.
- Deployment ordering:
orderinlitellm_paramsprioritises deployments; on failure the router escalates order levels, then falls through to model-levelfallbacks. - Fallback types:
fallbacks(all errors),context_window_fallbacks(the cascade trigger from 2.9),content_policy_fallbacks. - Settings hierarchy: key > team > global router settings — different routes per tenant.
# litellm proxy config — reference, unrun
model_list:
- model_name: chat-fast
litellm_params: {model: openai/gpt-6-luna, api_key: os.environ/OPENAI_API_KEY}
- model_name: chat-smart
litellm_params: {model: anthropic/claude-sonnet-5-5, api_key: os.environ/ANTHROPIC_API_KEY}
router_settings:
routing_strategy: latency-based-routing
fallbacks: [{"chat-fast": ["chat-smart"]}]
context_window_fallbacks: [{"chat-fast": ["chat-smart"]}]Portkey gateway (@portkey-ai/gateway, MIT, Node; portkey-ai 2.3.4 Python SDK) — configs compose three strategies, nestable:
conditional: route by metadata/params/url-path (e.g.params.model == "fastest"→ cheap target; EU residents → EU endpoint).loadbalance: weighted targets, weights normalised to percentages.fallback: ordered targets withon_status_codes.
Nesting is the point: a conditional branch can itself be a load balancer across providers, and each slot can carry its own fallback — failure isolation per model family.
Cloudflare AI Gateway — Dynamic Routes: a versioned visual/JSON flow (conditional, percentage, model, rate-limit, budget-limit nodes) published per gateway; model aliases with preferred ordering or smart routing; an Auto Router feature (the cloudflare/auto model name; its docs page read 12 November 2026 carries no stability label, so check before relying on it). Strong when non-engineers must edit routing.
Vercel AI Gateway — managed; provider selection by recent uptime/latency, model fallbacks, "decision fallbacks", virtual models, routing rules. Kong AI Gateway — AI Proxy plugin with semantic, lowest-latency, usage-based and weighted balancing (advanced tier). Google Cloud API Gateway — model routing (Public Preview) transcodes OpenAI-compatible requests and routes by the model field to Gemini/Claude/GPT MaaS endpoints on Agent Platform Model Garden, configured in an OpenAPI spec — gateway-level routing by name, not intelligent selection (docs). Vercel and Kong are thinner on quality-aware routing than the above; check current docs before relying on specifics. Bifrost (weighted distribution across keys and ordered per-request fallbacks) and TensorZero (provider routing lists and weighted variant sampling; repository archived June 2026) are covered in 11C.3, 9.2.
2.13 The decision table#
| Your situation | Start with | Graduate to |
|---|---|---|
| Each feature already has its own endpoint/model | Static routing (2.3) | Add rules only for mixed-difficulty features |
| One feature, mixed easy/hard traffic, measurable quality signal | Cascade (2.9) | Add classifier pre-routing if cascade waste is high |
| Clear request signals (tier, language, media, size) | Rule-based (2.4) | kNN/LLM classifier when rules get brittle |
| Releasing a new model/prompt version | Canary + sticky split (2.5) | Shadow traffic for risky changes |
| Same model, many endpoints/regions/keys | Gateway cost/latency routing (2.6–2.7) | Your own weighted router if gateway limits bite |
| No routing engineering capacity | Hosted router: OpenRouter Auto / Azure model-router / Cloudflare (2.11) | Bring in-house once you have evals to beat it |
| Self-hosted open models at scale | vLLM Semantic Router or LiteLLM router (2.11–2.12) | Custom classifier on your traffic |
| Multi-provider HA with equal quality | Active-active weighted arms (2.8) + 11C.3 resilience | — |
2.14 Failure gallery#
Routing failures are quiet — nothing errors, the answers just get worse or the bill gets bigger. The gallery:
| Failure | Symptom | Root cause | Fix |
|---|---|---|---|
| Rule rot | Quality drift, no deploy | Rules tuned for last year's models/traffic | Log features + decisions; re-eval per slice monthly (2.4, 4.4) |
| Cascade pass-rate collapse | Cost spikes, latency up | Cheap model's validator pass rate p fell (model update, traffic shift) |
Alert on p; re-tune validators or re-balance the chain (2.9) |
| Confident wrong answers | Quality complaints the validators can't see | Cheap model passes every cheap check | Decide which bar the cheap tier must hold alone; add judge/grounding checks where it matters (2.9) |
| Router sends everything to frontier | Bill doubles | Broken rule, flag flip, or feature extraction regression | Route-distribution dashboard + decision logs (4.3) |
| Sticky split re-shuffles users | Inconsistent answers mid-conversation | Salt or key changed; weights edited carelessly | Version the salt; treat weight changes as a rollout (2.5) |
| Data-policy leak via fallback | Compliance incident | Fallback/gateway arm with weaker retention terms | Uniform data policy across every arm; enforce zdr/data_collection in config (1.5) |
| Label leakage in router eval | Router "wins" offline, loses in prod | Difficulty labels correlated with classifier features | Label by outcome independently of features; hold out a slice (4.2) |
| Quantised endpoint surprise | Quality drop on "same" model | Cheapest provider serves a lower-precision build | Pin quantizations, provider.order, or registry entries per endpoint (2.7) |
| Prompt breaks on escalation | Cascade's stronger model answers worse | Prompt tuned for the cheap model's habits | Per-model prompt variants; eval every (prompt × model) pair (Part 5) |
| Router call itself fails | All requests hit default | LLM-as-router dependency down or unparsable | Cheap alias + defensive parse + default; count its cost (3.4) |
| Gateway hides the decision | Can't audit why a model served | Vendor router is a black box | Log response.model and requested route; prefer evaluable routers for quality-critical paths (2.11) |
Part 3: llm_service/router.py — the routing layer#
Deep-dive
llm_service/router.py — the routing layer#Everything in Part 2 is implementable in one stdlib-only module. This part builds it: feature extraction, the four router classes (static/rules, weighted split, cascade, kNN and LLM classifiers), decision logging, and the offline evaluator. The design rule from the module plan: every provider call goes through the injected complete callable, so the whole layer is unit-testable with fakes — the same fake-server discipline as 03.10 and 03.11, Part 11.
Save the blocks below, in order, as llm_service/router.py (they concatenate into one file). In production, complete is LLMClient.complete from 03.11 wrapped to return the canonical Response.
3.1 Shared types and feature extraction#
# llm_service/router.py (part 1 of 4)
"""Routing layer for llm_service.
Sits between application code and provider_agnostic.LLMClient (lesson 03.11):
it decides WHICH route a request enters (alias name + provider hints + reason)
and logs the decision. Provider calls still go through the injected `complete`
callable, so everything here is unit-testable with fakes — no SDK, no keys.
Stdlib only. The canonical Request/Response types come from provider_agnostic;
this module duck-types them so it also works with test doubles.
"""
from __future__ import annotations
import hashlib
import json
import time
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Callable, Iterable, Protocol
@dataclass(frozen=True)
class RouteContext:
"""Who is asking and for what — from YOUR auth layer, never from the model."""
feature: str # e.g. "support_chat", "invoice_extract"
user_tier: str = "free" # free | pro | enterprise
session_key: str | None = None # keyed hash of user/session id (03.10 hash_user)
request_id: str = ""
@dataclass(frozen=True)
class RouteFeatures:
"""Cheap signals extracted before any model call.
Extraction must stay O(size of request): never a model call, never a
network call, never a tokenizer download.
"""
n_messages: int = 0
approx_input_tokens: int = 0
request_chars: int = 0
has_images: bool = False
has_documents: bool = False
needs_tools: bool = False
needs_structured_output: bool = False
language: str | None = None # non-Latin script tag, or None = unknown/Latin-script
@dataclass(frozen=True)
class RouteDecision:
"""What the router decided, and why. Logged before the call is made."""
alias: str # provider_agnostic alias or entry key
router: str # which router produced it ("rules", "knn", ...)
reason: str # human-readable, e.g. "rule:has_images"
signals: dict[str, Any] = field(default_factory=dict)
class Router(Protocol):
"""Every routing pattern implements this one method."""
name: str
def route(self, ctx: RouteContext, feats: RouteFeatures) -> RouteDecision: ...
def approx_tokens(text: str) -> int:
"""~4 chars/token rule of thumb — precise enough for routing thresholds."""
return max(1, len(text) // 4)
def detect_language(text: str) -> str | None:
"""A tiny script-based hint, NOT a real language detector.
Production should use a proper detector (fastText lang-id, CLD3, or the
provider's own language handling) — this exists so rules have *something*
to switch on in tests and demos. It detects only NON-Latin scripts:
Latin-script text (English, French, German, ...) all returns None because
the script alone cannot tell those languages apart. Treat None as
"unknown or Latin-script" and use a real detector when a route cares
about Latin languages.
"""
sample = text[:4000]
if not sample.strip():
return None
for lo, hi, tag in [
(0x0900, 0x097F, "hi"), (0x0B80, 0x0BFF, "ta"), (0x0C00, 0x0C7F, "te"),
(0x0980, 0x09FF, "bn"), (0x4E00, 0x9FFF, "zh"), (0x3040, 0x30FF, "ja"),
(0xAC00, 0xD7AF, "ko"), (0x0600, 0x06FF, "ar"), (0x0370, 0x03FF, "el"),
(0x0400, 0x04FF, "ru"),
]:
if any(lo <= ord(ch) <= hi for ch in sample):
return tag
return None
def _part_kinds(parts: Any) -> set[str]:
"""Normalise provider_agnostic Part objects (or test doubles) to kind names."""
kinds: set[str] = set()
for p in parts or []:
kind = getattr(p, "kind", None)
if kind is None:
kind = type(p).__name__.lower()
kinds.add(str(kind))
return kinds
def _has_kind(kinds: set[str], *needles: str) -> bool:
return any(any(n in k for n in needles) for k in kinds)
def extract_features(req: Any) -> RouteFeatures:
"""Extract RouteFeatures from a provider_agnostic Request (duck-typed).
Works with the real `provider_agnostic.types.Request` and with simple
test doubles that expose .messages/.tools/.output_schema/.system.
"""
messages = list(getattr(req, "messages", None) or [])
tools = list(getattr(req, "tools", None) or [])
system = str(getattr(req, "system", "") or "")
schema = getattr(req, "output_schema", None)
kinds: set[str] = set()
chars = len(system)
for m in messages:
kinds |= _part_kinds(getattr(m, "parts", None))
chars += len(str(getattr(m, "text", "") or ""))
text_blob = system + " " + " ".join(str(getattr(m, "text", "") or "") for m in messages)
return RouteFeatures(
n_messages=len(messages),
approx_input_tokens=approx_tokens(text_blob),
request_chars=chars,
has_images=_has_kind(kinds, "image"),
has_documents=_has_kind(kinds, "document", "pdf", "file"),
needs_tools=bool(tools),
needs_structured_output=schema is not None,
language=detect_language(text_blob),
)3.2 Static, rule-based and weighted-split routers#
# llm_service/router.py (part 2 of 4)
@dataclass(frozen=True)
class Rule:
"""One ordered rule: first match wins. `when` gets (ctx, feats) -> bool."""
name: str
when: Callable[[RouteContext, RouteFeatures], bool]
alias: str
class StaticRouter:
"""Feature -> alias lookup. The default for most routes."""
name = "static"
def __init__(self, routes: dict[str, str], default: str) -> None:
self.routes = dict(routes)
self.default = default
def route(self, ctx: RouteContext, feats: RouteFeatures) -> RouteDecision:
alias = self.routes.get(ctx.feature, self.default)
return RouteDecision(alias=alias, router=self.name,
reason=f"feature:{ctx.feature}" if ctx.feature in self.routes else "default",
signals={"feature": ctx.feature})
class RuleRouter:
"""Ordered first-match rules over RouteFeatures + RouteContext."""
name = "rules"
def __init__(self, rules: Iterable[Rule], default: str) -> None:
self.rules = list(rules)
self.default = default
def route(self, ctx: RouteContext, feats: RouteFeatures) -> RouteDecision:
for rule in self.rules:
if rule.when(ctx, feats):
return RouteDecision(alias=rule.alias, router=self.name,
reason=f"rule:{rule.name}",
signals={"rule": rule.name,
"tier": ctx.user_tier,
"lang": feats.language,
"tokens": feats.approx_input_tokens})
return RouteDecision(alias=self.default, router=self.name,
reason="default", signals={"fell_through": True})
def stable_bucket(key: str, salt: str = "router-v1") -> int:
"""Map a stable key to 0..9999. Same key + salt -> same bucket, always."""
digest = hashlib.sha256(f"{salt}:{key}".encode()).digest()
return int.from_bytes(digest[:8], "big") % 10_000
class WeightedSplitRouter:
"""Percentage split across aliases, sticky per session/request key.
arms: [(weight, alias), ...] — weights are relative shares (normalised).
Cumulative rounding means the LAST arm absorbs any rounding remainder
(three equal arms give the last ~33.34%) — negligible at real weights.
A request with session_key="u-abc" always lands on the same arm while the
weights are unchanged: that is what makes this usable for BOTH A/B tests
(weights 50/50) and canary rollouts (weights 97/3) without per-request
flapping. Requests with no key get request_id; if both are absent the
split is random per call (still logged).
"""
name = "split"
def __init__(self, arms: list[tuple[int, str]], salt: str = "split-v1") -> None:
if not arms:
raise ValueError("WeightedSplitRouter needs at least one arm")
total = sum(w for w, _ in arms)
if total <= 0:
raise ValueError("weights must sum to > 0")
self.arms: list[tuple[int, str]] = []
acc = 0
for w, alias in arms:
acc += round(w * 10_000 / total)
self.arms.append((acc, alias))
self.salt = salt
def pick(self, key: str | None) -> tuple[str, int]:
"""Return (alias, bucket). Deterministic for a given key."""
bucket = stable_bucket(key, self.salt) if key else int.from_bytes(
hashlib.sha256(f"{self.salt}:{time.time_ns()}".encode()).digest()[:8], "big") % 10_000
for threshold, alias in self.arms:
if bucket < threshold:
return alias, bucket
return self.arms[-1][1], bucket
def route(self, ctx: RouteContext, feats: RouteFeatures) -> RouteDecision:
key = ctx.session_key or ctx.request_id or None
alias, bucket = self.pick(key)
return RouteDecision(alias=alias, router=self.name,
reason="weighted-split",
signals={"bucket": bucket, "keyed": key is not None})3.3 The cascade#
# llm_service/router.py (part 3 of 4)
# A validator inspects (response, request) and returns True to ACCEPT the answer.
# It may also raise — any exception counts as a failed validation (escalate).
Validator = Callable[[Any, Any], bool]
# The callable that performs one model call. In production this is
# client.complete with Request.model set to the step's alias; in tests it is a
# fake returning canned responses. Signature: complete(req) -> response.
CompleteFn = Callable[[Any], Any]
def finish_ok(resp: Any, req: Any) -> bool:
"""The reply ended cleanly: not truncated, not refused, not errored.
`finish_reason` is a FinishReason(str, Enum) member on the canonical
Response — unwrap `.value` before comparing, because str(member) gives
'FinishReason.STOP', not 'stop'.
"""
reason = getattr(resp, "finish_reason", "stop")
reason = getattr(reason, "value", reason) # unwrap str-enum members
return str(reason).lower() in {"stop", "tool_calls", "end_turn", "completed"}
def schema_ok(resp: Any, req: Any) -> bool:
"""Structured output was requested AND validated (resp.parsed is set)."""
if getattr(req, "output_schema", None) is None:
return True
return getattr(resp, "parsed", None) is not None
def max_cost_usd(resp: Any, req: Any) -> bool:
"""Reject answers whose computed cost exceeds a ceiling (rare but real:
runaway reasoning tokens). Reads resp.cost.usd when present."""
cost = getattr(resp, "cost", None)
usd = getattr(cost, "usd", None) if cost is not None else None
return usd is None or usd <= 0.05
@dataclass(frozen=True)
class CascadeStep:
alias: str
validators: tuple[Validator, ...] = (finish_ok, schema_ok)
class CascadeRouter:
"""Try steps in order; escalate when a step's answer fails validation.
`complete` is called once per step with a shallow copy of the request whose
`model` field is set to the step alias. The FIRST response that passes all
of that step's validators wins. If every step fails, the last response is
returned anyway so the caller can decide (log, alert, human review) — a
cascade never silently drops the request.
"""
name = "cascade"
def __init__(self, steps: list[CascadeStep]) -> None:
if not steps:
raise ValueError("CascadeRouter needs at least one step")
self.steps = steps
def _with_model(self, req: Any, alias: str) -> Any:
"""Copy the request with a different model alias.
Handles pydantic models (model_copy), dataclasses (dataclasses.replace)
and plain mutable objects (shallow copy + setattr). Raises TypeError
rather than silently returning the request unchanged — a cascade that
cannot switch models must not run every step against the same one.
"""
if hasattr(req, "model_copy"):
return req.model_copy(update={"model": alias})
import copy
import dataclasses
if dataclasses.is_dataclass(req):
return dataclasses.replace(req, model=alias)
if hasattr(req, "model"):
new_req = copy.copy(req)
try:
setattr(new_req, "model", alias)
except (AttributeError, TypeError) as exc:
raise TypeError(f"cannot set 'model' on {type(req).__name__}") from exc
return new_req
raise TypeError(
f"CascadeRouter cannot route {type(req).__name__}: it has no "
"'model' attribute. Pass a pydantic model, a dataclass, or an "
"object with a settable `model` field.")
def complete_cascade(self, req: Any, complete: CompleteFn) -> tuple[Any, list[dict[str, Any]]]:
"""Run the cascade. Returns (response, trail) where trail records each
step's alias, whether it was tried, and why it was rejected."""
trail: list[dict[str, Any]] = []
last_resp = None
for i, step in enumerate(self.steps):
attempt_req = self._with_model(req, step.alias)
try:
resp = complete(attempt_req)
except Exception as exc:
trail.append({"step": i, "alias": step.alias, "error": type(exc).__name__})
raise # error fallback/retry policy owns errors — don't swallow them
last_resp = resp
failures = []
for v in step.validators:
try:
ok = bool(v(resp, attempt_req))
except Exception as exc:
ok = False
failures.append(f"{getattr(v, '__name__', v)}:raised {type(exc).__name__}")
if not ok and not failures:
failures = [getattr(v, "__name__", str(v))]
trail.append({"step": i, "alias": step.alias, "accepted": not failures,
"rejected_because": failures or None})
if not failures:
return resp, trail
return last_resp, trail # all steps failed validation: return last, flagged by trail
def route(self, ctx: RouteContext, feats: RouteFeatures) -> RouteDecision:
"""A cascade's *entry* decision is its first step; escalation happens
inside complete_cascade, not here. Kept for the Router protocol."""
return RouteDecision(alias=self.steps[0].alias, router=self.name,
reason="cascade-entry", signals={"steps": len(self.steps)})3.4 Classifier routers: kNN and LLM#
# llm_service/router.py (part 4 of 4)
def cosine(a: list[float], b: list[float]) -> float:
"""Cosine similarity. Pure stdlib — the same formula Module 06 uses."""
dot = sum(x * y for x, y in zip(a, b))
na = sum(x * x for x in a) ** 0.5
nb = sum(y * y for y in b) ** 0.5
return dot / (na * nb) if na and nb else 0.0
@dataclass(frozen=True)
class LabelledExample:
"""One labelled request: text used for embedding + the route it deserved.
Labels should come from OUTCOMES (the cheap model failed here), not vibes —
see lesson text 2.10. `route` is the alias this kind of request should get.
"""
text: str
route: str
class EmbeddingKnnRouter:
"""k-nearest-neighbour router over request embeddings.
embedder: text -> vector (in production: your Module 06 embedding pipeline;
in tests: a fake). examples: labelled requests. k neighbours vote; ties
break toward the CHEAPER route (a wrong vote toward cheap is caught by the
cascade, a wrong vote toward expensive just costs money).
"""
name = "knn"
def __init__(self, embedder: Callable[[str], list[float]],
examples: list[LabelledExample], k: int = 5,
cost_rank: dict[str, int] | None = None) -> None:
if not examples:
raise ValueError("EmbeddingKnnRouter needs labelled examples")
self.embedder = embedder
self.k = max(1, k)
self.cost_rank = cost_rank or {}
self._indexed = [(self.embedder(e.text), e.route) for e in examples]
def _embed_request(self, ctx: RouteContext, feats: RouteFeatures) -> list[float]:
# The router sees features, not the raw prompt, by design: embed a
# compact descriptor so the embedding call stays cheap and PII-light.
descriptor = (f"feature={ctx.feature} tier={ctx.user_tier} "
f"tokens~{feats.approx_input_tokens} msgs={feats.n_messages} "
f"media={feats.has_images or feats.has_documents} "
f"tools={feats.needs_tools} lang={feats.language}")
return self.embedder(descriptor)
def route(self, ctx: RouteContext, feats: RouteFeatures) -> RouteDecision:
q = self._embed_request(ctx, feats)
scored = sorted(((cosine(q, v), route) for v, route in self._indexed),
key=lambda t: -t[0])[: self.k]
votes: dict[str, int] = {}
for sim, route in scored:
votes[route] = votes.get(route, 0) + 1
best = max(votes.items(),
key=lambda kv: (kv[1], -self.cost_rank.get(kv[0], 0)))[0]
return RouteDecision(alias=best, router=self.name, reason="knn-vote",
signals={"votes": votes,
"top_sim": round(scored[0][0], 3) if scored else None,
"k": self.k})
@dataclass
class _RouterRequest:
"""Minimal request shape for the router's own classification call.
In production you would build a real provider_agnostic Request instead."""
model: str
messages: list[dict[str, str]]
system: str | None = None
tools: list[Any] = field(default_factory=list)
output_schema: Any = None
max_output_tokens: int | None = 16
class LLMRouter:
"""Ask a cheap model which route should handle this request.
complete: the injected client call (same one the cascade uses). The router
model should be your cheapest reliable tier; its answer is matched against
a small set of route names, parsed defensively — an unparsable or unknown
answer falls back to `default`, never raises.
"""
name = "llm"
def __init__(self, complete: CompleteFn, cheap_alias: str,
routes: list[str], default: str) -> None:
self.complete = complete
self.cheap_alias = cheap_alias
self.routes = list(routes)
self.default = default
def _prompt(self, ctx: RouteContext, feats: RouteFeatures) -> str:
return (
"Route this request to exactly one lane. Reply with ONLY the lane name.\n"
f"Lanes: {', '.join(self.routes)}\n"
f"Feature: {ctx.feature} | tier: {ctx.user_tier}\n"
f"Size: ~{feats.approx_input_tokens} input tokens, {feats.n_messages} messages\n"
f"Media: {'yes' if (feats.has_images or feats.has_documents) else 'no'} | "
f"tools: {'yes' if feats.needs_tools else 'no'} | "
f"structured output: {'yes' if feats.needs_structured_output else 'no'} | "
f"language: {feats.language or 'unknown'}\n"
"Lane:"
)
def route(self, ctx: RouteContext, feats: RouteFeatures) -> RouteDecision:
# The router call itself is a model call — keep it tiny and on the
# cheapest alias. In production wrap it in the same client (retries,
# deadline) and count its cost in the request's total.
req = _RouterRequest(model=self.cheap_alias,
messages=[{"role": "user", "content": self._prompt(ctx, feats)}])
try:
resp = self.complete(req)
text = str(getattr(resp, "text", getattr(resp, "content", "")) or "").strip().lower()
except Exception:
text = ""
# Exact match first (case-insensitive); then the LONGEST prefix match,
# so "fast-plus" beats "fast" regardless of route order.
lowered = {r.lower(): r for r in self.routes}
if text in lowered:
chosen = lowered[text]
else:
prefixes = [r for r in self.routes if text.startswith(r.lower())]
chosen = max(prefixes, key=len) if prefixes else None
if chosen is not None:
return RouteDecision(alias=chosen, router=self.name,
reason="llm-classifier", signals={"raw": text[:80]})
return RouteDecision(alias=self.default, router=self.name,
reason="llm-unparseable->default", signals={"raw": text[:80]})
class DecisionLog:
"""Append-only JSONL log of routing decisions and their outcomes.
One record per decision BEFORE the call; outcome fields are appended as
separate lines joined on request_id. This is the dataset Part 4's
evaluator and lesson 11A.2's metrics are built on.
"""
def __init__(self, path: str | Path) -> None:
self.path = Path(path)
self.path.parent.mkdir(parents=True, exist_ok=True)
def record(self, decision: RouteDecision, ctx: RouteContext,
feats: RouteFeatures, **extra: Any) -> str:
rec = {
"ts": time.time(),
"request_id": ctx.request_id or None,
"feature": ctx.feature,
"user_tier": ctx.user_tier,
"session_key": ctx.session_key, # already a keyed hash
"router": decision.router,
"reason": decision.reason,
"alias": decision.alias,
"signals": decision.signals,
"feats": {"tokens": feats.approx_input_tokens, "msgs": feats.n_messages,
"media": feats.has_images or feats.has_documents,
"tools": feats.needs_tools, "schema": feats.needs_structured_output,
"lang": feats.language},
**extra,
}
with self.path.open("a") as fh:
fh.write(json.dumps(rec, default=str) + "\n")
return rec.get("request_id") or ""
def record_outcome(self, request_id: str, **outcome: Any) -> None:
"""Append an outcome line; join offline on request_id. Separate lines
preserve the 'decision before call' ordering guarantee."""
with self.path.open("a") as fh:
fh.write(json.dumps({"ts": time.time(), "kind": "outcome",
"request_id": request_id, **outcome}, default=str) + "\n")
class ModelRouter:
"""Top-level router: static feature routes, then per-feature rules, then
a default. Compose it with the specialised routers above where needed —
e.g. a RuleRouter for chat.* and a CascadeRouter for extract.*.
static: {feature: alias}; rules: ordered Rules applied when the feature
has no static entry.
"""
name = "model-router"
def __init__(self, static: dict[str, str], rules: list[Rule] | None = None,
default: str = "smart") -> None:
self.static = dict(static)
self.rules = RuleRouter(rules or [], default=default)
self.default = default
def route(self, ctx: RouteContext, feats: RouteFeatures) -> RouteDecision:
if ctx.feature in self.static:
return RouteDecision(alias=self.static[ctx.feature], router=self.name,
reason=f"static:{ctx.feature}",
signals={"feature": ctx.feature})
return self.rules.route(ctx, feats)3.5 Try it: the whole layer with fakes#
This demo runs the real code against canned responses — no keys, no network. Save it as demo_router.py next to router.py:
# demo_router.py — exercises router.py with fakes. Stdlib only.
import sys, types, os, tempfile, enum
sys.path.insert(0, ".")
from router import (RouteContext, RouteFeatures, RuleRouter, Rule, WeightedSplitRouter,
CascadeRouter, CascadeStep, EmbeddingKnnRouter, LabelledExample,
LLMRouter, DecisionLog, ModelRouter, extract_features, stable_bucket,
finish_ok)
# --- feature extraction on a duck-typed request ---
class Msg:
def __init__(self, text, parts=None):
self.text = text; self.parts = parts or []
class Img: kind = "image_url"
class FakeReq:
def __init__(self, **kw):
self.messages = kw.get("messages", []); self.tools = kw.get("tools", [])
self.output_schema = kw.get("output_schema"); self.system = kw.get("system", "")
f = extract_features(FakeReq(messages=[Msg("Hello, my order is late"), Msg("", [Img()])],
tools=[{"name": "lookup"}], output_schema=object(),
system="You are helpful."))
print("features:", f)
print("lang Devanagari ->", __import__("router").detect_language("नमस्ते दुनिया"))
# --- rules ---
rr = RuleRouter([
Rule("enterprise", lambda c, f: c.user_tier == "enterprise", "smart"),
Rule("media", lambda c, f: f.has_images or f.has_documents, "vision"),
Rule("big", lambda c, f: f.approx_input_tokens > 8000 or f.needs_tools, "smart"),
Rule("non-en", lambda c, f: f.language not in (None, "en"), "smart"),
], default="fast")
for desc, ctx, ft in [
("free en short", RouteContext(feature="chat", user_tier="free"), RouteFeatures(language="en", approx_input_tokens=200)),
("enterprise", RouteContext(feature="chat", user_tier="enterprise"), RouteFeatures(language="en")),
("hindi", RouteContext(feature="chat"), RouteFeatures(language="hi", approx_input_tokens=300)),
]:
print(f"{desc:>15} -> {rr.route(ctx, ft).alias} ({rr.route(ctx, ft).reason})")
# --- sticky split ---
ws = WeightedSplitRouter([(97, "stable"), (3, "canary")], salt="canary-v1")
counts = {}
for i in range(2000):
d = ws.route(RouteContext(feature="chat", session_key=f"user-{i % 500}"), RouteFeatures())
counts[d.alias] = counts.get(d.alias, 0) + 1
print("2000 requests / 500 users ->", counts)
# --- cascade ---
class Resp:
def __init__(self, text, finish="stop", parsed=None):
self.text = text; self.finish_reason = finish; self.parsed = parsed
def fake_complete(req):
if req.model == "fast" and "hardcase" in req.messages[0]["content"]:
return Resp('{"bad": true}', parsed=None) # schema fails
return Resp('{"ok": 1}', parsed={"ok": 1})
cas = CascadeRouter([CascadeStep("fast"), CascadeStep("smart")])
req_hard = types.SimpleNamespace(model="fast",
messages=[{"role": "user", "content": "hardcase please"}],
output_schema=dict, system=None, tools=[])
resp, trail = cas.complete_cascade(req_hard, fake_complete)
print("cascade trail:", trail)
# --- finish_ok must accept the canonical enum member, not just plain strings ---
class FakeFinish(str, enum.Enum): # same shape as provider_agnostic FinishReason
STOP = "stop"; TOOL_CALLS = "tool_calls"; LENGTH = "length"
assert finish_ok(Resp("done", finish=FakeFinish.STOP), None)
assert not finish_ok(Resp("cut", finish=FakeFinish.LENGTH), None)
print("finish_ok accepts FinishReason-style enum members")
# --- knn router with a toy embedder ---
def fake_embed(text):
v = [0.0] * 8
for ch in text.lower():
v[ord(ch) % 8] += 1.0
n = sum(x * x for x in v) ** 0.5 or 1.0
return [x / n for x in v]
knn = EmbeddingKnnRouter(fake_embed, [
LabelledExample("feature=chat tier=free tokens~200 msgs=2 media=False tools=False lang=en", "fast"),
LabelledExample("feature=support tier=free tokens~300 msgs=3 media=False tools=False lang=en faq", "fast"),
LabelledExample("feature=chat tier=enterprise tokens~9000 msgs=8 media=True tools=True lang=en", "smart"),
LabelledExample("feature=chat tier=pro tokens~7000 msgs=6 media=True tools=True lang=en docs", "smart"),
LabelledExample("feature=chat tier=free tokens~15000 msgs=20 media=False tools=True lang=ta", "frontier"),
LabelledExample("feature=chat tier=enterprise tokens~20000 msgs=25 media=True tools=True lang=hi hard", "frontier"),
], k=3, cost_rank={"fast": 0, "smart": 1, "frontier": 2})
print("knn easy en ->", knn.route(RouteContext(feature="chat", user_tier="free"),
RouteFeatures(approx_input_tokens=200, n_messages=2, language="en")).alias)
print("knn pro+media ->", knn.route(RouteContext(feature="chat", user_tier="pro"),
RouteFeatures(approx_input_tokens=7000, n_messages=6, has_images=True,
needs_tools=True, language="en")).alias)
# --- llm router: the fake 'model' echoes a route name ---
def router_complete(req):
return Resp("smart") # pretend the cheap classifier answered "smart"
llm = LLMRouter(router_complete, cheap_alias="router-tiny",
routes=["fast", "smart", "frontier"], default="smart")
print("llm router ->", llm.route(RouteContext(feature="chat"),
RouteFeatures(approx_input_tokens=500, language="en")).alias)
print("stable_bucket('user-7','canary-v1') =", stable_bucket("user-7", "canary-v1"))
# --- model router composition ---
mr = ModelRouter(static={"invoice": "fast"},
rules=[Rule("big", lambda c, f: f.approx_input_tokens > 8000, "frontier")],
default="smart")
print("model-router invoice ->", mr.route(RouteContext(feature="invoice"), RouteFeatures()).alias)
print("model-router huge chat ->", mr.route(RouteContext(feature="chat"),
RouteFeatures(approx_input_tokens=20000)).alias)
# --- decision log ---
log = DecisionLog(os.path.join(tempfile.mkdtemp(), "decisions.jsonl"))
d = rr.route(RouteContext(feature="chat", user_tier="pro", session_key="h-123", request_id="req-1"),
RouteFeatures(language="en", approx_input_tokens=300))
log.record(d, RouteContext(feature="chat", user_tier="pro", session_key="h-123", request_id="req-1"),
RouteFeatures(language="en", approx_input_tokens=300))
log.record_outcome("req-1", model="smart", cost_usd=0.004, latency_ms=1800,
served_by="anthropic/claude-sonnet-5-5")
print(open(log.path).read().strip().splitlines()[-1])features: RouteFeatures(n_messages=2, approx_input_tokens=10, request_chars=39, has_images=True, has_documents=False, needs_tools=True, needs_structured_output=True, language=None)
lang Devanagari -> hi
free en short -> fast (default)
enterprise -> smart (rule:enterprise)
hindi -> smart (rule:non-en)
2000 requests / 500 users -> {'stable': 1924, 'canary': 76}
cascade trail: [{'step': 0, 'alias': 'fast', 'accepted': False, 'rejected_because': ['schema_ok']}, {'step': 1, 'alias': 'smart', 'accepted': True, 'rejected_because': None}]
finish_ok accepts FinishReason-style enum members
knn easy en -> fast
knn pro+media -> smart
llm router -> smart
stable_bucket('user-7','canary-v1') = 7200
model-router invoice -> fast
model-router huge chat -> frontier
{"ts": ..., "kind": "outcome", "request_id": "req-1", "model": "smart", "cost_usd": 0.004, "latency_ms": 1800, "served_by": "anthropic/claude-sonnet-5-5"}3.6 Decision logging#
DecisionLog writes two line types to one JSONL file: a decision record before the call (router, reason, alias, the features that drove it) and outcome records after (cost, latency, which model actually served, validator trail). Join them on request_id offline. This is the raw material for everything in Part 4: router accuracy, cost attribution per route, and the per-slice quality checks that catch rule drift. It also feeds lesson 11A.1's traces — the decision is a span attribute, not a separate system.
Two rules: log the decision before the call (a crash mid-request must still leave the decision behind), and never log raw user text in signals — features and hashed IDs only (03.10 owns redaction).
3.7 The offline router evaluator#
llm_service/router_eval.py answers the question every router must answer: compared to the best possible assignment, what did this policy cost and lose? It consumes a results table — one row per (eval case, model) with quality and cost, exactly what you get by running your evalkit suite across candidate models. Its row class is called RouterCaseResult, not CaseResult, so it cannot be confused with evalkit.runner.CaseResult (10A.8), the per-run record that evalkit writes; here you copy each run's score and cost into the one-row-per-(case, model) shape the evaluator needs.
# llm_service/router_eval.py — offline evaluation of routing policies.
# Pure stdlib; the "results table" is built from real evalkit runs.
from __future__ import annotations
from dataclasses import dataclass, field
@dataclass(frozen=True)
class RouterCaseResult:
"""One (case, model) outcome: what that model scored and cost on this case."""
case_id: str
model: str
quality: float # 0..1, from your eval scorer
cost_usd: float
latency_ms: float = 0.0
@dataclass(frozen=True)
class Case:
"""One eval case with the slice labels you analyse per-slice."""
case_id: str
difficulty: str # easy | medium | hard — the label a PERFECT router uses
lang: str = "en"
feature: str = "chat"
class ResultsTable:
"""case_id -> {model -> RouterCaseResult}. Build it from evalkit runs."""
def __init__(self) -> None:
self.rows: dict[tuple[str, str], RouterCaseResult] = {}
def add(self, r: RouterCaseResult) -> None:
self.rows[(r.case_id, r.model)] = r
def get(self, case_id: str, model: str) -> RouterCaseResult | None:
return self.rows.get((case_id, model))
def models(self) -> list[str]:
return sorted({m for _, m in self.rows})
def cases(self) -> list[str]:
return sorted({c for c, _ in self.rows})
@dataclass
class PolicyReport:
name: str
total_cost: float
mean_quality: float
per_case: dict[str, tuple[str, float, float]] = field(default_factory=dict)
def slice_report(self, cases: dict[str, Case], key: str):
"""Aggregate (mean quality, mean cost, n) per slice value of `key`."""
agg: dict[str, list] = {}
for cid, (model, q, c) in self.per_case.items():
case = cases.get(cid)
if case is None:
continue
slice_val = getattr(case, key) if hasattr(case, key) else "?"
agg.setdefault(str(slice_val), []).append((q, c))
return {k: (sum(x[0] for x in v) / len(v), sum(x[1] for x in v) / len(v), len(v))
for k, v in sorted(agg.items())}
def oracle_assign(table: ResultsTable, cases: dict[str, Case],
quality_floor: float) -> dict[str, str]:
"""Best possible per-case assignment under a quality floor: cheapest model
meeting the floor; if none meets it, the highest-quality one. The upper
bound every router is measured against."""
assign: dict[str, str] = {}
for cid in table.cases():
rows = [(m, table.get(cid, m)) for m in table.models()]
rows = [(m, r) for m, r in rows if r is not None]
ok = [(m, r) for m, r in rows if r.quality >= quality_floor]
if ok:
assign[cid] = min(ok, key=lambda t: t[1].cost_usd)[0]
else:
assign[cid] = max(rows, key=lambda t: t[1].quality)[0]
return assign
def always_model(table: ResultsTable, model: str) -> dict[str, str]:
return {cid: model for cid in table.cases()}
def evaluate(name: str, table: ResultsTable, assign: dict[str, str],
cases: dict[str, Case]) -> PolicyReport:
rep = PolicyReport(name=name, total_cost=0.0, mean_quality=0.0, per_case={})
qs, n = 0.0, 0
for cid, model in assign.items():
r = table.get(cid, model)
if r is None:
continue
rep.per_case[cid] = (model, r.quality, r.cost_usd)
rep.total_cost += r.cost_usd
qs += r.quality
n += 1
rep.mean_quality = qs / n if n else 0.0
return rep
def regret(rep: PolicyReport, oracle: PolicyReport) -> dict[str, float]:
"""Cost delta vs oracle and quality gap vs oracle."""
return {
"cost_delta_usd": rep.total_cost - oracle.total_cost,
"cost_ratio": (rep.total_cost / oracle.total_cost) if oracle.total_cost else 0.0,
"quality_gap": rep.mean_quality - oracle.mean_quality,
}The demo data and main() complete the file — save them after the code above:
# llm_service/router_eval.py (part 2 of 2) — demo table and report
def demo_table() -> tuple[ResultsTable, dict[str, Case]]:
"""12 support tickets x 3 model tiers. Invented but internally consistent;
replace with real evalkit runs — the shape is what matters."""
table = ResultsTable()
raw = [
("T01", "easy", "en", {"fast": (0.95, 0.001), "smart": (0.97, 0.004), "frontier": (0.98, 0.015)}),
("T02", "easy", "en", {"fast": (0.90, 0.001), "smart": (0.95, 0.004), "frontier": (0.96, 0.015)}),
("T03", "easy", "hi", {"fast": (0.82, 0.0013), "smart": (0.93, 0.005), "frontier": (0.95, 0.016)}),
("T04", "medium", "en", {"fast": (0.71, 0.001), "smart": (0.92, 0.004), "frontier": (0.95, 0.015)}),
("T05", "medium", "en", {"fast": (0.68, 0.001), "smart": (0.90, 0.004), "frontier": (0.94, 0.015)}),
("T06", "medium", "ta", {"fast": (0.60, 0.0014), "smart": (0.86, 0.0055), "frontier": (0.93, 0.017)}),
("T07", "hard", "en", {"fast": (0.45, 0.001), "smart": (0.78, 0.004), "frontier": (0.93, 0.015)}),
("T08", "hard", "en", {"fast": (0.40, 0.001), "smart": (0.74, 0.004), "frontier": (0.91, 0.015)}),
("T09", "hard", "hi", {"fast": (0.38, 0.0013), "smart": (0.70, 0.005), "frontier": (0.90, 0.016)}),
("T10", "easy", "en", {"fast": (0.93, 0.001), "smart": (0.96, 0.004), "frontier": (0.97, 0.015)}),
("T11", "medium", "en", {"fast": (0.74, 0.001), "smart": (0.91, 0.004), "frontier": (0.95, 0.015)}),
("T12", "hard", "ta", {"fast": (0.35, 0.0014), "smart": (0.66, 0.0055), "frontier": (0.88, 0.017)}),
]
cases: dict[str, Case] = {}
for cid, diff, lang, models in raw:
cases[cid] = Case(case_id=cid, difficulty=diff, lang=lang)
for model, (q, c) in models.items():
table.add(RouterCaseResult(case_id=cid, model=model, quality=q, cost_usd=c))
return table, cases
def _cascade_assign(table: ResultsTable, cases: dict[str, Case]) -> dict[str, str]:
"""Model a cascade fast->smart->frontier where 'fast' only *passes* on
easy cases (its quality >= 0.85 threshold); failures escalate one step.
ORACLE-ASSISTED: it reads each case's true difficulty label and per-case
fast/smart outcomes — information that does not exist at request time.
It shows the ceiling a perfect escalation policy could reach, not a
deployable router."""
out = {}
for cid in table.cases():
diff = cases[cid].difficulty
fast_q = table.get(cid, "fast").quality
smart_q = table.get(cid, "smart").quality
if diff == "easy" or fast_q >= 0.85:
out[cid] = "fast"
elif diff == "medium" and smart_q >= 0.85:
out[cid] = "smart"
else:
out[cid] = "frontier"
return out
def demo_policies(table: ResultsTable, cases: dict[str, Case]) -> dict[str, dict[str, str]]:
"""The policies a router could implement, as case->model assignments.
NOTE: `rules-difficulty` and `cascade-fast-smart` are ORACLE-ASSISTED —
they read the true difficulty label and per-case outcomes, neither of
which exists at request time. They bracket what PERFECT routing could
do; a deployable router predicts the route instead, and the prediction
error is the gap between this table and production (Part 4 measures it).
"""
return {
"always-fast": always_model(table, "fast"),
"always-smart": always_model(table, "smart"),
"always-frontier": always_model(table, "frontier"),
"rules-difficulty": {cid: {"easy": "fast", "medium": "smart", "hard": "frontier"}[cases[cid].difficulty]
for cid in table.cases()},
"cascade-fast-smart": _cascade_assign(table, cases),
}
def main() -> None:
table, cases = demo_table()
floor = 0.85
oracle_map = oracle_assign(table, cases, floor)
oracle = evaluate("oracle", table, oracle_map, cases)
print(f"quality floor: {floor} cases: {len(cases)} models: {table.models()}")
print(f"{'policy':<20} {'cost':>9} {'quality':>8} {'cost_ratio':>11} {'qual_gap':>9}")
for name, assign in demo_policies(table, cases).items():
rep = evaluate(name, table, assign, cases)
r = regret(rep, oracle)
print(f"{name:<20} ${rep.total_cost:>8.4f} {rep.mean_quality:>8.3f} "
f"{r['cost_ratio']:>10.2f}x {r['quality_gap']:>+9.3f}")
print(f"{'ORACLE':<20} ${oracle.total_cost:>8.4f} {oracle.mean_quality:>8.3f}")
rep = evaluate("rules-difficulty", table, demo_policies(table, cases)["rules-difficulty"], cases)
print("\nrules-difficulty per language slice (quality, cost, n):")
for lang, (q, c, n) in rep.slice_report(cases, "lang").items():
print(f" {lang}: quality={q:.3f} cost=${c:.4f} n={n}")
if __name__ == "__main__":
main()quality floor: 0.85 cases: 12 models: ['fast', 'frontier', 'smart']
policy cost quality cost_ratio qual_gap
always-fast $ 0.0134 0.659 0.15x -0.251
always-smart $ 0.0530 0.857 0.60x -0.053
always-frontier $ 0.1860 0.938 2.10x +0.027
rules-difficulty $ 0.0848 0.901 0.96x -0.009
cascade-fast-smart $ 0.0848 0.901 0.96x -0.009
ORACLE $ 0.0885 0.910
rules-difficulty per language slice (quality, cost, n):
en: quality=0.919 cost=$0.0056 n=8
hi: quality=0.860 cost=$0.0086 n=2
ta: quality=0.870 cost=$0.0112 n=2Read it: always-frontier buys +0.027 quality over the oracle at 2.1× the cost; always-fast is about 6.6× cheaper than the oracle but loses a quarter of quality. The rules-difficulty policy lands within 4% of oracle cost at −0.009 quality — but read that row with the caveat from the code: it cheats. It assigns each case by its true difficulty label, which no router can see at request time, and cascade-fast-smart similarly reads per-case outcomes that only exist after the fact. Treat both as the ceiling for perfect difficulty knowledge; the deployable version replaces the label with a predicted route, and the classifier's errors are the gap between this table and production — Part 4 measures exactly that gap. Whether it survives production is Part 4's question.
Part 4: Evaluating a router#
A router is a model-selection policy, and like any policy it must be evaluated against data — not vibes. The offline evaluator from 3.7 gives you the machinery; this part gives you the metrics and the traps.
4.1 The metrics: oracle, regret, frontier, slices#
Given a results table (every candidate model × every eval case, with quality and cost), four numbers decide whether a router is worth keeping:
| Metric | Definition | What it tells you |
|---|---|---|
| Oracle bound | Per-case cheapest model meeting the quality floor (else best quality) | The ceiling: no router can beat it. If your router is already at 95% of oracle efficiency, more routing engineering has diminishing returns |
| Cost ratio / regret | router_cost / oracle_cost at the same quality floor |
The money. A ratio of 0.96 means you spent 4% less than perfect routing — or that your "oracle" floor was set wrong |
| Quality gap | router_quality − oracle_quality |
The risk. Negative means you're shipping worse answers than the best assignment would have |
| Per-slice deltas | The same metrics split by language, feature, difficulty, tier | Where the router wins and where it quietly loses — the aggregate hides this |
The demo output showed the shape: rules-difficulty at 0.96× cost / −0.009 quality is a good router on this table — with the §3.7 caveat attached. rules-difficulty and cascade-fast-smart are oracle-assisted: they read the true difficulty label and per-case outcomes that do not exist at request time, so they show the ceiling for perfect routing knowledge, not a deployable policy. A real router predicts the route from RouteFeatures, and its prediction errors are the gap between this table and production — which is what 4.2 exists to measure. But look at the per-language slice from the real run:
rules-difficulty per lang: en q=0.919 c=$0.0056 n=8 | hi q=0.860 c=$0.0086 n=2 | ta q=0.870 c=$0.0112 n=2English traffic is fine; Hindi and Tamil pay more per case (longer tokenisations, 02.9, 10.7) and score lower. A router tuned on the aggregate would never see this. Always evaluate per slice before shipping a routing change — the same discipline as Module 10A's per-slice evals.
4.2 Router accuracy vs downstream quality — and label leakage#
Two subtleties separate a router that looks good from one that is good:
- Router accuracy ≠ downstream quality. A classifier that picks the "right" difficulty label 95% of the time can still route badly if the labels don't match cost. Measure the outcome (cost at equal quality), not the label agreement. A router that confuses "medium" and "hard" but sends both to adequate models may beat a "more accurate" router whose errors are expensive.
- Label leakage. If your difficulty labels were assigned by "which model succeeded", and your classifier features include signals correlated with that outcome (e.g. you labelled by running the smart model and it happened to do well on short inputs), the classifier learns the label's artefacts, not real difficulty. The fix: label by human judgement of difficulty or by cheap-model failure, independently of the classifier's features, and keep a held-out slice the router never trained on. This is the same train/test discipline as 10A.2, applied to routing.
And one framing that keeps the demo honest: the two best-looking policies in the §3.7 table — rules-difficulty and cascade-fast-smart — are oracle-assisted upper bounds. They read information (the true label, the per-case outcomes) that is unavailable at request time, so no production router can reproduce their numbers exactly. The deployable version replaces the oracle's label with a predicted route — a RuleRouter on cheap features, a kNN classifier, an LLM-as-router — and classifier accuracy is the gap between this table and production. That is why this lesson's offline evaluator takes a case → model assignment rather than simulating the classifier: first prove the ceiling is worth chasing, then measure how close your predictor gets to it.
4.3 Online monitoring of routing decisions#
Offline evals tell you the router should work; production tells you whether it does. The signals to watch (11A.2 owns the dashboards):
- Route distribution over time — a sudden shift (all traffic to
smart) means a rule broke or a feature flag flipped. - Per-route quality proxies — thumbs-down rate, judge scores, abstention rate, schema-failure rate, per route.
- Cascade pass rate
p— the fraction of first-step attempts accepted. Whenpdrops, cascade cost rises silently (2.9). - Cost per request by route — catches a route silently escalating to a pricier model.
- Router-vs-served-model agreement — for cascades, which step actually served; for gateways,
response.modelvs what you asked for.
Join decision records to outcomes on request_id (the DecisionLog from 3.6) and you have a live router-eval feed: every production request becomes a labelled row for the next offline evaluation. That flywheel — production outcomes → new eval cases → re-tuned router — is the same loop 10A.9 describes for evals generally.
4.4 Distribution shift and router decay#
Routers decay for the same reasons models do: the traffic changes underneath them. New features, new languages, new user tiers, a provider model update that makes the "hard" tier easy — all silently invalidate the routing boundaries. The mitigations:
- Re-run the offline evaluator on a schedule (monthly, or on any model/prompt deploy).
- Monitor per-slice quality, not just aggregate — shift shows up in slices first.
- Version your routing config alongside prompts (04.10) so a routing change is a reviewable, revertible artefact.
- Keep the oracle computation cheap enough to run continuously on sampled production traffic.
Part 5: Portability across routed models#
Deep-dive
A router that can send the same request to three different models has a problem a single-model system never faces: the prompt, the output contract and the tool formats must work on all of them. This is where routing meets 04.9 (porting prompts) and 03.11 (the canonical interface).
5.1 Why routed models break prompts#
04.9, 4.1 lists the five portability failures — format habits, instruction weight, reasoning defaults, vocabulary, provider plumbing. Routing multiplies the exposure: instead of porting a prompt once, you port it across every model in every route's chain, and a cascade can hit two of them in one request. The practical rules:
- Write for the weakest model in the chain, not the strongest. If
fastcan't follow XML-structured prompts, don't use them — or keep per-model variants (5.2). - Prefer provider-appropriate output control over prompt pleading. Structured output via
output_schema(03.4) works across providers because the canonical client picks each provider's native mechanism (03.11, 5.2) — that's the whole point of the abstraction. - Reasoning defaults differ per model. A prompt tuned for a non-reasoning model can hurt on a reasoning model (02.8, Part 7). If your route mixes reasoning and non-reasoning models, the prompt must work for both — usually by being explicit about desired thoroughness rather than implying it.
5.2 Per-model prompt variants and versioning#
When one prompt genuinely can't serve all models in a route, keep per-model variants — but version them as a unit:
- Store variants keyed by (route, model-family) in your prompt library (04.10 owns
promptlib), not scattered through code. - A prompt version and a model version are one unit (04.9, 4.4):
chat.smart@sonnet-5.5andchat.smart@haiku-5.5can be different prompt texts, each evaluated separately. - The router's
RouteDecisionshould record which prompt variant was used alongside the model alias, so a quality regression can be attributed to prompt-vs-model-vs-route.
5.3 Structured output and tool formats across providers#
The canonical client already normalises the hard parts, but routing adds two checks:
- Structured output subsets differ per provider (03.4, Part 4). A schema that works on OpenAI's strict mode may exceed Anthropic's complexity limits or hit Gemini's unsupported keywords.
check_capabilities(03.11, 7.3) catches missing features; the schema linter from 03.4 catches subset violations before the call — run it per route, not once globally. - Tool formats differ (03.5, 03.11). Forced tool choice is
falseon Claude Sonnet/Opus 5.x — a route that relies ontool_choice: "required"will 400 the moment the cascade lands there. The capability registry records this; the router must respect it.
The discipline: one canonical interface, per-provider adaptation underneath, per-model prompt variants on top, and every combination eval'd before it ships. A route is only as portable as its weakest (prompt × model × schema) combination.
Part 6: Governance of model choice#
Deep-dive
Routing multiplies the number of models that can serve production traffic; governance keeps that number reviewed. Four mechanisms:
6.1 Allow-lists and approval for new models#
- Allow-list per route. A route's chain may only contain models on its approved list — enforced in the registry/config, not by convention. New model = new allow-list entry = a PR with eval evidence attached.
- Approval gate. Adding a model to production requires: eval results on the route's slice, data-policy check (1.5), cost/latency numbers, and a named owner. This is the same review discipline as a dependency upgrade, because it is one — you're adding a vendor to your runtime.
- The router enforces it.
ModelRouter/RuleRoutershould reject (or loudly log) any alias not in the route's allow-list; a router that can be pointed at an unapproved model by a config typo is a governance hole.
Here is that enforcement as code — a wrapper you put around any router from Part 3, appended to llm_service/router.py (it uses Router, RouteContext, RouteFeatures and RouteDecision from part 1):
# llm_service/router.py (appendix) — a fail-closed allow-list around any Router.
class RouteNotAllowed(RuntimeError):
"""A router picked an alias the feature's approved list does not contain."""
class AllowListRouter:
"""Wrap any Router and enforce the per-feature allow-list from 6.1.
allowed: {feature: {alias, ...}}. A feature with no entry gets `default_allowed`
(empty by default, so an unlisted feature fails closed). If the inner router's
alias is not allowed: use `safe_alias` when one is given and itself allowed
(the decision records what was blocked), otherwise raise RouteNotAllowed.
"""
name = "allow-list"
def __init__(self, inner: Router, allowed: dict[str, set[str]], *,
default_allowed: set[str] | None = None,
safe_alias: str | None = None) -> None:
self.inner = inner
self.allowed = {k: set(v) for k, v in allowed.items()}
self.default_allowed = set(default_allowed or ())
self.safe_alias = safe_alias
def route(self, ctx: RouteContext, feats: RouteFeatures) -> RouteDecision:
decision = self.inner.route(ctx, feats)
ok = self.allowed.get(ctx.feature, self.default_allowed)
if decision.alias in ok:
return decision
if self.safe_alias is not None and self.safe_alias in ok:
return RouteDecision(
alias=self.safe_alias, router=self.name,
reason=f"allow-list:blocked:{decision.alias}",
signals={**decision.signals, "blocked_alias": decision.alias,
"inner_router": decision.router})
raise RouteNotAllowed(
f"{decision.router} chose {decision.alias!r} for feature "
f"{ctx.feature!r}; allowed: {sorted(ok)}")A short check (demo_allowlist.py, stdlib only; a one-rule RuleRouter stands in for any router):
# demo_allowlist.py
from router import (AllowListRouter, RouteNotAllowed, RouteContext, RouteFeatures,
Rule, RuleRouter)
inner = RuleRouter([Rule("big", lambda c, f: f.approx_input_tokens > 8000, "frontier")],
default="smart")
ctx = RouteContext(feature="chat")
guard = AllowListRouter(inner, {"chat": {"fast", "smart"}}, safe_alias="smart")
print(guard.route(ctx, RouteFeatures(approx_input_tokens=200)).alias)
blocked = guard.route(ctx, RouteFeatures(approx_input_tokens=20000))
print(blocked.alias, blocked.reason)
strict = AllowListRouter(inner, {"chat": {"fast", "smart"}}) # no safe_alias: fail loudly
for feature, tokens in (("chat", 20000), ("unlisted", 10)):
try:
strict.route(RouteContext(feature=feature), RouteFeatures(approx_input_tokens=tokens))
except RouteNotAllowed as exc:
print("RouteNotAllowed:", exc)smart
smart allow-list:blocked:frontier
RouteNotAllowed: rules chose 'frontier' for feature 'chat'; allowed: ['fast', 'smart']
RouteNotAllowed: rules chose 'smart' for feature 'unlisted'; allowed: []Two design choices worth copying: an unlisted feature fails closed (empty default allow-list), and a blocked alias is recorded, not hidden (reason="allow-list:blocked:frontier", plus blocked_alias in the signals) so a config typo or a rule drifting toward an unapproved model shows up on the route-distribution dashboard of 4.3. Choose safe_alias only when degrading to a cheaper approved model is acceptable for that feature; for a route with a data-policy constraint, raising is usually the right behaviour.
6.2 Deprecation tracking and migration playbooks#
1.6 covered the mechanics; governance adds the ownership:
- A scheduled check (CI cron or daily job) audits configured routes against provider lifecycle APIs — the pattern from 02.9, 8.3 and
provider_agnostic/refresh.py(03.11, 7.4). - A migration runbook per route: candidate → eval → canary → cutover → rollback window. Write it once, reuse it every deprecation.
- Deprecation is a scheduled task, not an incident. The alert fires at ~90 days, not at shutdown day.
6.3 The model inventory#
The artefact from 1.7, kept live: route × model × provider × purpose × data-policy × owner × eval-result × status. It's the answer to "which models can touch customer data", "who owns this route", and "what did we eval this against" — the three questions an auditor or incident review asks first. Keep it in version control next to the route config; generate views from it rather than maintaining parallel lists.
6.4 Cost caps per route#
Routing can increase spend as easily as decrease it (a broken rule sends everything to frontier). Guardrails:
- Per-route budget alerts (11A.2 owns the alerting; the route label on every cost record is what makes it possible — 03.7 owns the cost tracker).
- Per-route rate limits where a runaway cascade could double-spend (03.7, Part 12 owns token buckets).
- Cascade cost ceilings — the
max_cost_usdvalidator in 3.3 is the per-request version; the monthly budget is the aggregate.
Common misconceptions#
| Misconception | Reality |
|---|---|
| "The biggest model is always safest." | On your eval set the frontier model is often dominated — a mid model at equal quality for a third of the cost. Safety comes from evals, not parameter count |
| "Routing is just fallbacks." | Fallbacks handle errors; routing decides which model gets the request in the first place and whether a successful answer should escalate. Different problems, different code (2.2) |
| "A cascade always saves money." | Only if the cheap model's pass rate p stays high. Every point of p lost costs the second model's price; measure p in production, not just in evals (2.9) |
| "The router's accuracy is what matters." | Downstream cost-at-equal-quality is what matters. A 'less accurate' router whose errors are cheap beats an 'accurate' one whose errors are expensive (4.2) |
| "Hosted routers (OpenRouter Auto, Azure model-router) know my workload." | They optimise for general benchmarks, live prices and generic quality predictions, not your eval set. Treat them as a baseline to beat or a stopgap, and always log which model actually served |
| "Once the router is tuned, it's done." | Traffic drifts, models update, languages shift. Re-run the offline evaluator on a schedule and monitor per-slice quality (4.4) |
| "Pinning a model ID means its behaviour is frozen." | Even pinned snapshots drift via serving infrastructure, safety classifiers and API-version changes (02.9, 8.1). Pinning removes announced change; monitoring catches the rest |
| "Rules are simpler than classifiers, so start there." | Rules are simpler and brittle. Start with rules for clear signals (tier, media, size), move to kNN/LLM classifiers when rules get unwieldy — but only with labelled outcome data (2.10) |
Key takeaways#
- Selection is offline, routing is online. Choose models per task from your eval set's quality–cost–latency frontier; route per request with rules, cascades, classifiers or gateways. You need both.
- Decompose by difficulty, not topic. "Billing questions" isn't a route; "easy FAQ vs disputed-charge investigation" is. Wrong boundaries hide in the aggregate.
- The frontier is per slice. A single model is rarely cheapest-at-equal-quality for every slice — that gap is the router's maximum saving, and the oracle bound is its ceiling.
- Cascades escalate on quality signals, not just errors. Validators range from free (finish reason, schema) to costly (judge model); the cheap model's confident wrong answers are the residue every validator misses.
- Sticky hashing makes A/B and canary safe. Same user → same arm; weights set the split. Use it for model releases, not just prompt tests.
- Gateways route endpoints; your router routes semantics. LiteLLM/Portkey/OpenRouter/Cloudflare handle cost/latency/failover within a route; your app decides which route a request enters. Keep the decisions separate and logged under one request ID.
- Evaluate the router like a model. Oracle bound, cost ratio, quality gap, per-slice deltas — offline on your eval table, online on production outcomes joined by
request_id. - Portability is per (prompt × model × schema). One canonical interface underneath, per-model prompt variants on top, every combination eval'd before it ships.
- Governance is the allow-list, the inventory and the deprecation calendar. New model = reviewed PR with eval evidence; migration is a runbook, not an incident.
What this means for you#
If you take one thing from this lesson, take this: model choice is a system, not a config value. The teams that get routing wrong treat it as "pick a model and maybe add a fallback"; the teams that get it right treat it as an evaluated pipeline — select candidates on your data, decompose traffic into routable slices, choose the cheapest pattern that clears the quality bar, log every decision, and re-evaluate on a schedule.
Concretely, for your next LLM feature:
- Write the route table first (1.2) — before any code. If you can't name the slices and their quality bars, you can't route them.
- Run your eval set across two or three candidate tiers and find the frontier (1.3). The cheapest model that clears the bar with margin is your baseline; everything else is a routing opportunity.
- Start with static + rules (2.3, 2.4) — they're testable, cheap and cover most traffic. Add a cascade only where you can name a validator (2.9).
- Log decisions before calls (3.6) — it's the difference between "the router seems fine" and "here's exactly which rule sent this request where, and what it cost".
- Evaluate the router like a model (Part 4) — oracle bound, cost ratio, quality gap, per-slice. If you can't beat always-smart on cost at equal quality, don't ship the router.
- Govern it from day one (Part 6) — allow-list, inventory, deprecation calendar. Retrofitting governance onto a live router is ten times harder than starting with it.
The routers and gateways in 2.11–2.12 are force multipliers, not replacements: they implement patterns you'd otherwise build, but they can't tell you whether the pattern is right for your traffic. That judgement comes from your evals — which is why the offline evaluator in 3.7 is the most important piece of code in this lesson.
Terms introduced in this lesson#
| Term | Meaning |
|---|---|
| Model selection | The offline decision of which models may serve which tasks, made from eval evidence |
| Routing | The online, per-request decision of which model/route serves a given call |
| Route | A named lane (e.g. chat.fast, extract.invoice) bound to an ordered chain of acceptable models |
| RouteFeatures | Cheap request signals (size, media, tools, language, tier) extracted before any model call |
| RouteDecision | The router's output: alias + router + reason + signals, logged before the call |
| Quality–cost–latency frontier | The set of non-dominated (quality, cost, latency) points across candidate models on your eval set |
| Oracle bound | The best possible per-case model assignment under a quality floor — the ceiling for any router |
| Regret | How much more a policy costs (or loses in quality) versus the oracle |
| Cascade | Trying a cheap model first and escalating to a stronger one when a validator fails |
| Validator | A check on a cascade step's answer: finish reason, schema validity, business rules, judge |
| Classifier router | A small model or embedding+kNN that predicts the route from request features |
| Learned router | A router trained on preference/outcome data (RouteLLM-style, vLLM Semantic Router, hosted routers) |
| Sticky hashing | Assigning users to arms by a stable hash so A/B and canary splits are consistent per user |
| Shadow traffic | Running a candidate model on real requests in parallel, results logged but not shown |
| Model inventory | The governed list of route × model × provider × purpose × data-policy × owner × eval-result |
| Deprecation calendar | The scheduled tracking of model lifecycle dates and the migration runbook per route |
| Active-active | Multiple providers serving the same route simultaneously, weighted by health/cost |
| Per-model prompt variant | A prompt text tuned for a specific model family within a route, versioned with the model |
All terms are also collected in the glossary.
Exercises#
-
Build the route table. Take one feature from your own project (or the support-bot example). Write its route table from 1.2: slices, quality bars, latency budgets, constraints. Then list which slices you'd actually route separately vs merge — and why.
-
Run the rules router. Copy
router.pyfrom Part 3 anddemo_router.pyfrom 3.5. Indemo_router.pytheenterpriserule comes first. Move it after themediarule and compare the decisions for the same requests. Which requests change route, and which order do you want? -
Sticky split sanity. Using
WeightedSplitRouterwith arms[(90, "stable"), (10, "canary")], write a loop over 1000 fakesession_keys and print the canary share. Then change the salt and re-run — does the set of canary users change? Why is that desirable for a rollout? -
Cascade economics. With
c1 = $0.001,c2 = $0.005, computeE[cost]forp∈ {0.5, 0.7, 0.9}. At whatpdoes the cascade beat always-smart ($0.005)? Now suppose the cheap model's pass rate is 0.9 in evals but 0.75 in production — what's the cost delta per 10k requests? -
Offline evaluator on real data. Run your evalkit suite (Module 10A) on two model tiers for one task. Build a
ResultsTablefrom the results and compute the oracle bound and your rules-router's regret withrouter_eval.py. What's the maximum saving a perfect router could achieve? -
Per-slice check. Take the evaluator output and add a
langordifficultyslice. Does the router's quality hold per slice, or does the aggregate hide a weak spot? -
Portability audit. Pick a route that mixes two model families. List every place the prompt, schema and tool definitions could diverge between them — then check each against 03.4 and 03.5.
-
Governance review. Write the model inventory row for one route in your project: model, provider, purpose, data policy, owner, eval result, status. What's missing?
-
Allow-list. Wrap your rules router in
AllowListRouter(6.1) withsafe_aliasset. Then try a config typo (a rule that returns"frotnier"): where does it show up — the response, the decision log, the dashboard? Which routes should instead raise?
Hints for the exercises
- With the
enterpriserule first, an enterprise user who attaches an image goes tosmart; after the move the same request goes tovision, because the first match wins. If you keep the original order, check thatsmartcan accept images (the capability gate of 1.4). - Expect about 10% canary (the hash is uniform, so a few percentage points of noise at 1,000 keys). A new salt re-draws which users are canary, which is what you want between two separate rollouts so the same users are not always the guinea pigs; within one rollout the salt must not change.
E = c1 + (1-p)·c2gives $0.0035, $0.0025 and $0.0015 for p = 0.5, 0.7, 0.9. The cascade beats always-smart whenc1 + (1-p)·c2 < c2, i.e. whenp > c1/c2 = 20%here. At 10,000 requests a drop from p = 0.9 to p = 0.75 raisesEfrom $0.0015 to $0.00225, which is $7.50 more per 10k requests.- The saving of a perfect router is
always-smart cost − oracle cost(at the same quality floor); your router's regret is how much of it you fail to capture. - Slice on language first: tokenisation cost and quality both differ for non-Latin scripts (4.1).
- Typical divergence points: XML versus JSON prompt habits, schema keywords one provider rejects, forced tool choice, reasoning defaults, system-prompt placement.
- Commonly missing: the owner, the review-by date and the eval set version.
- A typo'd alias is not on the allow-list, so the wrapper substitutes
safe_aliasand recordsallow-list:blocked:frotnierin the decision log; the route-distribution dashboard shows the shift. Routes with a data-policy constraint should raise instead.
Check yourself#
- What's the difference between model selection and model routing?Selection is the offline, per-task decision of which models may serve which work, made from eval evidence. Routing is the online, per-request decision of which model/route serves a given call.
- Why is "route by topic" usually wrong, and what should you route by instead?Topic isn't difficulty — "billing questions" mixes easy FAQs and hard dispute investigations. Route by what a good answer requires (difficulty, modality, context, risk), not by subject.
- What are the three axes of the quality–cost–latency frontier, and why is the frontier per-slice rather than per-feature?Quality, cost per task, latency. The frontier is per-slice because different slices have different capability mixes; a single model is rarely cheapest-at-equal-quality for all of them — that gap is the router's maximum saving.
- Name four capability checks that should gate a model before it enters a route's chain.Tools, forced tool choice, structured output, images/documents, reasoning, context window, stop sequences — the
Capabilitiesrecord in the registry (03.11, Part 7). - Why must a cascade's fallback chain honour the same data policy as the primary?An outage is exactly when a permissive fallback leaks data. The fallback must honour the same ZDR/residency/training-use terms or it violates policy at the worst moment.
- What's the difference between
provider.sort: "price"and the:floorvariant on OpenRouter?provider.sort: "price"sorts endpoints by price;:floordoes that and admits flex-tier endpoints into the eligible pool. Billing follows whichever tier actually serves. - In a weighted split, why does a user need a stable hash rather than a random assignment per request?A user whose answers come from different models across turns gets inconsistent behaviour, and provider-side caches only warm if the same prefix hits the same provider. Sticky hashing keeps a user on one arm.
- What does the oracle bound represent, and why is it the ceiling for any router?The best possible per-case assignment under a quality floor — no router can beat it. It's the ceiling that tells you when more routing engineering has diminishing returns.
- What's label leakage in router evaluation, and how do you avoid it?When router labels are assigned by an outcome correlated with the classifier's features, the classifier learns the label's artefacts. Label by human difficulty judgement or cheap-model failure, independently of the features, and keep a held-out slice.
- Why is "router accuracy" the wrong metric for a cascade?Because a router that picks the "right" label can still route badly if the labels don't match cost. Measure cost-at-equal-quality, not label agreement.
- Name three hosted/learned routers and one reason each might not fit your workload.OpenRouter Auto (black-box: a decision model plus a policy over general benchmarks and live prices), Azure model-router (Foundry-only; context window of the smallest model in the pool), Amazon Bedrock prompt routing (within-family only, English-only), RouteLLM (unmaintained since ~2024), Martian (router docs gone, emphasis shifted to research). Each has scope or maintenance limits.
- What's the difference between gateway routing (LiteLLM
latency-based-routing) and your app'sRuleRouter?Gateway routing decides which endpoint serves a model (cost/latency/failover within a route); your app's router decides which route a request enters (semantics, user tier, feature). Different layers, both needed. - Why should a prompt version and a model version be treated as one unit?Because a prompt tuned for one model can break on another;
chat.smart@sonnetandchat.smart@haikumay need different prompt texts, each eval'd separately. - What four things does governance require before a new model enters production?Eval evidence on the route's slice, data-policy check, cost/latency numbers, and a named owner — a reviewed PR, not a config edit.
Further resources#
- 11B.2 — Tokenomics: the price spread between tiers (about 80 times) that makes routing worth building, with worked RAG and batch examples.
- Lesson 02.9, Part 10: the selection framework this lesson extends — requirements, constraints, shortlist, eval, pick, operate.
- Lesson 02.9, Part 8: aliases vs snapshots, lifecycle stages, notice periods, pinning.
- Lesson 02.9, 10.6: the routing/cascade preview this lesson implements.
- Lesson 03.11: the
provider_agnosticclient, capability registry and fallback chains the router sits on top of. - Lesson 04.8, 2.4: the prompt pattern for LLM-based routing.
- Lesson 04.9, Part 4: prompt portability across models and providers.
- Lesson 04.10: prompt versioning and A/B testing.
- Module 10A: eval datasets, metrics and the offline/online evaluation loop the router is measured by.
- OpenRouter docs: Auto Router, Auto Code, Pareto Router, Model Fallbacks (
modelsarray), Presets, Model Variants, Provider Selection. - LiteLLM docs: Router, Load Balancing, Fallbacks.
- Portkey docs: Conditional Routing, Load Balancing; gateway repo Portkey-AI/gateway (MIT).
- RouteLLM: lm-sys/RouteLLM (Apache-2.0; reference for learned routers, maintenance sporadic as of Nov 2026).
- vLLM Semantic Router: vllm-project/semantic-router (
vllm-sr0.4.0 on PyPI), docs (v0.4: signals → projections → decisions → algorithms → recipes). - Amazon Bedrock: Intelligent Prompt Routing.
- Google: ModelOptimizer quickstart notebook (official GoogleCloudPlatform repo), ModelRoutingPreference, GenerationConfig (REST:
routingConfig,autoMode,manualMode), GenerationConfig.RoutingConfig (Python SDK), API Gateway model routing (Public Preview). - Microsoft Foundry: Model router, How it works.
- Cloudflare AI Gateway: Dynamic Routes, Model aliases.
← 11B.4 — Token Caching in Depth: How It Works, Who Supports It, and How to Use It | Module 11B overview | 11B.6 — Budgets, Quotas, Cost Attribution and Chargeback →