CONTENTS
CHAPTER 5

Retrieval systems

8 MIN READ

A model's knowledge is frozen at training time and doesn't include your private data. Retrieval-augmented generation (RAG) fixes both: fetch relevant information at request time and put it in the context. The essay What We Learned from a Year of Building with LLMs puts the priority plainly: prefer RAG over fine-tuning for giving a model new knowledge. It's cheaper, updates instantly, and lets you show sources.

But RAG has a reputation for being easy to demo and hard to get right. The reason is that RAG is really two systems: a search engine and a writer. Most failures come from the search engine, and most teams spend their time tuning the writer.

Retrieval first

Jason Liu, who has spent years consulting on RAG systems and teaches the course "Systematically Improving RAG Applications", has one central piece of advice in "The RAG Playbook" (2024): get your retrieval working first. If the right document never reaches the context, no prompt can save the answer.

That means measuring retrieval on its own, with the classic search metrics:

  • Recall@k: of the documents that should be found, what fraction appear in the top kk results?
  • Precision@k: of the top kk results, what fraction are actually relevant?
  • MRR (mean reciprocal rank): on average, how high does the first relevant result appear?

Liu argues that recall usually matters more than precision for RAG, because modern models are fairly good at ignoring an irrelevant chunk, but they can't use one that isn't there. (Chroma's context rot findings are a reminder not to push this too far: distractors do hurt.)

How do you get test data before you have users? Liu's suggestion: generate synthetic questions from your own chunks. For each chunk, ask a model to write a question that this chunk answers. Now you have (question, correct chunk) pairs, and you can measure recall in minutes. Later, replace them with real user questions from your logs.

def recall_at_k(pairs, search, k=10):
    hits = 0
    for question, expected_chunk_id in pairs:
        results = search(question, limit=k)
        if expected_chunk_id in [r.id for r in results]:
            hits += 1
    return hits / len(pairs)

That loop is the most valuable twenty lines in a RAG project. Run it every time you change chunking, embeddings or search settings.

The pipeline

A RAG system has an offline half (indexing) and an online half (querying).

 OFFLINE                                         ONLINE
 documents                                        user question
    │                                                 │
    ▼                                                 ▼
 parse & clean ─► chunk ─► add context          query understanding
                       │                        (rewrite, filter, route)
              ┌────────┴────────┐                     │
              ▼                 ▼               ┌─────┴──────┐
         embed (dense)    index terms (BM25)    ▼            ▼
              │                 │           vector search  keyword search
              ▼                 ▼               └─────┬──────┘
         vector index      inverted index        fuse (RRF)
                                                      │
                                                   rerank
                                                      │
                                              top chunks ─► prompt ─► answer + citations

Let's walk through each stage and the decisions in it.

Parsing and chunking

Parsing is unglamorous and decides a lot. PDFs with tables, slides, scanned pages and HTML with navigation menus all need cleaning. Garbage text in the index means garbage results. Look at your parsed output with your own eyes before anything else.

Chunking splits documents into pieces small enough to retrieve precisely. The trade-off: small chunks match precisely but lose surrounding meaning; large chunks keep meaning but match vaguely and waste context. Practical defaults:

  • Split on structure (headings, sections, paragraphs) rather than fixed character counts.
  • Keep chunks a few hundred tokens, with a little overlap.
  • Store metadata with each chunk: source, title, section path, date, version, access permissions.

Concept deep dive: embeddings, BM25 and why you want both

There are two fundamentally different ways to find relevant text.

Lexical search (BM25). BM25 is a decades-old scoring formula used by classic search engines. It scores a document by how often the query's words appear in it, weighting rare words more (a match on "PagedAttention" matters more than a match on "the") and normalizing for document length. It's exact: great for names, error codes, product SKUs and jargon. It's also literal: "car" doesn't match "automobile".

Semantic search (dense embeddings). An embedding model turns text into a vector, a list of numbers, such that texts with similar meanings land near each other. You embed every chunk once, embed the query at request time, and find the nearest vectors. It matches meaning ("how do I get my money back" finds the refund policy) but can miss exact identifiers, because "error E4021" and "error E4012" look nearly identical in meaning-space.

Each covers the other's blind spot. That's why What We Learned from a Year of Building with LLMs reports that hybrid keyword-plus-embedding retrieval often works best, and why Anthropic's experiments (below) found the same.

How nearest-neighbour search scales. Comparing a query to millions of vectors one by one is too slow, so vector databases use approximate nearest-neighbour indexes. The most common is HNSW (Hierarchical Navigable Small World, Malkov and Yashunin). Picture a set of road maps at different zoom levels: a sparse highway map on top, denser local maps below. Search starts on the highway map, greedily moves toward the query, drops a level, and repeats. It finds very good (though not guaranteed perfect) neighbours in roughly logarithmic time. The word "approximate" matters: the index trades a little recall for a lot of speed, and its parameters let you tune that trade.

Fusing two result lists. How do you merge a BM25 ranking and a vector ranking whose scores aren't comparable? The standard answer is Reciprocal Rank Fusion (Cormack, Clarke and Büttcher, SIGIR 2009). Ignore the scores; use only the ranks:

RRF(d)=∑r∈rankers1k+rankr(d)\text{RRF}(d) = \sum_{r \in \text{rankers}} \frac{1}{k + \text{rank}_r(d)}

with k=60k = 60, a constant the authors fixed in a pilot study and found near-optimal but not critical. A document ranked 1st by one system and 3rd by the other scores 1/61+1/631/61 + 1/63. It's simple, needs no tuning, and is hard to beat.

Reranking

Embedding search uses a bi-encoder: the query and the document are embedded separately, which is what makes precomputing an index possible. But encoding them separately means the model never looks at the two together.

A cross-encoder reads the query and a candidate document together and outputs a relevance score. It's much more accurate and much slower, because nothing can be precomputed. So you use both: retrieve broadly and cheaply with the bi-encoder and BM25 (say the top 100–150), then rerank that shortlist with a cross-encoder and keep the best 10–20. The Sentence-Transformers documentation describes exactly this retrieve-then-rerank pattern.

Contextual retrieval: a case study in measured improvement

In September 2024 Anthropic published "Introducing Contextual Retrieval", which is worth studying as much for its method as its result.

The problem: chunks lose their context. A chunk that says "revenue grew 3% over the previous quarter" doesn't say which company or which quarter, so neither BM25 nor embeddings can match it to a question that names them.

The fix: before indexing, use a model to write a short (usually 50–100 token) description that situates each chunk within its whole document, and prepend it to the chunk for both embedding and BM25. With prompt caching on the full document, they estimated the one-time cost at $1.02 per million document tokens.

Their results, measured as the rate at which the right chunk was missing from the top 20:

Configuration Retrieval failure rate Reduction
Embeddings only (baseline) 5.7%
+ contextual embeddings 3.7% 35%
+ contextual BM25 (hybrid) 2.9% 49%
+ reranking 1.9% 67%

Notice the shape: three independent, stacked improvements, each measured. They also tested passing 5, 10 and 20 chunks to the model and found 20 worked best, with a caveat that more information can also distract. And they added a note that's easy to miss: if your whole knowledge base is under about 200,000 tokens (roughly 500 pages), you may not need RAG at all. Put it all in the prompt and use prompt caching.

Key insight: "Should I use RAG?" has a size threshold. Below a few hundred pages, try the whole corpus in context with caching first. RAG earns its complexity when the corpus is large, changes often, or has per-user permissions.

Query understanding

Users write bad queries: vague, conversational, full of pronouns that refer to earlier turns. Several techniques sit between the user and the index:

  • Rewriting. Have a small model turn "what about the other one?" into a standalone query using the conversation history. This is the single most common fix in chat-based RAG.
  • Decomposition. Split "compare our 2024 and 2025 refund policies" into two searches.
  • Filtering. Extract structured filters (date range, product, version) and apply them as metadata filters before or alongside vector search. This is often more effective than any embedding trick.
  • Routing. Decide which index or tool to use: docs, tickets, a SQL database. Some questions ("how many orders shipped last week") need a database query, not document retrieval.
  • HyDE. Gao and colleagues (2022) had a model write a hypothetical answer, then embedded that and searched for real documents near it. Answers look more like documents than questions do, so they land in a better part of embedding space. Useful when queries and documents are worded very differently; measure before adopting.

Agentic retrieval

All of the above is a fixed pipeline: one query, one search, one answer. An alternative is to give an agent search tools and let it search, read, refine and search again. Coding agents do this with grep and file reads, and research agents with web search.

Agentic retrieval handles multi-step questions that a single search can't answer, at the cost of latency, tokens and predictability. A sensible design does one good retrieval pass up front (for speed on easy questions) and lets the model call search tools for more when it needs them, which is the hybrid Anthropic's context engineering post recommends.

Generation: citations and refusal

The writer half has two jobs beyond writing well.

Cite sources. Ask the model to attach chunk IDs to claims, then verify in code that each cited ID was actually in the context. Citations let users check answers and let you measure faithfulness: does the answer say only what the sources support?

Say "I don't know". Tell the model explicitly what to do when the retrieved text doesn't answer the question, and test it with questions you know the corpus can't answer. A RAG system that never refuses will make things up.

Common confusions and failures

  • Stale index. Documents change; the index doesn't. Design incremental re-indexing and track document versions.
  • Permission leaks. If a user can't read a document, retrieval must never return it. Filter by access rights in the search query, not after generation.
  • Tuning the prompt when retrieval is broken. Check recall first. Always.
  • One chunk size for everything. Code, FAQs, legal contracts and chat logs need different chunking.
  • Blaming the embedding model first. Parsing, chunking, metadata filters and hybrid search usually matter more than switching embedding providers.

Key takeaways

  • RAG is a search engine plus a writer. Fix and measure the search engine first (recall@k on synthetic, then real, questions).
  • Use hybrid search: BM25 for exact terms, embeddings for meaning, merged with Reciprocal Rank Fusion.
  • Retrieve broadly, then rerank a shortlist with a cross-encoder.
  • Situate chunks in their documents (contextual retrieval cut failures by up to 67% in Anthropic's tests).
  • For small corpora, try putting everything in context with caching before building RAG.
  • Rewrite queries, extract filters, cite sources, and handle "not found".

Exercises

  1. Build a 50-question synthetic eval for a document set you have. Measure recall@5 and recall@20 for embeddings alone, then BM25 alone, then hybrid with RRF.
  2. Compute RRF scores by hand for three documents, where ranker A orders them (X, Y, Z) and ranker B orders them (Z, X, Y). Which wins?
  3. Design the permission model for RAG over a company's Google Drive, where each user sees different files. Where exactly is access enforced?