Skip to content

resource

Agent Evaluation: Unit A Exercises

Study agent evaluation in Chapter 16. Unit A: build the mechanism, record your predictions and test a changed case in the student notebook.

Student edition · 90 minutes of dedicated work · 2026-09-09

Open in Colab Runs on Google Colab as it ships today, or on any local Python 3.12+ kernel.

This is one of two practical units for Chapter 16. Unit A constructs and connects the mechanism; Unit B investigates a controlled failure, repairs it and transfers the invariant. Each is a complete ninety-minute session, with its own setup and required conceptual introductions. Basic Python variables, conditions, loops, functions, lists and dictionaries are the starting knowledge. Libraries and specialized concepts used here are introduced below before the main task.

By the end you should be able to:

  1. Explain the chapter's mechanism using a prediction and an observed intermediate result.
  2. Construct the independent replenishment baseline over a Case: use physical minus reserved stock, include only actual deficits, retain product identity and avoid a model call.
  3. Solve build an oracle that cannot copy the expected answer using changed inputs and an independent expectation.
  4. Retain your implementation, failed/corrected observations, causal explanation and limits.
MinutesDedicated activityEvidence you produce
0–5State the problem and make a predictionInitial prediction in your own words
5–25Foundations and library examplesValues, explanations, revised predictions
25–35Trace setup and the main interfaceInput → learner function → observation
35–60Construct and connectSource, visible checks and runtime evidence
60–80Implement and challenge the transfer taskFunction and a new counterexample
80–90Retrieve, explain and saveExit ticket and retained submission

Installation is preparation time. These are planning estimates, not measured completion times. Use the reference primers when a term is unfamiliar; in Unit B retrieve an explanation before re-reading it. Run All checks that the artifact executes. Unfinished student functions deliberately produce NEEDS_WORK. Keep your first attempt before opening answers.

This notebook belongs to the construction edition. Its supplied teaching runtime is embedded, so it can run without the textbook or another notebook. Where code uses REFERENCE_LESSON, that is the frozen runtime exercise identifier; the reader-facing chapter and saved unit identifiers use the current edition. Building against a supplied runtime is not proof that you have constructed all of its dependencies.

Run the self-contained setup

Open this notebook in Google Colab with the badge above, or use a local Python 3.12+ Jupyter kernel, with Pydantic 2. If needed, run %pip install "pydantic==2.13.4" once in a separate cell and restart the kernel. Package installation needs internet; the lesson itself needs no repository download, API key or prior notebook. The closing extension can use an OpenAI key from Colab's Secrets pane to put a live model behind the same tools; without a key it replays a recorded transcript and says so.

The collapsed cell contains 90 frozen teaching files. Base85 represents compressed bytes as text; zlib decompresses them; SHA-256 checks that the decoded files match this edition. These are supplied packaging operations, not learner algorithms. tempfile creates an isolated working copy; Path handles file locations; sys.path tells Python where the supplied modules live; a .pth file, the mechanism an editable install uses, tells reviewed local subprocesses the same. The code is available for inspection below and performs no package installation itself. The subsequent lesson teaches the libraries used by the mechanisms you will implement.

Run setup on every fresh kernel. It writes scratch runtime files separately from your retained practical-work/ch16-a folder. Rerunning setup restores the frozen support files and keeps your saved work. Restarting a kernel clears variables, not saved submission files. Source basis: Sovereign Agent 444c5f6. Some tasks use reviewed local subprocesses; they are not an OS sandbox.

Supplied offline setup and teaching files

The complete supplied setup cell is in the downloadable notebook. Run it there before attempting the cells below. This web edition omits only that compressed setup payload.

Commit to a prediction before the examples

python
prediction_notes = {
    "prediction": "Write the expected behavior before running the worked example.",
    "reason": "Name the input and rule behind that prediction.",
    "falsifier": "Name an observation that would prove the explanation wrong.",
    "revision": "After execution, explain what changed in your understanding.",
}

Reading the Python vocabulary used in this notebook

You need basic assignments, if, loops, functions, lists and dictionaries. The less familiar features used by the supplied code are introduced here. A library is reusable code that Python can import. The standard library ships with Python; Pydantic is an additional package. An import makes a name available, but does not mean that you have completed the exercise.

JSON is text for exchanging structured values. A Python dictionary is an in-memory object; the JSON representation is a string. Use json.dumps to encode and json.loads to decode. Decoding proves that text has valid JSON syntax, not that its fields match our business contract. Predict which of the following two decoded objects could describe a stock count.

python
import json

intro_data = {"sku": "MANGO", "count": 3}
intro_text = json.dumps(intro_data, sort_keys=True)
print(type(intro_data).__name__, type(intro_text).__name__, intro_text)
print(json.loads(intro_text))
print("Also valid JSON:", json.loads('["not", "a", "stock", "record"]'))
assert json.loads(intro_text) == intro_data

The first result is a dictionary; the second is a list. Before indexing a decoded object, check the shape that your function promises to accept. An exception interrupts the normal path. raise ValueError(...) refuses an invalid value; try/except lets a caller inspect that expected refusal. Catch the expected class, rather than turning every programming error into apparent success. finally runs cleanup even when an earlier operation raises.

An annotation, such as count: int, documents the expected type. It does not by itself enforce the type at runtime. A class defines a kind of object; an instance holds one object's data. @dataclass asks Python to generate routine construction and comparison methods from annotated fields. frozen=True prevents ordinary reassignment of the instance's fields; it does not make every object nested inside those fields immutable. A method is a function attached to a class; self refers to the instance receiving the call.

python
from dataclasses import dataclass


@dataclass(frozen=True)
class IntroObservation:
    operation: str
    count: int


intro_observation = IntroObservation("count-mango", 3)
print(intro_observation.operation, intro_observation.count)
assert intro_observation == IntroObservation("count-mango", 3)

A callback is a function passed to another function. This is how the classroom harness invokes your implementation. The argument candidate below is a function object; parentheses perform the call. Predict the two answers before execution, then trace the result to the callback.

python
def intro_apply(candidate, value):
    return {"input": value, "observed": candidate(value)}


def intro_double(value):
    return value * 2


print(intro_apply(intro_double, 3))
print(intro_apply(lambda value: value + 2, 3))
assert intro_apply(intro_double, 3)["observed"] == 6

lambda value: value + 2 is a small anonymous function. A closure is a function that retains access to values from its surrounding scope. It can bind a tool to a shop snapshot. A shallow copy duplicates only the outer container; copy.deepcopy also copies nested containers used in these fixtures. A set stores distinct values; required <= allowed asks whether every required item is allowed. frozenset is the corresponding immutable set. A tuple groups ordered values; (value,) is a one-item tuple, including the comma.

Paths and cleanup. Path represents a filesystem location. path / "file.json" constructs a child path; read_text and write_text read and write text. A context manager, used with with, manages entry and exit. A temporary-directory context removes its contents on exit. Save your submission outside temporary runtime directories. Reopening a file is different from reusing a Python variable: the former tests retained bytes, while the latter only tests this kernel.

python
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as intro_folder:
    intro_path = Path(intro_folder) / "observation.json"
    intro_path.write_text(json.dumps(intro_data), encoding="utf-8")
    intro_reopened = json.loads(intro_path.read_text(encoding="utf-8"))
    assert intro_reopened == intro_data
    print("Read from a file:", intro_reopened)

Retrieval check: explain JSON versus a dictionary, annotation versus validation, class versus instance, and defining a callback versus invoking it. Change the callback above so an incorrect implementation visibly changes the observed output. This distinction will matter when grading your connected work. Reference: Python's JSON, dataclasses, and pathlib documentation.

Pydantic: turn an input dictionary into a checked object

Pydantic is an additional Python library for validating data. Its model is a class describing fields, not a neural network. Inherit from BaseModel, declare annotated fields, then call model_validate on incoming data. A field without a default is required. A field with a default can be omitted. The result is an instance whose values you read with dot notation.

python
from pydantic import BaseModel, ConfigDict, Field, ValidationError


class IntroCourseRequest(BaseModel):
    model_config = ConfigDict(strict=True, extra="forbid")
    name: str = Field(min_length=1)
    quantity: int = Field(gt=0, le=1000)
    note: str = ""


intro_request = IntroCourseRequest.model_validate({"name": "mango", "quantity": 4})
print(intro_request.name, intro_request.quantity, repr(intro_request.note))
assert intro_request.note == ""

The annotation says the field's type. Field supplies constraints: gt=0 means greater than zero, le=1000 means at most 1000, and min_length=1 excludes an empty name. ConfigDict sets model-wide behavior. strict=True rejects conversions for this integer field, including "4", 4.0 and True; extra="forbid" rejects undeclared keys. Pydantic can otherwise convert some compatible inputs, so choose this boundary deliberately rather than assuming every accepted input arrived in the expected type.

Predict which rule refuses each payload. ValidationError reports a failed contract. Its errors() entries contain loc, the field location, and type, the failure category. Catching that expected exception lets the notebook inspect the failure and continue.

python
intro_bad_requests = [
    {"name": "mango", "quantity": "4"},
    {"name": "mango", "quantity": True},
    {"name": "", "quantity": 4},
    {"name": "mango", "quantity": 0},
    {"name": "mango", "quantity": 4, "approved": True},
    {"quantity": 4},
]
for intro_bad_request in intro_bad_requests:
    try:
        IntroCourseRequest.model_validate(intro_bad_request)
    except ValidationError as intro_error:
        print([(item["loc"], item["type"]) for item in intro_error.errors(include_input=False)])
    else:
        raise AssertionError("An invalid input crossed the declared contract")

Use model_dump() for a Python dictionary, model_dump_json() for JSON text, and model_validate_json() to parse and validate JSON. model_json_schema() describes the contract; it is neither an instance's current values nor an invocation of the business handler.

python
intro_serialized = intro_request.model_dump_json()
intro_schema = IntroCourseRequest.model_json_schema()
assert IntroCourseRequest.model_validate_json(intro_serialized) == intro_request
print("Actual values:", intro_request.model_dump())
print("Quantity contract:", intro_schema["properties"]["quantity"])
assert intro_schema["properties"]["quantity"]["exclusiveMinimum"] == 0

Four is valid input to this schema even if the shop needs six. Pydantic checks the declared shape and constraints; the handler still needs authoritative stock, price and permission. Ordinary assignments to an existing instance are not automatically revalidated unless configured for assignment validation. This lesson validates new input at the boundary and uses the resulting values. Explain these limits before relying on a model object in a transaction or tool call.

Chapter 2's full introduction expands this pattern with a separate data-repair checkpoint. This notebook contains the required pattern here so prior Pydantic experience is not needed. References: models, fields, and strict mode.

SQLite from the first row to an atomic change

A dictionary disappears when its process ends. A database can retain records so a later process can resume from evidence. SQLite is an embedded database: Python's sqlite3 library opens a local database file without starting a separate database server. SQL is the language used to define, select and change its records. A table has named columns and rows. A primary key identifies a row; a query asks for rows satisfying a condition.

Start with a deliberately small preference table. Read the SQL as instructions: create the table, insert one named value, then select the value for one session. ? is a parameter placeholder; the values are passed separately so they are data, not SQL instructions. fetchone() returns one row or None; it does not guarantee that a matching row exists.

python
import sqlite3
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as intro_sql_folder:
    intro_db_path = Path(intro_sql_folder) / "example.sqlite"
    intro_db = sqlite3.connect(intro_db_path, autocommit=True)
    intro_db.execute("CREATE TABLE preference (id INTEGER PRIMARY KEY, session TEXT, value TEXT)")
    intro_db.execute("INSERT INTO preference (session,value) VALUES (?,?)", ("lucy", "09:00"))
    intro_row = intro_db.execute(
        "SELECT value FROM preference WHERE session=?", ("lucy",)
    ).fetchone()
    print("Matching row:", intro_row)
    assert intro_row == ("09:00",)
    assert (
        intro_db.execute(
            "SELECT value FROM preference WHERE session=?", ("another-session",)
        ).fetchone()
        is None
    )
    intro_db.close()
    intro_reopen = sqlite3.connect(intro_db_path, autocommit=True)
    assert intro_reopen.execute("SELECT count(*) FROM preference").fetchone()[0] == 1
    intro_reopen.close()
print("The row survived closing and reopening its connection.")

Index [0] selects the first column of a returned tuple. sqlite3.Row is an alternative row factory that also permits named-column access. dict(row) then produces an ordinary dictionary. The book's Database wrapper supplies that configuration and its schema; the wrapper is course code, while sqlite3 is the standard library. You will use the public connection and transaction methods explained at the exercise boundary, rather than needing to reconstruct the wrapper.

Now consider a budget. Moving five cents from reserved to spent requires two values to change together. A transaction makes a group of local changes commit together or roll back together. The example explicitly controls SQL transactions with autocommit=True and SQL statements. BEGIN IMMEDIATE starts a write transaction; COMMIT keeps its changes; ROLLBACK discards them. Predict the row after the deliberately raised exception. Catching an error alone would not undo the first update; the rollback is the operation that restores the prior state.

python
intro_ledger = sqlite3.connect(":memory:", autocommit=True)
intro_ledger.execute(
    "CREATE TABLE budget (id INTEGER PRIMARY KEY, reserved INTEGER, spent INTEGER)"
)
intro_ledger.execute("INSERT INTO budget VALUES (1,5,0)")
intro_ledger.execute("BEGIN IMMEDIATE")
try:
    intro_ledger.execute("UPDATE budget SET reserved=0 WHERE id=1")
    raise ValueError("injected failure before the matching spend update")
except ValueError:
    intro_ledger.execute("ROLLBACK")
assert intro_ledger.execute("SELECT reserved,spent FROM budget").fetchone() == (5, 0)
intro_ledger.execute("BEGIN IMMEDIATE")
intro_ledger.execute("UPDATE budget SET reserved=0,spent=5 WHERE id=1")
intro_ledger.execute("COMMIT")
print(
    "After a complete change:", intro_ledger.execute("SELECT reserved,spent FROM budget").fetchone()
)
intro_ledger.close()

The literal :memory: creates a temporary database inside this connection; it is useful for the small experiment, but the earlier file example establishes persistence. Neither example proves that a remote supplier rolls back when the local transaction rolls back. An external operation has its own state and evidence.

SQL you will meet later. UPDATE ... SET ... WHERE ... changes selected rows. AND combines conditions. ORDER BY makes an ordering explicit; absent that clause, do not rely on row order. count(*) counts rows; sum(amount) totals a column and can be NULL on an empty input; coalesce(sum(amount),0) uses zero for that empty aggregate. A UNIQUE constraint rejects duplicate identities. GROUP BY status computes one aggregate per status.

An invariant is a condition that must remain true across operations, such as nonnegative reserved money. A snapshot is a consistent view at one point; two separate reads can describe different moments unless their transaction contract binds them. In the book, with db.immediate() groups related writes. It is a course-defined context manager with the commit/rollback purpose you just observed. Do not assume that an arbitrary with connection has identical behavior under every SQLite autocommit setting.

Your prediction: two workers both read ten remaining cents outside a transaction and each approve seven. Why can both believe the next order fits? Explain what must be checked together with the write. Then change the example's initial reserved amount and repeat the failure. Reference: Python's SQLite tutorial and transaction control.

Evaluation asks a precise question of independently specified evidence

An agent can produce fluent text and still order the wrong amount. An evaluation case fixes inputs, a task and expected business outcomes. An oracle defines those outcomes independently of the candidate. A baseline is a simpler method used for comparison. A metric summarizes observations; it does not replace the per-case evidence that produced it.

For Lucy, relevant facts include product identity, physical stock, reserved stock, target and price. Sellable stock is physical stock minus reserved stock. If physical stock is six, four are reserved and the target is five, the deficit is three. A baseline that ignores reservations will report no deficit and can make a correct agent look wrong.

Calculate a case before writing its oracle

Predict the needed quantities for the rows below, including the exact-threshold row. The expected dictionary is written independently, before the baseline calculation. Do not replace it with the candidate's own output when the comparison fails.

python
intro_case_rows = [
    {"sku": "MANGO", "physical": 6, "reserved": 4, "target": 5},
    {"sku": "COCOA", "physical": 7, "reserved": 2, "target": 5},
]
intro_expected = {"MANGO": 3}
intro_baseline = {}
for intro_row in intro_case_rows:
    intro_available = intro_row["physical"] - intro_row["reserved"]
    intro_need = max(0, intro_row["target"] - intro_available)
    if intro_need:
        intro_baseline[intro_row["sku"]] = intro_need
print(intro_baseline)
assert intro_baseline == intro_expected

The baseline omits products with no deficit. Including zero entries would change its declared output contract. Empty input should produce an empty dictionary. Renaming the SKU must change the identity in the output without changing arithmetic. These are useful checks against a candidate that simply looks up the visible example.

Keep the denominator visible

Suppose one system solves nine of ten easy cases and none of two difficult cases. “90%” describes only the easy subset. A reported aggregate needs its population and missingness. Unrun cases are not successes or observed failures; retain their status separately. The same discipline applies to cost and latency: specify which attempts the total includes.

python
intro_case_results = [
    {"case": "ordinary", "status": "PASS", "cents": 2},
    {"case": "reserved", "status": "FAIL", "cents": 3},
    {"case": "provider-down", "status": "NOT_RUN", "cents": None},
]
intro_observed = [row for row in intro_case_results if row["status"] != "NOT_RUN"]
intro_passes = sum(row["status"] == "PASS" for row in intro_observed)
print("Observed pass fraction:", intro_passes, "/", len(intro_observed))
print("Unrun:", len(intro_case_results) - len(intro_observed))
print("Known recorded cost:", sum(row["cents"] for row in intro_observed))
assert intro_passes == 1 and len(intro_observed) == 2

The fraction is one of two observed cases, with one unrun case. A mean alone can hide an important failed case, so the course retains each observation. Holdouts are additional cases withheld from the visible feedback. They test transfer, but a finite holdout suite is still not proof for every possible input or every natural-language claim.

A saved report needs a subject and provenance

Record the evaluated configuration, scenario identities and exact evidence. A digest can detect changed report bytes; it cannot establish that the report's oracle was correct. A supplied Case.expected is the reference for grading, not an input the baseline may read to generate its answer. A candidate returning that field would pass by copying the answer rather than calculating.

The actual baseline function is connected to evaluate, which also invokes the offline shop model and actual tools. The construction task implements the deterministic calculation from stock rows. The failure task removes reserved stock from the oracle's arithmetic. Inspect both baseline and tool observations to determine which side is wrong; do not automatically trust the component named “baseline.”

Before coding, write cases for no products, exact threshold, a renamed product and reservations larger than physical stock. Add a fluent but wrong explanation while holding correct tool calls fixed. Explain why substring checks cannot establish arbitrary prose faithfulness and why an honest review-required outcome is preferable to a fabricated pass.

Understand the supplied execution interface

The course runtime is provided so your implementation can be connected to real callers and storage. SourceTask(ROOT, chapter) makes a private copy. install(source) replaces only the declared function; visible() invokes the real chapter probe; save(path, result) retains a successful implementation and its evidence. load(path) checks the saved identities and hashes. inject_failure() changes the declared boundary; repair(fragment) replaces that broken fragment. close() removes the scratch copy after you retain evidence. These methods are supplied harness operations, not additional packages you must discover or install.

RuntimeLab provides the same copied-source failure experiment without the complete-function construction layer. Its run method records exit status, observations and the compared expectation. A subprocess log from an unfinished learner implementation is feedback about that implementation; it is not a successful connection. A syntax error in the notebook cell itself is a separate issue to fix. The task below names which interface it uses.

For direct-function units, the visible driver calls your callback without installing a source string. In either case, trace where your code is invoked. Supplied fixtures, database wrappers and replay models are labeled infrastructure; your own implementation and changed-case explanation are the evidence of learning.

Main practical: construct, connect and challenge

Design question: The oracle must account for reserved stock?

Construct the independent replenishment baseline over a Case: use physical minus reserved stock, include only actual deficits, retain product identity and avoid a model call.

You edit a complete function in a temporary copy of src/reference_organizations/store/evaluation.py. The real callers, database and tool boundaries remain connected. The self-contained setup above supplies the frozen development runtime. The notebook runs reviewed local subprocesses; it is not a security sandbox. No live account is required.

Predict before running

Feed the same Case through evaluate with OfflineShopModel and compare authored expected quantities to both baseline and real tool observations.

Write the expected result and a falsifying observation before running. Include one legal action, one refusal, and the exact-empty case where the interface permits it. Explain the consequence for Lucy if your prediction is wrong.

python
import json
import os
import runpy
from pathlib import Path

ROOT = COURSE_ROOT

SourceTask = runpy.run_path(str(ROOT / "book/always_on/exercises/source_tasks_v1.py"))["SourceTask"]
REFERENCE_LESSON = 12
HANDOFF = Path("ch16-unit-a-handoff-v1.json")

Construct the complete mechanism

Implement baseline in the string below. Keep the named signature and existing helper interfaces. The starter is intentionally incomplete; its failed connection is reported separately from whether the notebook itself executed. A constant answer cannot stand in for the real mechanism.

Inspect the supplied caller around the function in src/reference_organizations/store/evaluation.py. Draw the data path from the observed output through this function to its actual input or query. Then write your implementation from the contract.

python
implementation_source = """
def baseline(case: Case) -> list[tuple[str, int]]:
    raise NotImplementedError("Construct this chapter mechanism")
"""

Hint 1: the design

Ignoring reservations makes the supposedly simpler baseline wrong while the agent can still be right.

Hint 2: the boundary

Inspect the parameters and the caller in src/reference_organizations/store/evaluation.py. Identify validation, durable state and the first externally observable effect. Preserve the existing surrounding helper contracts.

Hint 3: the structure

For each stock row compare available stock with threshold; calculate needed from the same quantities; do not read case.expected to produce an answer.

Connect to the cumulative runtime

The following installs your complete function into the copied runtime and executes the chapter probe against it. It saves your implementation and the observed connection for Unit B only after that connection succeeds.

python
def connect_build(source):
    task = SourceTask(ROOT, REFERENCE_LESSON)
    try:
        task.install(source)
        result = task.visible()
        if result["status"] == "PASS":
            task.save(HANDOFF, result)
        return result
    finally:
        task.close()


build_result = connect_build(implementation_source)
print("CONNECTION", build_result["status"])
print("OBSERVATION", build_result["observation"])

Challenge and transfer

Use an empty catalog, exact threshold, renamed products and high reservations. A visible-case lookup and an implementation returning case.expected must fail.

Use a fresh SourceTask, install your implementation and edit only its copied probe to run the changed input. Keep the expected result in your prediction notes, independent of your implementation. Call task.run("MY_TRANSFER", expected=your_expected) and close the task in finally. Retain both a valid and a refused case so rejecting everything cannot pass.

The instructor runs additional cases with different identities and boundaries against the real source. Passing the visible connection alone is not the transfer verdict. Do not put instructor solutions or holdouts into a student submission.

Save and explain

After success, submit ch13-unit-a-handoff-v1.json, your source, prediction notes and changed-input observations. Unit B checks the chapter, runtime hash and exact implementation hash and re-executes your code.

Explain which input or state caused the output, which observation would refute the explanation and what remains outside the guarantee: A passing finite scenario suite is not proof of arbitrary language faithfulness.

python
exercise_report = {
    "unit": "ch16-a",
    "attempted": 1,
    "completed": int(build_result["status"] == "PASS"),
    "failed": int(build_result["status"] != "PASS"),
    "skipped": 0,
    "connection": build_result["status"],
    "handoff": "WRITTEN" if build_result["status"] == "PASS" else "NOT_READY",
}
print("EXERCISE_REPORT=" + json.dumps(exercise_report, sort_keys=True))

Changed-constraint construction: Build an oracle that cannot copy the expected answer

Allow twenty minutes. Spend three minutes predicting, ten implementing and tracing, five on a new case of your own, and two explaining the surviving limitation. This is dedicated work, not an invitation to run a supplied answer. Both units revisit the same invariant after different core experiences; in Unit B, attempt this task from memory before consulting Unit A.

Implement transfer_check(rows). Each row has sku, physical, reserved and target nonnegative integer fields. Return a dictionary of only positive deficits, calculated from physical minus reserved. There is deliberately no expected field in this interface. Inputs have unique identities and must remain unchanged.

Write your expected values before running the table. Keep one accepted case and one refusal. Your function is passed directly into the driver below. The driver copies inputs and checks they remain unchanged; it does not replace your implementation with the reference answer.

Hint 1: identify the authoritative inputs Name the source field for each output value. Which input changes while the rule remains the same?

Hint 2: choose the boundary cases Start with exact empty, exact equality and one value on each side of the boundary where valid. Do not add a special case for a visible product name or operation identity.

python
def transfer_check(rows):
    raise NotImplementedError("Calculate independent deficits from stock inputs")
python
import copy
import json

TRANSFER_CASES = [
    (
        "reserved deficit",
        [[{"sku": "MANGO", "physical": 6, "reserved": 4, "target": 5}]],
        {"MANGO": 3},
    ),
    ("exact threshold", [[{"sku": "MANGO", "physical": 7, "reserved": 2, "target": 5}]], {}),
    ("empty", [[]], {}),
    (
        "renamed identity",
        [[{"sku": "PEAR", "physical": 1, "reserved": 0, "target": 4}]],
        {"PEAR": 3},
    ),
]


def same_transfer_value(actual, expected):
    if type(actual) is not type(expected):
        return False
    if isinstance(expected, dict):
        return actual.keys() == expected.keys() and all(
            same_transfer_value(actual[key], value) for key, value in expected.items()
        )
    if isinstance(expected, list):
        return len(actual) == len(expected) and all(
            same_transfer_value(a, e) for a, e in zip(actual, expected, strict=True)
        )
    return actual == expected


def run_transfer(candidate, cases):
    observations = []
    for label, arguments, expected in cases:
        supplied = copy.deepcopy(arguments)
        before = copy.deepcopy(supplied)
        raised = None
        try:
            actual = candidate(*supplied)
        except NotImplementedError:
            raised = "NotImplementedError"
            actual = {"unfinished": True}
        except Exception as error:
            raised = type(error).__name__
            actual = {"raises": raised}
        expects_error = isinstance(expected, dict) and set(expected) == {"raises"}
        correct = (
            raised == expected["raises"]
            if expects_error
            else (raised is None and same_transfer_value(actual, expected))
        )
        passed = correct and same_transfer_value(supplied, before)
        observations.append(
            {"case": label, "expected": expected, "observed": actual, "passed": passed}
        )
        print("PASS" if passed else "NEEDS_WORK", label, "expected", expected, "observed", actual)
    return observations


transfer_observations = run_transfer(transfer_check, TRANSFER_CASES)
TRANSFER_PASSED = all(row["passed"] for row in transfer_observations)
print("TRANSFER_STATUS", "PASS" if TRANSFER_PASSED else "NEEDS_WORK")

Design a counterexample and retrieve the mechanism

Add one new case with an independently calculated expected outcome to TRANSFER_CASES and rerun the driver. Change one condition at a time. Then deliberately replace your candidate with a constant answer in a temporary copy and show a case that rejects it. Restore your implementation. Explain why that counterexample is stronger than repeating the original example with a new name.

Without viewing the worked example, write the invariant in words and trace one observed value back to its input. Identify which part is a local fixture result and which claim would need a live provider, host or external-system observation. Keep a first attempt even if you used a hint.

Save your evidence and explain the result

Fill the prediction notes and your explanation before saving. Include the exact observed value, the input or retained row that caused it, your code's invocation point, one failed hypothesis, and the strongest claim the evidence still cannot support. A completed code cell alone does not earn explanation credit. Do not label reference-start behavior as your own Unit A construction.

Keep this edited notebook, the Markdown if used for notes, saved handoff files, and the JSON record below. Your work folder survives scratch cleanup and can be reopened in a new kernel. An instructor can ask for an unseen case after the visible checks; keep your implementation general.

python
explanation_notes = {
    "causal_trace": "Explain the input, learner invocation and observed result.",
    "failed_hypothesis": "Describe a prediction the evidence changed.",
    "remaining_limit": "Name the guarantee not established by this experiment.",
}
course_submission = {
    "unit": "ch16-a",
    "planned_minutes": 90,
    "starting_evidence": globals().get("HANDOFF_ORIGIN", "INDEPENDENT_UNIT_A"),
    "prediction": prediction_notes,
    "explanation": explanation_notes,
    "core_report": exercise_report,
    "transfer": transfer_observations,
    "explanation_review": "HUMAN_REVIEW_REQUIRED",
}
submission_path = COURSE_WORK / "ch16-a-submission-v1.json"
submission_path.write_text(
    json.dumps(course_submission, indent=2, sort_keys=True), encoding="utf-8"
)
print("Saved evidence:", submission_path)
print(
    "COURSE_REPORT="
    + json.dumps(
        {
            "unit": "ch16-a",
            "transfer_passed": TRANSFER_PASSED,
            "starting_evidence": course_submission["starting_evidence"],
            "edition": "student",
        },
        sort_keys=True,
    )
)

Extension: put a language model behind the evaluation report

Above, you ran evaluate yourself and read the report. The oracle, baseline, was written without looking at case.expected, and the report's passed is the conjunction of named checks over a transcript, never a judgment of the prose. The remaining question is what happens when a model reads that report and is the one asked to record the verdict. A verdict is durable: once Lucy's ledger says a case passed, the next chapter's activation boundary trusts it.

This section makes the model an evaluation clerk. Its tools wrap the chapter's real functions: baseline for the independent answer, evaluate with the runtime's OfflineShopModel as the agent under test, and one consequential tool that appends a verdict to the append-only events table through append_event. The loop is the Chapter 3 run_loop; the tools are behind the Chapter 15 Dispatcher, so a verdict needs write authority and the guard can refuse.

The guard's rule is the chapter's rule: a verdict may only name a case that was evaluated in this session, and it must say what the report said. llm_lab.py supplies ScriptedModel and OpenAIModel behind the book's Model protocol; the record always says which one ran.

Prediction: the next cell prints four tool contracts. Write down which tool reveals the authored expected answer, which one is consequential, and what baseline should return for the reserved_stock case (physical 8, reserved 3, threshold 8) before you run it.

python
import json
from pathlib import Path

from pydantic import BaseModel, ConfigDict, Field

from reference_organizations.store.agent import OfflineShopModel
from reference_organizations.store.evaluation import CASES, Case, baseline, evaluate
from sovereign_agent.agent_loop import Limits, run_loop
from sovereign_agent.database import Database
from sovereign_agent.events import append_event, replay
from sovereign_agent.llm_lab import ScriptedModel, describe, scripted_turn, tool_trace
from sovereign_agent.model_turn import ToolCall
from sovereign_agent.tool_dispatch import Dispatcher, ExecutableTool

LLM_VERDICT_DB = COURSE_WORK / "ch16-a-llm-verdicts.sqlite"
CASE_BOOK = {case.name: case for case in CASES}
EVALUATION_LIMITS = Limits()
OPEN_DATABASES = []


class NoArguments(BaseModel):
    model_config = ConfigDict(extra="forbid", strict=True)


class CaseArguments(NoArguments):
    name: str = Field(min_length=1, max_length=64)


class VerdictArguments(CaseArguments):
    passed: bool
    note: str = Field(min_length=1, max_length=200)


class VerdictGate:
    """Write authority for verdicts: only an evaluated case, and only what its report says."""

    def __init__(self):
        self.evaluated, self.refused = {}, []

    def __call__(self, call):
        name, passed = call.arguments.get("name"), call.arguments.get("passed")
        if name not in self.evaluated:
            reason = "verdict_without_evaluation"
        elif self.evaluated[name]["passed"] != passed:
            reason = "verdict_contradicts_evidence"
        else:
            return
        self.refused.append((name, reason))
        raise PermissionError(reason)


def fresh_verdict_database(path):
    """Start from an empty verdict ledger so reruns and replays observe the same events."""
    while OPEN_DATABASES:
        OPEN_DATABASES.pop().close()
    for stale in (path, Path(f"{path}-wal"), Path(f"{path}-shm"), path.with_suffix(".authority")):
        stale.unlink(missing_ok=True)
    db = Database(path)
    OPEN_DATABASES.append(db)
    return db


def build_clerk(book=CASE_BOOK):
    """Four tools over the chapter's own functions; the case book never exposes `expected`."""
    db = fresh_verdict_database(LLM_VERDICT_DB)
    gate = VerdictGate()

    def case_for(name):
        if name not in book:
            raise KeyError(name)
        return book[name]

    def list_cases(_: NoArguments):
        return [{"name": c.name, "split": c.split, "products": len(c.stock)} for c in book.values()]

    def describe_case(args: CaseArguments):
        return [
            {
                "sku": sku,
                "on_hand": on_hand,
                "reserved": reserved,
                "reorder_point": point,
                "unit_cost_cents": price,
            }
            for sku, on_hand, reserved, point, price in case_for(args.name).stock
        ]

    def baseline_answer(args: CaseArguments):
        drafts = [
            {"sku": sku, "quantity": quantity} for sku, quantity in baseline(case_for(args.name))
        ]
        return {"drafts": drafts, "model_calls": 0}

    def evaluate_case(args: CaseArguments):
        report = evaluate(OfflineShopModel, cases=(case_for(args.name),), limits=EVALUATION_LIMITS)
        row = report["cases"][0]
        summary = {
            "case": row["case"],
            "passed": row["passed"],
            "checks": row["checks"],
            "observed": [list(item) for item in row["observed"]],
            "expected": [list(item) for item in row["expected"]],
            "acceptance": report["acceptance"]["status"],
        }
        gate.evaluated[args.name] = summary
        return summary

    def record_verdict(args: VerdictArguments):
        payload = {"case": args.name, "passed": args.passed, "note": args.note}
        with db.immediate():
            event = append_event(db, "evaluation_verdict", payload)
        return {"event": event.id, **payload}

    tools = [
        ExecutableTool(
            "list_cases", "List the authored scenario names and splits.", NoArguments, list_cases
        ),
        ExecutableTool(
            "describe_case",
            "Read one case's stock rows. Never shows the answer.",
            CaseArguments,
            describe_case,
        ),
        ExecutableTool(
            "baseline_answer",
            "The independent replenishment oracle for one case.",
            CaseArguments,
            baseline_answer,
        ),
        ExecutableTool(
            "evaluate_case",
            "Run the offline shop agent through the named checks.",
            CaseArguments,
            evaluate_case,
        ),
        ExecutableTool(
            "record_verdict",
            "Append a verdict to Lucy's ledger. Only for a case evaluated in this session.",
            VerdictArguments,
            record_verdict,
            consequential=True,
        ),
    ]
    dispatcher = Dispatcher(
        tools, allowed=frozenset(tool.name for tool in tools), before_write=gate
    )
    return db, dispatcher, gate


def verdicts(db):
    return [
        (e.payload["case"], e.payload["passed"])
        for e in replay(db)
        if e.kind == "evaluation_verdict"
    ]


clerk_db, clerk_dispatcher, clerk_gate = build_clerk()
for tool_schema in clerk_dispatcher.schemas():
    function = tool_schema["function"]
    print(function["name"], "requires", function["parameters"].get("required", []))
    print("   ", function["description"])
print("Consequential:", [t.name for t in clerk_dispatcher.tools.values() if t.consequential])
print("Cases:", {name: case.split for name, case in CASE_BOOK.items()})
print("Default limits:", EVALUATION_LIMITS)
CLERK_MESSAGES = [
    {
        "role": "system",
        "content": (
            "You are the evaluation clerk for Lucy's shop assistant. Evidence is what you produce "
            "in this session: read the case, ask for the independent baseline, run the "
            "evaluation, then record the verdict the report supports. Never record a verdict "
            "before evaluating and never one the report contradicts. If a call is refused, do "
            "not repeat it. Finish with a short summary that names the checks."
        ),
    },
    {"role": "user", "content": "Please check the reserved_stock case and record its verdict."},
]

describe_case shows stock rows and nothing else: the authored answer only appears in the report after evaluate_case has run, alongside the observed drafts it was compared with. record_verdict is the one consequential tool, and the guard attached to the dispatcher keeps evaluated, the session's own evidence, next to refused, its ledger of reasons. The dispatcher flattens a guard refusal to tool_failed, which is why the guard keeps that ledger.

Run the loop against a recorded transcript

The turns below are what a model replied, written down. Turn one lists the cases. Turn two reads reserved_stock and asks for the baseline. Turn three records a verdict on the strength of the baseline alone. Turn four runs the evaluation. Turn five records the verdict again. Turn six reports, which ends the loop.

Prediction: write the six observations in order as ok or refused, the reason the guard logs for the refusal, the baseline's drafts, and how many evaluation_verdict events the ledger holds when the loop stops. Then check each against the printed record.

python
def recorded_turns(name):
    """The same six turns for any case: read, baseline, verdict too early, evaluate, verdict."""
    return [
        scripted_turn(calls=[{"name": "list_cases", "arguments": {}}]),
        scripted_turn(
            calls=[
                {"name": "describe_case", "arguments": {"name": name}},
                {"name": "baseline_answer", "arguments": {"name": name}},
            ]
        ),
        scripted_turn(
            calls=[
                {
                    "name": "record_verdict",
                    "arguments": {"name": name, "passed": True, "note": "baseline looks right"},
                }
            ]
        ),
        scripted_turn(calls=[{"name": "evaluate_case", "arguments": {"name": name}}]),
        scripted_turn(
            calls=[
                {
                    "name": "record_verdict",
                    "arguments": {"name": name, "passed": True, "note": "every named check passed"},
                }
            ]
        ),
        scripted_turn(
            f"Case {name}: the baseline and the offline agent agree, the evaluation passed its "
            "named checks and the verdict is recorded. My first verdict was refused because no "
            "evaluation had run yet."
        ),
    ]


RECORDED_TURNS = recorded_turns("reserved_stock")
LOOP_LIMITS = Limits(model_calls=8, tool_calls=16, seconds=120, output_tokens=4096)

scripted_db, scripted_dispatcher, scripted_gate = build_clerk()
scripted_result = run_loop(
    ScriptedModel(RECORDED_TURNS), scripted_dispatcher, CLERK_MESSAGES, limits=LOOP_LIMITS
)
print(describe(scripted_result, "scripted"))
print("Guard refused:", scripted_gate.refused, "| verdicts:", verdicts(scripted_db))
scripted_trace = tool_trace(scripted_result)
assert scripted_result.status == "COMPLETED"
assert [step["ok"] for step in scripted_trace] == [True, True, True, False, True, True]
assert scripted_trace[2]["result"]["drafts"] == [{"sku": "V", "quantity": 3}]
assert scripted_trace[3]["result"] == "tool_failed"
assert scripted_gate.refused == [("reserved_stock", "verdict_without_evaluation")]
evaluation = scripted_trace[4]["result"]
assert evaluation["passed"] is True and evaluation["observed"] == [["V", 3]]
assert evaluation["checks"]["baseline_matches_authored_answer"] is True
scripted_verdicts = verdicts(scripted_db)
assert scripted_verdicts == [("reserved_stock", True)]
# Every observation in the transcript carries the identifier of the request it answers.
assert all(
    message.get("tool_call_id") for message in scripted_result.messages if message["role"] == "tool"
)

The early verdict reached the transcript as a failed observation and the loop carried on; the ledger holds one event, written after the evaluation. The baseline said three tubs, not zero: physical minus reserved is five, three below the threshold. An oracle that forgot reserved would have disagreed with the authored answer, and the report would have said so.

Run the same loop against a live model

Nothing changes except the model. build_model looks for an OPENAI_API_KEY in Colab's Secrets pane (the key icon in the left sidebar: add a secret with that name and switch on notebook access for it), then in the process environment for a local kernel. Without a key it returns the scripted model again and the record says so. A missing key is a normal condition, never a silent substitution.

The live model is gpt-5.1 through the openai library, which Colab ships preinstalled; on a local kernel run %pip install openai once. It receives the same four schemas and the same request. It may skip the baseline, evaluate more cases than asked, or try to record early. What it cannot do is put a verdict in the ledger that its own session's evaluation does not support, because that rule lives in the guard and not in the prompt.

Prediction: write which ledger properties must hold whatever the model does, then run the cell and compare the model's judgment, or the recorded transcript, with your list.

python
from sovereign_agent.llm_lab import DEFAULT_MODEL, build_model, resolve_api_key

live_db, live_dispatcher, live_gate = build_clerk()
chosen_model = build_model(RECORDED_TURNS, model=DEFAULT_MODEL)
print("Model source:", chosen_model.source, "| key found:", resolve_api_key() is not None)
live_result = run_loop(chosen_model, live_dispatcher, CLERK_MESSAGES, limits=LOOP_LIMITS)
print(describe(live_result, chosen_model.source))
print("Guard refused:", live_gate.refused, "| verdicts:", verdicts(live_db))
live_trace = tool_trace(live_result)
live_verdicts = verdicts(live_db)
assert live_result.status in {"COMPLETED", "MODEL_CALL_LIMIT", "TOOL_LIMIT", "MODEL_FAILED"}
# Whatever the model did, every verdict in the ledger names a case this session evaluated and
# repeats that report's own outcome; every refused verdict has a reason in the guard's ledger.
for case_name, passed in live_verdicts:
    assert case_name in live_gate.evaluated and live_gate.evaluated[case_name]["passed"] == passed
refused_verdicts = [
    s for s in live_trace if s["tool"] == "record_verdict" and s["result"] == "tool_failed"
]
assert len(refused_verdicts) == len(live_gate.refused)
for step in live_trace:
    if step["tool"] == "evaluate_case" and step["ok"]:
        assert step["result"]["checks"]["baseline_matches_authored_answer"] is True, step
        assert step["result"]["checks"]["no_purchases"] is True, step
assert all(
    message.get("tool_call_id") for message in live_result.messages if message["role"] == "tool"
)

Challenge: author a case, then author it wrongly

Cases are data, so add two. saturday_hold holds five of eight vanilla tubs back for a party, with the expected answer calculated by hand from physical minus reserved. saturday_hold_naive has the same stock but an authored answer written as if reservations did not exist. The recorded transcript is reused unchanged for both; only the case name changes.

Predict before running: the baseline's drafts for the new case; which checks the naive case fails and whether the offline agent or the authored answer is the one that is wrong; and what the guard refuses at turn five on the naive case, given that the recorded model insists on passed: True. The final direct call records the verdict the report supports.

In your notes, separate what the scripted runs prove (the oracle, the named checks, the guard, the ledger) from what only a live run shows (whether the model read the report before writing). A passing finite suite is still not proof of arbitrary language faithfulness; the saved record keeps the scripted and live results apart so neither is mistaken for the other.

python
SATURDAY_STOCK = (("SKU-VANILLA", 8, 5, 8, 250), ("SKU-CHOCOLATE", 12, 0, 6, 300))
AUTHORED_CASES = {
    **CASE_BOOK,
    "saturday_hold": Case("saturday_hold", "notebook", SATURDAY_STOCK, (("SKU-VANILLA", 5),)),
    "saturday_hold_naive": Case("saturday_hold_naive", "notebook", SATURDAY_STOCK, ()),
}
challenge_db, challenge_dispatcher, challenge_gate = build_clerk(AUTHORED_CASES)
hold_result = run_loop(
    ScriptedModel(recorded_turns("saturday_hold")),
    challenge_dispatcher,
    CLERK_MESSAGES,
    limits=LOOP_LIMITS,
)
hold_trace = tool_trace(hold_result)
print("saturday_hold:", [step["ok"] for step in hold_trace], hold_trace[2]["result"]["drafts"])
assert hold_trace[2]["result"]["drafts"] == [{"sku": "SKU-VANILLA", "quantity": 5}]
assert hold_trace[4]["result"]["passed"] is True and hold_trace[5]["ok"] is True

naive_result = run_loop(
    ScriptedModel(recorded_turns("saturday_hold_naive")),
    challenge_dispatcher,
    CLERK_MESSAGES,
    limits=LOOP_LIMITS,
)
naive_trace = tool_trace(naive_result)
naive_checks = naive_trace[4]["result"]["checks"]
print("saturday_hold_naive:", [step["ok"] for step in naive_trace])
print("  failed checks:", sorted(name for name, held in naive_checks.items() if not held))
print(
    "  observed:",
    naive_trace[4]["result"]["observed"],
    "authored:",
    naive_trace[4]["result"]["expected"],
)
assert naive_trace[4]["result"]["passed"] is False and naive_trace[5]["result"] == "tool_failed"
assert (
    naive_checks["quantities"] is False
    and naive_checks["baseline_matches_authored_answer"] is False
)
assert naive_trace[4]["result"]["observed"] == [["SKU-VANILLA", 5]]
assert challenge_gate.refused[-1] == ("saturday_hold_naive", "verdict_contradicts_evidence")

supported = challenge_dispatcher.invoke(
    ToolCall(
        id="supported",
        name="record_verdict",
        arguments={
            "name": "saturday_hold_naive",
            "passed": False,
            "note": "authored answer ignores reserved",
        },
    )
)
print("Supported verdict:", supported["ok"], "| ledger:", verdicts(challenge_db))
assert supported["ok"] is True
assert verdicts(challenge_db) == [("saturday_hold", True), ("saturday_hold_naive", False)]

llm_lab_report = {
    "unit": "ch16-a",
    "scripted": {
        "status": scripted_result.status,
        "tool_calls": scripted_result.tool_calls,
        "refused": scripted_gate.refused,
        "verdicts": scripted_verdicts,
    },
    "session": {
        "source": chosen_model.source,
        "model": DEFAULT_MODEL if chosen_model.source == "live" else None,
        "status": live_result.status,
        "model_calls": live_result.model_calls,
        "tool_calls": live_result.tool_calls,
        "evaluated": sorted(live_gate.evaluated),
        "refused": live_gate.refused,
        "verdicts": live_verdicts,
        "answer": live_result.answer[:400],
    },
    "authored": {
        "saturday_hold": {"baseline": hold_trace[2]["result"]["drafts"], "passed": True},
        "saturday_hold_naive": {
            "failed_checks": sorted(name for name, held in naive_checks.items() if not held),
            "refused": challenge_gate.refused[-1],
            "verdicts": verdicts(challenge_db),
        },
    },
}
llm_report_path = COURSE_WORK / "ch16-a-llm-lab-report-v1.json"
llm_report_path.write_text(json.dumps(llm_lab_report, indent=2, sort_keys=True), encoding="utf-8")
print("Saved evidence:", llm_report_path)
print("LLM_LAB_REPORT=" + json.dumps(llm_lab_report["session"], sort_keys=True))
while OPEN_DATABASES:
    OPEN_DATABASES.pop().close()

Keep building with Prof Rod

Found this material through a colleague, classroom or shared download? Get the complete book at profrod.ai/book and join the Prof Rod learner community. Bring one result, one question or one failure you learned from. Share this resource with another learner and keep its source links with it so they can find the full course and future updates.