Skip to content

Support recursive nested-model $ref resolution in Pydantic tool parameter schemas #911

Closed

Description

@akihikokuroda

Description: Tool parameter schema generation currently does not fully resolve nested Pydantic models referenced via $ref, causing failures for cases like Address nested inside Person. We should track implementation of recursive $ref resolution so nested fields are expanded safely without breaking schema generation or introducing dangling references. This issue should replace the PR’s inline placeholder reference to the local NESTED_MODEL_RESOLUTION_ISSUE.md file and serve as the canonical tracker for the expected behavior documented by the new test.

Nested Model Resolution Issue

Summary

The current convert_function_to_ollama_tool implementation doesn't fully resolve nested $ref references in Pydantic BaseModel schemas. When a model contains another model (e.g., Person with an address: Address field), the top-level model is inlined but nested references remain unresolved, causing validation failures.

Problem Description

Schema Generation Issue

When Pydantic generates a schema for a nested type like Person (which has an address: Address field), resolve_ref inlines Person at the top level but leaves "address": {"$ref": "#/$defs/Address"} unresolved inside it. Ollama receives a dangling $ref it can't follow.

Validation Issue

The validation side has the same gap — _build_pydantic_type_from_schema has no $ref case, so it defaults json_type to "string" for any sub-schema that's a reference. Passing a nested dict then fails with a Pydantic ValidationError.

Example

from pydantic import BaseModel

class Address(BaseModel):
    street: str
    city: str
    state: str
    zip_code: str

class Person(BaseModel):
    name: str
    age: int
    email: str
    address: Address  # Nested model

def create_contact(person: Person) -> str:
    """Create a new contact."""
    return f"Created contact for {person.name}"

tool = MelleaTool.from_callable(create_contact)
schema = tool.as_json_tool

# Current behavior: Person is inlined but Address remains as $ref
# params["properties"]["person"]["properties"]["address"] = {"$ref": "#/$defs/Address"}

Required Fixes

1. Recursive Reference Resolution in Schema Generation

resolve_ref (or a wrapper) should recursively walk the inlined schema and resolve any further $refs it finds:

def resolve_ref_recursive(ref_path: str, defs: dict, visited: set | None = None) -> dict:
    """Resolve a $ref path recursively, handling nested references.
    
    Args:
        ref_path: The $ref path to resolve (e.g., '#/$defs/Email')
        defs: The $defs dictionary containing schema definitions
        visited: Set of already-visited refs to prevent cycles
    
    Returns:
        The fully resolved schema with all nested $refs inlined
    """
    if visited is None:
        visited = set()
    
    # Prevent infinite recursion on circular references
    if ref_path in visited:
        return {"type": "object"}  # Fallback for circular refs
    
    visited.add(ref_path)
    
    # Resolve the current reference
    schema = resolve_ref(ref_path, defs)
    if not schema:
        return {}
    
    # Deep copy to avoid mutations
    resolved = copy.deepcopy(schema)
    
    # Recursively resolve any $refs in properties
    if "properties" in resolved:
        for prop_name, prop_schema in resolved["properties"].items():
            if "$ref" in prop_schema:
                resolved["properties"][prop_name] = resolve_ref_recursive(
                    prop_schema["$ref"], defs, visited
                )
            elif "anyOf" in prop_schema:
                # Handle Optional[Model] cases
                resolved_anyof = []
                for sub_schema in prop_schema["anyOf"]:
                    if "$ref" in sub_schema:
                        resolved_anyof.append(
                            resolve_ref_recursive(sub_schema["$ref"], defs, visited)
                        )
                    else:
                        resolved_anyof.append(sub_schema)
                resolved["properties"][prop_name]["anyOf"] = resolved_anyof
    
    return resolved

2. Reference Resolution in Validation

_build_pydantic_type_from_schema needs a $ref branch that looks up the definition in defs and recurses:

def _build_pydantic_type_from_schema(schema: dict[str, Any], defs: dict) -> Any:
    """Recursively build Pydantic type from JSON schema.
    
    Args:
        schema: The JSON schema to convert
        defs: The $defs dictionary for resolving references
    """
    # Handle $ref references
    if "$ref" in schema:
        ref_path = schema["$ref"]
        resolved_schema = resolve_ref(ref_path, defs)
        if resolved_schema:
            return _build_pydantic_type_from_schema(resolved_schema, defs)
        # Fallback if we can't resolve
        return dict
    
    json_type = schema.get("type", "string")
    
    # ... rest of the existing logic

Note: defs is currently only in scope inside convert_function_to_ollama_tool; it'll need to be passed to _build_pydantic_type_from_schema or closed over.

Test Coverage

The test test_nested_models_fully_inlined in test/backends/test_pydantic_tool_parameters.py documents the expected behavior and will pass once this issue is resolved.

Related Files

  • mellea/backends/tools.py - Lines 930-994 (schema generation)
  • mellea/backends/tools.py - Lines 503-568 (validation)
  • test/backends/test_pydantic_tool_parameters.py - Lines 461-520 (test case)

Priority

Medium - This is not a regression from the Optional parameter fix, but it affects tools with nested Pydantic models. The workaround is to flatten the structure or use dict types instead of nested BaseModels.

Labels

  • enhancement
  • tools
  • pydantic%

Activity

  1. psschwei commented on Apr 24, 2026

    @psschwei
    Contributor

    instead of attaching a file, can we just include the contents as part of the issue body (or in a follow up comment)?

  2. added
    enhancement
    bug
    on May 19, 2026
  3. added
    area/tools
    on May 20, 2026
  4. added
    p2
    on Jun 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area/toolsbugenhancementp2

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions