From 6c24f64860b2ccbbfdfb203ef27729b75202eafe Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Mon, 29 Jun 2026 17:18:08 -0700 Subject: [PATCH 1/9] fix(websearch): wire chat completion agentic loop to correct hooks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit maybe_run_chat_completion_agentic_loop was calling async_should_run_agentic_loop (Anthropic format) and async_run_agentic_loop (Anthropic path) instead of the chat-completion variants. This meant WebSearchInterceptionLogger never intercepted chat completion requests — the LLM returned a litellm_web_search tool_call but the agentic loop never executed, so the raw tool_calls response was returned to the caller. Fix: gate on async_should_run_chat_completion_agentic_loop override, call that hook and async_build_chat_completion_agentic_loop_plan / async_run_chat_completion_agentic_loop in the execution path. Regression test added. --- .../chat_completion_agentic_loop.py | 73 +++--- .../test_websearch_chat_completion.py | 231 +++++++++++++----- 2 files changed, 194 insertions(+), 110 deletions(-) diff --git a/litellm/litellm_core_utils/chat_completion_agentic_loop.py b/litellm/litellm_core_utils/chat_completion_agentic_loop.py index 938e892bd50c..df8a3e572603 100644 --- a/litellm/litellm_core_utils/chat_completion_agentic_loop.py +++ b/litellm/litellm_core_utils/chat_completion_agentic_loop.py @@ -34,12 +34,24 @@ def _gate_overridden(callback: CustomLogger) -> bool: return getattr(func, "__func__", func) is not getattr(base, "__func__", base) +def _chat_completion_gate_overridden(callback: CustomLogger) -> bool: + base = CustomLogger.async_should_run_chat_completion_agentic_loop + func = type(callback).async_should_run_chat_completion_agentic_loop + return getattr(func, "__func__", func) is not getattr(base, "__func__", base) + + def _build_plan_overridden(callback: CustomLogger) -> bool: base = CustomLogger.async_build_agentic_loop_plan func = type(callback).async_build_agentic_loop_plan return getattr(func, "__func__", func) is not getattr(base, "__func__", base) +def _chat_completion_build_plan_overridden(callback: CustomLogger) -> bool: + base = CustomLogger.async_build_chat_completion_agentic_loop_plan + func = type(callback).async_build_chat_completion_agentic_loop_plan + return getattr(func, "__func__", func) is not getattr(base, "__func__", base) + + def _post_hook_overridden(callback: CustomLogger) -> bool: base = CustomLogger.async_post_agentic_loop_response_hook func = type(callback).async_post_agentic_loop_response_hook @@ -54,11 +66,7 @@ def _agentic_loop_settings(kwargs: dict[str, object]) -> tuple[int, int, list[st depth = _coerce_int(kwargs.get("_agentic_loop_depth"), 0) max_loops = max(_coerce_int(kwargs.get("max_agentic_loops"), 3), 1) raw_fingerprints = kwargs.get("_agentic_loop_fingerprints") - fingerprints = ( - [str(fp) for fp in raw_fingerprints] - if isinstance(raw_fingerprints, list) - else [] - ) + fingerprints = [str(fp) for fp in raw_fingerprints] if isinstance(raw_fingerprints, list) else [] return depth, max_loops, fingerprints @@ -78,9 +86,7 @@ def _check_agentic_loop_safety( ) -> str: fingerprint = _fingerprint_tools(tool_calls) if fingerprint in fingerprints: - raise ValueError( - "Agentic loop detected repeated tool-call fingerprint; aborting rerun" - ) + raise ValueError("Agentic loop detected repeated tool-call fingerprint; aborting rerun") if depth >= max_loops: raise ValueError(f"Exceeded max_agentic_loops={max_loops} for model={model}") return fingerprint @@ -102,11 +108,7 @@ def _add_agentic_loop_metadata(kwargs_for_followup: dict[str, object]) -> None: metadata = kwargs_for_followup.get("litellm_metadata") metadata = dict(metadata) if isinstance(metadata, dict) else {} for key, value in kwargs_for_followup.items(): - if ( - key.startswith("_agentic_loop") - or key == "max_agentic_loops" - or is_interception_internal_key(key) - ): + if key.startswith("_agentic_loop") or key == "max_agentic_loops" or is_interception_internal_key(key): metadata[key] = value kwargs_for_followup["litellm_metadata"] = metadata @@ -115,9 +117,7 @@ def _filter_followup_kwargs(source: dict[str, object]) -> dict[str, object]: return { k: v for k, v in source.items() - if not is_interception_internal_key( - k, prefixes=NON_CODE_INTERPRETER_INTERCEPTION_INTERNAL_PREFIXES - ) + if not is_interception_internal_key(k, prefixes=NON_CODE_INTERPRETER_INTERCEPTION_INTERNAL_PREFIXES) and k not in _FOLLOWUP_INTERNAL_PARAMS } @@ -154,11 +154,7 @@ async def _execute_chat_completion_agentic_plan( kwargs_for_followup = _filter_followup_kwargs(kwargs) kwargs_for_followup.update( - { - k: v - for k, v in _filter_followup_kwargs(patch.kwargs).items() - if k not in optional_params_for_followup - } + {k: v for k, v in _filter_followup_kwargs(patch.kwargs).items() if k not in optional_params_for_followup} ) kwargs_for_followup["_agentic_loop_depth"] = depth + 1 kwargs_for_followup["max_agentic_loops"] = max_loops @@ -174,10 +170,8 @@ async def _execute_chat_completion_agentic_plan( ) if _post_hook_overridden(callback): try: - response_followup = ( - await callback.async_post_agentic_loop_response_hook( - response=response_followup, plan=plan, kwargs=kwargs - ) + response_followup = await callback.async_post_agentic_loop_response_hook( + response=response_followup, plan=plan, kwargs=kwargs ) except Exception as e: _call_id = getattr(logging_obj, "litellm_call_id", "unknown") @@ -197,8 +191,7 @@ async def _execute_chat_completion_agentic_plan( except Exception as e: _call_id = getattr(logging_obj, "litellm_call_id", "unknown") verbose_logger.exception( - "LiteLLM.AgenticHookError: Exception in " - "async_agentic_loop_cleanup_hook [call_id=%s model=%s]: %s", + "LiteLLM.AgenticHookError: Exception in async_agentic_loop_cleanup_hook [call_id=%s model=%s]: %s", _call_id, model, str(e), @@ -218,16 +211,14 @@ async def maybe_run_chat_completion_agentic_loop( ) -> ModelResponse | CustomStreamWrapper | None: import litellm - callbacks = litellm.callbacks + ( - getattr(logging_obj, "dynamic_success_callbacks", None) or [] - ) + callbacks = litellm.callbacks + (getattr(logging_obj, "dynamic_success_callbacks", None) or []) depth, max_loops, fingerprints = _agentic_loop_settings(kwargs) tools = optional_params.get("tools", []) for callback in callbacks: if not isinstance(callback, CustomLogger): continue - if not _gate_overridden(callback): + if not _chat_completion_gate_overridden(callback): continue gate_kwargs = { @@ -236,7 +227,7 @@ async def maybe_run_chat_completion_agentic_loop( "custom_llm_provider": custom_llm_provider, } try: - should_run, tool_calls = await callback.async_should_run_agentic_loop( + should_run, tool_calls = await callback.async_should_run_chat_completion_agentic_loop( response=response, model=model, messages=messages, @@ -269,26 +260,24 @@ async def maybe_run_chat_completion_agentic_loop( "_agentic_loop_api_surface": CHAT_COMPLETION_AGENTIC_SURFACE, "custom_llm_provider": custom_llm_provider, } - if not _build_plan_overridden(callback): - return await callback.async_run_agentic_loop( + if not _chat_completion_build_plan_overridden(callback): + return await callback.async_run_chat_completion_agentic_loop( tools=tool_calls, model=model, messages=messages, response=response, - anthropic_messages_provider_config=None, - anthropic_messages_optional_request_params=optional_params, + optional_params=optional_params, logging_obj=logging_obj, stream=stream, kwargs=plan_kwargs, ) - plan = await callback.async_build_agentic_loop_plan( + plan = await callback.async_build_chat_completion_agentic_loop_plan( tools=tool_calls, model=model, messages=messages, response=response, - anthropic_messages_provider_config=None, - anthropic_messages_optional_request_params=optional_params, + optional_params=optional_params, logging_obj=logging_obj, stream=stream, kwargs=plan_kwargs, @@ -320,11 +309,7 @@ async def maybe_run_chat_completion_agentic_loop( str(e), ) - if ( - kwargs.get("_code_interpreter_interception_converted_stream") - and not depth - and hasattr(response, "choices") - ): + if kwargs.get("_code_interpreter_interception_converted_stream") and not depth and hasattr(response, "choices"): return cast( "ModelResponse | CustomStreamWrapper", _wrap_response_as_fake_stream(response), diff --git a/tests/test_litellm/integrations/websearch_interception/test_websearch_chat_completion.py b/tests/test_litellm/integrations/websearch_interception/test_websearch_chat_completion.py index 34555d76554d..a1cdbe542131 100644 --- a/tests/test_litellm/integrations/websearch_interception/test_websearch_chat_completion.py +++ b/tests/test_litellm/integrations/websearch_interception/test_websearch_chat_completion.py @@ -6,7 +6,7 @@ """ import os -from unittest.mock import AsyncMock, MagicMock, patch +from unittest.mock import MagicMock import pytest @@ -34,9 +34,7 @@ def mock_search_response(): @pytest.fixture def websearch_logger(): """Create a WebSearchInterceptionLogger instance""" - return WebSearchInterceptionLogger( - enabled_providers=[LlmProviders.OPENAI, LlmProviders.MINIMAX] - ) + return WebSearchInterceptionLogger(enabled_providers=[LlmProviders.OPENAI, LlmProviders.MINIMAX]) @pytest.mark.asyncio @@ -55,9 +53,7 @@ async def test_websearch_chat_completion_with_openai(): """ # Configure WebSearch interception original_callbacks = litellm.callbacks.copy() if litellm.callbacks else [] - websearch_logger = WebSearchInterceptionLogger( - enabled_providers=[LlmProviders.OPENAI] - ) + websearch_logger = WebSearchInterceptionLogger(enabled_providers=[LlmProviders.OPENAI]) litellm.callbacks = [websearch_logger] try: @@ -100,9 +96,7 @@ async def test_websearch_chat_completion_with_openai(): if hasattr(response.choices[0].message, "tool_calls"): # If tool_calls exist, it means agentic loop didn't run # This could happen if search tool is not configured - pytest.skip( - "Agentic loop did not execute - search tool may not be configured" - ) + pytest.skip("Agentic loop did not execute - search tool may not be configured") # Verify we got a meaningful response assert response.choices[0].finish_reason in ["stop", "end_turn"] @@ -122,9 +116,7 @@ async def test_websearch_chat_completion_hook_detection(): Message, ) - websearch_logger = WebSearchInterceptionLogger( - enabled_providers=[LlmProviders.OPENAI] - ) + websearch_logger = WebSearchInterceptionLogger(enabled_providers=[LlmProviders.OPENAI]) # Mock response with litellm_web_search tool call mock_response = ModelResponse( @@ -155,21 +147,19 @@ async def test_websearch_chat_completion_hook_detection(): ) # Test should_run_chat_completion_agentic_loop - should_run, tools_dict = ( - await websearch_logger.async_should_run_chat_completion_agentic_loop( - response=mock_response, - model="gpt-4o", - messages=[{"role": "user", "content": "What's the weather?"}], - tools=[ - { - "type": "function", - "function": {"name": "litellm_web_search"}, - } - ], - stream=False, - custom_llm_provider="openai", - kwargs={}, - ) + should_run, tools_dict = await websearch_logger.async_should_run_chat_completion_agentic_loop( + response=mock_response, + model="gpt-4o", + messages=[{"role": "user", "content": "What's the weather?"}], + tools=[ + { + "type": "function", + "function": {"name": "litellm_web_search"}, + } + ], + stream=False, + custom_llm_provider="openai", + kwargs={}, ) # Verify hook detected the tool call @@ -185,9 +175,7 @@ async def test_websearch_not_triggered_without_tool(): """Test that websearch hook is NOT triggered when no web search tool in request.""" from litellm.types.utils import Choices, Message - websearch_logger = WebSearchInterceptionLogger( - enabled_providers=[LlmProviders.OPENAI] - ) + websearch_logger = WebSearchInterceptionLogger(enabled_providers=[LlmProviders.OPENAI]) mock_response = ModelResponse( id="test-123", @@ -208,21 +196,19 @@ async def test_websearch_not_triggered_without_tool(): ) # Test without web search tool - should_run, tools_dict = ( - await websearch_logger.async_should_run_chat_completion_agentic_loop( - response=mock_response, - model="gpt-4o", - messages=[{"role": "user", "content": "Hello"}], - tools=[ - { - "type": "function", - "function": {"name": "some_other_tool"}, - } - ], - stream=False, - custom_llm_provider="openai", - kwargs={}, - ) + should_run, tools_dict = await websearch_logger.async_should_run_chat_completion_agentic_loop( + response=mock_response, + model="gpt-4o", + messages=[{"role": "user", "content": "Hello"}], + tools=[ + { + "type": "function", + "function": {"name": "some_other_tool"}, + } + ], + stream=False, + custom_llm_provider="openai", + kwargs={}, ) # Verify hook did NOT trigger @@ -241,9 +227,7 @@ async def test_websearch_not_triggered_for_disabled_provider(): ) # Only enable bedrock - websearch_logger = WebSearchInterceptionLogger( - enabled_providers=[LlmProviders.BEDROCK] - ) + websearch_logger = WebSearchInterceptionLogger(enabled_providers=[LlmProviders.BEDROCK]) mock_response = ModelResponse( id="test-123", @@ -273,21 +257,19 @@ async def test_websearch_not_triggered_for_disabled_provider(): ) # Test with OpenAI provider (not enabled) - should_run, tools_dict = ( - await websearch_logger.async_should_run_chat_completion_agentic_loop( - response=mock_response, - model="gpt-4o", - messages=[{"role": "user", "content": "test"}], - tools=[ - { - "type": "function", - "function": {"name": "litellm_web_search"}, - } - ], - stream=False, - custom_llm_provider="openai", # Not in enabled_providers - kwargs={}, - ) + should_run, tools_dict = await websearch_logger.async_should_run_chat_completion_agentic_loop( + response=mock_response, + model="gpt-4o", + messages=[{"role": "user", "content": "test"}], + tools=[ + { + "type": "function", + "function": {"name": "litellm_web_search"}, + } + ], + stream=False, + custom_llm_provider="openai", # Not in enabled_providers + kwargs={}, ) # Verify hook did NOT trigger @@ -341,8 +323,7 @@ async def test_websearch_json_serialization_fix(): @pytest.mark.asyncio @pytest.mark.skipif( - os.environ.get("OPENAI_API_KEY") is None - or os.environ.get("PERPLEXITY_API_KEY") is None, + os.environ.get("OPENAI_API_KEY") is None or os.environ.get("PERPLEXITY_API_KEY") is None, reason="OPENAI_API_KEY or PERPLEXITY_API_KEY not set", ) async def test_websearch_streaming_conversion(): @@ -395,6 +376,124 @@ async def test_websearch_streaming_conversion(): litellm.callbacks = [] +@pytest.mark.asyncio +async def test_maybe_run_chat_completion_agentic_loop_calls_chat_completion_hook(): + """Regression test: maybe_run_chat_completion_agentic_loop must call + async_should_run_chat_completion_agentic_loop, not async_should_run_agentic_loop. + + Before the fix, the function used the wrong gate check and wrong hook, + causing WebSearchInterceptionLogger to never intercept chat completion requests + even when the LLM returned a litellm_web_search tool call. + """ + from litellm.litellm_core_utils.chat_completion_agentic_loop import ( + maybe_run_chat_completion_agentic_loop, + ) + from litellm.types.utils import ( + ChatCompletionMessageToolCall, + Choices, + Function, + Message, + ) + + mock_response = ModelResponse( + id="test-regression-123", + choices=[ + Choices( + finish_reason="tool_calls", + index=0, + message=Message( + role="assistant", + content=None, + tool_calls=[ + ChatCompletionMessageToolCall( + id="call_abc", + type="function", + function=Function( + name="litellm_web_search", + arguments='{"query": "latest news"}', + ), + ) + ], + ), + ) + ], + model="gpt-4o", + object="chat.completion", + created=1234567890, + ) + + sentinel = ModelResponse( + id="sentinel-final", + choices=[ + Choices( + finish_reason="stop", + index=0, + message=Message(role="assistant", content="Here is the news."), + ) + ], + model="gpt-4o", + object="chat.completion", + created=1234567890, + ) + + websearch_logger = WebSearchInterceptionLogger(enabled_providers=[LlmProviders.OPENAI]) + + chat_completion_hook_called = False + + async def fake_should_run_chat_completion(response, model, messages, tools, stream, custom_llm_provider, kwargs): + nonlocal chat_completion_hook_called + chat_completion_hook_called = True + return True, { + "tool_calls": [{"id": "call_abc", "name": "litellm_web_search", "input": {"query": "latest news"}}], + "tool_type": "websearch", + "provider": "openai", + "response_format": "openai", + } + + async def fake_build_plan(tools, model, messages, response, optional_params, logging_obj, stream, kwargs): + from litellm.types.integrations.custom_logger import AgenticLoopPlan + + return AgenticLoopPlan(run_agentic_loop=False, response_override=sentinel) + + websearch_logger.async_should_run_chat_completion_agentic_loop = fake_should_run_chat_completion + websearch_logger.async_build_chat_completion_agentic_loop_plan = fake_build_plan + + import litellm as _litellm + + original_callbacks = _litellm.callbacks[:] + _litellm.callbacks = [websearch_logger] + + mock_logging_obj = MagicMock() + mock_logging_obj.dynamic_success_callbacks = None + + try: + result = await maybe_run_chat_completion_agentic_loop( + response=mock_response, + model="gpt-4o", + messages=[{"role": "user", "content": "Latest news?"}], + optional_params={ + "tools": [ + { + "type": "function", + "function": {"name": "litellm_web_search"}, + } + ] + }, + kwargs={}, + logging_obj=mock_logging_obj, + custom_llm_provider="openai", + stream=False, + ) + finally: + _litellm.callbacks = original_callbacks + + assert chat_completion_hook_called, ( + "async_should_run_chat_completion_agentic_loop was never called; " + "maybe_run_chat_completion_agentic_loop used the wrong hook" + ) + assert result is sentinel, "Expected agentic loop to return sentinel final response" + + if __name__ == "__main__": # Run with: pytest test_websearch_chat_completion.py -v -s pytest.main([__file__, "-v", "-s"]) From a8d44d069dbfb3defb7f9f71dc360f32b29c19ca Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Mon, 29 Jun 2026 18:01:42 -0700 Subject: [PATCH 2/9] fix(websearch): strip tool_choice from follow-up request When the original request forces tool_choice to litellm_web_search, the follow-up request after search execution inherited that tool_choice, causing the model to call the search tool again instead of synthesizing an answer from the results. --- .../websearch_interception/handler.py | 244 +++++------------- 1 file changed, 63 insertions(+), 181 deletions(-) diff --git a/litellm/integrations/websearch_interception/handler.py b/litellm/integrations/websearch_interception/handler.py index ab4c787c96f6..e715e3d15a31 100644 --- a/litellm/integrations/websearch_interception/handler.py +++ b/litellm/integrations/websearch_interception/handler.py @@ -80,9 +80,7 @@ def __init__( if enabled_providers is None: self.enabled_providers = [LlmProviders.BEDROCK.value] else: - self.enabled_providers = [ - p.value if isinstance(p, LlmProviders) else p for p in enabled_providers - ] + self.enabled_providers = [p.value if isinstance(p, LlmProviders) else p for p in enabled_providers] self.search_tool_name = search_tool_name self._request_has_websearch = False # Track if current request has web search @@ -118,10 +116,7 @@ async def try_short_circuit_search( # Check if provider is in enabled list provider_str = custom_llm_provider or "" - if ( - self.enabled_providers is not None - and provider_str not in self.enabled_providers - ): + if self.enabled_providers is not None and provider_str not in self.enabled_providers: return None # Only short-circuit for providers without native Anthropic Messages @@ -132,10 +127,8 @@ async def try_short_circuit_search( # return raw search text — a regression for existing users. try: provider_enum = LlmProviders(provider_str) - anthropic_config = ( - ProviderConfigManager.get_provider_anthropic_messages_config( - model=model, provider=provider_enum - ) + anthropic_config = ProviderConfigManager.get_provider_anthropic_messages_config( + model=model, provider=provider_enum ) if anthropic_config is not None: verbose_logger.debug( @@ -160,8 +153,7 @@ async def try_short_circuit_search( return None verbose_logger.debug( - "WebSearchInterception: Short-circuit search detected " - f"(provider={provider_str}, query='{query}')" + f"WebSearchInterception: Short-circuit search detected (provider={provider_str}, query='{query}')" ) # Native clients (Claude Desktop / Cowork / Anthropic SDK) make a @@ -180,9 +172,7 @@ async def try_short_circuit_search( try: search_result_text, structured = await self._execute_search(query) except Exception as e: - verbose_logger.error( - f"WebSearchInterception: Short-circuit search failed: {e}" - ) + verbose_logger.error(f"WebSearchInterception: Short-circuit search failed: {e}") search_result_text, structured = f"Search failed: {e}", None content: List[Dict[str, Any]] = [] @@ -225,9 +215,7 @@ async def try_short_circuit_search( ) return response - async def async_pre_call_deployment_hook( - self, kwargs: Dict[str, Any], call_type: Optional[Any] - ) -> Optional[dict]: + async def async_pre_call_deployment_hook(self, kwargs: Dict[str, Any], call_type: Optional[Any]) -> Optional[dict]: """ Pre-call hook to convert native Anthropic web_search tools to regular tools. @@ -237,14 +225,12 @@ async def async_pre_call_deployment_hook( """ # Check if this is for an enabled provider # Try top-level kwargs first, then nested litellm_params, then derive from model name - custom_llm_provider = kwargs.get("custom_llm_provider", "") or kwargs.get( - "litellm_params", {} - ).get("custom_llm_provider", "") + custom_llm_provider = kwargs.get("custom_llm_provider", "") or kwargs.get("litellm_params", {}).get( + "custom_llm_provider", "" + ) if not custom_llm_provider: try: - _, custom_llm_provider, _, _ = litellm.get_llm_provider( - model=kwargs.get("model", "") - ) + _, custom_llm_provider, _, _ = litellm.get_llm_provider(model=kwargs.get("model", "")) except Exception: custom_llm_provider = "" if custom_llm_provider not in self.enabled_providers: @@ -261,9 +247,7 @@ async def async_pre_call_deployment_hook( if not has_websearch: return None - verbose_logger.debug( - "WebSearchInterception: Converting native web_search tools to LiteLLM standard" - ) + verbose_logger.debug("WebSearchInterception: Converting native web_search tools to LiteLLM standard") # If the client sent an Anthropic-native web_search_* tool, mark the # request so the agentic loop emits native web_search_tool_result @@ -291,18 +275,14 @@ async def async_pre_call_deployment_hook( kwargs["tools"] = converted_tools if kwargs.get("stream"): - verbose_logger.debug( - "WebSearchInterception: deployment hook converting stream=True to stream=False" - ) + verbose_logger.debug("WebSearchInterception: deployment hook converting stream=True to stream=False") kwargs["stream"] = False kwargs["_websearch_interception_converted_stream"] = True return kwargs @classmethod - def from_config_yaml( - cls, config: WebSearchInterceptionConfig - ) -> "WebSearchInterceptionLogger": + def from_config_yaml(cls, config: WebSearchInterceptionConfig) -> "WebSearchInterceptionLogger": """ Initialize WebSearchInterceptionLogger from proxy config.yaml parameters. @@ -354,9 +334,7 @@ def _tool_name(tool: dict[str, Any]) -> Optional[str]: return tool.get("name") @classmethod - def _sync_forced_tool_choice( - cls, tool_choice: Any, converted_tools: list[dict[str, Any]] - ) -> Any: + def _sync_forced_tool_choice(cls, tool_choice: Any, converted_tools: list[dict[str, Any]]) -> Any: """Repoint a forced ``tool_choice`` at ``litellm_web_search`` when it names a web-search tool that was just converted away. @@ -373,9 +351,7 @@ def _sync_forced_tool_choice( return tool_choice return {**tool_choice, "name": LITELLM_WEB_SEARCH_TOOL_NAME} - async def async_pre_request_hook( - self, model: str, messages: List[Dict], kwargs: Dict - ) -> Optional[Dict]: + async def async_pre_request_hook(self, model: str, messages: List[Dict], kwargs: Dict) -> Optional[Dict]: """ Pre-request hook to convert native web search tools to LiteLLM standard. @@ -391,9 +367,7 @@ async def async_pre_request_hook( Modified kwargs dict with converted tools, or None if no modifications needed """ # Check if this request is for an enabled provider - custom_llm_provider = kwargs.get("litellm_params", {}).get( - "custom_llm_provider", "" - ) + custom_llm_provider = kwargs.get("litellm_params", {}).get("custom_llm_provider", "") verbose_logger.debug( f"WebSearchInterception: Pre-request hook called" @@ -401,10 +375,7 @@ async def async_pre_request_hook( f" - enabled_providers={self.enabled_providers or 'ALL'}" ) - if ( - self.enabled_providers is not None - and custom_llm_provider not in self.enabled_providers - ): + if self.enabled_providers is not None and custom_llm_provider not in self.enabled_providers: verbose_logger.debug( f"WebSearchInterception: Skipping - provider {custom_llm_provider} not in {self.enabled_providers}" ) @@ -420,9 +391,7 @@ async def async_pre_request_hook( if not has_websearch: return None - verbose_logger.debug( - f"WebSearchInterception: Pre-request hook triggered for provider={custom_llm_provider}" - ) + verbose_logger.debug(f"WebSearchInterception: Pre-request hook triggered for provider={custom_llm_provider}") # If the client sent an Anthropic-native web_search_* tool, mark the # request so the agentic loop emits native web_search_tool_result @@ -451,15 +420,11 @@ async def async_pre_request_hook( ) if "tool_choice" in kwargs: - kwargs["tool_choice"] = self._sync_forced_tool_choice( - kwargs.get("tool_choice"), converted_tools - ) + kwargs["tool_choice"] = self._sync_forced_tool_choice(kwargs.get("tool_choice"), converted_tools) # Also convert here for direct callers that bypass the deployment hook. if kwargs.get("stream"): - verbose_logger.debug( - "WebSearchInterception: Converting stream=True to stream=False" - ) + verbose_logger.debug("WebSearchInterception: Converting stream=True to stream=False") kwargs["stream"] = False kwargs["_websearch_interception_converted_stream"] = True @@ -482,18 +447,13 @@ async def async_should_run_agentic_loop( For chat completions, use async_should_run_chat_completion_agentic_loop instead. """ - verbose_logger.debug( - f"WebSearchInterception: Hook called! provider={custom_llm_provider}, stream={stream}" - ) + verbose_logger.debug(f"WebSearchInterception: Hook called! provider={custom_llm_provider}, stream={stream}") verbose_logger.debug(f"WebSearchInterception: Response type: {type(response)}") # Check if provider should be intercepted # Note: custom_llm_provider is already normalized by get_llm_provider() # (e.g., "bedrock/invoke/..." -> "bedrock") - if ( - self.enabled_providers is not None - and custom_llm_provider not in self.enabled_providers - ): + if self.enabled_providers is not None and custom_llm_provider not in self.enabled_providers: verbose_logger.debug( f"WebSearchInterception: Skipping provider {custom_llm_provider} (not in enabled list: {self.enabled_providers})" ) @@ -513,9 +473,7 @@ async def async_should_run_agentic_loop( ) if not should_intercept: - verbose_logger.debug( - "WebSearchInterception: No WebSearch tool_use detected in response" - ) + verbose_logger.debug("WebSearchInterception: No WebSearch tool_use detected in response") return False, {} verbose_logger.debug( @@ -547,9 +505,7 @@ async def async_should_run_agentic_loop( thinking_block_dict: Dict = {"type": block_type} if block_type == "thinking": thinking_block_dict["thinking"] = getattr(block, "thinking", "") - thinking_block_dict["signature"] = getattr( - block, "signature", "" - ) + thinking_block_dict["signature"] = getattr(block, "signature", "") else: # redacted_thinking thinking_block_dict["data"] = getattr(block, "data", "") thinking_blocks.append(thinking_block_dict) @@ -591,23 +547,16 @@ async def async_should_run_chat_completion_agentic_loop( verbose_logger.debug(f"WebSearchInterception: Response type: {type(response)}") # Check if provider should be intercepted - if ( - self.enabled_providers is not None - and custom_llm_provider not in self.enabled_providers - ): + if self.enabled_providers is not None and custom_llm_provider not in self.enabled_providers: verbose_logger.debug( f"WebSearchInterception: Skipping provider {custom_llm_provider} (not in enabled list: {self.enabled_providers})" ) return False, {} # Check if tools include any web search tool (strict check for chat completions) - has_websearch_tool = any( - is_web_search_tool_chat_completion(t) for t in (tools or []) - ) + has_websearch_tool = any(is_web_search_tool_chat_completion(t) for t in (tools or [])) if not has_websearch_tool: - verbose_logger.debug( - "WebSearchInterception: No litellm_web_search tool in request" - ) + verbose_logger.debug("WebSearchInterception: No litellm_web_search tool in request") return False, {} # Detect WebSearch tool_calls in response (OpenAI format) @@ -618,9 +567,7 @@ async def async_should_run_chat_completion_agentic_loop( ) if not should_intercept: - verbose_logger.debug( - "WebSearchInterception: No WebSearch tool_calls detected in response" - ) + verbose_logger.debug("WebSearchInterception: No WebSearch tool_calls detected in response") return False, {} verbose_logger.debug( @@ -657,9 +604,7 @@ async def async_run_agentic_loop( tool_calls = tools["tool_calls"] thinking_blocks = tools.get("thinking_blocks", []) - verbose_logger.debug( - f"WebSearchInterception: Executing agentic loop for {len(tool_calls)} search(es)" - ) + verbose_logger.debug(f"WebSearchInterception: Executing agentic loop for {len(tool_calls)} search(es)") return await self._execute_agentic_loop( model=model, @@ -706,11 +651,9 @@ async def async_build_agentic_loop_plan( # (while we still have the structured SearchResponse list) and stash # them on plan metadata for the post-hook to inject. if kwargs.get(WEBSEARCH_EMIT_NATIVE_BLOCKS_KEY): - metadata[WEBSEARCH_NATIVE_BLOCKS_METADATA_KEY] = ( - self._build_native_result_blocks( - tool_calls=tool_calls, - structured_results=structured_results, - ) + metadata[WEBSEARCH_NATIVE_BLOCKS_METADATA_KEY] = self._build_native_result_blocks( + tool_calls=tool_calls, + structured_results=structured_results, ) return AgenticLoopPlan( @@ -759,9 +702,7 @@ def _build_native_result_blocks( return blocks @staticmethod - def _inject_native_blocks( - response: Any, native_blocks: List[Dict[str, Any]] - ) -> Any: + def _inject_native_blocks(response: Any, native_blocks: List[Dict[str, Any]]) -> Any: """Prepend native blocks to response content, dict or object form.""" if not native_blocks: return response @@ -776,8 +717,7 @@ def _inject_native_blocks( # Object refused write — fall through and leave the response # untouched rather than crash the request. verbose_logger.debug( - "WebSearchInterception: could not inject native blocks into " - f"response of type {type(response).__name__}" + f"WebSearchInterception: could not inject native blocks into response of type {type(response).__name__}" ) return response @@ -891,9 +831,7 @@ def _prepare_followup_kwargs(kwargs: Dict) -> Dict: """ _internal_keys = {"litellm_logging_obj"} return { - k: v - for k, v in kwargs.items() - if not k.startswith("_websearch_interception") and k not in _internal_keys + k: v for k, v in kwargs.items() if not k.startswith("_websearch_interception") and k not in _internal_keys } async def _execute_agentic_loop( @@ -975,21 +913,15 @@ async def _build_anthropic_request_patch( for tool_call in tool_calls: query = tool_call["input"].get("query") if query: - verbose_logger.debug( - f"WebSearchInterception: Queuing search for query='{query}'" - ) + verbose_logger.debug(f"WebSearchInterception: Queuing search for query='{query}'") search_tasks.append(self._execute_search(query)) else: - verbose_logger.debug( - f"WebSearchInterception: Tool call {tool_call['id']} has no query" - ) + verbose_logger.debug(f"WebSearchInterception: Tool call {tool_call['id']} has no query") # Add empty result for tools without query search_tasks.append(self._create_empty_search_result()) # Execute searches in parallel - verbose_logger.debug( - f"WebSearchInterception: Executing {len(search_tasks)} search(es) in parallel" - ) + verbose_logger.debug(f"WebSearchInterception: Executing {len(search_tasks)} search(es) in parallel") search_results = await asyncio.gather(*search_tasks, return_exceptions=True) # Split the gathered (text, structured) tuples into two parallel lists. @@ -999,29 +931,17 @@ async def _build_anthropic_request_patch( structured_results: List[Optional[SearchResponse]] = [] for i, result in enumerate(search_results): if isinstance(result, Exception): - verbose_logger.error( - f"WebSearchInterception: Search {i} failed with error: {str(result)}" - ) + verbose_logger.error(f"WebSearchInterception: Search {i} failed with error: {str(result)}") final_search_results.append(f"Search failed: {str(result)}") structured_results.append(None) elif isinstance(result, tuple) and len(result) == 2: text_value, structured_value = result - final_search_results.append( - cast(str, text_value) - if isinstance(text_value, str) - else str(text_value) - ) - structured_results.append( - structured_value - if isinstance(structured_value, SearchResponse) - else None - ) + final_search_results.append(cast(str, text_value) if isinstance(text_value, str) else str(text_value)) + structured_results.append(structured_value if isinstance(structured_value, SearchResponse) else None) else: # Defensive: legacy callers / unexpected shape — preserve text, # drop structure. - verbose_logger.debug( - f"WebSearchInterception: Unexpected result type {type(result)} at index {i}" - ) + verbose_logger.debug(f"WebSearchInterception: Unexpected result type {type(result)} at index {i}") final_search_results.append(str(result)) structured_results.append(None) @@ -1035,35 +955,24 @@ async def _build_anthropic_request_patch( follow_up_messages = messages + [assistant_message, cast(Dict, user_message)] # Correlation context for structured logging - _call_id = getattr(logging_obj, "litellm_call_id", None) or kwargs.get( - "litellm_call_id", "unknown" - ) + _call_id = getattr(logging_obj, "litellm_call_id", None) or kwargs.get("litellm_call_id", "unknown") full_model_name = model # safe default before try block - max_tokens = self._resolve_max_tokens( - anthropic_messages_optional_request_params, kwargs - ) + max_tokens = self._resolve_max_tokens(anthropic_messages_optional_request_params, kwargs) - verbose_logger.debug( - f"WebSearchInterception: Using max_tokens={max_tokens} for follow-up request" - ) + verbose_logger.debug(f"WebSearchInterception: Using max_tokens={max_tokens} for follow-up request") optional_params_without_max_tokens = { - k: v - for k, v in anthropic_messages_optional_request_params.items() - if k != "max_tokens" + k: v for k, v in anthropic_messages_optional_request_params.items() if k != "max_tokens" } kwargs_for_followup = self._prepare_followup_kwargs(kwargs) if logging_obj is not None: - agentic_params = logging_obj.model_call_details.get( - "agentic_loop_params", {} - ) + agentic_params = logging_obj.model_call_details.get("agentic_loop_params", {}) full_model_name = agentic_params.get("model", model) verbose_logger.debug( - "WebSearchInterception: Built anthropic request patch " - "[call_id=%s model=%s messages=%d searches=%d]", + "WebSearchInterception: Built anthropic request patch [call_id=%s model=%s messages=%d searches=%d]", _call_id, full_model_name, len(follow_up_messages), @@ -1112,9 +1021,7 @@ async def _execute_search(self, query: str) -> Tuple[str, Optional[SearchRespons ] if matching_tools: search_tool = matching_tools[0] - search_provider = search_tool.get("litellm_params", {}).get( - "search_provider" - ) + search_provider = search_tool.get("litellm_params", {}).get("search_provider") verbose_logger.debug( f"WebSearchInterception: Found search tool '{self.search_tool_name}' " f"with provider '{search_provider}'" @@ -1128,9 +1035,7 @@ async def _execute_search(self, query: str) -> Tuple[str, Optional[SearchRespons # If no specific tool or not found, use first available if not search_provider and llm_router.search_tools: first_tool = llm_router.search_tools[0] - search_provider = first_tool.get("litellm_params", {}).get( - "search_provider" - ) + search_provider = first_tool.get("litellm_params", {}).get("search_provider") verbose_logger.debug( f"WebSearchInterception: Using first available search tool with provider '{search_provider}'" ) @@ -1156,9 +1061,7 @@ async def _execute_search(self, query: str) -> Tuple[str, Optional[SearchRespons ) return search_result_text, result except Exception as e: - verbose_logger.error( - f"WebSearchInterception: Search failed for '{query}': {str(e)}" - ) + verbose_logger.error(f"WebSearchInterception: Search failed for '{query}': {str(e)}") raise async def _execute_chat_completion_agentic_loop( @@ -1218,21 +1121,15 @@ async def _build_chat_completion_request_patch( query = args.get("query") if query: - verbose_logger.debug( - f"WebSearchInterception: Queuing search for query='{query}'" - ) + verbose_logger.debug(f"WebSearchInterception: Queuing search for query='{query}'") search_tasks.append(self._execute_search(query)) else: - verbose_logger.debug( - f"WebSearchInterception: Tool call {tool_call.get('id')} has no query" - ) + verbose_logger.debug(f"WebSearchInterception: Tool call {tool_call.get('id')} has no query") # Add empty result for tools without query search_tasks.append(self._create_empty_search_result()) # Execute searches in parallel - verbose_logger.debug( - f"WebSearchInterception: Executing {len(search_tasks)} search(es) in parallel" - ) + verbose_logger.debug(f"WebSearchInterception: Executing {len(search_tasks)} search(es) in parallel") search_results = await asyncio.gather(*search_tasks, return_exceptions=True) # Chat-completion path only needs text — OpenAI tool_result format @@ -1240,21 +1137,13 @@ async def _build_chat_completion_request_patch( final_search_results: List[str] = [] for i, result in enumerate(search_results): if isinstance(result, Exception): - verbose_logger.error( - f"WebSearchInterception: Search {i} failed with error: {str(result)}" - ) + verbose_logger.error(f"WebSearchInterception: Search {i} failed with error: {str(result)}") final_search_results.append(f"Search failed: {str(result)}") elif isinstance(result, tuple) and len(result) == 2: text_value, _ = result - final_search_results.append( - cast(str, text_value) - if isinstance(text_value, str) - else str(text_value) - ) + final_search_results.append(cast(str, text_value) if isinstance(text_value, str) else str(text_value)) else: - verbose_logger.debug( - f"WebSearchInterception: Unexpected result type {type(result)} at index {i}" - ) + verbose_logger.debug(f"WebSearchInterception: Unexpected result type {type(result)} at index {i}") final_search_results.append(str(result)) # Build assistant and tool messages using transformation @@ -1270,9 +1159,7 @@ async def _build_chat_completion_request_patch( # Make follow-up request with search results # For OpenAI format, tool_messages_or_user is a list of tool messages if response_format == "openai": - follow_up_messages = ( - messages + [assistant_message] + cast(List[Dict], tool_messages_or_user) - ) + follow_up_messages = messages + [assistant_message] + cast(List[Dict], tool_messages_or_user) else: # For Anthropic format (shouldn't happen in this method, but handle it) follow_up_messages = messages + [ @@ -1280,12 +1167,8 @@ async def _build_chat_completion_request_patch( cast(Dict, tool_messages_or_user), ] - verbose_logger.debug( - "WebSearchInterception: Making follow-up chat completion request with search results" - ) - verbose_logger.debug( - f"WebSearchInterception: Follow-up messages count: {len(follow_up_messages)}" - ) + verbose_logger.debug("WebSearchInterception: Making follow-up chat completion request with search results") + verbose_logger.debug(f"WebSearchInterception: Follow-up messages count: {len(follow_up_messages)}") # Remove internal parameters that shouldn't be passed to follow-up request internal_params = { @@ -1298,9 +1181,7 @@ async def _build_chat_completion_request_patch( "custom_prompt_dict", } kwargs_for_followup = { - k: v - for k, v in kwargs.items() - if not k.startswith("_websearch_interception") and k not in internal_params + k: v for k, v in kwargs.items() if not k.startswith("_websearch_interception") and k not in internal_params } full_model_name = model @@ -1322,6 +1203,7 @@ async def _build_chat_completion_request_patch( if k not in { "tools", + "tool_choice", "extra_body", "model_alias_map", "stream_response", From a9bcd2372fa46ab0681e032b68ed399f331ab073 Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Mon, 29 Jun 2026 18:23:08 -0700 Subject: [PATCH 3/9] fix(websearch): inject api_key into agentic hook kwargs for anthropic messages Follow-up calls inside async_run_agentic_loop (e.g. websearch interception's synthesis call after executing Exa/Perplexity searches) were missing api_key because the named api_key param in async_anthropic_messages_handler was never merged into the kwargs dict forwarded downstream. Result: every /v1/messages websearch follow-up failed with "x-api-key header is required" and the caller received the raw tool_use response instead of the synthesized answer. --- litellm/llms/custom_httpx/llm_http_handler.py | 8 ++- .../custom_httpx/test_llm_http_handler.py | 67 +++++++++++++++++++ 2 files changed, 73 insertions(+), 2 deletions(-) diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.py index 056d3a4b4d59..4cf9fd1d5087 100644 --- a/litellm/llms/custom_httpx/llm_http_handler.py +++ b/litellm/llms/custom_httpx/llm_http_handler.py @@ -2210,7 +2210,7 @@ async def async_anthropic_messages_handler( anthropic_messages_optional_request_params=anthropic_messages_optional_request_params, logging_obj=logging_obj, custom_llm_provider=custom_llm_provider, - kwargs=kwargs, + kwargs={**kwargs, "api_key": api_key} if api_key else kwargs, ) return initial_response else: @@ -2220,6 +2220,10 @@ async def async_anthropic_messages_handler( logging_obj=logging_obj, ) + # Inject api_key into kwargs so follow-up calls in agentic hooks can + # authenticate. api_key is a named param here (not in kwargs), so + # _prepare_followup_kwargs would miss it otherwise. + kwargs_for_agentic = {**kwargs, "api_key": api_key} if api_key else kwargs # Call agentic completion hooks (non-streaming path only) final_response = await self._call_agentic_completion_hooks( response=initial_response, @@ -2230,7 +2234,7 @@ async def async_anthropic_messages_handler( logging_obj=logging_obj, stream=False, custom_llm_provider=custom_llm_provider, - kwargs=kwargs, + kwargs=kwargs_for_agentic, ) return self._maybe_wrap_in_fake_stream( diff --git a/tests/test_litellm/llms/custom_httpx/test_llm_http_handler.py b/tests/test_litellm/llms/custom_httpx/test_llm_http_handler.py index 64ae30daa708..76f2659ea41a 100644 --- a/tests/test_litellm/llms/custom_httpx/test_llm_http_handler.py +++ b/tests/test_litellm/llms/custom_httpx/test_llm_http_handler.py @@ -1170,3 +1170,70 @@ def test_async_compact_handler_sends_json_when_not_signed(): ) assert kwargs.get("json") == {"model": "openai.gpt-5.5", "input": "hi"} assert "data" not in kwargs + + +@pytest.mark.asyncio +async def test_async_anthropic_messages_handler_passes_api_key_to_agentic_hooks(): + """ + Regression: async_anthropic_messages_handler must inject api_key into the + kwargs dict forwarded to _call_agentic_completion_hooks. + + Without this, follow-up calls made by agentic hooks (e.g. websearch + interception's second LLM call after executing searches) have no api_key + and fail with "x-api-key header is required". + """ + handler = BaseLLMHTTPHandler() + + mock_config = Mock() + mock_config.validate_anthropic_messages_environment = Mock( + return_value=({"x-api-key": "sk-test"}, "https://api.anthropic.com") + ) + mock_config.transform_anthropic_messages_request = Mock( + return_value={"model": "claude-haiku", "messages": [], "max_tokens": 16} + ) + mock_config.sign_request = Mock(return_value=({}, None)) + + fake_raw_response = {"id": "msg_1", "type": "message", "role": "assistant", "content": [], "stop_reason": "end_turn"} + mock_config.transform_anthropic_messages_response = Mock(return_value=fake_raw_response) + + mock_logging_obj = Mock() + mock_logging_obj.update_environment_variables = Mock() + mock_logging_obj.model_call_details = {} + mock_logging_obj.stream = False + mock_logging_obj.dynamic_success_callbacks = None + + captured_kwargs: dict = {} + sentinel_response = object() + + async def fake_agentic_hooks(**call_kwargs): + captured_kwargs.update(call_kwargs) + return sentinel_response + + mock_httpx_response = Mock() + mock_httpx_response.status_code = 200 + + with ( + patch.object(handler, "_async_post_anthropic_messages_with_http_error_retry", new=AsyncMock(return_value=mock_httpx_response)), + patch.object(handler, "_call_agentic_completion_hooks", side_effect=fake_agentic_hooks), + patch("litellm.llms.custom_httpx.llm_http_handler.get_async_httpx_client"), + patch("litellm.litellm_core_utils.get_provider_specific_headers.ProviderSpecificHeaderUtils.get_provider_specific_headers", return_value=None), + ): + result = await handler.async_anthropic_messages_handler( + model="claude-haiku", + messages=[{"role": "user", "content": "hi"}], + anthropic_messages_provider_config=mock_config, + anthropic_messages_optional_request_params={"stream": False}, + custom_llm_provider="anthropic", + litellm_params=GenericLiteLLMParams(api_key="sk-real-anthropic-key"), + logging_obj=mock_logging_obj, + api_key="sk-real-anthropic-key", + stream=False, + ) + + assert result is sentinel_response + assert "kwargs" in captured_kwargs, "_call_agentic_completion_hooks not called" + forwarded = captured_kwargs["kwargs"] + assert forwarded.get("api_key") == "sk-real-anthropic-key", ( + "api_key must be injected into kwargs passed to _call_agentic_completion_hooks " + "so follow-up calls in agentic hooks (e.g. websearch) can authenticate" + ) From 45b60e088d6493c564b6fefc9994b3ada335e96e Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Mon, 29 Jun 2026 18:39:07 -0700 Subject: [PATCH 4/9] ci: trigger CI run From 087edeb16b6aa0d8c2258afd4362ec8229f39eeb Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Mon, 29 Jun 2026 18:46:46 -0700 Subject: [PATCH 5/9] fix(websearch): support unified agentic hooks alongside chat-completion-specific hooks CodeInterpreterInterceptionLogger uses async_should_run_agentic_loop with _agentic_loop_api_surface to handle both surfaces from one hook. The chat completion loop must also check _gate_overridden so callbacks using the unified hook pattern still fire for chat completions. --- .../chat_completion_agentic_loop.py | 69 +++++++++++++------ .../test_chat_completion_agentic_loop.py | 7 +- 2 files changed, 51 insertions(+), 25 deletions(-) diff --git a/litellm/litellm_core_utils/chat_completion_agentic_loop.py b/litellm/litellm_core_utils/chat_completion_agentic_loop.py index df8a3e572603..9aecf9c2e28b 100644 --- a/litellm/litellm_core_utils/chat_completion_agentic_loop.py +++ b/litellm/litellm_core_utils/chat_completion_agentic_loop.py @@ -218,7 +218,10 @@ async def maybe_run_chat_completion_agentic_loop( for callback in callbacks: if not isinstance(callback, CustomLogger): continue - if not _chat_completion_gate_overridden(callback): + + uses_chat_completion_hooks = _chat_completion_gate_overridden(callback) + uses_unified_hooks = not uses_chat_completion_hooks and _gate_overridden(callback) + if not uses_chat_completion_hooks and not uses_unified_hooks: continue gate_kwargs = { @@ -227,15 +230,26 @@ async def maybe_run_chat_completion_agentic_loop( "custom_llm_provider": custom_llm_provider, } try: - should_run, tool_calls = await callback.async_should_run_chat_completion_agentic_loop( - response=response, - model=model, - messages=messages, - tools=tools, - stream=stream, - custom_llm_provider=custom_llm_provider, - kwargs=gate_kwargs, - ) + if uses_chat_completion_hooks: + should_run, tool_calls = await callback.async_should_run_chat_completion_agentic_loop( + response=response, + model=model, + messages=messages, + tools=tools, + stream=stream, + custom_llm_provider=custom_llm_provider, + kwargs=gate_kwargs, + ) + else: + should_run, tool_calls = await callback.async_should_run_agentic_loop( + response=response, + model=model, + messages=messages, + tools=tools, + stream=stream, + custom_llm_provider=custom_llm_provider, + kwargs=gate_kwargs, + ) except Exception as e: verbose_logger.exception( "LiteLLM.AgenticHookError: Exception in chat completion agentic gate: %s", @@ -260,7 +274,7 @@ async def maybe_run_chat_completion_agentic_loop( "_agentic_loop_api_surface": CHAT_COMPLETION_AGENTIC_SURFACE, "custom_llm_provider": custom_llm_provider, } - if not _chat_completion_build_plan_overridden(callback): + if uses_chat_completion_hooks and not _chat_completion_build_plan_overridden(callback): return await callback.async_run_chat_completion_agentic_loop( tools=tool_calls, model=model, @@ -272,16 +286,29 @@ async def maybe_run_chat_completion_agentic_loop( kwargs=plan_kwargs, ) - plan = await callback.async_build_chat_completion_agentic_loop_plan( - tools=tool_calls, - model=model, - messages=messages, - response=response, - optional_params=optional_params, - logging_obj=logging_obj, - stream=stream, - kwargs=plan_kwargs, - ) + if uses_chat_completion_hooks: + plan = await callback.async_build_chat_completion_agentic_loop_plan( + tools=tool_calls, + model=model, + messages=messages, + response=response, + optional_params=optional_params, + logging_obj=logging_obj, + stream=stream, + kwargs=plan_kwargs, + ) + else: + plan = await callback.async_build_agentic_loop_plan( + tools=tool_calls, + model=model, + messages=messages, + response=response, + anthropic_messages_provider_config=None, + anthropic_messages_optional_request_params=optional_params, + logging_obj=logging_obj, + stream=stream, + kwargs=plan_kwargs, + ) if plan.response_override is not None: return plan.response_override diff --git a/tests/test_litellm/litellm_core_utils/test_chat_completion_agentic_loop.py b/tests/test_litellm/litellm_core_utils/test_chat_completion_agentic_loop.py index f1196ab46923..613c4931eb83 100644 --- a/tests/test_litellm/litellm_core_utils/test_chat_completion_agentic_loop.py +++ b/tests/test_litellm/litellm_core_utils/test_chat_completion_agentic_loop.py @@ -228,7 +228,7 @@ def __init__(self, plan: AgenticLoopPlan, tool_calls: Dict[str, Any]) -> None: self._tool_calls = tool_calls self.cleanup_calls = 0 - async def async_should_run_agentic_loop( + async def async_should_run_chat_completion_agentic_loop( self, response: Any, model: str, @@ -240,14 +240,13 @@ async def async_should_run_agentic_loop( ) -> Tuple[bool, Dict[str, Any]]: return True, self._tool_calls - async def async_build_agentic_loop_plan( + async def async_build_chat_completion_agentic_loop_plan( self, tools: Dict[str, Any], model: str, messages: List[Dict[str, Any]], response: Any, - anthropic_messages_provider_config: Any, - anthropic_messages_optional_request_params: Dict[str, Any], + optional_params: Dict[str, Any], logging_obj: Any, stream: bool, kwargs: Dict[str, Any], From 7a41f6e497bb66b213d0b657935372b3214bca2e Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Mon, 29 Jun 2026 19:12:30 -0700 Subject: [PATCH 6/9] fix(websearch): strip tool_choice from legacy chat completion follow-up call The _execute_chat_completion_agentic_loop path merged original optional_params (which includes forced tool_choice) into follow-up params without explicit removal. _build_chat_completion_request_patch already excluded tool_choice from its optional_params output, but dict.update() with a missing key leaves the original value intact. Explicit pop after the merge removes it. --- .../websearch_interception/handler.py | 1 + .../test_websearch_chat_completion.py | 50 +++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/litellm/integrations/websearch_interception/handler.py b/litellm/integrations/websearch_interception/handler.py index e715e3d15a31..f93adb77ed48 100644 --- a/litellm/integrations/websearch_interception/handler.py +++ b/litellm/integrations/websearch_interception/handler.py @@ -1088,6 +1088,7 @@ async def _execute_chat_completion_agentic_loop( raise ValueError("WebSearchInterception: missing follow-up messages") params = dict(optional_params) params.update(request_patch.optional_params) + params.pop("tool_choice", None) return await litellm.acompletion( model=request_patch.model or model, messages=request_patch.messages, diff --git a/tests/test_litellm/integrations/websearch_interception/test_websearch_chat_completion.py b/tests/test_litellm/integrations/websearch_interception/test_websearch_chat_completion.py index a1cdbe542131..7ef43e2eadf5 100644 --- a/tests/test_litellm/integrations/websearch_interception/test_websearch_chat_completion.py +++ b/tests/test_litellm/integrations/websearch_interception/test_websearch_chat_completion.py @@ -494,6 +494,56 @@ async def fake_build_plan(tools, model, messages, response, optional_params, log assert result is sentinel, "Expected agentic loop to return sentinel final response" +@pytest.mark.asyncio +async def test_execute_chat_completion_agentic_loop_strips_tool_choice(): + """Regression: _execute_chat_completion_agentic_loop must not forward tool_choice + from the original request into the follow-up synthesis call. + + When the original request forces tool_choice to litellm_web_search, merging + optional_params into the follow-up params without explicit removal causes the + model to call the search tool again instead of synthesizing an answer. + """ + from unittest.mock import patch + + websearch_logger = WebSearchInterceptionLogger(enabled_providers=[LlmProviders.OPENAI]) + + captured_kwargs: dict = {} + + async def fake_acompletion(**kwargs): + captured_kwargs.update(kwargs) + return ModelResponse(id="followup", model="gpt-4o", object="chat.completion") + + async def fake_search(query): + return ("Bitcoin price is $60,000", None) + + with patch.object(websearch_logger, "_execute_search", side_effect=fake_search): + with patch("litellm.acompletion", side_effect=fake_acompletion): + await websearch_logger._execute_chat_completion_agentic_loop( + model="gpt-4o", + messages=[{"role": "user", "content": "What is Bitcoin price?"}], + tool_calls=[ + { + "id": "call_1", + "name": "litellm_web_search", + "input": {"query": "bitcoin price"}, + } + ], + optional_params={ + "tools": [{"type": "function", "function": {"name": "litellm_web_search"}}], + "tool_choice": {"type": "function", "function": {"name": "litellm_web_search"}}, + "max_tokens": 512, + }, + logging_obj=MagicMock(), + stream=False, + kwargs={}, + ) + + assert "tool_choice" not in captured_kwargs, ( + "tool_choice must not appear in follow-up acompletion kwargs; " + "it would force the model to call the search tool again instead of synthesizing" + ) + + if __name__ == "__main__": # Run with: pytest test_websearch_chat_completion.py -v -s pytest.main([__file__, "-v", "-s"]) From 8eeee03fcb7f53deea3abf23e7b132442d8d9079 Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Mon, 29 Jun 2026 19:22:12 -0700 Subject: [PATCH 7/9] fix(websearch): always strip tool_choice from plan-path follow-up params The tool_choice removal was gated on patch.tools is not None. WebSearch sets tools via patch.optional_params not patch.tools, so the gate was False and forced tool_choice from the original request survived into the synthesis call. Move the pop outside the patch.tools branch so it applies unconditionally. --- litellm/litellm_core_utils/chat_completion_agentic_loop.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/litellm/litellm_core_utils/chat_completion_agentic_loop.py b/litellm/litellm_core_utils/chat_completion_agentic_loop.py index 9aecf9c2e28b..6a56bd8b9abb 100644 --- a/litellm/litellm_core_utils/chat_completion_agentic_loop.py +++ b/litellm/litellm_core_utils/chat_completion_agentic_loop.py @@ -149,8 +149,8 @@ async def _execute_chat_completion_agentic_plan( optional_params_for_followup = {**optional_params, **patch.optional_params} if patch.tools is not None: optional_params_for_followup["tools"] = patch.tools - if "tool_choice" not in patch.optional_params: - optional_params_for_followup.pop("tool_choice", None) + if "tool_choice" not in patch.optional_params: + optional_params_for_followup.pop("tool_choice", None) kwargs_for_followup = _filter_followup_kwargs(kwargs) kwargs_for_followup.update( From c16096fb80c8a835c55bd05e8e8da3efccd35418 Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Mon, 29 Jun 2026 20:57:50 -0700 Subject: [PATCH 8/9] refactor(websearch): simplify agentic hook dispatch to single boolean Replace three-variable conditional logic with one use_chat_hooks bool. Gate dispatch (gate fn selection) and plan dispatch both key off the same bool, with no intermediate uses_unified_hooks variable needed. --- .../chat_completion_agentic_loop.py | 56 ++++++++----------- 1 file changed, 22 insertions(+), 34 deletions(-) diff --git a/litellm/litellm_core_utils/chat_completion_agentic_loop.py b/litellm/litellm_core_utils/chat_completion_agentic_loop.py index 6a56bd8b9abb..8a4a9a782599 100644 --- a/litellm/litellm_core_utils/chat_completion_agentic_loop.py +++ b/litellm/litellm_core_utils/chat_completion_agentic_loop.py @@ -219,37 +219,30 @@ async def maybe_run_chat_completion_agentic_loop( if not isinstance(callback, CustomLogger): continue - uses_chat_completion_hooks = _chat_completion_gate_overridden(callback) - uses_unified_hooks = not uses_chat_completion_hooks and _gate_overridden(callback) - if not uses_chat_completion_hooks and not uses_unified_hooks: + use_chat_hooks = _chat_completion_gate_overridden(callback) + if not use_chat_hooks and not _gate_overridden(callback): continue - gate_kwargs = { + hook_kwargs = { **kwargs, "_agentic_loop_api_surface": CHAT_COMPLETION_AGENTIC_SURFACE, "custom_llm_provider": custom_llm_provider, } try: - if uses_chat_completion_hooks: - should_run, tool_calls = await callback.async_should_run_chat_completion_agentic_loop( - response=response, - model=model, - messages=messages, - tools=tools, - stream=stream, - custom_llm_provider=custom_llm_provider, - kwargs=gate_kwargs, - ) - else: - should_run, tool_calls = await callback.async_should_run_agentic_loop( - response=response, - model=model, - messages=messages, - tools=tools, - stream=stream, - custom_llm_provider=custom_llm_provider, - kwargs=gate_kwargs, - ) + gate = ( + callback.async_should_run_chat_completion_agentic_loop + if use_chat_hooks + else callback.async_should_run_agentic_loop + ) + should_run, tool_calls = await gate( + response=response, + model=model, + messages=messages, + tools=tools, + stream=stream, + custom_llm_provider=custom_llm_provider, + kwargs=hook_kwargs, + ) except Exception as e: verbose_logger.exception( "LiteLLM.AgenticHookError: Exception in chat completion agentic gate: %s", @@ -269,12 +262,7 @@ async def maybe_run_chat_completion_agentic_loop( ) try: - plan_kwargs = { - **kwargs, - "_agentic_loop_api_surface": CHAT_COMPLETION_AGENTIC_SURFACE, - "custom_llm_provider": custom_llm_provider, - } - if uses_chat_completion_hooks and not _chat_completion_build_plan_overridden(callback): + if use_chat_hooks and not _chat_completion_build_plan_overridden(callback): return await callback.async_run_chat_completion_agentic_loop( tools=tool_calls, model=model, @@ -283,10 +271,10 @@ async def maybe_run_chat_completion_agentic_loop( optional_params=optional_params, logging_obj=logging_obj, stream=stream, - kwargs=plan_kwargs, + kwargs=hook_kwargs, ) - if uses_chat_completion_hooks: + if use_chat_hooks: plan = await callback.async_build_chat_completion_agentic_loop_plan( tools=tool_calls, model=model, @@ -295,7 +283,7 @@ async def maybe_run_chat_completion_agentic_loop( optional_params=optional_params, logging_obj=logging_obj, stream=stream, - kwargs=plan_kwargs, + kwargs=hook_kwargs, ) else: plan = await callback.async_build_agentic_loop_plan( @@ -307,7 +295,7 @@ async def maybe_run_chat_completion_agentic_loop( anthropic_messages_optional_request_params=optional_params, logging_obj=logging_obj, stream=stream, - kwargs=plan_kwargs, + kwargs=hook_kwargs, ) if plan.response_override is not None: From b0ced1d6b274585421aadeadbc4a5392662b201b Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Tue, 30 Jun 2026 12:45:45 -0700 Subject: [PATCH 9/9] refactor(websearch): unify agentic hook dispatch to single flow Remove the if/else branching between chat-completion-specific hooks and unified hooks in maybe_run_chat_completion_agentic_loop. The dispatcher now exclusively uses _gate_overridden + async_should_run_agentic_loop. WebSearchInterceptionLogger routes to the appropriate internal method based on _agentic_loop_api_surface, keeping the separation of concerns inside the callback rather than in the dispatcher. --- .../websearch_interception/handler.py | 29 +++++++-- .../chat_completion_agentic_loop.py | 61 +++++-------------- .../test_chat_completion_agentic_loop.py | 25 +++----- 3 files changed, 48 insertions(+), 67 deletions(-) diff --git a/litellm/integrations/websearch_interception/handler.py b/litellm/integrations/websearch_interception/handler.py index f93adb77ed48..bfae6d5b7b0f 100644 --- a/litellm/integrations/websearch_interception/handler.py +++ b/litellm/integrations/websearch_interception/handler.py @@ -31,6 +31,7 @@ WebSearchInterceptionConfig, ) from litellm.types.integrations.custom_logger import ( + CHAT_COMPLETION_AGENTIC_SURFACE, AgenticLoopPlan, AgenticLoopRequestPatch, ) @@ -440,12 +441,16 @@ async def async_should_run_agentic_loop( custom_llm_provider: str, kwargs: Dict, ) -> Tuple[bool, Dict]: - """ - Check if WebSearch tool interception is needed for Anthropic Messages API. - - This is the legacy method for Anthropic-style responses. - For chat completions, use async_should_run_chat_completion_agentic_loop instead. - """ + if kwargs.get("_agentic_loop_api_surface") == CHAT_COMPLETION_AGENTIC_SURFACE: + return await self.async_should_run_chat_completion_agentic_loop( + response=response, + model=model, + messages=messages, + tools=tools, + stream=stream, + custom_llm_provider=custom_llm_provider, + kwargs=kwargs, + ) verbose_logger.debug(f"WebSearchInterception: Hook called! provider={custom_llm_provider}, stream={stream}") verbose_logger.debug(f"WebSearchInterception: Response type: {type(response)}") @@ -629,6 +634,18 @@ async def async_build_agentic_loop_plan( stream: bool, kwargs: Dict, ) -> AgenticLoopPlan: + if kwargs.get("_agentic_loop_api_surface") == CHAT_COMPLETION_AGENTIC_SURFACE: + return await self.async_build_chat_completion_agentic_loop_plan( + tools=tools, + model=model, + messages=messages, + response=response, + optional_params=anthropic_messages_optional_request_params, + logging_obj=logging_obj, + stream=stream, + kwargs=kwargs, + ) + tool_calls = tools["tool_calls"] thinking_blocks = tools.get("thinking_blocks", []) request_patch, structured_results = await self._build_anthropic_request_patch( diff --git a/litellm/litellm_core_utils/chat_completion_agentic_loop.py b/litellm/litellm_core_utils/chat_completion_agentic_loop.py index 8a4a9a782599..b7262a423248 100644 --- a/litellm/litellm_core_utils/chat_completion_agentic_loop.py +++ b/litellm/litellm_core_utils/chat_completion_agentic_loop.py @@ -34,24 +34,12 @@ def _gate_overridden(callback: CustomLogger) -> bool: return getattr(func, "__func__", func) is not getattr(base, "__func__", base) -def _chat_completion_gate_overridden(callback: CustomLogger) -> bool: - base = CustomLogger.async_should_run_chat_completion_agentic_loop - func = type(callback).async_should_run_chat_completion_agentic_loop - return getattr(func, "__func__", func) is not getattr(base, "__func__", base) - - def _build_plan_overridden(callback: CustomLogger) -> bool: base = CustomLogger.async_build_agentic_loop_plan func = type(callback).async_build_agentic_loop_plan return getattr(func, "__func__", func) is not getattr(base, "__func__", base) -def _chat_completion_build_plan_overridden(callback: CustomLogger) -> bool: - base = CustomLogger.async_build_chat_completion_agentic_loop_plan - func = type(callback).async_build_chat_completion_agentic_loop_plan - return getattr(func, "__func__", func) is not getattr(base, "__func__", base) - - def _post_hook_overridden(callback: CustomLogger) -> bool: base = CustomLogger.async_post_agentic_loop_response_hook func = type(callback).async_post_agentic_loop_response_hook @@ -219,8 +207,7 @@ async def maybe_run_chat_completion_agentic_loop( if not isinstance(callback, CustomLogger): continue - use_chat_hooks = _chat_completion_gate_overridden(callback) - if not use_chat_hooks and not _gate_overridden(callback): + if not _gate_overridden(callback): continue hook_kwargs = { @@ -229,12 +216,7 @@ async def maybe_run_chat_completion_agentic_loop( "custom_llm_provider": custom_llm_provider, } try: - gate = ( - callback.async_should_run_chat_completion_agentic_loop - if use_chat_hooks - else callback.async_should_run_agentic_loop - ) - should_run, tool_calls = await gate( + should_run, tool_calls = await callback.async_should_run_agentic_loop( response=response, model=model, messages=messages, @@ -262,31 +244,8 @@ async def maybe_run_chat_completion_agentic_loop( ) try: - if use_chat_hooks and not _chat_completion_build_plan_overridden(callback): - return await callback.async_run_chat_completion_agentic_loop( - tools=tool_calls, - model=model, - messages=messages, - response=response, - optional_params=optional_params, - logging_obj=logging_obj, - stream=stream, - kwargs=hook_kwargs, - ) - - if use_chat_hooks: - plan = await callback.async_build_chat_completion_agentic_loop_plan( - tools=tool_calls, - model=model, - messages=messages, - response=response, - optional_params=optional_params, - logging_obj=logging_obj, - stream=stream, - kwargs=hook_kwargs, - ) - else: - plan = await callback.async_build_agentic_loop_plan( + if not _build_plan_overridden(callback): + return await callback.async_run_agentic_loop( tools=tool_calls, model=model, messages=messages, @@ -298,6 +257,18 @@ async def maybe_run_chat_completion_agentic_loop( kwargs=hook_kwargs, ) + plan = await callback.async_build_agentic_loop_plan( + tools=tool_calls, + model=model, + messages=messages, + response=response, + anthropic_messages_provider_config=None, + anthropic_messages_optional_request_params=optional_params, + logging_obj=logging_obj, + stream=stream, + kwargs=hook_kwargs, + ) + if plan.response_override is not None: return plan.response_override if plan.terminate: diff --git a/tests/test_litellm/litellm_core_utils/test_chat_completion_agentic_loop.py b/tests/test_litellm/litellm_core_utils/test_chat_completion_agentic_loop.py index 613c4931eb83..cc16ad558e47 100644 --- a/tests/test_litellm/litellm_core_utils/test_chat_completion_agentic_loop.py +++ b/tests/test_litellm/litellm_core_utils/test_chat_completion_agentic_loop.py @@ -181,8 +181,7 @@ async def test_internal_control_fields_never_leak_into_provider_body(restore_cal # The loop must have actually fired (sanity: two provider calls). assert create.await_count == 2, ( - "expected the agentic loop to issue a follow-up provider call; " - f"got {create.await_count} call(s)" + f"expected the agentic loop to issue a follow-up provider call; got {create.await_count} call(s)" ) for idx, call in enumerate(create.await_args_list): @@ -194,8 +193,7 @@ async def test_internal_control_fields_never_leak_into_provider_body(restore_cal f"top-level request body: {sorted(body.keys())}" ) assert field not in extra_body, ( - f"provider call #{idx}: internal field {field!r} leaked into " - f"extra_body: {sorted(extra_body.keys())}" + f"provider call #{idx}: internal field {field!r} leaked into extra_body: {sorted(extra_body.keys())}" ) # The native code_interpreter tool must have been swapped for the # function tool, never sent raw to OpenAI as a chat-completions request. @@ -228,7 +226,7 @@ def __init__(self, plan: AgenticLoopPlan, tool_calls: Dict[str, Any]) -> None: self._tool_calls = tool_calls self.cleanup_calls = 0 - async def async_should_run_chat_completion_agentic_loop( + async def async_should_run_agentic_loop( self, response: Any, model: str, @@ -240,22 +238,21 @@ async def async_should_run_chat_completion_agentic_loop( ) -> Tuple[bool, Dict[str, Any]]: return True, self._tool_calls - async def async_build_chat_completion_agentic_loop_plan( + async def async_build_agentic_loop_plan( self, tools: Dict[str, Any], model: str, messages: List[Dict[str, Any]], response: Any, - optional_params: Dict[str, Any], + anthropic_messages_provider_config: Any, + anthropic_messages_optional_request_params: Dict[str, Any], logging_obj: Any, stream: bool, kwargs: Dict[str, Any], ) -> AgenticLoopPlan: return self._plan - async def async_agentic_loop_cleanup_hook( - self, plan: AgenticLoopPlan, kwargs: Dict[str, Any] - ) -> None: + async def async_agentic_loop_cleanup_hook(self, plan: AgenticLoopPlan, kwargs: Dict[str, Any]) -> None: self.cleanup_calls += 1 @@ -342,9 +339,7 @@ async def test_dispatcher_runs_followup_with_incremented_depth_and_patched_messa assert call_kwargs["max_agentic_loops"] >= 1 assert "_agentic_loop_fingerprints" in call_kwargs # Interception markers are mirrored into litellm_metadata for the follow-up. - assert ( - call_kwargs["litellm_metadata"]["_code_interpreter_interception_active"] is True - ) + assert call_kwargs["litellm_metadata"]["_code_interpreter_interception_active"] is True # The transient surface marker is NOT forwarded to the follow-up call. assert "_agentic_loop_api_surface" not in call_kwargs # Cleanup hook always runs. @@ -389,9 +384,7 @@ async def test_dispatcher_raises_on_repeated_tool_call_fingerprint(restore_callb # The dispatcher fingerprints the whole value the gate returns as its second # tuple element, so the seeded fingerprint must mirror that dict exactly. - gate_tool_calls = { - "tool_calls": [{"id": "call_abc", "name": "litellm_code_execution"}] - } + gate_tool_calls = {"tool_calls": [{"id": "call_abc", "name": "litellm_code_execution"}]} fingerprint = json.dumps(gate_tool_calls, sort_keys=True, default=str) logger = _GateOnlyLogger(