From f6fffdd9cebee4841445e753f5346088fb55f9d2 Mon Sep 17 00:00:00 2001 From: Clawd Date: Fri, 8 May 2026 15:20:51 +0800 Subject: [PATCH 1/3] fix(websearch): wrap agentic loop response in fake stream for streaming requests When websearch_interception converts stream=True to stream=False internally, the agentic loop returns a plain dict. Previously this dict was returned directly to the client expecting SSE events, resulting in empty streams. Added _maybe_wrap_in_fake_stream() which checks the websearch_interception_converted_stream flag and wraps dict responses in FakeAnthropicMessagesStreamIterator. Applied to all return paths in _call_agentic_completion_hooks: - async_run_agentic_loop (legacy path) - _execute_anthropic_agentic_plan (plan-based path) - plan.response_override - plan.terminate Includes unit tests for _maybe_wrap_in_fake_stream(). --- litellm/llms/custom_httpx/llm_http_handler.py | 108 ++++++++++-------- .../test_websearch_streaming_wrap.py | 70 ++++++++++++ 2 files changed, 131 insertions(+), 47 deletions(-) create mode 100644 tests/test_litellm/integrations/websearch_interception/test_websearch_streaming_wrap.py diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.py index d33ec295e94c..43ad3a8740b6 100644 --- a/litellm/llms/custom_httpx/llm_http_handler.py +++ b/litellm/llms/custom_httpx/llm_http_handler.py @@ -5504,6 +5504,42 @@ async def _execute_chat_completion_agentic_plan( **kwargs_for_followup, ) + def _maybe_wrap_in_fake_stream( + self, + response: Any, + logging_obj: "LiteLLMLoggingObj", + ) -> Any: + """ + If the original request was streaming but converted to non-streaming for + WebSearch interception, wrap the dict response in a FakeAnthropicMessagesStreamIterator. + """ + 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 +5622,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 +5633,7 @@ async def _call_agentic_completion_hooks( stream=stream, kwargs=kwargs_with_provider, ) + return self._maybe_wrap_in_fake_stream(agentic_result, logging_obj) plan = await callback.async_build_agentic_loop_plan( tools=tool_calls, @@ -5611,14 +5648,16 @@ 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 + ) 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) if not plan.run_agentic_loop: continue @@ -5636,19 +5675,22 @@ 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, ) except Exception as e: _call_id = getattr(logging_obj, "litellm_call_id", "unknown") @@ -5665,37 +5707,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) + 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..6b38a703427d --- /dev/null +++ b/tests/test_litellm/integrations/websearch_interception/test_websearch_streaming_wrap.py @@ -0,0 +1,70 @@ +""" +Unit tests for _maybe_wrap_in_fake_stream in BaseLLMHTTPHandler. + +Tests that agentic loop responses are correctly wrapped in +FakeAnthropicMessagesStreamIterator when the original request was streaming. +""" + +from unittest.mock import MagicMock + + +from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler +from litellm.llms.anthropic.experimental_pass_through.messages.fake_stream_iterator import ( + FakeAnthropicMessagesStreamIterator, +) + + +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 + } + response = { + "id": "msg_123", + "type": "message", + "role": "assistant", + "content": [{"type": "text", "text": "hello"}], + "stop_reason": "end_turn", + "usage": {"input_tokens": 10, "output_tokens": 5}, + } + + result = self.handler._maybe_wrap_in_fake_stream(response, logging_obj) + + 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) + + 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) + + 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) + + assert result is response From 2a8e48457fe52d61f8df75269a9481b00f064c02 Mon Sep 17 00:00:00 2001 From: mateo-berri <277851410+mateo-berri@users.noreply.github.com> Date: Sat, 27 Jun 2026 00:20:40 +0000 Subject: [PATCH 2/3] test(websearch): cover agentic-loop wrap paths; gate fake-stream on anthropic_messages surface Guard _maybe_wrap_in_fake_stream on api_surface == anthropic_messages so the responses API surface is never wrapped in an Anthropic SSE iterator, and type logging_obj as Optional to match the None call sites. Adds regression tests that drive the legacy, response_override, and terminate return paths of _call_agentic_completion_hooks end to end. --- litellm/llms/custom_httpx/llm_http_handler.py | 23 ++- .../test_websearch_streaming_wrap.py | 170 ++++++++++++++++-- 2 files changed, 174 insertions(+), 19 deletions(-) diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.py index 43ad3a8740b6..8ab12bf3f7ab 100644 --- a/litellm/llms/custom_httpx/llm_http_handler.py +++ b/litellm/llms/custom_httpx/llm_http_handler.py @@ -5507,12 +5507,20 @@ async def _execute_chat_completion_agentic_plan( def _maybe_wrap_in_fake_stream( self, response: Any, - logging_obj: "LiteLLMLoggingObj", + 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 @@ -5633,7 +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) + return self._maybe_wrap_in_fake_stream( + agentic_result, logging_obj, api_surface + ) plan = await callback.async_build_agentic_loop_plan( tools=tool_calls, @@ -5649,7 +5659,7 @@ async def _call_agentic_completion_hooks( if plan.response_override is not None: return self._maybe_wrap_in_fake_stream( - plan.response_override, logging_obj + plan.response_override, logging_obj, api_surface ) if plan.terminate: verbose_logger.debug( @@ -5657,7 +5667,9 @@ async def _call_agentic_completion_hooks( callback.__class__.__name__, plan.stop_reason, ) - return self._maybe_wrap_in_fake_stream(response, logging_obj) + return self._maybe_wrap_in_fake_stream( + response, logging_obj, api_surface + ) if not plan.run_agentic_loop: continue @@ -5691,6 +5703,7 @@ async def _call_agentic_completion_hooks( callback=callback, ), logging_obj, + api_surface, ) except Exception as e: _call_id = getattr(logging_obj, "litellm_call_id", "unknown") @@ -5707,7 +5720,7 @@ 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 - result = self._maybe_wrap_in_fake_stream(response, logging_obj) + result = self._maybe_wrap_in_fake_stream(response, logging_obj, api_surface) if result is not response: return result 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 index 6b38a703427d..bb147590efa6 100644 --- a/tests/test_litellm/integrations/websearch_interception/test_websearch_streaming_wrap.py +++ b/tests/test_litellm/integrations/websearch_interception/test_websearch_streaming_wrap.py @@ -1,17 +1,54 @@ """ -Unit tests for _maybe_wrap_in_fake_stream in BaseLLMHTTPHandler. +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. +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: @@ -24,16 +61,10 @@ def test_wraps_dict_when_converted_stream_flag_is_true(self): logging_obj.model_call_details = { "websearch_interception_converted_stream": True } - response = { - "id": "msg_123", - "type": "message", - "role": "assistant", - "content": [{"type": "text", "text": "hello"}], - "stop_reason": "end_turn", - "usage": {"input_tokens": 10, "output_tokens": 5}, - } - result = self.handler._maybe_wrap_in_fake_stream(response, logging_obj) + result = self.handler._maybe_wrap_in_fake_stream( + _anthropic_response(), logging_obj, "anthropic_messages" + ) assert isinstance(result, FakeAnthropicMessagesStreamIterator) @@ -45,7 +76,9 @@ def test_returns_response_unchanged_when_flag_is_false(self): } response = {"id": "msg_123", "content": []} - result = self.handler._maybe_wrap_in_fake_stream(response, logging_obj) + result = self.handler._maybe_wrap_in_fake_stream( + response, logging_obj, "anthropic_messages" + ) assert result is response @@ -57,7 +90,9 @@ def test_returns_response_unchanged_when_not_dict(self): } response = MagicMock() # Not a dict - result = self.handler._maybe_wrap_in_fake_stream(response, logging_obj) + result = self.handler._maybe_wrap_in_fake_stream( + response, logging_obj, "anthropic_messages" + ) assert result is response @@ -65,6 +100,113 @@ 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) + 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 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_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) From bec6c87eeebc29329b624b2a15de8c748762b7cf Mon Sep 17 00:00:00 2001 From: mateo-berri <277851410+mateo-berri@users.noreply.github.com> Date: Sat, 27 Jun 2026 00:25:48 +0000 Subject: [PATCH 3/3] test(websearch): cover _execute_anthropic_agentic_plan and tail wrap paths Drives the remaining two fake-stream return paths of _call_agentic_completion_hooks (the _execute_anthropic_agentic_plan branch via a stubbed handler, and the tail path when no agentic loop runs) so every converted-stream return path is regression-tested. --- .../test_websearch_streaming_wrap.py | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) 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 index bb147590efa6..f221e07a57dd 100644 --- a/tests/test_litellm/integrations/websearch_interception/test_websearch_streaming_wrap.py +++ b/tests/test_litellm/integrations/websearch_interception/test_websearch_streaming_wrap.py @@ -169,6 +169,14 @@ async def async_build_agentic_loop_plan( 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.""" @@ -202,6 +210,24 @@ async def test_terminate_path_wraps(self): 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())