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]

fix: check for model_response_choices before guardrail input (#19784)

Alexander Grattancc76f95555b5
diff --git a/litellm/integrations/custom_guardrail.py b/litellm/integrations/custom_guardrail.py
index a5bb530fc56..1652ec2aa0c 100644
--- a/litellm/integrations/custom_guardrail.py
+++ b/litellm/integrations/custom_guardrail.py
@@ -475,11 +475,18 @@ class CustomGuardrail(CustomLogger):
guardrail_config: DynamicGuardrailParams = DynamicGuardrailParams(
**guardrail[self.guardrail_name]
)
+ extra_body = guardrail_config.get("extra_body", {})
if self._validate_premium_user() is not True:
+ if isinstance(extra_body, dict) and extra_body:
+ verbose_logger.warning(
+ "Guardrail %s: ignoring dynamic extra_body keys %s because premium_user is False",
+ self.guardrail_name,
+ list(extra_body.keys()),
+ )
return {}
# Return the extra_body if it exists, otherwise empty dict
- return guardrail_config.get("extra_body", {})
+ return extra_body
return {}
diff --git a/litellm/llms/anthropic/chat/guardrail_translation/handler.py b/litellm/llms/anthropic/chat/guardrail_translation/handler.py
index 8e1016bd5bd..a14e7d118e8 100644
--- a/litellm/llms/anthropic/chat/guardrail_translation/handler.py
+++ b/litellm/llms/anthropic/chat/guardrail_translation/handler.py
@@ -34,6 +34,7 @@ from litellm.types.llms.openai import (
)
from litellm.types.utils import (
ChatCompletionMessageToolCall,
+ Choices,
GenericGuardrailAPIInputs,
ModelResponse,
)
@@ -76,7 +77,8 @@ class AnthropicMessagesHandler(BaseTranslation):
chat_completion_compatible_request, tool_name_mapping = (
LiteLLMAnthropicMessagesAdapter().translate_anthropic_to_openai(
- anthropic_message_request=cast(AnthropicMessagesRequest, data)
+ # Use a shallow copy to avoid mutating request data (pop on litellm_metadata).
+ anthropic_message_request=cast(AnthropicMessagesRequest, data.copy())
)
)
@@ -84,9 +86,9 @@ class AnthropicMessagesHandler(BaseTranslation):
texts_to_check: List[str] = []
images_to_check: List[str] = []
- tools_to_check: List[ChatCompletionToolParam] = (
- chat_completion_compatible_request.get("tools", [])
- )
+ tools_to_check: List[
+ ChatCompletionToolParam
+ ] = chat_completion_compatible_request.get("tools", [])
task_mappings: List[Tuple[int, Optional[int]]] = []
# Track (message_index, content_index) for each text
# content_index is None for string content, int for list content
@@ -282,7 +284,10 @@ class AnthropicMessagesHandler(BaseTranslation):
if hasattr(content_block, "model_dump"):
block_dict = content_block.model_dump()
else:
- block_dict = {"type": block_type, "text": getattr(content_block, "text", None)}
+ block_dict = {
+ "type": block_type,
+ "text": getattr(content_block, "text", None),
+ }
else:
continue
@@ -358,30 +363,40 @@ class AnthropicMessagesHandler(BaseTranslation):
"""
has_ended = self._check_streaming_has_ended(responses_so_far)
if has_ended:
-
# build the model response from the responses_so_far
- model_response = cast(
- ModelResponse,
- AnthropicPassthroughLoggingHandler._build_complete_streaming_response(
- all_chunks=responses_so_far,
- litellm_logging_obj=cast("LiteLLMLoggingObj", litellm_logging_obj),
- model="",
- ),
- )
- tool_calls_list = cast(Optional[List[ChatCompletionMessageToolCall]], model_response.choices[0].message.tool_calls) # type: ignore
- string_so_far = model_response.choices[0].message.content # type: ignore
- guardrail_inputs = GenericGuardrailAPIInputs()
- if string_so_far:
- guardrail_inputs["texts"] = [string_so_far]
- if tool_calls_list:
- guardrail_inputs["tool_calls"] = tool_calls_list
-
- _guardrailed_inputs = await guardrail_to_apply.apply_guardrail( # allow rejecting the response, if invalid
- inputs=guardrail_inputs,
- request_data={},
- input_type="response",
- logging_obj=litellm_logging_obj,
+ built_response = AnthropicPassthroughLoggingHandler._build_complete_streaming_response(
+ all_chunks=responses_so_far,
+ litellm_logging_obj=cast("LiteLLMLoggingObj", litellm_logging_obj),
+ model="",
)
+
+ # Check if model_response is valid and has choices before accessing
+ if (
+ built_response is not None
+ and hasattr(built_response, "choices")
+ and built_response.choices
+ ):
+ model_response = cast(ModelResponse, built_response)
+ first_choice = cast(Choices, model_response.choices[0])
+ tool_calls_list = cast(
+ Optional[List[ChatCompletionMessageToolCall]],
+ first_choice.message.tool_calls,
+ )
+ string_so_far = first_choice.message.content
+ guardrail_inputs = GenericGuardrailAPIInputs()
+ if string_so_far:
+ guardrail_inputs["texts"] = [string_so_far]
+ if tool_calls_list:
+ guardrail_inputs["tool_calls"] = tool_calls_list
+
+ _guardrailed_inputs = await guardrail_to_apply.apply_guardrail( # allow rejecting the response, if invalid
+ inputs=guardrail_inputs,
+ request_data={},
+ input_type="response",
+ logging_obj=litellm_logging_obj,
+ )
+ else:
+ verbose_proxy_logger.debug("Skipping output guardrail - model response has no choices")
return responses_so_far
string_so_far = self.get_streaming_string_so_far(responses_so_far)
@@ -648,7 +663,10 @@ class AnthropicMessagesHandler(BaseTranslation):
if isinstance(content_block, dict):
if content_block.get("type") == "text":
cast(Dict[str, Any], content_block)["text"] = guardrail_response
- elif hasattr(content_block, "type") and getattr(content_block, "type", None) == "text":
+ elif (
+ hasattr(content_block, "type")
+ and getattr(content_block, "type", None) == "text"
+ ):
# Update Pydantic object's text attribute
if hasattr(content_block, "text"):
content_block.text = guardrail_response
diff --git a/litellm/llms/openai/chat/guardrail_translation/handler.py b/litellm/llms/openai/chat/guardrail_translation/handler.py
index fb00aa28f45..c406f502b45 100644
--- a/litellm/llms/openai/chat/guardrail_translation/handler.py
+++ b/litellm/llms/openai/chat/guardrail_translation/handler.py
@@ -21,7 +21,13 @@ from litellm._logging import verbose_proxy_logger
from litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslation
from litellm.main import stream_chunk_builder
from litellm.types.llms.openai import ChatCompletionToolParam
-from litellm.types.utils import Choices, GenericGuardrailAPIInputs, ModelResponse, ModelResponseStream, StreamingChoices
+from litellm.types.utils import (
+ Choices,
+ GenericGuardrailAPIInputs,
+ ModelResponse,
+ ModelResponseStream,
+ StreamingChoices,
+)
if TYPE_CHECKING:
from litellm.integrations.custom_guardrail import CustomGuardrail
@@ -80,9 +86,9 @@ class OpenAIChatCompletionsHandler(BaseTranslation):
if tool_calls_to_check:
inputs["tool_calls"] = tool_calls_to_check # type: ignore
if messages:
- inputs["structured_messages"] = (
- messages # pass the openai /chat/completions messages to the guardrail, as-is
- )
+ inputs[
+ "structured_messages"
+ ] = messages # pass the openai /chat/completions messages to the guardrail, as-is
# Pass tools (function definitions) to the guardrail
tools = data.get("tools")
if tools:
@@ -362,14 +368,17 @@ class OpenAIChatCompletionsHandler(BaseTranslation):
# check if the stream has ended
has_stream_ended = False
for chunk in responses_so_far:
- if chunk.choices[0].finish_reason is not None:
+ if chunk.choices and chunk.choices[0].finish_reason is not None:
has_stream_ended = True
break
if has_stream_ended:
# convert to model response
model_response = cast(
- ModelResponse, stream_chunk_builder(chunks=responses_so_far, logging_obj=litellm_logging_obj)
+ ModelResponse,
+ stream_chunk_builder(
+ chunks=responses_so_far, logging_obj=litellm_logging_obj
+ ),
)
# run process_output_response
await self.process_output_response(
diff --git a/litellm/llms/openai/responses/guardrail_translation/handler.py b/litellm/llms/openai/responses/guardrail_translation/handler.py
index d943662f9e4..ad3d4c932d4 100644
--- a/litellm/llms/openai/responses/guardrail_translation/handler.py
+++ b/litellm/llms/openai/responses/guardrail_translation/handler.py
@@ -319,9 +319,7 @@ class OpenAIResponsesHandler(BaseTranslation):
return response
if not response_output:
- verbose_proxy_logger.debug(
- "OpenAI Responses API: Empty output in response"
- )
+ verbose_proxy_logger.debug("OpenAI Responses API: Empty output in response")
return response
# Step 1: Extract all text content and tool calls from response output
@@ -427,27 +425,30 @@ class OpenAIResponsesHandler(BaseTranslation):
handle_raw_dict_callback=None,
)
- tool_calls = model_response_choices[0].message.tool_calls
- text = model_response_choices[0].message.content
- guardrail_inputs = GenericGuardrailAPIInputs()
- if text:
- guardrail_inputs["texts"] = [text]
- if tool_calls:
- guardrail_inputs["tool_calls"] = cast(
- List[ChatCompletionToolCallChunk], tool_calls
- )
- # Include model information from the response if available
- response_model = final_chunk.get("response", {}).get("model")
- if response_model:
- guardrail_inputs["model"] = response_model
- if tool_calls or text:
- _guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
- inputs=guardrail_inputs,
- request_data={},
- input_type="response",
- logging_obj=litellm_logging_obj,
- )
- return responses_so_far
+ if model_response_choices:
+ tool_calls = model_response_choices[0].message.tool_calls
+ text = model_response_choices[0].message.content
+ guardrail_inputs = GenericGuardrailAPIInputs()
+ if text:
+ guardrail_inputs["texts"] = [text]
+ if tool_calls:
+ guardrail_inputs["tool_calls"] = cast(
+ List[ChatCompletionToolCallChunk], tool_calls
+ )
+ # Include model information from the response if available
+ response_model = final_chunk.get("response", {}).get("model")
+ if response_model:
+ guardrail_inputs["model"] = response_model
+ if tool_calls or text:
+ _guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
+ inputs=guardrail_inputs,
+ request_data={},
+ input_type="response",
+ logging_obj=litellm_logging_obj,
+ )
+ return responses_so_far
+ else:
+ verbose_proxy_logger.debug("Skipping output guardrail - model response has no choices")
# model_response_stream = OpenAiResponsesToChatCompletionStreamIterator.translate_responses_chunk_to_openai_stream(final_chunk)
# tool_calls = model_response_stream.choices[0].tool_calls
# convert openai response to model response
@@ -513,11 +514,9 @@ class OpenAIResponsesHandler(BaseTranslation):
# Check if it's an OutputText with text
if isinstance(content_item, OutputText):
if content_item.text:
-
return True
elif isinstance(content_item, dict):
if content_item.get("text"):
-
return True
return False
diff --git a/tests/test_litellm/llms/anthropic/chat/guardrail_translation/test_anthropic_guardrail_handler.py b/tests/test_litellm/llms/anthropic/chat/guardrail_translation/test_anthropic_guardrail_handler.py
new file mode 100644
index 00000000000..82517b7af9e
--- /dev/null
+++ b/tests/test_litellm/llms/anthropic/chat/guardrail_translation/test_anthropic_guardrail_handler.py
@@ -0,0 +1,236 @@
+"""
+Unit tests for Anthropic Messages Guardrail Translation Handler
+
+Tests the handler's ability to process streaming output for Anthropic Messages API
+with guardrail transformations, specifically testing edge cases with empty choices.
+"""
+
+import os
+import sys
+from typing import Any, List, Literal, Optional
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+sys.path.insert(
+ 0, os.path.abspath("../../../../../../..")
+) # Adds the parent directory to the system path
+
+from litellm.integrations.custom_guardrail import CustomGuardrail
+from litellm.llms.anthropic.chat.guardrail_translation.handler import (
+ AnthropicMessagesHandler,
+)
+from litellm.types.utils import GenericGuardrailAPIInputs
+
+
+class MockPassThroughGuardrail(CustomGuardrail):
+ """Mock guardrail that passes through without blocking - for testing streaming fallback behavior"""
+
+ async def apply_guardrail(
+ self,
+ inputs: GenericGuardrailAPIInputs,
+ request_data: dict,
+ input_type: Literal["request", "response"],
+ logging_obj: Optional[Any] = None,
+ ) -> GenericGuardrailAPIInputs:
+ """Simply return inputs unchanged"""
+ return inputs
+
+
+class MockDynamicGuardrail(CustomGuardrail):
+ """Mock guardrail that records dynamic params from request metadata."""
+
+ def __init__(self, guardrail_name: str):
+ super().__init__(guardrail_name=guardrail_name)
+ self.dynamic_params: Optional[dict] = None
+
+ async def apply_guardrail(
+ self,
+ inputs: GenericGuardrailAPIInputs,
+ request_data: dict,
+ input_type: Literal["request", "response"],
+ logging_obj: Optional[Any] = None,
+ ) -> GenericGuardrailAPIInputs:
+ self.dynamic_params = self.get_guardrail_dynamic_request_body_params(
+ request_data
+ )
+ return inputs
+
+
+class TestAnthropicMessagesHandlerStreamingOutputProcessing:
+ """Test streaming output processing functionality"""
+
+ @pytest.mark.asyncio
+ async def test_process_output_streaming_response_empty_model_response(self):
+ """Test that streaming response with None model_response doesn't raise error
+
+ This test verifies the fix for the bug where accessing model_response.choices[0]
+ would raise an error when _build_complete_streaming_response returns None.
+ """
+ handler = AnthropicMessagesHandler()
+ guardrail = MockPassThroughGuardrail(guardrail_name="test")
+
+ # Mock _check_streaming_has_ended to return True (stream ended)
+ # and _build_complete_streaming_response to return None
+ with patch.object(
+ handler, "_check_streaming_has_ended", return_value=True
+ ), patch(
+ "litellm.llms.anthropic.chat.guardrail_translation.handler.AnthropicPassthroughLoggingHandler._build_complete_streaming_response",
+ return_value=None,
+ ):
+ responses_so_far = [b"data: some chunk"]
+
+ # This should not raise an error
+ result = await handler.process_output_streaming_response(
+ responses_so_far=responses_so_far,
+ guardrail_to_apply=guardrail,
+ litellm_logging_obj=MagicMock(),
+ )
+
+ # Should return the responses unchanged
+ assert result == responses_so_far
+
+
+class TestAnthropicMessagesHandlerInputProcessing:
+ """Test input processing preserves litellm_metadata for dynamic guardrails."""
+
+ @pytest.mark.asyncio
+ async def test_process_input_messages_preserves_litellm_metadata_guardrails(self):
+ handler = AnthropicMessagesHandler()
+ guardrail = MockDynamicGuardrail(guardrail_name="cygnal-monitor")
+
+ data = {
+ "model": "claude-3-5-sonnet-20241022",
+ "messages": [{"role": "user", "content": "hello"}],
+ "litellm_metadata": {
+ "guardrails": [
+ {
+ "cygnal-monitor": {
+ "extra_body": {"policy_id": "policy-123"}
+ }
+ }
+ ]
+ },
+ }
+
+ with patch("litellm.proxy.proxy_server.premium_user", True):
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert data.get("litellm_metadata", {}).get("guardrails")
+ assert guardrail.dynamic_params == {"policy_id": "policy-123"}
+
+ @pytest.mark.asyncio
+ async def test_process_output_streaming_response_empty_choices(self):
+ """Test that streaming response with empty choices doesn't raise IndexError
+
+ This test verifies the fix for the bug where accessing model_response.choices[0]
+ would raise IndexError when the response has an empty choices list.
+ """
+ from litellm.types.utils import ModelResponse
+
+ handler = AnthropicMessagesHandler()
+ guardrail = MockPassThroughGuardrail(guardrail_name="test")
+
+ # Create a mock response with empty choices
+ mock_response = ModelResponse(
+ id="msg_123",
+ created=1234567890,
+ model="claude-3",
+ object="chat.completion",
+ choices=[], # Empty choices
+ )
+
+ # Mock _check_streaming_has_ended to return True (stream ended)
+ # and _build_complete_streaming_response to return the mock response
+ with patch.object(
+ handler, "_check_streaming_has_ended", return_value=True
+ ), patch(
+ "litellm.llms.anthropic.chat.guardrail_translation.handler.AnthropicPassthroughLoggingHandler._build_complete_streaming_response",
+ return_value=mock_response,
+ ):
+ responses_so_far = [b"data: some chunk"]
+
+ # This should not raise IndexError
+ result = await handler.process_output_streaming_response(
+ responses_so_far=responses_so_far,
+ guardrail_to_apply=guardrail,
+ litellm_logging_obj=MagicMock(),
+ )
+
+ # Should return the responses unchanged
+ assert result == responses_so_far
+
+ @pytest.mark.asyncio
+ async def test_process_output_streaming_response_with_valid_choices(self):
+ """Test that streaming response with valid choices still works correctly"""
+ from litellm.types.utils import Choices, Message, ModelResponse
+
+ handler = AnthropicMessagesHandler()
+ guardrail = MockPassThroughGuardrail(guardrail_name="test")
+
+ # Create a mock response with valid choices
+ mock_response = ModelResponse(
+ id="msg_123",
+ created=1234567890,
+ model="claude-3",
+ object="chat.completion",
+ choices=[
+ Choices(
+ finish_reason="stop",
+ index=0,
+ message=Message(
+ content="Hello world",
+ role="assistant",
+ ),
+ )
+ ],
+ )
+
+ # Mock _check_streaming_has_ended to return True (stream ended)
+ # and _build_complete_streaming_response to return the mock response
+ with patch.object(
+ handler, "_check_streaming_has_ended", return_value=True
+ ), patch(
+ "litellm.llms.anthropic.chat.guardrail_translation.handler.AnthropicPassthroughLoggingHandler._build_complete_streaming_response",
+ return_value=mock_response,
+ ):
+ responses_so_far = [b"data: some chunk"]
+
+ # This should process successfully
+ result = await handler.process_output_streaming_response(
+ responses_so_far=responses_so_far,
+ guardrail_to_apply=guardrail,
+ litellm_logging_obj=MagicMock(),
+ )
+
+ # Should return the responses
+ assert result == responses_so_far
+
+ @pytest.mark.asyncio
+ async def test_process_output_streaming_response_stream_not_ended(self):
+ """Test that streaming response falls back to text processing when stream hasn't ended"""
+ handler = AnthropicMessagesHandler()
+ guardrail = MockPassThroughGuardrail(guardrail_name="test")
+
+ # Mock _check_streaming_has_ended to return False (stream not ended)
+ with patch.object(
+ handler, "_check_streaming_has_ended", return_value=False
+ ), patch.object(
+ handler, "get_streaming_string_so_far", return_value="partial text"
+ ):
+ responses_so_far = [b"data: some chunk"]
+
+ # This should process successfully using text-based guardrail
+ result = await handler.process_output_streaming_response(
+ responses_so_far=responses_so_far,
+ guardrail_to_apply=guardrail,
+ litellm_logging_obj=MagicMock(),
+ )
+
+ # Should return the responses
+ assert result == responses_so_far
+
+
+if __name__ == "__main__":
+ # Run the tests
+ pytest.main([__file__, "-v"])
diff --git a/tests/test_litellm/llms/openai/chat/guardrail_translation/test_openai_guardrail_handler.py b/tests/test_litellm/llms/openai/chat/guardrail_translation/test_openai_guardrail_handler.py
index 6c0195d2831..1f5f53d0f0c 100644
--- a/tests/test_litellm/llms/openai/chat/guardrail_translation/test_openai_guardrail_handler.py
+++ b/tests/test_litellm/llms/openai/chat/guardrail_translation/test_openai_guardrail_handler.py
@@ -733,6 +733,154 @@ class TestOpenAIChatCompletionsHandlerToolCallsOutput:
assert response.choices[0].finish_reason == "tool_calls"
+class MockPassThroughGuardrail(CustomGuardrail):
+ """Mock guardrail that passes through without blocking - for testing streaming fallback behavior"""
+
+ async def apply_guardrail(
+ self,
+ inputs: GenericGuardrailAPIInputs,
+ request_data: dict,
+ input_type: Literal["request", "response"],
+ logging_obj: Optional[Any] = None,
+ ) -> GenericGuardrailAPIInputs:
+ """Simply return inputs unchanged"""
+ return inputs
+
+
+class TestOpenAIChatCompletionsHandlerStreamingOutput:
+ """Test streaming output processing functionality"""
+
+ @pytest.mark.asyncio
+ async def test_process_output_streaming_response_empty_choices(self):
+ """Test that streaming response with empty choices doesn't raise IndexError
+
+ This test verifies the fix for the bug where accessing chunk.choices[0]
+ would raise IndexError when a streaming chunk has an empty choices list.
+ """
+ from litellm.types.utils import Delta, ModelResponseStream, StreamingChoices
+
+ handler = OpenAIChatCompletionsHandler()
+ guardrail = MockPassThroughGuardrail(guardrail_name="test")
+
+ # Create a streaming chunk with empty choices
+ chunk_with_empty_choices = ModelResponseStream(
+ id="chatcmpl-123",
+ created=1234567890,
+ model="gpt-4",
+ object="chat.completion.chunk",
+ choices=[], # Empty choices - this was causing the IndexError
+ )
+
+ responses_so_far = [chunk_with_empty_choices]
+
+ # This should not raise IndexError
+ result = await handler.process_output_streaming_response(
+ responses_so_far=responses_so_far,
+ guardrail_to_apply=guardrail,
+ litellm_logging_obj=None,
+ )
+
+ # Should return the responses unchanged
+ assert result == responses_so_far
+
+ @pytest.mark.asyncio
+ async def test_process_output_streaming_response_with_valid_choices(self):
+ """Test that streaming response with valid choices still works correctly"""
+ from litellm.types.utils import Delta, ModelResponseStream, StreamingChoices
+
+ handler = OpenAIChatCompletionsHandler()
+ guardrail = MockPassThroughGuardrail(guardrail_name="test")
+
+ # Create streaming chunks with valid choices
+ chunk1 = ModelResponseStream(
+ id="chatcmpl-123",
+ created=1234567890,
+ model="gpt-4",
+ object="chat.completion.chunk",
+ choices=[
+ StreamingChoices(
+ index=0,
+ delta=Delta(content="Hello"),
+ finish_reason=None,
+ )
+ ],
+ )
+
+ chunk2 = ModelResponseStream(
+ id="chatcmpl-123",
+ created=1234567890,
+ model="gpt-4",
+ object="chat.completion.chunk",
+ choices=[
+ StreamingChoices(
+ index=0,
+ delta=Delta(content=" world"),
+ finish_reason="stop",
+ )
+ ],
+ )
+
+ responses_so_far = [chunk1, chunk2]
+
+ # This should process successfully
+ result = await handler.process_output_streaming_response(
+ responses_so_far=responses_so_far,
+ guardrail_to_apply=guardrail,
+ litellm_logging_obj=None,
+ )
+
+ # Should return the responses
+ assert result == responses_so_far
+
+ @pytest.mark.asyncio
+ async def test_process_output_streaming_response_mixed_empty_and_valid_choices_no_finish(self):
+ """Test streaming response with mix of empty and valid choices chunks (stream not finished)
+
+ This tests the has_stream_ended check when iterating through chunks with mixed choices.
+ The stream hasn't finished yet (no finish_reason), so it won't trigger stream_chunk_builder.
+ """
+ from litellm.types.utils import Delta, ModelResponseStream, StreamingChoices
+
+ handler = OpenAIChatCompletionsHandler()
+ guardrail = MockPassThroughGuardrail(guardrail_name="test")
+
+ # Mix of chunks - some with empty choices, some with valid choices
+ # Stream hasn't finished (no finish_reason)
+ chunk_empty = ModelResponseStream(
+ id="chatcmpl-123",
+ created=1234567890,
+ model="gpt-4",
+ object="chat.completion.chunk",
+ choices=[],
+ )
+
+ chunk_valid = ModelResponseStream(
+ id="chatcmpl-123",
+ created=1234567890,
+ model="gpt-4",
+ object="chat.completion.chunk",
+ choices=[
+ StreamingChoices(
+ index=0,
+ delta=Delta(content="Hello"),
+ finish_reason=None, # Stream not finished
+ )
+ ],
+ )
+
+ responses_so_far = [chunk_empty, chunk_valid]
+
+ # This should not raise IndexError when checking has_stream_ended
+ result = await handler.process_output_streaming_response(
+ responses_so_far=responses_so_far,
+ guardrail_to_apply=guardrail,
+ litellm_logging_obj=None,
+ )
+
+ # Should return the responses
+ assert result == responses_so_far
+
+
if __name__ == "__main__":
# Run the tests
pytest.main([__file__, "-v"])
diff --git a/tests/test_litellm/llms/openai/responses/test_openai_responses_guardrail_handler.py b/tests/test_litellm/llms/openai/responses/test_openai_responses_guardrail_handler.py
index a2849ab91a2..ccece8018ff 100644
--- a/tests/test_litellm/llms/openai/responses/test_openai_responses_guardrail_handler.py
+++ b/tests/test_litellm/llms/openai/responses/test_openai_responses_guardrail_handler.py
@@ -817,3 +817,181 @@ class TestOpenAIResponsesHandlerToolCallExtraction:
assert task_mappings[0] == (0, 0)
assert task_mappings[1] == (0, 1)
assert task_mappings[2] == (0, 2)
+
+
+class MockPassThroughGuardrail(CustomGuardrail):
+ """Mock guardrail that passes through without blocking - for testing streaming fallback behavior"""
+
+ async def apply_guardrail(
+ self,
+ inputs: GenericGuardrailAPIInputs,
+ request_data: dict,
+ input_type: Literal["request", "response"],
+ logging_obj: Optional[Any] = None,
+ ) -> GenericGuardrailAPIInputs:
+ """Simply return inputs unchanged"""
+ return inputs
+
+
+class TestOpenAIResponsesHandlerStreamingOutputProcessing:
+ """Test streaming output processing functionality"""
+
+ @pytest.mark.asyncio
+ async def test_process_output_streaming_response_empty_output(self):
+ """Test that streaming response with empty output doesn't raise IndexError
+
+ This test verifies the fix for the bug where accessing model_response_choices[0]
+ would raise IndexError when the response.completed event has an empty output array.
+ """
+ handler = OpenAIResponsesHandler()
+ guardrail = MockPassThroughGuardrail(guardrail_name="test")
+
+ # Simulate a response.completed streaming event with empty output
+ responses_so_far = [
+ {
+ "type": "response.completed",
+ "response": {
+ "id": "resp_123",
+ "output": [], # Empty output - this was causing the IndexError
+ "status": "completed",
+ },
+ }
+ ]
+
+ # This should not raise IndexError
+ result = await handler.process_output_streaming_response(
+ responses_so_far=responses_so_far,
+ guardrail_to_apply=guardrail,
+ litellm_logging_obj=None,
+ )
+
+ # Should return the responses unchanged
+ assert result == responses_so_far
+
+ @pytest.mark.asyncio
+ async def test_process_output_streaming_response_missing_output_key(self):
+ """Test that streaming response with missing output key doesn't raise IndexError
+
+ This test verifies the handler gracefully handles when the response dict
+ doesn't contain an 'output' key at all.
+ """
+ handler = OpenAIResponsesHandler()
+ guardrail = MockPassThroughGuardrail(guardrail_name="test")
+
+ # Simulate a response.completed streaming event with missing output key
+ responses_so_far = [
+ {
+ "type": "response.completed",
+ "response": {
+ "id": "resp_123",
+ "status": "completed",
+ # No 'output' key - get() will return []
+ },
+ }
+ ]
+
+ # This should not raise IndexError
+ result = await handler.process_output_streaming_response(
+ responses_so_far=responses_so_far,
+ guardrail_to_apply=guardrail,
+ litellm_logging_obj=None,
+ )
+
+ # Should return the responses unchanged
+ assert result == responses_so_far
+
+ @pytest.mark.asyncio
+ async def test_process_output_streaming_response_unrecognized_output_type(self):
+ """Test that streaming response with unrecognized output types doesn't raise IndexError
+
+ This test verifies the handler gracefully handles when output items are of
+ unrecognized types that _convert_response_output_to_choices skips over.
+ """
+ handler = OpenAIResponsesHandler()
+ guardrail = MockPassThroughGuardrail(guardrail_name="test")
+
+ # Simulate a response.completed streaming event with unrecognized output type
+ responses_so_far = [
+ {
+ "type": "response.completed",
+ "response": {
+ "id": "resp_123",
+ "output": [
+ {
+ "type": "unknown_type", # Unrecognized type
+ "id": "item_123",
+ "data": "some data",
+ }
+ ],
+ "status": "completed",
+ },
+ }
+ ]
+
+ # This should not raise IndexError
+ result = await handler.process_output_streaming_response(
+ responses_so_far=responses_so_far,
+ guardrail_to_apply=guardrail,
+ litellm_logging_obj=None,
+ )
+
+ # Should return the responses unchanged
+ assert result == responses_so_far
+
+ @pytest.mark.asyncio
+ async def test_process_output_streaming_response_with_valid_output(self):
+ """Test that streaming response with valid output still works correctly"""
+ handler = OpenAIResponsesHandler()
+ guardrail = MockPassThroughGuardrail(guardrail_name="test")
+
+ # Simulate a response.completed streaming event with valid message output
+ responses_so_far = [
+ {
+ "type": "response.created",
+ "response": {"id": "resp_123"},
+ },
+ {
+ "type": "response.output_item.added",
+ "item": {"type": "message", "id": "msg_123"},
+ },
+ {
+ "type": "response.content_part.added",
+ "part": {"type": "output_text", "text": ""},
+ },
+ {
+ "type": "response.output_text.delta",
+ "delta": "Hello",
+ },
+ {
+ "type": "response.output_text.delta",
+ "delta": " world",
+ },
+ {
+ "type": "response.completed",
+ "response": {
+ "id": "resp_123",
+ "output": [
+ {
+ "type": "message",
+ "id": "msg_123",
+ "status": "completed",
+ "role": "assistant",
+ "content": [
+ {"type": "output_text", "text": "Hello world"},
+ ],
+ }
+ ],
+ "status": "completed",
+ },
+ },
+ ]
+
+ # This should process successfully
+ result = await handler.process_output_streaming_response(
+ responses_so_far=responses_so_far,
+ guardrail_to_apply=guardrail,
+ litellm_logging_obj=None,
+ )
+
+ # Should return the responses
+ assert result == responses_so_far