Sub topic 16
Routing requests between small and large models
This chapter assumes you have read the chapters on model sizes, token pricing, and evaluation. You should be comfortable calling a chat API from Python and reading short functions. Routing builds on a simple observation: most traffic in a real application is easy, and a small model can handle easy requests at a fraction of the cost.
Why route at all
The decision process in this tutorial picks the smallest model that meets your requirements. That rule has a weakness. If 85% of requests are easy and 15% are hard, a single small model fails the hard ones. A single large model passes everything but overpays for the easy majority.
Routing removes that trade-off. A router is a piece of code that looks at each request and chooses which model should answer it. The usual setup has two tiers:
- A small, cheap, fast model for routine requests.
- A large, more capable, slower model for requests the small one is likely to get wrong.
Routing is also a reliability tool. The same mechanism that sends hard requests to a large model can send requests to a second provider when the first one is down.
Three routing strategies
Rule-based routing
The router uses properties you can read directly from the request: task type, input length, the customer's plan, or a flag set by your own code. It is the simplest strategy, it needs no extra model call, and its behavior is easy to predict and test.
Examples:
- Classification and field extraction go to the small model. Open-ended analysis goes to the large one.
- Inputs longer than the small model's context window go to a model with a larger window.
- Requests marked "premium" go to the large model.
The weakness is that rules only capture what you thought of in advance. Two requests of the same task type can differ a lot in difficulty.
Classifier-based routing
A small model, or a cheap call to the small model, rates the request first, and the rating decides where it goes. A typical prompt asks for one word: simple or complex. This adapts to the content of each request. The cost is one extra call, so it only pays off when the classification is much cheaper than the savings it creates. It also adds latency to every request.
Cascade (escalation)
The cascade sends every request to the small model first. If the answer fails a check, the request is sent to the large model. Checks can be:
- Output validation: the reply must parse as JSON, match a schema, or contain a value from an allowed list.
- A confidence signal: the model says it is unsure, or returns a refusal.
- A verifier: a second call or a rule that tests the answer.
The cascade is safe by construction, because anything the small model cannot handle is retried on the large one. Its cost is that escalated requests pay for both calls and wait for both.
| Strategy | Extra cost per request | Adapts to content | Main risk |
|---|---|---|---|
| Rule-based | None | No | Rules miss hard cases |
| Classifier-based | One small call | Yes | Misclassification, added latency |
| Cascade | Second call only when escalated | Yes | Slow and costly if many requests escalate |
How the pieces fit together
The diagram shows a cascade with a fallback for provider failures.
Estimating the savings
Use the token-price arithmetic from the earlier chapter. Suppose the small model costs $0.25 per million input tokens and $1.00 per million output tokens, and the large model costs $3.00 and $12.00. These are made-up prices. Each request has 2,000 input tokens and 300 output tokens.
The code below computes the expected cost per request for a cascade, given the share of requests that escalate.
def request_cost(input_tokens: int, output_tokens: int,
price_in: float, price_out: float) -> float:
return (input_tokens / 1_000_000) * price_in + \
(output_tokens / 1_000_000) * price_out
SMALL = (0.25, 1.00) # $ per million tokens: input, output
LARGE = (3.00, 12.00)
def cascade_cost(escalation_rate: float, in_tok: int = 2_000, out_tok: int = 300) -> float:
small = request_cost(in_tok, out_tok, *SMALL)
large = request_cost(in_tok, out_tok, *LARGE)
# Every request pays for the small call. Escalated ones also pay for the large call.
return small + escalation_rate * large
all_large = request_cost(2_000, 300, *LARGE)
for rate in (0.0, 0.1, 0.2, 0.4, 0.8):
cost = cascade_cost(rate)
print(f"escalation {rate:.0%}: ${cost:.5f} per request "
f"({cost / all_large:.0%} of all-large)")With these prices, an all-large setup costs $0.00960 per request. A cascade with 20% escalation costs about $0.00096 + ... in total roughly $0.0029, or about 30% of the all-large price. At 80% escalation the cascade costs about $0.0086, which is close to the all-large cost, and it adds latency. The break-even point depends on the price ratio between the two models. The larger the ratio, the more escalation you can tolerate.
Measuring a router
A router is a model-selection decision, so evaluate it the same way you evaluated models. Reuse your evaluation set and record, for each case, which model answered and whether the answer passed.
Track three numbers:
- Quality: the overall pass rate of the routed system. It should be close to the large model's pass rate.
- Escalation rate: the share of requests that reach the large model.
- Cost and latency per request, including the cost of failed small-model attempts.
The sketch below reuses the pass_rate idea from the evaluation chapter and adds routing.
cases = [
{"prompt": "Extract the invoice number: 'Invoice INV-2041, due May 3'", "expected": "INV-2041"},
{"prompt": "Extract the invoice number: 'Ref: INV-17, total $90'", "expected": "INV-17"},
]
def route_and_answer(prompt: str, ask_small, ask_large, is_valid) -> tuple[str, bool]:
"""Return (answer, escalated)."""
answer = ask_small(prompt)
if is_valid(answer):
return answer, False
return ask_large(prompt), True
def evaluate_router(cases, ask_small, ask_large, is_valid):
passed = escalated = 0
for c in cases:
answer, esc = route_and_answer(c["prompt"], ask_small, ask_large, is_valid)
passed += c["expected"] in answer
escalated += esc
n = len(cases)
return {"pass_rate": passed / n, "escalation_rate": escalated / n}
# Stand-in models so the example runs without any API.
def ask_small(prompt):
return "INV-2041" if "2041" in prompt else "not sure"
def ask_large(prompt):
return "INV-17"
def is_valid(answer):
return answer.startswith("INV-")
print(evaluate_router(cases, ask_small, ask_large, is_valid))
# {'pass_rate': 1.0, 'escalation_rate': 0.5}Common errors
- Validating too weakly. A check that only tests the format accepts a well-formed wrong answer. An invoice number that looks right can still be the wrong number. Add checks that test content where you can.
- Ignoring the cost of the first attempt. In a cascade, escalated requests pay twice. Include both calls in your estimates.
- Routing on an unmeasured assumption. "Short prompts are easy" may be false for your task. Test the rule on your evaluation set before relying on it.
- Mixing prompts across models. A prompt tuned for one model can behave differently on another. Check that each tier passes your cases with its own prompt.
- Averaging away the hard cases. A high overall pass rate can hide failures concentrated in one category. Break results down by task type.
- Silent fallbacks. If a fallback provider has different data-handling terms, routing to it can break your privacy requirements. Apply the same privacy review to every model in the route.
- Letting the router drift. Traffic changes over time. Log the route taken for each request and review the escalation rate regularly.
Keep routing simple
Routing adds code, tests, and monitoring. It earns its place when three conditions hold: the traffic is mixed in difficulty, the price gap between tiers is large, and a reliable check or rule can separate easy from hard. If one small model already passes your cases, do not add a router. If almost every request needs the large model, use the large model.
Routing also depends on the portability work from the previous chapter. If your code reads the endpoint and model name from configuration, each tier is just another configuration entry, and adding a tier is a small change.
Exercise
Your small model costs $0.50 per million total tokens and your large model costs $5.00 per million total tokens. Each request uses 2,000 tokens in total, and you run a cascade where every request goes to the small model first. What is the highest escalation rate at which the cascade still costs no more than sending everything to the large model? Which strategy would you consider if escalation is expected to be above that rate?
Show answer
Per request, the small call costs 2,000 / 1,000,000 × $0.50 = $0.001, and the large call costs 2,000 / 1,000,000 × $5.00 = $0.01. The cascade costs 0.001 + rate × 0.01. Setting this equal to 0.01 gives rate = 0.009 / 0.01 = 0.90, so the break-even escalation rate is 90%. Above that rate, the cascade costs more than all-large, and it is also slower. In that situation, consider rule-based or classifier-based routing to send likely-hard requests straight to the large model, or drop routing and use the large model alone.
Exercise
Name two failure modes of a cascade whose only validation check is "the output parses as JSON", and one way to reduce each.
Show answer
First, the small model can return valid JSON with wrong values, so wrong answers are never escalated. Reduce this by adding content checks, such as an allowed-values list, a pattern for IDs, or a verifier step. Second, the check can reject correct answers that are formatted differently, which raises the escalation rate and the cost. Reduce this by logging escalations, reviewing a sample, and fixing the prompt or loosening the check where the small model was actually right.