What does a run return?
A run is one execution of an agent: agt.Generate calls the model and the tools until the run ends, then returns a *weft.RunResult. The result holds the run’s id, the full transcript, one weft.StepRecord per model call, and the summed weft.Usage.
concepts/runs.go runs a one-tool agent and prints what the result holds:
res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))if err != nil { return nil, err}fmt.Fprintln(w, "id length:", len(res.ID))fmt.Fprintln(w, "text:", res.Text())fmt.Fprintln(w, "steps:", res.NumSteps(), "last stop reason:", res.StopReason)fmt.Fprintln(w, "messages:", len(res.Messages))fmt.Fprintln(w, "usage:", res.Usage.InputTokens, "in,", res.Usage.OutputTokens, "out")fmt.Fprintln(w, "pending:", len(res.Pending))id length: 32text: Order 1234 has shipped.steps: 2 last stop reason: stopmessages: 4usage: 20 in, 10 outpending: 0Two steps: the model asked for lookup_order, then answered. Four messages: the prompt, the assistant’s tool call, the tool result, the answer.
How it works
Section titled “How it works”A run starts with a RunStart event, makes one model call per step, and ends either successfully, with a RunFinish event, or with an error. Every run has an id, fixed before it executes. What happens inside one step is on What happens in one step?; how a run decides to end is on How does a run stop?.
Generate
Section titled “Generate”agt.Generate(ctx, opts...) runs the agent to completion and returns (*RunResult, error). Its options are weft.RunOption values: they configure this run alone and are applied in the order given.
weft.Promptadds a user message to the run’s input.weft.Messagesadds existing messages: an earlier transcript, few-shot examples.weft.Messages(res.Messages...)followed byweft.Prompt(...)continues a conversation.weft.RunIDsets the run’s id instead of generating one, for replays, idempotent retries, or an id from an outer system; an empty value is ignored, and a generated id is 128 random bits as 32 hex characters. For an idempotent retry, keep the outer system’s key stable across attempts, not the run id. A recorded run needs a fresh id for each attempt (gotcha).
Generate is agt.Stream with the events folded away. Stream returns a *weft.Run, a handle that does nothing until you consume it. Its id is fixed when Stream returns, so run.ID() can go into a log line or a response header before the first event:
run := agt.Stream(ctx, weft.RunID("order-1234-attempt-1"), weft.Prompt("Where is order 1234?"))fmt.Fprintln(w, "id before the run starts:", run.ID())res, err := run.Wait() // runs to the end, discarding the eventsif err != nil { return err}fmt.Fprintln(w, "result id:", res.ID)run.Wait() runs the agent itself when nobody ranges over run.Events(), discarding the events; Stream a run’s events covers the event side. The package example ExampleAgent_generate is the same call in its shortest form.
Some options exist at both levels. weft.Instructions, weft.MaxSteps, weft.Parallelism, weft.Thinking, weft.ToolChoice and weft.Params are accepted by New as the agent’s default and by Generate as a one-run override. A run may only lower MaxSteps and Parallelism: a raise fails the run with ErrInvalidRunOption before any model call. A one-run override stays with the run it was given to: a weft.Subagent child runs on its own agent’s defaults, and only context-carried state such as weft.Metadata reaches it (what reaches the child run). Change an agent’s configuration for one run lists them all.
The result
Section titled “The result”| Field or method | What it holds |
|---|---|
res.ID | The run’s id: the RunID option’s value, else a generated one. |
res.Messages | The full transcript, the input messages included, as the loop repaired and extended it. Feed it back with weft.Messages to continue. |
res.Steps | One StepRecord per model call, in order. |
res.Usage | Token usage summed over every step, subagent runs included. |
res.StopReason | The last step’s finish reason. StopMaxTokens here means the final reply was cut off; the run still succeeds and the caller decides what the truncated text means. |
res.Pending | Tool calls of the last step waiting for an approval decision. The run ended successfully without running them, and the transcript has no result for them. See Require human approval for a tool. |
res.NumSteps() | How many model calls the run made: len(res.Steps). |
res.Text() | The text parts of the last assistant message: the answer when the run ended on a text reply. After a StopWhen(HasToolCall(...)) stop it is only the text the model wrote beside the call, often ""; the answer is the call’s arguments, on the last step’s ToolCalls. |
A StepRecord captures what one model call produced and what its tool calls returned:
| Field | What it holds |
|---|---|
Index | The step’s zero-based number. |
StopReason | Why the model call ended, mapped to stop, tool_calls or max_tokens. |
RawStopReason | The provider’s own reason when the mapping was approximate (refusal, content_filter, …); empty when it was exact. |
Usage | This step’s own model call only. |
Text | The assistant text the step streamed. |
ToolCalls | The calls the model requested, as weft.ToolCallPart values. |
Results | Their results, in call order, as weft.ToolResultPart values. |
SubagentUsage | The usage of each child run the step started, keyed by the parent’s call id, a failed child’s partial usage included. Nil when the step ran no subagent. |
Calls an approval resumed run before the first step and belong to no step, so they have no StepRecord.
A Usage counts tokens for one step or one run. InputTokens and OutputTokens are inclusive totals; the other three fields are subsets of them, reported when the provider gives them:
| Field | Subset of | Counts |
|---|---|---|
InputTokens | — | Every token billed as input. |
OutputTokens | — | Every token billed as output. |
CachedInputTokens | InputTokens | Input read from a provider prompt cache. |
CacheWriteTokens | InputTokens | Input written to a prompt cache (Anthropic). |
ReasoningTokens | OutputTokens | Output the model spent on provider-side reasoning. |
All three adapters fill the splits. They are reporting, not budget bases: weft.UsageLimit and Usage.Total read the two totals, so a run served from cache budgets the same as one that was not. Total() returns input plus output; Usage.Add returns the element-wise sum.
The steps’ own usage adds up to the run’s when no subagent ran:
var sum weft.Usagefor _, st := range res.Steps { fmt.Fprintf(w, "step %d: %s, %d call(s), %d result(s), %d tokens\n", st.Index, st.StopReason, len(st.ToolCalls), len(st.Results), st.Usage.Total()) sum = sum.Add(st.Usage)}fmt.Fprintln(w, "sum of steps:", sum.Total(), "run total:", res.Usage.Total())step 0: tool_calls, 1 call(s), 1 result(s), 15 tokensstep 1: stop, 0 call(s), 0 result(s), 15 tokenssum of steps: 30 run total: 30With a subagent, res.Usage is larger than the sum of the steps’ own Usage: the child runs’ usage is in res.Usage and in each step’s SubagentUsage, never in the step’s own Usage.
Run results
Section titled “Run results”A run ends one of two ways, and the return values say which:
- Success:
resis the result anderris nil. The run’s last event wasRunFinish. - Failure:
resis nil anderris a*weft.RunError. ItsResultfield holds the partial transcript, steps and usage up to the failure. See Tool errors are data, run errors are yours.
The terminal RunFinish decides the outcome. A run that delivered RunFinish returns success; a cancellation that lands between the loop’s last context check and that event fails the run with the cancellation error instead, the resumable result on the RunError. A run never returns success without its RunFinish, and never delivers RunFinish and then fails.
Complete example
Section titled “Complete example”concepts/runs.go runs the agent, reads the result and its steps, and starts a run with an id the caller chose:
package main
import ( "context" "fmt" "io"
"github.com/weftgo/weft" "github.com/weftgo/weft/wefttest")
// runOrderAgent builds a one-tool agent over model: lookup_order answers// "shipped" for any order.func runOrderAgent(model weft.Model) *weft.Agent { return weft.New(model, weft.Tool("lookup_order", "Look up an order by ID.", func(ctx context.Context, in OrderLookup) (string, error) { return "order " + in.OrderID + ": shipped", nil }), )}
// orderScript plays two model turns: call lookup_order, then answer.func orderScript() *wefttest.Model { return wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`}), wefttest.Say("Order 1234 has shipped."), )}
// readResult runs the agent once and prints what the RunResult holds.func readResult(ctx context.Context, w io.Writer, agt *weft.Agent) (*weft.RunResult, error) { res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) if err != nil { return nil, err } fmt.Fprintln(w, "id length:", len(res.ID)) fmt.Fprintln(w, "text:", res.Text()) fmt.Fprintln(w, "steps:", res.NumSteps(), "last stop reason:", res.StopReason) fmt.Fprintln(w, "messages:", len(res.Messages)) fmt.Fprintln(w, "usage:", res.Usage.InputTokens, "in,", res.Usage.OutputTokens, "out") fmt.Fprintln(w, "pending:", len(res.Pending)) return res, nil}
// readSteps prints one line per step and checks the steps add up to the// run's usage.func readSteps(w io.Writer, res *weft.RunResult) { var sum weft.Usage for _, st := range res.Steps { fmt.Fprintf(w, "step %d: %s, %d call(s), %d result(s), %d tokens\n", st.Index, st.StopReason, len(st.ToolCalls), len(st.Results), st.Usage.Total()) sum = sum.Add(st.Usage) } fmt.Fprintln(w, "sum of steps:", sum.Total(), "run total:", res.Usage.Total())}
// namedRun starts a run with an id the caller chose and reads the id// before the run executes.func namedRun(ctx context.Context, w io.Writer, agt *weft.Agent) error { run := agt.Stream(ctx, weft.RunID("order-1234-attempt-1"), weft.Prompt("Where is order 1234?")) fmt.Fprintln(w, "id before the run starts:", run.ID()) res, err := run.Wait() // runs to the end, discarding the events if err != nil { return err } fmt.Fprintln(w, "result id:", res.ID) return nil}
// demoRuns runs the order agent and reads its result, its steps, and a// run whose id the caller set.func demoRuns(ctx context.Context, w io.Writer) error { res, err := readResult(ctx, w, runOrderAgent(orderScript())) if err != nil { return err } readSteps(w, res) return namedRun(ctx, w, runOrderAgent(orderScript()))}Run it from docs-site/examples:
go run ./concepts runsgo test ./conceptsid length: 32text: Order 1234 has shipped.steps: 2 last stop reason: stopmessages: 4usage: 20 in, 10 outpending: 0step 0: tool_calls, 1 call(s), 1 result(s), 15 tokensstep 1: stop, 0 call(s), 0 result(s), 15 tokenssum of steps: 30 run total: 30id before the run starts: order-1234-attempt-1result id: order-1234-attempt-1Best practices & gotchas
Section titled “Best practices & gotchas”- Read a failed run’s work from the error, not from
res.Generatereturns a nil result with a*RunError; the partial transcript is onRunError.Result. (Source:weft/core/loop.go:264-274, AGENTS.md rule 1) - Check
res.Pendingafter every successful run that has approval-gated tools. A parked call ends the run successfully, soerr == nildoes not mean every call ran. (Source:weft/core/run.go:701-706, AGENTS.md rule 12) - Check
res.StopReasonbefore trusting the answer.StopMaxTokenson a successful run means the final text was cut off. (Source:weft/core/run.go:693-697, AGENTS.md rule 8) - Read a final-answer tool’s answer from the last step, not from
res.Text(). A run thatStopWhen(HasToolCall("submit_answer"))ended has the call’s message as its last assistant message and the tool message after it, sores.Text()is""unless the model also wrote text. Readres.Steps[len(res.Steps)-1].ToolCalls(the arguments) or.Results(what the handler returned), or useweft.Output[T]withweft.GenerateAs. (Source:weft/core/run.go:714-721,weft/core/agent.go:577-588; scratch proof insources) - Budget on
res.Usage, not on the steps. Onlyres.Usageincludes subagent runs. (Source:weft/core/run.go:682-686) - Give every attempt its own
weft.RunID, and correlate attempts withweft.Metadata. Under a reused id, the store keeps the first run’s events and transcript and drops the later run’s, its subagent children (<parent>/<step>/<call>) included. The later run’s spans and metadata are still added, so the run row and the span and trace views blend both runs. Use ids likeorder-1234-attempt-2, withweft.Metadata(map[string]string{"request_key": "order-1234"})on each attempt. (Source:weft/core/run.go:225-232;weft/obsdb/db.go:27-28;weft/obsdb/sqlite/write.go:19-21;weft/core/subagent.go:166-174; scratch proof insources)
See also
Section titled “See also”- Stream a run’s events
- Continue a conversation
- Change an agent’s configuration for one run
- How does a run stop?
- Event types
Symbols used: Agent.Generate · Agent.Stream · weft.Run · Run.ID · Run.Wait · weft.RunOption · weft.Prompt · weft.Messages · weft.RunID · weft.Metadata · weft.RunResult · weft.StepRecord · weft.Usage · weft.RunError · weft.UsageLimit · weft.Tool · wefttest.Script