rumblr Work in progressWIP

● The AI Primer · Lesson 44 · Part 6: building systems people rely on

Retrieval-augmented generation

(RAG), end to end

This lesson covers How a language model answers from your documents, with citations and access control

Free lesson 29 min11 figures and diagrams11 interactive

What this is

What is retrieval-augmented generation?

Retrieval-augmented generation (RAG) lets an AI language model answer from your own documents, which it was never trained on. Before it answers, a search fetches the few passages most likely to hold the answer and puts them in the prompt. The language model answers from those passages and cites them. Think of an open-book exam with a librarian: the librarian fetches the right pages, and you answer from them and note where each fact came from. Most of what decides an answer's quality happens before the language model runs: how the documents are cleaned, cut into passages and searched.

Why it matters: You need this when an assistant must answer from documents its language model has never seen, which change faster than you could retrain it, and every answer must name its source. Fine-tuning teaches behaviour and format, not facts that change.

At a glance

Key takeaways

  1. RAG searches your documents when a question arrives and has the model answer from the passages it finds, citing each one, so knowledge can change or be checked without retraining.
  2. Quality is decided before the model runs: in parsing (tables above all), in chunks that carry their document's metadata, and in hybrid search followed by reranking.
  3. Check permissions before retrieval, never after generation: once the model has read a restricted passage, deleting its citation leaves the fact in the answer.
  4. Each retrieval upgrade fixes one named failure; agentic RAG handles questions that need several searches, and GraphRAG handles questions about connections.
  5. Debug a wrong answer by measuring retrieval (recall@k) first, and look at generation only after.

How it works, from scratch

A language model knows only what was in its training data, and your company's documents were not in it. Retrieval-augmented generation works in two stages. Ahead of time, the documents are parsed, cut into passages and indexed. Then, for every question, the system retrieves the passages the asker may read that best match the question, keeps the best few, puts them in the prompt, and the model generates an answer from them, citing the passage behind each claim.

Figure 1 · Diagram

Reading it: the top row runs once per document, whenever documents change; the bottom row runs for every question. An answer can contain only what survives every box, left to right. A table mangled at Parse, or a passage missing at Retrieve, cannot be fixed by a better prompt at Generate, which is why most of the work on a RAG system's quality goes into the early boxes.

In code: RAGIndex builds the top row's indexes, and answer runs the bottom row and returns a RAGResult. View source

The whole pipeline, running on a small company knowledge base of 20 documents: IT guides, and HR and finance policies. The language model stays the same throughout; only the shelf of documents changes. Pick a question, then take a document off the shelf and ask again.

Chapter 1

Parsing: where quality dies first

Before a document can be searched, its text has to be pulled out of the file, and text pulled out of a PDF comes out damaged. Here is what a naive extractor does to two pages of a travel policy, and what four repairs make of it:

Damage Before After
Header repeated on every page Northwind Ltd Travel Policy 2026 … CONFIDENTIAL removed (it appears on 2 of 2 pages)
Page-number footer Page 1 of 2 removed
Word hyphenated across a line break all em- / ployees travelling all employees travelling
Table flattened L1-L3 150 60 L4-L6 200 75 kept as rows, then one sentence per row

The table is the dangerous one. Flattened, "200" no longer says which grade it belongs to. The last repair writes each row as a sentence that stands on its own, Grade L4-L6: hotel cap 200, meal cap 75., so any row can be retrieved by itself and still say what its numbers mean.

Figure 2 · Diagram

Reading it: each box removes one kind of extraction damage. The diamond is the decision that matters: prose and tables need different handling, because a table's meaning lives in its columns. Real pipelines add layout-aware parsers and OCR (optical character recognition: reading text from an image of a page) for scanned documents, with a quality check on the output.

Company documents are scanned, laid out in columns and full of tables that span pages. If parsing garbles a number, no retriever or model later in the pipeline can recover it, and the failure looks like a model error.

In code: clean_extracted_text makes the first three repairs and keeps table rows on their own lines; extract_table reads the rows and table_rows_as_sentences writes each one as a sentence. View source

Make the four repairs to the travel policy one at a time, and watch whether a search can find the hotel cap for grade L4-L6.

Chapter 2

Chunking, with metadata that travels

Clean text is still too long to search as one piece. A passage that holds one idea can match a question precisely, so each document is cut into small passages called chunks. Every chunk carries a label copied from its document: the title, the date it was last updated and who may read it. With a 15-word limit, the VPN error guide it-004 splits into two chunks:

Passage id Text Updated Readers
it-004#0 ERR-4012 means the VPN tunnel could not be established, usually because the client is out of date. 2026-04-10 everyone
it-004#1 Update AnyConnect to version 5.1 or later and reboot. 2026-04-10 everyone

The limit is tiny because these documents are tiny; real systems use chunks of a few hundred tokens. Cut on the document's own structure (sentences, paragraphs, sections), not every so many characters, which cuts sentences in half. Retrieval compares chunking strategies in depth.

Small chunks match precisely but can lose their context: the second chunk never says which error it fixes, a problem contextual retrieval solves under the retrieval upgrades below. The label is what makes the permission and date filters possible later.

In code: chunk_document splits a document on sentence boundaries into Passages, each carrying its id, title, department, date and readers. View source

Pick a document and drag the word limit to see where the cuts fall.

Chapter 3

Retrieval: keyword and meaning, fused

A question now has to find its chunks, and there are two ways to search them.

  • Keyword search (BM25) scores passages by the question's words, giving more weight to rare words and less to long passages. It finds exact identifiers like ERR-4012 and misses synonyms.
  • Dense search compares embeddings (vectors where closeness means similar meaning; see primer.ml.embeddings). It matches "scam message in my inbox" to the phishing guide with no word in common, but blurs exact codes.

Hybrid search runs both and merges the two rankings with reciprocal rank fusion (RRF), which uses only each passage's rank, never its score. BM25 scores and cosine similarities are on different scales, so adding them would mean nothing.

The formula and its symbols

Symbols

Symbol Meaning here Worked example
one passage it-004#0
one of the rankings being fused (keyword, dense) 2 rankings
position of in ranking (1 = best); rankings that miss contribute nothing 1st, 3rd
a damping constant; 60 is the usual choice 60
add up over the rankings

In words: each ranking gives a passage a vote worth one over sixty-plus its position, and the votes are added.

On the worked example: a passage ranked 1st by dense search and 3rd by keyword search scores 1/61 + 1/63 = 0.0323. A passage ranked 1st by one list and absent from the other scores only 1/61 = 0.0164. Passages that both methods agree on rise to the top.

In Python
k = 60
# 1st by dense, 3rd by keyword: Σ_i 1/(k + rank_i(d))
round(1 / (k + 1) + 1 / (k + 3), 4)  # → 0.0323
# 1st in one list, absent from the other
round(1 / (k + 1), 4)  # → 0.0164

New to Σ, ∂ or ‖x‖? The symbols reference decodes each one as a few lines of Python.

Pick a question and watch the keyword and dense lists disagree, then press a passage to see how its fused score adds up.

Measuring retrieval

Which search to use is settled by measuring it. Take a set of questions whose right document you know, here 12, and count how often that document is among the top k passages a method returns. That share is recall@k.

Figure 3 · Chart

1 2 3 4 5 k (passages kept) 0.0 0.2 0.4 0.6 0.8 1.0 recall@k on the labelled questions Which retrieval finds the answer? keyword (BM25) dense hybrid (RRF) hybrid + rerank

Dense search plateaus at 92% recall because it never finds the error code, while hybrid reaches 100% by k = 2 and reranking lifts its top-1 from 75% to 92%

Reading it: the x-axis is how many passages you keep (k), and the y-axis is recall@k over the 12 labelled questions. On this small set many questions reuse the documents' own words, so keyword search is already strong. Dense search levels off at 92% because it never finds ERR-4012. Hybrid reaches 100% by k = 2 but only 75% at k = 1, and reranking the hybrid shortlist (the next step) lifts the top-1 result to 92%. Run this measurement on your questions before choosing a method.
The formula and its symbols

Symbols

Symbol Meaning here
the labelled questions; is how many (12 here)
one question
1 if true, 0 if not

In words: the share of questions for which the right document made it into the top k.

On the worked example: dense search at k = 3 finds the right document for 11 of 12 questions (all but ERR-4012): 11/12 = 0.92.

In Python
# 𝟙[...] for each of the 12 questions; ERR-4012 is the 0
found = [1] * 11 + [0]
# (1/|Q|) Σ over q in Q
round(sum(found) / len(found), 2)  # → 0.92

In code: RAGIndex.retrieve runs keyword, dense or hybrid search over the passages the asker may read, and recall_curve measures recall@k for each. View source

Chapter 4

Reranking: read the question and each passage together

Both searches are fast because their indexes are built ahead of time: a question is compared with what is stored, never read alongside a passage. A reranker does read them together. It is usually a cross-encoder, a model that takes the question and one passage at once and outputs a relevance score. That is far more precise than comparing stored vectors, and far too slow to run over every passage. So retrieval casts a wide, cheap net (8 candidates here) and the reranker keeps the best few (3 here), using the small cross-encoder built in Retrieval.

In code: RAGIndex.rerank scores each (question, passage) pair with primer.ml.embeddings.retrieval.CrossEncoder and keeps the best few. View source

Drag the size of the net and the number kept, and switch off parts of the reranker's score to see what each part adds.

Chapter 5

Assemble, generate, cite, verify

The passages the reranker keeps go into the prompt. Each sits in its own tag with its id, title and date, its text escaped so it cannot break out of the tag, and the question comes last (see Context engineering). The instructions tell the model to answer only from the sources, to cite the id of each source it uses, and to say it doesn't know when the sources don't hold the answer. For "What does ERR-4012 mean?" the prompt reads:

<sources>
<source id="it-004#1" title="Error ERR-4012: VPN tunnel failed" updated="2026-04-10">Update AnyConnect to version 5.1 or later and reboot.</source>
<source id="it-004#0" title="Error ERR-4012: VPN tunnel failed" updated="2026-04-10">ERR-4012 means the VPN tunnel could not be established, usually because the client is out of date.</source>
<source id="it-002#2" title="Password policy" updated="2025-11-20">This policy applies to all employees and contractors.</source>
</sources>
<question>What does ERR-4012 mean?</question>

The answer is "ERR-4012 means the VPN tunnel could not be established, usually because the client is out of date. [it-004#0]". A final check then reads every citation: the cited id must have been in the context, and the cited passage must support the claim before it. A question the sources don't cover gets "I don't know based on the provided sources."

Figure 4 · Diagram

Reading it: time runs downward. The permission filter runs at the index, before any passage is fetched; the model sees only three passages; and nothing reaches the user until the citations check out. A checked citation lets a person confirm the answer in seconds by reading the passage it points to.

In code: answer chains RAGIndex.retrieve, RAGIndex.rerank, assemble_context, generate and verify_citations; grounded_policy is the offline model that stands in for a real one. View source

The citation check, run on an answer you can edit. Change a claim or a citation and see which of the two tests it fails.

Chapter 6

Permission-aware retrieval: filter before, never after

The diagram above filters at the index, before anything is ranked. In a company not everyone may read every document: the revenue forecast is for finance and executives only. So each passage carries its document's access-control list (ACL: the groups allowed to read it), copied from the system the document came from (SharePoint, Google Drive, a wiki). The question is when to check it. Retrieval checks it before ranking and drops every passage the asker cannot read, so restricted text never reaches the context, the model or the answer. The alternative, deleting restricted citations after the answer is written, leaves the fact behind. Here is "What is the Q3 revenue forecast?", where the forecast document is readable only by finance and exec:

Who asks How it's filtered Answer
finance user before retrieval "Q3 revenue is forecast at 41 million dollars… [fin-006#0]"
anyone else before retrieval "I don't know based on the provided sources."
anyone else after generation (citation removed) "Q3 revenue is forecast at 41 million dollars…"

Figure 5 · Diagram

Reading it: in the red box the model saw the restricted passage, so the number is already in its words, and deleting the citation marker afterwards leaves the fact behind. In the green box the passage never left the index. Permission changes in the source system must also reach the index quickly, or a user whose access was revoked keeps it until the next re-index.

In code: post_generation_filter_answer is the wrong way, kept to show the leak: it retrieves for every group, generates, then strips the restricted citation markers. View source

Ask about the forecast as an employee outside finance, with the check before retrieval and then after generation.

Chapter 7

Retrieval upgrades

Even filtered hybrid search with a reranker fails in a few recognizable ways: a follow-up question that says "it", a question worded nothing like its answer, an out-of-date document that still matches, a passage that never names its subject. Each upgrade fixes one failure. The last column shows the top three passages without it and with it, on a question that has that failure:

Upgrade What it does Before → after (top 3)
Query rewriting Fills in a follow-up's subject from earlier in the conversation "what if it fails?" after a VPN question: printer guide → VPN setup and ERR-4012
HyDE Searches with a drafted answer instead of the question "a weird message asking for my bank details": nothing relevant → phishing guide first
Multi-query Searches several phrasings of the question and fuses the results "two step login setup": no MFA guide → MFA guide in top 3
Metadata filter Drops documents updated before a given date superseded 2023 travel policy first → gone
Contextual retrieval Writes where each passage comes from into it before indexing "how do I fix ERR-4012": fix sentence missing → found
Parent-child Matches a small passage, hands the model its whole document a matching sentence → its full document

In code: rewrite_query, hyde_search, multi_query_search and RAGIndex.retrieve_parents are four of the upgrades. The date filter is an option of RAGIndex.retrieve, contextual chunks are an option of RAGIndex, and demo runs each upgrade on its question. View source

Pick an upgrade and switch it off and on, on the question it was made for.

HyDE

HyDE (Hypothetical Document Embeddings) sounds backwards: it asks a model to invent an answer, then searches with the invented answer instead of the question.

Figure 6 · Diagram

Reading it: questions and answers are written differently. The user's words ("weird", "bank details") appear nowhere in the phishing guide, but the drafted answer uses the words answers use ("phishing", "report", "suspicious"), so its embedding lands next to the real passage. The draft may be wrong in its details. That does not matter, because it is used only to search and is never shown to the user.

Contextual retrieval

Contextual retrieval fixes the second it-004 chunk from the chunking step, the one that never says which error it fixes. Before indexing, each passage gets a short line saying where it comes from. Here that line is just the document's title and department; Anthropic's version asks a model to write one sentence placing the chunk in its document.

Figure 7 · Chart

0.0 2.5 5.0 7.5 10.0 12.5 15.0 17.5 20.0 rank of the passage containing the fix (lower is better; 21 = not in top 20) how do I fix ERR-4012 ERR-4012 what should I do resolve ERR-4012 on my laptop Contextual retrieval plain chunks chunks with a context line

Without a context line the fix passage misses the top 20 for all three phrasings; with the title prefixed it ranks 2nd, 2nd and 4th

Reading it: three ways of asking how to fix ERR-4012. Each pair of bars is the rank of the passage "Update AnyConnect to version 5.1 or later and reboot." (shorter is better, and 21 means not in the top 20). Without a context line the passage never mentions ERR-4012, and for all three phrasings it misses the top 20. With the title prefixed it ranks 2nd, 2nd and 4th. That is in the top five every time, though "resolve ERR-4012 on my laptop" still ranks three passages from the laptop guide above it. The context line gets the passage found; putting it first is the reranker's job.

Chapter 9

GraphRAG: questions about connections

Some questions are not answered by any passage, however many searches run: "what depends on two-factor authentication?" or "what are the main themes across these contracts?". The answer is spread across many documents. GraphRAG first extracts entities (named things: systems, people, products) and the relationships between them into a graph, then answers by walking the graph or by summarizing groups of connected entities. The version here is the smallest one that works: two entities are linked when one sentence mentions both, and each link remembers which document said so.

Figure 9 · Diagram

Reading it: each circle is an entity found in the documents, and each line is a sentence that mentions both ends, labelled with its source document. "What depends on two-factor?" is answered by reading the neighbours of one circle, and each neighbour comes with the document that links it. Real GraphRAG uses a model to extract typed relations ("requires", "replaces") and to write a summary for each cluster, which is what makes questions about the whole collection answerable.

In code: build_graph links the entities, and communities groups them into connected clusters, the "themes" a real GraphRAG system would summarize. View source

The graph built from the 20 documents: press a circle to ask what connects to it, and take documents away to see which links they held up.

Chapter 10

Debugging a confident wrong answer

With this many steps between a question and its answer, a confident wrong answer could start in any of them. Either retrieval brought the wrong passages or the model misused the right ones. The fixes are different, so find out which before changing anything. Run the 12 labelled questions and sort each one: a retrieval miss when no passage from the right document is in the top 3 (no prompt can fix that), a generation miss when the right document was there but the answer didn't use it, or ok.

With dense-only retrieval, "what does ERR-4012 mean" is a retrieval miss and recall@3 is 0.92; switching to hybrid fixes it (recall@3 = 1.00). What's left are generation misses. One of them, "per-diem for meals when traveling", is answered from the superseded 2023 policy: a data problem that a date filter fixes. The other, "enroll in MFA", is a limit of the simple model used here, not of RAG: it matches words literally, so "enroll" misses the passage's "enrolling", and with only "MFA" in common it declines to answer. A real model would read it-006 and answer.

Figure 10 · Diagram

Reading it: start at the top and answer each question with a measurement, not a guess. Editing the prompt is the bottom-right box. Rule out the three boxes before it first, because no prompt can fix a failure in any of them.

Figure 11 · Chart

0 2 4 6 8 10 12 labelled questions (top 3 passages) bm25 dense hybrid Where do wrong answers come from? ok generation miss retrieval miss

Dense search has the only retrieval miss; switching to hybrid removes it, and the wrong answers left are generation misses

Reading it: each bar is one retrieval method over the 12 labelled questions, split into ok (green), generation misses (orange) and retrieval misses (red). Dense search has one retrieval miss, the error code, and hybrid removes it. The orange that remains is generation, and that is where to look next.

In code: debug_wrong_answers sorts the labelled questions into the three kinds. View source

The decision tree, run on all twelve labelled questions at once: each comes out as a retrieval miss, a generation miss or ok. Change the search and watch the misses move.

Test yourself

5 questions

Answer each one out loud or on paper before you open it.

Question 1Your RAG system gives confident wrong answers. Debug it step by step.Think it through, then reveal

Take the failing questions (and build a labelled set if you don't have one). First, is the right passage in the index at all? If not, it's ingestion: parsing, chunking or permission sync. Second, is it in the top k? Measure recall@k; if not, fix retrieval: hybrid search, a reranker, query rewriting or HyDE, metadata filters, contextual chunks, domain-tuned embeddings. Third, did it survive into the final context? If not, fix reranking or the context budget. Only then look at generation: instructions to answer only from sources and to decline otherwise, citation checks, stale or contradictory sources. Add every case to the golden set.

Question 2Why does hybrid search beat pure vector search on enterprise data?Think it through, then reveal

Enterprise questions are full of exact identifiers (error codes, product names, ticket numbers) that embeddings blur, and full of paraphrases that keyword search misses. Hybrid gets both, and RRF merges the rankings without having to reconcile incompatible score scales.

Question 3How do you make RAG respect document permissions?Think it through, then reveal

Copy each document's access-control list onto every chunk at ingestion, filter candidates by the user's groups before ranking, and sync permission changes from the source system promptly. Never filter after generation: the model has already used the restricted text.

Question 4When would you use agentic RAG instead of a single retrieval step?Think it through, then reveal

For multi-part or vague questions, and when the model needs to judge whether results are good enough and search again. It costs more calls and latency, so keep single-shot retrieval for simple lookups.

Question 5RAG or fine-tuning for a company knowledge assistant?Think it through, then reveal

RAG for knowledge: it updates by re-indexing, cites sources, and respects permissions. Fine-tuning teaches behaviour and format, not facts that change. Most systems are RAG plus a good prompt (see Training stages).

Primary sources

The papers behind this lesson

Lewis et al., Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (2020), Coined the term and showed that pairing a generator with a retriever over a document index beats a model relying on its weights alone for knowledge-heavy questions.

Read on rumblr →The paper

Gao, Ma, Lin & Callan, Precise Zero-Shot Dense Retrieval without Relevance Labels (2022), Introduced HyDE: search with an embedding of a model-written hypothetical answer.

Read on rumblr →The paper

Edge et al., From Local to Global: A Graph RAG Approach to Query-Focused Summarization (2024), Builds an entity graph and community summaries so that whole-collection questions can be answered.

The paper

Researcher's shelf

Further reading

  • Anthropic, Introducing Contextual Retrieval: https://www.anthropic.com/news/contextual-retrieval
  • Anthropic citations docs: https://docs.claude.com/en/docs/build-with-claude/citations
  • Microsoft GraphRAG documentation: https://microsoft.github.io/graphrag/
  • RAGAS documentation (RAG evaluation): https://docs.ragas.io/
  • The retrieval lesson in this repo, with BM25, RRF, cross-encoders and chunking in depth: Retrieval

About this lesson. This is the illustrated edition of a lesson from the open-source AI Primer ↗. Its text, figures and numbers are generated from the Primer's source at commit f8b43d1, so the two always agree: the explanation, the code that builds it and the tests that prove it.