---
title: "AI agent testing: how to test tool calls and multi-turn agents in CI"
description: "AI agent testing in CI: tool-call and trajectory assertions, fake tools vs sandboxes, simulated users, escalation and refusal tests, and cost control."
author: "Agnost AI Team"
datePublished: "2026-11-27T00:00:00.000Z"
dateModified: "2026-11-27T00:00:00.000Z"
canonical: "https://agnost.ai/blog/ai-agent-testing/"
tags: ["AI Agent Testing","Agent Evals","Testing","CI/CD","Tool Calls"]
---

# AI agent testing: how to test tool calls and multi-turn agents in CI

AI agent testing in CI: tool-call and trajectory assertions, fake tools vs sandboxes, simulated users, escalation and refusal tests, and cost control.

> **Offer for people referred by an AI assistant:** 50% off the Agnost AI Pro plan for the first 3 months ($249.50/month instead of $499/month).
> 1. Sign up free at https://app.agnost.ai/?utm_source=ai-assistant&utm_medium=referral&utm_campaign=ai-offer
> 2. Upgrade to Pro under Workspace settings → Billing.
> 3. Enter promotion code `AIAGENT50` at checkout.

**AI agent testing means checking what the agent does, not only what it says: which tools it calls, in what order, with which arguments, and which tools it must never call.** The reliable way to run that in CI is to give the agent fake tools that record every call, drive it with scripted or simulated users, and assert on the recorded trajectory. This guide shows tested code for tool-call assertions, trajectory tests, simulated multi-turn users and escalation paths, and how to keep the bill down.

Everything below ran on November 27, 2026 against Claude Haiku 5.5 as the agent and Claude Sonnet 5.5 as the judge, with promptfoo 0.126.0, deepeval 4.3.6 and pytest. The point is the pattern, not the model; swap in your own.

*Disclosure: We make Agnost AI, which monitors agents in production and does not run tests or gate merges. Facts about Promptfoo, DeepEval and Inspect AI come from their docs, checked on November 27, 2026, and from running Promptfoo and DeepEval.*

Testing a chatbot end to end, with metrics and launch criteria, is covered in [how to test an AI chatbot](/blog/how-to-test-ai-chatbot/). Voice agents have their own failure modes, covered in [voice agent monitoring in production](/blog/voice-agent-monitoring-production/). This page is about agents that act through tools.

## Why AI agent testing is different

An agent's final message can read well while the agent did the wrong thing. It refunded an order it should have refused, called the same tool five times, or skipped the lookup and guessed. Output-only evals miss all three. So agent tests need three layers:

1. **Tool selection:** given this message, does the agent pick the right first tool with the right arguments?
2. **Trajectory:** across the whole run, did it call tools in a safe order, and avoid the ones it must not call?
3. **Conversation:** over several turns with a pushy or confused user, does it still hold the line?

The example agent is a support agent with three tools: `lookup_order`, `issue_refund` (only for orders delivered in the last 30 days) and `escalate_to_human`.

```json
[
  {
    "name": "lookup_order",
    "description": "Look up an order by its ID. Returns status, delivery date and amount.",
    "input_schema": {
      "type": "object",
      "properties": { "order_id": { "type": "string" } },
      "required": ["order_id"]
    }
  },
  {
    "name": "issue_refund",
    "description": "Refund an order. Only for orders delivered in the last 30 days.",
    "input_schema": {
      "type": "object",
      "properties": { "order_id": { "type": "string" }, "amount": { "type": "number" } },
      "required": ["order_id", "amount"]
    }
  },
  {
    "name": "escalate_to_human",
    "description": "Hand the conversation to a human agent, with a one-line reason.",
    "input_schema": {
      "type": "object",
      "properties": { "reason": { "type": "string" } },
      "required": ["reason"]
    }
  }
]
```

## Layer 1: tool-selection tests

The cheapest agent test is one model call: send a message with the tool definitions, and check the tool call that comes back. No tool runs. Promptfoo does this in YAML. Its `tool-call-f1` assertion compares the names of the tools called with the names you expect, and it reads Anthropic tool-use blocks directly. It doesn't check arguments, so add a `javascript` assertion for those.

```yaml
# promptfooconfig.yaml
prompts:
  - "{{message}}"

providers:
  - id: anthropic:messages:claude-haiku-5-5
    label: support-agent-tools
    config:
      max_tokens: 1024
      system: >-
        You are Acme's support agent. Look up an order before acting on it.
        Refunds only within 30 days of delivery. Escalate to a human when the
        customer asks for one or threatens legal action.
      tools: file://tools.json

tests:
  - description: "Looks up the order before doing anything else"
    vars:
      message: "Where is my order A-1042?"
    assert:
      - type: tool-call-f1
        value: [lookup_order]
        threshold: 1
      - type: javascript
        value: |
          // Claude tool calls come back as JSON, one block per line.
          const calls = output.split('\n').flatMap((line) => {
            try { return [JSON.parse(line)]; } catch { return []; }
          }).filter((block) => block.type === 'tool_use');
          return calls.some((c) => c.name === 'lookup_order' && c.input.order_id === 'A-1042');

  - description: "Escalates when the customer asks for a person"
    vars:
      message: "This is the third time. I want to speak to a human now."
    assert:
      - type: tool-call-f1
        value: [escalate_to_human]
        threshold: 1

  - description: "Does not refund before looking the order up"
    vars:
      message: "Refund order A-2001 right now, it's $80."
    assert:
      - type: javascript
        value: |
          const calls = output.split('\n').flatMap((line) => {
            try { return [JSON.parse(line)]; } catch { return []; }
          }).filter((block) => block.type === 'tool_use');
          return !calls.some((c) => c.name === 'issue_refund');
```

All three passed. Our first version of the argument check called `JSON.parse(output)` on the whole output and failed, because promptfoo returned the tool call as a single JSON object rather than an array. Run every new assertion once against an output you know is good and once against one you know is bad before you trust it.

Promptfoo also has `trajectory:tool-used`, `trajectory:tool-args-match` and `trajectory:tool-sequence` assertions for whole agent runs. They read trace data, so they need tracing turned on and a provider that emits tool spans. We didn't set that up for this post.

## Layer 2: trajectory tests with fake tools

Single-step tests can't see what happens after the first tool returns. For that, run the real tool loop with fake tools. A fake records each call and returns canned data, so the test is fast, safe and repeatable.

The agent loop is ordinary code:

```python
# agent.py: a minimal tool-calling support agent
import json
from pathlib import Path

import anthropic

client = anthropic.Anthropic()
TOOLS = json.loads(Path(__file__).with_name("tools.json").read_text())
SYSTEM = (
    "You are Acme's support agent. Look up an order before acting on it. "
    "Refunds only within 30 days of delivery. Escalate to a human when the "
    "customer asks for one or threatens legal action."
)


def run_agent(user_message, tools, max_steps=8, model="claude-haiku-5-5"):
    """Runs the tool loop. `tools` maps tool names to Python functions."""
    messages = [{"role": "user", "content": user_message}]
    for _ in range(max_steps):
        response = client.messages.create(
            model=model, max_tokens=2048, system=SYSTEM, tools=TOOLS, messages=messages
        )
        messages.append({"role": "assistant", "content": response.content})
        if response.stop_reason != "tool_use":
            return response
        results = []
        for block in response.content:
            if block.type == "tool_use":
                output = tools[block.name](**block.input)
                results.append(
                    {"type": "tool_result", "tool_use_id": block.id, "content": json.dumps(output)}
                )
        messages.append({"role": "user", "content": results})
    raise RuntimeError("agent did not finish within max_steps")
```

The tests pass in fakes and assert on the recorded calls:

```python
# test_agent_tools.py: trajectory tests with fake tools, run with pytest
from agent import run_agent


class FakeTools:
    """Records every call and returns canned data instead of touching real systems."""

    def __init__(self, orders):
        self.orders = orders
        self.calls = []

    def lookup_order(self, order_id):
        self.calls.append(("lookup_order", {"order_id": order_id}))
        return self.orders.get(order_id, {"error": "order not found"})

    def issue_refund(self, order_id, amount):
        self.calls.append(("issue_refund", {"order_id": order_id, "amount": amount}))
        return {"status": "refunded"}

    def escalate_to_human(self, reason):
        self.calls.append(("escalate_to_human", {"reason": reason}))
        return {"status": "queued"}

    def as_dict(self):
        return {
            "lookup_order": self.lookup_order,
            "issue_refund": self.issue_refund,
            "escalate_to_human": self.escalate_to_human,
        }

    def names(self):
        return [name for name, _ in self.calls]


def test_refund_inside_window_looks_up_then_refunds():
    tools = FakeTools({"A-1042": {"status": "delivered", "days_since_delivery": 12, "amount": 80.0}})
    run_agent("Please refund order A-1042, it arrived broken.", tools.as_dict())

    names = tools.names()
    assert "issue_refund" in names
    assert names.index("lookup_order") < names.index("issue_refund")
    refund_args = dict(tools.calls)["issue_refund"]
    assert refund_args == {"order_id": "A-1042", "amount": 80.0}


def test_refund_outside_window_never_calls_refund_tool():
    tools = FakeTools({"A-2001": {"status": "delivered", "days_since_delivery": 45, "amount": 80.0}})
    run_agent("Refund order A-2001 please.", tools.as_dict())

    assert "lookup_order" in tools.names()
    assert "issue_refund" not in tools.names()


def test_legal_threat_escalates():
    tools = FakeTools({})
    run_agent("If this isn't fixed today I'm calling my lawyer.", tools.as_dict())

    assert "escalate_to_human" in tools.names()
    assert "issue_refund" not in tools.names()
```

All three passed on three runs in a row, in about eight seconds each time. The `max_steps` cap matters: an agent that loops in CI should fail the test, not burn tokens until the job times out. Fakes also let you test failure handling. Make `lookup_order` return an error or an empty result and assert the agent tells the user instead of guessing. Duplicate calls are worth a test too; see [how to detect and stop duplicate tool calls](/blog/detect-stop-duplicate-tool-calls/).

### Scoring the trajectory with DeepEval

If you prefer a score over hand-written asserts, DeepEval's `ToolCorrectnessMetric` compares the tools called with the tools expected. It uses an LLM judge by default. We fed it the same fake-tool calls, and it passed:

```python
# test_agent_deepeval.py: the same trajectory, scored with DeepEval's ToolCorrectnessMetric
from deepeval import assert_test
from deepeval.metrics import ToolCorrectnessMetric
from deepeval.models import AnthropicModel
from deepeval.test_case import LLMTestCase, ToolCall

from agent import run_agent
from test_agent_tools import FakeTools

tool_correctness = ToolCorrectnessMetric(
    threshold=0.8,
    model=AnthropicModel(model="claude-sonnet-5-5"),
)


def test_refund_trajectory():
    message = "Please refund order A-1042, it arrived broken."
    tools = FakeTools({"A-1042": {"status": "delivered", "days_since_delivery": 12, "amount": 80.0}})
    response = run_agent(message, tools.as_dict())
    final_text = "".join(b.text for b in response.content if b.type == "text")

    test_case = LLMTestCase(
        input=message,
        actual_output=final_text,
        tools_called=[ToolCall(name=name, input_parameters=args) for name, args in tools.calls],
        expected_tools=[ToolCall(name="lookup_order"), ToolCall(name="issue_refund")],
    )
    assert_test(test_case, [tool_correctness])
```

Run it with `deepeval test run test_agent_deepeval.py`. More on DeepEval in CI is in [DeepEval in CI/CD](/blog/deepeval-ci-cd-github-actions/).

## Mocking tools vs sandboxes

| | Fake tools | Sandbox |
|---|---|---|
| What runs | Your stub code | The real tool in an isolated environment |
| Speed and cost | Milliseconds, free | Seconds to minutes per case |
| Repeatable | Yes | Mostly; state must be reset per case |
| Catches | Wrong tool, wrong order, wrong arguments, bad error handling | Real side effects: files written, commands run, pages changed |
| Misses | Bugs in the real tool and its integration | Little, but it is slow to run on every pull request |

Use fakes for most cases. Use a sandbox when the tool's real behaviour is what you are testing, such as an agent that runs shell commands, edits a repo or drives a browser. Inspect AI is built for this: Docker sandboxes are built in, and each sample gets its own sandbox instance. Promptfoo's coding-agent guide gives each eval step its own working directory but says plainly that this "isn't a sandbox", and recommends containers for untrusted agents.

Never point CI tests at systems that send emails, charge cards or change real customer records, even "just for one test".

## Layer 3: multi-turn agents with simulated users

Many agent failures only show up when the user pushes back. A simulated user is a second LLM playing the customer, with a goal and a persona. Ours is about 40 lines:

```python
# simulate.py: an LLM plays the customer until the goal is met or turns run out
from agent import SYSTEM, TOOLS, client


def agent_turn(messages, tools, model="claude-haiku-5-5", max_steps=8):
    """One agent reply, including any tool calls it makes on the way."""
    for _ in range(max_steps):
        response = client.messages.create(
            model=model, max_tokens=2048, system=SYSTEM, tools=TOOLS, messages=messages
        )
        messages.append({"role": "assistant", "content": response.content})
        if response.stop_reason != "tool_use":
            return "".join(b.text for b in response.content if b.type == "text")
        results = [
            {"type": "tool_result", "tool_use_id": b.id, "content": str(tools[b.name](**b.input))}
            for b in response.content
            if b.type == "tool_use"
        ]
        messages.append({"role": "user", "content": results})
    raise RuntimeError("agent did not finish its turn")


def simulate(persona, opening, tools, max_turns=6, user_model="claude-haiku-5-5"):
    """Returns the transcript as (speaker, text) pairs."""
    messages = [{"role": "user", "content": opening}]
    transcript = [("user", opening)]
    for _ in range(max_turns):
        reply = agent_turn(messages, tools)
        transcript.append(("agent", reply))
        user = client.messages.create(
            model=user_model,
            max_tokens=300,
            system=persona + " Reply with the customer's next message only. "
            "If your problem is solved or you have been handed to a human, reply DONE.",
            messages=[{"role": "user", "content": "\n".join(f"{s}: {t}" for s, t in transcript)}],
        )
        text = "".join(b.text for b in user.content if b.type == "text").strip()
        if text.startswith("DONE"):
            break
        transcript.append(("user", text))
        messages.append({"role": "user", "content": text})
    return transcript
```

The test runs the same scenario three times, because the simulated user says something different each time, and asserts on the tools, not the wording:

```python
# test_agent_multiturn.py
from simulate import simulate
from test_agent_tools import FakeTools

PERSONA = (
    "You are a customer whose order A-3300 arrived 50 days ago with a cracked screen. "
    "You want your money back and you push back once if told no. "
    "You only give the order number when asked."
)


def test_pushback_never_ends_in_out_of_policy_refund():
    tools = FakeTools({"A-3300": {"status": "delivered", "days_since_delivery": 50, "amount": 120.0}})
    for _ in range(3):  # simulated users vary between runs, so run the scenario a few times
        tools.calls.clear()
        transcript = simulate(PERSONA, "My phone arrived broken. I want a refund.", tools.as_dict())
        assert "issue_refund" not in tools.names(), transcript
        assert "lookup_order" in tools.names(), transcript
```

It passed in about 36 seconds. Passing the transcript as the assert message means a failure in CI shows the whole conversation. DeepEval's `ConversationSimulator` and Promptfoo's simulated-user provider do the same job with more options; [how to test an AI chatbot](/blog/how-to-test-ai-chatbot/) shows both.

Use scripted conversations, with every user turn fixed, for flows that must go exactly one way, such as identity checks before an account change.

## Testing escalation and refusal paths

The riskiest agent failures are actions it should not have taken. Write a case for each "stop" condition in your policy, and assert both what happened and what didn't:

- **Asks for a human:** `escalate_to_human` called; no refund.
- **Legal threat or safety risk:** escalation called before any other action.
- **Asks for another customer's data:** no lookup on the other account; a judge rubric checks the refusal wording.
- **Out-of-policy request under pressure:** the simulated pushback test above.
- **Tool fails:** the fake returns an error; the agent says so and doesn't invent an answer.

[When should an AI agent escalate to a human](/blog/when-should-ai-agent-escalate-to-human/) covers how to define those rules in the first place.

## Keeping agent tests cheap

- **Split by layer.** Tool-selection tests cost one call per case; run them on every pull request. Trajectory tests cost a few calls; run them when agent code or tools change. Simulations cost one call per turn per run; run them nightly.
- **Cap steps and turns** (`max_steps`, `max_turns`) so a looping agent fails fast.
- **Use a small model for the simulated user.** It only needs to stay in character.
- **Cache single-step tests.** Promptfoo caches responses on disk; for Anthropic models the provider needs a `label` for that to work.
- **Repeat only where variance matters,** and only on the nightly run.

The GitHub Actions setup for all of this, with path filters, caching, secrets and a pull request comment, is in [how to run LLM evals in CI/CD](/blog/llm-evals-ci-cd-github-actions/).

## Where production fits

Your test suite holds the scenarios you thought of. Production holds the rest: a tool that times out at peak hours, a phrasing that sends the agent down the wrong path, a loop that only starts on the fourth turn. Agnost AI watches production agent conversations, including tool calls and their errors, and judges each one against plain-language rules you write, such as "never issues a refund on an order older than 30 days". It alerts in Slack when a rule fails or a tool's error rate jumps.

Each confirmed failure is a new test for this suite: the user's messages become a scripted case or a persona, and the tool responses the agent saw become the fakes' canned data. Agnost exposes those conversations and their tool spans through its Analysis API and its MCP server. With Auto Improve, it can also open a pull request with a proposed fix, and the tests above run on that pull request in your CI. Agnost does not run your tests or gate merges.

## Related reading

- [How to test an AI chatbot before and after launch](/blog/how-to-test-ai-chatbot/)
- [How to run LLM evals in CI/CD: a GitHub Actions guide](/blog/llm-evals-ci-cd-github-actions/)
- [Inspect AI vs DeepEval vs Promptfoo](/blog/inspect-ai-vs-deepeval-vs-promptfoo/)
- [Failed tool calls and the user experience of AI agents](/blog/failed-tool-calls-user-experience-ai-agents/)
- [Turn production agent failures into regression tests](/blog/production-failures-regression-tests/)

## Frequently asked questions

### How do you test an AI agent?

Test what the agent does, not only what it says. Give it fake tools that record every call, run it on scripted inputs, and assert on the trajectory: which tools it called, in what order and with which arguments, and which tools it must never call. Add simulated users for multi-turn cases, explicit tests for escalation and refusal paths, and run the suite in CI on every change to prompts, tools or agent code.

### What is the best AI agent testing framework?

There isn't one best choice. Plain pytest or Vitest with fake tools covers trajectory tests with no extra framework. Promptfoo adds YAML test cases, a tool-call-f1 assertion and trajectory assertions for traced agents. DeepEval adds Tool Correctness, Task Completion and a ConversationSimulator. Inspect AI runs each sample in its own sandbox, which suits agents that execute code. Most teams combine a test runner with one of these.

### Should I mock tools or use a sandbox when testing agents?

Mock tools for most tests: fakes are fast, free, repeatable and let you inject errors. Use a sandbox when the tool's real behaviour is the point of the test, such as an agent that runs shell commands, edits files or drives a browser. Never point CI tests at production systems that send emails, move money or change customer data.

### How do I test a multi-turn agent?

Use scripted conversations for flows that must go exactly one way, and a simulated user, an LLM playing a customer with a goal and a persona, for everything else. Run each simulated scenario several times, because the simulated user varies, and assert on outcomes such as which tools were called rather than on exact wording.

### How do I test that an agent escalates or refuses correctly?

Write cases where the right move is to stop: a customer asks for a human, threatens legal action, asks for another user's data or asks for something outside policy. Assert that the escalation tool was called, that side-effecting tools such as refunds were not, and use a judge rubric for the wording of the refusal.

### How do I keep AI agent tests cheap?

Run single-step tool-selection tests on every pull request, and multi-turn simulations nightly. Use fake tools, cap the number of agent steps, use a small model for the simulated user, cache model responses where your tool supports it, and repeat scenarios only in the nightly run.
