Model Routing for AI Agents: Send Each Step to the Right LLM in Python

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:3bmkdir router-agents && cd router-agentspip install requests anthropicexport 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. 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 # clients.pyimport osimport timefrom dataclasses import dataclassimport requests@dataclassclass 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. 1234567891011121314151617181920212223 # 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_000class 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. 1234567891011121314151617181920212223242526272829303132333435363738394041424344 # tickets.pyORDERS = { "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 = { "maya@example.com": {"status": "locked", "next_step": "use the Forgot Password link"}, "dan@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 maya@example.com is locked and I cannot sign in.", "account_access", "maya@example.com"), _t(8, "dan@example.com says my account is suspended. Why?", "account_access", "dan@example.com"), _t(9, "Two things: my login for maya@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. 123456789101112131415161718192021222324252627282930313233343536373839404142434445 # validators.pyimport jsonimport refrom tickets import INTENTS, TOOLS, TOOL_PARAMFENCE = "`" * 3 # built this way so a markdown fence can't end this block earlydef 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 Nonedef 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 checkdef 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. 123456789101112131415161718192021222324252627282930313233343536373839404142434445 # router.pyfrom dataclasses import dataclass# The routing table: which tier handles which kind of step.ROUTED_POLICY = {"plan": "frontier", "tool_call": "local", "summarize": "local"}FRONTIER_ONLY = {"plan": "frontier", "tool_call": "frontier", "summarize": "frontier"}LOCAL_ONLY = {"plan": "local", "tool_call": "local", "summarize": "local"}def classify_step(system, user): """Guess the step type from the prompt text. Use your own step labels if you have them.""" text = f"{system}\n{user}".lower() if "available tools" in text or '"args"' in text: return "tool_call" if "reply to the customer" in text: return "summarize" return "plan"@dataclassclass StepOutcome: text: str ok: bool escalated: boolclass Router: def __init__(self, clients, ledger, policy, escalate): self.clients, self.ledger, self.policy, self.escalate = clients, ledger, policy, escalate def run(self, system, user, validate): kind = classify_step(system, user) tier = self.policy[kind] json_mode = kind != "summarize" result = self.clients[tier].complete(system, user, json_mode=json_mode) self.ledger.add(kind, result) ok, _ = validate(result.text) if ok or tier == "frontier" or not self.escalate: return StepOutcome(result.text, ok, False) # Escalate once: send the same prompt to the frontier model. retry = self.clients["frontier"].complete(system, user, json_mode=json_mode) self.ledger.add(kind, retry, escalated=True) return StepOutcome(retry.text, validate(retry.text)[0], True) The three dictionaries are the routing table. ROUTED_POLICY sends planning to the frontier model and the two mechanical steps to the local one. The other two exist so the baseline arms run through the same code path. A table is easy to read and debug. classify_step guesses the step type from the prompt text, and if your agent already labels its steps, use the labels instead. Router.run classifies the step, looks up the tier, calls that client, records the call, and validates the output. If validation passes, or the call already went to the frontier, or escalation is off, it returns. Otherwise it sends the same prompt to the frontier client, records that call as an escalation, and returns the result. Escalation happens at most once, so cost can’t spiral. Step 6: The Agent This step has three prompts and a function that runs a ticket through them. Every model call goes through router.run. 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 # agent.pyimport jsonfrom tickets import INTENTS, TOOLS, TOOL_PARAMfrom validators import make_summary_validator, make_tool_validator, parse_json, validate_planPLAN_SYSTEM = """You are the planning step of a customer support agent.Decide what the customer mainly wants: shipping_status, refund_request or account_access.Rules:- Choose refund_request only when the customer clearly asks for money back or a refund.- If the ticket mentions several problems, choose the one the customer says matters most or asks about first.Tools: lookup_order (for shipping_status and refund_request), lookup_account (for account_access).Respond with JSON only: {"intent": "...", "tool": "...", "reason": "one short sentence"}"""TOOL_SYSTEM = """You are the tool-calling step of a customer support agent.Available tools:- lookup_order(order_id): order IDs look like A1001- lookup_account(email)Call the tool named in the plan, using values copied exactly from the ticket.Respond with JSON only: {"tool": "", "args": {"": ""}}"""SUMMARY_SYSTEM = """You are the reply-writing step of a customer support agent.Write a reply to the customer in 2 to 3 short sentences.Quote the exact values from the tool result (statuses, dates, amounts, next steps) word for word.Do not invent anything that is not in the tool result."""def run_ticket(ticket, router): """Run one ticket through plan, tool call and summary. Returns how each step scored.""" out = {"plan_ok": False, "tool_ok": False, "reply_ok": False, "escalations": 0} plan = router.run(PLAN_SYSTEM, f"Ticket: {ticket['text']}", validate_plan) out["escalations"] += plan.escalated plan_obj = parse_json(plan.text) if plan.ok else None if plan_obj is None: return out out["plan_ok"] = plan_obj["intent"] == ticket["intent"] and plan_obj["tool"] == ticket["tool"] # The tool step sees the plan's choice, so a wrong plan flows downstream. call = router.run(TOOL_SYSTEM, f"Ticket: {ticket['text']}\nPlan: use {plan_obj['tool']}", make_tool_validator(ticket["text"])) out["escalations"] += call.escalated call_obj = parse_json(call.text) if call.ok else None if call_obj is None: return out out["tool_ok"] = call_obj["tool"] == ticket["tool"] and call_obj["args"] == ticket["args"] # Run the real tool with whatever arguments the model produced. tool_result = TOOLS[call_obj["tool"]](call_obj["args"].get(TOOL_PARAM[call_obj["tool"]], "")) # The summary is validated against the facts the plan's intent says to quote. keys = INTENTS[plan_obj["intent"]][1] facts = [str(tool_result[k]) for k in keys if k in tool_result] summary = router.run(SUMMARY_SYSTEM, f"Ticket: {ticket['text']}\nTool result: {json.dumps(tool_result)}", make_summary_validator(facts)) out["escalations"] += summary.escalated # Final scoring is independent of the validator: it uses the dataset's gold facts. out["reply_ok"] = all(f.lower() in summary.text.lower() for f in ticket["required_facts"]) return out The planning prompt spells out the tie-break rules the tricky tickets depend on, and the tool prompt lists tools under “Available tools”, the phrase the classifier looks for. run_ticket plans, then records whether the plan matches the gold labels. The tool step receives the plan’s chosen tool, so a wrong plan really does flow downstream, which is the effect we want to measure. The model’s JSON then runs against the mock tool, as in a real agent. The summary is validated against the facts the plan’s intent says to quote, but the final score uses the dataset’s own facts, so a fluent reply after a wrong plan still fails. Step 7: The Evaluation Harness The last file runs every arm over every ticket and prints one table. 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 # evaluate.pyimport osimport sysfrom agent import run_ticketfrom clients import FrontierClient, LocalClientfrom ledger import Ledgerfrom router import FRONTIER_ONLY, LOCAL_ONLY, ROUTED_POLICY, Routerfrom tickets import TICKETS# arm name -> (routing policy, escalation on or off)ARMS = {"frontier_only": (FRONTIER_ONLY, False), "local_only": (LOCAL_ONLY, False), "routed": (ROUTED_POLICY, False), "routed_escalate": (ROUTED_POLICY, True)}def run_arm(name, tickets, clients): policy, escalate = ARMS[name] ledger = Ledger() router = Router(clients, ledger, policy, escalate) passed = escalations = 0 for ticket in tickets: try: outcome = run_ticket(ticket, router) passed += outcome["plan_ok"] and outcome["tool_ok"] and outcome["reply_ok"] escalations += outcome["escalations"] except Exception as error: # a crashed ticket counts as a failure, but say so print(f" ticket {ticket['id']} crashed: {error}") cost = ledger.total("cost") local_calls = sum(r["tier"] == "local" for r in ledger.records) return {"arm": name, "pass": passed / len(tickets), "cost": cost / len(tickets), "per_accepted": cost / passed if passed else float("inf"), "latency": ledger.total("latency") / len(tickets), "escalation": escalations / local_calls if local_calls else 0.0}def print_table(rows): print(f"{'arm':6}{'\$/ticket':>11}{'\$/accepted':>12}{'sec/ticket':>12}{'escal.':>8}") for r in rows: accepted = "n/a" if r["per_accepted"] == float("inf") else f"{r['per_accepted']:.5f}" print(f"{r['arm']:6.0%}{r['cost']:>11.5f}{accepted:>12}" f"{r['latency']:>12.1f}{r['escalation']:>8.0%}")if __name__ == "__main__": if not os.getenv("ANTHROPIC_API_KEY"): sys.exit("Set ANTHROPIC_API_KEY first, or every frontier call will crash and score 0%.") limit = int(sys.argv[1]) if len(sys.argv) > 1 else len(TICKETS) clients = {"local": LocalClient(), "frontier": FrontierClient()} rows = [] for arm in ARMS: print(f"Running {arm}...") rows.append(run_arm(arm, TICKETS[:limit], clients)) print() print_table(rows) ARMS maps each arm to its policy and whether escalation is on. run_arm builds a fresh ledger and router, runs each ticket, and wraps the call in try so one crashed ticket counts as a failure and prints its error. A ticket passes only if the plan, tool call, and reply are all right. The per_accepted value divides total cost by the number of passing tickets, and escalation is escalations divided by local calls, showing how often the cheap model wasn’t good enough. The script exits early if the API key is missing, because otherwise every frontier call would crash and frontier_only would show a 0% pass rate that looks real. Running It Start with a smoke test on two tickets, then run everything: python evaluate.py 2python evaluate.py The number after the script name limits how many tickets run, so the first command is a cheap check that both models respond. The second runs all 10 tickets through all four arms and prints one row per arm: pass rate, dollars per ticket, dollars per accepted ticket, seconds per ticket, and escalation rate. Conclusion You now have a router that classifies each agent step, sends planning to a frontier model and the mechanical work to a local one, escalates once when a cheap answer fails a check, and prints what that did to cost and quality. The habit worth keeping is measuring cost per accepted task instead of price per token. Plug in your own agent and models, run the harness, and let the table decide where each step goes. For related reading, my piece on choosing between tool calling and code execution covers how the action step is built, and the Hermes + Ollama setup goes deeper on the local side. No comments yet.

Original Source

Read the full article at Machinelearningmastery →

KhanList aggregates and links to publicly available news content. We do not host full articles from third-party sources. Always verify important information with original sources.