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
feat(types/utils.py): support 'images' field in output
Krrish Dholakia0fbcc0117385
diff --git a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.pyindex 99a04c20fba..464c8d0aad3 100644--- a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py+++ b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py@@ -792,11 +792,12 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):content_str += _content_strreturn content_str, reasoning_content_str-+def _extract_image_response_from_parts(self, parts: List[HttpxPartType]- ) -> Optional[ImageURLObject]:+ ) -> Optional[List[ImageURLObject]]:"""Extract image response from parts if present"""+ images: List[ImageURLObject] = []for part in parts:if "inlineData" in part:mime_type = part["inlineData"]["mimeType"]@@ -804,11 +805,8 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):if mime_type.startswith("image/"):# Convert base64 data to data URI formatdata_uri = f"data:{mime_type};base64,{data}"- return ImageURLObject(- url=data_uri,- detail="auto"- )- return None+ images.append(ImageURLObject(url=data_uri, detail="auto"))+ return imagesdef _extract_audio_response_from_parts(self, parts: List[HttpxPartType]@@ -1127,7 +1125,7 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):elif web_search_queries:web_search_requests = len(grounding_metadata)return web_search_requests-+@staticmethoddef _create_streaming_choice(chat_completion_message: ChatCompletionResponseMessage,@@ -1136,7 +1134,7 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):tools: Optional[List[ChatCompletionToolCallChunk]],functions: Optional[ChatCompletionToolCallFunctionChunk],chat_completion_logprobs: Optional[ChoiceLogprobs],- image_response: Optional[ImageURLObject],+ image_response: Optional[List[ImageURLObject]],) -> StreamingChoices:"""Helper method to create a streaming choice object for Vertex AI@@ -1151,11 +1149,9 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):index=candidate.get("index", idx),delta=Delta(content=chat_completion_message.get("content"),- reasoning_content=chat_completion_message.get(- "reasoning_content"- ),+ reasoning_content=chat_completion_message.get("reasoning_content"),tool_calls=tools,- image=image_response,+ images=image_response,function_call=functions,),logprobs=chat_completion_logprobs,@@ -1164,13 +1160,15 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):return choice@staticmethod- def _extract_candidate_metadata(candidate: Candidates) -> Tuple[List[dict], List[dict], List, List]:+ def _extract_candidate_metadata(+ candidate: Candidates,+ ) -> Tuple[List[dict], List[dict], List, List]:"""Extract metadata from a single candidate response.-+Returns:grounding_metadata: List[dict]- url_context_metadata: List[dict]+ url_context_metadata: List[dict]safety_ratings: Listcitation_metadata: List"""@@ -1178,7 +1176,7 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):url_context_metadata: List[dict] = []safety_ratings: List = []citation_metadata: List = []-+if "groundingMetadata" in candidate:if isinstance(candidate["groundingMetadata"], list):grounding_metadata.extend(candidate["groundingMetadata"]) # type: ignore@@ -1194,8 +1192,13 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):if "urlContextMetadata" in candidate:# Add URL context metadata to grounding metadataurl_context_metadata.append(cast(dict, candidate["urlContextMetadata"]))-- return grounding_metadata, url_context_metadata, safety_ratings, citation_metadata++ return (+ grounding_metadata,+ url_context_metadata,+ safety_ratings,+ citation_metadata,+ )@staticmethoddef _process_candidates(@@ -1219,7 +1222,7 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):grounding_metadata: List[dict] = []url_context_metadata: List[dict] = []- image_response: Optional[ImageURLObject] = None+ image_response: Optional[List[ImageURLObject]] = Nonesafety_ratings: List = []citation_metadata: List = []chat_completion_message: ChatCompletionResponseMessage = {"role": "assistant"}@@ -1239,7 +1242,7 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):candidate_safety_ratings,candidate_citation_metadata,) = VertexGeminiConfig._extract_candidate_metadata(candidate)-+grounding_metadata.extend(candidate_grounding_metadata)url_context_metadata.extend(candidate_url_context_metadata)safety_ratings.extend(candidate_safety_ratings)@@ -1271,7 +1274,9 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):chat_completion_message["content"] = None # OpenAI specif image_response is not None:# Handle image response - combine with text content into structured format- cast(Dict[str, Any], chat_completion_message)["image"] = image_response+ cast(Dict[str, Any], chat_completion_message)[+ "images"+ ] = image_responseif content is not None:chat_completion_message["content"] = content@@ -1301,12 +1306,12 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):if isinstance(model_response, ModelResponseStream):choice = VertexGeminiConfig._create_streaming_choice(chat_completion_message=chat_completion_message,- candidate=candidate,- idx=idx,- tools=tools,- functions=functions,+ candidate=candidate,+ idx=idx,+ tools=tools,+ functions=functions,chat_completion_logprobs=chat_completion_logprobs,- image_response=image_response+ image_response=image_response,)model_response.choices.append(choice)elif isinstance(model_response, ModelResponse):diff --git a/litellm/types/utils.py b/litellm/types/utils.pyindex adac065d2d9..7ff02f3ad9f 100644--- a/litellm/types/utils.py+++ b/litellm/types/utils.py@@ -573,7 +573,7 @@ class Message(OpenAIObject):tool_calls: Optional[List[ChatCompletionMessageToolCall]]function_call: Optional[FunctionCall]audio: Optional[ChatCompletionAudioResponse] = None- image: Optional[ImageURLObject] = None+ images: Optional[List[ImageURLObject]] = Nonereasoning_content: Optional[str] = Nonethinking_blocks: Optional[List[Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock]]@@ -646,7 +646,7 @@ class Message(OpenAIObject):# OpenAI compatible APIs like mistral API will raise an error if audio is passed inif hasattr(self, "audio"):del self.audio-+if image is None:if hasattr(self, "image"):del self.image@@ -703,7 +703,7 @@ class Delta(OpenAIObject):function_call=None,tool_calls=None,audio: Optional[ChatCompletionAudioResponse] = None,- image: Optional[ImageURLObject] = None,+ images: Optional[List[ImageURLObject]] = None,reasoning_content: Optional[str] = None,thinking_blocks: Optional[List[@@ -721,7 +721,7 @@ class Delta(OpenAIObject):self.function_call: Optional[Union[FunctionCall, Any]] = Noneself.tool_calls: Optional[List[Union[ChatCompletionDeltaToolCall, Any]]] = Noneself.audio: Optional[ChatCompletionAudioResponse] = None- self.image: Optional[ImageURLObject] = None+ self.images: Optional[List[ImageURLObject]] = Noneself.annotations: Optional[List[ChatCompletionAnnotation]] = Noneif reasoning_content is not None:@@ -741,9 +741,9 @@ class Delta(OpenAIObject):self.annotations = annotationselse:del self.annotations-- if image is not None:- self.image = image++ if images is not None:+ self.images = imageselse:del self.image@@ -1927,7 +1927,9 @@ class StandardLoggingMetadata(StandardLoggingUserAPIKeyMetadata):vector_store_request_metadata: Optional[List[StandardLoggingVectorStoreRequest]]applied_guardrails: Optional[List[str]]usage_object: Optional[dict]- cold_storage_object_key: Optional[str] # S3/GCS object key for cold storage retrieval+ cold_storage_object_key: Optional[+ str+ ] # S3/GCS object key for cold storage retrievalclass StandardLoggingAdditionalHeaders(TypedDict, total=False):@@ -2354,6 +2356,7 @@ class LlmProviders(str, Enum):VERCEL_AI_GATEWAY = "vercel_ai_gateway"DOTPROMPT = "dotprompt"+# Create a set of all provider values for quick lookupLlmProvidersSet = {provider.value for provider in LlmProviders}diff --git a/tests/llm_translation/test_gemini.py b/tests/llm_translation/test_gemini.pyindex 22a54b8a56b..215a7f35ea6 100644--- a/tests/llm_translation/test_gemini.py+++ b/tests/llm_translation/test_gemini.py@@ -436,7 +436,10 @@ def test_gemini_with_empty_function_call_arguments():async def test_claude_tool_use_with_gemini():response = await litellm.anthropic.messages.acreate(messages=[- {"role": "user", "content": "Hello, can you tell me the weather in Boston. Please respond with a tool call?"}+ {+ "role": "user",+ "content": "Hello, can you tell me the weather in Boston. Please respond with a tool call?",+ }],model="gemini/gemini-2.5-flash",stream=True,@@ -578,17 +581,23 @@ def test_gemini_tool_use():assert stop_reason is not Noneassert stop_reason == "tool_calls"+@pytest.mark.asyncioasync def test_gemini_image_generation_async():litellm._turn_on_debug()response = await litellm.acompletion(- messages=[{"role": "user", "content": "Generate an image of a banana wearing a costume that says LiteLLM"}],+ messages=[+ {+ "role": "user",+ "content": "Generate an image of a banana wearing a costume that says LiteLLM",+ }+ ],model="gemini/gemini-2.5-flash-image-preview",)CONTENT = response.choices[0].message.content- IMAGE_URL = response.choices[0].message.image+ IMAGE_URL = response.choices[0].message.images[0]print("IMAGE_URL: ", IMAGE_URL)assert CONTENT is not None, "CONTENT is not None"@@ -597,12 +606,16 @@ async def test_gemini_image_generation_async():assert IMAGE_URL["url"].startswith("data:image/png;base64,")-@pytest.mark.asyncioasync def test_gemini_image_generation_async_stream():- #litellm._turn_on_debug()+ # litellm._turn_on_debug()response = await litellm.acompletion(- messages=[{"role": "user", "content": "Generate an image of a banana wearing a costume that says LiteLLM"}],+ messages=[+ {+ "role": "user",+ "content": "Generate an image of a banana wearing a costume that says LiteLLM",+ }+ ],model="gemini/gemini-2.5-flash-image-preview",stream=True,)@@ -611,35 +624,38 @@ async def test_gemini_image_generation_async_stream():model_response_image = Noneasync for chunk in response:print("CHUNK: ", chunk)- if hasattr(chunk.choices[0].delta, "image") and chunk.choices[0].delta.image is not None:+ if (+ hasattr(chunk.choices[0].delta, "image")+ and chunk.choices[0].delta.image is not None+ ):model_response_image = chunk.choices[0].delta.imageprint("MODEL_RESPONSE_IMAGE: ", model_response_image)assert model_response_image is not Noneassert model_response_image["url"].startswith("data:image/png;base64,")break-+########################################################## Important: Validate we did get an image in the response#########################################################assert model_response_image is not Noneassert model_response_image["url"].startswith("data:image/png;base64,")-+def test_system_message_with_no_user_message():- """- Test that the system message is translated correctly for non-OpenAI providers.- """- messages = [- {- "role": "system",- "content": "Be a good bot!",- },- ]+ """+ Test that the system message is translated correctly for non-OpenAI providers.+ """+ messages = [+ {+ "role": "system",+ "content": "Be a good bot!",+ },+ ]- response = litellm.completion(- model="gemini/gemini-2.5-flash",- messages=messages,- )- assert response is not None+ response = litellm.completion(+ model="gemini/gemini-2.5-flash",+ messages=messages,+ )+ assert response is not None- assert response.choices[0].message.content is not None\ No newline at end of file+ assert response.choices[0].message.content is not None