diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.py index d33ec295e94c..8ab12bf3f7ab 100644 --- a/litellm/llms/custom_httpx/llm_http_handler.py +++ b/litellm/llms/custom_httpx/llm_http_handler.py @@ -5504,6 +5504,50 @@ async def _execute_chat_completion_agentic_plan( **kwargs_for_followup, ) + def _maybe_wrap_in_fake_stream( + self, + response: Any, + logging_obj: Optional["LiteLLMLoggingObj"], + api_surface: str, + ) -> Any: + """ + If the original request was streaming but converted to non-streaming for + WebSearch interception, wrap the dict response in a FakeAnthropicMessagesStreamIterator. + + The converted-stream flag is only ever set by anthropic-messages websearch + interception, and the wrapper rebuilds an Anthropic SSE stream, so wrapping + is gated on ``api_surface == "anthropic_messages"`` to leave other surfaces + (e.g. the responses API) untouched. + """ + if api_surface != "anthropic_messages": + return response + websearch_converted_stream = ( + logging_obj.model_call_details.get( + "websearch_interception_converted_stream", False + ) + if logging_obj is not None + else False + ) + if websearch_converted_stream and isinstance(response, dict): + from typing import cast + + from litellm._logging import verbose_logger + from litellm.llms.anthropic.experimental_pass_through.messages.fake_stream_iterator import ( + FakeAnthropicMessagesStreamIterator, + ) + from litellm.types.llms.anthropic_messages.anthropic_response import ( + AnthropicMessagesResponse, + ) + + verbose_logger.debug( + "WebSearchInterception: Agentic loop completed, " + "converting non-streaming response to fake stream" + ) + return FakeAnthropicMessagesStreamIterator( + response=cast(AnthropicMessagesResponse, response) + ) + return response + async def _call_agentic_completion_hooks( self, response: Any, @@ -5586,7 +5630,7 @@ async def _call_agentic_completion_hooks( is not CustomLogger.async_build_agentic_loop_plan ) if not build_plan_overridden: - return await callback.async_run_agentic_loop( + agentic_result = await callback.async_run_agentic_loop( tools=tool_calls, model=model, messages=messages, @@ -5597,6 +5641,9 @@ async def _call_agentic_completion_hooks( stream=stream, kwargs=kwargs_with_provider, ) + return self._maybe_wrap_in_fake_stream( + agentic_result, logging_obj, api_surface + ) plan = await callback.async_build_agentic_loop_plan( tools=tool_calls, @@ -5611,14 +5658,18 @@ async def _call_agentic_completion_hooks( ) if plan.response_override is not None: - return plan.response_override + return self._maybe_wrap_in_fake_stream( + plan.response_override, logging_obj, api_surface + ) if plan.terminate: verbose_logger.debug( "Agentic loop terminated by callback=%s reason=%s", callback.__class__.__name__, plan.stop_reason, ) - return response + return self._maybe_wrap_in_fake_stream( + response, logging_obj, api_surface + ) if not plan.run_agentic_loop: continue @@ -5636,19 +5687,23 @@ async def _call_agentic_completion_hooks( callback=callback, ) - return await self._execute_anthropic_agentic_plan( - plan=plan, - model=model, - messages=messages, - anthropic_messages_optional_request_params=anthropic_messages_optional_request_params, - logging_obj=logging_obj, - kwargs=kwargs_with_provider, - depth=depth, - max_loops=max_loops, - fingerprints=fingerprints, - fingerprint=fingerprint, - stream=stream, - callback=callback, + return self._maybe_wrap_in_fake_stream( + await self._execute_anthropic_agentic_plan( + plan=plan, + model=model, + messages=messages, + anthropic_messages_optional_request_params=anthropic_messages_optional_request_params, + logging_obj=logging_obj, + kwargs=kwargs_with_provider, + depth=depth, + max_loops=max_loops, + fingerprints=fingerprints, + fingerprint=fingerprint, + stream=stream, + callback=callback, + ), + logging_obj, + api_surface, ) except Exception as e: _call_id = getattr(logging_obj, "litellm_call_id", "unknown") @@ -5665,37 +5720,9 @@ async def _call_agentic_completion_hooks( # 1. Stream was originally True but converted to False for WebSearch interception # 2. No agentic loop ran (LLM didn't use the tool) # 3. We have a non-streaming response that needs to be converted to streaming - websearch_converted_stream = ( - logging_obj.model_call_details.get( - "websearch_interception_converted_stream", False - ) - if logging_obj is not None - else False - ) - - if api_surface == "anthropic_messages" and websearch_converted_stream: - from typing import cast - - from litellm._logging import verbose_logger - from litellm.llms.anthropic.experimental_pass_through.messages.fake_stream_iterator import ( - FakeAnthropicMessagesStreamIterator, - ) - from litellm.types.llms.anthropic_messages.anthropic_response import ( - AnthropicMessagesResponse, - ) - - verbose_logger.debug( - "WebSearchInterception: No tool call made, converting non-streaming response to fake stream" - ) - - # Convert the non-streaming response to a fake stream - # The response should be an AnthropicMessagesResponse (dict) - if isinstance(response, dict): - # Create a fake streaming iterator - fake_stream = FakeAnthropicMessagesStreamIterator( - response=cast(AnthropicMessagesResponse, response) - ) - return fake_stream + result = self._maybe_wrap_in_fake_stream(response, logging_obj, api_surface) + if result is not response: + return result return None diff --git a/tests/test_litellm/integrations/websearch_interception/test_websearch_streaming_wrap.py b/tests/test_litellm/integrations/websearch_interception/test_websearch_streaming_wrap.py new file mode 100644 index 000000000000..f221e07a57dd --- /dev/null +++ b/tests/test_litellm/integrations/websearch_interception/test_websearch_streaming_wrap.py @@ -0,0 +1,238 @@ +""" +Unit tests for fake-stream wrapping of agentic loop responses in +BaseLLMHTTPHandler. + +Tests that agentic loop responses are correctly wrapped in +FakeAnthropicMessagesStreamIterator when the original request was streaming +but converted to non-streaming for WebSearch interception. +""" + +from unittest.mock import MagicMock + +import pytest + +from litellm.integrations.custom_logger import CustomLogger +from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler +from litellm.llms.anthropic.experimental_pass_through.messages.fake_stream_iterator import ( + FakeAnthropicMessagesStreamIterator, +) +from litellm.types.integrations.custom_logger import AgenticLoopPlan + + +def _anthropic_response() -> dict: + return { + "id": "msg_123", + "type": "message", + "role": "assistant", + "content": [{"type": "text", "text": "hello"}], + "stop_reason": "end_turn", + "usage": {"input_tokens": 10, "output_tokens": 5}, + } + + +def _converted_stream_logging_obj(callback: CustomLogger) -> MagicMock: + logging_obj = MagicMock() + logging_obj.model_call_details = {"websearch_interception_converted_stream": True} + logging_obj.dynamic_success_callbacks = [callback] + return logging_obj + + +async def _run_hooks(handler: BaseLLMHTTPHandler, logging_obj: MagicMock): + return await handler._call_agentic_completion_hooks( + response=_anthropic_response(), + model="claude-3-5-sonnet", + messages=[{"role": "user", "content": "search the web"}], + anthropic_messages_provider_config=MagicMock(), + anthropic_messages_optional_request_params={}, + logging_obj=logging_obj, + stream=True, + custom_llm_provider="anthropic", + kwargs={}, + ) + + +class TestMaybeWrapInFakeStream: + def setup_method(self): + self.handler = BaseLLMHTTPHandler() + + def test_wraps_dict_when_converted_stream_flag_is_true(self): + """When websearch_interception_converted_stream is True and response is dict, wrap it.""" + logging_obj = MagicMock() + logging_obj.model_call_details = { + "websearch_interception_converted_stream": True + } + + result = self.handler._maybe_wrap_in_fake_stream( + _anthropic_response(), logging_obj, "anthropic_messages" + ) + + assert isinstance(result, FakeAnthropicMessagesStreamIterator) + + def test_returns_response_unchanged_when_flag_is_false(self): + """When flag is False, return response as-is.""" + logging_obj = MagicMock() + logging_obj.model_call_details = { + "websearch_interception_converted_stream": False + } + response = {"id": "msg_123", "content": []} + + result = self.handler._maybe_wrap_in_fake_stream( + response, logging_obj, "anthropic_messages" + ) + + assert result is response + + def test_returns_response_unchanged_when_not_dict(self): + """When response is not a dict (e.g., already a stream), return as-is.""" + logging_obj = MagicMock() + logging_obj.model_call_details = { + "websearch_interception_converted_stream": True + } + response = MagicMock() # Not a dict + + result = self.handler._maybe_wrap_in_fake_stream( + response, logging_obj, "anthropic_messages" + ) + + assert result is response + + def test_returns_response_when_logging_obj_is_none(self): + """When logging_obj is None, return response as-is.""" + response = {"id": "msg_123", "content": []} + + result = self.handler._maybe_wrap_in_fake_stream( + response, None, "anthropic_messages" + ) + + assert result is response + + def test_does_not_wrap_for_non_anthropic_surface(self): + """Even with the flag set and a dict response, leave non-anthropic surfaces untouched.""" + logging_obj = MagicMock() + logging_obj.model_call_details = { + "websearch_interception_converted_stream": True + } + + result = self.handler._maybe_wrap_in_fake_stream( + _anthropic_response(), logging_obj, "responses" + ) + + assert isinstance(result, dict) + + +class _LegacyAgenticCallback(CustomLogger): + """Triggers the agentic loop via the legacy async_run_agentic_loop path.""" + + async def async_should_run_agentic_loop( + self, response, model, messages, tools, stream, custom_llm_provider, kwargs + ): + return True, {"tool_calls": [{"name": "web_search"}]} + + async def async_run_agentic_loop( + self, + tools, + model, + messages, + response, + anthropic_messages_provider_config, + anthropic_messages_optional_request_params, + logging_obj, + stream, + kwargs, + ): + return _anthropic_response() + + +class _PlanAgenticCallback(CustomLogger): + """Drives the plan-based paths by returning a caller-supplied plan.""" + + def __init__(self, plan: AgenticLoopPlan): + self._plan = plan + + async def async_should_run_agentic_loop( + self, response, model, messages, tools, stream, custom_llm_provider, kwargs + ): + return True, {"tool_calls": [{"name": "web_search"}]} + + async def async_build_agentic_loop_plan( + self, + tools, + model, + messages, + response, + anthropic_messages_provider_config, + anthropic_messages_optional_request_params, + logging_obj, + stream, + kwargs, + ): + return self._plan + + +class _StubExecuteHandler(BaseLLMHTTPHandler): + """Handler whose agentic-plan execution is stubbed to a dict so the + _execute_anthropic_agentic_plan return path can be exercised in isolation.""" + + async def _execute_anthropic_agentic_plan(self, **kwargs): + return _anthropic_response() + + +class TestCallAgenticCompletionHooksWrapping: + """Regression tests: every agentic-loop return path must wrap the dict + response in a fake stream when the request was a converted stream.""" + + def setup_method(self): + self.handler = BaseLLMHTTPHandler() + + @pytest.mark.asyncio + async def test_legacy_run_agentic_loop_path_wraps(self): + logging_obj = _converted_stream_logging_obj(_LegacyAgenticCallback()) + + result = await _run_hooks(self.handler, logging_obj) + + assert isinstance(result, FakeAnthropicMessagesStreamIterator) + + @pytest.mark.asyncio + async def test_response_override_path_wraps(self): + plan = AgenticLoopPlan(response_override=_anthropic_response()) + logging_obj = _converted_stream_logging_obj(_PlanAgenticCallback(plan)) + + result = await _run_hooks(self.handler, logging_obj) + + assert isinstance(result, FakeAnthropicMessagesStreamIterator) + + @pytest.mark.asyncio + async def test_terminate_path_wraps(self): + plan = AgenticLoopPlan(terminate=True, stop_reason="done") + logging_obj = _converted_stream_logging_obj(_PlanAgenticCallback(plan)) + + result = await _run_hooks(self.handler, logging_obj) + + assert isinstance(result, FakeAnthropicMessagesStreamIterator) + + @pytest.mark.asyncio + async def test_anthropic_plan_execution_path_wraps(self): + plan = AgenticLoopPlan(run_agentic_loop=True) + logging_obj = _converted_stream_logging_obj(_PlanAgenticCallback(plan)) + + result = await _run_hooks(_StubExecuteHandler(), logging_obj) + + assert isinstance(result, FakeAnthropicMessagesStreamIterator) + + @pytest.mark.asyncio + async def test_tail_path_wraps_when_no_loop_runs(self): + plan = AgenticLoopPlan(run_agentic_loop=False) + logging_obj = _converted_stream_logging_obj(_PlanAgenticCallback(plan)) + + result = await _run_hooks(self.handler, logging_obj) + + assert isinstance(result, FakeAnthropicMessagesStreamIterator) + + @pytest.mark.asyncio + async def test_legacy_path_not_wrapped_without_flag(self): + logging_obj = _converted_stream_logging_obj(_LegacyAgenticCallback()) + logging_obj.model_call_details = {} + + result = await _run_hooks(self.handler, logging_obj) + + assert isinstance(result, dict)