Objectives: LO-10.1, LO-10.2, LO-10.3, LO-10.4
Prerequisites: the Module 10 reading
Time: about 2.5 hours
In this lab you build a grounded prompt from tagged handbook sections, rank the sections with BM25, measure recall at on 40 labeled questions, check that a quotation occurs exactly in the section it names, and compare the cost of a cached prompt prefix with an uncached one.
The handbook belongs to the course’s fictional bicycle shop: 10 short sections, H01–H10, and 40 questions, each labeled with the sections that answer it. Nothing in the lab calls a model, and every number you compute describes this small data set only.
Each exercise ends with a check cell that prints passed or fails with a message. Run the
cells in order, from the top. Some cells fail on purpose until you finish the exercise above
them.
Setup¶
import sys
from collections import Counter
from math import isclose, log1p
import re
from statistics import mean
from xml.etree import ElementTree
from promptlab import load_json
docs = load_json("handbook/sections.json")
questions = load_json("handbook/questions.json")
rates = load_json("prices.json")["models"]["claude-opus-5-5"]
import matplotlib
import matplotlib.pyplot as plt
print("Python", sys.version.split()[0], "| matplotlib", matplotlib.__version__)
print(len(docs), "sections and", len(questions), "questions; Opus 5.5 rates:", rates)Read the handbook records¶
Each section is a dictionary with an id, a title, and its text. Each question has an
id, the question, and a list of relevant section IDs. Read the first question, and
predict which section should rank first, before you rank them.
print(questions[0]["question"])
print(docs[0]["id"], docs[0]["text"])Exercise L10.1 (LO-10.1, LO-10.3, ★★, about 25 minutes)¶
Build a grounded prompt. Write prompt(docs, question), which returns the prompt as an XML
string. Its root element holds three children, in this order: documents, instructions, and
question. documents holds one doc element for each section, with the section’s ID in an
id attribute and its original text. The instructions ask for an exact quote and its section
ID, or the reply “I don’t know”. If you build the tree with ElementTree, it escapes text
containing < or & for you.
def prompt(docs, question):
raise NotImplementedError("L10.1")root = ElementTree.fromstring(prompt(docs[:2], "What if text has < or &?"))
assert [e.tag for e in root] == ["documents", "instructions", "question"], \
f"The root's children should be documents, instructions, question: {[e.tag for e in root]}"
assert [(d.tag, d.attrib.get("id")) for d in root[0]] == [("doc", "H01"), ("doc", "H02")], \
"Put one doc element per section in documents, each with its ID in an id attribute."
assert root[0][0].text == docs[0]["text"], "Each doc should hold its section's original text."
instructions = root.findtext("instructions")
assert "I don't know" in instructions, "Allow the answer \"I don't know\" in the instructions."
assert "quot" in instructions.lower(), "Ask for an exact quote in the instructions."
assert root.findtext("question") == "What if text has < or &?", \
"The question should come back unchanged, with its < and & intact."
print("passed")Exercise L10.2 (LO-10.2, ★★, about 25 minutes)¶
Rank sections with BM25. Write bm25(query, docs, *, k1=1.2, b=0.75), using the formula in
the reading. Lowercase the text, and take as terms the matches of the regular expression
[a-z]+; count each distinct query term once. Return a list of (section ID, score) pairs,
ordered by decreasing score, then by ascending ID. Include sections that score zero. If docs
is empty, return an empty list.
def bm25(query, docs, *, k1=1.2, b=0.75):
raise NotImplementedError("L10.2")assert bm25("loan bicycles loan", docs) == bm25("loan bicycles", docs), \
"Count each distinct query term once: a repeated word shouldn't change the scores."
assert bm25("loan bicycles", docs)[0][0] == "H04", "The loan section, H04, should rank first."
loan = dict(bm25("loan", docs))
assert isclose(loan["H04"], 3.0737, abs_tol=1e-3), \
f"H04 has 'loan' 3 times in 25 terms (average 23), so it scores about 3.0737: {loan['H04']}"
assert len(bm25("the", docs)) == 10, "Return a pair for every section."
assert bm25("xyz", docs)[0] == ("H01", 0), "Break ties, zeros included, by ascending ID."
assert bm25("stock", []) == [], "With no documents, return an empty list."
print("passed")Exercise L10.3 (LO-10.2, ★★, about 25 minutes)¶
Measure recall and full coverage. Write recall(ranked, relevant, k), which returns the
share of the relevant IDs that appear among the first k IDs of ranked. Raise
ValueError for a negative k or an empty relevant list.
The check then ranks the handbook for all 40 questions and plots two lines against , the number of sections retrieved, on the horizontal axis. The vertical axis is a proportion. The line with circles is mean recall, and the line with squares is full coverage: the share of questions with every required section retrieved. Read the plot, and note where full coverage falls below mean recall, and the smallest at which both reach 1.
def recall(ranked, relevant, k):
raise NotImplementedError("L10.3")assert recall(["A", "B"], ["B", "C"], 2) == 0.5, \
"One of two relevant IDs among the first 2 gives 0.5."
assert recall(["A", "B"], ["A"], 0) == 0, "With k = 0 nothing is retrieved, so recall is 0."
for args, why in [((["A"], ["A"], -1), "a negative k"),
((["A"], [], 1), "an empty relevant list")]:
try:
recall(*args)
except ValueError:
pass
else:
raise AssertionError(f"recall should raise ValueError for {why}.")
ranks = [[ident for ident, score in bm25(q["question"], docs)] for q in questions]
depths = list(range(1, len(docs)+1))
values = [[recall(rank, q["relevant"], k) for rank, q in zip(ranks, questions, strict=True)]
for k in depths]
assert len(ranks) == 40 and min(values[-1]) == 1, \
"With all 10 sections retrieved, every question's recall should be 1."
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(depths, [mean(v) for v in values], marker="o", label="Mean recall")
ax.plot(depths, [mean(x == 1 for x in v) for v in values], marker="s", label="Full coverage")
ax.set(xlabel="Retrieved sections (k)", ylabel="Proportion of questions", ylim=(0, 1.06),
title="BM25 retrieval on the 40 handbook questions")
ax.legend()
plt.show()
print("passed")Exercise L10.4 (LO-10.3, ★★, about 25 minutes)¶
Verify verbatim quotations. Write valid_quote(docs, ident, quote). A quote passes if it
contains at least one visible character and occurs, exactly as written, in the section with ID
ident. Check only the sections in docs, which stand for the ones retrieved into the prompt.
In your notes, give a true quote that would still fail to support a claim.
def valid_quote(docs, ident, quote):
raise NotImplementedError("L10.4")assert valid_quote(docs, "H04", "The shop has two loan bicycles."), \
"A sentence copied exactly from H04 should pass."
assert not valid_quote(docs[:1], "H04", "The shop has two loan bicycles."), \
"H04 wasn't retrieved here, so a quote from it can't pass."
assert not valid_quote(docs, "H04", "The shop has three loan bicycles."), \
"A changed word means the quote doesn't occur in H04."
assert not valid_quote(docs, "H04", " "), "A quote of spaces only shouldn't pass."
print("passed")Exercise L10.5 (LO-10.4, ★★, about 25 minutes)¶
Compare cached and uncached input. Write cost(requests, prefix, suffix, rates), which
returns the pair (uncached, cached) in US dollars for requests requests, each with a
prefix of stable tokens and a suffix of tokens that change. The cached case writes the
prefix once to the 5-minute cache, then hits the cache on every later request. Charge the
suffix at the input rate on every request in both cases, and leave out output, which is the
same either way. Raise ValueError for a requests count of zero or less.
def cost(requests, prefix, suffix, rates):
raise NotImplementedError("L10.5")a, b = cost(10, 10_000, 2_000, rates)
assert isclose(a, .48), \
f"Ten uncached requests of 12,000 tokens at $4 per million cost $0.48, not {a}."
assert isclose(b, .148), f"One write, nine reads, and ten suffixes cost $0.148, not {b}."
assert cost(1, 10_000, 2_000, rates)[1] > cost(1, 10_000, 2_000, rates)[0], \
"A single request costs more cached than uncached, because a write costs more than input."
try:
cost(0, 10_000, 2_000, rates)
except ValueError:
pass
else:
raise AssertionError("cost should raise ValueError for zero requests.")
print("passed")Summary¶
A grounded prompt puts tagged sections, each with an ID, before its instructions and its question, and asks for an exact quote or “I don’t know”.
BM25 ranks sections by the query terms they contain, weighting rare terms up, limiting repeats, and adjusting for length. It matches words exactly, so a question in other words can miss its section.
Recall at and full coverage measure retrieval, and full coverage caps how many answers can quote all their evidence.
An exact-match check proves where a quote came from, not that it supports the claim.
A cached prefix pays one write and then cheap reads, so it saves money only when requests reuse it.