Skip to content

Behavior of Union Types as Output type #2509

@vikigenius

Description

@vikigenius

Initial Checks

Description

Following the current docs in https://ai.pydantic.dev/output/#structured-output

from pydantic_ai import Agent

CustomType = list[str] | list[int]

agent1 = Agent[None, list[str] | list[int]](
    'openai:gpt-4o-mini',
    output_type=list[str] | list[int],  
    system_prompt='Extract either colors or sizes from the shapes provided.',
)

agent2 = Agent[None, CustomType](
    'openai:gpt-4o-mini',
    output_type=CustomType,  
    system_prompt='Extract either colors or sizes from the shapes provided.',
)

agent1 is fine. But pyright still complains about agent2

/home/void/Projects/myproj/test.py
  /home/void/Projects/myproj/test.py:13:10 - error: No overloads for "__init__" match the provided arguments (reportCallIssue)
  /home/void/Projects/myproj/test.py:15:17 - error: Argument of type "CustomType" cannot be assigned to parameter "output_type" of type "OutputSpec[CustomType]" in function "__init__"
    Type "UnionType" is not assignable to type "OutputSpec[CustomType]"
      Type "UnionType" is not assignable to type "type[list[str]]"
      Type "UnionType" is not assignable to type "type[list[int]]"
      Type "UnionType" is not assignable to type "(...) -> (CustomType | Awaitable[CustomType])"
      "UnionType" is not assignable to "ToolOutput[CustomType]"
      "UnionType" is not assignable to "NativeOutput[CustomType]"
      "UnionType" is not assignable to "PromptedOutput[CustomType]"
      "UnionType" is not assignable to "TextOutput[CustomType]"
    ... (reportArgumentType)```

This used to work around in the 0.3.5 versions of pydantic-ai. Did something change about the type signature of init

Example Code

from pydantic_ai import Agent

CustomType = list[str] | list[int]

agent1 = Agent[None, list[str] | list[int]](
    'openai:gpt-4o-mini',
    output_type=list[str] | list[int],  
    system_prompt='Extract either colors or sizes from the shapes provided.',
)

agent2 = Agent[None, CustomType](
    'openai:gpt-4o-mini',
    output_type=CustomType,  
    system_prompt='Extract either colors or sizes from the shapes provided.',
)

Python, Pydantic AI & LLM client version

pydantic-ai 0.6.2
python 3.12

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions