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
fix(anthropic): check Vertex forced-tool support on the real model, skip non-string user ids, drop speed where unsupported (#46337)
ryan-crabbe-berri12cce6c372e5
diff --git a/litellm/llms/anthropic/chat/transformation.py b/litellm/llms/anthropic/chat/transformation.pyindex c43e5f9b05b..1b47f044fb3 100644--- a/litellm/llms/anthropic/chat/transformation.py+++ b/litellm/llms/anthropic/chat/transformation.py@@ -335,6 +335,11 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):def _resolved_provider(self) -> str:return self.custom_llm_provider or "anthropic"+ def uses_native_structured_output(self, model: str) -> bool:+ return AnthropicConfig._supports_model_capability(+ model, "supports_native_structured_output", self._resolved_provider+ )+@classmethoddef get_config(cls, *, model: str | None = None):config: Final = super().get_config()@@ -1600,11 +1605,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):output_key=param,)elif param == "response_format" and isinstance(value, dict):- if AnthropicConfig._supports_model_capability(- model,- "supports_native_structured_output",- self._resolved_provider,- ):+ if self.uses_native_structured_output(model):_output_format = self.map_response_format_to_anthropic_output_format(value)if _output_format is not None:optional_params["output_format"] = _output_format@@ -2906,11 +2907,13 @@ class JsonModeRequest(BaseModel):return None if json_tool is None else response_format_schema(json_tool.get("input_schema"))-def _valid_user_id(user_id: str) -> bool:+def _valid_user_id(user_id: object) -> bool:"""- Validate that user_id is not an email or phone number.- Returns: bool: True if valid (not email or phone), False otherwise+ Validate that user_id is a string and not an email or phone number.+ Returns: bool: True if valid (string, not email or phone), False otherwise"""+ if not isinstance(user_id, str):+ return Falseemail_pattern: Final = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"phone_pattern: Final = r"^\+?[\d\s\(\)-]{7,}$"diff --git a/litellm/llms/bedrock/chat/invoke_transformations/anthropic_claude3_transformation.py b/litellm/llms/bedrock/chat/invoke_transformations/anthropic_claude3_transformation.pyindex 0be087d2dd4..68264539da0 100644--- a/litellm/llms/bedrock/chat/invoke_transformations/anthropic_claude3_transformation.py+++ b/litellm/llms/bedrock/chat/invoke_transformations/anthropic_claude3_transformation.py@@ -3,7 +3,6 @@ from typing import TYPE_CHECKING, Any, Finalimport httpxfrom litellm.anthropic_beta_headers_manager import filter_and_transform_beta_headers-from litellm.constants import RESPONSE_FORMAT_TOOL_NAMEfrom litellm.litellm_core_utils.prompt_templates.factory import (convert_to_anthropic_image_obj,)@@ -73,6 +72,11 @@ class AmazonAnthropicClaudeConfig(AmazonInvokeConfig, AnthropicConfig):def get_supported_openai_params(self, model: str) -> list[str]:return AnthropicConfig.get_supported_openai_params(self, model)+ def uses_native_structured_output(self, model: str) -> bool:+ from litellm.utils import supports_native_structured_output++ return supports_native_structured_output(model=model, custom_llm_provider="bedrock")+def map_openai_params(self,non_default_params: dict,@@ -80,19 +84,8 @@ class AmazonAnthropicClaudeConfig(AmazonInvokeConfig, AnthropicConfig):model: str,drop_params: bool,) -> dict:- # Force tool-based structured outputs for Bedrock Invoke- # (similar to VertexAI fix in #19201) unless the model map advertises- # native structured output- from litellm.utils import supports_native_structured_output-- original_model: Final = modelrequested_thinking: Final = non_default_params.get("thinking")requested_display_updates: Final = self.is_thinking_display_updates_used(requested_thinking)- if "response_format" in non_default_params and not supports_native_structured_output(- model=model, custom_llm_provider="bedrock"- ):- # Use a model name that forces tool-based approach- model = "claude-3-sonnet-20240229"# Clamp ``reasoning_effort`` to the Bedrock effort ceiling before the# parent mapping converts it to ``output_config.effort`` and the@@ -101,9 +94,9 @@ class AmazonAnthropicClaudeConfig(AmazonInvokeConfig, AnthropicConfig):# ``_clamp_adaptive_reasoning_effort_for_bedrock`` so adaptive Claude# requests degrade ``xhigh`` -> ``max`` rather than 400-ing on# models like Opus 4.6 that don't natively advertise xhigh.- self._clamp_adaptive_reasoning_effort_for_bedrock(model=original_model, params=non_default_params)+ self._clamp_adaptive_reasoning_effort_for_bedrock(model=model, params=non_default_params)- optional_params = AnthropicConfig.map_openai_params(+ mapped_params: Final = AnthropicConfig.map_openai_params(self,non_default_params,optional_params,@@ -111,32 +104,19 @@ class AmazonAnthropicClaudeConfig(AmazonInvokeConfig, AnthropicConfig):drop_params,)- # Restore original model name- model = original_model-AnthropicModelInfo.translate_legacy_thinking_for_adaptive_model(- model=original_model, optional_params=optional_params, custom_llm_provider="bedrock"+ model=model, optional_params=mapped_params, custom_llm_provider="bedrock")- translated_thinking: Final = optional_params.get("thinking")+ translated_thinking: Final = mapped_params.get("thinking")if (requested_display_updatesand isinstance(translated_thinking, dict)and translated_thinking.get("type") == "adaptive"):thinking_with_display: Final[AnthropicThinkingParam] = {"type": "adaptive", "display": "updates"}- optional_params["thinking"] = thinking_with_display+ mapped_params["thinking"] = thinking_with_display- # The stub model hides the original model from the parent's forced-tool-use backstop- response_format_tool_choice: Final = optional_params.get("tool_choice")- if (- "response_format" in non_default_params- and isinstance(response_format_tool_choice, dict)- and response_format_tool_choice.get("name") == RESPONSE_FORMAT_TOOL_NAME- and AnthropicModelInfo.forced_tool_use_unsupported(original_model)- ):- optional_params.pop("tool_choice")-- return optional_params+ return mapped_params@staticmethoddef _clamp_adaptive_reasoning_effort_for_bedrock(model: str, params: dict) -> None:diff --git a/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/transformation.py b/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/transformation.pyindex 72c08c6b8d7..b57081589ee 100644--- a/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/transformation.py+++ b/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/transformation.py@@ -149,6 +149,16 @@ class VertexAIAnthropicConfig(AnthropicConfig):return data+ def uses_native_structured_output(self, model: str) -> bool:+ from litellm.llms.anthropic.common_utils import AnthropicModelInfo++ return (+ AnthropicModelInfo._get_provider_resolved_capability(+ model, "supports_native_structured_output", "vertex_ai"+ )+ is True+ )+def map_openai_params(self,non_default_params: dict,@@ -156,36 +166,20 @@ class VertexAIAnthropicConfig(AnthropicConfig):model: str,drop_params: bool,) -> dict:- """- Override parent method so VertexAI uses tool-based structured outputs- unless the vertex map entry advertises native structured output- (sent to Vertex AI Claude as ``output_config.format``).- """from litellm.llms.anthropic.common_utils import AnthropicModelInfo- original_model: Final = model- native_structured_output: Final = AnthropicModelInfo._get_provider_resolved_capability(- model, "supports_native_structured_output", "vertex_ai"- )- if "response_format" in non_default_params and native_structured_output is not True:- model = "claude-3-sonnet-20240229" # Use a model that will use tool-based approach-- # Call parent method with potentially modified model name- optional_params = super().map_openai_params(+ mapped_params: Final = super().map_openai_params(non_default_params=non_default_params,optional_params=optional_params,model=model,drop_params=drop_params,)- # Restore original model name for any other processing- model = original_model-AnthropicModelInfo.translate_legacy_thinking_for_adaptive_model(- model=original_model, optional_params=optional_params, custom_llm_provider="vertex_ai"+ model=model, optional_params=mapped_params, custom_llm_provider="vertex_ai")- return optional_params+ return mapped_paramsdef transform_response(self,diff --git a/litellm/utils.py b/litellm/utils.pyindex 238122b77f4..b5511254e63 100644--- a/litellm/utils.py+++ b/litellm/utils.py@@ -5073,6 +5073,13 @@ def get_optional_params(model=model,drop_params=bool(drop_params),)+ if (litellm.drop_params or drop_params) and custom_llm_provider != "litellm_proxy":+ litellm.AnthropicConfig.maybe_drop_speed_param(+ model=model,+ optional_params=passed_params,+ drop_params=True,+ custom_llm_provider=custom_llm_provider or None,+ )# if user passed in non-default kwargs for specific providers/models, pass them alongoptional_params = add_provider_specific_params_to_optional_params(optional_params=optional_params,diff --git a/tests/integration/providers/test_vertex_anthropic_structured_output_wire.py b/tests/integration/providers/test_vertex_anthropic_structured_output_wire.pyindex 6080840a5d2..11543dee1e0 100644--- a/tests/integration/providers/test_vertex_anthropic_structured_output_wire.py+++ b/tests/integration/providers/test_vertex_anthropic_structured_output_wire.py@@ -96,6 +96,8 @@ _ADDITIONAL_TRUE_SCHEMA: Final[dict[str, JsonValue]] = {**_OPTIONAL_SCHEMA, "add_CLOSED_OPTIONAL_SCHEMA: Final[dict[str, JsonValue]] = {**_OPTIONAL_SCHEMA, "additionalProperties": False}_CALLERS_FORMAT: Final[dict[str, JsonValue]] = {"type": "json_schema", "schema": {**_SCHEMA, "title": "callers"}}_ANTHROPIC_JSON_TOOL: Final[dict[str, JsonValue]] = {"name": _JSON_TOOL, "input_schema": _SCHEMA}+_FORCED_JSON_TOOL: Final[dict[str, JsonValue]] = {"type": "tool", "name": _JSON_TOOL}+_REASONING_FIELDS: Final = ("thinking", "output_config", "max_tokens")_USER_TOOL_SPEC: Final[dict[str, JsonValue]] = {"type": "function","function": {@@ -597,6 +599,14 @@ def _chat_body(return body if tools is None else {**body, "tools": tools}+def _effort_body(model: str, marker: str) -> dict[str, JsonValue]:+ return {"model": model, "messages": [{"role": "user", "content": marker}], "reasoning_effort": "low"}+++def _reasoning_fields(delivery: _Delivery) -> dict[str, JsonValue]:+ return {field: delivery.body.get(field) for field in _REASONING_FIELDS}++def _messages_body(model: str, marker: str, *, stream: bool = False, **extra: JsonValue) -> dict[str, JsonValue]:return {"model": model,@@ -740,6 +750,30 @@ def _vertex_deployment(gateway: Gateway, scenario: Scenario, api_base: str, back)+def _bedrock_invoke_deployment(scenario: Scenario, api_base: str, backend: str) -> str:+ return scenario.model(+ model=f"bedrock/invoke/{backend}",+ api_base=api_base,+ api_key=_BEDROCK_TOKEN,+ aws_region_name="us-east-1",+ )+++def _rejects_forced_tools_without_native_output(row: Mapping[str, JsonValue]) -> bool:+ return row.get("supports_forced_tool_use") is False and row.get("supports_native_structured_output") is not True+++def _claude_rejecting_forced_tools(gateway: Gateway, namespace: str, family: str) -> str:+ rows: Final = gateway.get("/public/litellm_model_cost_map")+ names: Final = sorted(+ name.removeprefix(namespace)+ for name, row in rows.items()+ if name.startswith(namespace + family) and _rejects_forced_tools_without_native_output(object_value(row))+ )+ assert names, f"The cost map has no {namespace}{family} row rejecting forced tools without native output"+ return names[0]++def _family_deployment(gateway: Gateway, scenario: Scenario, api_base: str, member: str) -> str:match member:case "anthropic_unmapped":@@ -747,12 +781,7 @@ def _family_deployment(gateway: Gateway, scenario: Scenario, api_base: str, membcase "azure_ai_unmapped":return scenario.model(model=f"azure_ai/{_UNMAPPED_MODEL}", api_base=api_base, api_key=_AZURE_KEY)case "bedrock_invoke":- return scenario.model(- model=f"bedrock/invoke/{_BEDROCK_INVOKE_MODEL}",- api_base=api_base,- api_key=_BEDROCK_TOKEN,- aws_region_name="us-east-1",- )+ return _bedrock_invoke_deployment(scenario, api_base, _BEDROCK_INVOKE_MODEL)case "bedrock_mantle":return scenario.model(model=f"bedrock_mantle/{_BEDROCK_INVOKE_MODEL}",@@ -1307,6 +1336,61 @@ def test_tool_path_family_stream_unwraps_the_envelope(gateway: Gateway, member:assert _json_tool_schema(sent)["properties"] == _SCHEMA["properties"], sent.body[email protected]("accepts_forced_tools", [True, False], ids=["accepts_forced_tools", "rejects_forced_tools"])+def test_vertex_chat_json_schema_forces_the_json_tool_only_when_the_model_accepts_forced_tools(+ gateway: Gateway, accepts_forced_tools: bool+) -> None:+ marker, marker_hex = _marker("plain")+ backend: Final = (+ _TOOL_MODEL if accepts_forced_tools else _claude_rejecting_forced_tools(gateway, "vertex_ai/", "claude")+ )+ with wire_server(_peer) as wire, gateway.scenario() as scenario:+ model: Final = _vertex_deployment(gateway, scenario, wire.url, backend)+ response: Final = gateway.request("POST", "/v1/chat/completions", _chat_body(model, marker))+ assert _chat_content(response) == _payload(marker_hex), response.text+ sent: Final = _one_delivery(wire, marker_hex)+ assert _json_tool_schema(sent)["properties"] == _SCHEMA["properties"], sent.body+ assert sent.body.get("tool_choice") == (_FORCED_JSON_TOOL if accepts_forced_tools else None), sent.body+ assert "output_config" not in sent.body and "output_format" not in sent.body, sent.body+++def test_vertex_chat_json_schema_on_a_model_rejecting_forced_tools_maps_reasoning_effort_like_plain_chat(+ gateway: Gateway,+) -> None:+ backend: Final = _claude_rejecting_forced_tools(gateway, "vertex_ai/", "claude")+ structured_marker, structured_hex = _marker("plain")+ plain_marker, plain_hex = _marker("plain")+ with wire_server(_peer) as wire, gateway.scenario() as scenario:+ model: Final = _vertex_deployment(gateway, scenario, wire.url, backend)+ structured: Final = gateway.request(+ "POST",+ "/v1/chat/completions",+ {**_effort_body(model, structured_marker), "response_format": _RESPONSE_FORMAT},+ )+ assert _chat_content(structured) == _payload(structured_hex), structured.text+ structured_sent: Final = _one_delivery(wire, structured_hex)+ plain: Final = gateway.request("POST", "/v1/chat/completions", _effort_body(model, plain_marker))+ assert plain.status_code == 200, plain.text+ plain_sent: Final = _one_delivery(wire, plain_hex)+ assert "thinking" in plain_sent.body, plain_sent.body+ assert _reasoning_fields(structured_sent) == _reasoning_fields(plain_sent), (structured_sent.body, plain_sent.body)+++def test_bedrock_invoke_json_schema_sends_the_json_tool_unforced_when_the_model_rejects_forced_tools(+ gateway: Gateway,+) -> None:+ marker, marker_hex = _marker("plain")+ backend: Final = _claude_rejecting_forced_tools(gateway, "", "anthropic.claude")+ with wire_server(_peer) as wire, gateway.scenario() as scenario:+ model: Final = _bedrock_invoke_deployment(scenario, wire.url, backend)+ response: Final = gateway.request("POST", "/v1/chat/completions", _chat_body(model, marker))+ assert _chat_content(response) == _payload(marker_hex), response.text+ sent: Final = _one_delivery(wire, marker_hex)+ assert sent.target == f"/model/{backend}/invoke", sent.target+ assert _json_tool_schema(sent)["properties"] == _SCHEMA["properties"], sent.body+ assert "tool_choice" not in sent.body, sent.body++@pytest.mark.parametrize("stream", [False, True], ids=["non_stream", "stream"])def test_vertex_chat_json_schema_native_folds_output_format_into_output_config(gateway: Gateway, stream: bool) -> None:marker, marker_hex = _marker("native")diff --git a/tests/unit/llms/anthropic/chat/test_anthropic_chat_transformation.py b/tests/unit/llms/anthropic/chat/test_anthropic_chat_transformation.pyindex b682d8661f3..edc9051dc40 100644--- a/tests/unit/llms/anthropic/chat/test_anthropic_chat_transformation.py+++ b/tests/unit/llms/anthropic/chat/test_anthropic_chat_transformation.py@@ -8192,6 +8192,15 @@ def test_metadata_user_id_from_litellm_params_strips_extras():assert data.get("metadata") == {"user_id": "abc123"}[email protected]("user_id", [12345, {"id": "abc123"}, ["abc123"]])+def test_metadata_non_string_user_id_is_skipped_instead_of_raising(user_id):+ data: Final = _make_transform_request(+ optional_params={},+ litellm_params={"metadata": {"user_id": user_id}},+ )+ assert "metadata" not in data++def test_metadata_filter_applies_to_vertex_anthropic():"""VertexAIAnthropicConfig inherits the metadata filter."""from litellm.llms.vertex_ai.vertex_ai_partner_models.anthropic.transformation import (diff --git a/tests/unit/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_transformation.py b/tests/unit/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_transformation.pyindex c82e6e541c5..56e76df25a4 100644--- a/tests/unit/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_transformation.py+++ b/tests/unit/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_transformation.py@@ -1,6 +1,7 @@import copyimport json+from collections.abc import Mappingfrom typing import Finalimport httpx@@ -968,6 +969,40 @@ def test_vertex_ai_fable_5_1_response_format_uses_native_output_format(local_modassert "tools" not in result_params+def _is_tool_based_vertex_claude_rejecting_forced_tools(info: Mapping[str, object]) -> bool:+ return (+ info.get("litellm_provider") == "vertex_ai-anthropic_models"+ and info.get("supports_forced_tool_use") is False+ and info.get("supports_native_structured_output") is not True+ )+++def test_vertex_ai_tool_based_response_format_skips_forced_tool_choice_when_model_rejects_it(local_model_cost_map):+ model: Final = next(+ name.removeprefix("vertex_ai/")+ for name, info in litellm.model_cost.items()+ if _is_tool_based_vertex_claude_rejecting_forced_tools(info)+ )+ result_params: Final = VertexAIAnthropicConfig().map_openai_params(+ non_default_params={+ "response_format": {+ "type": "json_schema",+ "json_schema": {+ "name": "test_schema",+ "schema": {"type": "object", "properties": {"result": {"type": "string"}}},+ },+ }+ },+ optional_params={},+ model=model,+ drop_params=False,+ )++ assert "output_format" not in result_params+ assert "tools" in result_params+ assert "tool_choice" not in result_params++def test_vertex_ai_anthropic_tool_based_response_format_still_upgrades_legacy_thinking(local_model_cost_map):result_params = VertexAIAnthropicConfig().map_openai_params(non_default_params={diff --git a/tests/unit/test_utils.py b/tests/unit/test_utils.pyindex 124369a9528..b3eced92bb4 100644--- a/tests/unit/test_utils.py+++ b/tests/unit/test_utils.py@@ -3570,6 +3570,64 @@ class TestDropParamsWithPromptCacheKey:assert result.get("temperature") == 0.7+class TestGetOptionalParamsSpeedGate:+ UNSUPPORTED_LEGS: Final = (+ ("bedrock", "anthropic.claude-opus-4-8-v1:0"),+ ("bedrock", "invoke/anthropic.claude-opus-4-8-v1:0"),+ ("vertex_ai", "claude-opus-4-8"),+ ("azure_ai", "claude-opus-4-8"),+ ("openai", "gpt-5.6"),+ ("azure", "gpt-5.6"),+ )++ @staticmethod+ def _speed_anywhere(optional_params: Mapping[str, object]) -> bool:+ extra_body: Final = optional_params.get("extra_body")+ return "speed" in optional_params or (isinstance(extra_body, dict) and "speed" in extra_body)++ @pytest.mark.parametrize("global_drop_params", [True, False])+ @pytest.mark.parametrize(("custom_llm_provider", "model"), UNSUPPORTED_LEGS)+ def test_drop_params_strips_speed_on_providers_without_fast_mode(+ self, monkeypatch: pytest.MonkeyPatch, custom_llm_provider: str, model: str, global_drop_params: bool+ ) -> None:+ monkeypatch.setattr(litellm, "drop_params", global_drop_params)+ result: Final = litellm.get_optional_params(+ model=model, custom_llm_provider=custom_llm_provider, speed="fast", drop_params=not global_drop_params+ )+ assert not self._speed_anywhere(result), result++ @pytest.mark.parametrize(("custom_llm_provider", "model"), [("openai", "gpt-5.6"), ("hosted_vllm", "my-model")])+ def test_speed_is_forwarded_untouched_without_drop_params(+ self, monkeypatch: pytest.MonkeyPatch, custom_llm_provider: str, model: str+ ) -> None:+ monkeypatch.setattr(litellm, "drop_params", False)+ result: Final = litellm.get_optional_params(+ model=model, custom_llm_provider=custom_llm_provider, speed="fast", drop_params=False+ )+ assert self._speed_anywhere(result), result++ def test_drop_params_keeps_speed_for_a_downstream_litellm_proxy(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(litellm, "drop_params", False)+ result: Final = litellm.get_optional_params(+ model="claude-opus-4-8", custom_llm_provider="litellm_proxy", speed="fast", drop_params=True+ )+ assert self._speed_anywhere(result), result++ def test_speed_survives_on_a_direct_anthropic_fast_mode_model(+ self, monkeypatch: pytest.MonkeyPatch, local_model_cost_map: None+ ) -> None:+ monkeypatch.setattr(litellm, "drop_params", False)+ fast_mode_model: Final = next(+ name+ for name, info in litellm.model_cost.items()+ if info.get("supports_speed") is True and info.get("litellm_provider") == "anthropic"+ )+ result: Final = litellm.get_optional_params(+ model=fast_mode_model, custom_llm_provider="anthropic", speed="fast", drop_params=True+ )+ assert result.get("speed") == "fast"++class TestGetOptionalParamsDeepSeek:"""Tests that deepseek provider uses DeepSeekChatConfig for parameter mapping."""