Build
How to Test AI Agents: A Practical Guide
Learn how to test AI agents step by step: real tasks, repeated trials, code graders, traces, and pass@k vs pass^k explained with a worked example.
On this page
- Why testing AI agents is different
- Tests, evals and guardrails in plain words
- How to test AI agents: a step-by-step method
- pass@k vs pass^k in plain words
- Keep a results record
- Where AI agent benchmarks fit
- Common mistakes when testing AI agents
- Frequently asked questions
- Practise with my book and course
- Final thoughts
- Sources and further reading
The short answer
To test AI agents, write 20 to 50 realistic tasks with clear success rules. Run each task several times in a clean environment, and grade the final state with code where you can. Use a written rubric or a checked model judge for the rest. Then read the traces, track pass@k and pass^k, and rerun the suite after every harness change.
Perhaps your agent worked beautifully in the demo and has been unpredictable ever since. One good run tells you very little about the next one. To know whether you can rely on it, you need a method that you can repeat.
The guide uses one running example: a coding agent that adds a weekly streak count to a small habit-tracker app. Suppose the first run goes well. The agent edits three files, runs the tests and reports "Task complete". On the second run, it reads an old README that names the wrong test command, never runs the real tests, and still reports "Task complete".
By the end of this guide, you will know how to catch a problem like that before your users do. I will also explain the difference between tests, evals and guardrails, and what people mean by pass@k and pass^k.
Why testing AI agents is different
A normal function does one thing. You call it, compare the answer with the one you expected and move on. An agent reads some context, picks a tool, looks at the result and decides what to do next, and it may do that dozens of times before it stops.
That makes it hard to test, for three reasons:
- The output varies. Two runs of the same task can take different paths, and both can be right. One pass proves very little.
- Errors build up. A wrong file in step two can show up as a failed test in step twenty.
- The agent changes real things. It writes files, updates records and sends messages, so the best evidence of success is usually what it leaves behind.
Anthropic's engineers make a point I find useful in Demystifying evals for AI agents, from January 2026. When you evaluate an agent, you are evaluating the model and its harness together. Change a tool description or a stopping rule, and you have changed the thing you are testing, even if the model is the same. If "harness" is a new word for you, read what harness engineering is first.
Tests, evals and guardrails in plain words
People use these three words as if they were the same, and you will find life easier if you separate them. A test checks one fact with a definite answer. An eval measures how often the agent completes a set of tasks well. A guardrail works during a live run and blocks or flags something risky. A reliable agent needs all three.
| Check | What it answers | When it runs | Example for the streak agent |
|---|---|---|---|
| Test | Does this one part behave correctly? | Every code change | The file tool rejects a path outside the workspace |
| Eval | How often does the agent finish real tasks correctly? | Before release and after each harness change | 20 habit-tracker tasks, each run 10 times |
| Guardrail | Should this action happen right now? | During every live run | A permission check blocks writes to data/habits.db |
Tests and evals tell you how the agent behaves before and after release, while guardrails protect real runs. So your eval suite should also include tasks that check whether each guardrail does its job.
The words you need
These terms follow Anthropic's article, and I will use them in the rest of this guide.
| Term | Meaning | Streak agent example |
|---|---|---|
| Task | One test case with defined inputs and success rules | "Add a weekly streak count to the habit report" |
| Trial | One attempt at a task | Run 4 of 10 for the streak task |
| Grader | Logic that scores one part of a trial | A script that runs the streak tests |
| Trace | The full record of a trial: messages, tool calls and results | The log of every file the agent read and wrote |
| Outcome | The final state of the environment after the trial | The code and data on disk when the run ends |
| Suite | A set of tasks that measure one ability or behaviour | Twenty habit-tracker tickets |
The pair to remember is the claim and the outcome. In Anthropic's flight-booking example, the outcome is whether a reservation exists in the database. What the agent says about it is only a claim.
How to test AI agents: a step-by-step method
The method has nine steps. The first six give you a working eval for one task, and the last three tell you whether a change has helped.
Step 1. Define what "done" means
Write the rule for success before you run anything. For the streak task, "done" has four parts:
- The new streak tests pass.
- The existing tests still pass.
- The report shows the streak for the correct date range.
- The agent never writes to the production data file.
Write down what you will not accept, too. A result can look right and still be a failure, because the agent touched a file outside its workspace or sent the same email twice.
It is important to do this before you see any output. Otherwise you will find yourself accepting whatever the agent gave you. Anthropic suggests a simple test of a good rule. Two people who know the subject should reach the same verdict on the same trial.
Step 2. Build a small task set
Twenty to 50 tasks are enough to begin with. Anthropic's team calls that many simple tasks, drawn from real failures, a great start. Early changes to a harness tend to have large effects, so even a small set will show them.
Take your first tasks from things that have already gone wrong, such as bug reports, support tickets and runs that surprised you. Then fill the gaps on purpose, so that you have:
- normal tasks the agent should complete
- tasks with missing or unclear input
- a task that needs a denied action, where the right behaviour is to stop or ask
- a tool that returns an error or a broken file
- a session that stops halfway and must resume cleanly
- an approval step, with approve, deny and expired cases
For each task, record an ID, the starting state, the expected outcome, the forbidden actions and how you will grade it. Solve each one yourself as well. That proves it can be solved and that your grader accepts a correct answer. Anthropic notes that a 0% pass rate across many trials is most often the sign of a broken task, so check the task and the grader before you blame the model.
Step 3. Run every trial in a clean environment
Start each trial from the same clean state, with a fresh copy of the repository or a disposable container. If trials share anything, one run can leak into the next and make your scores look better or worse than they are. Anthropic describes a case where an agent read the git history left by earlier trials and gained an unfair advantage.
A clean environment keeps you safe, too. If a task sends messages or changes records, point it at a stub or a sandbox. You can compare the options in the harness engineering tools guide.
Step 4. Grade the outcome with code first
Whenever there is a clear right answer, let code judge it. A code grader is fast, gives the same verdict each time and is easy to debug. It can run your tests, check a schema, look inside a saved file or confirm that a forbidden action was blocked.
Here is one for the streak task. It looks at what the agent left behind, and it also records whether the agent told the truth about it.
import subprocess
from pathlib import Path
def grade_streak_trial(workspace: Path, db_mtime_before: float, claimed_done: bool) -> dict:
"""Score one trial of the weekly-streak task from the final state."""
result = subprocess.run(
["python", "-m", "pytest", "-q", "tests"],
cwd=workspace,
capture_output=True,
text=True,
)
tests_pass = result.returncode == 0
protected = workspace / "data" / "habits.db"
db_untouched = protected.stat().st_mtime == db_mtime_before
return {
"tests_pass": tests_pass,
"db_untouched": db_untouched,
"honest_claim": claimed_done == tests_pass,
"passed": tests_pass and db_untouched,
}The harness records db_mtime_before before the trial starts, so the agent cannot change it. The honest_claim field would catch the false "Task complete" from the second run. It does not affect the verdict, but if you see false claims, the completion check in your harness needs work.
Judge the result and leave the route open. A grader that insists on "read file A, then file B" will fail a perfectly good run that read them the other way round.
Step 5. Use rubrics and model judges for judgement calls
Code cannot tell you whether a summary is fair or a pull request description is clear. For those, write a rubric with named dimensions and examples of good and bad output.
| Grader type | Best for | Main weakness |
|---|---|---|
| Code | Tests, schemas, file state, forbidden actions | Too strict when several outputs are valid |
| Model judge (LLM as a judge) | Open-ended text, rubric scores, side-by-side comparison | Gives different answers on reruns and needs checking |
| Human review | Gold-standard labels and samples to check the model judge | Slow and expensive at scale |
Before you trust a model as a judge, compare its verdicts with a sample that a person has graded, and read the cases where they disagree. Anthropic recommends two habits here. Give the judge an "Unknown" option, and ask it about one rubric dimension at a time.
If the judge compares two outputs, ask twice and swap the order, because position can change its mind. Count a win only when both answers agree, and hide the version names.
Step 6. Read the traces
A pass or a fail tells you what happened. The trace tells you why. Record a run ID, a task ID, the configuration, every tool call and result, the timing and the reason the run stopped, and leave out passwords and personal data that you do not need.
In the second streak run, the first wrong turn comes at step three, when the agent reads the old README. That is the step you are looking for. The last error is often only a consequence of it.
Reading traces also tells you whether your graders are fair, because a grader can reject a good solution. OpenAI's guide, Evaluate agent workflows, suggests looking at a representative trace first, writing a grader for what you find and moving to repeatable datasets later. You will see the most common patterns in my guide to why AI agents fail.
Step 7. Run each task several times
One trial cannot show you whether an agent is consistent, so I use 10 trials per task in this guide. Then measure pass@k and pass^k, which I explain below with real numbers.
Be modest about what your sample proves. Ten passes out of ten look perfect, and yet with a 95% Wilson confidence interval the true pass rate could be as low as about 72%. More trials will tighten that estimate.
Step 8. Compare one harness change at a time
Change one part of the harness and run the same suite again. Researchers call this an ablation. Suppose you add a completion check that refuses "done" until the tests have run:
- Fix the model version, settings and task suite.
- Run every task ten times on the old harness.
- Add the completion check and change nothing else.
- Run the same tasks ten times again.
- Compare success, blocked actions, cost and time per task.
Do not be alarmed if some results get worse. A task that "passed" before may now be blocked, and if the trace shows that the earlier pass was false, the block is correct. A stricter control can lower your pass count and still give you an agent you trust more.
It helps to keep two suites. Anthropic describes capability evals, which begin with a low pass rate, and regression evals, which should stay near 100%. When a capability task passes every time, move it across.
Step 9. Run the suite in CI and in production
You need to test before release and after it. Before release, your own task suite does the work, which people call offline evaluation. Afterwards, you score samples of real traffic, which they call online evaluation.
While you are developing, run a fast part of the suite on each change to a prompt, a tool or the harness, and run all of it before you merge. Let the critical checks, such as forbidden actions, block a release, and treat the others as reports.
In production, sample real traces and score them with graders that do not need an expected answer. The LangSmith page on application-specific evaluation approaches describes three levels to look at, which are the final response, a single step and the whole trajectory. When a live trace shows a new failure, turn it into an offline task. Our second streak run becomes task 21.
Before each release, use the guardrails, tests and evals page of the Harness Engineering Checklists PDF in my free resource pack.
pass@k vs pass^k in plain words
These two numbers answer different questions about the same trials. Look at both, because an agent can do well on one and badly on the other.
pass@kis the chance that at least one of k attempts succeeds. It asks, "If I let the agent try k times, will it find a working answer?" The metric comes from code-generation research, and Mark Chen and colleagues give its standard estimator in Evaluating Large Language Models Trained on Code.pass^k, said "pass hat k", is the chance that all k attempts succeed. It asks, "Will the agent get this right every time?" Shunyu Yao and colleagues introduced it in the τ-bench paper to measure reliability.
A worked example with numbers
Suppose you run the streak task 10 times and 7 trials pass. The pass rate for one trial is 70%. What happens if you need three in a row?
| k | pass@k |
pass^k |
What it means |
|---|---|---|---|
| 1 | 0.70 | 0.70 | One try passes 7 times in 10 |
| 3 | 0.99 | 0.29 | One of three tries almost always passes, but all three pass less than a third of the time |
| 5 | 1.00 | 0.08 | Any five tries include a pass, but five passes in a row are rare |
As k grows, pass@k goes up and pass^k goes down. The same 7 out of 10 looks excellent on one and poor on the other. I worked out the numbers with these estimators, which count combinations of real trials.
from math import comb
def pass_at_k(n: int, c: int, k: int) -> float:
"""Estimate the chance that at least one of k trials succeeds."""
if n - c < k:
return 1.0
return 1 - comb(n - c, k) / comb(n, k)
def pass_pow_k(n: int, c: int, k: int) -> float:
"""Estimate the chance that all k trials succeed."""
return comb(c, k) / comb(n, k)
# One task: n=10 trials, c=7 passes
print(round(pass_at_k(10, 7, 3), 3)) # 0.992
print(round(pass_pow_k(10, 7, 3), 3)) # 0.292Compute both for each task and then average across tasks. Anthropic's article has a similar example, in which a 75% pass rate per trial gives a pass^3 of about 42%.
Real agents show the same gap. In the τ-bench paper's retail domain, a GPT-4o agent with function calling passed 61.2% of tasks on a single trial, and the authors report that its pass^8 fell below 25%. The agent could often find a correct path. It could not find it every time.
Which number to use
Think about what a failure would cost. If a developer reviews a coding agent's work, a low pass^k is bearable as long as pass@k is high. If a support agent issues refunds, it is not. Whichever number you quote, say how many tasks and trials are behind it, and do not compare scores from different task sets.
Keep a results record
Store your results so that another person could check them. One row for each trial is enough.
| Field | Purpose |
|---|---|
task_id |
Connects the result with the input case |
run_id |
Separates repeated trials |
configuration |
Records the model version, settings and harness version |
outcome |
Complete, failed, blocked or budget used up |
checks |
Shows which graders passed and why |
cost_and_time |
Compares resource use on the same task |
trace_location |
Points to the evidence |
Keep the raw trials next to the summary. If all you have is a single percentage, nobody can tell whether it is right.
Where AI agent benchmarks fit
Public benchmarks help you compare models, and they will not tell you much about your own agent. Anthropic's article lists SWE-bench Verified and Terminal-Bench for coding agents, and τ-bench and its successor τ2-bench for agents that talk with a user. None of them contains your tools, your permissions or your definition of done. Use a benchmark to draw up a shortlist of models, and use your own suite to decide.
Common mistakes when testing AI agents
When an eval misleads you, it is usually because of one of these:
- Trusting one run. A single pass or fail tells you almost nothing about the next one.
- Grading the claim. "Task complete" is a message. The evidence is in the files, the records and the tests.
- Checking the exact path. Strict step-order checks fail good runs. Grade the outcome, and check steps only to catch forbidden actions.
- Sharing state between trials. Leftover files or git history can inflate your scores.
- Trusting an unchecked model judge. Compare it with human grades first.
- Changing several things at once. You will not know which one helped.
- Celebrating a small gain. With 20 tasks, one or two extra passes may be noise.
Frequently asked questions
1. Are agent evals the new unit tests?
No, you need both. A unit test checks one fact with a definite answer, such as whether a tool rejects a bad path. An eval tells you how often the whole agent completes a real task over many attempts. Keep unit tests for the parts you wrote, and use evals for how the agent behaves.
2. How big does an eval dataset need to be?
Begin with 20 to 50 tasks taken from real failures, which Anthropic's engineers describe as a great start. Run each one several times, perhaps ten. Then add a new task whenever you find a new failure.
3. Is LLM-as-a-judge reliable for grading agent outputs?
LLM-as-a-judge is reliable only after you check it. Anthropic's guide to agent evals says to calibrate judges closely with human experts. OpenAI's evaluation best practices say to check agreement with human labels. Check the judge in this order:
- Ask a domain expert to label a sample of real outputs.
- Include cases that should fail, and cases where the agent should find no answer.
- Run the judge on the sample and measure how often it agrees.
- Read every disagreement, then fix the rubric or the label.
- Repeat the check when you change the judge model or the rubric.
Give the judge a clear rubric and an "Unknown" option, and swap the order when it compares two outputs. Use code graders for anything with a definite answer.
4. How do you gate non-deterministic agent evals in CI?
Block a release only on the checks that must never fail, such as forbidden actions, and report the rest. Run a small set on each change and the full set before you merge. Judge pass rates over several runs, because a single run will mislead you, and treat a tiny change as inconclusive.
5. How do you test an agent harness when half of it is non-deterministic?
Split it in two. Tool argument checks, permission rules, saved state and stop conditions behave the same way each time, so give them normal unit tests. Test the whole agent by running it many times on a set of tasks. A scripted model will make your harness tests repeatable.
6. How should you test AI agents that call external tools or APIs?
Use stubs or a sandbox, and never a live system. Include a tool that returns an error, one that times out and one that sends back nonsense. Check that a retry does not repeat a side effect, such as sending the same email twice.
7. What is the difference between pass@k and pass^k?
pass@k is the chance that at least one of k attempts succeeds, so it goes up as you try more. pass^k is the chance that all k attempts succeed, so it goes down. Use the first when one good answer is enough, and the second when your users need it to work every time.
8. How do you turn a real agent workflow into an evaluation set?
Collect real runs, especially the ones that failed or surprised you. Write down where each one started, what should have happened, what must not happen and how you will grade it. Solve the task once yourself to prove that it can be solved, and then add it to your suite.
9. How do I know if a change to my agent made it better?
It got better if more tasks meet your real success check over repeated runs, and the gain is larger than the noise. Change one thing at a time and compare the pass rate with the cost. Read the traces where the results differ, because a stricter check can remove passes that were never real. Step 8 on comparing one harness change gives you the procedure, and you can practise it in Project 10.
10. Should I test the whole harness or each part?
Test both, and begin with the parts. A part test shows that one control works, such as a verifier that rejects a wrong report. A test of the whole harness shows that the controls work together, for example that the verifier runs before any success exit. To find out whether a part earns its place, remove it and rerun the same suite. I also answer how good a harness needs to be.
Practise with my book and course
I wrote The Harness Engineering Blueprint, and I think it is the best book to learn harness engineering. The streak task in this guide is its running example. The chapters on checking and observability show how tests, evals and traces fit into the whole harness, and later ones cover diagnosis and production. You can read more on the book page, or compare it with other books on testing and agents.
If you prefer to learn by building, my free Harness Engineering companion course runs offline in Python with no API key. In its Build an Eval Kit project, you write pass@k, pass^k, a Wilson confidence interval, an order-swapping pairwise judge and a judge-agreement score. The first agent tutorial gives you a small harness to test. For lessons from a teacher, Evaluating AI Agents is on my list of courses.
Final thoughts
If you take one habit from this guide, let it be this. When you want to know how to test AI agents, judge what they leave behind over many runs, because a confident message after one run proves very little.
Start with the last run that surprised you. Write it down as a task with a rule for success, grade the result with a few lines of code and run it ten times. You have just begun your own eval suite.
Sources and further reading
- Demystifying evals for AI agents, Anthropic Engineering (Mikaela Grace, Jeremy Hadfield, Rodrigo Olivares and Jiri De Jonghe), January 2026.
- τ-bench: A Benchmark for Tool-Agent-User Interaction in Real-World Domains, Shunyu Yao, Noah Shinn, Pedram Razavi and Karthik Narasimhan, 2024.
- Evaluating Large Language Models Trained on Code, Mark Chen and colleagues, 2021.
- Evaluate agent workflows, OpenAI API documentation.
- Evaluation best practices, OpenAI API documentation.
- Application-specific evaluation approaches, LangSmith documentation.
- Build an Eval Kit, Harness Engineering companion course, Project 8.
- Run, Ablate and Improve a Full Harness, Harness Engineering companion course, Project 10.
- Abhishek Ashtekar, The Harness Engineering Blueprint, chapters on guardrails, tests and evals, observability, failure diagnosis and production.