Chapter 8 · Retrieval-Augmented Generation

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.

Definition

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.

Definition

Hallucination: a fluent statement that no evidence supports.

Missing source

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.

SettingDocumentsA typical question
Customer supportProduct manuals, FAQs, past tickets“How do I reset this router model?”
Company knowledgeInternal wiki, HR policies“How many vacation days do new employees get?”
Law and complianceContracts, regulations“Which clause covers early termination?”
FinanceAnnual reports, filings“What revenue did the company report last quarter?”
SoftwareAPI references, code documentation“Which function parses a date string?”
ResearchPapers“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.

Training on the documents
Documents at answer time
Knowledge
In the weights
In external documents
Change
Training again
An edit of the document
New facts
Absorbed unreliably
Read directly from the text
Source
Not shown reliably
The passage that the answer used
Definition

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.

Definition

RAG: a method that retrieves relevant passages from external documents and gives them to a language model, which answers from them.

Parametric

Written into the weights by training.

Non-parametric

Placed into the current input by retrieval.

Training data updates the learned weights of the language model, which hold parametric knowledge. External documents reach the model's current input through retrieval, as non-parametric memory. The model uses both to generate the answer.

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.

Preparation: documents become chunks with source metadata and then a search index. Question processing: the question goes to a retriever, which reads the index and returns passages with sources; the generator receives the passages and the original question and writes the answer.
Stage 1 · Preparation

The documents are divided and encoded. This runs when documents are added or changed.

Stage 2 · Answering

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

Question

How many vacation days do new employees get?

Retrieved

§3.1Employees in their first year receive 15 days of annual leave.

Answer

New 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.

Need

Real documents are long: the EU AI Act has about 330,000 characters.

Definition

Chunk: a short passage of a document. The system splits each document into chunks and retrieves chunks.

Record

Each chunk keeps its text, its position in the document, and its source.

A long document, drawn as lines of text with the headings Abstract, 1 Introduction, and 2 Method, is split into four chunks, C1 to C4. Neighboring chunks share a few shaded lines of overlap. Each chunk becomes a record with a short description, its character range, and its page.

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

Employees in their first year receive 15 days of annual leave.
CUT
This increases by one day for each year of service.

“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.

chunk 1chunk 2 (shared start)

2.3 · Document preparation

Chunk count

Overlap repeats text, so it increases the number of chunks.

n equals the ceiling of (L minus o) divided by (s minus o)

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 ]

Q §3.1 §1.2 small angle drawn in 2 of the 1,536 dimensions
Q and §3.1

Almost the same direction: the same meaning in different words (vacation days ↔ annual leave, new ↔ first year).

Q and §1.2

A clearly different direction, although both contain “new employees”.

Embedding model

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.

sim of q and d equals q dot d divided by the product of the lengths of q and d
Reason

Embedding models are trained so that related texts have a small angle between them.

Numerator

The dot product is large when two vectors point the same way.

Denominator

Division by the lengths removes length, so only the angle remains.

1.00
q = (1, 2), d = (2, 4)
same direction
0.71
q = (1, 2), d = (3, 1)
45° apart
0.00
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?”

§3.1

Employees in their first year receive 15 days of annual leave.

0.71
k = 1
§3.2

Annual leave increases by one day for each year of service, up to 25 days.

0.58
§3.4

Leave requests must be submitted two weeks in advance.

0.49
k = 3
§1.2

New employees receive a laptop on their first day.

0.36
Definition

Top-k retrieval: the system keeps only the k chunks with the highest scores.

Small k

Can leave out a needed passage.

Large k

Fills the input with text that the question does not need.

Here

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.

Definition

Grounded answer: an answer in which every claim is supported by the supplied passages.

Method: the system prompt gives the model three rules.

1

Only the passages. No facts from the model’s own knowledge.

2

A citation after each claim, such as [§3.1], so a reader can check it.

3

“Not in the passages” when the passages do not contain the answer.

Example · actual run, gpt-4.1, temperature 0

System
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.
User
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.
Assistant
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.

Retriever · DPR

Finds the top-k passages among about 21 million Wikipedia passages. pη(z | x) is the relevance of passage z to question x.

Generator · BART

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.

Training

The question encoder and the generator learn together from question–answer pairs. The passage index stays fixed.

p of y given x is approximately the sum over z in the top-k passages of p-eta of z given x times the product over i of p-theta of y-i given x, z, and y-1 to y-i-minus-1
Reading of the formula

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.

Question
Retrieval
Passages
Generation
Answer
① retrieval error
② grounding error

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.

recall at k equals the number of needed chunks in the top k divided by the number of needed chunks

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.

The query feeds both keyword search and embedding search. Their results are merged into one candidate list, reranked by a model that reads the query together with each candidate, and the top text is selected.

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.1

Claim 2 · Unused days carry over to the next year.

Not established: §3.1 does not say this
Check

Each claim of the answer is compared with the passage.

Origin

Claim 2 comes from the model’s general knowledge of leave policies, not from §3.1.

Status

“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.

Agent Retriever tool Answer search query passages enough evidence
Definition

Agentic RAG: RAG in which an agent uses the retriever as a tool and decides after each search.

Illustrative trace

  1. 1

    Search “leave approval, sales team”

    §5.3: “approved by the sales director.”

  2. 2

    Search “sales director extension”

    The term comes from step 1. Result: §9.1, extension 4120.

  3. 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.

Top: a fixed workflow, Question, Retrieve, Generate, Answer. Bottom: an agent receives the request, sends search queries to a retrieval tool, receives passages with sources, and then selects another search or the answer.
Fixed workflow

Retrieve, then generate: one search for every question.

Agent loop

After each observation, the next search or the answer.

Cost

Each search adds a model call and time.

Stop rule

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.

Definition

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.

TokenQuestion it answersRelated step in this chapter
RetrieveShould I retrieve now?Choice of the next search
IsRelIs this passage relevant?Ranking by similarity
IsSupDoes the passage support what I wrote?Claim-by-claim check
IsUseIs 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.

Starting from the question and the text so far, the model decides whether to retrieve. If yes, it retrieves passages and assesses their relevance; if no, it continues without new retrieval. It generates candidates, assesses support and utility, selects text, and continues if more text is needed.

Simplified redraw after the Self-RAG authors’ overview (selfrag.github.io), CC BY-SA 4.0

Process

A retrieval decision, candidate generation, assessment of relevance, support, and utility, then selection of the text to keep.

Limit

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

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.