Velamuvi AIAcademy

Lesson 8 of 9 · Patterns

Routing

The routing pattern for AI agents: classify each request and send it to a specialist. Compare rule, embedding and LLM routers and measure routing accuracy.

  • 5 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Explain the routing pattern and why specialists beat one do-everything agent
  • Build a simple router with a safe fallback
  • Compare rule-based, embedding-based and LLM-based routers
  • Measure and improve routing accuracy

One door, many rooms

A single agent with every tool and every instruction gets confused and expensive. Routing puts a cheap decision at the front door, then hands the request to a specialist that is good at one kind of task.

Each specialist can differ in:

  • Prompt: billing rules for billing, troubleshooting steps for technical support.
  • Tools: refund tools only where refunds belong.
  • Model: a small fast model for simple FAQs, a stronger one for complex cases.
  • Policy: stricter approvals where money or data is involved.

A router with a safe fallback

Try it yourselfPython
import re

ROUTES = {
    "billing":   ["invoice", "refund", "charge", "charged", "payment", "price"],
    "technical": ["error", "crash", "crashes", "login", "password", "bug", "slow"],
    "sales":     ["upgrade", "plan", "demo", "quote", "enterprise"],
}

def route(message):
    """Pick a specialist by keyword score; send unclear messages to a general handler."""
    words = set(re.findall(r"[a-z]+", message.lower()))
    scores = {name: len(words & set(keys)) for name, keys in ROUTES.items()}
    best = max(scores, key=scores.get)
    ranked = sorted(scores.values(), reverse=True)
    if ranked[0] == 0 or ranked[0] == ranked[1]:
        return "general", scores                 # no signal, or a tie: don't guess
    return best, scores

HANDLERS = {
    "billing": "Billing specialist (has refund tools, billing prompt)",
    "technical": "Tech support specialist (has log search, status page tools)",
    "sales": "Sales assistant (has pricing and booking tools)",
    "general": "General assistant (asks a clarifying question)",
}

for message in ["I was charged twice for my invoice",
                "The app shows an error at login",
                "Can we get a demo of the enterprise plan?",
                "Hello, quick question",
                "Payment page crashes"]:
    name, scores = route(message)
    print(f"{message!r}\n   -> {HANDLERS[name]}   {scores}")

Clear messages go straight to a specialist. “Hello, quick question” matched nothing, and “Payment page crashes” matched billing and technical equally, so both went to the general handler, which asks a clarifying question instead of guessing.

Three kinds of router

RouterHow it decidesStrengthsWeaknesses
Rules (keywords, patterns)Matches words or IDsInstant, free, predictableMisses synonyms and phrasing
EmbeddingsSimilarity to example messages for each routeHandles paraphrases; cheapNeeds good examples per route
LLMA small model picks a route from descriptionsUnderstands nuance and contextSlower, costs a call, can be wrong

Combining them is common: rules for the obvious cases (“refund” plus an order number), and a model for the rest, with a confidence threshold that sends unclear cases to the fallback.

Common mistakes

Practice exercise

Make a router safe: when the signal is weak or two routes tie, hand over to a general handler instead of guessing.

Your solutionPython
def route(scores, min_score=2):
    # scores: how strongly a message matches each specialist.
    # Return the best specialist, but return "general" if the best score is below
    # min_score, or if two specialists share the best score.
    return max(scores, key=scores.get)

print(route({"billing": 3, "technical": 1}))
print(route({"billing": 1, "technical": 0}))
print(route({"billing": 2, "technical": 2}))
Knowledge check

A message matches the billing and technical routes equally. What should a well-designed router do?

Summary

  • Routing classifies requests and sends them to specialists with focused prompts, tools, models and policies.
  • Routers can use rules, embeddings or an LLM, often combined.
  • Always include a fallback for weak or tied signals.
  • Measure routing accuracy and let specialists hand back misrouted requests.

Next: choosing between workflows and agents.

Finished reading? Tick it off to track your progress.