Grading Trajectories with Code and Models
Grade recorded agent runs with code checks for tool selection, argument correctness, step efficiency and policy adherence, see why exact-sequence matching is both too strict and too lenient, and calibrate a rubric-based model grader against expert labels with agreement, confusion counts and Cohen's kappa.
Contentsand lesson path
On this page
- The problem
- Step 1: Recorded trajectories as data
- Step 2: Four code checks
- Step 3: Run the checks, and see why exact matching misleads
- Step 4: A model grader for what code cannot judge
- Step 5: Calibrate the grader against expert labels
- Check your understanding
- Apply it
- Review prompt
Lessons of Agent Evaluation
- Outcomes, Trajectories and Why Both Matter Concept · 15 min
- Lab: A Reproducible Task Suite with Mock Tools Lab · 30 min
- Grading Trajectories with Code and Models Worked example · 20 min
- Reliability over Repeated Trials Lab · 20 min
- From Production Trace to Regression Task Worked example · 15 min
- Check: Interpret an Agent Evaluation Report Knowledge check · 8 questions
What you will learn
- Score trajectories for tool selection, argument correctness, step efficiency and policy adherence, using code checks and calibrated model graders.
Prerequisites: AI Evaluation, Agent Loops & ReAct
01. The problem
Lab 2 graded the end state. This lesson grades the path. Take one task from the lab, the partial refund of £15.00 on order 1003, and six recorded trajectories of it. Some are fine, some reach the right state in a way the shop does not accept, and one passes a wrong argument. You will:
- write code checks for tool selection, argument correctness, step efficiency and policy adherence;
- compare them with an exact-sequence check, and see where that goes wrong;
- write a model grader with a rubric for what code cannot judge, the quality of the reply;
- calibrate that grader against an expert's labels, and improve its rubric.
A code check is a function that inspects the trajectory and returns pass or fail. It is fast, free and repeatable, so use it for every property that can be stated exactly. A model grader is a language model that reads the run and a rubric and returns a verdict. It can judge things without an exact definition, but it can be wrong and costs money per call, so check it against people before you trust it. Save the files in a folder called grading (Python 3.10 or later, tested with 3.12, no packages).
02. Step 1: Recorded trajectories as data
Each call in a trajectory is a tuple of tool name, arguments and result, the same information lab 2 recorded. TASK holds the rules the checks will apply: the tools a correct run must use, the tools it must not use, the arguments the state-changing call must have, and a policy rule as a pair, "this tool must succeed before that one". reference is one known good path. It is used only to measure efficiency, never as the one path a run must follow.
"""Six recorded trajectories for one task: partial refund of order 1003."""
TASK = {
"request": "This is [email protected], code 9050. One item from order 1003 "
"was missing. Please refund £15.00.",
"required": ["verify_identity", "issue_refund"],
"forbidden": ["cancel_order"],
"expected_args": {"issue_refund": {"order_id": "1003", "amount_pence": 1500}},
"must_precede": [("verify_identity", "issue_refund")], # policy rule
"reference": ["lookup_customer", "verify_identity", "get_order", "issue_refund"],
}
LOOKUP = ("lookup_customer", {"email": "[email protected]"}, {"customer_id": "C-2"})
VERIFY = ("verify_identity", {"customer_id": "C-2", "code": "9050"},
{"verified": True})
ORDER = ("get_order", {"order_id": "1003"}, {"total_pence": 6000})
REFUND = ("issue_refund", {"order_id": "1003", "amount_pence": 1500},
{"refunded_pence": 1500})
RUNS = {
"reference": [LOOKUP, VERIFY, ORDER, REFUND],
"other-order": [ORDER, LOOKUP, VERIFY, REFUND], # a different, valid path
"wrong-amount": [LOOKUP, VERIFY, ORDER,
("issue_refund", {"order_id": "1003", "amount_pence": 6000},
{"refunded_pence": 6000})],
"refund-first": [LOOKUP, REFUND, VERIFY],
"looping": [LOOKUP, VERIFY, ORDER, ORDER, LOOKUP, ORDER, REFUND],
"wrong-tool": [LOOKUP, VERIFY, ORDER,
("cancel_order", {"order_id": "1003"}, {"error": "not pending"}),
REFUND],
}03. Step 2: Four code checks
"""Code checks over a trajectory: each returns (passed, detail)."""
from recorded import RUNS, TASK
def exact_sequence(run: list) -> bool:
"""The brittle check: the tool names must match the reference, in order."""
return [name for name, _args, _result in run] == TASK["reference"]
def selection(run: list) -> tuple[bool, str]:
names = {name for name, _args, _result in run}
missing = [t for t in TASK["required"] if t not in names]
banned = [t for t in TASK["forbidden"] if t in names]
return not missing and not banned, ", ".join(missing + banned) or "ok"
def arguments(run: list) -> tuple[bool, str]:
for name, args, _result in run:
expected = TASK["expected_args"].get(name)
if expected and args != expected:
wrong = {k: v for k, v in args.items() if expected.get(k) != v}
return False, f"{name} {wrong}"
return True, "ok"
def efficiency(run: list) -> tuple[bool, str]:
calls = [(name, sorted(args.items())) for name, args, _result in run]
redundant = len(calls) - len({str(c) for c in calls}) # exact repeats
ratio = len(run) / len(TASK["reference"])
return redundant == 0 and ratio <= 1.5, f"{len(run)} calls, {redundant} repeated"
def policy(run: list) -> tuple[bool, str]:
seen = set()
for name, _args, result in run:
for before, after in TASK["must_precede"]:
if name == after and before not in seen:
return False, f"{after} before {before}"
if "error" not in result and result.get("verified", True):
seen.add(name) # only a successful call counts
return True, "ok"
CHECKS = [selection, arguments, efficiency, policy]
if __name__ == "__main__":
print(f"{'run':<13} {'exact':<5} {'select':<6} {'args':<5} {'effic':<5}"
f" {'policy':<6} first problem")
for run_id, run in RUNS.items():
exact = exact_sequence(run)
results = [check(run) for check in CHECKS]
problem = next((d for ok, d in results if not ok), "-")
marks = [("yes" if exact else "no")] + ["PASS" if ok else "FAIL"
for ok, _d in results]
print(f"{run_id:<13} {marks[0]:<5} {marks[1]:<6} {marks[2]:<5}"
f" {marks[3]:<5} {marks[4]:<6} {problem}")Each check answers one question and returns a short reason when it fails, so a failing run explains itself:
- Tool selection: did the run use every required tool and no forbidden one? Requiring a set of tools, not an order, leaves the agent free to choose its route. The tool selection lab measures single tool choices; this applies the idea to a whole run.
- Argument correctness: do the calls that change state, here
issue_refund, have exactly the expected IDs and amounts? Read-only calls are left alone, because checking every argument of every call makes tests brittle without protecting anything. - Step efficiency: how many calls are exact repeats, and how long is the run compared with the reference? The limit of 1.5 times the reference is a choice; many teams report this number instead of failing on it.
- Policy adherence: does
issue_refundcome before a successfulverify_identity? A check that returnedverified: falsedoes not count: refunding after a failed check breaks the rule as badly as never checking.
04. Step 3: Run the checks, and see why exact matching misleads
python3 trajectory_checks.pyrun exact select args effic policy first problem
reference yes PASS PASS PASS PASS -
other-order no PASS PASS PASS PASS -
wrong-amount yes PASS FAIL PASS PASS issue_refund {'amount_pence': 6000}
refund-first no PASS PASS PASS FAIL issue_refund before verify_identity
looping no PASS PASS FAIL PASS 7 calls, 3 repeated
wrong-tool no FAIL PASS PASS PASS cancel_orderCompare the exact column with the four checks. other-order read the order before looking up the customer: a valid path the task author did not write down, which the exact check fails although every rule holds. wrong-amount follows the reference exactly, so the exact check passes it, yet it refunded £60.00 instead of £15.00. Exact-sequence matching is wrong in both directions: too strict about harmless ordering, and blind to the arguments that matter.
The better pattern is to grade the outcome, as lab 2 does, plus invariants: rules that must hold on every acceptable path, such as required and forbidden tools, the values of state-changing arguments and ordering rules like "verify before refund". The four checks are exactly that, and each problem run fails on one named rule, which tells you what to fix.
05. Step 4: A model grader for what code cannot judge
The trajectory checks say nothing about the reply. "Does it state the amount?" could be a regular expression, but "does it promise anything the tools did not do?" and "does it blame the customer?" need judgement. That is the job of a model grader, also called an LLM judge. It needs a rubric: grading instructions that a person could apply too, asking for one binary verdict and saying exactly what makes a reply fail.
Below are twelve final replies from runs of the partial-refund task, each labelled by a support lead who knows the policy. Rubric v1 is vague; rubric v2 lists fail conditions. To run offline, a deterministic stub plays the model by turning each rubric into rules. It is not a language model, but it fails the way vague rubrics tend to: it passes almost anything that sounds right.
"""Final replies from 12 runs of the partial-refund task, with expert labels.
Facts from the tools: £15.00 refunded on order 1003. Shop policy: refunds reach
the card within 5 working days. A support lead labelled each reply by hand.
"""
REPLIES = [
("r01", "I have refunded £15.00 for the missing item on order 1003. It should "
"reach your card within 5 working days.", "pass"),
("r02", "Refund done.", "fail"),
("r03", "I have refunded £15.00 to your card. You will see it tomorrow.", "fail"),
("r04", "Sorry about the missing item! I have refunded £15.00, and I have "
"added a £10 voucher for the trouble.", "fail"),
("r05", "I've refunded £15.00 for order 1003. Sorry for the trouble.", "pass"),
("r06", "Your refund is on its way, sorry again for the missing item.", "fail"),
("r07", "£15.00 has been refunded for order 1003; allow up to 5 working days.",
"pass"),
("r08", "I have refunded £15.00. Next time, please check the parcel before "
"you sign for it.", "fail"),
("r09", "I have processed your refund of £15.00 and will refund your delivery "
"charge as well.", "fail"),
("r10", "Refunded £15.00 for the missing item. Anything else I can help with?",
"pass"),
("r11", "Good news: your full refund has been issued!", "fail"),
("r12", "I've refunded £15.00 for order 1003. It will arrive within 5 working "
"days.", "pass"),
]"""A model grader with a rubric, played by a deterministic STUB so it runs offline.
The stub turns each rubric into rules. A real grader would send the rubric and
the reply to a model and read back a pass/fail verdict.
"""
import re
RUBRICS = {
"v1": "Is the reply polite and does it confirm the refund? Answer pass or fail.",
"v2": ("Fail the reply if ANY of these is true, otherwise pass: "
"(1) it does not state the amount refunded; "
"(2) it promises anything the tools did not do, such as a voucher, "
"an extra refund or a faster timescale than 5 working days; "
"(3) it blames the customer."),
}
PROMISES = ("tomorrow", "today", "voucher", "as well", "24 hours")
def stub_grade(reply: str, rubric: str) -> str:
if rubric == "v1": # vague rubric: almost any refund message passes
confirms = "refund" in reply.lower() and len(reply.split()) > 3
return "pass" if confirms else "fail"
states_amount = re.search(r"£\d+\.\d\d", reply) is not None
promises = any(p in reply.lower() for p in PROMISES)
# The stub has no rule for (3), blame: a weakness the calibration will show.
return "pass" if states_amount and not promises else "fail"With a real model, stub_grade becomes one API call per reply. The sketch below was not run for this lesson, because it needs an API key. It asks for the reason before the verdict, so the model states its evidence first, and it raises an error on an unexpected answer instead of guessing.
import json
import os
import anthropic
from grader import RUBRICS
MODEL = os.environ.get("ANTHROPIC_MODEL", "claude-sonnet-5-5")
client = anthropic.Anthropic()
def model_grade(reply: str, rubric: str) -> str:
response = client.messages.create(
model=MODEL, max_tokens=4000, # room for any thinking plus the JSON
system=RUBRICS[rubric] + ' Answer only with JSON: '
'{"reason": "<one sentence>", "verdict": "pass" or "fail"}',
messages=[{"role": "user", "content": f"<reply>{reply}</reply>"}])
if response.stop_reason != "end_turn": # e.g. max_tokens or refusal
raise ValueError(f"no verdict: stop_reason={response.stop_reason}")
text = "".join(b.text for b in response.content if b.type == "text")
verdict = json.loads(text)["verdict"]
if verdict not in ("pass", "fail"):
raise ValueError(f"unexpected verdict: {verdict!r}")
return verdict06. Step 5: Calibrate the grader against expert labels
A grader is a measuring instrument, and an instrument needs calibration: you compare its readings with a trusted reference before you use it. Here the reference is the expert's labels. calibrate.py counts the four combinations of grader and expert verdicts and reports two numbers. Agreement is the share of replies where both gave the same verdict. Cohen's kappa corrects agreement for chance: a grader that passes nearly everything agrees with the expert on every reply the expert passed, without judging anything. Kappa is 0 for agreement at chance level and 1 for perfect agreement.
"""Compare the grader with expert labels: confusion counts, agreement, kappa."""
import sys
from grader import stub_grade
from replies import REPLIES
def cohen_kappa(pairs: list) -> float:
n = len(pairs)
observed = sum(g == h for g, h in pairs) / n
g_pass = sum(g == "pass" for g, _h in pairs) / n
h_pass = sum(h == "pass" for _g, h in pairs) / n
expected = g_pass * h_pass + (1 - g_pass) * (1 - h_pass) # agreement by chance
return (observed - expected) / (1 - expected)
rubric = sys.argv[1]
pairs = [(stub_grade(text, rubric), label) for _id, text, label in REPLIES]
counts = {(g, h): sum(p == (g, h) for p in pairs)
for g in ("pass", "fail") for h in ("pass", "fail")}
n = len(pairs)
print(f"rubric {rubric}: grader passes {sum(g == 'pass' for g, _ in pairs)}/{n},"
f" experts pass {sum(h == 'pass' for _, h in pairs)}/{n}")
print(f" both pass {counts['pass', 'pass']} grader pass, expert fail"
f" {counts['pass', 'fail']}")
print(f" both fail {counts['fail', 'fail']} grader fail, expert pass"
f" {counts['fail', 'pass']}")
print(f" agreement {sum(g == h for g, h in pairs) / n:.2f}"
f" Cohen's kappa {cohen_kappa(pairs):.2f}")
disagree = [rid for (rid, _t, h), (g, _h) in zip(REPLIES, pairs) if g != h]
print(" disagreements:", ", ".join(disagree))python3 calibrate.py v1rubric v1: grader passes 11/12, experts pass 5/12
both pass 5 grader pass, expert fail 6
both fail 1 grader fail, expert pass 0
agreement 0.50 Cohen's kappa 0.12
disagreements: r03, r04, r06, r08, r09, r11The grader passes 11 replies and the expert 5. All six disagreements go the same way: the grader passed replies the expert failed. That is a lenient grader, and its errors do not cancel out over more replies; they inflate every score you report with it. Agreement of 0.50 sounds like something, but kappa of 0.12 shows that it is barely better than chance. Read the disagreements before you change anything: r03 promises the money tomorrow, r04 and r09 promise things the tools never did, r06 and r11 give no amount, and r08 blames the customer. Each one is a fail condition the vague rubric never stated. Rubric v2 states them:
python3 calibrate.py v2rubric v2: grader passes 6/12, experts pass 5/12
both pass 5 grader pass, expert fail 1
both fail 6 grader fail, expert pass 0
agreement 0.92 Cohen's kappa 0.83
disagreements: r08Agreement rises to 0.92 and kappa to 0.83. The remaining disagreement, r08, is the blame condition, which the stub has no rule for. A real model may catch it, but only the same comparison can tell you. Two limits apply. You refined the rubric while looking at these twelve replies, so the second score is optimistic: measure the final rubric on fresh labelled replies. And twelve labels are far too few; one changed label moves agreement by eight points. The judge lab of the AI Evaluation skill covers tune and test splits, error rates and bias probes.
In a full grader, code checks run first, because they are exact and free, and the model grader only judges what code cannot. Keep a person in the loop too: read a small sample of graded runs regularly, and recalibrate whenever the grader's model or rubric changes.
07. Check your understanding
08. Apply it
For the practice project, add trajectory checks to your support-agent suite: give every task its required and forbidden tools, the expected arguments of its state-changing calls and at least one ordering rule, and report repeated calls next to each verdict. Then write a binary rubric for the replies with explicit fail conditions. Label 40 replies yourself, use 20 to write and refine the rubric and the other 20 only once, to report agreement and kappa for your grader. Adopt it only if it clears a bar you wrote down before you measured.
09. Review prompt
Without looking back: name the four trajectory properties checked in code here and what each inspects. Give one run that an exact-sequence check fails wrongly and one it passes wrongly. Then explain how you would tell that a model grader is too lenient, what Cohen's kappa adds to agreement, and why a rubric is measured on labels it was not written from.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.