TEXTBOOK·ENGINEERING AI AGENTSPreviousCHAPTER 02 OF 15NextContents
02LLMS FOR BUILDERS + RAG

Model calls and retrieval

A model call returns a sample, not a theorem. Reliability is something you build around the call — with schemas, validation, and evidence the answer can be checked against.

2.1The model call as an unreliable function

The API returns a sample, not a theorem. Reliability comes from schema enforcement, semantic validation, observability, and task-level evaluation.

Keep three layers separate: syntactic validity (does it parse?), semantic validity (is it supported?), and policy validity (may the system act on it?). Constrained generation addresses only the first.

TYPED BOUNDARY
class Answer:
    answer: str
    citations: list[str]
    confidence: float

raw = model.generate(messages, response_schema=Answer)
parsed = validate_syntax(raw)
checked = validate_semantics(parsed, retrieved_sources)

2.2Constrained decoding

A model produces logits over its vocabulary. Compile a JSON Schema or grammar into an incremental parser state, determine which token byte sequences are legal continuations, and mask all other logits before sampling.

Production implementations use a tokenizer trie and cache masks by parser state. Grammar validity cannot ensure a citation exists, a confidence score is calibrated, or a tool call is appropriate.

p′(v | prefix) ∝ p(v | prefix) · 𝟙[v ∈ A(prefix)]
A(prefix) is the valid next-token set implied by the grammar and the current parser state.
DECODER PSEUDOCODE
state = grammar.start_state()

while not state.accepting:
    logits  = model.next_logits(tokens)
    allowed = token_trie.valid_extensions(state)
    logits[not allowed] = -inf
    token = sample(logits)
    state.consume(token.bytes)

2.3Decoding, context, and model selection

Model selection should be made per stage. A cheap model can rewrite queries; a stronger one can synthesise the final evidence. Evaluate the whole system, because an expensive component may lower total cost if it prevents retries.

maximise E[quality(x)] subject to cost(x) ≤ C, p95-latency(x) ≤ L
DECISIONUSEFAILURE TO WATCH
Low temperatureExtraction, tool argumentsSystematic error, no diversity
Multiple samplesCandidates when a scorer existsCost grows; errors correlate
Larger modelHard synthesis or planningWasted budget on trivial routing
More contextRelevant evidence and stateAttention dilution, stale instructions

2.4Retrieval before generation

BM25 rewards exact lexical overlap with term-frequency saturation and document-length normalisation. Dense retrieval embeds queries and passages into a shared vector space, which improves paraphrase matching but can miss identifiers and rare strings.

A robust baseline is hybrid retrieval followed by reranking. Reciprocal Rank Fusion combines ranked lists without requiring calibrated score scales.

A cross-encoder jointly processes each query–document pair, offering rich interaction at high cost. ColBERT contextualises query and document tokens independently, then performs token-level late interaction.

RRF(d) = Σ 1 / (k + rank(d))
Fusion by rank, not by score, so two rankers need no shared scale.
score(Q,D) = Σᵢ maxⱼ qᵢᵀdⱼ
With normalised token vectors the dot product is cosine similarity. MaxSim is the aggregation strategy, not a different primitive.

2.5ColBERTv2: making late interaction affordable

ColBERT keeps one vector per token, which is why it works and why it was impractical. At 128 dimensions and two bytes per value, that is 256 bytes per token. The 8.8 million passages of MS MARCO occupy 286 GiB at four bytes per dimension in the re-ranking configuration, and 154 GiB in the end-to-end variant — either way, roughly a hundred times a single-vector index over the same corpus.

ColBERTv2 rests on an observation about the geometry: token vectors cluster tightly around a modest number of semantic centroids. A token's meaning is mostly determined by which centroid it sits near, and the residual carries only context-specific refinement. So do not store the vector. Store the centroid index and a cheap encoding of the residual.

One or two bits per dimension sounds destructive and is not, because the scheme quantises a residual rather than a vector. Two bits is the default and matches uncompressed quality; one bit trades a little accuracy for a further nine gibibytes. The residual is small and roughly zero-centred, so its sign carries most of what remains once the centroid has absorbed direction and magnitude. Product quantisation works for the same reason: quantise the error, not the signal.

r = v − C, C = argmin over centroids of ‖v − c‖
The residual against the nearest centroid, computed once at index time.
bytes/token = 4 + m·b/8 = 20 (b=1) or 36 (b=2)
Four bytes for the centroid index plus m=128 dimensions at b bits, against 256 bytes uncompressed.
CONFIGURATIONINDEX SIZEMRR@10
ColBERT, float32286 GiB34.9 (re-ranking)
ColBERT, end-to-end L2154 GiB36.0
ColBERTv2, b = 225 GiB36.2
ColBERTv2, b = 116 GiB35.5

2.6Chunking sets the ceiling

No reranker recovers a fact that was split across a boundary, and no embedding represents a chunk containing four unrelated topics. Chunking is decided before anything else and constrains everything after it.

The tension is exact. Retrieval precision wants small chunks, because a short span embeds to a vector that means one thing. Generation quality wants large chunks, because a short span often lacks the antecedents and qualifying clauses needed to read it correctly. A chunk reading “This does not apply to enterprise accounts” is retrievable and useless.

Two decompositions resolve most of this without choosing a size. Sentence-window retrieval indexes one or two sentences but returns the surrounding window. Parent-document retrieval indexes small children and returns the whole parent section. In both, the unit you match on and the unit you read from are different objects — which is correct, because those two jobs never wanted the same size.

STRATEGYMATCH ONRETURNCOSTS
Fixed + overlap512 tokensthe samecuts through meaning
Structurala sectionthe samewildly uneven sizes
Sentence-window1–2 sentences±3 sentencesextra store for windows
Parent-documentchild chunkfull parentduplicated storage, longer prompts

2.7Rewriting the query before you run it

The query the user typed is often not the query you should run, and three distinct failures live here.

Conversational dependence is the first and the most damaging in agent systems. “What about the enterprise tier?” has no subject; as a standalone retrieval string it means nothing. A rewriting step folds the conversation history into a self-contained query. Skipping it is the most common reason retrieval collapses after the second turn.

Vocabulary mismatch is the second, and it falls on the lexical leg. A query and the passage that answers it may share no terms at all, so a term-matching retriever scores zero however relevant the passage is. Expanding the query with synonyms, expanded acronyms, and morphological variants recovers those matches. It does little for dense retrieval, which already handles synonymy.

R = RRF( retrieve(q₀), retrieve(q₁), … , retrieve(qₙ) )
Always keep the original q₀ as one leg, so a faulty rewrite degrades the result instead of replacing it.
TECHNIQUEFAILURE ADDRESSEDWATCH FOR
Conversational rewriteAnaphora after turn twoDrifted entity names
Synonym expansionLexical mismatch on the BM25 legExpansion swamping the rare term
Multi-queryQuestions with several facetsContext bloat; needs reranking
Step-backMissing governing contextOver-general passages crowding out specifics

2.8Repairing context at index time

Chunking destroys context by construction. Three techniques repair it before a query ever arrives, each at a different scale.

Contextual retrieval repairs local loss. A chunk reading “revenue grew by 3% over the previous quarter” cannot be retrieved by any query naming the company or the period, because neither appears in the chunk. Pass the whole document and the chunk to a cheap model, ask for fifty to a hundred tokens of situating context, and prepend it before indexing. Reported top-20 failure rates fall from 5.7% to 3.7% with contextual embeddings, to 2.9% adding contextual BM25, and to 1.9% with reranking.

RAPTOR repairs mid-scale loss, where a question needs synthesis across a chapter and no leaf chunk holds the answer. Cluster the chunks, summarise each cluster, embed the summaries, and recurse upward into a tree. Index every level together, so specific questions land on leaves and thematic ones on interior summaries.

GraphRAG repairs corpus-scale loss. “What are the main themes across these three thousand tickets?” is not a retrieval question at all — no top-k answers it, because the answer is a property of the whole corpus. Extract entities and relations, detect communities, summarise each, then answer by map-reduce over those summaries.

TECHNIQUELOSS REPAIREDINDEX COSTUSE WHEN
Contextual retrievalMissing referentsOne cheap call per chunkAlmost always
RAPTORCross-section synthesisCluster and summarise, recursivelyBooks, manuals, filings
GraphRAGCorpus-wide themesEntity extraction over everythingSensemaking traffic

2.9Measuring retrieval on its own

Retrieval metrics need labels: a set of queries and, for each, which documents are relevant. Building a hundred to three hundred of these against your own corpus is the highest-value day of work in a retrieval project, and the one most often skipped in favour of reading outputs and forming an impression.

Recall@k ignores order entirely, which makes it right for the first stage — the retriever's only job is to avoid losing the answer. Mean reciprocal rank measures how far down the first correct result sits, and its discount is harsh: rank one scores 1.0, rank ten scores 0.1. It says nothing about the second relevant document. Normalised discounted cumulative gain handles graded relevance and several relevant documents, discounting logarithmically by rank, which makes it the right metric once a reranker is in play.

Report all three, because they disagree in informative ways. High recall with low nDCG means retrieval works and ranking does not — add a reranker. Low recall with high nDCG means you answer the easy queries perfectly and miss an entire class. Both low means the embedding model or the chunking is wrong, and nothing downstream will rescue it.

Recall@k = |relevant ∩ top-k| / |relevant|
Order-insensitive. The first-stage metric.
nDCG@k = DCG@k / IDCG@k, DCG = Σ relᵢ / log₂(i+1)
Normalised against the best achievable ordering, so scores compare across queries with different numbers of relevant documents.
RECALL@50nDCG@10DIAGNOSISNEXT ACTION
0.940.31Retrieval fine, ranking poorAdd a cross-encoder reranker
0.520.68Finds easy queries, misses a classInspect misses; check chunking
0.410.22The foundation is wrongRevisit embedding model and chunk size
0.960.81Retrieval is healthyMove to generation-side evaluation

2.10Vector search underneath retrieval

Every retrieval diagram contains an arrow labelled “retrieve”. This section describes what happens inside it. The problem in its exact form: you hold N vectors of dimension d, a query arrives as another vector, and you want the k nearest. An exact answer requires comparing the query against all N, at d multiply-adds each. That cost cannot be engineered away without giving up exactness.

Put numbers on it. Ten million vectors at 768 dimensions in single precision occupy 30.7 gigabytes, or 28.6 gibibytes, which already exceeds the memory of most machines you would want to pay for, and each query costs roughly 7.7 billion multiply-adds. At ten queries a second you have saturated a server.

This is the entire motivation for approximate search. Every index below is a scheme for not looking at most of the database, and each pays for that with recall. The question is never whether it is exact — it is what recall, at what latency, at what memory cost, and whether that recall is good enough for the generator downstream.

Students routinely overlook the last clause. A pipeline retrieving twenty chunks does not need perfect recall. If the answer-bearing chunk sits in the true top five and the index returns it at rank seven, nothing downstream is affected. Set recall targets against the behaviour of the generator rather than against a leaderboard.

cost_exact = N × d multiply-adds per query
At ten million vectors and 768 dimensions this is 7.68 billion operations for a single query.

2.11Metrics, and why they collapse into each other

Three metrics appear in practice: squared Euclidean distance, inner product, and cosine similarity. The two that matter in practice are distance and inner product, and cosine is deliberately absent from most libraries — it is inner product on normalised vectors, so implementing it separately would be redundant.

Expanding the squared distance makes the relationship visible. For a fixed query, the term involving the query's own norm is constant across candidates and cannot affect the ranking, so ranking by distance reduces to ranking by the document norm minus twice the dot product. The two metrics therefore agree only when every stored vector has the same norm, which is the condition normalisation establishes.

Without normalisation they disagree, and the disagreement has a direction: inner product rewards magnitude, so a long vector pointing roughly the right way beats a short vector pointing exactly the right way. For most text embedding models magnitude correlates with chunk length rather than relevance, which is why nearly every text stack normalises. For models that deliberately encode popularity in the norm, raw inner product is correct and normalising destroys information.

Read the model card before choosing. Using the wrong metric degrades quality without raising a single error, which is the worst failure category there is.

‖x − y‖² = ‖x‖² + ‖y‖² − 2⟨x, y⟩
The identity linking the two metrics. For a fixed query the first term is constant and cannot affect ranking.
‖x‖ = ‖y‖ = 1 ⟹ ‖x − y‖² = 2 − 2⟨x, y⟩
On unit-norm vectors, minimising distance and maximising the dot product give identical orderings.

2.12Three index structures

The flat index stores vectors contiguously and compares against every one. No training, no parameters, no approximation. It is not a strawman: it is the correct choice more often than the literature suggests, and it is the only thing that can tell you what recall an approximate index actually achieves. You cannot compute recall without ground truth, and for anything under a few million vectors the cheapest ground truth is a flat index run offline over your evaluation queries.

The inverted file index attacks the number of vectors rather than their width. Cluster the database into cells, store which vectors landed in each, and at query time compare against the cell centroids and scan only the nearest few. With sixteen thousand cells and thirty-two probes you touch about two thousandths of the database. The cost is the boundary problem: a query near a cell edge has true neighbours on the other side, and they are never considered at all.

Product quantisation attacks memory instead. Split each vector into subvectors, learn a small codebook per subspace, and replace every subvector with a one-byte centroid index. At 768 dimensions split into ninety-six pieces, a 3,072-byte vector becomes 96 bytes — thirty-two times smaller. Combining the two, and quantising the residual against the coarse centroid rather than the raw vector, gives the structure most large systems actually run.

The hierarchical graph takes a different route: build a proximity graph, assign each node a maximum layer from a decaying distribution, and walk greedily downhill from a sparse top layer to a dense base. It has the best recall per millisecond of the mainstream methods and costs more memory than the flat index it replaces — it is not a compression scheme, it buys latency with memory.

INDEXBYTES / VECTOR10M TOTALRECALLUSE WHEN
Flat3,07230.7 GB1.000Under ~100k vectors, or few queries
IVF flat3,08030.8 GB0.95 – 0.99Speed needed, memory available
IVF-PQ (m = 96)1041.04 GB0.85 – 0.95Large corpus, limited memory
HNSW (M = 32)3,32833.3 GB0.96 – 0.99Latency critical; deletes need rebuilds

2.13Choosing an operating point

There is no correct value for the probe count. There is a curve, and a point on it your product can live with. Measuring that curve is mechanical and should happen before the index reaches production.

Hold out a thousand to ten thousand real queries — real ones from logs, because synthetic queries have different distance distributions and will mislead you. Build a flat index and compute exact results once; that is ground truth and it changes only when the corpus or the embedding model changes. Then sweep the parameter, recording mean recall and the full latency distribution at each setting.

Report the ninety-fifth or ninety-ninth percentile, never the mean. Retrieval sits inside a user-facing request and the tail is what determines whether you meet your latency target. Plotted against each other, recall and latency form a hockey stick: recall climbs steeply while latency is cheap, then flattens while latency keeps rising.

Take the operating point at the knee — the last setting where more latency still buys meaningful recall. For most systems that lands around ninety to ninety-five per cent recall at ten. Going from there to ninety-nine typically costs three to five times the latency and changes generated answers almost never, because the chunks at ranks eight to ten rarely carry the answer when the earlier ranks did not.

Below roughly a hundred thousand vectors, skip all of this. A flat scan at that size is a few milliseconds, memory is a few hundred megabytes, recall is exactly one, there are no parameters to tune, and there is no drift between index and data. An approximate index there is complexity you have chosen to maintain for no benefit.

N (d = 768)FLAT MEMORYOPS / QUERYRECOMMENDATION
10,00031 MB7.7 × 10⁶Flat. An index here is pure overhead.
100,000307 MB7.7 × 10⁷Flat. Milliseconds, perfect recall, no tuning.
1,000,0003.1 GB7.7 × 10⁸Crossover. Measure before deciding.
10,000,00030.7 GB7.7 × 10⁹IVF-PQ or a graph index.
STUDIO 02

Build RAG from scratch

Index a small paper corpus. Compare BM25, dense retrieval, hybrid fusion, and a reranker over thirty questions. Report Recall@k, MRR, grounded-answer accuracy, citation entailment, latency, and token cost. Include three failure traces where the answer generator was blamed incorrectly.

KNOWLEDGE CHECK
READING
PRIMARYRetrieval-Augmented Generation for Knowledge-Intensive NLP Tasks
PRIMARYColBERT: Efficient and Effective Passage Search
PRACTICEBuilding Effective Agents