Lab: Query Rewriting and Reranking
Measure retrieval on a fixed set of labelled questions, then add a cross-encoder reranker, rewrite follow-up questions into standalone queries, and fuse several query variants (paraphrase, step-back and hypothetical answer) with RRF, comparing recall@1, recall@3 and MRR before and after each change.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Measure the baseline
- Step 2: Add a cross-encoder reranker
- Step 3: Rewrite follow-up questions
- Step 4: Search with several variants and fuse them
- Troubleshooting
- Check your understanding
- Apply it: stretch tasks
- Review prompt
Lessons of RAG Foundations
- When Retrieval Beats Fine-Tuning or Long Context Concept · 15 min
- A Minimal RAG Pipeline End to End Worked example · 25 min
- Assembling Context for Generation Concept · 15 min
- Lab: Query Rewriting and Reranking Lab · 25 min
- Common RAG Failure Modes Concept · 15 min
- Check: Trace a Wrong Answer to Its Cause Knowledge check · 6 questions
What you will learn
- Improve retrieval with query rewriting or reranking and show the effect on a fixed query set.
Prerequisites: Vector Search Foundations, Chunking, LLM API Integration
01. Goal and setup
The pipeline from lesson 2 retrieves with one vector search for the question exactly as the user typed it. That fails in two ways: the evidence is among the candidates but ranked too low to be sent, or the question does not describe what it needs, as with a follow-up such as how long do they stay there? This lab fixes each failure with a technique built for it, and proves the effect with numbers rather than with one convincing example:
- a reranker, a second model that reorders the candidates;
- query rewriting, which turns a follow-up into a standalone query;
- multi-query retrieval, which searches with several variants and fuses the results.
Every comparison uses the same labelled questions and changes one thing at a time, as in the Chunking lab. You need: the chunk-lab folder with the lesson 2 files and a built index. Tested with Python 3.12, sentence-transformers 6.3.0, torch 2.15.0 (CPU build), fastembed 0.9.1 and numpy 2.5.5. All rewriting runs against FAKE hand-written queries by default, so the outputs are reproducible offline; each script has a real-model function as well.
cd chunk-lab
source .venv/bin/activate # Windows: .venv\Scripts\activate
# Linux: the CPU build of torch avoids several GB of GPU libraries
python -m pip install torch --index-url https://download.pytorch.org/whl/cpu
python -m pip install sentence-transformers
python ingest.py # if index/ is missing or chunks.jsonl changedchunk-lab/
├── measure.py step 1: recall@k and MRR on the labelled questions
├── baseline.py step 1
├── rerank.py step 2: cross-encoder second stage
├── compare_rerank.py step 2
├── followups.py step 3: eight follow-up questions with evidence
├── rewrite.py step 3: fake and real rewriters
├── compare_rewrite.py step 3
└── multi_query.py step 4: query variants fused with RRF02. Step 1: Measure the baseline
"""Light retrieval metrics on the labelled evidence: recall@k and MRR."""
from statistics import mean
from labels import load_docs, load_labels
from retrieve import Hit
DOCS = load_docs()
LABELS = load_labels(DOCS) # the 15 questions, evidence as (doc, start, end) spans
def contains(record: dict, span: tuple[str, int, int]) -> bool:
"""Does this chunk hold the whole evidence span?"""
doc, start, end = span
return (record["doc_id"].endswith("/" + doc)
and record["char_start"] <= start and end <= record["char_end"])
def recall_at(hits: list[Hit], spans: list, k: int) -> float:
"""Share of the evidence spans that sit inside one of the top k hits."""
return mean(any(contains(h.record, s) for h in hits[:k]) for s in spans)
def reciprocal_rank(hits: list[Hit], spans: list) -> float:
"""1 / rank of the first hit holding any evidence; 0 if no hit does."""
for rank, hit in enumerate(hits, start=1):
if any(contains(hit.record, s) for s in spans):
return 1 / rank
return 0.0
def report(name: str, rankings: list[list[Hit]], items: list[dict]) -> list[float]:
"""Print recall@1, recall@3 and MRR; return the per-question reciprocal ranks."""
rr = [reciprocal_rank(hits, q["spans"]) for hits, q in zip(rankings, items)]
r1 = mean(recall_at(h, q["spans"], 1) for h, q in zip(rankings, items))
r3 = mean(recall_at(h, q["spans"], 3) for h, q in zip(rankings, items))
print(f"{name:<12} recall@1 {r1:.2f} recall@3 {r3:.2f} MRR {mean(rr):.2f}")
return rrmeasure.py reuses the labelled evidence from the Chunking lab. A span counts as found only when one chunk holds all of it, because the reranker and the prompt handle whole chunks. Next to recall@k it reports the mean reciprocal rank (MRR): 1 divided by the rank of the first chunk holding any evidence, averaged over the questions. Recall@3 tells you whether the evidence is in what you send; MRR tells you how near the top it sits, which is what a reranker changes.
from measure import LABELS, report
from retrieve import search
rankings = [search(q["question"], k=10) for q in LABELS]
rr = report("vector only", rankings, LABELS)
print("not at rank 1:", {q["qid"]: round(1 / r) if r else None
for q, r in zip(LABELS, rr) if r < 1})python baseline.pyvector only recall@1 0.87 recall@3 0.93 MRR 0.94
not at rank 1: {'q07': 6}These are the configuration B numbers from the Chunking lab, so the pipeline is unchanged. Only q07, Why did a scheduled run happen twice during the night?, has its evidence below rank 1: the daylight-saving sentence is at rank 6 and never reaches a prompt with k = 3. Recall@1 is below 1 for another reason too: q13 and q15 have two evidence spans in different chunks, so one chunk can hold only half of their evidence.
03. Step 2: Add a cross-encoder reranker
The embedding model is a bi-encoder: it turns the question and each chunk into vectors separately, which is why chunk vectors can be computed at ingest time and searched in milliseconds. It never sees the question and a chunk together. A cross-encoder reads the question and one passage as a single input and outputs a relevance score, so it can weigh how each word of the question relates to each word of the passage. Nogueira and Cho (2019) showed how much this improves ranking. The price is one model run per pair at question time, so a cross-encoder is used as a second stage: the vector search returns a short candidate list, and the reranker reorders only those candidates.
"""Second stage: score (question, passage) pairs with a cross-encoder and reorder."""
import os
from functools import cache
from sentence_transformers import CrossEncoder
from ingest import embed_text
from retrieve import Hit, search
RERANKER = os.environ.get("RERANKER", "cross-encoder/ms-marco-MiniLM-L6-v2")
@cache
def reranker() -> CrossEncoder:
return CrossEncoder(RERANKER) # downloads about 90 MB on first use
def rerank(question: str, hits: list[Hit]) -> list[Hit]:
pairs = [(question, embed_text(hit.record)) for hit in hits] # header included
scores = reranker().predict(pairs)
order = sorted(range(len(hits)), key=lambda i: -scores[i]) # stable for ties
return [hits[i] for i in order]
def search_reranked(question: str, k: int = 3, candidates: int = 10) -> list[Hit]:
return rerank(question, search(question, candidates))[:k]cross-encoder/ms-marco-MiniLM-L6-v2 is a small cross-encoder trained on MS MARCO, a large set of real search queries with passages marked relevant. predict() returns unbounded scores, which are only meaningful for sorting. The reranker gets the same header text that was embedded, so it knows that a chunk belongs to Retries and failures > Timeouts. Compare both stages on the same 10 candidates:
import time
from measure import LABELS, report
from rerank import rerank, reranker
from retrieve import search
first = [search(q["question"], k=10) for q in LABELS] # the same 10 candidates
reranker().predict([("warm-up", "warm-up")]) # load and warm up before timing
start = time.perf_counter()
second = [rerank(q["question"], hits) for q, hits in zip(LABELS, first)]
ms = (time.perf_counter() - start) * 1000 / len(LABELS)
before = report("vector only", first, LABELS)
after = report("+ reranker", second, LABELS)
for q, b, a in zip(LABELS, before, after):
if b != a:
print(f"{q['qid']}: first evidence at rank {round(1 / b) if b else '-'}"
f" -> {round(1 / a) if a else '-'}")
print(f"reranking 10 candidates: {ms:.0f} ms per question")python compare_rerank.pyvector only recall@1 0.87 recall@3 0.93 MRR 0.94
+ reranker recall@1 0.93 recall@3 1.00 MRR 1.00
q07: first evidence at rank 6 -> 1
reranking 10 candidates: 2270 ms per questionThe reranker moves q07 from rank 6 to rank 1 and does not push any other question down, so recall@3 and MRR reach 1.00. The header matters: when only the chunk text is passed (hit.record["text"]), recall@1 falls to 0.80, because q08 and q09 slip to rank 2. Try it.
The cost is time: about 2 seconds per question in the run above, and several times more or less on other machines. The time grows with the number and length of the candidates, so measure it on your hardware, after a warm-up call as the script does. A GPU, a smaller candidate list or a hosted reranking API reduces it. One limit no reranker can lift: it only reorders what the first stage returned. Evidence outside the candidates stays lost.
04. Step 3: Rewrite follow-up questions
In a chat the retriever sees only the text you search with, not the conversation. Can I see it again later? says nothing about API tokens. To measure this, label eight follow-ups, each with the turn before it, exactly as you labelled the 15 questions:
"""Eight follow-up questions, each with the turn before it and labelled evidence."""
from labels import locate
from measure import DOCS
# (id, previous question, previous answer, follow-up, (doc, evidence quote))
CHATS = [
("f1", "What is the default timeout for a job?", "15 minutes.",
"And what happens when it is exceeded?",
("retries.md", "A job that runs longer than its `timeout` is stopped")),
("f2", "What do I need to install Larkspur?", "Python 3.11 or later.",
"Which operating systems does it support?",
("install.md", "It runs on Linux and macOS.")),
("f3", "How do I see the jobs in the dead-letter queue?", "Run larkspur dlq list.",
"How long do they stay there?",
("retries.md", "It stays there for 14 days and is then deleted.")),
("f4", "How do I trigger a job over the HTTP API?", "POST to /jobs/<name>/runs.",
"How many times a minute can I do that?",
("api.md", "Each token may make 60 requests per minute.")),
("f5", "What does the workers setting control?", "How many jobs run at once.",
"What is it set to if I leave it out?",
("configuration.md", "The default is 4.")),
("f6", "Why are my jobs stuck as queued after upgrading?", "A skipped migration.",
"How do I fix it?",
("install.md", "run `larkspur migrate` once before you start the new version")),
("f7", "How do I create an API token?", "Run larkspur token create.",
"Can I see it again later?",
("api.md", "A token is shown once and cannot be retrieved later.")),
("f8", "Which time zone do schedules use?", "UTC, unless you set timezone.",
"Can that cause problems?",
("configuration.md", "Daylight-saving changes can skip or repeat a run")),
]
def load_chats() -> list[dict]:
return [{"qid": cid, "history": [prev_q, prev_a], "question": follow_up,
"spans": [(doc, *locate(DOCS[doc], quote))]}
for cid, prev_q, prev_a, follow_up, (doc, quote) in CHATS]"""Rewrite a follow-up into a standalone search query."""
import os
PROMPT = """Rewrite the user's last message as one standalone search query for the
Larkspur documentation. Resolve words such as "it", "that" and "there" using the
conversation. Keep the user's meaning; do not answer. Reply with the query only.
<conversation>
User: {question}
Assistant: {answer}
User: {follow_up}
</conversation>"""
# FAKE rewriter for offline runs: queries written by hand, standing in for a model.
HAND_WRITTEN = {
"f1": "What happens when a job exceeds its timeout?",
"f2": "Which operating systems does Larkspur support?",
"f3": "How long do jobs stay in the dead-letter queue?",
"f4": "How many times a minute can I trigger a job over the HTTP API?",
"f5": "What is the workers setting set to if I leave it out?",
"f6": "How do I fix jobs stuck as queued after upgrading?",
"f7": "Can I see an API token again after creating it?",
"f8": "Can the time zone that schedules use cause problems?",
}
def fake_rewrite(chat: dict) -> str:
return HAND_WRITTEN[chat["qid"]]
def claude_rewrite(chat: dict) -> str:
"""The real rewriter. Needs ANTHROPIC_API_KEY and ANTHROPIC_MODEL."""
import anthropic
(question, answer), follow_up = chat["history"], chat["question"]
response = anthropic.Anthropic().messages.create(
model=os.environ["ANTHROPIC_MODEL"], # a small, fast model is enough here
max_tokens=16000, # thinking and text share this cap
messages=[{"role": "user", "content": PROMPT.format(
question=question, answer=answer, follow_up=follow_up)}],
)
if response.stop_reason != "end_turn": # refusal or cut off: no usable query
raise RuntimeError(f"rewrite stopped with {response.stop_reason}")
return "".join(b.text for b in response.content if b.type == "text").strip()The rewrite prompt gives the model the last exchange and asks for one standalone query, with references such as it and there resolved and nothing answered. This is the simplest form of the rewrite-retrieve-read pattern of Ma et al. (2023). The fake rewriter returns queries written by hand from the same instructions. The comparison adds a third, cheaper option that needs no model: put the previous question in front of the follow-up.
import sys
from followups import load_chats
from measure import report
from retrieve import search
from rewrite import claude_rewrite, fake_rewrite
rewrite = claude_rewrite if "--claude" in sys.argv else fake_rewrite
chats = load_chats()
queries = {
"follow-up": [c["question"] for c in chats],
"+ previous": [f"{c['history'][0]} {c['question']}" for c in chats],
"rewritten": [rewrite(c) for c in chats],
}
for name, texts in queries.items():
rr = report(name, [search(t, k=10) for t in texts], chats)
ranks = [f"{c['qid']}={round(1 / r) if r else '-'}" for c, r in zip(chats, rr)]
print(" first evidence at rank:", " ".join(ranks))python compare_rewrite.py # hand-written rewrites
python compare_rewrite.py --claude # real rewrites: needs ANTHROPIC_* env varsfollow-up recall@1 0.38 recall@3 0.50 MRR 0.47
first evidence at rank: f1=4 f2=1 f3=1 f4=1 f5=- f6=2 f7=- f8=-
+ previous recall@1 0.88 recall@3 0.88 MRR 0.91
first evidence at rank: f1=1 f2=1 f3=1 f4=4 f5=1 f6=1 f7=1 f8=1
rewritten recall@1 0.75 recall@3 1.00 MRR 0.85
first evidence at rank: f1=1 f2=1 f3=1 f4=3 f5=2 f6=1 f7=1 f8=1Searched as typed, the follow-ups find their evidence at rank 1 only three times in eight, and three not even in the top 10. Both fixes repair most of that. Adding the previous question wins more first places, but on f4 the previous question, about triggering jobs, pulls the triggering section above the rate limits. The rewritten queries put all eight in the top 3. With eight questions a difference of one or two is not a reliable ranking of the two methods; what is reliable is that searching with the bare follow-up is far worse than either. Run the --claude variant, read the queries a real model writes, and compare its line with the hand-written one. A rewrite costs a model call per turn, so many systems skip it when the message already makes sense on its own.
05. Step 4: Search with several variants and fuse them
Rewriting helps when the question lacks context. q07 has a different problem: it describes a symptom (ran twice during the night) in words the docs do not use (daylight-saving changes can skip or repeat a run). Two published techniques generate queries that close such a gap:
- Step-back prompting (Zheng et al., 2023) asks a more general question behind the specific one, here which time zone do schedules use?
- HyDE, hypothetical document embeddings (Gao et al., 2022), has a model write a passage that might answer the question and searches with that, because a passage looks more like a chunk than a question does.
Multi-query retrieval searches with several such variants and fuses the rankings with reciprocal rank fusion, the RRF from the Vector Search skill, so a chunk that ranks well for several variants comes first.
"""Multi-query: search with several phrasings, then fuse the rankings with RRF."""
import os
from measure import LABELS, reciprocal_rank
from retrieve import Hit, search
VARIANTS_PROMPT = """Write three search queries for the Larkspur docs that could find
the answer to the question below: a paraphrase in other words, a more general
question behind it, and a short passage that might answer it, written as if
copied from the docs. One per line, no labels.
Question: {question}"""
# FAKE generator for offline runs: written by hand, standing in for a model.
FAKE_VARIANTS = {
"q07": [
"Can a schedule run the same job twice in one night?", # paraphrase
"Which time zone do Larkspur schedules use?", # step-back
"Larkspur may run a job twice at night if its schedule " # hypothetical
"follows local time and the clocks change for daylight saving.", # answer
],
}
def claude_variants(question: str) -> list[str]:
"""The real generator. Needs ANTHROPIC_API_KEY and ANTHROPIC_MODEL."""
import anthropic
response = anthropic.Anthropic().messages.create(
model=os.environ["ANTHROPIC_MODEL"],
max_tokens=16000, # thinking and text share this cap
messages=[{"role": "user",
"content": VARIANTS_PROMPT.format(question=question)}],
)
if response.stop_reason != "end_turn": # refusal or cut off: no variants
raise RuntimeError(f"variants stopped with {response.stop_reason}")
text = "".join(b.text for b in response.content if b.type == "text")
return [line.strip() for line in text.splitlines() if line.strip()][:3]
def rrf(rankings: list[list[Hit]], k: int = 60) -> list[Hit]:
"""Reciprocal rank fusion, as in the Vector Search skill, over Hit lists."""
scores: dict[str, float] = {}
hits: dict[str, Hit] = {}
for ranking in rankings:
for rank, hit in enumerate(ranking, start=1):
scores[hit.chunk_id] = scores.get(hit.chunk_id, 0.0) + 1 / (k + rank)
hits[hit.chunk_id] = hit
return [hits[c] for c in sorted(scores, key=lambda c: (-scores[c], c))]
if __name__ == "__main__":
q07 = next(q for q in LABELS if q["qid"] == "q07")
queries = [q07["question"], *FAKE_VARIANTS["q07"]]
rankings = [search(text, k=10) for text in queries]
for text, ranking in zip(queries, rankings):
rr = reciprocal_rank(ranking, q07["spans"])
print(f"rank {round(1 / rr) if rr else '-':>2} {text[:70]}")
fused = rrf(rankings)
print(f"rank {round(1 / reciprocal_rank(fused, q07['spans'])):>2} fused with RRF")python multi_query.pyrank 6 Why did a scheduled run happen twice during the night?
rank 3 Can a schedule run the same job twice in one night?
rank 1 Which time zone do Larkspur schedules use?
rank 1 Larkspur may run a job twice at night if its schedule follows local ti
rank 1 fused with RRFThe paraphrase lifts the evidence to rank 3, the step-back query and the hypothetical answer to rank 1, and the fused ranking keeps it at rank 1. The hypothetical answer may contain invented details. That is acceptable because it is only a search query: it is never shown to the user or sent to the model as a source. Multi-query costs one model call and three extra searches, and returns more distinct chunks, which is the case assemble() from lesson 3 handles.
Choose by the failure you see. When the evidence is in the candidates but too low, rerank. When the query does not say what it needs, rewrite or add variants. On q07 both worked; on your own corpus the fixed query set tells you which one pays for its cost.
06. Troubleshooting
07. Check your understanding
08. Apply it: stretch tasks
Finish the practice project:
- Add a
--rerankflag to yourask.pythat callssearch_reranked()instead ofsearch(), with 20 candidates. - Run your 15 test questions again with the real model and save the results as
answers_reranked.jsonl. Mark each answer right or wrong against your labelled evidence. - Count how many questions changed from wrong to right, and how many from right to wrong. Add both numbers, recall@3 and MRR before and after, and the reranking time per question to
DECISION.md. - Stretch: set
RERANKER=cross-encoder/ms-marco-MiniLM-L12-v2, a larger model of the same family, and decide whether its gain is worth its time on your set. - Stretch: write ten follow-up questions from your own docs, label their evidence, and repeat step 3 with
claude_rewrite.
09. Review prompt
Without looking back, answer in your own words:
- What does MRR measure that recall@3 does not, and which technique in this lab mainly changes it?
- How does a cross-encoder differ from the embedding model, and why does that make it a second stage?
- Name three ways to turn a follow-up into a better search query, and what each costs.
- What are step-back queries and hypothetical-answer queries, and why must the hypothetical answer never reach the answer prompt?
References
- Passage Re-ranking with BERT (Nogueira and Cho, 2019)
- Sentence Transformers documentation: Cross Encoder usage
- cross-encoder/ms-marco-MiniLM-L6-v2 model card (Hugging Face)
- Query Rewriting for Retrieval-Augmented Large Language Models (Ma et al., 2023)
- Take a Step Back: Evoking Reasoning via Abstraction in Large Language Models (Zheng et al., 2023)
- Precise Zero-Shot Dense Retrieval without Relevance Labels (Gao et al., 2022)
- Retrieval-Augmented Generation for Large Language Models: A Survey (Gao et al., 2023)
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.