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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
Add beta header in vertex request for claude websearch request (#16269)
Sameer Kankute5f27c70bb070
diff --git a/litellm/llms/anthropic/common_utils.py b/litellm/llms/anthropic/common_utils.pyindex 246618ad9e2..7ca3c555542 100644--- a/litellm/llms/anthropic/common_utils.py+++ b/litellm/llms/anthropic/common_utils.py@@ -12,7 +12,7 @@ from litellm.litellm_core_utils.prompt_templates.common_utils import ()from litellm.llms.base_llm.base_utils import BaseLLMModelInfo, BaseTokenCounterfrom litellm.llms.base_llm.chat.transformation import BaseLLMException-from litellm.types.llms.anthropic import AllAnthropicToolsValues, AnthropicMcpServerTool+from litellm.types.llms.anthropic import AllAnthropicToolsValues, AnthropicMcpServerTool, ANTHROPIC_HOSTED_TOOLSfrom litellm.types.llms.openai import AllMessageValuesfrom litellm.types.utils import TokenCountResponse@@ -72,6 +72,17 @@ class AnthropicModelInfo(BaseLLMModelInfo):return tool["type"]return None+ def is_web_search_tool_used(+ self, tools: Optional[List[AllAnthropicToolsValues]]+ ) -> bool:+ """Returns True if web_search tool is used"""+ if tools is None:+ return False+ for tool in tools:+ if "type" in tool and tool["type"].startswith(ANTHROPIC_HOSTED_TOOLS.WEB_SEARCH.value):+ return True+ return False+def is_pdf_used(self, messages: List[AllMessageValues]) -> bool:"""Set to true if media passed into messages.@@ -252,6 +263,7 @@ class AnthropicModelInfo(BaseLLMModelInfo):pdf_used: bool = False,file_id_used: bool = False,mcp_server_used: bool = False,+ web_search_tool_used: bool = False,tool_search_used: bool = False,programmatic_tool_calling_used: bool = False,input_examples_used: bool = False,@@ -292,9 +304,12 @@ class AnthropicModelInfo(BaseLLMModelInfo):if user_anthropic_beta_headers is not None:betas.update(user_anthropic_beta_headers)- # Don't send any beta headers to Vertex, Vertex has failed requests when they are sent+ # Don't send any beta headers to Vertex, except web search which is requiredif is_vertex_request is True:- pass+ # Vertex AI requires web search beta header for web search to work+ if web_search_tool_used:+ from litellm.types.llms.anthropic import ANTHROPIC_BETA_HEADER_VALUES+ headers["anthropic-beta"] = ANTHROPIC_BETA_HEADER_VALUES.WEB_SEARCH_2025_03_05.valueelif len(betas) > 0:headers["anthropic-beta"] = ",".join(betas)@@ -325,6 +340,7 @@ class AnthropicModelInfo(BaseLLMModelInfo):)pdf_used = self.is_pdf_used(messages=messages)file_id_used = self.is_file_id_used(messages=messages)+ web_search_tool_used = self.is_web_search_tool_used(tools=tools)tool_search_used = self.is_tool_search_used(tools=tools)programmatic_tool_calling_used = self.is_programmatic_tool_calling_used(tools=tools)input_examples_used = self.is_input_examples_used(tools=tools)@@ -338,6 +354,7 @@ class AnthropicModelInfo(BaseLLMModelInfo):pdf_used=pdf_used,api_key=api_key,file_id_used=file_id_used,+ web_search_tool_used=web_search_tool_used,is_vertex_request=optional_params.get("is_vertex_request", False),user_anthropic_beta_headers=user_anthropic_beta_headers,mcp_server_used=mcp_server_used,diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py b/litellm/llms/anthropic/experimental_pass_through/messages/transformation.pyindex 99d19f0460c..790e7901960 100644--- a/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py+++ b/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py@@ -103,7 +103,7 @@ class AnthropicMessagesConfig(BaseAnthropicMessagesConfig):status_code=400,)####### get required params for all anthropic messages requests ######- verbose_logger.debug(f"🔍 TRANSFORMATION DEBUG - Messages: {messages}")+ verbose_logger.debug(f"TRANSFORMATION DEBUG - Messages: {messages}")anthropic_messages_request: AnthropicMessagesRequest = AnthropicMessagesRequest(messages=messages,max_tokens=max_tokens,diff --git a/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/experimental_pass_through/transformation.py b/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/experimental_pass_through/transformation.pyindex 2133cac2c58..c22072af2f3 100644--- a/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/experimental_pass_through/transformation.py+++ b/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/experimental_pass_through/transformation.py@@ -5,6 +5,7 @@ from litellm.llms.anthropic.experimental_pass_through.messages.transformation im)from litellm.types.llms.vertex_ai import VertexPartnerProviderfrom litellm.types.router import GenericLiteLLMParams+from litellm.types.llms.anthropic import ANTHROPIC_BETA_HEADER_VALUES, ANTHROPIC_HOSTED_TOOLSfrom ....vertex_llm_base import VertexBase@@ -49,6 +50,15 @@ class VertexAIPartnerModelsAnthropicMessagesConfig(AnthropicMessagesConfig, Vert)headers["content-type"] = "application/json"++ # Add web search beta header for Vertex AI only if not already set+ if "anthropic-beta" not in headers:+ tools = optional_params.get("tools", [])+ for tool in tools:+ if isinstance(tool, dict) and tool.get("type", "").startswith(ANTHROPIC_HOSTED_TOOLS.WEB_SEARCH.value):+ headers["anthropic-beta"] = ANTHROPIC_BETA_HEADER_VALUES.WEB_SEARCH_2025_03_05.value+ break+return headers, api_basedef get_complete_url(diff --git a/litellm/types/llms/anthropic.py b/litellm/types/llms/anthropic.pyindex 507b382f785..df6580f9b3a 100644--- a/litellm/types/llms/anthropic.py+++ b/litellm/types/llms/anthropic.py@@ -627,8 +627,8 @@ class ANTHROPIC_BETA_HEADER_VALUES(str, Enum):"""Known beta header values for Anthropic."""-WEB_FETCH_2025_09_10 = "web-fetch-2025-09-10"+ WEB_SEARCH_2025_03_05 = "web-search-2025-03-05"CONTEXT_MANAGEMENT_2025_06_27 = "context-management-2025-06-27"STRUCTURED_OUTPUT_2025_09_25 = "structured-outputs-2025-11-13"ADVANCED_TOOL_USE_2025_11_20 = "advanced-tool-use-2025-11-20"diff --git a/tests/test_litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_messages_config.py b/tests/test_litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_messages_config.pyindex ba2e686c5ff..623f8c579ff 100644--- a/tests/test_litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_messages_config.py+++ b/tests/test_litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_messages_config.py@@ -31,3 +31,70 @@ def test_validate_environment_uses_vertex_ai_location():api_base=None,)assert mock_get_url.call_args.kwargs["vertex_location"] == "europe-west1"+++def test_web_search_header_added_for_messages_endpoint():+ """Test that web search tool adds the required beta header for Vertex AI /v1/messages requests"""+ config = VertexAIPartnerModelsAnthropicMessagesConfig()+ headers = {}+ litellm_params = {+ "vertex_ai_project": "test-project",+ "vertex_ai_location": "us-central1",+ "vertex_credentials": "{}",+ }+ # Include web search tool in optional_params+ optional_params = {+ "tools": [+ {"type": "web_search_20250305", "name": "web_search", "max_uses": 5}+ ]+ }++ with patch.object(+ config, "_ensure_access_token", return_value=("token", "test-project")+ ), patch.object(+ config, "get_complete_vertex_url", return_value="https://mock-url"+ ):+ updated_headers, api_base = config.validate_anthropic_messages_environment(+ headers=headers,+ model="claude-sonnet-4",+ messages=[],+ optional_params=optional_params,+ litellm_params=litellm_params,+ api_base=None,+ )++ # Assert that the anthropic-beta header with web-search is present+ assert "anthropic-beta" in updated_headers, "anthropic-beta header should be present"+ assert updated_headers["anthropic-beta"] == "web-search-2025-03-05", \+ f"anthropic-beta should be 'web-search-2025-03-05', got: {updated_headers['anthropic-beta']}"+++def test_web_search_header_not_added_without_tool():+ """Test that beta header is NOT added when web search tool is not present"""+ config = VertexAIPartnerModelsAnthropicMessagesConfig()+ headers = {}+ litellm_params = {+ "vertex_ai_project": "test-project",+ "vertex_ai_location": "us-central1",+ "vertex_credentials": "{}",+ }+ # No web search tool+ optional_params = {}++ with patch.object(+ config, "_ensure_access_token", return_value=("token", "test-project")+ ), patch.object(+ config, "get_complete_vertex_url", return_value="https://mock-url"+ ):+ updated_headers, api_base = config.validate_anthropic_messages_environment(+ headers=headers,+ model="claude-sonnet-4",+ messages=[],+ optional_params=optional_params,+ litellm_params=litellm_params,+ api_base=None,+ )++ # Assert that the anthropic-beta header is NOT present when no web search tool+ assert "anthropic-beta" not in updated_headers, \+ "anthropic-beta header should not be present without web search tool"diff --git a/tests/test_litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_transformation.py b/tests/test_litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_transformation.pyindex 4a65b692a49..b129b7bab7f 100644--- a/tests/test_litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_transformation.py+++ b/tests/test_litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_transformation.py@@ -32,3 +32,43 @@ def test_get_supported_params_thinking():config = VertexAIAnthropicConfig()params = config.get_supported_openai_params(model="claude-sonnet-4")assert "thinking" in params+++def test_vertex_ai_anthropic_web_search_header_in_completion():+ """Test that web search tool adds the required beta header for Vertex AI completion requests"""+ from unittest.mock import MagicMock, patch+ from litellm.llms.anthropic.common_utils import AnthropicModelInfo++ # Create the config instance+ model_info = AnthropicModelInfo()++ # Test the header generation directly+ tools = [{"type": "web_search_20250305", "name": "web_search", "max_uses": 5}]++ # Check if web search tool is detected+ web_search_detected = model_info.is_web_search_tool_used(tools=tools)+ assert web_search_detected is True, "Web search tool should be detected"++ # Generate headers with is_vertex_request=True+ headers = model_info.get_anthropic_headers(+ api_key="test-key",+ web_search_tool_used=web_search_detected,+ is_vertex_request=True,+ )++ # Assert that the anthropic-beta header with web-search is present+ assert "anthropic-beta" in headers, "anthropic-beta header should be present"+ assert headers["anthropic-beta"] == "web-search-2025-03-05", \+ f"anthropic-beta should be 'web-search-2025-03-05', got: {headers['anthropic-beta']}"++ # Test that header is NOT added for non-Vertex requests+ headers_non_vertex = model_info.get_anthropic_headers(+ api_key="test-key",+ web_search_tool_used=web_search_detected,+ is_vertex_request=False,+ )++ # For non-Vertex (Anthropic-hosted), the web search header should NOT be in anthropic-beta+ # because Anthropic doesn't require it+ assert "anthropic-beta" not in headers_non_vertex or "web-search" not in headers_non_vertex.get("anthropic-beta", ""), \+ "anthropic-beta with web-search should not be present for non-Vertex requests"