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]

Anthropic - add tool cache control support (#12668)

Krish Dholakiaf6f3f151f128
diff --git a/litellm/litellm_core_utils/prompt_templates/factory.py b/litellm/litellm_core_utils/prompt_templates/factory.py
index 2a1fc6cdc88..91a5b317fd6 100644
--- a/litellm/litellm_core_utils/prompt_templates/factory.py
+++ b/litellm/litellm_core_utils/prompt_templates/factory.py
@@ -1212,6 +1212,7 @@ def convert_to_anthropic_tool_result(
AnthropicMessagesToolResultContent(
type="text",
text=content["text"],
+ cache_control=content.get("cache_control", None),
)
)
elif content["type"] == "image_url":
diff --git a/litellm/types/llms/anthropic.py b/litellm/types/llms/anthropic.py
index da94408202f..076d8e414a3 100644
--- a/litellm/types/llms/anthropic.py
+++ b/litellm/types/llms/anthropic.py
@@ -172,6 +172,7 @@ class AnthropicMessagesDocumentParam(TypedDict, total=False):
class AnthropicMessagesToolResultContent(TypedDict):
type: Literal["text"]
text: str
+ cache_control: Optional[Union[dict, ChatCompletionCachedContent]]
class AnthropicMessagesToolResultParam(TypedDict, total=False):
diff --git a/tests/llm_translation/test_anthropic_completion.py b/tests/llm_translation/test_anthropic_completion.py
index 599aff3bbe5..e3334658281 100644
--- a/tests/llm_translation/test_anthropic_completion.py
+++ b/tests/llm_translation/test_anthropic_completion.py
@@ -1374,3 +1374,67 @@ async def test_claude_tool_use_with_anthropic_acreate():
async for chunk in response:
print(chunk)
+
+
+def test_anthropic_tool_cache_control():
+ from litellm.utils import return_raw_request
+ from litellm.types.utils import CallTypes
+ import json
+
+ tool_content = "Result: 4. " * 1000 # ~10k chars
+ messages = [
+ {"role": "user", "content": "Calculate 2+2"},
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": "call_proxy_123",
+ "type": "function",
+ "function": {"name": "calc", "arguments": "{}"},
+ }
+ ],
+ },
+ {
+ "role": "tool",
+ "tool_call_id": "call_proxy_123",
+ "content": [
+ {
+ "type": "text",
+ "text": "1234567890",
+ "cache_control": {"type": "ephemeral"},
+ }
+ ],
+ },
+ ]
+
+ tools = [
+ {
+ "type": "function",
+ "function": {
+ "name": "calc",
+ "description": "Calculator",
+ "parameters": {"type": "object", "properties": {}},
+ },
+ }
+ ]
+
+ vertex_ai_model = "vertex_ai/claude-sonnet-4@20250514"
+ anthropic_api_model = "claude-sonnet-4-20250514"
+ result = return_raw_request(
+ endpoint=CallTypes.completion,
+ kwargs={
+ "model": anthropic_api_model,
+ "messages": messages + [{"role": "user", "content": "What's 1+1?"}],
+ "tools": tools,
+ "max_tokens": 50,
+ },
+ )
+
+ print(f"result: {result}")
+
+ print(result["raw_request_body"]["messages"][2])
+
+ assert "cache_control" in json.dumps(
+ result["raw_request_body"]["messages"][2]["content"]
+ )
diff --git a/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py b/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py
index 5e7a8a4c397..21395f59e5c 100644
--- a/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py
+++ b/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py
@@ -604,7 +604,7 @@ def test_vertex_ai_transform_parts():
"""
Test the _transform_parts method for converting Vertex AI function calls
to OpenAI-compatible tool calls and function calls.
-
+
Tests both:
1. Multiple tool calls within a single message
2. Multiple tool calls across different messages (cumulative indexing)
@@ -651,7 +651,9 @@ def test_vertex_ai_transform_parts():
]
function, tools, updated_idx = VertexGeminiConfig._transform_parts(
- parts=parts_with_multiple_functions, cumulative_tool_call_idx=0, is_function_call=False
+ parts=parts_with_multiple_functions,
+ cumulative_tool_call_idx=0,
+ is_function_call=False,
)
# Should return multiple tools with correct indices
@@ -671,9 +673,7 @@ def test_vertex_ai_transform_parts():
HttpxPartType(
functionCall={"name": "get_weather", "args": {"location": "Boston"}}
),
- HttpxPartType(
- functionCall={"name": "get_time", "args": {"timezone": "EST"}}
- ),
+ HttpxPartType(functionCall={"name": "get_time", "args": {"timezone": "EST"}}),
]
function, tools, updated_idx = VertexGeminiConfig._transform_parts(
@@ -695,7 +695,9 @@ def test_vertex_ai_transform_parts():
]
function, tools, updated_idx = VertexGeminiConfig._transform_parts(
- parts=second_message_parts, cumulative_tool_call_idx=updated_idx, is_function_call=False
+ parts=second_message_parts,
+ cumulative_tool_call_idx=updated_idx,
+ is_function_call=False,
)
assert function is None
@@ -710,13 +712,13 @@ def test_vertex_ai_transform_parts():
HttpxPartType(
functionCall={"name": "create_calendar_event", "args": {"title": "Meeting"}}
),
- HttpxPartType(
- functionCall={"name": "set_reminder", "args": {"time": "10:00"}}
- ),
+ HttpxPartType(functionCall={"name": "set_reminder", "args": {"time": "10:00"}}),
]
function, tools, final_idx = VertexGeminiConfig._transform_parts(
- parts=third_message_parts, cumulative_tool_call_idx=updated_idx, is_function_call=False
+ parts=third_message_parts,
+ cumulative_tool_call_idx=updated_idx,
+ is_function_call=False,
)
assert function is None
@@ -735,7 +737,9 @@ def test_vertex_ai_transform_parts():
]
function, tools, updated_idx = VertexGeminiConfig._transform_parts(
- parts=parts_without_functions, cumulative_tool_call_idx=5, is_function_call=False
+ parts=parts_without_functions,
+ cumulative_tool_call_idx=5,
+ is_function_call=False,
)
# Should return nothing and preserve the cumulative index
@@ -815,12 +819,105 @@ def test_vertex_ai_usage_metadata_missing_token_count():
}
usage_metadata = UsageMetadata(**usage_metadata)
result = v._calculate_usage(completion_response={"usageMetadata": usage_metadata})
-
+
# Should not crash and should default missing tokenCount to 0
assert result.prompt_tokens == 57
assert result.completion_tokens == 74
assert result.total_tokens == 131
- assert result.completion_tokens_details.text_tokens == 0 # Default value for missing tokenCount
- assert result.completion_tokens_details.audio_tokens == 0 # Default value for missing tokenCount
+ assert (
+ result.completion_tokens_details.text_tokens == 0
+ ) # Default value for missing tokenCount
+ assert (
+ result.completion_tokens_details.audio_tokens == 0
+ ) # Default value for missing tokenCount
+
+def test_vertex_ai_process_candidates_with_grounding_metadata():
+ from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import (
+ VertexGeminiConfig,
+ )
+
+ v = VertexGeminiConfig()
+ result = v._process_candidates(
+ _candidates=[
+ {
+ "content": {
+ "role": "model",
+ "parts": [
+ {
+ "text": " rain during the day and a 20% chance at night. The temperature will be between 56°F (13°C) and 62°F (17°C)."
+ }
+ ],
+ },
+ "finishReason": "STOP",
+ "groundingMetadata": {
+ "webSearchQueries": ["weather San Francisco today"],
+ "searchEntryPoint": {
+ "renderedContent": '<style>\n.container {\n align-items: center;\n border-radius: 8px;\n display: flex;\n font-family: Google Sans, Roboto, sans-serif;\n font-size: 14px;\n line-height: 20px;\n padding: 8px 12px;\n}\n.chip {\n display: inline-block;\n border: solid 1px;\n border-radius: 16px;\n min-width: 14px;\n padding: 5px 16px;\n text-align: center;\n user-select: none;\n margin: 0 8px;\n -webkit-tap-highlight-color: transparent;\n}\n.carousel {\n overflow: auto;\n scrollbar-width: none;\n white-space: nowrap;\n margin-right: -12px;\n}\n.headline {\n display: flex;\n margin-right: 4px;\n}\n.gradient-container {\n position: relative;\n}\n.gradient {\n position: absolute;\n transform: translate(3px, -9px);\n height: 36px;\n width: 9px;\n}\n@media (prefers-color-scheme: light) {\n .container {\n background-color: #fafafa;\n box-shadow: 0 0 0 1px #0000000f;\n }\n .headline-label {\n color: #1f1f1f;\n }\n .chip {\n background-color: #ffffff;\n border-color: #d2d2d2;\n color: #5e5e5e;\n text-decoration: none;\n }\n .chip:hover {\n background-color: #f2f2f2;\n }\n .chip:focus {\n background-color: #f2f2f2;\n }\n .chip:active {\n background-color: #d8d8d8;\n border-color: #b6b6b6;\n }\n .logo-dark {\n display: none;\n }\n .gradient {\n background: linear-gradient(90deg, #fafafa 15%, #fafafa00 100%);\n }\n}\n@media (prefers-color-scheme: dark) {\n .container {\n background-color: #1f1f1f;\n box-shadow: 0 0 0 1px #ffffff26;\n }\n .headline-label {\n color: #fff;\n }\n .chip {\n background-color: #2c2c2c;\n border-color: #3c4043;\n color: #fff;\n text-decoration: none;\n }\n .chip:hover {\n background-color: #353536;\n }\n .chip:focus {\n background-color: #353536;\n }\n .chip:active {\n background-color: #464849;\n border-color: #53575b;\n }\n .logo-light {\n display: none;\n }\n .gradient {\n background: linear-gradient(90deg, #1f1f1f 15%, #1f1f1f00 100%);\n }\n}\n</style>\n<div class="container">\n <div class="headline">\n <svg class="logo-light" width="18" height="18" viewBox="9 9 35 35" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path fill-rule="evenodd" clip-rule="evenodd" d="M42.8622 27.0064C42.8622 25.7839 42.7525 24.6084 42.5487 23.4799H26.3109V30.1568H35.5897C35.1821 32.3041 33.9596 34.1222 32.1258 35.3448V39.6864H37.7213C40.9814 36.677 42.8622 32.2571 42.8622 27.0064V27.0064Z" fill="#4285F4"/>\n <path fill-rule="evenodd" clip-rule="evenodd" d="M26.3109 43.8555C30.9659 43.8555 34.8687 42.3195 37.7213 39.6863L32.1258 35.3447C30.5898 36.3792 28.6306 37.0061 26.3109 37.0061C21.8282 37.0061 18.0195 33.9811 16.6559 29.906H10.9194V34.3573C13.7563 39.9841 19.5712 43.8555 26.3109 43.8555V43.8555Z" fill="#34A853"/>\n <path fill-rule="evenodd" clip-rule="evenodd" d="M16.6559 29.8904C16.3111 28.8559 16.1074 27.7588 16.1074 26.6146C16.1074 25.4704 16.3111 24.3733 16.6559 23.3388V18.8875H10.9194C9.74388 21.2072 9.06992 23.8247 9.06992 26.6146C9.06992 29.4045 9.74388 32.022 10.9194 34.3417L15.3864 30.8621L16.6559 29.8904V29.8904Z" fill="#FBBC05"/>\n <path fill-rule="evenodd" clip-rule="evenodd" d="M26.3109 16.2386C28.85 16.2386 31.107 17.1164 32.9095 18.8091L37.8466 13.8719C34.853 11.082 30.9659 9.3736 26.3109 9.3736C19.5712 9.3736 13.7563 13.245 10.9194 18.8875L16.6559 23.3388C18.0195 19.2636 21.8282 16.2386 26.3109 16.2386V16.2386Z" fill="#EA4335"/>\n </svg>\n <svg class="logo-dark" width="18" height="18" viewBox="0 0 48 48" xmlns="http://www.w3.org/2000/svg">\n <circle cx="24" cy="23" fill="#FFF" r="22"/>\n <path d="M33.76 34.26c2.75-2.56 4.49-6.37 4.49-11.26 0-.89-.08-1.84-.29-3H24.01v5.99h8.03c-.4 2.02-1.5 3.56-3.07 4.56v.75l3.91 2.97h.88z" fill="#4285F4"/>\n <path d="M15.58 25.77A8.845 8.845 0 0 0 24 31.86c1.92 0 3.62-.46 4.97-1.31l4.79 3.71C31.14 36.7 27.65 38 24 38c-5.93 0-11.01-3.4-13.45-8.36l.17-1.01 4.06-2.85h.8z" fill="#34A853"/>\n <path d="M15.59 20.21a8.864 8.864 0 0 0 0 5.58l-5.03 3.86c-.98-2-1.53-4.25-1.53-6.64 0-2.39.55-4.64 1.53-6.64l1-.22 3.81 2.98.22 1.08z" fill="#FBBC05"/>\n <path d="M24 14.14c2.11 0 4.02.75 5.52 1.98l4.36-4.36C31.22 9.43 27.81 8 24 8c-5.93 0-11.01 3.4-13.45 8.36l5.03 3.85A8.86 8.86 0 0 1 24 14.14z" fill="#EA4335"/>\n </svg>\n <div class="gradient-container"><div class="gradient"></div></div>\n </div>\n <div class="carousel">\n <a class="chip" href="https://vertexaisearch.cloud.google.com/grounding-api-redirect/AUZIYQGP8AFqMh5rK5GIcrn7IPR_roruBYkwl9apbI0dvDTV_9j_phIsditU7pvQPOy8mLpi6OEE_HuEGRG7LCpVT1-X4fCFmuyQwy_iyVtgZ5KgAZOW4SA1bjxDefc91H9Y8_1ehEXg02lXvwHk1CfcrrJETI2ErIqn-WGqsYpwysNLPKj_KWPzetU14WOAu5vnVIeaqwRVRTHESUahHtW1NA==">weather San Francisco today</a>\n </div>\n</div>\n'
+ },
+ "groundingChunks": [
+ {
+ "web": {
+ "uri": "https://www.google.com/search?q=weather+in+San Francisco,+CA",
+ "title": "Weather information for locality: San Francisco, administrative_area: CA",
+ "domain": "google.com",
+ }
+ }
+ ],
+ "groundingSupports": [
+ {
+ "segment": {
+ "endIndex": 90,
+ "text": "The weather in San Francisco, California today, Wednesday, July 16, 2025, is mostly cloudy",
+ },
+ "groundingChunkIndices": [0],
+ "confidenceScores": [0.6749268],
+ },
+ {
+ "segment": {
+ "startIndex": 92,
+ "endIndex": 157,
+ "text": "The temperature is 61°F (16°C), but it feels like 58°F (15°C)",
+ },
+ "groundingChunkIndices": [0],
+ "confidenceScores": [0.96708393],
+ },
+ {
+ "segment": {
+ "startIndex": 159,
+ "endIndex": 219,
+ "text": "The humidity is around 77%, and there is a 0% chance of rain",
+ },
+ "groundingChunkIndices": [0],
+ "confidenceScores": [0.8192763],
+ },
+ {
+ "segment": {
+ "startIndex": 221,
+ "endIndex": 360,
+ "text": "The forecast for today is cloudy during the day and light rain at night, with a 10% chance of rain during the day and a 20% chance at night",
+ },
+ "groundingChunkIndices": [0],
+ "confidenceScores": [0.875334],
+ },
+ {
+ "segment": {
+ "startIndex": 362,
+ "endIndex": 425,
+ "text": "The temperature will be between 56°F (13°C) and 62°F (17°C)",
+ },
+ "groundingChunkIndices": [0],
+ "confidenceScores": [0.8203865],
+ },
+ ],
+ "retrievalMetadata": {},
+ },
+ }
+ ],
+ model_response=ModelResponse(),
+ standard_optional_params={},
+ )
+ print(result)
+ assert isinstance(result[0], list)
+ assert len(result[0]) == 1