Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

refactor(responses): rebuild the streaming snapshot output instead of mutating items

mateo-berri05ee5756e7c0
diff --git a/litellm/responses/litellm_completion_transformation/streaming_iterator.py b/litellm/responses/litellm_completion_transformation/streaming_iterator.py
index 2a94fcb2a89..ff05fc0d5c6 100644
--- a/litellm/responses/litellm_completion_transformation/streaming_iterator.py
+++ b/litellm/responses/litellm_completion_transformation/streaming_iterator.py
@@ -48,6 +48,22 @@ from litellm.types.utils import (
)
+def _output_items_with_id(items: tuple[Any, ...], item_type: str, item_id: str | None) -> tuple[Any, ...]:
+ if item_id is None:
+ return items
+
+ target_index: Final = next(
+ (index for index, item in enumerate(items) if getattr(item, "type", None) == item_type),
+ None,
+ )
+ if target_index is None:
+ return items
+
+ return tuple(
+ item.model_copy(update={"id": item_id}) if index == target_index else item for index, item in enumerate(items)
+ )
+
+
class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):
"""
Async iterator for processing streaming responses from the Responses API.
@@ -1059,34 +1075,18 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):
chat_completion_delta: Final[ChatCompletionDelta] = choice.delta
return chat_completion_delta.content or ""
- def _align_output_item_ids_with_streamed_ids(self, responses_api_response: ResponsesAPIResponse) -> None:
+ def _output_with_streamed_item_ids(self, responses_api_response: ResponsesAPIResponse) -> tuple[Any, ...]:
"""
Reuse the item IDs already emitted by the incremental streaming events in the
``response.completed`` snapshot, so a streaming client that replays the snapshot
sends back the same IDs it observed mid-stream.
"""
- self._set_first_output_item_id(responses_api_response, "message", self._cached_item_id)
- self._set_first_output_item_id(responses_api_response, "reasoning", self._cached_reasoning_item_id)
-
- @staticmethod
- def _set_first_output_item_id(
- responses_api_response: ResponsesAPIResponse,
- item_type: str,
- cached_id: str | None,
- ) -> None:
- if cached_id is None:
- return
-
- for item in getattr(responses_api_response, "output", None) or []:
- current_type = item.get("type") if isinstance(item, dict) else getattr(item, "type", None)
- if current_type != item_type:
- continue
-
- if isinstance(item, dict):
- item["id"] = cached_id
- else:
- item.id = cached_id
- return
+ message_aligned: Final = _output_items_with_id(
+ tuple(responses_api_response.output or ()),
+ "message",
+ self._cached_item_id,
+ )
+ return _output_items_with_id(message_aligned, "reasoning", self._cached_reasoning_item_id)
def _emit_response_completed_event(self, litellm_model_response: ModelResponse) -> ResponseCompletedEvent | None:
if litellm_model_response:
@@ -1113,7 +1113,7 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):
if self._cached_response_id:
responses_api_response.id = self._cached_response_id
- self._align_output_item_ids_with_streamed_ids(responses_api_response)
+ responses_api_response.output = list(self._output_with_streamed_item_ids(responses_api_response))
# Encode the response ID to match non-streaming behavior
encoded_response: Final = ResponsesAPIRequestUtils._update_responses_api_response_id_with_model_id(
diff --git a/tests/test_litellm/responses/litellm_completion_transformation/test_image_generation_output.py b/tests/test_litellm/responses/litellm_completion_transformation/test_image_generation_output.py
index 41057d49a97..a0bf8664551 100644
--- a/tests/test_litellm/responses/litellm_completion_transformation/test_image_generation_output.py
+++ b/tests/test_litellm/responses/litellm_completion_transformation/test_image_generation_output.py
@@ -199,3 +199,47 @@ class TestExtractMessageOutputItemsIntegration:
assert len(result) == 1
assert isinstance(result[0], GenericResponseOutputItem)
assert result[0].type == "message"
+
+
+class TestImageGenerationOutputItemIds:
+ """Image generation call IDs must use the ig_ prefix (issue #27333).
+
+ Native OpenAI Responses validates the prefix before it looks the item up, so a
+ replayed chatcmpl-*_img_N ID is rejected outright.
+ """
+
+ def _choice_with_images(self, count):
+ mock_message = Mock(spec=Message)
+ mock_message.images = [
+ {"image_url": {"url": f"data:image/png;base64,IMG{idx}"}}
+ for idx in range(count)
+ ]
+ mock_choice = Mock(spec=Choices)
+ mock_choice.message = mock_message
+ mock_choice.finish_reason = "stop"
+ return mock_choice
+
+ def _chat_completion_response(self):
+ mock_response = Mock(spec=ModelResponse)
+ mock_response.id = "chatcmpl-dfa2da3a-1586-4ff7-b64e-f59c692a5d11"
+ return mock_response
+
+ def test_image_generation_item_id_uses_ig_prefix(self):
+ result = LiteLLMCompletionResponsesConfig._extract_image_generation_output_items(
+ chat_completion_response=self._chat_completion_response(),
+ choice=self._choice_with_images(2),
+ )
+
+ assert len(result) == 2
+ for item in result:
+ assert item.id.startswith("ig_")
+ assert "chatcmpl-" not in item.id
+ assert "_img_" not in item.id
+
+ def test_image_generation_item_ids_are_unique(self):
+ result = LiteLLMCompletionResponsesConfig._extract_image_generation_output_items(
+ chat_completion_response=self._chat_completion_response(),
+ choice=self._choice_with_images(3),
+ )
+
+ assert len({item.id for item in result}) == 3
diff --git a/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py b/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py
index daa732e032a..0a2621b94e6 100644
--- a/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py
+++ b/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py
@@ -3771,3 +3771,177 @@ def test_function_call_tool_id_falls_back_to_unique_id_for_degenerate_call_id():
id="fc_2", call_id="call_tokyo", name="get_weather", arguments="{}"
)
assert convert(openai)["id"] == "call_tokyo"
+
+
+BRIDGED_CHAT_COMPLETION_ID = "chatcmpl-dfa2da3a-1586-4ff7-b64e-f59c692a5d11"
+
+
+def _bridged_chat_completion_response(**overrides):
+ defaults = dict(
+ id=BRIDGED_CHAT_COMPLETION_ID,
+ created=1717000000,
+ model="claude-sonnet-4-5",
+ object="chat.completion",
+ choices=[
+ Choices(
+ index=0,
+ finish_reason="stop",
+ message=Message(role="assistant", content="apple"),
+ )
+ ],
+ usage=Usage(prompt_tokens=10, completion_tokens=5, total_tokens=15),
+ )
+ defaults.update(overrides)
+ return ModelResponse(**defaults)
+
+
+def _bridged_output_items(response, item_type):
+ return [item for item in response.output if getattr(item, "type", None) == item_type]
+
+
+class TestBridgedOutputItemIdPrefixes:
+ """Bridged output items must carry Responses API ID prefixes (issue #27333).
+
+ Native OpenAI Responses rejects a replayed history whose message item ID does not
+ begin with "msg", so leaking the upstream chatcmpl-* ID makes the conversation
+ impossible to hand off from a bridged provider to OpenAI.
+ """
+
+ def _transform(self, chat_completion_response):
+ return LiteLLMCompletionResponsesConfig.transform_chat_completion_response_to_responses_api_response(
+ request_input="Say the single word: apple",
+ responses_api_request={},
+ chat_completion_response=chat_completion_response,
+ )
+
+ def test_message_item_id_uses_msg_prefix(self):
+ response = self._transform(_bridged_chat_completion_response())
+
+ message_items = _bridged_output_items(response, "message")
+ assert len(message_items) == 1
+ assert message_items[0].id.startswith("msg_")
+
+ def test_message_item_id_does_not_leak_chat_completion_id(self):
+ response = self._transform(_bridged_chat_completion_response())
+
+ for item in _bridged_output_items(response, "message"):
+ assert item.id != BRIDGED_CHAT_COMPLETION_ID
+ assert not item.id.startswith("chatcmpl-")
+
+ def test_message_item_ids_are_unique_across_responses(self):
+ first = self._transform(_bridged_chat_completion_response())
+ second = self._transform(_bridged_chat_completion_response())
+
+ first_id = _bridged_output_items(first, "message")[0].id
+ second_id = _bridged_output_items(second, "message")[0].id
+ assert first_id != second_id
+
+ def _reasoning_items(self):
+ message = Message(role="assistant", content="apple")
+ message.reasoning_content = "thinking about fruit"
+ choice = Choices(index=0, finish_reason="stop", message=message)
+ return LiteLLMCompletionResponsesConfig._extract_reasoning_output_items(
+ chat_completion_response=_bridged_chat_completion_response(),
+ choices=[choice],
+ )
+
+ def test_reasoning_item_id_uses_rs_prefix(self):
+ items = self._reasoning_items()
+
+ assert len(items) == 1
+ assert items[0].id.startswith("rs_")
+
+ def test_reasoning_item_id_is_not_a_salted_hash(self):
+ """Python's hash() is salted per process, so the old rs_{hash(...)} ID for the
+ same reasoning text differed between workers and across restarts."""
+ suffix = self._reasoning_items()[0].id.removeprefix("rs_")
+
+ assert not suffix.lstrip("-").isdigit()
+ assert not suffix.startswith("-")
+
+
+class TestStreamingSnapshotItemIds:
+ """The response.completed snapshot must reuse the streamed item ID (issue #27333).
+
+ The incremental events already minted msg_* IDs while the final snapshot went back
+ through the non-streaming transform, so a streaming client replaying the snapshot
+ sent back an ID it had never been shown.
+ """
+
+ def _make_iterator(self):
+ from unittest.mock import Mock
+
+ import litellm
+ from litellm.responses.litellm_completion_transformation.streaming_iterator import (
+ LiteLLMCompletionStreamingIterator,
+ )
+
+ mock_stream_wrapper = Mock(spec=litellm.CustomStreamWrapper)
+ mock_stream_wrapper.logging_obj = Mock()
+ return LiteLLMCompletionStreamingIterator(
+ model="anthropic/claude-sonnet-4-5",
+ litellm_custom_stream_wrapper=mock_stream_wrapper,
+ request_input="Say the single word: apple",
+ responses_api_request={},
+ custom_llm_provider="anthropic",
+ )
+
+ def _make_chunk(self, content):
+ from litellm.types.utils import Delta, ModelResponseStream, StreamingChoices
+
+ return ModelResponseStream(
+ id=BRIDGED_CHAT_COMPLETION_ID,
+ choices=[
+ StreamingChoices(
+ index=0,
+ delta=Delta(content=content, role="assistant"),
+ finish_reason=None,
+ )
+ ],
+ created=1717000000,
+ model="claude-sonnet-4-5",
+ object="chat.completion.chunk",
+ )
+
+ def test_incremental_item_id_uses_msg_prefix(self):
+ iterator = self._make_iterator()
+
+ event = iterator._transform_chat_completion_chunk_to_response_api_chunk(
+ self._make_chunk("apple")
+ )
+
+ assert event is not None
+ assert event.item_id.startswith("msg_")
+ assert event.item_id != BRIDGED_CHAT_COMPLETION_ID
+
+ def test_completed_snapshot_reuses_streamed_item_id(self):
+ iterator = self._make_iterator()
+
+ streamed_event = iterator._transform_chat_completion_chunk_to_response_api_chunk(
+ self._make_chunk("apple")
+ )
+ assert streamed_event is not None
+
+ completed_event = iterator._emit_response_completed_event(
+ _bridged_chat_completion_response()
+ )
+
+ assert completed_event is not None
+ message_items = _bridged_output_items(completed_event.response, "message")
+ assert len(message_items) == 1
+ assert message_items[0].id == streamed_event.item_id
+
+ def test_completed_snapshot_item_id_is_replayable(self):
+ iterator = self._make_iterator()
+ iterator._transform_chat_completion_chunk_to_response_api_chunk(
+ self._make_chunk("apple")
+ )
+
+ completed_event = iterator._emit_response_completed_event(
+ _bridged_chat_completion_response()
+ )
+
+ assert completed_event is not None
+ for item in _bridged_output_items(completed_event.response, "message"):
+ assert item.id.startswith("msg_")
+ assert not item.id.startswith("chatcmpl-")
diff --git a/tests/test_litellm/responses/litellm_completion_transformation/test_response_output_item_id_prefixes.py b/tests/test_litellm/responses/litellm_completion_transformation/test_response_output_item_id_prefixes.py
deleted file mode 100644
index 4b24b2be90d..00000000000
--- a/tests/test_litellm/responses/litellm_completion_transformation/test_response_output_item_id_prefixes.py
+++ /dev/null
@@ -1,214 +0,0 @@
-"""
-Regression tests for the Chat Completions -> Responses API bridge item IDs.
-
-Bridged output items must carry Responses API ID prefixes (msg_, ig_, rs_) rather
-than the upstream chatcmpl-* ID. Native OpenAI Responses rejects a replayed history
-whose message item ID does not begin with "msg", and rejects an image generation
-call whose ID does not begin with "ig".
-
-Regression test for https://github.com/BerriAI/litellm/issues/27333
-"""
-
-from unittest.mock import Mock
-
-import litellm
-from litellm.responses.litellm_completion_transformation.streaming_iterator import (
- LiteLLMCompletionStreamingIterator,
-)
-from litellm.responses.litellm_completion_transformation.transformation import (
- LiteLLMCompletionResponsesConfig,
-)
-from litellm.types.utils import (
- Choices,
- Delta,
- Message,
- ModelResponse,
- ModelResponseStream,
- StreamingChoices,
- Usage,
-)
-
-CHAT_COMPLETION_ID = "chatcmpl-dfa2da3a-1586-4ff7-b64e-f59c692a5d11"
-
-
-def _make_chat_completion_response(**overrides) -> ModelResponse:
- defaults = dict(
- id=CHAT_COMPLETION_ID,
- created=1717000000,
- model="claude-sonnet-4-5",
- object="chat.completion",
- choices=[
- Choices(
- index=0,
- finish_reason="stop",
- message=Message(role="assistant", content="apple"),
- )
- ],
- usage=Usage(prompt_tokens=10, completion_tokens=5, total_tokens=15),
- )
- defaults.update(overrides)
- return ModelResponse(**defaults)
-
-
-def _transform(chat_completion_response):
- return LiteLLMCompletionResponsesConfig.transform_chat_completion_response_to_responses_api_response(
- request_input="Say the single word: apple",
- responses_api_request={},
- chat_completion_response=chat_completion_response,
- )
-
-
-def _output_items_of_type(response, item_type):
- return [item for item in response.output if getattr(item, "type", None) == item_type]
-
-
-class TestMessageOutputItemIds:
- def test_message_item_id_uses_msg_prefix(self):
- response = _transform(_make_chat_completion_response())
-
- message_items = _output_items_of_type(response, "message")
- assert len(message_items) == 1
- assert message_items[0].id.startswith("msg_")
-
- def test_message_item_id_does_not_leak_chat_completion_id(self):
- response = _transform(_make_chat_completion_response())
-
- for item in _output_items_of_type(response, "message"):
- assert item.id != CHAT_COMPLETION_ID
- assert not item.id.startswith("chatcmpl-")
-
- def test_message_item_ids_are_unique_across_responses(self):
- first = _transform(_make_chat_completion_response())
- second = _transform(_make_chat_completion_response())
-
- first_id = _output_items_of_type(first, "message")[0].id
- second_id = _output_items_of_type(second, "message")[0].id
- assert first_id != second_id
-
-
-class TestImageGenerationOutputItemIds:
- def _make_choice_with_images(self, count):
- message = Mock(spec=Message)
- message.images = [
- {"image_url": {"url": f"data:image/png;base64,IMG{idx}"}} for idx in range(count)
- ]
- choice = Mock(spec=Choices)
- choice.message = message
- choice.finish_reason = "stop"
- return choice
-
- def test_image_generation_item_id_uses_ig_prefix(self):
- items = LiteLLMCompletionResponsesConfig._extract_image_generation_output_items(
- chat_completion_response=_make_chat_completion_response(),
- choice=self._make_choice_with_images(2),
- )
-
- assert len(items) == 2
- for item in items:
- assert item.id.startswith("ig_")
- assert "chatcmpl-" not in item.id
- assert "_img_" not in item.id
-
- def test_image_generation_item_ids_are_unique(self):
- items = LiteLLMCompletionResponsesConfig._extract_image_generation_output_items(
- chat_completion_response=_make_chat_completion_response(),
- choice=self._make_choice_with_images(3),
- )
-
- assert len({item.id for item in items}) == 3
-
-
-class TestReasoningOutputItemIds:
- def _reasoning_items(self):
- message = Message(role="assistant", content="apple")
- message.reasoning_content = "thinking about fruit"
- choice = Choices(index=0, finish_reason="stop", message=message)
- return LiteLLMCompletionResponsesConfig._extract_reasoning_output_items(
- chat_completion_response=_make_chat_completion_response(),
- choices=[choice],
- )
-
- def test_reasoning_item_id_uses_rs_prefix(self):
- items = self._reasoning_items()
-
- assert len(items) == 1
- assert items[0].id.startswith("rs_")
-
- def test_reasoning_item_id_is_not_a_salted_hash(self):
- item_id = self._reasoning_items()[0].id
-
- suffix = item_id.removeprefix("rs_")
- assert not suffix.lstrip("-").isdigit()
- assert not suffix.startswith("-")
-
-
-class TestStreamingItemIdConsistency:
- def _make_iterator(self):
- mock_stream_wrapper = Mock(spec=litellm.CustomStreamWrapper)
- mock_stream_wrapper.logging_obj = Mock()
- return LiteLLMCompletionStreamingIterator(
- model="anthropic/claude-sonnet-4-5",
- litellm_custom_stream_wrapper=mock_stream_wrapper,
- request_input="Say the single word: apple",
- responses_api_request={},
- custom_llm_provider="anthropic",
- )
-
- def _make_chunk(self, chunk_id, content, finish_reason=None):
- return ModelResponseStream(
- id=chunk_id,
- choices=[
- StreamingChoices(
- index=0,
- delta=Delta(content=content, role="assistant"),
- finish_reason=finish_reason,
- )
- ],
- created=1717000000,
- model="claude-sonnet-4-5",
- object="chat.completion.chunk",
- )
-
- def test_incremental_item_id_uses_msg_prefix(self):
- iterator = self._make_iterator()
-
- event = iterator._transform_chat_completion_chunk_to_response_api_chunk(
- self._make_chunk(CHAT_COMPLETION_ID, "apple")
- )
-
- assert event is not None
- assert event.item_id.startswith("msg_")
- assert event.item_id != CHAT_COMPLETION_ID
-
- def test_completed_snapshot_reuses_streamed_item_id(self):
- iterator = self._make_iterator()
-
- streamed_event = iterator._transform_chat_completion_chunk_to_response_api_chunk(
- self._make_chunk(CHAT_COMPLETION_ID, "apple")
- )
- assert streamed_event is not None
- streamed_item_id = streamed_event.item_id
-
- completed_event = iterator._emit_response_completed_event(
- _make_chat_completion_response()
- )
-
- assert completed_event is not None
- message_items = _output_items_of_type(completed_event.response, "message")
- assert len(message_items) == 1
- assert message_items[0].id == streamed_item_id
-
- def test_completed_snapshot_item_id_is_replayable(self):
- iterator = self._make_iterator()
- iterator._transform_chat_completion_chunk_to_response_api_chunk(
- self._make_chunk(CHAT_COMPLETION_ID, "apple")
- )
-
- completed_event = iterator._emit_response_completed_event(
- _make_chat_completion_response()
- )
-
- assert completed_event is not None
- for item in _output_items_of_type(completed_event.response, "message"):
- assert item.id.startswith("msg_")
- assert not item.id.startswith("chatcmpl-")