Sub topic 11
Building an iterative retrieval loop with a stopping rule
This chapter assumes you can read Python, have built a basic RAG pipeline (index, retrieve, generate), and know what top-k search returns. It also assumes you have seen reciprocal rank fusion and query decomposition in earlier chapters. Here you build the loop that ties multi-step retrieval together: search, check the evidence, and either stop or search again.
Why a loop
Single-shot retrieval runs one query and passes the results to the generator. That fails when the answer depends on facts you only learn by reading earlier results. Take the question "Which team did the author of the Raft paper's PhD advisor's lab belong to?" No single query matches a passage that holds the whole chain. You need the first result to tell you what to search for next.
An iterative retrieval loop handles this. At each step it does three things:
- Retrieve passages for the current query.
- Ask a model whether the passages answer the question.
- If not, take a new query from the model and go back to step 1.
The loop needs a stopping rule. Without one, it can run forever, or run long enough to cost more than the answer is worth.
The loop in code
This implementation is the one from the plan. It takes two callables, so you can plug in any model and any search backend.
from typing import Callable
def iterative_retrieve(
question: str,
llm: Callable[[str], str],
search: Callable[[str, int], list[str]],
max_steps: int = 3,
top_k: int = 4,
) -> list[str]:
passages: list[str] = []
query = question
for _ in range(max_steps):
for passage in search(query, top_k):
if passage not in passages:
passages.append(passage)
prompt = (
f"Question: {question}\n\nPassages so far:\n"
+ "\n".join(passages)
+ "\n\nIf the passages are enough to answer the question, reply "
"with exactly DONE. Otherwise reply with one new search query."
)
reply = llm(prompt).strip()
if reply.upper() == "DONE":
break
query = reply
return passagesPoints worth noticing:
search(query, top_k)returns passage text. The loop deduplicates by exact string match, so a passage found in step 1 is not added again in step 2.- The prompt always contains the original
question, not only the latest query. This keeps the model anchored to what the user asked. - The prompt contains all passages gathered so far, so the model judges the whole pool, not only the newest results.
max_stepsis a hard cap. Theforloop guarantees termination even if the model never says DONE.
Try it with fakes
You can test the control flow without a real model. The fake search below holds a tiny two-hop knowledge base, and the fake model asks for one follow-up search.
from typing import Callable
DOCS = {
"who wrote the raft paper": ["Raft was written by Diego Ongaro and John Ousterhout."],
"diego ongaro phd advisor": ["Diego Ongaro's PhD advisor was John Ousterhout at Stanford."],
}
def fake_search(query: str, k: int) -> list[str]:
return DOCS.get(query.lower(), [])[:k]
replies = iter(["diego ongaro phd advisor", "DONE"])
def fake_llm(prompt: str) -> str:
return next(replies)
def iterative_retrieve(
question: str,
llm: Callable[[str], str],
search: Callable[[str, int], list[str]],
max_steps: int = 3,
top_k: int = 4,
) -> list[str]:
passages: list[str] = []
query = question
for _ in range(max_steps):
for passage in search(query, top_k):
if passage not in passages:
passages.append(passage)
prompt = (
f"Question: {question}\n\nPassages so far:\n"
+ "\n".join(passages)
+ "\n\nIf the passages are enough to answer the question, reply "
"with exactly DONE. Otherwise reply with one new search query."
)
reply = llm(prompt).strip()
if reply.upper() == "DONE":
break
query = reply
return passages
for p in iterative_retrieve("Who wrote the Raft paper", fake_llm, fake_search):
print(p)The output is two passages, one per step. The first step retrieves the authors. The model then proposes a new query, and the second step retrieves the advisor passage. The model replies DONE and the loop exits after two of the three allowed steps.
Designing the stopping rule
The stopping rule decides how much the loop costs and how good the result is. The example combines two rules, and real systems often add more.
| Rule | What it checks | Strength | Weakness |
|---|---|---|---|
| Step limit | Number of iterations | Always terminates, bounds cost | Stops even when evidence is still missing |
| Model sufficiency check | Model says DONE | Adapts to question difficulty | Model may say DONE too early or too late |
| No new passages | A step added nothing to the pool | Cheap, needs no model call | Misses cases where new wording would help |
| Repeated query | The new query equals an earlier one | Catches loops where the model is stuck | Needs normalization of query text |
| Budget | Tokens, time or money spent | Protects latency and cost directly | Requires tracking usage |
The step limit is the only rule that is mandatory. Everything else is an early exit.
Choosing max_steps
Most multi-hop questions need two or three hops. A limit of 3 to 5 covers nearly all of them. Higher limits mostly pay for loops that were already failing. Choose the limit from your data: run the loop on a set of real questions, record how many steps each needed before DONE, and set the cap just above the 95th percentile.
Adding cheap early exits
The loop above can waste a step when a query returns only passages already in the pool. Add a check that stops when a step finds nothing new, and one that stops when the model repeats a query.
from typing import Callable
def iterative_retrieve_guarded(
question: str,
llm: Callable[[str], str],
search: Callable[[str, int], list[str]],
max_steps: int = 3,
top_k: int = 4,
) -> list[str]:
passages: list[str] = []
seen_queries: set[str] = set()
query = question
for _ in range(max_steps):
seen_queries.add(query.lower())
added = 0
for passage in search(query, top_k):
if passage not in passages:
passages.append(passage)
added += 1
if added == 0:
break
prompt = (
f"Question: {question}\n\nPassages so far:\n"
+ "\n".join(passages)
+ "\n\nIf the passages are enough to answer the question, reply "
"with exactly DONE. Otherwise reply with one new search query."
)
reply = llm(prompt).strip()
if reply.upper() == "DONE" or reply.lower() in seen_queries:
break
query = reply
return passagesThe added == 0 check saves a model call when a step brings nothing new. The seen_queries check stops the model from asking the same thing twice.
Common errors
The model does not reply with exactly DONE
The loop compares the reply to DONE after strip() and upper(). A model that replies "DONE." or "The passages are sufficient" will be treated as a new search query, and that text will be sent to the search backend. Three fixes help:
- Make the instruction strict and show the exact allowed forms.
- Accept a looser match, such as checking whether the reply starts with DONE.
- Use structured output, such as a JSON object with a
doneboolean and anext_queryfield, and validate it.
Empty or multi-line replies
An empty reply becomes an empty query. Some search backends return arbitrary results for it. Guard against this by treating an empty reply as a stop. Likewise, take only the first line of the reply if the model sometimes explains itself.
Context growth
The prompt grows every step because it includes every passage. With large passages and a high top_k, you can exceed the model's context window or pay for the same text repeatedly. Truncate each passage, cap the pool size, or ask the model to judge on short summaries.
Query drift
Each new query is written from the previous evidence, so small errors compound. A step-two query that slightly misreads a passage can pull in off-topic results, and step three builds on those. Because the prompt always repeats the original question, the model has a reference point, but drift still happens. Watch for it by logging every query, and read those logs on failing cases.
Sufficiency judged by the same model that wants to be helpful
Models tend to say DONE when the passages look plausible, even if a needed fact is missing. If you see answers that are confident but unsupported, tighten the prompt: ask the model to name the missing fact first, and only then decide.
SUFFICIENCY_PROMPT = (
"Question: {question}\n\nPassages so far:\n{passages}\n\n"
"First, on one line starting with MISSING:, name any fact needed to answer "
"the question that is not in the passages, or write MISSING: none. "
"Then, on a second line, write DONE if nothing is missing, or one new "
"search query if something is missing."
)When you use this prompt, parse the second line as the decision. Naming the gap first makes an early DONE less likely.
Observing the loop
An iterative loop is hard to debug if you only see the final passages. Return a trace along with the result: for each step, the query, the number of new passages, and the model's reply. A trace shows you where the loop went wrong, such as a step that retrieved nothing new or a query that drifted away from the topic.
from dataclasses import dataclass, field
@dataclass
class Step:
query: str
new_passages: int
reply: str
@dataclass
class Trace:
steps: list[Step] = field(default_factory=list)Append one Step per iteration and return the Trace next to the passages. When you evaluate the loop, compare traces of good and bad runs.
When not to use a loop
A loop adds at least one model call per step, plus the retrieval. For a question that a single query answers, that is wasted latency. Routing, covered later in this tutorial, decides when to skip the loop. Until then, a simple guard is useful: run the first retrieval, and enter the loop only if the sufficiency check fails.
Summary of the design
- The loop retrieves, checks sufficiency, and either stops or writes a new query.
- The step limit guarantees termination. Other rules are early exits that save cost.
- The prompt carries the original question and the whole evidence pool.
- Strict output parsing prevents a malformed reply from becoming a search query.
- Traces and stop reasons make failures visible.
Exercise
In iterative_retrieve, the model replies "DONE." (with a trailing period) on step 2. What does the loop do, and give one change that fixes it.
Show answer
The reply "DONE." does not equal "DONE" after strip and upper, so the loop treats it as a new search query and runs another step, sending "DONE." to the search backend. Fixes: accept replies that start with DONE (for example, reply.upper().startswith("DONE")), or use structured output with a boolean done field and validate it.
Exercise
A step returns only passages that are already in the pool. Which stopping rule from this chapter catches this, and why is it cheaper than the model sufficiency check?
Show answer
The "no new passages" rule. It compares the count of newly added passages to zero, which needs no model call, so it saves both latency and cost. The model sufficiency check needs a full prompt containing the whole pool.
Exercise
You run the loop on 200 real questions and find that 40% end because of the step limit with max_steps=3. Name two possible causes and one way to tell them apart.
Show answer
Either the cap is too low for these questions, or the loop is stuck, for example by drifting queries or a model that never says DONE. Read the traces of the step-limit runs. If the queries make steady progress and a larger cap would let them finish, raise the cap. If queries repeat or wander off topic, fix the prompt or add the repeated-query and drift checks instead.