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:
| Answer | Quote | In H09? | Supports the answer? |
|---|---|---|---|
| 14 days, with a receipt | “Unopened accessories may be returned within 14 days with a receipt.” | Yes | Yes |
| 30 days | “Unopened accessories may be returned within 30 days.” | No | |
| 14 days | “The shift lead records each approved return.” | Yes | No: it says nothing about time |
| I don’t know | None | Right, 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 that occur in it:
Here is the total number of documents. Document frequency () counts the documents containing a query term. Term frequency () counts its occurrences in the document being scored. The ratio 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. sets how fast repeated terms stop adding score: a term’s
contribution approaches a limit, which the survey calls saturation. sets how much length
counts: normalizes fully for length, and turns normalization off. The survey reports
that values such as and work reasonably well in many circumstances.
The lab uses and , 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:
, which turns negative for a term in more than half the
documents. For “the,” it is . With the 1, “the” gets
, and “loan” gets . For ,
, , 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 terms long, and the sections average . The length part of the denominator is , and .
| Query term | IDF | in H08 | Weight in H08 | |
|---|---|---|---|---|
| stock | 1 | 1.992 | 2 | 1.992 × 2 × 2.2 / (2 + 1.278) = 2.674 |
| count | 2 | 1.482 | 1 | 1.482 × 2.2 / (1 + 1.278) = 1.431 |
| when | 2 | 1.482 | 1 | 1.431 |
| the | 10 | 0.047 | 3 | 0.072 |
| does, run | 0 | 0 | 0 |
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 rewards a match in a short section. Exercise L10.2 implements the formula and ranks all 10 sections.
Measure retrieval before answers¶
Recall at is the share of a question’s relevant sections that appear among the first results, where 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:
| Question | Needs | First two results | Recall at 1 | Recall at 2 |
|---|---|---|---|---|
| HQ09: What reference is needed for a receipt copy? | H03 | H03, H07 | 1 | 1 |
| HQ10: Does a cash sale get a printed receipt? | H03 | H03, H09 | 1 | 1 |
| HQ11: How do staff send electronic receipts? | H03 | H03, H01 | 1 | 1 |
| HQ12: How do I obtain proof of a purchase a second time? | H03 | H06, H03 | 0 | 1 |
| HQ40: Which section covers the opening sign and the closing alarm? | H01, H10 | H01, H10 | 0.5 | 1 |
At , 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 , 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 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 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 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 prefix covers the request’s
tools,system, andmessages, in that order, up to a block marked withcache_control. A hit needs a 100% identical prefix, so put whatever changes per request last.A cache entry lasts 5 minutes, and each use refreshes it at no extra cost. A 1-hour lifetime is also available, which the guide suggests for prompts used less often than every 5 minutes but more often than every hour.
On Claude Opus 5.5, Sonnet 5.5, and Haiku 5.5, a prefix must be at least 512 tokens. A shorter one is processed without caching, and no error is returned.
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:
| Scenario | Uncached | Cached |
|---|---|---|
| 100 questions, each within 5 minutes of the last; 5-minute cache | 100 × 1,230 × 4 = 492,000, so $0.492 | 1,200 × 5 + 99 × 1,200 × 0.20 + 100 × 30 × 4 = 41,760, so $0.042 |
| 6 questions, 10 minutes apart; 5-minute cache | 6 × 1,230 × 4 = 29,520, so $0.030 | Every request misses: 6 × (1,200 × 5 + 30 × 4) = 36,720, so $0.037 |
| The same 6 questions; 1-hour cache | $0.030 | 1,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¶
“Put the question first, so the model knows what to look for.” Anthropic reports that a query at the end, after long documents, can improve response quality by up to 30% in its tests.
“A quote that appears in the document proves the answer.” “Morning staff unlock the front door at 08:45.” is a real sentence from H01, and it doesn’t show that the shop opens at 08:45: the open sign goes up at 09:00. Exact match proves provenance, not support.
“BM25 understands what the question means.” It matches words. “Proof of a purchase” never matches “receipt,” and “run” doesn’t match “runs.”
“High mean recall means every question is covered.” In the worked example, mean recall at is 0.7, but only 60% of the questions have every section they need.
“Marking a prompt for caching always saves money.” A prefix under 512 tokens isn’t cached. A timestamp at the start changes the prefix every time, so every request writes and none reads, and a 5-minute write costs 1.25 times the input rate.
Summary¶
Put tagged documents with stable IDs before the instructions and the question, and ask for an exact quote with its section ID, or “I don’t know”.
Check quotes in code for provenance: the exact text occurs in a section the prompt contained. Judge support separately.
BM25 ranks sections by the query terms they contain, weighting rare terms up, limiting the effect of repeats, and adjusting for length.
Recall at and full coverage measure retrieval, and full coverage caps how many answers can be fully supported.
Put stable parts first so they can be cached, and compute the saving for the expected pattern of hits and misses.
Self-check¶
Answer each question before you open its answer.
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.
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.
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.
What gets charged on a cache hit?
Answer
The matching prefix at the cache read rate,
$0.20per 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.Why does “the” add so little to a BM25 score in the handbook?
Answer
It appears in all 10 sections, so and its IDF is . A word that every section contains can’t tell the sections apart.
Further reading¶
Robertson and Zaragoza, “The Probabilistic Relevance Framework: BM25 and Beyond,” Foundations and Trends in Information Retrieval, 2009, Robertson & Zaragoza (2009). Where BM25’s saturation and length normalization come from, and how to tune and .
Liu and colleagues, “Lost in the Middle: How Language Models Use Long Contexts,” TACL, 2024, Liu & others (2024). How the position of the relevant document, and the number retrieved, change accuracy.
Anthropic, Prompt caching. The cache prefix, its lifetimes, the minimum length for each model, and what invalidates a cache.
Anthropic, Citations. The API’s built-in citations, and how they compare with asking for quotes in the prompt.
Anthropic, Reduce hallucinations. Allowing “I don’t know”, grounding in quotes, and verifying claims, each with an example prompt.
- 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
- 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