Testing a tool-using chat agent (single agent, mock tools)

Study time
≈ 3 h (estimate)
Needs
L1-M05-L04
Updated
2026-11-06

Progress is saved in this browser only. No account, nothing is sent to a server.

Draft · reviewed by AI, not yet by a person. Content may change. English translation: AI-assisted, not human-reviewed.
On this page

Module: L1-M05 · Duration: ~180 min (estimate, including the independent exercise) · Previous: L04 · Next: Module exercises, then L1-M06

1. Introduction

An agent here is a loop: the model decides which tool to call, the application runs the tool, the model reads the result, and the loop continues over several turns of conversation with the customer. An agent's bugs are usually not in one answer but in the sequence: in which order the tools are called, which turn an argument comes from, whether the context is kept across turns.

This lesson teaches one specific technique: conversation regression. You write a multi-turn conversation script, run it through the agent with fake model replies, record a transcript, review it, and then save it as a golden file. Every time the agent's code changes, you rerun the script and compare. A difference means that the behaviour of the integration has changed.

2. Learning objectives

  1. Distinguish integration tests with fake model replies from evaluating the behaviour of the real model.
  2. Write a multi-turn conversation script for an agent.
  3. Assert the trajectory (the sequence of tools called), the arguments, the answers, the side effects and the conversation state.
  4. Create, review and use a golden transcript to detect regressions.
  5. Explain when a golden file needs to be updated, and why it must never be updated automatically.

3. Prerequisites and tools

  • L03, L04: the tool-use loop, the layers of protection.
  • L1-M02-L05: comparing output between two versions.

4. Concepts

4.1 Two different questions

Question Example How to test Module
Does the application handle everything the model returns correctly? Two tool calls, one bad call, one cut-off turn Fake replies, deterministic This lesson
Does the model choose the right tool and arguments? The customer asks "where is my order"; does the model call lookup_order? The real model, repeated runs, measured rates L1-M06, Level 2

Fake replies do not test the model. They test the code around the model. That is the part you can fix when it is wrong, and the part that should be protected by regression tests at every commit.

Everyday example. A building runs a fire drill with fake smoke on floor 3, following a known script. The drill tests the building's procedure: does the alarm ring, do the exits open, are the wardens in place? It says nothing about how a real fire would spread. Fake replies are fake smoke: they test the application, not the model.

4.2 Where an agent needs to be tested

Point Question Evidence in the lab
Trajectory Which tools are called, in which order? trajectory(transcript)
Arguments Does each call have the right arguments and outcome (ok/invalid/declined/failed)? The tool_calls of each turn
Side effects Which changes to real data have happened? side_effects
State Does a later turn carry the context of the earlier turn? The messages_sent of each request
Protocol Are the results sent back with the right id, in the right format? The tool_results of each request
Answer What does the agent answer, is there an error? answer, error

An example for the "state" point: in turn 2, the customer only says "trả 1 cái" ("return one of them"). The agent understands that this means order SE1003 only if turn 1 is still in the request. A fix "to make requests lighter" that cuts the history breaks this.

Worked example: counting messages_sent in CONV-01. Print how many messages each request sends, turn by turn, from the golden file:

python -c "from lab import conversation as C; g = C.load_golden('CONV-01'); [print(i, [r['messages_sent'] for r in t['requests']], [c[0] for c in t['tool_calls']]) for i, t in enumerate(g['turns'], 1)]"
1 [1, 3] ['lookup_order']
2 [5, 7] ['create_return']
Request messages_sent Where it comes from
Turn 1, request 1 1 The customer's question
Turn 1, request 2 3 + assistant (lookup_order's tool_use) + user (tool_result)
Turn 2, request 1 5 + assistant "Đơn SE1003 đã giao." + the customer's new message
Turn 2, request 2 7 + assistant (create_return's tool_use) + user (tool_result)

Each step adds exactly 2. The "forgetful" agent in section 8.1 sends 1 instead of 5 in turn 2; an agent that forgets to store its own final answer would send 4. Both are state regressions, and both show up in this column. Output run on 2026-11-06 on Python 3.14.6 and 3.12.3, Linux, identical on both versions; so is every other output in this lesson.

4.3 Golden transcripts

A golden file is output that has been reviewed by a person and accepted as correct. It is an oracle (L1-M04-L01). Three rules:

  1. Store only stable values. No timestamps, no message ids, no request ids. Otherwise the golden file changes on every run and nobody reads the diff any more.
  2. Review before saving. Saving a wrong transcript as a golden file means protecting a bug. The command python -m lab.conversation record prints the transcript first, and saves only with --save.
  3. When a diff appears, ask before updating: is this a regression or an intended change? Update the golden file only when the change has been agreed, and write the reason in the commit.

Everyday example. A paint shop mixes paint for a customer against a colour sample the customer approved. Every new batch is compared with that sample. If a batch is off, the mixer may not replace the sample with the new batch "so it matches": the customer must be asked. A golden file is the colour sample; updating it is the approver's decision, not the mixer's.

4.4 Strict or loose assertions

With fake replies, the trajectory is fixed, so an exact assertion (== ["lookup_order", "create_return"]) is reasonable. With the real model, the trajectory can differ between runs and still be right. In that case, assert properties instead of the exact sequence, for example: "no create_return without approval", "lookup_order is called before answering about an order's status". L1-M06 continues this topic.

Good vs bad: assertions for the "customer does not approve" script (CONV-02).

# Weak: the trajectory alone
assert C.trajectory(t) == ["create_return"]

# Good: the consequence, then everything the reviewer accepted
assert t["side_effects"] == []
assert C.compare(t, C.load_golden("CONV-02")) == []

Worked example: why the trajectory alone is not enough. Run CONV-02 with an agent that always approves (a real regression: it ignores the customer's answer). Save this as try_l05_approve.py in the lab folder and run python try_l05_approve.py:

import os
os.environ["ANTHROPIC_API_KEY"] = "sk-test-fake-key-0000"     # fake key: the fake API only

from lab import conversation as C
from lab.agent import OrderAgent

script = C.load_script(C.DATA / "conversations" / "CONV-02.json")
always_yes = C.run_script(script, lambda c, b, a: OrderAgent(c, b, approve=lambda name, args: True))
print("trajectory:", C.trajectory(always_yes))
for diff in C.compare(always_yes, C.load_golden("CONV-02")):
    print("  ", diff)
trajectory: ['create_return']
   turn 1 tool_calls: got [['create_return', {'order_id': 'SE1003', 'reason': 'changed_mind', 'quantity': 2}, 'ok']], golden [['create_return', {'order_id': 'SE1003', 'reason': 'changed_mind', 'quantity': 2}, 'declined']]
   turn 1 requests: got [{'messages_sent': 1, 'tool_results': []}, {'messages_sent': 3, 'tool_results': [['toolu_c2a', False]]}], golden [{'messages_sent': 1, 'tool_results': []}, {'messages_sent': 3, 'tool_results': [['toolu_c2a', True]]}]
   side_effects: got [['create_return', {'order_id': 'SE1003', 'reason': 'changed_mind', 'quantity': 2}]], golden []

The trajectory is still exactly ['create_return'], so the weak assertion stays green. The golden file reports three differences: outcome ok instead of declined, the tool_result's is_error turned False, and a side effect nobody approved. Delete the file when you are done.

5. Technical deep dive

5.1 Scripts (data/conversations/*.json)

{"id": "CONV-02", "approvals": [false],
 "turns": [{"user": "Tôi muốn trả 2 sản phẩm của đơn SE1003, tôi đổi ý.",
            "model": [{"tool_uses": [{"name": "create_return", "input": {...}, "id": "toolu_c2a"}]},
                      {"text": "Mình chưa tạo yêu cầu trả hàng vì bạn chưa xác nhận."}]}]}

In English: the user says they want to return two items of the order because they have changed their mind; the model's text reply says the return request has not been created because the customer has not confirmed.

  • model lists the fake replies for that turn, in request order.
  • approvals are the customer's answers to each approval request, in order.
  • tool_failures makes a tool fail (CONV-04).
  • load_script() rejects a script without an id, with no turns, or with a turn that has no reply (fail closed).

5.2 run_script() and compare()

run_script(script, make_agent) runs every turn with one fake API for the whole script, clears the unused fake replies after each turn (so that they do not "leak" into the next turn), and returns the transcript. compare(transcript, golden) returns a readable list of differences, empty if there is no regression.

make_agent is a function that creates an agent. This lets the same script run with the reference agent, with v2 of the module exercises, or with an agent that has been broken on purpose to prove that the golden file catches the bug.

5.3 The Python you need for this lesson

  • Functions that take functions: run_script(script, lambda c, b, a: OrderAgent(c, b, approve=a)). run_script creates the client and the backend itself, then calls your function to get an agent.
  • class Forgetful(OrderAgent) overrides send and calls super().send(...) to reuse the rest.

6. The QA perspective

  • A minimal script set for an agent: a successful multi-turn flow; an action whose approval is declined; a wrong argument that the model corrects; a tool error; a cut-off turn; a turn that depends on the context of the previous turn.
  • Prove that the oracle works: for each kind of regression you care about, have an agent broken on purpose that makes compare() report a difference (for example Forgetful, an auto-approving agent).
  • What can go wrong: a golden file containing values that change on every run; updating a golden file without a review; scripts with only one turn; treating fake scripts as evidence about the model.
  • How to report a regression: the script id, the turn, the field that differs, the values before and after, and the commit that caused the difference.

7. Real-world scenarios

Scenario 1 (fictional): a cost optimisation loses the context. A team cuts the history down to 4 messages to save tokens. Every single-turn test is still green. The customer says "I want to return the second one" in turn 3 and the agent asks back "which order?". A three-turn script with a golden file would have reported the change in messages_sent at that very commit.

Scenario 2 (fictional): a golden file "updated to make it green". After a change, CI reports a diff in the approval script. Someone runs the command that updates the golden file without reading the diff. From then on, the golden file "protects" the behaviour of approving return orders automatically. The lesson: updating a golden file is a review decision, not a way to make CI green.

8. Hands-on tutorial

8.1 Running the demo

python -m lab.demo l05

Output (copied from a real run, 2026-10-31):

CONV-01: trajectory=['lookup_order', 'create_return'] side_effects=1 -> MATCH
CONV-02: trajectory=['create_return'] side_effects=0 -> MATCH
CONV-03: trajectory=['create_return', 'create_return'] side_effects=1 -> MATCH
CONV-04: trajectory=['lookup_order', 'handoff_to_human'] side_effects=0 -> MATCH
forgetful agent, CONV-01:
   turn 2 requests: got [{'messages_sent': 1, 'tool_results': []}, {'messages_sent': 3, 'tool_results': [['toolu_c1b', False]]}], golden [{'messages_sent': 5, 'tool_results': []}, {'messages_sent': 7, 'tool_results': [['toolu_c1b', False]]}]

The four scripts match their golden files. The "forgetful" agent makes turn 2 of CONV-01 send only 1 message instead of 5: turn 1 has been lost.

8.2 Recording the transcript of a script

python -m lab.conversation record data/conversations/CONV-02.json

The command runs offline with a fake API key and prints the transcript. Add --save to save it as the golden file after you have read it and agree with it.

8.3 Running the tests

python -m pytest tests/test_l05_conversation.py -v

The two test_golden_comparison_catches_... tests prove that the golden file catches two kinds of regression.

8.4 Troubleshooting

Symptom Cause Fix
FileNotFoundError: no golden file The golden file has not been saved yet record, read the transcript, then record ... --save
ValueError: every turn needs at least one scripted model reply A turn lacks model Add at least one fake reply
A turn's answer is Hello! (the fake's default reply) The earlier turn has fewer replies than the number of requests the agent sends Count the requests: each tool call needs one more reply
compare() reports a difference in turn N user (or answer) even though nothing was changed The script was typed with a composing input method and the text is in NFD form (L1-M04-L02): save_golden stores NFC, while run_script keeps the script text as it is Save the script file in NFC form
UnicodeEncodeError when saving output to a file on Windows The console uses an old encoding record prints JSON in escaped form (\u...); if it still fails, run set PYTHONUTF8=1 first

9. Independent exercise

Problem: Write a regression script for a three-turn flow: look up an order, the customer declines the return, then the customer agrees.

Requirements:

  1. Write exercises/CONV-05.json (id CONV-05) with at least 3 turns and approvals containing both false and true.
  2. Run python -m lab.conversation record exercises/CONV-05.json, read the transcript, check it against the contract A1-A10, then save it with --save. The command always runs the reference agent (lab/agent.py).
  3. Fill in EXPECTED_TRAJECTORY in exercises/test_l05_my_conversation.py and run the test.
  4. Prove that your golden file catches a regression: write a broken agent (for example one that always approves) and show that compare() reports a difference.

Test data: ORDERS in lab/tools.py.

Deliverable: the script, the golden file, the test file, and the output of step 4.

Acceptance criteria: the test passes; the transcript has exactly one side effect; step 4 shows at least one difference in side_effects.

Hint: after the customer declines, the (fake) model usually asks again. The agreeing turn needs a new tool_use with a new id.

9.1 Extra exercise: property checks next to the golden file (20-30 minutes)

Problem: a golden file says "exactly this happened". With a real model, the trajectory may change and still be right (section 4.4), so you also need properties that hold in every correct run.

Requirements:

  1. Run python -m pytest exercises/test_l05_extra_properties.py once, untouched: 13 failed, each failure starting with TODO.
  2. Write property_violations(transcript) for two properties:
    • history_lost: for every turn k from 2 on whose turn k-1 ended without error, the first request of turn k sends exactly 2 more messages than the last request of turn k-1;
    • side_effect_mismatch: the number of side_effects differs from the number of create_return calls with outcome ok.
  3. In TODO 2, open data/golden/CONV-01.json and work out by hand the messages_sent of the first request of turn 2 before running.

Acceptance criteria: 13 passed. An agent that forgets to store its own answer (NoAnswerInHistory) must be caught; an agent that always approves is caught by no property, but by the golden file.

Hint: read the messages_sent table in the example in section 4.2. "A later request sends more messages than an earlier one" is not strict enough: try it with NoAnswerInHistory.

9.2 Real-world scenario: a hotel booking-change agent (fictional)

Context. The fictional hotel chain PhongDep has a chat agent with three tools: search_rooms, change_booking (side effect: may charge a change fee) and cancel_booking (side effect: partial refund). A typical conversation: turn 1 "move booking BK2041 to 12/12"; turn 2 "actually, keep the old date but add one night"; turn 3 "how much is the fee?". To cut costs, a commit trims the history to the 4 most recent messages. CI reports a difference in one script:

turn 3 requests: got [{'messages_sent': 5, ...}], golden [{'messages_sent': 9, ...}]
turn 3 answer: got 'Bạn muốn đổi đặt phòng nào?', golden 'Phí thêm một đêm cho BK2041 là 0 đồng.'

(The new answer asks which booking the customer wants to change; the golden answer gives the fee for the extra night.)

Task: write (a) an outline of 3 conversation scripts (turns, the model's fake replies, approvals), each saying which point of the table in section 4.2 it checks; (b) a decision note (5-8 sentences) on the CI difference above: regression or intended change, update the golden file or not; (c) 3 properties usable in runs with a real model.

A good answer has:

  • A script in which a later turn depends on the context of an earlier one ("add one night" only makes sense if BK2041 is still in the request)
  • A script in which the customer does not approve change_booking or cancel_booking, expecting no side effect, and a script with a failing tool
  • The decision note calls this a regression: messages_sent drops from 9 to 5 and the answer has lost its context; the golden file is not updated; it proposes a fix (for example keeping the booking details when trimming the history)
  • States that updating a golden file needs a reviewer's agreement and a reason in the commit (section 4.3)
  • The properties check consequences, not wording: for example "no change_booking or cancel_booking runs without approval", "the number of side effects equals the number of calls with outcome ok"
  • Separates fake scripts (integration tests) clearly from real-model runs (measured rates, L1-M06)

10. Knowledge check

0/20 done · Results are kept in this browser only.

P02 · True or false

When CI reports a diff in a golden file, the right thing to do is to update the golden file so that CI goes green.

P03 · Short answer

Why must a golden file not contain message ids or timestamps?

P04 · Short answer

Name a regression that a single-turn test can never catch.

P05 · Short answer

(Scenario) With the real model, the trajectory changes between runs. Write two property-style assertions to replace an exact-sequence assertion.

P06 · Match

Using the table in §4.2, match each point where an agent needs testing with its evidence in the lab.

P08 · Multiple choice

In the demo in §8.1, CONV-03 has trajectory=['create_return', 'create_return'] side_effects=1. Why two calls but only one side effect?

P09 · Spot the bug

The loop below was copied from run_script() in lab/conversation.py but is missing one line. Find the bug.

        for turn_spec in script["turns"]:
            api.queue(*[_reply(r) for r in turn_spec["model"]])
            first = len(api.requests)
            turn = agent.send(turn_spec["user"])
            sent = [r["body"] for r in api.requests[first:]]
            transcript["turns"].append({
                "user": turn_spec["user"],
                "tool_calls": [[n, a, o] for n, a, o in turn.tool_calls],
                "answer": turn.text,
                "error": turn.error,
                "requests": [{"messages_sent": len(b["messages"]),
                              "tool_results": [[r["tool_use_id"], bool(r.get("is_error"))]
                                               for r in _last_user_blocks(b) if r.get("type") == "tool_result"]}
                             for b in sent],
            })
        transcript["side_effects"] = [[n, a] for n, a in backend.side_effects()]

P10 · True or false

python -m lab.conversation record exercises/CONV-05.json saves the transcript as the golden file as soon as it runs.

P11 · Recall

Lesson: L1-M05-L04

Lesson L04 §5.2: which outcome is recorded in turn.tool_calls for a create_return call that the customer does not approve?

P12 · Select all that apply

According to §6, what does a minimal script set for an agent contain? Select every correct option.

P13 · Short answer

Why does run_script() take a make_agent function instead of a ready-made agent?

P15 · True or false

In the worked example in §4.4, an agent that always approves still gives the trajectory ['create_return'] on CONV-02, exactly like the golden file.

P16 · Fill in the blank

According to the example in §4.2, the four requests of CONV-01 send 1, 3, ___ and ___ messages.

P17 · Select all that apply

When CONV-02 runs with an agent that always approves (the example in §4.4), which differences does compare() report? Select all that apply.

P18 · Multiple choice

In extra exercise §9.1, the agent NoAnswerInHistory forgets to store its own final answer. How many messages does the first request of turn 2 in CONV-01 send?

P19 · Spot the bug

Here is a wrong solution for the history_lost property of extra exercise §9.1. Find the defect.

def property_violations(transcript):
    turns = transcript["turns"]
    lost = any(cur["requests"][0]["messages_sent"] <= prev["requests"][0]["messages_sent"]
               for prev, cur in zip(turns, turns[1:]))
    return ["history_lost"] if lost else []

P20 · Apply now

In code-labs/l1-m05, run python -m pytest exercises/test_l05_extra_properties.py once untouched, then do extra exercise §9.1 and run it again.

Checklist

11. Summary

  • Concepts: integration tests and model evaluation; trajectory; conversation state; golden transcripts; reviewing before saving; strict and loose assertions.
  • Skills: writing multi-turn scripts; recording and reviewing transcripts; proving that the oracle catches regressions.
  • Pitfalls: golden files with unstable values; updating golden files to make them green; testing only one turn; treating fake replies as evidence about the model.
  • You can now: build a conversation regression suite for a tool-using agent.

12. References

ID Title Publisher URL Accessed Relevance
R1 Tool use with Claude Anthropic https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview 2026-10-31 The tool-use loop that the agent carries out
R2 LLM06:2025 Excessive Agency OWASP GenAI Security Project https://genai.owasp.org/llmrisk/llm062025-excessive-agency/ 2026-10-31 Why side effects are the most important checkpoint

Key terms (English ↔ Vietnamese)

English Tiếng Việt
Agent Vòng lặp model gọi tool và đọc kết quả
Trajectory Chuỗi tool được gọi
Transcript Bản ghi một cuộc hội thoại
Golden file Output đã review, dùng làm oracle
Conversation regression Phát hiện thay đổi hành vi qua kịch bản nhiều lượt