litellm/tests/unit/integrations/websearch_interception/test_websearch_responses.py
martenj4 8ef5cf1f25
fix(websearch_interception): answer a web search turn that reaches max_agentic_loops (#54053)
* fix(websearch_interception): answer from gathered results on the last follow-up the loop cap allows

When a web search turn reached max_agentic_loops, the last follow-up still
offered the search tool, so the model asked for one more search, the loop
refused it, and the user got no answer (an empty end_turn on /v1/messages and
a dangling litellm_web_search call on chat and responses).

The follow-up the cap allows last now drops the intercepted search tool and
keeps client tools. When no tools remain it sends tool_choice none, because
Claude otherwise calls the search tool it saw in the history. This applies to
anthropic, azure_ai, vertex_ai, openai and gemini, the providers probed live.
Bedrock and other providers keep today's behavior.

The deployment hook now passes the callback's max_agentic_loops into the call,
so the dispatchers and the builder agree on the ceiling. Chat follow-ups carry
the loop depth in litellm_metadata, so the openai and http chat paths can see
it.

* fix(websearch_interception): answer a capped turn with a max_uses_exceeded result and one last call without search

Claude ended a capped turn with no text when the last allowed follow-up simply
dropped the search tool, since it still wanted to search. The dispatchers now
let a callback that opts in through answers_tool_calls_at_agentic_loop_cap run
once more at the cap. The websearch hook answers the refused search calls with
a max_uses_exceeded search result instead of searching, and sends one last call
without the search tool (client tools kept, tool_choice none when nothing is
left). Bedrock is not opted in and keeps the old refusal.

The three per-surface search loops are now one helper.

* fix(anthropic messages): keep the client's max_tokens on every agentic follow-up

The request transform popped max_tokens off the params dict the agentic hooks
read afterwards, so every /v1/messages follow-up fell back to 1024 and a capped
turn could stop at max_tokens before answering. The handler now gives the
transform its own copy.

* fix(websearch_interception): keep the allowed_tools limit on the capped call and strip loop controls from client metadata

* fix(websearch): keep the capped last call from searching again or calling a forced client tool

The refused search now tells the model to answer from the results it has. If the
last call at the cap still asks for a search, the chat and Responses gates claim it
so the loop ends the turn with that call removed instead of handing the client a
tool it never declared. A tool_choice that forces some tool is relaxed to auto on
that call, while a choice naming one client tool stays. ARCHITECTURE.md now says the
feature-level cap covers all three routes and which providers get the last call

* docs(websearch_interception): say the loop cap counts rounds of searching, not single searches

* fix(websearch_interception): keep the one-tool-call limit and drop parallel_tool_calls on the last call at the cap

The tool-free last chat call no longer sends parallel_tool_calls, which OpenAI rejects without tools

A forced choice relaxed to auto keeps disable_parallel_tool_use on /v1/messages, and a choice forcing the search tool becomes auto instead of being dropped

/v1/messages drops a search call the capped call still made, like chat and Responses already do

The chat capped call reads the request's tool_choice the same way the other routes do

* fix(azure_ai): drop tool_choice when a chat request has no tools, as the OpenAI config does

* fix(websearch_interception): keep the feature-level max_agentic_loops on /v1/messages only, as on main

Chat and Responses read the deployment's own max_agentic_loops or the default of 3. Applying the feature-level value there ended turns empty on Bedrock and other providers outside the answer-at-cap list once it was below 3

* test(websearch_interception): type the cap-source parameters of the chat and Responses cap tests

---------

Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
2026-11-24 01:55:38 -08:00

616 lines
22 KiB
Python

"""
Integration tests for WebSearch interception with the Responses API.
Tests that the websearch_interception callback intercepts litellm_web_search
tool calls returned by /v1/responses, executes the search server-side, and
builds a Responses-format follow-up request.
"""
import datetime
from types import SimpleNamespace
from typing import Final
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
import respx
import litellm
from litellm.integrations.websearch_interception.handler import (
WebSearchInterceptionLogger,
)
from litellm.integrations.websearch_interception.tools import get_litellm_web_search_tool_responses
from litellm.types.integrations.custom_logger import (
RESPONSES_AGENTIC_SURFACE,
)
from litellm.litellm_core_utils.allowed_tools_tool_choice import tool_calls_the_choice_excludes
from litellm.litellm_core_utils.litellm_logging import Logging
from litellm.types.utils import CallTypes, LlmProviders
from .conftest import FINAL_ANSWER, offered_tool_names, request_bodies
def _responses_output_with_web_search(call_id: str = "fc_1", query: str = "latest ai news"):
return SimpleNamespace(
output=[
SimpleNamespace(
type="function_call",
name="litellm_web_search",
call_id=call_id,
arguments='{"query": "%s"}' % query,
)
]
)
@pytest.mark.asyncio
async def test_responses_hook_detects_function_call():
"""async_should_run_responses_agentic_loop detects a litellm_web_search function_call."""
logger = WebSearchInterceptionLogger(enabled_providers=[LlmProviders.OPENAI])
should_run, tools_dict = await logger.async_should_run_responses_agentic_loop(
response=_responses_output_with_web_search(),
model="gpt-4o",
messages=[{"role": "user", "content": "What's the latest AI news?"}],
tools=[{"type": "function", "name": "litellm_web_search"}],
stream=False,
custom_llm_provider="openai",
kwargs={},
)
assert should_run is True
assert tools_dict["response_format"] == "responses"
assert len(tools_dict["tool_calls"]) == 1
assert tools_dict["tool_calls"][0]["name"] == "litellm_web_search"
assert tools_dict["tool_calls"][0]["call_id"] == "fc_1"
assert tools_dict["tool_calls"][0]["input"] == {"query": "latest ai news"}
@pytest.mark.asyncio
async def test_responses_hook_not_triggered_without_tool():
"""No web search tool in the request -> hook must not run."""
logger = WebSearchInterceptionLogger(enabled_providers=[LlmProviders.OPENAI])
should_run, tools_dict = await logger.async_should_run_responses_agentic_loop(
response=_responses_output_with_web_search(),
model="gpt-4o",
messages=[{"role": "user", "content": "hi"}],
tools=[{"type": "function", "name": "get_weather"}],
stream=False,
custom_llm_provider="openai",
kwargs={},
)
assert should_run is False
assert tools_dict == {}
@pytest.mark.asyncio
async def test_responses_hook_not_triggered_for_disabled_provider():
"""Provider not in enabled_providers -> hook must not run."""
logger = WebSearchInterceptionLogger(enabled_providers=[LlmProviders.BEDROCK])
should_run, tools_dict = await logger.async_should_run_responses_agentic_loop(
response=_responses_output_with_web_search(),
model="gpt-4o",
messages=[{"role": "user", "content": "hi"}],
tools=[{"type": "function", "name": "litellm_web_search"}],
stream=False,
custom_llm_provider="openai",
kwargs={},
)
assert should_run is False
assert tools_dict == {}
@pytest.mark.asyncio
async def test_responses_hook_ignores_non_websearch_function_call():
"""A function_call for a different tool must not be intercepted."""
logger = WebSearchInterceptionLogger(enabled_providers=[LlmProviders.OPENAI])
response = SimpleNamespace(
output=[SimpleNamespace(type="function_call", name="get_weather", call_id="c1", arguments="{}")]
)
should_run, tools_dict = await logger.async_should_run_responses_agentic_loop(
response=response,
model="gpt-4o",
messages=[{"role": "user", "content": "hi"}],
tools=[{"type": "function", "name": "litellm_web_search"}],
stream=False,
custom_llm_provider="openai",
kwargs={},
)
assert should_run is False
assert tools_dict == {}
@pytest.mark.asyncio
async def test_responses_hook_ignores_bare_web_search_function_call():
logger = WebSearchInterceptionLogger(enabled_providers=[LlmProviders.OPENAI])
response = SimpleNamespace(
output=[SimpleNamespace(type="function_call", name="web_search", call_id="c1", arguments="{}")]
)
should_run, tools_dict = await logger.async_should_run_responses_agentic_loop(
response=response,
model="gpt-4o",
messages=[{"role": "user", "content": "hi"}],
tools=[{"type": "function", "name": "litellm_web_search"}],
stream=False,
custom_llm_provider="openai",
kwargs={},
)
assert should_run is False
assert tools_dict == {}
@pytest.mark.asyncio
async def test_surface_marker_routes_should_run_to_responses_branch():
"""async_should_run_agentic_loop must dispatch to the responses branch when the
surface marker says responses.
Without the marker the default anthropic branch runs and never detects the
Responses-format function_call, so interception silently no-ops on /v1/responses.
"""
logger = WebSearchInterceptionLogger(enabled_providers=[LlmProviders.OPENAI])
should_run, tools_dict = await logger.async_should_run_agentic_loop(
response=_responses_output_with_web_search(),
model="gpt-4o",
messages=[{"role": "user", "content": "What's the latest AI news?"}],
tools=[{"type": "function", "name": "litellm_web_search"}],
stream=False,
custom_llm_provider="openai",
kwargs={"_agentic_loop_api_surface": RESPONSES_AGENTIC_SURFACE},
)
assert should_run is True
assert tools_dict["response_format"] == "responses"
@pytest.mark.asyncio
async def test_default_branch_does_not_detect_responses_output():
"""Regression guard: the default (anthropic) branch must not detect a
Responses-format function_call, proving the responses branch is required.
"""
logger = WebSearchInterceptionLogger(enabled_providers=[LlmProviders.OPENAI])
should_run, tools_dict = await logger.async_should_run_agentic_loop(
response=_responses_output_with_web_search(),
model="gpt-4o",
messages=[{"role": "user", "content": "hi"}],
tools=[{"type": "function", "name": "litellm_web_search"}],
stream=False,
custom_llm_provider="openai",
kwargs={},
)
assert should_run is False
@pytest.mark.asyncio
async def test_build_responses_plan_produces_responses_input():
"""async_build_responses_agentic_loop_plan builds a Responses-format follow-up:
the user input followed by function_call + function_call_output items, with
the web search tool preserved and tool_choice stripped.
"""
logger = WebSearchInterceptionLogger(enabled_providers=[LlmProviders.OPENAI])
tools_dict = {
"tool_calls": [
{
"id": "fc_1",
"call_id": "fc_1",
"type": "function_call",
"name": "litellm_web_search",
"arguments": '{"query": "latest ai news"}',
"input": {"query": "latest ai news"},
}
],
"tool_type": "websearch",
"provider": "openai",
"response_format": "responses",
}
with patch.object(
logger,
"_execute_search",
new=AsyncMock(return_value=("OpenAI shipped a new model", None)),
):
plan = await logger.async_build_responses_agentic_loop_plan(
tools=tools_dict,
model="gpt-4o",
messages=[{"role": "user", "content": "What's the latest AI news?"}],
response=_responses_output_with_web_search(),
optional_params={
"tools": [{"type": "function", "name": "litellm_web_search"}],
"tool_choice": {"type": "function", "name": "litellm_web_search"},
},
logging_obj=MagicMock(),
stream=False,
kwargs={
"custom_llm_provider": "openai",
"_agentic_loop_api_surface": RESPONSES_AGENTIC_SURFACE,
},
)
assert plan.run_agentic_loop is True
patch_obj = plan.request_patch
assert patch_obj is not None
input_items = patch_obj.messages
assert input_items is not None
assert input_items[0] == {"role": "user", "content": "What's the latest AI news?"}
assert input_items[1] == {
"type": "function_call",
"call_id": "fc_1",
"name": "litellm_web_search",
"arguments": '{"query": "latest ai news"}',
}
assert input_items[2] == {
"type": "function_call_output",
"call_id": "fc_1",
"output": "OpenAI shipped a new model",
}
assert patch_obj.tools == [{"type": "function", "name": "litellm_web_search"}]
assert "tool_choice" not in patch_obj.optional_params
assert "_agentic_loop_api_surface" not in patch_obj.kwargs
assert patch_obj.model == "openai/gpt-4o"
_WEB_SEARCH_FUNCTION_CALL: Final = {
"tool_calls": [
{
"id": "fc_1",
"call_id": "fc_1",
"type": "function_call",
"name": "litellm_web_search",
"arguments": '{"query": "latest ai news"}',
"input": {"query": "latest ai news"},
}
],
"tool_type": "websearch",
"response_format": "responses",
}
async def _responses_followup_model(model: str, custom_llm_provider: str, logging_obj: Logging | None) -> str | None:
logger: Final = WebSearchInterceptionLogger()
plan: Final = await logger.async_build_responses_agentic_loop_plan(
tools={**_WEB_SEARCH_FUNCTION_CALL, "provider": custom_llm_provider},
model=model,
messages=[{"role": "user", "content": "What's the latest AI news?"}],
response=_responses_output_with_web_search(),
optional_params={"tools": [{"type": "function", "name": "litellm_web_search"}]},
logging_obj=logging_obj,
stream=False,
kwargs={
"custom_llm_provider": custom_llm_provider,
"_agentic_loop_api_surface": RESPONSES_AGENTIC_SURFACE,
},
)
assert plan.request_patch is not None
return plan.request_patch.model
@pytest.mark.asyncio
@pytest.mark.usefixtures("perplexity_search")
async def test_build_responses_plan_keeps_the_provider_on_a_sub_path_model() -> None:
"""#38829 on the Responses surface: a provider-stripped model whose remainder still holds a
slash was left unqualified, so the follow-up could not resolve a provider."""
followup_model: Final = await _responses_followup_model("mantle/anthropic.claude-sonnet-5", "bedrock", None)
assert followup_model == "bedrock/mantle/anthropic.claude-sonnet-5"
@pytest.mark.asyncio
@pytest.mark.usefixtures("perplexity_search")
async def test_responses_followup_reuses_the_model_the_caller_requested() -> None:
"""An OpenRouter model whose own id starts with "openrouter/" reaches the handler as
"openrouter/free", which re-qualifying alone cannot tell apart from a request for model "free"."""
requested_model: Final = "openrouter/openrouter/free"
logging_obj: Final = Logging(
model=requested_model,
messages=[],
stream=False,
call_type=CallTypes.responses.value,
start_time=datetime.datetime(2026, 1, 1, tzinfo=datetime.timezone.utc),
litellm_call_id="call-responses-followup",
function_id="fn-responses-followup",
)
litellm.responses(
model=requested_model,
input="What's the latest AI news?",
mock_response="searching",
litellm_logging_obj=logging_obj,
)
followup_model: Final = await _responses_followup_model("openrouter/free", "openrouter", logging_obj)
assert followup_model == requested_model
@pytest.mark.asyncio
@pytest.mark.usefixtures("perplexity_search")
async def test_responses_followup_keeps_the_caller_model_across_the_chat_completions_bridge() -> None:
"""A Responses request bridged to chat completions re-enters completion() with the stripped model."""
requested_model: Final = "openrouter/openrouter/free"
logging_obj: Final = Logging(
model=requested_model,
messages=[],
stream=False,
call_type=CallTypes.responses.value,
start_time=datetime.datetime(2026, 1, 1, tzinfo=datetime.timezone.utc),
litellm_call_id="call-bridged-followup",
function_id="fn-bridged-followup",
)
litellm.responses(
model=requested_model,
input="What's the latest AI news?",
mock_response="searching",
litellm_logging_obj=logging_obj,
)
litellm.completion(
model="openrouter/free",
custom_llm_provider="openrouter",
messages=[{"role": "user", "content": "What's the latest AI news?"}],
mock_response="searching",
litellm_logging_obj=logging_obj,
_skip_responses_api_bridge=True,
)
followup_model: Final = await _responses_followup_model("openrouter/free", "openrouter", logging_obj)
assert followup_model == requested_model
@pytest.mark.asyncio
@pytest.mark.usefixtures("perplexity_search")
@pytest.mark.parametrize(
("tool_choice", "followup_tool_choice"),
[
(
{"type": "allowed_tools", "mode": "required", "tools": [{"type": "function", "name": "litellm_web_search"}]},
{"type": "allowed_tools", "mode": "auto", "tools": [{"type": "function", "name": "litellm_web_search"}]},
),
({"type": "function", "name": "litellm_web_search"}, None),
("required", None),
],
)
async def test_responses_followup_keeps_only_an_allowed_tools_choice_without_forcing_another_call(
tool_choice: object, followup_tool_choice: object
) -> None:
plan: Final = await WebSearchInterceptionLogger().async_build_responses_agentic_loop_plan(
tools={**_WEB_SEARCH_FUNCTION_CALL, "provider": "azure"},
model="gpt-5.4-mini",
messages=[{"role": "user", "content": "What's the latest AI news?"}],
response=_responses_output_with_web_search(),
optional_params={"tools": [{"type": "function", "name": "litellm_web_search"}], "tool_choice": tool_choice},
logging_obj=None,
stream=False,
kwargs={"custom_llm_provider": "azure", "_agentic_loop_api_surface": RESPONSES_AGENTIC_SURFACE},
)
assert plan.request_patch is not None
assert plan.request_patch.optional_params.get("tool_choice") == followup_tool_choice
@pytest.mark.asyncio
async def test_deployment_hook_converts_native_responses_web_search_tool():
"""async_pre_call_deployment_hook converts a native Responses web_search tool
into the flat litellm_web_search function tool (Responses shape, not the
nested Chat Completions {"function": {...}} wrapper).
"""
logger = WebSearchInterceptionLogger(enabled_providers=[LlmProviders.OPENAI])
result = await logger.async_pre_call_deployment_hook(
kwargs={
"model": "gpt-4o",
"custom_llm_provider": "openai",
"tools": [{"type": "web_search"}],
},
call_type=CallTypes.aresponses,
)
assert result is not None
converted_tools = result["tools"]
assert len(converted_tools) == 1
tool = converted_tools[0]
assert tool["type"] == "function"
assert tool["name"] == "litellm_web_search"
assert "function" not in tool
assert tool["parameters"]["required"] == ["query"]
@pytest.mark.asyncio
@pytest.mark.parametrize(
("call_type", "tool_choice"),
[
(CallTypes.aresponses, {"type": "allowed_tools", "mode": "auto", "tools": [{"type": "web_search"}]}),
(CallTypes.acompletion, {"type": "allowed_tools", "mode": "auto", "tools": [{"type": "web_search"}]}),
(
CallTypes.acompletion,
{"type": "allowed_tools", "allowed_tools": {"mode": "required", "tools": [{"type": "web_search"}]}},
),
],
)
async def test_deployment_hook_lets_an_allowed_tools_choice_listing_web_search_allow_the_search(
call_type: CallTypes, tool_choice: dict[str, object]
):
logger: Final = WebSearchInterceptionLogger(enabled_providers=[LlmProviders.OPENAI])
result: Final = await logger.async_pre_call_deployment_hook(
kwargs={
"model": "gpt-4o",
"custom_llm_provider": "openai",
"tools": [{"type": "web_search"}, {"type": "function", "name": "get_weather"}],
"tool_choice": tool_choice,
},
call_type=call_type,
)
assert result is not None
assert tool_calls_the_choice_excludes(result["tool_choice"], ("litellm_web_search", "get_weather")) == (
"get_weather",
)
@pytest.mark.asyncio
async def test_deployment_hook_responses_returns_none_without_web_search():
"""No web search tool in a responses request -> deployment hook makes no change."""
logger = WebSearchInterceptionLogger(enabled_providers=[LlmProviders.OPENAI])
result = await logger.async_pre_call_deployment_hook(
kwargs={
"model": "gpt-4o",
"custom_llm_provider": "openai",
"tools": [{"type": "function", "name": "get_weather"}],
},
call_type=CallTypes.aresponses,
)
assert result is None
@pytest.mark.asyncio
async def test_deployment_hook_responses_converts_stream_to_non_stream():
"""Streaming responses requests are converted to non-streaming so the agentic
loop can run, and flagged for re-wrapping afterwards.
"""
logger = WebSearchInterceptionLogger(enabled_providers=[LlmProviders.OPENAI])
result = await logger.async_pre_call_deployment_hook(
kwargs={
"model": "gpt-4o",
"custom_llm_provider": "openai",
"tools": [{"type": "web_search_preview"}],
"stream": True,
},
call_type=CallTypes.aresponses,
)
assert result is not None
assert result["stream"] is False
assert result["_websearch_interception_converted_stream"] is True
WEATHER_RESPONSES_TOOL = {
"type": "function",
"name": "get_weather",
"description": "Get the current weather for a city",
"parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
}
def _output_text(response) -> list[str]:
messages = [item for item in response.model_dump()["output"] if item["type"] == "message"]
return [part["text"] for message in messages for part in message["content"]]
@pytest.mark.asyncio
@pytest.mark.parametrize(
("feature_max_loops", "deployment_max_loops", "searches"),
[(None, 4, 4), (4, None, 3), (1, None, 3)],
ids=["deployment cap above the default", "feature cap above the default", "feature cap below the default"],
)
async def test_responses_turn_stops_at_the_deployment_cap_with_the_model_answer(
feature_max_loops: int | None,
deployment_max_loops: int | None,
searches: int,
monkeypatch: pytest.MonkeyPatch,
openai_responses_model: respx.Route,
perplexity_search: respx.Route,
):
monkeypatch.setattr(
litellm,
"callbacks",
[WebSearchInterceptionLogger(enabled_providers=["openai"], max_agentic_loops=feature_max_loops)],
)
response = await litellm.aresponses(
model="openai/gpt-5.6",
input="What's the latest AI news?",
tools=[get_litellm_web_search_tool_responses(), WEATHER_RESPONSES_TOOL],
tool_choice="auto",
api_key="test-openai-key-capped-responses",
max_agentic_loops=deployment_max_loops,
)
bodies = request_bodies(openai_responses_model)
assert _output_text(response) == [FINAL_ANSWER]
assert [offered_tool_names(body) for body in bodies] == [
*[["litellm_web_search", "get_weather"]] * (searches + 1),
["get_weather"],
]
assert [body.get("tool_choice") for body in bodies] == ["auto"] * (searches + 2)
assert perplexity_search.call_count == searches
@pytest.mark.asyncio
async def test_responses_last_follow_up_blocks_tool_calls_when_search_was_the_only_tool(
monkeypatch, openai_responses_model, perplexity_search
):
monkeypatch.setattr(
litellm, "callbacks", [WebSearchInterceptionLogger(enabled_providers=["openai"])]
)
response = await litellm.aresponses(
max_agentic_loops=1,
model="openai/gpt-5.6",
input="What's the latest AI news?",
tools=[get_litellm_web_search_tool_responses()],
tool_choice="required",
api_key="test-openai-key-search-only-responses",
)
last_request = request_bodies(openai_responses_model)[-1]
assert _output_text(response) == [FINAL_ANSWER]
assert "tools" not in last_request
assert last_request["tool_choice"] == "none"
def _responses_function_tool(name: str) -> dict:
return {"type": "function", "name": name, "parameters": {"type": "object", "properties": {}}}
def _responses_allowed_tools(*names: str) -> dict:
return {"type": "allowed_tools", "mode": "auto", "tools": [{"type": "function", "name": name} for name in names]}
@pytest.mark.asyncio
@pytest.mark.parametrize(
("allowed_client_tools", "last_call_tools", "last_call_tool_choice"),
[
((), [], "none"),
(("get_weather",), ["get_weather", "delete_records"], _responses_allowed_tools("get_weather")),
],
ids=["only search allowed", "a client tool allowed"],
)
async def test_responses_last_follow_up_keeps_the_allowed_tools_limit(
allowed_client_tools, last_call_tools, last_call_tool_choice, monkeypatch, openai_responses_model, perplexity_search
):
monkeypatch.setattr(
litellm, "callbacks", [WebSearchInterceptionLogger(enabled_providers=["openai"])]
)
response = await litellm.aresponses(
max_agentic_loops=1,
model="openai/gpt-5.6",
input="What's the latest AI news?",
tools=[
get_litellm_web_search_tool_responses(),
_responses_function_tool("get_weather"),
_responses_function_tool("delete_records"),
],
tool_choice=_responses_allowed_tools("litellm_web_search", *allowed_client_tools),
api_key="test-openai-key-allowed-tools-responses",
)
last_request = request_bodies(openai_responses_model)[-1]
assert _output_text(response) == [FINAL_ANSWER]
assert offered_tool_names(last_request) == last_call_tools
assert last_request["tool_choice"] == last_call_tool_choice