How to Test an AI Agent's Tool Calls with pytest (Without Paying for API Calls)
Chatbots say things. AI agents do things: they check the weather, book meetings, update tickets. So a bug is no longer just a bad sentence. It's a meeting booked on the wrong day, or an API hit in an endless loop. The g
Chatbots say things. AI agents do things: they check the weather, book meetings, update tickets. So a bug is no longer just a bad sentence. It's a meeting booked on the wrong day, or an API hit in an endless loop.
The good news: most of that risk lives in your code around the model, and plain pytest can test it. In this guide you'll build a tiny agent and write 5 tests that run in under a second, with no real LLM and no API cost.
You need Python 3.10+ and pip install pytest pydantic.
What Can Go Wrong in an Agent
An agent runs in a loop: the model picks a tool, your code runs it, the result goes back to the model, repeat until it answers. Four things break most often:
- The model picks the wrong tool
- It sends invalid arguments (like
"next friday"instead of a date) - A tool fails and the agent crashes
- The model never stops calling tools
We'll write one check for each.
Step 1: A Tiny Agent
# agent.py
import json
from dataclasses import dataclass, field
@dataclass
class ToolCall:
name: str
arguments: dict
@dataclass
class LLMResponse:
content: str | None = None
tool_calls: list[ToolCall] = field(default_factory=list)
class MaxStepsExceeded(Exception):
pass
class Agent:
def __init__(self, llm, tools, max_steps=5):
self.llm, self.tools, self.max_steps = llm, tools, max_steps
self.trace = [] # every tool call the agent made
def run(self, user_message):
messages = [{"role": "user", "content": user_message}]
for _ in range(self.max_steps):
response = self.llm.chat(messages)
if not response.tool_calls:
return response.content
for call in response.tool_calls:
self.trace.append(call)
try:
result = self.tools<a href="**call.arguments">call.name</a>
except Exception as exc: # never crash: tell the model
result = {"error": f"{type(exc).__name__}: {exc}"}
messages.append({"role": "tool", "content": json.dumps(result)})
raise MaxStepsExceeded(f"no answer after {self.max_steps} steps")
Two things make it testable: the LLM is passed in (so tests can pass a fake), and self.trace records every tool call.
Step 2: Tools with Pydantic Schemas
# tools.py
from datetime import date
from pydantic import BaseModel
class WeatherArgs(BaseModel):
city: str
class CreateEventArgs(BaseModel):
title: str
day: date # a real ISO date, e.g. "2026-12-11"
def get_weather(city):
return {"city": city, "temp": 31}
def create_event(title, day):
return {"status": "created"}
TOOLS = {"get_weather": get_weather, "create_event": create_event}
ARG_MODELS = {"get_weather": WeatherArgs, "create_event": CreateEventArgs}
Step 3: A Fake LLM
The key trick: instead of a real model, use a fake that replays responses you script and remembers what it was sent. Put this at the top of test_agent.py:
# test_agent.py
import json
import pytest
from pydantic import ValidationError
from agent import Agent, LLMResponse, MaxStepsExceeded, ToolCall
from tools import ARG_MODELS, TOOLS
class FakeLLM:
"""Replays scripted responses and remembers what it was sent."""
def __init__(self, *responses):
self.responses = list(responses)
self.seen = []
def chat(self, messages):
self.seen = list(messages)
return self.responses.pop(0)
def call(name, **args):
return LLMResponse(tool_calls=[ToolCall(name, args)])
def say(text):
return LLMResponse(content=text)
Step 4: The 4 Checks
Check 1: Did it call the right tool? Assert on the full list, so extra calls fail too.
def test_calls_the_right_tool():
agent = Agent(FakeLLM(call("get_weather", city="Pune"), say("31ยฐC in Pune")), TOOLS)
agent.run("Weather in Pune?")
assert [c.name for c in agent.trace] == ["get_weather"]
Check 2: Were the arguments valid? The second test proves the check really catches the classic mistake.
def test_arguments_match_schema():
agent = Agent(FakeLLM(call("create_event", title="Demo", day="2026-12-11"), say("Done")), TOOLS)
agent.run("Add a demo next Friday")
for c in agent.trace:
ARG_MODELS[c.name].model_validate(c.arguments)
def test_schema_catches_bad_date():
with pytest.raises(ValidationError):
ARG_MODELS["create_event"].model_validate({"title": "Demo", "day": "next friday"})
Check 3: Does it survive a tool failure? The error should go back to the model, not crash the app.
def test_tool_error_goes_back_to_model():
def broken(city):
raise TimeoutError("API timed out")
llm = FakeLLM(call("get_weather", city="Pune"), say("Sorry, try again later"))
result = Agent(llm, {"get_weather": broken}).run("Weather in Pune?")
assert "TimeoutError" in json.loads(llm.seen[-1]["content"])["error"]
assert result == "Sorry, try again later"
Check 4: Does it stop? A looping agent can burn hundreds of paid calls in minutes.
def test_stops_after_max_steps():
llm = FakeLLM(*[call("get_weather", city="Pune")] * 10)
agent = Agent(llm, TOOLS, max_steps=3)
with pytest.raises(MaxStepsExceeded):
agent.run("Weather in Pune?")
assert len(agent.trace) == 3
Step 5: Run It
pytest -v
test_agent.py::test_calls_the_right_tool PASSED [ 20%]
test_agent.py::test_arguments_match_schema PASSED [ 40%]
test_agent.py::test_schema_catches_bad_date PASSED [ 60%]
test_agent.py::test_tool_error_goes_back_to_model PASSED [ 80%]
test_agent.py::test_stops_after_max_steps PASSED [100%]
============================== 5 passed in 0.17s ===============================
Fast and free, so run it on every commit.
What About the Real Model?
Fake LLMs test your code. To check that the real model picks the right tools, keep a few live tests behind a marker (@pytest.mark.live) and run them nightly. Assert on behaviour (which tool, valid arguments), never on exact wording, because real models aren't deterministic.
Wrapping Up
Every agent test suite needs four checks: right tool, valid arguments, safe failures, and a stop limit. With a fake LLM, all of them run in milliseconds at zero cost.
Next up: running these tests automatically in GitHub Actions.
How is your team testing AI agents? Let me know in the comments.
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes โ full credit and traffic to the original publisher.