Skip to content

OpenAIModel fails with OpenRouter Gemini: missing "choices" and "created" keys #1746

@gkeb

Description

@gkeb

Initial Checks

Description

Summary

When using OpenAIModel with OpenRouter and the model google/gemini-2.0-flash-exp:free, the agent fails with:

TypeError: 'NoneType' object is not subscriptable

This happens because the response returned by OpenRouter for Gemini does not include the choices or created keys expected by _process_response().


Steps to Reproduce

from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIModel
from pydantic_ai.providers.openai import OpenAIProvider

model = OpenAIModel(
    'google/gemini-2.0-flash-exp:free',
    provider=OpenAIProvider(
        base_url='https://openrouter.ai/api/v1',
        api_key='sk-or-v1-...',
    ),
)


agent = Agent(model=model, system_prompt="Be helpful.")
result = agent.run_sync("Tell me a joke.")

Observed Error

  • response.created is None, causing datetime.fromtimestamp() to fail
  • response.choices is None, causing choices[0] to throw

Suggestion

  • Add a fallback timestamp = datetime.now() when created is missing
  • Handle cases where choices is missing — or validate the response format before attempting to parse
  • Possibly support custom response parsers for models that aren't 100% OpenAI-compatible

Why it matters

OpenRouter is a growing ecosystem for multimodel access, and many of the available models (Gemini, Cohere, etc.) do not fully follow the OpenAI ChatCompletion schema. Supporting them would improve compatibility.

Let me know if you'd like me to submit a PR or share sample responses.

Thanks for the awesome tool!

Example Code

Python, Pydantic AI & LLM client version

Python 3.12
pydantic>=2.11.4
pydantic-ai-slim[openai]>=0.2.4
pydantic-settings>=2.9.1

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions