-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Fix structured output with nested definitions with Gemini via OpenRouter #3618
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
dsfaccini
wants to merge
3
commits into
pydantic:main
Choose a base branch
from
dsfaccini:docs-stuff
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -7,13 +7,14 @@ | |
| from openai import AsyncOpenAI | ||
|
|
||
| from pydantic_ai import ModelProfile | ||
| from pydantic_ai._json_schema import JsonSchema, JsonSchemaTransformer | ||
| from pydantic_ai.exceptions import UserError | ||
| from pydantic_ai.models import cached_async_http_client | ||
| from pydantic_ai.profiles.amazon import amazon_model_profile | ||
| from pydantic_ai.profiles.anthropic import anthropic_model_profile | ||
| from pydantic_ai.profiles.cohere import cohere_model_profile | ||
| from pydantic_ai.profiles.deepseek import deepseek_model_profile | ||
| from pydantic_ai.profiles.google import google_model_profile | ||
| from pydantic_ai.profiles.google import GoogleModelProfile | ||
| from pydantic_ai.profiles.grok import grok_model_profile | ||
| from pydantic_ai.profiles.meta import meta_model_profile | ||
| from pydantic_ai.profiles.mistral import mistral_model_profile | ||
|
|
@@ -31,6 +32,70 @@ | |
| ) from _import_error | ||
|
|
||
|
|
||
| class OpenRouterGoogleJsonSchemaTransformer(JsonSchemaTransformer): | ||
| """Legacy Google JSON schema transformer for OpenRouter compatibility. | ||
|
|
||
| OpenRouter's compatibility layer doesn't fully support modern JSON Schema features | ||
| like $defs/$ref and anyOf for nullable types. This transformer restores v1.19.0 | ||
| behavior by inlining definitions and simplifying nullable unions. | ||
|
|
||
| See: https://github.com/pydantic/pydantic-ai/issues/3617 | ||
| """ | ||
|
|
||
| def __init__(self, schema: JsonSchema, *, strict: bool | None = None): | ||
| super().__init__(schema, strict=strict, prefer_inlined_defs=True, simplify_nullable_unions=True) | ||
|
|
||
| def transform(self, schema: JsonSchema) -> JsonSchema: | ||
| # Remove properties not supported by Gemini | ||
| schema.pop('$schema', None) | ||
| schema.pop('title', None) | ||
| schema.pop('discriminator', None) | ||
| schema.pop('examples', None) | ||
| schema.pop('exclusiveMaximum', None) | ||
| schema.pop('exclusiveMinimum', None) | ||
|
|
||
| if (const := schema.pop('const', None)) is not None: | ||
| schema['enum'] = [const] | ||
|
|
||
| # Convert enums to string type (legacy Gemini requirement) | ||
| if enum := schema.get('enum'): | ||
| schema['type'] = 'string' | ||
| schema['enum'] = [str(val) for val in enum] | ||
|
|
||
| # Convert oneOf to anyOf for discriminated unions | ||
| if 'oneOf' in schema and 'type' not in schema: | ||
| schema['anyOf'] = schema.pop('oneOf') | ||
|
|
||
| # Handle string format -> description | ||
| type_ = schema.get('type') | ||
| if type_ == 'string' and (fmt := schema.pop('format', None)): | ||
| description = schema.get('description') | ||
| if description: | ||
| schema['description'] = f'{description} (format: {fmt})' | ||
| else: | ||
| schema['description'] = f'Format: {fmt}' | ||
|
|
||
| return schema | ||
|
|
||
|
|
||
| def openrouter_google_model_profile(model_name: str) -> ModelProfile | None: | ||
| """Get the model profile for a Google model accessed via OpenRouter. | ||
|
|
||
| Uses the legacy transformer to maintain compatibility with OpenRouter's | ||
| translation layer, which doesn't fully support modern JSON Schema features. | ||
| """ | ||
| is_image_model = 'image' in model_name | ||
| is_3_or_newer = 'gemini-3' in model_name | ||
| return GoogleModelProfile( | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We shouldn't copy paste all of this! We should call the original |
||
| json_schema_transformer=OpenRouterGoogleJsonSchemaTransformer, | ||
| supports_image_output=is_image_model, | ||
| supports_json_schema_output=is_3_or_newer or not is_image_model, | ||
| supports_json_object_output=is_3_or_newer or not is_image_model, | ||
| supports_tools=not is_image_model, | ||
| google_supports_native_output_with_builtin_tools=is_3_or_newer, | ||
| ) | ||
|
|
||
|
|
||
| class OpenRouterProvider(Provider[AsyncOpenAI]): | ||
| """Provider for OpenRouter API.""" | ||
|
|
||
|
|
@@ -48,7 +113,7 @@ def client(self) -> AsyncOpenAI: | |
|
|
||
| def model_profile(self, model_name: str) -> ModelProfile | None: | ||
| provider_to_profile = { | ||
| 'google': google_model_profile, | ||
| 'google': openrouter_google_model_profile, | ||
| 'openai': openai_model_profile, | ||
| 'anthropic': anthropic_model_profile, | ||
| 'mistralai': mistral_model_profile, | ||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is public now, I don't think it should be :)