How to build an LLM model router to cut AI agent costs

2026-11-30来源 dev.toEnglish

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.

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:

Tier What goes there Example model
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:

Strategy How it decides My take
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.0005 ok labelled simple routed simple answered simple scores [7] $0.0005 ok labelled simple routed simple answered simple scores [9] $0.0005 ok labelled simple routed simple answered simple scores [8] $0.0005 ok labelled simple routed simple answered simple scores [7] $0.0006 ok labelled simple routed simple answered simple scores [8] $0.0005 ok labelled standard routed standard answered standard scores [7] $0.0055 ok labelled standard routed standard answered frontier scores [6, 6] $0.0160 ok labelled standard routed standard answered standard scores [9] $0.0060 MISS labelled standard routed simple answered simple scores [9] $0.0008 ok labelled frontier routed frontier answered frontier scores [7] $0.0443 ok labelled frontier routed frontier answered frontier scores [7] $0.0373 router agreed with my labels: 11/12 answered by: {'simple': 7, 'standard': 2, 'frontier': 3} escalation rate: 8% total cost (routing, answers and judging): $0.1128 

And baseline.py:

simple prompts on the frontier model: $0.0086 standard prompts on the frontier model: $0.0183 frontier prompts on the frontier model: $0.0522 every prompt on the frontier model: $0.0791 

Your numbers will differ, because model outputs and their lengths change from run to run.

What the test showed

The router agreed with my labels on 11 of 12 prompts. The miss was the refund question, which I'd labelled standard because it takes a few steps of maths. The router sent it to the simple tier, Haiku got the right answer ($18 for the returned item plus the $5.99 charged twice, $23.99), and the judge gave it 9. That miss saved money.

The six simple prompts cost $0.0030 through the router, counting the routing and judging calls, against $0.0086 when Opus answered them directly. That's about 65% less, and the routing and judging calls are a big part of what's left.

The total is a different story. The routed run cost $0.1128 and the all-Opus run cost $0.0791, so on this test the router cost more. Two things did that. The two frontier prompts were most of the bill in both runs, because hard questions get long answers. And Opus's answers vary a lot in length: an earlier run of the same prompts on Opus cost $0.1472. Twelve prompts can't show you savings that small run-to-run swings hide. You need weeks of real traffic and the costs from your log.

The one escalation was a false alarm. Sonnet wrote a fine 100-word product description, and the Haiku judge scored it 6 twice, so Opus wrote it again. A cheap judge saves money, but check a sample of its scores against your own before you let it trigger escalations.

So the savings depend on what share of your spend goes to simple work, not what share of your requests. If your agent mostly classifies tickets and pulls data out of invoices, a router cuts the bill a lot. If most of your money goes to a few long, hard requests, it barely moves, and you're better off caching repeated answers or cutting what you send the model.

LLM routing FAQ

Is LLM routing cheaper than using one frontier model for everything? Only when most of your spend goes to simple work. A router sends easy requests to models that cost a small fraction of a frontier model, but every request also pays for the routing call, and escalations pay twice. In my test the simple prompts got about 65% cheaper, while the whole run cost more because two hard prompts made up most of the bill. Log a few weeks of real traffic, check what share of the money goes to simple requests, and you'll know before you build anything.

How do I route simple tasks to a cheap LLM and hard ones to a frontier model? Label a sample of your real prompts by difficulty, map each label to a model tier, and put a classifier in front of your agent that picks the tier for each new request. That classifier can be a small LLM, as in my code above, or plain rules like prompt length and keywords. Then score a sample of the cheap model's answers and send the weak ones up a tier.

Are there services that do the routing for me? Yes. Not Diamond is a hosted router that picks a model for each request and can train a custom router on your own eval data. RouteLLM is an open-source framework from LMSYS that trains routers to send simpler queries to a cheaper model. Either one still needs your labelled prompts to tell whether it's routing well for your traffic.

Is it worth it?

For most businesses, yes. When you do the labelling in step 1, you'll find that only a small share of what your AI handles really needs a frontier model. Most of it is simple tasks and simple questions that cheaper models can answer. If you're sending all of it to the frontier model today, that's where your token bill is going. Route the simple work to a cheap model, measure what you actually save, and keep the frontier model for the requests that need it.

If you'd rather have someone build this into your workflows, that's the kind of thing I do in AI automation projects.

Originally published on hassandev.me.

原文:https://www.a8q9.cn/en/article/how-to-build-an-llm-model-router-to-cut-ai-agent-costs-75b9b8.html

相关文章