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.

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

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.

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.

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.

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.

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.

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.

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.

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.

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:

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.

Leave a Reply

Machine Learning Mastery is part of Guiding Tech Media, a leading digital media publisher focused on helping people figure out technology. Visit our corporate website to learn more about our mission and team.