Skip to main content

Overview

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.

Basic usage

1

Kick off the stream

2

Consume deltas + partial objects

Pass on_partial=lambda obj: print("partial", obj) to receive partially-parsed objects while streaming.

Parameters

Same as stream_text plus:

Return value

stream_object returns a StreamObjectResult with:
  • object_stream: Async iterator yielding text chunks
  • object(): Async method to get the complete parsed object
  • text(): Async method to get the complete text
  • usage: Token usage statistics
  • finish_reason: Why the stream ended
  • tool_calls: Tool calls if any were made

Examples

Basic streaming with objects

With partial object callbacks

With system instructions

With custom parameters

With complex nested schemas

Error handling

stream_object handles validation errors gracefully:

Tool-calling with streaming objects

See the dedicated Tool page for a complete walkthrough.

stream_object is provider-agnostic. Swap openai() for anthropic() or any other future implementation – no code changes required.