IamBishal

Chapter 13 · Part III: Context, models and testing

Testing your first agent: golden tasks, traces and simple evals

Build evidence that the Kestrel operations agent works before anyone else uses it. Unit-test tools and every StopCause with the fake model, record each run as a JSONL trace and read one to diagnose a wrong answer, then write golden tasks graded by plain code and run a local eval that reports pass rate, pass@k, pass^k, cost and steps over repeated trials.

37 min read · from Agentic AI Foundations

Tomasz Wójcik asks the operations agent from Chapters 7 and 8 whether order O-0000042 has been delivered. It calls get_order, reads the status and answers correctly. Is that enough to hand it to his team? No. One correct answer shows that the agent can get it right. It doesn't show how often it does, what each answer costs, or what happens on the run where a tool fails or the data can't answer the question.

This chapter builds the evidence that answers those questions. By the end of it you should be able to:

  1. Unit-test the tools and the agent loop with the fake model, including a failing tool and every budget stop.
  2. Record any run as a JSONL trace, and read one to find out why an answer was wrong.
  3. Write golden tasks whose expectations (required and forbidden tool calls, required facts, an output schema) are graded by plain code.
  4. Run a local eval that reports pass rate, average cost and average steps over repeated trials, and explain why a single run proves little.

Evals make problems and changes in behaviour visible before they reach users, which is why you build them before anyone else depends on the agent.

Nothing here is re-taught. The chapter combines sampling variability (Chapter 2), the fake model (Chapter 3), the six-section prompt and the NEEDS INFO marker (Chapter 4), pydantic validation (Chapter 5), tool errors as results (Chapter 6), run_agent, StopCause and the step log (Chapter 7), tool design (Chapter 8), the tool-result header (Chapter 9) and prices as configuration (Chapter 11).

The code is in books-code/agentic-ai-foundations/ch13-testing-your-agent/. The package ch13/ copies the Chapter 11 stack, with one optional parameter added to run_agent; the folder's README lists every new file. The golden tasks are a TOML file rather than YAML: the standard library's tomllib reads TOML, while YAML would add a parser the book's pinned packages don't include. The format that matters, and that later chapters reuse, is the set of fields, not the file syntax. Every output in this chapter is fake-model output, labelled as such; you see a real model's output when you run the code with your own key.

1. Why one good run is an anecdote, not evidence

Chapter 2 showed that the same prompt can produce different output from one call to the next. An agent amplifies that, because each step's output becomes the next step's input. A slightly different first tool call returns a different result, and that changes the context for every call after it.

Many of those routes are correct. Anthropic's write-up of its multi-agent research system notes that agents may take completely different valid paths from the same starting point, for example one searching three sources while another searches ten. A test that expects one exact sequence of tool calls would mark a correct agent as broken. Agent tests have to check outcomes and required actions, not a fixed script.

What about turning the temperature down? The glossary's rule holds: lower temperature gives more repeatable output, never identical output. Our ModelClient sends no temperature at all, so every trial uses the provider's default, and each trace records that. If you add a sampling setting, check your provider's documentation for which settings a model accepts, and keep it fixed across the trials you compare.

So trust comes in layers, and each layer answers a different question:

LayerQuestion it answersKind of answer
Unit tests with the fake modelDoes our code (tools, loop, budget) behave correctly?Deterministic pass/fail
TracesWhat actually happened in this run?A record you can query
Golden tasksWhat does a correct answer to this fixed input look like?Checkable expectations
EvalHow often does the agent get it right, and at what cost?Counts over repeated runs

The first layer never touches a real model and belongs in every pytest run. The other three measure the model, which varies from run to run. They give you a rate with a cost attached, never a certainty.

2. Deterministic tests: tools, the loop and every StopCause

The first layer proves that our own code works; until it does, any wrong answer could be our bug as easily as the model's. Everything here runs on the fake model and httpx.MockTransport, or on the seeded mock API, with no key.

The registry holds five read tools: get_order, get_shipment, list_shipments, get_stock and get_ticket. Chapter 8's write tool, create_return_authorisation, stays in Chapter 8's folder: an eval runs every task several times, and an agent under evaluation shouldn't create a return on every trial.

The tools take an httpx.Client, so a test can pass one whose transport answers like the Kestrel API. Assert on two things: the request the tool sent, and what the model would see.

books-code/agentic-ai-foundations/ch13-testing-your-agent/tests/test_tools.py (excerpt)
def test_list_shipments_sends_the_filters():
    seen: list[httpx.Request] = []
    call = ToolCall(id="c1", name="list_shipments", arguments={"carrier": "Swiftway Parcel"})
    result = make_registry(seen).dispatch(call)
    assert seen[0].url.params["carrier"] == "Swiftway Parcel"
    assert seen[0].url.params["late"] == "true"
    assert seen[0].url.params["limit"] == "10"
    assert not result.is_error and "S-0000011" in result.content


def test_unknown_order_is_a_result_the_model_can_act_on():
    call = ToolCall(id="c2", name="get_order", arguments={"order_id": "O-9999999"})
    result = make_registry([]).dispatch(call)
    assert result.is_error and result.tool_call_id == "c2"
    assert result.content == "No order O-9999999 exists."

The mock transport routes on the path alone, so without the query assertions a tool that forgot to send carrier would still pass. The second test checks the Chapter 6 rule: a 404 comes back as a result with is_error=True and a sentence the model can act on.

The loop tests build scripted responses with helpers from ch13/scripted.py, which also holds the fake-model scripts the eval uses. BUDGET and LIMITS in the tests are module constants, and registry is a pytest fixture in conftest.py that builds the tools against the mock API.

books-code/agentic-ai-foundations/ch13-testing-your-agent/ch13/scripted.py (excerpt)
def tool_use(name: str, args: dict, *, input_tokens: int = 900, output_tokens: int = 60):
    """A scripted response that requests one tool call, with a unique call id."""
    call = ToolCall(id=f"call_fake_{next(_call_ids)}", name=name, arguments=args)
    usage = Usage(input_tokens=input_tokens, output_tokens=output_tokens)
    return ModelResponse(text="", stop_reason="tool_call", usage=usage, tool_calls=[call])


def finished(text: str, *, input_tokens: int = 1_300, output_tokens: int = 50) -> ModelResponse:
    """A scripted final answer."""
    usage = Usage(input_tokens=input_tokens, output_tokens=output_tokens)
    return ModelResponse(text=text, stop_reason="finished", usage=usage)


def never_stops(name: str, args: dict, n: int = 50) -> list[ModelResponse]:
    """A script that asks for a tool on every step and never ends its turn."""
    return [tool_use(name, args) for _ in range(n)]


class FakeClock:
    """Returns start, start + step, start + 2*step, ... on successive calls."""

    def __init__(self, start: float = 0.0, step: float = 1.0) -> None:
        self.now, self.step = start, step

    def __call__(self) -> float:
        value, self.now = self.now, self.now + self.step
        return value
books-code/agentic-ai-foundations/ch13-testing-your-agent/tests/test_loop.py (excerpt)
def test_tool_error_is_returned_not_raised(registry):
    model = FakeModelClient(
        [
            tool_use("get_order", {"order_id": "O-9999999"}),
            finished("NEEDS INFO: there is no order O-9999999."),
        ]
    )
    result = run_agent(model, "system", "Status of O-9999999?", registry, BUDGET, LIMITS)

    assert result.steps[0].tool_calls[0].is_error is True
    assert result.cause is StopCause.FINISHED  # the loop carried on after the error

If run_agent raised here, one bad ID from the model would crash the run.

tests/test_budget.py provokes each of the other six StopCauses from Chapter 7. Each test checks the same contract: the run ends with that cause, final_text stays empty because only finished carries an answer, and the step log is kept for the partial result.

books-code/agentic-ai-foundations/ch13-testing-your-agent/tests/test_budget.py (excerpt)
CASES = {
    StopCause.STEP_LIMIT: (never_stops(*STOCK), RunBudget(3, 60_000, 90), None),
    StopCause.TOKEN_LIMIT: (
        [tool_use(*STOCK, input_tokens=59_900)],
        RunBudget(5, 60_000, 90),
        None,
    ),
    StopCause.TIME_LIMIT: (never_stops(*STOCK), RunBudget(50, 60_000, 60), FakeClock(step=40.0)),
    StopCause.TRUNCATED: ([stopped("truncated")], RunBudget(5, 60_000, 90), None),
    StopCause.UNEXPECTED_STOP: ([stopped("other")], RunBudget(5, 60_000, 90), None),
    StopCause.MODEL_ERROR: (
        [tool_use(*STOCK), ModelError("timeout", "timed out")],
        RunBudget(5, 60_000, 90),
        None,
    ),
}


@pytest.mark.parametrize("cause", list(CASES), ids=str)
def test_each_stop_cause(cause, registry):
    script, budget, clock = CASES[cause]
    extra = {"clock": clock} if clock else {}
    result = run_agent(
        FakeModelClient(script), "system", "How much SKU-00042?", registry, budget, LIMITS, **extra
    )
    assert result.cause is cause
    assert result.final_text == ""  # only FINISHED carries an answer

stopped(reason) is a two-line helper that returns a response with that stop reason. The token case leaves 40 tokens of the 60,000 budget, and Chapter 7's loop needs room for one useful call (256 tokens) before each step, so it stops on token_limit. The clock and the token counts are both injected. A time-limit test that really waited sixty seconds would be slow and flaky. run_agent has taken a clock since Chapter 7, and it reads usage from whatever the client returns.

These tests say nothing about whether a real model picks the right tool. Run them without a key:

bash
cd books-code/agentic-ai-foundations/ch13-testing-your-agent
uv run pytest -q
text
............................                                             [100%]
28 passed in 1.11s

3. From step log to trace: one JSONL line per event

Chapter 7's step log lives only inside the Python process. If the process dies, the step log goes with it, and nothing outside the test that created it can read it. It also keeps only a preview of each tool result.

In this book a trace is a structured record of one agent run, written locally as a JSONL file: each step's model call, tool calls, results, tokens, cost and duration. A printed line like step 3: 1x list_shipments is for a person to read. A trace line is data a program can filter and sum. Every record has kind and ts (a UTC timestamp); the other fields depend on the kind:

kindFields
run_startrun_id, task_id, prompt (the prompt file, e.g. operations_v1), model, sampling, price_as_of, budget
model_callstep, stop_reason, input_tokens, output_tokens, cost_usd, max_output_tokens, duration_ms, text, tool_calls
tool_callstep, call_id, tool, args, is_error, content, duration_ms
run_endstop_cause, steps, total_tokens, cost_usd, output

The trace keeps more than the step log: the whole tool result exactly as the model saw it, header included, and the model's text on every call. It leaves out the system prompt and the message history, because both are rebuilt from the prompt file and the earlier events, and repeating them on every line would make each trace many times larger.

books-code/agentic-ai-foundations/ch13-testing-your-agent/ch13/trace.py (excerpt)
class TraceRecorder:
    """Writes one JSON object per event to a new .jsonl file. Use it in a with block."""

    def __init__(self, path: Path, price: Price | None) -> None:
        self.path = path
        self._price = price
        self._file: TextIO | None = None
        self.cost_usd: Decimal | None = Decimal(0) if price else None  # None: unpriced

    def __enter__(self) -> "TraceRecorder":
        self.path.parent.mkdir(parents=True, exist_ok=True)
        self._file = self.path.open("x", encoding="utf-8")  # an existing file is an error
        return self

    def __exit__(self, *exc: object) -> None:
        if self._file is not None:
            self._file.close()

    def _write(self, kind: str, **fields: Any) -> None:
        if self._file is None:
            raise RuntimeError("TraceRecorder must be used in a with block")
        record = {"kind": kind, "ts": datetime.now(UTC).isoformat(), **fields}
        self._file.write(json.dumps(record, default=str) + "\n")
        self._file.flush()  # every event leaves the process before the loop moves on

    def model_call(
        self, step: int, response: ModelResponse, limits: CallLimits, duration_ms: int
    ) -> None:
        cost = cost_of(response.usage, self._price)
        if cost is not None and self.cost_usd is not None:
            self.cost_usd += cost
        self._write(
            "model_call",
            step=step,
            stop_reason=response.stop_reason,
            input_tokens=response.usage.input_tokens,
            output_tokens=response.usage.output_tokens,
            cost_usd=None if cost is None else float(cost),
            max_output_tokens=limits.max_output_tokens,
            duration_ms=duration_ms,
            text=response.text,  # empty when the model only asked for tools
            tool_calls=[c.name for c in response.tool_calls],
        )

    def tool_call(self, step: int, call: ToolCall, result: ToolResult, duration_ms: int) -> None:
        self._write(
            "tool_call",
            step=step,
            call_id=call.id,
            tool=call.name,
            args=call.arguments,
            is_error=result.is_error,
            content=result.content,  # the whole result, exactly as the model saw it
            duration_ms=duration_ms,
        )

Token counts come from the provider. The SDK's usage property gives exact token usage for each request (Anthropic Python SDK docs, as of November 2026), and the Chapter 3 adapter already copies it into our Usage. Cost is Chapter 11's cost_of(usage, price): tokens times the configured price per million, or None for an unpriced configuration, never zero. run_start records the price's as_of date, so a trace from last month still says which prices it was costed at.

Why JSONL, and why mode "x"? The recorder writes and flushes each event as it happens, so a run that crashes still leaves a readable trace up to its last event, and each line parses on its own. Mode "x" refuses to open a file that already exists. With "w", a rerun into the same path would silently overwrite the earlier trace; with "a", it would merge two runs into one.

The loop needs one change. run_agent gains an optional recorder parameter and reports to it after each model call and each tool call:

books-code/agentic-ai-foundations/ch13-testing-your-agent/ch13/agent.py (excerpt)
        if recorder:
            recorder.model_call(index, response, call_limits, ms_since(started, clock))
        tracker.record(response.usage.input_tokens, response.usage.output_tokens)
        messages.append(assistant_message(response))

        results: list[ToolResult] = []
        if response.stop_reason == "tool_call" and response.tool_calls:
            for call in response.tool_calls:
                tool_started = clock()
                results.append(registry.dispatch(call))
                if recorder:
                    recorder.tool_call(index, call, results[-1], ms_since(tool_started, clock))
            messages.append(tool_results_message(results))  # all results, one message

run_start isn't part of the loop's protocol. The loop doesn't know the task ID or the prompt version, but the caller does, so the caller writes it. The recorder only observes: it never changes a decision the loop makes, and calls without a recorder behave exactly as in Chapter 11. It doesn't swallow its own errors either. If the disk is full, _write raises, because a grade read from an incomplete trace couldn't be trusted. The eval runner limits that failure to one trial.

The recorder only observes: the caller writes run_start, the loop reports every other event, and each one becomes an appended, flushed JSONL line, so even a crashed run leaves a readable trace.

tests/test_trace.py records a fake-model run, checks the event kinds (run_start, model_call, tool_call, model_call, run_end), grades the trace with grade() (explained in the grading section below), and checks that a second recorder on the same path raises FileExistsError.

4. Reading a trace to find out why the answer was wrong

A trace earns its place when an answer is wrong. Here's one that ships with the chapter: Tomasz asks which carrier has the most late shipments, and how many. The agent confidently answers Harbour Express, 7. The run is scripted, so the model's side is fake-model output; the tool result is real, from the seeded mock API. The trace is fixtures/traces/wrong_carrier.jsonl.

The tempting first move is to reword the system prompt. Read the trace first, starting with how the run ended. The commands use jq (install it from your package manager); without it, read_trace() gives you the same events as a list of dicts.

books-code/agentic-ai-foundations/ch13-testing-your-agent (shell)
jq -c 'select(.kind == "run_end") | {stop_cause, steps, output}' fixtures/traces/wrong_carrier.jsonl
text
{"stop_cause":"finished","steps":2,"output":"{\"carrier\": \"Harbour Express\", \"late_shipments\": 7}"}

finished in two steps: no budget stop, no partial result. So look at what the tools were asked and what came back:

books-code/agentic-ai-foundations/ch13-testing-your-agent (shell)
jq -c 'select(.kind == "tool_call") | {step, tool, args, is_error}' fixtures/traces/wrong_carrier.jsonl
jq -r 'select(.kind == "tool_call") | .content | split("\n")[0]' fixtures/traces/wrong_carrier.jsonl
text
{"step":0,"tool":"list_shipments","args":{"late":true,"limit":20},"is_error":false}
[origin: list_shipments({"late": true, "limit": 20}) | kind: tool | shown: 0-5760 of 5760 chars]

One call, no carrier filter, no error, and the header from Chapter 9's render_tool_result shows every character (shown: 0-5760 of 5760), with no truncated flag. The model saw everything the tool returned. Count what that was:

books-code/agentic-ai-foundations/ch13-testing-your-agent (shell)
jq -r 'select(.kind == "tool_call") | .content' fixtures/traces/wrong_carrier.jsonl \
  | grep -o '"carrier": "[^"]*"' | sort | uniq -c
text
      7 "carrier": "Harbour Express"
      4 "carrier": "Northline Freight"
      5 "carrier": "Swiftway Parcel"
      4 "carrier": "Tallpine Logistics"

Twenty rows, exactly the limit the model asked for, and the most the tool allows. A full page means more rows probably exist, and in the seeded data they do. The model's arithmetic was fine. It counted a sample and reported it as the total, although both the tool description ("not a full count") and the prompt's constraints said not to.

Rewording the prompt again won't fix that reliably. The tools can't answer the question: /shipments has no offset, so no tool can page to a complete count. Filtering by carrier doesn't help either: every carrier has more than 20 late shipments in the seeded data, so each per-carrier call also returns a full page (tests/test_golden.py checks this). With these tools, the right answer is NEEDS INFO, and the golden task in the next section expects exactly that. Two tool-design fixes, in the spirit of Chapter 8's granularity and output shaping, would last longer, and Chapter 14 returns to the problem when it designs the capstone's tools. A counts tool could ask the API for its maximum page per carrier and return an error whenever a page comes back full, because then it can't know the set is complete. A notice in the result could say "20 of more than 20 rows; counts from this result are not totals" right next to the data, where the model reads it on every call.

Reviewing a run's trace can reveal tool misuse, wasted steps and broken constraints that grading only the outcome often misses.

When you open a trace, read it in this order:

  1. The run_end cause. Anything other than finished means a partial result, not a wrong answer.
  2. Tool errors. Find is_error: true and check whether the model acted on the message.
  3. Incomplete results. A result header with a truncated or summarised flag, an oversize-JSON error, or a list exactly as long as its limit: the model saw only part of the data.
  4. Steps against the budget. A run that used most of its steps was probably searching rather than answering.
  5. The model's text, in model_call.text and run_end.output. By then you usually know what you're looking for.

5. Golden tasks: fixed inputs with checkable expectations

To know whether a fix works, and keeps working, we need fixed questions with answers a program can check. That's a golden task: a fixed input plus expectations a program can verify, covering which tools must or must not be called, which facts must appear and which schema the output must match. It's your own task, written against your own data.

The operations agent's six golden tasks live in golden_tasks.toml. Here are three:

books-code/agentic-ai-foundations/ch13-testing-your-agent/golden_tasks.toml (excerpt)
[[task]]
id = "stock-total"
input = """How many units of SKU-00042 are on hand across both warehouses? \
Answer as JSON with sku and total_on_hand."""
required_tool_calls = [{ tool = "get_stock", args = { sku = "SKU-00042" } }]
forbidden_tool_calls = [{ tool = "get_ticket" }]  # a stock question has no reason to read tickets
output_schema = "StockTotal"
required_facts = [{ field = "total_on_hand", value = 198 }]
max_steps = 4

[[task]]
id = "unknown-order-needs-info"
input = "What is the status of order O-9999999? Answer as JSON with order_id and status."
required_tool_calls = [{ tool = "get_order", args = { order_id = "O-9999999" } }]
required_facts = [{ value = "NEEDS INFO" }]  # no such order: the right answer is the marker
max_steps = 4

[[task]]
id = "late-top-carrier-needs-info"
input = """Which carrier has the most late shipments overall, and how many? \
Answer as JSON with carrier and late_shipments."""
required_any_tool = ["list_shipments"]  # the answer must come from shipment data
required_facts = [{ value = "NEEDS INFO" }]  # list_shipments returns at most 20 rows: no totals
max_steps = 6

Each field does one job:

  • input is the question exactly as the agent receives it, naming the JSON fields the answer needs.
  • required_tool_calls names a tool and a subset of its arguments that must appear somewhere in the trace.
  • required_any_tool lists tools of which at least one must be called.
  • forbidden_tool_calls lists calls that must not appear. A stock question has no reason to read tickets.
  • required_facts holds a value. With field, it must equal that field of the parsed output; without one, it must appear in the raw text.
  • output_schema names a pydantic model, validated the way Chapter 5 validated ExpenseClaim.
  • max_steps sets the step limit in this task's run budget.

Checking a field against an exact value is stricter than searching the whole answer: an answer that lists both warehouses contains 198 somewhere too. The expected values come from the seeded data, which uv run kestrel up generates from a fixed seed, so your values match the book's. tests/test_golden.py checks every fact against the mock API, so if the kestrel package or its seed changes, the test fails loudly instead of the eval grading against stale facts.

The last two tasks test the other direction. Asked about an order that doesn't exist, or for a count the tools can't give, the agent should write the NEEDS INFO marker from Chapter 4 instead of a confident guess. Anthropic's guide Demystifying evals for AI agents advises testing cases where a behaviour should occur and cases where it shouldn't; otherwise tuning the agent in one direction can quietly break the other, and an agent pushed always to answer starts guessing. Chapter 14 designs the capstone's refusal behaviour; here we only check that the marker appears.

Six tasks is a small set on purpose. Write each task from a failure you've seen: late-top-carrier-needs-info exists because of the trace you just read. The same guide suggests 20 to 50 simple tasks drawn from real failures as a good start for an initial eval dataset, because early on the gap between a broken agent and a fixed one tends to be large, so a small sample shows it. Six tasks and five trials can show a large gap like that. They can't tell an agent that passes 90% of the time from one that passes 99%, so read 5/5 as "no failure seen yet", not "reliable".

The file loads through pydantic, so a mistake fails at load time instead of producing a task that silently checks nothing:

books-code/agentic-ai-foundations/ch13-testing-your-agent/ch13/golden.py (excerpt)
class Strict(BaseModel):
    model_config = ConfigDict(extra="forbid")  # a misspelt field is an error, not ignored


class ToolExpectation(Strict):
    tool: str
    args: dict[str, object] = {}  # a subset: other arguments are allowed


class FactExpectation(Strict):
    value: str | int | bool
    field: str | None = None  # check one field of the parsed output, not the raw text

    @model_validator(mode="after")
    def raw_text_facts_are_strings(self) -> "FactExpectation":
        if self.field is None and not isinstance(self.value, str):
            raise ValueError("a fact without a field is a substring, so its value must be text")
        return self

With extra="forbid", a misspelt requried_facts raises a validation error instead of giving a task with no fact checks. GoldenTask also rejects an unknown output_schema, and check_tool_names runs before any trial, against the registry's tool names: a task naming a tool the agent doesn't have would fail every trial.

6. Grading: deterministic checks first, a model judge only where you must

A grader is the code that decides whether a golden task's expectations were met. A task, its graders and the outcome they record make up the smallest useful unit of an eval: give the agent a fixed input, then apply assertions to what it produced. For us, what it produced is the trace and its final output. Each expectation has a check that returns pass or fail, with a reason on failure. None of them calls a model:

books-code/agentic-ai-foundations/ch13-testing-your-agent/ch13/grading.py (excerpt)
def check_tool_calls(task: GoldenTask, events: list[dict]) -> list[Check]:
    calls = [e for e in events if e["kind"] == "tool_call"]

    def seen(exp: ToolExpectation) -> bool:  # name plus a subset of arguments, in any order
        return any(
            c["tool"] == exp.tool and all(c["args"].get(k) == v for k, v in exp.args.items())
            for c in calls
        )

    checks = []
    for exp in task.required_tool_calls:
        ok = seen(exp)
        checks.append(Check("tool_calls", ok, "" if ok else f"missing call: {exp.tool} {exp.args}"))
    if task.required_any_tool:
        ok = any(c["tool"] in task.required_any_tool for c in calls)
        reason = "" if ok else f"no call to any of {task.required_any_tool}"
        checks.append(Check("tool_calls", ok, reason))
    for exp in task.forbidden_tool_calls:
        ok = not seen(exp)
        checks.append(Check("tool_calls", ok, "" if ok else f"forbidden call: {exp.tool}"))
    return checks


def grade(task: GoldenTask, events: list[dict]) -> list[Check]:
    """A trial passes only when every check passes."""
    run_end = next((e for e in reversed(events) if e["kind"] == "run_end"), None)
    if run_end is None:
        return [Check("stop", False, "no run_end: the run did not complete")]
    stop = check_stop(run_end)
    if not stop.passed:
        return [stop]  # a partial result has no answer to grade
    output = run_end["output"]
    parsed, schema_checks = check_schema(task, output)
    return [
        stop,
        *check_tool_calls(task, events),
        *schema_checks,
        *check_facts(task, output, parsed),
    ]

seen matches a tool name plus a subset of arguments anywhere in the trace, ignoring order and extra calls, so the outcome-over-path rule lives in code. grade returns early twice. A trace with no run_end (a crashed process) becomes one failed check instead of an exception. A run that stopped on step_limit is reported under that cause alone, without missing-fact failures piled on top.

check_schema is strict on purpose. An answer wrapped in a code fence, or followed by a friendly sentence, fails. Chapter 5's validate-and-retry isn't used here, because a retry would hide exactly the failure rate the eval exists to measure. The reason strings matter too: missing fact: NEEDS INFO sends you to the trace, and from there to the full page of rows. A bare FAIL sends you back to the start.

Some qualities resist string checks. Is a summary of a ticket thread faithful to what the customer said? Model-as-judge grading handles these: a second model call scores the output against a written rubric. Anthropic's guide to success criteria and evaluations (as of November 2026) calls LLM-based grading fast, flexible and scalable, and advises testing it for reliability before scaling it up. The Demystifying evals guide adds three conditions. Use deterministic graders where you can and model graders only where you must. Calibrate a judge closely against human experts, and give it a way out, such as returning "Unknown". Grade each dimension with its own isolated judge, rather than one judge for everything.

A judge brings its own sampling variability and costs money on every call: noise in the instrument that measures noise in the agent. This book's evals use deterministic checks only; if you add a judge, an "Unknown" counts as a failure, never a pass.

7. eval.py: repeated runs, pass rate, average cost and average steps

An eval runs the golden tasks, usually several times each, and reports pass rate, cost and steps. Each run of one task is a trial. Pass rate is passed trials divided by trials run, per task and overall.

Anthropic recommends running evals programmatically, with simple while-loops over direct API calls, one loop per task (Writing effective tools for AI agents). The runner follows that spirit with no eval framework, but it calls the model through run_agent, because the loop is part of what we're measuring.

Every trial starts fresh and is graded from its own trace, inside one cost cap for the whole eval, so the report reflects repeated evidence, not one lucky pass.
books-code/agentic-ai-foundations/ch13-testing-your-agent/ch13/eval.py (excerpt)
def run_eval(
    tasks: Sequence[GoldenTask],
    client_for: ClientFor,
    registry: ToolRegistry,
    settings: Settings,
    price: Price | None,
    trials: int,
    traces_dir: Path,
    model_name: str,
) -> tuple[list[TrialResult], Decimal]:
    if price is None:  # an unpriced run would cost "zero" and the cap would never fire
        raise ConfigError("an eval needs a price: its cost cap is in money")
    check_tool_names(list(tasks), {d.name for d in registry.definitions()})
    eval_dir = traces_dir / datetime.now(UTC).strftime("%Y%m%dT%H%M%S%fZ")
    results: list[TrialResult] = []
    spent = Decimal(0)
    for trial in range(1, trials + 1):  # trial-major: a cap hit thins every task evenly
        for task in tasks:
            if spent >= settings.eval_max_cost_usd:
                results.append(
                    TrialResult(
                        task_id=task.id,
                        trial=trial,
                        status="skipped",
                        failures=["eval cost cap reached"],
                    )
                )
                continue
            trace_path = eval_dir / f"{task.id}-t{trial}.jsonl"
            client = client_for(task, trial)
            result, cost = run_trial(
                task, trial, client, registry, settings, price, trace_path, model_name
            )
            results.append(result)
            spent += cost or 0
    return results, spent

run_trial, not shown, builds the task's run budget, opens a new TraceRecorder, writes run_start, calls run_agent with the prompt file PROMPT_VERSION selects, then grades the trace it just wrote. Each trial is a fresh run with a fresh client, its own trace file and its own run budget, under a timestamped folder: traces/<eval_id>/<task_id>-t<trial>.jsonl. Nothing carries over between trials or between evals.

A trial ends in one of three trial statuses, which are not StopCauses. graded means the run ended and was graded; its StopCause is one of Chapter 7's seven. error means the trial itself crashed (a recorder that couldn't write, a script that ran out) and counts as not passed, so a long eval survives one broken trial without hiding it. skipped means the cost cap stopped it from starting.

Repeated runs multiply cost: six tasks at five trials is thirty agent runs. EVAL_MAX_COST_USD caps the whole eval, which is a different thing from a run budget: the runner checks it before each trial starts, while the run budget stops one run. Skipped trials are listed but left out of the pass-rate denominator. The loop is trial-major, so if the cap stops the eval early, every task has fewer trials instead of the last tasks having none. The last trial can push the total past the cap, by at most what its own run budget allows. run_eval refuses an unpriced configuration, because an unpriced run would cost "zero" and the cap would never fire. A money limit inside one run is Chapter 16's job.

Two more terms. pass@k asks whether any of a task's k trials passed: the agent can do it. pass^k asks whether all of them did: it does it every time. For an agent that Tomasz's team will rely on daily, pass^k is the honest metric, so the report shows both.

Without --live, client_for returns a fresh FakeModelClient per task and trial from ch13/scripted.py. Two of the five late-top-carrier-needs-info scripts repeat the capped-count guess, and one stock-total script never stops, so the report has failures to count. Run it with the mock API up:

bash
uv run python -m ch13.eval
Eval report (fake-model output: scripted replies and token counts, illustrative price)
[fake model: scripted replies and token counts; tool results from Kestrel]
task                         pass   pass@k  pass^k  avg cost  avg steps  stop causes              top failure
order-status                 5/5    yes     yes     $0.0028   2.0        finished=5               -
shipment-late                5/5    yes     yes     $0.0028   2.0        finished=5               -
stock-total                  4/5    yes     no      $0.0032   2.4        finished=4 step_limit=1  stopped by step_limit
ticket-order                 5/5    yes     yes     $0.0028   2.0        finished=5               -
unknown-order-needs-info     5/5    yes     yes     $0.0028   2.0        finished=5               -
late-top-carrier-needs-info  3/5    yes     no      $0.0028   2.0        finished=5               missing fact: NEEDS INFO
overall                      27/30  6/6     4/6     spent $0.0846 of $0.50 cap, 0 skipped

This is where repeated trials earn their cost: 3/5 on late-top-carrier-needs-info is worth investigating. Read the two failing traces, then rerun with more trials before treating the problem as established. Five trials are coarse, which is why the report prints fractions, not percentages.

The eval also supports decisions. To compare two versions of the prompt, run the same golden tasks twice, changing only PROMPT_VERSION (Chapter 4's versioned files). Compare two Chapter 11 configurations the same way with --live --config NAME. Chapter 11's compare_models.py answered "which model?" on its own six tasks; this runner adds golden tasks, traces and pass^k, and it's the one the capstone reuses. Change one thing at a time; if the prompt and the model both change, a better pass rate tells you nothing about which change caused it. --live uses your key and costs real money, within the cap, and its numbers will vary from run to run, which is the reason for repeated trials.

8. Where this testing breaks down

A green report means every check passed on the tasks you wrote. That's narrower than "the agent works".

Fact checks can fail in both directions. An exact match fails a correct answer that says "Swiftway" instead of "Swiftway Parcel"; a substring search can pass a wrong answer that mentions every carrier. Expect to adjust an expectation after reading a failure and finding the answer was right. If the report shows a schema failure, open the output before blaming the agent's reasoning: it may be a correct answer inside a code fence.

Golden tasks can be overfitted: tune a prompt until all six pass, and other inputs can get worse unseen. Keep adding tasks from new failures, and hold back a few you never tune against. The opposite problem is saturation: once every task passes on every trial, the eval can no longer tell a better prompt from a worse one, and it's time to add harder tasks.

Stop causes and trial statuses need reading, not just counting. model_error and an error trial are infrastructure failures: the provider or the harness broke, not the agent's judgement. They still count against the pass rate here, so check the stop causes column before reading a drop as the agent's fault. Chapter 16 separates transient failures from permanent ones and retries the transient ones. time_limit, step_limit and token_limit are different: a slow or wandering agent hits them, and the eval rightly counts them as failures.

Finally, the scope is local: evidence for one developer before anyone else uses the agent. Production monitoring is covered in Books 6-8.

9. Exercises

All four exercises run on the fake model.

Exercise 1: tool errors under a step budget. Add a loop test in which every scripted tool call fails, for example never_stops("get_order", {"order_id": "O-9999999"}) with max_steps=3. Expected result: StopCause step_limit, no answer, and three step-log entries whose tool calls all have is_error=True. How to verify: uv run pytest -q passes. If the test raises, the loop is propagating tool errors instead of returning them.

Exercise 2: read a trace. Open fixtures/traces/wrong_stock.jsonl, a fake-model run that reports the wrong stock total for SKU-00042. Read it in the five-step order from the trace-reading section, find the line that explains the error, and name a tool-design fix. Common mistake: rewriting the prompt before checking what the tool returned. Hint: compare the answer with each warehouse's on_hand.

Exercise 3: a should-not-occur task. In exercises/golden_extra.toml, write a stock task whose forbidden_tool_calls lists get_ticket. Load it with load_golden_tasks(path), then record and grade two scripted runs, as tests/test_trace.py does: one that respects the rule and one that also calls get_ticket. Expected result: the first passes; the second fails with forbidden call: get_ticket.

Exercise 4: pass@k against pass^k. In ch13/scripted.py, remove stock-total from FAILING_TRIALS and rerun the eval. Expected result: pass@k stays at 6/6, and pass^k rises from 4/6 to 5/6. Write two sentences on what that difference means for a tool Tomasz's team uses daily.

10. Summary and what Chapter 14 does with it

Two lessons carry forward. One run proves little: trust comes from repeated trials and pass^k, not from one good demo. And grade with deterministic checks first, using a model judge only where no tool-call, fact or schema check will do.

Chapter 14, Capstone I, Design: Kestrel's research assistant, takes Sam Adeyemi's request and builds the assistant's test strategy on this chapter's trace format, golden-task file and eval runner. Chapter 16, Capstone III, Harden, adds expected citations to the golden tasks, enforces a money limit per run, and grows eval.py into the capstone's eval suite.

Bishal SahaLet's build together

Have a system to design, or an AI feature to get right?

Tell me about the problem. You'll get a clear, honest view of the best way forward.

  • Reply within 24 hoursOn business days, with my honest view and a next step.
  • Accepting select engagementsArchitecture, AI features and full builds.
  • Remote, worldwideWorking with startups, SMEs and enterprises.