ChatCompletionStream.get_final_completion() can return an incomplete result after an early EOF

未关闭
#4,063 5 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
4/5
预计耗时
1-2 天
新手友好度
53/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
活跃
技术栈
python
领域
api, backend, testing

调研方向

Read src/openai/_streaming.py and src/openai/lib/streaming/chat/_completions.py, then trace how ChatCompletionStreamState.get_final_completion() handles a snapshot without a terminal finish_reason. Start by adapting the proposed offline reproduction and the repository’s streaming test harness for both sync and async paths. Done means early EOF cannot yield a successful final completion, while normal terminal chunks still work.

由索引模型根据 Issue 内容生成。

描述

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
  1. src/openai/_streaming.py (~lines 62–117 / 177–232): the base Stream / AsyncStream loops until [DONE] or iterator exhaustion, without recording which condition ended the loop.
  2. src/openai/lib/streaming/chat/_completions.py (~lines 93–119 and 216–242): get_final_completion() consumes that iterator with until_done(), then unconditionally calls ChatCompletionStreamState.get_final_completion().
  3. The state helper (~lines 326–336) calls parse_chat_completion on the current snapshot and explicitly notes that the helper itself does not guarantee the stream finished.
  4. src/openai/lib/_parsing/_completions.py (~lines 96–166) only checks for finish_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_snapshot rather 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 base Stream necessarily 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
  • #2486 / #3263 concern Responses API structured-output parsing/incomplete responses. This is specific to Chat Completions get_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.

主要语言
Python
星标
32.2k
派生
5.8k
平均合并
12 小时 29 分钟
30 天内合并 PR
112

环境准备

在 Codespaces 中打开

在浏览器里用你自己的 GitHub 账号启动这个项目的开发容器。

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

openai/openai-python 的其他 Issue

查看 openai/openai-python 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。