Skip to content
Hands-on4 min readPublished 2026-11-29Reviewed 2027-11-29

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 arguments field 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 style2,262 single cut points200 double-cut pairs323 cuts at every 7 bytes
Split each chunk by \n, json.loads immediately (stateless)2,236 failures, 98.85%all 200 pairs failfails at the first cut
Line buffer: split on \n, keep the remainder for the next feed0 failures0 failuresnever fails
Event buffer: split on blank lines0 failures0 failuresnever 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:

FragmentBytesjson.loads
"" (empty string in the first chunk)0invalid
{"2invalid
location8invalid
":"3valid (parses to the string ":")
Paris5invalid
,1invalid
France7invalid
"}2invalid

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:

python
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 ​

  1. Keying by name or id. Both are null after the first chunk, so keying by them leaves you with seven empty shells.
  2. 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.
  3. Applying Responses API patterns to Chat Completions. The Responses API emits semantic events: response.function_call_arguments.delta for fragments and .done carrying the full arguments. Chat Completions has you assemble delta.tool_calls[].function.arguments yourself. 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.

OpenAIChat · Full-stack engineering for LLM-powered conversations and apps