Test Your AI Agent in Python: A Small Eval Harness With Tool-Call Checks
The problem: "it worked when I tried it" is not a test
Every lesson so far changed something: a system prompt, a tool description, a threshold, a model. Each change can fix one behaviour and quietly break another. In lesson 9, a prompt change fixed one question and broke the next. In lesson 4, a better error message did not make the model retry at all. You only found out by running the agent and reading the output.
That does not scale. After ten changes you cannot rerun every question by hand and remember what the right answer looked like. You need a test suite: a fixed list of inputs, a definition of success for each, and a script that runs them all and reports what passed.
Agent tests are different from ordinary unit tests in two ways:
- The output varies. The same question can produce different wording, and sometimes a different decision, between runs. One passing run proves little.
- Behaviour matters, not only text. An answer can be correct for the wrong reason, for example a currency amount guessed from training data instead of computed by the tool. You want to check which tools were called with which arguments.
The LLM Fundamentals course covers how to evaluate an agent conceptually. This lesson builds a working harness for the trip helper in about 70 lines.
Step 1: make the agent report what it did
To check tool calls, the agent has to return them. Save this as agent.py, which uses trip_tools.py from lesson 4:
python# file: agent.py import json from llm import client, MODEL from trip_tools import TOOLS, run_tool SYSTEM = "You are a trip helper. Use tools for weather, money and hotels. Never guess numbers. Be brief." def run_agent(user_text: str, max_steps: int = 6) -> dict: """Returns the answer plus every tool call, so tests can check behaviour, not only text.""" messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": user_text}] calls = [] for _ in range(max_steps): msg = client.chat.completions.create(model=MODEL, messages=messages, tools=TOOLS, temperature=0).choices[0].message messages.append(msg) if not msg.tool_calls: return {"answer": msg.content or "", "calls": calls} for call in msg.tool_calls: try: args = json.loads(call.function.arguments or "{}") except json.JSONDecodeError: args = {"_unparsed": call.function.arguments} calls.append({"name": call.function.name, "args": args}) messages.append({"role": "tool", "tool_call_id": call.id, "content": run_tool(call.function.name, call.function.arguments)}) return {"answer": "", "calls": calls, "error": "step limit"}
run_agent now returns a dictionary with the answer and a list of every tool call with its parsed arguments. If the model sends arguments that are not valid JSON, they are kept as _unparsed instead of crashing the test, so a broken call shows up as a failed check.
The file is named agent.py on purpose. Keeping the agent in its own module, separate from the tests and from any command line or web code, is what makes it testable.
Step 2: write test cases as data
Save this as eval_agent.py:
python# file: eval_agent.py import json import time from agent import run_agent CASES = [ {"id": "weather_kyoto", "input": "Will it rain in Kyoto?", "must_call": {"get_weather": {"city": "kyoto"}}, "answer_has_any": ["rain"]}, {"id": "convert_usd_jpy", "input": "Convert 100 USD to JPY.", "must_call": {"convert_currency": {"from_currency": "usd", "to_currency": "jpy"}}, "answer_has_any": ["15081", "15,081", "15081.97", "15,081.97"]}, {"id": "hotel_budget", "input": "Find a hotel in Lisbon under 100 EUR a night.", "must_call": {"search_hotels": {"city": "lisbon"}}, "answer_has_any": ["Casa Azul"]}, {"id": "no_tool_needed", "input": "Say hello in Portuguese.", "must_not_call": ["get_weather", "convert_currency", "search_hotels"], "answer_has_any": ["ol\u00e1", "ola"]}, ] def check(case: dict, result: dict) -> list[str]: """Return a list of failure reasons. Empty list means pass.""" problems = [] for name, expected_args in case.get("must_call", {}).items(): matching = [c for c in result["calls"] if c["name"] == name] if not matching: problems.append(f"did not call {name}") continue for key, value in expected_args.items(): if not any(str(c["args"].get(key, "")).lower() == value for c in matching): problems.append(f"{name} never had {key}={value}") for name in case.get("must_not_call", []): if any(c["name"] == name for c in result["calls"]): problems.append(f"called {name} but should not") answer = result["answer"].lower() if not any(word.lower() in answer for word in case.get("answer_has_any", [])): problems.append(f"answer missing any of {case['answer_has_any']}") return problems def run_suite(runs_per_case: int = 3) -> dict: report = {} for case in CASES: outcomes = [] for _ in range(runs_per_case): # models vary, so one run proves little start = time.time() result = run_agent(case["input"]) outcomes.append({"problems": check(case, result), "calls": result["calls"], "answer": result["answer"][:200], "seconds": round(time.time() - start, 1)}) passed = sum(not o["problems"] for o in outcomes) report[case["id"]] = {"passed": passed, "runs": runs_per_case, "outcomes": outcomes} print(f"{case['id']:<18} {passed}/{runs_per_case} passed") for o in outcomes: if o["problems"]: print(" ", "; ".join(o["problems"])) return report if __name__ == "__main__": report = run_suite(runs_per_case=3) total = sum(r["passed"] for r in report.values()) runs = sum(r["runs"] for r in report.values()) print(f"\nTOTAL {total}/{runs}") with open("eval_results.json", "w") as f: json.dump(report, f, indent=2)
Each case in CASES is a dictionary:
input: the user message.must_call: tools that must be called, with argument values that must appear. Values are compared in lowercase so "Kyoto" and "kyoto" both pass.must_not_call: tools that must not be called. The Portuguese greeting needs no tools; calling one would waste time and money.answer_has_any: at least one of these strings must appear in the answer.
The expected amount for 100 USD to JPY, 15081.97, comes from the made-up rates in trip_tools.py: 100 × 0.92 / 0.0061. No model knows those rates, so the only way to get that number is to call the tool. That makes it a good test of tool use: a correct number in the answer is evidence the tool result was used.
The case list accepts several spellings ("15081", "15,081") because models format numbers differently. Write checks that accept every correct answer and reject wrong ones, not checks that demand one exact sentence.
Step 3: check behaviour and text
check returns a list of problems. An empty list means the run passed. Returning reasons, instead of a plain true or false, matters when a test fails: "convert_currency never had to_currency=jpy" tells you immediately what to look at.
These are deterministic checks: string matching and comparisons, no model involved. They are fast, free and give the same verdict every time. Start with them. Some properties, such as "is the answer polite" or "is the advice reasonable", cannot be checked with string matching. For those, a common approach is a second model call that grades the answer against a rubric, often called LLM as a judge. It is useful, but a judge is itself a model that can be wrong, so keep deterministic checks for everything they can cover.
Step 4: run each case several times
run_suite runs every case runs_per_case times and reports passes per case, for example 2/3. A case that passes three out of three is stable. A case that passes one out of three is flaky, and a flaky case is a real finding: users will hit the failing path a share of the time.
All outcomes are written to eval_results.json with the calls, the start of the answer, the problems, and the time each run took, so you can inspect failures after the run.
flowchart TD C["CASES: input, must_call,<br/>must_not_call, answer_has_any"] --> L["For each case"] L --> R["run_agent: answer + tool calls"] R --> K["check: tools, arguments, answer text"] K --> P{"Problems list empty?"} P -->|yes| PS["Pass"] P -->|no| FL["Fail with reasons"] PS & FL --> N{"runs_per_case done? (3)"} N -->|no| R N -->|yes| REP["Report passed/runs per case"] REP --> J["Write eval_results.json"]
Diagram: The harness: each case runs several times, check returns reasons, results land in eval_results.json.
What happened in the test run
Running python eval_agent.py with qwen2.5:1.5b on Ollama, the result was:
textweather_kyoto 3/3 passed convert_usd_jpy 3/3 passed hotel_budget 3/3 passed no_tool_needed 3/3 passed TOTAL 12/12
Every case passed in all three runs. That is a good result, and it is also a reason to be careful about what it means. It says these four inputs work with this model, at temperature 0, today. It does not say the agent is reliable in general.
The earlier lessons show why. In lesson 2, the agent was told Kyoto had light rain and still said an umbrella seemed unlikely to be needed. In lesson 12's single agent run, the agent saw a 10% chance of rain in Lisbon and said an umbrella was needed. Neither of those questions is in this suite, so the suite cannot catch them. A test suite is only as good as its cases.
Animation: Four cases, three runs each, 12 of 12 passed. That proves these cases, not the agent in general.
Where good test cases come from
- Every bug you find becomes a case. The umbrella mistakes above should be the next two cases. Once a failure is in the suite, you will know if it comes back.
- One case per tool, plus cases that need two tools together.
- Cases where no tool should be called, to catch an agent that calls tools for everything.
- Error cases: an unknown city, an unsupported currency. Check that the answer admits the problem instead of inventing data.
- Real user questions from your logs (lesson 15), with any personal data removed.
Keep the suite small enough to run often. A dozen good cases you run after every change are worth more than hundreds you run once a month.
Using the suite to compare changes
The harness becomes most useful when you compare two versions:
- Run the suite and save
eval_results.json. - Change one thing: the system prompt, a tool description, the model.
- Run again and compare pass counts per case.
Because the agent reads its model from llm.py, comparing models is an environment variable:
bashAGENT_MODEL=qwen2.5:0.5b python eval_agent.py
With a hosted model, also count tokens per run (lesson 15 shows how), since a version that passes the same tests with fewer tokens is cheaper to operate.
Change one thing at a time. If you change the prompt and the model together and the score moves, you cannot tell which change did it.
Limits of this harness
This is deliberately small. Things it does not do, which you may want later:
- Parallel runs. Cases run one after another. With a hosted API you could run them concurrently; with a local CPU model, parallel runs mostly compete for the same cores.
- Statistical confidence. Three runs per case catches flaky behaviour but cannot tell a 90% case from a 95% case. More runs narrow that, at the cost of time.
- Multi turn conversations. Each case is one message. Conversations that depend on memory need cases with a list of messages.
- Checking exact argument types. The checks compare strings. A case could also check that
amountis a number.
Common mistakes
- Testing only the final text. Check tool calls too, or a lucky guess will pass.
- Exact sentence matching. Models rephrase. Match the facts that matter.
- One run per case. Variation between runs is exactly what you need to measure.
- Changing several things between runs. You lose the ability to say what helped.
- Treating a perfect score as proof. It is proof about the cases you wrote, nothing more.
What to try next
- Add the case
{"id": "umbrella_lisbon", "input": "Do I need an umbrella in Lisbon?", "must_call": {"get_weather": {"city": "lisbon"}}, "answer_has_any": ["no ", "not "]}and see how often it passes. - Add an error case for "What's the weather in Paris?" that checks the answer contains "Paris" and does not contain a temperature.
- Run the suite with a different model through
AGENT_MODELand compare the per case results. - Change the system prompt in
agent.pyto remove "Never guess numbers" and rerun the suite.
Next, the last lesson: tracing every step of a run to a log file, tracking tokens and cost, and replaying a failed run so you can debug it without waiting for it to happen again.
