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.
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.
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.
| DECISION | USE | FAILURE TO WATCH |
|---|---|---|
| Low temperature | Extraction, tool arguments | Systematic error, no diversity |
| Multiple samples | Candidates when a scorer exists | Cost grows; errors correlate |
| Larger model | Hard synthesis or planning | Wasted budget on trivial routing |
| More context | Relevant evidence and state | Attention 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.
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.
| CONFIGURATION | INDEX SIZE | MRR@10 |
|---|---|---|
| ColBERT, float32 | 286 GiB | 34.9 (re-ranking) |
| ColBERT, end-to-end L2 | 154 GiB | 36.0 |
| ColBERTv2, b = 2 | 25 GiB | 36.2 |
| ColBERTv2, b = 1 | 16 GiB | 35.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.
| STRATEGY | MATCH ON | RETURN | COSTS |
|---|---|---|---|
| Fixed + overlap | 512 tokens | the same | cuts through meaning |
| Structural | a section | the same | wildly uneven sizes |
| Sentence-window | 1–2 sentences | ±3 sentences | extra store for windows |
| Parent-document | child chunk | full parent | duplicated 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.
| TECHNIQUE | FAILURE ADDRESSED | WATCH FOR |
|---|---|---|
| Conversational rewrite | Anaphora after turn two | Drifted entity names |
| Synonym expansion | Lexical mismatch on the BM25 leg | Expansion swamping the rare term |
| Multi-query | Questions with several facets | Context bloat; needs reranking |
| Step-back | Missing governing context | Over-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.
| TECHNIQUE | LOSS REPAIRED | INDEX COST | USE WHEN |
|---|---|---|---|
| Contextual retrieval | Missing referents | One cheap call per chunk | Almost always |
| RAPTOR | Cross-section synthesis | Cluster and summarise, recursively | Books, manuals, filings |
| GraphRAG | Corpus-wide themes | Entity extraction over everything | Sensemaking 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@50 | nDCG@10 | DIAGNOSIS | NEXT ACTION |
|---|---|---|---|
| 0.94 | 0.31 | Retrieval fine, ranking poor | Add a cross-encoder reranker |
| 0.52 | 0.68 | Finds easy queries, misses a class | Inspect misses; check chunking |
| 0.41 | 0.22 | The foundation is wrong | Revisit embedding model and chunk size |
| 0.96 | 0.81 | Retrieval is healthy | Move 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.
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.
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.
| INDEX | BYTES / VECTOR | 10M TOTAL | RECALL | USE WHEN |
|---|---|---|---|---|
| Flat | 3,072 | 30.7 GB | 1.000 | Under ~100k vectors, or few queries |
| IVF flat | 3,080 | 30.8 GB | 0.95 – 0.99 | Speed needed, memory available |
| IVF-PQ (m = 96) | 104 | 1.04 GB | 0.85 – 0.95 | Large corpus, limited memory |
| HNSW (M = 32) | 3,328 | 33.3 GB | 0.96 – 0.99 | Latency 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 MEMORY | OPS / QUERY | RECOMMENDATION |
|---|---|---|---|
| 10,000 | 31 MB | 7.7 × 10⁶ | Flat. An index here is pure overhead. |
| 100,000 | 307 MB | 7.7 × 10⁷ | Flat. Milliseconds, perfect recall, no tuning. |
| 1,000,000 | 3.1 GB | 7.7 × 10⁸ | Crossover. Measure before deciding. |
| 10,000,000 | 30.7 GB | 7.7 × 10⁹ | IVF-PQ or a graph index. |
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.