Sub topic 8
Step-Back Queries for Broader Context
This chapter covers the step-back technique. It assumes you know the basic RAG pipeline (index, retrieve, generate) and can call a language model with a text prompt. You should also be able to read Python and know what embedding search and BM25 do. It reuses reciprocal_rank_fusion from the earlier chapter on merging ranked lists.
When a specific question finds nothing useful
Some questions are too specific for the documents you have indexed. Take this one:
> Why does my Python 3.12 thread pool give no speedup when hashing 1 KB strings with md5?
No document is likely to describe that exact situation. Retrieval might match "md5" and "Python 3.12" and return hashing tutorials and release notes. The page that explains the cause is a general explanation of the global interpreter lock (GIL) and CPU-bound threads. That page shares few words with the question, and its embedding sits closer to "threads and the GIL" than to "md5 hashing of small strings".
A step-back query handles this. The model rewrites the question into a more general one that asks for the underlying concept or principle:
> How does the GIL limit threading performance for CPU-bound work in Python?
Searching with that broader question retrieves background material. The generator then combines the background with the specific facts in the user's question.
What a step-back query is
A step-back query is a rewrite that moves up one level of abstraction. It drops incidental details such as version numbers, names, and sizes, and keeps the topic or principle behind them. The technique comes from "step-back prompting" research, which found that asking for the underlying principle first improved answers on reasoning-heavy questions. In retrieval, you use the same idea to fetch the principle.
Here are some typical transformations:
| Specific question | Step-back query |
|---|---|
| Why did my invoice for March 2024 include a 4.5% surcharge? | How are surcharges calculated and applied on invoices? |
| Can employee 4471 carry over unused leave into Q1? | What is the policy on carrying over unused leave? |
| Why does `pandas.merge` return duplicate rows with `how="left"`? | How do joins handle duplicate keys in pandas? |
| Which GPU do I need for Llama 3 70B at 8-bit? | How much memory does running a large language model require? |
The rewrite is still a question a retriever can answer. It does not summarize or answer the original question.
Where it sits in the pipeline
Step-back runs before retrieval, like the other rewriting techniques. In most systems you do not replace the original query. You search with both and merge the results.
Keeping the original query protects you when the question is already well formed. The exact-match passage stays in the results, and the broader passages are added to it.
Implementation
The code below asks the model for one broader question and searches with both queries. It then merges the two lists. The llm and search arguments are placeholders for your own model call and retriever. search takes a query and a count and returns a list of document IDs. The demo at the end uses fakes so you can run the file as it is.
from typing import Callable
def reciprocal_rank_fusion(rankings: list[list[str]], k: int = 60) -> list[str]:
scores: dict[str, float] = {}
for ranking in rankings:
for rank, doc_id in enumerate(ranking, start=1):
scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank)
return sorted(scores, key=scores.get, reverse=True)
STEP_BACK_PROMPT = (
"Rewrite the question below as a more general question about the "
"underlying concept or principle. Remove specific names, numbers and "
"versions. Return only the general question on one line.\n\n"
"Example\n"
"Question: Can employee 4471 carry over unused leave into Q1?\n"
"General question: What is the policy on carrying over unused leave?\n\n"
"Question: {question}\n"
"General question:"
)
def step_back_query(question: str, llm: Callable[[str], str]) -> str:
reply = llm(STEP_BACK_PROMPT.format(question=question)).strip()
lines = reply.splitlines()
return lines[0].strip() if lines and lines[0].strip() else question
def step_back_search(
question: str,
llm: Callable[[str], str],
search: Callable[[str, int], list[str]],
top_k: int = 5,
broad_k: int = 3,
) -> list[str]:
broad = step_back_query(question, llm)
specific_hits = search(question, top_k)
broad_hits = search(broad, broad_k)
return reciprocal_rank_fusion([specific_hits, broad_hits])[: top_k + broad_k]
if __name__ == "__main__":
question = "Why does my Python 3.12 thread pool give no speedup hashing 1 KB strings?"
broad_question = "How does the GIL limit threading performance for CPU-bound work?"
def fake_llm(prompt: str) -> str:
return broad_question
index = {
question: ["faq_hashing", "blog_threadpool"],
broad_question: ["gil_overview", "blog_threadpool", "threads_guide"],
}
def fake_search(query: str, k: int) -> list[str]:
return index.get(query, [])[:k]
print(step_back_search(question, fake_llm, fake_search, top_k=2, broad_k=3))Running it prints:
['blog_threadpool', 'faq_hashing', 'gil_overview', 'threads_guide']blog_threadpool comes first because both searches returned it. faq_hashing and gil_overview have the same fused score. Python's sort is stable, so faq_hashing stays ahead because it was added first.
Design choices in the code
- A worked example in the prompt. One or two examples teach the model the right level of abstraction better than the instruction alone. Use examples from your own domain.
- Only the first line is used. Models sometimes add explanations. Taking the first line keeps a chatty reply from becoming a search query.
- Fallback to the original. If the reply is empty, the original question is used, so the function degrades to normal retrieval.
- A smaller
broad_k. Broad queries match many documents loosely, so you take fewer results from them. This keeps them from crowding out specific passages.
Choosing between step-back, HyDE and decomposition
All three rewrite the query, but they fix different failures. Choose by the mismatch you observe in your retrieval logs.
| Technique | Failure it addresses | What it searches with |
|---|---|---|
| Step-back | The question is too specific, and the answer depends on general background | A broader question |
| HyDE | The question and the answer documents use different vocabulary or style | A fake answer passage |
| Decomposition | The question has several parts that need different documents | Several narrower sub-questions |
Step-back and decomposition move in opposite directions. Step-back goes broader and decomposition goes narrower. A question like "Compare the GIL's effect on md5 hashing and on file downloads" needs decomposition. Each half then needs its own retrieval, and step-back can be applied to each sub-question if it is still too specific.
Step-back fits best when:
- Users ask about their own case and the documentation describes general rules.
- The corpus is conceptual: policies, manuals, textbooks, and design docs.
- Answers need a principle plus a case-specific calculation.
Failure modes and edge cases
The step-back is too broad
"How does Python handle concurrency?" matches dozens of documents, and none of them is clearly relevant. The retrieved passages fill the context window and the model loses the thread. Mitigations:
- Ask in the prompt for "one level more general", not "the general topic".
- Cap
broad_kat a small number. - Fuse with the original query so specific hits keep their rank.
The step-back drops a constraint that matters
A question about "the EU refund policy" can step back to "the refund policy". The retrieved general policy may then contradict the regional one. Tell the model to keep jurisdiction, product, and customer type, and remove only identifiers and incidental details. Check your prompt against questions where the dropped detail changes the answer.
The query is an exact lookup
Questions such as "What does error code E4471 mean?" or "Show ticket 88213" need the specific token. A step-back query loses it. A router (covered later in this tutorial) can skip step-back for identifier-heavy questions. A simple rule that detects codes and IDs also works until you build one.
Conversation context
A follow-up such as "and what about its latency?" cannot be stepped back until it is a standalone question. Run conversational condensing first, then step-back on the condensed question. Doing it the other way round abstracts away the very subject of the question.
Cost
Step-back adds one model call and one extra search to each question. The call is small, because the prompt is short and the output is a single line, but it sits on the critical path before retrieval can finish. You can run the original search in parallel with the model call to hide some of that delay. In the code above the two searches are independent, so only the model call has to come first.
The generator can mistake background for evidence
Broad passages describe the general rule, not the user's case. If you pass all passages in one block, the generator may state a general rule as if it applied to the specific case. Labeling the passages ("background" and "directly relevant") or ordering them by group makes this less likely.
Checking that it helps
Step-back helps some questions and hurts others, so judge it on a labeled set of your own questions. For each one, record which documents should be retrieved. Compare recall at k and mean reciprocal rank with and without step-back. Group the results by question type. Step-back often improves "why" and "how" questions about a specific case, and lowers results for lookup questions. If the gains are confined to one type, apply it only to that type, using routing. Evaluation is covered in detail in a later chapter.
Exercise
A user asks "Why did my invoice for March 2024 include a 4.5% surcharge?" Your corpus has a general page called "How surcharges are applied" and a changelog of individual fee changes. Describe how step-back retrieval would handle this question, and name one setting you would use to keep the broad results from drowning out the specific ones.
Show answer
The model rewrites the question to something like "How are surcharges calculated and applied on invoices?". You search with both the original and the rewritten question, and merge the two ranked lists with reciprocal rank fusion. The general page should surface from the step-back search, and the changelog entries for March 2024 from the original search. To keep the broad results from dominating, take fewer results from the step-back search (a small broadk, such as 3, against topk of 5). The original query's ranking also stays in the fusion.
Exercise
Your system receives "What does error code E4471 mean?" and the step-back rewrite is "What do error codes mean in general?". What goes wrong, and how would you prevent it?
Show answer
The rewrite removes the code E4471, which is the one token that identifies the right document. The broad search returns generic error-code material, and the specific page may be missing if you replaced the original query. Prevent it by always keeping the original query in the fusion, and by routing identifier-heavy questions (codes, ticket numbers, exact names) past step-back to plain keyword or hybrid search.