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(websearch): restore snippet text in native web_search_tool_result blocks (LIT-5315) (#36228)

tin-berrie50a42051c53
diff --git a/litellm/integrations/websearch_interception/handler.py b/litellm/integrations/websearch_interception/handler.py
index 71388134e98..9748db2dcd2 100644
--- a/litellm/integrations/websearch_interception/handler.py
+++ b/litellm/integrations/websearch_interception/handler.py
@@ -9,7 +9,7 @@ server-side using litellm router's search tools.
import asyncio
import math
import uuid
-from collections.abc import AsyncIterator, Mapping
+from collections.abc import AsyncIterator, Mapping, Sequence
from typing import TYPE_CHECKING, Any, Final, cast
import litellm
@@ -37,6 +37,8 @@ from litellm.types.integrations.custom_logger import (
AgenticLoopRequestPatch,
)
from litellm.types.integrations.websearch_interception import (
+ AnthropicSearchQuery,
+ AnthropicServerToolUseBlock,
WebSearchInterceptionConfig,
)
from litellm.types.llms.openai import AllMessageValues
@@ -833,22 +835,48 @@ class WebSearchInterceptionLogger(CustomLogger):
def _build_native_result_blocks(
tool_calls: list[dict],
structured_results: list[SearchResponse | None],
- ) -> list[dict[str, object]]:
- """Build one ``web_search_tool_result`` block per tool_call."""
- blocks: Final[list[dict[str, object]]] = []
- for i, tool_call in enumerate(tool_calls):
- tool_use_id = tool_call.get("id") or ""
- structured = structured_results[i] if i < len(structured_results) else None
- blocks.append(
- WebSearchTransformation.build_web_search_tool_result_block(
- tool_use_id=tool_use_id,
- search_response=structured,
- )
+ ) -> tuple[Mapping[str, object], ...]:
+ """
+ Build a ``server_tool_use`` + ``web_search_tool_result`` pair per tool_call.
+
+ The pair is what Anthropic's spec requires: a bare result block, or one
+ keyed by the model's ``toolu_...`` id instead of a ``srvtoolu_...`` one,
+ is rejected on replay ("String should match pattern '^srvtoolu_'") and
+ leaves native clients without a search to attach the sources to.
+ """
+ return tuple(
+ block
+ for i, tool_call in enumerate(tool_calls)
+ for block in WebSearchInterceptionLogger._native_result_pair(
+ query=WebSearchInterceptionLogger._tool_call_query(tool_call),
+ search_response=structured_results[i] if i < len(structured_results) else None,
)
- return blocks
+ )
+
+ @staticmethod
+ def _tool_call_query(tool_call: Mapping[str, object]) -> str:
+ tool_input: Final = tool_call.get("input")
+ if not isinstance(tool_input, Mapping):
+ return ""
+ query: Final = tool_input.get("query")
+ return query if isinstance(query, str) else ""
+
+ @staticmethod
+ def _native_result_pair(
+ query: str,
+ search_response: SearchResponse | None,
+ ) -> tuple[Mapping[str, object], Mapping[str, object]]:
+ tool_use_id: Final = f"srvtoolu_{uuid.uuid4().hex}"
+ return (
+ AnthropicServerToolUseBlock(id=tool_use_id, input=AnthropicSearchQuery(query=query)).model_dump(),
+ WebSearchTransformation.build_web_search_tool_result_block(
+ tool_use_id=tool_use_id,
+ search_response=search_response,
+ ),
+ )
@staticmethod
- def _inject_native_blocks(response: Any, native_blocks: list[dict[str, object]]) -> Any:
+ def _inject_native_blocks(response: Any, native_blocks: Sequence[Mapping[str, object]]) -> Any:
"""Prepend native blocks to response content, dict or object form."""
if not native_blocks:
return response
diff --git a/litellm/integrations/websearch_interception/transformation.py b/litellm/integrations/websearch_interception/transformation.py
index 795810a7c40..199ab020559 100644
--- a/litellm/integrations/websearch_interception/transformation.py
+++ b/litellm/integrations/websearch_interception/transformation.py
@@ -412,6 +412,15 @@ class WebSearchTransformation:
block that should accompany the model's text reply when the original
request used a native ``web_search_*`` tool.
+ The spec'd shape carries page text only in ``encrypted_content``, an
+ opaque server-issued blob that we cannot mint. Emitting the four spec
+ fields alone would drop the snippet entirely, leaving the client (and
+ the model, on any replayed follow-up turn) with URLs and titles but no
+ evidence to answer from, forcing a fetch per result. So the snippet is
+ carried in an additive ``snippet`` key alongside the spec fields.
+ ``encrypted_content`` stays empty rather than holding plaintext, which
+ would assert encryption semantics that do not hold.
+
Spec reference:
https://docs.anthropic.com/en/api/web-search-tool
@@ -438,6 +447,7 @@ class WebSearchTransformation:
"title": title,
"page_age": page_age,
"encrypted_content": "",
+ "snippet": getattr(r, "snippet", "") or "",
}
)
return {
diff --git a/litellm/llms/anthropic/common_utils.py b/litellm/llms/anthropic/common_utils.py
index 314cfef6d84..9aa5a4f465f 100644
--- a/litellm/llms/anthropic/common_utils.py
+++ b/litellm/llms/anthropic/common_utils.py
@@ -4,9 +4,12 @@ This file contains common utils for anthropic calls.
import copy
import re
-from typing import Any, Final
+from collections.abc import Mapping, Sequence
+from types import MappingProxyType
+from typing import Any, Final, Literal
import httpx
+from pydantic import BaseModel, ConfigDict, TypeAdapter, ValidationError
import litellm
from litellm.litellm_core_utils.prompt_templates.common_utils import (
@@ -1057,6 +1060,152 @@ def sanitize_tool_use_ids_in_anthropic_messages(messages: list[Any]) -> list[Any
return out
+class _ReplayedSearchQuery(BaseModel):
+ model_config = ConfigDict(extra="allow")
+
+ query: str = ""
+
+
+class _ReplayedWebSearchResult(BaseModel):
+ model_config = ConfigDict(extra="allow")
+
+ type: Literal["web_search_result"]
+ url: str = ""
+ title: str = ""
+ snippet: str = ""
+ encrypted_content: str = ""
+
+
+class _ReplayedWebSearchToolResult(BaseModel):
+ model_config = ConfigDict(extra="allow")
+
+ type: Literal["web_search_tool_result"]
+ tool_use_id: str
+ content: tuple[_ReplayedWebSearchResult, ...]
+
+
+class _ReplayedServerToolUse(BaseModel):
+ model_config = ConfigDict(extra="allow")
+
+ type: Literal["server_tool_use"]
+ id: str
+ input: _ReplayedSearchQuery = _ReplayedSearchQuery()
+
+
+class _TextBlock(BaseModel):
+ type: Literal["text"] = "text"
+ text: str
+
+
+_WEB_SEARCH_TOOL_RESULT_ADAPTER: Final = TypeAdapter(_ReplayedWebSearchToolResult)
+_SERVER_TOOL_USE_ADAPTER: Final = TypeAdapter(_ReplayedServerToolUse)
+
+
+def _flattenable_web_search_tool_result(block: object) -> _ReplayedWebSearchToolResult | None:
+ """
+ The parsed block when it is a ``web_search_tool_result`` carrying no
+ ``encrypted_content``, else None for anything Anthropic itself issued.
+
+ An empty ``content`` list is flattenable too. It is what the interceptor emits
+ when a search legitimately returns nothing and when a search raises, and it
+ carries neither evidence to preserve nor an ``encrypted_content`` to respect,
+ so leaving it in place only buys the 400 this whole function exists to avoid.
+ """
+ try:
+ parsed: Final = _WEB_SEARCH_TOOL_RESULT_ADAPTER.validate_python(block)
+ except ValidationError:
+ return None
+ if any(result.encrypted_content for result in parsed.content):
+ return None
+ return parsed
+
+
+def _replayed_server_tool_use(block: object) -> _ReplayedServerToolUse | None:
+ try:
+ return _SERVER_TOOL_USE_ADAPTER.validate_python(block)
+ except ValidationError:
+ return None
+
+
+def _render_web_search_results(query: str, results: tuple[_ReplayedWebSearchResult, ...]) -> str:
+ header: Final = f"Web search results for '{query}':" if query else "Web search results:"
+ if not results:
+ return f"{header}\n\nNo results were returned."
+ body: Final = "\n\n".join(
+ "\n".join(
+ line
+ for line in (
+ f"Title: {result.title}" if result.title else "",
+ f"URL: {result.url}" if result.url else "",
+ f"Snippet: {result.snippet}" if result.snippet else "",
+ )
+ if line
+ )
+ for result in results
+ )
+ return f"{header}\n\n{body}" if body else header
+
+
+def _rewrite_replayed_web_search_block(
+ block: object,
+ flattenable: Mapping[str, _ReplayedWebSearchToolResult],
+ queries: Mapping[str, str],
+) -> object | None:
+ parsed_result: Final = _flattenable_web_search_tool_result(block)
+ if parsed_result is not None:
+ return _TextBlock(
+ text=_render_web_search_results(queries.get(parsed_result.tool_use_id, ""), parsed_result.content)
+ ).model_dump()
+ parsed_use: Final = _replayed_server_tool_use(block)
+ if parsed_use is not None and parsed_use.id in flattenable:
+ return None
+ return block
+
+
+def _flatten_web_search_results_in_message(message: object) -> object:
+ if not isinstance(message, Mapping) or not isinstance(message.get("content"), Sequence):
+ return message
+ content: Final = message["content"]
+ if isinstance(content, str):
+ return message
+ flattenable: Final = MappingProxyType(
+ {
+ parsed.tool_use_id: parsed
+ for parsed in (_flattenable_web_search_tool_result(block) for block in content)
+ if parsed is not None
+ }
+ )
+ if not flattenable:
+ return message
+ queries: Final = MappingProxyType(
+ {
+ parsed.id: parsed.input.query
+ for parsed in (_replayed_server_tool_use(block) for block in content)
+ if parsed is not None
+ }
+ )
+ rewritten: Final = tuple(_rewrite_replayed_web_search_block(block, flattenable, queries) for block in content)
+ return {**message, "content": [b for b in rewritten if b is not None]} # mutable-ok: JSON wire format
+
+
+def flatten_unencrypted_web_search_results_in_anthropic_messages( # mutable-ok: as sibling sanitizers
+ messages: list[Any],
+) -> list[Any]:
+ """
+ Return a new message list with replayed ``web_search_tool_result`` blocks that
+ carry no ``encrypted_content`` rewritten into plain ``text`` blocks holding the
+ same title / url / snippet evidence.
+
+ ``encrypted_content`` is an opaque blob only Anthropic's own search backend can
+ mint, so blocks synthesized by LiteLLM (websearch interception against a search
+ provider) are rejected with ``Invalid encrypted_content in search_result block``
+ when a native client loops them back as history. Flattening them keeps the
+ evidence in the conversation instead of 400ing the follow-up turn, and leaves
+ genuine Anthropic-issued blocks untouched.
+ """
+ return [_flatten_web_search_results_in_message(m) for m in messages] # mutable-ok: JSON wire format
+
+
def process_anthropic_headers(headers: httpx.Headers | dict) -> dict:
openai_headers: Final = {}
if "anthropic-ratelimit-requests-limit" in headers:
diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/handler.py b/litellm/llms/anthropic/experimental_pass_through/messages/handler.py
index 3ef298aa336..c4b5cc628e2 100644
--- a/litellm/llms/anthropic/experimental_pass_through/messages/handler.py
+++ b/litellm/llms/anthropic/experimental_pass_through/messages/handler.py
@@ -14,6 +14,7 @@ from typing import Any, Final, cast
import litellm
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
from litellm.llms.anthropic.common_utils import (
+ flatten_unencrypted_web_search_results_in_anthropic_messages,
sanitize_tool_use_ids_in_anthropic_messages,
strip_empty_text_blocks_from_anthropic_messages,
)
@@ -222,6 +223,7 @@ async def anthropic_messages(
# Replay of cross-provider tool history (e.g. kimi -> Anthropic) may carry
# ids like ``functions.Bash:0`` that violate Anthropic's id pattern.
messages = sanitize_tool_use_ids_in_anthropic_messages(messages)
+ messages = flatten_unencrypted_web_search_results_in_anthropic_messages(messages)
from litellm.integrations.anthropic_cache_control_hook import (
AnthropicCacheControlHook,
@@ -413,6 +415,7 @@ def anthropic_messages_handler(
if not kwargs.pop("_litellm_messages_presanitized", False):
messages = strip_empty_text_blocks_from_anthropic_messages(messages)
messages = sanitize_tool_use_ids_in_anthropic_messages(messages)
+ messages = flatten_unencrypted_web_search_results_in_anthropic_messages(messages)
from litellm.integrations.anthropic_cache_control_hook import (
AnthropicCacheControlHook,
diff --git a/litellm/types/integrations/websearch_interception.py b/litellm/types/integrations/websearch_interception.py
index 05537da67d7..90713b270be 100644
--- a/litellm/types/integrations/websearch_interception.py
+++ b/litellm/types/integrations/websearch_interception.py
@@ -2,7 +2,28 @@
Type definitions for WebSearch Interception integration.
"""
-from typing import TypedDict
+from typing import Literal, TypedDict
+
+from pydantic import BaseModel
+
+
+class AnthropicSearchQuery(BaseModel):
+ """``input`` of an Anthropic ``server_tool_use`` block for a web search."""
+
+ query: str
+
+
+class AnthropicServerToolUseBlock(BaseModel):
+ """
+ The ``server_tool_use`` block that must accompany a ``web_search_tool_result``.
+
+ Anthropic requires the pair, with a ``srvtoolu_``-prefixed id shared by both.
+ """
+
+ type: Literal["server_tool_use"] = "server_tool_use"
+ id: str
+ name: Literal["web_search"] = "web_search"
+ input: AnthropicSearchQuery
class WebSearchInterceptionConfig(TypedDict, total=False):
diff --git a/tests/test_litellm/integrations/websearch_interception/test_websearch_native_blocks.py b/tests/test_litellm/integrations/websearch_interception/test_websearch_native_blocks.py
index 544abab8dcf..c859f9b2f55 100644
--- a/tests/test_litellm/integrations/websearch_interception/test_websearch_native_blocks.py
+++ b/tests/test_litellm/integrations/websearch_interception/test_websearch_native_blocks.py
@@ -134,6 +134,30 @@ class TestBuildWebSearchToolResultBlock:
assert first["title"] == "LiteLLM Docs"
assert first["page_age"] == "2025-01-15"
assert first["encrypted_content"] == ""
+ assert first["snippet"] == "Unified interface for LLMs."
+
+ def test_snippet_carried_for_every_result(self):
+ # The snippet is the only field carrying page text. Losing it leaves the
+ # client and the model with nothing to answer from, forcing a fetch per
+ # result.
+ block = WebSearchTransformation.build_web_search_tool_result_block(
+ tool_use_id="toolu_abc",
+ search_response=_make_search_response(),
+ )
+ assert [r["snippet"] for r in block["content"]] == [
+ "Unified interface for LLMs.",
+ "Pay-per-use pricing model.",
+ ]
+
+ def test_missing_snippet_degrades_to_empty_string(self):
+ response = SearchResponse(
+ results=[SearchResult(title="T", url="https://x/", snippet="")]
+ )
+ block = WebSearchTransformation.build_web_search_tool_result_block(
+ tool_use_id="toolu_abc",
+ search_response=response,
+ )
+ assert block["content"][0]["snippet"] == ""
def test_handles_none_search_response(self):
block = WebSearchTransformation.build_web_search_tool_result_block(
@@ -223,11 +247,15 @@ class TestBuildPlanAttachesBlocks:
)
blocks = plan.metadata.get(WEBSEARCH_NATIVE_BLOCKS_METADATA_KEY)
- assert isinstance(blocks, list)
- assert len(blocks) == 1
- assert blocks[0]["type"] == "web_search_tool_result"
- assert blocks[0]["tool_use_id"] == "toolu_one"
- assert blocks[0]["content"][0]["url"] == "https://docs.litellm.ai/"
+ assert isinstance(blocks, tuple)
+ assert [b["type"] for b in blocks] == [
+ "server_tool_use",
+ "web_search_tool_result",
+ ]
+ assert blocks[0]["id"].startswith("srvtoolu_")
+ assert blocks[0]["input"] == {"query": "what is litellm"}
+ assert blocks[1]["tool_use_id"] == blocks[0]["id"]
+ assert blocks[1]["content"][0]["url"] == "https://docs.litellm.ai/"
@pytest.mark.asyncio
async def test_metadata_does_not_carry_blocks_when_flag_absent(self):
@@ -479,6 +507,9 @@ class TestLegacyPathMatchesNewPath:
kwargs={WEBSEARCH_EMIT_NATIVE_BLOCKS_KEY: True},
)
- assert out["content"][0]["type"] == "web_search_tool_result"
- assert out["content"][0]["tool_use_id"] == "toolu_legacy"
- assert out["content"][1]["type"] == "text"
+ assert [b["type"] for b in out["content"]] == [
+ "server_tool_use",
+ "web_search_tool_result",
+ "text",
+ ]
+ assert out["content"][1]["tool_use_id"] == out["content"][0]["id"]
diff --git a/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_anthropic_experimental_pass_through_messages_handler.py b/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_anthropic_experimental_pass_through_messages_handler.py
index df3db3d2c57..f11324ca376 100644
--- a/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_anthropic_experimental_pass_through_messages_handler.py
+++ b/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_anthropic_experimental_pass_through_messages_handler.py
@@ -732,6 +732,61 @@ def test_handler_skips_strip_when_presanitized():
assert result is not None
+def test_handler_flattens_replayed_unencrypted_web_search_results():
+ """Synthesized search blocks replayed as history must reach the provider as text."""
+ from litellm.llms.anthropic.experimental_pass_through.messages import handler
+
+ captured = {}
+
+ def fake_base_handler(*args, **kwargs):
+ captured.update(kwargs)
+ return "stub"
+
+ with patch.object(
+ handler.base_llm_http_handler,
+ "anthropic_messages_handler",
+ side_effect=fake_base_handler,
+ ):
+ handler.anthropic_messages_handler(
+ max_tokens=10,
+ messages=[
+ {"role": "user", "content": "latest litellm version?"},
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "server_tool_use",
+ "id": "srvtoolu_1",
+ "name": "web_search",
+ "input": {"query": "latest litellm version"},
+ },
+ {
+ "type": "web_search_tool_result",
+ "tool_use_id": "srvtoolu_1",
+ "content": [
+ {
+ "type": "web_search_result",
+ "url": "https://github.com/BerriAI/litellm/releases",
+ "title": "Releases",
+ "page_age": None,
+ "encrypted_content": "",
+ "snippet": "Latest release v1.95.0",
+ }
+ ],
+ },
+ ],
+ },
+ {"role": "user", "content": "which version?"},
+ ],
+ model="anthropic/claude-3-5-sonnet-20241022",
+ custom_llm_provider="anthropic",
+ )
+
+ replayed = captured["messages"][1]["content"]
+ assert [b["type"] for b in replayed] == ["text"]
+ assert "Snippet: Latest release v1.95.0" in replayed[0]["text"]
+
+
def test_presanitized_flag_not_leaked_to_provider_params():
"""The private sentinel must be popped, never forwarded as a request param."""
from litellm.llms.anthropic.experimental_pass_through.messages import handler
diff --git a/tests/test_litellm/llms/anthropic/test_anthropic_common_utils.py b/tests/test_litellm/llms/anthropic/test_anthropic_common_utils.py
index 6ab0f2c08ab..9df72108332 100644
--- a/tests/test_litellm/llms/anthropic/test_anthropic_common_utils.py
+++ b/tests/test_litellm/llms/anthropic/test_anthropic_common_utils.py
@@ -10,8 +10,10 @@ Verifies that:
- ANTHROPIC_API_KEY / ANTHROPIC_API_BASE take precedence over their aliases.
"""
+import json
import os
import sys
+from types import SimpleNamespace
from unittest.mock import patch
import pytest
@@ -1457,6 +1459,190 @@ class TestAnthropicThinkingSignatureSelfHeal:
out = strip_empty_text_blocks_from_anthropic_messages(msgs)
assert [b["type"] for b in out[0]["content"]] == ["tool_result"]
+ def test_flatten_unencrypted_web_search_results_keeps_snippet_evidence(self):
+ from litellm.llms.anthropic.common_utils import (
+ flatten_unencrypted_web_search_results_in_anthropic_messages,
+ )
+
+ msgs = [
+ {"role": "user", "content": "latest litellm version?"},
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "server_tool_use",
+ "id": "srvtoolu_1",
+ "name": "web_search",
+ "input": {"query": "latest litellm version"},
+ },
+ {
+ "type": "web_search_tool_result",
+ "tool_use_id": "srvtoolu_1",
+ "content": [
+ {
+ "type": "web_search_result",
+ "url": "https://github.com/BerriAI/litellm/releases",
+ "title": "Releases",
+ "page_age": None,
+ "encrypted_content": "",
+ "snippet": "Latest release v1.95.0",
+ }
+ ],
+ },
+ {"type": "text", "text": "v1.95.0"},
+ ],
+ },
+ ]
+
+ out = flatten_unencrypted_web_search_results_in_anthropic_messages(msgs)
+
+ assert out[0] is msgs[0]
+ assert [b["type"] for b in out[1]["content"]] == ["text", "text"]
+ flattened = out[1]["content"][0]["text"]
+ assert "Web search results for 'latest litellm version':" in flattened
+ assert "URL: https://github.com/BerriAI/litellm/releases" in flattened
+ assert "Snippet: Latest release v1.95.0" in flattened
+ assert msgs[1]["content"][0]["type"] == "server_tool_use"
+
+ @pytest.mark.parametrize("results", [[], None], ids=["empty_list", "search_raised"])
+ def test_flatten_unencrypted_web_search_results_flattens_a_resultless_search(self, results):
+ """A search that found nothing, or that raised, still has to be flattened.
+
+ Both cases reach the client as ``content: []``, and leaving that block in
+ place ships an unsupported tag to Bedrock on the next turn just as surely
+ as a populated one does.
+ """
+ from litellm.integrations.websearch_interception.transformation import (
+ WebSearchTransformation,
+ )
+ from litellm.llms.anthropic.common_utils import (
+ flatten_unencrypted_web_search_results_in_anthropic_messages,
+ )
+
+ block = WebSearchTransformation.build_web_search_tool_result_block(
+ tool_use_id="srvtoolu_1",
+ search_response=None if results is None else SimpleNamespace(results=results),
+ )
+ assert block["content"] == [], "fixture drifted from what the interceptor emits"
+
+ msgs = [
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "server_tool_use",
+ "id": "srvtoolu_1",
+ "name": "web_search",
+ "input": {"query": "who won"},
+ },
+ block,
+ {"type": "text", "text": "I could not find that."},
+ ],
+ }
+ ]
+
+ out = flatten_unencrypted_web_search_results_in_anthropic_messages(msgs)
+
+ assert [b["type"] for b in out[0]["content"]] == ["text", "text"]
+ assert out[0]["content"][0]["text"] == ("Web search results for 'who won':\n\nNo results were returned.")
+
+ @pytest.mark.parametrize("results", [[SimpleNamespace(title="Rome", url="u", snippet="s", date=None)], []])
+ def test_flatten_unencrypted_web_search_results_is_idempotent(self, results):
+ """Flattening twice must equal flattening once.
+
+ The agentic loop re-enters the same entry point for its follow-up call and
+ hands it the original history, so this runs again on already-flattened
+ messages once per iteration. A pass that appended instead of replacing
+ would duplicate the evidence on every loop.
+ """
+ from litellm.integrations.websearch_interception.transformation import (
+ WebSearchTransformation,
+ )
+ from litellm.llms.anthropic.common_utils import (
+ flatten_unencrypted_web_search_results_in_anthropic_messages,
+ )
+
+ msgs = [
+ {
+ "role": "assistant",
+ "content": [
+ {"type": "server_tool_use", "id": "srvtoolu_1", "name": "web_search", "input": {"query": "when"}},
+ WebSearchTransformation.build_web_search_tool_result_block(
+ tool_use_id="srvtoolu_1",
+ search_response=SimpleNamespace(results=results),
+ ),
+ {"type": "text", "text": "753 BC."},
+ ],
+ }
+ ]
+
+ once = flatten_unencrypted_web_search_results_in_anthropic_messages(msgs)
+ twice = flatten_unencrypted_web_search_results_in_anthropic_messages(once)
+
+ assert [b["type"] for b in once[0]["content"]] == ["text", "text"]
+ assert json.dumps(twice) == json.dumps(once)
+
+ def test_flatten_unencrypted_web_search_results_preserves_real_anthropic_blocks(self):
+ from litellm.llms.anthropic.common_utils import (
+ flatten_unencrypted_web_search_results_in_anthropic_messages,
+ )
+
+ msgs = [
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "server_tool_use",
+ "id": "srvtoolu_1",
+ "name": "web_search",
+ "input": {"query": "q"},
+ },
+ {
+ "type": "web_search_tool_result",
+ "tool_use_id": "srvtoolu_1",
+ "content": [
+ {
+ "type": "web_search_result",
+ "url": "https://example.com",
+ "title": "Example",
+ "page_age": None,
+ "encrypted_content": "EqgfCioIARgBIiQ4",
+ }
+ ],
+ },
+ ],
+ }
+ ]
+
+ out = flatten_unencrypted_web_search_results_in_anthropic_messages(msgs)
+
+ assert out[0] is msgs[0]
+
+ def test_flatten_unencrypted_web_search_results_leaves_error_blocks_alone(self):
+ from litellm.llms.anthropic.common_utils import (
+ flatten_unencrypted_web_search_results_in_anthropic_messages,
+ )
+
+ msgs = [
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "web_search_tool_result",
+ "tool_use_id": "srvtoolu_1",
+ "content": {
+ "type": "web_search_tool_result_error",
+ "error_code": "max_uses_exceeded",
+ },
+ }
+ ],
+ }
+ ]
+
+ out = flatten_unencrypted_web_search_results_in_anthropic_messages(msgs)
+
+ assert out[0] is msgs[0]
+
def test_sanitize_tool_use_ids_in_anthropic_messages(self):
from litellm.llms.anthropic.common_utils import (
sanitize_tool_use_ids_in_anthropic_messages,
diff --git a/tests/test_litellm/llms/bedrock/messages/invoke_transformations/test_anthropic_claude3_transformation.py b/tests/test_litellm/llms/bedrock/messages/invoke_transformations/test_anthropic_claude3_transformation.py
index 3b8b4af78d9..76bb11cc26d 100644
--- a/tests/test_litellm/llms/bedrock/messages/invoke_transformations/test_anthropic_claude3_transformation.py
+++ b/tests/test_litellm/llms/bedrock/messages/invoke_transformations/test_anthropic_claude3_transformation.py
@@ -4,6 +4,7 @@ import json
import os
import sys
from datetime import datetime
+from types import SimpleNamespace
from unittest.mock import Mock
import pytest
@@ -2515,3 +2516,67 @@ def test_bedrock_messages_thinking_shape_follows_exact_bedrock_entry_flag(
assert thinking.get("type") == "enabled"
assert isinstance(thinking.get("budget_tokens"), int)
assert "output_config" not in flipped
+
+
+ "search_results, expected_evidence",
+ [
+ pytest.param(
+ [SimpleNamespace(title="Rome", url="https://ex.com/rome", snippet="Founded 753 BC.", date=None)],
+ "Snippet: Founded 753 BC.",
+ id="search_returned_results",
+ ),
+ pytest.param([], "No results were returned.", id="search_returned_nothing"),
+ ],
+)
+def test_replayed_intercepted_search_turn_leaves_no_unsupported_block_for_bedrock(search_results, expected_evidence):
+ """A native client replaying an intercepted search turn must not 400 on Bedrock.
+
+ ``websearch_interception`` hands Claude Desktop an Anthropic-native
+ ``server_tool_use`` + ``web_search_tool_result`` pair, and Anthropic's protocol
+ obliges the client to replay that assistant turn verbatim on every later turn.
+ Bedrock's Anthropic schema defines neither tag, so both have to be gone from the
+ outbound body by the time it is signed, with the search evidence carried forward
+ as text instead. Built from the real builder rather than a hand-written fixture
+ so the two cannot drift apart.
+ """
+ from litellm.integrations.websearch_interception.transformation import (
+ WebSearchTransformation,
+ )
+ from litellm.llms.anthropic.common_utils import (
+ flatten_unencrypted_web_search_results_in_anthropic_messages,
+ )
+ from litellm.types.router import GenericLiteLLMParams
+
+ replayed_turn = [
+ {
+ "type": "server_tool_use",
+ "id": "srvtoolu_1",
+ "name": "web_search",
+ "input": {"query": "when was Rome founded"},
+ },
+ WebSearchTransformation.build_web_search_tool_result_block(
+ tool_use_id="srvtoolu_1",
+ search_response=SimpleNamespace(results=search_results),
+ ),
+ {"type": "text", "text": "Rome was founded in 753 BC."},
+ ]
+ messages = [
+ {"role": "user", "content": [{"type": "text", "text": "When was Rome founded?"}]},
+ {"role": "assistant", "content": replayed_turn},
+ {"role": "user", "content": [{"type": "text", "text": "Repeat the year."}]},
+ ]
+
+ body = AmazonAnthropicClaudeMessagesConfig().transform_anthropic_messages_request(
+ model="us.anthropic.claude-sonnet-4-5-20250929-v1:0",
+ messages=flatten_unencrypted_web_search_results_in_anthropic_messages(messages),
+ anthropic_messages_optional_request_params={"max_tokens": 64},
+ litellm_params=GenericLiteLLMParams(),
+ headers={},
+ )
+
+ serialized = json.dumps(body)
+ assert "web_search_tool_result" not in serialized
+ assert "server_tool_use" not in serialized
+ assert expected_evidence in serialized
+ assert "Rome was founded in 753 BC." in serialized