Sub topic 11
Handling several tool calls in one turn
This chapter assumes you know the message roles (user, assistant, tool), can read a tool definition written in JSON Schema, and have seen the basic loop that runs one tool call and returns its result. Here you will learn what changes when the model asks for more than one call in a single reply.
Why a reply can contain several calls
A model can propose more than one tool call in a single assistant message. This is often called parallel tool calling. It usually happens when the user's request has independent parts.
Suppose the user asks, "What is the weather in Oslo and in Lima?" Both lookups are needed, and neither depends on the other. The model can return two calls in one reply instead of asking for one, waiting, and then asking for the other.
The model still only proposes. Your code runs every call and sends every result back. The benefit is fewer round trips to the model, which reduces latency and cost.
[
{"role": "user", "content": "What is the weather in Oslo and in Lima?"},
{"role": "assistant", "tool_calls": [
{"id": "call_1", "name": "get_weather", "arguments": {"city": "Oslo"}},
{"id": "call_2", "name": "get_weather", "arguments": {"city": "Lima"}}
]},
{"role": "tool", "tool_call_id": "call_1", "content": "{\"temperature\": 7, \"unit\": \"celsius\"}"},
{"role": "tool", "tool_call_id": "call_2", "content": "{\"temperature\": 19, \"unit\": \"celsius\"}"},
{"role": "assistant", "content": "Oslo is 7 degrees Celsius and Lima is 19 degrees Celsius."}
]The two calls have different ids, and each result carries the id of the call it answers. Field names differ between providers, but the shape is the same: one assistant message, several calls, one result per call.
Matching results to calls
The id is how the model knows which result belongs to which call. Follow these rules:
- Return exactly one result for every call id. Most providers reject a request in which a call has no matching result.
- Copy the id exactly as received. Do not generate your own.
- Keep the results directly after the assistant message that made the calls, before any new user message.
- Return a result even when a call failed. In that case the content is an error message (see the chapter on errors).
Some providers care about the order of results and some do not. Returning results in the same order as the calls is the safe choice. Some providers also put all results in one message, and others use one message per result. Check your SDK's documentation for the exact format.
Running calls one at a time
The loop from the earlier chapter already handles several calls, because it iterates over reply["tool_calls"]. This version runs them one after another:
def run_sequentially(calls):
results = []
for call in calls:
outcome = run_tool_call(call)
results.append({
"role": "tool",
"tool_call_id": call["id"],
"content": outcome["content"],
})
return resultsThis is simple and predictable, but total time is the sum of all the tool times. If each lookup takes two seconds and there are five calls, the user waits about ten seconds.
Running calls concurrently
If the calls are independent and the tools are safe to run at the same time, you can run them concurrently. Most tools spend their time waiting on a network or disk, so threads work well in Python.
import json
from concurrent.futures import ThreadPoolExecutor
def get_weather(city, unit="celsius"):
return {"city": city, "temperature": 7, "unit": unit}
TOOLS = {"get_weather": get_weather}
def run_tool_call(call):
fn = TOOLS.get(call["name"])
if fn is None:
return {"is_error": True, "content": "Unknown tool: " + str(call["name"])}
try:
result = fn(**call["arguments"])
except TypeError as exc:
return {"is_error": True, "content": "Bad arguments: " + str(exc)}
except Exception as exc:
return {"is_error": True, "content": "Tool failed: " + str(exc)}
return {"is_error": False, "content": json.dumps(result)}
def run_concurrently(calls, max_workers=4):
with ThreadPoolExecutor(max_workers=max_workers) as pool:
outcomes = list(pool.map(run_tool_call, calls))
return [
{
"role": "tool",
"tool_call_id": call["id"],
"content": outcome["content"],
}
for call, outcome in zip(calls, outcomes)
]
calls = [
{"id": "call_1", "name": "get_weather", "arguments": {"city": "Oslo"}},
{"id": "call_2", "name": "get_weather", "arguments": {"city": "Lima"}},
]
for message in run_concurrently(calls):
print(message)pool.map returns results in the order of the input, so each result stays paired with its call even when the tools finish in a different order. The max_workers value caps how many tools run at once. Keep it small to avoid overloading an API or hitting rate limits.
Because run_tool_call catches its own exceptions, one failing tool does not stop the others. Every call still gets a result.
When not to run calls in parallel
Parallel execution is safe only when the calls do not affect each other. Run sequentially, or ask the model to make one call at a time, in these cases:
- Order matters. "Create a folder, then save a file in it" must run in that order. If the model puts both in one turn, running them at the same time can fail.
- Shared state. Two calls that update the same record can overwrite each other.
- Side effects with limits. Sending ten emails at once may trigger rate limits or be hard to undo.
- Dependent data. If call B needs the output of call A, the model should not issue them together. Models usually get this right, but they can guess an argument they have not seen yet. Treat such a call as suspect and validate it.
Remember that the model decides which calls go in one turn, not you. You cannot assume that calls in a single turn are independent. If your tools are not safe to run concurrently, either run them in order or turn off parallel calls.
Turning parallel calls off
Many providers let you disable parallel calls with a request setting. The name varies. Some use a boolean such as parallel_tool_calls: false, and some attach the option to the tool-choice setting. When it is off, the model sends at most one call per turn.
Turn it off when:
- your tools have ordering dependencies or side effects,
- you want simpler logs and easier debugging,
- your downstream system cannot handle concurrent requests.
The cost is more model round trips for multi-part requests. Check your provider's documentation, because some models ignore the setting or do not support parallel calls at all.
Partial failures
With several calls, some can succeed while others fail. Do not discard the successes. Send back every result, marking failures clearly, and let the model decide what to do.
[
{"role": "tool", "tool_call_id": "call_1", "content": "{\"temperature\": 7, \"unit\": \"celsius\"}"},
{"role": "tool", "tool_call_id": "call_2", "content": "Error: city 'Limaa' not found. Check the spelling and try again."}
]The model can then answer for Oslo and retry Lima with a corrected spelling, or tell the user that Lima could not be found. In the next loop iteration it may issue a new call for only the failed part.
Validation, limits, and security still apply per call
Every call in the batch must be validated on its own, using the same checks as for a single call. A batch does not make arguments more trustworthy.
Batches also affect your limits:
- A step limit counts model turns, not individual calls. One turn with twenty calls is one step but twenty executions.
- Set a separate cap on calls per turn, for example 10. If the model exceeds it, return an error for the extra calls instead of running them.
- Cost and latency grow with the number of results, since all of them are added to the context for the next model call.
MAX_CALLS_PER_TURN = 10
def limit_calls(calls):
allowed = calls[:MAX_CALLS_PER_TURN]
skipped = calls[MAX_CALLS_PER_TURN:]
return allowed, skipped
def skipped_results(skipped):
return [
{
"role": "tool",
"tool_call_id": call["id"],
"content": "Error: too many tool calls in one turn. Retry this call later.",
}
for call in skipped
]Note that the skipped calls still receive a result. Leaving them out would break the rule of one result per call id.
Flow of a multi-call turn
Common mistakes
- Handling only the first call. Code that reads
tool_calls[0]works in tests with one call and breaks in production. Always iterate over the full list. - Missing results. Skipping a result for a call, even a failed or refused one, usually causes an API error on the next request.
- Mixing up ids. In concurrent code, build each result from its own call, as
zip(calls, outcomes)does above. Do not use a shared variable that other threads can change. - Assuming independence. Running everything in parallel for speed can break tools with side effects.
- Unbounded concurrency. Without a cap, a large batch can flood a downstream service.
Exercise
A model returns three tool calls in one turn: a read-only search, a read-only price lookup, and a "delete_record" call that removes a database row. Your executor runs all three concurrently. Name one risk and one way to reduce it.
Show answer
The risk is that the calls may not be independent and the delete has a side effect that is hard to undo. The delete might run before or while the model's other calls read the same record, or it might run on an argument the model guessed. To reduce it, run side-effect tools sequentially after the read-only ones, validate the delete's arguments, and consider turning off parallel tool calls or requiring user confirmation for destructive tools. Every call, including the delete, must still get a result with its own id.
Exercise
Your loop receives five tool calls. The third one raises an exception inside the tool. What should your code send back to the model, and why?
Show answer
Send five tool results, one per call id. Four contain normal results and the third contains an error message that explains what went wrong. Every call needs a result or the next request will probably be rejected, and the model needs the error text so that it can retry the third call with different arguments or explain the problem to the user.