-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Fix StructuredDict with nested JSON schemas using $ref #2570
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
base: main
Are you sure you want to change the base?
Changes from all commits
adea654
3ad3d07
2c7b476
368e47d
41c5a36
da286d8
1823581
5613cf9
6cc3416
19eaabf
87bd740
2ed1bf4
3588f79
ebc364d
1f97912
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -10,6 +10,7 @@ | |
from typing_extensions import TypeAliasType, TypeVar | ||
|
||
from . import _utils | ||
from .exceptions import UserError | ||
from .messages import ToolCallPart | ||
from .tools import RunContext, ToolDefinition | ||
|
||
|
@@ -304,6 +305,19 @@ def StructuredDict( | |
""" | ||
json_schema = _utils.check_object_json_schema(json_schema) | ||
|
||
# If the schema contains $defs, inline them to avoid issues with pydantic's | ||
# JSON schema generator (Issue #2466) | ||
if '$defs' in json_schema: | ||
from .profiles import InlineDefsJsonSchemaTransformer | ||
|
||
try: | ||
transformer = InlineDefsJsonSchemaTransformer(json_schema) | ||
json_schema = transformer.walk() | ||
except UserError: | ||
# If the transformer can't resolve refs (e.g., missing definitions), | ||
# keep the original schema unchanged | ||
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. Let's raise a descriptive error instead of continuing and hitting the confusing Pydantic error |
||
pass | ||
|
||
if name: | ||
json_schema['title'] = name | ||
|
||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -46,7 +46,11 @@ | |
) | ||
from pydantic_ai.models.function import AgentInfo, FunctionModel | ||
from pydantic_ai.models.test import TestModel | ||
from pydantic_ai.output import DeferredToolCalls, StructuredDict, ToolOutput | ||
from pydantic_ai.output import ( | ||
DeferredToolCalls, | ||
StructuredDict, | ||
ToolOutput, | ||
) | ||
from pydantic_ai.profiles import ModelProfile | ||
from pydantic_ai.result import Usage | ||
from pydantic_ai.tools import ToolDefinition | ||
|
@@ -1362,6 +1366,64 @@ def call_tool(_: list[ModelMessage], info: AgentInfo) -> ModelResponse: | |
) | ||
|
||
|
||
def test_output_type_structured_dict_nested(): | ||
"""Test StructuredDict with nested JSON schemas using $ref - Issue #2466.""" | ||
# Schema with nested $ref that pydantic's generator can't resolve | ||
CarDict = StructuredDict( | ||
{ | ||
'$defs': { | ||
'Tire': { | ||
'type': 'object', | ||
'properties': {'brand': {'type': 'string'}, 'size': {'type': 'integer'}}, | ||
'required': ['brand', 'size'], | ||
} | ||
}, | ||
'type': 'object', | ||
'properties': { | ||
'make': {'type': 'string'}, | ||
'model': {'type': 'string'}, | ||
'tires': {'type': 'array', 'items': {'$ref': '#/$defs/Tire'}}, | ||
}, | ||
'required': ['make', 'model', 'tires'], | ||
}, | ||
name='Car', | ||
description='A car with tires', | ||
) | ||
|
||
def call_tool(_: list[ModelMessage], info: AgentInfo) -> ModelResponse: | ||
assert info.output_tools is not None | ||
|
||
# Verify the output tool schema has been properly transformed | ||
# The $refs should be inlined by InlineDefsJsonSchemaTransformer | ||
output_tool = info.output_tools[0] | ||
assert output_tool.parameters_json_schema is not None | ||
schema = output_tool.parameters_json_schema | ||
|
||
# Check that the Tire definition has been inlined in the tires array items | ||
assert 'properties' in schema | ||
assert 'tires' in schema['properties'] | ||
tires_schema = schema['properties']['tires'] | ||
assert tires_schema['type'] == 'array' | ||
|
||
# The $ref should have been resolved to the actual Tire schema | ||
items_schema = tires_schema['items'] | ||
assert '$ref' not in items_schema # Should be inlined, not a ref | ||
assert items_schema['type'] == 'object' | ||
assert 'properties' in items_schema | ||
assert 'brand' in items_schema['properties'] | ||
assert 'size' in items_schema['properties'] | ||
|
||
args_json = '{"make": "Toyota", "model": "Camry", "tires": [{"brand": "Michelin", "size": 17}]}' | ||
return ModelResponse(parts=[ToolCallPart(info.output_tools[0].name, args_json)]) | ||
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. Can we add an assertion for the output tool schema to ensure it has the expected format? |
||
|
||
agent = Agent(FunctionModel(call_tool), output_type=CarDict) | ||
|
||
result = agent.run_sync('Generate a car') | ||
|
||
expected = {'make': 'Toyota', 'model': 'Camry', 'tires': [{'brand': 'Michelin', 'size': 17}]} | ||
assert result.output == expected | ||
|
||
|
||
def test_default_structured_output_mode(): | ||
def hello(_: list[ModelMessage], _info: AgentInfo) -> ModelResponse: | ||
return ModelResponse(parts=[TextPart(content='hello')]) # pragma: no cover | ||
|
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.
Why was this change necessary? What was not working correctly before that is now?