Sub topic 12
Routing Queries to Strategies, or Skipping Retrieval
This chapter assumes you have read the earlier chapters on conversational rewriting, multi-query expansion, decomposition, and the iterative loop. You should be comfortable calling an LLM with a text prompt and reading Python. Everything so far has applied one technique to every question. Here you will learn to decide per question which technique to use, including none at all.
Why one pipeline for every question is wasteful
Each technique you have learned costs something. Multi-query expansion adds an LLM call and several searches. Decomposition adds an LLM call plus one search per sub-question. An iterative loop can add up to max_steps more LLM calls. If you apply all of this to "thanks, that helps", you pay latency and money for nothing. Worse, you may inject irrelevant passages into the answer prompt.
Routing is a small decision step placed before retrieval. It reads the question, and optionally the conversation, and picks one path. The router itself should be much cheaper than the paths it chooses between. If it is not, the routing step defeats its own purpose.
What a router can decide
A router chooses from a short, fixed list of routes. Each route maps to a strategy you already know.
| Route | Use when | Strategy |
|---|---|---|
| `none` | Greetings, thanks, chit-chat, or questions the model can answer from general knowledge | Skip retrieval and call the generator directly |
| `single` | A clear, self-contained, factual question | One search with the (possibly condensed) question |
| `multi_query` | Short or vague wording, or a likely vocabulary mismatch | Multi-query expansion with reciprocal rank fusion |
| `decompose` | The question has several parts or compares things | Decomposition into sub-questions |
| `iterative` | The second search depends on what the first one finds | The iterative loop with a step limit |
Keep the list short. Each extra route is another label the router can confuse and another path you must test. Three to five routes is a practical range.
Routing can also select a data source, such as a product-docs index versus a policy index, or a keyword index versus a vector index. The mechanics are the same: classify, then dispatch. This chapter focuses on strategy routing.
When to skip retrieval
Skipping retrieval is the most valuable route because it removes the entire retrieval cost. Good candidates for none are:
- Conversational filler: greetings, thanks, "ok", "can you repeat that".
- Requests about the conversation itself: "summarize what we just discussed". The needed text is already in the prompt.
- Transformations of supplied text: "translate this paragraph", "make this shorter".
- General knowledge that does not depend on your corpus, such as "what does HTTP stand for".
Be careful with the last category. Your users may ask general-sounding questions whose correct answer lives in your documents, such as "what is our refund window?". A model that answers confidently from memory will be wrong and will not tell you. As a rule, skip retrieval only when a wrong answer is cheap or when the question is clearly not about your corpus. When unsure, retrieve.
Signals a router can use
A router can work from three kinds of signal, from cheapest to most expensive.
- Rules. Regular expressions or keyword checks catch the obvious cases, such as a message that is only "thanks!". They cost almost nothing and are predictable. They break on anything subtle.
- A small classifier. A trained model or an embedding-similarity check against example questions per route. It is fast and consistent, but it needs labeled examples.
- An LLM call. You describe the routes in a prompt and ask for one label. It needs no training data and handles unusual phrasing, but it adds latency and can return unexpected text.
Many systems layer these: rules first for the trivial cases, then an LLM for the rest. The rules save an LLM call on the most common easy inputs.
Implementing an LLM router
Three details matter in an LLM router. Constrain the output to a fixed set of labels. Validate the reply against that set. Fall back to a safe default when validation fails. The safe default is usually single, because it always works and is cheap.
import re
from typing import Callable
ROUTES = ("none", "single", "multi_query", "decompose", "iterative")
SMALLTALK = re.compile(
r"^\s*(hi|hello|hey|thanks|thank you|ok|okay|bye)\b[\s!.,]*$",
re.IGNORECASE,
)
ROUTE_PROMPT = (
"Choose how to retrieve documents for the question below. "
"Reply with exactly one word from this list:\n"
"none: no documents needed (small talk, or not about our documents)\n"
"single: a clear, self-contained factual question\n"
"multi_query: vague or very short wording\n"
"decompose: several parts, or a comparison\n"
"iterative: later searches depend on earlier findings\n\n"
"Question: {question}"
)
def route_query(
question: str,
llm: Callable[[str], str],
default: str = "single",
) -> str:
if SMALLTALK.match(question):
return "none"
reply = llm(ROUTE_PROMPT.format(question=question)).strip().lower()
label = reply.split()[0].strip(".,:;\"'") if reply else ""
return label if label in ROUTES else default
def answer(
question: str,
llm: Callable[[str], str],
strategies: dict[str, Callable[[str], list[str]]],
generate: Callable[[str, list[str]], str],
) -> tuple[str, str]:
route = route_query(question, llm)
if route == "none":
passages: list[str] = []
else:
passages = strategies.get(route, strategies["single"])(question)
return generate(question, passages), route
def fake_llm(prompt: str) -> str:
question = prompt.rsplit("Question:", 1)[1].lower()
if "compare" in question:
return "decompose."
return "banana" # an invalid label, to show the fallback
strategies = {
"single": lambda q: [f"single-search result for: {q}"],
"decompose": lambda q: [f"sub-question results for: {q}"],
}
def generate(question: str, passages: list[str]) -> str:
return f"{len(passages)} passage(s) used"
for q in ["thanks!", "Compare plan A and plan B", "What is the refund window?"]:
print(q, "->", answer(q, fake_llm, strategies, generate))Running this prints none for the first question, decompose for the second, and single for the third. The third shows the fallback: the fake model returned an invalid label, so the router used the default. In a real system you would pass in multi_query_search, iterative_retrieve, and your own single-search function as the strategies.
If a route has no registered strategy, the code falls back to single instead of raising a KeyError. Silent fallbacks hide bugs, so log every fallback and review the counts.
Where routing sits in the pipeline
Routing should see the standalone question, not the raw follow-up. A message like "what about its pricing?" looks like a short vague query and might be routed to multi_query. After condensing, it may be a clear single-fact question. So the order is: condense, route, retrieve with the chosen strategy, generate.
The exception is the none decision for conversational requests. "Summarize our conversation" needs the history, not a rewritten search query. If your router handles these, give it access to the history, or detect them with a rule before the condensing step.
Failure modes
Wrong skip. The router marks a corpus-specific question as none. The model then answers from memory with no sources. This is the most damaging error because it looks like a normal answer. Bias the prompt toward retrieving, and test with questions whose answers exist only in your documents.
Over-routing to expensive paths. An LLM router often favors elaborate-sounding choices. If 60% of traffic lands on iterative, your latency and cost will rise with no quality gain. Track the route distribution.
Unstable labels. The same question may get different routes on different calls. Use a low temperature if your API supports it, and keep the label set small.
Format drift. Models may reply "Route: single" or add an explanation. The validation step in route_query handles some of this, but you should still count how often the fallback triggers. A rising fallback rate means the prompt or model changed.
Router cost exceeding savings. If most questions need the same strategy, routing adds a call to every request and saves little. Use a plain default and add routing only when traffic has distinct types.
Checking that routing helps
Treat the router as a classifier and as a system component. For the classifier, build a small labeled set of real questions with the route you would want for each, then measure accuracy and the confusion between routes. Pay most attention to false none decisions. For the whole system, compare answer quality, latency, and cost against the single-strategy baseline on the same questions. The next chapter covers how to build that comparison.
Summary of decision criteria
- Skip retrieval for small talk and text-transformation requests. Retrieve whenever the answer might live in your corpus.
- Route after condensing, so the router sees a standalone question.
- Prefer rules for obvious cases and an LLM for the ambiguous remainder.
- Keep the route list short, validate labels, and log fallbacks and route counts.
Exercise
A user asks, "What is the maximum file upload size?" Your router, using a general-knowledge rule, marks it none, and the model answers "10 MB" from memory. Your documentation says 25 MB. Name the failure mode and give two changes that reduce the chance of it happening.
Show answer
This is a wrong skip: a corpus-specific question was routed to none, so the answer came from the model's memory. Two changes: (1) rewrite the router prompt to bias toward retrieval, so none is allowed only for small talk, requests about the conversation, or text transformations; (2) add corpus-specific questions like this one to the routing test set and track false none rate. Making single the default when the router is unsure also helps.
Exercise
In the code above, the fake model returns "banana" for "What is the refund window?". Which route is used, and why? What should you monitor in production because of this behavior?
Show answer
The single route is used. route_query checks the label against ROUTES, finds that "banana" is not in it, and returns the default single. In production, monitor how often the fallback triggers. A rising rate means the router prompt or model is producing invalid output, which the fallback would otherwise hide.