Skip to content

Support OpenRouter image generation #3258

@Powerostad

Description

@Powerostad

Question

Hi, I have openrouter account and trying to use the nano banana model via openrouter with pydantic_ai, the problem is that the model response is str and the image that is being generated by model is not in the response object. Can someone Help me?
sample code:

from pydantic_ai import Agent, BinaryImage
from pydantic_ai.models.openai import OpenAIModel
from pydantic_ai.providers.openrouter import OpenRouterProvider

def generate_image(prompt: str, api_key: str):
    """Generate image using pydantic_ai with OpenRouter."""
    
    # Configure model
    provider = OpenRouterProvider(api_key=api_key)
    model = OpenAIModel(
        model_name="google/gemini-2.5-flash-image-preview",  # Doesn't exist on OpenRouter
        provider=provider,
    )
    
    # Create agent expecting BinaryImage
    agent = Agent(model=model, output_type=BinaryImage)
    
    # This fails: model returns text instead of image data
    result = agent.run_sync(prompt)  # Error: "Exceeded maximum retries for output validation"
    
    return result.output.data

if __name__ == "__main__":
    try:
        image_data = generate_image("A cat", "your_api_key")
        print("Success!")
    except Exception as e:
        print(f"Error: {e}")

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions