Skip to content

[BUG] Tool has validation error due to convert_pydantic_to_tool_spec failing to resolve $ref #337

@dtmhuang

Description

@dtmhuang

Checks

  • I have updated to the lastest minor and patch version of Strands
  • I have checked the documentation and this is not expected behavior
  • I have searched ./issues and there are no duplicates of my issue

Strands Version

0.1.9

Python Version

3.12.10

Operating System

macOS Sequoia 15.5

Installation Method

pip

Steps to Reproduce

Run this python script:

from typing import List, Optional
from pydantic import BaseModel, Field
from strands import Agent
from strands.tools import convert_pydantic_to_tool_spec

class Address(BaseModel):
    street: str
    city: str
    country: str
    postal_code: Optional[str] = None

class Contact(BaseModel):
    email: Optional[str] = None
    phone: Optional[str] = None

class Person(BaseModel):
    """Complete person information."""
    name: str = Field(description="Full name of the person")
    age: int = Field(description="Age in years")
    address: Address = Field(description="Home address")
    contacts: Optional[List[Contact]] = Field(description="Contact methods")
    skills: List[str] = Field(default_factory=list, description="Professional skills")


if __name__ == '__main__':
    print(convert_pydantic_to_tool_spec(Person))  # shows the buggy json
    # in the json:
    # 'contacts': {'items': {'$ref': '#/$defs/Contact'}

    agent = Agent()
    result = agent.structured_output(
        Person,
        "Extract info: Jane Doe, a systems admin, 28, lives at 123 Main St, New York, NY"
    )  # throws an exception, won't get to the print statements below


    print(result.name)                    # "Jane Doe"
    print(result.address.city)            # "New York"
    if result.contacts is not None and result.contacts[0] is not None:
        print(result.contacts[0].email)       # "[email protected]"
    else:
        print("contact is None")
    print(result.skills)                  # ["systems admin"]

The printed json tool spec includes an unresolved $ref, and this causes a ValidationException when calling the ConverseStream operation, saying the JSON schema is invalid

Expected Behavior

convert_pydantic_to_tool_spec() should properly resolve the $ref in a field with type Optional[List[BaseModel]]

Actual Behavior

convert_pydantic_to_tool_spec() currently leaves a $ref field when the field has a type Optional[List[BaseModel]], shown in script to reproduce the bug as Optional[List[Contact]]

Additional Context

No response

Possible Solution

No response

Related Issues

No response

Metadata

Metadata

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions