Sub topic 1
Recap: Single-Shot Retrieval and Where It Stops Working
Prerequisites
This chapter assumes you already know the following:
- The shape of a retrieval-augmented generation (RAG) pipeline: index documents, retrieve, then generate an answer.
- What embeddings are, and the difference between vector search and keyword search such as BM25.
- How to send a text prompt to a large language model (LLM) and read the reply.
- Basic Python. The examples use only the standard library.
The rest of this tutorial changes what happens before and around retrieval. This chapter fixes the baseline those changes build on, and it shows the kinds of failure they are meant to fix.
What "single-shot" retrieval means
In a single-shot pipeline the user's text goes to the retriever once, unchanged. The retriever returns a fixed number of passages, and the generator answers from them. The retriever never sees the conversation. It does not know whether its results were any good, and it does not get a second try.
Its strengths are real. It has one retrieval call, so latency is low and cost is predictable. It has no loop that can run away. It is easy to debug, because you can log the query and the passages and read them. For many applications, such as a FAQ bot over a small, consistently worded knowledge base, this is enough, and you should not add complexity you do not need.
Top-k and ranking
The retriever scores every candidate passage against the query and keeps the best few. Three details matter for everything that follows.
- Top-k. The parameter
kis the number of passages returned. A smallk(3 to 5) keeps the prompt short and cheap but risks missing the passage you need. A largekraises the chance of including it, but adds noise and cost, and the generator may ignore passages buried in the middle of a long context. - Ranking. Only the order matters for the cut-off. A passage at rank 6 with
k=5is invisible to the generator, even if its score is almost the same as the passage at rank 5. - Scores depend on the method. A BM25 score, a cosine similarity, and a reranker score are on different scales. You cannot add or compare them directly. Later chapters merge ranked lists by position for this reason, not by score.
A retriever also has no notion of "I found nothing good". It returns the k nearest passages even when all of them are irrelevant, unless you add a score threshold yourself.
A runnable baseline
The following program implements single-shot keyword retrieval with a bag-of-words cosine score. It is deliberately simple, so you can see exactly why a query succeeds or fails. It has no stemming and no synonyms, which makes the failures easy to see. Real systems use BM25 or embeddings, which soften these problems without removing them.
import math
import re
from collections import Counter
STOP = {"a", "an", "the", "of", "to", "how", "do", "i", "my",
"is", "are", "what", "in", "within", "can", "and"}
DOCS = {
"d1": "Refunds are issued within 14 days of returning the item.",
"d2": "Standard shipping takes 3 to 5 business days.",
"d3": "Premium plan costs 20 dollars per month.",
"d4": "To reset your password, open Settings and choose Security.",
}
def tokenize(text: str) -> Counter:
words = re.findall(r"[a-z0-9]+", text.lower())
return Counter(w for w in words if w not in STOP)
def cosine(a: Counter, b: Counter) -> float:
dot = sum(a[t] * b[t] for t in a if t in b)
norm_a = math.sqrt(sum(v * v for v in a.values()))
norm_b = math.sqrt(sum(v * v for v in b.values()))
return dot / (norm_a * norm_b) if norm_a and norm_b else 0.0
def search(query: str, k: int = 3) -> list[tuple[str, float]]:
q = tokenize(query)
scored = [(cosine(q, tokenize(text)), doc_id) for doc_id, text in DOCS.items()]
scored.sort(reverse=True)
return [(doc_id, round(score, 3)) for score, doc_id in scored[:k] if score > 0]
print(search("refund policy for returning an item"))
print(search("How do I get my money back?"))The first query prints [('d1', 0.365)]. The words "returning" and "item" appear in both the query and the refund passage, so it is found.
The second query prints []. It asks for the same thing as the first, but shares no word with the refund passage. The passage says "refunds" and "returning". The user wrote "money back". The passage exists and the index is healthy, yet retrieval returns nothing.
Dense embeddings would probably rank the refund passage first for this query, because they capture meaning and not only spelling. They fail in a quieter way. The ranking still contains the right passage somewhere, but it may sit below passages that merely sound similar. The mechanism of the failure is the same in both cases: the query as written is a poor match for the text as written.
The if score > 0 filter in search is a minimal version of the score threshold mentioned earlier. Without it, the second query would return three zero-score passages, and the generator would receive irrelevant text that looks like evidence.
Where single-shot retrieval stops working
The failures below share one cause. The retriever sees one string, and that string is not a good description of what the index contains. The next chapter examines each in detail, so here is only a short list with the signs to look for.
| Failure | What the user does | Typical sign in your logs |
|---|---|---|
| Vocabulary mismatch | Uses different words from the documents ("money back" and "refund") | Right passage missing from top-k, or far down the list |
| Missing context | Asks a follow-up that depends on earlier turns ("what about its pricing?") | Query has pronouns or fragments with no subject |
| Multi-part question | Asks about two or more things at once ("compare plan A and plan B limits") | Results cover only one part, or a blurry mix of both |
| Multi-hop question | Asks something where the second lookup depends on the first answer | Needed fact is in a passage that the question never mentions |
| Wrong granularity | Asks too narrowly or too broadly for how the documents are written | Results are near-duplicates, or are high-level when you needed a detail, or the reverse |
Two further cases do not fit a single query rewrite. Some questions need no retrieval at all ("what is 12 times 12?" or "hello"). Retrieving for them wastes time and can inject distracting text. Other questions have no answer in the index, and the system should say so instead of answering from weak matches.
Diagnosing the failure before you fix it
Before you add any rewriting step, decide whether retrieval is the problem. A wrong answer has two possible sources: the right passage was not retrieved, or it was retrieved and the generator misused it. The fixes differ, and rewriting queries only helps with the first.
A practical check, using a set of questions where you know which passage should answer each:
- Run each question through the retriever and record the rank of the known-correct passage.
- Count how often it appears in the top-k. This share is the retrieval hit rate (also called recall at k).
- For misses, read the query next to the correct passage and name the cause using the table above.
- If the hit rate is high but answers are still wrong, look at the prompt and the generator instead.
Step 3 is the most useful. Counting causes tells you which technique to learn first. If most misses are follow-up questions, conversational rewriting pays off. If most are vocabulary mismatch, multi-query expansion or HyDE is the better bet.
def hit_rate(cases: list[tuple[str, str]], k: int = 3) -> float:
"""cases: (question, id of the passage that should be retrieved)."""
hits = 0
for question, expected_id in cases:
retrieved_ids = [doc_id for doc_id, _ in search(question, k)]
hits += expected_id in retrieved_ids
return hits / len(cases)
cases = [
("refund policy for returning an item", "d1"),
("How do I get my money back?", "d1"),
("how long does shipping take", "d2"),
("reset password", "d4"),
]
print(hit_rate(cases))This prints 0.5. Run it against the baseline above. The refund question phrased with "money back" fails, and so does the shipping question, because "take" does not match "takes" without stemming. Two of the four cases hit. This number is a baseline, and later chapters compare against it.
Keep a small set like this and grow it from real user logs. Chapter 13 returns to measurement in more depth.
Common mistakes at this stage
- Raising k to hide the problem. A bigger
ksometimes rescues a miss, but it adds noise and tokens for every query, including the ones that already worked. - Judging by the final answer only. A fluent answer can come from the model's own knowledge while retrieval returned nothing useful. Always inspect the retrieved passages.
- Testing with questions written by the document author. These reuse the document's own words, so they overstate the hit rate. Real users phrase things differently.
- Ignoring chunking. If the answer is split across two chunks, no query rewrite will fix it. Rewriting improves the query and cannot repair the index.
What changes next
Everything in this tutorial keeps the same pipeline and inserts work before or around the retrieval call. A model rewrites the query, produces several queries, or retrieves repeatedly. Each addition costs at least one extra model call. The tutorial therefore treats latency, cost, and the risk of a rewrite drifting away from what the user meant as part of the design, not as an afterthought.
Exercise
A user asks "How do I get my money back?" and your keyword retriever returns no relevant passages, although the knowledge base contains a passage titled "Refund policy". Name the failure type, and explain why raising k from 3 to 20 is unlikely to fix it.
Show answer
This is vocabulary mismatch. The query and the passage share no useful words ("money back" versus "refund"), so the passage scores zero or near zero and ranks below many others. Raising k only helps if the correct passage is just below the cut-off. Here it has no matching terms, so it may stay outside even a large top-k, while a larger k adds noise and cost for every other query.
Exercise
You measure a hit rate of 0.9 at k=5 on your test questions, yet users still report wrong answers. Where should you look first, and why would query rewriting probably not help?
Show answer
Look at the generation step: the prompt, how the passages are ordered and presented, and whether the model follows them. A 0.9 hit rate means the right passage is usually in the context already, so a better query would change little. Also check that your test questions resemble real user questions, since questions written from the documents inflate the hit rate.