Module 1: Set up your model routing today
The team that did this cut cost per thread by 64 percent with no change in quality. This module walks you through the same four steps on one of your own agents.
Map what your agent is actually asked to do
A model router sends each task to the smallest model that meets its quality bar. That rule only works when you know what tasks your agent receives and how hard each kind is. So the first step is a task map, not a model choice.
Why is model routing important?
Agent tasks vary widely in how much reasoning they need, but default routing sends every one of them to the same large model. The AWS Well-Architected Agentic AI Lens rates the risk of leaving this unaddressed as high, because inference cost and latency scale with model size.
You pay in two directions at once. The Augment Code routing guide names them: over-provisioning, where a frontier model does simple work and you pay its price and its latency for nothing, and under-provisioning, where a small model takes on work it cannot finish and the errors compound downstream.
The first failure is the quiet one. File reads, directory listings, and formatting checks happen hundreds of times in a coding session, and on a frontier model each one costs about five times what it needs to.
The second failure is the loud one. A weak model that plans a task produces malformed subtasks that no later step can correct, and the retries and manual escalation that follow erase the saving the small model was meant to deliver.
Routing is the fix for both: each task goes to the smallest model that meets its quality bar, and only the work that needs frontier reasoning pays frontier prices. The team that built the router this module follows cut median cost per thread by 64 percent with no measurable change in quality.
Four terms this guide uses: router, gateway, tier, prompt cache
You will meet four terms throughout this guide, and SSD Nodes founder and CEO Matt Connor defines them in one place. A router picks a model per request. A gateway is the proxy the request passes through, and it may or may not also route.
A prompt cache is the provider's stored copy of your processed prompt prefix, so a later request that repeats the prefix bills at a fraction of the input price.
The fourth term is ours. A tier is a cost and capability band, and we call the three bands fast, balanced, and performance. The AWS Lens uses fast, standard, and advanced for the same idea.
A tier holds a model today and a different model next quarter; the band stays.
Group tasks before you pick models
An agent workload mixes simple classification with multi-step reasoning. When one large model serves all of it, blended cost and latency track the most capable option, even though many requests do not need it.
Group the workload's tasks by the reasoning they require, then use that grouping as the input to model assignment. If you let each caller pick a model case by case, you end up with routing decisions nobody can audit.
The Lens gives you three classes to start from:
- Single-step extraction or classification. One pass, a known shape of output.
- Structured multi-step reasoning over known steps. Several passes, but the steps are defined.
- Open-ended investigation. The agent decides what to look at next.
Write two or three representative examples next to each class. The examples make routing decisions auditable, and you revisit them when the task distribution shifts.
What one week of a coding agent's traffic looks like
LangChain engineers mapped their own traffic before they built a model router for Open SWE, their open source coding agent.
They pulled one week of interactive threads from traces, labeled each thread by task type with an LLM classifier, and recorded the cost and turn count of each thread as rough measures of complexity.
Code changes dominated the week, and the six largest categories showed how cost and effort differed by type.
At the time, every thread went to a top-tier frontier model. The spread of complexity suggested that many tasks did not need frontier intelligence, which became the hypothesis the router tested.
Two numbers to record for every task
Record two signals for every thread as you label it. Cost tracks complexity fairly directly, because bigger tasks use more tokens. Invocation count is more nuanced: a high count can mean a hard task, or a model that needed follow-ups to finish.
Tag each trace with its task type from the start. Datadog's guidance on AI gateways in production makes the same point: once spans carry the task type and the model, cost, latency, and quality become visible per task.
Goal: Build a task-mix table for one agent your team runs, with examples per class.
- Export one week of threads or traces from the agent. Keep cost and call count per thread.
Label each thread by task type. Use the prompt below with a small model, or label by hand if the week is small.
prompt.txtYou classify coding-agent threads by task type. Read the thread title and first user message. Return exactly one label from this list: feature, bug_fix, test_or_noop, release_ops, design, diagnosis, pr_upkeep, question, review, other. Return only the label.- Group the labels into the three classes: single-step, structured multi-step, open-ended investigation.
- For each class, compute the share of threads, the median cost, and the median call count.
- Write two representative threads next to each class.
Expected result: A table with three rows (class, share, median cost, median calls) and six example threads. In the next lesson you map these classes to tiers.
Pick three tiers and give each an alias
A tier is a band, and the model inside it is replaceable. Three tiers along the cost-intelligence curve cover most task mixes. When you give each tier a name of its own, the router keeps working when the model behind the name changes.
Plot models on cost against intelligence
Pick models by where they sit on one curve of intelligence against cost. The LangChain engineers who built the Open SWE router used the Artificial Analysis Intelligence Index, which scores models on a common set of tasks and reports the cost per task.
Plotted together, the models that are both most cost-effective and smartest form the Pareto frontier.
They chose three models along that curve, each with a different balance of cost, speed, and intelligence:
| Tier | Model picked | Note |
|---|---|---|
| Fast | GLM-5.3-Flash (xhigh effort) | Open model, on the frontier next to closed models |
| Balanced | GPT-5.6 Sol (medium effort) | |
| Performance | GPT-6 Astra (low effort) |
Why a leaderboard is a shortlist, not a decision
A general benchmark ranks models on averages across many tasks. The AWS Well-Architected Agentic AI Lens warns that those task distributions can bear little resemblance to a specific workload. A model that leads a public leaderboard can underperform on the traffic your agent serves.
Build an evaluation set that represents production traffic and score candidate models against it.
Capture quality signals (correctness, goal success rate, tool-trajectory match) beside latency and tokens, so you can find the smallest model that meets the quality bar for each class. Treat leaderboard rankings as the starting shortlist.
Write each tier's criteria from two inputs, as LangChain did: your own task analysis, and what each provider says its models are best at. You turn those criteria into the router's prompt in the next lesson.
How to assign each task class to a tier
Define a small set of tiers and assign each task class to the tier your benchmarks show is sufficient. Then select a specific model for each tier. Start with the three classes from your task map, mapped below.
You can add a fourth tier. LiteLLM's complexity router ships with simple, medium, complex, and reasoning tiers, where the reasoning tier is the frontier model at high effort.
Token volume belongs in the calculation beside tier. The cost-aware agent design pattern on AgentPatterns makes the point with current rates: a verbose session on a cost-effective model can outspend a compact session on an expensive one.
Why aliases beat pinned model IDs
Model IDs have finite lifespans. A hardcoded ID breaks silently at retirement: the API returns an error instead of routing to a successor. Use display names where you can, and pin full IDs only when reproducibility requires it.
An alias per tier gives you that stability at the router. When a better model lands, you swap the model behind the alias and nothing else changes.
Picking up a new frontier model then means swapping a tier, not rebuilding the agent.
The AWS Lens goes one step further and holds the mapping as runtime configuration, so a new release rolls out without a redeploy. We cover the config-store pattern later, in the lesson on keeping routing current.
Goal: Run a LiteLLM proxy with three aliased tiers, each answering a request.
Install the proxy. The project recommends uv, because a bare pip install does not provision a compatible Python.
terminaluv tool install 'litellm[proxy]'Write
config.yamlwith three aliases. Replace eachmodel:value with your pick for that tier, and keep the API keys in the environment.config.yamlmodel_list: - model_name: fast litellm_params: model: anthropic/claude-haiku-4-5 # your fast-tier pick api_key: os.environ/ANTHROPIC_API_KEY - model_name: balanced litellm_params: model: anthropic/claude-sonnet-5 # your balanced-tier pick api_key: os.environ/ANTHROPIC_API_KEY - model_name: performance litellm_params: model: anthropic/claude-opus-5 # your performance-tier pick api_key: os.environ/ANTHROPIC_API_KEYStart the proxy.
terminallitellm --config config.yamlSend one request to each alias.
terminalcurl -X POST http://localhost:4000/v1/chat/completions \ -H "Authorization: Bearer $LITELLM_API_KEY" \ -d '{"model": "fast", "messages": [{"role": "user", "content": "Write a one-line function that reverses a string."}]}'Repeat with
"model": "balanced"and"model": "performance".- Read the
modelfield in each response. Then fill a tier table: task class, tier, model behind it, date picked.
Expected result: Three responses whose model field shows the provider model behind each alias, and a tier table with three rows dated today. In the next lesson you write the rule that decides which alias each request goes to.
Write the routing rule and the fallback
The router decides, at the start of a task, which tier gets it. The fallback decides what happens when that tier fails. They are different decisions with different triggers, and a working setup needs both.
In this lesson you write the two rules and wire them into the proxy from the previous lesson.
Two ways to write the first routing rule
A static map sends each task class to a tier by a predefined rule, without reading the request. The Augment Code routing guide describes where it fits: teams with predictable workloads, where task types map cleanly to roles or classes.
It breaks down when complexity varies inside one class, because the team must then over-provision the class or accept quality drops on its harder tasks.
A dynamic classifier reads each request and picks a tier at runtime. It adds a classification step before every request, with some latency per decision. In exchange, it handles the variation a static map cannot.
The three parts of a classifier router
The router LangChain engineers built for Open SWE runs on the thread's first human message and has three parts:
- A base prompt that tells the classifier its job: pick the least expensive model likely to complete the task.
- Criteria per tier, a short plain-language description of the work each tier should take.
- A classifier model that reads the request and picks a tier according to the criteria and the prompt.
The criteria come from the two inputs you gathered in the previous lesson: your task analysis and each provider's own description of what its models do best. They are written for one agent's task set, so the router is tightly coupled to that agent.
LangChain puts the router in the harness for this reason: the harness already holds the agent's prompt, tools, and domain context, which a generic gateway lacks.
You have a menu for the classifier itself. LiteLLM's complexity router accepts heuristics, an LLM, a decision model, keyword rules, or a custom plugin. You start with the heuristic in the hands-on step below, because it needs no extra model call.
Fallback is a different decision from retry
A retry repeats the same call and hopes for a better draw. A fallback changes a variable by switching models.
The AWS Well-Architected Agentic AI Lens draws that line. Selection is the starting point of a request, not the end of the decision.
A cascading fallback preserves quality on the requests that need it, without forcing a whole task class onto the larger model.
Define the signals that trigger it. There are four: a confidence score below a threshold, a schema validation failure, a parse error, or an explicit incomplete response. Limit escalation to a single step, so tail latency stays predictable.
Log both the primary and the fallback decision for every request that escalates.
Keep the standby on the same tool-call format
An availability fallback pairs a primary model with a standby. SSD Nodes founder and CEO Matt Connor keeps both on the same provider, so the tool-call format does not change when the fallback fires. The agent stays on the primary until that model is unreachable.
You accept a tier change at that moment. The trade is right only because the alternative is a failed request. Log which model served each call, because the log is the only record that the switch happened.
We give the silent-behavior problem and the cross-provider format differences their full treatment later, in the lesson on fallback design.
Goal: Route one request per tier and force one fallback, with both visible in the proxy log.
Add a router entry to
config.yamlbelow the three aliases. The tiers point at the aliases from the previous lesson.config.yaml- model_name: smart-router litellm_params: model: auto_router/complexity_router complexity_router_config: tiers: SIMPLE: fast MEDIUM: balanced COMPLEX: performance REASONING: performance classifier_type: heuristic complexity_router_default_model: balancedAdd the fallback block at the top level of the file. The standby is on the same provider as the primary.
config.yamlrouter_settings: fallbacks: [{"performance": ["balanced"]}] num_retries: 2 cooldown_time: 30Restart the proxy.
terminallitellm --config config.yamlSend three requests of rising complexity to
smart-router.terminalcurl -X POST http://localhost:4000/v1/chat/completions \ -H "Authorization: Bearer $LITELLM_API_KEY" \ -d '{"model": "smart-router", "messages": [{"role": "user", "content": "Write a one-line function that reverses a string."}]}'Repeat with "Write a function that parses ISO dates and add unit tests for it," then with "Find why the login test is flaky in this repository and propose a fix."
- Set the performance tier's API key to an invalid value, restart the proxy, and send the third request again.
- Read the proxy log. Find the
modelfield for each request and the fallback event for the last one.
Expected result: Three requests served by three different models, and a fourth request whose log shows the standby model after the primary failed. In the next lesson you prove whether the router saved money without losing quality.
The Code: Your daily unfair advantage in software engineering.
Join 350,000+ software engineers, tech leads, and CTOs who start their morning with The Code.
Prove the router cut cost without hurting quality
A router earns its place only if cost drops and quality holds. You cannot read either from the invoice alone. You need an outcome signal you can measure on every task, and a baseline to compare against.
This lesson gives you both, then shows you what one team found when they ran the comparison.
Two ways to measure the router against a baseline
The LangChain engineers who built the Open SWE router describe two ways to track task outcomes. Offline evals run the router against a fixed dataset, so you can compare versions safely and repeatably.
The catch is the dataset: it has to look like your real traffic and be graded on what your users care about. For a coding agent that means PR quality and reviewability, which are hard to grade offline.
An A/B test splits live threads between the router and a single-model baseline, then compares them on a success metric you can measure for every thread. Live traffic is a naturally representative dataset.
The downside is that your users ride a router that may not be optimal yet.
Put the measure of success in place before you route. If an eval dataset is too costly or difficult to build, an A/B test on live traffic works well.
Choose one success metric you can record every time
LangChain used two signals. Open SWE records every PR it opens and whether it is merged or closed, so merged PRs per thread became the main success metric.
They also added thumbs up and down, so a user can rate any thread, including questions that never produce a PR, and each rating is logged as feedback on the thread's trace.
Merged PRs were the stronger signal. Feedback was sparse, since only a small share of threads get rated, but it was where they heard about routing mistakes.
Two models can both pass a task and still differ. Scott Wu, CEO of Cognition, names the problem: even when different models pass the task, subtle differences in behavior and style mean they are not interchangeable.
You need evals that account for style and behavior, not just pass or fail.
You can also test before you switch anything. A shadow evaluation runs the router beside your current model on live traffic and judges both answers. In one gateway's shadow run, the router matched or beat the current model on 88.1% of 143 judged turns.
What LangChain's A/B showed
Their first test compared the router against always using the performance model. Half of the threads went through the router and half always used the performance model, across 973 threads in one week.
Quality did not measurably change. Cost dropped a lot, and the mean and p90 fell too, so the savings were not a few low-cost outliers.
The tier split tells you why. Only a small share of routed threads went to the performance tier, and the cost ladder between tiers was steep.

User feedback pointed the same way. When a simple request ran on the performance model, engineers flagged the overspend directly, with comments like "pretty expensive for this query" and "this request should not have been routed to the performance model."
What to keep watching after the test
The A/B is a one-time gate. The AWS Well-Architected Agentic AI Lens tells you what to keep on the dashboard afterward: per-class latency, token consumption, quality scores, and fallback-escalation rate, beside total latency.
Watch the fallback rate most closely. A rising fallback rate on a class is the early sign that its primary model no longer fits, because traffic shifted or a newer model would serve the class better.
It shows up before the user-facing regression is large enough to alarm.
Attribute latency, tokens, and evaluation scores to the class and the model that served each request, so you can see which routing decision moved which number.
Goal: Build a one-week before-and-after sheet for the router you set up.
- Choose one success metric you can record for every task: a merged PR, a passing test run, or a thumbs rating.
- Split the agent's traffic. Send half to
smart-routerand half toperformance, by alternating threads or by team. - Log four fields per thread: the arm, the tier that served it (from the
modelfield in the log), the cost, and the metric. - After a week, compute the median and p90 cost per arm, and the metric per arm.
- Compute the tier share of routed threads.
- Read any feedback comments for routing mistakes in either direction: simple requests on the performance tier, or hard requests on the fast tier.
Expected result: A two-column table (baseline, routed) with median cost, p90 cost, and your success metric, plus a tier-share line. A cost drop with a flat metric means your router works. A flat cost, or a falling metric, points you to the next module.
By this point you should have:
- A task-mix table for one agent, with three task classes and examples per class.
- A running proxy with three aliased tiers and a dated tier table.
- A classifier router and a same-provider fallback, both visible in the log.
- A before-and-after sheet that shows cost per arm, quality per arm, and tier share.
You now have a router. The next module revisits three of the decisions you made quickly, with the evidence and the counter-arguments, so you can defend or change them.
Module 2: How to make your routing decisions stronger
Routing saves money only inside certain boundaries. Learn where those boundaries are, from the cache arithmetic to the fallback chain, and write them into a one-page decision record.