Skip to content

fix: add recursive nested-model $ref resolution in Pydantic tool parameter schemas - #1416

Merged
akihikokuroda merged 6 commits into
generative-computing:mainfrom
akihikokuroda:issue911
Jul 23, 2026
Merged

akihikokuroda merged 6 commits into
generative-computing:mainfrom
akihikokuroda:issue911

Conversation

@akihikokuroda

@akihikokuroda akihikokuroda commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Pull Request

Issue

Fixes #911
Fixes #1105

Description

Testing

  • Tests added to the respective file if code was changed
  • New code has 100% coverage if code was added
  • Ensure existing tests and github automation passes (a maintainer will kick off the github automation when the rest of the PR is populated)

Attribution

  • AI coding assistants used

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.

  • Component
  • Requirement
  • Sampling Strategy
  • Tool

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.

@github-actions github-actions Bot added the bug Something isn't working label Jul 20, 2026
@akihikokuroda
akihikokuroda marked this pull request as ready for review July 21, 2026 18:08
@akihikokuroda
akihikokuroda requested a review from a team as a code owner July 21, 2026 18:08
@akihikokuroda

Copy link
Copy Markdown
Contributor Author

This PR includes the changes in #1411.

@AngeloDanducci AngeloDanducci left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_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.

Comment thread mellea/backends/tools.py Resolved
Comment thread mellea/backends/tools.py Outdated
Comment on lines +1150 to +1153
# Replace schema contents with inlined schema, keeping other keys
schema.clear()
schema.update(inlined)
active_refs = active_refs | {ref_name}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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" }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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"]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! I made change and added the test.

@AngeloDanducci
AngeloDanducci dismissed their stale review July 22, 2026 18:13

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]>
@akihikokuroda
akihikokuroda added this pull request to the merge queue Jul 23, 2026
Merged via the queue into generative-computing:main with commit 22e242d Jul 23, 2026
10 checks passed
@akihikokuroda
akihikokuroda deleted the issue911 branch July 23, 2026 20:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Recursively flatten nested discriminated unions in tool schemas Support recursive nested-model $ref resolution in Pydantic tool parameter schemas

3 participants