Subscribe to Newsletter

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.

Start moduleModule 1 of 3 · 4 lessons

1.1

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.

OVER-PROVISIONINGUNDER-PROVISIONINGsimple work: file reads,listings, format checksfrontier modelpays ~5x the price and the latencyfor work a small model does as wellhard work: planning,multi-file refactorssmall modelmalformed plans cascade downstream;retries and escalation erase the saving
Scroll sideways →The two ways one model for everything costs you: frontier prices on simple work, and compounding errors when a small model takes on planning.

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.

AgentrequestGATEWAY (THE PROXY)Routerpicks a tierTieraliasfast / balancedModelbehind the tierprompt cache lives herelog: which model served this call
Scroll sideways →How one request moves through a router: the gateway receives it, the router picks a tier, the model behind that tier answers, and the log records which model served the call.

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.

SHARE OF THREADS BY TASK TYPEFeature work21.7%Bug fix17.1%Test or no-op15.6%Other14.9%Release and ops8.0%Design6.2%Diagnosis6.0%PR upkeep5.1%Question2.9%Review2.4%
Scroll sideways →What one coding agent was asked to do in a week: feature work, bug fixes, and tests made up more than half of all threads. Source: LangChain, Open SWE router.
MEDIAN LLM COST PER THREAD · THREADS · MEDIAN CALLSInvestigation$3.4252 threads · 3 callsFeature work$3.28189 threads · 2 callsBug fixes$2.05140 threads · 2 callsScoping and design$1.7554 threads · 3 callsRelease and ops$0.8870 threads · 2 callsTest or no-op$0.52136 threads · 1 call
Scroll sideways →Which task types cost the most per thread: investigation and feature work ran five to six times the cost of a test run. Source: LangChain, Open SWE router, Aug 29 to Sep 5.

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.

LangChain engineers walk the same four steps as this module, starting with the week of traces they labeled by task type. Watch: How to Build a Model Router in the Harness.
TRY THIS TODAY

Goal: Build a task-mix table for one agent your team runs, with examples per class.

  1. Export one week of threads or traces from the agent. Keep cost and call count per thread.
  2. Label each thread by task type. Use the prompt below with a small model, or label by hand if the week is small.

    prompt.txt
    You 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.
  3. Group the labels into the three classes: single-step, structured multi-step, open-ended investigation.
  4. For each class, compute the share of threads, the median cost, and the median call count.
  5. 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.

1.2

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:

TierModel pickedNote
FastGLM-5.3-Flash (xhigh effort)Open model, on the frontier next to closed models
BalancedGPT-5.6 Sol (medium effort)
PerformanceGPT-6 Astra (low effort)
Cost per task (log scale)IntelligencePareto frontierFastBalancedPerformance
Scroll sideways →Where the three tiers sit on the cost-intelligence curve: each pick is the most cost-effective model on the frontier at its level of capability. Schematic after the chart in the LangChain, Open SWE router post; positions are illustrative, not plotted data.

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.

TASK CLASSTIER (ALIAS)Single-step extraction or classificationfastmost cost-effective model that passesStructured multi-step reasoningbalancedmiddle of the curveOpen-ended investigationperformancefrontier modelThe alias stays; the model behind it changes when a better one lands.
Scroll sideways →How the three task classes map to the three tiers. The alias on the right stays fixed; the model behind it changes when a better one lands.

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.

An eight-minute setup of the proxy you are about to install, from config file to first request. Watch: LiteLLM: Free Open Source Gateway to Manage All Your LLM Providers.
TRY THIS TODAY

Goal: Run a LiteLLM proxy with three aliased tiers, each answering a request.

  1. Install the proxy. The project recommends uv, because a bare pip install does not provision a compatible Python.

    terminal
    uv tool install 'litellm[proxy]'
  2. Write config.yaml with three aliases. Replace each model: value with your pick for that tier, and keep the API keys in the environment.

    config.yaml
    model_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_KEY
  3. Start the proxy.

    terminal
    litellm --config config.yaml
  4. Send one request to each alias.

    terminal
    curl -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".

  5. Read the model field 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.

1.3

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.

STATIC MAPCLASSIFIERclass Afastclass Bbalancedclass Cperformancerule fixed per class, request not readrequest 1request 2request 3read+ pickfastbalancedperformanceeach request read, tier decided at runtime
Scroll sideways →The two ways to write a first routing rule. A static map sends each task class down a fixed path; a classifier reads each request and decides the tier at runtime.

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.

A nine-minute definition of a router and the trade it makes, before you write yours. Watch: What is an LLM Router?.

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.

RETRY: SAME CALL, SAME MODELFALLBACK: CHANGE THE MODEL, ONE STEPrequesttry 1primarytry 2 … up to num_retriesrequestprimarystandbysignal: schema fail, parse error,low confidence, incompletesame provider, same tool formatlog both decisions
Scroll sideways →Retry versus fallback. A retry repeats the same call to the same model; a fallback moves the request one step to a standby model after a failure signal.

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.

TRY THIS TODAY

Goal: Route one request per tier and force one fallback, with both visible in the proxy log.

  1. Add a router entry to config.yaml below 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: balanced
  2. Add the fallback block at the top level of the file. The standby is on the same provider as the primary.

    config.yaml
    router_settings:
      fallbacks: [{"performance": ["balanced"]}]
      num_retries: 2
      cooldown_time: 30
  3. Restart the proxy.

    terminal
    litellm --config config.yaml
  4. Send three requests of rising complexity to smart-router.

    terminal
    curl -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."

  5. Set the performance tier's API key to an invalid value, restart the proxy, and send the third request again.
  6. Read the proxy log. Find the model field 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.

Subscribe to Newsletter
1.4

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.

How to build the eval dataset and the judge you need before you trust a router with live traffic. Watch: How to Systematically Setup LLM Evals.

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.

COST PER THREAD, BY EXPERIMENT ARMAlways performance modelRoutedMedian cost$2.61$0.94Mean cost$4.76$2.75p90 cost$11.07$6.93477 vs 496 threads · merged-PR rate 27.3% vs 29.2% (p = 0.49) · PR open rate 39.6% vs 38.9% (p = 0.82)
Scroll sideways →What routing saved per thread: median cost fell 64 percent against always using the performance model, while the merged-PR rate held. Source: LangChain, Open SWE router, 973 threads, Sep 16 to 22, 2026.

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.

WHERE ROUTED THREADS WENTFast 34%Balanced 56%Performance 10%median thread cost: fast $0.097 balanced $1.50 performance $2.88 (a 30x spread)Only one routed thread in ten needed the top tier.
Scroll sideways →Where routed threads went: nine in ten were served by the fast or balanced tier, and the cost ladder between tiers was 30x. Source: LangChain, Open SWE router, 496 routed threads.
LLM cost per thread on a log scale: always GPT-6 Astra versus routed, and routed threads split by tier, as violin plots with the median marked.
How cost per thread was spread, not just its median: the routed arm shifts the whole distribution down, and the three tiers sit at clearly different price levels. Source: LangChain, Open SWE router, Sep 16 to 22, 2026.

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.

TRY THIS TODAY

Goal: Build a one-week before-and-after sheet for the router you set up.

  1. Choose one success metric you can record for every task: a merged PR, a passing test run, or a thumbs rating.
  2. Split the agent's traffic. Send half to smart-router and half to performance, by alternating threads or by team.
  3. Log four fields per thread: the arm, the tier that served it (from the model field in the log), the cost, and the metric.
  4. After a week, compute the median and p90 cost per arm, and the metric per arm.
  5. Compute the tier share of routed threads.
  6. 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.

END OF MODULE 1

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.