Stream structured output asynchronously with real-time validation and partial object updates.
stream_object
provides real-time streaming of structured output with automatic validation. It combines the benefits of streaming (low latency) with structured output (type safety) by providing both text chunks and partially-parsed objects as they become available.
Kick off the stream
Consume deltas + partial objects
on_partial=lambda obj: print("partial", obj)
to receive partially-parsed objects while streaming.stream_text
plus:
Name | Type | Required | Description |
---|---|---|---|
schema | Type[BaseModel] | ✓ | Pydantic model defining the desired output shape. |
on_partial | Callable[[BaseModel], None] | – | Callback executed when a partial object is successfully parsed. |
stream_object
returns a StreamObjectResult
with:
object_stream
: Async iterator yielding text chunksobject()
: Async method to get the complete parsed objecttext()
: Async method to get the complete textusage
: Token usage statisticsfinish_reason
: Why the stream endedtool_calls
: Tool calls if any were madestream_object
handles validation errors gracefully:
stream_object
is provider-agnostic. Swap openai()
for
anthropic()
or any other future implementation – no code changes required.