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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(responses): use OpenAI SSEDecoder for Responses API streaming (#28566)
Sameer Kankute21a21e01f7e5
diff --git a/litellm/responses/streaming_iterator.py b/litellm/responses/streaming_iterator.pyindex da8da1b486f..c4e72cb7dc5 100644--- a/litellm/responses/streaming_iterator.py+++ b/litellm/responses/streaming_iterator.py@@ -9,6 +9,7 @@ from functools import lru_cachefrom typing import Any, Dict, List, Literal, Optionalimport httpx+from openai._streaming import SSEDecoderimport litellmfrom litellm.constants import (@@ -27,7 +28,7 @@ from litellm.llms.base_llm.responses.transformation import BaseResponsesAPIConfifrom litellm.responses.utils import ResponsesAPIRequestUtilsfrom litellm.types.llms.openai import ResponsesAPIStreamEventsfrom litellm.types.utils import CallTypes-from litellm.utils import CustomStreamWrapper, async_post_call_success_deployment_hook+from litellm.utils import async_post_call_success_deployment_hook@lru_cache(maxsize=1)@@ -120,10 +121,10 @@ class BaseResponsesAPIStreamingIterator:if not chunk:return None- # Handle SSE format (data: {...})- chunk = CustomStreamWrapper._strip_sse_data_from_chunk(chunk)- if chunk is None:- return None+ # NOTE: ``SSEDecoder`` already strips the SSE ``data:`` field prefix, so+ # the value passed in here is the raw field content. Do not re-run+ # ``_strip_sse_data_from_chunk`` on it — doing so would incorrectly mangle+ # payloads whose actual JSON value happens to start with ``data:``.# Handle "[DONE]" markerif chunk == STREAM_SSE_DONE_STRING:@@ -634,7 +635,7 @@ class ResponsesAPIStreamingIterator(BaseResponsesAPIStreamingIterator):request_data,call_type,)- self.stream_iterator = response.aiter_lines()+ self.stream_iterator = SSEDecoder().aiter_bytes(response.aiter_bytes())def __aiter__(self):return self@@ -645,13 +646,13 @@ class ResponsesAPIStreamingIterator(BaseResponsesAPIStreamingIterator):while True:# Get the next chunk from the streamtry:- chunk = await self.stream_iterator.__anext__()+ sse = await self.stream_iterator.__anext__()except StopAsyncIteration:self.finished = Trueraise StopAsyncIterationself._check_max_streaming_duration()- result = self._process_chunk(chunk)+ result = self._process_chunk(sse.data)if self.finished:raise StopAsyncIteration@@ -708,7 +709,7 @@ class SyncResponsesAPIStreamingIterator(BaseResponsesAPIStreamingIterator):request_data,call_type,)- self.stream_iterator = response.iter_lines()+ self.stream_iterator = SSEDecoder().iter_bytes(response.iter_bytes())def __iter__(self):return self@@ -719,13 +720,13 @@ class SyncResponsesAPIStreamingIterator(BaseResponsesAPIStreamingIterator):while True:# Get the next chunk from the streamtry:- chunk = next(self.stream_iterator)+ sse = next(self.stream_iterator)except StopIteration:self.finished = Trueraise StopIterationself._check_max_streaming_duration()- result = self._process_chunk(chunk)+ result = self._process_chunk(sse.data)if self.finished:raise StopIterationdiff --git a/tests/llm_responses_api_testing/test_base_responses_api_streaming_iterator.py b/tests/llm_responses_api_testing/test_base_responses_api_streaming_iterator.pyindex e2c50810cc2..37fcc602d37 100644--- a/tests/llm_responses_api_testing/test_base_responses_api_streaming_iterator.py+++ b/tests/llm_responses_api_testing/test_base_responses_api_streaming_iterator.py@@ -41,6 +41,62 @@ from litellm.types.llms.openai import (class TestBaseResponsesAPIStreamingIterator:"""Test cases for BaseResponsesAPIStreamingIterator"""+ @pytest.mark.asyncio+ async def test_responses_streaming_iterator_parses_u2028_in_sse_json(self):+ """+ U+2028 inside JSON must not split the SSE event. httpx aiter_lines uses+ str.splitlines() and drops response.completed; OpenAI SSEDecoder does not.+ """+ from litellm.responses.streaming_iterator import ResponsesAPIStreamingIterator++ u2028 = "\u2028"+ payload = json.dumps(+ {+ "type": "response.completed",+ "response": {"instructions": f"eligible{u2028}promo"},+ }+ )+ sse_bytes = f"data: {payload}\n\n".encode("utf-8")++ async def mock_aiter_bytes():+ yield sse_bytes++ mock_response = Mock()+ mock_response.headers = {}+ mock_response.aiter_bytes = mock_aiter_bytes++ mock_logging_obj = Mock(spec=LiteLLMLoggingObj)+ mock_logging_obj.model_call_details = {"litellm_params": {}}+ mock_config = Mock(spec=BaseResponsesAPIConfig)++ mock_responses_api_response = Mock(spec=ResponsesAPIResponse)+ mock_responses_api_response.id = "resp_u2028"+ mock_completed_event = Mock(spec=ResponseCompletedEvent)+ mock_completed_event.type = ResponsesAPIStreamEvents.RESPONSE_COMPLETED+ mock_completed_event.response = mock_responses_api_response+ mock_config.transform_streaming_response.return_value = mock_completed_event++ iterator = ResponsesAPIStreamingIterator(+ response=mock_response,+ model="gpt-5.5",+ responses_api_provider_config=mock_config,+ logging_obj=mock_logging_obj,+ litellm_metadata={"model_info": {"id": "model_123"}},+ custom_llm_provider="openai",+ )++ chunks = []+ with (+ patch("asyncio.create_task"),+ patch("litellm.responses.streaming_iterator.executor"),+ ):+ async for chunk in iterator:+ chunks.append(chunk)++ assert len(chunks) == 1+ assert chunks[0].type == ResponsesAPIStreamEvents.RESPONSE_COMPLETED+ assert iterator.completed_response is not None+def test_process_chunk_with_response_completed_event(self):"""Test that _process_chunk correctly processes a ResponseCompletedEvent@@ -270,7 +326,7 @@ class TestBaseResponsesAPIStreamingIterator:# Mock dependenciesmock_response = Mock()mock_response.headers = {}- mock_response.aiter_lines = Mock()+ mock_response.aiter_bytes = Mock()mock_logging_obj = Mock(spec=LiteLLMLoggingObj)mock_logging_obj.model_call_details = {"litellm_params": {}}mock_logging_obj.async_success_handler = Mock()@@ -334,12 +390,10 @@ class TestBaseResponsesAPIStreamingIterator:mock_response = Mock()mock_response.headers = {}- # Create an async iterator that raises StopAsyncIteration after yielding one chunk- async def mock_aiter_lines():- yield 'data: {"type": "response.output_text.delta", "delta": "test"}'- # Normal end of stream - raise StopAsyncIteration+ async def mock_aiter_bytes():+ yield b'data: {"type": "response.output_text.delta", "delta": "test"}\n\n'- mock_response.aiter_lines = mock_aiter_lines+ mock_response.aiter_bytes = mock_aiter_bytesmock_logging_obj = Mock(spec=LiteLLMLoggingObj)mock_logging_obj.model_call_details = {"litellm_params": {}}@@ -396,12 +450,10 @@ class TestBaseResponsesAPIStreamingIterator:mock_response = Mock()mock_response.headers = {}- # Create a sync iterator that raises StopIteration after yielding one chunk- def mock_iter_lines():- yield 'data: {"type": "response.output_text.delta", "delta": "test"}'- # Normal end of stream - raise StopIteration+ def mock_iter_bytes():+ yield b'data: {"type": "response.output_text.delta", "delta": "test"}\n\n'- mock_response.iter_lines = mock_iter_lines+ mock_response.iter_bytes = mock_iter_bytesmock_logging_obj = Mock(spec=LiteLLMLoggingObj)mock_logging_obj.model_call_details = {"litellm_params": {}}@@ -450,7 +502,7 @@ class TestBaseResponsesAPIStreamingIterator:mock_response = Mock()mock_response.headers = {}- mock_response.aiter_lines = Mock()+ mock_response.aiter_bytes = Mock()mock_logging_obj = Mock(spec=LiteLLMLoggingObj)mock_logging_obj.model_call_details = {"litellm_params": {}}mock_logging_obj.async_failure_handler = Mock()@@ -532,7 +584,7 @@ class TestBaseResponsesAPIStreamingIterator:mock_response = Mock()mock_response.headers = {}- mock_response.aiter_lines = Mock()+ mock_response.aiter_bytes = Mock()mock_logging_obj = Mock(spec=LiteLLMLoggingObj)mock_logging_obj.model_call_details = {"litellm_params": {}}mock_logging_obj.async_failure_handler = Mock()