openai-python icon indicating copy to clipboard operation
openai-python copied to clipboard

Streaming helpers re-parse the whole accumulated JSON on every delta (quadratic in output size)

Open deadstrobe5 opened this issue 1 month ago • 3 comments

ChatCompletionStreamState._accumulate_chunk (src/openai/lib/streaming/chat/_completions.py) calls from_json(bytes(..., "utf-8"), partial_mode=True) on the full accumulated message.content (with a response_format model) and on the full accumulated arguments of strict function tools, on every delta. Streaming one structured output or tool call therefore costs O(n²) in its size.

Here is the parse cost alone, for a tool argument that writes a file, in 10-byte deltas (CPython 3.14, jiter, median of 5):

arguments deltas time in from_json
4 KB 502 0.7 ms
20 KB 2,499 12.6 ms
70 KB 8,739 141 ms

Because partial_mode=True drops an unterminated trailing string, a delta that only extends an open string cannot change parsed / parsed_arguments. Tracking the string and escape state incrementally (including \uXXXX and surrogates) lets those parses be skipped, and anything unusual can still fall back to jiter, so values and errors stay the same. The same fix in the Anthropic Python SDK gave 2.5x at 4 KB and 24x at 74 KB end to end, with a differential test over 2M+ events: anthropics/anthropic-sdk-python#2022.

import json, time
from jiter import from_json

doc = json.dumps({"path": "a.py", "content": "def f(x):\n    return x * 2\n" * 2500})
t = time.perf_counter(); acc = ""
for i in range(0, len(doc), 10):
    acc += doc[i:i + 10]
    from_json(bytes(acc, "utf-8"), partial_mode=True)  # what _accumulate_chunk does per delta
print(f"{len(doc)} bytes: {(time.perf_counter() - t) * 1000:.1f} ms")

deadstrobe5 avatar Oct 16 '26 18:10 deadstrobe5

I have a minimal fix passing all CI suites that avoids the quadratic parsing cost on streaming structured outputs by incrementally tracking string boundaries and only re-parsing with jiter when tokens fall outside open string literals: https://github.com/mohmedmm/openai-python/tree/perf-streaming-json-delta

Happy to open the PR if collaborator/interaction limits allow, or maintainers can cherry-pick commit 5610707.

mohmedmm avatar Oct 17 '26 22:10 mohmedmm

Thanks for the report! We’re closing this for now. If this is affecting your application in production, please share a representative workload and benchmarks showing the impact—we’d be happy to take another look.

marcuswood-oai avatar Oct 22 '26 21:10 marcuswood-oai

Here is a concrete benchmark measuring streaming tool call arguments for a code-generation agent writing ~48 KB and ~112 KB payloads in 15-byte deltas (CPython 3.12, jiter):

  • 48 KB (3,303 deltas): baseline takes 44.3 ms in rom_json across 3,303 full re-parses; with string-boundary tracking it takes 3.6 ms (4 parses, 3,299 skipped), a 12.3x speedup.
  • 112 KB (7,700 deltas): baseline blocks the event loop for 227.8 ms of CPU time; string-boundary tracking takes 7.3 ms (31.1x speedup).

For async agents handling concurrent streams, saving 200+ ms of synchronous JSON parsing per stream directly unblocks the event loop. Happy to share the standalone repro script or open the PR if you'd like to take a look.

mohmedmm avatar Oct 22 '26 22:10 mohmedmm