08D.2 Hands-On: Two-Agent vs Single-Agent, Built, Traced and Evaluated
In 08D.1 you learned when a second agent is justified and how to hand work from one agent to the next. Here you build the thing. You will write a small refund-eligibility desk twice, once as a single agent and once as two agents (a researcher and a writer), record a trace of every run with a minimal span recorder you write yourself, read those traces to see who did what, and then run the question that matters: is the two-agent version actually better? You will answer it with the three Module 10A agent metrics: task success rate, tool-call correctness and cost per successful task. Everything runs offline, with scripted models and fake tools, so every number in this lesson reproduces exactly on your machine.
What you'll learn
- How to build a two-agent system (an orchestrator in plain code, a researcher with tools, a writer without) and a single-agent version of the same job, sharing one set of fake tools
- How to write a minimal span and trace recorder in plain Python and what to record so a multi-agent trace answers "who did what"
- How to read a trace: spans, nesting, per-agent totals, and the trap of a trace that hides the handoff
- How to compute task success rate, tool-call correctness and cost per successful task with plain Python, and report them with an interval
- Why an evaluation result depends on the script, and how a what-if run shows which assumption drives the verdict
- Where a real OpenAI or Anthropic client plugs into the same project (illustrative)
What you don't need
- API keys. The models are scripted functions and the tools are in-memory fakes. No network, no Docker, no services.
- DeepEval or Inspect. The project never imports them. They appear only as links in Part 9.
- Earlier multi-agent theory beyond 08D.1. Skim 08D.3 if you want the wider map.
Setup
Python 3.11 or newer, standard library only. As of 1 December 2026 there is nothing to install. The provider client sketch in Part 8 would need openai and anthropic (package names only) and keys, but you can skip it.
mkdir two-vs-one && cd two-vs-one
python3 --version # 3.11 or newerSave the files from this lesson in that folder under the names in their first comment: world.py, tracing.py, models.py, agents.py, evaluate.py, read_trace.py, whatif.py. Run every program from that folder with python3 <file>.
What you must be able to do after this lesson#
- Build a single-agent and a two-agent version of the same job on shared tools and a shared task set
- Record a nested span trace in plain Python and mark agent boundaries with an agent span
- Read a trace to say which agent did what, and find a bug that sits in a handoff between two spans
- Compute task success rate (with an interval), tool-call correctness and cost per successful task by hand
- Decide between the two versions against a pass rule written before the run
- Change one scripted assumption and re-run the comparison to see what drives the verdict
Why this matters for an AI engineer#
Teams rarely get to choose an architecture from first principles. They have a working single agent and someone proposes splitting it. The useful skill is not the splitting, it is the comparison: same tasks, same tools, same metrics, a pass rule decided in advance, and a trace you can read when a number moves. That skill transfers to every change you will make to an agent, including model upgrades, prompt rewrites and new tools.
| You'll hear... | You'll understand it after... |
|---|---|
| "Did the split help?" | Part 9: Evaluate it |
| "Open the trace and see which agent did that." | Part 7: Reading a trace |
| "Cost per successful task, not cost per run." | 9.2 The three numbers |
| "The numbers are too close to call." | 9.3 Reading a tie |
| "The result changes if we change one assumption." | 9.4 What would change the verdict |
| "How do we plug in a real model?" | Part 8 |
Part 1: What we are building#
The job. A support desk question: "Can order X be refunded?" The answer must be one of three strings: ELIGIBLE <amount>, NOT_ELIGIBLE <reason> or NOT_FOUND. The rule (from a fake policy) is: the order must exist, be delivered, not be final sale, and be within 30 days of delivery.
Two tools (both fake, in world.py): order_lookup(order_id) and policy_lookup(topic).
Two versions of the system.
| Single agent | Two agents | |
|---|---|---|
| Agents | One agent with both tools, deciding the answer | A researcher (both tools, reports facts as JSON, does not decide) and a writer (no tools, applies the rule to the findings) |
| Control | The agent's own loop | An orchestrator in plain code: researcher, check the handoff, writer |
| Pattern | None | Orchestrator with workers (08D.1, 3.1) |
Seven tasks, one per order: an ordinary eligible one, one past the window, a final-sale item, an order not yet delivered, one at 29 days, one at exactly 30 days (the boundary), and an order that does not exist.
Three metrics, defined in 10A.7 and computed in Part 6: task success rate, tool-call correctness and cost per successful task.
Part 2: The fake world#
world.py holds the data, the two tools, and decide, the ground-truth rule. The evaluation uses decide to know what the right answer is. The agents' scripts use it too, so a "correct" run and the grader can never disagree about the rule itself.
# world.py: fake data and fake tools for a refund-eligibility desk (no network, no model)
ORDERS = {
"A17": {"status": "delivered", "total": 49.00, "days_since_delivery": 10, "final_sale": False},
"B22": {"status": "delivered", "total": 120.00, "days_since_delivery": 45, "final_sale": False},
"C31": {"status": "delivered", "total": 15.00, "days_since_delivery": 5, "final_sale": True},
"D40": {"status": "shipped", "total": 80.00, "days_since_delivery": None, "final_sale": False},
"E55": {"status": "delivered", "total": 200.00, "days_since_delivery": 29, "final_sale": False},
"F60": {"status": "delivered", "total": 75.50, "days_since_delivery": 30, "final_sale": False},
}
POLICY = {"refunds": {"window_days": 30, "final_sale_refundable": False, "needs_delivery": True}}
def order_lookup(order_id: str) -> dict:
return ORDERS.get(order_id, {"error": "not_found"})
def policy_lookup(topic: str) -> dict:
return POLICY[topic]
TOOLS = {"order_lookup": order_lookup, "policy_lookup": policy_lookup}
def decide(order: dict, policy: dict) -> str:
"""The ground-truth rule. The answer format is: ELIGIBLE <amount> | NOT_ELIGIBLE <reason> | NOT_FOUND."""
if "error" in order:
return "NOT_FOUND"
if policy["needs_delivery"] and order["status"] != "delivered":
return "NOT_ELIGIBLE not_delivered"
if order["final_sale"] and not policy["final_sale_refundable"]:
return "NOT_ELIGIBLE final_sale"
if order["days_since_delivery"] > policy["window_days"]:
return "NOT_ELIGIBLE window"
return f"ELIGIBLE {order['total']:.2f}"Two details matter later. D40 is shipped, so it has no delivery day. F60 sits exactly on the 30-day boundary, which tests <= against <.
Part 3: A minimal span recorder#
03.12, Part 2 builds a one-JSON-line-per-span recorder with a real clock for a single LLM app. This part builds a smaller recorder with an agent span kind, a virtual clock and a tree printer, which is what a multi-agent trace needs.
tracing.py is about 60 lines. It gives you Tracer.span(kind, name, **attrs) as a context manager. Spans nest automatically through a stack. The clock is virtual: code calls tracer.advance(ms) to add simulated latency, so timings are identical on every run. A real tracer reads the wall clock instead, and that is the only thing you would change.
# tracing.py: a minimal span recorder in plain Python (virtual clock, so output is reproducible)
import json
from contextlib import contextmanager
from dataclasses import dataclass, field
@dataclass
class Span:
span_id: int
parent_id: int | None
kind: str # "run" | "agent" | "llm" | "tool"
name: str
start_ms: int
end_ms: int = 0
attrs: dict = field(default_factory=dict)
@property
def duration_ms(self) -> int:
return self.end_ms - self.start_ms
class Tracer:
def __init__(self):
self.spans: list[Span] = []
self._stack: list[Span] = []
self.now_ms = 0 # virtual clock; a real tracer reads the wall clock
def advance(self, ms: int):
self.now_ms += ms
@contextmanager
def span(self, kind: str, name: str, **attrs):
parent = self._stack[-1].span_id if self._stack else None
sp = Span(len(self.spans) + 1, parent, kind, name, self.now_ms, attrs=dict(attrs))
self.spans.append(sp)
self._stack.append(sp)
try:
yield sp
finally:
sp.end_ms = self.now_ms
self._stack.pop()
def to_jsonl(self) -> str:
return "\n".join(json.dumps(sp.__dict__, sort_keys=True) for sp in self.spans)
def print_tree(self):
depth = {}
for sp in self.spans:
d = 0 if sp.parent_id is None else depth[sp.parent_id] + 1
depth[sp.span_id] = d
detail = ""
if sp.kind == "llm":
detail = f" in={sp.attrs['tokens_in']} out={sp.attrs['tokens_out']}"
elif sp.kind == "tool":
detail = f" args={json.dumps(sp.attrs['args'])}"
elif sp.kind == "agent":
detail = f" output={sp.attrs.get('output', '')[:95]!r}"
print(f"{' ' * d}{sp.kind}:{sp.name} [{sp.duration_ms} ms]{detail}")Four span kinds are enough: run (the whole job), agent (one agent's loop), llm (one model call, with tokens_in and tokens_out) and tool (one tool call, with its args). To mark a span as an agent boundary in a trace you simply give it kind="agent". That one convention is what makes "who did what" answerable later.
Part 4: Scripted models, with their flaws written down#
models.py is where honesty lives. A ScriptedModel picks its tool calls from a plan and writes its answer by a fixed rule. The FLAWS table at the top lists every deliberate mistake, so a reader can see exactly what the results depend on.
# models.py: scripted stand-ins for model calls. They are code, not intelligence.
# Each one picks tool calls from a fixed plan and writes its answer by a fixed rule,
# so every run is identical. The flaws are written down on purpose, in FLAWS below.
import json
import re
from world import ORDERS, decide
PRICE_IN, PRICE_OUT = 2.0, 10.0 # toy cost units per 1,000 tokens: NOT any provider's price
def count_tokens(obj) -> int:
return len(json.dumps(obj).split()) # a stand-in for a tokenizer; the method matters, not the number
# The behaviour we script. Change these and the evaluation changes: that is the point of Part 7.
FLAWS = {
# single agent: has all the tools, one long prompt. It sometimes "remembers" the policy instead of looking it up.
"single_skips_policy": {"A17", "C31"},
# single agent: calls the policy tool even when the order does not exist (a wasted call)
"single_overcalls": {"Z99"},
# researcher: when the order is not delivered it leaves out the delivery fields, and the writer fills the gap
"researcher_drops_status": {"D40"},
}
def order_id_of(text: str) -> str:
return re.search(r"\b[A-Z]\d{2}\b", text).group(0)
class ScriptedModel:
"""plan: tool calls to make in order. finish: function(results) -> final text."""
def __init__(self, plan, finish):
self.plan, self.finish = list(plan), finish
def __call__(self, messages):
results = [m["content"] for m in messages if m["role"] == "tool"]
step = len(results)
if step < len(self.plan):
name, args = self.plan[step]
return {"tool": name, "args": args}
return {"text": self.finish(results)}
def single_agent_model(task_text: str) -> ScriptedModel:
oid = order_id_of(task_text)
plan = [("order_lookup", {"order_id": oid})]
# a sensible agent looks up the policy only for an order that exists; the overcall flaw does it anyway
wants_policy = oid in ORDERS or oid in FLAWS["single_overcalls"]
if wants_policy and oid not in FLAWS["single_skips_policy"]:
plan.append(("policy_lookup", {"topic": "refunds"}))
def finish(results):
order = results[0]
# when it skipped the policy it guesses from memory: a 30 day window, but no final-sale rule
policy = results[1] if len(results) > 1 else {
"window_days": 30, "final_sale_refundable": True, "needs_delivery": True}
return decide(order, policy)
return ScriptedModel(plan, finish)
def researcher_model(task_text: str) -> ScriptedModel:
oid = order_id_of(task_text)
# the researcher fetches the policy only for an order that exists, so its next step depends on the result
class Researcher(ScriptedModel):
def __call__(self, messages):
results = [m["content"] for m in messages if m["role"] == "tool"]
if not results:
return {"tool": "order_lookup", "args": {"order_id": oid}}
if "error" in results[0]:
return {"text": json.dumps({"order_id": oid, "found": False})}
if len(results) == 1:
return {"tool": "policy_lookup", "args": {"topic": "refunds"}}
order, policy = results
findings = {"order_id": oid, "found": True, "total": order["total"],
"final_sale": order["final_sale"], "policy": policy}
if oid not in FLAWS["researcher_drops_status"]:
findings["status"] = order["status"]
findings["days_since_delivery"] = order["days_since_delivery"]
return {"text": json.dumps(findings)}
return Researcher([], None)
def writer_model(handoff_text: str) -> ScriptedModel:
"""Reads the findings JSON from the handoff and applies the rule. It trusts what it is given."""
def finish(_results):
findings = json.loads(handoff_text.split("FINDINGS: ", 1)[1].split("\nANSWER FORMAT", 1)[0])
if not findings["found"]:
return "NOT_FOUND"
order = {"status": findings.get("status", "delivered"), # a missing field is assumed fine
"days_since_delivery": findings.get("days_since_delivery", 0),
"final_sale": findings["final_sale"], "total": findings["total"]}
return decide(order, findings["policy"])
return ScriptedModel([], finish)Read the FLAWS table slowly, because the whole lesson follows from it.
single_skips_policy = {A17, C31}: on those two orders the single agent "remembers" the policy instead of calling the policy tool. OnA17that is harmless to the answer (the remembered rule gives the right result) but it is a wrong process. OnC31the remembered rule lacks the final-sale exception, so the answer is wrong.single_overcalls = {Z99}: the single agent calls the policy tool even when the order does not exist (a sensible agent would not). The answer is right; the call was wasted.researcher_drops_status = {D40}: the researcher reports an unshipped order without itsstatusanddays_since_deliveryfields. The writer, trusting its input, fills the gap by assuming "delivered, 0 days". That is error propagation in thirty lines.
These are assumptions about model behaviour. Real models fail in less tidy ways. The point of writing them down is that you can change them (Part 9.4) and watch the verdict move.
Part 5: The two versions#
agents.py has the agent loop (with spans around every model call and tool call), the single-agent version, and the two-agent version.
# agents.py: the agent loop, the single-agent version and the two-agent version, all traced
import json
from models import PRICE_IN, PRICE_OUT, count_tokens, researcher_model, single_agent_model, writer_model
from world import TOOLS
def run_agent(tracer, name, model, system, user, tools=None, max_steps=6):
tools = tools or {}
messages = [{"role": "system", "content": system}, {"role": "user", "content": user}]
with tracer.span("agent", name, input=user) as agent_span:
for _ in range(max_steps):
tokens_in = count_tokens(messages)
with tracer.span("llm", f"{name}.model_call", tokens_in=tokens_in) as sp:
reply = model(messages)
sp.attrs["tokens_out"] = count_tokens(reply)
tracer.advance(100 + 5 * sp.attrs["tokens_out"]) # simulated latency
if "tool" in reply:
with tracer.span("tool", reply["tool"], args=reply["args"]):
result = tools[reply["tool"]](**reply["args"])
tracer.advance(20)
messages.append({"role": "assistant", "content": reply})
messages.append({"role": "tool", "content": result})
continue
agent_span.attrs["output"] = reply["text"] # without this the trace cannot show what was handed on
return reply["text"]
raise RuntimeError(f"{name} hit max_steps")
def single_agent(tracer, task_text):
with tracer.span("run", "single_agent"):
return run_agent(tracer, "agent", single_agent_model(task_text),
"You are a refunds agent. Use the tools. Reply ELIGIBLE <amount>, NOT_ELIGIBLE <reason> or NOT_FOUND.",
task_text, TOOLS)
FINDINGS_FORMAT = {"order_id": str, "found": bool} # minimum the writer needs; extra fields allowed
def two_agents(tracer, task_text):
"""Orchestrator (plain code) -> researcher (has the tools) -> writer (no tools)."""
with tracer.span("run", "two_agents"):
brief = f"TASK: {task_text}\nReturn the facts as JSON: order_id, found, total, final_sale, status, days_since_delivery, policy."
raw = run_agent(tracer, "researcher", researcher_model(task_text),
"You look facts up with tools and report them as JSON. You do not decide.",
brief, TOOLS)
findings = json.loads(raw) # the contract check
missing = [k for k in FINDINGS_FORMAT if k not in findings]
if missing:
raise ValueError(f"researcher broke the contract: missing {missing}")
handoff = f"TASK: write the final decision for: {task_text}\nFINDINGS: {raw}\nANSWER FORMAT: ELIGIBLE <amount> | NOT_ELIGIBLE <reason> | NOT_FOUND"
return run_agent(tracer, "writer", writer_model(handoff),
"You turn findings into the final decision. You have no tools.", handoff)
def cost_of(spans) -> float:
llm = [s for s in spans if s.kind == "llm"]
return sum(s.attrs["tokens_in"] / 1000 * PRICE_IN + s.attrs["tokens_out"] / 1000 * PRICE_OUT for s in llm)Three choices deserve a comment.
The handoff. two_agents sends the researcher a brief (the task plus the fields wanted), checks the reply against a minimal contract (order_id and found must exist), then sends the writer a second brief that contains the researcher's findings. The writer never sees the researcher's tool calls. That isolation is cheaper and safer, and it is exactly why the missing status field travels unnoticed.
The contract is deliberately minimal. It checks only order_id and found. A stricter contract (require status whenever found is true) would catch the D40 bug at the handoff. Exercise 3 asks you to add it. The lesson leaves the bug in so the trace in Part 7 has something to show.
What the agent span records. run_agent saves the agent's input and output on its span. Part 7 shows why you want that. Without it, the trace tells you that the writer answered, but not what the writer was given.
Part 6: Run both on the task set#
10A.7 defines the three metrics, and 10A.12, Part 6 runs a larger single-agent baseline against a multi-agent system with the evalkit harness. This part computes the same three metrics by hand on a small task set so you can see every number.
evaluate.py runs each version on all seven tasks, one trace per run, and computes the metrics from the spans and the answers. Everything is plain Python: counting, division, and a small interval function.
- Task success: the final answer string equals the expected answer from
decide. - Tool-call correctness: precision, recall and F1 of the calls the run made, against the reference set (
order_lookup, pluspolicy_lookupwhen the order exists). Calls are compared as(tool, arguments)pairs, the way 10A.7, 4.2 describes. - Cost: summed from the
llmspans' token counts and the toy prices inmodels.py. Cost per successful task is total cost over all runs divided by the number of successes (10A.7, 5.6).
# evaluate.py: run both versions on the task set and compute three metrics in plain Python
import sys
from collections import Counter
from agents import cost_of, single_agent, two_agents
from tracing import Tracer
from world import ORDERS, POLICY, decide, order_lookup
# (task id, question, order id). The expected answer comes from the rule, applied to the data.
TASKS = [(f"t{i}", f"Can order {oid} be refunded?", oid) for i, oid in enumerate(
["A17", "B22", "C31", "D40", "E55", "F60", "Z99"], start=1)]
def expected_answer(oid):
return decide(order_lookup(oid), POLICY["refunds"])
def expected_calls(oid):
calls = [("order_lookup", (("order_id", oid),))]
if oid in ORDERS:
calls.append(("policy_lookup", (("topic", "refunds"),)))
return Counter(calls)
def actual_calls(spans):
return Counter((s.name, tuple(sorted(s.attrs["args"].items()))) for s in spans if s.kind == "tool")
def tool_call_f1(expected: Counter, actual: Counter) -> float:
hit = sum((expected & actual).values())
if not actual or not expected:
return 0.0
p, r = hit / sum(actual.values()), hit / sum(expected.values())
return 0.0 if hit == 0 else 2 * p * r / (p + r)
def run_version(name, fn, verbose=True):
rows = []
for tid, question, oid in TASKS:
tracer = Tracer()
answer = fn(tracer, question)
ok = answer == expected_answer(oid)
f1 = tool_call_f1(expected_calls(oid), actual_calls(tracer.spans))
rows.append({"task": tid, "order": oid, "answer": answer, "ok": ok, "f1": f1,
"cost": cost_of(tracer.spans), "latency": tracer.now_ms, "tracer": tracer})
if verbose:
print(f" {name:12s} {tid} {oid} answer={answer!r:32} ok={ok!s:5} tool_f1={f1:.2f} "
f"cost={rows[-1]['cost']:.2f} latency={tracer.now_ms}ms")
return rows
def wilson(successes, n, z=1.96):
"""95% interval for a success rate (10A.7 Part 5.2 explains why you want one)."""
p = successes / n
centre = (p + z * z / (2 * n)) / (1 + z * z / n)
half = z * ((p * (1 - p) / n + z * z / (4 * n * n)) ** 0.5) / (1 + z * z / n)
return centre - half, centre + half
def summarize(rows):
n = len(rows)
successes = sum(r["ok"] for r in rows)
total_cost = sum(r["cost"] for r in rows)
return {"task_success": successes / n, "tool_call_f1": sum(r["f1"] for r in rows) / n,
"total_cost": total_cost,
"cost_per_success": total_cost / successes if successes else float("inf"),
"successes": successes, "n": n}
if __name__ == "__main__":
results = {}
for name, fn in (("single", single_agent), ("two-agent", two_agents)):
print(f"\n{name}")
results[name] = run_version(name, fn)
print("\n" + f"{'metric':22s}{'single':>12s}{'two-agent':>12s}")
s, t = summarize(results["single"]), summarize(results["two-agent"])
for key, label in (("successes", "tasks passed"), ("task_success", "task success rate"),
("tool_call_f1", "tool-call F1 (mean)"), ("total_cost", "total cost (toy units)"),
("cost_per_success", "cost per successful task")):
fmt = (lambda v: f"{v:.2f}") if "cost" in key else (lambda v: f"{v:.2f}" if isinstance(v, float) else str(v))
print(f"{label:22s}{fmt(s[key]):>12s}{fmt(t[key]):>12s}")
for name, m in (("single", s), ("two-agent", t)):
lo, hi = wilson(m["successes"], m["n"])
print(f"{name} success rate 95% interval: {lo:.2f} to {hi:.2f} (n={m['n']})")Run it:
python3 evaluate.pyOutput (real, run on 1 December 2026; scripted models, toy cost units, not any provider's price):
single
single t1 A17 answer='ELIGIBLE 49.00' ok=True tool_f1=0.67 cost=0.22 latency=260ms
single t2 B22 answer='NOT_ELIGIBLE window' ok=True tool_f1=1.00 cost=0.40 latency=405ms
single t3 C31 answer='ELIGIBLE 15.00' ok=False tool_f1=0.67 cost=0.22 latency=260ms
single t4 D40 answer='NOT_ELIGIBLE not_delivered' ok=True tool_f1=1.00 cost=0.40 latency=405ms
single t5 E55 answer='ELIGIBLE 200.00' ok=True tool_f1=1.00 cost=0.40 latency=405ms
single t6 F60 answer='ELIGIBLE 75.50' ok=True tool_f1=1.00 cost=0.40 latency=405ms
single t7 Z99 answer='NOT_FOUND' ok=True tool_f1=0.67 cost=0.36 latency=400ms
two-agent
two-agent t1 A17 answer='ELIGIBLE 49.00' ok=True tool_f1=1.00 cost=0.78 latency=605ms
two-agent t2 B22 answer='NOT_ELIGIBLE window' ok=True tool_f1=1.00 cost=0.78 latency=605ms
two-agent t3 C31 answer='NOT_ELIGIBLE final_sale' ok=True tool_f1=1.00 cost=0.78 latency=605ms
two-agent t4 D40 answer='ELIGIBLE 80.00' ok=False tool_f1=1.00 cost=0.73 latency=585ms
two-agent t5 E55 answer='ELIGIBLE 200.00' ok=True tool_f1=1.00 cost=0.78 latency=605ms
two-agent t6 F60 answer='ELIGIBLE 75.50' ok=True tool_f1=1.00 cost=0.78 latency=605ms
two-agent t7 Z99 answer='NOT_FOUND' ok=True tool_f1=1.00 cost=0.38 latency=380ms
metric single two-agent
tasks passed 6 6
task success rate 0.86 0.86
tool-call F1 (mean) 0.86 1.00
total cost (toy units) 2.39 5.00
cost per successful task 0.40 0.83
single success rate 95% interval: 0.49 to 0.97 (n=7)
two-agent success rate 95% interval: 0.49 to 0.97 (n=7)The per-task rows already show the shape. The single agent fails t3 (it skipped the policy and missed the final-sale rule) and takes a lower tool-call F1 on three tasks. The two-agent version fails t4 (the missing status field), has perfect tool-call F1, and costs about twice as much per run. Part 9 reads these numbers properly.
Part 7: Reading a trace to see who did what#
A trace answers three questions, in this order.
- What happened, in order? Read the tree top to bottom.
- Who did it? Group the model calls and tool calls by the agent span that contains them.
- Where did the run go wrong? Compare what happened with what should have happened, then look at the handoff between the last good step and the first bad one.
read_trace.py prints the trace tree for the two failing tasks (t3 for the single agent, t4 for the two-agent version), a per-agent table, and a comparison with the expected tool calls.
# read_trace.py: read the traces of the two failing tasks and answer "who did what?"
from collections import defaultdict
from agents import single_agent, two_agents
from evaluate import TASKS, actual_calls, expected_calls, expected_answer
from tracing import Tracer
def who_did_what(spans):
"""Walk up from every llm/tool span to its agent span, then total per agent."""
by_id = {s.span_id: s for s in spans}
table = defaultdict(lambda: {"llm_calls": 0, "tokens_in": 0, "tokens_out": 0, "tools": []})
for s in spans:
if s.kind not in ("llm", "tool"):
continue
p = by_id[s.parent_id]
while p.kind != "agent":
p = by_id[p.parent_id]
row = table[p.name]
if s.kind == "llm":
row["llm_calls"] += 1
row["tokens_in"] += s.attrs["tokens_in"]
row["tokens_out"] += s.attrs["tokens_out"]
else:
row["tools"].append(s.name)
return table
def show(title, fn, task_id):
_, question, oid = next(t for t in TASKS if t[0] == task_id)
tracer = Tracer()
answer = fn(tracer, question)
print(f"=== {title}: {task_id} {question!r}")
print(f"answer={answer!r} expected={expected_answer(oid)!r}")
tracer.print_tree()
print("who did what:")
for agent, row in who_did_what(tracer.spans).items():
print(f" {agent:11s} {row}")
missing = expected_calls(oid) - actual_calls(tracer.spans)
extra = actual_calls(tracer.spans) - expected_calls(oid)
print("expected tool calls not made:", [m[0] for m in missing.elements()] or "none")
print("tool calls not expected: ", [e[0] for e in extra.elements()] or "none")
return tracer
show("single agent", single_agent, "t3")
print()
t = show("two agents", two_agents, "t4")
print("\nfirst 2 lines of the JSONL export:")
print("\n".join(t.to_jsonl().splitlines()[:2]))
# The contract check passed (order_id and found are present), but the brief asked for more fields.
import json
asked = ["order_id", "found", "total", "final_sale", "status", "days_since_delivery", "policy"]
got = json.loads(next(s for s in t.spans if s.name == "researcher" and s.kind == "agent").attrs["output"])
print("\nfields asked of the researcher but missing from its answer:", [k for k in asked if k not in got])python3 read_trace.py=== single agent: t3 'Can order C31 be refunded?'
answer='ELIGIBLE 15.00' expected='NOT_ELIGIBLE final_sale'
run:single_agent [260 ms]
agent:agent [260 ms] output='ELIGIBLE 15.00'
llm:agent.model_call [125 ms] in=26 out=5
tool:order_lookup [20 ms] args={"order_id": "C31"}
llm:agent.model_call [115 ms] in=45 out=3
who did what:
agent {'llm_calls': 2, 'tokens_in': 71, 'tokens_out': 8, 'tools': ['order_lookup']}
expected tool calls not made: ['policy_lookup']
tool calls not expected: none
=== two agents: t4 'Can order D40 be refunded?'
answer='ELIGIBLE 80.00' expected='NOT_ELIGIBLE not_delivered'
run:two_agents [585 ms]
agent:researcher [470 ms] output='{"order_id": "D40", "found": true, "total": 80.0, "final_sale": false, "policy": {"window_days"'
llm:researcher.model_call [125 ms] in=38 out=5
tool:order_lookup [20 ms] args={"order_id": "D40"}
llm:researcher.model_call [125 ms] in=57 out=5
tool:policy_lookup [20 ms] args={"topic": "refunds"}
llm:researcher.model_call [180 ms] in=74 out=16
agent:writer [115 ms] output='ELIGIBLE 80.00'
llm:writer.model_call [115 ms] in=51 out=3
who did what:
researcher {'llm_calls': 3, 'tokens_in': 169, 'tokens_out': 26, 'tools': ['order_lookup', 'policy_lookup']}
writer {'llm_calls': 1, 'tokens_in': 51, 'tokens_out': 3, 'tools': []}
expected tool calls not made: none
tool calls not expected: none
first 2 lines of the JSONL export:
{"attrs": {}, "end_ms": 585, "kind": "run", "name": "two_agents", "parent_id": null, "span_id": 1, "start_ms": 0}
{"attrs": {"input": "TASK: Can order D40 be refunded?\nReturn the facts as JSON: order_id, found, total, final_sale, status, days_since_delivery, policy.", "output": "{\"order_id\": \"D40\", \"found\": true, \"total\": 80.0, \"final_sale\": false, \"policy\": {\"window_days\": 30, \"final_sale_refundable\": false, \"needs_delivery\": true}}"}, "end_ms": 470, "kind": "agent", "name": "researcher", "parent_id": 1, "span_id": 2, "start_ms": 0}
fields asked of the researcher but missing from its answer: ['status', 'days_since_delivery']How to read it.
The single-agent trace (t3). One agent span, two model calls, one tool call. The answer is wrong, and the last lines say why: expected tool calls not made: ['policy_lookup']. The agent never looked at the policy. The trace is short, and the cause is visible in the tree itself: the policy tool span is absent. A missing span is evidence.
The two-agent trace (t4). There is a researcher span (three model calls, two tool calls) and a writer span (one model call, no tools). The "who did what" table is the payoff of the agent-span convention: the researcher consumed 169 input tokens, the writer 51, and only the researcher called tools. Now the surprise. The tool-call comparison says none missing and none extra. Every tool call was correct, and the answer is still wrong. The fault is not in what anyone did, it is in what was handed over.
The handoff is where to look. The researcher span's output attribute shows what it gave the writer. The last line of the output compares the fields the brief asked for with the fields that came back: status and days_since_delivery are missing. The writer then assumed they were fine and answered ELIGIBLE 80.00 for an order that has not been delivered.
Part 8: Where a real OpenAI or Anthropic client plugs in#
Reference
The project was built so that the only thing that needs to change is the model object. A ScriptedModel is a callable, model(messages) -> {"tool": name, "args": {...}} or {"text": ...}. A real client is the same callable with the network behind it. The two classes below keep each provider's native history inside, because the two APIs want different message shapes back (the loop has to preserve whole assistant turns; 08A.2 explains why).
The calls follow the shapes in the official docs as checked on 1 December 2026: OpenAI's Responses API (client.responses.create, function_call output items with name, arguments as a JSON string and call_id, answered by a function_call_output item) and Anthropic's Messages API (client.messages.create, stop_reason == "tool_use", tool_use blocks with id, name and input, answered by a tool_result block in a user message). Model ids (gpt-6-luna, claude-sonnet-5-5) are examples. Pin the exact id you evaluated (11C.5). This code needs pip install openai anthropic and keys in your environment, so it is illustrative and not run in this lesson. Verify names against the SDK versions you install.
# real_clients.py: where a real client would plug in (ILLUSTRATIVE: needs keys, not run in this lesson)
# Each class has the same interface as ScriptedModel: model(messages) -> {"tool": ..., "args": ...} or {"text": ...}
# `messages` is the loop's neutral history. The adapter keeps the provider's native history privately,
# because OpenAI and Anthropic want different shapes back (08A.2 explains why).
import json
from openai import OpenAI
import anthropic
class OpenAIModel:
def __init__(self, model, tools): # model e.g. "gpt-6-luna"; tools in Responses format
self.client, self.model, self.tools, self.history, self.pending = OpenAI(), model, tools, [], None
def __call__(self, messages):
last = messages[-1]
if last["role"] == "user":
self.history += [{"role": "system", "content": messages[0]["content"]}, {"role": "user", "content": last["content"]}]
elif last["role"] == "tool":
self.history.append({"type": "function_call_output", "call_id": self.pending,
"output": json.dumps(last["content"])})
resp = self.client.responses.create(model=self.model, input=self.history, tools=self.tools)
self.history += resp.output # keep the model's own output items, unchanged
for item in resp.output:
if item.type == "function_call":
self.pending = item.call_id
return {"tool": item.name, "args": json.loads(item.arguments)}
return {"text": resp.output_text}
class AnthropicModel:
def __init__(self, model, tools): # model e.g. "claude-sonnet-5-5"; tools with input_schema
self.client, self.model, self.tools, self.history, self.pending = anthropic.Anthropic(), model, tools, [], None
self.system = ""
def __call__(self, messages):
last = messages[-1]
if last["role"] == "user":
self.system = messages[0]["content"]
self.history.append({"role": "user", "content": last["content"]})
elif last["role"] == "tool":
self.history.append({"role": "user", "content": [
{"type": "tool_result", "tool_use_id": self.pending, "content": json.dumps(last["content"])}]})
resp = self.client.messages.create(model=self.model, max_tokens=1024, system=self.system,
tools=self.tools, messages=self.history)
self.history.append({"role": "assistant", "content": resp.content})
if resp.stop_reason == "tool_use":
block = next(b for b in resp.content if b.type == "tool_use")
self.pending = block.id
return {"tool": block.name, "args": block.input}
return {"text": "".join(b.text for b in resp.content if b.type == "text")}
# Usage: replace single_agent_model(task) with AnthropicModel("claude-sonnet-5-5", TOOL_SPECS) (or OpenAIModel).
# For cost, read the usage object on each response (input and output token counts) into the llm span's
# tokens_in / tokens_out instead of count_tokens(); check the field names in the provider's API reference.Three things change when the model is real, and each one touches the evaluation.
- Results become noisy. A scripted model gives the same answer every time. A real model does not, so one run per task is not enough. Run each task several times and report pass^k and an interval (10A.7, Part 5).
- Cost is measured, not estimated. Replace
count_tokenswith the token counts the provider returns on each response, and the toy prices with the current numbers from the provider's pricing page. - Tools can have side effects. The fake tools here are safe to call twice. Real ones may not be (08A.7 covers idempotency).
Part 9: Evaluate it#
This part is the core of the lesson. You have two versions, a trace for every run and three numbers. The job now is to decide, honestly, what they say.
Concept lessons first.
- 10A.7 Evaluating Agents, Tool Use and Multimodal Systems defines the three metrics used here: tool-call precision and recall (4.2), intervals for success rates (5.2) and task success rate and cost per successful task (5.6).
- 10A.12 Evaluating Multi-Agent Systems and Validating User Simulators covers what this project only touches: scoring a handoff, attributing a failure to one agent, and the failure categories of multi-agent systems.
- 10A.11 Evaluating Agent Memory and Context helps when the question becomes "what did each agent see?".
Then the DeepEval lessons (required track): 10B.2, 10B.3, 10B.4, 10B.5 tracing and agent evaluation, 10B.6 and 10B.7. The one to open next is 10B.5, Part 13: it shows how DeepEval nests agent spans (one agent span inside another, with tool calls attributed to the agent that made them), which is the same structure as the trace you just built.
Then, optionally: 10B.14 Inspect: tools and agents (optional), whose Part 9 is an advanced follow-up on handoff(), as_tool() and limits per composition mechanism. The rest of the Inspect track (10B.8 to 10B.17, all optional) is there if you later adopt Inspect.
9.1 The question and the rule, before the numbers#
Write the rule first, so the numbers cannot talk you into something. For this project:
Replace the single agent with the two-agent version only if (a) task success is not lower, beyond noise; (b) tool-call F1 is not lower; and (c) cost per successful task is no more than 1.5 times the single agent's.
The 1.5 is a choice for the example, standing in for a budget your team would set. Change it for your own system, but fix it before you look.
9.2 The three numbers and what they say#
From the run in Part 6:
| Metric | Single agent | Two agents |
|---|---|---|
| Tasks passed | 6 of 7 | 6 of 7 |
| Task success rate | 0.86 | 0.86 |
| Tool-call F1 (mean over tasks) | 0.86 | 1.00 |
| Cost per successful task (toy units) | 0.40 | 0.83 |
- Task success is tied, 6 of 7 for both. But they failed on different tasks and for different reasons: the single agent on a skipped lookup, the two-agent version on a missing field. A tie in the headline hides two different weaknesses, and only the traces told us so.
- Tool-call correctness favours the two-agent version. The researcher's narrow job makes it call the right tools. The single agent skipped one needed call on two tasks and made one extra call on another, which is what an F1 of 0.67 means on those tasks (the F1 formula here treats a missing call and an extra call as errors in recall and precision respectively).
- Cost per successful task favours the single agent, by roughly a factor of two here. Two agents mean two system prompts and a handoff, and the failed run still counts in the numerator. Using cost per run would hide the point that failures cost money too (10A.7, 5.6).
Against the rule in 9.1: (a) holds (tied), (b) holds, (c) fails (0.83 is about 2.1 times 0.40, over the 1.5 limit). Verdict: do not replace. The decision came from a rule and three numbers, not from taste.
9.3 Reading a tie: intervals and the small task set#
The program also printed a 95 percent interval for each success rate: 0.49 to 0.97 for both, with n = 7. That range is wide. With seven tasks, 6 of 7 and 7 of 7 are not distinguishable, and 5 of 7 would not be either. If your decision depends on a one-task difference, you have not measured anything yet. 10A.7, 5.2 explains the interval and 10A.7, 5.4 how many trials you need. Two practical rules:
- Use more tasks before you use more runs. Repeating a scripted task adds nothing. Repeating a real-model task measures noise but does not add new situations. A task set of dozens, chosen from real traffic and from the failure cases you already know, is what narrows the interval.
- Report the interval next to the number. "0.86 (0.49 to 0.97, n = 7)" is honest. "0.86" alone is not.
9.4 What would change the verdict#
The verdict depends on the script, so test the script. whatif.py changes the flaw table and re-runs the whole comparison.
# whatif.py: change one scripted flaw and re-run the evaluation. The verdict depends on the script.
import models
from agents import single_agent, two_agents
from evaluate import run_version, summarize
def report(label):
s = summarize(run_version("single", single_agent, verbose=False))
t = summarize(run_version("two-agent", two_agents, verbose=False))
print(f"{label}")
print(f" single success={s['successes']}/{s['n']} tool_f1={s['tool_call_f1']:.2f} cost/success={s['cost_per_success']:.2f}")
print(f" two-agent success={t['successes']}/{t['n']} tool_f1={t['tool_call_f1']:.2f} cost/success={t['cost_per_success']:.2f}")
report("A. as scripted in Part 5")
models.FLAWS["researcher_drops_status"] = set()
report("B. the researcher always reports every field (the D40 bug fixed)")
models.FLAWS["single_skips_policy"] = set()
models.FLAWS["single_overcalls"] = set()
report("C. B, and the single agent never skips a lookup or makes the wasted one")python3 whatif.pyA. as scripted in Part 5
single success=6/7 tool_f1=0.86 cost/success=0.40
two-agent success=6/7 tool_f1=1.00 cost/success=0.83
B. the researcher always reports every field (the D40 bug fixed)
single success=6/7 tool_f1=0.86 cost/success=0.40
two-agent success=7/7 tool_f1=1.00 cost/success=0.72
C. B, and the single agent never skips a lookup or makes the wasted one
single success=7/7 tool_f1=1.00 cost/success=0.37
two-agent success=7/7 tool_f1=1.00 cost/success=0.72Read the three blocks as three different worlds.
- A is the world above.
- B fixes the researcher's missing-field bug (as a stricter handoff contract would). Now the two-agent version passes 7 of 7 against the single agent's 6 of 7, with perfect tool-call F1. Cost per successful task is lower than in A (0.72 against 0.83) because a success now divides the same spending. Rule (c) still fails: 0.72 is 1.8 times 0.40.
- C also stops the single agent from skipping lookups and from the wasted call on the unknown order. Both pass 7 of 7 with perfect tool-call F1. The remaining difference is cost (0.37 against 0.72 per successful task), which favours the single agent. In a world where one agent can do the job, the second agent is pure overhead, which is the point of 08D.1's first rule.
Two lessons. First, a design is only as good as its handoff contract: the two-agent system went from tied to better by tightening one check. Second, the comparison measures a system under assumptions. With real models, the "flaw table" is unknown, so you measure it by running real tasks and reading the traces of the failures (as in Part 7), then writing what you learn down as a regression case.
9.5 A checklist for your own comparison#
- Same tasks, same tools, same grader for both versions.
- Decide the pass rule before running.
- Report task success with its interval, tool-call correctness, and cost per successful task. Add latency if users wait for the answer.
- For every failure, read the trace and label where it went wrong: a wrong tool call, a missing tool call, or a bad handoff.
- Turn each labelled failure into a task in the set, so it cannot come back unnoticed (11A.4 shows how production traces become eval data).
- With a real model, repeat each task and use pass^k and intervals.
- Re-run the comparison when the model, prompt or tools change (10A.8, 8.1).
Common misconceptions#
- "If the final answer is right, the agent did it right." The single agent got
A17right while skipping the policy lookup. Right answer, wrong process: it will fail on the next order that needs the policy. Tool-call correctness catches this, task success does not. - "A tie in task success means the versions are equal." The two failures here were different, and the cost differed by a factor of two.
- "Cost per run is the cost metric." Cost per successful task includes the spend on failures. A cheap-looking agent that fails often is expensive per success.
- "A trace of tool calls tells me where the bug is." In the two-agent failure every tool call was correct. The bug lived in the handoff, which the trace shows only if you record agent inputs and outputs.
- "Seven tasks are enough." They illustrate the method. A decision needs enough tasks to narrow the interval.
- "These numbers show two agents are better (or worse)." They come from scripted models and illustrate the method. They say nothing about real model behaviour.
Key takeaways#
- Build both versions on the same tools and the same task set, so only the architecture differs.
- A minimal span recorder (run, agent, llm and tool spans, nested, with token counts and agent inputs and outputs) is enough to answer "who did what".
- Read a trace in three steps: what happened in order, who did it (group by agent span), and where it diverged from what should have happened. Check the handoff payloads.
- Report task success rate (with an interval), tool-call correctness and cost per successful task, and decide against a rule written before the run.
- A tie in the headline can hide different failures. Tool-call correctness and traces separate them.
- The handoff contract decides the multi-agent result. Tightening one required field turned a tied comparison into a win for the two-agent version.
- Scripted models illustrate a method. Real models need repeated runs, measured costs and more tasks.
Terms introduced in this lesson#
| Term | Meaning |
|---|---|
| Trace | The recorded history of one run: model calls, tool calls, timing and sizes, in order |
| Span | One entry in a trace, with a start, an end, a parent and attributes |
| Agent span | A span that marks one agent's loop, so calls inside it can be attributed to that agent |
| Span attribute | A key and value attached to a span, such as token counts or the arguments of a tool call |
| Virtual clock | A counter advanced by code instead of the wall clock, so timings are reproducible |
| Task success rate | Successes divided by trials, where success is judged by an outcome check |
| Tool-call correctness | How well the tool calls made match a reference set, measured as precision, recall and F1 over (tool, arguments) pairs |
| Cost per successful task | Total spend on all runs, failed ones included, divided by the number of successes |
| Confidence interval (success rate) | A range that the true success rate probably lies in, wide when the task set is small |
| Pass rule | The thresholds, written before a comparison, that decide whether a change ships |
| What-if run | Re-running an evaluation after changing one assumption, to see which assumption drives the verdict |
| Scripted model | A fake model that replays a fixed plan, used to test code and illustrate methods without keys |
Exercises#
- Tighten the contract. In
agents.py, changeFINDINGS_FORMATand the check so that whenfoundis true the findings must containstatusanddays_since_delivery. Re-runevaluate.py. What happens tot4, and what does the error message look like? Hint: raiseValueErrorfor missing fields, and decide whether the orchestrator retries the researcher once before failing. - Add a task. Add an order
G71that is delivered 31 days ago andfinal_sale: True. Predict each version's answer and tool-call F1 before running. Hint: checkmodels.FLAWSto see whether either version is scripted to mishandle it. - A reviewer agent. Add a third agent, a reviewer that gets the writer's answer and the original order and policy and rejects wrong decisions. Does success change? What does it do to cost per successful task? Hint: give the reviewer the source data, as in 08D.1 Part 5.3, and count its model call in the cost.
- Log the handoff cost. Add an attribute
handoff_tokenson the writer's agent span (tokens in the brief the writer received) and print the share of total input tokens that handoffs account for. Hint: you already havetokens_inon the first writerllmspan. - Change the price. In
models.py, changePRICE_OUTto 40.0 (an output-heavy price). Which version's cost per successful task moves more, and why? Hint: the two-agent researcher writes a longer JSON output than the single agent's one-line answer. - Write a regression case. Turn the
D40failure into a permanent task with a comment saying which handoff field was missing, then show the task fails with the minimal contract and passes with the strict one. Hint: this is the pattern in checklist item 5.
Check yourself#
- Why do both versions share the same tools and the same task set?So the only difference between the runs is the architecture. Different tools or tasks would confound the comparison.
- What are the four span kinds in this lesson's recorder, and what does the agent span make possible?
run,agent,llmandtool. The agent span lets you group model calls and tool calls under the agent that made them, so you can total tokens and tools per agent. - In the Part 7 two-agent trace, every tool call was correct and the answer was wrong. Where was the bug, and how did you find it?In the handoff: the researcher's output lacked
statusanddays_since_delivery, and the writer assumed they were fine. It was found by looking at the researcher span'soutputand comparing its fields with the fields the brief asked for. - Define tool-call precision, recall and F1 for this project.Precision is the share of calls made that were expected, recall is the share of expected calls that were made, and F1 is their harmonic mean, over
(tool, arguments)pairs. - Why is cost per successful task a better metric than cost per run?It includes the spend on failed runs in the numerator, so an agent that fails often looks as expensive as it really is per useful result.
- The two versions tied on task success. Why can that still hide a real difference?The two versions can fail on different tasks for different reasons, and differ in cost and in process correctness. Task success alone does not show that.
- What does the interval 0.49 to 0.97 tell you, and what would narrow it?With only seven tasks the true success rate could lie anywhere in that range, so 6 of 7 and 7 of 7 cannot be told apart. More tasks narrow it.
- Why did the two-agent version look better in what-if run B, and what single change caused it?The researcher always reported every field, which is what a stricter handoff contract enforces. The writer then received what it needed and passed 7 of 7.
- Why are the results in this lesson not evidence about real models?The models are scripted and their flaws were written down in advance, and the prices are toy numbers. The method transfers, the numbers do not.
- Name three things that change when you replace a scripted model with a real OpenAI or Anthropic client.Results become noisy (repeat runs, pass^k and intervals), cost must be measured from returned token counts and real prices, and tools may have side effects that need idempotency.
Further resources#
- 08D.1 — One Agent or Several: roles, the two basic patterns, handoff contracts and the three common problems.
- 08F.13 — Subgraphs and Multi-Agent Systems: the same patterns built in LangGraph (optional track, the better next step if you use LangGraph).
- 08D.3 — Multi-Agent Systems: the architecture zoo, 3.8 nested traces and 3.9 evaluating multi-agent systems.
- 10A.7, 10A.12 and 10B.5 Part 13: the evaluation lessons this hands-on builds on.
- 03.12 — Minimal Tracing: See What Your First LLM App Did and 11A.1, Part 3 — OpenTelemetry for GenAI: tracing before and after this lesson.
- 13A.8, 11.2 — Single agent vs multi-agent: the general single-versus-multi-agent decision.
- OpenAI: Function calling guide and Anthropic: Handle tool calls: the wire shapes used in Part 8.
- OpenTelemetry: Semantic conventions for generative AI: the standard span names and attributes.
← 08D.1 — One Agent or Several: Roles and the Two Basic Patterns | Module 08D overview | 08D.3 — Multi-Agent Systems →