Skip to content

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]

fix(bedrock): deduplicate tool calls in assistant history (#15178) (#19324)

0x1f99d1cce71855140
diff --git a/docs/my-website/docs/providers/vertex.md b/docs/my-website/docs/providers/vertex.md
index 33ebf535d29..be2bf86ab10 100644
--- a/docs/my-website/docs/providers/vertex.md
+++ b/docs/my-website/docs/providers/vertex.md
@@ -1390,6 +1390,77 @@ model_list:
+### **Workload Identity Federation**
+
+LiteLLM supports [Google Cloud Workload Identity Federation (WIF)](https://cloud.google.com/iam/docs/workload-identity-federation), which allows you to grant on-premises or multi-cloud workloads access to Google Cloud resources without using a service account key. This is the recommended approach for workloads running in other cloud environments (AWS, Azure, etc.) or on-premises.
+
+To use Workload Identity Federation, pass the path to your WIF credentials configuration file via `vertex_credentials`:
+
+<Tabs>
+<TabItem value="sdk" label="SDK">
+
+```python
+from litellm import completion
+
+response = completion(
+ model="vertex_ai/gemini-1.5-pro",
+ messages=[{"role": "user", "content": "Hello!"}],
+ vertex_credentials="/path/to/wif-credentials.json", # 👈 WIF credentials file
+ vertex_project="your-gcp-project-id",
+ vertex_location="us-central1"
+)
+```
+
+</TabItem>
+<TabItem value="proxy" label="PROXY">
+
+```yaml
+model_list:
+ - model_name: gemini-model
+ litellm_params:
+ model: vertex_ai/gemini-1.5-pro
+ vertex_project: your-gcp-project-id
+ vertex_location: us-central1
+ vertex_credentials: /path/to/wif-credentials.json # 👈 WIF credentials file
+```
+
+Alternatively, you can create credentials in **LLM Credentials** in the LiteLLM UI and use those to authenticate your models:
+
+```yaml
+model_list:
+ - model_name: gemini-model
+ litellm_params:
+ model: vertex_ai/gemini-1.5-pro
+ vertex_project: your-gcp-project-id
+ vertex_location: us-central1
+ litellm_credential_name: my-vertex-wif-credential # 👈 Reference credential stored in UI
+```
+
+</TabItem>
+</Tabs>
+
+**WIF Credentials File Format**
+
+Your WIF credentials JSON file typically looks like this (for AWS federation):
+
+```json
+{
+ "type": "external_account",
+ "audience": "//iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID",
+ "subject_token_type": "urn:ietf:params:aws:token-type:aws4_request",
+ "service_account_impersonation_url": "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/SERVICE_ACCOUNT_EMAIL:generateAccessToken",
+ "token_url": "https://sts.googleapis.com/v1/token",
+ "credential_source": {
+ "environment_id": "aws1",
+ "region_url": "http://169.254.169.254/latest/meta-data/placement/availability-zone",
+ "url": "http://169.254.169.254/latest/meta-data/iam/security-credentials",
+ "regional_cred_verification_url": "https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15"
+ }
+}
+```
+
+For more details on setting up Workload Identity Federation, see [Google Cloud WIF documentation](https://cloud.google.com/iam/docs/workload-identity-federation).
+
### **Environment Variables**
You can set:
diff --git a/litellm/litellm_core_utils/prompt_templates/factory.py b/litellm/litellm_core_utils/prompt_templates/factory.py
index 43ed23587d8..a5fb6f1597c 100644
--- a/litellm/litellm_core_utils/prompt_templates/factory.py
+++ b/litellm/litellm_core_utils/prompt_templates/factory.py
@@ -6,7 +6,7 @@ import mimetypes
import re
import xml.etree.ElementTree as ET
from enum import Enum
-from typing import Any, Dict, List, Optional, Tuple, Union, cast, overload
+from typing import Any, Dict, List, Optional, Set, Tuple, Union, cast, overload
from jinja2.sandbox import ImmutableSandboxedEnvironment
@@ -2143,6 +2143,9 @@ def anthropic_messages_pt( # noqa: PLR0915
if user_content:
new_messages.append({"role": "user", "content": user_content})
+ # Track unique tool IDs in this merge block to avoid duplication
+ unique_tool_ids: Set[str] = set()
+
assistant_content: List[AnthropicMessagesAssistantMessageValues] = []
## MERGE CONSECUTIVE ASSISTANT CONTENT ##
while msg_i < len(messages) and messages[msg_i]["role"] == "assistant":
@@ -2236,13 +2239,25 @@ def anthropic_messages_pt( # noqa: PLR0915
assistant_tool_calls,
web_search_results=_web_search_results,
)
- # AnthropicMessagesAssistantMessageValues includes AnthropicMessagesToolUseParam
- assistant_content.extend(
- cast(
- List[AnthropicMessagesAssistantMessageValues],
- tool_invoke_results,
+
+ # Prevent "tool_use ids must be unique" errors by filtering duplicates
+ # This can happen when merging history that already contains the tool calls
+ for item in tool_invoke_results:
+ # tool_use items are typically dicts, but handle objects just in case
+ item_id = (
+ item.get("id")
+ if isinstance(item, dict)
+ else getattr(item, "id", None)
+ )
+
+ if item_id:
+ if item_id in unique_tool_ids:
+ continue
+ unique_tool_ids.add(item_id)
+
+ assistant_content.append(
+ cast(AnthropicMessagesAssistantMessageValues, item)
)
- )
assistant_function_call = assistant_content_block.get("function_call")
diff --git a/litellm/responses/litellm_completion_transformation/transformation.py b/litellm/responses/litellm_completion_transformation/transformation.py
index ad910c9cd97..eaa80c6cfe4 100644
--- a/litellm/responses/litellm_completion_transformation/transformation.py
+++ b/litellm/responses/litellm_completion_transformation/transformation.py
@@ -2,7 +2,8 @@
Handles transforming from Responses API -> LiteLLM completion (Chat Completion API)
"""
-from typing import Any, Dict, List, Literal, Optional, Tuple, Union, cast
+from collections.abc import Sequence
+from typing import Any, Dict, List, Literal, Optional, Set, Tuple, Union, cast
from openai.types.responses import ResponseFunctionToolCall
from openai.types.responses.tool_param import FunctionToolParam
@@ -378,6 +379,7 @@ class LiteLLMCompletionResponsesConfig:
if isinstance(input, str):
messages.append(ChatCompletionUserMessage(role="user", content=input))
elif isinstance(input, list):
+ existing_tool_call_ids: Set[str] = set()
for _input in input:
chat_completion_messages = LiteLLMCompletionResponsesConfig._transform_responses_api_input_item_to_chat_completion_message(
input_item=_input
@@ -390,12 +392,98 @@ class LiteLLMCompletionResponsesConfig:
input_item=_input
):
tool_call_output_messages.extend(chat_completion_messages)
- else:
- messages.extend(chat_completion_messages)
+ continue
+
+ if LiteLLMCompletionResponsesConfig._is_input_item_function_call(
+ input_item=_input
+ ):
+ call_id_raw = _input.get("call_id") or _input.get("id") or ""
+ if call_id_raw:
+ existing_tool_call_ids.add(str(call_id_raw))
+
+ messages.extend(chat_completion_messages)
- messages.extend(tool_call_output_messages)
+ deduped_tool_call_messages = (
+ LiteLLMCompletionResponsesConfig._deduplicate_tool_call_output_messages(
+ tool_call_output_messages=tool_call_output_messages,
+ existing_tool_call_ids=existing_tool_call_ids,
+ )
+ )
+ messages.extend(deduped_tool_call_messages)
return messages
+ @staticmethod
+ def _deduplicate_tool_call_output_messages(
+ tool_call_output_messages: List[
+ Union[
+ AllMessageValues,
+ GenericChatCompletionMessage,
+ ChatCompletionMessageToolCall,
+ ChatCompletionResponseMessage,
+ ]
+ ],
+ existing_tool_call_ids: Set[str],
+ ) -> List[
+ Union[
+ AllMessageValues,
+ GenericChatCompletionMessage,
+ ChatCompletionMessageToolCall,
+ ChatCompletionResponseMessage,
+ ]
+ ]:
+ """Return tool call outputs after dropping assistant entries with duplicate call_ids."""
+ if not tool_call_output_messages:
+ return []
+
+ filtered_messages: List[
+ Union[
+ AllMessageValues,
+ GenericChatCompletionMessage,
+ ChatCompletionMessageToolCall,
+ ChatCompletionResponseMessage,
+ ]
+ ] = []
+ seen_tool_call_ids: Set[str] = set(existing_tool_call_ids)
+
+ for tool_call_message in tool_call_output_messages:
+ if isinstance(tool_call_message, dict):
+ role = tool_call_message.get("role", "")
+ else:
+ role = getattr(tool_call_message, "role", "")
+ call_id = ""
+
+ if role == "assistant":
+ tool_calls: Any = None
+ if isinstance(tool_call_message, dict):
+ tool_calls = tool_call_message.get("tool_calls")
+ else:
+ tool_calls = getattr(tool_call_message, "tool_calls", None)
+
+ if (
+ isinstance(tool_calls, Sequence)
+ and not isinstance(tool_calls, (str, bytes))
+ and len(tool_calls) > 0
+ ):
+ first_call = tool_calls[0]
+ call_id_raw = None
+ if isinstance(first_call, dict):
+ call_id_raw = first_call.get("id")
+ else:
+ call_id_raw = getattr(first_call, "id", None)
+
+ if call_id_raw:
+ call_id = str(call_id_raw)
+
+ if call_id and call_id in seen_tool_call_ids and role == "assistant":
+ continue
+
+ if call_id and role == "assistant":
+ seen_tool_call_ids.add(call_id)
+
+ filtered_messages.append(tool_call_message)
+
+ return filtered_messages
+
@staticmethod
def _ensure_tool_call_output_has_corresponding_tool_call(
messages: List[Union[AllMessageValues, GenericChatCompletionMessage]],
diff --git a/litellm/responses/mcp/mcp_streaming_iterator.py b/litellm/responses/mcp/mcp_streaming_iterator.py
index c00c2a2f3b2..ac040d3d6ec 100644
--- a/litellm/responses/mcp/mcp_streaming_iterator.py
+++ b/litellm/responses/mcp/mcp_streaming_iterator.py
@@ -655,7 +655,6 @@ class MCPEnhancedStreamingIterator(BaseResponsesAPIStreamingIterator):
follow_up_params.update(
{
"input": follow_up_input,
- "previous_response_id": self.collected_response.id, # type: ignore[attr-defined]
"stream": True,
}
)
diff --git a/tests/litellm_core_utils/test_anthropic_dedup_factory.py b/tests/litellm_core_utils/test_anthropic_dedup_factory.py
new file mode 100644
index 00000000000..99248db0aec
--- /dev/null
+++ b/tests/litellm_core_utils/test_anthropic_dedup_factory.py
@@ -0,0 +1,83 @@
+
+import sys
+import os
+import pytest
+sys.path.insert(0, os.path.abspath("."))
+
+from litellm.litellm_core_utils.prompt_templates.factory import anthropic_messages_pt
+
+def test_anthropic_deduplication_logic():
+ """
+ Verify that anthropic_messages_pt correctly deduplicates tool calls
+ when merging consecutive assistant messages.
+
+ Scenario:
+ - User message
+ - Assistant message with tool call A
+ - Assistant message (merged) with tool call A (duplicate) and tool call B (new)
+
+ Expected Result:
+ - Assistant message contains tool call A and tool call B exactly once.
+ """
+ messages = [
+ {"role": "user", "content": "Weather in Paris?"},
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": "tool_call_unique_1",
+ "type": "function",
+ "function": {"name": "get_weather", "arguments": "{}"}
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": "tool_call_unique_1", # Duplicate! Should be removed
+ "type": "function",
+ "function": {"name": "get_weather", "arguments": "{}"}
+ },
+ {
+ "id": "tool_call_unique_2", # New! Should be kept
+ "type": "function",
+ "function": {"name": "get_time", "arguments": "{}"}
+ }
+ ]
+ }
+ ]
+
+ # Run transformation
+ # We pass dummy model/provider args as they are required but valid for this test
+ result = anthropic_messages_pt(
+ messages=messages,
+ model="claude-3-opus-20240229",
+ llm_provider="anthropic"
+ )
+
+ # Inspect results
+ # We expect 1 user message and 1 merged assistant message
+ assert len(result) == 2
+ assert result[0]["role"] == "user"
+ assert result[1]["role"] == "assistant"
+
+ assistant_content = result[1]["content"]
+
+ # Filter for tool_use blocks
+ tool_uses = [
+ b for b in assistant_content
+ if isinstance(b, dict) and b.get("type") == "tool_use"
+ ]
+
+ # We expect exactly 2 tool uses (one for unique_1, one for unique_2)
+ # The duplicate unique_1 should be gone.
+ assert len(tool_uses) == 2
+
+ ids = [t["id"] for t in tool_uses]
+ assert "tool_call_unique_1" in ids
+ assert "tool_call_unique_2" in ids
+ assert ids.count("tool_call_unique_1") == 1
+ assert ids.count("tool_call_unique_2") == 1
diff --git a/tests/mcp_tests/test_aresponses_api_with_mcp.py b/tests/mcp_tests/test_aresponses_api_with_mcp.py
index 865a580f0ca..57c79039ee0 100644
--- a/tests/mcp_tests/test_aresponses_api_with_mcp.py
+++ b/tests/mcp_tests/test_aresponses_api_with_mcp.py
@@ -1,3 +1,4 @@
+import logging
import os
import sys
import pytest
@@ -660,16 +661,25 @@ async def test_streaming_mcp_events_validation():
@pytest.mark.asyncio
-async def test_streaming_responses_api_with_mcp_tools():
+ "model",
+ [
+ pytest.param("gpt-4o-mini", id="openai"),
+ pytest.param("claude-haiku-4-5", id="anthropic"),
+ ],
+)
+async def test_streaming_responses_api_with_mcp_tools(
+ model: str, caplog: pytest.LogCaptureFixture
+):
"""
Test the streaming responses API with MCP tools when using server_url="litellm_proxy"
Under the hood the follow occurs
- MCP: responses called litellm MCP manager.list_tools (MOCKED)
- - Request 1: Made to gpt-4o with fetched tools (REAL LLM CALL)
+ - Request 1: Made to model under test with fetched tools (REAL LLM CALL)
- MCP: Execute tool call from request 1 and returns result (MOCKED)
- - Request 2: Made to gpt-4o with fetched tools and tool results (REAL LLM CALL)
+ - Request 2: Made to model under test with fetched tools and tool results (REAL LLM CALL)
Return the user the result of request 2
"""
@@ -693,75 +703,101 @@ async def test_streaming_responses_api_with_mcp_tools():
]
# Only mock the MCP-specific operations, let LLM responses be real
- with patch.object(LiteLLM_Proxy_MCP_Handler, '_get_mcp_tools_from_manager', new_callable=AsyncMock) as mock_get_tools, \
- patch.object(LiteLLM_Proxy_MCP_Handler, '_execute_tool_calls', new_callable=AsyncMock) as mock_execute_tools:
-
- # Setup MCP mocks only
- mock_get_tools.return_value = (mock_mcp_tools, ["litellm_proxy"])
-
- # Create a dynamic mock that will match the actual tool call ID from the LLM response
- def mock_execute_tool_calls_side_effect(tool_calls, user_api_key_auth):
- """Mock function that returns results matching the actual tool call IDs from the LLM"""
- results = []
- for tool_call in tool_calls:
- # Extract call_id from the tool call
- call_id = None
- if isinstance(tool_call, dict):
- call_id = tool_call.get("call_id") or tool_call.get("id")
- elif hasattr(tool_call, 'call_id'):
- call_id = tool_call.call_id
- elif hasattr(tool_call, 'id'):
- call_id = tool_call.id
-
- if call_id:
- results.append({
- "tool_call_id": call_id,
- "result": "LiteLLM is a unified interface for 100+ LLMs that translates inputs to provider-specific completion endpoints and provides consistent OpenAI-format output."
- })
- return results
-
- mock_execute_tools.side_effect = mock_execute_tool_calls_side_effect
-
- # Make the actual call - LLM responses will be real
- mcp_tool_config = cast(Any, {
- "type": "mcp",
- "server_url": "litellm_proxy",
- "require_approval": "never"
- })
- response = await litellm.aresponses(
- model="gpt-4o-mini",
- tools=[mcp_tool_config],
- tool_choice="required",
- input=[
+ with caplog.at_level(logging.ERROR):
+ with patch.object(
+ LiteLLM_Proxy_MCP_Handler,
+ '_get_mcp_tools_from_manager',
+ new_callable=AsyncMock,
+ ) as mock_get_tools, patch.object(
+ LiteLLM_Proxy_MCP_Handler,
+ '_execute_tool_calls',
+ new_callable=AsyncMock,
+ ) as mock_execute_tools:
+ # Setup MCP mocks only
+ mock_get_tools.return_value = (mock_mcp_tools, ["litellm_proxy"])
+
+ # Create a dynamic mock that will match the actual tool call ID from the LLM response
+ def mock_execute_tool_calls_side_effect(
+ tool_calls, user_api_key_auth, **kwargs
+ ):
+ """Mock function that returns results matching the actual tool call IDs from the LLM"""
+ results = []
+ for tool_call in tool_calls:
+ # Extract call_id from the tool call
+ call_id = None
+ if isinstance(tool_call, dict):
+ call_id = tool_call.get("call_id") or tool_call.get("id")
+ elif hasattr(tool_call, 'call_id'):
+ call_id = tool_call.call_id
+ elif hasattr(tool_call, 'id'):
+ call_id = tool_call.id
+
+ if call_id:
+ results.append(
+ {
+ "tool_call_id": call_id,
+ "result": "LiteLLM is a unified interface for 100+ LLMs that translates inputs to provider-specific completion endpoints and provides consistent OpenAI-format output.",
+ }
+ )
+ return results
+
+ mock_execute_tools.side_effect = mock_execute_tool_calls_side_effect
+
+ # Make the actual call - LLM responses will be real
+ mcp_tool_config = cast(
+ Any,
{
- "role": "user",
- "type": "message",
- "content": "give me a TLDR of what BerriAI/litellm is about"
- }
- ],
- stream=True
- )
-
- print(f"📋 Response type: {type(response)}")
- assert hasattr(response, '__aiter__'), "Response should be an async streaming response"
-
- # Collect streaming chunks
- chunks = []
- async for chunk in response:
- chunks.append(chunk)
- print(f"📦 Chunk type: {getattr(chunk, 'type', 'unknown')}")
-
- print(f"📊 Total chunks received: {len(chunks)}")
-
- # Verify MCP mocks were called (may be called multiple times in streaming)
- assert mock_get_tools.call_count >= 1, f"Expected MCP tools to be fetched at least once, got {mock_get_tools.call_count}"
- print(f"MCP tools fetched: {len(mock_mcp_tools)}")
-
- # Verify we got a response
- assert response is not None
- assert len(chunks) > 0, "Should have received streaming chunks"
-
- print("Basic streaming responses API with MCP tools test passed!")
+ "type": "mcp",
+ "server_url": "litellm_proxy",
+ "require_approval": "never",
+ },
+ )
+ response = await litellm.aresponses(
+ model=model,
+ tools=[mcp_tool_config],
+ tool_choice="required",
+ input=[
+ {
+ "role": "user",
+ "type": "message",
+ "content": "give me a TLDR of what BerriAI/litellm is about",
+ }
+ ],
+ stream=True,
+ )
+
+ print(f"📋 Response type: {type(response)}")
+ assert hasattr(response, '__aiter__'), "Response should be an async streaming response"
+
+ # Collect streaming chunks
+ chunks = []
+ async for chunk in response:
+ chunks.append(chunk)
+ print(f"📦 Chunk type: {getattr(chunk, 'type', 'unknown')}")
+
+ print(f"📊 Total chunks received: {len(chunks)}")
+
+ # Verify MCP mocks were called (may be called multiple times in streaming)
+ assert (
+ mock_get_tools.call_count >= 1
+ ), f"Expected MCP tools to be fetched at least once, got {mock_get_tools.call_count}"
+ print(f"MCP tools fetched: {len(mock_mcp_tools)}")
+
+ # Verify we got a response
+ assert response is not None
+ assert len(chunks) > 0, "Should have received streaming chunks"
+
+ print("Basic streaming responses API with MCP tools test passed!")
+
+ lite_errors = [
+ record
+ for record in caplog.records
+ if record.levelno >= logging.ERROR
+ and ("LiteLLM" in record.name or "LiteLLM" in record.getMessage())
+ ]
+ assert not lite_errors, "Unexpected LiteLLM errors: " + ", ".join(
+ record.getMessage() for record in lite_errors
+ )
@pytest.mark.asyncio