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]

Merge origin/main into feat/websearch-multi-query-schema

mateo-berri12f831e863e2
diff --cc litellm/integrations/websearch_interception/handler.py
index 093e0351c70,b7238629c85..6a4c67c7db1
--- a/litellm/integrations/websearch_interception/handler.py
+++ b/litellm/integrations/websearch_interception/handler.py
@@@ -44,7 -44,8 +44,9 @@@ from litellm.types.integrations.custom_
from litellm.types.integrations.websearch_interception import (
AnthropicSearchQuery,
AnthropicServerToolUseBlock,
+ RichWebSearchInput,
+ SearchFailed,
+ SearchOutcome,
WebSearchInterceptionConfig,
)
from litellm.types.llms.anthropic import AnthropicThinkingParam
@@@ -1177,11 -1144,7 +1145,9 @@@ class WebSearchInterceptionLogger(Custo
"""Execute litellm.asearch() and build a Responses API rerun patch."""
search_tasks: Final = [
(
- self._execute_search(tool_call["input"]["query"], kwargs=kwargs)
+ self._execute_search(
- tool_call["input"]["query"],
- kwargs=kwargs,
- rich=self._rich_search_input(tool_call["input"]),
++ tool_call["input"]["query"], kwargs=kwargs, rich=self._rich_search_input(tool_call["input"])
+ )
if isinstance(tool_call.get("input"), dict) and tool_call["input"].get("query")
else self._create_empty_search_result()
)
@@@ -1416,13 -1362,7 +1365,9 @@@
query = tool_call["input"].get("query")
if query:
verbose_logger.debug("WebSearchInterception: Queuing search for query='%s'", query)
- search_tasks.append(self._execute_search(query, kwargs=kwargs))
+ search_tasks.append(
- self._execute_search(
- query,
- kwargs=kwargs,
- rich=self._rich_search_input(tool_call["input"]),
- )
++ self._execute_search(query, kwargs=kwargs, rich=self._rich_search_input(tool_call["input"]))
+ )
else:
verbose_logger.debug("WebSearchInterception: Tool call %s has no query", tool_call["id"])
# Add empty result for tools without query
@@@ -1508,55 -1418,21 +1423,66 @@@
optional_params=optional_params_without_max_tokens,
kwargs=kwargs_for_followup,
)
- return patch, structured_results
+ return patch, search_outcomes
+
+ async def _short_circuit_search_outcome(self, query: str, kwargs: Mapping[str, object] | None) -> SearchOutcome:
+ try:
+ result: Final = (
+ await self._execute_search(query)
+ if kwargs is None
+ else await self._execute_search(query, kwargs=kwargs)
+ )
+ except Exception as e:
+ return WebSearchTransformation.search_outcome(e)
+ return WebSearchTransformation.search_outcome(result)
+ @staticmethod
+ def _rich_search_input(tool_input: object) -> RichWebSearchInput | None:
+ """
+ Extract the optional objective/search_queries pair from a tool input.
+
+ Returns None when the input carries neither, so callers can pass the
+ result straight through as ``_execute_search``'s ``rich`` argument.
+ """
+ if not isinstance(tool_input, Mapping):
+ return None
+ objective = tool_input.get("objective")
+ valid_objective = objective if isinstance(objective, str) and objective.strip() else None
+ raw_queries = tool_input.get("search_queries")
+ valid_queries: list[str] | None = None # mutable-ok: matches litellm.asearch's list[str] query parameter
+ if isinstance(raw_queries, Sequence) and not isinstance(raw_queries, str):
+ queries = [q for q in raw_queries if isinstance(q, str) and q.strip()]
+ if queries:
+ # Providers cap multi-query requests (Parallel drops queries
+ # past the fifth); trim here so nothing is silently ignored.
+ valid_queries = queries[:5]
+ if valid_objective is not None and valid_queries is not None:
+ return {"objective": valid_objective, "search_queries": valid_queries}
+ if valid_objective is not None:
+ return {"objective": valid_objective}
+ if valid_queries is not None:
+ return {"search_queries": valid_queries}
+ return None
+
+ @staticmethod
+ def _provider_supports_rich_search(search_provider: str | None) -> bool:
+ """Whether the provider's search config accepts objective + multi-query input."""
+ if not search_provider:
+ return False
+ try:
+ from litellm.utils import ProviderConfigManager
+ except ImportError:
+ return False
+ # SearchProviders is a str enum, so an unknown provider string simply
+ # misses the config map and returns None rather than raising.
+ config = ProviderConfigManager.get_provider_search_config(search_provider) # pyright: ignore[reportArgumentType] -- SearchProviders is a str enum, so the router's provider string hashes to the matching member; unknown strings miss the map and yield None
+ return config is not None and config.supports_rich_search_input()
+
async def _execute_search(
- self, query: str, kwargs: Mapping[str, object] | None = None
+ self,
+ query: str,
+ kwargs: Mapping[str, object] | None = None,
+ rich: RichWebSearchInput | None = None,
) -> tuple[str, SearchResponse | None]:
"""
Execute a single web search using router's search tools.
@@@ -1616,23 -1490,9 +1540,20 @@@
for key, value in search_litellm_params.items()
if key != "search_provider" and value is not None
}
+ # Forward the model's richer shape (objective + keyword queries)
+ # only to providers whose search API takes it natively; everyone
+ # else keeps the single query string the model also provided.
+ query_arg: str | list[str] = query # mutable-ok: litellm.asearch declares query as str | list[str]
+ if rich and self._provider_supports_rich_search(search_provider):
+ rich_queries = rich.get("search_queries")
+ if rich_queries:
+ query_arg = rich_queries
+ rich_objective = rich.get("objective")
+ if rich_objective and "objective" not in search_kwargs:
+ search_kwargs["objective"] = rich_objective
result: Final = (
await litellm.asearch(
- query=query_arg,
- search_provider=search_provider,
- **_NO_ASEARCH_NAMED,
- **search_kwargs,
- query=query, search_provider=search_provider, **_NO_ASEARCH_NAMED, **search_kwargs
++ query=query_arg, search_provider=search_provider, **_NO_ASEARCH_NAMED, **search_kwargs
)
if search_metadata is None
else await litellm.asearch(
@@@ -1861,12 -1712,9 +1776,9 @@@
if query:
verbose_logger.debug("WebSearchInterception: Queuing search for query='%s'", query)
- search_tasks.append(self._execute_search(query, kwargs=kwargs))
+ search_tasks.append(self._execute_search(query, kwargs=kwargs, rich=self._rich_search_input(tool_args)))
else:
- verbose_logger.debug(
- "WebSearchInterception: Tool call %s has no query",
- tool_call.get("id"),
- )
+ verbose_logger.debug("WebSearchInterception: Tool call %s has no query", tool_call.get("id"))
# Add empty result for tools without query
search_tasks.append(self._create_empty_search_result())
diff --cc litellm/types/integrations/websearch_interception.py
index ea5e6d51749,a7c2e7f2315..22233404fb3
--- a/litellm/types/integrations/websearch_interception.py
+++ b/litellm/types/integrations/websearch_interception.py
@@@ -27,22 -31,31 +31,47 @@@ class AnthropicServerToolUseBlock(BaseM
input: AnthropicSearchQuery
+class RichWebSearchInput(TypedDict, total=False):
+ """
+ Optional richer search shape a model may emit alongside ``query``.
+
+ Collected from the intercepted tool call and forwarded only to search
+ providers whose config reports ``supports_rich_search_input()``; every
+ other provider keeps receiving the single ``query`` string.
+ """
+
+ objective: ReadOnly[str]
+ """Natural-language description of the goal behind the search."""
+
+ search_queries: ReadOnly[list[str]] # mutable-ok: forwarded verbatim as litellm.asearch's list[str] query argument
+ """Two to five short keyword queries covering different angles."""
+
+
+ WebSearchToolResultErrorCode: TypeAlias = Literal[
+ "invalid_tool_input",
+ "unavailable",
+ "max_uses_exceeded",
+ "too_many_requests",
+ "query_too_long",
+ "request_too_large",
+ ]
+
+
+ @dataclass(frozen=True, slots=True)
+ class SearchSucceeded:
+ text: str
+ response: "SearchResponse | None"
+
+
+ @dataclass(frozen=True, slots=True)
+ class SearchFailed:
+ error_code: WebSearchToolResultErrorCode
+ message: str
+
+
+ SearchOutcome: TypeAlias = SearchSucceeded | SearchFailed
+
+
class WebSearchInterceptionConfig(TypedDict, total=False):
"""
Configuration parameters for WebSearchInterceptionLogger.
diff --cc tests/test_litellm/integrations/websearch_interception/test_websearch_agentic_loop_cap.py
index 40fd8c4e9e6,57e3ba59456..b7326b9048b
--- a/tests/test_litellm/integrations/websearch_interception/test_websearch_agentic_loop_cap.py
+++ b/tests/test_litellm/integrations/websearch_interception/test_websearch_agentic_loop_cap.py
@@@ -490,6 -494,135 +494,135 @@@ class TestOuterFramePostHookStillRuns
assert result["stop_reason"] == "end_turn"
+ def _response_asking_for_searches(*queries: str) -> dict:
+ return {
+ "id": "msg_123",
+ "type": "message",
+ "role": "assistant",
+ "model": "claude-sonnet-4-5",
+ "content": [
+ {"id": f"toolu_internal_{index}", "type": "tool_use", "name": INTERNAL_TOOL_NAME, "input": {"query": query}}
+ for index, query in enumerate(queries, start=1)
+ ],
+ "stop_reason": "tool_use",
+ "usage": {"input_tokens": 10, "output_tokens": 5},
+ }
+
+
+ class TestFailedSearchEndsTheTurn:
+ """
+ A search that failed used to come back to the client as an empty successful
+ ``web_search_tool_result`` while the model was re-asked the same query until
+ the loop cap tripped. When the client sent a native web search tool, the
+ turn now ends after the first failed search, with Anthropic's
+ ``web_search_tool_result_error`` object in the tool result and no follow-up
+ model call. An iteration where some search still succeeded keeps its
+ follow-up call.
+ """
+
+ def setup_method(self):
+ self.handler = BaseLLMHTTPHandler()
+ self.logger = WebSearchInterceptionLogger(enabled_providers=["anthropic"])
+ self.followup_calls: list[dict] = []
+
+ async def _fake_acreate(self, **call_kwargs):
+ self.followup_calls.append(call_kwargs)
+ return {
+ "id": "msg_followup",
+ "type": "message",
+ "role": "assistant",
+ "model": "claude-sonnet-4-5",
+ "content": [{"type": "text", "text": "final answer"}],
+ "stop_reason": "end_turn",
+ "usage": {"input_tokens": 20, "output_tokens": 5},
+ }
+
+ async def _run(self, response: dict, converted_stream: bool = False):
+ return await self.handler._call_agentic_completion_hooks(
+ response=response,
+ model="claude-sonnet-4-5",
+ messages=[{"role": "user", "content": "who won the world cup"}],
+ anthropic_messages_provider_config=MagicMock(),
+ anthropic_messages_optional_request_params={"tools": [get_litellm_web_search_tool()]},
+ logging_obj=_logging_obj(self.logger, converted_stream=converted_stream),
+ stream=False,
+ custom_llm_provider="anthropic",
+ kwargs={"_agentic_loop_depth": 0, "max_agentic_loops": 3, WEBSEARCH_EMIT_NATIVE_BLOCKS_KEY: True},
+ )
+
+ @pytest.mark.asyncio
+ async def test_all_failed_iteration_ends_the_turn_without_a_follow_up_call(self, monkeypatch):
+ monkeypatch.setattr("litellm.anthropic_interface.messages.acreate", self._fake_acreate)
+
+ with patch.object(
+ self.logger,
+ "_execute_search",
+ side_effect=AuthenticationError("401 Unauthorized", llm_provider="tavily", model="tavily"),
+ ):
+ result = await self._run(_response_asking_for_searches("who won the world cup"))
+
+ assert self.followup_calls == []
+ assert result["stop_reason"] == "end_turn"
+ assert INTERNAL_TOOL_NAME not in _tool_use_names(result)
+ assert _block_types(result) == ["server_tool_use", "web_search_tool_result"]
+ server_tool_use, tool_result = result["content"]
+ assert server_tool_use["id"].startswith("srvtoolu_")
+ assert server_tool_use["input"] == {"query": "who won the world cup"}
+ assert tool_result["tool_use_id"] == server_tool_use["id"]
+ assert tool_result["content"] == {"type": "web_search_tool_result_error", "error_code": "unavailable"}
+
+ @pytest.mark.asyncio
+ async def test_all_failed_iteration_streams_the_error_block(self, monkeypatch):
+ monkeypatch.setattr("litellm.anthropic_interface.messages.acreate", self._fake_acreate)
+
+ with patch.object(
+ self.logger,
+ "_execute_search",
+ side_effect=AuthenticationError("401 Unauthorized", llm_provider="tavily", model="tavily"),
+ ):
+ result = await self._run(_response_asking_for_searches("who won the world cup"), converted_stream=True)
+
+ assert self.followup_calls == []
+ assert isinstance(result, FakeAnthropicMessagesStreamIterator)
+ events = _stream_events(result.response)
+ started = [event["content_block"] for event in events if event["type"] == "content_block_start"]
+ assert [block["type"] for block in started] == ["server_tool_use", "web_search_tool_result"]
+ assert started[1]["tool_use_id"] == started[0]["id"]
+ assert started[1]["content"] == {"type": "web_search_tool_result_error", "error_code": "unavailable"}
+ assert [event["delta"]["stop_reason"] for event in events if event["type"] == "message_delta"] == ["end_turn"]
+
+ @pytest.mark.asyncio
+ async def test_mixed_iteration_keeps_the_follow_up_call(self, monkeypatch):
+ monkeypatch.setattr("litellm.anthropic_interface.messages.acreate", self._fake_acreate)
+
- async def search(query, kwargs=None):
++ async def search(query, kwargs=None, rich=None):
+ if query == "fails":
+ raise RateLimitError("slow down", llm_provider="tavily", model="tavily")
+ found = SearchResult(title="Result", url="https://example.com", snippet="A result.", date=None)
+ return ("Title: Result\nURL: https://example.com", SearchResponse(results=[found]))
+
+ with patch.object(self.logger, "_execute_search", side_effect=search):
+ result = await self._run(_response_asking_for_searches("fails", "works"))
+
+ assert len(self.followup_calls) == 1
+ tool_results = self.followup_calls[0]["messages"][-1]["content"]
+ assert [block["type"] for block in tool_results] == ["tool_result", "tool_result"]
+ assert tool_results[0]["content"] == "Search failed: litellm.RateLimitError: slow down"
+ assert tool_results[1]["content"] == "Title: Result\nURL: https://example.com"
+ assert result["stop_reason"] == "end_turn"
+ assert _block_types(result) == [
+ "server_tool_use",
+ "web_search_tool_result",
+ "server_tool_use",
+ "web_search_tool_result",
+ "text",
+ ]
+ assert result["content"][0]["input"] == {"query": "fails"}
+ assert result["content"][1]["content"] == {"type": "web_search_tool_result_error", "error_code": "too_many_requests"}
+ assert result["content"][2]["input"] == {"query": "works"}
+ assert result["content"][3]["content"][0]["url"] == "https://example.com"
+
+
class TestMaxAgenticLoopsConfigKnob:
def test_from_config_yaml_reads_the_knob(self):
logger = WebSearchInterceptionLogger.from_config_yaml(
diff --cc tests/test_litellm/integrations/websearch_interception/test_websearch_native_blocks.py
index c859f9b2f55,291fb5a5941..068a60e1fff
--- a/tests/test_litellm/integrations/websearch_interception/test_websearch_native_blocks.py
+++ b/tests/test_litellm/integrations/websearch_interception/test_websearch_native_blocks.py
@@@ -294,6 -307,145 +307,145 @@@ class TestBuildPlanAttachesBlocks
assert WEBSEARCH_NATIVE_BLOCKS_METADATA_KEY not in plan.metadata
+ class TestFailedSearchOutcome:
+ """A search that raises becomes a ``web_search_tool_result_error`` block, coded by exception type."""
+
+ @pytest.mark.parametrize(
+ ("error", "expected_code"),
+ [
+ (RateLimitError("slow down", llm_provider="tavily", model="tavily"), "too_many_requests"),
+ (BadRequestError("bad query", model="tavily", llm_provider="tavily"), "invalid_tool_input"),
+ (AuthenticationError("401 Unauthorized", llm_provider="tavily", model="tavily"), "unavailable"),
+ (APIConnectionError("connection refused", llm_provider="tavily", model="tavily"), "unavailable"),
+ (Timeout("timed out", model="tavily", llm_provider="tavily"), "unavailable"),
+ (RuntimeError("boom"), "unavailable"),
+ ],
+ )
+ def test_error_block_carries_the_mapped_error_code(self, error, expected_code):
+ outcome = WebSearchTransformation.search_outcome(error)
+
+ assert outcome == SearchFailed(error_code=expected_code, message=str(error))
+ assert WebSearchTransformation.build_web_search_outcome_block("srvtoolu_x", outcome) == {
+ "type": "web_search_tool_result",
+ "tool_use_id": "srvtoolu_x",
+ "content": {"type": "web_search_tool_result_error", "error_code": expected_code},
+ }
+ assert WebSearchTransformation.search_outcome_text(outcome) == f"Search failed: {error}"
+
+ def test_succeeded_outcome_still_yields_result_items(self):
+ outcome = WebSearchTransformation.search_outcome(("Title: x", _make_search_response()))
+
+ assert outcome == SearchSucceeded(text="Title: x", response=_make_search_response())
+ block = WebSearchTransformation.build_web_search_outcome_block("srvtoolu_x", outcome)
+ assert [item["type"] for item in block["content"]] == ["web_search_result", "web_search_result"]
+ assert block["content"][0]["url"] == "https://docs.litellm.ai/"
+ assert WebSearchTransformation.search_outcome_text(outcome) == "Title: x"
+
+ @pytest.mark.asyncio
+ async def test_all_failed_iteration_terminates_when_native_blocks_are_emitted(self):
+ logger = WebSearchInterceptionLogger(enabled_providers=["bedrock"])
+ tool_calls = [
+ {"id": "toolu_one", "type": "tool_use", "name": "litellm_web_search", "input": {"query": "q1"}},
+ {"id": "toolu_two", "type": "tool_use", "name": "litellm_web_search", "input": {"query": "q2"}},
+ ]
+
+ with patch.object(
+ logger,
+ "_execute_search",
+ side_effect=AuthenticationError("401 Unauthorized", llm_provider="tavily", model="tavily"),
+ ):
+ plan = await logger.async_build_agentic_loop_plan(
+ tools={"tool_calls": tool_calls, "thinking_blocks": []},
+ model="bedrock/claude",
+ messages=[{"role": "user", "content": "hi"}],
+ response=MagicMock(),
+ anthropic_messages_provider_config=None,
+ anthropic_messages_optional_request_params={},
+ logging_obj=MagicMock(model_call_details={}),
+ stream=False,
+ kwargs={WEBSEARCH_EMIT_NATIVE_BLOCKS_KEY: True},
+ )
+
+ assert plan.run_agentic_loop is False
+ assert plan.terminate is True
+ assert plan.stop_reason == "web_search_failed"
+ blocks = plan.metadata[WEBSEARCH_NATIVE_BLOCKS_METADATA_KEY]
+ assert [b["type"] for b in blocks] == [
+ "server_tool_use",
+ "web_search_tool_result",
+ "server_tool_use",
+ "web_search_tool_result",
+ ]
+ assert blocks[1]["tool_use_id"] == blocks[0]["id"]
+ assert blocks[1]["content"] == {"type": "web_search_tool_result_error", "error_code": "unavailable"}
+ assert blocks[3]["tool_use_id"] == blocks[2]["id"]
+ assert blocks[3]["content"] == {"type": "web_search_tool_result_error", "error_code": "unavailable"}
+
+ @pytest.mark.asyncio
+ async def test_all_failed_iteration_keeps_the_follow_up_without_native_blocks(self):
+ logger = WebSearchInterceptionLogger(enabled_providers=["bedrock"])
+ tool_calls = [
+ {"id": "toolu_one", "type": "tool_use", "name": "litellm_web_search", "input": {"query": "q1"}},
+ ]
+
+ with patch.object(
+ logger,
+ "_execute_search",
+ side_effect=AuthenticationError("401 Unauthorized", llm_provider="tavily", model="tavily"),
+ ):
+ plan = await logger.async_build_agentic_loop_plan(
+ tools={"tool_calls": tool_calls, "thinking_blocks": []},
+ model="bedrock/claude",
+ messages=[{"role": "user", "content": "hi"}],
+ response=MagicMock(),
+ anthropic_messages_provider_config=None,
+ anthropic_messages_optional_request_params={},
+ logging_obj=MagicMock(model_call_details={}),
+ stream=False,
+ kwargs={},
+ )
+
+ assert plan.run_agentic_loop is True
+ assert plan.terminate is False
+ assert plan.request_patch is not None
+ tool_results = plan.request_patch.messages[-1]["content"]
+ assert "Search failed: litellm.AuthenticationError: 401 Unauthorized" in tool_results[0]["content"]
+
+ @pytest.mark.asyncio
+ async def test_mixed_iteration_keeps_the_follow_up_and_pairs_each_block(self):
+ logger = WebSearchInterceptionLogger(enabled_providers=["bedrock"])
+ tool_calls = [
+ {"id": "toolu_one", "type": "tool_use", "name": "litellm_web_search", "input": {"query": "fails"}},
+ {"id": "toolu_two", "type": "tool_use", "name": "litellm_web_search", "input": {"query": "works"}},
+ ]
+
- async def search(query, kwargs=None):
++ async def search(query, kwargs=None, rich=None):
+ if query == "fails":
+ raise RateLimitError("slow down", llm_provider="tavily", model="tavily")
+ return ("Title: x", _make_search_response())
+
+ with patch.object(logger, "_execute_search", side_effect=search):
+ plan = await logger.async_build_agentic_loop_plan(
+ tools={"tool_calls": tool_calls, "thinking_blocks": []},
+ model="bedrock/claude",
+ messages=[{"role": "user", "content": "hi"}],
+ response=MagicMock(),
+ anthropic_messages_provider_config=None,
+ anthropic_messages_optional_request_params={},
+ logging_obj=MagicMock(model_call_details={}),
+ stream=False,
+ kwargs={WEBSEARCH_EMIT_NATIVE_BLOCKS_KEY: True},
+ )
+
+ assert plan.run_agentic_loop is True
+ assert plan.terminate is False
+ blocks = plan.metadata[WEBSEARCH_NATIVE_BLOCKS_METADATA_KEY]
+ assert blocks[0]["input"] == {"query": "fails"}
+ assert blocks[1]["content"] == {"type": "web_search_tool_result_error", "error_code": "too_many_requests"}
+ assert blocks[2]["input"] == {"query": "works"}
+ assert blocks[3]["content"][0]["url"] == "https://docs.litellm.ai/"
+
+
class TestPostHookInjectsBlocks:
"""The post-hook must prepend blocks; absent metadata is a no-op."""