Sub topic 10
Multi-step retrieval: using earlier results to shape later queries
This chapter assumes you can read Python and have built a basic RAG pipeline (index, retrieve, generate). It also assumes you know what a top-k search returns and have read the earlier chapters on decomposition and reciprocal rank fusion. Here we cover the case where a later search cannot be written until an earlier search has returned.
The problem: the second query depends on the first answer
Take this question: "Where was the founder of the company that makes the Orion X1 laptop born?"
No single passage is likely to contain the whole answer. The facts are spread over three documents:
- The Orion X1 is made by Kestrel Systems.
- Kestrel Systems was founded by Mara Voss.
- Mara Voss was born in Tallinn.
You can't write the query "Mara Voss birthplace" at the start, because you don't yet know the founder's name. Each search needs the result of the one before it. This is a bridge question (also called a multi-hop question). The answer is reached by hopping across documents.
Decomposition splits a question into sub-questions. That split is enough when the sub-questions are independent. Multi-step retrieval is what you add when they are not. Earlier results shape later queries.
Parallel versus sequential retrieval
Two patterns cover most systems.
| Property | Parallel (multi-query, independent sub-questions) | Sequential (multi-step) |
|---|---|---|
| Query dependence | Every query can be written up front | A query needs earlier evidence |
| Latency | One round of searches, run concurrently | One round per hop, run in series |
| Merging | Reciprocal rank fusion over lists | Evidence accumulates across steps |
| Typical question | "Compare plan A and plan B on price and limits" | "Who founded the maker of X, and where were they born?" |
| Main risk | Redundant or noisy results | An early mistake carries into later steps |
Use the parallel pattern when you can. It is faster and has fewer failure modes. Switch to sequential retrieval only when a sub-question contains something you can only learn by searching. The two also combine. Each step can issue several query variants, then fuse their ranked lists before the next step.
How the loop works
The core cycle has four parts. Retrieve for the current sub-question. Add the new evidence to what you already have. Use that evidence to write the next query. Repeat until the sub-questions run out.
The planner is the model call that writes each query. Its prompt must contain three things: the original question, the sub-question for this hop, and the evidence so far. Without the evidence, the model cannot know that "the company" means Kestrel Systems.
A runnable example
The code below is self-contained. It uses a toy keyword search and a scripted stand-in for the model, so you can run it without an API key. In a real system, replace search with your vector or BM25 search and llm with a real model call.
import re
from typing import Callable
CORPUS = [
"The Orion X1 laptop is manufactured by Kestrel Systems.",
"Kestrel Systems was founded in 2009 by Mara Voss.",
"Mara Voss was born in Tallinn.",
"The Orion X1 has a 14-inch display.",
]
def tokens(text: str) -> set[str]:
return set(re.findall(r"[a-z0-9]+", text.lower()))
def search(query: str, top_k: int) -> list[str]:
q = tokens(query)
scored = [(len(q & tokens(doc)), doc) for doc in CORPUS]
scored = [item for item in scored if item[0] > 0]
scored.sort(key=lambda item: item[0], reverse=True)
return [doc for _, doc in scored[:top_k]]
def multi_step_retrieve(
question: str,
sub_questions: list[str],
llm: Callable[[str], str],
search: Callable[[str, int], list[str]],
top_k: int = 1,
) -> list[str]:
evidence: list[str] = []
for sub in sub_questions:
prompt = (
f"Original question: {question}\n"
f"Current sub-question: {sub}\n\n"
"Evidence found so far:\n"
+ ("\n".join(evidence) if evidence else "(none)")
+ "\n\nWrite one short search query for the current sub-question. "
"Use names from the evidence instead of pronouns or descriptions. "
"Return only the query."
)
query = llm(prompt).strip()
for passage in search(query, top_k):
if passage not in evidence:
evidence.append(passage)
return evidence
replies = iter(
["Orion X1 manufactured", "Kestrel Systems founded", "Mara Voss born"]
)
fake_llm = lambda prompt: next(replies)
result = multi_step_retrieve(
"Where was the founder of the company that makes the Orion X1 born?",
[
"Who makes the Orion X1?",
"Who founded that company?",
"Where was that person born?",
],
fake_llm,
search,
)
for passage in result:
print(passage)Running it prints the three bridging passages in order. The "Orion X1 has a 14-inch display" passage is never retrieved, because each query was narrow.
In this run the scripted replies stand in for what a real model would write after reading the evidence. The prompt carries the dependency. By hop 3 the model sees "Mara Voss" in the evidence and can use the name directly.
Where the sub-questions come from
The example hard-codes the sub-questions. Real systems get them in one of two ways.
- Plan first. The model decomposes the question once, up front, as in the decomposition chapter. This is cheap and predictable. The plan can be wrong, because the model is guessing the structure before seeing any evidence.
- Plan as you go. The model proposes the next sub-question after each hop. This adapts to what the corpus actually contains. It costs one extra model call per hop and needs a stopping rule, which the next chapter builds.
A plan-first loop has a fixed number of hops, so it always ends. A plan-as-you-go loop does not, so it needs a step limit.
What to carry between steps
Passing every retrieved passage into every later prompt is the simplest design. It breaks down as hops grow. The prompt gets long, cost rises, and irrelevant passages distract the model. You have three options:
- Raw passages. Keep full text. This is the most faithful option and the most expensive.
- Extracted facts. After each hop, ask the model for the one fact the sub-question needed, such as "Kestrel Systems was founded by Mara Voss." Carry the facts forward and keep the passages for the final answer. Prompts stay short, but a wrong extraction hides the error from later steps.
- Rolling summary. Keep a short summary updated after each hop. This is the cheapest option and loses the most detail.
Whichever you choose, keep the source passages for the final generation step so you can cite them.
Edge cases and failure modes
- Empty or weak results. If a hop returns nothing relevant, the next prompt has no name to use, and the model may invent one. Check for an empty result or a low score, and stop or fall back to the original question as the query instead of continuing blindly.
- Error propagation. If hop 1 retrieves the wrong company, hops 2 and 3 faithfully follow the wrong trail. Using
top_kabove 1 per hop, or fusing several query variants per hop, reduces the chance that one bad ranking sinks the chain. - Duplicate evidence. Later queries often retrieve passages you already have. The example filters these with
if passage not in evidence. Without that check, repeated passages waste context. - Query drift. Each rewrite adds a chance to move away from the user's intent. Keep the original question in every prompt, as the example does.
- Latency stacking. Three hops mean at least three sequential model calls and three searches, plus the answer call. You cannot parallelize them. Measure the added time and set a budget on the number of hops.
- Questions that aren't multi-hop. A one-hop question run through a three-step pipeline pays three times the cost for no gain. Routing, covered later in this tutorial, decides when to skip this machinery.
Combining with fusion
Nothing stops a single hop from being a multi-query search. At each hop, ask for two or three phrasings of the query, run them, and merge the ranked lists with reciprocal rank fusion before adding the top results to the evidence. This costs extra searches but not extra model calls beyond the one that writes the variants. It is a good first defence against error propagation, because a bad ranking from one phrasing is outvoted by the others.
Exercises
Exercise
A user asks, "Compare the free and pro plans on storage limits and price." Should you use parallel or sequential retrieval, and why?
Show answer
Parallel. The two sub-questions (free plan limits and price, pro plan limits and price) can both be written from the question alone. Neither query needs evidence from the other. You can run them concurrently, then merge the results, which is faster than sequential hops.
Exercise
In the example code, the model sometimes returns "Mara Voss" born in hop 3 but the search returns the passage about Kestrel Systems instead. Name two changes that make the chain more robust to a bad hop.
Show answer
Any two of these: raise top_k above 1 so the correct passage has a chance to appear; generate several query variants per hop and merge them with reciprocal rank fusion; check for a weak or empty result and fall back to the original question; keep the original question in the prompt so the model can recover; log the queries to find the failing hop.