How does a run stop?
A run stops in one of two ways. It ends successfully at its intended end: the model answers without calling a tool, a weft.StopWhen condition matches, or calls are waiting for approval. It fails with a sentinel error, such as ErrMaxSteps, when a safety budget runs out (weft.MaxSteps, weft.UsageLimit, weft.MaxModelRetries, weft.DetectLoops) or its context is canceled. Reaching a budget is never a quiet success.
The intended end, from concepts/budgets.go: the run is over once the model calls submit:
submit := weft.Tool("submit", "Submit the final answer.", func(ctx context.Context, in SubmitInput) (string, error) { return "recorded", nil })agt := weft.New(model, submit, weft.StopWhen(weft.HasToolCall("submit")))for ev, err := range agt.Stream(ctx, weft.Prompt("Answer, then submit.")).Events() { if err != nil { return err } if fin, ok := ev.(weft.RunFinish); ok { fmt.Fprintln(w, "stopped by:", fin.StoppedBy, "after", fin.Steps, "step(s)") }}stopped by: has_tool_call:submit after 1 step(s)The step that called submit runs its tools, then the run ends without another model call.
How it works
Section titled “How it works”After each step’s tool calls have run, the loop asks, in order: are calls pending approval? Does a StopWhen condition match? Did the model make no tool calls? Any yes ends the run with RunFinish, so a final answer that also matches a condition reports the condition. One exception: when a steering source delivers a message at what would be the final step, the run takes one more step instead of ending (Steer a running turn); pending approvals and StopWhen ends are never redirected. Otherwise the loop has reached the continuation point, where it would spend more, and checks the budgets there: MaxModelRetries, then UsageLimit, then DetectLoops, first breach wins. MaxSteps bounds the loop itself.
Budgets fail only at the continuation point. A step that ends the run succeeds even if it overshot a budget, because a budget’s job is to stop further spend, not to discard finished work.
What stopped a run
Section titled “What stopped a run”Every run records what ended it. RunFinish.StoppedBy and the invoke_agent span’s weft.run.stopped_by attribute carry the same value:
| Value | Ended by | Outcome |
|---|---|---|
final_answer | A step with no tool calls | success |
has_tool_call:<names>, step_count_is:<n>, output_submitted | That StopWhen condition | success |
a custom condition’s String(), else custom | A custom StopWhen condition | success |
parked | Calls pending approval | success |
max_steps, usage_limit, loop_detected, model_retries_exceeded | That budget | failure (span only) |
canceled | The run’s ctx | failure (span only) |
A failed run has no RunFinish, so the failure values exist only on the span. A run that failed for another reason, such as a model error, has no stopped_by; its span’s error.type names the cause.
Stop when
Section titled “Stop when”weft.StopWhen(conds...) adds stop conditions; the run ends when any one matches. Without it, a run ends when the model replies without requesting tools. A weft.StopCondition is one method, Stop(steps []StepRecord) bool, called after a step’s tool calls have run with every step so far; the last element is the step just finished.
weft.HasToolCall(names...)matches once the step just finished called any named tool: the final-answer-tool pattern. It checks only the call, not its result, so asubmitcall that failed (bad arguments, a handler error) ends the run too, successfully, with theINVALID_INPUTor error result as the last message and no step left for the model to repair it.weft.Output[T]ends only on a valid submission. After such a stop,res.Text()holds only text the model wrote beside the call, often"": the answer is the call’s arguments onres.Steps[len(res.Steps)-1].ToolCalls, and the handler’s return on that step’sResults.weft.StepCountIs(n)matches afternsteps, successfully, where reachingMaxStepsis a failure.weft.StopFuncadapts an ordinaryfunc([]StepRecord) bool, thehttp.HandlerFuncshape; itsStopmethod calls the function. Conditions seeStepRecord.Results, so a custom one can wait for a tool’s result.
The built-ins implement fmt.Stringer, which is how the manifest and StoppedBy name them; give a custom condition a String() method to name it too. weft.Output[T] registers its own condition, output_submitted (Get structured output from a run).
Max steps
Section titled “Max steps”weft.MaxSteps(n) is the safety budget behind ErrMaxSteps: the most model calls a run may make, 10 by default. When the model still requests tools after the last allowed step, the run fails with weft.ErrMaxSteps, the whole transcript (the last step’s tool results included) on the RunError:
agt := weft.New(model, checkOrder(), weft.MaxSteps(3))_, err := agt.Generate(ctx, weft.Prompt("Tell me when order 1234 ships."))var re *weft.RunErrorif errors.As(err, &re) && errors.Is(err, weft.ErrMaxSteps) { fmt.Fprintln(w, err) fmt.Fprintln(w, "kept:", re.Result.NumSteps(), "steps,", len(re.Result.Messages), "messages")}weft: run failed at step 3: weft: run exceeded the maximum number of stepskept: 3 steps, 7 messagesUse StopWhen for the end you intend and MaxSteps for the one you do not. Values below 1 are ignored. As a run option weft.MaxSteps may only lower the agent’s value; a raise fails with ErrInvalidRunOption before any model call. If the run is canceled during its last step’s tools, it fails with the cancellation, not ErrMaxSteps: the cause wins over the budget.
Usage limit
Section titled “Usage limit”weft.UsageLimit(max) bounds a run’s total tokens: its own model calls plus every subagent’s, as RunResult.Usage sums them. A field left zero is unlimited, and there is no default limit. Past the limit, the run fails with weft.ErrUsageLimit, wrapped with the numbers:
researcher := weft.New(researchModel, weft.Name("researcher"))lead := weft.New(leadModel, weft.Subagent("research", "Research a topic in depth.", researcher), weft.UsageLimit(weft.Usage{OutputTokens: 8}), // the run's own calls plus every subagent's)_, err := lead.Generate(ctx, weft.Prompt("Why are shipments late?"))var re *weft.RunErrorif errors.As(err, &re) && errors.Is(err, weft.ErrUsageLimit) { fmt.Fprintln(w, err) fmt.Fprintln(w, "own step:", re.Result.Steps[0].Usage.OutputTokens, "output tokens; with the subagent:", re.Result.Usage.OutputTokens)}weft: run failed at step 0: weft: run exceeded its usage limit (input 20/0, output 10/8)own step: 5 output tokens; with the subagent: 10The lead’s own model call spent 5 output tokens, under the limit; the research subagent’s 5 more pushed the run over.
The limit counts a child’s usage but cannot stop a running child. A delegation is one tool call in one of the lead’s steps, and the lead checks its limit only before its next model call. The child runs to its own end first, bounded by its own agent’s MaxSteps and UsageLimit, and every delegation of that step runs. A lead with UsageLimit{OutputTokens: 6} delegated once to a child that made 7 model calls; only then did the lead fail with output 40/6. The same child with its own UsageLimit{OutputTokens: 6} stopped after 2 calls.
Usage.Total() is not a separate limit: to bound the total, set both fields. A thread/pool child is a session, not a tool-call child: its usage is not on the parent run’s Usage, so UsageLimit does not cover it (Run bounded child sessions with a pool).
Model retries
Section titled “Model retries”weft.MaxModelRetries(n) bounds how many RETRY results one tool may produce in a run since its last successful result, 3 by default. Past it, the run fails with weft.ErrModelRetriesExceeded: a model that cannot correct itself is a failure, not an endless loop. The count is per tool name; a successful result for the tool resets it, other error results neither count nor reset it, and calls resumed under Approve do not count. Ask the model to retry shows the RETRY side.
Detect loops
Section titled “Detect loops”weft.DetectLoops(repeats) fails a run with weft.ErrLoopDetected when repeats consecutive steps request the same set of tool calls: the same names with the same raw argument bytes, in any order. It is off by default, and values below 2 are ignored.
agt := weft.New(model, checkOrder(), weft.DetectLoops(3))_, err := agt.Generate(ctx, weft.Prompt("Tell me when order 1234 ships."))fmt.Fprintln(w, err)weft: run failed at step 2: weft: the model repeated the same tool calls too many times: 3 identical steps in a rowResults are not part of the comparison, so a tool whose output carries a timestamp cannot hide a loop. Different arguments are not a loop: a corrected retry has a different signature.
Stop reasons
Section titled “Stop reasons”Each model call ends with a weft.StopReason, recorded on StepRecord.StopReason, on StepFinish.Reason, and for the last step on RunResult.StopReason:
| Constant | Value | Meaning |
|---|---|---|
weft.StopEndTurn | stop | The model finished its turn. |
weft.StopToolCalls | tool_calls | The model stopped to call tools. |
weft.StopMaxTokens | max_tokens | The output hit the token limit. |
When the provider’s own reason did not map exactly (refusal, content_filter, …), it is kept beside the mapped one in StepRecord.RawStopReason.
Truncation is visible
Section titled “Truncation is visible”A max_tokens finish never passes silently:
- Text only: the run succeeds with
RunResult.StopReasonset toStopMaxTokens. The caller decides what truncated text means. - With tool calls: none of the calls runs, because an intact-looking call may be the first of several the model never finished. Each gets the error result
tool call <name> was not executed: the response hit the output token limit, and the loop continues so the model retries with a full budget.
cut := wefttest.Raw( // the response hit max_tokens after one tool call weft.ModelToolCall{ID: "call_1", Name: "check_order", Args: json.RawMessage(`{"order_id":"1234"}`)}, weft.ModelFinish{Reason: weft.StopMaxTokens},)agt := weft.New(wefttest.Script(cut, wefttest.Say("Order 1234 is still processing.")), checkOrder())res, err := agt.Generate(ctx, weft.Prompt("Is order 1234 ready?"))if err != nil { return err}fmt.Fprintln(w, res.Steps[0].Results[0].Content)fmt.Fprintln(w, "steps:", res.NumSteps(), "final stop reason:", res.StopReason)tool call check_order was not executed: the response hit the output token limitsteps: 2 final stop reason: stopThe same rule makes long tool results visible: a result past MaxResultBytes ends with a marker naming the bytes cut.
Cancel with a cause
Section titled “Cancel with a cause”A canceled ctx fails the run with a *RunError matching context.Canceled (or context.DeadlineExceeded). No event follows the cancellation, and the partial transcript is on RunError.Result. To say why the run was canceled, cancel through context.WithCancelCause with a weft.CancelCause:
ctx, cancel := context.WithCancelCause(ctx)cancel(weft.CancelCause("app.shutdown")) // e.g. on SIGTERM
_, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))fmt.Fprintln(w, "context.Canceled:", errors.Is(err, context.Canceled))fmt.Fprintln(w, "cause:", context.Cause(ctx))context.Canceled: truecause: context canceled: app.shutdownThe run’s error is unchanged, still the context’s. Its invoke_agent span records weft.cancel.cause = app.shutdown beside weft.run.stopped_by = canceled, so Studio shows who canceled it. The loop records any cause with a Kind() string method, so a layer may bring its own type; a deadline reads deadline, and a cancel with no cause records none.
CancelCause is a string type, a short, low-cardinality dotted name. Kind() returns it, Error() returns context canceled: <name>, and Is reports it as context.Canceled. weft’s own layers pass theirs: weft/thread cancels a turn with thread.interrupted or thread.closed, and weft/runtime with studio.cancel or app.shutdown. The core example ExampleCancelCause is this snippet.
Cancellation wins everywhere, at the approval boundary too: a run canceled while calls are parked fails with the cancellation error, and the parked calls stay resumable on RunError.Result.Pending.
Complete example
Section titled “Complete example”concepts/budgets.go runs each way a run stops:
package main
import ( "context" "encoding/json" "errors" "fmt" "io"
"github.com/weftgo/weft" "github.com/weftgo/weft/wefttest")
// SubmitInput is the submit tool's input.type SubmitInput struct { Answer string `json:"answer" jsonschema:"the final answer"`}
// CheckInput is the check_order tool's input.type CheckInput struct { OrderID string `json:"order_id"`}
// checkOrder is a tool the scripted models below call again and again.func checkOrder() *weft.ToolDef { return weft.Tool("check_order", "Check an order's status.", func(ctx context.Context, in CheckInput) (string, error) { return "still processing", nil })}
// stopOnSubmit ends the run on its intended end: the submit call.func stopOnSubmit(ctx context.Context, w io.Writer, model weft.Model) error { submit := weft.Tool("submit", "Submit the final answer.", func(ctx context.Context, in SubmitInput) (string, error) { return "recorded", nil }) agt := weft.New(model, submit, weft.StopWhen(weft.HasToolCall("submit"))) for ev, err := range agt.Stream(ctx, weft.Prompt("Answer, then submit.")).Events() { if err != nil { return err } if fin, ok := ev.(weft.RunFinish); ok { fmt.Fprintln(w, "stopped by:", fin.StoppedBy, "after", fin.Steps, "step(s)") } } return nil}
// exhaustSteps runs into the step budget.func exhaustSteps(ctx context.Context, w io.Writer, model weft.Model) error { agt := weft.New(model, checkOrder(), weft.MaxSteps(3)) _, err := agt.Generate(ctx, weft.Prompt("Tell me when order 1234 ships.")) var re *weft.RunError if errors.As(err, &re) && errors.Is(err, weft.ErrMaxSteps) { fmt.Fprintln(w, err) fmt.Fprintln(w, "kept:", re.Result.NumSteps(), "steps,", len(re.Result.Messages), "messages") } return nil}
// overBudget runs a lead agent whose subagent pushes the run past its// token budget.func overBudget(ctx context.Context, w io.Writer, leadModel, researchModel weft.Model) error { researcher := weft.New(researchModel, weft.Name("researcher")) lead := weft.New(leadModel, weft.Subagent("research", "Research a topic in depth.", researcher), weft.UsageLimit(weft.Usage{OutputTokens: 8}), // the run's own calls plus every subagent's ) _, err := lead.Generate(ctx, weft.Prompt("Why are shipments late?")) var re *weft.RunError if errors.As(err, &re) && errors.Is(err, weft.ErrUsageLimit) { fmt.Fprintln(w, err) fmt.Fprintln(w, "own step:", re.Result.Steps[0].Usage.OutputTokens, "output tokens; with the subagent:", re.Result.Usage.OutputTokens) } return nil}
// repeating runs a model that asks for the same call every step.func repeating(ctx context.Context, w io.Writer, model weft.Model) error { agt := weft.New(model, checkOrder(), weft.DetectLoops(3)) _, err := agt.Generate(ctx, weft.Prompt("Tell me when order 1234 ships.")) fmt.Fprintln(w, err) return nil}
// truncated runs a step whose tool call was cut off by the output-token// limit.func truncated(ctx context.Context, w io.Writer) error { cut := wefttest.Raw( // the response hit max_tokens after one tool call weft.ModelToolCall{ID: "call_1", Name: "check_order", Args: json.RawMessage(`{"order_id":"1234"}`)}, weft.ModelFinish{Reason: weft.StopMaxTokens}, ) agt := weft.New(wefttest.Script(cut, wefttest.Say("Order 1234 is still processing.")), checkOrder()) res, err := agt.Generate(ctx, weft.Prompt("Is order 1234 ready?")) if err != nil { return err } fmt.Fprintln(w, res.Steps[0].Results[0].Content) fmt.Fprintln(w, "steps:", res.NumSteps(), "final stop reason:", res.StopReason) return nil}
// cancelled runs an agent under a context cancelled with a cause. opts// are added to the agent (the test passes a recording TracerProvider).func cancelled(ctx context.Context, w io.Writer, opts ...weft.Option) error { agt := weft.New(wefttest.Script(wefttest.Say("never sent")), opts...) ctx, cancel := context.WithCancelCause(ctx) cancel(weft.CancelCause("app.shutdown")) // e.g. on SIGTERM
_, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) fmt.Fprintln(w, "context.Canceled:", errors.Is(err, context.Canceled)) fmt.Fprintln(w, "cause:", context.Cause(ctx)) return nil}
// checking scripts n steps that each call check_order; distinct makes the// arguments differ from step to step.func checking(n int, distinct bool) *wefttest.Model { turns := make([]wefttest.Turn, 0, n+1) for i := range n { id := "1234" if distinct { id = fmt.Sprintf("1234-%d", i) } turns = append(turns, wefttest.ToolCalls(wefttest.Call{Name: "check_order", Args: `{"order_id":"` + id + `"}`})) } turns = append(turns, wefttest.Say("Order 1234 shipped.")) return wefttest.Script(turns...)}
// demoBudgets runs each way a run stops.func demoBudgets(ctx context.Context, w io.Writer) error { submit := wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "submit", Args: `{"answer":"Order 1234 shipped."}`}), wefttest.Say("never reached: StopWhen ended the run"), ) if err := stopOnSubmit(ctx, w, submit); err != nil { return err } if err := exhaustSteps(ctx, w, checking(3, true)); err != nil { return err } lead := wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "research", Args: `{"prompt":"shipping delays this week"}`}), wefttest.Say("never reached: the budget stopped the run"), ) research := wefttest.Script(wefttest.Say("Port congestion.")) if err := overBudget(ctx, w, lead, research); err != nil { return err } if err := repeating(ctx, w, checking(3, false)); err != nil { return err } if err := truncated(ctx, w); err != nil { return err } return cancelled(ctx, w)}Run it from docs-site/examples:
go run ./concepts budgetsgo test ./conceptsstopped by: has_tool_call:submit after 1 step(s)weft: run failed at step 3: weft: run exceeded the maximum number of stepskept: 3 steps, 7 messagesweft: run failed at step 0: weft: run exceeded its usage limit (input 20/0, output 10/8)own step: 5 output tokens; with the subagent: 10weft: run failed at step 2: weft: the model repeated the same tool calls too many times: 3 identical steps in a rowtool call check_order was not executed: the response hit the output token limitsteps: 2 final stop reason: stopcontext.Canceled: truecause: context canceled: app.shutdownBest practices & gotchas
Section titled “Best practices & gotchas”- Give every agent an intended end. A final-answer tool with
StopWhen(HasToolCall(...))ends on purpose; relying onMaxStepsturns the end into an error. (Source: deep dive §4,weft/core/agent.go:100-108) - Check the final tool’s result, or use
weft.Output[T].HasToolCall("submit")fires on asubmitcall with bad arguments:erris nil, the run took one step, and the last message isINVALID_INPUT: tool "submit": field …. When the final answer must be valid, useweft.Output[T], whoseoutput_submittedcondition waits for a submission without an error and lets the model repair a bad one first. Otherwise check the last result’sIsErroryourself. Valid means it decodes: a field the submission leaves out arrives as its zero value, so check required fields afterGenerateAs(structured output). (Source:weft/core/agent.go:577-588,weft/core/output.go:101-112) - Do not read a final-answer tool’s answer with
res.Text(). The run ends on the tool message, sores.Text()is the text beside the call, usually"". Read the last step’sToolCallsorResults, or useweft.Output[T]withweft.GenerateAs. (Source:weft/core/run.go:714-721,weft/core/agent.go:577-588) - Expect a budget to overshoot by one step, and a step to hold whole child runs. Limits are checked after a step, so the run that breaches
UsageLimithas already spent the step that breached it. A step that delegates includes each child’s whole run, so the overshoot can be several child runs. Bound each child with its ownUsageLimitandMaxSteps. (Source: AGENTS.md rule 13,weft/core/agent.go:114-125;weft/core/loop.go:849, 1102-1116) - Set both
UsageLimitfields to bound the total.Total()is not a limit of its own. (Source:weft/core/agent.go:122-124) - Consider
DetectLoopswhere a model may repeat itself. It is off by default, so a model stuck on the same calls spends steps untilMaxSteps. (Source:weft/core/agent.go:180-187) - Check
res.StopReasonon success.StopMaxTokensthere means the answer was cut off, and the run still returned nil. (Source: AGENTS.md rule 8) - Cancel with a
CancelCausein your own shutdown paths. A plaincancel()leaves the record without a reason. (Source:weft/core/observe.go:845-859)
See also
Section titled “See also”- Guard against runaway agents
- Get structured output from a run
- Tool errors are data, run errors are yours
- Change an agent’s configuration for one run
- Require human approval for a tool
Symbols used: weft.StopWhen · weft.StopCondition · weft.StopFunc · weft.HasToolCall · weft.StepCountIs · weft.MaxSteps · weft.UsageLimit · weft.MaxModelRetries · weft.DetectLoops · weft.ErrMaxSteps · weft.ErrUsageLimit · weft.ErrModelRetriesExceeded · weft.ErrLoopDetected · weft.StopReason · weft.CancelCause · weft.RunFinish · weft.Subagent · weft.RunError · wefttest.Raw