Module: L1-M05 · Duration: ~180 min (estimate, including the independent exercise) · Previous: L02 · Next: L04 - Validating tool-call arguments and handling bad calls
1. Introduction
An assistant that only answers in words does not know where order SE1001 is. To find out, it has to call a
function of the order system. That is tool use (also called function calling): the model does not run the
function itself; it returns a request "please call lookup_order with order_id = SE1001". The application's code
runs that function and sends the result back to the model.
For a tester, most of the risk sits in the application code between the two API calls: reading the tool-call request, running the right function, sending the result back in the right format, in the right order, with the right id. This part can be tested deterministically with a fake API. This lesson teaches you to read and check each step of that loop.
2. Learning objectives
- Describe the tool-use flow: a request with tools, a
tool_useresponse, a request with atool_result, the answer. - Read a tool definition (
name,description,input_schema,strict) and assess it. - Assert the content of a
tool_useblock and of thetool_resultblocks that the application sends back. - Apply the rules on the order and ids of
tool_resultblocks, including when there are several parallel tool calls. - Explain the values of
tool_choiceand why the application in the lab never forces a tool call.
3. Prerequisites and tools
- L02: strict tool use, the fake API.
- L1-M03-L02: contract tests for requests (asserting the content of the request that the code sends).
4. Concepts
4.1 The tool-use flow
The documentation sums it up: "the response carries a tool_use block, your code runs the lookup, and a second request
sends the result back in a tool_result block so Claude can reply with the answer" [R1]. Tools defined by the
application (client tools) "run in your application. Claude responds with stop_reason: "tool_use" and one or more tool_use blocks. Your code runs the operation and sends back a
tool_result" [R1].
Everyday example. In a phở shop, the customer orders from the waiter. The waiter does not cook: he
writes a slip "table 5, one rare-beef bowl" and passes it to the kitchen (tool_use). The kitchen
cooks and hands out the bowl with that same slip (tool_result), and only then does the waiter carry
it out and talk to the customer (the final answer). The model is the waiter; the application's code is
the kitchen. Bugs usually sit in passing the slips: a bowl taken to the wrong table (a wrong id), or
bowls carried out one at a time in separate trips (one result per message).
In English: the final answer, quoted exactly as the lab returns it, says that the order is being delivered.
4.2 Tool definitions
According to the "Define tools" page [R2]:
name"Must match the regex^[a-zA-Z0-9_-]{1,128}$".description: "A detailed plain text description of what the tool does, when it should be used, and how it behaves." The model relies on this description to decide whether to call the tool.input_schema: "A JSON Schema object defining the expected parameters for the tool."
The tools in the lab (lab/tools.py) use strict: true (L02), so their schemas have additionalProperties: false,
and the schema that is sent has dropped keywords such as minimum (not supported) and pattern (the lab chooses to
check it in code, L02). Checking those keywords is the subject of L04.
When reviewing a tool definition, a tester asks: does the description say when to call the tool? Is a tool with side effects (creating a return order, paying money) clearly described as having side effects?
Good vs bad: a tool definition. A weak definition for the same order lookup:
{"name": "order", "description": "Order tool.",
"input_schema": {"type": "object", "properties": {"id": {"type": "string"}}}}
| Weak (above) | Good (lookup_order in lab/tools.py) |
|---|---|
The name order does not say what the tool does |
The name states the action: lookup_order |
| "Order tool." does not say when to call it | Says when to call it ("when the customer asks where an order is") and the format (SE1234) |
id is not required, and extra fields are not limited |
required: ["order_id"], additionalProperties: false, strict: true |
With the weak version, the model may call the tool for an account question, or send {}. Both are
bugs of the definition, not of the model.
4.3 tool_use and tool_result blocks
A tool_use block has an id, a name and an input [R3]. The application answers with a tool_result block
that has a tool_use_id (equal to the id of the tool_use), a content, and optionally is_error [R3].
The important rules, according to the "Handle tool calls" page [R4]:
- "Tool result blocks must immediately follow their corresponding tool use blocks in the message history. You cannot include any messages between…"
- "the
tool_resultblocks must come FIRST in the content array. Any text must come AFTER all tool results."
And according to the "Parallel tool use" page [R5]: when the model calls several tools in one response, the
application must "return one tool_result for each tool_use block, all together in the next user message."
Everyday example. A parking garage: you hand over two tickets, 27 and 28, at once. The attendant
must return the right vehicle for each ticket number, and return both in one visit to the counter,
not send you back to the queue for the second one. tool_use_id is the ticket number; "one user
message" is one visit to the counter.
Worked example: two parallel tool calls. Save this as try_l03_parallel.py in the lab folder and
run python try_l03_parallel.py:
import json
import os
os.environ["ANTHROPIC_API_KEY"] = "sk-test-fake-key-0000" # fake key: the fake API only
from lab.agent import OrderAgent, make_client
from lab.fake_api import FakeClaudeAPI, message, text, tool_use
from lab.tools import MockOrderSystem
with FakeClaudeAPI() as api:
backend = MockOrderSystem()
api.queue(message(tool_use("lookup_order", {"order_id": "SE1001"}, "toolu_a"),
tool_use("lookup_order", {"order_id": "SE1003"}, "toolu_b"), stop_reason="tool_use"),
message(text("SE1001 đang giao, SE1003 đã giao.")))
turn = OrderAgent(make_client(api.base_url), backend).send("Hai đơn SE1001 và SE1003 sao rồi?")
sent = api.requests[1]["body"]["messages"]
print("messages in request 2:", len(sent))
for block in sent[-1]["content"]:
print(" ", block["type"], block["tool_use_id"], json.loads(block["content"])["status"])
print("backend.calls:", backend.calls)
messages in request 2: 3
tool_result toolu_a shipped
tool_result toolu_b delivered
backend.calls: [('lookup_order', {'order_id': 'SE1001'}), ('lookup_order', {'order_id': 'SE1003'})]
Line by line: request 2 has 3 messages (the question, the assistant with two tool_use blocks, one
user message); that user message holds two tool_result blocks, in the order toolu_a then
toolu_b; the backend ran exactly two calls. 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. Delete the file when you
are done.
4.4 tool_choice
According to the "Define tools" page [R2]: auto "allows Claude to determine whether to call any provided tools.
This is the default value when tools are provided"; any "tells Claude that it must use one of the
provided tools"; tool "forces Claude to always use a particular tool"; none "prevents Claude from using
any tools".
An important detail as of 2026-10-31: that page says that with "Claude Opus 5.5, Claude Sonnet 5.5,
Claude Fable 5.1, and Claude Mythos 5.1", any and tool "return a 400 error", and it recommends using "auto with
strict tool use … or structured outputs" [R2]. That is why the agent in the lab never sends tool_choice. A test
asserts it. With auto, the model may not call a tool, so the application has to handle that case too.
Worked example: tool_choice with claude-opus-5-5. Save this as try_l03_choice.py and run it:
import os
os.environ["ANTHROPIC_API_KEY"] = "sk-test-fake-key-0000" # fake key: the fake API only
import anthropic
from lab.agent import make_client
from lab.fake_api import FakeClaudeAPI
from lab.tools import TOOLS
with FakeClaudeAPI() as api:
client = make_client(api.base_url)
for choice in ({"type": "auto"}, {"type": "any"}):
try:
client.messages.create(model="claude-opus-5-5", max_tokens=100, tools=TOOLS, tool_choice=choice,
messages=[{"role": "user", "content": "Đơn SE1001 đâu?"}])
print(choice["type"], "-> 200")
except anthropic.BadRequestError as exc:
print(choice["type"], "-> 400:", exc.body["error"]["message"])
auto -> 200
any -> 400: tool_choice: type "tool" and "any" are not supported for this model.
Same tools, same question; only tool_choice changes. With any, the fake returns 400, as the
documentation describes for these models. A test "the request contains no forced tool_choice" catches
this configuration change before it reaches customers (situation 2 in section 7).
5. Technical deep dive
5.1 The agent in the lab
lab/agent.py is a manual loop: it sends a request; if the stop_reason is tool_use, it runs the tools and
sends the results, and repeats until end_turn. Its contract has 10 clauses A1-A10 at the top of the file. This
lesson tests A2 and A8; L04 tests A3-A7; L05 tests A1.
The SDK also has a tool runner, a ready-made loop. The lab writes the loop by hand so that you can see each step you are testing. With the tool runner, the test questions stay the same.
Everyday example. Learning to drive a manual car, you see and make every gear change yourself. An automatic car goes through the same gears; you just do not see it. The tool runner is the automatic gearbox: convenient, but the questions "did it change gear correctly" (right id, right order, every result) stay exactly the same.
5.2 What the SDK does and does not do
Observed with anthropic 2.3.0 (2026-10-31) and recorded in tests:
- A
tool_useblock is parsed into aToolUseBlockwith.id,.name,.input. .inputis an ordinarydict. The SDK does not check it against the tool's schema.- The SDK does not check the conversation history before sending. A
tool_resultwith the wrong id is still sent, and the API returns a 400 error.
5.3 The fake API checks the rules too
lab/fake_api.py returns 400 when the history breaks the rules in §4.3 (a missing tool_result, a wrong id, text
before a tool_result), and when tool_choice is any/tool with the models in §4.4. The tests in
tests/test_l03_tool_calls.py prove that the fake really rejects these cases. Without those tests, a "passing"
agent test might only mean that the fake is lenient.
Worked example: a strict fake and a lenient fake. Send the same history with a wrong id (tool_use
is toolu_01, tool_result is toolu_99) to the fake with check_protocol=True, then False. Save
this as try_l03_fakes.py and run it:
import os
os.environ["ANTHROPIC_API_KEY"] = "sk-test-fake-key-0000" # fake key: the fake API only
import anthropic
from lab.agent import make_client
from lab.fake_api import FakeClaudeAPI, tool_use
HISTORY = [{"role": "user", "content": "Đơn SE1001 đâu?"},
{"role": "assistant", "content": [tool_use("lookup_order", {"order_id": "SE1001"}, "toolu_01")]},
{"role": "user", "content": [{"type": "tool_result", "tool_use_id": "toolu_99", "content": "{}"}]}]
for strict in (True, False):
with FakeClaudeAPI(check_protocol=strict) as api:
try:
r = make_client(api.base_url).messages.create(model="claude-opus-5-5", max_tokens=100, messages=HISTORY)
print(f"check_protocol={strict}: 200, reply {r.content[0].text!r}")
except anthropic.BadRequestError as exc:
print(f"check_protocol={strict}: 400, {exc.body['error']['message']}")
check_protocol=True: 400, messages.2: tool_use ids ['toolu_01'] have no tool_result in the next message; messages.2: tool_result ids ['toolu_99'] do not match a tool_use in the previous message
check_protocol=False: 200, reply 'Hello!'
The lenient fake cheerfully answers 'Hello!', so an agent that sends a wrong id still "passes". That
is why the lab turns check_protocol on by default, and has tests proving the fake really rejects a
broken history.
5.4 The Python you need for this lesson
- Classes and objects:
agent = OrderAgent(client, backend)creates an object that holds state (the conversation history).agent.send("...")calls one of its methods. api.requests[1]["body"]["messages"]is the list of messages that the second request sent. Indexes start at[r["tool_use_id"] for r in results]takes one field from each element of a list (a list comprehension).
6. The QA perspective
| What to check | How to check it in the lab |
|---|---|
The tools are sent with the right name, description, schema, strict |
Read api.requests[0]["body"]["tools"] |
No forced tool_choice |
"tool_choice" not in body |
Each tool_use has exactly one tool_result with the same id |
Compare the ids in the next request |
| Several tool calls: every result in one user message, in the right order | Count the messages, read the order of the ids |
| The right function runs with the right arguments | backend.calls |
| The final answer | turn.text |
- What can go wrong: sending each result in its own message; wrong ids when there are several calls; putting text
before a
tool_result; forgetting to send back the assistant'stool_useblock; forcingtool_choice. - How to report: attach the list of messages of the failing request and the 400 message. This bug often appears only when the model calls several tools at once, so state the reproduction conditions clearly.
7. Real-world scenarios
Scenario 1 (fictional): a bug that only happens with two orders. A delivery assistant works fine in the demo,
because the presenter always asks about one order. A real customer asks "how are my two orders doing?", the model
calls lookup_order twice in one response, and the code sends the two tool_result blocks in two separate
messages. The API returns 400 and the customer sees "An error occurred". A test with two parallel tool calls would
catch this bug before release.
Scenario 2 (fictional): forcing a tool call after a model change. A team uses tool_choice tool to always
extract data with a tool. After switching to a new model, every request returns 400. A contract test "the request
contains no forced tool_choice", combined with reading the new model's notes, would catch it early.
8. Hands-on tutorial
8.1 Running the demo
python -m lab.demo l03
Output (copied from a real run, 2026-10-31):
request 1:
user "Đơn SE1001 đâu rồi?"
request 2:
user "Đơn SE1001 đâu rồi?"
assistant [{"text": "Mình kiểm tra nhé.", "type": "text"}, {"id": "toolu_01", "input": {"order_id": "SE1001"}, "name": "lookup_order", "type": "tool_use"}]
user [{"type": "tool_result", "tool_use_id": "toolu_01", "content": "{\"order_id\": \"SE1001\", \"status\": \"shipped\"}"}]
answer: Đơn SE1001 đang giao. | steps: 2 | tool calls: [('lookup_order', {'order_id': 'SE1001'}, 'ok')]
In English: the user asks where the order is, the assistant's text block says "Let me check.", and the answer says that the order is being delivered.
Request 1 contains only the question. Request 2 adds the assistant's tool_use block and a tool_result block whose
tool_use_id equals toolu_01. The agent needs 2 requests (steps: 2) to answer.
8.2 Running the tests
python -m pytest tests/test_l03_tool_calls.py -v
Read test_parallel_calls_answered_in_one_message_in_order and the three
test_fake_rejects_a_broken_tool_history tests.
8.3 Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
BadRequestError: ... have no tool_result |
A tool_use has no result |
Answer every tool_use in the response |
BadRequestError: ... must come first |
Text comes before a tool_result |
Put the tool_result blocks first in the content |
BadRequestError: ... "tool" and "any" are not supported |
Forcing tool_choice with claude-opus-5-5 |
Use auto and describe the tool more clearly |
IndexError when reading api.requests[1] |
The agent sent only one request | Check that the fake reply has stop_reason="tool_use" |
9. Independent exercise
Problem: The model calls three tools at once, and one call has a wrong argument.
Requirements: complete exercises/test_l03_tool_protocol.py. The (fake) model calls lookup_order for
SE1001, "se1002" (wrong format) and SE1003 in one reply. Assert that:
- The next request has exactly one user message containing three
tool_resultblocks. - The order and the ids match the three
tool_useblocks. - Only the result of the wrong call has
is_error: true. - The backend runs exactly two calls.
Test data: the fixtures api, agent, backend in tests/conftest.py.
Deliverable: the completed test file.
Acceptance criteria: the test passes; the test fails if you swap two tool_use blocks without changing the
expectation (try it, to be sure that the test really checks the order).
Hint: r.get("is_error", False) returns False when the field does not exist.
9.1 Extra exercise: write your own tool-use history checker (20-30 minutes)
Problem: your team logs every messages list it sends. Before a release, you want to scan the logs
for histories the API would reject, without calling the API.
Requirements:
- Run
python -m pytest exercises/test_l03_extra_history_check.pyonce, untouched:7 failed, each failure starting withTODO. - Write
history_problems(messages)following the two rules in section 4.3: every assistanttool_useid has atool_resultwith the same id in the next message (a user message); and in that message, everytool_resultcomes before any other block. Each problem string must contain the id it is about. Do not import the fake'sprotocol_errors: the point is to write it yourself. - In TODO 2, read the history
THREEby eye before running and write the id that has no result.
Acceptance criteria: 7 passed; the history of the demo in section 8.1 and the valid two-call
history have no problem.
Hint: a content can be a string ("Đơn SE1001 đâu rồi?"), not a list of blocks. Check "next" with
messages[i + 1], not "somewhere later".
9.2 Real-world scenario: reviewing the tools of a food delivery app (fictional)
Context. The fictional app GiaoNhanh adds a chat assistant with two tools. The configuration sent to
the API, with the model claude-opus-5-5, has "tool_choice": {"type": "tool", "name": "track"} and
these two definitions:
[{"name": "track", "description": "Tracking.",
"input_schema": {"type": "object", "properties": {"code": {"type": "string"}}}},
{"name": "cancel_order", "description": "Cancel an order.",
"input_schema": {"type": "object", "properties": {"order_code": {"type": "string"},
"reason": {"type": "string"}},
"required": ["order_code"]}}]
The internal demo always asks about one order and works well.
Task: write (a) your findings from reviewing the tool definitions and the request; (b) at least 5 test cases for the tool-use loop (precondition, the model's fake reply, expected result); (c) a severity ranking of the findings, one sentence of reason each.
A good answer has:
- Points out that forcing
toolgets a 400 error withclaude-opus-5-5(section 4.4), and that even if it ran, the model could never answer with text only - Points out that
track's description does not say when to call it or what an order code looks like;codeis not required - Points out that
cancel_orderhas a side effect the description does not mention, and has nostrictoradditionalProperties: false - A test case with two parallel
trackcalls: twotool_resultblocks in one user message, in order, with matching ids - A test case checking the request has no forced
tool_choice, and a test case for a model that calls no tool at all - The ranking puts the 400 error (every request fails) and the undescribed side effect first
10. Knowledge check
0/20 done · Results are kept in this browser only.
P02 · True or false
P03 · Short answer
The model calls two tools in one response. How must the application send the results?
P04 · Short answer
Why does the lab have tests proving that the fake API rejects a broken history?
P05 · Short answer
(Scenario) You want to be sure that the model always calls lookup_order when a customer asks about an order, with claude-opus-5-5. You may not use tool_choice tool. How do you design and test it?
P06 · Match
P08 · Multiple choice
P09 · Spot the bug
The code below was copied from send() in lab/agent.py but is missing one line. Find the bug.
content = [block.model_dump(exclude_none=True) for block in response.content]
has_calls = any(b["type"] == "tool_use" for b in content)
if has_calls and response.stop_reason != "tool_use":
del self.messages[checkpoint:]
turn.error = "unexpected_stop"
return turn
if response.stop_reason == "end_turn":
turn.text = "".join(b["text"] for b in content if b["type"] == "text")
return turn
if response.stop_reason != "tool_use":
del self.messages[checkpoint:]
turn.error = "unexpected_stop"
return turn
results = [self._run(block, turn) for block in content if block["type"] == "tool_use"]
self.messages.append({"role": "user", "content": results})P10 · Select all that apply
P11 · True or false
P12 · Recall
Lesson: L1-M05-L02P13 · Put in order
P14 · Multiple choice
P15 · Short answer
The SDK has a tool runner, a ready-made loop. Why does the lab write the loop by hand, and do the test questions change if the product uses the tool runner?
P17 · True or false
P18 · Multiple choice
P19 · Spot the bug
Here is a wrong solution to extra exercise §9.1. Find the defect.
def history_problems(messages):
problems = []
for i, msg in enumerate(messages):
content = msg["content"] if isinstance(msg["content"], list) else []
for b in content:
if b.get("type") == "tool_use":
later = [r.get("tool_use_id") for n in messages[i + 1:]
for r in (n["content"] if isinstance(n["content"], list) else [])]
if b["id"] not in later:
problems.append(f"{b['id']}: never answered")
return problemsP20 · Apply now
In code-labs/l1-m05, run python -m pytest exercises/test_l03_extra_history_check.py once untouched, then do extra exercise §9.1 and run it again.
11. Summary
- Concepts: the tool-use flow; tool definitions;
tool_useandtool_result; the rules on order and ids; parallel tool calls;tool_choiceand the 400 error with the new models. - Skills: asserting the requests that the agent sends; checking ids and order; proving that the test double is strict enough.
- Pitfalls: testing only one tool call; sending the results in several messages; forcing
tool_choice; believing that the SDK checksinput. - You can now: test an application's tool-use loop without the real API.
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 flow; client tools |
| R2 | Define tools | Anthropic | https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools | 2026-10-31 | Tool fields; tool_choice; the 400 error with the 5.5 models |
| R3 | Messages API reference | Anthropic | https://platform.claude.com/docs/en/api/messages | 2026-10-31 | Structure of tool_use and tool_result |
| R4 | Handle tool calls | Anthropic | https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls | 2026-10-31 | Order of tool_result; is_error |
| R5 | Parallel tool use | Anthropic | https://platform.claude.com/docs/en/agents-and-tools/tool-use/parallel-tool-use | 2026-10-31 | Every result in one user message |
Key terms (English ↔ Vietnamese)
| English | Tiếng Việt |
|---|---|
| Tool use / function calling | Gọi công cụ / gọi hàm |
| Tool definition | Định nghĩa công cụ |
| Client tool | Công cụ do ứng dụng chạy |
| Parallel tool use | Gọi nhiều công cụ trong một response |
| Manual loop / tool runner | Vòng lặp tự viết / vòng lặp có sẵn của SDK |
| Side effect | Tác dụng phụ (thay đổi dữ liệu thật) |