A model knows what was in its training data, up to a cutoff date. Your company’s travel
policy, last week’s incident report and your own product’s error codes are not in it. The
model will still answer questions about them, fluently and wrongly. The fix is to put the
right text in front of the model when it answers, and the hard part is the word “right”.
The course’s made-up handbook has 44 pages and about 6,300 tokens. Sending all of it with
every question costs 17 times as much as sending the three most relevant passages, and real
document collections are thousands of times larger. So this module is about choosing. It
covers how to cut documents into pieces, how to score the pieces against a question, how
to tell whether the scoring works, and how to let the agent do the searching itself.
Notebooks
Notebook 5a: Retrieval chunks the handbook three ways. It
implements BM25 from its formula, builds a vector store, fuses the two with reciprocal
rank fusion, and measures recall on 24 questions of three kinds.
Notebook 5b: Agentic RAG turns retrieval into a tool and
answers a two-hop question. It browses the handbook as files, adds callbacks that log,
cache, block and compress, and pauses for approval before sending an email.
Retrieval-augmented generation
Definition 5.1 (Retrieval-augmented generation).
Retrieval-augmented generation (RAG) answers a question in two stages. A
retriever scores the pieces of a document collection against the question and
returns the top . A generator, the language model, then answers from a prompt
that holds the question, those passages and an instruction to use only them and to cite
their sources.
Lewis et al. (2020) introduced the name, for a retriever and generator trained together.
Today the retriever is usually a separate search system and the generator an unchanged
model, which is the version this module builds. Two properties of RAG (Definition 5.1) matter as
much as accuracy. The knowledge is current: edit a document and the next answer uses it,
with no retraining. And the answer is checkable: each claim points at a passage that a
person can read.
Retrieval also helps with a problem of long contexts. A model with a large window can read
the whole handbook, but Liu et al. (2023) found that models use information at the start
and end of a long context much better than information in the middle. A short prompt with
the right passages is cheaper and easier for the model to use.
Remark 5.1 (Saying "not found" is part of the job).
The RAG prompt in Notebook 5a tells the model to say so when the passages do not answer
the question. That instruction matters most when retrieval fails. For “Who do I tell if
my work computer gets stolen?” the right page is not in the top three, and the answer is
a refusal instead of a guess. A retriever’s misses become wrong answers unless the
generator is allowed to say no.
Chunks: the unit of retrieval
A retriever does not return documents. It returns chunks, the pieces the collection was
cut into before indexing, and the choice of chunk decides what a hit can contain.
Fixed-size chunks cut every 400 characters, with some overlap. They are simple and
blind to the text. In Notebook 5a they cut words in half and separate table rows from
their header.
Structure-aware chunks split at headings and paragraphs, up to a maximum size, and
start each chunk with the document title and section heading. A row such as
| Oslo | NOK 1,800 | stays under the header that says it is a nightly hotel cap.
Whole documents keep everything together. The price is long passages that cost
tokens and mix topics.
For this handbook the three choices give 44, 96 and 64 chunks. On the 24 test questions,
the choice changes recall at rank 1 by at most one question for any one retriever. What
differs more is the passage a hit returns: a fixed-size hit can be half a table, while a
structure-aware hit carries its own context. Anthropic’s contextual retrieval (2024) takes
the idea further. Before indexing, a model writes a sentence for each chunk that places it
in its document.
Scoring passages: words and vectors
There are two families of retrievers, and they fail in different places.
Definition 5.2 (BM25).
BM25 scores a chunk against a query by the query words that contains.
Rare words count more, repeats count with diminishing returns, and long chunks are
penalised:
Here counts in , is the chunk’s length in words and
the average length, is the number of chunks and the number
that contain . The usual constants are and .
BM25 (Robertson and Zaragoza, 2009) is old, fast and hard to beat on exact terms. An error
code such as E-417 is a rare word with a high IDF, and BM25 finds it at once. Its weakness
comes from the same property: in , a word that is not in the chunk adds
nothing. “Calibrating” does not match “calibration”, which in Notebook 5a appears in zero
chunks, and “computer” does not match “laptop”.
A vector retriever maps each chunk and the query to a vector and ranks chunks by cosine
similarity. A trained embedding model, such as dense passage retrieval (Karpukhin et al.,
2020), places texts with similar meanings close together, so “computer” can find “laptop”.
The offline notebooks use a hashing embedder built from letter sequences, which needs no
download. It fixes word variants (the cosine of “calibrating” and “calibration” is 0.68)
but knows nothing about meaning (the cosine of “laptop” and “computer” is 0). It shows how
vector search works, not how well it can work.
Definition 5.3 (Reciprocal rank fusion).
Hybrid retrieval runs several retrievers and merges their ranked lists.
Reciprocal rank fusion (RRF) merges them using ranks only:
where is the position of chunk in retriever ‘s list. A
chunk missing from a list adds nothing for that list.
Raw scores cannot be added: a BM25 score (Definition 5.2) of 14 and a cosine of 0.37 are on different
scales. First place and third place are on the same scale for every retriever. The constant
flattens the curve, so a chunk near the top of both lists beats one that is first in a
single list. Cormack et al. (2009) found that this simple rule beat more elaborate fusion
methods.
index of chunksqueryfrom the agentBM25rare exact wordsvectorsnearby embeddingsRRF1 / (k + rank)top 3to the prompt
Measuring a retriever
A retriever can be tested without the model, which is cheaper and tells you more than
grading answers. Notebook 5a uses 24 questions with known source documents, in three kinds.
Eight contain an exact term from the page, nine use a different form of a word on the page,
and seven paraphrase it without its words. Write for the gold documents of question
, for the top results and for the position of the
first gold document. Then
With structure-aware chunks, all three retrievers find 0.94 of the exact-term answers at
rank 1. On word variants, recall@1 is 0.78 with BM25, 0.89 with vectors and 1.00 with the
hybrid (Definition 5.3). On paraphrases it is 0.43, 0.57 and 0.57. By , the
overall MRR rises from 0.84 for BM25 to 0.91 for the hybrid. The numbers support the usual advice to
start with hybrid retrieval, and they show its limit. No mix of letter-matching methods
finds a paraphrase. Only a model of meaning can, which is what a real embedding model adds.
Remark 5.2 (Small test sets).
Seven paraphrase questions is a tiny sample, and one question moves the score by 14
points. The standard error from Module 4 applies here as well. Use the numbers to find
which kind of question fails, then read those failures. Notebook 5a prints the three
paraphrases the hybrid misses. For one of them, the right page is not even in the top
ten.
Retrieval as a tool
So far the program decided when to search and what to search for: once, with the user’s
words. CS329Z Lecture 3 names the three decisions that this leaves out. Should the agent
retrieve at all or answer directly? What query should it send? Are the results good
enough, is another search needed, or is the answer not there at all (Remark 5.1)?
Definition 5.4 (Agentic RAG).
In agentic RAG the retriever is a tool. The model writes its own queries, sees the
results as observations, and decides whether to search again, use another tool, or
answer.
The gain shows on questions that need two facts. “What is the nightly hotel cap in Oslo in
US dollars?” needs the cap and the exchange rate, which sit in different documents. One
search with the question returns the lodging page and part of the currency page, but not
the chunk with the rate table. In Notebook 5b the agent searches again with its own query
for the rate and then calls the calculator: NOK 1,800 at 10.50 NOK per dollar is USD
171.43. A fixed pipeline with one search could not have answered.
An index is one way to search. The other is to browse the way a person uses a file
system: list a folder, read a file, search the files for a string. The book uses this for
benchmark tasks whose answers are in attached files, and coding agents work this way on
code. Browsing needs no index, always sees the current files, and can follow the folder
structure. It costs more steps per question, and it depends on the agent guessing where to
look. File tools must also keep the agent inside its workspace. In Notebook 5b, a request
for ../../../../pyproject.toml raises a PermissionError.
index (retrieval)
browse (file tools)
set-up
chunk and index first
none
after a document changes
stale until re-indexed
current
cost per question
one search
several list and read steps
good for
many documents, unknown location
known folders, exact strings, code
Callbacks: changing what the agent sees
An agentic RAG system (Definition 5.4) needs plumbing that is not the model’s job, such as
logging calls, caching results, blocking some sources and shrinking large results. The
course’s Agent has hooks for this, as the book’s does.
Definition 5.5 (Tool callbacks).
A before-tool callback receives each tool call before the tool runs. If it returns a
result, the tool is skipped and the agent uses that result. An after-tool callback
receives the call and its result and may return a replacement. Both run in the harness:
the model sees only their effect.
Notebook 5b writes four of them. A logger prints every call, and a cache answers a repeated
call without running the tool. A guard refuses to read the security folder and tells the
model why. A compression callback shortens web search results, and it is the most
instructive of the four. The raw results for a question about the Airport Express fare come
to 5,072 characters, about 1,268 tokens, from three pages of which one paragraph matters.
The callback splits the results into passages, ranks them against the agent’s query and
keeps the best three:
Compression is retrieval applied to a tool’s output, and it fails the way retrieval does.
With the agent’s query (“What does an adult single ticket on the Airport Express cost”)
the passage with the fare survives. With a vaguer one (“the Airport Express train from
Oslo airport cost”) it is dropped, and the agent never learns it was there. The same run
shows a problem that no retriever fixes: the web says the fare is NOK 240 and the
handbook says NOK 230. When sources disagree, the agent has to say which one it used.
Pausing before side effects
Retrieval only reads. Sooner or later an agent also acts: it sends an email, books a trip
or files a report. A tool with side effects can be marked requires_confirmation. When the
model calls it, the run stops with status pending_confirmation and keeps the call. A
person approves the call, possibly with edited arguments, or rejects it with a reason, and
the run resumes from the same context. In Notebook 5b the person approves an email after
adding a sentence to its body. A second request, to email the whole company, is rejected.
The model sees the reason as the tool’s result, and the outbox still holds one email.
Module 6 stores the paused call in a session, so it can be approved after a restart.
Try this
In Notebook 5a, write three paraphrase questions of your own and add them to the
evaluation. Which retriever finds them, and how far does each score move
(Remark 5.2)? Then try TfidfEmbedder instead of
HashingEmbedder. Why does it not help with paraphrases either?
In equation , which chunk wins: one ranked first by one retriever and
missing from the other, or one ranked third by one and fourth by the other? Work it out
for and for , then check with reciprocal_rank_fusion.
In Notebook 5b, give the compression callback keep=1. Which question now loses its
answer (Remark 5.3)?
Write a before-tool callback (Definition 5.5) that refuses read_file for any file over
20 KB and tells the model to use search_files instead.
Readings
Hur and Song, Build an AI Agent (From Scratch), Manning 2026, chapter 5.
Stanford CS329Z, Engineering AI Agents, Lecture 3: RAG and agents
(slides).