Sub topic 3
Multi-Step Retrieval: Using Earlier Results to Shape Later Queries
Assume you know the basics of a retrieval-augmented generation (RAG) pipeline, embeddings, vector or BM25 search, and Python. Multi-step retrieval uses the results from one search to improve the next search. It helps when the answer requires several connected facts.
Iterative retrieval with a stopping rule
A retrieval loop should have:
- An original question that remains fixed.
- A current search query.
- A store of unique passages.
- A stopping check.
- A maximum number of steps.
from typing import Callable
def iterative_retrieve(
question: str,
search: Callable[[str], list[str]],
judge: Callable[[str, list[str]], str],
max_steps: int = 3,
) -> list[str]:
passages: list[str] = []
query = question
for _ in range(max_steps):
for passage in search(query):
if passage not in passages:
passages.append(passage)
decision = judge(question, passages).strip()
if decision.upper() == "DONE":
break
query = decision
return passagesThe judge returns DONE when the passages are sufficient. Otherwise, it returns one follow-up query. The step limit prevents an expensive or endless loop.
Route or skip retrieval
Do not use the same strategy for every question. A router can classify the request before retrieval:
| Query condition | Action |
|---|---|
| Needs several connected facts | Use decomposition or iterative retrieval |
| Refers to earlier conversation | Condense it first |
| Needs only general model knowledge | Skip retrieval |
| Uses unfamiliar terminology | Try multi-query expansion or HyDE |
Routing reduces unnecessary model calls. It also makes failures easier to diagnose because each strategy has a clear purpose.
Measure the improvement
Compare the rewritten pipeline with a single-shot baseline. Use the same test questions and documents. Track:
- Recall: whether relevant documents were retrieved.
- Answer accuracy: whether the final answer is correct.
- Groundedness: whether claims are supported by passages.
- Latency and token cost.
A rewriting step is worthwhile only when its quality gain justifies its added cost.
Cost, latency, and query drift
Each loop can add a search and an LLM call. Set a step limit, deduplicate passages, and stop as soon as the evidence is sufficient. Query drift occurs when follow-up queries gradually move away from the original question. Keep the original question in every judge prompt and reject queries that introduce unsupported topics.
Exercise
Why must iterative retrieval have both a stopping check and a maximum step limit?
Show answer
The stopping check ends a successful search early, while the maximum limit prevents endless loops when the judge or search results fail.