Sub topic 4
What the model returns when it wants a tool
This chapter covers the shape of the model's reply when it decides to use a tool. It assumes you can read JSON, know that chat APIs take a list of role-tagged messages, and have seen a tool definition with a name, a description, and JSON Schema parameters. You will learn to recognize a tool-call reply, read its fields, and avoid the usual mistakes in handling it.
The model proposes, your code executes
A model cannot run code or reach the network. When it wants a tool, it writes a structured message that names a tool and supplies arguments. Your program reads that message and decides what to do with it. Nothing has happened yet. The call is a request, and your code can run it, change it, or refuse it.
This matters for correctness and for security. The arguments are text generated by a model, so they can be wrong, incomplete, or influenced by untrusted input. Later chapters cover validation and security. Here the goal is to read the reply accurately.
Anatomy of a tool-call reply
A normal reply is an assistant message with text in content. A tool-call reply is still an assistant message, but it carries a list of tool calls. Providers use different key names, so this chapter uses a provider-neutral view.
{
"role": "assistant",
"content": null,
"tool_calls": [
{
"id": "call_1",
"name": "get_weather",
"arguments": {"city": "Oslo", "unit": "celsius"}
}
]
}Each entry in the list has three parts that matter:
- id: a unique string for this call. You send it back with the result so the model can match the result to the request.
- name: the tool the model wants. It should match a name in the definitions you sent, but the model can get it wrong.
- arguments: the values for the tool's parameters, which the model produced to fit your JSON Schema.
The id is the link between request and result. It is also what keeps several calls in one turn from getting mixed up.
Differences between providers
The ideas are the same everywhere, but the wire format varies. The table lists the variations you are most likely to meet.
| Aspect | Common variations |
|---|---|
| Where calls appear | A `tool_calls` array on the message, or typed blocks (such as a `tool_use` block) inside the message content |
| Arguments type | A JSON object, or a string that contains JSON text |
| Text alongside calls | Some providers allow explanatory text in the same message, others return `null` content |
| Stop signal | A finish reason such as `tool_calls` or `tool_use`, instead of a normal stop |
Read your provider's documentation for the exact keys. The rest of this chapter holds for all of them.
Arguments may be a string
The most common surprise is that arguments is sometimes a JSON string, not an object. In that case you must parse it before use. A defensive reader handles both forms.
import json
def read_arguments(call):
raw = call.get("arguments", {})
if isinstance(raw, dict):
return raw
if isinstance(raw, str):
if raw.strip() == "":
return {}
parsed = json.loads(raw)
if not isinstance(parsed, dict):
raise ValueError("Arguments must be a JSON object")
return parsed
raise ValueError("Unsupported arguments type: " + type(raw).__name__)
print(read_arguments({"arguments": '{"city": "Oslo"}'}))
print(read_arguments({"arguments": {"city": "Oslo"}}))The function accepts a dict as is, parses a string, treats an empty string as no arguments, and rejects anything that is not a JSON object. json.loads raises json.JSONDecodeError on malformed text, which is a subclass of ValueError. Catch it where you call this function and turn it into an error the model can read.
Detecting that a tool call happened
Do not check whether content is empty. Some providers return text together with tool calls, and some return no text at all. Check for tool calls directly.
def extract_calls(reply):
calls = reply.get("tool_calls") or []
return [c for c in calls if isinstance(c, dict)]
reply = {
"role": "assistant",
"content": "Let me check that for you.",
"tool_calls": [
{"id": "call_1", "name": "get_weather", "arguments": {"city": "Oslo"}}
],
}
print(len(extract_calls(reply)))This reply has text and a call. If your code treated the text as a final answer, the user would see "Let me check that for you." and the weather lookup would never run. Always look at the calls first.
The sequence below shows who does what in one exchange.
The model never talks to the tool. All traffic goes through your code.
What can go wrong in the reply
Treat every field as untrusted input. These failures happen in practice.
- Unknown tool name. The model names a tool you did not define, or misspells one.
- Malformed argument JSON. When arguments arrive as a string, the text can be truncated or contain a syntax error. Truncation is likely when the reply hit the output token limit.
- Wrong shape. The JSON parses, but a required field is missing, a value has the wrong type, or an enum value is not in the list.
- Extra fields. The model adds a parameter that you never defined.
- Duplicate or missing ids. Rare, but a missing id makes it impossible to tag the result.
Schema constraints guide the model but do not guarantee compliance in every provider mode. Some providers offer a strict mode that constrains generation to the schema. Even then, check values on your side, because a valid type can still be a bad value, such as a city that does not exist.
Truncated replies
If the reply stops because of the token limit, the tool call can be cut off mid-JSON. Check the finish reason before you parse. If it says the output was truncated, do not run a half-formed call. Retry with a higher output limit or report the problem.
def is_truncated(finish_reason):
return finish_reason in ("length", "max_tokens")The exact values differ by provider, so confirm them in your provider's documentation.
Several calls and the assistant message
A reply can hold more than one call. Each has its own id. Keep the whole assistant message, including all its calls, in the history before you add any results. Providers usually reject a result whose id does not match a call in an earlier assistant message.
{
"role": "assistant",
"content": null,
"tool_calls": [
{"id": "call_1", "name": "get_weather", "arguments": {"city": "Oslo"}},
{"id": "call_2", "name": "get_weather", "arguments": {"city": "Bergen"}}
]
}Chapter handling of several calls is covered later. For now, remember that you read them as a list and never assume there is exactly one.
A reader for the reply
This function combines the checks above. It returns a plain list of validated call records and reports problems as data instead of raising.
import json
KNOWN_TOOLS = {"get_weather"}
def parse_tool_calls(reply):
parsed = []
for call in reply.get("tool_calls") or []:
call_id = call.get("id")
name = call.get("name")
problem = None
args = {}
if not call_id:
problem = "Missing call id"
elif name not in KNOWN_TOOLS:
problem = "Unknown tool: " + str(name)
else:
try:
raw = call.get("arguments", {})
args = json.loads(raw) if isinstance(raw, str) else raw
if not isinstance(args, dict):
problem = "Arguments must be a JSON object"
except json.JSONDecodeError as exc:
problem = "Arguments are not valid JSON: " + str(exc)
parsed.append({"id": call_id, "name": name, "arguments": args, "problem": problem})
return parsed
reply = {
"tool_calls": [
{"id": "call_1", "name": "get_weather", "arguments": '{"city": "Oslo"}'},
{"id": "call_2", "name": "get_stock", "arguments": {}},
]
}
for item in parse_tool_calls(reply):
print(item["id"], item["name"], item["problem"])Running it prints call_1 get_weather None and call_2 get_stock Unknown tool: get_stock. The next chapter uses records like these when dispatching.
Summary of the working model
- A tool-call reply is an assistant message that contains a list of calls.
- Each call has an id, a tool name, and arguments.
- The call is a proposal. Your code decides whether to run it.
- Check for calls explicitly, because text and calls can appear together.
- Expect arguments as an object or as a JSON string, and handle both.
- Expect errors: unknown names, bad JSON, wrong shapes, and truncation.
Exercise
A provider returns an assistant message with content "Checking now." and a tool_calls list with one call. Your code treats any non-empty content as the final answer. What goes wrong, and how do you fix it?
Show answer
The loop ends early. The user sees "Checking now." and the tool never runs, so the real answer is never produced. Fix it by checking the tool_calls list first. If it has entries, run them and continue the loop. Treat the content as a final answer only when there are no tool calls.
Exercise
The model returns a call whose arguments field is the string '{"city": "Os'. What most likely happened, what should you check first, and what should your code do?
Show answer
The reply was probably cut off by the output token limit, so the JSON is incomplete. Check the finish reason for a length or max-token value before parsing. Do not run the call. Either retry with a higher output limit, or send the model an error result for that call id describing the invalid arguments so it can try again.
Exercise
Write the one-line condition in Python that is true when a reply from a provider-neutral API contains at least one tool call, including when the key is missing or the value is null.
Show answer
bool(reply.get("tool_calls")). A missing key and None both give a falsy value, as does an empty list.