How to build an LLM model router to cut AI agent costs
The short version
An LLM model router reads each request and sends it to the cheapest model that can handle it, so your frontier model only gets the hard requests.
Start by labelling at least 500 real user prompts by task type and difficulty. More than half usually turn out to be simple work like formatting text or pulling data out of documents.
Use a small, cheap LLM as the router instead of keyword rules, which break as soon as users phrase things in ways you didn't expect.
Judge answers with another LLM and escalate failed ones to the next tier up. If 20% or more of requests get escalated, your routing needs fixing.
Savings depend on what share of your spend goes to simple work, not what share of your requests. In my test the router cut the simple prompts' cost by about 65%, but two hard prompts were most of the bill either way.
What a model router is
An LLM model router is a small step in front of your AI agent that reads each request and sends it to the cheapest model that can handle it, instead of sending everything to your most expensive model.
You keep the frontier model for the hard requests and let small, cheap models answer the rest, which is where most of the savings on an AI agent come from.
Below is how I'd build one in four steps, then a working router in Python with escalation and an LLM judge, and what it cost when I ran it. The video above covers the same steps.
Why one model for everything costs so much
Most businesses that use AI pick one model, usually the smartest one, and send it every request. In a perfect world that's what you'd do: let the most intelligent model handle everything. But your company has a limited budget, and frontier models are the most expensive tokens you can buy.
Most of what a business agent does doesn't need that much intelligence. Turning messy meeting notes into a clean summary with action items, pulling fields out of an invoice into JSON, sorting support tickets into categories, summarizing a short document, answering a customer's question when the answer is in your docs: small models like Gemma 4 or Qwen 3.6 27B do all of these well. I use them for this kind of work myself. I wouldn't use them for coding or for hard reasoning, but for everyday business tasks they're great.
If a frontier model does those jobs, you're paying for intelligence you don't use. A router fixes that.
How a model router works
The user sends a prompt like always. Before it reaches a model, the router reads it and picks the tier that should answer it. The request goes to that tier, and the answer goes back to the user. The user never sees the router.
Building one is mostly manual work, so be ready for that. Here are the steps.
Step 1: label at least 500 real prompts
Take a sample of at least 500 prompts that real users have sent your agent. Go through them by hand and tag each one with its task type and how hard it is.
You'll find that most users send the same kinds of requests over and over. Once you've tagged 500, you'll usually see that more than half of them could be handled by a cheaper model. That's the big win.
Keep the labelled set, because you'll use it to test the router later.
Step 2: set up three tiers
Make three tiers to route requests to:
- Simple: Formatting, extracting data, classifying, short summaries, simple Q&A - A small model like Claude Haiku or Gemma 4
- Standard: Writing emails and product copy, everyday coding - A mid-tier model like Claude Sonnet
- Frontier: Hard reasoning and debugging, decisions with lots of trade-offs - Your best model, like Claude Opus or GPT-5.6
I wouldn't go past three tiers. Every extra tier is another boundary the router can get wrong and another model you have to test, and it gets complicated fast.
To pick the actual model for each tier, use the method from how to choose the cheapest LLM that still does the job .
Step 3: pick a routing strategy
The router needs a way to decide which tier gets each request. There are a few options:
- Rule-based: Prompt length and keywords - Cheap and fast, but brittle. Users phrase things in ways your rules never expected
- Semantic: Compares the prompt's embedding with example prompts for each tier - Works well, but you have to build and maintain the example sets
- LLM router: A small, cheap model reads the prompt and names the tier - What I recommend for most businesses
- Cascade: Always tries the cheap model first and moves up when the answer fails a check - Good as a backup, but every hard request pays for a failed cheap attempt
I recommend the LLM router. It's the first step in the chain. The router sends the prompt to a small model that understands language well, and that model replies with the name of the tier that should handle it. The routing call is tiny, so it costs very little compared to what it saves.
The semantic approach (the same embedding comparison I use for semantic caching ) is good too, but most business owners don't need that complexity.
Step 4: track costs and quality, and escalate
You won't get the router right on the first try, so deploy it with a way to measure it.
Track your costs first. The whole point of the router is to save money, so log what every request costs and compare it with what you paid before. If you aren't saving money, what are we even doing?
Then check quality, because cheaper models shouldn't mean worse answers for your users. Have a person review a sample of answers, and use an LLM as a judge: send the user's prompt and the answer to another model and ask it to score the answer. Low scores tell you something needs fixing. Ideally you'd judge every response, but if you get thousands of requests a day, a random sample of a couple of hundred is enough.
When a model fails a request, escalate it to the next tier up. If the router sent a hard request to the cheap model and the answer fails the judge, the stronger model should get a second try. Then track your escalation rate, the share of requests that end up escalated. If it's 20% or more, your routing is broken: the router keeps sending hard requests to cheap models, and you're paying for two answers on every one of them.
Build a model router in Python
I tested this with the Claude Code CLI in print mode (claude -p), because it reports what each call costs at API list prices and I didn't want to pay for demo API calls. In production you'd swap the one complete() function for your provider's SDK or an OpenAI-compatible endpoint, and nothing else changes. It only uses Python's standard library, so there's nothing to install.
router/
├── llm.py # one function that calls a model
├── router.py# the tiers and the routing prompt
├── agent.py # route, answer, judge, escalate, log
├── prompts.json # my labelled prompts
├── run.py # runs every prompt through the agent
└── baseline.py# the same prompts on the frontier model only
llm.py
import json
import subprocess
def complete ( model , system , prompt ) :
"""Send one prompt to a Claude model and return (text, cost in USD)."""
result = subprocess . run ( [ "claude" , "-p" , "--model" , model , "--system-prompt" , system , "--tools" , "" , "--output-format" , "json" , "--no-session-persistence" , "--setting-sources" , "" , "--strict-mcp-config" , ] , input = prompt , capture_output = True , text = True , check = True , )
data = json . loads ( result . stdout )
return data [ "result" ] , data [ "total_cost_usd" ]
Every model call in the project goes through this function. It replaces Claude Code's system prompt with ours, turns off its tools and settings, and reads the answer and the cost from the JSON output. The CLI still adds around 600 tokens of its own to each call, so the costs below are a bit higher than direct API calls would be.
router.py
from llm import complete
TIERS = { "simple" : "haiku" , "standard" : "sonnet" , "frontier" : "opus" }
ORDER = [ "simple" , "standard" , "frontier" ]
ROUTER_MODEL = "haiku"
ROUTER_PROMPT = """You route requests for a small online store's AI assistant. Pick the cheapest tier that can handle the request well. simple: formatting, pulling fields out of text, classifying, short summaries, and questions whose answer is in the request. standard: writing emails or product copy, everyday code, and questions that need a few steps of working out. frontier: hard reasoning, decisions with many trade-offs, and debugging or designing systems. Reply with the tier name only."""
def route ( prompt ) :
text , cost = complete ( ROUTER_MODEL , ROUTER_PROMPT , prompt )
tier = text . strip ( ) . lower ( ) . rstrip ( "." )
if tier not in TIERS :
tier = "standard"
return tier , cost
The tier descriptions in ROUTER_PROMPT come straight from step 1. Write them from your own labelled prompts, not from my list. If the router model replies with anything that isn't a tier name, the request goes to the standard tier, which is a safe middle.
agent.py
import json
import random
from llm import complete
from router import ORDER , TIERS , route
ANSWER_PROMPT = "You are the assistant for a small online store. Be concise."
JUDGE_MODEL = "haiku"
JUDGE_PROMPT = """You grade an AI assistant's answers. Score how well the answer handles the request, from 1 to 10. 10 means correct, complete and ready to send. Reply with the number only."""
PASS_SCORE = 7
JUDGE_RATE = 1.0 # share of answers to judge; lower it when traffic is high
def judge ( prompt , answer ) :
text , cost = complete ( JUDGE_MODEL , JUDGE_PROMPT , f "Request:\n{prompt}\n\nAnswer:\n{answer}" )
try :
return int ( text . strip ( ) ) , cost
except ValueError :
return 0 , cost
def handle ( prompt , log_path = "log.jsonl" ) :
tier , cost = route ( prompt )
routed_to = tier
scores = [ ]
while True :
answer , answer_cost = complete ( TIERS [ tier ] , ANSWER_PROMPT , prompt )
cost += answer_cost
if random . random ( ) >= JUDGE_RATE :
break
score , judge_cost = judge ( prompt , answer )
cost += judge_cost
scores . append ( score )
if score >= PASS_SCORE or tier == ORDER [ - 1 ] :
break
tier = ORDER [ ORDER . index ( tier ) + 1 ] # escalate one tier
with open ( log_path , "a" ) as f :
record = { "prompt" : prompt , "routed_to" : routed_to , "answered_by" : tier , "escalated" : tier != routed_to , "scores" : scores , "cost_usd" : cost , }
f . write ( json . dumps ( record ) + "\n" )
return answer
handle() is what your agent calls for each user request. It routes the prompt and has the judge score the answer from that tier. An answer below 7 out of 10 moves up one tier and tries again, until it passes or reaches the frontier model.
JUDGE_RATE is the sampling from step 4: at 0.1, only one answer in ten gets judged. Every request ends up as one line in log.jsonl. Comparing routed_to with answered_by gives you the escalation rate, and cost_usd is your cost tracking.
The test prompts and the runner
For the test I wrote 12 prompts for a made-up online store and labelled each one by hand, the way step 1 describes. Half of them are simple, which is roughly what step 1 tends to show, and the rest are four standard prompts and two frontier ones. The file starts like this:
[ { "tier" : "simple" , "prompt" : "Turn these notes into a list of action items: call supplier about the late mugs, Sara updates the shipping page, refund order 1043 by Friday" } , { "tier" : "simple" , "prompt" : "Pull the invoice number, date and total out of this as JSON: Invoice INV-2291, issued 3 Nov 2026, total due $412.50, payable within 30 days." } ,
run.py sends each prompt through handle() and compares the router's pick with my label:
import json
from collections import Counter
from agent import handle
with open ( "prompts.json" ) as f :
samples = json . load ( f )
open ( "log.jsonl" , "w" ) . close ( )
for sample in samples :
handle ( sample [ "prompt" ] )
with open ( "log.jsonl" ) as f :
records = [ json . loads ( line ) for line in f ]
correct = 0
for sample , record in zip ( samples , records ) :
match = sample [ "tier" ] == record [ "routed_to" ]
correct += match
print ( f "{'ok' if match else 'MISS'} labelled {sample['tier']:<8} " f "routed {record['routed_to']:<8} answered {record['answered_by']:<8} " f "scores {record['scores']}${record['cost_usd']:.4f}" )
total = sum ( r [ "cost_usd" ] for r in records )
escalated = sum ( r [ "escalated" ] for r in records )
print ( f "\nrouter agreed with my labels: {correct}/{len(records)}" )
print ( f "answered by: {dict(Counter(r['answered_by'] for r in records))}" )
print ( f "escalation rate: {escalated / len(records):.0%}" )
print ( f "total cost (routing, answers and judging): ${total:.4f}" )
baseline.py sends the same prompts straight to the frontier model, so there's something to compare against:
import json
from collections import defaultdict
from agent import ANSWER_PROMPT
from llm import complete
with open ( "prompts.json" ) as f :
samples = json . load ( f )
by_tier = defaultdict ( float )
for sample in samples :
_ , cost = complete ( "opus" , ANSWER_PROMPT , sample [ "prompt" ] )
by_tier [ sample [ "tier" ] ] += cost
for tier , cost in by_tier . items ( ) :
print ( f "{tier:<8} prompts on the frontier model: ${cost:.4f}" )
print ( f "every prompt on the frontier model: ${sum(by_tier.values()):.4f}" )
Run it
With Claude Code installed and logged in, run both scripts from the router folder:
python3 run.py
python3 baseline.py
Here's what run.py printed for me, with the Haiku 5.5, Sonnet 5.5 and Opus 5.5 models behind the CLI aliases:
ok labelled simple routed simple answered simple scores [8]$0.0005ok labelled simple routed simple answered simple scores [7]$0.0005ok labelled simple routed simple answered simple scores [9]$0.0005ok labelled simple routed simple answered simple scores [8]$0.0005ok labelled simple routed simple answered simple scores [7]$0.0006ok labelled simple routed simple answered simple scores [8]$0.0005ok labelled standard routed standard answered standard scores [7]$0.0055ok labelled standard routed standard answered frontier scores [6, 6]$0.0160ok labelled standard routed standard
Comments
No comments yet. Start the discussion.