Skip to content

What does a run return?

View as Markdown

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:

concepts/runs.go
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))

concepts/runs.go on GitHub

id length: 32
text: Order 1234 has shipped.
steps: 2 last stop reason: stop
messages: 4
usage: 20 in, 10 out
pending: 0

Two steps: the model asked for lookup_order, then answered. Four messages: the prompt, the assistant’s tool call, the tool result, the answer.

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?.

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.Prompt adds a user message to the run’s input.
  • weft.Messages adds existing messages: an earlier transcript, few-shot examples. weft.Messages(res.Messages...) followed by weft.Prompt(...) continues a conversation.
  • weft.RunID sets 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:

concepts/runs.go
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)

concepts/runs.go on GitHub

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.

Field or methodWhat it holds
res.IDThe run’s id: the RunID option’s value, else a generated one.
res.MessagesThe full transcript, the input messages included, as the loop repaired and extended it. Feed it back with weft.Messages to continue.
res.StepsOne StepRecord per model call, in order.
res.UsageToken usage summed over every step, subagent runs included.
res.StopReasonThe 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.PendingTool 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:

FieldWhat it holds
IndexThe step’s zero-based number.
StopReasonWhy the model call ended, mapped to stop, tool_calls or max_tokens.
RawStopReasonThe provider’s own reason when the mapping was approximate (refusal, content_filter, …); empty when it was exact.
UsageThis step’s own model call only.
TextThe assistant text the step streamed.
ToolCallsThe calls the model requested, as weft.ToolCallPart values.
ResultsTheir results, in call order, as weft.ToolResultPart values.
SubagentUsageThe 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:

FieldSubset ofCounts
InputTokens—Every token billed as input.
OutputTokens—Every token billed as output.
CachedInputTokensInputTokensInput read from a provider prompt cache.
CacheWriteTokensInputTokensInput written to a prompt cache (Anthropic).
ReasoningTokensOutputTokensOutput 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:

concepts/runs.go
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())

concepts/runs.go on GitHub

step 0: tool_calls, 1 call(s), 1 result(s), 15 tokens
step 1: stop, 0 call(s), 0 result(s), 15 tokens
sum of steps: 30 run total: 30

With 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.

A run ends one of two ways, and the return values say which:

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.

concepts/runs.go runs the agent, reads the result and its steps, and starts a run with an id the caller chose:

concepts/runs.go
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()))
}

View concepts/runs.go on GitHub

Run it from docs-site/examples:

Terminal window
go run ./concepts runs
go test ./concepts
id length: 32
text: Order 1234 has shipped.
steps: 2 last stop reason: stop
messages: 4
usage: 20 in, 10 out
pending: 0
step 0: tool_calls, 1 call(s), 1 result(s), 15 tokens
step 1: stop, 0 call(s), 0 result(s), 15 tokens
sum of steps: 30 run total: 30
id before the run starts: order-1234-attempt-1
result id: order-1234-attempt-1
  • Read a failed run’s work from the error, not from res. Generate returns a nil result with a *RunError; the partial transcript is on RunError.Result. (Source: weft/core/loop.go:264-274, AGENTS.md rule 1)
  • Check res.Pending after every successful run that has approval-gated tools. A parked call ends the run successfully, so err == nil does not mean every call ran. (Source: weft/core/run.go:701-706, AGENTS.md rule 12)
  • Check res.StopReason before trusting the answer. StopMaxTokens on 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 that StopWhen(HasToolCall("submit_answer")) ended has the call’s message as its last assistant message and the tool message after it, so res.Text() is "" unless the model also wrote text. Read res.Steps[len(res.Steps)-1].ToolCalls (the arguments) or .Results (what the handler returned), or use weft.Output[T] with weft.GenerateAs. (Source: weft/core/run.go:714-721, weft/core/agent.go:577-588; scratch proof in sources)
  • Budget on res.Usage, not on the steps. Only res.Usage includes subagent runs. (Source: weft/core/run.go:682-686)
  • Give every attempt its own weft.RunID, and correlate attempts with weft.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 like order-1234-attempt-2, with weft.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 in sources)

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