Sub topic 11
Building an iterative retrieval loop with a stopping rule
This chapter assumes you know the basic RAG pipeline (index, retrieve, generate), can call an LLM with a text prompt, and can read Python. It builds on multi-step retrieval, where earlier results shape later queries.
Why a loop
Single-shot retrieval fails when the first search cannot reveal what to search for next. Take the question "Who founded the company that makes the library we use for retries?" The first search finds the library. Only then do you know which company to look up.
An iterative retrieval loop handles this. Each step searches, then asks the model one question: is the evidence enough, or what should I search next?
The loop
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 passagesThe function takes llm and search as arguments, so you can test it with fakes and swap in any model or index. Four details matter:
passagesaccumulates across steps. The model judges all evidence gathered so far, not only the latest batch.- The
if passage not in passagescheck removes duplicates. Without it, repeated queries fill the context with copies. - The prompt always includes the original
question. The model sees the goal at every step, which limits drift. - The reply is either the exact word
DONEor a new query. This keeps the output easy to parse.
Stopping rules
A loop needs more than one way to end. The code above has two, and you can add others.
| Rule | What it does | Failure it prevents |
|---|---|---|
| Model says `DONE` | Stops when evidence looks sufficient | Wasted searches on easy questions |
| Step limit (`max_steps`) | Stops after a fixed number of rounds | Infinite loops if the model never says `DONE` |
| No new passages | Stops when a search adds nothing new | Repeating the same query forever |
The step limit is required. The model decides when it is done, and models sometimes keep asking for more. A hard cap bounds cost and latency no matter what the model replies.
The code does not yet implement the "no new passages" rule. To add it, track whether a step added anything and break if it did not.
def added_new(passages: list[str], found: list[str]) -> bool:
new = [p for p in found if p not in passages]
passages.extend(new)
return bool(new)Call it in place of the inner for loop and break when it returns False.
Common errors
- Strict
DONEmatching. If the model replies "DONE." or "Done, the passages suffice", the check fails and the text becomes a search query. Tighten the prompt, or test whether the reply starts withDONE. - Repeated queries. The model may propose a query it already used. Keep a set of past queries and stop if a new one repeats.
- Query drift. Each new query is written from the last one, so the topic can wander. Keep the original question in every prompt, as above.
- Context growth. Passages pile up, and the prompt grows each step. Cap the total passages or truncate each one.
Cost
Each step costs one search and one model call. With max_steps=3, a question can take up to three searches and three model calls before generation begins. Use a loop only for questions that need it. A router that sends simple questions to single-shot retrieval keeps the average cost low.
Exercise
The loop returns after step 2 with passages that clearly do not answer the question, and the model never replied DONE. Which stopping rule ended it, and what should you do about the result?
Show answer
The step limit (or the "no new passages" rule, if you added it) ended it. Do not treat the passages as sufficient. Return a flag or message saying the evidence may be incomplete, so the generator can say it could not find an answer instead of guessing.
Exercise
A fake llm always replies "DONE." (with a trailing period). What does the loop do, and how do you fix it?
Show answer
"DONE.".upper() == "DONE" is false, so the loop treats "DONE." as a new search query and keeps running until max_steps. Fix it by stripping punctuation or checking reply.upper().startswith("DONE").