Retrieval-Augmented Generation
Give the model the right facts at question time, and know which half to fix when it still gets things wrong.
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
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 cost | Much faster and cheaper | Embedding and vector search add latency; vector DB bills can reach ⅕–½ of model-API spend |
| Quality | Strong out of the box, hard to improve; confused by ambiguous terms | Can beat BM25 with finetuning; handles natural phrasing |
| Blind spot | Synonyms and paraphrases | Exact 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)
- “help I can’t log in” first retrieved the 2FA article: it contains “log”, while the password article never says “log in.” Precision and recall were both 0%. BM25 can't know that “log in” relates to “password.”
- “robot won’t hold a charge” matched the controller article on the word “robot.” The battery article says “Robots” and “battery,” and with no stemming, those don't match.
- Ticking contextual retrieval added each article's “questions it answers” to the index, and both queries recovered. Embedding-based retrieval would also catch these paraphrases, but it might fumble “EADDRNOTAVAIL.” That's why hybrid search exists.
- “transformer” is ambiguous: the ML article and the power-supply article both match. Two words of meaning would fix it, which is where query rewriting helps.
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
| Tactic | What it does | Huyen's example |
|---|---|---|
| Chunking | Split 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.” |
| Reranking | Reorder candidates with a more precise (or recency-aware) scorer, then keep only what fits. | Chat-with-your-email ranks recent threads higher. |
| Query rewriting | Have a model turn a context-dependent turn into a standalone query. | “How about Emily Doe?” → “When did Emily Doe last buy something?” |
| Contextual retrieval | Add 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
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.
Next: Lesson 7, Agents & Memory (Ch. 6)