---
title: Stream a run's events
description: Range over agt.Stream(...).Events() to handle a run's events as they happen, read the terminal error, and stop early without leaking the run.
url: https://weftgo.dev/docs/guides/streaming/
type: how-to
sources:
  - weft/core/run.go:723-756 (Run, Stream, ID), 757-820 (Events), 822-826 (Close), 828-844 (Wait)
  - weft/core/events.go:8-184 (Event and every event type)
  - weft/core/errors.go:52-54 (ErrRunConsumed)
  - weft/docs/adr/0004-event-ordering.md
  - weft/AGENTS.md:152-164 (block 3b), 677-679 (rule 3)
  - weft/example_test.go:195 (ExampleAgent_stream), 558 (ExampleTap_async)
  - weft/CHANGELOG.md:6585, 6601, 6682
  - docs-site/examples/streaming/main.go, main_test.go TestStreaming, TestEventOrder, TestBreakEarlyIsRunError
---

# Stream a run's events

[`agt.Stream`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Stream) starts a run and returns a [`*weft.Run`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Run); ranging over [`run.Events()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#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:

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/streaming/main.go)

The switch needs no `default`: an event type you do not name is skipped. The package example [`ExampleAgent_stream`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Agent-Stream) is the same loop over a dice-rolling tool.

## How it works

`Stream` is lazy. Nothing runs until you range over `Events`, so you can read [`run.ID()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#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](https://github.com/weftgo/weft/blob/v0.20.2/docs/adr/0004-event-ordering.md)).

A `weft.Tap` on the agent sees the same events in the same order ([rule 3](https://github.com/weftgo/weft/blob/v0.20.2/AGENTS.md#the-rules-do-not-break-these-tests-pin-them)). Events are snapshots: you may keep them or write into them without touching the run's transcript.

## Stream events

[`weft.Event`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Event) is a sealed interface. These are its types, in the order a run emits them:

| Event | Fields | When |
|---|---|---|
| [`RunStart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunStart) | `ID`, `Model`, `Agent`, `InstructionsHash` | First event of every run |
| [`StepStart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StepStart) | `Index` | The model is being called for a step |
| [`ReasoningDelta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReasoningDelta) | `Text` | Provider reasoning, in order with the text |
| [`TextDelta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#TextDelta) | `Text` | An increment of assistant text |
| [`ToolArgsDelta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolArgsDelta) | `Name`, `Args` | The model is still writing a tool call; progress only |
| [`ToolStart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolStart) | `Seq`, `CallID`, `Name`, `Args` | A tool call began |
| [`Nested`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Nested) | `Seq`, `CallID`, `Event` | One event of a subagent's child run |
| [`ToolFinish`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolFinish) | `Seq`, `CallID`, `Name`, `Content`, `IsError` | A tool call completed; `Content` is what the model sees |
| [`StepFinish`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StepFinish) | `Index`, `Reason`, `Usage`, `Raw`, `LatencyMS`, `TTFTMS` | The step's model call and tools are done |
| [`Steered`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Steered) | `Seq`, `Step`, `Messages` | The run's steering source delivered messages |
| [`RunFinish`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) with the partial transcript on `.Result`. A failed run has no `RunFinish`. The [events reference](https://weftgo.dev/docs/reference/events/) lists every field.

## Close and wait

[`run.Wait()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#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:

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/streaming/main.go)

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()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Run.Close) cancels it and releases it:

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/streaming/main.go)

`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

`Events` is single-use. A second call yields one element, [`weft.ErrRunConsumed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrRunConsumed), and nothing else:

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/streaming/main.go)

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

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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Tap-Async) shows the same queue pattern for a slow tap.

## Complete example

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

```go title="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)
	}
}
```

[streaming/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/streaming/main.go)

[View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/streaming) · run it from `docs-site/examples`:

```sh
go run ./streaming
go test ./streaming
```

```text
== 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
```

## Best practices & gotchas

- **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)

## See also

- [What does a run return?](https://weftgo.dev/docs/concepts/runs/)
- [Event types](https://weftgo.dev/docs/reference/events/)
- [Observe a run without changing it](https://weftgo.dev/docs/guides/observers/)
- [Get structured output from a run](https://weftgo.dev/docs/guides/structured-output/): partial values while a run streams
- [Delegate to another agent](https://weftgo.dev/docs/guides/subagents/): `Nested` events

Symbols used: [`Agent.Stream`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Stream) · [`weft.Run`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Run) · [`Run.Events`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Run.Events) · [`Run.Wait`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Run.Wait) · [`Run.Close`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Run.Close) · [`Run.ID`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Run.ID) · [`weft.Event`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Event) · [`weft.ErrRunConsumed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrRunConsumed) · [`weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) · [`weft.Tap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tap) · [`weft.Prompt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Prompt) · [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) · [`weft.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#New) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) · [`ExampleAgent_stream`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Agent-Stream)
