LLM model routing means sending each request to the cheapest model that can handle it and keeping the expensive model for the requests that need it. In an agent, that usually takes one of three forms: a fixed route per step type (extraction always goes to the small model), a router that classifies each task before it runs, or a cascade that tries the small model first, checks the answer and escalates when the check fails. The savings can be large because model prices differ by more than an order of magnitude, but a router that guesses wrong costs you quality, so route by rules you can test and measure the result against your evals.
This post covers why the price gap matters, the three routing patterns, a working Python router with escalation, and what the research on learned routers found. The code was tested with the anthropic Python SDK 2.9.0, using a stubbed client in place of live API calls.
Why routing pays off
Anthropic's current price list shows the spread. Per million tokens, Claude Haiku 5.5 costs $0.10 input and $0.50 output for prompts up to 100,000 tokens. Claude Sonnet 5.5 costs $2 and $10, Claude Opus 5.5 costs $4 and $20, and Claude Fable 5.2 costs $8 and $40. Fable's output price is 80 times Haiku's. Anthropic's model guide describes Haiku 5.5 as the option for "high-volume, latency-sensitive tasks such as classification, extraction, and routing," and says to use Fable 5.2 for "demanding reasoning and long-horizon agentic work."
The FrugalGPT paper made the same observation in 2023 across vendors: LLM API prices it compared differed by up to about two orders of magnitude. Many agents send a mix of work through one model: planning that needs the strongest model, and lookups, classifications and short rewrites that don't. Routing lets the second group run at the small model's price.
Three ways to route
1. Fixed routes by step type. You already know which steps are easy. Classifying an incoming ticket, extracting fields from a document or summarizing a tool result are good candidates for a small model, while planning and writing code go to a large one. In a multi-agent setup this is one line per agent. The OpenAI Agents SDK docs say, "Within a single workflow, you may want to use different models for each agent," and their example gives a triage agent one model and the agents it hands off to different ones. Each Agent takes its own model, and RunConfig(model=...) sets the default for agents that don't set one. Fixed routes cost nothing to run and are easy to test, so start here.
2. A router that picks the model per task. When the same entry point receives easy and hard requests, a cheap call or a small trained classifier decides the tier before the main call. The cost is one extra small-model call per task and the risk of a wrong guess.
3. A cascade. Send the task to the small model, check the answer, and escalate if the check fails. FrugalGPT works this way: it queries models one at a time, and a separate scorer rates each answer between 0 and 1. In the paper's case study the scorer is DistilBERT adapted for regression, far cheaper than the models it judges. If the score clears that stage's threshold, the answer is returned; otherwise it queries the next model. A cascade pays twice on the tasks that escalate, so it works best when most tasks pass on the first try and the check is cheap.
These combine well: fixed routes for steps you understand, a router at the front door, and a cascade for outputs you can validate.
A router with escalation
The code below routes a task to one of three Claude tiers. A rule sends high-stakes tasks straight to the top. Everything else is classified by Haiku 5.5 with a one-word answer. The chosen model runs, and if a validator rejects its output the task moves up one tier.
"""Route each task to the cheapest model tier that can handle it, and escalate on failure."""
import json
from dataclasses import dataclass
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY
TIERS = ["claude-haiku-5-5", "claude-sonnet-5-5", "claude-opus-5-5"]
# USD per million tokens (input, output), from Anthropic's pricing page.
PRICES = {
"claude-haiku-5-5": (0.10, 0.50), # prompts up to 100,000 tokens
"claude-sonnet-5-5": (2.00, 10.00),
"claude-opus-5-5": (4.00, 20.00),
}
HAIKU_LONG_PROMPT = 100_000 # above this, Haiku 5.5 bills $0.50 / $2.50 for the whole request
ROUTER_PROMPT = """Rate how hard this request is for an AI assistant.
Answer with one word: easy, medium or hard.
easy: lookup, extraction, classification, short rewrite.
medium: multi-step reasoning over the given data, writing with constraints.
hard: planning across many steps, code changes, ambiguous or high-stakes requests."""
@dataclass
class Result:
text: str
model: str
cost_usd: float
escalations: int
def call(model: str, prompt: str, system: str | None = None, max_tokens: int = 1024):
extra = {"system": system} if system else {}
return client.messages.create(
model=model,
max_tokens=max_tokens,
messages=[{"role": "user", "content": prompt}],
**extra,
)
def cost(model: str, usage) -> float:
"""Uncached input and output only; add cache reads and writes if you use caching."""
price_in, price_out = PRICES[model]
prompt_tokens = (usage.input_tokens
+ (getattr(usage, "cache_read_input_tokens", 0) or 0)
+ (getattr(usage, "cache_creation_input_tokens", 0) or 0))
if model == "claude-haiku-5-5" and prompt_tokens > HAIKU_LONG_PROMPT:
price_in, price_out = 0.50, 2.50
return (usage.input_tokens * price_in + usage.output_tokens * price_out) / 1_000_000
def pick_tier(prompt: str, high_stakes: bool) -> tuple[int, float]:
"""Rules first, then a cheap classifier. Anything unclear goes up, not down."""
if high_stakes:
return 2, 0.0
reply = call(TIERS[0], prompt[:4000], system=ROUTER_PROMPT, max_tokens=5)
label = reply.content[0].text.strip().lower() if reply.content else ""
tier = {"easy": 0, "medium": 1, "hard": 2}.get(label, 2) # unknown label: strongest
return tier, cost(TIERS[0], reply.usage)
def run(prompt: str, validate, high_stakes: bool = False) -> Result:
"""Try the routed tier; if the answer fails validation, move up one tier."""
tier, spent = pick_tier(prompt, high_stakes)
start = tier
while True:
model = TIERS[tier]
reply = call(model, prompt)
spent += cost(model, reply.usage)
text = reply.content[0].text if reply.content else ""
if validate(text) or tier == len(TIERS) - 1:
return Result(text, model, spent, tier - start)
tier += 1
def is_json_with_total(text: str) -> bool:
"""Example validator: the answer must be JSON with a numeric 'total'."""
try:
return isinstance(json.loads(text).get("total"), (int, float))
except (ValueError, AttributeError):
return False
In a test with a stubbed client, a task the router labeled easy went to Haiku, which answered in prose. is_json_with_total rejected it, Sonnet answered with valid JSON, and the result reported one escalation and the cost of all three calls. A router reply of banana sent the task to Opus, and high_stakes=True skipped the classifier entirely.
Four choices matter more than the code itself:
- Fail upward. An unknown label, an empty reply or a high-stakes flag picks the strongest tier. A wrong guess upward costs money; a wrong guess downward costs a bad answer.
- The validator does the real work. A cascade is only as good as its check. Schema validation, a passing test, a tool call that succeeded or a rubric score from an LLM judge all work. "The model sounded confident" does not. If you need structured output, the comparison of structured outputs and function calling covers how to get a reliable shape to validate.
- Count the router's cost. The classifier call is cheap but not free, and
pick_tierreturns its cost so the total is honest. - Cap the climb. The loop stops at the top tier and returns whatever it got. Don't let escalation retry forever, for the same reasons covered in debugging agent loops.
Routing inside a long agent run
Agents resend their whole history on every turn, so where you route matters as much as how.
Watch the long-prompt price. Anthropic's pricing page says Haiku 5.5 is priced by prompt length: a request whose prompt is over 100,000 tokens pays $0.50 input and $2.50 output, and the prompt length counts all input tokens, including cache reads and cache writes. A small model reading a long agent history costs five times its headline price. The cost function above applies that rule. Keeping the history short helps here too, which budgeting the context window covers.
Mind the cache. Cache reads are cheap on the large models: the prompt caching docs list 0.05x the base input price for Opus 5.5 and Sonnet 5.5, and 0.025x for Fable 5.2. At those rates, a cached prefix on Opus 5.5 costs $0.20 per million tokens. The docs promise a hit only for identical prompt segments and don't say a cache is shared across models, so plan for a model you switch to mid-run to pay its own cache write on the history. Routing once per task or per subagent, with each subagent keeping its own short history, usually keeps the cache working. See prompt caching for AI agents for how to check your hit rate.
What the research on learned routers found
RouteLLM, from LMSYS, trains routers that choose between a strong and a weak model. The routers learn from Chatbot Arena preference data, where people compared two models' answers to the same prompt, plus augmented data from benchmark labels and an LLM judge. The project's blog post reports cost reductions of over 85% on MT Bench, 45% on MMLU and 35% on GSM8K compared with using only GPT-4, "while still achieving 95% of GPT-4's performance." Cost there is measured as the share of calls sent to the strong model, with GPT-4 Turbo as the strong model and Mixtral 8x7B as the weak one. Two details are worth knowing before you rely on those numbers:
- Trained on Arena data alone, all routers performed close to random on MMLU, which the authors attribute to most MMLU questions being outside the training distribution. Results improved once benchmark data was added. A router trained on someone else's traffic may not fit yours.
- When the authors swapped in Claude 3 Opus and Llama 3 8B without retraining, MT Bench results were comparable to the original pair, which suggests the routers learned something about which prompts are hard rather than about one model pair.
The open-source package exposes routers through an OpenAI-compatible Controller with strong_model and weak_model arguments, and you choose the router and threshold in the model name, such as router-mf-0.11593. Its calibrate_threshold command finds the threshold that sends a target share of queries to the strong model, and the README recommends calibrating on a sample of your own queries.
FrugalGPT reports that its learned cascade could match GPT-4's performance with up to 98% lower cost on the tasks it tested. The authors also list the limits: it needs labeled training data that matches the real query distribution, and when every model in the chain gives the same wrong answer the cascade may still query all of them.
The common lesson is that published savings depend on the traffic. Measure on your own.
Measure it
Treat routing as a change that needs evals:
- Label a sample of real tasks and run each through every tier once. That tells you which tasks the small model gets right, and gives you data to tune rules or a threshold.
- Log the route on every call. Record the chosen tier, whether it escalated and the cost per task. On a trace, these belong on the model span next to token counts; agent observability tracing shows the attribute names.
- Watch two numbers: the share of tasks that reach the top tier, and the quality score per tier from your agent evals. If quality on the small tier drops, tighten the rules. If almost everything escalates, the router is adding a call for nothing.
Checklist
- Start with fixed routes for step types you understand.
- Route to the strongest tier when the label is unknown or the task is high-stakes.
- Escalate only on a concrete check: schema, test, tool success or rubric score.
- Count the router's own calls in the cost.
- Cap escalation at the top tier.
- Watch long-prompt pricing on small models and keep worker contexts short.
- Route per task or per subagent, not per turn, to keep the cache.
- Calibrate any learned router on your own traffic.
- Log tier, escalations and cost per task, and compare quality per tier.
FAQ
What is LLM model routing?
It is choosing which model handles each request, so easy requests go to a cheaper model and hard ones to a stronger one. It can be a fixed rule, a classifier that runs first or a cascade that escalates when a check fails.
How much can model routing save?
It depends on your traffic. RouteLLM reported cost reductions of over 85% on MT Bench at 95% of GPT-4's performance, but smaller ones on MMLU and GSM8K. Measure the share of tasks your small model handles correctly on your own data.
Should the router be an LLM?
It can be. A small model answering with one label is easy to set up. Learned routers such as RouteLLM's matrix factorization router are trained on preference data and should be calibrated on your own traffic. Fixed rules are cheaper than both when the step type tells you enough.
Is a cascade better than a router?
A cascade is safer when you can check the answer cheaply, because a wrong first guess gets corrected. It costs more on tasks that escalate, since you pay for both attempts. A router costs less per task but can't recover from a wrong pick.
Does switching models break prompt caching?
Plan for it. Cache hits need identical prompt segments, and the Claude docs don't say a cache is shared between models, so a model you switch to should be expected to write its own cache for the history.
Sources
- Ong et al., RouteLLM: Learning to Route LLMs with Preference Data (arXiv 2406.18665)
- LMSYS, RouteLLM: An Open-Source Framework for Cost-Effective LLM Routing (blog post, July 2024)
- lm-sys/RouteLLM (GitHub repository and README)
- Chen, Zaharia and Zou, FrugalGPT: How to Use Large Language Models While Reducing Cost and Improving Performance (arXiv 2305.05176)
- Anthropic, Pricing (Claude API documentation)
- Anthropic, Models overview (Claude API documentation)
- Anthropic, Prompt caching (Claude API documentation)
- OpenAI, Models (Agents SDK documentation)
- anthropic on PyPI (package, version 2.9.0)