Agent routing explained: send each task to the cheapest model that can do it well
Most agent traffic does not need the most expensive model. Routing decides up front which model handles a task, and a cascade tries a cheap model first and escalates when it is unsure. This guide explains both, works through the cost maths and runs LangChain 1.5's new model router.
- Reading time
- 13 min
- Sections
- 8
- Code examples
- 5
- Tables
- 1
- Sources
- 7
- Published
- 24 Nov 2026
- What changed
- FrugalGPT introduces LLM cascades
- Why it matters
- Routing is a classification problem.
- What to do
- Log difficulty signals today
An agent that sends every request to a frontier model pays frontier prices for "what is the capital of France?" and "summarise this two-line email". An agent that sends everything to a small model saves money and fails the hard cases. Routing sits between the two. A router looks at a request and picks the model, tool chain or sub-agent best suited to it, by difficulty, cost or domain. A cascade does the same in sequence: try the cheap option first, check how confident it is, and escalate only when needed.
Research has put numbers on the savings. The FrugalGPT paper from Stanford reported matching GPT-4's performance with up to 98% lower cost on its benchmarks, and the RouteLLM project from LMSYS reports cost reductions of up to 85% while keeping 95% of GPT-4's performance on MT Bench. In late 2026 routing is moving into agent frameworks themselves: LangChain 1.5 ships a beta ModelRouterMiddleware that picks a model per run with a decision model. This article explains how routers and cascades work, how to do the cost maths, and how to run both patterns.
What happened
FrugalGPT introduces LLM cascades (May 2023)
Lingjiao Chen, Matei Zaharia and James Zou proposed FrugalGPT, which combines strategies such as prompt adaptation, model approximation and an LLM cascade to cut the cost of using LLM APIs. Its cascade sends a query to a sequence of models, scores each answer with a learned scorer, and stops as soon as an answer is judged reliable. They report that FrugalGPT can match the best individual model with up to 98% cost reduction, or improve accuracy over GPT-4 by 4% at the same cost.
RouteLLM releases trained routers (June and July 2024)
LMSYS researchers published "RouteLLM: Learning to Route LLMs with Preference Data" and an open-source framework. It provides four trained routers, mf (matrix factorisation), sw_ranking (similarity-weighted Elo), bert (a BERT classifier) and causal_llm (an LLM classifier), plus a random baseline, all trained on Chatbot Arena preference data for a strong and weak model pair. The project reports cost reductions of up to 85% while maintaining 95% of GPT-4 performance on MT Bench.
LangChain 1.5 adds a model router middleware (November 2026)
The langchain==1.5.2 release (18 November 2026) includes ModelRouterMiddleware, marked beta. It classifies the latest human message once before an agent run with a "decision model", stores the full answer with probabilities and confidence in agent state, and sends every model call in that run to the chosen model.
Routing and cascades, step by step
Think of a hospital. A triage nurse looks at each patient for a minute and sends them to the right place: a pharmacist for a prescription refill, a GP for a cough, a specialist for chest pain. That is routing: one quick decision before the expensive work. A second approach is a referral chain: the GP sees everyone first and refers on when unsure. That is a cascade: the cheap option always runs, and escalation is decided after seeing its result.
| Router | Cascade | |
|---|---|---|
| When is the model chosen? | Before any answer is produced | After the cheap model answers |
| What drives the decision? | Features of the request: length, topic, difficulty score | Quality of the cheap answer: confidence, a judge, a check |
| Cost on escalated requests | Only the chosen model | Cheap model plus expensive model |
| Latency on escalated requests | One call | Two or more calls in sequence |
| Main failure mode | Misjudging difficulty from the request alone | A cheap answer that is wrong but confident |
How a router decides
- Define the routes. Each route is a model or sub-agent with a description of what it is good for and its cost.
- Score the request. A classifier estimates which route fits. It can be rules, an embedding model, a fine-tuned classifier or a small LLM.
- Apply a threshold. RouteLLM, for example, turns the router's score into a decision with a cost threshold, which you calibrate to a target share of strong-model calls.
- Dispatch and log. Send the request, and record the route, the score and the outcome so you can retrain or recalibrate.
How a cascade decides
- Answer with the cheapest tier.
- Score the answer. Use token probabilities, self-consistency agreement, a verifier (tests, schema checks) or a small judge model.
- Stop or escalate. If the score passes the threshold, return the answer; otherwise send the request to the next tier.
- Optionally pass context. The next tier can see the cheap answer and the reason it was rejected.
Cascade cost maths, worked through
Take 1,000 queries. A small model costs $0.0004 per query and is right on 80% of them. A large model costs $0.0060 per query. A confidence check flags 250 queries as low-confidence, and those 250 contain most of the small model's errors: on the 750 it keeps, it is right 705 times. The large model is right on 88% of the hard queries it receives.
def cascade(queries, small, large, threshold):
"""Answer with the small model; escalate when its confidence is below the threshold."""
cost, answers = 0.0, []
for q in queries:
ans, conf, c = small(q)
cost += c
if conf < threshold:
ans, _, c2 = large(q)
cost += c2
answers.append(ans)
return answers, cost
qs = [{"hard": i < 250} for i in range(1000)]
small = lambda q: (None, 0.4 if q["hard"] else 0.9, 0.0004)
large = lambda q: (None, 1.0, 0.0060)
_, cost = cascade(qs, small, large, threshold=0.6)
correct = 705 + round(0.88 * 250)
print(f"cascade: {correct / 1000:.1%} correct, ${cost:.2f} per 1,000 queries")
Output:
cascade: 92.5% correct, $1.90 per 1,000 queries
Compare: the small model alone costs $0.40 per 1,000 queries at 80% accuracy; the large model alone costs $6.00. The cascade costs $0.40 for the small tier plus 250 x $0.006 = $1.50 for escalations, $1.90 in total, under a third of the large-only bill. The whole result rests on one assumption: that the confidence signal concentrates errors in the escalated set. If it flags queries at random, you pay for escalations without fixing many errors. Measure that first, by plotting accuracy against confidence on labelled data, exactly as you would for a classifier's threshold in the precision and recall simulation.
A router changes the arithmetic. If the same 250 hard queries are sent straight to the large model, you save the 250 small-model calls ($0.10) and the extra latency, but the router must recognise hard queries from the request alone, which is harder than judging an answer that already exists.
Routing in LangChain 1.5
ModelRouterMiddleware takes named ModelChoice routes, each with a model and a natural-language criterion, an instruction for the classifier, and a classifier that implements LangChain's BaseDecisionModel. The example below uses a keyword classifier and two fake chat models, so it runs offline; it was run on langchain==1.5.2.
from langchain.agents import create_agent
from langchain.agents.middleware import ModelChoice, ModelRouterMiddleware
from langchain_core.decisions import BaseDecisionModel, ClassifierResponse
from langchain_core.language_models.fake_chat_models import FakeListChatModel
class KeywordRouter(BaseDecisionModel):
"""A toy decision model. In production: a trained classifier or a small LLM."""
model: str = "keyword-router"
@property
def _provider(self) -> str:
return "local"
def _classify(self, state, questions):
text = state.content.lower()
hard = any(w in text for w in ("prove", "refactor", "multi-step", "why"))
p_hard = 0.85 if hard else 0.10
answers = {qid: {"type": "choice", "choice": "powerful" if hard else "fast",
"probabilities": {"powerful": p_hard, "fast": 1 - p_hard},
"confidence": max(p_hard, 1 - p_hard)}
for qid in questions}
return ClassifierResponse.model_validate({"model": self.model, "answers": answers})
fast = FakeListChatModel(responses=["[fast model] Paris."] * 5)
powerful = FakeListChatModel(responses=["[powerful model] Here is the step-by-step refactor..."] * 5)
router = ModelRouterMiddleware(
choices={"fast": ModelChoice(model=fast, criteria="Short factual or simple tasks."),
"powerful": ModelChoice(model=powerful, criteria="Complex multi-step reasoning or code.")},
instructions="Choose the least costly model suited to the task.",
classifier=KeywordRouter(),
)
agent = create_agent(fast, middleware=[router])
for q in ["What is the capital of France?",
"Refactor this module into three services and explain why."]:
out = agent.invoke({"messages": [{"role": "user", "content": q}]})
r = out["model_route"]
print(f"{r.choice:>8} (confidence {r.confidence:.2f}) -> {out['messages'][-1].content}")
Output:
fast (confidence 0.90) -> [fast model] Paris.
powerful (confidence 0.85) -> [powerful model] Here is the step-by-step refactor...
Three behaviours from the source code are worth knowing. The route is chosen once per run in a before_agent hook, so every model call in a multi-step agent run uses the same model. The full answer, including probabilities and confidence, is kept in state under model_route, so traces show why a route was picked. And classifier errors stop the run rather than silently falling back to another model. For error-based fallback, the separate ModelFallbackMiddleware tries alternative models when a call fails, which is a reliability tool rather than a cost router.
Continue learning
How this article connects
2 pages link to or from it. Drag to turn, click a dot to open it.
Routing inside agents, not just across models
Agents give routing more places to act.
Per run. Pick one model for the whole run, as ModelRouterMiddleware does. Simple and cache-friendly, because the prompt prefix stays on one model.
Per step. Use a strong model for planning and a cheap one for routine tool calls, as in plan-and-execute designs. This often saves more than per-run routing but needs care so that each model gets the context it needs.
Per sub-agent. A supervisor routes tasks to specialised sub-agents, each with its own model and tools. The multi-agent supervisor simulation shows this kind of routing.
Per tool set. Route to a smaller tool set before the model call, which shortens prompts. LangChain's LLMToolSelectorMiddleware selects relevant tools with a model before the main call.
What it means in practice
Routing is a classification problem. Treat it like one: labelled data, a held-out test set, precision and recall per route, and recalibration as traffic changes. The LLM routing page lists common router types.
Confidence must be calibrated. A cascade is only as good as its escalation signal. Self-consistency agreement is a strong, cheap signal for answers that can be compared; the temperature and top-p simulation shows how sampling settings control the diversity that agreement depends on.
Watch the cache. Switching models mid-session throws away prompt caches, which can erase the savings; the prompt cache simulation shows what is at stake. Per-run routing keeps caches intact.
Cost per solved task is the metric. Track solved tasks per dollar, not tokens saved. The model tracker helps estimate what each tier would cost for your workload, and cost and latency budgets help set targets.
What to do now
- Log difficulty signals today. Record request length, topic, tools used, steps, outcome and cost per run; they are your future routing features.
- Build a labelled set. Label a few hundred requests with whether the cheap model's answer was acceptable.
- Start with a cascade if you have a verifier. Tests, schemas or exact checks make cascades safe and simple.
- Start with a router if latency matters. A cheap classifier before the call avoids double calls on hard requests.
- Calibrate thresholds to a budget. Pick the threshold that hits your target share of strong-model calls, as RouteLLM's calibration step does.
- Route per run first. It keeps prompt caches and traces simple; move to per-step routing only with evidence.
- Add a safety override. Force the strong model, or a human, for high-risk actions regardless of the router's choice.
- Re-evaluate monthly. New model releases shift prices and quality; re-run the labelled set and recalibrate.
Risks and open questions
Silent quality loss. A router that sends too much to the cheap model saves money while users quietly get worse answers. Monitor quality per route, not just overall.
Distribution shift. Routers trained on one traffic mix, such as Chatbot Arena prompts, may misjudge your domain. RouteLLM reports that its routers generalise to other model pairs, but your traffic is the real test.
Adversarial inputs. Users or injected content can be crafted to trigger the expensive route, or to keep risky requests on a weaker, less guarded model.
Beta APIs. LangChain marks ModelRouterMiddleware as beta, so its interface may change; pin versions and wrap it behind your own function.
Watch next: routers built into model providers' APIs, routing on reasoning effort rather than model choice, and shared benchmarks for router quality on agent tasks rather than single prompts.
Frequently asked questions
What is the difference between a router and a cascade?
A router chooses the model before any answer exists, using features of the request. A cascade always runs the cheap model first and escalates based on how good its answer looks, which costs more on hard requests but uses more information.
How much can routing save?
It depends on your traffic and models. Published results include up to 98% cost reduction while matching GPT-4 in FrugalGPT's experiments and up to 85% reduction with 95% of GPT-4 quality on MT Bench for RouteLLM; measure on your own data before relying on similar numbers.
What should the router itself be?
Start with rules or a small classifier on embeddings; move to a fine-tuned classifier or a small LLM when you have labelled data. The router must be much cheaper than the calls it saves.
Does routing break prompt caching?
Switching models within a session usually means the new model has no cached prefix. Choosing once per run, as LangChain's middleware does, avoids most of this cost.
Is ModelFallbackMiddleware a router?
No. It switches to another model when a call fails, for example on an outage or rate limit. It improves reliability; it does not pick models by difficulty or cost.
Summary
Routing sends each request to the cheapest model or sub-agent likely to handle it well, and cascades try a cheap model first and escalate when confidence is low. Research such as FrugalGPT and RouteLLM shows large savings, up to 98% and 85% respectively on their benchmarks, when the decision signal is good. The worked example here cut cost per 1,000 queries from $6.00 to $1.90 while raising accuracy from 80% to 92.5%, but only because the confidence signal caught most errors. LangChain 1.5 now ships a beta model router that picks a model per run with a decision model and records its confidence. Treat routing as a classification problem: label data, calibrate thresholds and monitor quality per route.
Sources
- Paper arXiv: FrugalGPT: How to Use Large Language Models While Reducing Cost and Improving Performance
- Paper arXiv: RouteLLM: Learning to Route LLMs with Preference Data
- Code GitHub: lm-sys/RouteLLM framework and routers
- Web LMSYS blog: RouteLLM
- Code PyPI: langchain 1.5.2
- Code GitHub: LangChain model router middleware source
- Docs LangChain docs: Middleware
Cite this article
Kelahmet, Ö. C. (2026, November 24). Agent routing explained: send each task to the cheapest model that can do it well. Özer Cem KELAHMET. https://www.ozercemkelahmet.com/articles/agent-routing-model-cascades-cost
BibTeX
@online{kelahmet2026agent,
author = {Kelahmet, {\"O}zer Cem},
title = {{Agent routing explained: send each task to the cheapest model that can do it well}},
year = {2026},
month = {nov},
url = {https://www.ozercemkelahmet.com/articles/agent-routing-model-cascades-cost}
}Version historyfirst version
- Published
Factual corrections are listed here with what changed. Wording and formatting edits are not listed.