Model Routing for AI Agents: Send Each Step to the Right LLM in Python
In this article, you will learn how to send each step of an AI agent to the right model, escalate to a stronger model when a cheap one fails a check, and measure the cost per accepted task.
Topics we will cover include:
- How a router, a cascade, and a fallback differ, and why this project combines a routing table with a single validated escalation.
- How to wrap a local Ollama model and a hosted Claude model behind one interface, then add a cost ledger and cheap validators.
- How to run a support-ticket agent through four routing setups and compare pass rate, latency, and cost per accepted task.
What Is Model Routing?
Model routing means choosing which model handles each request. A router decides before the call. A cascade decides after it: try the cheap model first, check the answer, and move up to a bigger model only if the check fails. A fallback is the emergency version, where a second model takes over when the first one errors out, such as the cloud fallback in my Hermes + Ollama walkthrough.
We combine the first two. A routing table picks the default model for each step type, and a validator triggers one escalation when a cheap model's output isn't usable. Each half covers the other's weakness.
The Experiment: A Support Agent, Four Ways
We'll use a customer support triage agent that handles 10 short tickets. Each ticket goes through three steps. In planning, the agent decides the customer's intent (shipping, refund, or account access) and which tool to use. In the tool call, it writes a small JSON object with the tool name and an argument, such as an order ID, and our code runs that tool against mock data. In summarization, it writes a short reply that quotes the facts the tool returned.
We run the same tickets through four setups.
| Arm | Plan | Tool call | Summarize | Escalation |
|---|---|---|---|---|
| frontier_only | frontier | frontier | frontier | n/a |
| local_only | local | local | local | off |
| routed | frontier | local | local | off |
| routed_escalate | frontier | local | local | on |
Scoring is deterministic, so you don't need an LLM judge. A ticket passes only if the plan has the right intent and tool, the tool call has the right arguments, and the reply contains every required fact from the tool result.
We report pass rate, cost and latency per ticket, escalation rate, and the number that matters most: cost per accepted task, which is total spend divided by the tickets that passed. A cheap setup that fails half the time isn't cheap.
Setup
You need Python 3.10 or newer, a machine that can run a small local model, and an Anthropic API key.
ollama pull llama3.2:3b
mkdir router-agents && cd router-agents
pip install requests anthropic
export ANTHROPIC_API_KEY="your-key-here"
The first line downloads llama3.2:3b into Ollama, which my Hermes article lists as needing about 2 GB on disk and roughly 4 GB of RAM. The next two create the folder and install requests (to talk to Ollama) and the official Anthropic SDK. The last stores your key, which the SDK reads from the environment, so it never appears in your code.
On Windows PowerShell, use $env:ANTHROPIC_API_KEY="your-key-here" .
Step 1: One Interface for Two Kinds of Model
A router can swap models freely only if every model looks the same from outside. This file defines one result type and two clients that return it.
# clients.py
import os
import time
from dataclasses import dataclass
import requests
@dataclass
class LLMResult:
text: str
input_tokens: int
output_tokens: int
latency_s: float
model: str
tier: str # "local" or "frontier"
class LocalClient:
"""A model served by Ollama through its /api/chat endpoint."""
tier = "local"
def __init__(self, model=None, host=None):
self.model = model or os.getenv("LOCAL_MODEL", "llama3.2:3b")
host = host or os.getenv("OLLAMA_HOST", "http://localhost:11434")
self.url = host.rstrip("/") + "/api/chat"
def complete(self, system, user, json_mode=False, max_tokens=400):
payload = {"model": self.model, "stream": False, "messages": [{"role": "system", "content": system}, {"role": "user", "content": user}], "options": {"temperature": 0, "num_predict": max_tokens}}
if json_mode:
payload["format"] = "json"
start = time.perf_counter()
response = requests.post(self.url, json=payload, timeout=300)
response.raise_for_status()
data = response.json()
return LLMResult(data["message"]["content"], data.get("prompt_eval_count", 0), data.get("eval_count", 0), time.perf_counter() - start, self.model, self.tier)
class FrontierClient:
"""A hosted Claude model through the Anthropic SDK."""
tier = "frontier"
def __init__(self, model=None):
import anthropic # imported here so the local path works without the SDK
self.model = model or os.getenv("FRONTIER_MODEL", "claude-sonnet-5-5")
self.client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
def complete(self, system, user, json_mode=False, max_tokens=1500):
start = time.perf_counter()
message = self.client.messages.create(model=self.model, max_tokens=max_tokens, system=system, messages=[{"role": "user", "content": user}])
text = "".join(block.text for block in message.content if block.type == "text")
return LLMResult(text, message.usage.input_tokens, message.usage.output_tokens, time.perf_counter() - start, self.model, self.tier)
LLMResult records what we'll need later: the text, token counts, latency, model, and tier. LocalClient calls Ollama's native /api/chat endpoint. stream: False returns one complete response, and format: "json" turns on Ollama's JSON mode, which guarantees a well-formed JSON object. We pin temperature to 0 so local runs are repeatable, and the token counts come from prompt_eval_count and eval_count .
FrontierClient wraps the Anthropic SDK, and the import sits inside __init__ so the local path works without the SDK. It accepts json_mode without using it, because for this client the prompt and the validators keep the output in shape. That way, the router never needs to know which client it holds.
Step 2: The Cost Ledger
Routing is an economics decision, so the numbers have to be right.
# ledger.py
# USD per million tokens (input, output). Check the pricing page: prices change.
PRICES = {"claude-sonnet-5-5": (2.00, 10.00), "claude-haiku-5-5": (0.10, 0.50)}
def cost_usd(result):
"""Local models have no per-token bill, so their marginal cost is zero."""
if result.tier == "local":
return 0.0
price_in, price_out = PRICES[result.model] # a KeyError means this model has no price yet
return (result.input_tokens * price_in + result.output_tokens * price_out) / 1_000_000
class Ledger:
def __init__(self):
self.records = []
def add(self, kind, result, escalated=False):
self.records.append({"kind": kind, "tier": result.tier, "cost": cost_usd(result), "latency": result.latency_s, "escalated": escalated})
def total(self, field):
return sum(r[field] for r in self.records)
PRICES holds the input and output price per million tokens: $2 and $10 for Claude Sonnet 5.5, and $0.10 and $0.50 for Haiku 5.5 on prompts up to 100,000 tokens. Prices change, so check that page first. cost_usd multiplies tokens by price, and local calls cost zero. That is a simplification worth stating when you publish results, since your hardware still costs electricity. A model missing from the table raises an error instead of counting as free.
To see the gap, take a step with 300 input and 50 output tokens: on Sonnet 5.5 that is $0.0011, and on Haiku 5.5 it is $0.000055, about 20 times less. That is arithmetic from the price list, not a measured result.
Step 3: The Tickets, Tools, and Gold Answers
The agent needs something to act on.
# tickets.py
ORDERS = {
"A1001": {"status": "in transit", "delivery_date": "2026-10-14", "amount": "$49.99", "refund_window_ends": "2026-11-01"},
"A1002": {"status": "delivered", "delivery_date": "2026-10-02", "amount": "$120.00", "refund_window_ends": "2026-10-17"},
"A1003": {"status": "processing", "delivery_date": "2026-10-16", "amount": "$18.50", "refund_window_ends": "2026-11-08"},
"A1005": {"status": "delivered", "delivery_date": "2026-09-20", "amount": "$33.00", "refund_window_ends": "2026-10-05"},
}
ACCOUNTS = {
"m***@example.com": {"status": "locked", "next_step": "use the Forgot Password link"},
"d**@example.com": {"status": "suspended", "next_step": "contact billing"},
}
# The two tools, and the one argument each takes.
TOOLS = {"lookup_order": lambda order_id: ORDERS.get(order_id, {"error": "order not found"}), "lookup_account": lambda email: ACCOUNTS.get(email, {"error": "account not found"})}
TOOL_PARAM = {"lookup_order": "order_id", "lookup_account": "email"}
# intent -> (tool to use, values from the tool result that a good reply must quote)
INTENTS = {
"shipping_status": ("lookup_order", ["status", "delivery_date"]),
"refund_request": ("lookup_order", ["amount", "refund_window_ends"]),
"account_access": ("lookup_account", ["status", "next_step"]),
}
def _t(ticket_id, text, intent, arg):
tool, keys = INTENTS[intent]
result = TOOLS[tool](arg) # gold facts come from the real tool, so they can't drift from the data
return {"id": ticket_id, "text": text, "intent": intent, "tool": tool, "args": {TOOL_PARAM[tool]: arg}, "required_facts": [str(result[k]) for k in keys]}
TICKETS = [
_t(1, "Hi, where is my order A1001? It was supposed to arrive already.", "shipping_status", "A1001"),
_t(2, "Can you tell me when A1003 will ship?", "shipping_status", "A1003"),
_t(3, "Is A1002 really delivered? I never saw it.", "shipping_status", "A1002"),
_t(4, "I would like my money back for order A1002, the lamp arrived cracked.", "refund_request", "A1002"),
_t(5, "Please refund A1005. I changed my mind about the jacket.", "refund_request", "A1005"),
_t(6, "A1001 is taking forever. Cancel it and refund me.", "refund_request", "A1001"),
_t(7, "My account m***@example.com is locked and I cannot sign in.", "account_access", "m***@example.com"),
_t(8, "d**@example.com says my account is suspended. Why?", "account_access", "d**@example.com"),
_t(9, "Two things: my login for m***@example.com is broken, but mainly I need to know where A1001 is.", "shipping_status", "A1001"),
_t(10, "Forget tracking A1005, I just want my $33.00 back.", "refund_request", "A1005"),
]
ORDERS and ACCOUNTS stand in for the databases a real agent would query, and TOOLS maps each tool name to its function. INTENTS says which tool serves each intent and which values from the tool result a good reply must quote. The helper _t builds each ticket and computes its required facts by running the real mock tool, so the gold answers can't drift from the data.
Tickets 6, 9, and 10 are the tricky ones: "Cancel it and refund me" about a late order, a broken login from a customer who mainly wants to know where an order is, and "Forget tracking" before asking for money back.
Step 4: Validators That Catch Bad Output Cheaply
Escalation needs a trigger. These checks are plain Python and make no model calls.
# validators.py
import json
import re
from tickets import INTENTS, TOOLS, TOOL_PARAM
FENCE = "`" * 3 # built this way so a markdown fence can't end this block early
def parse_json(text):
"""Pull the first JSON object out of a model reply, tolerating code fences."""
cleaned = re.sub(re.escape(FENCE) + "(?:json)?", "", text)
try:
obj = json.loads(cleaned[cleaned.find("{"): cleaned.rfind("}") + 1])
except json.JSONDecodeError:
return None
return obj if isinstance(obj, dict) else None
def validate_plan(text):
obj = parse_json(text) or {}
ok = obj.get("intent") in INTENTS and obj.get("tool") in TOOLS
return ok, "" if ok else "plan is not JSON with a known intent and tool"
def make_tool_validator(ticket_text):
def check(text):
obj = parse_json(text) or {}
tool, args = obj.get("tool"), obj.get("args")
if tool not in TOOLS or not isinstance(args, dict):
return False, "not a valid tool call"
value = args.get(TOOL_PARAM[tool])
if not isinstance(value, str) or value not in ticket_text: # catches invented order IDs
return False, "argument was not copied from the ticket"
return True, ""
return check
def make_summary_validator(required_facts, max_words=80):
def check(text):
missing = [f for f in required_facts if f.lower() not in text.lower()]
if not text.strip() or len(text.split()) > max_words or missing:
return False, f"reply is empty, too long or missing {missing}"
return True, ""
return check
parse_json strips code fences and takes the first {...} block, because small models love to wrap JSON in fences or add a sentence before it. validate_plan checks only the shape: valid JSON, a known intent, a known tool. It can't tell whether the intent is correct, which is exactly why planning goes to the frontier model by default.
make_tool_validator confirms the argument value really appears in the ticket, which catches the classic small-model mistake of inventing a plausible order ID. make_summary_validator requires a short reply containing every required fact. Validators check that output is well formed, while the evaluator in Step 7 checks it against the dataset's gold answers.
Step 5: The Router
This is the center of the project, and it's short on purpose.
# router.py
from dataclasses import dataclass
# The routing table: which tier handles which kind of step.
ROUTED_POLICY = {"plan": "f
Comments
No comments yet. Start the discussion.