---
title: What does a run return?
description: A run is one Generate or Stream call; it returns a RunResult with the run's id, the full transcript, one StepRecord per model call and the summed Usage.
url: https://weftgo.dev/docs/concepts/runs/
type: concept
sources:
  - weft/AGENTS.md (block 3, lines 107–122; rules 4 and 13)
  - weft/core/run.go:21-24 (RunOption), 225-232 (RunID), 649-666 (Prompt, Messages)
  - weft/core/run.go:668-721 (StepRecord, RunResult, NumSteps, Text)
  - 'weft/core/run.go:714-721 (Text: the last assistant message''s text parts; after a HasToolCall stop that message holds the call)'
  - 'scratch proof (weft v0.17.0, docs a9 fix): a script calling submit_answer with {"answer":"42"} under StopWhen(HasToolCall("submit_answer")) gave err nil, res.Text() "", a last message with role tool, and res.Steps[len-1].ToolCalls[0].Args {"answer":"42"} beside Results[0].Content "submitted 42"'
  - weft/core/run.go:723-858 (Run, Stream, Run.ID, Events, Wait, Generate)
  - weft/core/run.go:576-589 (newRunID — 128-bit hex)
  - 'weft/obsdb/db.go:27-28 (Write: idempotent on (run, record kind, pos) and (trace, span)); weft/obsdb/sqlite/write.go:19-21 (INSERT OR IGNORE on the idempotency keys)'
  - weft/core/subagent.go:316 (a child run's config is the call's id and the prompt alone, so no parent override reaches it); weft/core/loop.go:63 (metadata merged from the context)
  - 'weft/core/subagent.go:166-174 (childRunID: a child''s id derives from the parent call, <parent>/<step>/<call>)'
  - 'scratch proof (weft v0.17.0, otel.Local): two Generate calls with RunID("order-1234"), prompts q one and q two, one Subagent call each; db.Run gave prompt q one, 2 steps, and the transcript and the child order-1234/0/call_1 of the first run only: the second run''s events and transcript were dropped, but its spans were kept and its metadata merged into the row (fact-check audit-a7-fixes: map[first:1 second:2] on parent and child; RunSpans gave 8 spans across two trace ids; the runs upsert per run, obsdb/sqlite/write.go:19-21). RunID order-1234-attempt-1 and -2 with Metadata request_key=order-1234 stored two runs, each with the key'
  - weft/core/model.go:9-49 (Usage, Add, Total, StopReason)
  - weft/core/loop.go:264-296 (fail returns nil and a *RunError; endRun delivers RunFinish), 344-351 (ErrInvalidRunOption), 755-773 (StepRecord built per step, SubagentUsage rolled up)
  - weft/core/errors.go:128-133 (ErrInvalidRunOption)
  - weft/CHANGELOG.md:6009 (cached, cache-write and reasoning splits), 6443 (the terminal RunFinish decides the outcome)
  - weft/example_test.go ExampleAgent_generate
  - docs-site/examples/concepts/runs.go, concepts_test.go TestDemos/runs, TestMaxStepsRaiseRefused
---

# What does a run return?

A run is one execution of an agent: [`agt.Generate`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Generate) calls the model and the tools until the run ends, then returns a [`*weft.RunResult`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunResult). The result holds the run's id, the full transcript, one [`weft.StepRecord`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StepRecord) per model call, and the summed [`weft.Usage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Usage).

`concepts/runs.go` runs a one-tool agent and prints what the result holds:

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

```text
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](https://weftgo.dev/docs/reference/glossary/#step): 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

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?](https://weftgo.dev/docs/concepts/the-loop/); how a run decides to end is on [How does a run stop?](https://weftgo.dev/docs/concepts/budgets-and-stopping/).

## Generate

`agt.Generate(ctx, opts...)` runs the agent to completion and returns `(*RunResult, error)`. Its options are [`weft.RunOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunOption) values: they configure this run alone and are applied in the order given.

- [`weft.Prompt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Prompt) adds a user message to the run's input.
- [`weft.Messages`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Messages) adds existing messages: an earlier transcript, few-shot examples. `weft.Messages(res.Messages...)` followed by `weft.Prompt(...)` continues a conversation.
- [`weft.RunID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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](#best-practices--gotchas)).

`Generate` is [`agt.Stream`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Stream) with the events folded away. `Stream` returns a [`*weft.Run`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Run), a handle that does nothing until you consume it. Its id is fixed when `Stream` returns, so [`run.ID()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Run.ID) can go into a log line or a response header before the first event:

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

`run.Wait()` runs the agent itself when nobody ranges over `run.Events()`, discarding the events; [Stream a run's events](https://weftgo.dev/docs/guides/streaming/) covers the event side. The package example [`ExampleAgent_generate`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#pkg-examples) 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](https://weftgo.dev/docs/guides/subagents/#what-reaches-the-child-run)). [Change an agent's configuration for one run](https://weftgo.dev/docs/guides/run-options/) lists them all.

## The result

| Field or method | What it holds |
|---|---|
| [`res.ID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunResult) | 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](https://weftgo.dev/docs/guides/approvals/). |
| [`res.NumSteps()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#RunResult.NumSteps) | How many model calls the run made: `len(res.Steps)`. |
| [`res.Text()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#RunResult.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`. |

## Steps

A [`StepRecord`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolCallPart) values. |
| `Results` | Their results, in call order, as [`weft.ToolResultPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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`.

## Usage

A [`Usage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#UsageLimit) and [`Usage.Total`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#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`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Usage.Add) returns the element-wise sum.

The steps' own usage adds up to the run's when no subagent ran:

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

```text
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](https://weftgo.dev/docs/reference/glossary/#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

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

- **Success:** `res` is the result and `err` is nil. The run's last event was `RunFinish`.
- **Failure:** `res` is nil and `err` is a [`*weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError). Its `Result` field holds the partial transcript, steps and usage up to the failure. See [Tool errors are data, run errors are yours](https://weftgo.dev/docs/concepts/errors/#run-errors).

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

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

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

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

Run it from `docs-site/examples`:

```sh
go run ./concepts runs
go test ./concepts
```

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

## Best practices & gotchas

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

## See also

- [Stream a run's events](https://weftgo.dev/docs/guides/streaming/)
- [Continue a conversation](https://weftgo.dev/docs/guides/conversations/)
- [Change an agent's configuration for one run](https://weftgo.dev/docs/guides/run-options/)
- [How does a run stop?](https://weftgo.dev/docs/concepts/budgets-and-stopping/)
- [Event types](https://weftgo.dev/docs/reference/events/)

Symbols used: [`Agent.Generate`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Generate) · [`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.ID`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Run.ID) · [`Run.Wait`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Run.Wait) · [`weft.RunOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunOption) · [`weft.Prompt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Prompt) · [`weft.Messages`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Messages) · [`weft.RunID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunID) · [`weft.Metadata`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Metadata) · [`weft.RunResult`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunResult) · [`weft.StepRecord`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StepRecord) · [`weft.Usage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Usage) · [`weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) · [`weft.UsageLimit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#UsageLimit) · [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script)
