Observe a run without changing it: Tap, OnRunEnd, OnMessages
weft has four ways to watch a run, none of which can change it. weft.Tap sees every event of every run. weft.OnRunEnd is called once per run with the result and the error, failures included. weft.OnMessages receives the exact messages as they join the transcript. weft.Logger sets the sink for the loop’s Debug lines.
A tap that counts tool calls, in observers/main.go:
var calls intagt := weft.New(script(), lookup, weft.Tap(func(_ context.Context, ev weft.Event) { if _, ok := ev.(weft.ToolStart); ok { calls++ } }), weft.Tap(func(context.Context, weft.Event) { panic("broken observer") }),)res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))if err != nil { return err}fmt.Fprintln(w, "tool calls:", calls)fmt.Fprintln(w, "answer:", res.Text())fmt.Fprintln(w, "contained tap panics:", agt.TapPanics()) // one per event the broken tap sawObservers observe; behaviour attaches at the two middleware seams, WrapModel and WrapTools. That is rule 10: two behavioural seams, one tap, no more.
How it works
Section titled “How it works”| Observer | Option kind | Called | Sees a failed run |
|---|---|---|---|
Tap | agent Option | once per event, every run | its events up to the failure, no end |
OnRunEnd | agent Option | once per run, at the end | yes: err is the *RunError |
OnMessages | RunOption, per run | once per batch of transcript messages | the messages that joined before it |
Logger | agent Option | one Debug line per phase | yes: the error text |
Tap, OnRunEnd and OnMessages are synchronous, and the run waits for them. A Tap runs on the goroutine that emits the event, a tool goroutine included, under the event-ordering lock. OnMessages and OnRunEnd run on the loop’s goroutine. Each receives the run’s context, which carries the run’s span and its metadata. A panic in a Tap, OnRunEnd or OnMessages observer is recovered and counted, never breaking the run.
Tap registers an observer that sees every event of every run, including runs made with Generate, which has no stream to range over. Taps run in emission order, the order Events() delivers (rule 3), and several taps run in registration order. The package example is ExampleTap.
The second tap in the region panics on every event. The run still answers, and agt.TapPanics() reports 9: one contained panic per event that tap saw. The counter covers taps, OnMessages and OnRunEnd observers, and attempt reports whose tracer or logger panicked. Since 0.18.0 it also counts every other call the loop makes into its TracerProvider or LoggerProvider that panics. That covers Tracer and Logger at New, span starts and attribute calls on the four span kinds, and the records’ Enabled and Emit. Each run names such a provider in one Warn line on the agent’s logger. A span whose attribute calls panic is still ended, and the run’s result and events equal a run with no provider. A rising count means an observer or a provider is broken.
Slow observers
Section titled “Slow observers”A tap runs under the step’s event-ordering lock. A slow tap delays every tool event of its step and blocks the tool goroutines that emit them, the same coupling a slow Events() consumer has. Do slow work, such as a database write or a network sink, off the tap: hand each event to a queue and drain it on your own goroutine.
events := make(chan weft.Event, 1024)dropped := 0 // written only inside the tap, read after the rundone := make(chan int)go func() { // the slow side: a database write, a network sink n := 0 for range events { n++ } done <- n}()agt := weft.New(script(), lookup, weft.Tap(func(_ context.Context, ev weft.Event) { select { case events <- ev: // never block inside a tap default: dropped++ // a full queue drops, visibly } }))_, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))close(events)fmt.Fprintln(w, "events drained:", <-done, "dropped:", dropped)The tap never blocks: when the queue is full it drops the event and counts it. The package example is ExampleTap_async.
On run end
Section titled “On run end”A failed run emits no event after its last delivered one (ADR 0004), so a tap cannot see a failure. OnRunEnd is the outcome signal. The loop calls it exactly once per run, after RunFinish is delivered or the RunError is built, and before Generate returns:
agt := weft.New(wefttest.Script(wefttest.Fail(errors.New("provider down"))), weft.OnRunEnd(func(_ context.Context, res *weft.RunResult, err error) { var runErr *weft.RunError fmt.Fprintf(w, "run ended: id set=%t steps=%d run error=%t\n", res.ID != "", res.NumSteps(), errors.As(err, &runErr)) }),)_, err := agt.Generate(ctx, weft.Prompt("hi"))fmt.Fprintln(w, "Generate returned:", err)run ended: id set=true steps=0 run error=trueGenerate returned: weft: run failed at step 0: model stream: provider downOn success err is nil and res is complete. On failure err is the *RunError and res is its partial transcript, the same value RunError.Result holds. On cancellation err is the RunError wrapping the context’s error. For a subagent’s child run it fires inside the parent’s tool call, and res.ID names the child. A run that panics, for example in a PrepareStep function, never fires it: the loop re-panics, to your caller under Generate; under Stream the panic crashes the program. The package example is ExampleOnRunEnd.
On messages
Section titled “On messages”OnMessages is a run option: pass it to Generate or Stream, not to New. The loop calls it whenever messages join the run’s transcript: the assistant message a step produced, in its final shape with reasoning signatures, the tool message that follows its calls, and the messages a steering drain delivered.
var saved []weft.Message // stands in for an append-only storepersist := weft.OnMessages(func(_ context.Context, step int, msgs []weft.Message) { for _, m := range msgs { b, _ := json.Marshal(m) fmt.Fprintf(w, "step %d: save %s (%d bytes)\n", step, m.Role, len(b)) } saved = append(saved, msgs...)})res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"), persist)if err != nil { return err}// The prompt is the caller's input: it is in res.Messages, not in a batch.fmt.Fprintln(w, "saved equals the transcript after the prompt:", reflect.DeepEqual(saved, res.Messages[1:]))step 0: save assistant (116 bytes)step 0: save tool (143 bytes)step 1: save assistant (81 bytes)saved equals the transcript after the prompt: trueOn an ordinary run the batches concatenate to res.Messages after the run’s input, so appending each batch to durable storage keeps the exact transcript of a run that crashes mid-way. An approval resume is the exception: its first batch is the parked step’s completed tool message, which belongs right after the parked assistant message, not at the end (gotcha).
msgs is exactly what joined, in transcript order, as a deep copy: keeping or changing it changes nothing the run sees. step is the step the messages belong to; a steer’s messages name the step whose drain delivered them. Rebuilding messages from events loses signatures and block boundaries; this does not. A subagent’s child run does not inherit the observer. The package example is ExampleOnMessages.
Agent from context
Section titled “Agent from context”weft.Option is sealed, so an observer packaged as weft.Options(weft.Tap(…), weft.OnRunEnd(…)) never receives the agent it was installed on. weft.AgentFromContext(ctx) returns it: the agent whose run produced the event, or that a tool handler is running for.
who := weft.Tap(func(ctx context.Context, ev weft.Event) { if _, ok := ev.(weft.RunStart); ok { agt := weft.AgentFromContext(ctx) // the running *Agent; nil outside a run agt.Logger().DebugContext(ctx, "observer saw a run") fmt.Fprintln(w, "run start by", agt.Name()) }})researcher := weft.New(wefttest.Script(wefttest.Say("notes")), weft.Name("researcher"), who)lead := weft.New(wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "research", Args: `{"prompt":"tariffs"}`}), wefttest.Say("done"),), weft.Name("lead"), who, weft.Subagent("research", "Research a topic.", researcher))run start by leadrun start by researcheroutside a run: trueFor a subagent’s child run it is the child. Outside a run, in a manual agt.CallTool or a handler called directly, it is nil, so an observer must not depend on it. The agent is read-only: an Agent is immutable after New. agt.Logger() returns the run lines’ sink, the Logger option’s value or slog.Default, so an observer can log its own errors where the run’s lines go.
Debug log lines
Section titled “Debug log lines”weft.Logger(l) sets the logger the agent’s runs report to, at Debug level: one line when a run starts and ends, one per model call, one per tool call.
scrub := func(_ []string, a slog.Attr) slog.Attr { if a.Key == slog.TimeKey || a.Key == "dur" { // not reproducible return slog.Attr{} } return a}l := slog.New(slog.NewTextHandler(w, &slog.HandlerOptions{Level: slog.LevelDebug, ReplaceAttr: scrub}))agt := weft.New(script(), lookup, weft.Name("support-bot"), weft.Logger(l))_, err := agt.Generate(ctx, weft.RunID("demo"), weft.Prompt("Where is order 1234?"))level=DEBUG msg="run start" run=demo agent=support-bot provider=wefttest model=scriptlevel=DEBUG msg="model call" run=demo step=0 provider=wefttest model=script reason=tool_calls input_tokens=10 output_tokens=5 tool_calls=1level=DEBUG msg="tool call" run=demo step=0 call=call_1 tool=lookup_order result_bytes=22level=DEBUG msg="model call" run=demo step=1 provider=wefttest model=script reason=stop input_tokens=10 output_tokens=5 tool_calls=0level=DEBUG msg="run finish" run=demo steps=2 input_tokens=20 output_tokens=10 stop=stopThe lines carry ids, the model, durations, usage, stop reasons and outcomes; never message text, tool arguments or tool results. The one exception is error text: a failed run, model call or tool call logs the error it returned. The region drops the time and the dur attribute only to make the output reproducible.
Without the option the logger is slog.Default, which is silent until its handler enables Debug, so weft logs nothing in a program that did not ask. slog.New(slog.DiscardHandler) turns the lines off outright. The lines carry the span-carrying context, so a handler that bridges to OpenTelemetry correlates them with the spans. mw.Log and mw.Audit are separate: middleware you place, at the level you choose. The package example is ExampleLogger.
Complete example
Section titled “Complete example”observers/main.go runs each region against a scripted model that calls lookup_order once and then answers:
// Command observers runs the examples of the guide "Observe a run// without changing it": go run ./observers. Every model is scripted// with wefttest, so it runs offline; swap in a provider adapter for a// real one.package main
import ( "context" "encoding/json" "errors" "fmt" "io" "log/slog" "os" "reflect"
"github.com/weftgo/weft" "github.com/weftgo/weft/wefttest")
// lookup is the one tool every example uses.var lookup = weft.Tool("lookup_order", "Look up an order by ID.", func(_ context.Context, in struct { OrderID string `json:"order_id" jsonschema:"the order to look up"` }) (string, error) { return "order " + in.OrderID + " has shipped", nil })
// script is a two-step dialogue: one tool call, then an answer.func script() *wefttest.Model { return wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`}), wefttest.Say("Order 1234 has shipped."), )}
// tap counts tool calls and shows a panicking tap contained.func tap(ctx context.Context, w io.Writer) error { var calls int agt := weft.New(script(), lookup, weft.Tap(func(_ context.Context, ev weft.Event) { if _, ok := ev.(weft.ToolStart); ok { calls++ } }), weft.Tap(func(context.Context, weft.Event) { panic("broken observer") }), ) res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) if err != nil { return err } fmt.Fprintln(w, "tool calls:", calls) fmt.Fprintln(w, "answer:", res.Text()) fmt.Fprintln(w, "contained tap panics:", agt.TapPanics()) // one per event the broken tap saw return nil}
// async hands events to a queue and drains it on its own goroutine.func async(ctx context.Context, w io.Writer) error { events := make(chan weft.Event, 1024) dropped := 0 // written only inside the tap, read after the run done := make(chan int) go func() { // the slow side: a database write, a network sink n := 0 for range events { n++ } done <- n }() agt := weft.New(script(), lookup, weft.Tap(func(_ context.Context, ev weft.Event) { select { case events <- ev: // never block inside a tap default: dropped++ // a full queue drops, visibly } })) _, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) close(events) fmt.Fprintln(w, "events drained:", <-done, "dropped:", dropped) return err}
// runEnd sees a failed run, which no event reports.func runEnd(ctx context.Context, w io.Writer) error { agt := weft.New(wefttest.Script(wefttest.Fail(errors.New("provider down"))), weft.OnRunEnd(func(_ context.Context, res *weft.RunResult, err error) { var runErr *weft.RunError fmt.Fprintf(w, "run ended: id set=%t steps=%d run error=%t\n", res.ID != "", res.NumSteps(), errors.As(err, &runErr)) }), ) _, err := agt.Generate(ctx, weft.Prompt("hi")) fmt.Fprintln(w, "Generate returned:", err) return nil}
// messages persists each batch of transcript messages as it joins.func messages(ctx context.Context, w io.Writer) error { agt := weft.New(script(), lookup) var saved []weft.Message // stands in for an append-only store persist := weft.OnMessages(func(_ context.Context, step int, msgs []weft.Message) { for _, m := range msgs { b, _ := json.Marshal(m) fmt.Fprintf(w, "step %d: save %s (%d bytes)\n", step, m.Role, len(b)) } saved = append(saved, msgs...) }) res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"), persist) if err != nil { return err } // The prompt is the caller's input: it is in res.Messages, not in a batch. fmt.Fprintln(w, "saved equals the transcript after the prompt:", reflect.DeepEqual(saved, res.Messages[1:])) return nil}
// agentFromContext names the agent behind each RunStart, child runs// included.func agentFromContext(ctx context.Context, w io.Writer) error { who := weft.Tap(func(ctx context.Context, ev weft.Event) { if _, ok := ev.(weft.RunStart); ok { agt := weft.AgentFromContext(ctx) // the running *Agent; nil outside a run agt.Logger().DebugContext(ctx, "observer saw a run") fmt.Fprintln(w, "run start by", agt.Name()) } }) researcher := weft.New(wefttest.Script(wefttest.Say("notes")), weft.Name("researcher"), who) lead := weft.New(wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "research", Args: `{"prompt":"tariffs"}`}), wefttest.Say("done"), ), weft.Name("lead"), who, weft.Subagent("research", "Research a topic.", researcher)) _, err := lead.Generate(ctx, weft.Prompt("Brief me.")) fmt.Fprintln(w, "outside a run:", weft.AgentFromContext(ctx) == nil) return err}
// logger prints the Debug lines one run writes.func logger(ctx context.Context, w io.Writer) error { scrub := func(_ []string, a slog.Attr) slog.Attr { if a.Key == slog.TimeKey || a.Key == "dur" { // not reproducible return slog.Attr{} } return a } l := slog.New(slog.NewTextHandler(w, &slog.HandlerOptions{Level: slog.LevelDebug, ReplaceAttr: scrub})) agt := weft.New(script(), lookup, weft.Name("support-bot"), weft.Logger(l)) _, err := agt.Generate(ctx, weft.RunID("demo"), weft.Prompt("Where is order 1234?")) return err}
func run(ctx context.Context, w io.Writer) error { steps := []struct { title string fn func(context.Context, io.Writer) error }{ {"tap", tap}, {"slow observer", async}, {"run end", runEnd}, {"messages", messages}, {"agent from context", agentFromContext}, {"logger", logger}, } for _, s := range steps { fmt.Fprintf(w, "== %s\n", s.title) if err := s.fn(ctx, w); 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 ./observersgo test ./observers== taptool calls: 1answer: Order 1234 has shipped.contained tap panics: 9== slow observerevents drained: 9 dropped: 0== run endrun ended: id set=true steps=0 run error=trueGenerate returned: weft: run failed at step 0: model stream: provider down== messagesstep 0: save assistant (116 bytes)step 0: save tool (143 bytes)step 1: save assistant (81 bytes)saved equals the transcript after the prompt: true== agent from contextrun start by leadrun start by researcheroutside a run: true== loggerlevel=DEBUG msg="run start" run=demo agent=support-bot provider=wefttest model=scriptlevel=DEBUG msg="model call" run=demo step=0 provider=wefttest model=script reason=tool_calls input_tokens=10 output_tokens=5 tool_calls=1level=DEBUG msg="tool call" run=demo step=0 call=call_1 tool=lookup_order result_bytes=22level=DEBUG msg="model call" run=demo step=1 provider=wefttest model=script reason=stop input_tokens=10 output_tokens=5 tool_calls=0level=DEBUG msg="run finish" run=demo steps=2 input_tokens=20 output_tokens=10 stop=stopBest practices & gotchas
Section titled “Best practices & gotchas”- Never block inside a tap. A tap runs under the event-ordering lock; a slow one gates the step’s tool events. Queue the event and drain elsewhere. (Source:
weft/core/agent.go:437-451,ExampleTap_async) - Use
OnRunEnd, notTap, to record failures. A failed run has noRunFinishand no event after its last one. (Source: ADR 0004,TestFailureIsInvisibleToTap) - Pass
OnMessagesper run. It is aRunOption; it is not an agent option and child runs do not inherit it. (Source: AGENTS.md:86-87,weft/core/run.go:551-574) - Replace, do not append, a resume’s first tool message. On a resume, the step-0 batch starts with the completed tool message. If the parked step had a call that already ran, say
lookupbeside a gatedrefund, your store already holds a partial tool message withlookup’s result. Appending gives two tool messages for one step, andweft.Repairthen keeps the partial one and answersrefundwithno result recorded: the call was interrupted, so the next model may refund again. Put the resume’s tool message right after the parked assistant message, in place of any tool message stored there.res.Messages[len(input):]misses it the same way.weft/threadhandles this for you (sessions). (Source:weft/core/loop.go:308-329, 431-440,weft/thread/perstep.go:111-117, 215-231; scratch test) - Watch
TapPanics. A panicking observer is contained and counted, so a broken one is otherwise silent. (Source:weft/core/agent.go:1004-1011, CHANGELOG 0.2.0) - Check
AgentFromContextfor nil. It is nil outside a run, such as a manualCallTool. (Source:weft/core/subagent.go:149-159) - Do not expect content in
weft.Logger’s lines.weft.Loggeronly sets where the loop’s own Debug lines go, and those lines carry ids and outcomes, never message text, tool arguments or results; content goes to the observability pipeline under its content policy. (Source:weft/core/agent.go:511-524)
See also
Section titled “See also”- Add behaviour with middleware (the two seams): when you need to change a call, not watch it
- Stream a run’s events
- Tag runs with metadata
- Record runs
- Event types
Symbols used: weft.Tap · weft.OnRunEnd · weft.OnMessages · weft.Logger · weft.AgentFromContext · Agent.Logger · Agent.TapPanics · Agent.CallTool · weft.RunError · weft.RunID · weft.Subagent · weft.Name · wefttest.Script · wefttest.Fail · ExampleTap · ExampleTap_async · ExampleOnRunEnd · ExampleOnMessages · ExampleLogger · weft.Repair