Objectives: LO-6.1, LO-6.2, LO-6.3
Prerequisites: the Module 6 reading
Time: about 2.5 hours
In this lab you choose an effort level from a table of illustrative measurements, extract a final answer from a tagged reply and reject malformed ones, and build a three-step chain. Then you compute how errors compound along the chain and what a check step catches.
No cell calls a real model. The model in Exercise L6.3 is ScriptedModel, a stand-in from
promptlab that answers each request from a script, in the shape of a Messages API response,
and records every request it receives. The measurements were written for this course.
Use a fresh kernel and run the cells from top to bottom. Fill each answer cell, then run its check. The checks raise errors until their exercises are complete. This notebook runs locally.
Setup¶
import sys
from math import prod, isclose
import re
from promptlab import ScriptedModel, make_response
measurements = [
{"effort": "low", "accuracy": 0.85, "seconds": 1.2, "cost": 4},
{"effort": "medium", "accuracy": 0.92, "seconds": 2.0, "cost": 7},
{"effort": "high", "accuracy": 0.94, "seconds": 3.4, "cost": 12},
]
print("Python", sys.version.split()[0])Set constraints first¶
Each row gives one effort level’s accuracy on labeled cases, its median latency in seconds, and its cost in relative units. The values are illustrative. Before you run the next cell, predict which row meets at least 90% accuracy and at most 2.5 seconds at the least cost.
for row in measurements:
print(row)Exercise L6.1 (LO-6.1, ★★, about 25 minutes)¶
Find the cheapest qualifying row. A row qualifies when its accuracy is at least
min_accuracy and its seconds is at most max_seconds: both thresholds are inclusive. Among
the qualifying rows, choose the lowest cost. Break cost ties by lower seconds, then by the
effort name in alphabetical order. Return the effort string, or None when no level
qualifies.
def choose(rows, min_accuracy, max_seconds):
raise NotImplementedError("L6.1")result = choose(measurements, 0.9, 2.5)
assert result == "medium", \
f"Keep the rows that meet both thresholds, then take the cheapest; got {result!r}."
result = choose(measurements, 0.92, 2)
assert result == "medium", \
f"The thresholds are inclusive: 0.92 meets 0.92, and 2.0 meets 2; got {result!r}."
result = choose(measurements, 0.99, 10)
assert result is None, f"No level reaches 99% accuracy, so return None; got {result!r}."
result = choose(measurements, 0.8, 5)
assert result == "low", \
f"Every level qualifies here, so return the cheapest, not the most accurate; got {result!r}."
ties = [{"effort": "a", "accuracy": 0.9, "seconds": 2.0, "cost": 5},
{"effort": "c", "accuracy": 0.9, "seconds": 1.0, "cost": 5}]
result = choose(ties, 0.9, 3)
assert result == "c", f"Break a cost tie by lower latency before the name; got {result!r}."
ties = [{"effort": "b", "accuracy": 0.9, "seconds": 2.0, "cost": 5},
{"effort": "a", "accuracy": 0.9, "seconds": 2.0, "cost": 5}]
result = choose(ties, 0.9, 3)
assert result == "a", \
f"When cost and latency both tie, take the effort name that sorts first; got {result!r}."
print("passed")Exercise L6.2 (LO-6.2, ★★, about 25 minutes)¶
Extract a final answer. Return the text inside the reply’s one <answer> section, with its
surrounding whitespace stripped. Match the tags exactly as written here, in lowercase. Use the
re.DOTALL flag, which lets . match a newline too, so an answer that spans lines is found.
Raise ValueError for a missing, empty, or repeated section. A second <answer> tag counts as
a repeat even without its own closing tag.
def extract(text):
raise NotImplementedError("L6.2")result = extract("<evidence>receipt</evidence><answer> billing </answer>")
assert result == "billing", \
f"Return the answer's text with its surrounding whitespace stripped; got {result!r}."
try:
result = extract("<answer>\nbilling\n</answer>")
except ValueError as error:
raise AssertionError(f"An answer can span lines: use re.DOTALL. extract raised: {error}") \
from error
assert result == "billing", f"Strip the newlines around a multiline answer; got {result!r}."
for text in ("no answer", "<answer> </answer>", "<answer>a</answer><answer>b</answer>",
"<answer><answer>billing</answer>"):
try:
result = extract(text)
except ValueError:
continue
raise AssertionError(f"extract({text!r}) returned {result!r}. Raise ValueError for a "
"missing, empty, or repeated answer section.")
print("passed")Exercise L6.3 (LO-6.3, ★★, about 25 minutes)¶
Pass the original input forward. Call the stand-in three times. Each request has one user
message, whose text begins with classify, draft, or check, followed by a newline. Include
the original ticket in every step. Include the extracted label in the draft step, and the
extracted reply in the check step. A response can begin with a thinking block, so read each
answer from the response’s text blocks, and extract it with your extract. Return the reply
when the final extracted answer is approved, and None otherwise.
def chain(model, ticket):
raise NotImplementedError("L6.3")model = ScriptedModel(["<answer>billing</answer>", "<answer>Please share the invoice ID.</answer>",
"<answer>approved</answer>"])
assert chain(model, "Please send the receipt") == "Please share the invoice ID.", \
"Return the drafted reply when the check approves it."
assert model.calls == 3, f"Call the model three times; it was called {model.calls} times."
turns = [request["messages"][0]["content"] for request in model.requests]
assert [turn.split("\n")[0] for turn in turns] == ["classify", "draft", "check"], \
"Begin the turns with classify, draft, and check, each followed by a newline."
assert all("Please send the receipt" in turn for turn in turns), \
"Include the original ticket in every step."
assert "billing" in turns[1], "Pass the extracted label to the draft step."
assert "Please share the invoice ID." in turns[2], "Pass the extracted reply to the check step."
thinking = make_response([{"type": "thinking", "thinking": "A receipt is billing.", "signature": ""},
{"type": "text", "text": "<answer>billing</answer>"}])
model = ScriptedModel([thinking, "<answer>Please share the invoice ID.</answer>",
"<answer>rejected</answer>"])
assert chain(model, "Please send the receipt") is None, \
"Return None when the check doesn't approve. Read the text blocks, not the first block."
print("passed")Exercise L6.4 (LO-6.3, ★★, about 25 minutes)¶
Measure error propagation. Return a tuple (passed, missed). passed is the probability
that every stage is right: the product of the conditional success rates in stage_rates. Each
rate is a stage’s success rate on runs where every earlier stage was right. missed is the
probability, as a share of all runs, of a failure that the check doesn’t catch. The check
catches the fraction caught of the failures, and it accepts every correct result.
def error_budget(stage_rates, caught):
raise NotImplementedError("L6.4")passed, missed = error_budget([0.9, 0.9, 0.9], 0.5)
assert isclose(passed, 0.729), \
f"passed is the product of the three conditional rates; got {passed}."
assert isclose(missed, 0.1355), \
f"missed is the share of all runs that fail and get past the check; got {missed}."
result = error_budget([0.5, 0.5], 1)
assert result == (0.25, 0.0), \
f"A check that catches every failure lets none through: expected (0.25, 0.0); got {result!r}."
print("passed")Summary¶
You chose an effort level by applying fixed thresholds first and a written rule second, and found that a table can leave no level that qualifies.
You extracted a final answer and raised an error for a missing, empty, or repeated section, so a malformed reply can’t pass for a valid one.
You built a chain that carries the original ticket to every step and reads answers from text blocks, and you computed how a check step changes the share of failures that get through.