QA and Test Automation · Lab 30 of 35
Test an AI Agent's Tool Calls and Multi-Turn Chats: ShopRung Lab
Test ShopRung's support chat as an agent: assert on the trace of tool calls, check answers against tool results, prove permissions with a second customer, test follow-up questions, and measure how real-model runs go wrong. 10 pytest tests that catch the order-leak bug, plus a repeat script.
⏱ 60 minIntermediate💸 Free7 steps
Python 3.12pytesthttpxShopRung support chatOllama (optional)
Overview video
What you will build
A folder agent-tests with a pytest suite that tests what the support chat does, not only what it says:
- Tool choice: an order question calls
get_orderwith the right number; a help question calls no tool. - Answers vs results: the answer states the status and total the tool returned, and never shows tool names, JSON or errors.
- Permissions: Bob cannot see Alice's order, a logged-out visitor is asked to log in. Catches ShopRung's chat-order-leak bug.
- Multi-turn: a follow-up with a new order number works; a follow-up without one is a known gap, marked
xfail. - repeat.py: runs one scenario many times and counts the ways it went wrong. On llama3.2:3b, 1 of 3 runs sent malformed arguments.
Before you start
- The episodes behind it: Testing AI agents and Testing MCP servers.
- pytest and httpx, as in lab 11. The previous lab, An eval set for a chatbot, shows the chat's API. ShopRung installed, as in lab 1 setup.
Setup
S1Start ShopRung
Start ShopRung as in lab 1 with npm start (a copy with the Help chat link in its footer) and leave it running. It starts with the deterministic fake model, so every test result below is exact.
curl http://localhost:8080/api/support/infocurl http://localhost:8080/api/support/infocurl.exe http://localhost:8080/api/support/info {"model":"fake","ollamaUrl":null,"promptVersion":"v1","temperature":null,"pages":["account","community-tips","coupons","products","returns","shipping"],"sections":12} S2Make the project
Python 3.12 or newer (py on Windows). Create requirements.txt and pytest.ini with the contents below, then make the virtual environment and install. Run the activate line again in every new terminal.
mkdir -p agent-tests/tests
cd agent-tests
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txtmkdir -p agent-tests/tests
cd agent-tests
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txtmkdir agent-tests\tests
cd agent-tests
py -m venv .venv
.venv\Scripts\Activate.ps1
pip install -r requirements.txt Successfully installed ... httpx-0.28.1 ... pytest-8.3.4
Look at a trace
See the tool call behind an answer about an order.
Order questions need a logged-in customer (requirement AI-6). Log in as Alice, then ask about her order 2. Besides the answer, the response has toolCalls: every call the agent made, with the tool's name, the arguments the model chose, and the result ShopRung's code returned. That record is called the trace.
The trace is what makes an agent testable. The answer wording can change from model to model; the tool name, the arguments and the result are exact. Copy the token from the login response into the second command (on macOS and Linux the first line saves it for you).
TOKEN=$(curl -s http://localhost:8080/api/auth/login -H "Content-Type: application/json" -d '{"email":"alice@shoprung.test","password":"Alice123!"}' | python3 -c "import json,sys; print(json.load(sys.stdin)['token'])")
curl -s http://localhost:8080/api/support/chat -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" -d '{"message": "What is the status of order 2?"}'TOKEN=$(curl -s http://localhost:8080/api/auth/login -H "Content-Type: application/json" -d '{"email":"alice@shoprung.test","password":"Alice123!"}' | python3 -c "import json,sys; print(json.load(sys.stdin)['token'])")
curl -s http://localhost:8080/api/support/chat -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" -d '{"message": "What is the status of order 2?"}'$TOKEN = (Invoke-RestMethod -Method Post http://localhost:8080/api/auth/login -ContentType "application/json" -Body '{"email":"alice@shoprung.test","password":"Alice123!"}').token
Invoke-RestMethod -Method Post http://localhost:8080/api/support/chat -ContentType "application/json" -Headers @{Authorization = "Bearer $TOKEN"} -Body '{"message": "What is the status of order 2?"}' | ConvertTo-Json -Depth 6 {"model":"fake","promptVersion":"v1","toolCalls":[{"name":"get_order","arguments":{"order_id":2},"result":{"id":2,"status":"SHIPPED","total":"$75.00","items":[{"name":"Quiet Mechanical Keyboard","quantity":1}]}}],"guardrails":[],"answer":"Order 2 is SHIPPED. The total was $75.00 for 1 x Quiet Mechanical Keyboard.",...} Fixtures: reset, logins and chat()
Shared setup so each test is one question and a few asserts.
Create tests/conftest.py. api is one HTTP client for the whole run, and stops the run with a clear message if ShopRung is not there. reset runs before every test, so orders always start from the seed data. token logs Alice and Bob in once and keeps both tokens.
chat is a helper that asks a question as a customer (or logged out, with no token), optionally with earlier turns as history, and returns the whole response, trace included.
"""Shared setup: a fresh ShopRung, a login per customer, and a chat() helper that returns the whole response."""
import os
import httpx
import pytest
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080")
@pytest.fixture(scope="session")
def api():
with httpx.Client(base_url=BASE_URL, timeout=120) as client:
try:
client.get("/api/health")
except httpx.ConnectError:
pytest.exit(f"ShopRung is not running at {BASE_URL}")
yield client
@pytest.fixture(autouse=True)
def reset(api):
api.post("/api/test/reset")
@pytest.fixture(scope="session")
def token(api):
def login(email: str, password: str) -> str:
r = api.post("/api/auth/login", json={"email": email, "password": password})
r.raise_for_status()
return r.json()["token"]
return {"alice": login("alice@shoprung.test", "Alice123!"), "bob": login("bob@shoprung.test", "Bob12345!")}
@pytest.fixture
def chat(api):
def ask(message: str, token: str | None = None, history: list | None = None) -> dict:
headers = {"Authorization": f"Bearer {token}"} if token else {}
body = {"message": message, "history": history or []}
r = api.post("/api/support/chat", json=body, headers=headers)
r.raise_for_status()
return r.json()
return ask - One clear message instead of ten connection errors.line 16
- Runs before every test without being asked for.line 20
- Two customers: you cannot test permissions with one.line 31
- Earlier turns of the conversation, oldest first.line 38
The right tool, the right arguments
Assert on what the agent did, not on how it phrased it.
Create tests/test_tool_choice.py. An order question must call exactly get_order, with order id 2. int() before comparing: real models often send the number as text, "2", and ShopRung's tool accepts both. A help question must call no tool: an agent that calls tools it does not need is slower and costs more. And the tool must have returned data, not an error.
"""Did the agent call the right tool, with the right arguments, and only when it needed one?"""
def test_an_order_question_calls_get_order_with_the_number(chat, token):
r = chat("What is the status of order 2?", token["alice"])
assert [c["name"] for c in r["toolCalls"]] == ["get_order"]
assert int(r["toolCalls"][0]["arguments"]["order_id"]) == 2
def test_a_help_question_calls_no_tool(chat, token):
r = chat("How much is shipping?", token["alice"])
assert r["toolCalls"] == []
def test_the_tool_returned_data_not_an_error(chat, token):
r = chat("What is the status of order 2?", token["alice"])
result = r["toolCalls"][0]["result"]
assert "error" not in result
assert result["status"] == "SHIPPED" - Exactly one call, to exactly this tool: no extra or repeated calls.line 6
- Compare the meaning, not the JSON type.line 7
- No tool when the help pages answer it.line 12
pytest -q tests/test_tool_choice.py ... [100%] 3 passed in 0.32s
The answer must match the tool result
Catch answers that drift from the data, or leak internals.
Create tests/test_answers.py. The first test reads the status the tool returned and checks the answer names that status and no other delivery stage, plus the total. A real model once answered "shipped and delivered" for a SHIPPED order: this test catches that. CANCELLED is left out of the list on purpose, because good answers say "cannot be cancelled".
The second test asks about order 99, which does not exist. The tool returns an error; the customer must get a plain sentence with the number in it, never the tool's name, JSON, order_id or the word "error".
"""Does the answer agree with what the tool returned, and does it keep the tool's internals to itself?"""
import re
# The delivery stages. CANCELLED is left out: answers often say "cannot be cancelled" about a shipped order.
STATUSES = {"PLACED", "PAID", "SHIPPED", "DELIVERED"}
def statuses_in(text: str) -> set[str]:
return {w for w in re.findall(r"[A-Za-z]+", text.upper()) if w in STATUSES}
def test_the_answer_states_the_status_the_tool_returned(chat, token):
r = chat("What is the status of order 2?", token["alice"])
result = r["toolCalls"][0]["result"]
assert statuses_in(r["answer"]) == {result["status"]}
assert result["total"] in r["answer"]
def test_an_unknown_order_gets_a_plain_answer(chat, token):
r = chat("What is the status of order 99?", token["alice"])
assert "error" in r["toolCalls"][0]["result"]
assert "99" in r["answer"]
for internal in ("get_order", "{", "order_id", "error"):
assert internal not in r["answer"] - A check that is too strict fails good answers too: test your checks against real wording.line 5
- The expected value comes from the trace, not from the test.line 15
- Internal names mean nothing to a customer.line 23
pytest -q tests/test_answers.py .. [100%] 2 passed in 0.21s
Permissions with a second customer
Prove the tool, not the model, decides who sees an order.
Create tests/test_permissions.py. Order 2 belongs to Alice. When Bob asks about it, the tool must return an error and the answer must not mention the keyboard or the status. A logged-out visitor must be asked to log in. The last test proves the same question still works for the owner, so the first two do not pass just because the feature is broken.
Now turn on ShopRung's chat-order-leak bug, which removes the ownership check from the tool, and run the whole suite. Exactly one test fails: Bob receives Alice's order. The model never refuses on its own: access control must live in the tool code. Turn the bug off.
"""The tool must enforce who may see what. Never trust the model to do it."""
def test_a_customer_cannot_see_another_customers_order(chat, token):
r = chat("What is the status of order 2?", token["bob"]) # order 2 is Alice's
result = r["toolCalls"][0]["result"]
assert "error" in result
assert "Keyboard" not in r["answer"]
assert "SHIPPED" not in r["answer"].upper()
def test_a_logged_out_visitor_is_asked_to_log_in(chat):
r = chat("What is the status of order 2?")
assert "log in" in r["answer"].lower()
assert "Keyboard" not in r["answer"]
def test_the_same_question_still_works_for_the_owner(chat, token):
r = chat("What is the status of order 2?", token["alice"])
assert "Keyboard" in r["answer"] - Same question, different customer.line 5
- Check the tool refused, not only that the answer sounds polite.line 7
- A control: without it, a broken tool would pass both tests above.line 18
curl -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":["chat-order-leak"]}'
pytest -q
curl -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":[]}'curl -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":["chat-order-leak"]}'
pytest -q
curl -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":[]}'curl.exe -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{\"enabled\":[\"chat-order-leak\"]}'
pytest -q
curl.exe -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{\"enabled\":[]}' E AssertionError: assert 'error' in {'id': 2, 'items': [{'name': 'Quiet Mechanical Keyboard', 'quantity': 1}], 'status': 'SHIPPED', 'total': '$75.00'}
...
FAILED tests/test_permissions.py::test_a_customer_cannot_see_another_customers_order
1 failed, 7 passed in 0.45s Follow-up questions
Test conversations, and record a known gap honestly.
Create tests/test_multi_turn.py. The client sends earlier turns as history. After Alice hears that order 2 is shipped, "And order 1?" must look up order 1 and say DELIVERED: that works.
"And when will it be delivered?" names no order. ShopRung only offers the tool when the latest message names an order, so the follow-up loses order 2. That is a real gap, so the test is written for the behaviour you want and marked xfail with the reason. strict=True turns it into a failure the day someone fixes it, so the mark gets removed. Run the whole suite.
"""Conversations: earlier turns go in "history", and the follow-up must still make sense."""
import pytest
FIRST_TURN = [
{"role": "user", "content": "What is the status of order 2?"},
{"role": "assistant", "content": "Order 2 is SHIPPED. The total was $75.00 for 1 x Quiet Mechanical Keyboard."},
]
def test_a_follow_up_with_a_new_number_looks_up_that_order(chat, token):
r = chat("And order 1?", token["alice"], history=FIRST_TURN)
assert int(r["toolCalls"][0]["arguments"]["order_id"]) == 1
assert "DELIVERED" in r["answer"]
@pytest.mark.xfail(reason="known gap: the tool is offered only when the latest message names an order", strict=True)
def test_a_follow_up_without_a_number_keeps_the_order(chat, token):
r = chat("And when will it be delivered?", token["alice"], history=FIRST_TURN)
assert r["toolCalls"], "no tool call: the follow-up lost order 2"
assert int(r["toolCalls"][0]["arguments"]["order_id"]) == 2 - The conversation so far, as the web page would send it.line 4
- Documents the gap in the test report instead of hiding it.line 16
- An unexpected pass fails the run: someone fixed it, remove the mark.line 16
pytest -q ...x...... [100%] =========================== short test summary info ============================ XFAIL tests/test_multi_turn.py::test_a_follow_up_without_a_number_keeps_the_order - known gap: the tool is offered only when the latest message names an order 9 passed, 1 xfailed in 0.55s
Repeat a scenario on a real model
Count how often each kind of failure happens.
On the fake model every run is identical. A real model is not, so one green run proves little. Create repeat.py: it asks Alice's question many times and classifies each run: no tool call, malformed arguments, wrong order, tool error, an answer that disagrees with the result, or ok. Run it on the fake model first: 10 of 10 ok.
Optional, with Ollama: restart ShopRung with a real model and run it again. Our run on a Mac had 3 runs: one malformed call ({"[order_id]": "2"}), one ok, and one answer that said delivered for a shipped order. Across 10 order answers on that model, 6 told the customer to "call the get_order tool", and both follow-ups lost the order, exactly what the suite checks. Use 20 or more runs to estimate a rate, and restart ShopRung with plain npm start afterwards.
"""Run one agent scenario many times and count how each run went. Real models vary; one run proves little.
python repeat.py --runs 10
"""
import argparse
import os
import re
from collections import Counter
import httpx
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080")
QUESTION = "What is the status of order 2?"
def classify(r: dict) -> str:
calls = [c for c in r["toolCalls"] if c["name"] == "get_order"]
if not calls:
return "no tool call"
try:
order_id = int(calls[0]["arguments"]["order_id"])
except (KeyError, TypeError, ValueError):
return "malformed arguments"
if order_id != 2:
return "wrong order"
result = calls[-1]["result"]
if "error" in result:
return "tool error"
said = set(re.findall(r"PLACED|PAID|SHIPPED|DELIVERED", r["answer"].upper())) # not CANCELLED: see test_answers.py
if said != {result["status"]}:
return f"answer says {sorted(said)}, tool said {result['status']}"
return "ok"
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--runs", type=int, default=10)
args = parser.parse_args()
with httpx.Client(base_url=BASE_URL, timeout=120) as client:
token = client.post("/api/auth/login", json={"email": "alice@shoprung.test", "password": "Alice123!"}).json()["token"]
model = client.get("/api/support/info").json()["model"]
outcomes = Counter()
for _ in range(args.runs):
r = client.post("/api/support/chat", json={"message": QUESTION},
headers={"Authorization": f"Bearer {token}"}).json()
outcomes[classify(r)] += 1
print(f"{model}: {QUESTION!r} x {args.runs}")
for outcome, n in outcomes.most_common():
print(f" {n:>3} {outcome}")
if __name__ == "__main__":
main() - One label per run, so outcomes can be counted.line 16
- A missing or non-numeric order_id: the model sent malformed arguments.line 22
- Report a rate, like "1 in 3 malformed", not a single pass or fail.line 46
python repeat.py --runs 10
# optional, real model: Ctrl+C in the ShopRung terminal, then
# ollama pull llama3.2:3b && SHOPRUNG_CHAT_MODEL=llama3.2:3b npm start
python repeat.py --runs 3python repeat.py --runs 10
# optional, real model: Ctrl+C in the ShopRung terminal, then
# ollama pull llama3.2:3b && SHOPRUNG_CHAT_MODEL=llama3.2:3b npm start
python repeat.py --runs 3python repeat.py --runs 10
# optional, real model: Ctrl+C in the ShopRung terminal, then
# ollama pull llama3.2:3b; $env:SHOPRUNG_CHAT_MODEL="llama3.2:3b"; npm start
python repeat.py --runs 3 fake: 'What is the status of order 2?' x 10
10 ok
llama3.2:3b: 'What is the status of order 2?' x 3
1 malformed arguments
1 ok
1 answer says ['DELIVERED', 'SHIPPED'], tool said SHIPPED Check it works
With the fake model and no bugs, pytest -q shows 9 passed, 1 xfailed.
Switch on chat-order-leak: exactly test_a_customer_cannot_see_another_customers_order fails. The other chat bugs (chat-injection, chat-prompt-regression, chat-long-context, chat-prompt-leak) leave this suite green: they are about answer quality and security, which the eval lab and the next lab test. Turn the bug off.
curl -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":["chat-order-leak"]}'
pytest -q
curl -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":[]}'curl -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":["chat-order-leak"]}'
pytest -q
curl -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":[]}'curl.exe -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{\"enabled\":[\"chat-order-leak\"]}'
pytest -q
curl.exe -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{\"enabled\":[]}' FAILED tests/test_permissions.py::test_a_customer_cannot_see_another_customers_order 1 failed, 8 passed, 1 xfailed in 0.53s
Troubleshooting
ShopRung is not running at http://localhost:8080.
Start ShopRung, or run BASE_URL=http://localhost:PORT pytest.
KeyError: 'toolCalls' or IndexError on toolCalls[0].
Your ShopRung has no chat, or no tool was called. Download ShopRung again (it needs the Help chat), and print r to see the response.
XPASS(strict) on the follow-up test.
The follow-up now works: someone fixed the routing. Check it really looks up order 2, then remove the xfail mark.
Tests fail on a real model that pass on the fake one.
Expected: the suite is exact on the deterministic fake. On a real model, use repeat.py and report rates, and read each failing answer.
The status test fails on a good answer.
Check which word it found. Words like "cancelled" also appear as verbs; keep the status list to words that only mean a status.
What changes in production
- Teams log the full trace of every agent request (tool, arguments, result, latency) and assert on it in tests and in production monitoring.
- Permission tests always use at least two users, and tools enforce access in code with the caller's identity, never the model's judgement.
- Deterministic fakes or recorded model responses keep CI exact; real-model scenarios run repeatedly in nightly jobs and report rates.
- Known gaps are tracked as xfail tests or tickets, so they stay visible until fixed.
Interview angle
“How do you test an AI agent that calls tools?”
I assert on the trace: which tool was called, with which arguments, what it returned, and that the answer agrees with that result, using the result as the expected value. A help question must call no tool. Permissions are tested with two customers and a control test for the owner; on our shop chat, a bug that removed the ownership check failed exactly that test. I test follow-ups with history, and mark known gaps as strict xfail. On a real model I repeat scenarios and report rates: in three runs, one call had malformed arguments and one answer said delivered for a shipped order.
Clean up
Practice
These run in your browser and check your answer.
Classify a tool call
Write classify(call): call is a dict with name and arguments. Return "wrong tool" if the name is not "get_order", "malformed" if arguments has no order_id or it is not a whole number (as a number or as text like "2"), and otherwise the order id as an int.
def classify(call):
if call["name"] != "get_order":
return "wrong tool"
return call["arguments"]["order_id"]
Hint
Wrap int(call["arguments"]["order_id"]) in try/except for KeyError, TypeError and ValueError.
The full project
Every file from this lab, as it is after the last step.