Retrieval that works
Getting the right passage into the prompt is most of the battle. This module covers the techniques that make retrieval reliable.
Learning objectives
- Compare lexical (BM25) and semantic search
- Implement hybrid search with reciprocal rank fusion
- Explain reranking and the retrieval funnel
- Describe contextual retrieval and its reported impact
- Apply query rewriting, filters and permission checks
- Run keyword, semantic and hybrid search over the same documents
- Enforce permissions by filtering before ranking
Setup: the documents and helper functions from earlier modules (runs automatically when you press Run on any cell)
Python · setupimport numpy as np
from openai import OpenAI
embed_client = OpenAI() # the real SDK reads OPENAI_API_KEY from the environment
EMBED_MODEL = "YOUR-EMBEDDING-MODEL" # copy a current model name from the provider's docs
def embed(texts):
resp = embed_client.embeddings.create(model=EMBED_MODEL, input=list(texts))
return np.array([d.embedding for d in resp.data])
documents = {
"Returns Policy v7": """Damaged items can be returned within 30 days for a full refund. Send a photo of the damage to support before returning the item.
Unwanted items in their original packaging can be returned within 14 days. The customer pays the return postage for unwanted items.
Refunds are paid to the original payment method within 7 days of the return arriving.""",
"Delivery FAQ": """Standard UK delivery takes 3 to 5 working days and costs £3.95. Orders over £40 are delivered free.
Express delivery arrives the next working day if ordered before 2pm and costs £7.95.
Delivery to Ireland takes 5 to 7 working days.""",
"Care Guide": """Hand-wash bamboo boards in warm soapy water and dry them upright. Never put a bamboo board in the dishwasher.
Oil the board once a month with food-safe mineral oil to stop it cracking.
Product code BB-204 is the large bamboo board, 45 cm by 30 cm. Product code BB-110 is the small bamboo board.""",
"Gift Cards": """Gift cards are valid for 12 months from the date of purchase. They can be used online only.
A gift card cannot be exchanged for cash.""",
}
def chunk_text(text, max_words=180, overlap_words=40):
paragraphs = [p.strip() for p in text.split("\n\n") if p.strip()]
chunks, current = [], []
for para in paragraphs:
words = para.split()
if current and len(current) + len(words) > max_words:
chunks.append(" ".join(current))
current = current[-overlap_words:] if overlap_words else []
current.extend(words)
if current:
chunks.append(" ".join(current))
return chunks
chunks = []
for title, text in documents.items():
for c in chunk_text(text, max_words=20, overlap_words=0): # these documents are short: one paragraph per chunk
chunks.append({"id": f"{title}#{len(chunks)}", "source": title, "text": f"{title}: {c}"})
vectors = embed([c["text"] for c in chunks])
def retrieve(question, k=3):
scores = vectors @ embed([question])[0] # cosine similarity: the vectors are normalised
return [chunks[i] for i in np.argsort(-scores)[:k] if scores[i] > 0] # nothing in common: not a result4.1 Lexical vs semantic search
Lexical (keyword) search, e.g. BM25
Matches exact words, weighting rare words more. Excellent for product codes, names, error messages and jargon. Misses synonyms and paraphrases.
Semantic (vector) search
Matches meaning. Excellent for paraphrased questions. Can miss exact identifiers and rare terms.
4.2 Hybrid search
Hybrid search runs both and merges the results. A simple, robust way to merge ranked lists is reciprocal rank fusion (RRF): each document scores 1/(k + rank) in each list, and scores are added up.
Python · reciprocal rank fusiondef rrf(rankings, k=60):
"""rankings: list of ranked lists of doc ids, e.g. [bm25_ids, vector_ids]"""
scores = {}
for ranked in rankings:
for rank, doc_id in enumerate(ranked, start=1):
scores[doc_id] = scores.get(doc_id, 0) + 1 / (k + rank)
return sorted(scores, key=scores.get, reverse=True)
print(rrf([["d3", "d1", "d7"], ["d1", "d9", "d3"]])) # d1 and d3 rise to the top
RRF uses only the positions in each list, never the scores. That is its strength: keyword scores and similarity scores are on different scales and can't sensibly be added, but "second in one list and first in the other" needs no conversion.
4.3 Reranking
Retrieval is a funnel. First, cheap search pulls back many candidates (say, the top 50–150). Then a reranker — a model that reads the query and each candidate together — scores them more accurately, and you keep the best handful (say, 5–20) for the prompt. Rerankers are slower per document, which is why they're applied only to the shortlist.
4.4 Contextual retrieval
A chunk like "Revenue grew 3% over the previous quarter" is ambiguous on its own: which company? which quarter? In 2024 Anthropic described contextual retrieval: before indexing, an LLM writes a short sentence situating each chunk within its document, and that context is prepended to the chunk for both embedding and BM25. In Anthropic's experiments, measured on the top 20 retrieved chunks:
| Technique | Reduction in retrieval failures |
|---|---|
| Contextual embeddings | 35% |
| + contextual BM25 (hybrid) | 49% |
| + reranking | 67% |
Results will vary with your data — but the lesson generalises: give chunks context, combine search methods, and rerank.
4.5 Improving the query
- Query rewriting: turn a chatty follow-up ("what about for furniture?") into a standalone query using the conversation history.
- Multi-query: generate several phrasings and merge results.
- Decomposition: split a complex question into sub-questions and retrieve for each. Agentic retrieval systems — where an LLM plans and runs several searches — take this further.
The need for rewriting is easy to demonstrate. A follow-up question makes sense to a person who has read the conversation, and none to a search index that hasn't:
Python · a follow-up question, before and after rewritinghistory = ["How long does standard delivery take?"]
follow_up = "And what about Ireland?"
rewritten = "How long does delivery to Ireland take?" # in a real system an LLM writes this from the history
for label, query in [("follow-up as typed", follow_up), ("rewritten", rewritten)]:
top = retrieve(query, k=1)[0]
print(f"{label:19} -> {top['text']}")
Both versions may find the Ireland passage here, because "Ireland" is such a distinctive word. Change the follow-up to "And the faster one?" and run it again: nothing in those words says "delivery", so the search has little to go on, while the rewritten form "How long does express delivery take?" finds the passage at once. Asking an LLM to rewrite the latest message into a standalone question is one of the cheapest improvements to a conversational RAG system.
4.6 Filters and permissions
Apply metadata filters before or during retrieval: date ranges, document types, regions — and, crucially, access control. A RAG system must never retrieve a document the user isn't allowed to see; the LLM cannot be trusted to keep secrets it has been shown. (See OWASP LLM08 in the AI Security course.)
Python · filtering by permission before rankingsecured = [dict(c, audience={"customer", "staff"}) for c in chunks] # the public documents
secured.append({"id": "handbook#0", "source": "Staff Handbook", "audience": {"staff"},
"text": "Staff Handbook: Support agents can approve refunds up to £100 without a manager."})
secured_vectors = embed([c["text"] for c in secured])
def retrieve_for(question, role, k=2):
allowed = [i for i, c in enumerate(secured) if role in c["audience"]] # filter FIRST
scores = secured_vectors[allowed] @ embed([question])[0]
return [secured[allowed[i]]["source"] for i in np.argsort(-scores)[:k]]
question = "How big a refund can be approved without a manager?"
print("Staff see: ", retrieve_for(question, "staff"))
print("Customers see:", retrieve_for(question, "customer"))
The staff-only passage is the best match for the question, and a member of staff gets it. For a customer it is removed before the search runs, so it can never reach the prompt. Filtering afterwards — retrieving first and asking the model not to mention restricted material — is not a control: anything in the prompt can end up in the answer.
4.7 Hybrid search you can run
Here are both kinds of search over the shop's documents, merged with the rrf function from 4.2. The keyword side is a small version of BM25: a passage scores for each query word it contains, and rarer words count for more.
Python · keyword search, semantic search and the two fusedimport math, re
def tokens(text):
return re.findall(r"[a-z0-9£.-]+", text.lower())
doc_tokens = [tokens(c["text"]) for c in chunks]
def rarity(word): # rare words are worth more (the "IDF" in TF-IDF and BM25)
containing = sum(word in t for t in doc_tokens)
return math.log(1 + len(chunks) / containing) if containing else 0.0
def keyword_rank(query, k=3):
scores = [sum(rarity(w) for w in set(tokens(query)) if w in t) for t in doc_tokens]
order = [i for i in np.argsort(-np.array(scores)) if scores[i] > 0]
return [chunks[i]["id"] for i in order[:k]]
def semantic_rank(query, k=3):
scores = vectors @ embed([query])[0]
return [chunks[i]["id"] for i in np.argsort(-scores)[:k] if scores[i] > 0]
def hybrid_rank(query, k=3):
return rrf([keyword_rank(query, k=5), semantic_rank(query, k=5)])[:k]
for query in ["BB-204", "when will my order arrive?"]:
print(query)
print(" keyword :", keyword_rank(query))
print(" semantic:", semantic_rank(query))
print(" hybrid :", hybrid_rank(query))
For the product code, keyword search goes straight to the care guide and semantic search returns nothing useful. For the second query it is the other way round: none of its words appears in the delivery FAQ ("arrive" is not "arrives" to a keyword index), and meaning alone finds it. The hybrid list has the right passage at the top both times, without anyone having to decide in advance which kind of question was coming.
Extend RRF so each ranked list has a weight: weighted_rrf(rankings, weights, k=60) multiplies each list's contribution by its weight. Using the two lists in the starter code, show how the order changes when the keyword list is trusted twice as much as the semantic list, and the reverse.
Your turnkeyword_list = ["care#2", "returns#0", "delivery#1"]
semantic_list = ["delivery#1", "delivery#0", "care#2"]
# Write weighted_rrf(rankings, weights, k=60), then press RunShow a solution
keyword_list = ["care#2", "returns#0", "delivery#1"]
semantic_list = ["delivery#1", "delivery#0", "care#2"]
def weighted_rrf(rankings, weights, k=60):
scores = {}
for ranked, w in zip(rankings, weights):
for rank, doc_id in enumerate(ranked, start=1):
scores[doc_id] = scores.get(doc_id, 0) + w / (k + rank)
return sorted(scores, key=scores.get, reverse=True)
print("equal: ", weighted_rrf([keyword_list, semantic_list], [1, 1]))
print("keyword x2: ", weighted_rrf([keyword_list, semantic_list], [2, 1]))
print("semantic x2: ", weighted_rrf([keyword_list, semantic_list], [1, 2]))
# Weights are a setting to tune on a test set (Module 6), not to guess.The index in the starter code contains two versions of the returns policy. Write current_only(chunk_list) that keeps only chunks whose status is "current", and show which sources a search for "how long do I have to return a damaged item?" can now come from. Why is filtering better here than hoping the newer version ranks higher?
Your turnversions = [
{"source": "Returns Policy v6", "status": "archived", "text": "Damaged items can be returned within 14 days for a full refund."},
{"source": "Returns Policy v7", "status": "current", "text": "Damaged items can be returned within 30 days for a full refund."},
{"source": "Delivery FAQ", "status": "current", "text": "Standard UK delivery takes 3 to 5 working days."},
]
# Write current_only(chunk_list), then press RunShow a solution
versions = [
{"source": "Returns Policy v6", "status": "archived", "text": "Damaged items can be returned within 14 days for a full refund."},
{"source": "Returns Policy v7", "status": "current", "text": "Damaged items can be returned within 30 days for a full refund."},
{"source": "Delivery FAQ", "status": "current", "text": "Standard UK delivery takes 3 to 5 working days."},
]
def current_only(chunk_list):
return [c for c in chunk_list if c["status"] == "current"]
print("All versions:", [c["source"] for c in versions])
print("Searchable: ", [c["source"] for c in current_only(versions)])
# The two versions are almost the same text, so they score almost the same.
# Which one ranks first is close to chance, and the archived one gives the wrong number of days.
# A filter removes the possibility; ranking only makes it less likely.Key takeaways
- BM25 catches exact terms; vectors catch meaning — use both.
- Reciprocal rank fusion is a simple, robust way to merge rankings.
- Retrieve broadly, then rerank a shortlist.
- Adding context to chunks reduced retrieval failures substantially in Anthropic's tests.
- Rewrite conversational queries; filter by metadata and permissions.
- RRF merges by position, so keyword and similarity scores never need converting.
- Filter by permission before searching; asking the model to keep a secret is not a control.