pub type EventStream = Pin<Box<dyn Stream<Item = Result<StreamEvent>> + Send>>;Expand description
A pinned, boxed stream of events from the model.
This type alias represents an asynchronous stream that yields StreamEvent items.
Each item is wrapped in a Result to handle potential errors during streaming.
The stream is:
- Pinned (
Pin<Box<...>>): Required for safe async operations and self-referential types - Boxed: Allows dynamic dispatch and hides the concrete stream implementation
- Send: Can be safely transferred between threads
§Events
StreamEvent::Block: oneContentBlock— a fragment of assistant text as it arrives, or a fully assembled tool callStreamEvent::Reasoning: chain-of-thought text, only whenAgentOptions::include_reasoningis enabledStreamEvent::Finish: exactly once, as the final item, carrying theFinishReason
§Migrating from ContentStream (0.7.x and earlier)
The stream used to yield bare ContentBlocks. Wrap the old match in
StreamEvent::into_block to get the previous behaviour, then handle
StreamEvent::Finish where the distinction between a clean stop and a truncated
response matters.
§Error Handling
Errors in the stream indicate issues like:
- Network failures or timeouts
- Malformed SSE events
- JSON parsing errors
- API errors from the model provider
When an error occurs, the stream typically terminates. It’s the caller’s responsibility to handle errors appropriately.
§Examples
use open_agent::{query, AgentOptions, ContentBlock, FinishReason, StreamEvent};
use futures::StreamExt;
let options = AgentOptions::builder()
.model("gpt-4")
.api_key("sk-...")
.build()?;
let mut stream = query("Hello!", &options).await?;
while let Some(result) = stream.next().await {
match result? {
StreamEvent::Block(ContentBlock::Text(text)) => print!("{}", text.text),
StreamEvent::Finish(reason) => println!("\nstopped: {reason}"),
_ => {}
}
}Aliased Type§
pub struct EventStream { /* private fields */ }