Skip to content

Commit 226630f

Browse files
committed
fix(lib): only raise finish-reason errors when there is parseable input
`parse_chat_completion` raised `LengthFinishReasonError` / `ContentFilterFinishReasonError` for any choice whose `finish_reason` was `length` / `content_filter`, regardless of whether structured-output parsing was requested. This is inconsistent with the streaming accumulator (`ChatCompletionStreamState._accumulate_chunk`), which only raises these when `has_parseable_input` is true. As a result a plain `client.chat.completions.stream(...)` (no `response_format` and no parseable tools) that stops at the token limit would iterate to completion without raising, but then raise `LengthFinishReasonError` from `get_final_completion()` — even though `client.chat.completions.create()` never raises for the same response and the length/content-filter restriction is documented only for `.parse()` (structured outputs). Guard both raises with `has_parseable_input`, mirroring the accumulator, so the errors are only raised when there is actually something to parse.
1 parent 8968560 commit 226630f

2 files changed

Lines changed: 60 additions & 2 deletions

File tree

‎src/openai/lib/_parsing/_completions.py‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,12 +104,20 @@ def parse_chat_completion(
104104
else:
105105
input_tools = []
106106

107+
# `length` / `content_filter` finish reasons only prevent us from producing a valid
108+
# parsed result when there is actually something to parse. For a plain completion
109+
# (no `response_format` and no parseable tools) there is nothing to parse, so we
110+
# mirror the streaming accumulator (`ChatCompletionStreamState`), which guards these
111+
# errors with `has_parseable_input`, and leave the completion untouched — matching
112+
# `chat.completions.create()`.
113+
raise_on_incomplete = has_parseable_input(response_format=response_format, input_tools=input_tools)
114+
107115
choices: list[ParsedChoice[ResponseFormatT]] = []
108116
for choice in chat_completion.choices:
109-
if choice.finish_reason == "length":
117+
if raise_on_incomplete and choice.finish_reason == "length":
110118
raise LengthFinishReasonError(completion=chat_completion)
111119

112-
if choice.finish_reason == "content_filter":
120+
if raise_on_incomplete and choice.finish_reason == "content_filter":
113121
raise ContentFilterFinishReasonError(completion=chat_completion)
114122

115123
message = choice.message

‎tests/lib/chat/test_completions_streaming.py‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
ParsedChatCompletionSnapshot,
3131
)
3232
from openai.lib._parsing._completions import ResponseFormatT
33+
from openai.types.chat.chat_completion_chunk import Choice as ChunkChoice, ChoiceDelta
3334

3435
from ..utils import print_obj
3536
from ...conftest import base_url
@@ -1110,6 +1111,55 @@ def streamer(client: OpenAI) -> Iterator[ChatCompletionChunk]:
11101111
)
11111112

11121113

1114+
def _chunk(delta: ChoiceDelta, finish_reason: str | None) -> ChatCompletionChunk:
1115+
return ChatCompletionChunk.construct(
1116+
id="chatcmpl-test",
1117+
object="chat.completion.chunk",
1118+
created=0,
1119+
model="gpt-4o-2024-08-06",
1120+
choices=[ChunkChoice.construct(index=0, delta=delta, finish_reason=finish_reason)],
1121+
)
1122+
1123+
1124+
def _content_chunk(text: str) -> ChatCompletionChunk:
1125+
return _chunk(ChoiceDelta.construct(role="assistant", content=text), finish_reason=None)
1126+
1127+
1128+
def _finish_chunk(finish_reason: str) -> ChatCompletionChunk:
1129+
return _chunk(ChoiceDelta.construct(), finish_reason=finish_reason)
1130+
1131+
1132+
@pytest.mark.parametrize("finish_reason", ["length", "content_filter"])
1133+
def test_non_parse_stream_terminal_finish_reason_does_not_raise(finish_reason: str) -> None:
1134+
# A plain stream (no `response_format` and no parseable tools) has nothing to parse,
1135+
# so a `length` / `content_filter` finish reason must not raise from
1136+
# `get_final_completion()` — matching `chat.completions.create()` and the
1137+
# streaming accumulator, which already suppresses these for non-parse streams.
1138+
state: ChatCompletionStreamState[None] = ChatCompletionStreamState()
1139+
1140+
# accumulating the chunks must not raise
1141+
state.handle_chunk(_content_chunk("partial answer that got cut o"))
1142+
state.handle_chunk(_finish_chunk(finish_reason))
1143+
1144+
completion = state.get_final_completion()
1145+
assert completion.choices[0].finish_reason == finish_reason
1146+
assert completion.choices[0].message.content == "partial answer that got cut o"
1147+
assert completion.choices[0].message.parsed is None
1148+
1149+
1150+
def test_parse_stream_length_finish_still_raises() -> None:
1151+
# When a `response_format` is given there *is* something to parse, so the terminal
1152+
# `length` finish reason must still raise (unchanged behavior).
1153+
class Location(BaseModel):
1154+
city: str
1155+
1156+
state: ChatCompletionStreamState[Location] = ChatCompletionStreamState(response_format=Location)
1157+
state.handle_chunk(_content_chunk('{"city":"San Francisc'))
1158+
1159+
with pytest.raises(openai.LengthFinishReasonError):
1160+
state.handle_chunk(_finish_chunk("length"))
1161+
1162+
11131163
@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"])
11141164
def test_stream_method_in_sync(sync: bool, client: OpenAI, async_client: AsyncOpenAI) -> None:
11151165
checking_client: OpenAI | AsyncOpenAI = client if sync else async_client

0 commit comments

Comments
 (0)