Skip to content

resource

First Model Call: Unit A Exercises

Study first model call in Chapter 1. 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

This is one of two practical units for Chapter 1. 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. Implement a response reader that accepts exactly one completed assistant text response; connect it to the exact shop snapshot and refuse malformed envelopes.
  3. Solve check a brief after the catalog changes 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 nineteen-chapter 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

Use a Python 3.14 Jupyter kernel and 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 complete source runtime uses Python 3.14, so this edition does not claim compatibility with a hosted notebook service's default interpreter.

The collapsed cell contains 89 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. 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/ch01-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.

First principles: a model response is a proposal to interpret

Lucy needs a morning stock brief. Before discussing models, calculate the business result: two vanilla tubs on the shelf and a target of eight imply six needed. Twelve chocolate tubs against a target of six imply zero needed, not negative six. A useful brief can explain this calculation, but a sentence saying “ordered” does not create a supplier record.

A language model generates output from the messages provided to it. An API is the interface a program calls to request that output. The program sends a request envelope containing messages and settings; it receives a response envelope containing completion metadata and content. A token is a unit of model text processing, not necessarily one word. The max_tokens setting is a generation bound in this lesson's API-shaped fixture; it is not an accounting statement about a live service. No live service is contacted in the core lesson.

A message's role describes its place in the conversation. System messages express operating instructions; user messages carry the current request; assistant messages are generated replies. These roles influence a supporting model's interpretation, while Python still decides what capabilities are available. A harness is the surrounding program that constructs requests, parses responses, enforces deterministic rules and retains observations.

Worked example: separate syntax, shape and truth

The three questions are sequential: can the text be decoded, is the decoded shape acceptable, and do its claims agree with authoritative records? Success at an earlier question does not answer a later one. Predict which question fails for each input below.

python
import json

intro_replies = ["not JSON", "[6, 4]", '{"quantity": 7}', '{"quantity": 6}']
for intro_reply in intro_replies:
    try:
        intro_decoded = json.loads(intro_reply)
    except json.JSONDecodeError:
        print(intro_reply, "SYNTAX_REFUSAL")
        continue
    if not isinstance(intro_decoded, dict) or set(intro_decoded) != {"quantity"}:
        print(intro_reply, "SHAPE_REFUSAL")
    else:
        print(intro_reply, "agrees with six needed:", intro_decoded["quantity"] == 6)

The seven-unit record is valid JSON and has the expected key. It is still a wrong replenishment proposal. This is why the exercise's response reader and its stock calculation are separate functions. An oracle is the independently specified expected result used for comparison; if you generate the expectation by calling the student's implementation, both can share the same bug. Here we calculated six before running any candidate.

A replay lets us study the boundary without a model account

A fixture is authored input for an experiment. A replay returns those inputs in a known sequence. It establishes what the program does with that sequence; it cannot establish the probability that a live model will produce it. A deliberately fluent wrong response is a useful fixture because it forces the harness to face the failure rather than hoping a model avoids it.

python
intro_messages = [
    {"role": "system", "content": "Prepare a draft using supplied stock."},
    {"role": "user", "content": json.dumps({"on_hand": 2, "target": 8})},
]
intro_completed = {"role": "assistant", "content": "I purchased seven tubs."}
print("Request roles:", [item["role"] for item in intro_messages])
print("Generated claim:", intro_completed["content"])
intro_supplier_rows = []
assert len(intro_supplier_rows) == 0
print("Independent purchases:", len(intro_supplier_rows))

Changing a system prompt modifies input text. It does not append a supplier row. Similarly, temperature zero is a setting, not evidence that every live execution is identical. For a live comparison you would hold stock and the output contract fixed, record model/settings, run more than one trial, and report both successes and failures. That comparison is an extension after you understand the deterministic boundary.

Read the envelope from outside to inside

The core exercise accepts exactly one completed assistant text response. First check the outer dictionary, then the choices list and its length, then the choice dictionary and completion reason, then the message's role and content. This order prevents an invalid outer shape from causing a confusing inner indexing failure. Refusing malformed data is different from proving the truth of accepted prose. Unit B strengthens the business boundary using exact product identities, quantities and integer-pence calculations.

An identity digest is a deterministic fingerprint of bytes. We serialize the shop consistently before hashing so the saved brief names its exact input snapshot. A matching digest establishes which bytes were used, not whether the shelf itself was counted correctly. The later chapters will reuse this distinction for approvals and evaluation versions.

Explain before constructing

Draw four boxes: shop record, request, response reader, draft. Put the deterministic calculation beside the model prose, not inside the model. Mark the point where your function is called. Name one malformed response, one well-formed lie, and one valid draft. For each, state which box has enough information to decide. Keep this diagram: the transfer exercise will change the products while preserving the same reasoning.

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 labelled infrastructure; your own implementation and changed-case explanation are the evidence of learning.

Main practical: construct, connect and challenge

Lucy wants a useful stock brief before opening her ice cream shop. You will build the boundary that accepts a completed model response, connect it to the shop snapshot, and save evidence for Unit B.

This notebook runs offline on Python 3.11 or newer with the standard library. It makes no purchase and needs no credential. A live model call is an optional comparison after the offline work; it is not required for the exercise.

Use the same loop throughout: predict → construct → connect → challenge → explain. Write each prediction before running the case. A wrong prediction is useful when you revise the explanation from evidence.

1. Predict from Lucy's records

Before running the cell, calculate the replenishment quantity for every product. What happens when stock equals its reorder point?

python
import copy
import hashlib
import json
import sys
from pathlib import Path

assert sys.version_info >= (3, 11)

SHOP = {
    "customer": "Lucy",
    "currency": "GBP",
    "products": [
        {"sku": "SKU-VANILLA", "name": "Vanilla", "on_hand": 2, "reorder_point": 8},
        {"sku": "SKU-CHOCOLATE", "name": "Chocolate", "on_hand": 12, "reorder_point": 6},
        {"sku": "SKU-STRAWBERRY", "name": "Strawberry", "on_hand": 1, "reorder_point": 5},
    ],
}


def stock_facts(shop):
    return [
        {
            "sku": product["sku"],
            "name": product["name"],
            "on_hand": product["on_hand"],
            "needed": max(0, product["reorder_point"] - product["on_hand"]),
        }
        for product in sorted(shop["products"], key=lambda item: item["sku"])
    ]


FACTS = stock_facts(SHOP)
print(json.dumps(FACTS, indent=2))
assert [(row["sku"], row["needed"]) for row in FACTS] == [
    ("SKU-CHOCOLATE", 0),
    ("SKU-STRAWBERRY", 4),
    ("SKU-VANILLA", 6),
]

The calculation is deterministic business logic. A model can explain the facts, but it does not decide that 8 - 2 is six.

2. Inspect the request bytes

Predict where the current stock appears, which text is guidance, and what prevents a purchase.

python
def messages(shop):
    return [
        {
            "role": "system",
            "content": (
                "Write Lucy a short morning stock brief. Use only the supplied shop facts. "
                "Do not purchase anything or claim that an order exists."
            ),
        },
        {"role": "user", "content": json.dumps(shop, sort_keys=True)},
    ]


def payload(shop, model="fixture-model"):
    return {
        "model": model,
        "messages": messages(shop),
        "stream": False,
        "temperature": 0,
        "max_tokens": 256,
    }


REQUEST = payload(SHOP)
print(json.dumps(REQUEST, indent=2))
assert json.loads(REQUEST["messages"][1]["content"]) == SHOP

The system prompt asks for bounded behavior. The program has no purchasing function, which is the stronger fact. Temperature zero does not prove that a live provider will return identical text.

3. Construct the response boundary

The starter below is a plausible first attempt. It accepts the happy-path fixture, but it also trusts missing fields and the first choice it sees. Repair read_brief so it accepts exactly one completed assistant text response and refuses tool calls, refusals, empty text, wrong roles, incomplete generation, and malformed containers.

python
def read_brief(document):
    """Return one completed assistant text response, or raise ValueError."""
    # STARTER: make this boundary explicit before relying on it.
    return document["choices"][0]["message"]["content"]

Hint 1 — the decision

Check the envelope from the outside in. Refuse a shape you cannot interpret instead of guessing a default.

Hint 2 — the evidence

Inspect choices, finish_reason, message.role, tool_calls, refusal, and content. A completed string is a narrower claim than a correct business answer.

Hint 3 — the structure

Require a dictionary, then a list of length one, then a dictionary choice with finish_reason == "stop", then an assistant message with no tool call/refusal, then nonempty text.

4. Run the visible contract

Predict which cases the starter mishandles. The grader catches candidate exceptions as observations so the notebook itself can finish. Passing visible cases is necessary; it is not the hidden transfer verdict.

python
GOOD_RESPONSE = {
    "choices": [
        {
            "finish_reason": "stop",
            "message": {
                "role": "assistant",
                "content": "Vanilla needs 6 tubs; strawberry needs 4. No order was placed.",
            },
        }
    ]
}

VISIBLE_CASES = [
    (GOOD_RESPONSE, "ACCEPT"),
    ({"choices": []}, "REFUSE"),
    (
        {
            "choices": [
                {"finish_reason": "length", "message": {"role": "assistant", "content": "Van"}}
            ]
        },
        "REFUSE",
    ),
    (
        {"choices": [{"finish_reason": "stop", "message": {"role": "user", "content": "six"}}]},
        "REFUSE",
    ),
    (
        {
            "choices": [
                {
                    "finish_reason": "stop",
                    "message": {
                        "role": "assistant",
                        "content": "",
                        "tool_calls": [{"name": "buy"}],
                    },
                }
            ]
        },
        "REFUSE",
    ),
]


def grade_reader(candidate, cases):
    rows = []
    for number, (document, expected) in enumerate(cases, 1):
        supplied = copy.deepcopy(document)
        try:
            result = candidate(supplied)
        except (ValueError, TypeError, KeyError, IndexError, AttributeError) as error:
            observed = "REFUSE"
            detail = type(error).__name__
        except Exception as error:
            observed = "ERROR"
            detail = type(error).__name__
        else:
            observed = "ACCEPT"
            detail = result if isinstance(result, str) else type(result).__name__
        rows.append(
            {
                "case": number,
                "expected": expected,
                "observed": observed,
                "status": "PASS" if observed == expected and supplied == document else "FAIL",
                "detail": detail,
            }
        )
    return rows


visible_results = grade_reader(read_brief, VISIBLE_CASES)
print(json.dumps(visible_results, indent=2))
VISIBLE_PASSED = all(row["status"] == "PASS" for row in visible_results)
print("VISIBLE_CONTRACT", "PASSED" if VISIBLE_PASSED else "NEEDS_WORK")

5. Connect your boundary to Lucy's brief

This is the cumulative behavior: morning_brief calls your read_brief, binds its result to the exact shop snapshot, and keeps deterministic stock facts beside model prose. It cannot silently use a supplied reference implementation.

python
def snapshot_id(shop):
    return hashlib.sha256(json.dumps(shop, sort_keys=True).encode()).hexdigest()


def morning_brief(shop, response, reader):
    text = reader(response)
    return {
        "shop_snapshot": snapshot_id(shop),
        "facts": stock_facts(shop),
        "model_text": text,
        "claim": "DRAFT_FOR_REVIEW",
    }


connected = None
if VISIBLE_PASSED:
    connected = morning_brief(SHOP, GOOD_RESPONSE, read_brief)
    assert connected["facts"] == FACTS
    assert connected["claim"] == "DRAFT_FOR_REVIEW"
    print(json.dumps(connected, indent=2))
else:
    print("CONNECTION_NOT_READY — repair read_brief, then run this cell again.")

Trace the displayed model_text backward. Which function admitted it? Which fields were calculated without the model? This trace is part of the exercise evidence.

6. Challenge a fluent lie

Predict whether a valid response envelope can still carry a false business claim.

python
LYING_RESPONSE = copy.deepcopy(GOOD_RESPONSE)
LYING_RESPONSE["choices"][0]["message"]["content"] = (
    "I bought six vanilla tubs and the supplier accepted the order."
)

if VISIBLE_PASSED:
    challenged = morning_brief(SHOP, LYING_RESPONSE, read_brief)
    print(challenged["claim"], challenged["model_text"])
    assert challenged["claim"] == "DRAFT_FOR_REVIEW"
else:
    print("CHALLENGE_WAITING_FOR_BOUNDARY")

A passing envelope check proves response shape. It does not prove the supplier accepted anything. Chapter 11 will require durable intent and supplier evidence for that stronger claim.

7. Save the handoff for Unit B

After the visible contract passes, save the connected artifact. Unit B will refuse an absent or mismatched handoff instead of silently recreating it.

python
ARTIFACT_PATH = Path("ch01-unit-a-handoff-v1.json")
artifact_status = "NOT_WRITTEN"
if connected is not None:
    encoded = json.dumps(connected, indent=2, sort_keys=True) + "\n"
    ARTIFACT_PATH.write_text(encoded, encoding="utf-8")
    artifact_status = "WRITTEN"
    print(ARTIFACT_PATH, hashlib.sha256(encoded.encode()).hexdigest())
else:
    print("HANDOFF_NOT_WRITTEN — the learner boundary has not passed.")

Exit ticket

Submit your prediction notes, repaired function, visible-case result, data-flow trace, and handoff artifact. In four sentences answer:

  1. What does the system prompt change?
  2. What does read_brief enforce?
  3. Which facts remain unverified after read_brief succeeds?
  4. What observation would falsify your claim that your function is connected?
python
exercise_report = {
    "unit": "ch01-a",
    "attempted": 1,
    "completed": int(VISIBLE_PASSED),
    "failed": int(not VISIBLE_PASSED),
    "skipped": 0,
    "connection": "PASSED" if connected is not None else "NOT_READY",
    "handoff": artifact_status,
}
print("EXERCISE_REPORT=" + json.dumps(exercise_report, sort_keys=True))

Changed-constraint construction: Check a brief after the catalog changes

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, claims). rows contains unique sku, on_hand and target fields. claims maps SKU to claimed needed quantity. Return True only when claims contains exactly the positive deficits, with exact integer quantities; bool is not a quantity. Empty stock and empty claims agree. Do not mutate either input.

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, claims):
    raise NotImplementedError("Compare every claimed deficit with the supplied catalog")
python
import copy
import json

TRANSFER_CASES = [
    ("new mango", [[{"sku": "MANGO", "on_hand": 1, "target": 5}], {"MANGO": 4}], True),
    ("fluent wrong number", [[{"sku": "MANGO", "on_hand": 1, "target": 5}], {"MANGO": 3}], False),
    ("exact empty", [[], {}], True),
    ("invented product", [[], {"MANGO": 4}], False),
]


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": "ch01-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 / "ch01-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": "ch01-a",
            "transfer_passed": TRANSFER_PASSED,
            "starting_evidence": course_submission["starting_evidence"],
            "edition": "student",
        },
        sort_keys=True,
    )
)

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.

SOURCE PROVENANCE

Derived from github.com/profrodai/sovereign-agent/blob/5b825f3a58461bce8aba1173acf0b6d175c44b64/book/exercises/ch01/profrod-sovereign-agent-ch01-a-grounded-morning-brief-exercise.md