Sub topic 12
Routing queries to strategies, or skipping retrieval
This chapter assumes you have read the earlier chapters on multi-query expansion, decomposition and the iterative retrieval loop. You should be comfortable reading Python and calling an LLM with a text prompt.
Why route at all
Every technique so far adds model calls and latency. Applying all of them to every question wastes money and can make easy questions worse. A router is a small decision step that looks at the question and picks one path:
- No retrieval. Greetings, thanks, and questions the model can answer from general knowledge ("What is a list comprehension?") need no documents.
- Single-shot search. A specific, self-contained question with distinctive terms usually works with plain retrieval.
- Multi-query search. A vague or short question benefits from several phrasings merged with reciprocal rank fusion.
- Decomposition or an iterative loop. A question with several parts, or one whose second search depends on the first answer, needs multiple steps.
A router built from a model call
The simplest router asks the model for one label. Constrain the output to a fixed set and fall back to the cheap, safe path when the reply is not a valid label.
from typing import Callable
ROUTES = {"none", "single", "multi_query", "decompose"}
def route_query(question: str, llm: Callable[[str], str]) -> str:
prompt = (
"Classify the question for a document search system. Reply with "
"exactly one word:\n"
"none - greeting or general knowledge, no documents needed\n"
"single - one specific, self-contained question\n"
"multi_query - vague or very short question\n"
"decompose - several parts, or needs one answer to find the next\n\n"
f"{question}"
)
reply = llm(prompt).strip().lower()
return reply if reply in ROUTES else "single"
def answer_with_routing(
question: str,
llm: Callable[[str], str],
strategies: dict[str, Callable[[str], list[str]]],
) -> tuple[str, list[str]]:
route = route_query(question, llm)
if route == "none":
return route, []
strategy = strategies.get(route, strategies["single"])
return route, strategy(question)
def fake_llm(prompt: str) -> str:
return "none" if prompt.rstrip().endswith("hi there") else "single"
strategies = {"single": lambda q: [f"passage about {q}"]}
print(answer_with_routing("hi there", fake_llm, strategies))
print(answer_with_routing("How do I rotate an API key?", fake_llm, strategies))In a real system, strategies maps each label to a function from earlier chapters, such as multi_query_search or iterative_retrieve, wrapped so it takes only the question.
Cheaper routers
A model call on every query adds latency. You have cheaper options:
- Rules first. A regular expression for greetings, or a length check, handles obvious cases for free.
- A small classifier. Train a lightweight model on labeled past queries once you have enough traffic.
- A small, fast LLM. Routing needs less capability than answering, so use the cheapest model that labels accurately.
Common errors
- Skipping retrieval too eagerly. If the router sends a question about your product to "none", the model answers from memory and may invent details. Route to "none" only for clearly generic questions, and when unsure, retrieve.
- No fallback. Models sometimes reply with extra words. Without a default path, a malformed label crashes the pipeline or silently skips retrieval.
- Too many routes. Each added label makes classification less reliable. Start with two or three.
- Unmeasured routing. Log the chosen route with each query so you can find misrouted questions later. The evaluation chapter covers how to measure this.
Exercise
Your router sends "What is our refund window for annual plans?" to the "none" route, and the model answers "30 days" with no sources. What went wrong, and what two changes would reduce the risk?
Show answer
The question depends on company-specific documents, so it needed retrieval. The router treated it as general knowledge. Two fixes: tighten the "none" label description so it covers only greetings and generic knowledge, and make the fallback and uncertain cases retrieve (for example, default to "single"). Logging routes and reviewing "none" decisions would also help catch such cases.