Stream a run's events
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:
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) }}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.
How it works
Section titled “How it works”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.
Stream events
Section titled “Stream events”weft.Event is a sealed interface. These are its types, in the order a run emits them:
| Event | Fields | When |
|---|---|---|
RunStart | ID, Model, Agent, InstructionsHash | First event of every run |
StepStart | Index | The model is being called for a step |
ReasoningDelta | Text | Provider reasoning, in order with the text |
TextDelta | Text | An increment of assistant text |
ToolArgsDelta | Name, Args | The model is still writing a tool call; progress only |
ToolStart | Seq, CallID, Name, Args | A tool call began |
Nested | Seq, CallID, Event | One event of a subagent’s child run |
ToolFinish | Seq, CallID, Name, Content, IsError | A tool call completed; Content is what the model sees |
StepFinish | Index, Reason, Usage, Raw, LatencyMS, TTFTMS | The step’s model call and tools are done |
Steered | Seq, Step, Messages | The run’s steering source delivered messages |
RunFinish | Usage, Steps, Pending, StoppedBy | Last 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.
Close and wait
Section titled “Close and wait”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:
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 resultif err != nil { return err}fmt.Fprintln(w, "answer:", res.Text())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:
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()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.
Range over events once
Section titled “Range over events once”Events is single-use. A second call yields one element, weft.ErrRunConsumed, and nothing else:
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))}To fan events out to several consumers, use one range and forward each event, or register a weft.Tap on the agent.
Consume events promptly
Section titled “Consume events promptly”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.
Complete example
Section titled “Complete example”streaming/main.go runs each region against a scripted model that calls lookup_order once and then answers:
// 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 on GitHub · run it from docs-site/examples:
go run ./streaminggo test ./streaming== eventsrun started: support-botstep 0 seq 1: lookup_order {"order_id":"1234"} seq 2: lookup_order → order 1234 has shipped (error: false) finished: tool_callsstep 1 text: Order 1234 has shipped. finished: stoprun finished: 2 steps, 10 output tokens, stopped by final_answer== waitrun id known before the first event: trueanswer: Order 1234 has shipped.== stop earlystopped early, canceled: true== consume oncesecond range: trueBest practices & gotchas
Section titled “Best practices & gotchas”- Check
erron 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 bySeq. Parallel tools interleave;Seqis 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 noToolFinish; the transcript onRunError.Resultis the source of truth. (Source: ADR 0004, amendment 2026-09-09) - Call
Closeon 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)
See also
Section titled “See also”- What does a run return?
- Event types
- Observe a run without changing it
- Get structured output from a run: partial values while a run streams
- Delegate to another agent:
Nestedevents
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