Model routing and cost tiers
Build LLM-backed product features end to end against a deterministic local mock: form well-formed chat requests, structure prompts and validated JSON outputs, stream and retry safely, ground answers in retrieved sources, call tools inside bounded agent loops, defend against prompt injection, and evaluate quality with reproducible checks instead of one-off demos. No API keys and no network calls are used anywhere in the course.
What you will be able to do
#- Implement a tier-based routing table that maps task classes to mock models with a stated reason, and a safe default for unknown classes.
- Compute blended request cost in integer micro-USD across mixed model tiers and identify which call class dominates spend.
- Gate routing changes behind eval results and escalate on measured signals instead of intuition.
Overview
#Not every task needs the largest model
Routing is the practice of choosing the cheapest model tier that meets the quality bar for a task class. The unit of routing is the task class, not the request: classification, summarization, multi-step reasoning and long drafting have different quality bars, and the bar, not habit, picks the tier.
| Task class | Mock tier | Why it fits |
|---|---|---|
| Classification, extraction | mock-mini | Short outputs, deterministic prompts, high volume |
| Summarization of known documents | mock-mini | Grounded, bounded length (lesson 9) |
| Multi-step reasoning, agent loops | mock-max | Tool loops, higher stakes (lesson 11) |
| Long-form drafting | mock-mid | Quality matters, cost moderate |
The tier names are mock labels for this course. The transferable skill is the decision procedure: start from the task's quality bar, verify with evals, and pay for capability only where the bar demands it.
The routing table as code
const ROUTES = {
classify: { model: "mock-mini", reason: "short deterministic outputs" },
summarize: { model: "mock-mini", reason: "grounded bounded outputs" },
reason: { model: "mock-max", reason: "multi-step tool loops" }
};
function routeRequest(taskClass) {
const route = ROUTES[taskClass];
if (route === undefined) {
return { model: "mock-max", reason: "unknown class falls back to the strongest tier" };
}
return route;
}
A routing table is an allowlist, and the default for an unknown class is the safe direction: quality first, then optimize downward with eval evidence. A default of the cheapest tier would silently degrade every task someone forgot to register.
Blended cost arithmetic
Cost is per-request arithmetic (lesson 4), and a mixed fleet of tiers needs blended math. The prices below are invented mock values for clean integer arithmetic, not a real price list:
const MOCK_PRICES = {
"mock-mini": { inputUsdPerMillion: 1, outputUsdPerMillion: 4 },
"mock-max": { inputUsdPerMillion: 10, outputUsdPerMillion: 30 }
};
function callCostMicroUsd(model, inputTokens, outputTokens) {
const p = MOCK_PRICES[model];
return inputTokens * p.inputUsdPerMillion + outputTokens * p.outputUsdPerMillion;
}
function batchCostMicroUsd(calls) {
return calls.reduce((sum, c) => sum + callCostMicroUsd(c.model, c.inputTokens, c.outputTokens), 0);
}
Worked batch: 400 classify calls on mock-mini at 300 input and 20 output tokens, plus 20 reason calls on mock-max at 2000 input and 500 output tokens.
- Classify per call: 300 * 1 + 20 * 4 = 380 micro-USD; 400 calls: 152000.
- Reason per call: 2000 * 10 + 500 * 30 = 35000 micro-USD; 20 calls: 700000.
- Batch total: 852000 micro-USD, which is 0.852 USD.
The 20 heavy calls are about 82 percent of spend. That ratio is the whole argument for routing: the expensive tail dominates, so getting the heavy tasks onto the right tier matters more than shaving the light ones.
Escalation on measured signals
Routing down needs eval evidence (lesson 13); routing up needs a measured signal from the pipeline: low self-consistency agreement (lesson 14), repeated validation failures after bounded repair (lesson 5), or abstention storms on a task class. Escalation is a policy you can write down:
function routeWithEscalation(taskClass, agreement) {
const base = routeRequest(taskClass);
if (taskClass === "classify" && agreement < 0.8) {
return { model: "mock-max", reason: "agreement " + agreement + " below 0.8 escalated" };
}
return base;
}
Honest limits of the mock
Mock prices are invented for clean arithmetic; real routing decisions need measured latency, quality and price from your own traffic. Real routers also face per-model quota pools, rate limits (lesson 7), and capability drift: a tier that passed the eval last quarter can regress, which is why routing changes are deploy-gated like any other change. And the router itself is a failure mode: a routing bug that sends every request to the expensive tier is invisible without a batch-cost metric (lesson 16).
Continue with ai-engineering-security-review to audit the assembled feature before launch.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Implement
Implement routeRequest(taskClass) against the ROUTES table: a known class returns its route object; an unknown class returns { model: "mock-max", reason: "unknown class falls back to the strongest tier" }. Log the routes for "classify" and "translate".
starter.javascriptconst ROUTES = { classify: { model: "mock-mini", reason: "short deterministic outputs" }, summarize: { model: "mock-mini", reason: "grounded bounded outputs" }, reason: { model: "mock-max", reason: "multi-step tool loops" } }; function routeRequest(taskClass) { // Known class -> its route object. // Unknown class -> { model: "mock-max", reason: "unknown class falls // back to the strongest tier" }. } console.log(JSON.stringify(routeRequest("classify"))); console.log(JSON.stringify(routeRequest("translate")));Reveal the reference answer
reference.javascriptconst ROUTES = { classify: { model: "mock-mini", reason: "short deterministic outputs" }, summarize: { model: "mock-mini", reason: "grounded bounded outputs" }, reason: { model: "mock-max", reason: "multi-step tool loops" } }; function routeRequest(taskClass) { const route = ROUTES[taskClass]; if (route === undefined) { return { model: "mock-max", reason: "unknown class falls back to the strongest tier" }; } return route; } console.log(JSON.stringify(routeRequest("classify"))); console.log(JSON.stringify(routeRequest("translate")));Authored expected output: {"model":"mock-mini","reason":"short deterministic outputs"} {"model":"mock-max","reason":"unknown class falls back to the strongest tier"}
classify hits the table and routes to the cheap tier; translate is unregistered and falls back to the strongest tier. The default direction is deliberate: an unregistered task degrades cost, not quality, and registering it is a tracked decision.
Exercise 2Implement
Implement callCostMicroUsd(model, inputTokens, outputTokens) and batchCostMicroUsd(calls) with the MOCK_PRICES table. Build the worked batch programmatically (400 classify calls at 300 input and 20 output tokens on mock-mini, 20 reason calls at 2000 input and 500 output tokens on mock-max) and log the batch total and the per-call cost of the heavy tier.
starter.javascriptconst MOCK_PRICES = { "mock-mini": { inputUsdPerMillion: 1, outputUsdPerMillion: 4 }, "mock-max": { inputUsdPerMillion: 10, outputUsdPerMillion: 30 } }; function callCostMicroUsd(model, inputTokens, outputTokens) { // inputTokens * input price + outputTokens * output price. } function batchCostMicroUsd(calls) { // Sum callCostMicroUsd over every call. } const batch = []; for (let i = 0; i < 400; i++) batch.push({ model: "mock-mini", inputTokens: 300, outputTokens: 20 }); for (let i = 0; i < 20; i++) batch.push({ model: "mock-max", inputTokens: 2000, outputTokens: 500 }); console.log(String(batchCostMicroUsd(batch))); console.log(String(callCostMicroUsd("mock-max", 2000, 500)));Reveal the reference answer
reference.javascriptconst MOCK_PRICES = { "mock-mini": { inputUsdPerMillion: 1, outputUsdPerMillion: 4 }, "mock-max": { inputUsdPerMillion: 10, outputUsdPerMillion: 30 } }; function callCostMicroUsd(model, inputTokens, outputTokens) { const p = MOCK_PRICES[model]; return inputTokens * p.inputUsdPerMillion + outputTokens * p.outputUsdPerMillion; } function batchCostMicroUsd(calls) { return calls.reduce((sum, c) => sum + callCostMicroUsd(c.model, c.inputTokens, c.outputTokens), 0); } const batch = []; for (let i = 0; i < 400; i++) batch.push({ model: "mock-mini", inputTokens: 300, outputTokens: 20 }); for (let i = 0; i < 20; i++) batch.push({ model: "mock-max", inputTokens: 2000, outputTokens: 500 }); console.log(String(batchCostMicroUsd(batch))); console.log(String(callCostMicroUsd("mock-max", 2000, 500)));Authored expected output: 852000 35000
Each classify call costs 300 * 1 + 20 * 4 = 380 micro-USD, so 400 calls cost 152000. Each reason call costs 2000 * 10 + 500 * 30 = 35000, so 20 calls cost 700000. The batch total is 852000 micro-USD, and the 20 heavy calls are about 82 percent of it: the tail dominates spend.
Exercise 3Predict
routeWithEscalation(taskClass, agreement) escalates a classify task to mock-max when agreement is below 0.8. Predict the three logged lines for classify at 0.95, classify at 0.6, and reason at 0.6.
starter.javascriptconst ROUTES = { classify: { model: "mock-mini", reason: "short deterministic outputs" }, summarize: { model: "mock-mini", reason: "grounded bounded outputs" }, reason: { model: "mock-max", reason: "multi-step tool loops" } }; function routeRequest(taskClass) { const route = ROUTES[taskClass]; if (route === undefined) { return { model: "mock-max", reason: "unknown class falls back to the strongest tier" }; } return route; } function routeWithEscalation(taskClass, agreement) { const base = routeRequest(taskClass); if (taskClass === "classify" && agreement < 0.8) { return { model: "mock-max", reason: "agreement " + agreement + " below 0.8 escalated" }; } return base; } console.log(JSON.stringify(routeWithEscalation("classify", 0.95))); console.log(JSON.stringify(routeWithEscalation("classify", 0.6))); console.log(JSON.stringify(routeWithEscalation("reason", 0.6)));Reveal the reference answer
reference.javascript// Predicted output: // // {"model":"mock-mini","reason":"short deterministic outputs"} // {"model":"mock-max","reason":"agreement 0.6 below 0.8 escalated"} // {"model":"mock-max","reason":"multi-step tool loops"} // // Trace: classify at 0.95 clears the 0.8 threshold and keeps the cheap // tier. classify at 0.6 is below the threshold, so the measured signal // escalates it to mock-max with the reason recorded. reason at 0.6 is // already mock-max, and the escalation rule only rewrites classify, so // the base route stands.Authored expected output: {"model":"mock-mini","reason":"short deterministic outputs"} {"model":"mock-max","reason":"agreement 0.6 below 0.8 escalated"} {"model":"mock-max","reason":"multi-step tool loops"}
Escalation fires on a measured agreement signal, not on a hunch, and the reason string records why the expensive tier was chosen. That reason field is what makes routing decisions auditable later.
Exercise 4Explain
Knowledge check: what must gate moving a task class from the strongest tier to a cheaper one?
starter.text// Choose the correct option.Reveal the reference answer
reference.textAn eval set showing the cheaper model meets the quality bar for that task class, run in CI like any other change. Cost savings without measured quality evidence are just a quiet quality regression with a smaller bill.Authored expected output: Eval evidence that the cheaper tier meets the quality bar
Routing changes are behavior changes; lesson 13's eval gate is what keeps them honest, and lesson 14's measured signals handle the escalation direction.
Common misconceptions
#- Myth: always use the biggest model. Fact: tiered routing with eval-gated downgrades and signal-based escalation matches cost to task difficulty; the biggest model everywhere is a cost bug.
- Myth: routing is a one-time decision. Fact: model behavior and prices drift; a routing table is configuration that changes under eval coverage, not a constant.
- Myth: cost is an afterthought measured at the end of the month. Fact: cost is per-request arithmetic you can compute, log and alert on; the heavy tail of calls usually dominates spend.
Follow-up practice
#- ai-engineering-security-review
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.