Open
Description
Initial Checks
- I confirm that I'm using the latest version of Pydantic AI
- I confirm that I searched for my issue in https://github.com/pydantic/pydantic-ai/issues before opening this issue
Description
Situation:
- I need LLM text output, to show it to the user, where the LLM reasons and explains.
- I want a structured output.
This is NOT working in streaming mode, but it does in NON-streaming mode.
See below tests. The first fails. The second passes.
Example Code
from typing import Union
from pydantic import BaseModel
from pydantic_ai import Agent
class CallAgent(BaseModel):
agent_name: str
agent = Agent(
model="google_gla:gemini-2.5-flash-preview-04-17",
output_type=Union[str, CallAgent],
instructions="Say hello and then transfer the user to 'user_assistant' agent",
)
async def test_output_with_str(): # FAILS
async with agent.run_stream(user_prompt="Hello") as result:
async for msg, is_last in result.stream_structured():
print(msg)
assert result.get_output() == CallAgent(agent_name="user_assistant")
async def test_output_with_str_no_stream(): # PASSES
result = await agent.run(user_prompt="Hello")
assert result.output == CallAgent(agent_name="user_assistant")
Python, Pydantic AI & LLM client version
pydanticai 0.1.4
any LLM
Python 3.12