cd /news/ai-agents/how-to-test-an-ai-agent-s-tool-calls… · home › topics › ai-agents › article
[ARTICLE · art-182362] src=dev.to ↗ pub= topic=ai-agents verified=true sentiment=↑ positive

How to Test an AI Agent's Tool Calls with pytest (Without Paying for API Calls)

A developer published a hands-on guide showing how to test an AI agent's tool calls with pytest using a scripted FakeLLM that replays canned responses, eliminating real LLM calls and API costs. The approach records every tool call in a trace and uses Pydantic argument models to verify tool selection and argument validity, with five tests running in under a second.

recommendation

Replace the real LLM with a scripted fake in tests and assert on the agent's tool-call trace and Pydantic-validated arguments to catch tool-selection and argument bugs without API calls.

more in playbook: Evals and testing for LLM apps
by read4 min views1 publishedDec 5, 2026

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.

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:

"next friday" instead of a date) We'll write one check for each.

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.

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}

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:

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)

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
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.

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.

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.

── more in #ai-agents 4 stories · sorted by recency
── more on @pytest 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/how-to-test-an-ai-ag…] indexed:0 read:4min 2026-12-05 · —