Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix(responses): map Anthropic tool search to OpenAI server tool search (#46441)

Mateo Wangd6e6c6f26c43
diff --git a/litellm/completion_extras/litellm_responses_transformation/transformation.py b/litellm/completion_extras/litellm_responses_transformation/transformation.py
index 996818b6fa0..979caa29832 100644
--- a/litellm/completion_extras/litellm_responses_transformation/transformation.py
+++ b/litellm/completion_extras/litellm_responses_transformation/transformation.py
@@ -35,6 +35,7 @@ from litellm.llms.base_llm.base_model_iterator import BaseModelResponseIterator
from litellm.llms.base_llm.bridges.completion_transformation import (
CompletionTransformationBridge,
)
+from litellm.responses.litellm_completion_transformation.tool_search import is_anthropic_tool_search_chat_tool
from litellm.responses.sse_output_recovery import (
parse_sse_json_chunk,
record_output_item_chunk,
@@ -1646,7 +1647,7 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge):
"client"
if any(tool.get("type") == "tool_search" and tool.get("execution") == "client" for tool in tools)
else "hosted"
- if any(tool.get("type") == "tool_search" for tool in tools)
+ if any(tool.get("type") == "tool_search" or is_anthropic_tool_search_chat_tool(tool) for tool in tools)
else "absent"
)
responses_tools: Final[list[ALL_RESPONSES_API_TOOL_PARAMS]] = []
diff --git a/litellm/llms/openai/responses/transformation.py b/litellm/llms/openai/responses/transformation.py
index 7c159c6a6a2..b83ad964425 100644
--- a/litellm/llms/openai/responses/transformation.py
+++ b/litellm/llms/openai/responses/transformation.py
@@ -10,8 +10,8 @@ from typing_extensions import ReadOnly, TypedDict
import litellm
from litellm._logging import verbose_logger
-from litellm.integrations.anthropic_cache_control_hook import AnthropicCacheControlHook
-from litellm.litellm_core_utils.core_helpers import process_response_headers
+from litellm.integrations.anthropic_cache_control_hook import AnthropicCacheControlHook, targets_openai_api
+from litellm.litellm_core_utils.core_helpers import normalize_drop_params, process_response_headers
from litellm.litellm_core_utils.get_model_cost_map import GetModelCostMap
from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import (
safe_convert_created_field,
@@ -28,6 +28,13 @@ from litellm.llms.base_llm.responses.transformation import BaseResponsesAPIConfi
from litellm.llms.openai.chat.gpt_5_transformation import is_gpt_reasoning_series_name
from litellm.responses.litellm_completion_transformation.custom_tools import TOOL_CALL_ITEM_ID_PREFIX_BY_TYPE
from litellm.responses.litellm_completion_transformation.reasoning_items import is_litellm_minted_reasoning_item
+from litellm.responses.litellm_completion_transformation.tool_search import (
+ input_without_unanswered_anthropic_tool_search_calls,
+ is_anthropic_tool_search_chat_tool,
+ is_openai_tool_search_tool,
+ tools_with_anthropic_tool_search_mapped,
+ tools_without_anthropic_tool_search,
+)
from litellm.secret_managers.main import get_secret_str
from litellm.types.llms.base import LiteLLMBaseModel
from litellm.types.llms.openai import *
@@ -69,6 +76,64 @@ class _DeploymentHost(BaseModel):
base_url: object = None
+class _DropParamsSetting(BaseModel):
+ model_config = ConfigDict(frozen=True, extra="ignore", from_attributes=True)
+
+ drop_params: object = None
+
+
+def _drops_params(litellm_params: GenericLiteLLMParams) -> bool:
+ setting: Final = _DropParamsSetting.model_validate(litellm_params)
+ return litellm.drop_params is True or normalize_drop_params(setting.drop_params) is True
+
+
+class _ToolDeferral(BaseModel):
+ model_config = ConfigDict(frozen=True, extra="ignore")
+
+ type: str = ""
+ defer_loading: object = None
+ tools: tuple[Mapping[str, object], ...] = ()
+
+ @property
+ def is_namespace(self) -> bool:
+ return self.type == "namespace"
+
+ @property
+ def defers(self) -> bool:
+ members_defer: Final = self.is_namespace and any(member.get("defer_loading") is True for member in self.tools)
+ return self.defer_loading is True or members_defer
+
+
+def _defer_loading_removed(fields: Mapping[str, object]) -> Mapping[str, object]:
+ return {key: value for key, value in fields.items() if key != "defer_loading"}
+
+
+def _tool_deferral(tool: object) -> _ToolDeferral:
+ try:
+ return _ToolDeferral.model_validate(tool)
+ except ValidationError:
+ return _ToolDeferral()
+
+
+def _runs_tool_search(model: str, tools: Sequence[ALL_RESPONSES_API_TOOL_PARAMS]) -> bool:
+ return any(_tool_deferral(tool).defers for tool in tools) and litellm.supports_tool_search(
+ model=model, custom_llm_provider=LlmProviders.OPENAI.value
+ )
+
+
+def _without_defer_loading(tool: ALL_RESPONSES_API_TOOL_PARAMS) -> ALL_RESPONSES_API_TOOL_PARAMS:
+ deferral: Final = _tool_deferral(tool)
+ if not deferral.defers:
+ return tool
+ undeferred: Final = _defer_loading_removed(tool)
+ members: Final = (
+ {"tools": [_defer_loading_removed(member) for member in deferral.tools]} if deferral.is_namespace else {}
+ )
+ return cast( # cast-ok: a TypedDict minus its deferral keys has no typed construction, and nothing else changes
+ ALL_RESPONSES_API_TOOL_PARAMS, {**undeferred, **members}
+ )
+
+
def _provider_name(provider: LlmProviders | str) -> str:
"""Configs generated from a provider JSON file return the slug as a plain str."""
return provider.value if isinstance(provider, LlmProviders) else provider
@@ -406,8 +471,21 @@ class OpenAIResponsesAPIConfig(BaseResponsesAPIConfig):
)
else validated_input
)
+ maps_anthropic_tool_search: Final = self._targets_openai_api(litellm_params) and any(
+ is_anthropic_tool_search_chat_tool(tool) for tool in tools or ()
+ )
+ mapped_tools: Final = (
+ self._tools_for_openai_tool_search(model=model, tools=tools, litellm_params=litellm_params)
+ if maps_anthropic_tool_search
+ else tools
+ )
+ replayable_input: Final = (
+ input_without_unanswered_anthropic_tool_search_calls(marked_input)
+ if maps_anthropic_tool_search
+ else marked_input
+ )
stripped_input, stripped_tools = self.remove_cache_control_flag_from_input_and_tools(
- model=model, input=marked_input, tools=tools
+ model=model, input=replayable_input, tools=mapped_tools
)
object_schema_tools: Final = self._tools_with_object_parameters(model=model, tools=stripped_tools)
sanitized_tools: Final = self._sanitized_tool_schemas_for_openai(
@@ -415,6 +493,26 @@ class OpenAIResponsesAPIConfig(BaseResponsesAPIConfig):
)
return self._drop_foreign_tool_call_item_ids(stripped_input), sanitized_tools
+ def _targets_openai_api(self, litellm_params: GenericLiteLLMParams) -> bool:
+ host: Final = _DeploymentHost.model_validate(litellm_params)
+ return self.custom_llm_provider == LlmProviders.OPENAI and targets_openai_api(host.api_base or host.base_url)
+
+ @staticmethod
+ def _tools_for_openai_tool_search(
+ model: str, tools: Sequence[ALL_RESPONSES_API_TOOL_PARAMS] | None, litellm_params: GenericLiteLLMParams
+ ) -> Sequence[ALL_RESPONSES_API_TOOL_PARAMS] | None:
+ if tools is None or not any(is_anthropic_tool_search_chat_tool(tool) for tool in tools):
+ return tools
+ callers_own_search: Final = any(is_openai_tool_search_tool(tool) for tool in tools)
+ if callers_own_search or not _drops_params(litellm_params) or _runs_tool_search(model, tools):
+ return tools_with_anthropic_tool_search_mapped(tools)
+ verbose_logger.warning(
+ "Dropping tool search under drop_params: OpenAI model '%s' cannot run it or no tool is deferred, so every "
+ "tool loads up front.",
+ model,
+ )
+ return tuple(_without_defer_loading(tool) for tool in tools_without_anthropic_tool_search(tools))
+
def _reads_prompt_cache_breakpoints(
self, model: str, litellm_params: GenericLiteLLMParams, prompt_cache_options: object
) -> bool:
diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.json
index afb3474c5b0..5621b51768b 100644
--- a/litellm/model_prices_and_context_window_backup.json
+++ b/litellm/model_prices_and_context_window_backup.json
@@ -35679,6 +35679,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_none_reasoning_effort": true,
@@ -35796,6 +35797,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_none_reasoning_effort": true,
@@ -35972,6 +35974,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_xhigh_reasoning_effort": true
@@ -36048,6 +36051,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_xhigh_reasoning_effort": true
@@ -36133,6 +36137,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_xhigh_reasoning_effort": true
@@ -36206,6 +36211,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_xhigh_reasoning_effort": true
@@ -36281,6 +36287,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_xhigh_reasoning_effort": true
@@ -36355,6 +36362,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_xhigh_reasoning_effort": true
@@ -36429,6 +36437,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_xhigh_reasoning_effort": true
@@ -36714,6 +36723,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_none_reasoning_effort": true,
@@ -36776,6 +36786,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_none_reasoning_effort": true,
@@ -36830,6 +36841,7 @@
"supports_response_schema": false,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_none_reasoning_effort": false,
@@ -36881,6 +36893,7 @@
"supports_response_schema": false,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_none_reasoning_effort": false,
@@ -36935,6 +36948,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_none_reasoning_effort": true,
"default_reasoning_effort": "none",
@@ -36992,6 +37006,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_none_reasoning_effort": true,
"default_reasoning_effort": "none",
@@ -37045,6 +37060,7 @@
"supports_response_schema": false,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_none_reasoning_effort": false,
@@ -37097,6 +37113,7 @@
"supports_response_schema": false,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_none_reasoning_effort": false,
@@ -37152,6 +37169,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_none_reasoning_effort": true,
@@ -37206,6 +37224,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_none_reasoning_effort": true,
@@ -37559,6 +37578,7 @@
"supports_response_schema": true,
"supports_system_messages": false,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_none_reasoning_effort": false,
@@ -72272,6 +72292,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_xhigh_reasoning_effort": true
diff --git a/litellm/responses/litellm_completion_transformation/tool_search.py b/litellm/responses/litellm_completion_transformation/tool_search.py
index 904aa86f841..0a94acdd461 100644
--- a/litellm/responses/litellm_completion_transformation/tool_search.py
+++ b/litellm/responses/litellm_completion_transformation/tool_search.py
@@ -6,6 +6,7 @@ from pydantic import ConfigDict, TypeAdapter, ValidationError
from litellm.litellm_core_utils.prompt_templates.mid_conversation_system import is_anthropic_tool_search_use
from litellm.types.llms.anthropic import ANTHROPIC_TOOL_SEARCH_TOOL_TYPES, AnthropicToolSearchToolRegex
from litellm.types.llms.base import LiteLLMBaseModel
+from litellm.types.llms.openai import ALL_RESPONSES_API_TOOL_PARAMS, OpenAIToolSearchToolParam, ResponseInputParam
from litellm.types.responses.main import OutputToolSearchCall
from litellm.types.utils import LlmProviders, Message
@@ -24,12 +25,16 @@ __all__ = [
"chat_route_rejects_unanswered_tool_calls",
"has_server_tool_search",
"holds_tool_search_use",
+ "input_without_unanswered_anthropic_tool_search_calls",
"is_anthropic_tool_search_chat_tool",
"is_anthropic_tool_search_use",
+ "is_openai_tool_search_tool",
"is_server_tool_search_tool",
"provider_builds_anthropic_request",
"runs_tool_search_on_the_server",
"tool_search_call_ids",
+ "tools_with_anthropic_tool_search_mapped",
+ "tools_without_anthropic_tool_search",
"unanswered_tool_search_call_ids",
"without_tool_search_calls",
"without_tool_search_uses",
@@ -74,8 +79,84 @@ def anthropic_tool_search_chat_tool() -> AnthropicToolSearchToolRegex:
return AnthropicToolSearchToolRegex(type=ANTHROPIC_TOOL_SEARCH_TOOL_TYPE, name=ANTHROPIC_TOOL_SEARCH_TOOL_NAME)
-def is_anthropic_tool_search_chat_tool(tool: Mapping[str, object]) -> bool:
- return tool.get("type") in ANTHROPIC_TOOL_SEARCH_TOOL_TYPES
+def _tool_type(tool: object) -> str:
+ try:
+ return _ToolSearchFields.model_validate(tool).type
+ except ValidationError:
+ return ""
+
+
+def is_anthropic_tool_search_chat_tool(tool: object) -> bool:
+ tool_type: Final = _tool_type(tool)
+ return tool_type in ANTHROPIC_TOOL_SEARCH_TOOL_TYPES
+
+
+def is_openai_tool_search_tool(tool: object) -> bool:
+ return _tool_type(tool) == "tool_search"
+
+
+def tools_with_anthropic_tool_search_mapped(
+ tools: Sequence[ALL_RESPONSES_API_TOOL_PARAMS] | None,
+) -> Sequence[ALL_RESPONSES_API_TOOL_PARAMS] | None:
+ if tools is None or not any(is_anthropic_tool_search_chat_tool(tool) for tool in tools):
+ return tools
+ if any(is_openai_tool_search_tool(tool) for tool in tools):
+ return tools_without_anthropic_tool_search(tools)
+ first_search_index: Final = next(
+ index for index, tool in enumerate(tools) if is_anthropic_tool_search_chat_tool(tool)
+ )
+ server_tool_search: Final[OpenAIToolSearchToolParam] = {"type": "tool_search", "execution": "server"}
+ return tuple(
+ server_tool_search if index == first_search_index else tool
+ for index, tool in enumerate(tools)
+ if index == first_search_index or not is_anthropic_tool_search_chat_tool(tool)
+ )
+
+
+def tools_without_anthropic_tool_search(
+ tools: Sequence[ALL_RESPONSES_API_TOOL_PARAMS],
+) -> tuple[ALL_RESPONSES_API_TOOL_PARAMS, ...]:
+ return tuple(tool for tool in tools if not is_anthropic_tool_search_chat_tool(tool))
+
+
+class _FunctionCallItemFields(LiteLLMBaseModel):
+ model_config = ConfigDict(frozen=True)
+
+ type: str = ""
+ call_id: str = ""
+ name: str = ""
+
+
+def _function_call_fields(item: object) -> _FunctionCallItemFields:
+ try:
+ return _FunctionCallItemFields.model_validate(item)
+ except ValidationError:
+ return _FunctionCallItemFields()
+
+
+def _is_unanswered_anthropic_tool_search_call(fields: _FunctionCallItemFields, answered_call_ids: Set[str]) -> bool:
+ return (
+ fields.type == "function_call"
+ and is_anthropic_tool_search_use(fields.call_id, fields.name)
+ and fields.call_id not in answered_call_ids
+ )
+
+
+def input_without_unanswered_anthropic_tool_search_calls(
+ input: str | ResponseInputParam,
+) -> str | ResponseInputParam:
+ if isinstance(input, str):
+ return input
+ item_fields: Final = tuple(map(_function_call_fields, input))
+ answered_call_ids: Final = frozenset(
+ fields.call_id for fields in item_fields if fields.type == "function_call_output"
+ )
+ kept: Final = [
+ item
+ for item, fields in zip(input, item_fields)
+ if not _is_unanswered_anthropic_tool_search_call(fields, answered_call_ids)
+ ]
+ return input if len(kept) == len(input) else kept
def provider_builds_anthropic_request(model: str, custom_llm_provider: str | None) -> bool:
diff --git a/litellm/types/llms/openai.py b/litellm/types/llms/openai.py
index 98448ee8b32..9784f0b1b6b 100644
--- a/litellm/types/llms/openai.py
+++ b/litellm/types/llms/openai.py
@@ -1283,7 +1283,12 @@ class ShellToolParam(TypedDict, total=False):
"""Environment config: ``type`` (e.g. ``\"container_auto\"``, ``\"container_reference\"``, ``\"local\"``), optional ``container_id``, ``network_policy``, ``domain_secrets``, ``skills``."""
-ALL_RESPONSES_API_TOOL_PARAMS = ToolParam | ComputerToolParam | ShellToolParam
+class OpenAIToolSearchToolParam(TypedDict, total=False):
+ type: Required[ReadOnly[Literal["tool_search"]]]
+ execution: ReadOnly[str]
+
+
+ALL_RESPONSES_API_TOOL_PARAMS = ToolParam | ComputerToolParam | ShellToolParam | OpenAIToolSearchToolParam
class PromptObject(TypedDict, total=False):
diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.json
index afb3474c5b0..5621b51768b 100644
--- a/model_prices_and_context_window.json
+++ b/model_prices_and_context_window.json
@@ -35679,6 +35679,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_none_reasoning_effort": true,
@@ -35796,6 +35797,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_none_reasoning_effort": true,
@@ -35972,6 +35974,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_xhigh_reasoning_effort": true
@@ -36048,6 +36051,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_xhigh_reasoning_effort": true
@@ -36133,6 +36137,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_xhigh_reasoning_effort": true
@@ -36206,6 +36211,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_xhigh_reasoning_effort": true
@@ -36281,6 +36287,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_xhigh_reasoning_effort": true
@@ -36355,6 +36362,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_xhigh_reasoning_effort": true
@@ -36429,6 +36437,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_xhigh_reasoning_effort": true
@@ -36714,6 +36723,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_none_reasoning_effort": true,
@@ -36776,6 +36786,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_none_reasoning_effort": true,
@@ -36830,6 +36841,7 @@
"supports_response_schema": false,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_none_reasoning_effort": false,
@@ -36881,6 +36893,7 @@
"supports_response_schema": false,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_none_reasoning_effort": false,
@@ -36935,6 +36948,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_none_reasoning_effort": true,
"default_reasoning_effort": "none",
@@ -36992,6 +37006,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_none_reasoning_effort": true,
"default_reasoning_effort": "none",
@@ -37045,6 +37060,7 @@
"supports_response_schema": false,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_none_reasoning_effort": false,
@@ -37097,6 +37113,7 @@
"supports_response_schema": false,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_none_reasoning_effort": false,
@@ -37152,6 +37169,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_none_reasoning_effort": true,
@@ -37206,6 +37224,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_none_reasoning_effort": true,
@@ -37559,6 +37578,7 @@
"supports_response_schema": true,
"supports_system_messages": false,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_none_reasoning_effort": false,
@@ -72272,6 +72292,7 @@
"supports_response_schema": true,
"supports_system_messages": true,
"supports_tool_choice": true,
+ "supports_tool_search": true,
"supports_vision": true,
"supports_web_search": true,
"supports_xhigh_reasoning_effort": true
diff --git a/tests/integration/providers/test_openai_responses_tool_search_wire.py b/tests/integration/providers/test_openai_responses_tool_search_wire.py
new file mode 100644
index 00000000000..0e5c539e3f9
--- /dev/null
+++ b/tests/integration/providers/test_openai_responses_tool_search_wire.py
@@ -0,0 +1,829 @@
+import asyncio
+import itertools
+import json
+import threading
+import uuid
+from collections.abc import Callable, Generator, Iterator, Mapping, Sequence
+from contextlib import contextmanager
+from dataclasses import dataclass, replace
+from pathlib import Path
+from queue import SimpleQueue
+from types import EllipsisType, MappingProxyType
+from typing import Final
+from urllib.parse import urlsplit
+
+import httpx
+import psutil
+import pytest
+import yaml
+from _pytest.mark.structures import ParameterSet
+from integration._support import responses_vendor as rv
+from integration._support.aws_control_plane import ControlPlane, ControlPlaneRequest, Responder, control_plane
+from integration._support.budget import readiness_seconds
+from integration._support.client import Gateway, eventually, gateway_from_environment
+from integration._support.database import read_rows
+from integration._support.process import OwnedProxy, graceful_stop_seconds, owned_proxy, owned_proxy_process
+from integration._support.wire import Reply, Request, Wire, wire_server
+from integration.providers.test_responses_bridge_tool_search_wire import (
+ _CACHE_BUST,
+ _CLAUDE,
+ _ITEMS,
+ _JSON_OBJECT,
+ _REGEX_TOOL,
+ _TICKER_PARAMETERS,
+ _WEATHER_PARAMETERS,
+ _anthropic_error,
+ _answer,
+ _assert_spend_rows,
+ _Client,
+ _completed_of,
+ _deployment,
+ _frames,
+ _function_tool,
+ _namespace_tool,
+ _output_types,
+ _prompt,
+ _raw,
+ _responses_body,
+ _spend_rows,
+ _tool_search,
+ _Vendor,
+)
+from pydantic import JsonValue
+
+pytestmark = pytest.mark.timeout(2 * graceful_stop_seconds() + 120)
+
+_OPENAI_HOST: Final = "api.openai.com"
+_OPENAI_API_BASE: Final = f"https://{_OPENAI_HOST}/v1"
+_RESPONSES_MODEL: Final = "openai/responses/gpt-5.5"
+_UNFLAGGED_MODEL: Final = "openai/gpt-5.4-nano"
+_BM25_TOOL_TYPE: Final = "tool_search_tool_bm25_20251119"
+_BM25_TOOL_NAME: Final = "tool_search_tool_bm25"
+_SERVER_TOOL_SEARCH: Final[Mapping[str, JsonValue]] = MappingProxyType({"type": "tool_search", "execution": "server"})
+_SEARCH_CALL_ID: Final = "srvtoolu_01AuditSearchCall"
+_BURST_SIZE: Final = 30
+
+
+def _bm25_tool() -> dict[str, JsonValue]:
+ return {"type": _BM25_TOOL_TYPE, "name": _BM25_TOOL_NAME}
+
+
+def _stock_function_tool() -> dict[str, JsonValue]:
+ return {
+ "type": "function",
+ "name": "get_stock_price",
+ "description": "Price of a ticker",
+ "parameters": _TICKER_PARAMETERS,
+ "defer_loading": True,
+ }
+
+
+def _undeferred(tool: Mapping[str, JsonValue]) -> dict[str, JsonValue]:
+ return {key: value for key, value in tool.items() if key != "defer_loading"}
+
+
+def _undeferred_namespace() -> dict[str, JsonValue]:
+ namespace: Final = _namespace_tool()
+ return {**namespace, "tools": [_undeferred(member) for member in _ITEMS.validate_python(namespace["tools"])]}
+
+
+def _deferred_tools() -> tuple[dict[str, JsonValue], ...]:
+ return (_bm25_tool(), _function_tool(), _stock_function_tool())
+
+
+def _mapped_tools() -> list[dict[str, JsonValue]]:
+ return [dict(_SERVER_TOOL_SEARCH), _function_tool(), _stock_function_tool()]
+
+
+def _search_call(
+ call_id: JsonValue | EllipsisType = _SEARCH_CALL_ID, name: str = _BM25_TOOL_NAME
+) -> dict[str, JsonValue]:
+ call: Final[dict[str, JsonValue]] = {"type": "function_call", "name": name, "arguments": '{"query": "weather"}'}
+ return call if isinstance(call_id, EllipsisType) else {**call, "call_id": call_id}
+
+
+def _search_output() -> dict[str, JsonValue]:
+ return {"type": "function_call_output", "call_id": _SEARCH_CALL_ID, "output": "[]"}
+
+
+def _tools_body(
+ tools: Sequence[Mapping[str, JsonValue]], stream: bool = False
+) -> Callable[[str, str], dict[str, JsonValue]]:
+ return lambda model, marker: _responses_body(model, marker, tools, stream)
+
+
+def _compaction(request: Request) -> Reply:
+ assert urlsplit(request.target).path == "/v1/responses/compact", request.target
+ return Reply(
+ body=json.dumps(
+ {
+ "id": f"resp_compact_{uuid.uuid4().hex}",
+ "created_at": 1,
+ "object": "response.compaction",
+ "output": [
+ {
+ "id": f"rs_compact_{uuid.uuid4().hex}",
+ "type": "reasoning",
+ "summary": [{"type": "summary_text", "text": "Compacted state"}],
+ "encrypted_content": "synthetic-compact-state",
+ }
+ ],
+ "usage": rv.USAGE,
+ }
+ ).encode()
+ )
+
+
+def _answered_as_openai_api(respond: Callable[[Request], Reply]) -> Responder:
+ def answer(request: ControlPlaneRequest) -> Reply:
+ reply: Final = respond(Request(request.method, request.target, request.headers, request.body))
+ return reply if reply.chunks is None else replace(reply, body=b"".join(reply.chunks), chunks=None)
+
+ return answer
+
+
+def _openai_api_requests(openai_api: ControlPlane, key: str) -> tuple[ControlPlaneRequest, ...]:
+ return tuple(request for request in openai_api.drain() if request.credential == key and request.method == "POST")
+
+
+@dataclass(frozen=True, slots=True)
+class _Exchange:
+ model: str
+ marker: str
+ response: httpx.Response
+ requests: tuple[ControlPlaneRequest, ...]
+
+ def only_body(self, path: str = "/v1/responses") -> dict[str, JsonValue]:
+ assert [(request.host, request.path) for request in self.requests] == [(_OPENAI_HOST, path)], self.requests
+ return _JSON_OBJECT.validate_json(self.requests[0].body)
+
+
+def _exchange(
+ openai_gateway: Gateway,
+ openai_api: ControlPlane,
+ body: Callable[[str, str], Mapping[str, JsonValue]],
+ *,
+ path: str = "/v1/responses",
+ respond: Callable[[Request], Reply] | None = None,
+ model: str = _RESPONSES_MODEL,
+ deployment: Mapping[str, JsonValue] = MappingProxyType({}),
+) -> _Exchange:
+ marker: Final = uuid.uuid4().hex
+ key: Final = f"synthetic-openai-key-{marker}"
+ responder: Final = respond if respond is not None else rv.ResponsesVendor().respond
+ with openai_gateway.scenario() as scenario, openai_api.answering(key, _answered_as_openai_api(responder)):
+ name: Final = scenario.model(model_info=None, model=model, api_base=_OPENAI_API_BASE, api_key=key, **deployment)
+ response: Final = _raw(openai_gateway, path, {**body(name, marker), **_CACHE_BUST})
+ return _Exchange(name, marker, response, _openai_api_requests(openai_api, key))
+
+
+def _response_id(response: httpx.Response, stream: bool) -> str:
+ payload: Final = _completed_of(_frames(response.text)) if stream else _JSON_OBJECT.validate_json(response.content)
+ return str(payload["id"])
+
+
+def _assert_success_rows(model: str, response_ids: Sequence[str], failures: int) -> None:
+ rows: Final = _spend_rows(model, len(response_ids) + failures)
+ assert len(rows) == len(response_ids) + failures, rows
+ successes: Final = [str(row["request_id"]) for row in rows if row["status"] == "success"]
+ assert len(successes) == len(response_ids), rows
+ matches: Final = [sum(1 for logged in successes if rv.same_response(logged, sent)) for sent in response_ids]
+ assert matches == [1] * len(response_ids), (response_ids, rows)
+
+
[email protected](scope="module")
+def openai_api(tmp_path_factory: pytest.TempPathFactory) -> Iterator[ControlPlane]:
+ with control_plane(tmp_path_factory.mktemp("openai_api"), (_OPENAI_HOST,)) as plane:
+ yield plane
+
+
+@dataclass(frozen=True, slots=True)
+class _FallbackRoute:
+ claude: str
+ openai: str
+ key: str
+
+
+@dataclass(frozen=True, slots=True)
+class _ClaudeOutage:
+ wire: Wire
+ routes: Mapping[bool, _FallbackRoute]
+
+
+def _fallback_route() -> _FallbackRoute:
+ marker: Final = uuid.uuid4().hex
+ return _FallbackRoute(
+ f"integration-claude-{marker}", f"integration-openai-{marker}", f"synthetic-openai-key-{marker}"
+ )
+
+
[email protected](scope="module")
+def claude_outage() -> Iterator[_ClaudeOutage]:
+ def respond(request: Request) -> Reply:
+ if request.method != "POST":
+ return Reply(body=b'{"object":"list","data":[]}')
+ return _anthropic_error(500, "scripted Claude failure")
+
+ with wire_server(respond) as wire:
+ yield _ClaudeOutage(wire, MappingProxyType({stream: _fallback_route() for stream in (False, True)}))
+
+
+def _proxy_config() -> dict[str, JsonValue]:
+ return rv.JSON_OBJECT.validate_python(yaml.safe_load(Path("tests/integration/proxy_config.yaml").read_text()))
+
+
+def _fallback_deployments(outage: _ClaudeOutage, route: _FallbackRoute) -> tuple[dict[str, JsonValue], ...]:
+ return (
+ {
+ "model_name": route.claude,
+ "litellm_params": {
+ "model": f"anthropic/{_CLAUDE}",
+ "api_base": outage.wire.url,
+ "api_key": "synthetic-invalid-key",
+ },
+ },
+ {
+ "model_name": route.openai,
+ "litellm_params": {"model": _RESPONSES_MODEL, "api_base": _OPENAI_API_BASE, "api_key": route.key},
+ },
+ )
+
+
+def _fallback_config(directory: Path, outage: _ClaudeOutage) -> Path:
+ config: Final = _proxy_config()
+ models: Final = rv.ITEMS.validate_python(config["model_list"])
+ added: Final = tuple(
+ itertools.chain.from_iterable(_fallback_deployments(outage, route) for route in outage.routes.values())
+ )
+ path: Final = directory / "openai-responses-tool-search-fallbacks.yaml"
+ path.write_text(yaml.safe_dump({**config, "model_list": [*models, *added]}))
+ return path
+
+
[email protected](scope="module")
+def openai_gateway(
+ openai_api: ControlPlane, claude_outage: _ClaudeOutage, tmp_path_factory: pytest.TempPathFactory
+) -> Iterator[Gateway]:
+ directory: Final = tmp_path_factory.mktemp("openai_gateway")
+ with (
+ gateway_from_environment() as parent,
+ owned_proxy(
+ parent, directory, openai_api.environment(), config=_fallback_config(directory, claude_outage), workers=2
+ ) as owned,
+ ):
+ yield owned
+
+
+def _drop_params_config(directory: Path) -> Path:
+ config: Final = _proxy_config()
+ settings: Final = rv.JSON_OBJECT.validate_python(config["litellm_settings"])
+ path: Final = directory / "openai-responses-tool-search-drop-params.yaml"
+ path.write_text(yaml.safe_dump({**config, "litellm_settings": {**settings, "drop_params": True}}))
+ return path
+
+
[email protected](scope="module")
+def openai_drop_params_proxy(
+ openai_api: ControlPlane, tmp_path_factory: pytest.TempPathFactory
+) -> Iterator[OwnedProxy]:
+ directory: Final = tmp_path_factory.mktemp("openai_drop_params")
+ with (
+ gateway_from_environment() as gateway,
+ owned_proxy_process(
+ gateway, directory, openai_api.environment(), config=_drop_params_config(directory), workers=2
+ ) as owned,
+ ):
+ yield owned
+
+
[email protected]("search_tool", [_bm25_tool(), dict(_REGEX_TOOL)], ids=["bm25", "regex"])
[email protected]("stream", [False, True], ids=["sync", "stream"])
+def test_anthropic_tool_search_reaches_openai_responses_as_server_tool_search(
+ openai_gateway: Gateway, openai_api: ControlPlane, stream: bool, search_tool: dict[str, JsonValue]
+) -> None:
+ exchange: Final = _exchange(
+ openai_gateway, openai_api, _tools_body((search_tool, _function_tool(), _stock_function_tool()), stream)
+ )
+
+ assert exchange.response.status_code == 200, exchange.response.text
+ body: Final = exchange.only_body()
+ assert (body["model"], body["stream"], body["input"]) == ("gpt-5.5", stream, _prompt(exchange.marker)), body
+ assert body["tools"] == _mapped_tools(), body
+ _assert_spend_rows(exchange.model, (_response_id(exchange.response, stream),))
+
+
[email protected]("stream", [False, True], ids=["sync", "stream"])
+def test_router_fallback_maps_anthropic_tool_search_for_openai_responses(
+ openai_gateway: Gateway, openai_api: ControlPlane, claude_outage: _ClaudeOutage, stream: bool
+) -> None:
+ route: Final = claude_outage.routes[stream]
+ body: Final = _responses_body(route.claude, uuid.uuid4().hex, _deferred_tools(), stream)
+ with openai_api.answering(route.key, _answered_as_openai_api(rv.ResponsesVendor().respond)):
+ response: Final = _raw(openai_gateway, "/v1/responses", {**body, **_CACHE_BUST, "fallbacks": [route.openai]})
+
+ assert response.status_code == 200, response.text
+ assert response.headers["x-litellm-attempted-fallbacks"] == "1", response.headers
+ claude_requests: Final = [request.target for request in claude_outage.wire.drain() if request.method == "POST"]
+ assert claude_requests == ["/v1/messages"], claude_requests
+ (received,) = _openai_api_requests(openai_api, route.key)
+ assert (received.host, received.path) == (_OPENAI_HOST, "/v1/responses"), received
+ forwarded: Final = _JSON_OBJECT.validate_json(received.body)
+ assert (forwarded["stream"], forwarded["tools"]) == (stream, _mapped_tools()), forwarded
+
+
+def test_responses_compact_maps_anthropic_tool_search_for_openai(
+ openai_gateway: Gateway, openai_api: ControlPlane
+) -> None:
+ exchange: Final = _exchange(
+ openai_gateway,
+ openai_api,
+ lambda model, marker: {"model": model, "input": _prompt(marker), "tools": list(_deferred_tools())},
+ path="/v1/responses/compact",
+ respond=_compaction,
+ )
+
+ assert exchange.response.status_code == 200, exchange.response.text
+ assert _JSON_OBJECT.validate_json(exchange.response.content)["object"] == "response.compaction", exchange.response
+ assert exchange.only_body("/v1/responses/compact")["tools"] == _mapped_tools()
+
+
[email protected]("client", ["sdk", "async_sdk"])
+def test_the_openai_sdk_gets_its_answer_with_the_search_tool_mapped(
+ openai_gateway: Gateway, openai_api: ControlPlane, client: _Client
+) -> None:
+ marker: Final = uuid.uuid4().hex
+ key: Final = f"synthetic-openai-key-{marker}"
+ with (
+ openai_gateway.scenario() as scenario,
+ openai_api.answering(key, _answered_as_openai_api(rv.ResponsesVendor().respond)),
+ ):
+ model: Final = scenario.model(model=_RESPONSES_MODEL, api_base=_OPENAI_API_BASE, api_key=key)
+ answer: Final = _answer(openai_gateway, client, _responses_body(model, marker, _deferred_tools(), False))
+ (received,) = _openai_api_requests(openai_api, key)
+
+ assert _output_types(answer.payload) == ["reasoning", "message"], answer.payload
+ assert _JSON_OBJECT.validate_json(received.body)["tools"] == _mapped_tools(), received.body
+ _assert_spend_rows(model, (str(answer.payload["id"]),))
+
+
+def test_model_info_reports_tool_search_support_for_an_openai_gpt_5_5_deployment(gateway: Gateway) -> None:
+ with gateway.scenario() as scenario:
+ model: Final = scenario.model(model="openai/gpt-5.5", api_base=_OPENAI_API_BASE, api_key="synthetic-openai-key")
+ response: Final = gateway.request("GET", "/model/info", None)
+
+ assert response.status_code == 200, response.text
+ (entry,) = [
+ item
+ for item in _ITEMS.validate_python(_JSON_OBJECT.validate_json(response.content)["data"])
+ if item["model_name"] == model
+ ]
+ assert _JSON_OBJECT.validate_python(entry["model_info"]).get("supports_tool_search") is True, entry
+
+
+ ("history", "replayed"),
+ [
+ pytest.param((_search_call(),), (), id="unanswered"),
+ pytest.param((_search_call(), _search_output()), (_search_call(), _search_output()), id="answered"),
+ pytest.param((_search_call(name="get_weather"),), (_search_call(name="get_weather"),), id="other-name"),
+ pytest.param((_search_call(call_id="call_audit"),), (_search_call(call_id="call_audit"),), id="other-id"),
+ pytest.param((_search_call(call_id=...),), (_search_call(call_id=...),), id="no-call-id"),
+ pytest.param((_search_call(call_id=5),), (_search_call(call_id=5),), id="int-call-id"),
+ ],
+)
+def test_only_an_unanswered_claude_search_call_leaves_the_replayed_input(
+ openai_gateway: Gateway,
+ openai_api: ControlPlane,
+ history: tuple[dict[str, JsonValue], ...],
+ replayed: tuple[dict[str, JsonValue], ...],
+) -> None:
+ exchange: Final = _exchange(
+ openai_gateway,
+ openai_api,
+ lambda model, marker: {
+ "model": model,
+ "input": [{"role": "user", "content": _prompt(marker)}, *history],
+ "tools": list(_deferred_tools()),
+ "stream": False,
+ },
+ )
+
+ assert exchange.response.status_code == 200, exchange.response.text
+ body: Final = exchange.only_body()
+ assert body["input"] == [{"role": "user", "content": _prompt(exchange.marker)}, *replayed], body
+ assert body["tools"] == _mapped_tools(), body
+
+
+def _drop_params_cells() -> list[ParameterSet]:
+ stripped: Final = [_function_tool(...), _undeferred(_stock_function_tool())]
+ return [
+ pytest.param(_UNFLAGGED_MODEL, True, _deferred_tools(), stripped, id="unflagged-true"),
+ pytest.param(_UNFLAGGED_MODEL, "true", _deferred_tools(), stripped, id="unflagged-string-true"),
+ pytest.param(_UNFLAGGED_MODEL, ..., _deferred_tools(), _mapped_tools(), id="unflagged-missing"),
+ pytest.param(_UNFLAGGED_MODEL, None, _deferred_tools(), _mapped_tools(), id="unflagged-null"),
+ pytest.param(_UNFLAGGED_MODEL, False, _deferred_tools(), _mapped_tools(), id="unflagged-false"),
+ pytest.param(_UNFLAGGED_MODEL, "", _deferred_tools(), _mapped_tools(), id="unflagged-empty-string"),
+ pytest.param(
+ _UNFLAGGED_MODEL,
+ True,
+ (_bm25_tool(), _namespace_tool()),
+ [_undeferred_namespace()],
+ id="unflagged-namespace",
+ ),
+ pytest.param(_RESPONSES_MODEL, True, _deferred_tools(), _mapped_tools(), id="flagged-deferred"),
+ pytest.param(
+ _RESPONSES_MODEL, True, (_bm25_tool(), _function_tool(...)), [_function_tool(...)], id="flagged-undeferred"
+ ),
+ ]
+
+
[email protected](("model", "drop_params", "tools", "forwarded"), _drop_params_cells())
+def test_drop_params_drops_the_search_only_when_the_openai_model_cannot_run_it(
+ openai_gateway: Gateway,
+ openai_api: ControlPlane,
+ model: str,
+ drop_params: JsonValue | EllipsisType,
+ tools: tuple[dict[str, JsonValue], ...],
+ forwarded: list[dict[str, JsonValue]],
+) -> None:
+ setting: Final[dict[str, JsonValue]] = {} if isinstance(drop_params, EllipsisType) else {"drop_params": drop_params}
+ exchange: Final = _exchange(openai_gateway, openai_api, _tools_body(tools), model=model, deployment=setting)
+
+ assert exchange.response.status_code == 200, exchange.response.text
+ assert exchange.only_body()["tools"] == forwarded
+
+
[email protected]("drop_params", [False, True], ids=["no-drop-params", "drop-params"])
+def test_the_callers_own_tool_search_replaces_the_anthropic_search_tool(
+ openai_gateway: Gateway, openai_api: ControlPlane, drop_params: bool
+) -> None:
+ exchange: Final = _exchange(
+ openai_gateway,
+ openai_api,
+ _tools_body((_bm25_tool(), _tool_search(), _function_tool(), _stock_function_tool())),
+ model=_UNFLAGGED_MODEL,
+ deployment={"drop_params": drop_params},
+ )
+
+ assert exchange.response.status_code == 200, exchange.response.text
+ assert exchange.only_body()["tools"] == [_tool_search(), _function_tool(), _stock_function_tool()]
+
+
+ ("tools", "forwarded"),
+ [
+ pytest.param(
+ (_bm25_tool(), _bm25_tool(), _function_tool()), [dict(_SERVER_TOOL_SEARCH), _function_tool()], id="twice"
+ ),
+ pytest.param(
+ (_function_tool(), dict(_REGEX_TOOL), _bm25_tool(), _stock_function_tool()),
+ [_function_tool(), dict(_SERVER_TOOL_SEARCH), _stock_function_tool()],
+ id="regex-then-bm25",
+ ),
+ *(
+ pytest.param(({"type": _BM25_TOOL_TYPE, "name": name}, _function_tool()), None, id=f"name-{label}")
+ for label, name in (("int", 5), ("list", [_BM25_TOOL_NAME]), ("empty", ""), ("5kb", "a" * 5000))
+ ),
+ pytest.param(({"type": _BM25_TOOL_TYPE}, _function_tool()), None, id="name-missing"),
+ ],
+)
+def test_the_search_tool_maps_by_its_type_whatever_sits_around_it(
+ openai_gateway: Gateway,
+ openai_api: ControlPlane,
+ tools: tuple[JsonValue, ...],
+ forwarded: list[JsonValue] | None,
+) -> None:
+ exchange: Final = _exchange(
+ openai_gateway,
+ openai_api,
+ lambda model, marker: {"model": model, "input": _prompt(marker), "tools": list(tools), "stream": False},
+ )
+
+ assert exchange.response.status_code == 200, exchange.response.text
+ expected: Final = forwarded if forwarded is not None else [dict(_SERVER_TOOL_SEARCH), _function_tool()]
+ assert exchange.only_body()["tools"] == expected
+
+
+def test_an_int_tool_beside_the_search_tool_reaches_openai_with_the_search_mapped(
+ openai_gateway: Gateway, openai_api: ControlPlane
+) -> None:
+ pytest.skip("BUG: an int tools element answers 401 Authentication Error from the vector store tool scan")
+ exchange: Final = _exchange(
+ openai_gateway,
+ openai_api,
+ lambda model, marker: {"model": model, "input": _prompt(marker), "tools": [5, _bm25_tool(), _function_tool()]},
+ )
+
+ assert exchange.response.status_code == 200, exchange.response.text
+ assert exchange.only_body()["tools"] == [5, dict(_SERVER_TOOL_SEARCH), _function_tool()]
+
+
+def _string_beside_search_body(model: str, marker: str) -> dict[str, JsonValue]:
+ return {"model": model, "input": _prompt(marker), "tools": ["get_weather", _bm25_tool(), _function_tool()]}
+
+
+def test_a_string_tool_beside_the_search_tool_is_refused_before_reaching_openai(
+ openai_gateway: Gateway, openai_api: ControlPlane
+) -> None:
+ exchange: Final = _exchange(openai_gateway, openai_api, _string_beside_search_body)
+
+ assert exchange.response.status_code == 400, exchange.response.text
+ assert exchange.requests == (), exchange.requests
+
+
+def test_a_string_tool_beside_the_search_tool_is_refused_before_reaching_claude(gateway: Gateway) -> None:
+ with wire_server(_Vendor().respond) as wire, gateway.scenario() as scenario:
+ model: Final = _deployment(scenario, "anthropic", wire.url, gateway.upstream_url)
+ response: Final = _raw(
+ gateway, "/v1/responses", {**_string_beside_search_body(model, uuid.uuid4().hex), **_CACHE_BUST}
+ )
+
+ assert response.status_code == 400, response.text
+ assert [request for request in wire.drain() if request.method == "POST"] == []
+
+
[email protected]("model", [_RESPONSES_MODEL, "azure/gpt-5.5"], ids=["openai-compatible-host", "azure"])
+def test_a_deployment_off_api_openai_com_keeps_the_anthropic_search_tool(gateway: Gateway, model: str) -> None:
+ marker: Final = uuid.uuid4().hex
+ with wire_server(rv.ResponsesVendor().respond) as wire, gateway.scenario() as scenario:
+ host: Final[dict[str, JsonValue]] = (
+ {"api_base": wire.url, "api_version": "preview"}
+ if model.startswith("azure/")
+ else {"api_base": f"{wire.url}/v1"}
+ )
+ deployment: Final = scenario.model(model_info=None, model=model, api_key="synthetic-provider-key", **host)
+ response: Final = _raw(
+ gateway, "/v1/responses", {**_responses_body(deployment, marker, _deferred_tools(), False), **_CACHE_BUST}
+ )
+
+ assert response.status_code == 200, response.text
+ (request,) = [request for request in wire.drain() if request.method == "POST"]
+ assert _JSON_OBJECT.validate_json(request.body)["tools"] == list(_deferred_tools()), request.body
+
+
[email protected]("status", [400, 401, 404])
+def test_an_openai_error_on_the_mapped_request_reaches_the_caller_and_lands_as_a_failed_spend_row(
+ openai_gateway: Gateway, openai_api: ControlPlane, status: int
+) -> None:
+ message: Final = f"scripted openai {status}"
+ exchange: Final = _exchange(
+ openai_gateway,
+ openai_api,
+ _tools_body(_deferred_tools()),
+ respond=lambda request: rv.error(status, message, "invalid_request_error"),
+ )
+
+ assert exchange.response.status_code == status, exchange.response.text
+ assert message in exchange.response.text, exchange.response.text
+ assert exchange.only_body()["tools"] == _mapped_tools()
+ call_id: Final = exchange.response.headers["x-litellm-call-id"]
+ rows: Final = eventually(
+ lambda: read_rows('SELECT status FROM "LiteLLM_SpendLogs" WHERE request_id=%s', (call_id,)),
+ lambda found: len(found) == 1,
+ seconds=70,
+ )
+ assert str(rows[0]["status"]) == "failure", rows
+
+
+ ("model", "forwarded"),
+ [
+ (_RESPONSES_MODEL, [("tool_search", "server", None, None), ("function", None, "get_weather", True)]),
+ ("openai/responses/gpt-5.4-nano", [("function", None, "get_weather", None)]),
+ ],
+ ids=["flagged-deferred", "unflagged"],
+)
+def test_chat_completions_through_the_responses_bridge_follow_drop_params(
+ openai_gateway: Gateway,
+ openai_api: ControlPlane,
+ model: str,
+ forwarded: list[tuple[JsonValue, ...]],
+) -> None:
+ exchange: Final = _exchange(
+ openai_gateway,
+ openai_api,
+ lambda model, marker: {
+ "model": model,
+ "messages": [{"role": "user", "content": _prompt(marker)}],
+ "tools": [
+ _bm25_tool(),
+ {
+ "type": "function",
+ "function": {
+ "name": "get_weather",
+ "description": "Weather for a city",
+ "parameters": _WEATHER_PARAMETERS,
+ },
+ "defer_loading": True,
+ },
+ ],
+ },
+ path="/v1/chat/completions",
+ model=model,
+ deployment={"drop_params": True},
+ )
+
+ assert exchange.response.status_code == 200, exchange.response.text
+ tools: Final = _ITEMS.validate_python(exchange.only_body()["tools"])
+ wire_keys: Final = ("type", "execution", "name", "defer_loading")
+ assert [tuple(tool.get(key) for key in wire_keys) for tool in tools] == forwarded, tools
+
+
+def test_messages_to_an_openai_model_with_the_search_tool_still_answers(
+ openai_gateway: Gateway, openai_api: ControlPlane
+) -> None:
+ exchange: Final = _exchange(
+ openai_gateway,
+ openai_api,
+ lambda model, marker: {
+ "model": model,
+ "max_tokens": 256,
+ "messages": [{"role": "user", "content": _prompt(marker)}],
+ "tools": [
+ _bm25_tool(),
+ {
+ "name": "get_weather",
+ "description": "Weather for a city",
+ "input_schema": _WEATHER_PARAMETERS,
+ "defer_loading": True,
+ },
+ ],
+ },
+ path="/v1/messages",
+ model="openai/gpt-5.5",
+ )
+
+ assert exchange.response.status_code == 200, exchange.response.text
+ assert len(exchange.requests) == 1, exchange.requests
+
+
+def test_a_global_drop_params_drops_the_search_for_an_openai_model_that_cannot_run_it(
+ openai_drop_params_proxy: OwnedProxy, openai_api: ControlPlane
+) -> None:
+ exchange: Final = _exchange(
+ openai_drop_params_proxy.gateway, openai_api, _tools_body(_deferred_tools()), model=_UNFLAGGED_MODEL
+ )
+
+ assert exchange.response.status_code == 200, exchange.response.text
+ assert exchange.only_body()["tools"] == [_function_tool(...), _undeferred(_stock_function_tool())]
+
+
+@dataclass(frozen=True, slots=True)
+class _BurstCall:
+ marker: str
+ path: str
+ stream: bool
+ fails: bool
+
+
+def _burst_calls() -> tuple[_BurstCall, ...]:
+ shapes: Final = itertools.cycle(
+ (("/v1/responses", False), ("/v1/responses", True), ("/v1/responses/compact", False))
+ )
+ return tuple(
+ _BurstCall(uuid.uuid4().hex, path, stream, index % 5 == 0)
+ for index, (path, stream) in zip(range(_BURST_SIZE), shapes)
+ )
+
+
+def _burst_body(model: str, call: _BurstCall) -> dict[str, JsonValue]:
+ body: Final[dict[str, JsonValue]] = {
+ "model": model,
+ "input": _prompt(call.marker),
+ "tools": list(_deferred_tools()),
+ **_CACHE_BUST,
+ }
+ return body if call.path.endswith("/compact") else {**body, "stream": call.stream}
+
+
+async def _post(client: httpx.AsyncClient, path: str, body: Mapping[str, JsonValue]) -> httpx.Response | None:
+ try:
+ return await client.post(path, json=dict(body))
+ except httpx.TransportError:
+ return None
+
+
+async def _burst(
+ gateway: Gateway, bodies: Sequence[tuple[str, Mapping[str, JsonValue]]]
+) -> list[httpx.Response | None]:
+ async with httpx.AsyncClient(
+ base_url=str(gateway.client.base_url),
+ headers={"Authorization": f"Bearer {gateway.key}"},
+ trust_env=False,
+ timeout=120,
+ ) as client:
+ return list(await asyncio.gather(*(_post(client, path, body) for path, body in bodies)))
+
+
+def _marker_of(request: ControlPlaneRequest) -> str:
+ marker: Final = rv.newest_marker(request.body.decode())
+ assert marker is not None, request.body
+ return marker
+
+
+async def test_a_mixed_burst_with_upstream_failures_maps_every_request_and_logs_each_once(
+ openai_drop_params_proxy: OwnedProxy, openai_api: ControlPlane
+) -> None:
+ calls: Final = _burst_calls()
+ failing: Final = frozenset(call.marker for call in calls if call.fails)
+ vendor: Final = rv.ResponsesVendor(pause_between_chunks=0.02)
+ key: Final = f"synthetic-openai-key-{uuid.uuid4().hex}"
+
+ def respond(request: Request) -> Reply:
+ marker: Final = rv.newest_marker(request.body.decode())
+ if marker in failing:
+ return rv.error(500, f"scripted outage marker-{marker}", "server_error")
+ return _compaction(request) if urlsplit(request.target).path.endswith("/compact") else vendor.respond(request)
+
+ proxy: Final = openai_drop_params_proxy.gateway
+ with proxy.scenario() as scenario, openai_api.answering(key, _answered_as_openai_api(respond)):
+ model: Final = scenario.model(model=_RESPONSES_MODEL, api_base=_OPENAI_API_BASE, api_key=key)
+ responses: Final = await _burst(proxy, [(call.path, _burst_body(model, call)) for call in calls])
+ received: Final = _openai_api_requests(openai_api, key)
+
+ for call, response in zip(calls, responses):
+ assert response is not None, call
+ if call.fails:
+ assert response.status_code == 500, (call, response.text)
+ assert f"scripted outage marker-{call.marker}" in response.text, response.text
+ continue
+ assert response.status_code == 200, (call, response.text)
+ for request in received:
+ assert _JSON_OBJECT.validate_json(request.body)["tools"] == _mapped_tools(), request.body
+ served: Final = [_marker_of(request) for request in received if _marker_of(request) not in failing]
+ assert sorted(served) == sorted(call.marker for call in calls if not call.fails), served
+ succeeded: Final = [
+ _response_id(response, call.stream)
+ for call, response in zip(calls, responses)
+ if response is not None and not call.fails
+ ]
+ _assert_success_rows(model, succeeded, failures=len(failing))
+
+
+def _open_tunnels(pid: int, openai_api: ControlPlane) -> int:
+ port: Final = urlsplit(openai_api.url).port
+ return sum(
+ 1
+ for connection in psutil.Process(pid).net_connections(kind="tcp")
+ if connection.status == psutil.CONN_ESTABLISHED and connection.raddr and connection.raddr.port == port
+ )
+
+
+@contextmanager
+def _released_on_exit(release: threading.Event) -> Generator[None]:
+ try:
+ yield
+ finally:
+ release.set()
+
+
+async def test_a_worker_killed_mid_burst_leaves_the_survivor_mapping_the_search_tool(
+ openai_api: ControlPlane, tmp_path: Path
+) -> None:
+ release: Final = threading.Event()
+ held: Final[SimpleQueue[str]] = SimpleQueue()
+ vendor: Final = rv.ResponsesVendor()
+ key: Final = f"synthetic-openai-key-{uuid.uuid4().hex}"
+ markers: Final = tuple(uuid.uuid4().hex for _ in range(20))
+
+ def respond(request: Request) -> Reply:
+ marker: Final = rv.newest_marker(request.body.decode())
+ if marker in markers:
+ held.put(marker)
+ assert release.wait(timeout=readiness_seconds(1) + 60), "The burst was never released"
+ return vendor.respond(request)
+
+ with (
+ gateway_from_environment() as parent,
+ owned_proxy_process(parent, tmp_path, openai_api.environment(), workers=2) as owned,
+ owned.gateway.scenario() as scenario,
+ openai_api.answering(key, _answered_as_openai_api(respond)),
+ _released_on_exit(release),
+ ):
+ model: Final = scenario.model(model=_RESPONSES_MODEL, api_base=_OPENAI_API_BASE, api_key=key)
+ workers: Final = eventually(owned.worker_pids, lambda pids: len(pids) == 2, seconds=30)
+ bodies: Final = [
+ ("/v1/responses", {**_responses_body(model, marker, _deferred_tools(), False), **_CACHE_BUST})
+ for marker in markers
+ ]
+ burst: Final = asyncio.create_task(_burst(owned.gateway, bodies))
+ await asyncio.to_thread(eventually, held.qsize, lambda size: size == len(markers), 60)
+ held_by: Final = MappingProxyType({pid: _open_tunnels(pid, openai_api) for pid in workers})
+ assert sum(held_by.values()) == len(markers), held_by
+ victim_pid, survivor_pid = sorted(workers, key=held_by.__getitem__)
+ await asyncio.to_thread(owned.kill_worker, victim_pid)
+ release.set()
+ responses: Final = await burst
+ served: Final = [response for response in responses if response is not None and response.status_code == 200]
+ assert held_by[survivor_pid] >= 1, held_by
+ assert len(served) == held_by[survivor_pid], (held_by, [r.status_code if r else None for r in responses])
+ follow_up: Final = uuid.uuid4().hex
+ (after,) = await _burst(
+ owned.gateway,
+ [("/v1/responses", {**_responses_body(model, follow_up, _deferred_tools(), False), **_CACHE_BUST})],
+ )
+ assert after is not None and after.status_code == 200, after
+ received: Final = _openai_api_requests(openai_api, key)
+ assert {_marker_of(request) for request in received} == {*markers, follow_up}
+ for request in received:
+ assert _JSON_OBJECT.validate_json(request.body)["tools"] == _mapped_tools(), request.body
diff --git a/tests/unit/completion_extras/litellm_responses_transformation/test_completion_extras_litellm_responses_transformation_transformation.py b/tests/unit/completion_extras/litellm_responses_transformation/test_completion_extras_litellm_responses_transformation_transformation.py
index e5c515f1a09..83c59480d37 100644
--- a/tests/unit/completion_extras/litellm_responses_transformation/test_completion_extras_litellm_responses_transformation_transformation.py
+++ b/tests/unit/completion_extras/litellm_responses_transformation/test_completion_extras_litellm_responses_transformation_transformation.py
@@ -9,6 +9,7 @@ from unittest.mock import ANY, MagicMock, Mock, patch
import httpx
import pytest
+import respx
from openai.types.responses import (
ResponseFunctionToolCall,
ResponseOutputMessage,
@@ -33,6 +34,54 @@ if TYPE_CHECKING:
from litellm.types.utils import ModelResponse
+def test_completion_over_responses_maps_anthropic_search_tool_to_openai_tool_search() -> None:
+ response_body: Final = {
+ "id": "resp_tool_search_bridge",
+ "object": "response",
+ "created_at": 1789788253,
+ "status": "completed",
+ "model": "gpt-5.5",
+ "output": [
+ {
+ "type": "message",
+ "id": "msg_tool_search_bridge",
+ "status": "completed",
+ "role": "assistant",
+ "content": [{"type": "output_text", "text": "ok", "annotations": []}],
+ }
+ ],
+ "usage": {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2},
+ }
+ tools: Final = [
+ {"type": "tool_search_tool_bm25_20251119", "name": "tool_search_tool_bm25"},
+ {
+ "type": "function",
+ "function": {
+ "name": "get_weather",
+ "description": "Get the weather",
+ "parameters": {"type": "object", "properties": {"city": {"type": "string"}}},
+ },
+ "defer_loading": True,
+ },
+ ]
+
+ with respx.mock(assert_all_called=True) as router:
+ upstream: Final = router.post("https://api.openai.com/v1/responses").mock(
+ return_value=httpx.Response(200, json=response_body)
+ )
+
+ litellm.completion(
+ model="openai/responses/gpt-5.5",
+ messages=[{"role": "user", "content": "Find a tool"}],
+ tools=tools,
+ api_key="sk-test",
+ cache={"no-cache": True},
+ )
+
+ request_body: Final = json.loads(upstream.calls[0].request.content)
+ assert request_body["tools"][0] == {"type": "tool_search", "execution": "server"}
+
+
def test_convert_chat_completion_messages_to_responses_api_image_input():
from litellm.completion_extras.litellm_responses_transformation.transformation import (
LiteLLMResponsesTransformationHandler,
diff --git a/tests/unit/llms/openai/responses/test_openai_responses_transformation.py b/tests/unit/llms/openai/responses/test_openai_responses_transformation.py
index 2a35031202a..0da28e7207e 100644
--- a/tests/unit/llms/openai/responses/test_openai_responses_transformation.py
+++ b/tests/unit/llms/openai/responses/test_openai_responses_transformation.py
@@ -79,6 +79,36 @@ def validate_responses_api_response(response: ResponsesAPIResponse, final_chunk:
return True
+_CLAUDE_SEARCH_CALL: Final = {
+ "type": "function_call",
+ "call_id": "srvtoolu_01Search",
+ "name": "tool_search_tool_bm25",
+ "arguments": '{"query": "weather"}',
+}
+
+
+_BM25_TOOL: Final = {"type": "tool_search_tool_bm25_20251119", "name": "tool_search_tool_bm25"}
+_DEFERRED_WEATHER: Final = {"type": "function", "name": "get_weather", "parameters": {"type": "object"}, "defer_loading": True}
+_CLIENT_TOOL_SEARCH: Final = {
+ "type": "tool_search",
+ "execution": "client",
+ "description": "Search the tool catalog",
+ "parameters": {"type": "object", "properties": {"query": {"type": "string"}}},
+}
+
+
+def _undeferred(tool: Mapping[str, object]) -> dict[str, object]:
+ return {key: value for key, value in tool.items() if key != "defer_loading"}
+
+
+def _openai_model(supports_tool_search: bool) -> str:
+ return next(
+ name
+ for name, info in litellm.model_cost.items()
+ if info.get("litellm_provider") == "openai" and info.get("supports_tool_search", False) is supports_tool_search
+ )
+
+
class TestOpenAIResponsesAPIConfig:
def setup_method(self):
self.config = OpenAIResponsesAPIConfig()
@@ -197,6 +227,248 @@ class TestOpenAIResponsesAPIConfig:
self.validate_responses_api_request_params(result, expected_fields)
+ @pytest.mark.parametrize(
+ "tool_type",
+ ["tool_search_tool_bm25_20251119", "tool_search_tool_regex_20251119"],
+ )
+ def test_transform_maps_anthropic_search_tool_and_preserves_deferred_functions(self, tool_type: str) -> None:
+ tools: Final = [
+ {
+ "type": "function",
+ "name": "get_weather",
+ "parameters": {"type": "object"},
+ "defer_loading": True,
+ },
+ {"type": tool_type, "name": "tool_search"},
+ {
+ "type": "function",
+ "name": "get_stock_price",
+ "parameters": {"type": "object"},
+ "defer_loading": True,
+ },
+ ]
+
+ result: Final = self.config.transform_responses_api_request(
+ model=self.model,
+ input="Find a tool",
+ response_api_optional_request_params={"tools": tools},
+ litellm_params=_OPENAI_API,
+ headers={},
+ )
+
+ assert result["tools"] == [
+ tools[0],
+ {"type": "tool_search", "execution": "server"},
+ tools[2],
+ ]
+
+ def test_transform_deduplicates_anthropic_search_tools(self) -> None:
+ tools: Final = [
+ {"type": "function", "name": "get_weather", "parameters": {"type": "object"}},
+ {"type": "tool_search_tool_bm25_20251119", "name": "tool_search_tool_bm25"},
+ {"type": "function", "name": "get_stock_price", "parameters": {"type": "object"}},
+ {"type": "tool_search_tool_regex_20251119", "name": "tool_search_tool_regex"},
+ ]
+
+ result: Final = self.config.transform_responses_api_request(
+ model=self.model,
+ input="Find a tool",
+ response_api_optional_request_params={"tools": tools},
+ litellm_params=_OPENAI_API,
+ headers={},
+ )
+
+ assert result["tools"] == [
+ tools[0],
+ {"type": "tool_search", "execution": "server"},
+ tools[2],
+ ]
+
+ @pytest.mark.parametrize("execution", [None, "client", "server"])
+ def test_transform_keeps_caller_tool_search_and_drops_anthropic_search_tools(
+ self, execution: str | None
+ ) -> None:
+ caller_tool_search: Final[dict[str, object]] = {
+ "type": "tool_search",
+ **({"execution": execution} if execution is not None else {}),
+ }
+ tools: Final = [
+ {"type": "tool_search_tool_bm25_20251119", "name": "tool_search_tool_bm25"},
+ {"type": "function", "name": "get_weather", "parameters": {"type": "object"}},
+ caller_tool_search,
+ {"type": "tool_search_tool_regex_20251119", "name": "tool_search_tool_regex"},
+ ]
+
+ result: Final = self.config.transform_responses_api_request(
+ model=self.model,
+ input="Find a tool",
+ response_api_optional_request_params={"tools": tools},
+ litellm_params=_OPENAI_API,
+ headers={},
+ )
+
+ assert result["tools"] == [tools[1], caller_tool_search]
+
+ def test_transform_leaves_tools_without_anthropic_search_unchanged(self) -> None:
+ tools: Final = [
+ {"type": "function", "name": "get_weather", "parameters": {"type": "object"}},
+ {"type": "tool_search", "execution": "client"},
+ ]
+
+ result: Final = self.config.transform_responses_api_request(
+ model=self.model,
+ input="Find a tool",
+ response_api_optional_request_params={"tools": tools},
+ litellm_params=_OPENAI_API,
+ headers={},
+ )
+
+ assert result["tools"] == tools
+
+ def test_transform_forwards_anthropic_search_tool_and_history_unchanged_to_another_gateway(self) -> None:
+ tools: Final = [
+ {"type": "tool_search_tool_bm25_20251119", "name": "tool_search_tool_bm25"},
+ {"type": "function", "name": "get_weather", "parameters": {"type": "object"}, "defer_loading": True},
+ ]
+ history: Final = [{"role": "user", "content": "What is the weather in Paris?"}, _CLAUDE_SEARCH_CALL]
+
+ result: Final = self.config.transform_responses_api_request(
+ model=self.model,
+ input=history,
+ response_api_optional_request_params={"tools": tools},
+ litellm_params=_OTHER_HOST,
+ headers={},
+ )
+
+ assert result["tools"] == tools
+ assert result["input"] == history
+
+ def _transform_tools(self, model: str, tools: list[dict[str, object]], drop_params: bool) -> object:
+ return self.config.transform_responses_api_request(
+ model=model,
+ input="Find a tool",
+ response_api_optional_request_params={"tools": tools},
+ litellm_params=GenericLiteLLMParams(api_base="https://api.openai.com/v1", drop_params=drop_params),
+ headers={},
+ )["tools"]
+
+ def test_drop_params_drops_tool_search_for_a_model_that_cannot_run_it(self) -> None:
+ eager: Final = {"type": "function", "name": "get_stock_price", "parameters": {"type": "object"}}
+ namespace: Final = {
+ "type": "namespace",
+ "name": "finance",
+ "description": "Finance tools",
+ "tools": [{**_DEFERRED_WEATHER, "name": "get_quote"}],
+ }
+
+ tools: Final = self._transform_tools(
+ _openai_model(supports_tool_search=False), [_BM25_TOOL, _DEFERRED_WEATHER, eager, namespace], True
+ )
+
+ assert tools == [
+ _undeferred(_DEFERRED_WEATHER),
+ eager,
+ {**namespace, "tools": [_undeferred({**_DEFERRED_WEATHER, "name": "get_quote"})]},
+ ]
+
+ def test_drop_params_drops_tool_search_when_no_tool_is_deferred(self) -> None:
+ tools: Final = self._transform_tools(
+ _openai_model(supports_tool_search=True), [_BM25_TOOL, _undeferred(_DEFERRED_WEATHER)], True
+ )
+
+ assert tools == [_undeferred(_DEFERRED_WEATHER)]
+
+ @pytest.mark.parametrize(
+ ("sent", "expected"),
+ [
+ pytest.param(
+ [{"type": "tool_search"}, _DEFERRED_WEATHER], [{"type": "tool_search"}, _DEFERRED_WEATHER], id="alone"
+ ),
+ pytest.param(
+ [_CLIENT_TOOL_SEARCH, _BM25_TOOL, _undeferred(_DEFERRED_WEATHER)],
+ [_CLIENT_TOOL_SEARCH, _undeferred(_DEFERRED_WEATHER)],
+ id="beside-anthropic-search",
+ ),
+ ],
+ )
+ def test_drop_params_keeps_a_callers_own_tool_search_unchanged(
+ self, sent: list[dict[str, object]], expected: list[dict[str, object]]
+ ) -> None:
+ tools: Final = self._transform_tools(_openai_model(supports_tool_search=False), sent, True)
+
+ assert tools == expected
+
+ @pytest.mark.parametrize("drop_params", [False, True])
+ @pytest.mark.parametrize(
+ "malformed",
+ [
+ pytest.param({"type": None, "name": "x"}, id="null-type"),
+ pytest.param({"type": "namespace", "name": "ns", "description": "d", "tools": "oops"}, id="string-members"),
+ pytest.param({"type": "namespace", "name": "ns", "description": "d", "tools": ["x"]}, id="string-member"),
+ ],
+ )
+ def test_malformed_tool_beside_the_search_tool_reaches_openai_as_sent(
+ self, malformed: dict[str, object], drop_params: bool
+ ) -> None:
+ model: Final = _openai_model(supports_tool_search=True)
+
+ tools: Final = self._transform_tools(model, [_BM25_TOOL, malformed], drop_params)
+
+ assert malformed in tools
+
+ @pytest.mark.parametrize(
+ "deferred",
+ [
+ pytest.param(_DEFERRED_WEATHER, id="function"),
+ pytest.param(
+ {"type": "namespace", "name": "weather", "description": "Weather", "tools": [_DEFERRED_WEATHER]},
+ id="namespace-member",
+ ),
+ ],
+ )
+ def test_drop_params_keeps_tool_search_for_a_model_that_runs_it(self, deferred: dict[str, object]) -> None:
+ tools: Final = self._transform_tools(_openai_model(supports_tool_search=True), [_BM25_TOOL, deferred], True)
+
+ assert tools == [{"type": "tool_search", "execution": "server"}, deferred]
+
+ def test_transform_drops_claude_search_calls_openai_cannot_answer_from_history(self) -> None:
+ answered_search_call: Final = {
+ **_CLAUDE_SEARCH_CALL,
+ "call_id": "srvtoolu_02Answered",
+ "name": "tool_search_tool_regex",
+ }
+ history: Final = [
+ {"role": "user", "content": "What is the weather in Paris?"},
+ _CLAUDE_SEARCH_CALL,
+ answered_search_call,
+ {"type": "function_call_output", "call_id": "srvtoolu_02Answered", "output": "get_weather"},
+ {"type": "function_call", "call_id": "toolu_01Weather", "name": "get_weather", "arguments": "{}"},
+ {"type": "function_call_output", "call_id": "toolu_01Weather", "output": "18C and sunny"},
+ ]
+
+ result: Final = self.config.transform_responses_api_request(
+ model=self.model,
+ input=history,
+ response_api_optional_request_params={"tools": [_BM25_TOOL, _DEFERRED_WEATHER]},
+ litellm_params=_OPENAI_API,
+ headers={},
+ )
+
+ assert result["input"] == [item for item in history if item is not _CLAUDE_SEARCH_CALL]
+
+ def test_transform_keeps_history_as_sent_when_no_anthropic_search_tool_is_mapped(self) -> None:
+ history: Final = [{"role": "user", "content": "What is the weather in Paris?"}, _CLAUDE_SEARCH_CALL]
+
+ result: Final = self.config.transform_responses_api_request(
+ model=self.model,
+ input=history,
+ response_api_optional_request_params={"tools": [_undeferred(_DEFERRED_WEATHER)]},
+ litellm_params=_OPENAI_API,
+ headers={},
+ )
+
+ assert result["input"] == history
+
def test_transform_strips_cache_control_from_input_content_blocks(self):
"""`cache_control` markers (Anthropic-only) must be stripped from
Responses API input content blocks before sending to OpenAI.
@@ -1122,6 +1394,19 @@ class TestAzureResponsesAPIConfig:
assert result["tools"][0]["parameters"] == {"type": "object"}
+ def test_azure_leaves_anthropic_search_tool_unchanged(self) -> None:
+ tool: Final = {"type": "tool_search_tool_bm25_20251119", "name": "tool_search_tool_bm25"}
+
+ result: Final = self.config.transform_responses_api_request(
+ model=self.model,
+ input="Find a tool",
+ response_api_optional_request_params={"tools": [tool]},
+ litellm_params={},
+ headers={},
+ )
+
+ assert result["tools"] == [tool]
+
def test_azure_get_complete_url_with_version_types(self):
"""Test Azure get_complete_url with different API version types"""
base_url = "https://litellm8397336933.openai.azure.com"
diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts
index de72737c7b8..620992b8059 100644
--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts
+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts
@@ -39460,6 +39460,16 @@ export interface components {
/** Value */
value: number;
};
+ /** OpenAIToolSearchToolParam */
+ OpenAIToolSearchToolParam: {
+ /** Execution */
+ execution?: string;
+ /**
+ * Type
+ * @constant
+ */
+ type: "tool_search";
+ };
/**
* OpenIdConnectSecurityScheme
* @description Defines a security scheme using OpenID Connect.
@@ -43747,7 +43757,7 @@ export interface components {
/** Tool Choice */
tool_choice?: ("none" | "auto" | "required") | components["schemas"]["ToolChoiceAllowedParam"] | components["schemas"]["ToolChoiceTypesParam"] | components["schemas"]["ToolChoiceFunctionParam"] | components["schemas"]["ToolChoiceMcpParam"] | components["schemas"]["ToolChoiceCustomParam"] | components["schemas"]["ToolChoiceApplyPatchParam"] | components["schemas"]["ToolChoiceShellParam"] | null;
/** Tools */
- tools?: (components["schemas"]["FunctionToolParam"] | components["schemas"]["FileSearchToolParam"] | components["schemas"]["openai__types__responses__computer_tool_param__ComputerToolParam"] | components["schemas"]["ComputerUsePreviewToolParam"] | components["schemas"]["WebSearchToolParam"] | components["schemas"]["Mcp"] | components["schemas"]["CodeInterpreter"] | components["schemas"]["ImageGeneration"] | components["schemas"]["LocalShell"] | components["schemas"]["FunctionShellToolParam"] | components["schemas"]["CustomToolParam"] | components["schemas"]["NamespaceToolParam"] | components["schemas"]["ToolSearchToolParam"] | components["schemas"]["WebSearchPreviewToolParam"] | components["schemas"]["ApplyPatchToolParam"] | components["schemas"]["litellm__types__llms__openai__ComputerToolParam"] | components["schemas"]["ShellToolParam"])[] | null;
+ tools?: (components["schemas"]["FunctionToolParam"] | components["schemas"]["FileSearchToolParam"] | components["schemas"]["openai__types__responses__computer_tool_param__ComputerToolParam"] | components["schemas"]["ComputerUsePreviewToolParam"] | components["schemas"]["WebSearchToolParam"] | components["schemas"]["Mcp"] | components["schemas"]["CodeInterpreter"] | components["schemas"]["ImageGeneration"] | components["schemas"]["LocalShell"] | components["schemas"]["FunctionShellToolParam"] | components["schemas"]["CustomToolParam"] | components["schemas"]["NamespaceToolParam"] | components["schemas"]["ToolSearchToolParam"] | components["schemas"]["WebSearchPreviewToolParam"] | components["schemas"]["ApplyPatchToolParam"] | components["schemas"]["litellm__types__llms__openai__ComputerToolParam"] | components["schemas"]["ShellToolParam"] | components["schemas"]["OpenAIToolSearchToolParam"])[] | null;
/** Top Logprobs */
top_logprobs?: number | null;
/** Top P */
@@ -66074,7 +66084,7 @@ export interface operations {
/** Tool Choice */
tool_choice?: ("none" | "auto" | "required") | components["schemas"]["ToolChoiceAllowedParam"] | components["schemas"]["ToolChoiceTypesParam"] | components["schemas"]["ToolChoiceFunctionParam"] | components["schemas"]["ToolChoiceMcpParam"] | components["schemas"]["ToolChoiceCustomParam"] | components["schemas"]["ToolChoiceApplyPatchParam"] | components["schemas"]["ToolChoiceShellParam"] | null;
/** Tools */
- tools?: (components["schemas"]["FunctionToolParam"] | components["schemas"]["FileSearchToolParam"] | components["schemas"]["openai__types__responses__computer_tool_param__ComputerToolParam"] | components["schemas"]["ComputerUsePreviewToolParam"] | components["schemas"]["WebSearchToolParam"] | components["schemas"]["Mcp"] | components["schemas"]["CodeInterpreter"] | components["schemas"]["ImageGeneration"] | components["schemas"]["LocalShell"] | components["schemas"]["FunctionShellToolParam"] | components["schemas"]["CustomToolParam"] | components["schemas"]["NamespaceToolParam"] | components["schemas"]["ToolSearchToolParam"] | components["schemas"]["WebSearchPreviewToolParam"] | components["schemas"]["ApplyPatchToolParam"] | components["schemas"]["litellm__types__llms__openai__ComputerToolParam"] | components["schemas"]["ShellToolParam"])[] | null;
+ tools?: (components["schemas"]["FunctionToolParam"] | components["schemas"]["FileSearchToolParam"] | components["schemas"]["openai__types__responses__computer_tool_param__ComputerToolParam"] | components["schemas"]["ComputerUsePreviewToolParam"] | components["schemas"]["WebSearchToolParam"] | components["schemas"]["Mcp"] | components["schemas"]["CodeInterpreter"] | components["schemas"]["ImageGeneration"] | components["schemas"]["LocalShell"] | components["schemas"]["FunctionShellToolParam"] | components["schemas"]["CustomToolParam"] | components["schemas"]["NamespaceToolParam"] | components["schemas"]["ToolSearchToolParam"] | components["schemas"]["WebSearchPreviewToolParam"] | components["schemas"]["ApplyPatchToolParam"] | components["schemas"]["litellm__types__llms__openai__ComputerToolParam"] | components["schemas"]["ShellToolParam"] | components["schemas"]["OpenAIToolSearchToolParam"])[] | null;
/** Top Logprobs */
top_logprobs?: number | null;
/** Top P */
@@ -69538,7 +69548,7 @@ export interface operations {
/** Tool Choice */
tool_choice?: ("none" | "auto" | "required") | components["schemas"]["ToolChoiceAllowedParam"] | components["schemas"]["ToolChoiceTypesParam"] | components["schemas"]["ToolChoiceFunctionParam"] | components["schemas"]["ToolChoiceMcpParam"] | components["schemas"]["ToolChoiceCustomParam"] | components["schemas"]["ToolChoiceApplyPatchParam"] | components["schemas"]["ToolChoiceShellParam"] | null;
/** Tools */
- tools?: (components["schemas"]["FunctionToolParam"] | components["schemas"]["FileSearchToolParam"] | components["schemas"]["openai__types__responses__computer_tool_param__ComputerToolParam"] | components["schemas"]["ComputerUsePreviewToolParam"] | components["schemas"]["WebSearchToolParam"] | components["schemas"]["Mcp"] | components["schemas"]["CodeInterpreter"] | components["schemas"]["ImageGeneration"] | components["schemas"]["LocalShell"] | components["schemas"]["FunctionShellToolParam"] | components["schemas"]["CustomToolParam"] | components["schemas"]["NamespaceToolParam"] | components["schemas"]["ToolSearchToolParam"] | components["schemas"]["WebSearchPreviewToolParam"] | components["schemas"]["ApplyPatchToolParam"] | components["schemas"]["litellm__types__llms__openai__ComputerToolParam"] | components["schemas"]["ShellToolParam"])[] | null;
+ tools?: (components["schemas"]["FunctionToolParam"] | components["schemas"]["FileSearchToolParam"] | components["schemas"]["openai__types__responses__computer_tool_param__ComputerToolParam"] | components["schemas"]["ComputerUsePreviewToolParam"] | components["schemas"]["WebSearchToolParam"] | components["schemas"]["Mcp"] | components["schemas"]["CodeInterpreter"] | components["schemas"]["ImageGeneration"] | components["schemas"]["LocalShell"] | components["schemas"]["FunctionShellToolParam"] | components["schemas"]["CustomToolParam"] | components["schemas"]["NamespaceToolParam"] | components["schemas"]["ToolSearchToolParam"] | components["schemas"]["WebSearchPreviewToolParam"] | components["schemas"]["ApplyPatchToolParam"] | components["schemas"]["litellm__types__llms__openai__ComputerToolParam"] | components["schemas"]["ShellToolParam"] | components["schemas"]["OpenAIToolSearchToolParam"])[] | null;
/** Top Logprobs */
top_logprobs?: number | null;
/** Top P */
@@ -80141,7 +80151,7 @@ export interface operations {
/** Tool Choice */
tool_choice?: ("none" | "auto" | "required") | components["schemas"]["ToolChoiceAllowedParam"] | components["schemas"]["ToolChoiceTypesParam"] | components["schemas"]["ToolChoiceFunctionParam"] | components["schemas"]["ToolChoiceMcpParam"] | components["schemas"]["ToolChoiceCustomParam"] | components["schemas"]["ToolChoiceApplyPatchParam"] | components["schemas"]["ToolChoiceShellParam"] | null;
/** Tools */
- tools?: (components["schemas"]["FunctionToolParam"] | components["schemas"]["FileSearchToolParam"] | components["schemas"]["openai__types__responses__computer_tool_param__ComputerToolParam"] | components["schemas"]["ComputerUsePreviewToolParam"] | components["schemas"]["WebSearchToolParam"] | components["schemas"]["Mcp"] | components["schemas"]["CodeInterpreter"] | components["schemas"]["ImageGeneration"] | components["schemas"]["LocalShell"] | components["schemas"]["FunctionShellToolParam"] | components["schemas"]["CustomToolParam"] | components["schemas"]["NamespaceToolParam"] | components["schemas"]["ToolSearchToolParam"] | components["schemas"]["WebSearchPreviewToolParam"] | components["schemas"]["ApplyPatchToolParam"] | components["schemas"]["litellm__types__llms__openai__ComputerToolParam"] | components["schemas"]["ShellToolParam"])[] | null;
+ tools?: (components["schemas"]["FunctionToolParam"] | components["schemas"]["FileSearchToolParam"] | components["schemas"]["openai__types__responses__computer_tool_param__ComputerToolParam"] | components["schemas"]["ComputerUsePreviewToolParam"] | components["schemas"]["WebSearchToolParam"] | components["schemas"]["Mcp"] | components["schemas"]["CodeInterpreter"] | components["schemas"]["ImageGeneration"] | components["schemas"]["LocalShell"] | components["schemas"]["FunctionShellToolParam"] | components["schemas"]["CustomToolParam"] | components["schemas"]["NamespaceToolParam"] | components["schemas"]["ToolSearchToolParam"] | components["schemas"]["WebSearchPreviewToolParam"] | components["schemas"]["ApplyPatchToolParam"] | components["schemas"]["litellm__types__llms__openai__ComputerToolParam"] | components["schemas"]["ShellToolParam"] | components["schemas"]["OpenAIToolSearchToolParam"])[] | null;
/** Top Logprobs */
top_logprobs?: number | null;
/** Top P */