Sub topic 11
Routing steps to the right model
This chapter assumes you have read the earlier chapters on token pricing, agent loop cost, model tiers and subagents. You should be able to read short Python programs and know that a coding agent runs a loop of model calls and tool calls.
What routing is and why it pays
An agent session is not one kind of work. Planning a refactor needs careful reasoning. Summarizing 3,000 lines of test output needs very little. If every step goes to the same large model, you pay large-model rates for work a small model would do equally well.
Routing means choosing a model for each step of the loop, instead of choosing one model for the whole session. The goal is to spend capability where it changes the result and save money where it does not.
Routing only helps if two things are true:
- The steps differ in difficulty. Most coding sessions do contain a mix.
- The cheaper model does the easy steps as reliably as the expensive one. You have to check this, not assume it.
Step kinds
Routing needs a label for each step. The label is called the step kind. It is a short string the agent code sets before it calls a model. Typical kinds in a coding agent:
| Step kind | What the step does | Typical tier |
|---|---|---|
| plan | Decide the approach, break down the task | Large |
| edit | Write or change code | Mid |
| summarize_tool_output | Condense logs, search results or file contents | Small |
| run_tests | Choose test commands and read pass/fail | Small |
| review | Check a finished diff for mistakes | Large or mid |
The tiers here are placeholders. Your provider's names and prices will differ, and they change over time.
A routing policy as a lookup table
The simplest policy is a dictionary from step kind to model, with a default for kinds the table does not list.
ROUTES = {
"plan": "large-model",
"edit": "mid-model",
"summarize_tool_output": "small-model",
"run_tests": "small-model",
}
def pick_model(step_kind, default="mid-model"):
return ROUTES.get(step_kind, default)
print(pick_model("plan")) # large-model
print(pick_model("other")) # mid-modelThe default matters. A new step kind that nobody added to the table will land on the default. Choose a default that is safe to be wrong about. A mid-tier model is usually a better default than the smallest one, because a silent quality drop on an unlisted step is harder to notice than a slightly higher bill.
A lookup table has real advantages over cleverer approaches:
- It is deterministic. The same step kind always gets the same model, so results are reproducible.
- It is easy to read and review. A change to the policy is a one-line diff.
- It costs nothing to run. There is no extra model call to decide the route.
How routing interacts with caching
Routing has a hidden cost that the lookup table does not show. Prompt caching, covered earlier, works per model. A cached prefix written for one model cannot be read by another. If a session alternates between a large and a small model on a long shared context, each switch can mean paying to write that context into a new cache and losing the discount.
The diagram shows the effect.
Switching is not always a loss. If the small model's input rate is far lower than the large model's, even an uncached read on the small model can cost less than a cached read on the large one. Compute it for your prices before deciding. The function from the caching chapter makes the comparison direct.
def input_cost_with_cache(context_tokens, cached_prefix_tokens, price_input, cache_read_multiplier):
"""Input cost in USD for one turn when a prefix is read from cache."""
uncached = context_tokens - cached_prefix_tokens
effective_tokens = uncached + cached_prefix_tokens * cache_read_multiplier
return effective_tokens * price_input / 1_000_000
# Placeholder prices in USD per million input tokens.
large_cached = input_cost_with_cache(40_000, 35_000, 3.0, 0.1)
small_uncached = input_cost_with_cache(40_000, 0, 0.25, 1.0)
print(round(large_cached, 4)) # 0.0225
print(round(small_uncached, 4)) # 0.01With these placeholder numbers the small model wins even without a cache. With a smaller price gap, it would not. The lesson is to measure the whole turn, not only the rate.
A second way to avoid the problem is to route work that does not share the big context. Subagents are the natural fit. A subagent starts with a small, fresh context, so there is no large cached prefix to lose. Sending a subagent that reads and summarizes search results to a small model costs little and also keeps the noisy output out of the main context.
Routing by step kind versus routing by difficulty
Step kind is a proxy for difficulty. It works when difficulty tracks the kind of step. It fails when it does not. An edit step that renames a variable is easy. An edit step that changes concurrency logic is hard. The same label covers both.
There are three common ways to handle this.
- Keep the lookup table and accept the error. Use it when the kinds are fairly uniform in difficulty.
- Add a size or risk signal. Route
editto the large model when the diff touches more than some number of files, or when the files match a sensitive path such as authentication or payments. - Escalate on failure. Run the cheaper model first. If the tests fail or a check rejects the output, retry on a stronger model.
Escalation deserves care. It lowers the average cost only when the cheap model succeeds often enough. If the cheap model fails 70% of the time, you pay for the failed attempt and then for the strong model, which costs more than going straight to the strong model.
The break-even is simple. Let c be the cost of the cheap attempt, s the cost of the strong attempt, and p the probability the cheap attempt succeeds. Expected cost of escalating is c + (1 - p) * s. This beats going straight to the strong model when that value is below s, which means c < p * s.
def escalation_pays(cheap_cost, strong_cost, cheap_success_rate):
expected = cheap_cost + (1 - cheap_success_rate) * strong_cost
return expected < strong_cost, expected
print(escalation_pays(0.02, 0.20, 0.8)) # (True, 0.06)
print(escalation_pays(0.02, 0.20, 0.05)) # (False, 0.21)This ignores the extra latency of a second attempt, and it assumes you can detect failure reliably. If a wrong answer looks like a right one, escalation never triggers. Tests, type checks and linters are good detectors. A model's own claim that it succeeded is not.
Using a model to route
Some systems use a small model to classify each step and pick the route. This handles varied work without hand-written rules, but it adds a model call to every step, and the classifier can be wrong. Do this only after a lookup table has proved too coarse. Log the classifier's choices so you can audit them.
Failure modes
- Silent quality loss. The cheap model produces plausible but wrong output on a step the table sent it. Tests catch some of this. Review steps catch more.
- Cache thrash. Frequent switching on a long context discards cache discounts, as shown above.
- Context mismatch. Models have different context window sizes. Routing a step with a 150k-token context to a model with a smaller window fails outright. Check the window before sending.
- Behavior differences. Models differ in how they follow tool-call formats and instructions. A prompt tuned for one model can break on another. Test each route, not just the main one.
- Stale tables. Providers release and retire models and change prices. A route that was right six months ago may not be now. Keep the table in configuration, with a date and the evidence for each entry.
Checking that a route is worth it
Do not judge a route by its per-token price. Run the same set of tasks under the old policy and the new one, then compare cost per resolved task, as covered in the next chapters. A routing change is an improvement only if resolved tasks stay about the same while total spend falls. If the cheaper policy resolves fewer tasks, the cost per resolved task can rise even though every token is cheaper.
Exercise
A session sends a 40,000-token context to a large model with a stable cached prefix of 35,000 tokens. The next step is "summarizetooloutput". Your table routes it to a small model, which has no cache for this context. Name two things you should compute or check before accepting that route, and say which one could make the route a bad idea even though the small model has a lower rate.
Show answer
First, compute the full cost of the turn on each model: the large model with the cache read, and the small model with the whole context billed uncached. If the price gap is small, the lost cache discount can make the small model cost more. Second, check that the small model's context window can hold the 40,000 tokens. The cache loss is the one that can turn a lower rate into a higher bill. A window that is too small is a hard failure, not only a cost issue. Also confirm the small model summarizes well enough on a sample of real outputs.
Exercise
A cheap attempt costs 0.03 USD and a strong attempt costs 0.15 USD. At what cheap-model success rate does escalating (cheap first, strong on failure) break even against always using the strong model?
Show answer
Escalation costs 0.03 + (1 - p) 0.15, which equals 0.15 when p = 0.2. Break-even is a success rate of 0.2 (0.03 = p 0.15). Above 20% success, escalation is cheaper on average. This assumes failures are detected reliably and ignores the extra latency.