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): inject dummy tool without modify_params (#27620)
Sameer Kankute4c1d91d96f36
diff --git a/litellm/llms/anthropic/chat/transformation.py b/litellm/llms/anthropic/chat/transformation.pyindex 2f11a3fccb5..1ce80207552 100644--- a/litellm/llms/anthropic/chat/transformation.py+++ b/litellm/llms/anthropic/chat/transformation.py@@ -1809,9 +1809,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):Translate messages to anthropic format."""## VALIDATE REQUEST- """- Anthropic doesn't support tool calling without `tools=` param specified.- """+ """Anthropic requires ``tools`` when messages include tool blocks; LiteLLM injects a dummy tool if omitted (no ``modify_params`` needed)."""from litellm.litellm_core_utils.prompt_templates.factory import (anthropic_messages_pt,)@@ -1821,16 +1819,9 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):and messages is not Noneand has_tool_call_blocks(messages)):- if litellm.modify_params:- optional_params["tools"], _ = self._map_tools(- add_dummy_tool(custom_llm_provider="anthropic")- )- else:- raise litellm.UnsupportedParamsError(- message="Anthropic doesn't support tool calling without `tools=` param specified. Pass `tools=` param OR set `litellm.modify_params = True` // `litellm_settings::modify_params: True` to add dummy tool to the request.",- model="",- llm_provider="anthropic",- )+ optional_params["tools"], _ = self._map_tools(+ add_dummy_tool(custom_llm_provider="anthropic")+ )# Drop thinking param if thinking is enabled but thinking_blocks are missing# This prevents the error: "Expected thinking or redacted_thinking, but found tool_use"diff --git a/tests/local_testing/test_function_calling.py b/tests/local_testing/test_function_calling.pyindex 6fd253ee294..3c7e004b62e 100644--- a/tests/local_testing/test_function_calling.py+++ b/tests/local_testing/test_function_calling.py@@ -268,51 +268,63 @@ def test_aaparallel_function_call_with_anthropic_thinking(model):from litellm.types.utils import ChatCompletionMessageToolCall, Function, Message+_PARALLEL_TOOL_HISTORY_MESSAGES = [+ {+ "role": "user",+ "content": "What's the weather like in San Francisco, Tokyo, and Paris? - give me 3 responses",+ },+ Message(+ content="Here are the current weather conditions for San Francisco, Tokyo, and Paris:",+ role="assistant",+ tool_calls=[+ ChatCompletionMessageToolCall(+ index=1,+ function=Function(+ arguments='{"location": "San Francisco, CA", "unit": "fahrenheit"}',+ name="get_current_weather",+ ),+ id="tooluse_Jj98qn6xQlOP_PiQr-w9iA",+ type="function",+ )+ ],+ function_call=None,+ ),+ {+ "tool_call_id": "tooluse_Jj98qn6xQlOP_PiQr-w9iA",+ "role": "tool",+ "name": "get_current_weather",+ "content": '{"location": "San Francisco", "temperature": "72", "unit": "fahrenheit"}',+ },+]++@pytest.mark.parametrize(- "model, provider",+ "model, messages, expect_unsupported_params_error",[+ # Bedrock Converse still requires modify_params to inject the dummy tool.("anthropic.claude-3-sonnet-20240229-v1:0",- "bedrock",+ _PARALLEL_TOOL_HISTORY_MESSAGES,+ True,+ ),+ # Anthropic Messages API: dummy tool is injected without modify_params.+ (+ "claude-haiku-4-5-20251001",+ _PARALLEL_TOOL_HISTORY_MESSAGES,+ False,),- ("claude-haiku-4-5-20251001", "anthropic"),- ],-)- "messages, expected_error_msg",- [(+ "anthropic.claude-3-sonnet-20240229-v1:0",[{"role": "user","content": "What's the weather like in San Francisco, Tokyo, and Paris? - give me 3 responses",- },- Message(- content="Here are the current weather conditions for San Francisco, Tokyo, and Paris:",- role="assistant",- tool_calls=[- ChatCompletionMessageToolCall(- index=1,- function=Function(- arguments='{"location": "San Francisco, CA", "unit": "fahrenheit"}',- name="get_current_weather",- ),- id="tooluse_Jj98qn6xQlOP_PiQr-w9iA",- type="function",- )- ],- function_call=None,- ),- {- "tool_call_id": "tooluse_Jj98qn6xQlOP_PiQr-w9iA",- "role": "tool",- "name": "get_current_weather",- "content": '{"location": "San Francisco", "temperature": "72", "unit": "fahrenheit"}',- },+ }],- True,+ False,),(+ "claude-haiku-4-5-20251001",[{"role": "user",@@ -324,25 +336,26 @@ from litellm.types.utils import ChatCompletionMessageToolCall, Function, Message],)def test_parallel_function_call_anthropic_error_msg(- model, provider, messages, expected_error_msg+ model, messages, expect_unsupported_params_error):"""- Anthropic doesn't support tool calling without `tools=` param specified.+ Tool history without an explicit ``tools`` param:- Ensure this error is thrown when `tools=` param is not specified. But tool call requests are made.+ - Bedrock **Converse** still raises ``UnsupportedParamsError`` unless+ ``litellm.modify_params`` is enabled (dummy tool is only added there).+ - **Anthropic** (and Bedrock Invoke via ``AnthropicConfig.transform_request``)+ always get a dummy tool so CLIs work with ``modify_params`` left off.Reference Issue: https://github.com/BerriAI/litellm/issues/5747, https://github.com/BerriAI/litellm/issues/5388"""- # Ensure modify_params is False so UnsupportedParamsError is raised+ # Ensure modify_params is False so Bedrock Converse path still raises.# (other tests in this file set it to True and don't reset it)original_modify_params = litellm.modify_paramslitellm.modify_params = Falsetry:litellm.set_verbose = True- messages = messages-- if expected_error_msg:+ if expect_unsupported_params_error:with pytest.raises(litellm.UnsupportedParamsError) as e:second_response = litellm.completion(model=model,diff --git a/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_transformation.py b/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_transformation.pyindex e38698c9100..a19752dc648 100644--- a/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_transformation.py+++ b/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_transformation.py@@ -2135,6 +2135,53 @@ def test_validate_effort_for_model_centralises_per_model_gating(assert err is None+def test_transform_request_injects_dummy_tool_without_tools_param():+ """+ Anthropic rejects messages that contain tool turns when ``tools`` is omitted.+ LiteLLM must inject a dummy tool without ``litellm.modify_params``.+ """+ config = AnthropicConfig()+ prev_modify_params = litellm.modify_params+ litellm.modify_params = False+ try:+ messages = [+ {"role": "user", "content": "Hello"},+ {+ "role": "assistant",+ "content": "Calling tool",+ "tool_calls": [+ {+ "id": "toolu_test_dummy",+ "type": "function",+ "function": {"name": "get_x", "arguments": "{}"},+ }+ ],+ },+ {+ "role": "tool",+ "tool_call_id": "toolu_test_dummy",+ "content": "{}",+ },+ ]+ result = config.transform_request(+ model="claude-3-5-haiku-20241022",+ messages=messages,+ optional_params={"max_tokens": 256},+ litellm_params={},+ headers={},+ )+ finally:+ litellm.modify_params = prev_modify_params++ assert "tools" in result+ names = [+ t.get("name")+ for t in result["tools"]+ if isinstance(t, dict) and t.get("name") is not None+ ]+ assert "dummy_tool" in names++def test_transform_request_uses_dynamic_max_tokens():"""Test that transform_request uses dynamic max_tokens based on model