Level 2 Agentic Coding · Building with AI
Advanced RAG
The techniques that take a RAG prototype to production quality. Better chunking, hybrid keyword-plus-vector search fused with reciprocal rank fusion, reranking, query rewriting and contextual retrieval, and how to measure retrieval with recall@k and MRR so you know which ones help.
- Level
- ●●●●● Intermediate
- Reading
- 16 min
- To learn it well
- 1.5 hours to read, a few days to apply
- Builds on
- 11 concepts →
- Quiz
- 5 questions ↓
This leads to
—The full path from zero — 11 concepts before this one
- What Is AI?
- Vectors
- Python for AI
- How Machines Learn
- Dot Product, Norms and Similarity
- Large Language Models, Explained Simply
- Using LLM APIs
- Prompt Engineering
- Embeddings and Semantic Search
- Retrieval-Augmented Generation
- Vector Databases
- Advanced RAG
Read them roughly in this order. See it on the concept map →
Why it matters
A basic RAG system takes an afternoon to build and works impressively on the first ten questions. Then real users arrive. They search for "E-4021" and get the page about "E-4012". They ask "and what about plums?" as a follow-up. They type "my pages come out pale" when the manual says "faded prints". A chunk reads "It must be returned within 14 days", and nothing says what "it" is. Each failure has the same root: the right passage never reached the model.
Retrieval quality caps answer quality. No prompt and no model can answer from a passage it never saw. This chapter covers the techniques that fix the common retrieval failures, roughly in the order you should try them, and, most importantly, how to measure retrieval so you can tell which ones help on your data. Many of them cost little: Anthropic reported that combining contextual embeddings, keyword search and reranking cut retrieval failures by 67% in its experiments.
The intuition
Think of hiring for a job with 5,000 applicants. You can't interview everyone, so you work in stages. A fast screen (keywords on the CV, a quick read of the summary) cuts 5,000 to 100, and its only job is not to throw out good candidates. Then careful interviews rank those 100, and the top 5 get offers. A better screen uses two independent screeners, one checking for specific qualifications and one judging general fit, and keeps anyone either likes.
Production retrieval works the same way:
- Stage 1, recall. Cheap retrievers cast a wide net: keyword search catches exact terms, vector search catches meanings, and their results are merged. Goal: the right passage is somewhere in the top 50 to 150.
- Stage 2, precision. A slower, more accurate reranker reads each candidate together with the query and reorders them. Goal: the right passage is in the top 5 to 20 that go to the LLM.
Around that core sit two more ideas: fix the chunks so each one can be found and understood on its own, and fix the query so it matches how the documents are written.
Key idea Retrieve broadly with complementary methods (keywords and vectors), merge the lists, rerank precisely, and measure recall@k on real questions after every change. Most RAG quality problems are retrieval problems.
How it works
Better chunks
Basic RAG cuts documents into fixed-size windows. Better strategies:
- Structure-aware splitting. Split on headings, then paragraphs, then sentences, only falling back to a hard cut when a piece is still too long. Many libraries call this recursive splitting. Tables, code blocks and list items stay whole.
- Semantic chunking. Embed each sentence and start a new chunk where the topic shifts, that is, where the similarity between neighbouring sentences drops.
- Small-to-big, or parent-document retrieval. Index small chunks (a few sentences) because they match queries precisely, but when one is retrieved, send its larger parent section to the LLM, because it reads better in context. A variant, sentence-window retrieval, returns the matched sentence plus a few sentences either side.
- Headings as context. Prefix each chunk with its document title and section path ("Printer manual › Troubleshooting › Error codes"). Cheap, and often a large win.
There is no universally best chunk size. Test two or three sizes on your evaluation set (below).
Hybrid search: keywords plus vectors
Dense embeddings (Embeddings and Semantic Search) are good at meaning but blur exact strings. "E-4012" and "E-4021" look nearly identical to an embedding model. Keyword search is the opposite: exact, but blind to synonyms. Hybrid search runs both and merges the results.
The standard keyword method is BM25 ("best matching 25"), a refined TF-IDF. A document's score for a query adds up, over each query word :
In words:
- rewards rare words. is the number of documents and how many contain . With and , IDF . A word in every document scores near zero.
- is how often appears in document . The fraction saturates: with the usual , one occurrence in an average-length document gives , and two occurrences give , not 2. Repeating a word doesn't keep paying.
- is the document's length relative to the average, and controls how much long documents are penalised, since they contain more words by chance.
Merging lists: reciprocal rank fusion
BM25 scores and cosine similarities are on different scales, so you can't simply add them. Reciprocal rank fusion (RRF, Cormack, Clarke and Büttcher, 2009) ignores the scores and uses only the ranks:
Each list contributes for document , with by convention. The constant damps the difference between rank 1 and rank 2, so no single list dominates.
Worked example. Document A is ranked 1st by BM25 and 5th by vectors: . Document B is 2nd in both: . B wins narrowly: a document both methods like beats one that only one method loves. A document found by only one list still gets its share, so nothing either method found well is lost.
Many vector databases (Weaviate, Qdrant, Elasticsearch, OpenSearch and others) offer hybrid search with RRF built in. With pgvector you can combine it with PostgreSQL's own full-text search.
Reranking
The embedding search in Embeddings and Semantic Search uses a bi-encoder: query and document are embedded separately, so document vectors can be computed in advance. That is fast, but the model never sees the query and document together. A cross-encoder takes the query and one document together as input and outputs a relevance score. Because every word of the query can attend to every word of the document (Attention), it judges relevance much more accurately. It is also far slower, since nothing can be precomputed, which is why it is used only to rerank a shortlist.
Reranking means: retrieve 50 to 150 candidates with the fast methods, score each (query, candidate) pair with a cross-encoder, and keep the top 5 to 20. Options include hosted reranking APIs (Cohere, Voyage and others), open cross-encoder models from the sentence-transformers family, and simply asking an LLM to rank or score the candidates. ColBERT sits between the two approaches: it keeps one vector per token and matches token to token, giving much of a cross-encoder's accuracy at closer to a bi-encoder's speed.
Rewriting the query
Users' questions are often a poor match for how documents are written. Query rewriting uses an LLM to transform the query before retrieval:
- Conversation condensing. In a chat, "and what about plums?" means nothing alone. Rewrite it, using the conversation history, into "When should I prune plum trees?" before searching. Every chat-based RAG system needs this.
- Multi-query. Generate three to five paraphrases, retrieve for each, and fuse the lists with RRF. This catches different vocabularies ("pale prints", "faded output", "light printing").
- Decomposition. Split "Which of our two plans includes phone support, and how much more does it cost?" into separate sub-questions, as in least-to-most prompting.
- HyDE (hypothetical document embeddings, Gao et al., 2022). Ask the LLM to write a plausible answer, then embed that and search with it. An answer looks more like the documents than the question does, even if its details are wrong.
Each rewrite costs an LLM call and adds latency, so use a small, fast model and measure the gain.
Contextual retrieval
A chunk often depends on its document for meaning. "The company's revenue grew by 3% over the previous quarter" doesn't say which company or which quarter, so neither embeddings nor BM25 can match it to a question about them. Contextual retrieval (Anthropic, September 2024) fixes this at indexing time: for every chunk, an LLM reads the whole document and writes a short context, typically 50 to 100 tokens, that situates the chunk ("This chunk is from ACME Corp's Q2 2023 report; the previous quarter's revenue was…"). The context is prepended to the chunk before both embedding and BM25 indexing.
Anthropic measured the retrieval failure rate (the share of questions whose relevant chunk was not in the top 20) across several datasets:
Generating context for every chunk sounds expensive, but each chunk's request repeats the same document, so prompt caching makes it cheap. Anthropic estimated about $1.02 per million document tokens with its small model at the time. You pay once, at indexing.
Evaluating retrieval
Without measurement, every technique above is a guess. Build a retrieval evaluation set: 50 to 200 real or realistic questions, each labelled with the chunk or chunks that answer it. You can draft questions with an LLM from your own chunks and then check them by hand. Then compute:
- Recall@k: the fraction of questions whose relevant chunk appears in the top (the same idea as in Vector Databases, but measured against human labels). Pick equal to the number of chunks you send to the LLM. This is the most important number.
- Mean reciprocal rank (MRR): the average of of the first relevant chunk, counting 0 when it is not found. It rewards putting the right chunk near the top.
Worked example. Four questions whose relevant chunks are found at ranks 1, 3, 2 and not at all: recall@3 = 3/4 = 0.75, and MRR = (1 + 1/3 + 1/2 + 0)/4 = 0.46.
Retrieval metrics tell you whether the right text reached the model. End-to-end metrics tell you whether the answer was good: faithfulness (is every claim supported by the retrieved text?) and answer relevance (does it answer the question?), usually scored by an LLM judge (Evaluating LLM Applications). Tools such as Ragas package these. Track both. They point at different fixes.
In code
A runnable comparison of BM25, a second retriever and their hybrid with RRF, evaluated with recall@3 and MRR on eight labelled questions about a printer manual. BM25 is written from scratch. The second retriever is character n-gram TF-IDF, an offline stand-in for a dense embedding model that, like embeddings, is forgiving of different word forms. Swap in real embeddings and you have production-shaped code.
import math
import re
from collections import Counter
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
chunks = [
"Error E-4012 means the printer's paper tray is empty. Refill it and press resume.", # 0
"Error E-4021 means the ink cartridge is not recognised. Reseat the cartridge.", # 1
"To connect the printer to Wi-Fi, hold the wireless button for five seconds.", # 2
"The printer goes to sleep after 15 minutes without use to save energy.", # 3
"Paper jams usually happen when the tray is overfilled. Remove loose sheets gently.", # 4
"Replacing cartridges: open the front cover and wait for the carriage to stop.", # 5
"Printing from a phone works through the companion app over wireless networks.", # 6
"The warranty covers manufacturing faults for two years from purchase.", # 7
"Faded prints often mean the print head needs cleaning from the maintenance menu.", # 8
"Energy saving: the sleeping printer wakes when a job arrives.", # 9
]
tests = [ # (query, index of the relevant chunk)
("E-4021", 1), ("error E-4012", 0), ("how do I set up wireless printing", 2),
("printer keeps switching itself off", 3), ("my pages come out pale", 8),
("paper stuck inside", 4), ("change ink cartridge", 5), ("print from my mobile", 6),
]
tok = lambda s: re.findall(r"[a-z0-9-]+", s.lower())
docs = [tok(c) for c in chunks]
N, avgdl = len(docs), sum(map(len, docs)) / len(docs)
df = Counter(t for d in docs for t in set(d))
def bm25(query, k1=1.5, b=0.75):
scores = np.zeros(N)
for t in tok(query):
if t not in df:
continue
idf = math.log(1 + (N - df[t] + 0.5) / (df[t] + 0.5))
for i, d in enumerate(docs):
f = d.count(t)
scores[i] += idf * f * (k1 + 1) / (f + k1 * (1 - b + b * len(d) / avgdl))
return list(np.argsort(-scores))
# Stand-in for a dense retriever: character n-gram TF-IDF (forgiving of word forms).
vec = TfidfVectorizer(analyzer="char_wb", ngram_range=(3, 5)).fit(chunks)
M = vec.transform(chunks).toarray()
dense = lambda q: list(np.argsort(-(M @ vec.transform([q]).toarray()[0])))
def rrf(*rankings, k=60):
fused = Counter()
for ranking in rankings:
for rank, doc in enumerate(ranking, start=1):
fused[doc] += 1 / (k + rank)
return [doc for doc, _ in fused.most_common()]
hybrid = lambda q: rrf(bm25(q), dense(q))
def evaluate(name, retriever, k=3):
ranks = [retriever(q).index(rel) + 1 for q, rel in tests]
recall = np.mean([r <= k for r in ranks])
mrr = np.mean([1 / r for r in ranks])
print(f"{name:7s} recall@{k} {recall:.2f} MRR {mrr:.2f} ranks {ranks}")
for name, r in [("bm25", bm25), ("dense", dense), ("hybrid", hybrid)]:
evaluate(name, r)
# bm25 recall@3 0.75 MRR 0.56 ranks [1, 1, 2, 3, 9, 1, 6, 3]
# dense recall@3 0.88 MRR 0.64 ranks [1, 1, 2, 1, 10, 2, 2, 2]
# hybrid recall@3 0.88 MRR 0.60 ranks [1, 1, 2, 2, 10, 1, 3, 3]
Read the per-question ranks, not just the averages. BM25 is best on "paper stuck inside" (rank 1) but poor on "change ink cartridge" (rank 6), because "change" and "cartridge" don't literally match "Replacing cartridges". The n-gram retriever is the reverse. The hybrid is never far behind whichever retriever happens to be better for a given question, without knowing in advance which one that is. That robustness is why hybrid search is a sensible default. Note also the fifth question: "pale" versus "faded" is pure synonymy, and every retriever here ranks the answer 9th or 10th. Only a real embedding model, or query rewriting, fixes that. Small test sets like this one are for understanding. Decisions need 50 or more questions.
Reranking the hybrid shortlist with an open cross-encoder (pip install sentence-transformers):
from sentence_transformers import CrossEncoder
reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")
def rerank(query, candidate_ids, top=3):
scores = reranker.predict([(query, chunks[i]) for i in candidate_ids])
order = np.argsort(-scores)
return [candidate_ids[j] for j in order[:top]]
best = rerank("my pages come out pale", hybrid("my pages come out pale")[:10])
Contextual retrieval with Anthropic's SDK: the whole document is marked for prompt caching, so it is paid for in full only once however many chunks it has:
import anthropic
client = anthropic.Anthropic()
def situate(document, chunk):
response = client.messages.create(
model="claude-haiku-5-5",
max_tokens=1000,
output_config={"effort": "low"},
messages=[{"role": "user", "content": [
{"type": "text", "text": f"<document>\n{document}\n</document>",
"cache_control": {"type": "ephemeral"}}, # reused for every chunk
{"type": "text", "text": f"Here is a chunk from the document:\n<chunk>\n{chunk}\n"
"</chunk>\nWrite a short context (one or two sentences) that situates this chunk "
"within the document, to improve search retrieval. Reply with the context only."},
]}],
)
context = next(b.text for b in response.content if b.type == "text")
return f"{context}\n{chunk}" # embed and BM25-index this instead
Common pitfalls
- Adding techniques without measuring. Each technique adds cost, latency and moving parts. Some will not help on your data. Keep a retrieval evaluation set and run it after every change.
- Evaluating only end-to-end. A good final answer can hide weak retrieval (the model guessed from memory), and a bad one can come from good retrieval. Measure retrieval separately.
- A test set the developer wrote. Questions written while looking at the documents reuse their vocabulary and flatter keyword search. Use real user questions as soon as you have them.
- Forgetting the follow-up question. Chat RAG without query condensing fails on every "what about…?".
- Reranking too few candidates. A reranker can only reorder what stage 1 found. If the right chunk isn't in the top 50, reranking can't help, so check recall at the shortlist size too.
- Mismatched tokenisation in BM25. "E-4012", "E4012" and "e-4012" must be normalised the same way at index and query time.
Watch out LLM-generated evaluation questions are a useful start but systematically too easy: a model writing a question while reading a chunk tends to copy the chunk's wording. Collect real questions from users, especially failed ones, and add them to the test set over time.
Where it leads
- Context Engineering and Memory: retrieval as one part of deciding what enters the context window, including memory and prompt caching.
- AI Agents and Tool Use and Function Calling: agentic retrieval, where the model issues searches itself, reads results and searches again.
- Evaluating LLM Applications: LLM-as-judge for faithfulness and relevance, regression testing and tracing.
- Building AI Products: latency and cost budgets for multi-stage retrieval.
- Sentence Embeddings: how bi-encoders and cross-encoders are trained.
A bit of history
Keyword ranking came first. BM25 grew out of Stephen Robertson and Karen Spärck Jones's probabilistic retrieval work, and the name comes from the Okapi system's experiments at City University London in the early 1990s. It is still a strong baseline. Reciprocal rank fusion was published by Cormack, Clarke and Büttcher in 2009, as a simple way to combine search systems that beat more complex methods. Learned reranking with BERT cross-encoders (Nogueira and Cho, 2019) brought a large jump on the MS MARCO passage-ranking benchmark, and ColBERT (2020) found a middle path between bi- and cross-encoders. HyDE appeared in late 2022. When RAG became the standard LLM architecture in 2023, practitioners rediscovered these information-retrieval tools and combined them with LLM-specific tricks: query rewriting, contextual retrieval (2024) and agentic search.
Try it
- In the code, add three test questions of your own, including one with an exact code or number and one that uses a synonym. Which retriever wins each?
- Implement multi-query: write three paraphrases of "my pages come out pale" by hand (pretend an LLM wrote them), retrieve with
hybridfor each, and fuse the four lists withrrf. Does the rank of chunk 8 improve?- Give the BM25 list double weight in the fusion (add
2 / (k + rank)for it instead of1 / (k + rank)). Which questions move up or down? When would you want to weight keywords more heavily?Hint for 2: a paraphrase like "faded printing" shares a word with chunk 8. With the original query plus three paraphrases, chunk 8 rises from 10th to around 5th, and a reranker could then lift it further.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Introducing Contextual Retrieval
Prepend a short, model-written context to each chunk before embedding and BM25 indexing. Measured retrieval-failure reductions for each added step, with a cookbook.
Building and Evaluating Advanced RAG
Sentence-window and auto-merging retrieval, and the RAG triad (context relevance, groundedness, answer relevance) for evaluating them.
Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods
A two-page SIGIR paper introducing reciprocal rank fusion, the simple formula most hybrid-search systems use to merge keyword and vector results.
Precise Zero-Shot Dense Retrieval without Relevance Labels (HyDE)
Ask a model to write a hypothetical answer, embed that, and search with it. A query-rewriting trick that needs no training data.
Ragas
An open-source library for evaluating RAG pipelines, with metrics for context precision and recall, faithfulness and answer relevance.
ColBERT: Efficient and Effective Passage Search via Contextualized Late Interaction over BERT
Keeps one vector per token and scores documents by matching tokens to tokens. Sits between fast bi-encoders and accurate cross-encoder rerankers.
Claude Cookbooks
Runnable notebooks for real tasks with Claude: RAG, contextual retrieval, structured JSON, tool use, prompt caching, sub-agents and more.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/building/advanced-rag.md