Repository navigation
fix: add recursive nested-model $ref resolution in Pydantic tool parameter schemas - #1416
Conversation
|
This PR includes the changes in #1411. |
AngeloDanducci
left a comment
There was a problem hiding this comment.
_recursively_inline_refs crashes on self-referential models. The cycle guard tracks id(schema) in a visited set, but each inline does a fresh copy.deepcopy + schema.clear()/update(), so every descent produces new dict objects with new ids and the guard never fires.
Recommend fixing cycles by tracking $ref targets on the resolution path (a frozenset[str]) instead of dict ids. I applied it in the worktree and confirmed it makes the recursive case return without raising.
test_no_infinite_loop_on_complex_structure I've suggested a corrected docstring plus a new test_recursive_model_terminates that exercises a self-referential model and asserts termination.
Signed-off-by: Akihiko Kuroda <[email protected]>
Signed-off-by: Akihiko Kuroda <[email protected]>
Signed-off-by: Akihiko Kuroda <[email protected]>
Signed-off-by: Akihiko Kuroda <[email protected]>
Signed-off-by: Akihiko Kuroda <[email protected]>
| # Replace schema contents with inlined schema, keeping other keys | ||
| schema.clear() | ||
| schema.update(inlined) | ||
| active_refs = active_refs | {ref_name} |
There was a problem hiding this comment.
The comment here is wrong. I believe this gets rid of sibling keys by calling schema.clear(). I think you want something like:
del schema["$ref"]
for kk, vv in inlined.items():
schema.setdefault(kk, vv) # existing siblings win over inlined keys
that way description fields don't get deleted:
"address": { "$ref": "#/$defs/Address", "description": "the person's mailing address" }
There was a problem hiding this comment.
I had Claude create some tests to confirm:
class TestSiblingKeysPreservedOnInline:
"""Sibling keys on a `$ref` node must survive recursive inlining.
Pydantic v2 emits a field-level description as a sibling of `$ref`:
`{"$ref": "#/$defs/Address", "description": "..."}`. When
`_recursively_inline_refs` expands the ref, those sibling keys (most
importantly `description`, which the LLM reads as tool-calling guidance)
must be preserved, not discarded. See PR #1416 review.
"""
def test_description_sibling_preserved_on_nested_ref(self):
"""A description alongside a nested-model `$ref` must survive inlining."""
from pydantic import Field
class Address(BaseModel):
street: str
city: str
class Person(BaseModel):
name: str
address: Address = Field(description="the person's mailing address")
def create_person(person: Person) -> str:
"""Create a person.
Args:
person: the person record
"""
return "ok"
tool = convert_function_to_ollama_tool(create_person)
assert tool.function is not None
assert tool.function.parameters is not None
params = tool.function.parameters.model_dump(exclude_none=True)
address = params["properties"]["person"]["properties"]["address"]
# The ref must be inlined (no dangling $ref)...
assert "$ref" not in address, f"nested ref not inlined: {address}"
assert address.get("type") == "object"
assert "street" in address.get("properties", {})
# ...and the sibling description must be preserved.
assert address.get("description") == "the person's mailing address", (
f"sibling description dropped during inlining: {address}"
)
def test_description_sibling_preserved_two_levels_deep(self):
"""A described `$ref` nested two levels deep must keep its description."""
from pydantic import Field
class Country(BaseModel):
name: str
code: str
class Address(BaseModel):
street: str
country: Country = Field(description="the country of residence")
class Person(BaseModel):
name: str
address: Address
def create_person(person: Person) -> str:
"""Create a person.
Args:
person: the person record
"""
return "ok"
tool = convert_function_to_ollama_tool(create_person)
assert tool.function is not None
assert tool.function.parameters is not None
params = tool.function.parameters.model_dump(exclude_none=True)
country = params["properties"]["person"]["properties"]["address"]["properties"][
"country"
]
assert "$ref" not in country, f"deeply nested ref not inlined: {country}"
assert country.get("type") == "object"
assert country.get("description") == "the country of residence", (
f"sibling description dropped at depth: {country}"
)
def test_inlined_object_fields_still_present(self):
"""Inlining must add the referenced object's own keys, not just siblings.
Guards against a fix that preserves siblings but stops populating the
inlined body (or vice versa).
"""
from pydantic import Field
class Address(BaseModel):
street: str
city: str
class Person(BaseModel):
name: str
address: Address = Field(description="mailing address")
def create_person(person: Person) -> str:
"""Create a person.
Args:
person: the person record
"""
return "ok"
tool = convert_function_to_ollama_tool(create_person)
assert tool.function is not None
assert tool.function.parameters is not None
params = tool.function.parameters.model_dump(exclude_none=True)
address = params["properties"]["person"]["properties"]["address"]
# Both the inlined body and the sibling description must coexist.
assert address.get("description") == "mailing address"
assert set(address.get("properties", {})) == {"street", "city"}
assert address.get("required") == ["street", "city"]
There was a problem hiding this comment.
Thanks! I made change and added the test.
My feedback has been addressed, agree with Jake on his comments - that should probably be in before approval.
Signed-off-by: Akihiko Kuroda <[email protected]>
22e242d
Pull Request
Issue
Fixes #911
Fixes #1105
Description
Testing
Attribution
Adding a new component, requirement, sampling strategy, or tool?
If your PR adds or modifies one of the types below, check the matching box. A checklist of type-specific review items will be posted as a comment.
NOTE: Please ensure you have an issue that has been acknowledged by a core contributor and routed you to open a pull request against this repository. Otherwise, please open an issue before continuing with this pull request.