{"slug": "how-to-test-an-ai-agent-s-tool-calls-with-pytest-without-paying-for-api-calls", "title": "How to Test an AI Agent's Tool Calls with pytest (Without Paying for API Calls)", "summary": "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.", "body_md": "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.\n\nThe 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**.\n\nYou need Python 3.10+ and `pip install pytest pydantic`.\n\nAn 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:\n\n`\"next friday\"` instead of a date)\nWe'll write one check for each.\n\n``` python\n# agent.py\nimport json\nfrom dataclasses import dataclass, field\n\n@dataclass\nclass ToolCall:\n    name: str\n    arguments: dict\n\n@dataclass\nclass LLMResponse:\n    content: str | None = None\n    tool_calls: list[ToolCall] = field(default_factory=list)\n\nclass MaxStepsExceeded(Exception):\n    pass\n\nclass Agent:\n    def __init__(self, llm, tools, max_steps=5):\n        self.llm, self.tools, self.max_steps = llm, tools, max_steps\n        self.trace = []  # every tool call the agent made\n\n    def run(self, user_message):\n        messages = [{\"role\": \"user\", \"content\": user_message}]\n        for _ in range(self.max_steps):\n            response = self.llm.chat(messages)\n            if not response.tool_calls:\n                return response.content\n            for call in response.tool_calls:\n                self.trace.append(call)\n                try:\n                    result = self.tools<a href=\"**call.arguments\">call.name</a>\n                except Exception as exc:  # never crash: tell the model\n                    result = {\"error\": f\"{type(exc).__name__}: {exc}\"}\n                messages.append({\"role\": \"tool\", \"content\": json.dumps(result)})\n        raise MaxStepsExceeded(f\"no answer after {self.max_steps} steps\")\n```\n\nTwo things make it testable: the **LLM is passed in** (so tests can pass a fake), and **`self.trace`** records every tool call.\n\n``` python\n# tools.py\nfrom datetime import date\n\nfrom pydantic import BaseModel\n\nclass WeatherArgs(BaseModel):\n    city: str\n\nclass CreateEventArgs(BaseModel):\n    title: str\n    day: date  # a real ISO date, e.g. \"2026-12-11\"\n\ndef get_weather(city):\n    return {\"city\": city, \"temp\": 31}\n\ndef create_event(title, day):\n    return {\"status\": \"created\"}\n\nTOOLS = {\"get_weather\": get_weather, \"create_event\": create_event}\nARG_MODELS = {\"get_weather\": WeatherArgs, \"create_event\": CreateEventArgs}\n```\n\nThe 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`:\n\n``` python\n# test_agent.py\nimport json\n\nimport pytest\nfrom pydantic import ValidationError\n\nfrom agent import Agent, LLMResponse, MaxStepsExceeded, ToolCall\nfrom tools import ARG_MODELS, TOOLS\n\nclass FakeLLM:\n    \"\"\"Replays scripted responses and remembers what it was sent.\"\"\"\n\n    def __init__(self, *responses):\n        self.responses = list(responses)\n        self.seen = []\n\n    def chat(self, messages):\n        self.seen = list(messages)\n        return self.responses.pop(0)\n\ndef call(name, **args):\n    return LLMResponse(tool_calls=[ToolCall(name, args)])\n\ndef say(text):\n    return LLMResponse(content=text)\n```\n\n**Check 1: Did it call the right tool?** Assert on the full list, so extra calls fail too.\n\n``` python\ndef test_calls_the_right_tool():\n    agent = Agent(FakeLLM(call(\"get_weather\", city=\"Pune\"), say(\"31°C in Pune\")), TOOLS)\n    agent.run(\"Weather in Pune?\")\n    assert [c.name for c in agent.trace] == [\"get_weather\"]\n```\n\n**Check 2: Were the arguments valid?** The second test proves the check really catches the classic mistake.\n\n``` python\ndef test_arguments_match_schema():\n    agent = Agent(FakeLLM(call(\"create_event\", title=\"Demo\", day=\"2026-12-11\"), say(\"Done\")), TOOLS)\n    agent.run(\"Add a demo next Friday\")\n    for c in agent.trace:\n        ARG_MODELS[c.name].model_validate(c.arguments)\n\ndef test_schema_catches_bad_date():\n    with pytest.raises(ValidationError):\n        ARG_MODELS[\"create_event\"].model_validate({\"title\": \"Demo\", \"day\": \"next friday\"})\n```\n\n**Check 3: Does it survive a tool failure?** The error should go back to the model, not crash the app.\n\n``` python\ndef test_tool_error_goes_back_to_model():\n    def broken(city):\n        raise TimeoutError(\"API timed out\")\n\n    llm = FakeLLM(call(\"get_weather\", city=\"Pune\"), say(\"Sorry, try again later\"))\n    result = Agent(llm, {\"get_weather\": broken}).run(\"Weather in Pune?\")\n    assert \"TimeoutError\" in json.loads(llm.seen[-1][\"content\"])[\"error\"]\n    assert result == \"Sorry, try again later\"\n```\n\n**Check 4: Does it stop?** A looping agent can burn hundreds of paid calls in minutes.\n\n``` python\ndef test_stops_after_max_steps():\n    llm = FakeLLM(*[call(\"get_weather\", city=\"Pune\")] * 10)\n    agent = Agent(llm, TOOLS, max_steps=3)\n    with pytest.raises(MaxStepsExceeded):\n        agent.run(\"Weather in Pune?\")\n    assert len(agent.trace) == 3\npytest -v\ntest_agent.py::test_calls_the_right_tool PASSED                          [ 20%]\ntest_agent.py::test_arguments_match_schema PASSED                        [ 40%]\ntest_agent.py::test_schema_catches_bad_date PASSED                       [ 60%]\ntest_agent.py::test_tool_error_goes_back_to_model PASSED                 [ 80%]\ntest_agent.py::test_stops_after_max_steps PASSED                         [100%]\n\n============================== 5 passed in 0.17s ===============================\n```\n\nFast and free, so run it on every commit.\n\nFake 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.\n\nEvery 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.\n\nNext up: running these tests automatically in GitHub Actions.\n\n*How is your team testing AI agents? Let me know in the comments.*", "url": "https://wpnews.pro/news/how-to-test-an-ai-agent-s-tool-calls-with-pytest-without-paying-for-api-calls", "canonical_source": "https://dev.to/isha_kumargupta_01fbbf71/how-to-test-an-ai-agents-tool-calls-with-pytest-without-paying-for-api-calls-196m", "published_at": "2026-12-05 10:11:12+00:00", "updated_at": "2026-12-05 10:13:53.050566+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "developer-tools", "large-language-models"], "entities": ["pytest", "Pydantic", "Python"], "also_reported_by": [], "takeaway": "Injecting a scripted FakeLLM and asserting on the agent's recorded tool-call trace lets you catch wrong-tool and invalid-argument bugs in under a second with zero API cost.", "recommendation": {"advice": "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.", "playbook": "evals-testing", "playbook_url": "https://wpnews.pro/playbooks/evals-testing"}, "alternates": {"html": "https://wpnews.pro/news/how-to-test-an-ai-agent-s-tool-calls-with-pytest-without-paying-for-api-calls", "markdown": "https://wpnews.pro/news/how-to-test-an-ai-agent-s-tool-calls-with-pytest-without-paying-for-api-calls.md", "text": "https://wpnews.pro/news/how-to-test-an-ai-agent-s-tool-calls-with-pytest-without-paying-for-api-calls.txt", "jsonld": "https://wpnews.pro/news/how-to-test-an-ai-agent-s-tool-calls-with-pytest-without-paying-for-api-calls.jsonld"}}