Skip to main content

Streaming

For printing an answer as it is written, showing tool progress, sending text to a web page and stopping partway, start with the Streaming answers guide. This page has the details.

An agent streams by adding .stream(on_event) to a send, an ask or a resume. The run takes the whole turn, tool calls included, and hands each event to the closure as it happens.

use freyja::{Agent, AgentEvent, InMemoryStorage, StreamEvent};

let agent = Agent::new(client).tool(add).max_turns(5);
let mut chat = agent.conversation(InMemoryStorage::new());

let run = chat
.send("What is 20 + 22?")
.stream(|event| match event {
AgentEvent::Model(StreamEvent::TextDelta(text)) => print!("{text}"),
AgentEvent::ToolResult { name, output, .. } => println!("[{name}: {output}]"),
_ => {}
})
.await?;

println!("\n{} turns", run.turns);

.context(&cx) adds a Context as well. The call returns the same Run that send would have, so run.answer, run.stop and run.usage are all there once the stream ends. Text deltas arrive mid-line, so flush after each one if you are printing them, or nothing appears until the process exits.

AgentEvent​

#[non_exhaustive]
pub enum AgentEvent {
Model(StreamEvent),
ToolResult { id: String, name: String, output: String },
}

Model is something the model streamed, exactly as the model yields it, and a tool call arrives there as StreamEvent::ToolCall before the tool runs. ToolResult fires once the turn's tool calls have all finished, in the order the model requested them, and it carries the text the model is about to read. A call that was denied or failed is reported too.

The enum is #[non_exhaustive], so a match needs a trailing _ => {} arm.

StreamEvent​

#[non_exhaustive]
pub enum StreamEvent {
TextDelta(String),
RefusalDelta(String),
ToolCall { id: String, name: String, arguments: String },
ReasoningDelta(String),
Reasoning { data: Value },
Done { id: String, model: String, status: ResponseStatus, usage: Option<Usage> },
}
VariantMeaningWhen it fires
TextDeltaA fragment of generated text, in orderRepeatedly, as the model produces text
RefusalDeltaA fragment of a refusalRepeatedly, when the model declines. Kept distinct from text for the same reason OutputContent::Refusal is
ToolCallA complete tool call, arguments fully assembledOnce per call, when that call is finished
ReasoningDeltaHuman-readable reasoning textRepeatedly, on providers that expose it
ReasoningOpaque provider reasoning state, complete and replayableOnce per block, when that block is finished
DoneId, model, status, and usageExactly once, immediately before the stream ends

The enum is #[non_exhaustive], so a match needs a trailing _ => {} arm. A provider gaining an event Freyja can model will not break your build.

let run = chat
.send("What is 20 + 22?")
.stream(|event| match event {
AgentEvent::Model(StreamEvent::TextDelta(text)) => print!("{text}"),
AgentEvent::Model(StreamEvent::ToolCall { id, name, arguments }) => {
println!("{name}({arguments}) as {id}");
}
AgentEvent::Model(StreamEvent::Done { status, usage, .. }) => {
println!("ended {status:?} after {usage:?}");
}
_ => {}
})
.await?;

Done fires at the end of each model call, so a run with tools sees it once per turn. The totals for the whole run are on run.usage.

Fragments are never exposed​

This is the main departure from other streaming APIs, and it is deliberate.

Providers stream tool-call arguments and reasoning blobs in pieces: a few characters of JSON per frame, split at arbitrary points. Freyja assembles those internally and emits them only once complete, so StreamEvent::ToolCall always carries arguments you can hand straight to serde_json::from_str, and StreamEvent::Reasoning always carries a blob you can replay verbatim. No caller stitches partial JSON, and no caller has to know that a given vendor splits its arguments differently from the last one.

Text and refusals are the exception, because a fragment of text is useful on its own. Those arrive as deltas, which is the entire point of streaming.

Client::streamfragment assemblyVendor SSE chunks"The ""ans"...{"a":20}...opaque reasoningchunksEventStreampass-through deltasstreamed unbufferedtool argument assemblerinternal bufferreasoning block bufferinternal bufferstream end / closefinal frame metadataStreamEventTextDelta / RefusalDeltaemitted liveToolCallcomplete argumentsReasoningcomplete replayable blockDoneterminal (status, usage)into_response()GenerateResponsematchesClient::generate

Streaming one model call​

Client::stream is the call under .stream. It returns once the provider has accepted the request, so a non-success status arrives as Error::Api rather than part-way through iteration, and it yields StreamEvent values you drain with next. Calling the model directly has the loop.

into_response​

EventStream::into_response consumes a drained stream and hands back the GenerateResponse that generate would have returned for the same turn. id, model, status, content and usage are identical, and to_message() produces the same assistant turn.

What differs is provider_metadata, and it differs by shape rather than by accident. generate collects the fields Freyja does not model, using serde's flatten, so you get the leftovers. A stream carries the provider's terminal object whole, because that object is what the final frame contains. Both are the provider's own data, so do not compare the two paths field for field. See Responses.

Calling into_response before next has returned None fails with Error::Stream. A response that looks complete but is not, replayed to a provider on the next turn, fails in ways that are hard to trace back here, so Freyja refuses instead. Drain first.

Timeouts​

The default HTTP client bounds inactivity, not total duration. It sets read_timeout, so a stream is cut off after 120 seconds of silence and not after 120 seconds of streaming. A long generation is safe as long as bytes keep arriving.

A client you supply through Client::with_http_client keeps whatever you built it with. Set read_timeout there rather than timeout, or a healthy long stream is killed part-way:

use std::time::Duration;

let http = reqwest::Client::builder()
.read_timeout(Duration::from_secs(120))
.connect_timeout(Duration::from_secs(5))
.build()?;

let client = Client::with_http_client(EndpointPreset::OpenAi, api_key, http);

timeout on a streaming request is a deadline for the whole response body, which for streaming is a deadline on how long the model is allowed to talk.

Size limits​

A timeout bounds silence. It does not bound volume, and an endpoint that keeps sending is never late, so there is a second bound underneath it: one server-sent event may buffer 16 MiB before the stream fails with Error::Stream.

probe stream failed: a single event grew past 16777216 bytes without ending

An event is a JSON object, and the largest any provider sends is a terminal object carrying the whole interaction, so the ceiling is orders of magnitude above anything real. What it catches is an endpoint that never emits a frame separator, which would otherwise be buffered whole until the process runs out of memory. Freyja is built to be pointed at gateways it has never met, so this is not hypothetical.

Non-streaming responses have the same protection at 64 MiB, reported as Error::InvalidResponse.

Errors​

Everything that can fail before the first byte surfaces from stream, classified by cause: RateLimit, Unauthorized, ServerError, and the rest of the status-bearing variants. After that, failures surface from next: Error::Stream for the provider's own mid-stream error frame, Error::Http with a Body kind for the connection dropping underneath.

A stream that simply stops early, with no error frame, is not an error. The Done event carries ResponseStatus::Incomplete, because nothing set a terminal status, so check status rather than assuming a stream that ended is a stream that finished. See Errors.

Provider differences​

All four dialects stream, and the neutral event sequence is the same on each. What differs is underneath:

ProviderHow
OpenAIstream: true in the body, semantic SSE events
OpenAI Chat Completionsstream: true, plus stream_options.include_usage so token counts still arrive
Geministream: true in the body and ?alt=sse on the URL, which is what selects SSE framing
Anthropicstream: true, with message_start / content_block_* / message_delta events

Freyja sets all of that for you. The per-provider pages have the detail.

All four have been exercised against a live endpoint for a text turn: deltas arrive, usage lands on Done, and into_response rebuilds exactly the text the deltas carried. Streamed tool calls have not. That is the path where argument fragments are joined, and it remains covered by recorded fixtures only, with a test per dialect asserting that a drained stream matches what generate builds from the same turn. See Features.