Streaming tool calls keep failing to parse: 2,236 of 2,262 byte cut points break a stateless reader
Environment: Python 3.12.11, standard library only. The sample follows the get_weather output in OpenAI's function-calling guide: one opening fragment (carrying id, name, type) plus seven argument fragments plus one closing chunk with finish_reason, nine chunk events in total, serialized as data: <single-line JSON> followed by a blank line into an SSE stream of 2,263 bytes. Checked on 2026-11-29.
The verdict up front: the failure is not network flakiness, it is structural in two places. When the transport cuts a JSON line in half, a stateless reader must fail. In the delta layer the arguments are fragments by design, so per-fragment parsing must fail too.
Two layers fail, and they need different fixes
The same JSONDecodeError: Expecting value: line 1 column 1 (char 0) can come from either place:
- Transport layer: a
data:line is split in the middle of its bytes, so the first half of the JSON has no closing brace. - Delta layer: the JSON is intact, but the
argumentsfield itself is only{"— half a string.
The first needs a buffer, the second needs concatenation. Debug them together and you end up adding retries that make it worse.
Layer one: one split line kills every stateless reader
For the 2,263-byte stream above, I walked every possible cut point (1 through 2,262), split the stream into two segments, fed them in order, and checked whether the reader recovered all nine events:
| Reader style | 2,262 single cut points | 200 double-cut pairs | 323 cuts at every 7 bytes |
|---|---|---|---|
Split each chunk by \n, json.loads immediately (stateless) | 2,236 failures, 98.85% | all 200 pairs fail | fails at the first cut |
Line buffer: split on \n, keep the remainder for the next feed | 0 failures | 0 failures | never fails |
| Event buffer: split on blank lines | 0 failures | 0 failures | never fails |
Only 26 cut points happen to land exactly on event boundaries; everything else breaks. Put differently, whether this reader works is up to how the network packets arrive. It works in practice because most of the time one chunk carries one complete SSE event. The moment a proxy sits in front, gzip is on, or TLS splits a large event into two, it breaks.
One spec detail that gets missed: SSE dispatches an event only when it hits a blank line, so if the stream ends without a blank line after the last event, that event is dropped. The symptom is a missing final sentence rather than an error, which is harder to trace.
Layer two: of 8 argument fragments, 1 parses
Taking the delta.tool_calls out of each of the nine chunks and testing whether each fragment's arguments parses on its own:
| Fragment | Bytes | json.loads |
|---|---|---|
"" (empty string in the first chunk) | 0 | invalid |
{" | 2 | invalid |
location | 8 | invalid |
":" | 3 | valid (parses to the string ":") |
Paris | 5 | invalid |
, | 1 | invalid |
France | 7 | invalid |
"} | 2 | invalid |
The one "valid" fragment parses to a string, not the argument object you wanted. Concatenated by index, {"location":"Paris, France"} is 28 bytes and parses in one go.
The official documentation is explicit here: index identifies which function call the delta belongs to, and id, function.name and type are only set for the first delta of each tool call, arriving as null otherwise. So you cannot key by name — only 1 of 8 deltas carries it. The same goes for the delta itself: it can hold nothing at all (the final chunk in the official example is {}), which makes delta["content"] raise KeyError on all nine chunks.
Three stateful steps
The working reader has three stateful steps, and missing any one of them breaks it:
buf, calls = "", {}
def feed(chunk_bytes):
global buf
buf += chunk_bytes.decode() # 1 buffer by line, keep the remainder
while "\n" in buf:
line, buf = buf.split("\n", 1)
if not line.startswith("data: "):
continue
payload = json.loads(line[6:]) # 2 parse complete events only
for tc in payload["choices"][0]["delta"].get("tool_calls") or []:
slot = calls.setdefault(tc["index"], {"name": "", "arguments": ""})
slot["name"] = slot["name"] or tc["function"].get("name") or ""
slot["arguments"] += tc["function"].get("arguments") or "" # 3 accumulate by index
def finalize(): # parse arguments only at the end
return {i: {"name": c["name"], "arguments": json.loads(c["arguments"])}
for i, c in calls.items()}Three points: never drop the remainder; key by index, not name; and arguments is complete JSON only after finish_reason.
Three defaults that bite
- Keying by
nameorid. Both arenullafter the first chunk, so keying by them leaves you with seven empty shells. - Parsing arguments as they arrive, for a live UI. Seven of the eight fragments are invalid. All you can show is a "generating arguments" indicator; you cannot execute a tool on a partial parse.
- Applying Responses API patterns to Chat Completions. The Responses API emits semantic events:
response.function_call_arguments.deltafor fragments and.donecarrying the fullarguments. Chat Completions has you assembledelta.tool_calls[].function.argumentsyourself. The two parsers are not interchangeable.
Reproducing it
The script does three things: build the nine chunk events from that official output and serialize them; for each cut point feed the two segments in order; count whether nine events came back. The stateless reader produces 98.85%; swapping in either buffered version produces 0. Tighten it further by cutting more often — 200 double-cut pairs, or one cut every 7 bytes — and the conclusion holds: the stateful readers never miss, the stateless one never survives.
The shared trait of this bug class is that it never shows up in small local tests. Don't wait for production error rates to find it. Run a cut-point sweep in CI instead: a few hundred milliseconds, covering tens of thousands of packet splits.