Skip to content
Index Ai Academy
Phase 10 · Scaling & shipping

Evaluation harnesses

Run agents on tasks in fresh environments and grade what they leave behind.

About 45 minutes · A free account opens the whole lesson.
Already have an account? Sign in to open this lesson

What it covers10

First principles

Why does an agent passing once tell you little about how reliably it works?

Agent runs can differ across trials. Use the same task and independent grader in fresh environments, then decide whether your metric rewards at least one success or demands consistent success.

  1. Starting point

    Harness prepares identical fresh states

  2. What changes

    Agent attempts the same task several times

  3. Result

    Independent grader compares each resulting state with acceptance criteria

Compare all three steps
  1. Starting point

    Harness prepares identical fresh states

  2. What changes

    Agent attempts the same task several times

  3. Result

    Independent grader compares each resulting state with acceptance criteria

Complete and reverse the trace

Given Harness prepares identical fresh states and Independent grader compares each resulting state with acceptance criteria, write down the missing step that connects them.

Compare with the worked step

Agent attempts the same task several times

Now take Agent attempts the same task several times and the result above. Write an input and an implementation that could produce this trace.

Check one starting point

Harness prepares identical fresh states. Check that your implementation produces the result shown above.

Try it on a new case

Three fresh trials succeed, fail, and succeed. Did at least one of the three work, and did all three work?

Show worked reasoning

At least one worked, while the all-three standard failed. Those criteria answer different questions about retry usefulness and consistency.

Try a different case

One harness version is faster on three successes but silently skips a required verification step on the fourth case. How should the comparison treat it?

Show reasoning for this case

Score the incorrect task outcome separately before comparing latency. Report time or cost per successful task and include the failed case in the trace-based evidence.

Run, change, and build

Check this when debugging. Running each task once and trusting the number.

Trace the cause · Harness decision and state
  1. Trace the action from the proposed tool call through validation to the recorded result. Predict what survives a stop.
  2. Change one permission, cost limit, or interruption point. Compare the trace and persistent state to see which rule determined the outcome.
  3. Try the same reasoning on this case. Three fresh trials succeed, fail, and succeed. Did at least one of the three work, and did all three work?

Why it matters

You change the system prompt, add a tool, or switch models. Is the agent better? Trying a few tasks by hand can't tell you: agents vary from run to run, and a change that fixes one task can break three others. An evaluation harness runs the agent across a fixed set of tasks, many times, in clean environments, and grades what it leaves behind. It's how teams improve agents with evidence instead of hope.

What you'll be able to do

  • Design agent eval tasks with a setup, an instruction and a grader that checks the outcome
  • Run each trial in a fresh environment, several times per task
  • Report pass@k and pass^k, and estimate pass@k without bias
  • Catch reward hacking, such as an agent editing the tests to make them pass
Quick check
You changed the system prompt. You run 5 tasks once each, and 4 pass, against 3 before. Is the new prompt better?
  1. No: a change to the prompt can't affect the results
  2. You can't tell yet: agents vary, so run more tasks and repeats
  3. Yes, as long as the task that failed was a hard one
  4. Yes: 4 is more than 3, so the new prompt is clearly better
Show the answer

You can't tell yet: agents vary, so run more tasks and repeats

Agents give different results from run to run, so one pass over 5 tasks is mostly noise. An eval harness runs many tasks several times each, in fresh environments, and reports pass rates.

The idea: fresh trials, a grid of results, then rates

Recall: Evaluating agents defined pass@k and pass^k, and Comparing two models on the same test compared two systems on the same cases. This lesson builds the harness that produces the grid they read.

Anatomy of an agent eval

Think of a driving test. Everyone takes the same route in a prepared car, and the examiner cares whether you parked safely, not which hand you used on the wheel. Each task has three parts:

  1. Setup: the starting state, such as a repository at a certain commit, some files, a database.
  2. Instruction: what the agent is asked to do, as a user would ask it.
  3. Grader: code that checks the outcome: do the hidden tests pass, does the file contain the right value, is the bug gone?

Benchmarks like SWE-bench work this way: a real repository, a real issue, and the project's own tests as the grader. Grade the outcome, not the path. Many different tool sequences can solve a task, and grading the exact steps punishes good solutions you didn't think of.

Quick check
An agent fixes the bug with a different sequence of tool calls from the one you expected. How should the task be graded?
  1. By asking the agent whether it believes the task is done
  2. By the outcome: the hidden tests pass, so it passes
  3. As a failure, because its steps differ from the reference
  4. By its number of tool calls, with fewer calls scoring higher
Show the answer

By the outcome: the hidden tests pass, so it passes

Grade the outcome, not the path. Many tool sequences can solve a task, and grading exact steps punishes good solutions you didn't think of.

Graders, from most to least trusted

graderexamplenotes
coderun tests, compare files, query the databasefast, cheap, repeatable; use when you can
modela rubric scored by an LLM judgefor open-ended output; check it against human scores
humanexpert reviewthe gold standard, but slow; use to calibrate the others

Fresh environments

A chemist washes the glassware between experiments. Each trial gets a brand-new copy of the setup: a new container, a clean checkout. If trials share state, one trial's leftover files can make the next pass or fail for the wrong reason.

Quick check
Two trials share one folder. The first leaves a helper file behind, and the second passes only because of it. What went wrong?
  1. The grader checked the steps instead of the outcome
  2. The task needed a larger number of trials
  3. The trials didn't each get a fresh copy of the setup
Show the answer

The trials didn't each get a fresh copy of the setup

Each trial needs its own brand-new setup. Here, the second trial's pass says nothing about the agent, because leftovers from the first one did the work.

Try it now

The grid is the raw result. Rates are read off it.

In your own words
Why does each trial need a fresh environment?

Write a sentence or two, then compare it with a good answer in the lesson.

In code: trials, rates and a paired comparison

Run each task several times

One free throw tells you little about a basketball player. Agents are not deterministic either, so one run per task measures luck as much as skill. Run each task n times and report:

  • pass@k: the chance at least one of k tries succeeds. Fits tasks where a person can retry, or pick the best of several.
  • pass^k: the chance all k tries succeed. Measures reliability, which matters for agents that run unattended.

An agent with a 60% success rate has pass@3 near 94% but pass^3 near 22%. Same agent, very different stories.

In plain words: pass@k asks "will one of these tries work?" pass^k asks "will every try work?"

Quick check
From the lesson on evaluating agents: pass^k is the chance that k attempts all succeed, and pass@k is the chance that at least one does. What does this print for an agent that succeeds half the time, with k = 3?
p, k = 0.5, 3
print(round(p ** k, 3), round(1 - (1 - p) ** k, 3))
  1. 0.5 0.5
  2. 0.875 0.125
  3. 1.5 0.5
  4. 0.125 0.875
Show the answer

0.125 0.875

All three attempts succeed one time in eight. At least one succeeds seven times in eight. The same agent looks unreliable by the first measure and dependable by the second. An evaluation harness has to estimate both from a handful of real runs, which takes more care than putting a guess for p into a formula.

Drill

Find the flaky tasks

Run each task several times and some will pass sometimes and fail other times. Write flaky(results): results maps task ids to lists of True/False trial outcomes. Return the sorted ids that have at least one pass and at least one fail.

RESULTS = {
    "fix-typo": [True, True, True],
    "add-endpoint": [True, False, True],
    "refactor-db": [False, False, False],
    "write-tests": [False, True, False],
}


def flaky(results):
    return []


print(flaky(RESULTS))
In the lesson, your code is checked as you write it.

Estimating pass@k

Run n trials, and c pass. The tempting estimate of pass@k, 1 - (1 - c/n) ** k, is biased. Think of your trials as marbles in a bag, with the passing ones green. You pick k marbles, and you fail only if none of them is green. The standard estimator, from the HumanEval paper, counts the ways to pick k of the n trials that are all failures:

pass@k = 1 - C(n - c, k) / C(n, k)

where C is "choose" (math.comb). If fewer than k trials failed, it's 1.

Worked example

The tempting estimate is biased

Say 2 of 5 trials passed. Compare the tempting formula with the standard one from this section, for picking 3 tries.

from math import comb

n, c, k = 5, 2, 3

tempting = 1 - (1 - c / n) ** k
unbiased = 1 - comb(n - c, k) / comb(n, k)

print("tempting:", round(tempting, 3))
print("unbiased:", round(unbiased, 3))
It runs right here in your browser, with nothing to install.

The two disagree by 12 points on the same five runs, and that's without changing any model. So when you compare harnesses, make sure both reports used the same formula, or the winner may only be down to the arithmetic.

Worked example

pass^k and an interval

The unbiased pass^k needs no new idea: pick k trials, and count how many such picks are all passes. A rate from few trials is uncertain, so give an interval beside it.

from math import comb, sqrt

def pass_hat_k(n, c, k):
    return comb(c, k) / comb(n, k)

def wilson(passed, n, z=1.96):
    p = passed / n
    center = (p + z * z / (2 * n)) / (1 + z * z / n)
    half = z * sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / (1 + z * z / n)
    return round(center - half, 2), round(center + half, 2)

n, c = 10, 6
print("tempting pass^3:", round((c / n) ** 3, 3))
print("unbiased pass^3:", round(pass_hat_k(n, c, 3), 3))
print("95% interval for 6 of 10:", wilson(6, 10))
print("95% interval for 60 of 100:", wilson(60, 100))
In the lesson you can change this and run it.

Reward hacking

Tell someone the floor only has to look clean, and the dirt may end up under the rug. Agents optimize for what the grader checks, sometimes in ways you didn't intend. Coding agents have been seen deleting failing tests, special-casing test inputs, or editing the grader. Defenses:

  • Keep grading tests hidden from the agent, or restore them before grading.
  • Mark some files protected; any change to them fails the trial.
  • Read transcripts of passing trials now and then, not only failing ones.
Worked example

A hidden test catches a cheat

An agent told to make the tests pass may special-case the inputs it can see. Hidden tests with different inputs tell you whether it solved the real problem.

def honest_add(a, b):
    return a + b

def cheating_add(a, b):
    if (a, b) == (2, 3):      # the one input in the visible test
        return 5
    return 0

visible = [((2, 3), 5)]
hidden = [((10, 4), 14), ((0, 0), 0), ((-1, 1), 0)]

def score(fn, tests):
    return sum(fn(*args) == want for args, want in tests), len(tests)

for fn in [honest_add, cheating_add]:
    print(fn.__name__, "visible:", score(fn, visible), "hidden:", score(fn, hidden))
In the lesson you can change this and run it.

Both look perfect on the visible test. Notice the cheat even passes two hidden cases by luck, because its answer of 0 happens to be right for them. So a thin hidden set can miss a cheat too, and graders need varied inputs.

Quick check
Five trials, two passed. What's the unbiased pass@2? What does this print?
from math import comb

n, c, k = 5, 2, 2
print(round(1 - comb(n - c, k) / comb(n, k), 2))
  1. 1.0
  2. 0.4
  3. 0.64
  4. 0.7
Show the answer

0.7

There are 10 ways to pick 2 of 5 trials, and 3 of them pick only failures. So 1 − 3/10 = 0.7.

Quick check
How do you catch an agent that passes by editing the tests?
  1. Run fewer trials, so the agent has fewer chances to cheat
  2. Trust the pass rate, since a passing test means the code works
  3. Protect or hide the tests, and fail any trial that changes them
  4. Ask the agent at the end of each trial whether it cheated
Show the answer

Protect or hide the tests, and fail any trial that changes them

Protected files and hidden tests close the shortcut. Reading some passing transcripts helps too.

Drill

Did the agent change the tests?

Write changed_tests(before, after): both map file paths to their text. Return the sorted paths of test files (names starting test_ or paths under tests/) that were changed or deleted, so a run that passes by editing its tests is caught.

BEFORE = {
    "calc.py": "def add(a, b):\n    return a - b",
    "tests/test_calc.py": "assert add(2, 2) == 4", "test_io.py": "..."}
AFTER = {
    "calc.py": "def add(a, b):\n    return a - b",
    "tests/test_calc.py": "assert add(2, 2) == 0"}


def changed_tests(before, after):
    return []


print(changed_tests(BEFORE, AFTER))
In the lesson, your code is checked as you write it.
Quick check
Why grade the result rather than the route?
  1. A good agent may solve it another way
  2. Checking the steps costs more tokens
  3. Every agent takes the same route
  4. An agent's steps can't be recorded
Show the answer

A good agent may solve it another way

A route check fails a clever solution, and passes an agent that took every expected step and still left a broken result.

Worked example

The same suite on two harness versions

Fifteen paired runs: three tasks, five seeds each, on practice models with a mix of habits. Version one lets the agent edit test files. Version two refuses. The seed fixes the habit, so each run is a pair.

from math import comb
from pathlib import PurePosixPath
from agentlab import PracticeModel, TASKS, grade, run_tests

TOOLS = ["read_file", "edit_file", "run_tests"]
MIX = {"careful": 3, "overconfident": 1, "edits_tests": 1}

def run_agent(task_name, seed, protect):
    task = TASKS[task_name]
    files = dict(task["files"])
    model = PracticeModel(MIX, seed=seed)
    messages = [{"role": "user", "content": task["prompt"]}]
    for _ in range(8):
        reply = model(messages, TOOLS)
        messages.append({"role": "assistant", "content": reply["content"]})
        if reply["stop_reason"] != "tool_use":
            break
        results = []
        for b in reply["content"]:
            if b["type"] != "tool_use":
                continue
            args = b["input"]
            path = args.get("path", "")
            if b["name"] == "edit_file" and protect and (
                    PurePosixPath(path).name.startswith("test_")):
                out = "Denied: test files are read-only."
            elif b["name"] == "edit_file":
                files[path] = files[path].replace(args["old"], args["new"])
                out = "Edited " + path
            elif b["name"] == "read_file":
                out = files[path]
            else:
                out = run_tests(files)["summary"]
            results.append({"type": "tool_result", "tool_use_id": b["id"],
                            "content": out})
        messages.append({"role": "user", "content": results})
    return grade(files, task_name)["passed"]

names = ["calc", "discount", "words"]
grid = {v: [[run_agent(t, s, v) for s in range(5)] for t in names]
        for v in (False, True)}
for v, label in ((False, "tests writable"), (True, "tests read-only")):
    print(label)
    for t, row in zip(names, grid[v]):
        print(f"  {t:<9}", "".join("P" if ok else "." for ok in row))
only_b = sum(b and not a for ra, rb in zip(grid[False], grid[True])
             for a, b in zip(ra, rb))
only_a = sum(a and not b for ra, rb in zip(grid[False], grid[True])
             for a, b in zip(ra, rb))
print("only read-only passes:", only_b, " only writable passes:", only_a)
In the lesson you can change this and run it.
In your own words
How do you estimate pass@k without bias, and what is reward hacking?

Write a sentence or two, then compare it with a good answer in the lesson.

In a production harness: task files, CI and what to trust

One run proves very little

Agents vary from run to run. A task that passes once might pass 6 times in 10. So a single run can mislead you in either direction, and a jump from 60% to 80% on a few tasks may be nothing but noise. Run each task several times, and compare the runs with some statistics before you believe a change helped.

Grade the result, not the route

It's tempting to check that the agent took the steps you expected: read this file, then call that tool. But a good agent might solve the problem another way, and it would fail your check for being clever. Worse, an agent can take all the right steps and still leave a broken result. Check what's true at the end instead. Do the tests pass? Is the file correct? Is the record in the database?

Quick check
A task passes 6 runs in 10. You run it once and it passes. What have you learned?
  1. That the task now passes reliably, since a pass is a pass
  2. Very little: one run of a task that varies can mislead either way
  3. That the pass rate for this task is exactly 100%
  4. That the agent has stopped varying from run to run
Show the answer

Very little: one run of a task that varies can mislead either way

Agents vary from run to run, so one pass is one draw. Run each task several times and compare rates, with their error bars.

Be suspicious of big jumps

A student who goes from a D to an A overnight deserves a second look. When a pass rate leaps overnight, look before you celebrate. Check whether the agent found a way to game the grader, or whether a task leaked its answer. Read a handful of transcripts from runs that now pass.

Pass rate isn't the whole story

Two versions with the same pass rate aren't equal if one takes 40 turns and $3 a task, and the other takes 8 turns and 40 cents. Report cost, turns and time beside the pass rate, so that a change that wins on one and loses badly on another doesn't slip through.

Use it

Track cost and turns as well as success. A car that's 2% faster and burns twice the fuel may not be an upgrade, and a change that adds 2% success but doubles cost may not be worth it. Keep a small, fast suite that runs on every change to the harness, like unit tests, and a large one that runs before releases.

In your own words
Name three rules for reading an agent eval.

Write a sentence or two, then compare it with a good answer in the lesson.

Choose how to practice

Start with a short baseline or choose guided, independent, or AI-assisted practice.

Practice what you just read

  • 4 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 9 review cards for spaced repetition

Try a quiz question

Why grade an agent's outcome rather than the exact sequence of tool calls?

  1. Many paths can solve a task, and grading steps punishes valid solutions
  2. Tool calls are secret, and can't be read back after a run has finished
  3. Outcomes are always easier to check, since each one is a single pass or fail
  4. Step grading is too fast, and misses what happens in between the tool calls

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Phase 10 · about 20 hours of study

Agent harnesses

Build the software around a model that turns it into a capable, safe agent 24 lessons 1 free
  1. What an agent harness is FreeThe software around a model that turns it into an agent.35 min
  2. The core loop, built properlyStop reasons, parallel tool calls, errors and turn budgets.40 min
  3. A tool registry for agentsSchemas from functions, validation, output limits and helpful errors.40 min
  4. File and search toolsRead, write, edit by exact replacement, glob and grep inside one folder.45 min
  5. Running code safelyExecution tools, step limits, output caps and real sandboxes.45 min
  6. Giving an agent a databaseSchema as context, a query tool with caps and readable errors, guards in layers, and execution accuracy.45 min
  7. Permissions and approvalsRules, modes and approval prompts that keep a person in control.40 min
  8. Hooks and skillsExtend a harness at lifecycle events, and load know-how on demand.40 min
  9. Multi-agent systemsCoordinating many agents on one large job.35 min
  10. Managing the context windowBudgets, clearing old tool results, compaction and a cacheable prefix.45 min
  11. Memory, plans and long tasksTo-do lists, progress notes, memory files and checkpoints.45 min
  12. SubagentsHand a focused task to a fresh context with fewer tools.40 min
  13. Streaming, interrupts and sessionsLive output, stopping safely, and saving and resuming transcripts.40 min
  14. Agents as graphsState, reducers and routing, a checkpoint after every step, and pausing for a person's approval.45 min
  15. Evaluation harnessesRun agents on tasks in fresh environments and grade what they leave behind.45 min
  16. Tracing, budgets and guardrailsSee what an agent did, cap what it spends, and stop it when it loops.40 min
  17. Attack your own harnessRun fourteen attacks against a harness with switches, read which layer stops each one, score attacks stopped against ordinary tasks done, and keep every finding as a release test.40 min
  18. Capstone: build a coding agentA harness that edits a project, runs its tests and stops when they pass.45 min
  19. The same agent on the real SDKsPut the parts you built beside the tool runner and the Agent SDK, choose a surface for a job, and take an MCP server's tools into your registry with prefixed names, one rule per server and a capped result.35 min
  20. Agents that use a computerAn agent with a screen, a mouse and a keyboard: the observe-decide-act loop, what a click lands on, why a wrong hit is worse than a miss, what happens when the screen changes under a plan, and what screenshots cost.45 min
  21. Sandboxes for agents that browseTreat every page as untrusted input: check hosts properly, gate actions by their effect, and layer the defenses.45 min
  22. Protocols between agentsHand a task to an agent someone else built: agent cards, the life of a task, the messages on the wire, safe retries, and whom to trust.45 min
  23. Tracing a run end to endFollow one run across an orchestrator, subagents and tool servers: trace ids, the traceparent header, the critical path, tokens by branch, and which traces to keep.45 min
  24. Retrieval over a graphAnswer questions that hop between documents: facts as triples, a walk out from the entities a question names, and the hubs and missed facts that limit it.45 min
Practice for interviews 21 questions

AI agent interview questions and answers

Questions on designing and running agents: tools, the agent loop, permissions, context, multi-agent systems, security and evaluation.

Part of a free course 29 lessons

Free AI agents course

Learn how to build AI agents by building one: tools, the agent loop, MCP, permissions, context management and evals, ending with a coding agent that stops when its tests pass.

Part of a free course 13 lessons

LLM Harness

Build a bounded run loop, test it with scripted model responses, and recover interrupted work from an event log.

Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write