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
google genai adapter inline data support (#18477)
Lu37c908caf977
diff --git a/litellm/google_genai/adapters/transformation.py b/litellm/google_genai/adapters/transformation.pyindex 9d3f990b1aa..58a52666d38 100644--- a/litellm/google_genai/adapters/transformation.py+++ b/litellm/google_genai/adapters/transformation.py@@ -8,8 +8,10 @@ from litellm.types.llms.openai import (AllMessageValues,ChatCompletionAssistantMessage,ChatCompletionAssistantToolCall,+ ChatCompletionImageObject,ChatCompletionRequest,ChatCompletionSystemMessage,+ ChatCompletionTextObject,ChatCompletionToolCallFunctionChunk,ChatCompletionToolChoiceValues,ChatCompletionToolMessage,@@ -385,13 +387,36 @@ class GoogleGenAIAdapter:if role == "user":# Handle user messages with potential function responses- combined_text = ""+ content_parts: List[+ Union[ChatCompletionTextObject, ChatCompletionImageObject]+ ] = []tool_messages: List[ChatCompletionToolMessage] = []for part in parts:if isinstance(part, dict):if "text" in part:- combined_text += part["text"]+ content_parts.append(+ cast(+ ChatCompletionTextObject,+ {"type": "text", "text": part["text"]},+ )+ )+ elif "inline_data" in part:+ # Handle Base64 image data+ inline_data = part["inline_data"]+ mime_type = inline_data.get("mime_type", "image/jpeg")+ data = inline_data.get("data", "")+ content_parts.append(+ cast(+ ChatCompletionImageObject,+ {+ "type": "image_url",+ "image_url": {+ "url": f"data:{mime_type};base64,{data}"+ },+ },+ )+ )elif "functionResponse" in part:# Transform function response to tool messagefunc_response = part["functionResponse"]@@ -402,13 +427,33 @@ class GoogleGenAIAdapter:)tool_messages.append(tool_message)elif isinstance(part, str):- combined_text += part+ content_parts.append(+ cast(+ ChatCompletionTextObject, {"type": "text", "text": part}+ )+ )- # Add user message if there's text content- if combined_text:- messages.append(- ChatCompletionUserMessage(role="user", content=combined_text)- )+ # Add user message if there's content+ if content_parts:+ # If only one text part, use simple string format for backward compatibility+ if (+ len(content_parts) == 1+ and isinstance(content_parts[0], dict)+ and content_parts[0].get("type") == "text"+ ):+ text_part = cast(ChatCompletionTextObject, content_parts[0])+ messages.append(+ ChatCompletionUserMessage(+ role="user", content=text_part["text"]+ )+ )+ else:+ # Use multimodal format (array of content parts)+ messages.append(+ ChatCompletionUserMessage(+ role="user", content=content_parts+ )+ )# Add tool messagesmessages.extend(tool_messages)@@ -468,7 +513,6 @@ class GoogleGenAIAdapter:Dict in Google GenAI generate_content response format"""-# Extract the main response contentchoice = response.choices[0] if response.choices else Noneif not choice:diff --git a/tests/test_litellm/google_genai/test_google_genai_adapter.py b/tests/test_litellm/google_genai/test_google_genai_adapter.pyindex e8882a1acb3..135881ad209 100644--- a/tests/test_litellm/google_genai/test_google_genai_adapter.py+++ b/tests/test_litellm/google_genai/test_google_genai_adapter.py@@ -1197,6 +1197,131 @@ async def test_agenerate_content_x_goog_api_key_header():# Verify other expected headersassert headers.get("Content-Type") == "application/json", f"Expected Content-Type application/json, got {headers.get('Content-Type')}"-+print(f"✓ Test passed: x-goog-api-key header correctly set to {api_key_value}")print(f"✓ All headers: {list(headers.keys())}")+++def test_inline_data_base64_image_transformation():+ """Test transformation of Gemini inline_data (Base64 images) to OpenAI format"""+ from litellm.google_genai.adapters.transformation import GoogleGenAIAdapter++ adapter = GoogleGenAIAdapter()++ # Test input with Base64 image+ model = "gpt-4-vision-preview"+ contents = {+ "role": "user",+ "parts": [+ {"text": "What's in this image?"},+ {+ "inline_data": {+ "mime_type": "image/jpeg",+ "data": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="+ }+ }+ ]+ }++ # Transform to completion format+ completion_request = adapter.translate_generate_content_to_completion(+ model=model,+ contents=contents+ )++ # Verify the transformation+ assert completion_request["model"] == model+ assert len(completion_request["messages"]) == 1+ assert completion_request["messages"][0]["role"] == "user"++ # Verify content is an array (multimodal format)+ content = completion_request["messages"][0]["content"]+ assert isinstance(content, list), "Content should be a list for multimodal messages"+ assert len(content) == 2, "Should have 2 content parts (text + image)"++ # Verify text part+ text_part = content[0]+ assert text_part["type"] == "text"+ assert text_part["text"] == "What's in this image?"++ # Verify image part+ image_part = content[1]+ assert image_part["type"] == "image_url"+ assert "image_url" in image_part+ assert "url" in image_part["image_url"]+ assert image_part["image_url"]["url"].startswith("data:image/jpeg;base64,")+ assert "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==" in image_part["image_url"]["url"]+++def test_inline_data_image_only_transformation():+ """Test transformation of Gemini inline_data with only image (no text)"""+ from litellm.google_genai.adapters.transformation import GoogleGenAIAdapter++ adapter = GoogleGenAIAdapter()++ # Test input with only Base64 image (no text)+ model = "gpt-4-vision-preview"+ contents = {+ "role": "user",+ "parts": [+ {+ "inline_data": {+ "mime_type": "image/png",+ "data": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="+ }+ }+ ]+ }++ # Transform to completion format+ completion_request = adapter.translate_generate_content_to_completion(+ model=model,+ contents=contents+ )++ # Verify the transformation+ assert completion_request["model"] == model+ assert len(completion_request["messages"]) == 1+ assert completion_request["messages"][0]["role"] == "user"++ # Verify content is an array (multimodal format)+ content = completion_request["messages"][0]["content"]+ assert isinstance(content, list), "Content should be a list for multimodal messages"+ assert len(content) == 1, "Should have 1 content part (image only)"++ # Verify image part+ image_part = content[0]+ assert image_part["type"] == "image_url"+ assert "image_url" in image_part+ assert "url" in image_part["image_url"]+ assert image_part["image_url"]["url"].startswith("data:image/png;base64,")+++def test_inline_data_backward_compatibility_text_only():+ """Test that pure text messages still use simple string format (backward compatibility)"""+ from litellm.google_genai.adapters.transformation import GoogleGenAIAdapter++ adapter = GoogleGenAIAdapter()++ # Test input with only text (no images)+ model = "gpt-3.5-turbo"+ contents = {+ "role": "user",+ "parts": [{"text": "Hello, how are you?"}]+ }++ # Transform to completion format+ completion_request = adapter.translate_generate_content_to_completion(+ model=model,+ contents=contents+ )++ # Verify the transformation+ assert completion_request["model"] == model+ assert len(completion_request["messages"]) == 1+ assert completion_request["messages"][0]["role"] == "user"++ # Verify content is a simple string (not an array) for backward compatibility+ content = completion_request["messages"][0]["content"]+ assert isinstance(content, str), "Content should be a string for text-only messages (backward compatibility)"+ assert content == "Hello, how are you?"