◆ AI All-in-One

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
↗ Plan a path here

Read first

Retrieval-Augmented GenerationVector Databases

This leads to

—
The full path from zero — 11 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Python for AI
  4. How Machines Learn
  5. Dot Product, Norms and Similarity
  6. Large Language Models, Explained Simply
  7. Using LLM APIs
  8. Prompt Engineering
  9. Embeddings and Semantic Search
  10. Retrieval-Augmented Generation
  11. Vector Databases
  12. 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.
Query Keyword (BM25) exact terms, codes 1. doc A 2. doc B 3. doc C 4. doc D Vector search meaning, synonyms 1. doc C 2. doc A 3. doc E 4. doc B Reciprocal rank fusion score = Σ 1 / (60 + rank) A: 1/61 + 1/62 = 0.0325 C: 1/63 + 1/61 = 0.0323 B: 1/62 + 1/64 = 0.0318 E: 1/63 = 0.0159 D: 1/64 = 0.0156 liked by both lists → top; found by one → still kept Reranker cross-encoder reads query + each doc top few → LLM e.g. 150 in, 20 out Stage 1 (fast, broad): don't miss the right passage. Stage 2 (slow, precise): put it at the top.
Fig. 1 Hybrid search with reciprocal rank fusion. Keyword search (BM25) and vector search each return a ranked list. Each document scores 1/(60 + rank) in each list, and the scores are added. A document ranked well by both rises to the top. A reranker then reorders the fused candidates before the best few 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 tt:

score(t,d)=IDF(t)⋅f(t,d) (k1+1)f(t,d)+k1(1−b+b ∣d∣avgdl)\text{score}(t, d) = \text{IDF}(t) \cdot \frac{f(t,d)\,(k_1 + 1)}{f(t,d) + k_1 \left(1 - b + b \,\frac{\lvert d \rvert}{\text{avgdl}}\right)}

In words:

  • IDF(t)=ln⁡ ⁣(1+N−nt+0.5nt+0.5)\text{IDF}(t) = \ln\!\left(1 + \frac{N - n_t + 0.5}{n_t + 0.5}\right) rewards rare words. NN is the number of documents and ntn_t how many contain tt. With N=10N = 10 and nt=2n_t = 2, IDF =ln⁡(1+8.5/2.5)=ln⁡4.4=1.48= \ln(1 + 8.5/2.5) = \ln 4.4 = 1.48. A word in every document scores near zero.
  • f(t,d)f(t,d) is how often tt appears in document dd. The fraction saturates: with the usual k1=1.5k_1 = 1.5, one occurrence in an average-length document gives 1×2.5/(1+1.5)=1.01 \times 2.5 / (1 + 1.5) = 1.0, and two occurrences give 2×2.5/(2+1.5)=1.432 \times 2.5/(2 + 1.5) = 1.43, not 2. Repeating a word doesn't keep paying.
  • ∣d∣/avgdl\lvert d \rvert / \text{avgdl} is the document's length relative to the average, and b=0.75b = 0.75 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:

RRF(d)=∑lists r1k+rankr(d)\text{RRF}(d) = \sum_{\text{lists } r} \frac{1}{k + \text{rank}_r(d)}

Each list rr contributes 1/(k+rank)1/(k + \text{rank}) for document dd, with k=60k = 60 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: 1/61+1/65=0.03181/61 + 1/65 = 0.0318. Document B is 2nd in both: 1/62+1/62=0.03231/62 + 1/62 = 0.0323. 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:

Standard embeddings 5.7% Contextual embeddings 3.7% (−35%) + contextual BM25 2.9% (−49%) + reranking 1.9% (−67%) 0% 1% 2% 3% 4% 5% 6% retrieval failure rate: relevant chunk not in the top 20 (lower is better) Source: Anthropic, "Introducing Contextual Retrieval" (2024), averaged over its test datasets. Each row adds a technique to the row above.
Fig. 2 Retrieval failure rates reported by Anthropic for contextual retrieval: 5.7% with standard embeddings, 3.7% with contextual embeddings, 2.9% adding contextual BM25, and 1.9% adding reranking. That is a 67% reduction overall.

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 kk (the same idea as in Vector Databases, but measured against human labels). Pick kk equal to the number of chunks you send to the LLM. This is the most important number.
  • Mean reciprocal rank (MRR): the average of 1/rank1/\text{rank} 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

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

  1. 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?
  2. Implement multi-query: write three paraphrases of "my pages come out pale" by hand (pretend an LLM wrote them), retrieve with hybrid for each, and fuse the four lists with rrf. Does the rank of chunk 8 improve?
  3. Give the BM25 list double weight in the fusion (add 2 / (k + rank) for it instead of 1 / (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.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Users searching for error code "E-4021" keep getting the page about "E-4012" from your embedding-only RAG system. Which change most directly fixes this?

  2. With reciprocal rank fusion (k = 60), document A is ranked 1st by BM25 and 5th by vector search; document B is 2nd in both. Which ranks higher after fusion?

  3. Why is a cross-encoder used only to rerank a shortlist rather than to search the whole collection?

  4. Four test questions have their relevant chunk at ranks 1, 3, 2 and not found. What are recall@3 and MRR?

  5. In a chat-based RAG app, a user asks "and what about plums?" after a question about pruning apple trees, and retrieval returns nothing useful. What is the fix?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Article

Introducing Contextual Retrieval

Anthropic · 2024 · Intermediate · Free

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.

Course

Building and Evaluating Advanced RAG

Jerry Liu & Anupam Datta (DeepLearning.AI with LlamaIndex and TruEra) · Intermediate · Free

Sentence-window and auto-merging retrieval, and the RAG triad (context relevance, groundedness, answer relevance) for evaluating them.

Tool

Ragas

Exploding Gradients · Intermediate · Free

An open-source library for evaluating RAG pipelines, with metrics for context precision and recall, faithfulness and answer relevance.

Tutorial

Claude Cookbooks

Anthropic · Intermediate · Free

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