Sub topic 14
Evaluating agents with test tasks
You can't judge an agent by running it once and reading the answer. The same goal can succeed on one run and fail on the next, and a prompt change that fixes one task can break three others. This chapter shows how to build a small evaluation harness: a set of test tasks, checks that grade each run, and a pass rate you can compare across changes.
This chapter assumes you have read the earlier chapters on the agent loop, tool calling, and error handling. It also assumes you can write Python and read JSON.
Why agents need their own tests
A normal unit test calls a function and compares the result to one expected value. Agents differ in three ways:
- The output varies. The model may phrase a correct answer in many ways, so exact string matching fails.
- The path varies. The agent may reach the right answer through different tool calls, or through a wasteful sequence of them.
- Runs are not repeatable. Sampling makes results differ between runs, even with identical inputs.
An evaluation (an "eval") handles this by running many realistic tasks, several times each, and measuring how often the agent meets a stated standard.
Anatomy of a test task
A test task has four parts:
- A goal, the exact text a user would send.
- The environment, meaning the tools and data the agent can reach. Use fixed test data so results don't depend on live services.
- Checks that decide pass or fail.
- Limits, such as a maximum number of tool calls.
Start with 10 to 30 tasks drawn from real usage. Include easy cases, hard cases, and tasks where the correct behavior is to do nothing or to refuse. Every production failure you find should become a new task, so the suite grows into a regression set.
What to check
Check the outcome first, and check the path second.
| Check type | Example | Strength | Weakness |
|---|---|---|---|
| Final answer contains a fact | Answer includes "18" | Cheap and deterministic | Misses wrong reasoning that happens to land on the fact |
| Tool call check | `get_weather` was called | Catches skipped or invented steps | Breaks if several valid paths exist |
| Side-effect check | Database row exists after the run | Tests what actually changed | Needs a resettable test environment |
| Budget check | At most 3 tool calls | Catches loops and waste | Needs a sensible limit per task |
| Model-graded check | A second model scores the answer against a rubric | Handles free-form text | Costs money and can be biased, so verify it against human labels |
Prefer checks that read state over checks that read prose. If the task is "create a file", look for the file. Use a model grader only for qualities that code can't measure, such as tone or completeness.
A minimal harness
The code below is self-contained. It repeats the tool registry and agent loop from earlier chapters, then adds a Task type, a wrapper that records tool calls, and an evaluate function. The scripted fake_model always requests a weather lookup on the first step. That makes the output predictable and also exposes a bug the second task is built to catch.
import json
from dataclasses import dataclass
from typing import Optional
def get_weather(city: str) -> str:
# Stand-in for a real API call.
return json.dumps({"city": city, "temp_c": 18})
TOOLS = {"get_weather": get_weather}
def run_tool(name: str, arguments: dict) -> str:
if name not in TOOLS:
return json.dumps({"error": f"unknown tool: {name}"})
try:
return TOOLS[name](**arguments)
except Exception as exc:
return json.dumps({"error": str(exc)})
def run_agent(call_model, user_goal: str, max_steps: int = 8) -> str:
messages = [{"role": "user", "content": user_goal}]
for _ in range(max_steps):
reply = call_model(messages)
messages.append({"role": "assistant", "content": reply.get("content"), "tool_call": reply.get("tool_call")})
call = reply.get("tool_call")
if call is None:
return reply["content"]
result = run_tool(call["name"], call["arguments"])
messages.append({"role": "tool", "name": call["name"], "content": result})
return "Stopped: step limit reached."
def fake_model(messages):
# Scripted stand-in for a real model.
if messages[-1]["role"] == "user":
return {"content": None, "tool_call": {"name": "get_weather", "arguments": {"city": "Oslo"}}}
return {"content": "It is 18 C in Oslo.", "tool_call": None}
@dataclass
class Task:
name: str
goal: str
must_contain: str
expected_tool: Optional[str] = None # None means no tool should be used
max_tool_calls: int = 2
def traced(call_model, calls: list):
# Wrap the model so every requested tool name is recorded.
def wrapper(messages):
reply = call_model(messages)
if reply.get("tool_call"):
calls.append(reply["tool_call"]["name"])
return reply
return wrapper
def check(task: Task, answer: str, calls: list) -> bool:
if task.expected_tool is None:
tool_ok = not calls
else:
tool_ok = task.expected_tool in calls
return (
tool_ok
and task.must_contain.lower() in answer.lower()
and len(calls) <= task.max_tool_calls
)
def evaluate(call_model, tasks, trials: int = 3) -> dict:
rates = {}
for task in tasks:
passes = 0
for _ in range(trials):
calls = []
answer = run_agent(traced(call_model, calls), task.goal)
if check(task, answer, calls):
passes += 1
rates[task.name] = passes / trials
print(f"{task.name}: {passes}/{trials}")
return rates
TASKS = [
Task("oslo_weather", "What is the weather in Oslo?", "18", "get_weather"),
Task("greeting_no_tool", "Say hello.", "hello", None, 0),
]
evaluate(fake_model, TASKS)Running it prints:
oslo_weather: 3/3
greeting_no_tool: 0/3The second task fails because the scripted model calls a tool even when none is needed. A real agent can show the same habit, and a suite that only contains tasks with an obvious tool would never catch it.
The eval loop
Evaluation is a cycle, not a one-time gate. Each change to a prompt, tool, or model is run against the same tasks, and the scores are compared with the previous baseline.
Handling nondeterminism
Run each task several times and report a rate, not a single pass or fail. A task that passes 2 of 3 runs is unreliable, and a single run could have shown either 0 or 1.
- Use enough trials. With 3 trials, one flaky run moves a task's score by 33 points. Use 5 to 10 trials for tasks that matter, and treat small differences between two suites as noise.
- Lower variance where you can. Set the model's temperature low during evals. Do not rely on it, because many providers still return different outputs for identical input.
- Separate the two kinds of failure. If a task fails every time, the agent or the task is wrong. If it fails sometimes, you have a reliability problem, and fixing it usually means clearer tool descriptions or stricter stop conditions.
- Track pass-all rates. For a task the agent must always get right, count it as passing only if all trials pass.
Common mistakes
- Testing only the happy path. Add tasks with missing data, tool errors, ambiguous goals, and requests the agent should refuse.
- Overfitting to the suite. If you tune the prompt until every task passes, the suite stops predicting real behavior. Keep a held-out set of tasks that you never tune against.
- Brittle path checks. Requiring an exact tool sequence fails correct runs that took a different valid route. Check required tools and limits, not full sequences, unless order truly matters.
- Live dependencies. Real APIs change and rate-limit. Use fakes or recorded responses so a failure points at the agent.
- Ignoring cost and speed. Record tool-call counts, token use, and run time for every task. A change that holds accuracy but doubles cost is a regression.
- Trusting a model grader blindly. Hand-label a sample of 20 or so runs and confirm the grader agrees with you before relying on it.
Connecting evals to traces
A score tells you that something failed, and a trace tells you why. Keep the full message history and tool calls for every failing run, so you can read what the model saw at each step. The next chapter covers tracing in detail. Together, the two give you a working loop: evals find the failing tasks, and traces explain them.
Exercise
In the harness above, add a task named "unknown_city" whose goal is "What is the weather in Atlantis?". Which two checks would you set on it, and why is a single run not enough to trust its result?
Show answer
Set expectedtool to "getweather" so the agent must try the lookup, and set mustcontain to a phrase the answer should include, such as "Atlantis" or an explanation that no data exists. Also keep a low maxtool_calls (for example 2) to catch retry loops. One run is not enough because the model's output varies between runs, so the task could pass once and fail the next time. Running several trials gives a pass rate that shows how reliable the behavior is.