Pattern: routing

In one sentence

Classify each input first, then send it to the prompt, model or pipeline built for that class: each path stays simple, and easy queries stop paying for the expensive model.

Analogy: A hospital triage nurse: a two-minute assessment decides whether you go to the ER, a GP or the pharmacy, so specialists only see the cases that need them.

One cheap decision up front; each branch is tuned and evaluated alone, and low confidence takes the fallback.

How it works

  • Each handler is tuned and evaluated in isolation: fixing refunds no longer breaks tech support.
  • The classifier is an LLM call (a few hundred ms), a local trained model (~1–20 ms), or rules.
  • Always add a fallback route: low-confidence or other inputs go to a general handler or a human.
  • The signature failure is the misroute: a good handler answering the wrong question.
  • Evaluate the router alone with a confusion matrix, and log the chosen route in every trace.

Check yourself

Answer to mark it learned; your answers aren't scored.

Your support router keeps flipping failed-payment tickets between billing and refund. The router's confusion matrix shows most misroutes sit between those two classes. Best fix?

Go deeper

Full explanation

Routing puts a classifier in front of several specialized handlers. Step one decides what kind of input this is; step two runs the handler built for that kind: its own prompt, tools, model or whole pipeline.

Two reasons to do it:

  • Separation of concerns. A refund prompt and a tech-support prompt are tuned and evaluated in isolation. One prompt covering every case drifts: fixing refunds breaks tech support.
  • Cost and latency. Easy, common queries go to a small, fast model; only hard ones reach the frontier model (see Model routing & cascades).

The classifier can be an LLM call with Structured outputs & JSON mode (flexible, adds a few hundred ms), a small fine-tuned or embedding classifier (milliseconds, needs labelled data), or plain rules for the obvious cases. Always include a fallback route: other / unsure goes to a general handler or a human, and a confidence threshold decides when to take it.

The signature failure is the misroute: a perfectly good handler answering the wrong question. Evaluate the router on its own with a confusion matrix (Precision, recall, F1, ROC-AUC), and log the chosen route in every trace so you can tell a routing bug from a handler bug.

Code LLM router with a confidence fallback
pythonLLM router with a confidence fallback
from typing import Literal
from openai import OpenAI
from pydantic import BaseModel

client = OpenAI()
ROUTER_MODEL = "gpt-4.1-nano"  # a small model is usually enough to classify

class Route(BaseModel):
    category: Literal["refund", "technical", "faq", "other"]  # exclusive classes + catch-all
    confidence: float  # self-reported: calibrate the threshold on labelled data

HANDLERS = {
    "refund": refund_pipeline,       # strict policy prompt + billing tools
    "technical": tech_rag_pipeline,  # docs RAG + larger model
    "faq": faq_small_model,          # cheap model, curated answers
    "other": general_assistant,      # fallback; may hand off to a human
}

def handle(ticket: str) -> str:
    r = client.chat.completions.parse(
        model=ROUTER_MODEL,
        messages=[{"role": "system", "content": ROUTER_PROMPT},  # class definitions + examples
                  {"role": "user", "content": ticket}],
        response_format=Route,
    ).choices[0].message.parsed
    route = r.category if r.confidence >= 0.7 else "other"  # unsure -> fallback
    log_route(ticket, r.category, r.confidence)  # needed later to measure misroutes
    return HANDLERS[route](ticket)
Real example

A fintech's support assistant answers ~20k tickets a day with one large-model prompt. Analysis shows ~60% are FAQ-style ("where's my card?"). They add a router: a small model classifies into faq, refund, fraud, technical or other. FAQ goes to a small model with curated answers; fraud skips the LLM answer entirely and pages a human queue. Cost per ticket drops ~3×. A weekly labelled sample of 300 tickets shows 4% misroutes, mostly refund↔technical on failed payments, fixed by merging both into a payments class with its own prompt.

Trade-offs +3 · −3

+ You gain

  • Each handler is small and specialized, tuned and evaluated without breaking the others.
  • Big cost and latency savings when most traffic is easy enough for a small model.
  • Natural place for policy: risky classes (fraud, legal) can skip the LLM and go to humans.

− You pay

  • Misroutes are silent: a good handler confidently answers the wrong question.
  • Adds a step: one more call or model to host, monitor and keep in sync with the classes.
  • Class boundaries drift as the product and traffic change, so the router needs re-labelling.

Use it when

Inputs fall into distinct categories that each deserve their own prompt, tools or model and can be classified accurately, or a large share of traffic is easy enough for a cheaper model.

Avoid it when

Categories overlap, one prompt already handles everything at acceptable cost, or an input needs several handlers at once (use parallelization or orchestrator–workers).

Numbers to know 4
  • The smallest and largest tiers of one vendor often differ 5–20× per token: GPT-4.1 nano launched at $0.10 vs GPT-4.1 at $2.00 per 1M input tokens (Apr 2025 list prices).
  • RouteLLM (2024): learned routers cut cost by over 2× on some benchmarks without losing response quality.
  • FrugalGPT (2023): an LLM cascade matched GPT-4's performance with up to 98% lower cost on its benchmarks.
  • Rule of thumb for router overhead: a small-LLM call adds a few hundred ms; a local embedding or fine-tuned classifier, ~1–20 ms.
Common pitfalls 4
  • Overlapping classes (billing vs refund): the router flips between them. Make classes mutually exclusive and define each with examples.
  • No fallback: out-of-scope and adversarial inputs get forced into some class and answered confidently.
  • Trusting the LLM's self-reported confidence as-is; calibrate the threshold on labelled data or use logprobs.
  • Measuring only end-to-end quality: you can't tell a misroute from a bad handler. Eval the router alone and log the route.
Interview questions 2

Answer out loud first, then reveal.

How would you build and evaluate the router for a support assistant?Show answer

I start from real traffic: label a few hundred tickets into mutually exclusive classes plus other. I baseline an LLM classifier with structured output, then check whether a small fine-tuned or embedding classifier matches it at a fraction of the latency. I evaluate the router alone with a confusion matrix, because errors are asymmetric: a fraud report routed to FAQ is far worse than an FAQ routed to a human. I set the fallback threshold from that matrix and keep sampling production routes to catch drift.

When is routing the wrong pattern?Show answer

When the categories aren't really distinct, or one good prompt already handles every class at acceptable cost: then the router is just an extra call and an extra failure point. It's also wrong when one input needs several handlers at once; that's parallelization or orchestrator–workers. And if the goal is only cost, I first try prompt caching or a cheaper default model with a quality check, because those save money without introducing misroutes.