Sub topic 16
Streaming Tool Calls and Partial JSON
This chapter assumes you can already read a streamed chat response and accumulate text deltas into a message. It also assumes you know what a tool call is: the model asks your code to run a function with JSON arguments. Examples use the OpenAI-style chat completions format, and the Anthropic differences are noted along the way.
Why tool calls are harder than text
Streamed text is forgiving. Each delta is a string, and any prefix of a sentence is still readable. A tool call is different. Its arguments are a JSON document, and the model writes that document token by token. Until the last token arrives, the document is usually not valid JSON.
import json
try:
json.loads('{"city": "Par')
except json.JSONDecodeError as error:
print("not parseable yet:", error.msg)The central rule of this chapter follows from this. Concatenate argument fragments as strings, and parse them only once the call is complete.
What a streamed tool call looks like
In the OpenAI format, each chunk may carry delta.tool_calls, a list of fragments. Each fragment has an index that identifies which call it belongs to. The first fragment for a call carries the id and the function name. Later fragments carry only the index and a slice of function.arguments.
A stream for one call looks roughly like this (the chunk wrapper is trimmed):
{"index": 0, "id": "call_1", "type": "function", "function": {"name": "get_weather", "arguments": ""}}{"index": 0, "function": {"arguments": "{\"ci"}}{"index": 0, "function": {"arguments": "ty\": \"Par"}}{"index": 0, "function": {"arguments": "is\"}"}}- A final chunk with an empty delta and
finish_reason: "tool_calls".
The fragment boundaries fall wherever the tokenizer puts them. They can split a key, a string value, or an escape sequence. Never assume a fragment is meaningful on its own.
Anthropic's Messages API uses a different shape for the same idea. A content_block_start event announces a tool_use block with its id and name. Then content_block_delta events carry input_json_delta objects with a partial_json string. A content_block_stop event marks the block as complete. The rule is the same: join the partial_json strings, then parse after the block stops.
Keying fragments by index, not by arrival order
The model can request several tools in one turn (parallel tool calls). Their fragments may be interleaved in the stream. The id appears only once per call, so it cannot be your lookup key for later fragments. Use index.
A complete accumulator
This program runs as written. It replays a hand-written stream that contains two interleaved calls, so no API key is needed.
import json
def accumulate_tool_calls(chunks):
"""Merge streamed tool-call fragments. Return (calls_by_index, finish_reason)."""
calls = {}
finish_reason = None
for chunk in chunks:
choice = chunk["choices"][0]
delta = choice.get("delta", {})
for fragment in delta.get("tool_calls") or []:
slot = calls.setdefault(
fragment["index"], {"id": None, "name": "", "arguments": ""}
)
if fragment.get("id"):
slot["id"] = fragment["id"]
function = fragment.get("function") or {}
if function.get("name"):
slot["name"] += function["name"]
if function.get("arguments"):
slot["arguments"] += function["arguments"]
if choice.get("finish_reason"):
finish_reason = choice["finish_reason"]
return calls, finish_reason
def wrap(delta, finish_reason=None):
return {"choices": [{"delta": delta, "finish_reason": finish_reason}]}
stream = [
wrap({"tool_calls": [{"index": 0, "id": "call_a", "type": "function",
"function": {"name": "get_weather", "arguments": ""}}]}),
wrap({"tool_calls": [{"index": 1, "id": "call_b", "type": "function",
"function": {"name": "get_time", "arguments": ""}}]}),
wrap({"tool_calls": [{"index": 0, "function": {"arguments": "{\"ci"}}]}),
wrap({"tool_calls": [{"index": 1, "function": {"arguments": "{\"tz\": \"UT"}}]}),
wrap({"tool_calls": [{"index": 0, "function": {"arguments": "ty\": \"Paris\"}"}}]}),
wrap({"tool_calls": [{"index": 1, "function": {"arguments": "C\"}"}}]}),
wrap({}, finish_reason="tool_calls"),
]
calls, finish_reason = accumulate_tool_calls(stream)
if finish_reason != "tool_calls":
raise RuntimeError(f"Stream did not finish cleanly: {finish_reason}")
for index in sorted(calls):
call = calls[index]
arguments = json.loads(call["arguments"] or "{}")
print(call["id"], call["name"], arguments)The output is:
call_a get_weather {'city': 'Paris'}
call_b get_time {'tz': 'UTC'}With the real SDK, the pattern is the same. Iterate the stream, read chunk.choices[0].delta.tool_calls, and use attribute access (fragment.index, fragment.function.arguments) instead of dictionary keys.
Edge cases that cause real bugs
- Empty arguments. A tool with no parameters may produce an empty string instead of
{}. Theor "{}"fallback above handles it. - Text and tool calls in one turn. A model may stream some text (
delta.content) before it starts a tool call. Keep a separate text buffer and show it in the UI as usual. - Truncation. If
finish_reasonislength(or Anthropic'smax_tokensstop reason), the arguments may be cut off mid-string. The buffer will not parse. Do not try to repair it and run the tool. Raisemax_tokensor retry the request. - Connection drop. If the stream ends with no finish reason, treat every buffered call as incomplete. This is the same failure as any mid-stream error, but here a half-executed action is more dangerous than half a sentence.
- Invalid JSON despite a clean finish. Models occasionally emit malformed arguments. Wrap
json.loadsin atry, and on failure return the error to the model as the tool result so it can correct itself. Also validate the parsed object against your tool's schema before acting on it. - Unknown tool names. Check the name against your registered tools before dispatching.
Should you ever parse early?
You may want to show something while arguments stream, for example a live "Searching for: Par…" label. Two options exist:
- Show the raw buffer as text. This is simple and always safe.
- Use a tolerant partial-JSON parser that closes open strings and brackets. This gives a best-effort preview object.
Treat any preview as display-only. A preview of {"amount": 5 could become {"amount": 500} one token later. Never execute a side effect from a partial parse. Run the tool only after the finish reason confirms the call is complete and the full buffer parses and validates.
Some providers offer a strict or structured-output mode that forces arguments to match a schema. It reduces malformed output, but it does not remove the need to wait for the end of the stream, because the document is still built one token at a time.
Relaying tool-call streams
If your backend relays the stream to a browser, you have two choices. You can forward raw fragments and accumulate in the client, or you can accumulate on the server and send the browser a clean event such as tool_call_ready. The second keeps credentials, tool execution, and validation on the server, which is usually where they belong. Whichever you pick, the tool itself should run on the server.
Exercise
A stream contains the fragments {"index": 0, "function": {"arguments": "{\"qty\": 1"}} and {"index": 0, "function": {"arguments": "0}"}}, then ends with finish_reason: "length". Is it safe to run the tool with {"qty": 10}? Explain why or why not.
Show answer
No. The stream was cut off by the token limit, so the call is incomplete even though this particular buffer happens to parse as valid JSON. The model may have intended a different value, or further arguments may be missing. Run a tool only when the finish reason is tool_calls (or the provider's equivalent) and the full buffer parses and validates. Otherwise, retry with a higher token limit.
Exercise
Why do you key tool-call fragments by index instead of by id?
Show answer
The id is sent only in the first fragment of each call. Later fragments carry only the index and an argument slice, so they cannot be matched by id. The index is present in every fragment and stays stable when parallel calls are interleaved.