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 tool call handling in Anthropic pass-through adapter (#12473)
Limbo Peng7c373140a8c4
diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py b/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.pyindex 5cf36a63f00..990d613ecf0 100644--- a/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py+++ b/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py@@ -215,15 +215,15 @@ class LiteLLMAnthropicMessagesAdapter:)tool_message_list.append(tool_result)+ if len(tool_message_list) > 0:+ new_messages.extend(tool_message_list)+if user_message is not None:new_messages.append(user_message)if len(new_user_content_list) > 0:new_messages.append({"role": "user", "content": new_user_content_list}) # type: ignore- if len(tool_message_list) > 0:- new_messages.extend(tool_message_list)-## ASSISTANT MESSAGE ##assistant_message_str: Optional[str] = Nonetool_calls: List[ChatCompletionAssistantToolCall] = []@@ -401,7 +401,7 @@ class LiteLLMAnthropicMessagesAdapter:type="tool_use",id=tool_call.id,name=tool_call.function.name or "",- input=json.loads(tool_call.function.arguments),+ input=json.loads(tool_call.function.arguments) if tool_call.function.arguments else {},))elif choice.message.content is not None:diff --git a/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_anthropic_experimental_pass_through_adapters_transformation.py b/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_anthropic_experimental_pass_through_adapters_transformation.pyindex 55cfb171e5b..b01ab0cfcb0 100644--- a/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_anthropic_experimental_pass_through_adapters_transformation.py+++ b/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_anthropic_experimental_pass_through_adapters_transformation.py@@ -6,17 +6,20 @@ from fastapi.testclient import TestClientsys.path.insert(0, os.path.abspath("../../../../.."))-from unittest.mock import MagicMock, patch+from unittest.mock import patchfrom litellm.llms.anthropic.experimental_pass_through.adapters.transformation import (LiteLLMAnthropicMessagesAdapter,)+from litellm.types.llms.anthropic import AnthropicMessagesUserMessageParam, AnthopicMessagesAssistantMessageParam+from litellm.types.llms.openai import ChatCompletionAssistantToolCallfrom litellm.types.utils import (ChatCompletionDeltaToolCall,Delta,Function,- ModelResponse,StreamingChoices,+ Choices,+ Message,)@@ -62,3 +65,86 @@ def test_translate_streaming_openai_chunk_to_anthropic_content_block():"name": "get_weather","input": {},}+++def test_translate_anthropic_messages_to_openai_tool_message_placement():+ """Test that tool result messages are placed before user messages in the conversation order."""++ anthropic_messages = [+ AnthropicMessagesUserMessageParam(+ role="user",+ content=[{"type": "text", "text": "What's the weather in Boston?"}]+ ),+ AnthopicMessagesAssistantMessageParam(+ role="assistant",+ content=[+ {+ "type": "tool_use",+ "id": "toolu_01234",+ "name": "get_weather",+ "input": {"location": "Boston"}+ }+ ]+ ),+ AnthropicMessagesUserMessageParam(+ role="user",+ content=[+ {+ "type": "tool_result",+ "tool_use_id": "toolu_01234",+ "content": "Sunny, 75°F"+ },+ {"type": "text", "text": "What about tomorrow?"}+ ]+ )+ ]++ adapter = LiteLLMAnthropicMessagesAdapter()+ result = adapter.translate_anthropic_messages_to_openai(messages=anthropic_messages)++ # find the indices of tool and user messages in the result+ tool_message_idx = None+ user_message_idx = None++ for i, msg in enumerate(result):+ if isinstance(msg, dict) and msg.get("role") == "tool":+ tool_message_idx = i+ elif isinstance(msg, dict) and msg.get("role") == "user" and "What about tomorrow?" in str(msg.get("content", "")):+ user_message_idx = i+ break++ assert tool_message_idx is not None, "Tool message not found"+ assert user_message_idx is not None, "User message not found"+ assert tool_message_idx < user_message_idx, "Tool message should be placed before user message"+++def test_translate_openai_content_to_anthropic_empty_function_arguments():+ """Test that empty function arguments are handled safely and don't cause JSON parsing errors."""++ openai_choices = [+ Choices(+ message=Message(+ role="assistant",+ content=None,+ tool_calls=[+ ChatCompletionAssistantToolCall(+ id="call_empty_args",+ type="function",+ function=Function(+ name="test_function",+ arguments="" # empty arguments string+ )+ )+ ]+ )+ )+ ]++ adapter = LiteLLMAnthropicMessagesAdapter()+ result = adapter._translate_openai_content_to_anthropic(choices=openai_choices)++ assert len(result) == 1+ assert result[0].type == "tool_use"+ assert result[0].id == "call_empty_args"+ assert result[0].name == "test_function"+ assert result[0].input == {}, "Empty function arguments should result in empty dict"