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] inconsistent response format in anthropic.messages.acreate() when using non anthropic providers (#20442)
Ishaan Jaff2a3843aa572d
diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py b/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.pyindex 444f821c20a..169b138a5f7 100644--- a/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py+++ b/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py@@ -939,22 +939,8 @@ class LiteLLMAnthropicMessagesAdapter:self,choices: List[Choices],tool_name_mapping: Optional[Dict[str, str]] = None,- ) -> List[- Union[- AnthropicResponseContentBlockText,- AnthropicResponseContentBlockToolUse,- AnthropicResponseContentBlockThinking,- AnthropicResponseContentBlockRedactedThinking,- ]- ]:- new_content: List[- Union[- AnthropicResponseContentBlockText,- AnthropicResponseContentBlockToolUse,- AnthropicResponseContentBlockThinking,- AnthropicResponseContentBlockRedactedThinking,- ]- ] = []+ ) -> List[Dict[str, Any]]:+ new_content: List[Dict[str, Any]] = []for choice in choices:# Handle thinking blocks firstif (@@ -978,7 +964,7 @@ class LiteLLMAnthropicMessagesAdapter:if signature_value is not Noneelse None),- )+ ).model_dump())elif thinking_block.get("type") == "redacted_thinking":data_value = thinking_block.get("data", "")@@ -986,7 +972,7 @@ class LiteLLMAnthropicMessagesAdapter:AnthropicResponseContentBlockRedactedThinking(type="redacted_thinking",data=str(data_value) if data_value is not None else "",- )+ ).model_dump())# Handle reasoning_content when thinking_blocks is not presentelif (@@ -998,7 +984,7 @@ class LiteLLMAnthropicMessagesAdapter:type="thinking",thinking=str(choice.message.reasoning_content),signature=None,- )+ ).model_dump())# Handle text content@@ -1006,7 +992,7 @@ class LiteLLMAnthropicMessagesAdapter:new_content.append(AnthropicResponseContentBlockText(type="text", text=choice.message.content- )+ ).model_dump())# Handle tool calls (in parallel to text content)if (@@ -1044,7 +1030,7 @@ class LiteLLMAnthropicMessagesAdapter:tool_use_block.provider_specific_fields = (provider_specific_fields)- new_content.append(tool_use_block)+ new_content.append(tool_use_block.model_dump())return new_contentdiff --git a/tests/pass_through_unit_tests/base_anthropic_unified_messages_test.py b/tests/pass_through_unit_tests/base_anthropic_unified_messages_test.pyindex b334966b441..2ebf9174e29 100644--- a/tests/pass_through_unit_tests/base_anthropic_unified_messages_test.py+++ b/tests/pass_through_unit_tests/base_anthropic_unified_messages_test.py@@ -130,6 +130,67 @@ class BaseAnthropicMessagesTest:return collected_chunks+ @pytest.mark.asyncio+ async def test_response_format_consistency(self):+ """+ Test that response content blocks are consistently dicts (not Pydantic objects).++ This ensures that code like response["content"][0]["type"] works+ regardless of the target provider.++ Issue: https://github.com/BerriAI/litellm/issues/20342+ """+ litellm._turn_on_debug()++ request_params = self.model_config++ # Set up test parameters+ messages = [{"role": "user", "content": "Say hi"}]++ # Prepare call arguments+ call_args = {+ "messages": messages,+ "max_tokens": 100,+ }++ # Add any additional config from subclass+ call_args.update(request_params)++ # Call the handler+ response = await litellm.anthropic.messages.acreate(**call_args)++ print(f"Response for {request_params['model']}: {json.dumps(response, indent=2, default=str)}")++ # Verify response structure+ assert "content" in response, "Response should have 'content' field"+ assert len(response["content"]) > 0, "Response content should not be empty"++ # Get the first content block+ block = response["content"][0]++ # Check that the block is a dict, not a Pydantic object+ assert isinstance(block, dict), (+ f"Content block should be a dict, but got {type(block)}. "+ f"This means response format is inconsistent across providers."+ )++ # Verify we can access fields using dict syntax (not object attributes)+ try:+ block_type = block["type"]+ print(f"✓ Successfully accessed block['type']: {block_type}")+ except TypeError as e:+ pytest.fail(+ f"Cannot access content block using dict syntax: {e}. "+ f"Block type: {type(block)}"+ )++ # Verify the block has expected structure+ assert "type" in block, "Content block should have 'type' field"+ if block["type"] == "text":+ assert "text" in block, "Text content block should have 'text' field"++ print(f"✓ Response format consistency test passed for {request_params['model']}")+@pytest.mark.asyncioasync def test_anthropic_messages_litellm_router_streaming_with_logging(self):"""diff --git a/tests/pass_through_unit_tests/test_anthropic_messages_passthrough.py b/tests/pass_through_unit_tests/test_anthropic_messages_passthrough.pyindex 17e72f29152..0a581fb512d 100644--- a/tests/pass_through_unit_tests/test_anthropic_messages_passthrough.py+++ b/tests/pass_through_unit_tests/test_anthropic_messages_passthrough.py@@ -876,4 +876,4 @@ def test_sync_openai_messages():assert response is not Noneassert isinstance(response, dict)- assert response["content"][0].text is not None+ assert response["content"][0]["text"] is not Nonediff --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 6a5c022ac7a..b228a51447b 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@@ -341,10 +341,10 @@ def test_translate_openai_content_to_anthropic_empty_function_arguments():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"+ 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"def test_translate_openai_content_to_anthropic_text_and_tool_calls():@@ -372,12 +372,12 @@ def test_translate_openai_content_to_anthropic_text_and_tool_calls():result = adapter._translate_openai_content_to_anthropic(choices=openai_choices)assert len(result) == 2- assert result[0].type == "text"- assert result[0].text == "Calling get_weather now."- assert result[1].type == "tool_use"- assert result[1].id == "call_weather"- assert result[1].name == "get_weather"- assert result[1].input == {"location": "Boston"}+ assert result[0]["type"] == "text"+ assert result[0]["text"] == "Calling get_weather now."+ assert result[1]["type"] == "tool_use"+ assert result[1]["id"] == "call_weather"+ assert result[1]["name"] == "get_weather"+ assert result[1]["input"] == {"location": "Boston"}def test_translate_openai_response_to_anthropic_text_and_tool_calls():@@ -414,11 +414,11 @@ def test_translate_openai_response_to_anthropic_text_and_tool_calls():anthropic_content = anthropic_response.get("content")assert anthropic_content is not Noneassert len(anthropic_content) == 2- assert cast(Any, anthropic_content[0]).type == "text"- assert cast(Any, anthropic_content[0]).text == "Let me grab the current weather."- assert cast(Any, anthropic_content[1]).type == "tool_use"- assert cast(Any, anthropic_content[1]).id == "call_tool_combo"- assert cast(Any, anthropic_content[1]).input == {"location": "Paris"}+ assert anthropic_content[0]["type"] == "text"+ assert anthropic_content[0]["text"] == "Let me grab the current weather."+ assert anthropic_content[1]["type"] == "tool_use"+ assert anthropic_content[1]["id"] == "call_tool_combo"+ assert anthropic_content[1]["input"] == {"location": "Paris"}assert anthropic_response.get("stop_reason") == "tool_use"@@ -484,11 +484,11 @@ def test_translate_openai_content_to_anthropic_thinking_and_redacted_thinking():result = adapter._translate_openai_content_to_anthropic(choices=openai_choices)assert len(result) == 2- assert result[0].type == "thinking"- assert result[0].thinking == "I need to summar"- assert result[0].signature == "sigsig"- assert result[1].type == "redacted_thinking"- assert result[1].data == "REDACTED"+ assert result[0]["type"] == "thinking"+ assert result[0]["thinking"] == "I need to summar"+ assert result[0]["signature"] == "sigsig"+ assert result[1]["type"] == "redacted_thinking"+ assert result[1]["data"] == "REDACTED"def test_translate_streaming_openai_chunk_to_anthropic_with_thinking():@@ -1443,13 +1443,13 @@ def test_translate_openai_content_to_anthropic_reasoning_content_without_thinkinassert len(result) == 2# First block should be thinking block with reasoning_content- assert result[0].type == "thinking"- assert "Considering Letter Frequency" in result[0].thinking- assert "Calculating the Count" in result[0].thinking- assert result[0].signature is None+ assert result[0]["type"] == "thinking"+ assert "Considering Letter Frequency" in result[0]["thinking"]+ assert "Calculating the Count" in result[0]["thinking"]+ assert result[0]["signature"] is None# Second block should be text block with content- assert result[1].type == "text"- assert result[1].text == "There are **3** \"r\"s in the word strawberry."+ assert result[1]["type"] == "text"+ assert result[1]["text"] == "There are **3** \"r\"s in the word strawberry."def test_translate_streaming_openai_chunk_to_anthropic_reasoning_content_without_thinking_blocks():@@ -1522,13 +1522,13 @@ def test_translate_openai_response_to_anthropic_with_reasoning_content_only():assert len(anthropic_content) == 2# First block should be thinking- assert cast(Any, anthropic_content[0]).type == "thinking"- assert "Considering Letter Frequency" in cast(Any, anthropic_content[0]).thinking- assert cast(Any, anthropic_content[0]).signature is None+ assert anthropic_content[0]["type"] == "thinking"+ assert "Considering Letter Frequency" in anthropic_content[0]["thinking"]+ assert anthropic_content[0].get("signature") is None# Second block should be text- assert cast(Any, anthropic_content[1]).type == "text"- assert cast(Any, anthropic_content[1]).text == "There are **3** \"r\"s in the word strawberry."+ assert anthropic_content[1]["type"] == "text"+ assert anthropic_content[1]["text"] == "There are **3** \"r\"s in the word strawberry."assert anthropic_response.get("stop_reason") == "end_turn"@@ -1702,7 +1702,7 @@ def test_translate_openai_response_restores_tool_names():)# Find the tool_use block in the response- tool_use_blocks = [c for c in result["content"] if getattr(c, "type", None) == "tool_use"]+ tool_use_blocks = [c for c in result["content"] if c.get("type") == "tool_use"]assert len(tool_use_blocks) == 1# Name should be restored to original- assert getattr(tool_use_blocks[0], "name", None) == original_name+ assert tool_use_blocks[0]["name"] == original_name