Knaph

Testing and Shipping33 of 376 min read

Testing an Agent

Leila changes one sentence in mini's system prompt, to stop it from rewriting whole files when a small change would do. She tries one task, and it works better. Is mini better now? Or did she get lucky on one run, and break something she didn't try?

Changing an agent without a way to measure it is guessing. This lesson is about the two kinds of test that turn the guess into a number.


Leila I'd test it like any program: run it on some tasks and see if they work.

Omid Which part of mini do you want to test?

Leila All of it... but I see what you mean. There's mini's own code, the loop and the tools and the permission checks. And there's what the model decides to do.

Omid Do those need the same kind of test?

Leila The code should do exactly the same thing every time. If a path outside the folder is refused today, it must be refused tomorrow. The model is different: it can do the same task two different ways.

Omid So for the code, what would make the test repeatable?

Leila Take the model out. Give mini a pretend model that always says the same things. That's what all the exercises did, wasn't it? A fake model reading its replies from the input.

Omid Exactly. And for the model's part?

Leila Use the real model, but run each task several times and count how often it works. One run tells me almost nothing.

Omid And who decides whether it worked?

Leila Not the agent's own summary. We learned that one: something that checks the result. The tests in the folder, or whether the file is there.


Unit tests with a fake model

mini talks to the model through one object, client, and only ever calls client.messages.create. Swap that object for a fake one that returns scripted replies, and you can test every line of mini's own code without a key, for free, in a fraction of a second, with the same result every time.

from types import SimpleNamespace as NS
import mini
 
def reply(*blocks, stop="tool_use"):
    usage = NS(input_tokens=1000, output_tokens=50, cache_read_input_tokens=0, cache_creation_input_tokens=0)
    return NS(content=list(blocks), stop_reason=stop, usage=usage)
 
class FakeClient:
    def __init__(self, replies):
        self.messages = self
        self.replies, self.requests = list(replies), []
    def create(self, **request):
        self.requests.append({**request, "messages": list(request["messages"])})
        return self.replies.pop(0)
Python

SimpleNamespace makes small objects with whatever attributes you give it, which is all mini needs: a reply with content, stop_reason and usage, and blocks with type, id, name and input. The fake keeps a copy of every request it was sent (a copy of the messages list, since mini keeps adding to it), so a test can look at exactly what mini would have sent the real model.

Now a test reads like a short story:

def test_a_path_outside_the_folder_is_refused():
    mini.client = FakeClient([
        reply(NS(type="tool_use", id="t1", name="read_file", input={"path": "../secrets.txt"})),
        reply(NS(type="text", text="I can't read that."), stop="end_turn"),
    ])
    answer = mini.run_agent("read ../secrets.txt", ["read_file"], mini.SYSTEM)
    result = mini.client.requests[1]["messages"][-1]["content"][0]
    assert result["is_error"] and "outside the project folder" in result["content"]
    assert answer == "I can't read that."
Python

The first scripted reply asks to read a file outside the project; the second is the model's final answer. The test then checks the second request: the tool result mini sent back must be an error, with the reason. Tests like this cover the turn limit, a max_tokens stop, the hooks, compaction and the subagent's tool list, without spending a cent.

Two kinds of test. A unit test feeds mini scripted replies from a fake model and checks what mini sent and did: no key, same result every time. An eval gives mini and the real model a task in a copy of a project, then runs a check command on the result, five times per task.

Evals with the real model

An eval (short for evaluation) is a set of tasks, each with a starting folder and an automatic check, run with the real model. For mini, a check is just a command that succeeds or fails:

taskstarting foldercheck
"fix the failing test"a project with one broken functionpython -m pytest exits with 0
"add a README with the run command"a project with no READMEgrep -q "python main.py" README.md
"rename every .jpeg to .jpg"a folder of photostest -z "$(ls *.jpeg 2>/dev/null)"

Running one is a loop of its own:

import shutil, subprocess, tempfile
from pathlib import Path
 
mini.check_permission = lambda name, args: None  # say yes to everything: only in a throwaway copy
 
def run_once(task, fixture, check):
    folder = Path(tempfile.mkdtemp())
    shutil.copytree(fixture, folder, dirs_exist_ok=True)
    mini.ROOT = folder
    mini.run_agent(task, list(mini.TOOLS), mini.SYSTEM)
    return subprocess.run(check, shell=True, cwd=folder).returncode == 0
Python

Each run gets a fresh copy of the starting folder, so one run's changes can't help or spoil the next. Permission prompts are switched off, because nobody is there to answer them. That's only acceptable because the copy is thrown away, and even then, a shell command could still reach the rest of the computer. Serious evals run each copy in a container.

Read the numbers, not one run

Run each task several times, five is a fair start, and look at three numbers:

  • Pass rate: how many runs passed. 5 of 5 is solid; 0 of 5 means something is missing (a tool, a permission, an instruction); 3 of 5 means flaky.
  • Cost per pass: a task's total cost divided by its passes. A cheap task that fails half its runs can cost more per finished job than an expensive one that always works.
  • Change between versions: run the same eval before and after a change to the prompt, a tool or the model. That's how Leila finds out whether her new sentence helped, and whether it broke something else.

An eval's results as a grid: three tasks, five runs each. Renaming the photos passes all five, adding a README passes four of five, and fixing the failing test passes two of five, so it is flaky; each task's pass rate is beside it.

Checks should be automatic and exact wherever they can be: tests, file contents, a command's output. Sometimes the result can't be checked by a program ("is this summary accurate?"); then people use a second model call to grade it, with written criteria. That works, but treat a model's grade as more evidence, not proof, and check some by hand.

Try it

Take the fake-model test above, save it with mini as test_mini.py, and run it with pytest (or call the function yourself). Then break mini on purpose: in check_permission, delete the line that checks inside, and run the test again. A test that fails when you break the thing it tests is a test you can trust. The exercise after this lesson writes the report an eval prints.

Using it well

  1. Test the harness without the model. A fake client that replays scripted replies makes mini's own code testable: free, fast and the same every time.
  2. Check results with code, not with the agent's summary. An eval's check is a command or a comparison, never "the agent said it worked".
  3. Run every eval task several times. One run can be luck; a pass rate is a measurement. Flaky tasks are where a change shows up first.
  4. Keep the eval, and run it after every change. The prompt, a tool description, the model, the effort setting: any of them can help one task and hurt another.

Words to know

  • fake model - a stand-in for the model in tests, which returns scripted replies so the harness can be tested without a key, the same way every time
  • eval - a set of tasks with starting states and automatic checks, run with the real model to measure how well an agent does
  • pass rate - the share of an eval task's runs whose check passed
  • flaky - passing on some runs and failing on others

Big idea

An agent is two things to test: code that must behave the same every time, tested with a fake model, and a model that varies, measured with evals. Check results with code, run each task several times, and you can change an agent knowing whether it got better.

Test your understanding

Sign in to test your understanding of this lesson and track your progress.