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
- 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.
- 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.
- Check permissions before retrieval, never after generation: once the model has read a restricted passage, deleting its citation leaves the fact in the answer.
- Each retrieval upgrade fixes one named failure; agentic RAG handles questions that need several searches, and GraphRAG handles questions about connections.
- 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
flowchart LR
subgraph ING["Ingestion, ahead of time"]
direction LR
D[Documents] --> P[Parse] --> C[Chunk + metadata] --> E[Embed + keyword index]
end
E --> IX[(Index)]
subgraph QRY["Query time, per question"]
direction LR
Q[Question] --> F[Filter by permissions<br/>and date] --> R[Retrieve: hybrid] --> RR[Rerank] --> AC[Assemble context] --> G[Generate + cite] --> V[Verify citations]
end
IX --> F
In code: RAGIndex builds the top row's indexes, and answer runs the
bottom row and returns a RAGResult. View source
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
flowchart LR
RAW[Raw extracted text] --> H[Drop lines repeated<br/>on most pages]
H --> N[Drop page numbers]
N --> J[Rejoin hyphenated words,<br/>unwrap paragraphs]
J --> T{Table rows?}
T -->|yes| S[One sentence per row,<br/>headers repeated]
T -->|no| P[Paragraphs]
S --> OUT[Clean text for chunking]
P --> OUT
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
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
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-4012and 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.
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
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%
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
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
sequenceDiagram participant U as User participant A as RAG service participant I as Index participant M as Model U->>A: What does ERR-4012 mean? A->>I: hybrid search, filtered to what this user may read I-->>A: 8 candidate passages A->>A: rerank, keep 3 A->>M: rules + tagged sources + question M-->>A: answer with [it-004#0] A->>A: verify: id was in context, passage supports claim A-->>U: answer + clickable citation
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
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
sequenceDiagram participant U as Employee (not finance) participant A as RAG service participant M as Model rect rgb(250, 225, 225) Note over A,M: Wrong: filter after generation A->>M: sources include the restricted forecast M-->>A: "…41 million dollars [fin-006#0]" A->>A: strip the restricted citation A-->>U: "…41 million dollars" (leaked) end rect rgb(225, 240, 225) Note over A,M: Right: filter before retrieval A->>A: drop passages the user can't read A->>M: sources without the forecast M-->>A: "I don't know…" A-->>U: nothing restricted end
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
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
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
flowchart LR Q["Question:<br/>'weird message asking<br/>for my bank details'"] --> M[Model drafts a<br/>plausible answer] M --> H["Draft: 'This sounds like a phishing<br/>email… report it in Outlook'"] H --> E[Embed the draft] E --> S[Dense search] S --> R[Phishing guide, rank 1]
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
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
Chapter 8
Agentic RAG: let the model decide when and what to search
Every pipeline so far runs the same steps for every question, whatever it
asks. Some questions need several searches, and some need none. In
agentic RAG search is a tool the model calls inside the agent loop (see
The agent loop): the model reads the question, decides whether
to search and with which words, reads the results, and searches again if
something is missing. Asked "What is the per-diem for meals and how do I
upload expense receipts?", it runs two searches ("What is the per-diem for
meals", "how do I upload expense receipts") and answers citing both
fin-002#2 and fin-004#0. Told "thanks, that's all!", it does not search
at all.
Figure 8 · Diagram
sequenceDiagram
participant U as User
participant M as Model
participant S as search_kb tool
U->>M: per-diem for meals AND how to upload receipts?
M->>S: search_kb("per-diem for meals")
S-->>M: fin-002 passages
M->>S: search_kb("how do I upload expense receipts")
S-->>M: fin-004 passages
M-->>U: both answers, each with its citation
In code: agentic_answer offers the model one search tool and runs the
loop: each search retrieves, reranks and returns tagged passages, until the
model answers or the step limit is hit. View source
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
flowchart LR TF((two-factor)) ---|it-006| VPN((VPN)) TF ---|it-006| EM((email)) TF ---|it-006| AA((authenticator app)) TF ---|it-003| AC((AnyConnect)) TF ---|it-003| SC((software center)) TF ---|hr-003| LT((laptop)) AC ---|it-003| SC VPN ---|it-006| EM AA ---|it-001| SSP((self-service portal))
In code: build_graph links the entities, and communities groups them
into connected clusters, the "themes" a real GraphRAG system would
summarize. View source
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
flowchart TD
W[Confident wrong answer] --> R{Right passage in<br/>the top k?}
R -->|no| P{Is it in the<br/>index at all?}
P -->|no| FIXI[Fix ingestion:<br/>parsing, chunking, permissions sync]
P -->|yes| FIXR[Fix retrieval:<br/>hybrid, rerank, rewrite, HyDE, filters]
R -->|yes| C{Was it in the<br/>final context?}
C -->|no| FIXC[Fix assembly:<br/>reranker, budget, top_n]
C -->|yes| FIXG[Fix generation:<br/>instructions, citations, stale sources]
Figure 11 · Chart
Dense search has the only retrieval miss; switching to hybrid removes it, and the wrong answers left are generation misses
In code: debug_wrong_answers sorts the labelled questions into the
three kinds. View source
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 paperGao, 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 paperEdge 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 paperResearcher'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.