Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Module 10: Documents, retrieval, and context

Objectives: LO-10.1, LO-10.2, LO-10.3, LO-10.4
Prerequisites: Module 7 and Module 8, and the tags of Module 4
Time: about 6 hours: 2 for this reading, 2.5 for Lab 10, and 1.5 for the practice

A model answers from what is in its prompt, so a program that answers questions about the shop’s handbook must put the right sections there. This module builds that program: a prompt with tagged documents, quotations that code checks, a search formula that finds the sections, a measure of how often it finds them, and a prompt order that can be cached. Lab 10 uses the bundled handbook, 10 short sections (H01–H10), and 40 questions labeled with the sections that answer them.

Put the documents first

Module 4 tagged the parts of a prompt. A prompt built on documents gives each document its own tag with a stable ID, and puts the documents before the instructions and the question. Anthropic’s prompting best practices say that for inputs of 20,000 tokens or more, long documents belong near the top, above the query, the instructions, and any examples. They report that a query at the end can improve response quality by up to 30% in their tests, especially with several complex documents.

Position inside a long context matters too. Liu and colleagues’ “Lost in the Middle” (TACL 2024) found that models used information best when it was at the beginning or the end of the context, and noticeably worse when it was in the middle, even for models built for long contexts.

Worked example. A rider asks where a bicycle goes once its repair is done. Sections H05 (storage) and H07 (work orders) are the likely sources:

<prompt>
  <documents>
    <doc id="H05">Put completed repairs on the green rack. Park bicycles awaiting inspection on
the orange rack. Return floor pumps to the wall hooks after use.</doc>
    <doc id="H07">A work order names the requested service and parts. Ask for approval before
adding any paid service. Record completed work in the service ticket.</doc>
  </documents>
  <instructions>Answer from the documents only. Quote the exact sentence that supports your
answer, with its section ID. If no section answers the question, reply "I don't know".
</instructions>
  <question>Where does a bicycle go after its repair is finished?</question>
</prompt>

A good answer quotes H05: “Put completed repairs on the green rack.” Escape the text you insert, as Module 4 showed, so a question containing < or & can’t break the tags. Exercise L10.1 builds such a prompt with ElementTree, and Exercise P10.1 sketches one about returns.

Ground answers in quotations

A grounded answer is one that the supplied sources support. Anthropic’s guide to reducing hallucinations gives three basic strategies: give the model explicit permission to say “I don’t know”; for long documents, ask for word-for-word quotes before the task; and ask for a supporting quote for every claim, retracting any claim without one. The guide notes that these techniques reduce hallucinations but don’t eliminate them.

Code can check that a quote occurs, character for character, in a section the prompt contained. That proves provenance, where the text came from, but not support, that the text backs the claim. Support needs a separate judgment, by a person or by a grader checked against people (Module 7).

Worked example. The question is “How long do I have to return an unopened bell?” Section H09 says: “Unopened accessories may be returned within 14 days with a receipt. Installed parts go through a service review. The shift lead records each approved return.” Four illustrative answers:

AnswerQuoteIn H09?Supports the answer?
14 days, with a receipt“Unopened accessories may be returned within 14 days with a receipt.”YesYes
30 days“Unopened accessories may be returned within 30 days.”No
14 days“The shift lead records each approved return.”YesNo: it says nothing about time
I don’t knowNoneRight, if H09 wasn’t in the prompt

The third answer passes the exact-match check and fails on support. Exact matching is strict: a curly apostrophe where the section has a straight one fails it, so decide on purpose whether to normalize such characters. Exercise L10.4 writes the exact-match check, and Exercise P10.3 scores a real quote that doesn’t support its answer.

The API can also do the quoting. Anthropic’s citations guide says that its citations are guaranteed to point into the supplied documents, and that the cited text doesn’t count toward output tokens; they can’t be combined with Module 8’s structured outputs. This course uses its own checker, so you can see where the evidence boundary lies.

Retrieve with BM25

A program retrieves the few sections most likely to answer each question, rather than sending them all. Lewis and colleagues’ 2020 NeurIPS paper calls this pattern retrieval-augmented generation (RAG).

BM25 is a formula for ranking documents by how well they match a search query. A word such as “the” adds little: it appears in all 10 handbook sections, so it can’t tell them apart. A rarer word such as “loan,” which appears in only one section, can move that section up the list. Repeating a word helps less with each repetition.

The score of a document is a sum over the distinct query terms tt that occur in it:

score=∑tIDF(t)⋅tf (k1+1)tf+k1(1−b+b L/Lˉ),IDF(t)=log⁡(1+N−df+0.5df+0.5)\text{score} = \sum_{t} \text{IDF}(t) \cdot \frac{tf \, (k_1 + 1)}{tf + k_1 \left(1 - b + b \, L / \bar{L}\right)}, \qquad \text{IDF}(t) = \log\left(1 + \frac{N - df + 0.5}{df + 0.5}\right)

Here NN is the total number of documents. Document frequency (dfdf) counts the documents containing a query term. Term frequency (tftf) counts its occurrences in the document being scored. The ratio L/LˉL/\bar{L} is document length divided by average length. The log is the natural log. The lab counts each distinct query word once.

Robertson and Zaragoza’s survey, “The Probabilistic Relevance Framework: BM25 and Beyond” (2009), explains the two settings. k1k_1 sets how fast repeated terms stop adding score: a term’s contribution approaches a limit, which the survey calls saturation. bb sets how much length counts: b=1b = 1 normalizes fully for length, and b=0b = 0 turns normalization off. The survey reports that values such as 0.5<b<0.80.5 < b < 0.8 and 1.2<k1<21.2 < k_1 < 2 work reasonably well in many circumstances. The lab uses k1=1.2k_1 = 1.2 and b=0.75b = 0.75, the defaults of the Apache Lucene search library’s BM25Similarity, and Lucene’s IDF, with the 1 inside the log. The survey’s IDF has no 1: log⁡((N−df+0.5)/(df+0.5))\log\big((N - df + 0.5)/(df + 0.5)\big), which turns negative for a term in more than half the documents. For “the,” it is log⁡(0.5/10.5)≈−3.04\log(0.5/10.5) \approx -3.04. With the 1, “the” gets log⁡(1+0.5/10.5)≈0.047\log(1 + 0.5/10.5) \approx 0.047, and “loan” gets log⁡(1+9.5/1.5)≈1.99\log(1 + 9.5/1.5) \approx 1.99. For N=10N=10, df=1df=1, tf=1tf=1, and an average-length section, the frequency factor is one and the term adds about 1.99. Break ties by ID.

Worked example: scoring a question

Score the labeled question “When does the stock count run?” against H08: “Order common tubes from the weekly stock list. Write a note when the last brake cable is used. The stock count runs on Friday afternoon.” The lab lowercases text and keeps runs of the letters a–z as terms, so H08 is L=25L = 25 terms long, and the sections average Lˉ=23\bar{L} = 23. The length part of the denominator is k1(1−b+b⋅25/23)=1.2×1.065≈1.278k_1(1 - b + b \cdot 25/23) = 1.2 \times 1.065 \approx 1.278, and k1+1=2.2k_1 + 1 = 2.2.

Query termdfdfIDFtftf in H08Weight in H08
stock11.99221.992 × 2 × 2.2 / (2 + 1.278) = 2.674
count21.48211.482 × 2.2 / (1 + 1.278) = 1.431
when21.48211.431
the100.04730.072
does, run000

H08 scores 2.674 + 1.431 + 1.431 + 0.072 ≈ 5.61. “run” earns nothing, because H08 says “runs” and BM25 matches words exactly. H06 comes next at 1.63, from “when” and “the,” then H10 at 1.56, from “count” (“Count the till”) and “the.” “when” adds 1.565 in H06 but 1.431 in H08, because H06 is only 20 terms long, and bb rewards a match in a short section. Exercise L10.2 implements the formula and ranks all 10 sections.

Measure retrieval before answers

Recall at kk is the share of a question’s relevant sections that appear among the first kk results, where kk is how many sections the program keeps. If a question needs H03 and H04 and the first two results contain only H04, recall at 2 is 0.5. The mean of these fractions describes the labeled questions. Report a second number beside it: the share of questions with every required section retrieved, which this course calls full coverage.

Worked example. Five of the 40 labeled questions, ranked by the lab’s BM25:

QuestionNeedsFirst two resultsRecall at 1Recall at 2
HQ09: What reference is needed for a receipt copy?H03H03, H0711
HQ10: Does a cash sale get a printed receipt?H03H03, H0911
HQ11: How do staff send electronic receipts?H03H03, H0111
HQ12: How do I obtain proof of a purchase a second time?H03H06, H0301
HQ40: Which section covers the opening sign and the closing alarm?H01, H10H01, H100.51

At k=1k = 1, mean recall is (1 + 1 + 1 + 0 + 0.5) / 5 = 0.7, and full coverage is 3 / 5 = 0.6. HQ12 says “proof of a purchase” where H03 says “receipt,” so it shares no meaningful word with H03. Its top result, H06, won on “of,” which appears in only one section (“clear of bags”), so BM25 treats it as rare. At k=2k = 2, both numbers reach 1 for these five.

Retrieval recall caps answer accuracy. If an answer must quote all its required evidence, and the prompt holds only the retrieved sections, then at k=1k = 1 at most 3 of these 5 questions can get a correct, fully supported answer, however good the model. Full coverage is that upper bound; mean recall alone doesn’t establish answer accuracy. A larger kk raises recall, but it lengthens the prompt, and more sections don’t always help: in Liu and colleagues’ study of question answering over retrieved documents, accuracy stopped improving long before retrieval recall did. Exercise L10.3 plots recall and full coverage against kk for all 40 questions, and Exercise P10.2 computes recall at three depths.

Pay once for the stable part

Many requests share the same instructions and handbook, with a new question at the end. Anthropic’s prompt caching guide describes how the API stores that shared start, the prefix, and reuses it:

The course’s data/prices.json, taken from Anthropic’s pricing page on November 26, 2026, gives Opus 5.5’s rates per million tokens: $4 for input, $5 for a 5-minute cache write, $8 for a 1-hour write, and $0.20 for a cache read. If every request after the first hits, a run pays one write of the prefix, a read of it for every later request, and the uncached suffix every time. If requests are spread out or the document changes, budget for misses: each one writes the prefix again at the write rate.

Worked example. Suppose a system prompt of about 570 tokens and the tagged handbook of about 630 (1,575 characters, at Module 1’s 2.5 characters per token) make a 1,200-token prefix, and each question adds about 30 tokens. On Opus 5.5, with each sum in millionths of a dollar:

ScenarioUncachedCached
100 questions, each within 5 minutes of the last; 5-minute cache100 × 1,230 × 4 = 492,000, so $0.4921,200 × 5 + 99 × 1,200 × 0.20 + 100 × 30 × 4 = 41,760, so $0.042
6 questions, 10 minutes apart; 5-minute cache6 × 1,230 × 4 = 29,520, so $0.030Every request misses: 6 × (1,200 × 5 + 30 × 4) = 36,720, so $0.037
The same 6 questions; 1-hour cache$0.0301,200 × 8 + 5 × 1,200 × 0.20 + 6 × 30 × 4 = 11,520, so $0.012

Caching cuts the busy run’s cost by over 90%. In the slow run, a 5-minute cache costs 24% more, because every request pays the write rate and none reads, while a 1-hour cache costs 61% less. The handbook alone is only about 630 tokens by this estimate, close to the 512-token minimum, so count the real prefix with the token-counting endpoint before relying on a saving. Exercise L10.5 computes the all-hit comparison, and Exercise P10.4 finds where caching starts to pay.

Common misconceptions

Summary

Self-check

Answer each question before you open its answer.

  1. Where does the final question go?

    Answer

    After the tagged documents and the instructions, at the end of the prompt. Anthropic reports better responses with the query at the end of a long prompt, and the documents then form a stable prefix that can be cached.

  2. Two sections are required, and only one is in the first four results. What is recall at 4?

    Answer

    0.5, because one of the two required sections was retrieved. Full coverage for that question is zero, because a required section is missing.

  3. A quote exists in the section. Does that establish the claim?

    Answer

    No. Exact match shows only where the text came from. Check separately whether the quote supports the claim, and whether evidence the answer needs was left out.

  4. What gets charged on a cache hit?

    Answer

    The matching prefix at the cache read rate, $0.20 per million tokens on Opus 5.5. The rest of the input pays the input rate, or the write rate for any part being written to the cache, and the output is charged as usual.

  5. Why does “the” add so little to a BM25 score in the handbook?

    Answer

    It appears in all 10 sections, so df=N=10df = N = 10 and its IDF is log⁡(1+0.5/10.5)≈0.047\log(1 + 0.5/10.5) \approx 0.047. A word that every section contains can’t tell the sections apart.

Further reading

References
  1. Liu, N. F., & others. (2024). Lost in the Middle: How Language Models Use Long Contexts. Transactions of the Association for Computational Linguistics, 12, 157–173. 10.1162/tacl_a_00638
  2. Robertson, S., & Zaragoza, H. (2009). The Probabilistic Relevance Framework: BM25 and Beyond. Foundations and Trends in Information Retrieval, 3(4), 333–389. 10.1561/1500000019