Evaluating AI Agents: Evals, Graders, Metrics and pass@k

Suraj Kumar

Suraj Kumar

Last updated November 3, 2026·18 min read

AI Agents course · lesson 28 of 36
  1. 1What Is an AI Agent? A Beginner's Guide to How Agents Work
  2. 2How LLMs Work: Tokens, Context Windows and Embeddings for Agent Builders
  3. 3Choosing and Configuring a Model for Your AI Agent
  4. 4The Agent Loop Explained: Perceive, Reason, Act, Observe
  5. 5Workflows or Agents? How to Decide What to Build
  6. 6Build Your First AI Agent From Scratch in Python
  7. 7Function Calling Across Providers: Claude, OpenAI and Gemini
  8. 8Errors, Retries and Rate Limits: Keep Your AI Agent From Crashing
  9. 9How to Write Tool Definitions and Get Structured Output From an AI Agent
  10. 10Designing Tools That Work: How to Make an AI Agent Better by Fixing Its Tools
  11. 11Common AI Agent Tools: Web Search, Code Execution, Databases, APIs and Email
  12. 12Computer Use and Web Browsing Agents: How They Work and When to Avoid Them
  13. 13MCP Explained: The Model Context Protocol for AI Agents
  14. 14Build and Deploy an MCP Server in Python
  15. 15Prompting for Agents: How to Write System Prompts an AI Agent Can Follow
  16. 16Context Engineering for AI Agents: What to Put in the Context Window
  17. 17AI Agent Memory: Short-Term vs Long-Term, and Where Each Lives
  18. 18Maintaining Agent Memory: Updating, Summarizing, Retrieving and Forgetting
  19. 19RAG and Vector Databases Explained: How Agents Search Your Documents
  20. 20Build a RAG Agent in Python That Answers From Your Documents With Citations
  21. 21ReAct and Chain of Thought: How AI Agents Reason and Act
  22. 22Planner-Executor, DAG Agents and Tree of Thought: Planning Architectures Explained
  23. 23Self-Critique and Evaluator-Optimizer: Improve Agent Output with a Review Loop
  24. 24Chaining, Routing and Parallelization: Three Core Workflow Patterns for AI Agents
  25. 25Orchestrator-Workers and Multi-Agent Systems: When to Use More Than One Agent
  26. 26Human-in-the-Loop Agents: Approval Gates, Checkpoints and Safe Oversight
  27. 27Testing AI Agents: Unit Tests, Mocked Models and Handling Non-Determinism
  28. 28Evaluating AI Agents: Evals, Graders, Metrics and pass@k
  29. 29Observability and Tracing for AI Agents: See What Your Agent Did and Why
  30. 30Prompt Injection and Tool Sandboxing: Protect AI Agents from Hostile Input
  31. 31Privacy, Bias and Red Teaming: Responsible Practices for AI Agents
  32. 32Agent Cost and Latency: Make AI Agents Cheaper and Faster Without Losing Quality
  33. 33AI Agent Frameworks Compared: Build Directly or Use LangGraph, CrewAI, the Agents SDKs and More
  34. 34Deploying AI Agents: Hosting, Queues, State, Secrets and Safe Releases
  35. 35Walkthrough: Build a Customer Support Agent with Tools, Approvals, Guardrails and Evals
  36. 36Walkthrough: Build a Research Agent with Parallel Workers, Citations and Source Checking
View full syllabus

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

The eval loop: collect tasks from real failures, run several trials each in a fresh environment, grade the outcomes, read the transcripts, change the agent or the task, and run again, with passing tasks moving into a regression suite

An eval is not something you build once. It is a loop:

  1. Collect tasks, especially from real failures.
  2. Run trials, several per task, each in a clean environment.
  3. Grade each trial.
  4. Read transcripts, to confirm the grades are fair and to see why failures happened.
  5. Change the agent, or fix a broken task.
  6. 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

GraderStrengthWeaknessUse for
CodeFast, cheap, objective, repeatableBrittle to valid variations, weak on subjective workState checks, tool-call checks, exact facts
ModelFlexible, handles nuanceNon-deterministic, costs money, needs calibrationTone, completeness, open-ended answers
HumanThe gold standardSlow and costlyCalibrating 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.

python
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_outcome takes 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_tool fails any trial that called a tool it should not have.
  • grade_with_model asks a judge model for pass, fail or unknown. A reply that is not valid counts as unknown, and not as a pass.
  • run_trial creates a fresh environment through make_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_eval runs every task trials times, in a thread pool.
  • summarize computes the numbers in the next section and flags any task that never passed.
  • regressions compares 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

python
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"] == 2

The 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

Metrics by what they show: quality metrics such as pass rate, pass at k and pass all k; efficiency metrics such as tool calls and tokens; speed such as latency; reliability such as errors and unknown verdicts; and safety such as forbidden tool calls

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. regressions finds 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. summarize flags these as check_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 LLMTestCase and calls assert_test with one or more metrics. It includes GEval, a model-as-judge metric that you give criteria and a threshold, and TaskCompletionMetric, which scores an agent's whole trajectory. You run tests with deepeval 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

  1. No eval at all, relying on "it seems fine".
  2. A test set invented at a desk, instead of drawn from real failures.
  3. One trial per task.
  4. Reporting only the average, and hiding inconsistency.
  5. Grading the exact path instead of the outcome.
  6. Trusting the agent's claim and not checking the state.
  7. An uncalibrated model judge that is never compared with a person.
  8. Shared state between trials.
  9. Never reading a transcript.
  10. Tuning against the whole test set, with no held-out tasks.
  11. Believing a 0 percent score without checking the task.
  12. 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.

Related lessons in other courses