Query Routing

Send each question to the right index, tool or pipeline.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 9 · Lesson 6 of 7 · Intermediate

Query Routing

Send each question to the right index, tool or pipeline.

Real assistants draw on more than one source: an HR policy index, product manuals, an orders database, maybe the web. Some messages ("thanks!", "translate this into Hindi") need no retrieval at all. Searching every source for every question wastes time and mixes irrelevant results into the prompt. A router decides where each question should go.

A router sends each question to the HR policy index, the orders database via SQL, the product manuals index, or answers directly without retrieval.
Figure 1. A router picks the right destination for each question.

Option 1: An LLM router

Describe each destination and let the LLM pick one, returning a structured decision. Clear descriptions are the key to accuracy.

router.py
from typing import Literal
from pydantic import BaseModel
import anthropic

client = anthropic.Anthropic()

ROUTES = """- hr_policies: company HR, leave, travel, expense and IT policies
- orders_db: questions needing numbers from the orders database: sales, totals, counts, customers
- product_manuals: setting up, using or troubleshooting our products (X100, X200 routers)
- none: greetings, thanks, or tasks that need no company information (rewrite, translate)"""

class Route(BaseModel):
    destination: Literal["hr_policies", "orders_db", "product_manuals", "none"]
    reason: str

def route(question: str) -> Route:
    response = client.messages.parse(
        model="claude-opus-5-5",
        max_tokens=300,
        output_config={"effort": "low"},
        system=f"Choose where to send the user's message.\nDestinations:\n{ROUTES}",
        messages=[{"role": "user", "content": question}],
        output_format=Route,
    )
    return response.parsed_output

for q in ["How many leave days do I get?", "Total sales in September?",
          "My X200 light is blinking red", "thanks a lot!"]:
    r = route(q)
    print(f"{r.destination:16} <- {q}")
hr_policies      <- How many leave days do I get?
orders_db        <- Total sales in September?
product_manuals  <- My X200 light is blinking red
none             <- thanks a lot!

Option 2: A semantic router (no LLM call)

For high traffic, an LLM call per question adds cost and latency. A semantic router embeds a handful of example questions per route and sends each new question to the route with the most similar examples. It takes milliseconds.

import numpy as np
from rag_helpers import embed

EXAMPLES = {
    "hr_policies": ["How many vacation days do I have?", "What is the travel policy?",
                    "Can I claim my internet bill?", "What are the rules for working from home?"],
    "orders_db": ["What were total sales last month?", "How many orders were cancelled?",
                  "Who are our top customers?", "Average order value in Q3"],
    "product_manuals": ["How do I reset the router?", "The light is blinking orange",
                        "How to update firmware on X100", "Wi-Fi keeps disconnecting"],
    "none": ["thanks", "hello", "translate this to Hindi", "make this shorter"],
}
route_names = list(EXAMPLES)
example_vecs = {name: embed(qs, query=True) for name, qs in EXAMPLES.items()}

def semantic_route(question: str, min_score: float = 0.5) -> str | None:
    q = embed(question, query=True)[0]
    scores = {name: float((vecs @ q).max()) for name, vecs in example_vecs.items()}
    best = max(scores, key=scores.get)
    return best if scores[best] >= min_score else None      # None = unsure

def hybrid_route(question: str) -> str:
    return semantic_route(question) or route(question).destination   # LLM only when unsure

The hybrid version uses the cheap semantic router when it is confident and falls back to the LLM router otherwise.

Dispatching

# answer_from_index(index, question): any retrieve-and-answer function, for example
# answer_from() in the query decomposition lesson. hr_index and manuals_index are two
# separate retrievers built over the HR documents and the product manuals.
def handle(question: str) -> str:
    destination = hybrid_route(question)
    if destination == "hr_policies":
        return answer_from_index(hr_index, question)
    if destination == "product_manuals":
        return answer_from_index(manuals_index, question)
    if destination == "orders_db":
        return answer_with_sql(question)            # from the Text-to-SQL lesson
    return ask(question)                            # no retrieval needed

Beyond picking a source

Routers can choose more than an index:

  • Pipeline choice: simple lookup, step-back prompting or decomposition.
  • Model choice: a fast model for simple questions, a stronger one (or higher effort) for complex ones.
  • Multiple destinations: return a list when a question spans sources, then merge the results.

When the routing decision itself needs several steps, let an agent choose tools instead (see Agentic RAG).

Evaluate the router separately

Collect 50 to 100 labelled questions per route and measure routing accuracy on its own. A misrouted question cannot be rescued by good retrieval downstream.

Key takeaways

  • A router sends each question to the right index, database, tool or to no retrieval at all.
  • LLM routers are flexible; describe each destination clearly and use structured output.
  • Semantic routers use example embeddings and are fast and cheap; combine both for the best trade-off.
  • Measure routing accuracy on its own labelled set.