Sub topic 16
Streaming tool calls and partial JSON
This chapter assumes you can already parse a streamed response and accumulate text deltas into a message. It covers what changes when the model streams a tool call instead of prose.
Why tool calls are different
Text deltas are useful on their own. You can show "Hel" to a user, then "lo". A tool call is not. The model emits the arguments as a JSON string, and that string arrives in fragments such as {"city": "Pa, then ris", then }. Any single fragment is usually invalid JSON. If you call json.loads on each chunk, it will fail.
In the OpenAI-style format, each chunk carries a list of tool_calls deltas:
indexsays which tool call the fragment belongs to. A response can contain several calls, and their fragments can interleave.idandfunction.namenormally appear only in the first fragment for a call.function.argumentsholds a piece of the JSON string. Append it. Never replace what you already have.
Accumulate by index, parse at the end
Keep one buffer per index. Concatenate the argument strings as they arrive. Parse only when the stream finishes.
import json
def accumulate(deltas):
"""Merge streamed tool-call deltas into complete calls, keyed by index."""
calls = {}
for d in deltas:
call = calls.setdefault(d["index"], {"id": None, "name": "", "arguments": ""})
if d.get("id"):
call["id"] = d["id"]
fn = d.get("function", {})
if fn.get("name"):
call["name"] += fn["name"]
if fn.get("arguments"):
call["arguments"] += fn["arguments"]
return calls
deltas = [
{"index": 0, "id": "call_a", "function": {"name": "get_weather", "arguments": ""}},
{"index": 1, "id": "call_b", "function": {"name": "get_time", "arguments": ""}},
{"index": 0, "function": {"arguments": '{"city": "Pa'}},
{"index": 1, "function": {"arguments": '{"zone": "UTC"}'}},
{"index": 0, "function": {"arguments": 'ris"}'}},
]
calls = accumulate(deltas)
finish_reason = "tool_calls" # taken from the final chunk of the stream
if finish_reason == "tool_calls":
for index, call in sorted(calls.items()):
args = json.loads(call["arguments"])
print(call["id"], call["name"], args)The first call's arguments are split across two deltas with a second call's fragment in between. Keying by index keeps them apart.
Common errors
- Parsing too early. Calling
json.loadsmid-stream raisesJSONDecodeError. Wait for the finish reason. - Mixing up indexes. Concatenating all fragments into one string produces invalid JSON when calls are parallel.
- Truncated output. If the finish reason is
length, the arguments can be cut off. Treat a parse failure as an error. Don't repair the string and run the tool anyway. - Running tools on unvalidated input. Check parsed arguments against your tool's schema before acting.
Showing progress
If you want to display arguments while they stream, for example a growing "Searching for Paris" label, use a tolerant partial-JSON parser for display only. Execute tools only from the fully parsed result.
Exercise
A stream contains two parallel tool calls. Why must you buffer argument fragments by index instead of in one shared string, and when is it safe to call json.loads?
Show answer
Fragments from different calls can interleave, so a single string would mix them and produce invalid JSON. Keeping one buffer per index keeps each call's arguments intact. It is safe to call json.loads once the stream has finished with finish reason tool_calls. Before that, a buffer may hold only part of the JSON.