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]

Add Anthropic cache control option to image tool call results (#18674)

Felipe Peter0756b48963c0
diff --git a/litellm/litellm_core_utils/prompt_templates/factory.py b/litellm/litellm_core_utils/prompt_templates/factory.py
index 12570a02de7..cbb31be146c 100644
--- a/litellm/litellm_core_utils/prompt_templates/factory.py
+++ b/litellm/litellm_core_utils/prompt_templates/factory.py
@@ -1645,9 +1645,12 @@ def convert_to_anthropic_tool_result(
)
elif content["type"] == "image_url":
format = content["image_url"].get("format") if isinstance(content["image_url"], dict) else None
- anthropic_content_list.append(
- create_anthropic_image_param(content["image_url"], format=format)
+ _anthropic_image_param = create_anthropic_image_param(content["image_url"], format=format)
+ _anthropic_image_param = add_cache_control_to_content(
+ anthropic_content_element=_anthropic_image_param,
+ original_content_element=content,
)
+ anthropic_content_list.append(_anthropic_image_param)
anthropic_content = anthropic_content_list
anthropic_tool_result: Optional[AnthropicMessagesToolResultParam] = None
diff --git a/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.py b/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.py
index c8fe6efeaa1..a4188f03cde 100644
--- a/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.py
+++ b/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.py
@@ -620,26 +620,26 @@ def test_bedrock_tools_unpack_defs():
def test_bedrock_image_processor_content_type_fallback_url_extension():
"""
- Test that _post_call_image_processing falls back to URL extension
+ Test that _post_call_image_processing falls back to URL extension
when content-type is binary/octet-stream or application/octet-stream
"""
import base64
-
+
# Create mock response with binary/octet-stream content-type
mock_response = MagicMock()
mock_response.headers.get.return_value = "binary/octet-stream"
-
+
# Create a simple PNG header (magic bytes)
png_header = b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a"
png_content = png_header + b"\x00" * 100 # Add some padding
mock_response.content = png_content
-
+
# Test with .png URL
image_url = "https://example.com/test-image.png"
base64_bytes, content_type = BedrockImageProcessor._post_call_image_processing(
mock_response, image_url
)
-
+
assert content_type == "image/png"
assert base64_bytes == base64.b64encode(png_content).decode("utf-8")
@@ -650,22 +650,22 @@ def test_bedrock_image_processor_content_type_fallback_binary_detection():
when content-type is missing and URL extension is not recognized
"""
import base64
-
+
# Create mock response with no content-type
mock_response = MagicMock()
mock_response.headers.get.return_value = None
-
+
# Create a JPEG header (magic bytes)
jpeg_header = b"\xff\xd8\xff"
jpeg_content = jpeg_header + b"\x00" * 100 # Add some padding
mock_response.content = jpeg_content
-
+
# Test with URL without extension
image_url = "https://example.com/test-image-without-extension"
base64_bytes, content_type = BedrockImageProcessor._post_call_image_processing(
mock_response, image_url
)
-
+
assert content_type == "image/jpeg"
assert base64_bytes == base64.b64encode(jpeg_content).decode("utf-8")
@@ -675,22 +675,22 @@ def test_bedrock_image_processor_content_type_fallback_application_octet_stream(
Test that _post_call_image_processing handles application/octet-stream correctly
"""
import base64
-
+
# Create mock response with application/octet-stream content-type
mock_response = MagicMock()
mock_response.headers.get.return_value = "application/octet-stream"
-
+
# Create a GIF header (magic bytes)
gif_header = b"GIF8" + b"\x00" + b"a"
gif_content = gif_header + b"\x00" * 100 # Add some padding
mock_response.content = gif_content
-
+
# Test with .gif URL
image_url = "https://s3.amazonaws.com/bucket/image.gif"
base64_bytes, content_type = BedrockImageProcessor._post_call_image_processing(
mock_response, image_url
)
-
+
assert content_type == "image/gif"
assert base64_bytes == base64.b64encode(gif_content).decode("utf-8")
@@ -700,22 +700,22 @@ def test_bedrock_image_processor_content_type_with_query_params():
Test that _post_call_image_processing correctly extracts extension from URL with query parameters
"""
import base64
-
+
# Create mock response with binary/octet-stream content-type
mock_response = MagicMock()
mock_response.headers.get.return_value = "binary/octet-stream"
-
+
# Create a WebP header (magic bytes)
webp_header = b"RIFF" + b"\x00\x00\x00\x00" + b"WEBP"
webp_content = webp_header + b"\x00" * 100 # Add some padding
mock_response.content = webp_content
-
+
# Test with URL containing query parameters (common in S3 signed URLs)
image_url = "https://s3.amazonaws.com/bucket/image.webp?AWSAccessKeyId=123&Expires=456&Signature=789"
base64_bytes, content_type = BedrockImageProcessor._post_call_image_processing(
mock_response, image_url
)
-
+
assert content_type == "image/webp"
assert base64_bytes == base64.b64encode(webp_content).decode("utf-8")
@@ -725,21 +725,21 @@ def test_bedrock_image_processor_content_type_normal_header():
Test that _post_call_image_processing works normally when content-type is correctly set
"""
import base64
-
+
# Create mock response with correct content-type
mock_response = MagicMock()
mock_response.headers.get.return_value = "image/png"
-
+
# Create a PNG header
png_header = b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a"
png_content = png_header + b"\x00" * 100
mock_response.content = png_content
-
+
image_url = "https://example.com/test-image.png"
base64_bytes, content_type = BedrockImageProcessor._post_call_image_processing(
mock_response, image_url
)
-
+
assert content_type == "image/png"
assert base64_bytes == base64.b64encode(png_content).decode("utf-8")
@@ -751,16 +751,16 @@ def test_bedrock_image_processor_content_type_fallback_failure():
# Create mock response with binary/octet-stream content-type
mock_response = MagicMock()
mock_response.headers.get.return_value = "binary/octet-stream"
-
+
# Create content with unrecognizable image format
mock_response.content = b"\x00" * 100
-
+
# Test with URL without recognizable extension
image_url = "https://example.com/unknown-file"
-
+
with pytest.raises(ValueError) as excinfo:
BedrockImageProcessor._post_call_image_processing(mock_response, image_url)
-
+
assert "Unable to determine content type" in str(excinfo.value)
@@ -771,18 +771,18 @@ def test_bedrock_image_processor_content_type_jpeg_variants():
# Create mock response with binary/octet-stream
mock_response = MagicMock()
mock_response.headers.get.return_value = "binary/octet-stream"
-
+
jpeg_header = b"\xff\xd8\xff"
jpeg_content = jpeg_header + b"\x00" * 100
mock_response.content = jpeg_content
-
+
# Test with .jpg extension
image_url_jpg = "https://example.com/photo.jpg"
_, content_type_jpg = BedrockImageProcessor._post_call_image_processing(
mock_response, image_url_jpg
)
assert content_type_jpg == "image/jpeg"
-
+
# Test with .jpeg extension
image_url_jpeg = "https://example.com/photo.jpeg"
_, content_type_jpeg = BedrockImageProcessor._post_call_image_processing(
@@ -797,22 +797,22 @@ def test_bedrock_image_processor_content_type_pdf_document():
when content-type is binary/octet-stream
"""
import base64
-
+
# Create mock response with binary/octet-stream content-type
mock_response = MagicMock()
mock_response.headers.get.return_value = "binary/octet-stream"
-
+
# Create a PDF header (magic bytes: %PDF)
pdf_header = b"%PDF-1.4"
pdf_content = pdf_header + b"\x00" * 100
mock_response.content = pdf_content
-
+
# Test with .pdf URL
pdf_url = "https://s3.amazonaws.com/bucket/document.pdf"
base64_bytes, content_type = BedrockImageProcessor._post_call_image_processing(
mock_response, pdf_url
)
-
+
assert content_type == "application/pdf"
assert base64_bytes == base64.b64encode(pdf_content).decode("utf-8")
@@ -822,12 +822,12 @@ def test_bedrock_image_processor_content_type_document_formats():
Test that _post_call_image_processing handles various document formats
"""
import base64
-
+
# Create mock response
mock_response = MagicMock()
mock_response.headers.get.return_value = "application/octet-stream"
mock_response.content = b"\x00" * 100
-
+
# Test various document formats
test_cases = [
("https://example.com/doc.pdf", "application/pdf"),
@@ -837,7 +837,7 @@ def test_bedrock_image_processor_content_type_document_formats():
("https://example.com/page.html", "text/html"),
("https://example.com/readme.txt", "text/plain"),
]
-
+
for url, expected_mime in test_cases:
_, content_type = BedrockImageProcessor._post_call_image_processing(
mock_response, url
@@ -850,21 +850,21 @@ def test_bedrock_image_processor_content_type_s3_pdf_with_query():
Test that _post_call_image_processing handles S3 PDF with query parameters
"""
import base64
-
+
# Create mock response
mock_response = MagicMock()
mock_response.headers.get.return_value = "binary/octet-stream"
-
+
pdf_content = b"%PDF-1.4" + b"\x00" * 100
mock_response.content = pdf_content
-
+
# S3 signed URL with query parameters
s3_url = "https://my-bucket.s3.us-east-1.amazonaws.com/documents/report.pdf?AWSAccessKeyId=AKIAIOSFODNN7EXAMPLE&Expires=1234567890&Signature=abcdef123456"
-
+
base64_bytes, content_type = BedrockImageProcessor._post_call_image_processing(
mock_response, s3_url
)
-
+
assert content_type == "application/pdf"
assert base64_bytes == base64.b64encode(pdf_content).decode("utf-8")
@@ -1137,3 +1137,169 @@ def test_bedrock_create_bedrock_block_different_document_formats():
assert f"DocumentPDFmessages_" in block["document"]["name"]
assert block["document"]["name"].endswith(f"_{format_type}")
assert block["document"]["format"] == format_type
+
+
+def test_convert_to_anthropic_tool_result_image_with_cache_control():
+ """
+ Test that cache_control is properly applied to image content in tool results.
+ This tests the functionality added in the uncommitted changes where
+ add_cache_control_to_content is called for image_url content types.
+ """
+ from litellm.litellm_core_utils.prompt_templates.factory import (
+ convert_to_anthropic_tool_result,
+ )
+
+ # Test with base64 image data URI
+ message = {
+ "role": "tool",
+ "tool_call_id": "call_test_123",
+ "content": [
+ {
+ "type": "text",
+ "text": "Here is the image you requested:",
+ },
+ {
+ "type": "image_url",
+ "image_url": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQ",
+ "cache_control": {"type": "ephemeral"},
+ },
+ ],
+ }
+
+ result = convert_to_anthropic_tool_result(message)
+
+ # Verify the result structure
+ assert result["type"] == "tool_result"
+ assert result["tool_use_id"] == "call_test_123"
+ assert isinstance(result["content"], list)
+ assert len(result["content"]) == 2
+
+ # Verify text content
+ assert result["content"][0]["type"] == "text"
+ assert result["content"][0]["text"] == "Here is the image you requested:"
+
+ # Verify image content with cache_control
+ assert result["content"][1]["type"] == "image"
+ assert result["content"][1]["source"]["type"] == "base64"
+ assert result["content"][1]["source"]["media_type"] == "image/jpeg"
+ assert "cache_control" in result["content"][1]
+ assert result["content"][1]["cache_control"]["type"] == "ephemeral"
+
+
+def test_convert_to_anthropic_tool_result_image_without_cache_control():
+ """
+ Test that images without cache_control in tool results work correctly.
+ """
+ from litellm.litellm_core_utils.prompt_templates.factory import (
+ convert_to_anthropic_tool_result,
+ )
+
+ message = {
+ "role": "tool",
+ "tool_call_id": "call_test_456",
+ "content": [
+ {
+ "type": "image_url",
+ "image_url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA",
+ },
+ ],
+ }
+
+ result = convert_to_anthropic_tool_result(message)
+
+ # Verify the result structure
+ assert result["type"] == "tool_result"
+ assert result["tool_use_id"] == "call_test_456"
+ assert isinstance(result["content"], list)
+ assert len(result["content"]) == 1
+
+ # Verify image content without cache_control (cache_control will be None if not set)
+ assert result["content"][0]["type"] == "image"
+ assert result["content"][0]["source"]["type"] == "base64"
+ assert result["content"][0]["source"]["media_type"] == "image/png"
+ assert result["content"][0].get("cache_control") is None
+
+
+def test_convert_to_anthropic_tool_result_mixed_content_with_cache_control():
+ """
+ Test tool results with mixed content types (text and image) where only some have cache_control.
+ """
+ from litellm.litellm_core_utils.prompt_templates.factory import (
+ convert_to_anthropic_tool_result,
+ )
+
+ message = {
+ "role": "tool",
+ "tool_call_id": "call_test_789",
+ "content": [
+ {
+ "type": "text",
+ "text": "First image:",
+ "cache_control": {"type": "ephemeral"},
+ },
+ {
+ "type": "image_url",
+ "image_url": "data:image/jpeg;base64,/9j/4AAQSkZJRg",
+ "cache_control": {"type": "ephemeral"},
+ },
+ {
+ "type": "text",
+ "text": "Second image (no cache):",
+ },
+ {
+ "type": "image_url",
+ "image_url": "data:image/png;base64,iVBORw0KGgo",
+ },
+ ],
+ }
+
+ result = convert_to_anthropic_tool_result(message)
+
+ assert result["type"] == "tool_result"
+ assert isinstance(result["content"], list)
+ assert len(result["content"]) == 4
+
+ # First text with cache_control
+ assert result["content"][0]["type"] == "text"
+ assert result["content"][0]["cache_control"]["type"] == "ephemeral"
+
+ # First image with cache_control
+ assert result["content"][1]["type"] == "image"
+ assert result["content"][1]["cache_control"]["type"] == "ephemeral"
+
+ # Second text without cache_control (cache_control will be None if not set)
+ assert result["content"][2]["type"] == "text"
+ assert result["content"][2].get("cache_control") is None
+
+ # Second image without cache_control (cache_control will be None if not set)
+ assert result["content"][3]["type"] == "image"
+ assert result["content"][3].get("cache_control") is None
+
+
+def test_convert_to_anthropic_tool_result_image_url_as_http():
+ """
+ Test that HTTP/HTTPS URLs with cache_control are handled correctly.
+ """
+ from litellm.litellm_core_utils.prompt_templates.factory import (
+ convert_to_anthropic_tool_result,
+ )
+
+ message = {
+ "role": "tool",
+ "tool_call_id": "call_http_001",
+ "content": [
+ {
+ "type": "image_url",
+ "image_url": "https://example.com/image.jpg",
+ "cache_control": {"type": "ephemeral"},
+ },
+ ],
+ }
+
+ result = convert_to_anthropic_tool_result(message)
+
+ # Verify image is passed as URL reference with cache_control
+ assert result["content"][0]["type"] == "image"
+ assert result["content"][0]["source"]["type"] == "url"
+ assert result["content"][0]["source"]["url"] == "https://example.com/image.jpg"
+ assert result["content"][0]["cache_control"]["type"] == "ephemeral"