Retrieval-augmented generation
Design evidence retrieval with separate recall, grounding, freshness, authorization, and context-budget measurements.
On this page
The question for today
What you’ll understand
- Separate document retrieval, context construction, and supported answer generation.
- Calculate context and coverage budgets without equating similarity with evidence.
- Evaluate retrieval failures and generator failures independently.
Retrieval-augmented generation supplies external material to a model at answer time. It supplies changing or specialized information without storing every fact in parameters. The system still has two distinct obligations: find suitable evidence and use it faithfully. A fluent cited answer proves neither. Build the pipeline so an evaluator can identify the exact source version, retrieved passage, and claim the answer says that passage supports.
Retrieval is an information-access stage
Begin with a corpus whose documents have stable identities, versions, timestamps, and access rules. Chunking decides which units can be retrieved and which surrounding context remains available. A chunk boundary can separate a rule from its exception; overlap can preserve context while increasing duplicated material. Dense embeddings retrieve by a learned similarity geometry, while lexical methods can be strong for names and exact identifiers. Choose and evaluate the retrieval design using the intended question distribution rather than assuming one index is universally best.
Query rewriting, candidate retrieval, reranking, and context selection are separate operations with their own failure modes and costs. Enforce authorization before exposing document content to a user or a downstream model. A generator instruction is not an access-control boundary. Preserve provenance through each transformation so a selected chunk can be traced to an exact source. Updating an index does not automatically update cached answers, replicas, or previously created embeddings; define a freshness and deletion policy for the complete path.
Construct a useful, bounded evidence context
Context selection should prefer answer-bearing evidence, remove avoidable duplication, and retain enough surrounding qualification to prevent misreading. Count final serialized tokens, including source labels and instructions, and reserve output capacity. More retrieved tokens can raise prefill cost and obscure the relevant passage. Lost in the Middle studies sensitivity to where relevant material appears in long contexts; its findings motivate position-aware evaluation, not a universal claim that the middle is unusable for every model and task.
The original RAG formulation combines a retrieval distribution with a generation model. A retrieve-then-prompt pipeline need not implement that exact training or marginalization. Be explicit about which architecture is used. Ask the generator to cite actual source identifiers and distinguish retrieved facts from inference. If required evidence is absent or conflicting, abstention or a targeted follow-up can be the correct result. Retrieval improves access to information; it does not confer truth on every indexed document.
Evaluate the pipeline by locating the failure
Maintain questions with labelled supporting passages, answer criteria, and cases where the corpus has no answer. Evaluate retrieval recall and ranking separately from supported-answer accuracy and citation entailment. If evidence never reached the prompt, modifying the generator can miss the problem. If evidence was present but the answer contradicted it, improving retrieval alone is unlikely to solve the failure. Include updated documents, conflicting versions, inaccessible content, and questions requiring evidence across more than one passage.
Compare to a no-retrieval baseline and to an oracle context containing verified evidence. The gap to oracle context helps locate retrieval limitations, while remaining oracle errors expose generation or task ambiguity. Track latency and cost for embedding, search, reranking, prefill, and decoding separately. Treat retrieved text as untrusted data, including instructions embedded within documents. Validate citations against the selected source versions and avoid publishing unsupported claims merely because the output is syntactically well formed.
Work it through
Choose evidence within a token budget
A system has context capacity 8,000 tokens, reserves 1,500 output tokens, and uses 900 tokens for instructions, question, history, and source labels. Each candidate chunk is 700 tokens. A labelled question needs four evidence units; top five retrieval finds three.
Available evidence capacity is 8,000 − 1,500 − 900 = 5,600 tokens. At 700 tokens each, at most eight chunks fit under these simplified counts.
Recall at five is 3/4 = 0.75. That says one labelled evidence unit is missing, not that the answer is 75% correct or that every retrieved chunk is relevant.
If top eight includes all four evidence units, recall rises to one and the context exactly reaches 8,000 reserved tokens. Check actual formatting and duplicated passages; zero spare tokens leaves no room for an underestimated label or delimiter.
More candidates can improve labelled coverage but consume context and processing time. The final decision should also test whether the model produces a supported answer from the selected evidence.
The living notebook
Explore the model
Interactive lab · vectors
Similarity is a geometric ingredient
Change the angle and magnitude of one two-dimensional vector and inspect its projections. This illustrates coordinate geometry only: there is no document index, second query vector, similarity ranking, or citation checker in the lab.
- x component
- 1.393
- y component
- 0.975
- Magnitude
- 1.7
Playback traces a fixed vector and its projections. Angle and magnitude set the geometry; the moving marker does not change them. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.
Look forA geometric representation can support retrieval, but relevance and evidential support require a task-specific test.
Pause & reason
Check your understanding
Your turn
Try it yourself
Top ten retrieves six of eight labelled evidence units, and only six of its ten chunks are relevant. Compute recall and precision. Why can neither metric certify the answer?
Take a moment to make a prediction or work it out on paper. Open a hint when you need one.
Give me a hint
Recall uses all labelled relevant units as its denominator; precision uses retrieved units.
Compare with the solution
Recall is 6/8 = 0.75 and precision is 6/10 = 0.60 under these labels. Neither measures whether the model accurately interprets the six relevant units, handles the missing evidence, cites the right source versions, or refuses an unsupported conclusion. Evaluate generated claims and no-answer cases separately.
Keep the idea
Take it with you
- Preserve authorized source identities and versions from indexing through citations.
- Context capacity and retrieval similarity do not establish evidence quality.
- Separate missing-evidence failures from failures to use evidence already supplied.
Read further
Original sources and deeper explanations to follow at your own pace.
Optional progress, saved in this browser when available. Revisit any lesson at any time.
Lesson not marked complete.