Sat 5 Dec 2026 International edition

Artificial Intelligence and Future Tech

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

The economic reality of deploying autonomous artificial intelligence agents at enterprise scale has forced a fundamental shift in software architecture. While frontier large language models such as OpenAI’s GPT-4o or Anthropic’s Claude 3.5 Sonnet offer exceptional reasoning capabilities, routing every granular task within a multi-step agentic workflow through these top-tier systems quickly becomes economically unsustainable. Conversely, relying entirely on smaller, locally hosted open-source models often compromises the reliability and logical coherence required for complex workflows. To resolve this tension, software engineers and machine learning practitioners are increasingly adopting dynamic model routing, cascading, and fallback frameworks. This architectural approach intelligently distributes execution loads across heterogeneous model tiers, optimizing both financial expenditure and operational throughput.

An exhaustive blueprint for implementing this architecture in Python demonstrates how to direct each distinct step of an AI agent to the appropriate model tier. By establishing a unified client interface, constructing a comprehensive cost ledger, utilizing deterministic validators, and orchestrating a multi-armed evaluation harness, development teams can systematically measure and minimize the cost per accepted task rather than merely optimizing for the superficial cost per token.

Deconstructing Model Routing: Routers, Cascades, and Fallbacks

In modern agentic systems, the terminology governing multi-model orchestration is frequently conflated. Understanding the distinct mechanisms of routing, cascading, and fallback strategies is essential for designing resilient software. Model routing operates as a pre-call decision engine. Before an inference request is dispatched, a classification layer analyzes the prompt context or step type and assigns the payload to a designated model tier. For example, high-level reasoning tasks are directed to frontier cloud APIs, while deterministic parsing or data formatting tasks are routed to local inference engines.

In contrast, a cascade operates as a post-call evaluation strategy. The system attempts execution using a low-cost, resource-efficient model first. The output is immediately subjected to a programmatic validation check. If the output fails the validation criteria, the execution cascades upward to a larger, more capable model.

A fallback mechanism serves as an emergency safety net. If a primary model encounters a runtime exception, timeout, or HTTP error—such as an interruption in cloud connectivity—a secondary model seamlessly takes over to complete the request.

Advanced orchestration frameworks combine these strategies. A structured routing table establishes a default model for each step type, while an automated validator triggers a single, controlled escalation when a cost-effective model’s output fails to meet quality standards. This hybrid design mitigates the individual weaknesses of both purely local and purely cloud-dependent architectures.

Experimental Design: Evaluating a Customer Support Triage Agent

To quantify the financial and operational trade-offs of model routing, developers can construct a simulated customer support triage agent designed to process a standardized dataset of short support tickets. Each ticket traverses a standardized, three-stage lifecycle: planning, tool calling, and summarization.

During the planning phase, the agent evaluates the customer’s raw text input to determine their underlying intent—such as checking shipping status, requesting a refund, or resolving an account access issue—and selects the appropriate backend tool. During the tool-calling phase, the agent generates a structured JSON payload containing the required arguments, which the host environment executes against mock database schemas. Finally, during the summarization phase, the agent synthesizes a concise, customer-facing response that accurately reflects the data retrieved by the tool.

To benchmark different architectural strategies, researchers evaluate four distinct deployment configurations, known as experimental arms:

  1. Frontier Only: Every step (planning, tool execution, and summarization) is processed by a high-tier frontier model. This configuration maximizes accuracy but incurs maximum financial cost.
  2. Local Only: Every step is processed entirely by a small local model running on local hardware via inference runtimes such as Ollama. While marginal financial costs are near zero, overall task success rates typically decline due to limitations in complex reasoning.
  3. Routed: A static routing policy assigns high-level planning to the frontier model while delegating mechanical tool-calling and summarization tasks to the local model, without automated escalation.
  4. Routed with Escalation: This configuration utilizes the same static routing policy as the routed arm but incorporates an automated validator that triggers a single escalation to the frontier model if the local model’s output fails programmatic checks.

Scoring across these configurations is entirely deterministic, eliminating the variance associated with LLM-as-a-judge evaluations. A ticket successfully passes only if the planner correctly identifies the intent and tool, the tool-calling step extracts accurate arguments directly from the source text, and the final summary explicitly includes all required factual data points returned by the database query. Performance metrics include overall pass rates, latency per ticket, cost per ticket, escalation rates, and the primary economic metric: cost per accepted task.

Environment Setup and Dependencies

Implementing this routing framework requires Python 3.10 or a later version, local hardware capable of executing compact open-source models, and valid API credentials for cloud-based frontier models. The initial setup commands configure the local runtime and project directory:

ollama pull llama3.2:3b
mkdir router-agents && cd router-agents
pip install requests anthropic
export ANTHROPIC_API_KEY="your-key-here"

The llama3.2:3b model requires approximately 2 GB of storage and roughly 4 GB of available system RAM when served via Ollama. The requests library facilitates HTTP communication with the local Ollama instance, while the official Anthropic Python SDK handles authenticated requests to frontier models. Storing the API key as an environment variable ensures sensitive credentials remain decoupled from the source code.

Unified Client Interfaces and Data Structures

A robust model router requires strict interface abstraction. Whether a prompt is dispatched to a local weights file or a proprietary cloud API, the calling code must receive a standardized response structure. The following implementation of clients.py defines a common data class, LLMResult, along with two distinct client wrappers:

# 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
        self.model = model or os.getenv("FRONTIER_MODEL", "claude-3-5-sonnet-20241022")
        self.client = anthropic.Anthropic()

    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
        )

The LLMResult data class captures output text, token consumption metrics, execution latency, model identifier, and tier classification. The LocalClient interacts with Ollama’s native chat endpoint, enforcing deterministic outputs via zero temperature settings and guaranteeing structural compliance using Ollama’s native JSON mode formatting. The FrontierClient encapsulates the Anthropic SDK, abstracting cloud API interactions behind the identical .complete() method signature.

Economics and the Cost Ledger

Because model routing is fundamentally an economic optimization problem, precise financial tracking is mandatory. The cost ledger module calculates cumulative expenditures based on published token pricing models.

# ledger.py
PRICES = 
    "claude-3-5-sonnet-20241022": (3.00, 15.00),
    "claude-3-5-haiku-20241022": (0.80, 4.00)


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]
    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)

While local model inference carries a marginal token cost of zero, enterprise architects must account for underlying infrastructure depreciation and electricity expenses in production deployments. Nevertheless, comparing frontier API token expenditures against local execution highlights the profound cost disparities that justify routing architectures.

Deterministic Validation and Guardrails

To automate escalation without relying on expensive secondary LLM judge calls, the routing architecture employs programmatic validation functions. These validators inspect model outputs for structural integrity, schema compliance, and factual grounding.

# validators.py
import json
import re
from tickets import INTENTS, TOOLS, TOOL_PARAM

FENCE = "`" * 3

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:
            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

The parsing utility strips markdown code fences and extracts the primary JSON object, addressing the tendency of smaller language models to wrap structured data in explanatory prose. The tool validator enforces strict entity extraction rules, ensuring parameters such as order identifiers are copied directly from the input text rather than hallucinated by the model.

Routing Policies and Execution Orchestration

The core routing engine evaluates incoming execution steps against predefined policy dictionaries, dispatching prompts to the appropriate client wrapper and managing conditional escalations.

# router.py
from dataclasses import dataclass

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):
    text = f"systemnuser".lower()
    if "available tools" in text or '"args"' in text:
        return "tool_call"
    if "reply to the customer" in text:
        return "summarize"
    return "plan"

@dataclass
class StepOutcome:
    text: str
    ok: bool
    escalated: bool

class Router:
    def __init__(self, clients, ledger, policy, escalate):
        self.clients = clients
        self.ledger = ledger
        self.policy = policy
        self.escalate = 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)

        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 Router.run method classifies the execution step, retrieves the target model tier from the active routing policy, invokes the corresponding client, logs token usage and latency to the ledger, and validates the output. If validation fails and escalation is enabled, the prompt is immediately re-sent to the frontier model, with the secondary call recorded as a controlled escalation.

Implications and Enterprise Adoption

Empirical evaluations of routed agent architectures consistently demonstrate substantial efficiency gains. While running an agent entirely on frontier models yields high accuracy at significant expense, and running entirely on local models reduces costs to near-zero at the expense of high failure rates, dynamic model routing achieves an optimal equilibrium. By leveraging frontier intelligence for high-level reasoning and cost-effective local models for mechanical execution, organizations can achieve near-frontier accuracy while reducing total operating costs by 50% to 70%.

Ultimately, implementing programmatic model routing represents a maturing of engineering practices in generative artificial intelligence. By treating model selection as an economic and architectural variable rather than a static configuration, development teams can build scalable, resilient, and economically viable AI agents ready for production deployment.

Related stories

More from Artificial Intelligence and Future Tech

View all →

Most viewed across the site

GearX News
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.