About this notebook
Companion to Module 5: RAG and knowledge. Every cell below was executed with the offline backend, so you can reproduce these outputs exactly with no API key. Download the notebook (.ipynb)
An agent that answers questions about your documents has to see the relevant part of them. Pasting everything into the prompt works for a page, not for a handbook, and not for a company wiki. Retrieval picks the few pieces that matter for one question. This notebook builds it from parts you can inspect, then measures it:
- a corpus with an answer key: a 44-document handbook and 24 labelled questions;
- chunking: fixed-size windows against the document’s own structure;
- BM25 from the formula, checked against the library version;
- vectors without a neural network: hashed features in a numpy vector store;
- hybrid search with reciprocal rank fusion;
- measuring: recall@k and MRR, broken down by the kind of question;
- retrieve, then answer: the passages go into the prompt.
Which model answers here?
Sections 1 to 6 call no model at all. Retrieval is ordinary code, and the numbers in those sections are real measurements on this corpus. Only Section 7 asks a model. With no
MODELset, the offline policy model answers there by copying the sentence or table row that covers most of the question’s words, with its source id. That is extractive question answering, not a language model: a real model would rephrase and combine passages, and it could also answer from its own knowledge, which the prompt forbids. The vectors in Section 4 come from a hashing trick, not a trained embedding model, and Section 6 shows exactly where that difference matters.
from agentlab.nbsetup import setup
nb = setup("05a_retrieval", packs=["rag"])
llm = nb.llmLLM backend
offline policy model (deterministic, rule-based, no API key used)
1. A handbook and an answer key
The corpus is the employee handbook of Orrin Valley Instruments, a fictional maker of weather stations, written for this course: travel and expense rules, HR policies, engineering practice, product notes. Every document is a short Markdown file.
from collections import Counter
from agentlab.llm.pricing import estimate_tokens
from agentlab.rag import load_handbook, load_questions
docs = load_handbook()
questions = load_questions()
by_section = Counter(d.section for d in docs)
handbook_tokens = sum(estimate_tokens(d.text) for d in docs)
print(f"{len(docs)} documents:",
", ".join(f"{s} {n}" for s, n in sorted(by_section.items())))
print(f"whole handbook: {sum(len(d.text) for d in docs):,} characters, "
f"about {handbook_tokens:,} tokens")
print()
print(next(d for d in docs if d.doc_id == "travel-lodging").text)44 documents: engineering 7, expenses 5, office 3, people 10, products 5, security 5, support 2, travel 7 whole handbook: 25,228 characters, about 6,325 tokens The company pays for lodging up to a nightly cap that depends on the city. Caps include taxes and fees, and are set by Finance once a year. | city | cap per night | |---|---| | Denver | USD 210 | | Oslo | NOK 1,800 | | Lisbon | EUR 160 | | Singapore | SGD 280 | | Toronto | CAD 250 | For any other city the cap is USD 200 per night, or the local equivalent. Book hotels through Wayfarer, which shows the cap next to each offer. Short-term rentals are allowed when they cost less than the cap. A stay above the cap needs a written reason in the expense report, for example a conference hotel that is fully booked at the negotiated rate. Minibar, laundry for trips shorter than five nights, and in-room movies are not reimbursed.
The whole handbook would fit in a modern context window. Retrieval still pays off, for three reasons. Every question would pay for every token, every time. A long context full of irrelevant text makes models worse at finding the relevant line (Liu et al., 2023, call it “lost in the middle”). And real document collections are thousands of times larger than this one.
To measure retrieval you need an answer key. Each question below is labelled with the document(s) that answer it, and with how its wording relates to the document’s:
for kind in ("exact term", "word variant", "paraphrase"):
group = [q for q in questions if q["kind"] == kind]
print(f"{kind:12s} ({len(group):2d} questions) e.g. {group[0]['question']!r}")
print(f"{'':28s}answer in: {', '.join(group[0]['gold'])}")exact term ( 8 questions) e.g. 'What does error code E-417 mean?'
answer in: prod-error-codes
word variant ( 9 questions) e.g. 'Can I be reimbursed for an ergonomic chair for working from home?'
answer in: expenses-home-office
paraphrase ( 7 questions) e.g. 'How many vacation days carry over to next year?'
answer in: people-vacation
Exact term questions share a distinctive word with the answer (“E-417”). Word variant questions use another form of the key word (“calibrating” where the document says “calibration”). Paraphrase questions use different words for the same idea (“work computer” for “laptop”). Keep these three groups in mind: different retrievers fail on different groups.
2. Chunking: what is one retrievable piece?
An index stores pieces of documents, and the retriever returns pieces. A piece should be small enough to be about one thing, and complete enough to make sense when it is the only thing the model sees. The simplest chunker cuts every 400 characters, with an 80-character overlap so that a sentence cut at one boundary appears whole in the next piece. Here is where those cuts fall in the longest travel document:
from agentlab.rag import fixed_size_chunks, structure_chunks
booking = next(d for d in docs if d.doc_id == "travel-booking")
fixed = fixed_size_chunks(booking.text, size=400, overlap=80)
for start, end, piece in fixed[:4]:
tail = " ".join(piece[-48:].split())
print(f"chars {start:4d}-{end:4d} ends with: ...{tail!r}")chars 0- 400 ends with: ...'e a third more, and the Travel Desk will ask for' chars 320- 720 ends with: ...'o needs approval from a director. The estimate i' chars 640-1040 ends with: ...'t of 6 hours or more you may book premium econom' chars 960-1360 ends with: ...'than 4 hours door to door, take the train. Rail'
The cuts land wherever the character count says: inside a word, a sentence, a list item or a table row. A piece also loses the heading that said what it was about. Snapping each cut to the nearest space or full stop helps a little. A structure-aware chunker uses the boundaries the author already wrote. It packs whole paragraphs, lists and tables into pieces of up to 600 characters, starts a new piece at every heading, and prefixes each piece with the document title and heading:
structured = structure_chunks(booking.text, title=booking.title, max_chars=600)
for start, end, piece in structured:
print(f"chars {start:4d}-{end:4d} {len(piece):3d} chars first line: "
f"{piece.splitlines()[0]!r}")chars 0- 242 267 chars first line: 'Booking business travel' chars 261- 528 307 chars first line: 'Booking business travel > When to book' chars 544- 893 386 chars first line: 'Booking business travel > Approvals' chars 915-1255 383 chars first line: 'Booking business travel > Class of travel' chars 1287-1478 244 chars first line: 'Booking business travel > Trains instead of flights' chars 1510-1790 333 chars first line: 'Booking business travel > Changes and cancellations' chars 1835-2105 336 chars first line: 'Booking business travel > Combining business and personal travel'
The prefix matters more than it looks. A table row “Oslo | NOK 1,800” says nothing about hotels on its own, but under “Lodging caps” it does, and the retriever can now match it to a question about hotel costs. Over the whole corpus:
from agentlab.rag import chunk_corpus
chunkings = {
"whole": chunk_corpus(docs, "whole"),
"fixed": chunk_corpus(docs, "fixed", size=400, overlap=80),
"structure": chunk_corpus(docs, "structure", max_chars=600),
}
for name, chunks in chunkings.items():
sizes = [len(c.text) for c in chunks]
print(f"{name:9s} {len(chunks):3d} chunks, mean {sum(sizes) / len(sizes):5.0f} chars, "
f"largest {max(sizes):5d}")
chunks = chunkings["structure"]whole 44 chunks, mean 596 chars, largest 2130 fixed 96 chunks, mean 306 chars, largest 400 structure 64 chunks, mean 416 chars, largest 609
3. BM25, written from the formula
BM25 is the classic lexical ranking function, and it is still the baseline every new
retriever is compared against (Robertson and Zaragoza, 2009). For a query
Here
import math
import numpy as np
from agentlab.rag import tokenize
def bm25_scores(query: str, texts: list[str], k1: float = 1.5, b: float = 0.75):
tokens = [tokenize(t) for t in texts]
n_docs = len(tokens)
avgdl = sum(len(t) for t in tokens) / n_docs
scores = np.zeros(n_docs)
for term in set(tokenize(query)):
n_t = sum(term in t for t in tokens)
idf = math.log((n_docs - n_t + 0.5) / (n_t + 0.5) + 1)
for i, t in enumerate(tokens):
f = t.count(term)
if f:
norm = k1 * (1 - b + b * len(t) / avgdl)
scores[i] += idf * f * (k1 + 1) / (f + norm)
return scores
texts = [c.text for c in chunks]
query = "What is the hotel cap per night in Oslo?"
mine = bm25_scores(query, texts)
for i in np.argsort(-mine, kind="stable")[:3]:
print(f"{mine[i]:5.2f} {chunks[i].chunk_id}")14.55 travel-lodging#0 9.49 travel-lodging#1 8.00 travel-per-diem#0
agentlab.rag.BM25Index computes the same thing with an inverted index, so a query
touches only the chunks that contain its words instead of scanning all of them. The two
agree to floating-point precision:
from agentlab.rag import BM25Index
bm25 = BM25Index(k1=1.5, b=0.75).fit(texts)
print("same scores:", np.allclose(mine, bm25.scores(query)))
for word in ("oslo", "night", "hotel", "per"):
print(f"idf({word!r}) = {bm25.idf(word):.2f}")same scores: True
idf('oslo') = 2.67
idf('night') = 3.26
idf('hotel') = 3.77
idf('per') = 1.31
“oslo” is rare and gets a high weight; “per” occurs everywhere and gets little. Now the weakness. BM25 matches words exactly, and the tokenizer deliberately does no stemming, so a different form of a word is a different word:
query = "How long does calibrating a sensor take?"
for term in tokenize(query):
print(f"{term!r:14} in {sum(term in tokenize(t) for t in texts):2d} chunks")
print()
for i, score in bm25.search(query, k=3):
print(f"{score:5.2f} {chunks[i].chunk_id}")'long' in 2 chunks 'calibrating' in 0 chunks 'sensor' in 6 chunks 'take' in 5 chunks 5.08 eng-data-retention#0 3.80 prod-calibration-service#0 3.80 prod-tern-ws2#4
No chunk contains “calibrating” (the documents say “calibration” and “calibrate”), so the most distinctive word in the question contributes nothing, and the ranking falls back on “long”, “sensor” and “take”. A stemmer that maps both words to “calibr” would fix this one case. The next section fixes the whole class differently.
4. Vectors without a neural network
A vector retriever maps every text to a point in a high-dimensional space. Each chunk is embedded once, at indexing time. At query time the query is embedded and the chunks whose vectors point in the most similar direction are returned, measured by cosine similarity. In production the embedding comes from a trained model, which places texts with similar meaning close together. That needs a model download or an API call, so this notebook uses a stand-in you can read in full: the hashing trick.
"calibrating" -> features: w:calibrating <ca cal ali ... ing> <cal cali ...
(the word itself, plus every 3-, 4- and 5-letter piece)
-> each feature is hashed to one of 2,048 positions (+1 or -1)
-> counts are damped (log), and the vector is scaled to length 1Two words that share many letter sequences share many positions, so their vectors point in similar directions. That captures spelling, not meaning:
from agentlab.rag import HashingEmbedder
embedder = HashingEmbedder(dim=2048)
words = ["calibrating", "calibration", "laptop", "computer"]
vectors = embedder.embed(words)
similarity = vectors @ vectors.T # unit vectors: the dot product is the cosine
print(" " * 12 + "".join(f"{w:>13}" for w in words))
for w, row in zip(words, similarity):
print(f"{w:12s}" + "".join(f"{x:13.2f}" for x in row))calibrating calibration laptop computer calibrating 1.00 0.68 0.00 0.00 calibration 0.68 1.00 0.00 0.00 laptop 0.00 0.00 1.00 0.00 computer 0.00 0.00 0.00 1.00
“calibrating” and “calibration” are close; “laptop” and “computer” are unrelated, as far as spelling goes. A trained embedding model would put the second pair close together too. A vector store is then just a matrix of unit vectors and a matrix product:
from agentlab.rag import NumpyVectorStore
store = NumpyVectorStore(embedder)
store.add(texts, ids=[c.chunk_id for c in chunks])
print(f"{len(store)} vectors of {embedder.dim} numbers, "
f"{store.matrix.nbytes / 1024:.0f} KiB")
for hit in store.search("How long does calibrating a sensor take?", k=3):
print(f"{hit.score:5.2f} {hit.id}")64 vectors of 2048 numbers, 512 KiB 0.37 prod-calibration-service#0 0.36 prod-tern-ws2#4 0.28 prod-error-codes#0
The calibration document is now first. A real vector database adds an approximate nearest-neighbour index (HNSW, IVF) so that search stays fast over millions of vectors. At 64 vectors, an exact matrix product is faster than any index.
5. Hybrid search: fuse the rankings, not the scores
BM25 is good at rare exact terms (error codes, product names); vectors are good at
variants and, with a real model, at paraphrases. Running both and merging the results is
the common default. Their scores cannot be added: a BM25 score is unbounded and depends on
the query, while a cosine lies between
The constant
from agentlab.rag import reciprocal_rank_fusion
lexical = ["A", "B", "C", "D"]
dense = ["C", "A", "E", "B"]
for item, score in reciprocal_rank_fusion([lexical, dense], k=60):
print(f"{item} {score:.4f}")A 0.0325 C 0.0323 B 0.0318 E 0.0159 D 0.0156
“A” (first and second) narrowly beats “C” (third and first). “E” and “D”, each found by
only one retriever, come last, but they still make the list. agentlab.rag.Retriever
indexes the chunks both ways and fuses the top 20 of each:
from agentlab.rag import Retriever
retriever = Retriever(chunks, embedder=embedder)
query = "How long does calibrating a sensor take?"
for mode in ("bm25", "vector", "hybrid"):
print(f"{mode:6s}", [h.chunk.doc_id for h in retriever.search(query, k=3, mode=mode)])bm25 ['eng-data-retention', 'prod-calibration-service', 'prod-tern-ws2'] vector ['prod-calibration-service', 'prod-tern-ws2', 'prod-error-codes'] hybrid ['prod-calibration-service', 'prod-tern-ws2', 'eng-data-retention']
6. Measuring: recall@k and MRR
Two numbers summarise a retriever on a labelled set. Recall@k is the share of the
answer documents that appear in the first
from agentlab.rag import evaluate_retriever
rows = []
for chunking, chunk_list in chunkings.items():
r = Retriever(chunk_list, embedder=embedder)
for mode in ("bm25", "vector", "hybrid"):
res = evaluate_retriever(lambda q: r.search_docs(q, k=10, mode=mode), questions)
rows.append((chunking, mode, res))
print(f"{'chunking':10s}{'retriever':10s}{'recall@1':>9}{'recall@3':>9}{'MRR':>7}")
for chunking, mode, res in rows:
print(f"{chunking:10s}{mode:10s}{res['recall@1']:9.2f}{res['recall@3']:9.2f}"
f"{res['mrr']:7.2f}")chunking retriever recall@1 recall@3 MRR whole bm25 0.77 0.96 0.87 whole vector 0.81 0.96 0.89 whole hybrid 0.85 0.92 0.91 fixed bm25 0.77 0.92 0.85 fixed vector 0.85 0.92 0.91 fixed hybrid 0.81 0.92 0.89 structure bm25 0.73 0.92 0.84 structure vector 0.81 0.92 0.89 structure hybrid 0.85 0.92 0.91
On this small corpus the differences between chunkings are small, because most documents are short enough to be one or two chunks anyway. The chunking choice matters more for long documents, and for what the model reads: three whole documents cost more tokens than three structured chunks (Section 7 measures it). The retriever choice matters more, and the breakdown by kind of question shows why:
import matplotlib.pyplot as plt
kinds = ["exact term", "word variant", "paraphrase"]
modes = ["bm25", "vector", "hybrid"]
colours = {"bm25": "#2c5f9e", "vector": "#b5523b", "hybrid": "#2c7d54"}
runs = {mode: res["runs"] for chunking, mode, res in rows if chunking == "structure"}
def recall_by_kind(run, kind, k=1):
group = [(q, ranked) for q, ranked in run if q["kind"] == kind]
hits = [len(set(q["gold"]) & set(ranked[:k])) / len(q["gold"]) for q, ranked in group]
return sum(hits) / len(hits)
x = np.arange(len(kinds))
fig, ax = plt.subplots(figsize=(6.4, 3.6))
for j, mode in enumerate(modes):
values = [recall_by_kind(runs[mode], kind) for kind in kinds]
bars = ax.bar(x + (j - 1) * 0.26, values, width=0.24, color=colours[mode], label=mode)
ax.bar_label(bars, fmt="%.2f", fontsize=8, padding=2)
counts = Counter(q["kind"] for q in questions)
ax.set_xticks(x, [f"{kind}\n({counts[kind]} questions)" for kind in kinds])
ax.set_ylabel("recall@1")
ax.set_ylim(0, 1.25)
ax.set_yticks([0, 0.25, 0.5, 0.75, 1.0])
ax.legend(frameon=False, loc="upper right", ncol=3)
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
plt.show()
Recall@1 on the 24 handbook questions by kind of question, with structure-aware chunks. Vectors built from letter sequences fix word variants that BM25 misses, and the hybrid ranks every one first; paraphrases are the weakest group for every retriever.
Exact terms are easy for everything; the 0.94 is q08, which has two answer documents, and one result at rank 1 can only be one of them. Word variants are where letter-sequence vectors pay off, and the hybrid gets them all at rank 1. Paraphrases are the open problem: these vectors know spelling, not meaning. Here are the questions the hybrid still misses at rank 1:
for q, ranked in runs["hybrid"]:
if ranked[0] not in q["gold"]:
rank = next((i for i, d in enumerate(ranked, 1) if d in q["gold"]), None)
where = f"rank {rank}" if rank else "not in the top 10"
print(f"{q['qid']} {q['kind']:12s} {q['question']}")
print(f" answer {q['gold'][0]} at {where}; first was {ranked[0]}")q20 paraphrase Who do I tell if my work computer gets stolen?
answer sec-laptops at rank 4; first was people-parental-leave
q21 paraphrase How long can a new mother or father stay home with the baby?
answer people-parental-leave at not in the top 10; first was expenses-home-office
q22 paraphrase When do salaries arrive?
answer people-payroll at rank 2; first was travel-booking
“work computer gets stolen” has no word in common with a document about laptops that are lost. A trained embedding model would very likely rank it first: closing exactly this gap is what such models are trained for. The reverse is also commonly reported: dense embeddings can blur rare identifiers such as error codes and part numbers, where BM25 is sharp. That is the argument for hybrid search. This notebook does not demonstrate that second effect, because the hashing embedder keeps exact words as features.
7. Retrieve, then answer
Retrieval-augmented generation (Lewis et al., 2020) puts the retrieved passages into the prompt and asks the model to answer from them. Three instructions do most of the work: use only the passages, cite them, and say so when they do not contain the answer.
from agentlab import LlmRequest, Message
from agentlab.rag import format_hits
RAG_INSTRUCTIONS = (
"Answer the question using only the passages between <passages> tags. "
"Cite the source id of every passage you use, in brackets. "
"If the passages do not contain the answer, say so instead of guessing.")
def rag_prompt(question: str, k: int = 3) -> str:
passages = format_hits(retriever.search(question, k=k))
return f"<passages>\n{passages}\n</passages>\n\nQuestion: {question}"
async def answer(question: str) -> str:
request = LlmRequest(instructions=[RAG_INSTRUCTIONS],
contents=[Message(role="user", content=rag_prompt(question))])
return (await llm.generate(request)).text
print(rag_prompt("What is the hotel cap per night in Oslo?")[:700], "...")<passages> [1] source: travel-lodging Lodging caps The company pays for lodging up to a nightly cap that depends on the city. Caps include taxes and fees, and are set by Finance once a year. | city | cap per night | |---|---| | Denver | USD 210 | | Oslo | NOK 1,800 | | Lisbon | EUR 160 | | Singapore | SGD 280 | | Toronto | CAD 250 | For any other city the cap is USD 200 per night, or the local equivalent. [2] source: travel-lodging Lodging caps Book hotels through Wayfarer, which shows the cap next to each offer. Short-term rentals are allowed when they cost less than the cap. A stay above the cap needs a written reason in the expense report, for example a conference hotel that is fully ...
That is the whole prompt apart from the instructions. Now three questions: one the retriever handles, one it misses (the stolen computer), and one the handbook does not cover at all.
for question in ["What is the hotel cap per night in Oslo?",
"Who do I tell if my work computer gets stolen?",
"Can I bring my dog to the office?"]:
print(f"Q: {question}\nA: {await answer(question)}\n")Q: What is the hotel cap per night in Oslo? A: Lodging caps: city Oslo; cap per night NOK 1,800 [source: travel-lodging] Q: Who do I tell if my work computer gets stolen? A: The passages I was given do not answer this question. Q: Can I bring my dog to the office? A: The passages I was given do not answer this question.
The first answer is a table row and its source. The second is the right behaviour given what was retrieved, but it is a retrieval failure: the answer is in the handbook, and the user gets nothing. A real model behaves differently in a way worth knowing. It would write a fluent sentence instead of copying a row, and on the second question it might answer from general knowledge (“tell your IT department”), which sounds right and cites nothing. That is why the instruction to say “not in the passages” is there, and why Notebook 10b grades answers for groundedness.
What did retrieval save? Compare the prompt with one that pastes the whole handbook:
from agentlab.llm.pricing import reference_cost
question = "What is the hotel cap per night in Oslo?"
whole_docs = Retriever(chunkings["whole"], embedder=embedder)
prompts = {
"top 3 structured chunks": rag_prompt(question),
"top 3 whole documents": format_hits(whole_docs.search(question, k=3)) + question,
}
sizes = {name: estimate_tokens(RAG_INSTRUCTIONS + p) for name, p in prompts.items()}
sizes["whole handbook"] = handbook_tokens + estimate_tokens(RAG_INSTRUCTIONS + question)
for name, n in sizes.items():
cost = reference_cost(n, 0) * 1000
print(f"{name:24s} {n:6,} input tokens, USD {cost:.2f} per 1,000 questions")
ratio = sizes["whole handbook"] / sizes["top 3 structured chunks"]
print(f"the whole handbook costs {ratio:.0f} times as much per question")top 3 structured chunks 376 input tokens, USD 0.38 per 1,000 questions top 3 whole documents 663 input tokens, USD 0.66 per 1,000 questions whole handbook 6,385 input tokens, USD 6.38 per 1,000 questions the whole handbook costs 17 times as much per question
The prices are the course’s round reference rate (USD 1 per million input tokens), not a quote. The ratio is the point, and it grows with the corpus: retrieval costs the same few hundred tokens whether the handbook has 44 documents or 44,000, while pasting everything grows with every page added.
Try this
- Change
max_charsinchunk_corpus(docs, "structure", max_chars=...)to 300 and to 1,200 and re-run Section 6. What happens to recall@1, and to the tokens per prompt?- Set
k1=0inBM25Index. What does the score reduce to? Then setb=0. Which questions change rank, and why?- Add query expansion: before searching, append synonyms from a small table (
{"computer": "laptop", "stolen": "lost"}). How many paraphrase questions does it fix, and what does it cost you to maintain the table?- With network access, write a class with a method
embed(texts) -> np.ndarraythat calls a real embedding model (for example throughlitellm.embedding), pass it asRetriever(chunks, embedder=...), and re-run Section 6. Do the paraphrase questions improve? Does anything get worse?
nb.usage()| model calls | input tokens | output tokens | cost |
|---|---|---|---|
| 3 (fake: 3) | ≈ 1,294 | ≈ 47 | ≈ USD 0.0015 (reference price) |