Skip to content

Stream a run's events

View as Markdown

agt.Stream starts a run and returns a *weft.Run; ranging over run.Events() yields each event as the loop emits it. A failed run yields its error once, as the last element; a successful run ends with RunFinish. Use it when a UI or log must show progress; use agt.Generate when only the result matters.

The range in streaming/main.go, with a type switch over the events it handles:

streaming/main.go
run := agt.Stream(ctx, weft.Prompt("Where is order 1234?"))
for ev, err := range run.Events() {
if err != nil {
return err // a failed run: non-nil at most once, as the last element
}
switch ev := ev.(type) {
case weft.RunStart:
fmt.Fprintln(w, "run started:", ev.Agent)
case weft.StepStart:
fmt.Fprintln(w, "step", ev.Index)
case weft.ToolStart:
fmt.Fprintf(w, " seq %d: %s %s\n", ev.Seq, ev.Name, ev.Args)
case weft.ToolFinish:
fmt.Fprintf(w, " seq %d: %s → %s (error: %t)\n", ev.Seq, ev.Name, ev.Content, ev.IsError)
case weft.TextDelta:
fmt.Fprintln(w, " text:", ev.Text)
case weft.StepFinish:
fmt.Fprintln(w, " finished:", ev.Reason)
case weft.RunFinish:
fmt.Fprintf(w, "run finished: %d steps, %d output tokens, stopped by %s\n",
ev.Steps, ev.Usage.OutputTokens, ev.StoppedBy)
}
}

streaming/main.go on GitHub

The switch needs no default: an event type you do not name is skipped. The package example ExampleAgent_stream is the same loop over a dice-rolling tool.

Stream is lazy. Nothing runs until you range over Events, so you can read run.ID() first and hand it to a client. Each Events call hands events over an unbuffered channel from the goroutine that runs the loop.

Every run’s first event is RunStart; a successful run’s last is RunFinish. Tool events carry Seq, a per-run counter assigned under the same lock that emits them, so the order you observe is the order of Seq. Pair ToolStart and ToolFinish by CallID when tools run in parallel (ADR 0004).

A weft.Tap on the agent sees the same events in the same order (rule 3). Events are snapshots: you may keep them or write into them without touching the run’s transcript.

weft.Event is a sealed interface. These are its types, in the order a run emits them:

EventFieldsWhen
RunStartID, Model, Agent, InstructionsHashFirst event of every run
StepStartIndexThe model is being called for a step
ReasoningDeltaTextProvider reasoning, in order with the text
TextDeltaTextAn increment of assistant text
ToolArgsDeltaName, ArgsThe model is still writing a tool call; progress only
ToolStartSeq, CallID, Name, ArgsA tool call began
NestedSeq, CallID, EventOne event of a subagent’s child run
ToolFinishSeq, CallID, Name, Content, IsErrorA tool call completed; Content is what the model sees
StepFinishIndex, Reason, Usage, Raw, LatencyMS, TTFTMSThe step’s model call and tools are done
SteeredSeq, Step, MessagesThe run’s steering source delivered messages
RunFinishUsage, Steps, Pending, StoppedByLast event of a successful run

Every event except RunStart also carries RunID. ToolArgsDelta arrives only from adapters that stream arguments: the OpenAI and Anthropic adapters emit it, and Gemini calls arrive whole. The assembled call still arrives as ToolStart when it executes.

The err element is non-nil at most once, as the last element. It is the run error agt.Generate would return: a *weft.RunError with the partial transcript on .Result. A failed run has no RunFinish. The events reference lists every field.

run.Wait() returns the run’s *RunResult and error. After the range it returns at once; called on a run nobody ranged over, it runs the agent itself and discards the events. It is safe from another goroutine while the range runs:

streaming/main.go
run := agt.Stream(ctx, weft.Prompt("Where is order 1234?"))
fmt.Fprintln(w, "run id known before the first event:", run.ID() != "")
for _, err := range run.Events() {
if err != nil {
return err
}
}
res, err := run.Wait() // the stream is consumed; Wait returns its result
if err != nil {
return err
}
fmt.Fprintln(w, "answer:", res.Text())

streaming/main.go on GitHub

Breaking out of the range cancels the run. Wait then reports an error matching context.Canceled. A run you create with Stream and never consume holds a context; run.Close() cancels it and releases it:

streaming/main.go
run := agt.Stream(ctx, weft.Prompt("Where is order 1234?"))
for ev, err := range run.Events() {
if err != nil {
return err
}
if _, ok := ev.(weft.ToolStart); ok {
break // stopping the range cancels the run
}
}
_, err := run.Wait()
fmt.Fprintln(w, "stopped early, canceled:", errors.Is(err, context.Canceled))
// A run you start but never consume: Close releases it.
abandoned := agt.Stream(ctx, weft.Prompt("Where is order 5678?"))
defer abandoned.Close()

streaming/main.go on GitHub

Close is for abandoned runs only. A run you range over or Wait on needs no Close: Events and Wait release everything themselves. Close is safe to call any number of times, before or after consumption.

Events is single-use. A second call yields one element, weft.ErrRunConsumed, and nothing else:

streaming/main.go
run := agt.Stream(ctx, weft.Prompt("Where is order 1234?"))
for range run.Events() {
}
for _, err := range run.Events() { // a second range yields only ErrRunConsumed
fmt.Fprintln(w, "second range:", errors.Is(err, weft.ErrRunConsumed))
}

streaming/main.go on GitHub

To fan events out to several consumers, use one range and forward each event, or register a weft.Tap on the agent.

The hand-off is unbuffered, and tool events are emitted while the loop holds the step’s ordering lock. A slow consumer does not only receive late: it delays emission and gates the start of the step’s next tools. For parallel tools where latency matters, range in a dedicated goroutine that buffers, or use Generate, which needs no consumer. The package example ExampleTap_async shows the same queue pattern for a slow tap.

streaming/main.go runs each region against a scripted model that calls lookup_order once and then answers:

streaming/main.go
// Command streaming runs the examples of the guide "Stream a run's
// events": go run ./streaming. The model is scripted with wefttest, so it
// runs offline; swap in a provider adapter for a real one.
package main
import (
"context"
"errors"
"fmt"
"io"
"os"
"github.com/weftgo/weft"
"github.com/weftgo/weft/wefttest"
)
type LookupInput struct {
OrderID string `json:"order_id" jsonschema:"the order to look up"`
}
// newAgent returns an agent whose scripted model calls lookup_order once,
// then answers.
func newAgent() *weft.Agent {
lookup := weft.Tool("lookup_order", "Look up an order by ID.",
func(_ context.Context, in LookupInput) (string, error) {
return "order " + in.OrderID + " has shipped", nil
})
model := wefttest.Script(
wefttest.ToolCalls(wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`}),
wefttest.Say("Order 1234 has shipped."),
)
return weft.New(model, weft.Name("support-bot"), lookup)
}
// streamEvents ranges over a run's events and prints each kind it handles.
func streamEvents(ctx context.Context, w io.Writer, agt *weft.Agent) error {
run := agt.Stream(ctx, weft.Prompt("Where is order 1234?"))
for ev, err := range run.Events() {
if err != nil {
return err // a failed run: non-nil at most once, as the last element
}
switch ev := ev.(type) {
case weft.RunStart:
fmt.Fprintln(w, "run started:", ev.Agent)
case weft.StepStart:
fmt.Fprintln(w, "step", ev.Index)
case weft.ToolStart:
fmt.Fprintf(w, " seq %d: %s %s\n", ev.Seq, ev.Name, ev.Args)
case weft.ToolFinish:
fmt.Fprintf(w, " seq %d: %s → %s (error: %t)\n", ev.Seq, ev.Name, ev.Content, ev.IsError)
case weft.TextDelta:
fmt.Fprintln(w, " text:", ev.Text)
case weft.StepFinish:
fmt.Fprintln(w, " finished:", ev.Reason)
case weft.RunFinish:
fmt.Fprintf(w, "run finished: %d steps, %d output tokens, stopped by %s\n",
ev.Steps, ev.Usage.OutputTokens, ev.StoppedBy)
}
}
return nil
}
// streamThenWait consumes the events, then reads the result with Wait.
func streamThenWait(ctx context.Context, w io.Writer, agt *weft.Agent) error {
run := agt.Stream(ctx, weft.Prompt("Where is order 1234?"))
fmt.Fprintln(w, "run id known before the first event:", run.ID() != "")
for _, err := range run.Events() {
if err != nil {
return err
}
}
res, err := run.Wait() // the stream is consumed; Wait returns its result
if err != nil {
return err
}
fmt.Fprintln(w, "answer:", res.Text())
return nil
}
// streamStopEarly breaks out of the range at the first tool call and
// shows what the run reports.
func streamStopEarly(ctx context.Context, w io.Writer, agt *weft.Agent) error {
run := agt.Stream(ctx, weft.Prompt("Where is order 1234?"))
for ev, err := range run.Events() {
if err != nil {
return err
}
if _, ok := ev.(weft.ToolStart); ok {
break // stopping the range cancels the run
}
}
_, err := run.Wait()
fmt.Fprintln(w, "stopped early, canceled:", errors.Is(err, context.Canceled))
// A run you start but never consume: Close releases it.
abandoned := agt.Stream(ctx, weft.Prompt("Where is order 5678?"))
defer abandoned.Close()
return nil
}
// streamTwice ranges over one run's events a second time.
func streamTwice(ctx context.Context, w io.Writer, agt *weft.Agent) error {
run := agt.Stream(ctx, weft.Prompt("Where is order 1234?"))
for range run.Events() {
}
for _, err := range run.Events() { // a second range yields only ErrRunConsumed
fmt.Fprintln(w, "second range:", errors.Is(err, weft.ErrRunConsumed))
}
return nil
}
func run(ctx context.Context, w io.Writer) error {
steps := []struct {
title string
fn func(context.Context, io.Writer, *weft.Agent) error
}{
{"events", streamEvents},
{"wait", streamThenWait},
{"stop early", streamStopEarly},
{"consume once", streamTwice},
}
for _, s := range steps {
fmt.Fprintf(w, "== %s\n", s.title)
if err := s.fn(ctx, w, newAgent()); err != nil {
return fmt.Errorf("%s: %w", s.title, err)
}
}
return nil
}
func main() {
if err := run(context.Background(), os.Stdout); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}

View streaming/main.go on GitHub

View on GitHub · run it from docs-site/examples:

Terminal window
go run ./streaming
go test ./streaming
== events
run started: support-bot
step 0
seq 1: lookup_order {"order_id":"1234"}
seq 2: lookup_order → order 1234 has shipped (error: false)
finished: tool_calls
step 1
text: Order 1234 has shipped.
finished: stop
run finished: 2 steps, 10 output tokens, stopped by final_answer
== wait
run id known before the first event: true
answer: Order 1234 has shipped.
== stop early
stopped early, canceled: true
== consume once
second range: true
  • Check err on every element. The error arrives as the last element of the range, at most once; a range that ignores it treats a failed run as finished. (Source: weft/core/run.go:766-771, AGENTS.md block 3b)
  • Pair tool events by CallID, order them by Seq. Parallel tools interleave; Seq is the total order. (Source: ADR 0004, weft/core/events.go:66-70)
  • After a cancel, render tool outcomes from RunError.Result, not from events. Delivery stops at cancellation, so a started tool may have no ToolFinish; the transcript on RunError.Result is the source of truth. (Source: ADR 0004, amendment 2026-09-09)
  • Call Close on a run you abandon unconsumed. Otherwise its context stays live until the parent context ends. (Source: weft/core/run.go:822-826, CHANGELOG 0.2.0)
  • Keep the consumer fast. A slow range gates the start of the step’s later tools. (Source: weft/core/run.go:760-768, CHANGELOG 0.2.0)

Symbols used: Agent.Stream · weft.Run · Run.Events · Run.Wait · Run.Close · Run.ID · weft.Event · weft.ErrRunConsumed · weft.RunError · weft.Tap · weft.Prompt · weft.Tool · weft.New · wefttest.Script · ExampleAgent_stream