Retrieval-Augmented Generation

Give the model the right facts at question time, and know which half to fix when it still gets things wrong.

Lesson 6 · Previews Chapter 6, first half · about 20 min

Your win today When a RAG app gives a bad answer, you'll be able to tell whether retrieval or generation failed, measure it with context precision and recall, and pick the retrieval fix: hybrid search, chunking, reranking, query rewriting or contextual retrieval.

Warm-up · spaced review

1 · Why retrieve at all?

RAG retrieves the information relevant to this query from an external source (your docs, a database, the web, past chats) and puts it in the prompt. The term comes from Lewis et al. (2020), who found that it produces more detailed answers and fewer hallucinations. Huyen calls it per-query context construction, the AI-engineering equivalent of feature engineering. Ch6 · RAG

Will huge context windows make RAG obsolete? Huyen says no, for two reasons. Data keeps growing faster than context windows. And models use long context badly: remember the lost middle from Lesson 5, plus every extra token costs money and time. But for small knowledge bases, skip RAG at first. Anthropic's guidance for Claude, which Huyen quotes, is that under about 200K tokens (roughly 500 pages) you can put the whole knowledge base in the prompt. Ch6 · RAG, Note

INDEXING (ahead of time) Documents Split into chunks Index QUERYING (per request) User query Retriever Generatorquery + top-k Answer fetch top-k chunks A RAG system is only as good as its retriever. If the right chunk isn't fetched, the generator can't use it.

2 · Two ways to retrieve

Term-based retrieval matches words. TF-IDF weights a term up when it appears often in a document (term frequency) and down when it appears in many documents (inverse document frequency), so “for” counts for nothing and “Vietnamese” counts for a lot. BM25 adds a correction for document length. Elasticsearch serves this kind of search from an inverted index, a map from each term to the documents that contain it. Ch6 · Term-based retrieval

Embedding-based retrieval matches meaning. Each chunk is embedded once and stored in a vector database. Each query is embedded with the same model, and the database returns the k nearest vectors. Exact nearest-neighbor search is slow at scale, so real systems use approximate search (ANN) algorithms such as HNSW or IVF. You'll pick a library rather than write one. Ch6 · Embedding-based retrieval

Term-based (BM25)Embedding-based
Speed and costMuch faster and cheaperEmbedding and vector search add latency; vector DB bills can reach ⅕–½ of model-API spend
QualityStrong out of the box, hard to improve; confused by ambiguous termsCan beat BM25 with finetuning; handles natural phrasing
Blind spotSynonyms and paraphrasesExact strings such as error codes and product names

So production systems combine them in a hybrid search. There are two ways. In sequence: a cheap retriever fetches candidates and a precise one reranks them. In parallel: run both and merge the rankings with reciprocal rank fusion, where each retriever contributes 1/rank, so a document ranked 1st by one and 2nd by the other scores 1 + 0.5 = 1.5 in the simplified version. Ch6 · Combining retrieval algorithms

3 · Try it: a real BM25 retriever

Below is a support knowledge base for a fictional robot company, searched with the actual BM25 formula. Click a preset query and predict what comes first before you look. Top-3 results count as “retrieved.” For presets, the widget knows which articles are truly relevant and computes the two retrieval metrics. Context precision asks what share of what you retrieved is relevant. Context recall asks what share of the relevant documents you retrieved. Ch6 · Comparing retrieval algorithms

What did you just see? (open after the challenges)

4 · Making retrieval better

Precision and recall don't cost the same to measure. Precision only needs a judge to look at what was retrieved. Recall needs every document labeled for every test query, so in production many teams track only precision. As in Lesson 4, evaluate retrieval and the final answer separately, and for embedding search, also the embeddings themselves. Ch6 · Comparing retrieval algorithms

TacticWhat it doesHuyen's example
ChunkingSplit by size or recursively (sections, then paragraphs, then sentences), with a little overlap. Smaller chunks mean more variety fits in the context, but also more vectors to store, and context can be lost.“I left my wife a note” split into “I left my wife” + “a note.”
RerankingReorder candidates with a more precise (or recency-aware) scorer, then keep only what fits.Chat-with-your-email ranks recent threads higher.
Query rewritingHave a model turn a context-dependent turn into a standalone query.“How about Emily Doe?” → “When did Emily Doe last buy something?”
Contextual retrievalAdd to each chunk the context it lacks: tags, the questions it answers, a 50–100-token summary of where it sits in the document.Anthropic's method, which cut retrieval failures by up to 67% when combined with reranking.

Sources: Ch6 · Retrieval Optimization; Anthropic, “Introducing Contextual Retrieval” (2024).

Practice: each problem has one best first fix.

Beyond text

RAG isn't only for documents. Multimodal RAG retrieves images too, by caption or with a joint text-image embedding model such as CLIP. Tabular RAG works differently. For “How many Fruity Fedoras sold in the last 7 days?” the system writes SQL from the table schema (text-to-SQL), executes it, and then generates the answer from the result. Retrieval becomes a tool call, which is exactly where agents begin (Lesson 7). Ch6 · RAG Beyond Texts

Check yourself

Primary source

Read next: Huyen, AI Engineering, Chapter 6, the RAG half, up to “Agents.” Read “RAG,” “RAG Architecture,” “Comparing retrieval algorithms,” “Combining retrieval algorithms” and all of “Retrieval Optimization.” Skim the vector-search algorithm list (LSH, HNSW, IVF…) and the TF-IDF math.

From a practitioner, about 15 min: Anthropic, “Introducing Contextual Retrieval” (Sept 2024). Huyen cites it. It shows the full stack you just played with (BM25 + embeddings + contextual chunks + reranking), with measured gains at each step.

Stuck or curious? Ask me anything. For example: “Sketch a RAG design for my product idea,” “What does a vector DB actually store?” or “Show me hybrid search in 30 lines of Python.” When you're done, send your first-try scores: the warm-up, the retriever challenges, the practice sorter and the quiz.

Next: Lesson 7, Agents & Memory (Ch. 6)

Related ideas