diff --git a/src/openai/lib/streaming/responses/_responses.py b/src/openai/lib/streaming/responses/_responses.py index da4c00f845..23af68bb3c 100644 --- a/src/openai/lib/streaming/responses/_responses.py +++ b/src/openai/lib/streaming/responses/_responses.py @@ -394,6 +394,8 @@ def _create_initial_response(self, event: RawResponseStreamEvent) -> ParsedRespo raise RuntimeError(f"Expected to have received `response.created` before `{event.type}`") snapshot = construct_type_unchecked(type_=ParsedResponseSnapshot, value=event.response.to_dict()) + if getattr(snapshot, "output", None) is None: + snapshot.output = [] # Stream indexes can have gaps when a provider emits an empty added event. - self._output_items = dict(enumerate(snapshot.output or [])) + self._output_items = dict(enumerate(snapshot.output)) return snapshot diff --git a/tests/lib/responses/test_null_output.py b/tests/lib/responses/test_null_output.py index 4c782de03a..8113564e37 100644 --- a/tests/lib/responses/test_null_output.py +++ b/tests/lib/responses/test_null_output.py @@ -15,9 +15,12 @@ class Answer(BaseModel): @pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) +@pytest.mark.parametrize("initial_output", ["null", "missing", "empty"]) @pytest.mark.parametrize("terminal_output", ["null", "missing", "empty", "present"]) @pytest.mark.parametrize("has_items", [True, False], ids=["with-items", "without-items"]) -async def test_stream_recovers_finalized_output(sync: bool, terminal_output: str, has_items: bool) -> None: +async def test_stream_recovers_finalized_output( + sync: bool, initial_output: str, terminal_output: str, has_items: bool +) -> None: items: list[dict[str, object]] = ( [ { @@ -54,7 +57,9 @@ async def test_stream_recovers_finalized_output(sync: bool, terminal_output: str if has_items else [] ) - response: dict[str, object] = {"id": "resp_test", "status": "in_progress", "output": []} + response: dict[str, object] = {"id": "resp_test", "status": "in_progress"} + if initial_output != "missing": + response["output"] = None if initial_output == "null" else [] events: list[dict[str, object]] = [{"type": "response.created", "response": response}] for index, item in enumerate(items): added = {**item, "status": "in_progress"}