STML 2026 · Week 9
Chapter 8
Retrieval-Augmented Generation
Answers from retrieved documents
Part 1
Knowledge gaps and RAG
Parametric knowledge · Hallucination · Document-based applications · Two ways to supply documents · Retrieval-augmented generation · Passage selection · Two stages · Example question and cited answer
1.1 · Knowledge gaps and RAG
Parametric knowledge and its gaps
What a model learns in training is broad, but some facts never reach its weights.
Parametric knowledge: what a language model learns from its training corpus, stored in its weights. Lewis et al. (2020) call it parametric memory.
Gap 1
Too new
Cause: training stops at a cutoff date.
Example: a paper published last month
Gap 2
Private
Cause: the documents were never in the training data.
Example: a company’s refund policy
Gap 3
Too rare
Cause: a fact seen only a few times is learned weakly.
Example: the exact setting in one small paper
1.2 · Knowledge gaps and RAG
Hallucination and missing sources
A question in a knowledge gap still gets a fluent answer, and nothing in the answer shows where it came from.
Input
A question in a gap
The fact is too new, private, or too rare for the weights.
Mechanism
A likely continuation
Training rewards likely text. Nothing rewards the answer “I don’t know.”
Result
A fluent, unsupported answer
A described paper that the model never read; invented numbers or references.
Hallucination: a fluent statement that no evidence supports.
The weights keep no record of where a fact came from, so a reader cannot tell a recalled fact from an invented one.
1.3 · Knowledge gaps and RAG
Document-based applications
Many applications must answer from a specific set of documents.
| Setting | Documents | A typical question |
|---|---|---|
| Customer support | Product manuals, FAQs, past tickets | “How do I reset this router model?” |
| Company knowledge | Internal wiki, HR policies | “How many vacation days do new employees get?” |
| Law and compliance | Contracts, regulations | “Which clause covers early termination?” |
| Finance | Annual reports, filings | “What revenue did the company report last quarter?” |
| Software | API references, code documentation | “Which function parses a date string?” |
| Research | Papers | “Which papers compare reasoning and acting?” |
The documents are private, specialized, or new, and an answer is useful only if someone can check it against its source.
1.4 · Knowledge gaps and RAG
Two ways to supply documents
The documents can go into the weights by training, or into the input at answer time.
Non-parametric knowledge: knowledge kept outside the model, in documents (Lewis et al.: non-parametric memory). The right column is the idea behind RAG.
1.5 · Knowledge gaps and RAG
Retrieval-augmented generation
RAG puts both kinds of knowledge to work: the model supplies the language ability, and the documents supply the facts.
RAG: a method that retrieves relevant passages from external documents and gives them to a language model, which answers from them.
Written into the weights by training.
Placed into the current input by retrieval.
1.6 · Knowledge gaps and RAG
Passage selection
A few pages fit into the prompt. Thousands of pages do not, so the system must select the passages that the question needs.
A few pages
All the documents fit into the prompt.
Thousands of pages
The input is too long and too costly, and most of it has nothing to do with the question.
1Retrieval
How is the right passage found among thousands?
2Grounding
How does the model answer from that passage, and not from its memory?
1.7 · Knowledge gaps and RAG
Two stages of a RAG system
Work that does not depend on the question runs once, before anyone asks.
The documents are divided and encoded. This runs when documents are added or changed.
Retrieval and generation run for each question. The preparation keeps each answer fast.
1.8 · Knowledge gaps and RAG
Example question and cited answer
A company assistant answers employees’ questions from the employee handbook. The answer comes from a retrieved passage and cites it.
Illustrative example · handbook text written for this chapter
How many vacation days do new employees get?
Retrieved§3.1Employees in their first year receive 15 days of annual leave.
AnswerNew employees get 15 days of annual leave [§3.1].
Observation
The question says “vacation days” and “new employees”; the passage says “annual leave” and “first year”.
Problem
A word-matching search prefers “New employees receive a laptop on their first day.” (§1.2), which repeats “new employees”. Part 2 shows how a system finds §3.1.
Part 2
Document preparation
Chunks · Chunk size and boundaries · Chunk count · Embeddings · Cosine similarity · Indexing and the vector store
2.1 · Document preparation
Chunks
A question needs a few sentences, not a whole document, so the system stores and retrieves short passages.
Real documents are long: the EU AI Act has about 330,000 characters.
Chunk: a short passage of a document. The system splits each document into chunks and retrieves chunks.
Each chunk keeps its text, its position in the document, and its source.
2.2 · Document preparation
Chunk size and boundaries
A cut in the wrong place separates a sentence from the words that give it meaning.
A handbook paragraph, cut between its two sentences
“This” refers to nothing inside its own chunk.
Small chunk
Precise, but it can lose its context.
Large chunk
Keeps its context, but mixes topics and fills the input.
Good boundary
The first safeguard: a cut at the end of a paragraph.
Overlap
The second safeguard: the end of each chunk is repeated at the start of the next.
2.3 · Document preparation
Chunk count
Overlap repeats text, so it increases the number of chunks.
L characters in the document
s characters at most in one chunk
o characters shared by neighboring chunks; each chunk after the first adds only s − o new characters
Measured on the EU AI Act text · L = 328,831, s = 1,500, o = 150
Formula
244
chunks if every chunk is full
Actual splitter
298
chunks: it first cuts at the 126 headings of articles and annexes, then at line ends, so most chunks stay below s
Check 1 · Document preparation
Overlap and the cut paragraph
The handbook paragraph is cut between its two sentences, with an overlap of 21 characters. The second chunk now begins with “days of annual leave.” Does it say how many days a first-year employee gets?
Answer
No. Overlap repeats only the end of the previous chunk, and “first year” and “15” are at its start. Only a better boundary, or a much larger overlap, keeps the whole statement in one chunk.
2.4 · Document preparation
Embeddings
An embedding model turns each text into a vector: a fixed-length list of numbers.
Text → embedding model → vector · illustrative values; real vectors have 1,536 numbers
Q“How many vacation days do new employees get?”
model[ 0.12, −0.48, 0.31, …, 0.07 ]
§3.1“Employees in their first year receive 15 days of annual leave.”
model[ 0.10, −0.45, 0.35, …, 0.05 ]
§1.2“New employees receive a laptop on their first day.”
model[ −0.38, 0.22, 0.05, …, −0.29 ]
Almost the same direction: the same meaning in different words (vacation days ↔ annual leave, new ↔ first year).
A clearly different direction, although both contain “new employees”.
Trained on pairs of related texts, so that related texts receive vectors with similar directions. “Relevant” becomes “a small angle”.
2.5 · Document preparation
Cosine similarity
Cosine similarity compares the directions of two vectors and ignores their lengths.
Embedding models are trained so that related texts have a small angle between them.
The dot product is large when two vectors point the same way.
Division by the lengths removes length, so only the angle remains.
q = (1, 2), d = (2, 4)
same direction
q = (1, 2), d = (3, 1)
45° apart
q = (1, 2), d = (2, −1)
perpendicular
For vectors of length 1, the cosine equals the dot product; vector stores use this to save computation.
2.6 · Document preparation
Indexing and the vector store
The index finds the nearest vectors quickly; the store keeps each vector with its text and source.
Exact search
Compares the question with every chunk vector. Fast enough for thousands of chunks.
Approximate nearest-neighbor index
Checks only part of the vectors for millions of chunks. It can miss a few true neighbors, but it is much faster.
Vector store: a store that keeps the vector, the text, and the metadata of each chunk together. The model reads text, not vectors, and the metadata carries the source.
One record · illustrative values
id §3.1
vector [0.021, -0.013, 0.044, ...]
text "Employees in their first year receive
15 days of annual leave."
metadata {source: "Employee handbook",
section: "3.1 Annual leave"}Check 2 · Document preparation
Source of a citation
An answer ends with “[§3.1]”. Which stored fields make this possible, and which problem of the model’s own knowledge do they address?
Answer
The ID and the metadata (source and section). They attach a source to each passage, which addresses the missing source: the model’s own knowledge keeps no record of where a fact came from.
Part 3
Retrieval and answer generation
Similarity scores · Top-k retrieval · Grounded generation · Original RAG model
3.1 · Retrieval and answer generation
Similarity scores
A score ranks the chunks for one question. It does not prove that a chunk is correct.
Step 1
Question embedding
The same embedding model as for the chunks, so all vectors share one space.
Step 2
Cosine with every chunk
One score per chunk.
Step 3
Ranked list
The chunks in order of score.
Meaning of a high score
“Closer than the other chunks”, not “correct”. A chunk can be on topic and still lack the needed fact.
Scale
Scores have no fixed scale across models. Compare the candidates for one question with one another.
3.2 · Retrieval and answer generation
Top-k retrieval
The model cannot read every chunk, so the system passes only the best few.
Illustrative scores · “How many vacation days do new employees get?”
Employees in their first year receive 15 days of annual leave.
Annual leave increases by one day for each year of service, up to 25 days.
Leave requests must be submitted two weeks in advance.
New employees receive a laptop on their first day.
Top-k retrieval: the system keeps only the k chunks with the highest scores.
Can leave out a needed passage.
Fills the input with text that the question does not need.
k = 1 already returns §3.1, which answers the question.
3.3 · Retrieval and answer generation
Grounded generation
The model answers only from the retrieved passages, not from its own memory.
Grounded answer: an answer in which every claim is supported by the supplied passages.
Method: the system prompt gives the model three rules.
Only the passages. No facts from the model’s own knowledge.
A citation after each claim, such as [§3.1], so a reader can check it.
“Not in the passages” when the passages do not contain the answer.
Example · actual run, gpt-4.1, temperature 0
Answer the question using only the passages in the user message. 1. Do not add facts from your own knowledge. 2. After each claim, cite the passage ID in brackets, such as [§3.1]. 3. If the passages do not contain the answer, say so and name what is missing.
Question: How many vacation days do new employees get? Passages: [§3.1] Employees in their first year receive 15 days of annual leave. [§3.4] Leave requests must be submitted two weeks in advance.
New employees receive 15 days of annual leave in their first year [§3.1].
3.4 · Retrieval and answer generation
Original RAG model (Lewis et al., 2020)
The first RAG model joins a retriever and a generator, and weights each retrieved passage by its relevance.
Finds the top-k passages among about 21 million Wikipedia passages. pη(z | x) is the relevance of passage z to question x.
Reads the question with one passage and writes the answer. pθ(y | x, z) is the probability of answer y with that passage: the product of its token probabilities.
The question encoder and the generator learn together from question–answer pairs. The passage index stays fixed.
For each retrieved passage: relevance of the passage × probability of the answer with that passage. The sum over the top-k passages gives the probability of the answer. One passage serves the whole answer (RAG-Sequence).
The RAG in this chapter trains nothing: it connects a ready-made embedding model and a ready-made chat model through a prompt.
Part 4
Retrieval errors and grounding errors
Two causes of a wrong answer · Recall at k · Hybrid search and reranking · Grounding errors
4.1 · Retrieval errors and grounding errors
Two causes of a wrong answer
RAG has two stages, so a wrong answer has two possible points of failure.
1Retrieval error
- Event
- The needed text never reaches the model.
- Fix
- The collection, the chunking, or the search.
2Grounding error
- Event
- The text reaches the model, but the answer contradicts it or goes beyond it.
- Fix
- The instruction, and a claim-by-claim check.
Better retrieval cannot repair a grounding error, and a better prompt cannot recover a passage that never arrived.
4.2 · Retrieval errors and grounding errors
Recall at k
Recall at k measures retrieval on its own: the share of the needed chunks that appear in the top k.
Illustrative example
How many vacation days does an employee get in the third year?
Needed§3.1§3.2
Top-2§3.1 ✓§3.4 ✗also about leave
recall@2 = 1/2
Without §3.2, no passage gives the third-year number; any number that the model writes is a guess.
4.3 · Retrieval errors and grounding errors
Hybrid search and reranking
The first search can miss a needed passage. Two methods reduce such misses.
Hybrid search
Adds a keyword search. Embeddings handle paraphrases but can blur exact names, codes, and numbers; keywords match them directly.
Reranker
Reads the question and each candidate together, so it judges relevance more precisely. It is slow, so it only reorders the short list.
Pattern: a cheap, broad search first, then an expensive, careful one. A reranker cannot add a chunk that the first search missed.
4.4 · Retrieval errors and grounding errors
Grounding errors
A claim can sound right and still have no support in the passage.
Illustrative answer · §3.1 is in the input
“New employees get 15 days of annual leave, and unused days carry over to the next year.”
Passage §3.1: “Employees in their first year receive 15 days of annual leave.”
Claim 1 · New employees get 15 days of annual leave.
Supported by §3.1Claim 2 · Unused days carry over to the next year.
Not established: §3.1 does not say thisEach claim of the answer is compared with the passage.
Claim 2 comes from the model’s general knowledge of leave policies, not from §3.1.
“Not established”, which differs from “false”. A citation cannot supply a missing fact.
Check 3 · Retrieval errors and grounding errors
The failed stage
For How many vacation days does an employee get in the third year?, the system retrieves §3.1 and §3.4. The model answers: “An employee in the third year gets 17 days of annual leave [§3.1].” Which stages failed, and what should be fixed first?
Answer
Both. Retrieval missed §3.2, so recall@2 is 1/2. Generation then wrote a number that §3.1 does not contain and cited §3.1 for it. Fix retrieval first, for example with a larger k or hybrid search; then check that every number in the answer appears in a cited passage.
Part 5
Agentic RAG and Self-RAG
Limit of a single search · Agentic RAG · Fixed workflow and agent loop · Self-RAG · Self-RAG process and limit
5.1 · Agentic RAG and Self-RAG
Limit of a single search
Basic RAG searches once. Some questions reveal the next search term only in the first result.
Illustrative example
Who approves leave for the sales team, and what is that person’s phone extension?
Search 1
“leave approval, sales team”
Returns §5.3: “Leave for the sales team is approved by the sales director.”
New term
“sales director”
Known only after §5.3 is read.
Search 2
“sales director extension”
Returns §9.1: “Sales director: extension 4120.”
The second search term is not in the question. A system that searches once with the question cannot target it.
5.2 · Agentic RAG and Self-RAG
Agentic RAG
The retriever becomes a tool. Each result is an observation, and the agent chooses the next search or the answer.
Agentic RAG: RAG in which an agent uses the retriever as a tool and decides after each search.
Illustrative trace
- 1
Search “leave approval, sales team”
§5.3: “approved by the sales director.”
- 2
Search “sales director extension”
The term comes from step 1. Result: §9.1, extension 4120.
- 3
Answer from §5.3 and §9.1
No further search.
5.3 · Agentic RAG and Self-RAG
Fixed workflow and agent loop
A workflow always searches once; an agent decides how many searches a question needs.
Retrieve, then generate: one search for every question.
After each observation, the next search or the answer.
Each search adds a model call and time.
A limit on searches, so the loop cannot run without end.
5.4 · Agentic RAG and Self-RAG
Self-RAG
A prompted agent judges only as well as its prompt. Self-RAG trains the model itself to make these judgments.
Self-RAG (Asai et al., 2023): a method that trains a model to write reflection tokens, special tokens that record its retrieval decisions and its assessments of passages and of its own output.
| Token | Question it answers | Related step in this chapter |
|---|---|---|
| Retrieve | Should I retrieve now? | Choice of the next search |
| IsRel | Is this passage relevant? | Ranking by similarity |
| IsSup | Does the passage support what I wrote? | Claim-by-claim check |
| IsUse | Is the response useful as a whole? | — |
5.5 · Agentic RAG and Self-RAG
Self-RAG process and limit
The decisions are learned in training, so they need labeled data and a trained model.
Simplified redraw after the Self-RAG authors’ overview (selfrag.github.io), CC BY-SA 4.0
A retrieval decision, candidate generation, assessment of relevance, support, and utility, then selection of the text to keep.
Training data labeled with these tokens and a model trained on that data. Prompting alone cannot add Self-RAG to an existing chat model.
Sources
Sources
Lewis et al., Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks, NeurIPS 2020.
Asai et al., Self-RAG: Learning to Retrieve, Generate, and Critique through Self-Reflection, ICLR 2024; authors’ overview (CC BY-SA 4.0).
Manning et al., Introduction to Information Retrieval: keyword retrieval and recall.
Sentence Transformers, semantic search and retrieve and rerank; LangChain, recursive text splitter.
Regulation (EU) 2024/1689 (Artificial Intelligence Act), EUR-Lex: character and chunk counts.
The employee-handbook passages are invented for this chapter. The diagrams are course-authored; diagram sources.