6.3Retrieval-augmented generation (RAG)
Give a model an open book. Follow a question through chunking, embedding, retrieval and prompt assembly, and see where RAG systems fail and how to measure them.
The model doesn’t know your handbook
A language model’s knowledge is frozen into its weights at training time. It has never read your company wiki, last week’s support tickets or the contract you signed yesterday, and it can’t tell you so reliably: asked about them, it tends to produce a plausible-sounding answer anyway. That is a hallucinationHallucinationWhen a model produces fluent but false or unsupported content., and from the outside it looks exactly like a correct answer.
You could fine-tune the model on your documents, but that is slow, expensive, has to be redone whenever the documents change, and is surprisingly unreliable for teaching specific facts. There is a much simpler option, which the previous two lessons set up: put the relevant text into the prompt at question time. The model is very good at reading a passage and answering from it. The hard part is finding the right passage among thousands.
That is retrieval-augmented generationRetrieval-augmented generation (RAG)Retrieving relevant documents at query time and placing them in the prompt so the model can answer from them. (RAG), named in a 2020 paper by Lewis et al. Its benefits:
- Fresh and private knowledge. Update the index and the very next answer reflects it, with no retraining.
- Citations. The answer can point to the exact passages it used, so people can verify it.
- Fewer hallucinations. Grounding the model in real text, and allowing it to say “not in the documents”, greatly reduces invented answers, though it doesn’t eliminate them.
- Access control. Retrieve only documents the current user is allowed to see, something weights can’t do.
A closed-book exam tests what you memorized; an open-book exam lets you look things up. RAG turns every question into an open-book exam, with one twist: you don’t get the whole library on your desk, only the few pages a librarian fetches for you in a hurry.
The library is the document collection; the index cards are the embeddings; the librarian is the retriever; the pages on your desk are the context in the prompt; and you, the student writing the answer, are the LLM. If the librarian brings the wrong pages, even a brilliant student writes a wrong answer, or worse, a confident one. That’s why most RAG engineering is about the librarian.
The pipeline, stage by stage
A RAG system has an offline half that prepares the documents and an online half that runs for each question.
Offline (indexing):
- Ingest. Load documents from wherever they live (PDFs, web pages, tickets, databases), extract clean text, and keep metadata such as title, URL, date and permissions.
- Chunk. Split each document into passages small enough to embed and to fit several into a prompt.
- Embed. Turn every chunk into a vector with an embedding model (see vector search).
- Index. Store the vectors (and usually a keyword index too) in a vector databaseVector databaseA store optimized for finding the vectors nearest to a query vector, usually with approximate nearest-neighbor indexes. or search engine.
Online (per question):
- Retrieve. Embed the question, fetch the top- most similar chunks, often with hybrid keyword + vector search.
- Rerank. Optionally rescore the candidates with a more accurate rerankerRerankerA slower, more accurate model (often a cross-encoder) that rescores a short list of retrieved candidates by reading the query and each document together. and keep the best few.
- Assemble the prompt. Instructions, numbered excerpts, the question, and rules such as “answer only from the excerpts, cite them, and say so if the answer isn’t there”.
- Generate. The LLM writes an answer with citations, which the application can turn into links.
The demo runs this whole pipeline in your browser on a fictional eight-document employee handbook. The “embedding” is a simple TF-IDF word-count vector rather than a neural model, and the final answer is assembled by extracting the best-matching sentences rather than by a real LLM. Everything else, including chunk boundaries, similarity scores and the prompt, is computed live.
The knowledge base: the fictional Lumen Labs employee handbook, 8 short documents. In real systems this step also parses PDFs, strips boilerplate and records metadata.
Things to try:
- Run the default question. “How many vacation days do I get per year?” retrieves the paid-time-off chunk first and answers “25 days” with a citation. Switch to No retrieval: the simulated model confidently says 20 days. Both answers sound equally sure of themselves.
- Shrink the chunks to ~8 words. The quoted sentence gets cut in half by a chunk boundary, and the answer warns you. Add overlap and the fragment is often healed.
- Make the chunks huge (~70 words). Each chunk now holds a whole document. Retrieval still finds the right one, but the prompt grows and the match score is diluted by unrelated sentences.
- Ask something the handbook doesn’t cover, such as “Is there a gym on site?”. Nothing relevant scores well and the system says it doesn’t know, which is exactly the behavior you want.
- Ask with different words, e.g. “time off allowance”. TF-IDF finds the chunk only through overlapping words such as “time” and “off”. A neural embedding would also match paraphrases like “holiday entitlement” that share no words at all.
Chunking: the most underrated decision
Chunking decides what the retriever can find. Common strategies:
- Fixed-size windows of N tokens with some overlap. Simple and predictable, but blind to structure.
- Structure-aware (recursive) splitting: split on headings first, then paragraphs, then sentences, only going finer when a piece is too big. Keeps ideas intact.
- Small-to-big retrieval: index small chunks for precise matching, but hand the model the surrounding paragraph or section (“parent document”) so it gets enough context.
- Contextualized chunks: prepend a short description of where the chunk comes from (“From the 2025 expenses policy, section on travel:”). A chunk that says only “the limit is 75 euros” is unfindable without it. Anthropic reported that generating such context with an LLM before embedding reduced failed retrievals substantially in their tests.
The size trade-off is real. Small chunks match questions precisely but can lose the context needed to interpret them (“it”, “the above”, a table header). Large chunks keep context but mix several topics, which blurs the embedding and spends prompt tokens on irrelevant text. Typical sizes are a few hundred tokens, with 10–20% overlap, but the only reliable way to choose is to measure on your own questions.
How RAG fails
When a RAG answer is wrong, find out which stage failed before touching the prompt.
- Retrieval misses. The right passage exists but isn’t in the top . Causes include vocabulary mismatch, a chunk boundary through the key sentence, a table that was mangled during ingestion, or a question that needs aggregation (“how many policies mention travel?”) or multi-hop reasoning across documents that no single chunk answers.
- Lost in the middle. Liu et al. (2023) found that models used information at the start or end of a long context better than information buried in the middle. Put the best passages first and don’t stuff the context with marginal ones.
- Conflicting or stale sources. The 2022 and 2025 versions of a policy both get retrieved. Without dates in the metadata and an instruction to prefer the newest, the model may blend them.
- Ignoring or over-trusting context. Models sometimes answer from memory despite contrary evidence in the prompt, or repeat a wrong passage faithfully.
- Injected instructions. Retrieved documents are untrusted input. A web page saying “ignore previous instructions” is a prompt injection vector.
Evaluating a RAG system
Evaluate the two halves separately, on a set of realistic questions with known answers and known source passages:
- Retrieval: recall@k (did the right passage make it into the top ?) and MRR (how high was it ranked?). If recall@k is low, no prompt can save you.
- Generation: faithfulness (is every claim supported by the retrieved text?), answer relevance (does it address the question?), correctness against the reference answer, and citation accuracy (do the cited passages actually support the sentence they’re attached to?).
Faithfulness and relevance are usually scored by an LLM-as-a-judgeLLM-as-a-judgeUsing a language model to grade or compare other models' outputs, which scales cheaply but brings biases such as favoring the first or the longer answer., with frameworks such as RAGAS packaging common metrics. Judges have biases of their own, covered in evaluation, so spot-check them against human labels.
Agentic RAG
The classic pipeline retrieves exactly once, using the user’s raw question. Agentic RAG gives the model retrieval as a tool (see tool use & agents) and lets it decide when and what to search: rewrite a vague question into a good query, search several times, follow up on what it finds, compare sources, and stop when it has enough. This handles multi-hop questions far better, at the cost of more latency, more tokens and less predictability.
MATH CORNER · optionalTF-IDF retrieval and recall@k, by hand
The demo scores chunk against query by cosine similarity of TF-IDF vectors. Each word gets weight
where counts occurrences in the chunk, is the number of chunks and is how many chunks contain . Vectors are normalized to length 1 and compared with a dot product.
Worked example. Three chunks, after removing stop-words and plurals: = {vacation, day, year}, = {sick, day}, = {home, office, chair}. With : “day” is in 2 chunks, so ; every other word is in 1 chunk, so .
| vacation | day | year | sick | length before norm. | |
|---|---|---|---|---|---|
| (normalized) | 0.623 | 0.474 | 0.623 | 0 | 2.719 |
| (normalized) | 0 | 0.606 | 0 | 0.796 | 2.127 |
| query “vacation days” | 0.796 | 0.606 | 0 | 0 | 2.127 |
The rare word “vacation” carries more weight than the common “day”, so wins clearly.
Recall@k over a test set of questions, each with a set of relevant chunks and retrieved top- list :
If 40 of 50 questions have their single relevant chunk in the top 3, recall@3 , and at least 10 answers are doomed before the LLM even starts.
In code
A minimal RAG loop: retrieve, assemble a citation-friendly prompt, generate. Real systems add hybrid search, reranking and metadata filters.
def answer(question, index, embed, llm, k=4):
q = embed(question) # same model as the documents
hits = index.search(q, k) # [(chunk_text, source, score), ...]
context = "\n\n".join(f"[{i+1}] ({src}) {text}" for i, (text, src, _) in enumerate(hits))
prompt = (
"Answer using ONLY the excerpts below. Cite them like [1]. "
"If the answer is not in the excerpts, say you don't know.\n\n"
f"{context}\n\nQuestion: {question}"
)
return llm(prompt), hits # return sources for display
# Offline, once per document update:
# for doc in documents:
# for chunk in split(doc.text, max_tokens=400, overlap=60):
# index.add(embed(chunk), text=chunk, source=doc.title)
- “RAG eliminates hallucinations.” It reduces them. The model can still misread a passage, blend conflicting passages, or answer from memory when retrieval comes back empty. Faithfulness has to be measured.
- “If the answer is wrong, fix the prompt.” Check retrieval first. If the right passage never reached the prompt, no wording can produce the right answer.
- “More retrieved chunks is always safer.” Extra marginal chunks cost tokens, can push the key passage into the middle where it’s used less, and add chances for distraction.
- “Fine-tuning is the better way to add knowledge.” Fine-tuning is good at teaching style, format and behavior. For facts that change or need citations, retrieval is usually cheaper, fresher and verifiable.
Check your understanding
Q1.Your RAG bot gives a wrong answer. Logs show the correct passage was not among the retrieved chunks. What should you work on first?
Q2.You shrink chunks from 400 to 40 tokens. What is the most likely trade-off?
Q3.According to the 'lost in the middle' findings, where should you place the most relevant retrieved passage in a long prompt?
Q4.What does a faithfulness metric check?
Further reading
- paperRetrieval-Augmented Generation for Knowledge-Intensive NLP Tasks — Lewis et al., 2020: the paper that named RAG.
- paperLost in the Middle: How Language Models Use Long Contexts — Why position within the context matters.
- blogIntroducing Contextual Retrieval — Anthropic on contextualized chunks, hybrid search and reranking, with measurements.
- paperRAGAS: Automated Evaluation of Retrieval Augmented Generation — Faithfulness, answer relevance and context metrics.
- paperSelf-RAG: Learning to Retrieve, Generate, and Critique through Self-Reflection — A model that decides when to retrieve and critiques its own use of sources.