AI Agents course · lesson 28 of 36
- 1What Is an AI Agent? A Beginner's Guide to How Agents Work
- 2How LLMs Work: Tokens, Context Windows and Embeddings for Agent Builders
- 3Choosing and Configuring a Model for Your AI Agent
- 4The Agent Loop Explained: Perceive, Reason, Act, Observe
- 5Workflows or Agents? How to Decide What to Build
- 6Build Your First AI Agent From Scratch in Python
- 7Function Calling Across Providers: Claude, OpenAI and Gemini
- 8Errors, Retries and Rate Limits: Keep Your AI Agent From Crashing
- 9How to Write Tool Definitions and Get Structured Output From an AI Agent
- 10Designing Tools That Work: How to Make an AI Agent Better by Fixing Its Tools
- 11Common AI Agent Tools: Web Search, Code Execution, Databases, APIs and Email
- 12Computer Use and Web Browsing Agents: How They Work and When to Avoid Them
- 13MCP Explained: The Model Context Protocol for AI Agents
- 14Build and Deploy an MCP Server in Python
- 15Prompting for Agents: How to Write System Prompts an AI Agent Can Follow
- 16Context Engineering for AI Agents: What to Put in the Context Window
- 17AI Agent Memory: Short-Term vs Long-Term, and Where Each Lives
- 18Maintaining Agent Memory: Updating, Summarizing, Retrieving and Forgetting
- 19RAG and Vector Databases Explained: How Agents Search Your Documents
- 20Build a RAG Agent in Python That Answers From Your Documents With Citations
- 21ReAct and Chain of Thought: How AI Agents Reason and Act
- 22Planner-Executor, DAG Agents and Tree of Thought: Planning Architectures Explained
- 23Self-Critique and Evaluator-Optimizer: Improve Agent Output with a Review Loop
- 24Chaining, Routing and Parallelization: Three Core Workflow Patterns for AI Agents
- 25Orchestrator-Workers and Multi-Agent Systems: When to Use More Than One Agent
- 26Human-in-the-Loop Agents: Approval Gates, Checkpoints and Safe Oversight
- 27Testing AI Agents: Unit Tests, Mocked Models and Handling Non-Determinism
- 28Evaluating AI Agents: Evals, Graders, Metrics and pass@k
- 29Observability and Tracing for AI Agents: See What Your Agent Did and Why
- 30Prompt Injection and Tool Sandboxing: Protect AI Agents from Hostile Input
- 31Privacy, Bias and Red Teaming: Responsible Practices for AI Agents
- 32Agent Cost and Latency: Make AI Agents Cheaper and Faster Without Losing Quality
- 33AI Agent Frameworks Compared: Build Directly or Use LangGraph, CrewAI, the Agents SDKs and More
- 34Deploying AI Agents: Hosting, Queues, State, Secrets and Safe Releases
- 35Walkthrough: Build a Customer Support Agent with Tools, Approvals, Guardrails and Evals
- 36Walkthrough: Build a Research Agent with Parallel Workers, Citations and Source Checking
The loop tests in Testing AI agents prove that your code works. They cannot tell you whether the agent is any good: whether it solves real tasks, how often, at what cost, and whether the last change made it better or worse. That is the job of evaluations, usually called evals. An eval runs the real agent on a set of tasks, scores the results, and gives you numbers to compare. This lesson shows how to build one, in tested Python, and how to read the numbers without fooling yourself.
Vocabulary
These terms follow Anthropic's guide to evaluating agents.
- Task: one test with an input and clear success criteria.
- Trial: one attempt at a task. Outputs vary, so you run several trials per task.
- Grader: logic that scores something about a trial. A task can have more than one.
- Transcript: the full record of a trial: outputs, tool calls and reasoning. Also called a trace.
- Outcome: the final state of the world after the trial. A refund that exists in the database is an outcome. An agent saying "refund issued" is only a claim.
- Eval harness: the code that runs tasks, records results, grades them and adds them up.
The eval loop

An eval is not something you build once. It is a loop:
- Collect tasks, especially from real failures.
- Run trials, several per task, each in a clean environment.
- Grade each trial.
- Read transcripts, to confirm the grades are fair and to see why failures happened.
- Change the agent, or fix a broken task.
- Run again, and compare with the last run.
Build a test set
Anthropic's advice is to start small. A set of 20 to 50 simple tasks drawn from real failures is a good start, because early changes tend to have large effects that a small sample can show. Begin with the checks you already do by hand before a release, and turn each user-reported failure into a task.
Good tasks share a few qualities:
- Unambiguous. Two experts reading the task should agree on what a pass is.
- Solvable. Have a reference solution, so you know the task can be done. If nobody can solve it, the task is broken.
- Realistic. Use real data and real complexity. Anthropic's guide on writing tools for agents warns against toy sandboxes, and notes that strong tasks may need many tool calls.
- Balanced. Include cases where the agent should act and cases where it should not. A set with only "should" cases rewards an agent that does everything.
- Isolated. Each trial starts clean, so one trial cannot affect another.
Keep a held-out set that you do not tune against, just as in machine learning, so you notice if you are fitting the agent to your own tests.
Graders
| Grader | Strength | Weakness | Use for |
|---|---|---|---|
| Code | Fast, cheap, objective, repeatable | Brittle to valid variations, weak on subjective work | State checks, tool-call checks, exact facts |
| Model | Flexible, handles nuance | Non-deterministic, costs money, needs calibration | Tone, completeness, open-ended answers |
| Human | The gold standard | Slow and costly | Calibrating model graders, spot checks |
Anthropic's summary is to prefer deterministic graders where possible, model graders where necessary, and humans for validation. A few rules make graders better:
- Grade the outcome, not the path. Tasks often have several valid routes. Requiring one exact sequence of tool calls punishes good, creative solutions. Check the result instead.
- Use partial credit for tasks with several parts.
- Let the model grader say "unknown". A judge forced to pick a side may guess. Give it an "unknown" option, and count how often it uses it.
- One judge per dimension. A judge that scores tone, accuracy and length together is harder to calibrate than three small ones.
- Calibrate against people. Have a person grade a sample, compare, and fix the rubric where they disagree. The rubric advice in Self-critique and evaluator-optimizer applies.
- Resist gaming. If an agent can pass without solving the problem, the grader is broken.
The code
The harness below runs each task several times, gives every trial a fresh environment, applies the graders, and summarizes the results.
1import json
2import time
3from concurrent.futures import ThreadPoolExecutor
4
5JUDGE_MODEL = "claude-haiku-5-5"
6
7
8def grade_outcome(check):
9 """Grade the final state of the environment, not what the agent said it did."""
10 return lambda run: {"pass": bool(check(run["env"])), "reason": "outcome check"}
11
12
13def grade_forbidden_tool(name):
14 return lambda run: {"pass": name not in run["tool_calls"], "reason": f"must not call {name}"}
15
16
17def grade_with_model(client, rubric):
18 """A model grader may answer unknown, so it is not forced to guess."""
19 def grade(run):
20 reply = client.messages.create(
21 model=JUDGE_MODEL, max_tokens=300,
22 system='Judge the answer against the rubric. Reply with JSON only: {"verdict": "pass" | "fail" | "unknown", "reason": "..."}',
23 messages=[{"role": "user", "content": f"Rubric: {rubric}\n\nTask: {run['input']}\n\nAnswer: {run['answer']}"}],
24 )
25 try:
26 data = json.loads(reply.content[0].text)
27 verdict = data["verdict"]
28 if verdict not in ("pass", "fail", "unknown"):
29 raise ValueError(verdict)
30 return {"pass": verdict == "pass", "unknown": verdict == "unknown", "reason": str(data.get("reason", ""))}
31 except (ValueError, KeyError, TypeError):
32 return {"pass": False, "unknown": True, "reason": "the judge reply was not valid"}
33 return grade
34
35
36def run_trial(agent, make_env, task):
37 env = make_env() # a fresh environment per trial, so trials cannot affect each other
38 start = time.time()
39 try:
40 out = agent(task["input"], env)
41 except Exception as exc:
42 return {"task": task["id"], "pass": False, "error": f"{type(exc).__name__}: {exc}", "tool_calls": 0, "tokens": 0, "seconds": time.time() - start}
43 run = {"input": task["input"], "env": env, "answer": out["answer"], "tool_calls": out["tool_calls"]}
44 verdicts = [g(run) for g in task["graders"]]
45 return {"task": task["id"], "pass": all(v["pass"] for v in verdicts), "unknown": any(v.get("unknown") for v in verdicts),
46 "error": None, "tool_calls": len(out["tool_calls"]), "tokens": out.get("tokens", 0), "seconds": time.time() - start,
47 "reasons": [v["reason"] for v in verdicts]}
48
49
50def run_eval(agent, make_env, tasks, trials=3, max_workers=4):
51 jobs = [t for t in tasks for _ in range(trials)]
52 with ThreadPoolExecutor(max_workers=max_workers) as pool:
53 return list(pool.map(lambda t: run_trial(agent, make_env, t), jobs))
54
55
56def summarize(results):
57 by_task = {}
58 for r in results:
59 by_task.setdefault(r["task"], []).append(r)
60 tasks = {}
61 for name, rs in by_task.items():
62 passes = [r["pass"] for r in rs]
63 tasks[name] = {"pass_rate": sum(passes) / len(passes), "pass_at_k": any(passes), "pass_all_k": all(passes),
64 "check_the_task": not any(passes)}
65 n = len(results)
66 return {
67 "pass_rate": sum(r["pass"] for r in results) / n,
68 "pass_at_k": sum(t["pass_at_k"] for t in tasks.values()) / len(tasks),
69 "pass_all_k": sum(t["pass_all_k"] for t in tasks.values()) / len(tasks),
70 "avg_tool_calls": sum(r["tool_calls"] for r in results) / n,
71 "avg_tokens": sum(r["tokens"] for r in results) / n,
72 "errors": sum(1 for r in results if r["error"]),
73 "unknown_verdicts": sum(1 for r in results if r.get("unknown")),
74 "tasks": tasks,
75 }
76
77
78def regressions(baseline, current, tolerance=0.0):
79 """Tasks whose pass rate fell by more than the tolerance."""
80 return sorted(t for t, b in baseline["tasks"].items()
81 if t in current["tasks"] and current["tasks"][t]["pass_rate"] < b["pass_rate"] - tolerance)What each part does
grade_outcometakes a function that looks at the environment after the run, such as "is there exactly one refund for order 42". It never reads the agent's answer, so an agent cannot pass by claiming success.grade_forbidden_toolfails any trial that called a tool it should not have.grade_with_modelasks a judge model forpass,failorunknown. A reply that is not valid counts as unknown, and not as a pass.run_trialcreates a fresh environment throughmake_env, runs the agent, and applies every grader. A task passes only if all its graders pass. If the agent crashes, that trial is a recorded failure and the eval continues.run_evalruns every tasktrialstimes, in a thread pool.summarizecomputes the numbers in the next section and flags any task that never passed.regressionscompares two summaries and lists tasks whose pass rate fell by more than a tolerance.
The agent you pass in takes a task input and an environment, and returns its answer, a list of the tools it called, and optionally a token count. It can wrap the agent from Testing AI agents, or any other.
The tests
1import json, threading
2from types import SimpleNamespace as NS
3import pytest
4from evals import *
5
6def make_env(): return {"refunds": [], "emails": []}
7
8def good_agent(text, env):
9 env["refunds"].append(text); return {"answer": "Refund issued", "tool_calls": ["lookup", "refund"], "tokens": 100}
10
11tasks = [{"id": "refund", "input": "order 42", "graders": [grade_outcome(lambda e: e["refunds"] == ["order 42"]), grade_forbidden_tool("delete_account")]}]
12
13def test_passes_and_collects_metrics():
14 res = run_eval(good_agent, make_env, tasks, trials=3)
15 assert len(res) == 3 and all(r["pass"] for r in res)
16 s = summarize(res)
17 assert s["pass_rate"] == s["pass_at_k"] == s["pass_all_k"] == 1.0 and s["avg_tool_calls"] == 2 and s["avg_tokens"] == 100 and s["errors"] == 0
18
19def test_environment_is_fresh_for_every_trial():
20 # if trials shared state, the second trial would see two refunds and fail
21 assert all(r["pass"] for r in run_eval(good_agent, make_env, tasks, trials=5, max_workers=1))
22
23def test_grades_the_outcome_not_the_claim():
24 liar = lambda text, env: {"answer": "Refund issued!", "tool_calls": [], "tokens": 1}
25 res = run_eval(liar, make_env, tasks, trials=1)
26 assert res[0]["pass"] is False
27
28def test_forbidden_tool():
29 bad = lambda text, env: (env["refunds"].append(text), {"answer": "ok", "tool_calls": ["delete_account"], "tokens": 1})[1]
30 assert run_eval(bad, make_env, tasks, trials=1)[0]["pass"] is False
31
32def test_agent_crash_is_a_failed_trial_not_a_crashed_eval():
33 boom = lambda text, env: 1 / 0
34 r = run_eval(boom, make_env, tasks, trials=2)
35 assert all(x["error"] == "ZeroDivisionError: division by zero" and not x["pass"] for x in r) and summarize(r)["errors"] == 2
36
37def test_pass_at_k_versus_pass_all_k_and_flagging_broken_tasks():
38 lock, n = threading.Lock(), {"i": 0}
39 def flaky(text, env):
40 with lock: n["i"] += 1; i = n["i"]
41 if i % 4: env["refunds"].append(text) # succeeds 3 times in 4
42 return {"answer": "x", "tool_calls": [], "tokens": 0}
43 s = summarize(run_eval(flaky, make_env, tasks, trials=4, max_workers=1))
44 assert s["pass_rate"] == 0.75 and s["pass_at_k"] == 1.0 and s["pass_all_k"] == 0.0
45 never = lambda text, env: {"answer": "x", "tool_calls": [], "tokens": 0}
46 assert summarize(run_eval(never, make_env, tasks, trials=3))["tasks"]["refund"]["check_the_task"] is True
47 assert round(0.75 ** 3, 2) == 0.42
48
49def test_regressions():
50 base = {"tasks": {"a": {"pass_rate": 1.0}, "b": {"pass_rate": 0.5}, "c": {"pass_rate": 1.0}}}
51 now = {"tasks": {"a": {"pass_rate": 0.6}, "b": {"pass_rate": 0.9}, "c": {"pass_rate": 0.95}}}
52 assert regressions(base, now) == ["a", "c"] and regressions(base, now, tolerance=0.1) == ["a"]
53 assert regressions({"tasks": {"a": {"pass_rate": 1.0}}}, {"tasks": {"a": {"pass_rate": 0.5}}}, tolerance=0.5) == [] # a drop equal to the tolerance is allowed
54
55class C:
56 def __init__(s, text): s.messages = s; s.text = text; s.calls = []
57 def create(s, **k): s.calls.append(k); return NS(content=[NS(text=s.text)])
58run = {"input": "q", "answer": "a", "env": {}, "tool_calls": []}
59
60def test_model_grader():
61 g = grade_with_model(C(json.dumps({"verdict": "pass", "reason": "polite"})), "be polite")
62 assert g(run) == {"pass": True, "unknown": False, "reason": "polite"}
63 assert grade_with_model(C(json.dumps({"verdict": "fail", "reason": "rude"})), "r")(run)["pass"] is False
64 u = grade_with_model(C(json.dumps({"verdict": "unknown", "reason": "cannot tell"})), "r")(run)
65 assert u["pass"] is False and u["unknown"] is True
66 for bad in ["nope", json.dumps({"verdict": "maybe"}), "[]"]:
67 assert grade_with_model(C(bad), "r")(run)["unknown"] is True
68 c = C(json.dumps({"verdict": "pass"})); grade_with_model(c, "be polite")(run)
69 assert "be polite" in c.calls[0]["messages"][0]["content"] and "unknown" in c.calls[0]["system"]
70
71def test_unknown_verdicts_are_counted():
72 c = C(json.dumps({"verdict": "unknown"}))
73 t = [{"id": "t", "input": "q", "graders": [grade_with_model(c, "r")]}]
74 assert summarize(run_eval(good_agent, make_env, t, trials=2))["unknown_verdicts"] == 2The tests use stand-in agents and a stand-in judge, so no API key is needed. I also broke the harness on purpose in five ways to check that the tests notice, and one change, a comparison that was off by one at the boundary, got past the first version of the tests. I added the boundary test at the end of test_regressions, and that change now fails it. That is the value of the exercise: it finds what your tests do not cover.
Numbers that matter

No single number tells the whole story. Collect a few from each family:
- Quality: pass rate, pass@k, pass^k (below).
- Efficiency: tool calls and tokens per task. Many redundant calls can mean a tool returns too little or has pagination problems. Anthropic's tool guide suggests this as a way to spot weak tools.
- Speed: time per tool call and per task.
- Reliability: errors, retries and invalid-parameter errors. A lot of the last kind can mean a tool description is unclear. See Designing tools that work.
- Safety: forbidden tool calls, and actions that needed approval but ran without it.
- Retrieval quality, for a RAG agent: recall@k and whether answers match the sources, as in RAG and vector databases.
pass@k and pass^k
Because a model varies, one run proves little. With k trials of one task:
- pass@k asks whether at least one trial passed. It fits cases where one working solution is enough.
- pass^k asks whether all trials passed. It fits customer-facing agents, where users expect the same good result every time.
Anthropic's example: an agent with a 75 percent success rate per trial passes three in a row only about 42 percent of the time, since 0.75 cubed is about 0.42. The two numbers can be far apart, and which one matters depends on your product. In summarize, pass_at_k and pass_all_k are the share of tasks that passed at least once and every time.
Capability and regression evals
- A capability eval asks "what can this agent do?" It should start with a low pass rate, so there is room to improve.
- A regression eval asks "does it still do what it used to?" It should sit near 100 percent, and a drop is a warning.
regressionsfinds the tasks that dropped.
Tasks that a capability eval has mastered can graduate into the regression suite. Watch for saturation: an eval that always scores near 100 percent no longer tells you whether you are improving, and needs harder tasks.
Read the transcripts
Numbers can lie. Anthropic gives an example where a model scored 42 percent on a benchmark until grading bugs were found, such as rigid grading and ambiguous task descriptions, and after the fixes the score was 95 percent. The agent had not changed. The test had been wrong.
So:
- A task that never passes is suspect. A 0 percent pass rate over many trials usually means the task or the grader is broken, not the agent.
summarizeflags these ascheck_the_task. - Read a sample of transcripts, both passes and failures. A fair failure is one where you can see what the agent got wrong.
- Look for a pass that should not be one, such as an agent that exploited a loophole.
- Fix unfair or vague tasks, and re-run.
Human evaluation
People are slow and costly, so use them where they add the most: building and checking the model grader, reviewing a small random sample every so often, and judging qualities no grader can, such as whether an answer is truly helpful. Real user feedback and A/B tests belong here too. Give reviewers a clear rubric and a way to say "unsure", as you give the model judge.
Tools that help
You can write your own harness, as above, and Anthropic's guide suggests starting simple. Libraries can save time once you know what you need. Two common ones, with names taken from their documentation:
- Ragas is a library for evaluating LLM applications with LLM-driven metrics. Its metric list has a section for retrieval-augmented generation, with metrics such as Context Precision, Context Recall and Faithfulness, and a section for agents and tool use, with metrics such as Tool call Accuracy and Agent Goal Accuracy. You can also write custom metrics.
- DeepEval is an open-source evaluation framework that plugs into pytest. A test builds an
LLMTestCaseand callsassert_testwith one or more metrics. It includesGEval, a model-as-judge metric that you give criteria and a threshold, andTaskCompletionMetric, which scores an agent's whole trajectory. You run tests withdeepeval test run.
Treat these as starting points. Metric names and APIs change, so read the current documentation before you build on them. A library does not remove the need for good tasks, careful graders and reading transcripts.
Mistakes beginners make
- No eval at all, relying on "it seems fine".
- A test set invented at a desk, instead of drawn from real failures.
- One trial per task.
- Reporting only the average, and hiding inconsistency.
- Grading the exact path instead of the outcome.
- Trusting the agent's claim and not checking the state.
- An uncalibrated model judge that is never compared with a person.
- Shared state between trials.
- Never reading a transcript.
- Tuning against the whole test set, with no held-out tasks.
- Believing a 0 percent score without checking the task.
- Running the eval once, not on every meaningful change.
Quick recap
- Tests prove that code works. Evals measure whether the agent is good.
- Start with 20 to 50 realistic tasks from real failures, each unambiguous, solvable and balanced. Keep a held-out set.
- Use code graders first, model graders where needed with an "unknown" option, and people to calibrate.
- Grade the outcome, not the path, and run every trial in a fresh environment.
- Run several trials. pass@k shows whether it can succeed, and pass^k shows whether it always does.
- Track quality, efficiency, speed, reliability and safety together.
- Keep a regression suite, watch for saturation, and read transcripts, because a broken task looks like a failing agent.
- Libraries such as Ragas and DeepEval help, but they do not replace good tasks.
Try it yourself
Pick an agent you have built and write ten tasks for it, drawn from things that went wrong or that you would worry about. Include two tasks where the right action is to do nothing. Give each an outcome grader where you can. Run the harness with three trials, read summarize, and open a few results. Break one grader on purpose so a task never passes, and check that the harness flags it. Then change a prompt, run again, and use regressions to see what got worse.
Next lesson: Observability and tracing.