flowchart TB
subgraph "Evaluation Surfaces"
O[Outcome<br/>Final answer & state]:::surface
T[Trajectory<br/>Path & steps taken]:::surface
C[Component<br/>Individual tool/model calls]:::surface
S[Environment State<br/>World changes & side effects]:::surface
end
O -->|"Did the right order<br/>get refunded?"| D[Decision: Ship / Hold]
T -->|"Was the lookup done<br/>before the refund?"| D
C -->|"Was each tool call<br/>correct & allowed?"| D
S -->|"Did only the target<br/>order change state?"| D
classDef surface fill:#e1f5e1,stroke:#333;
classDef decision fill:#fff3cd,stroke:#333;
style D fill:#fff3cd,stroke:#333,stroke-width:2px
Chapter 1. Agent Systems and Evaluation Fundamentals
Why Agent Evaluation Is Different
Harbor & Pine, a fictional outdoor-gear retailer, is preparing to launch Juniper, a support agent that can look up orders, issue refunds, and hand cases to a person. On a pre-launch set, it completes about 80% of the tasks. Two weeks after launch, however, the support lead discovers that the same refund request sometimes succeeds and sometimes receives a polite refusal. The score was calculated correctly; it simply did not describe how reliably Juniper handled a repeated request.
That distinction is easy to miss when a team grades one answer at a time. Because an agent can choose actions, call tools, and change state, a convincing response is only part of the evidence. This chapter follows Juniper from an individual run through repeated trials and an evaluation loop, showing how each view answers a different question about whether the system is ready to use.
After this chapter you will be able to:
- explain how evaluating an agent differs from evaluating a model or a chat application;
- name the main quality dimensions and say which ones a single pass rate hides;
- distinguish pass@k from pass^k and compute both;
- describe the eval-driven development loop;
- run a small evaluation in Python with two frameworks, Inspect AI and DeepEval;
- describe the agent loop, its tools, context, guardrails and possible failures;
- choose evaluation surfaces, identify the trace evidence they need, and find the chapters relevant to a particular system.
Illustrative material. Harbor & Pine, Juniper and the data in this chapter are fictional (see the case-study list in section 1.6). The failure stories are composites, not reports of real incidents.
1.1 From models to LLM apps to agents
Teams often use “LLM” to refer to three different kinds of system, even though a test appropriate for a model response may not capture the actions and consequences of an agent. The distinction is a useful starting point for deciding what an evaluation needs to observe:
- A model maps text—and sometimes images or audio—to an output. A model benchmark usually evaluates responses to fixed inputs against references or human judgments.
- An LLM application combines a model with a prompt, data, and often retrieval to perform a defined job, such as summarizing a ticket. The unit may still be one input and one output, but the result depends on the whole application configuration.
- An agent chooses what to do next. It can call tools, inspect results, and continue until it finishes or reaches a limit. A survey of agent evaluation organizes methods by what is evaluated, how, and in which setting [1]; that framing reflects the broader evidence an agent produces.
An agent run produces a trajectory: model calls, tool calls, observations, and a final outcome. It may also change the world by refunding an order or editing a file. Juniper could say that it issued a refund while the database shows none, for example, or it could refund the wrong order. To understand the run, we therefore need the user outcome, the steps taken, and the resulting state—not just the final message.
For product managers. When you hear “the model scored X”, ask: what was the unit of evaluation? If it was one prompt and one answer, the number tells you little about what the agent will do across a conversation that touches real systems.
1.2 What makes agents hard to evaluate
Once the evaluation boundary includes actions and state, a grader must account for more than the quality of a single response. Four properties make that broader task especially challenging.
Non-determinism. The same input can produce different tool calls or outcomes, as Juniper’s inconsistent refund handling illustrates. Because one run provides only one observation, repeated runs help reveal how much behavior varies.
Long horizons. An agent may take dozens of steps, and a mistake at step 3 can surface much later. Conversely, a correct final answer may follow an unsafe path, such as skipping an authorization check.
Side effects. Tools can change records, send messages, or modify files, and a reply that says “done” does not prove that the correct order changed. For that reason, refund tests need isolated fixtures as well as an inspection of the resulting state.
Compounding errors. If each of ten steps succeeds independently with probability 0.95, the probability that all ten succeed is \(0.95^{10}\approx0.60\). The calculation assumes independence, whereas real step errors may be related. It nevertheless illustrates why a strong per-step rate can coexist with a much weaker end-to-end rate.
τ-bench (the Tool-Agent-User Interaction Benchmark) brings several of these challenges together. It evaluates whether an agent can help simulated users, use domain-specific tools, and follow policy rules consistently. Its tasks combine simulated conversations, tools, and policy documents; the evaluator compares the final database state with a target state and, for some tasks, checks the agent’s answers. The benchmark reports pass^k, a repeated-run reliability measure. The paper reports that strong function-calling agents solved fewer than half of the tasks and had retail pass^8 below 25% [2]. Section 1.3 defines pass^k, and the lab computes it on a small synthetic set.
1.3 What “quality” means
The preceding failures suggest that “quality” is not one question. “Did the task succeed?” differs from “Will it succeed every time?”, “Did it stay within policy?”, and “How much did it cost?” Juniper’s team can use the following dimensions as a first scorecard, while keeping the answers separate enough to see their trade-offs.
| Dimension | Question it answers | Example measure (Juniper) |
|---|---|---|
| Success | Did the task get done correctly? | Right action on the right order |
| Reliability | Does it get done every time? | pass^k over repeated trials |
| Safety and policy | Did it stay within the rules? | No refund outside the return window |
| Cost | What did it spend? | Tokens and tool calls per resolved ticket |
| Latency | How long did the user wait? | Time to resolution |
| Experience | Was it clear and appropriate? | Rubric-scored tone and clarity |
The scorecard names the qualities that matter, but it does not yet say where to find evidence for them. A refund claim, a tool call, and a database change each expose a different part of the same run; the four evaluation surfaces in the diagram therefore give us a way to examine those parts together:
- Outcome: Did Juniper resolve the customer’s request? For a refund, check the intended order and result.
- Trajectory: Did it follow the required sequence, including lookup and authorization before the refund?
- Component: Were individual calls valid? Check the tool name, arguments, and response handling.
- Environment state: What changed in the system of record? Confirm that only the target order was modified.
These surfaces tell us what happened in a run, while repeated runs address another question: how often does the agent meet the requirement? Suppose a task has n trials and c successes:
- pass@k estimates the chance that at least one of k attempts succeeds. It fits settings where a verifier or person can select a successful result, such as code generation with tests [3].
- pass^k estimates the chance that all k attempts succeed. It fits autonomous use where each run matters, such as a support agent acting on customer accounts [2]. The standard unbiased estimator is \(\binom{c}{k}/\binom{n}{k}\).
If each attempt independently succeeds with probability 0.8, the chance of at least one success in eight attempts is \(1-(1-0.8)^8\approx1.00\), while the chance that all eight succeed is \(0.8^8\approx0.17\). The near-certain chance of finding one success is reassuring only when the operating process can actually select that success; it does not tell a support team that every customer interaction will work. Report the measure that matches the experience being evaluated, and state the independence assumption.
1.4 Anatomy of agent failures: four short stories
These are fictional composites for illustration.
- The right answer, wrong order. Juniper says, “I’ve refunded your order,” but its tool call names a different order ID. The response passes a text-only check; the state diff exposes the wrong target.
- The green test, broken behavior. Tallow Labs’ coding agent makes a test suite pass by deleting a failing test. The test result is green, but the code diff and test inventory show that the requirement was removed.
- The demo that does not repeat. Fernhill Analytics’ research agent answers correctly in one demo and fails one run in four. A single run hides that variation.
- The handoff with a time-zone error. A Kestrel Logistics agent passes “tomorrow” to another agent. The second interprets it in a different time zone, so the dispatch misses its window.
Although each story has a visible result, that result conceals a different problem. A state check exposes the wrong refund; a diff and invariant check reveal the removed test; repeated trials show the research agent’s variability; and an end-to-end handoff test can reveal the dispatch error. Part II develops these methods, but first we need to consider how to make them part of everyday development rather than a one-time audit.
1.5 Eval-driven development: the core loop
When Harbor & Pine fixes the wrong-order refund, the team needs more than a reassuring demonstration of the new version. It needs a case that will fail if the defect returns, alongside checks for the other behaviors the change might affect. Eval-driven development puts those expectations next to the implementation: define the task contract and checks before changing the agent, then keep both under version control as the product evolves.
flowchart TB
A[Define task & quality criteria] --> B[Collect & version cases]
B --> C[Run agent in harness]
C --> D[Grade with checks, judges, humans]
D --> E[Analyze by slice, surface, failure mode]
E --> F[Change agent, prompt, tools, data]
F --> G[Monitor production]
G --> B
style A fill:#e1f5e1,stroke:#333
style D fill:#fff3cd,stroke:#333
style G fill:#e3f2fd,stroke:#333
The diagram is a cycle rather than a linear checklist because new evidence can change both the agent and the evaluation. In practice, the team moves through the following activities:
- Define the user task, success state, constraints, and quality dimensions.
- Collect cases with expected outcomes and evidence for each label (Chapters 3 and 6).
- Run the agent in a sandbox. Repeat stochastic tasks and record the full trace.
- Grade with checks suited to the claim: deterministic rules for verifiable state, model judges for validated rubric questions, and people for ambiguous or high-impact cases (Chapters 5–7).
- Analyze failures by task slice and earliest observable point of failure.
- Change the agent or the test suite, then rerun the regression cases.
- Monitor production with approved signals and turn verified failures into reviewed test cases.
The first lab later in this chapter makes the first four steps concrete on a small synthetic support set. Moving the loop into production, however, requires additional care: failures must be verified and reviewed before they become new test cases, and monitoring must use approved signals.
1.6 Introducing the running case studies
Juniper’s refund problem is one thread through the book, but other products expose different evaluation questions. Four fictional companies recur so that we can follow those questions from task definition through measurement and operation.
| Company | Agent | What it does | Main themes |
|---|---|---|---|
| Harbor & Pine | Juniper | Customer support for an outdoor-gear retailer | Conversation, policy, tools, ground truth |
| Tallow Labs | Quill | Coding assistant for a developer-tools startup | Test-based grading, flakiness, side effects |
| Fernhill Analytics | Compass | Research and retrieval for a market-research firm | RAG, citations, long-horizon work |
| Kestrel Logistics | Relay | A team of dispatch agents for freight routing | Handoffs, orchestration, attribution |
All datasets are fictional. Juniper’s support_v0 set, for example, contains 20 invented support tasks, each with an expected action such as issue_refund(order=HP-1004); its results teach the mechanics rather than estimate the performance of a deployed support agent. We have named the surfaces an evaluation can inspect; next, we will look inside an agent to see how those surfaces produce evidence and where that evidence can be missing.
Anatomy of an Agent, for Evaluators
Harbor & Pine’s support lead reviews a complaint: “Juniper said the refund was done. Why did it refund the wrong order?” Although the transcript sounds correct, the trace reveals a crucial earlier step: Juniper passed the wrong order ID to the refund tool.
To investigate a failure like this, we need to know what the agent can observe, what it can change, and which of those events the trace records. This section builds that picture from the evaluator’s perspective, then revisits the four surfaces with those details in view. The second lab connects the concepts to a runnable agent, a tool call, and a state change in a synthetic environment; a simulator, not a real model, drives the agent.
1.7 The agent loop: plan, act, observe, reflect
Many agents follow a loop: they read instructions and context, choose an action, receive an observation, and then continue or stop. When that action is a tool call, the environment’s response becomes context for the next decision, so an error in one step can influence what follows. ReAct is one influential formulation of this interleaving of reasoning and action [4].
+--------------------------------------------+
| v
user -> [ model: plan / choose ] -> tool call -> [ environment ]
^ |
+------------- observation <-----------------+
|
+--> final answer (stop)
For an evaluator, each transition creates a different opportunity for failure. The following four moments are useful places to begin:
| Moment | What happens | Typical failure |
|---|---|---|
| Plan | The model decides what to do next | Skips a required check; pursues the wrong goal |
| Act | It emits a tool call with arguments | Wrong tool, wrong or invented arguments, malformed call |
| Observe | The tool result returns to the model | Result ignored, misread, or an error treated as success |
| Reflect and stop | It decides whether it is done | Stops too early, loops, claims success it did not achieve |
Frameworks use different names, and some do not expose a separate reflection step. The observable pattern remains: a decision leads to an action, the environment returns a result, and the agent makes another decision or stops. Capturing those transitions makes it possible to distinguish, for example, a bad tool argument from a correct call whose result the agent later ignored.
For product managers. Each failure in the table is a different product risk. “Skips a check” is a policy risk. “Invented arguments” is a data-integrity risk. “Claims success it did not achieve” is a trust risk. When you review quality results, ask which of these the numbers cover.
1.8 Tools, MCP servers, and the environment
Tools let an agent read data or request an action; each has a name, description, and input schema. Juniper’s lookup_order(order_id) reads a record, whereas issue_refund(order_id) changes it, and that difference affects both test design and risk. A repeated read usually costs time, while a repeated refund may create a duplicate or irreversible effect. Tests should therefore use isolated state and verify the resulting transaction.
The environment includes the systems the tools can reach: databases, files, browsers, and external services. Its state records what actually happened—for example, which order was refunded or which files changed. As Section 1.11 shows, that state is a distinct source of evaluation evidence.
MCP (the Model Context Protocol) connects LLM applications to tools and data. Its specification describes hosts (the application), clients (connectors in the host), and servers (services that provide context or capabilities), communicating over JSON-RPC 2.0 [5]. A server may be maintained outside your team, and its tool descriptions can change independently of your application code. Those changes still affect the system under test, so record the server and tool versions and include their descriptions and behavior in the evaluation (Chapter 22).
With these boundaries in view, the wrong-order complaint becomes several testable questions: did Juniper select the right tool, where did its order ID come from, and did the authorization layer permit the call? Related cases can also check that it handles a lookup timeout without claiming success and does not call the refund tool before confirming eligibility.
1.9 Memory, retrieval, and context management
The tool is only one part of the story. Before Juniper selects an order ID or applies a policy, the model must have the relevant information available in its current context. Alongside the conversation, that context may be shaped by three mechanisms:
- Context management. Which parts of a long conversation or trace are kept, summarized or dropped as the run goes on.
- Retrieval. Documents or records fetched at query time, for example Harbor & Pine’s return policy.
- Memory. Information written during one session and read in a later one, such as a customer’s preferred contact method.
Each mechanism has a distinct failure mode: retrieval may omit the applicable policy, context compaction may drop an earlier constraint, and persistent memory may return an outdated preference. By recording the material context and memory/retrieval references supplied to the model, evaluators can distinguish those possibilities from a generation error. Chapter 24 develops the tests.
1.10 Guardrails, permissions, and human-in-the-loop
Even with the right information, the agent may attempt an action it should not take. The deployed product therefore includes controls around the model, and those controls affect both behavior and the result we measure.
- Guardrails check inputs and outputs: filters for personal data, topic limits, format validators.
- Permissions limit what a tool may do: a refund tool that rejects amounts above a limit, or a read-only database role.
- Human-in-the-loop (HITL) steps ask a person to approve or take over: escalation to a human agent, or approval before a high-value refund.
Measure the product with its controls enabled, because that is the system users encounter. If the team also needs to know whether the model would attempt a prohibited action, investigate only in an isolated sandbox where a blocked action cannot reach real systems. Record both the attempted action and the control’s response: a permission layer can prevent harm while masking model behavior that needs correction. The controls themselves need tests for false blocks, missed violations, and escalation rates; Chapters 25–27 return to those methods.
1.11 The four evaluation surfaces
The loop, tools, context, and controls all produce evidence, but they do not answer the same question. Section 1.3 introduced four evaluation surfaces; here we return to them with a clearer picture of what a run can expose.
| Surface | What you look at | Question | Example grader (Juniper) |
|---|---|---|---|
| Outcome | The final answer or artifact | Did it say or produce the right thing? | Final message matches the expected resolution |
| Trajectory | The sequence of steps and tool calls | Was the path acceptable? | The order was looked up before a refund was issued |
| Component | One step in isolation: a single tool call, retrieval, or judgment | Was this piece correct? | Each tool call used the customer’s order ID |
| Environment state | The world after the run | Did the world end up right? | Exactly the right order was refunded |
These surfaces can disagree: an outcome grader may see a reassuring message while a state grader finds that no refund occurred—or that the wrong order changed. Neither result should overwrite the other, because preserving both records lets the team investigate why the apparent outcome and the system of record differ.
Two practical rules help you choose checks:
- When the task changes state, verify the state. Use the system of record to establish what happened; check the response separately for whether it described the result accurately.
- Choose checks that answer the decision question. A state predicate may be enough to verify a refund. Add trajectory and component checks when you need to find why a run failed or whether it respected prerequisites (Chapter 5).
In the lab, the same 120 runs receive all four grades, making it possible to see which failure patterns each surface catches and where the graders disagree.
1.12 Observability primitives: traces, spans, events, artifacts
Those graders can work only if the necessary evidence was recorded. A final message without the underlying tool calls, for example, cannot explain how Juniper chose the wrong order. The basic observability units provide a vocabulary for collecting and navigating that evidence:
- A trace is the record of one run, from the user’s request to the final answer.
- A span is one timed step inside a trace: a model call, a tool call, a retrieval. Spans nest and carry attributes such as the tool name, its arguments, its result and its duration.
- An event is a point-in-time record attached to a span: a user message, a model reply, an error.
- An artifact is something the run produced or consumed: a file, a screenshot, a database snapshot.
OpenTelemetry maintains semantic conventions for generative-AI telemetry, including spans, events, and metrics for model and agent activity [6]. These conventions evolve, so check the current specification before standardizing attribute names. Shared names make it easier for graders, dashboards, and monitors to interpret the same trace (Chapter 16).
For each run, capture the task ID and system versions; model and tool calls with inputs, outputs, and errors; timing and token counts; the final response; and a state snapshot or diff. Privacy and retention controls apply to that content as well. Together, these records support the four surfaces and, provided the retained evidence remains sufficient, can let the team rerun improved graders against old traces.
1.13 A map of system types
“Agent” covers systems with different capabilities and risks. Juniper illustrates a conversational agent that can change state, but a coding assistant or a research agent will need additional checks. The table offers starting points; many products combine several rows.
| If you are building… | The core risk | Start with |
|---|---|---|
| A chatbot with a conversational flow | Losing state, drifting from policy over turns | Chapter 25 |
| A RAG system over documents | Retrieval misses; answers not grounded in sources | Chapter 24 |
| A tool-using assistant that calls APIs | Wrong tool or arguments, unsafe write actions | Chapters 5 and 22 |
| A coding or computer-use agent | Flaky environments, side effects, partial credit | Chapter 22 |
| An autonomous, long-horizon agent | Goal drift, runaway loops, irreversible actions | Chapter 26 |
| A multi-agent system | Handoff loss, orchestration errors | Chapter 26 |
| A system with images, audio or video | Modality-specific quality and safety | Chapter 23 |
All of these systems need the measurement and evaluation foundations in Chapters 2–7, along with safety coverage from Chapter 27. If the product spans several rows, start by identifying the outcome, trajectory, component, and state evidence it can expose; you can then follow the capability chapters that match its tools and user workflow.
Chapter summary
The opening complaint and the evaluation loop lead to the same conclusion: a credible assessment needs evidence about both what the agent accomplished and how consistently it can do so. The main principles are:
- Evaluate an agent’s user outcome, execution path, component behavior, and resulting environment state.
- Repeat stochastic tasks and report the task and run counts; a single run cannot describe reliability.
- Track capability, reliability, safety, cost, latency, and user experience as separate dimensions.
- Use pass@k when a successful attempt can be selected; use pass^k when each autonomous run must succeed.
- Keep the task contract and regression cases alongside the implementation, then feed verified production failures back into the suite.
Those principles depend on the agent’s architecture, which determines what evidence is available and which controls need their own tests:
- Agents run a loop of plan, act, observe and stop. Each step has its own failure modes.
- Tools split into read tools and write tools. Write tools change the environment, which makes state the ground truth for what happened.
- MCP moves some of the system, such as tool descriptions, outside your codebase but not outside your evaluation.
- Failures that look like model errors may come from retrieval, memory, context management or tool outputs. Record what the model was given.
- Guardrails, permissions and human handoff shape the behavior you measure. Evaluate the deployed configuration with controls enabled; investigate behavior without them only in an isolated sandbox.
- The four evaluation surfaces can disagree, and those disagreements help identify what a single grade misses.
- Record traces with enough detail to re-grade runs later.
For product managers. Before launch, ask how many times each task was run, which reliability measure matches real use, and which quality dimensions remain unmeasured. Ask, too, which tools can change state and how the team checks the system of record; which surfaces the evaluation grades; whether traces contain tool arguments and an environment snapshot; which controls are enabled and what happens when they are off; and who will turn a verified production failure into a regression case.
Hands-on labs (Python)
Lab 1: Repeated trials with Juniper
The runnable lab is code/ch01/lab_juniper.py; install the companion package once with pip install -e code. Its mock LLM returns the expected action with configured probabilities of 0.95, 0.80, and 0.55 for easy, medium, and hard tasks. A fixed seed makes the simulated sequence reproducible, but the rates are teaching inputs, not estimates of a real model. A provider adapter can implement the same complete(messages) -> str interface.
The excerpts below follow the runnable lab’s setup. First, load the synthetic cases and inspect one task contract:
from bookkit.data import load_support_tasks
tasks = load_support_tasks("v0")
print(f"{len(tasks)} tasks")
print(tasks[2])20 tasks
SupportTask(id='S03', customer_message='Can I return the headlamp from HP-1003? It was delivered 45 days ago.', policy_area='returns', expected_action='deny_request(order=HP-1003)', common_mistake='issue_refund(order=HP-1003)', difficulty='medium')
The expected outcome is denial because the return window has passed. Even so, running that same task eight times shows how the simulator can produce different actions for a fixed request:
trials = [agent.act(task.customer_message) for _ in range(8)]
for i, action in enumerate(trials, start=1):
verdict = "pass" if action == task.expected_action else "FAIL"
print(f"trial {i}: {action:<30} {verdict}")trial 1: issue_refund(order=HP-1003) FAIL
trial 2: deny_request(order=HP-1003) pass
trial 3: deny_request(order=HP-1003) pass
trial 4: deny_request(order=HP-1003) pass
trial 5: issue_refund(order=HP-1003) FAIL
trial 6: issue_refund(order=HP-1003) FAIL
trial 7: deny_request(order=HP-1003) pass
trial 8: deny_request(order=HP-1003) pass
The eight trials produced both correct denials and incorrect refunds. That variation raises a broader question: does it occur only for this task, or does the evaluation set as a whole show a gap between occasional and consistent success? Repeat each of the 20 tasks eight times and summarize the results for several values of \(k\):
from bookkit.stats import summarize
results = {t.id: [agent.act(t.customer_message) == t.expected_action
for _ in range(8)] for t in tasks}
for name, value in summarize(results, ks=[1, 4, 8]).items():
print(f"{name:<8} {value:.2f}")pass@1 0.79
pass^1 0.79
pass@4 0.99
pass^4 0.47
pass@8 1.00
pass^8 0.30
Across the 20 tasks and their repeated runs, mean per-attempt success is about 79%, while 30% of tasks pass on all eight observed attempts. Because the sample is small and synthetic, those numbers do not estimate deployed performance. They do, however, show why average success and repeated-run reliability answer different questions, and why \(k\) should match the real operating condition.
Inspect AI. The same experiment can run as an [7] task. A dataset supplies samples, a solver runs the agent, a scorer records outcomes, and epochs repeat each case; reducers then summarize the runs:
@inspect_task
def juniper_support():
return Task(
dataset=MemoryDataset([Sample(id=t.id, input=t.customer_message,
target=t.expected_action) for t in tasks]),
solver=[system_message(SYSTEM_PROMPT), generate()],
scorer=action_match(),
epochs=Epochs(8, ["mean", "pass_at_8", "pass_k_8"]),
)
[log] = eval(juniper_support(), model=model, display="none")
for score in log.results.scores:
print(score.name, {k: round(m.value, 3) for k, m in score.metrics.items()})action_match {'accuracy': 0.787, 'stderr': 0.045}
action_match {'accuracy': 1.0, 'stderr': 0.0}
action_match {'accuracy': 0.3, 'stderr': 0.105}
The three rows report mean success (pass@1), pass@8, and pass^8, agreeing with the direct calculation above. The pass^8 standard error is 0.105 across only 20 tasks, a reminder that the estimate itself is uncertain. Chapter 2 explains how to report uncertainty with the task structure in view.
DeepEval. The same action check can also be expressed as a custom metric in [8]. Unlike the repeated-trial example above, this one runs a single trial per task:
cases = [LLMTestCase(input=t.customer_message,
actual_output=agent.act(t.customer_message),
expected_output=t.expected_action, name=t.id)
for t in tasks]
result = evaluate(cases, metrics=[ActionMatch()],
async_config=AsyncConfig(run_async=False))
print(f"DeepEval: {sum(r.success for r in result.test_results)}/{len(cases)} passed")DeepEval: 15/20 passed on one trial
The single-run score is 15/20. Although the repeated-run mean of 0.79 would correspond to about 16 successes in 20 cases, a particular set of trials need not equal that average. The difference illustrates why one run provides only a limited view of variable behavior.
Choosing a framework. Inspect AI provides epochs, reducers, sandboxes, and a log viewer, making it useful for repeated agent runs. DeepEval offers test cases, metrics, and a pytest-style workflow. The choice depends on the harness, reporting needs, and how evaluation will run in CI; the book uses each for examples it supports well.
Lab 2: The four evaluation surfaces
The first lab measured whether an expected action appeared across repeated trials. This second lab asks what the agent actually did along the way and what changed in its environment.
The runnable lab is code/ch02/lab_four_surfaces.py. It contains an agent loop, two tools, and a trace recorder, all operating in a synthetic environment. SimulatedSupportLLM supplies model behavior by emitting JSON tool calls and injecting four configured errors: skipping the lookup, targeting the wrong order, refunding an ineligible order, or claiming a refund that did not occur. The error rates are synthetic teaching inputs. To use a real model, implement complete(messages) -> str and return the same JSON format.
The loop calls the model, executes the requested tool against the test environment, adds the result to the next model input, and records each step as a span:
def run_agent(llm, env, task_id, message, max_steps=6) -> Trace:
trace = Trace(task_id)
messages = [{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": message}]
for _ in range(max_steps):
reply = llm.complete(messages)
trace.spans.append(Span("llm", "complete", len(messages), reply, ...))
action = json.loads(reply)
if "final" in action:
trace.final = action["final"]
return trace
result = env.call(action["tool"], action["args"])
trace.spans.append(Span("tool", action["tool"], action["args"], result, ...))
messages += [{"role": "assistant", "content": reply},
{"role": "user", "content": "OBSERVATION: " + json.dumps(result)}]
trace.final = "(stopped: step limit)"
return traceThe max_steps limit bounds the run if the agent loops. With that protection in place, execute one scenario and inspect both its trace and the resulting refund state:
scenario = SCENARIOS[0]
env = SupportEnv()
trace = run_agent(SimulatedSupportLLM(seed=3), env, scenario.id, scenario.customer_message)
for i, s in enumerate(trace.spans):
if s.kind == "tool":
print(f"{i}: tool {s.name}({s.input}) -> {s.output}")
print("final:", trace.final)
print("world state, refunds:", env.refunds)1: tool lookup_order({'order_id': 'HP-1004'}) -> {'order_id': 'HP-1004', 'item': 'tent', 'delivered_days_ago': 10, 'refund_eligible': True}
3: tool issue_refund({'order_id': 'HP-1004'}) -> {'status': 'refunded', 'order_id': 'HP-1004'}
final: Your refund for order HP-1004 has been issued.
world state, refunds: ['HP-1004']
This run refunded the expected order, and its trace also shows the lookup before the refund. Next, grade the same scenario, trace, and environment on each evaluation surface:
def grade_outcome(s, trace, env):
claims_refund = "refund for order" in trace.final and "can't" not in trace.final
return claims_refund == s.should_refund
def grade_state(s, trace, env):
return env.refunds == ([s.order_id] if s.should_refund else [])
def grade_trajectory(s, trace, env):
names = [c.name for c in trace.tool_calls]
return "issue_refund" not in names or ("lookup_order" in names and
names.index("lookup_order") < names.index("issue_refund"))
def grade_component(s, trace, env):
return all(c.input.get("order_id") == s.order_id for c in trace.tool_calls)
print(grade(scenario, trace, env)){'outcome': True, 'trajectory': True, 'component': True, 'state': True}
One successful trace cannot reveal how often the surfaces disagree, so the next step is to run three scenarios 40 times each—two expect a refund and one expects a denial—and apply all four graders to every run:
llm = SimulatedSupportLLM(seed=11)
runs = []
for s in SCENARIOS:
for _ in range(40):
env = SupportEnv()
trace = run_agent(llm, env, s.id, s.customer_message)
runs.append((s, grade(s, trace, env)))
for name in GRADERS:
print(f"{name:<12}{sum(g[name] for _, g in runs) / len(runs):>10.2f}")
print(f"{'all four':<12}{sum(all(g.values()) for _, g in runs) / len(runs):>10.2f}")outcome 0.88
trajectory 0.86
component 0.92
state 0.84
all four 0.70
The outcome grader passes 88% of runs and the state grader passes 84%, but only 70% pass all four surfaces together. Although the aggregate suggests a gap, understanding it requires a closer look at cases where the answer sounds successful while the state is wrong:
looks_fine = [(s, g) for s, g in runs if g["outcome"] and not g["state"]]
print(f"{len(looks_fine)} of {len(runs)} runs read well but left the world wrong")
for s, g in looks_fine[:3]:
print(" ", s.id, g)10 of 120 runs read well but left the world wrong
A {'outcome': True, 'trajectory': True, 'component': False, 'state': False}
A {'outcome': True, 'trajectory': True, 'component': False, 'state': False}
A {'outcome': True, 'trajectory': True, 'component': False, 'state': False}
These runs reproduce the opening failure: Juniper claims success but targets another order. The component and state checks catch it, whereas the outcome-only evaluation counts it as a pass. This does not make the outcome grader useless; it shows why its answer needs to be interpreted alongside the other evidence.
Inspect AI. A custom solver can run this loop, and a scorer can return one named value per surface. The solver stores the grades in sample metadata. Inspect still receives a model argument for its task interface; the agent itself calls the local LLMClient simulator:
@solver
def run_support_agent():
async def solve(state: TaskState, generate):
s = SCEN[state.sample_id]
env = SupportEnv()
trace = run_agent(sim, env, s.id, s.customer_message)
state.metadata["graded"] = grade(s, trace, env)
state.output.completion = trace.final
return state
return solve
@scorer(metrics={k: [accuracy()] for k in GRADERS})
def four_surfaces():
async def score(state: TaskState, target: Target) -> Score:
return Score(value={k: float(v) for k, v in state.metadata["graded"].items()})
return score
[log] = eval(support_surfaces(), model="mockllm/model", display="none")
for score in log.results.scores:
print(f"{score.name:<11}", {k: round(m.value, 2) for k, m in score.metrics.items()})outcome {'accuracy': 0.88}
trajectory {'accuracy': 0.86}
component {'accuracy': 0.92}
state {'accuracy': 0.84}
The seeded simulator produces the same aggregates as the direct loop.
DeepEval. A test case can carry tool calls in tools_called, allowing the trajectory check to use the recorded sequence. This deterministic metric needs no judge model or API key:
cases.append(LLMTestCase(
input=s.customer_message, actual_output=trace.final, name=s.id,
tools_called=[ToolCall(name=c.name, input_parameters=c.input)
for c in trace.tool_calls]))
result = evaluate(cases, metrics=[CheckBeforeRefund()], ...)
print(f"DeepEval trajectory check: {sum(r.success for r in result.test_results)}/{len(cases)} passed")DeepEval trajectory check: 26/30 passed
The examples emphasize different parts of the workflow: Inspect is useful for repeated epochs and multiple scores per run, while DeepEval’s test-case representation makes tool-call checks straightforward, including when adapting the pattern to traces exported from another system.
Exercises
The first group returns to repeated-trial reliability in Lab 1; the second asks you to extend the traces and graders in Lab 2.
Why Agent Evaluation Is Different
- (Conceptual) A support agent solves a task 90% of the time. Compute pass@3 and pass^3 by hand. Which would you put on a launch dashboard, and why?
- (Conceptual) Section 1.2 gives 0.95^10 ≈ 0.60. What per-step success rate gives 90% end-to-end success over ten steps?
- (Hands-on) Change the seed in the lab. How much do pass@1 and pass^8 move? What does that say about trusting one run?
- (Hands-on) Add a second
ActionMatch-style metric that checks only the action name, ignoring the order ID. When do the two metrics disagree, and which failure story in section 1.4 does that resemble? - (Hands-on) Increase the trials from 8 to 16. Which metrics change and which do not?
- (Discussion) Pick a feature in your own product. Which quality dimensions from section 1.3 matter most, and how would you measure each?
Anatomy of an Agent, for Evaluators
- (Conceptual) For each of the four moments in section 1.7, write one failure that a final-answer grader would miss.
- (Conceptual) Juniper gains a third tool,
send_email(to, body). Is it a read tool or a write tool? Which surface would you use to check it, and what would you need to record? - (Hands-on) In the lab, set
wrong_order=0.0and rerun. Which surfaces change and which do not? Explain why. - (Hands-on) Add a fifth grader,
grade_efficiency, that fails a run with more than three tool calls. Does it correlate with any other surface? - (Hands-on) Write a component grader that checks the content of the lookup result against the final message (for example, that the final message names the right order). What does it catch that the outcome grader does not?
- (Discussion) Pick a product you work on. Fill in section 1.13’s table for it. Which chapter would you read second, and why?
Further reading
- The τ-bench paper introduces pass^k and a simulated-user evaluation setup [2].
- A survey of LLM-agent evaluation organizes objectives, process and benchmarks [1].
- The origin of pass@k, in the context of code generation [3].
- Inspect documentation [7] and DeepEval repository [8].
- The ReAct paper, for the reasoning-and-acting loop most agents descend from [4].
- The MCP specification, to see how tools and context are exposed to models [5].
- The OpenTelemetry GenAI semantic conventions, for trace vocabulary [6].
- τ-bench compares end database state with a goal state, an example of the state surface [2].
- A survey of agent evaluation, for how benchmarks are organized [1].