litellm/tests/unit/integrations/websearch_interception/test_websearch_responses.py
Mateo Wang 9fb29c7e38
fix(tool_choice): accept the Responses API's flat allowed_tools layout on chat completions (#50467)
* fix(tool_choice): accept the Responses API's flat allowed_tools layout on chat completions

An allowed_tools tool_choice in the flat Responses layout ({"type": "allowed_tools", "mode": ..., "tools": [...]})
answered 400 on litellm.completion, acompletion, Router and the proxy's chat and /v1/responses-to-chat routes. One
parser now reads both layouts into the nested Chat layout, and the existing Responses bridge flattens it back for
/v1/responses, so either layout reaches OpenAI in the shape each endpoint expects

* fix(tool_choice): drop an allowed_tools choice under drop_params and refuse conflicting flat entries

An allowed_tools tool_choice a provider can't enforce, or a malformed one, now drops under drop_params and answers 400 without it, the same rule LiteLLM uses for other unsupported values. That covers providers outside OpenAI and Azure, malformed choices on every provider, and Azure api versions older than 2023-12-01

A flat allowed_tools entry that carries both name and a nested function or custom key answers 400, since the two names can disagree, matching what flattening already refuses

* fix(tool-choice): keep the 400 when LiteLLM runs the tools, report auto after a drop

Under drop_params an allowed_tools choice a provider can't enforce was dropped, so on MCP gateway tools and in
run_tool_loop and arun_tool_loop LiteLLM could run a tool the allow list excluded. Those paths now keep the 400 they
answered before the flat layout was accepted, and a malformed choice stays a 400 on MCP gateway tools.

/v1/responses served through chat echoed a choice it had dropped, on sync, async and streamed responses. It now
reports auto, and a choice the provider received is still echoed as sent.

* fix(tool-choice): refuse an excluded tool right before LiteLLM runs it

Checking the provider up front missed a model alias, an old Azure api_version,
a litellm_proxy hop, and SDK fallbacks. The tool loop and the MCP gateway now
check the allowed_tools list right before they run a tool call, so an excluded
call answers 400 and never runs.

Under drop_params the choice now drops only when the caller runs every tool,
so a provider-run MCP server or built-in keeps the 400. The Azure checks read
the request's api_version, which also fixes the /v1/responses echo there.

* fix(tool-choice): drop the choice under drop_params and hand an excluded MCP call back unrun

The drop now applies to every provider that cannot take an allowed_tools
tool_choice, whatever the request's tools hold. LiteLLM never runs a call the
choice excludes: on MCP paths the whole round goes back to the caller in a 200,
the same shape as require_approval, and the tool loop keeps its 400 because it
only returns final content. A malformed choice stays a 400 before any request
on the tool loop and on chat with MCP gateway tools.

* fix(tool-choice): refuse an allowed_tools entry whose name is not a string

An mcp or other non-function entry with a list or dict name passed the
parser and crashed when the allow list was hashed. The parser now treats
it as malformed on both layouts, so it answers the same 400 as an empty
allow list, or drops under drop_params.

* fix(tool-choice): honor server-level and null-name mcp entries and stop hooks running excluded calls

* fix(tool-choice): match named mcp entries by server label and let built-in entries allow their interception call

* fix(tool-choice): leave a malformed allowed_tools choice unrewritten in the interception hooks

* fix(tool-choice): resolve mcp entries like the gateway and keep the choice on every hook path

Under drop_params a malformed allowed_tools choice now acts as if it was never sent, and only a choice that parses is stored and enforced. Without drop_params it answers 400 before any provider request, on /v1/responses with gateway tools before MCP listing

An mcp entry resolves its label the way the gateway picks servers to list (server name in any case, alias, access group, toolset), and a named entry matches the tool's own name or the gateway's prefixed name. The gateway rewrites mcp entries into function entries in the caller's layout and sends "none" when nothing is left

The web search follow-up keeps an allowed_tools choice, compression's litellm_content_retrieve is never excluded and joins the provider-facing choice, and the native /v1/responses hook loop applies the exclusion check and stores the choice

* fix(allowed_tools): stop web search and code interpreter follow-ups forcing another call

A kept allowed_tools choice now goes to the follow-up in mode auto, so a
required choice no longer loops to the agentic loop limit. The MCP label
scope dataclass uses a default_factory so the module imports on Python 3.11

* fix(allowed_tools): stop the Responses web search follow-up forcing another call

The Responses-shaped follow-up after a web search left tool_choice out of its patch, so the caller's required choice went out again through the chat to Responses bridge and looped to the loop limit. It now carries a kept allowed_tools choice in mode auto, like the chat follow-up

* fix(mcp): scope each MCP entry to its own allowed_tools and keep the allowlist on follow-ups

A label now covers only the tools its own allowed_tools lists, so a second label on the same server no longer widens it. Responses MCP follow-ups, streamed or not, keep an allowed_tools choice in auto mode instead of dropping it. The new Responses tests fake only the upstream MCP listing, so LiteLLM's own discovery runs

* fix(mcp): match an entry's allowed_tools against the tool name the gateway lists

A server with a display name override lists the display name, and the listing
filter matches allowed_tools against it, but the label scope only checked the
original name, so no spelling worked. The scope now also accepts the listed
name and its unprefixed part, like the listing filter. Tests now cover the
whole gateway and toolset entries and a display-named tool.

* fix(mcp): match an entry's allowed_tools only against a server's own prefix, not the first hyphen

* fix(mcp): match a tool no server resolves only by its exact listed name in an entry's allowed_tools

* fix(mcp): refuse a tool whose display name only looks like an allowed name, and let the chat follow-up answer

An MCP entry's allowed_tools now matches a tool only by its exact listed name or a spelling routing
accepts for its real name, so a display name that carries the server's own prefix no longer passes for
another tool. The chat MCP follow-up keeps an allowed_tools choice in auto mode, so the model can answer
with text after the tool ran.

* fix(mcp): match a toolset label's tools by exact native name

A toolset label served any tool whose name a routing spelling of a granted name matched, so a toolset granting the literal name "server-tool" also served the real tool "tool" that only another toolset grants. It now serves a tool only when the toolset grants its exact native name, the same check tool_is_granted uses when the gateway lists tools
2026-11-10 13:04:06 -08:00

494 lines
18 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 litellm
from litellm.integrations.websearch_interception.handler import (
WebSearchInterceptionLogger,
)
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
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