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]

feat(openrouter.py): add image generation via google on openrouter support

Krrish Dholakiad4cc748b4092
diff --git a/docs/my-website/docs/extras/gemini_img_migration.md b/docs/my-website/docs/extras/gemini_img_migration.md
index 29678d859fa..a29f301e382 100644
--- a/docs/my-website/docs/extras/gemini_img_migration.md
+++ b/docs/my-website/docs/extras/gemini_img_migration.md
@@ -41,13 +41,16 @@ response = completion(
)
# Image is now available in the response
-image_url = response.choices[0].message.images[0]["url"] # "data:image/png;base64,..."
+image_url = response.choices[0].message.images[0]["image_url"]["url"] # "data:image/png;base64,..."
```
### Why the change?
Because the newer `gemini-2.5-flash-image-preview` model sends both text and image responses in the same response. This interface allows a developer to explicitly access the image or text components of the response. Before a developer would have needed to search through the message content to find the image generated by the model.
+**Why the change from `image` to `images`?**
+This is to be consistent with the OpenRouter API, making sure we are using simple, well-known interfaces where possible.
+
## Usage
### Using the Python SDK
@@ -58,7 +61,7 @@ Because the newer `gemini-2.5-flash-image-preview` model sends both text and ima
-- base_64_image_data = response.choices[0].message.content
# After
-++ image_url = response.choices[0].message.images[0]["url"]
+++ image_url = response.choices[0].message.images[0]["image_url"]["url"]
```
#### Basic Image Generation
@@ -84,12 +87,16 @@ print(response.choices[0].message.images[0]) # Image data
#### Response Format
-The image is returned in the `message.image` field:
+The image is returned in the `message.images` field:
```python
{
- "url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...",
- "detail": "auto"
+ "image_url": {
+ "url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...",
+ "detail": "auto"
+ },
+ "index": 0,
+ "type": "image_url"
}
```
@@ -102,8 +109,12 @@ The image is returned in the `message.image` field:
# After
++ "images": [{
-++ "url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...",
-++ "detail": "auto"
+++ "image_url": {
+++ "url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...",
+++ "detail": "auto"
+++ },
+++ "index": 0,
+++ "type": "image_url"
++ }]
```
diff --git a/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py b/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py
index 54adef9c958..8dc3061460a 100644
--- a/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py
+++ b/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py
@@ -43,13 +43,13 @@ from .get_headers import get_response_headers
def _safe_convert_created_field(created_value) -> int:
"""
Safely convert a 'created' field value to an integer.
-
- Some providers (like SambaNova) return the 'created' field as a float
+
+ Some providers (like SambaNova) return the 'created' field as a float
(Unix timestamp with fractional seconds), but LiteLLM expects an integer.
-
+
Args:
created_value: The value from response_object["created"]
-
+
Returns:
int: Unix timestamp as integer
"""
@@ -161,7 +161,9 @@ async def convert_to_streaming_response_async(response_object: Optional[dict] =
model_response_object.id = response_object["id"]
if "created" in response_object:
- model_response_object.created = _safe_convert_created_field(response_object["created"])
+ model_response_object.created = _safe_convert_created_field(
+ response_object["created"]
+ )
if "system_fingerprint" in response_object:
model_response_object.system_fingerprint = response_object["system_fingerprint"]
@@ -209,7 +211,9 @@ def convert_to_streaming_response(response_object: Optional[dict] = None):
model_response_object.id = response_object["id"]
if "created" in response_object:
- model_response_object.created = _safe_convert_created_field(response_object["created"])
+ model_response_object.created = _safe_convert_created_field(
+ response_object["created"]
+ )
if "system_fingerprint" in response_object:
model_response_object.system_fingerprint = response_object["system_fingerprint"]
@@ -557,9 +561,9 @@ def convert_to_model_response_object( # noqa: PLR0915
provider_specific_fields["thinking_blocks"] = thinking_blocks
if reasoning_content:
- provider_specific_fields[
- "reasoning_content"
- ] = reasoning_content
+ provider_specific_fields["reasoning_content"] = (
+ reasoning_content
+ )
message = Message(
content=content,
@@ -571,6 +575,7 @@ def convert_to_model_response_object( # noqa: PLR0915
reasoning_content=reasoning_content,
thinking_blocks=thinking_blocks,
annotations=choice["message"].get("annotations", None),
+ images=choice["message"].get("images", None),
)
finish_reason = choice.get("finish_reason", None)
if finish_reason is None:
@@ -606,7 +611,9 @@ def convert_to_model_response_object( # noqa: PLR0915
usage_object = litellm.Usage(**response_object["usage"])
setattr(model_response_object, "usage", usage_object)
if "created" in response_object:
- model_response_object.created = _safe_convert_created_field(response_object["created"])
+ model_response_object.created = _safe_convert_created_field(
+ response_object["created"]
+ )
if "id" in response_object:
model_response_object.id = response_object["id"] or str(uuid.uuid4())
diff --git a/litellm/types/llms/openai.py b/litellm/types/llms/openai.py
index a0c8e5b6295..753cf884646 100644
--- a/litellm/types/llms/openai.py
+++ b/litellm/types/llms/openai.py
@@ -43,10 +43,14 @@ from openai.types.responses.response import (
# Handle OpenAI SDK version compatibility for Text type
try:
- from openai.types.responses.response_create_params import Text as ResponseText
+ from openai.types.responses.response_create_params import (
+ Text as ResponseText, # type: ignore
+ )
except (ImportError, AttributeError):
# Fall back to the concrete config type available in all SDK versions
- from openai.types.responses.response_text_config_param import ResponseTextConfigParam as ResponseText
+ from openai.types.responses.response_text_config_param import (
+ ResponseTextConfigParam as ResponseText,
+ )
from openai.types.responses.response_create_params import (
Reasoning,
@@ -192,11 +196,17 @@ class ImageFileObject(TypedDict):
detail: Optional[str]
-class ImageURLObject(TypedDict):
+class ImageURLObject(TypedDict, total=False):
url: Required[str]
detail: Optional[str]
+class ImageURLListItem(TypedDict):
+ image_url: ImageURLObject
+ index: int
+ type: Literal["image_url"]
+
+
class MessageContentTextObject(TypedDict):
type: Required[Literal["text"]]
text: str
diff --git a/litellm/types/utils.py b/litellm/types/utils.py
index 8487e4bef6d..1c257f7bb46 100644
--- a/litellm/types/utils.py
+++ b/litellm/types/utils.py
@@ -51,7 +51,7 @@ from .llms.openai import (
ChatCompletionUsageBlock,
FileSearchTool,
FineTuningJob,
- ImageURLObject,
+ ImageURLListItem,
OpenAIChatCompletionChunk,
OpenAIFileObject,
OpenAIRealtimeStreamList,
@@ -573,7 +573,7 @@ class Message(OpenAIObject):
tool_calls: Optional[List[ChatCompletionMessageToolCall]]
function_call: Optional[FunctionCall]
audio: Optional[ChatCompletionAudioResponse] = None
- images: Optional[List[ImageURLObject]] = None
+ images: Optional[List[ImageURLListItem]] = None
reasoning_content: Optional[str] = None
thinking_blocks: Optional[
List[Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock]]
@@ -590,7 +590,7 @@ class Message(OpenAIObject):
function_call=None,
tool_calls: Optional[list] = None,
audio: Optional[ChatCompletionAudioResponse] = None,
- image: Optional[ImageURLObject] = None,
+ images: Optional[List[ImageURLListItem]] = None,
provider_specific_fields: Optional[Dict[str, Any]] = None,
reasoning_content: Optional[str] = None,
thinking_blocks: Optional[
@@ -624,8 +624,8 @@ class Message(OpenAIObject):
if audio is not None:
init_values["audio"] = audio
- if image is not None:
- init_values["image"] = image
+ if images is not None:
+ init_values["images"] = images
if thinking_blocks is not None:
init_values["thinking_blocks"] = thinking_blocks
@@ -647,9 +647,9 @@ class Message(OpenAIObject):
if hasattr(self, "audio"):
del self.audio
- if image is None:
- if hasattr(self, "image"):
- del self.image
+ if images is None:
+ if hasattr(self, "images"):
+ del self.images
if annotations is None:
# ensure default response matches OpenAI spec
@@ -703,7 +703,7 @@ class Delta(OpenAIObject):
function_call=None,
tool_calls=None,
audio: Optional[ChatCompletionAudioResponse] = None,
- images: Optional[List[ImageURLObject]] = None,
+ images: Optional[List[ImageURLListItem]] = None,
reasoning_content: Optional[str] = None,
thinking_blocks: Optional[
List[
diff --git a/tests/llm_translation/test_openrouter.py b/tests/llm_translation/test_openrouter.py
index 4c3cb1d6e4a..839d08e12bf 100644
--- a/tests/llm_translation/test_openrouter.py
+++ b/tests/llm_translation/test_openrouter.py
@@ -1,12 +1,13 @@
-
import os
import sys
import pytest
+
sys.path.insert(
0, os.path.abspath("../..")
) # Adds the parent directory to the system paths
import litellm
+
def test_completion_openrouter_reasoning_content():
litellm._turn_on_debug()
resp = litellm.completion(
@@ -16,3 +17,18 @@ def test_completion_openrouter_reasoning_content():
)
print(resp)
assert resp.choices[0].message.reasoning_content is not None
+
+
+def test_completion_openrouter_image_generation():
+ litellm._turn_on_debug()
+ resp = litellm.completion(
+ model="openrouter/google/gemini-2.5-flash-image-preview",
+ messages=[{"role": "user", "content": "Generate an image of a cat"}],
+ modalities=["image", "text"],
+ )
+ print(resp)
+ assert (
+ resp.choices[0]
+ .message.images[0]["image_url"]["url"]
+ .startswith("data:image/png;base64,")
+ )