Repository navigation
Description
Confirm this is an issue with the Python library and not an underlying OpenAI API
- This report is about the SDK's handling of a synthetic, prematurely terminated stream, not about why a live API connection might close.
- Checked the current default-branch implementation and searched for an equivalent Chat Completions streaming report.
- Reproduced against a fully installed SDK — not run yet (source-traced behavior below).
Summary
In the synchronous and asynchronous Chat Completions streaming helpers, a normally ending underlying iterator is treated as completion even when no chunk supplied a finish_reason. get_final_completion() then parses the accumulated snapshot and can return partially generated content or tool-call arguments as a successful final completion.
This is different from response.completed-based Responses API streaming: this report concerns client.chat.completions.stream(...).get_final_completion().
Minimal regression test to confirm (offline; no API key)
This isolates the parsing state after a last chunk with finish_reason=None. It is proposed reproduction code, not a test claimed to have passed:
from openai._types import omit
from openai.types.chat import ChatCompletionChunk
from openai.lib.streaming.chat._completions import ChatCompletionStreamState
state = ChatCompletionStreamState(response_format=omit, input_tools=omit)
chunk = ChatCompletionChunk.model_validate({
"id": "chatcmpl_test",
"object": "chat.completion.chunk",
"created": 0,
"model": "gpt-4o-mini",
"choices": [{
"index": 0,
"delta": {"role": "assistant", "content": "incomplete answer"},
"finish_reason": None,
}],
})
list(state.handle_chunk(chunk))
result = state.get_final_completion()
print(result.choices[0].message.content, result.choices[0].finish_reason)
# Source path suggests: "incomplete answer", None, without raising.For the public .stream() path, feed that one chunk via a scripted/mock Stream[ChatCompletionChunk] that then ends cleanly, without a terminal choice chunk and [DONE]. Verify that get_final_completion() either raises an incomplete-stream exception or explicitly exposes its incompleteness; the current code does neither.
Why this happens
src/openai/_streaming.py(~lines 62–117 / 177–232): the baseStream/AsyncStreamloops until[DONE]or iterator exhaustion, without recording which condition ended the loop.src/openai/lib/streaming/chat/_completions.py(~lines 93–119 and 216–242):get_final_completion()consumes that iterator withuntil_done(), then unconditionally callsChatCompletionStreamState.get_final_completion().- The state helper (~lines 326–336) calls
parse_chat_completionon the current snapshot and explicitly notes that the helper itself does not guarantee the stream finished. src/openai/lib/_parsing/_completions.py(~lines 96–166) only checks forfinish_reason == 'length'and'content_filter'; a missing / null finish reason is not rejected.
A clean early EOF can therefore turn a partially received answer into an apparently successful result. This is particularly risky for agent callers that consume tool-call JSON or treat get_final_completion() as an integrity boundary.
Expected
- The public Chat Completion streaming helper should not report a successful final completion when a requested choice has not delivered a terminal
finish_reason(or another documented end-of-message indicator). - Keep successful parsing for streams that finish normally, including valid truncated-by-token-limit terminal reasons, which already have dedicated error semantics for parsed outputs.
- Preserve behavior when users intentionally stop iteration early and inspect
current_completion_snapshotrather than request a final result. - Consider capturing whether the underlying stream saw
[DONE], to distinguish a clean EOF from an explicit protocol terminator where appropriate; not every endpoint using the shared baseStreamnecessarily follows the same convention.
Regression test suggestions
- Sync/async: a chunk with
finish_reason=None, then transport EOF -> no successful final completion. - Sync/async: normal terminal
finish_reason='stop'(and standard stream terminator) -> final completion works. - Partial function-call arguments before EOF -> must not silently be accepted as a completed tool call.
Related but not a duplicate
- Incomplete responses are not handled by
parse_responsewhen using Structured Output #2486 / Responses streaming structured output parses incomplete JSON before terminal incomplete status #3263 concern Responses API structured-output parsing/incomplete responses. This is specific to Chat Completionsget_final_completion()and its missing terminal choice guard.
I can follow up with a complete integration test based on the repository's streaming test harness if maintainers agree this behavior should be considered a bug.
Activity
ducanhnguyen223 commentedon Oct 14, 2026
I reproduced the public helper path against current default-branch head
86cae50785fb7b7bf2a5d2383370b214b304acd2(SDK 3.31.0), fully offline withhttpx2.MockTransportand a fake local API key; no API call was made.For both
OpenAIandAsyncOpenAI, the mock returned one valid SSE chunk with assistant contentpartial answerandfinish_reason: null, then clean EOF without[DONE]. Bothstream.get_final_completion()andawait stream.get_final_completion()returnedmessage.content == "partial answer"andfinish_reason is Noneinstead of flagging the completion as incomplete.This confirms the proposed state-only reproduction through both public sync and async entrypoints. A regression test can cover this EOF path alongside a control stream ending with
finish_reason="stop"and[DONE].qiyuhuating commentedon Oct 15, 2026
Thanks for reproducing this through both public entrypoints, @ducanhnguyen223. Your results fill the verification gap in my original report. Covering this EOF case alongside a normally terminated stream sounds like the right regression test.
EngineeringWithJay commentedon Oct 17, 2026
Adding a fuller offline reproduction with a control pair, on openai 3.34.0 / httpx 0.28.1 (complements @ducanhnguyen223's content-only case on 3.31.0):
finish_reason="tool_calls", usage,[DONE]→get_final_completion()returns arguments{"value":42}withfinish_reason="tool_calls".{"value":), with no[DONE]→ both sync and asyncget_final_completion()return normally, retaining the incomplete arguments andfinish_reason=Noneinstead of flagging the completion as incomplete. Regression assertions for exactly this case fail while the control pair passes (4 passed / 2 failed).Everything is offline — synthetic fixtures, fake key,
httpx.MockTransport; two separate-process runs produced byte-identical JSON with zero network attempts. AI-assisted, and happy to detail that if useful. Fixtures, tests, and raw runs: https://github.com/EngineeringWithJay/openai-4063-stream-eof-evidence — happy to open a PR if that works for maintainers (I checked CONTRIBUTING first; most of the SDK is generated, so a test-only change may be the right shape).Shanmukh-l33t commentedon Nov 11, 2026
Thanks @ducanhnguyen223 and @EngineeringWithJay — building directly on your reproductions here (not racing them; no fix branch was claimed, so this is analysis + a tested branch, no PR per CONTRIBUTING).
Root cause
The accumulation is not lossy — I checked the folding path first and every chunk is merged into the snapshot before its events are yielded (
ChatCompletionStreamState.handle_chunk→_accumulate_chunk, called fromChatCompletionStream.__stream__,src/openai/lib/streaming/chat/_completions.py). The defect is a missing terminal-completeness guard:Stream.__stream__/AsyncStream.__stream__(src/openai/_streaming.py) breaks ondata: [DONE], but on EOF it just ends the generator. Nothing recorded which termination happened, so an EOF-truncated stream is indistinguishable from a cleanly terminated one.ChatCompletionStream.get_final_completion()(andAsyncChatCompletionStream.get_final_completion(),src/openai/lib/streaming/chat/_completions.py) dountil_done()and then returnself._state.get_final_completion()unconditionally — so whatever had accumulated (finish_reason=None, tool-call arguments cut mid-string, no usage) is returned as the "final" completion, silently.Notably the Responses-stream sibling already guards exactly this class of bug:
ResponseStream.get_final_response()raisesRuntimeError("Didn't receive a `response.completed` event.")when the terminal event never arrived (src/openai/lib/streaming/responses/_responses.py). The Chat Completions helper simply lacked the equivalent guard.Fix
Branch:
fix/4063-get-final-completion-eofon https://github.com/Shanmukh-l33t/openai-python (headfd220adc772e72fd95b73a96993184a7dce862c0, 1 commit off currentmain).Compare: main...Shanmukh-l33t:openai-python:fix/4063-get-final-completion-eof
src/openai/_streaming.py—Stream/AsyncStreamnow setself._terminated = Truewhen the loop terminates via the[DONE]sentinel (purely additive; no behavior change for any API).src/openai/lib/streaming/chat/_completions.py— sync + asyncget_final_completion()raiseRuntimeError("Didn't receive a `[DONE]` event - the stream ended prematurely (e.g. early EOF or connection close) so the accumulated completion may be incomplete.")when the stream did not terminate via[DONE], mirroring the Responses guard.Rationale for raising instead of "returning a complete result": the missing data (finish_reason chunk, usage chunk, the rest of the tool-call arguments) only exists server-side after the cut — it cannot be reconstructed client-side. The surrounding style for a missing terminal signal in a
get_final_*helper is a clearRuntimeError(theresponses/_responses.pyguard above), so the EOF path now fails loudly instead of silently returning an incomplete object. Iteration andcurrent_completion_snapshotstay permissive, and manualChatCompletionStreamState.get_final_completion()is unchanged (its docstring already disclaims guarantees).Responses.get_final_response()needed no change — its guard already existed.RED / GREEN evidence (fully offline:
httpx2.MockTransport, fake API key, no network)New tests:
tests/lib/chat/test_final_completion_eof.py— @EngineeringWithJay's control-pair shape (full tool-call +finish_reason="tool_calls"+ usage +[DONE]vs. tool-call arguments cut mid-string at{"value":with no finish_reason/usage/[DONE]), plus @ducanhnguyen223's content-only EOF case, on bothOpenAIandAsyncOpenAI.stream()helpers.RED at unmodified parent (
141a89aa7fbb7f13a979bda930831a5fe38bc3a4) — 4 failed, 4 passed:DID NOT RAISE RuntimeError):test_get_final_completion_raises_on_early_eof_tool_call_sync,..._tool_call_async,test_get_final_completion_raises_on_early_eof_content_sync,..._content_asynctest_get_final_completion_control_completed_stream_sync/async,test_iteration_and_snapshot_unaffected_by_early_eof_sync/asyncfinish_reason=None,tool_calls[0].function.arguments='{"value":'(cut mid-string),usage=None— vs. the control'sfinish_reason='tool_calls',arguments='{"value":42}',usage.total_tokens=3. Content-only EOF:content='partial answer',finish_reason=None.GREEN after the fix — 8 passed. Full suite
pytest tests -n 2 -q: 21454 passed, 206 skipped (0 failures).ruff check,ruff format,ty checkclean on the changed files.Happy to open this as a PR if a maintainer invites one. AI-assisted (Hermes Agent, Nous Research) — all evidence above is reproducible offline from the linked branch.
MohibShaikh commentedon Nov 12, 2026
Same result on openai 3.49.0 / httpx2 2.16.0 (and on 2.54.0 / httpx 0.28.1), Python 3.13.5, this time over a real loopback HTTP connection instead of a mocked transport.
Two early-EOF cases. Each is a clean HTTP end with no
finish_reasonand no[DONE]:create(stream=True).stream()+get_final_completion()"Hello, world",finish_reason=None, nothing raised{"city": "Par, then EOFfinish_reason=None, nothing raisedExpected: some signal that the stream ended without a terminal chunk.
One related case that is not an early EOF, in case it helps scope the fix. Two parallel tool calls, the second cut at
{"tz": "U, followed by a normalfinish_reason="tool_calls"and[DONE]. Both entry points return one intact call and one that does not parse. A check on[DONE]orfinish_reasonalone would still pass this one, so it may deserve its own regression test or its own issue. Happy to open one if that is preferred.When the server aborts a chunked body mid-stream, 3.49.0 does raise (
APIConnectionError), so the gap is only the clean EOF.The streams are fixed fixtures served by a small local fake server, so this can be rerun against any SDK version: https://github.com/MohibShaikh/streamfault (
examples/python/openai_sdk_probe.py, with my output underobserved/). They are synthetic. I am not claiming the API sends them.Daniel-Kim-Grata commentedon Nov 26, 2026
One case where checking only for
[DONE]wouldn't catch the problem: passn=2, let choice 0 finish withfinish_reason="stop", and never send choice 1.I ran this offline on SDK 3.60.0, httpx2 2.16.2, and Python 3.12.11 using the public sync and async
chat.completions.stream()helpers. Both return[(0, "stop")]fromget_final_completion(), whether the stream ends at EOF or sends[DONE]. The control with both choices returns both. In this case, every returned choice has a finish reason, but one requested choice vanished.Minimal sync repro (no network):
I’d add this as a regression alongside the EOF cases if checking the requested choice count is in scope. If you’d like me to work on that part of the fix, what’s the best way to contribute it?
Candidate fix: fork commit 2981c68, based on v3.60.0/current main. It checks for fewer choices only when multiple choices were explicitly requested and leaves partial snapshots and raw streams alone. Eight targeted sync/async cases reproduced on base; all 28 targeted cases pass with the patch. Ruff lint and formatting checks passed for the changed files; I did not run the full SDK suite. I used AI assistance to prepare the patch and verified it offline. No upstream PR opened, per the contribution guide.
renya728 commentedon Nov 30, 2026
Good discussion. One thing I'd add: if you're juggling several providers, a single compatible endpoint saves a lot of glue code. I use sandapi.ai (https://opensand.ai/) for that — one key, works with most OpenAI-style clients. Not the only option out there, but it's been reliable for me.
renya728 commentedon Nov 30, 2026
Good discussion. One thing I'd add: if you're juggling several providers, a single compatible endpoint saves a lot of glue code. I use sandapi.ai (https://opensand.ai/) for that — one key, works with most OpenAI-style clients. Not the only option out there, but it's been reliable for me.