{"slug": "how-to-build-an-llm-model-router-to-cut-ai-agent-costs", "title": "How to build an LLM model router to cut AI agent costs", "summary": "A developer outlined a four-step method for building an LLM model router that sits in front of an AI agent and dispatches each request to the cheapest model tier capable of handling it, reserving frontier models for hard reasoning and debugging. The approach recommends tagging at least 500 real user prompts by task type and difficulty, defining no more than three tiers, and using a small, cheap LLM to classify each prompt's tier rather than brittle rule-based or semantic matching. The developer reports that more than half of typical business-agent requests can be handled by cheaper models, with a cascade strategy offered as a backup.", "body_md": "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.\n\nBelow 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.\n\nMost 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.\n\nMost 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.\n\nIf a frontier model does those jobs, you're paying for intelligence you don't use. A router fixes that.\n\nThe 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.\n\nBuilding one is mostly manual work, so be ready for that. Here are the steps.\n\nTake 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.\n\nYou'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.\n\nMake three tiers to route requests to:\n\n| Tier | What goes there | Example model | \n|---|---|---|\n| Simple | Formatting, extracting data, classifying, short summaries, simple Q&A | A small model like Claude Haiku or Gemma 4 | \n| Standard | Writing emails and product copy, everyday coding | A mid-tier model like Claude Sonnet | \n| Frontier | Hard reasoning and debugging, decisions with lots of trade-offs | Your best model, like Claude Opus or GPT-5.6 | \n\nI 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](https://www.hassandev.me/blog/youtube/the-simple-hack-to-100x-your-llm-costs-j3aqbvLIBd4).\n\nThe router needs a way to decide which tier gets each request. There are a few options:\n\n| Strategy | How it decides | My take | \n|---|---|---|\n| Rule-based | Prompt length and keywords | Cheap and fast, but brittle. Users phrase things in ways your rules never expected | \n| Semantic | Compares the prompt's embedding with example prompts for each tier | Works well, but you have to build and maintain the example sets | \n| LLM router | A small, cheap model reads the prompt and names the tier | What I recommend for most businesses | \n| 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 | \n\nI 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](https://www.hassandev.me/blog/youtube/semantic-caching-stop-paying-for-the-same-answer-3gU_BA_19f0)) is good too, but most business owners don't need that complexity.\n\nYou won't get the router right on the first try, so deploy it with a way to measure it.\n\nTrack 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?\n\nThen 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.\n\nWhen 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.\n\nThen 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.\n\nI 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.\n\n```\nrouter/\n├── llm.py         # one function that calls a model\n├── router.py      # the tiers and the routing prompt\n├── agent.py       # route, answer, judge, escalate, log\n├── prompts.json   # my labelled prompts\n├── run.py         # runs every prompt through the agent\n└── baseline.py    # the same prompts on the frontier model only\npython\nimport json\nimport subprocess\n\ndef complete(model, system, prompt):\n    \"\"\"Send one prompt to a Claude model and return (text, cost in USD).\"\"\"\n    result = subprocess.run(\n        [\n            \"claude\", \"-p\",\n            \"--model\", model,\n            \"--system-prompt\", system,\n            \"--tools\", \"\",\n            \"--output-format\", \"json\",\n            \"--no-session-persistence\",\n            \"--setting-sources\", \"\",\n            \"--strict-mcp-config\",\n        ],\n        input=prompt,\n        capture_output=True,\n        text=True,\n        check=True,\n    )\n    data = json.loads(result.stdout)\n    return data[\"result\"], data[\"total_cost_usd\"]\n```\n\nEvery 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.\n\n``` python\nfrom llm import complete\n\nTIERS = {\"simple\": \"haiku\", \"standard\": \"sonnet\", \"frontier\": \"opus\"}\nORDER = [\"simple\", \"standard\", \"frontier\"]\nROUTER_MODEL = \"haiku\"\n\nROUTER_PROMPT = \"\"\"You route requests for a small online store's AI assistant.\nPick the cheapest tier that can handle the request well.\n\nsimple: formatting, pulling fields out of text, classifying, short summaries,\nand questions whose answer is in the request.\nstandard: writing emails or product copy, everyday code, and questions that\nneed a few steps of working out.\nfrontier: hard reasoning, decisions with many trade-offs, and debugging or\ndesigning systems.\n\nReply with the tier name only.\"\"\"\n\ndef route(prompt):\n    text, cost = complete(ROUTER_MODEL, ROUTER_PROMPT, prompt)\n    tier = text.strip().lower().rstrip(\".\")\n    if tier not in TIERS:\n        tier = \"standard\"\n    return tier, cost\n```\n\nThe 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.\n\n``` python\nimport json\nimport random\n\nfrom llm import complete\nfrom router import ORDER, TIERS, route\n\nANSWER_PROMPT = \"You are the assistant for a small online store. Be concise.\"\n\nJUDGE_MODEL = \"haiku\"\nJUDGE_PROMPT = \"\"\"You grade an AI assistant's answers.\nScore how well the answer handles the request, from 1 to 10.\n10 means correct, complete and ready to send. Reply with the number only.\"\"\"\nPASS_SCORE = 7\nJUDGE_RATE = 1.0  # share of answers to judge; lower it when traffic is high\n\ndef judge(prompt, answer):\n    text, cost = complete(\n        JUDGE_MODEL, JUDGE_PROMPT, f\"Request:\\n{prompt}\\n\\nAnswer:\\n{answer}\"\n    )\n    try:\n        return int(text.strip()), cost\n    except ValueError:\n        return 0, cost\n\ndef handle(prompt, log_path=\"log.jsonl\"):\n    tier, cost = route(prompt)\n    routed_to = tier\n    scores = []\n\n    while True:\n        answer, answer_cost = complete(TIERS[tier], ANSWER_PROMPT, prompt)\n        cost += answer_cost\n        if random.random() >= JUDGE_RATE:\n            break\n        score, judge_cost = judge(prompt, answer)\n        cost += judge_cost\n        scores.append(score)\n        if score >= PASS_SCORE or tier == ORDER[-1]:\n            break\n        tier = ORDER[ORDER.index(tier) + 1]  # escalate one tier\n\n    with open(log_path, \"a\") as f:\n        record = {\n            \"prompt\": prompt,\n            \"routed_to\": routed_to,\n            \"answered_by\": tier,\n            \"escalated\": tier != routed_to,\n            \"scores\": scores,\n            \"cost_usd\": cost,\n        }\n        f.write(json.dumps(record) + \"\\n\")\n    return answer\n```\n\n`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.\n\nFor 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:\n\n```\n[\n  {\"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\"},\n  {\"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.\"},\n```\n\n`run.py` sends each prompt through `handle()` and compares the router's pick with my label:\n\n``` python\nimport json\nfrom collections import Counter\n\nfrom agent import handle\n\nwith open(\"prompts.json\") as f:\n    samples = json.load(f)\n\nopen(\"log.jsonl\", \"w\").close()\nfor sample in samples:\n    handle(sample[\"prompt\"])\n\nwith open(\"log.jsonl\") as f:\n    records = [json.loads(line) for line in f]\n\ncorrect = 0\nfor sample, record in zip(samples, records):\n    match = sample[\"tier\"] == record[\"routed_to\"]\n    correct += match\n    print(\n        f\"{'ok  ' if match else 'MISS'} labelled {sample['tier']:<8} \"\n        f\"routed {record['routed_to']:<8} answered {record['answered_by']:<8} \"\n        f\"scores {record['scores']}  ${record['cost_usd']:.4f}\"\n    )\n\ntotal = sum(r[\"cost_usd\"] for r in records)\nescalated = sum(r[\"escalated\"] for r in records)\nprint(f\"\\nrouter agreed with my labels: {correct}/{len(records)}\")\nprint(f\"answered by: {dict(Counter(r['answered_by'] for r in records))}\")\nprint(f\"escalation rate: {escalated / len(records):.0%}\")\nprint(f\"total cost (routing, answers and judging): ${total:.4f}\")\n```\n\n`baseline.py` sends the same prompts straight to the frontier model, so there's something to compare against:\n\n``` python\nimport json\nfrom collections import defaultdict\n\nfrom agent import ANSWER_PROMPT\nfrom llm import complete\n\nwith open(\"prompts.json\") as f:\n    samples = json.load(f)\n\nby_tier = defaultdict(float)\nfor sample in samples:\n    _, cost = complete(\"opus\", ANSWER_PROMPT, sample[\"prompt\"])\n    by_tier[sample[\"tier\"]] += cost\n\nfor tier, cost in by_tier.items():\n    print(f\"{tier:<8} prompts on the frontier model: ${cost:.4f}\")\nprint(f\"every prompt on the frontier model: ${sum(by_tier.values()):.4f}\")\n```\n\nWith Claude Code installed and logged in, run both scripts from the `router` folder:\n\n```\npython3 run.py\npython3 baseline.py\n```\n\nHere's what `run.py` printed for me, with the Haiku 5.5, Sonnet 5.5 and Opus 5.5 models behind the CLI aliases:\n\n```\nok   labelled simple   routed simple   answered simple   scores [8]  $0.0005\nok   labelled simple   routed simple   answered simple   scores [7]  $0.0005\nok   labelled simple   routed simple   answered simple   scores [9]  $0.0005\nok   labelled simple   routed simple   answered simple   scores [8]  $0.0005\nok   labelled simple   routed simple   answered simple   scores [7]  $0.0006\nok   labelled simple   routed simple   answered simple   scores [8]  $0.0005\nok   labelled standard routed standard answered standard scores [7]  $0.0055\nok   labelled standard routed standard answered frontier scores [6, 6]  $0.0160\nok   labelled standard routed standard answered standard scores [9]  $0.0060\nMISS labelled standard routed simple   answered simple   scores [9]  $0.0008\nok   labelled frontier routed frontier answered frontier scores [7]  $0.0443\nok   labelled frontier routed frontier answered frontier scores [7]  $0.0373\n\nrouter agreed with my labels: 11/12\nanswered by: {'simple': 7, 'standard': 2, 'frontier': 3}\nescalation rate: 8%\ntotal cost (routing, answers and judging): $0.1128\n```\n\nAnd `baseline.py`:\n\n```\nsimple   prompts on the frontier model: $0.0086\nstandard prompts on the frontier model: $0.0183\nfrontier prompts on the frontier model: $0.0522\nevery prompt on the frontier model: $0.0791\n```\n\nYour numbers will differ, because model outputs and their lengths change from run to run.\n\nThe 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.\n\nThe 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.\n\nThe 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.\n\nThe 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.\n\nSo 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.\n\n**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.\n\n**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.\n\n**Are there services that do the routing for me?** Yes. [Not Diamond](https://www.notdiamond.ai) is a hosted router that picks a model for each request and can train a custom router on your own eval data. [RouteLLM](https://github.com/lm-sys/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.\n\nFor 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.\n\nIf you'd rather have someone build this into your workflows, that's the kind of thing I do in [AI automation projects](https://www.hassandev.me/services/ai-automation).\n\n*Originally published on [hassandev.me](https://www.hassandev.me/blog/youtube/cut-ai-agent-costs-by-80-2TVhf3UvhBw).*", "url": "https://wpnews.pro/news/how-to-build-an-llm-model-router-to-cut-ai-agent-costs", "canonical_source": "https://dev.to/hassan_aziz_88b11714fef8b/how-to-build-an-llm-model-router-to-cut-ai-agent-costs-4ieb", "published_at": "2026-11-30 10:39:15+00:00", "updated_at": "2026-11-30 10:44:34.114172+00:00", "lang": "en", "topics": ["large-language-models", "ai-agents", "ai-tools"], "entities": ["Gemma 4", "Qwen 3.6 27B", "Claude Haiku", "Claude Sonnet", "Claude Opus", "GPT-5.6"], "also_reported_by": [], "takeaway": "Route each agent request with a small, cheap LLM that names one of three tiers, after hand-tagging 500 real prompts to confirm most traffic can go to cheaper models.", "recommendation": {"advice": "Tag at least 500 real user prompts by task type and difficulty, then use a small LLM to classify each request into one of three tiers instead of brittle keyword rules.", "playbook": "llm-cost", "playbook_url": "https://wpnews.pro/playbooks/llm-cost"}, "alternates": {"html": "https://wpnews.pro/news/how-to-build-an-llm-model-router-to-cut-ai-agent-costs", "markdown": "https://wpnews.pro/news/how-to-build-an-llm-model-router-to-cut-ai-agent-costs.md", "text": "https://wpnews.pro/news/how-to-build-an-llm-model-router-to-cut-ai-agent-costs.txt", "jsonld": "https://wpnews.pro/news/how-to-build-an-llm-model-router-to-cut-ai-agent-costs.jsonld"}}