Skip to main content

Streaming answers

A long answer can take many seconds to finish. Streaming shows it as the model writes it, so the reader sees the first words at once. Add .stream(on_event) to an ask, a send or a resume, and the closure is called with each event as it happens. The call still returns the same Run at the end.

Printing as it is written​

use freyja::{Agent, AgentEvent, Client, EndpointPreset, StreamEvent};
use std::io::Write;

// Connects to Anthropic with the key in ANTHROPIC_API_KEY.
let agent = Agent::new(Client::from_env(EndpointPreset::Anthropic)?);

let run = agent
.ask("Write a haiku about rust.")
.stream(|event| {
if let AgentEvent::Model(StreamEvent::TextDelta(text)) = event {
print!("{text}");
let _ = std::io::stdout().flush();
}
})
.await?;
println!("\n{} tokens", run.usage.total_tokens);

Text arrives in pieces that end mid-word, so print each piece as it is and flush, or the terminal shows nothing until a newline. Once the stream ends, run.answer holds the whole text, and run.stop and run.usage are there as usual.

Showing what the agent is doing​

An agent that calls tools streams those too. A tool call arrives as StreamEvent::ToolCall before the tool runs, and AgentEvent::ToolResult once it has run, with the text the model is about to read:

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

#[tool(description = "adds two numbers")]
fn add(a: i64, b: i64) -> i64 {
a + b
}

let agent = Agent::new(client).tool(add);

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

client is the Client from the first example. Both enums are #[non_exhaustive], so a match needs the trailing _ => {} arm.

Sending it to a web page​

The closure runs while the run is awaited, so a web handler starts the run in a task and forwards the text through a channel. The receiving end is what your web framework streams to the browser, for example as server-sent events.

use freyja::{Agent, AgentEvent, StreamEvent};
use tokio::sync::mpsc;

fn answer(agent: Agent, question: String) -> mpsc::UnboundedReceiver<String> {
let (sender, receiver) = mpsc::unbounded_channel();
tokio::spawn(async move {
let streamed = agent
.ask(question)
.stream(move |event| {
if let AgentEvent::Model(StreamEvent::TextDelta(text)) = event {
let _ = sender.send(text);
}
})
.await;
if let Err(error) = streamed {
eprintln!("{error}");
}
});
receiver
}

Agent is cheap to clone, so each request gets its own copy. The channel closes when the run ends, which ends the stream to the browser.

Stopping partway​

A stop button needs to end a run that is still streaming. Put a Cancel in the run's context and call cancel from anywhere, such as the handler for the button. The model call is dropped at once, the text already streamed has reached the reader, and the run returns Ok with StopReason::Stopped:

use freyja::{Cancel, Context, StopReason};

let cancel = Cancel::new();
let mut cx = Context::new();
cx.insert(cancel.clone());

// Elsewhere, when the reader presses stop:
// cancel.cancel("stopped by the reader");

let run = agent
.ask("Write a long story.")
.context(&cx)
.stream(|event| { /* print as above */ })
.await?;
if let StopReason::Stopped(reason) = &run.stop {
println!("\n({reason})");
}

See Stopping a request for when a cancel takes effect.

One model call​

Without an agent, Client::stream streams a single call and hands back StreamEvents to read one at a time. See Calling the model directly. Event types, size limits, timeouts and provider differences are in the Streaming reference.