Skip to content

Tool errors are data, run errors are yours

View as Markdown

weft has one error rule: a tool error is data the model sees, a run error is a Go error the caller sees. When a tool call fails (the handler returns an error or panics, the tool does not exist, the arguments do not decode, the call times out) the loop records an error result, the model reads it on its next step, and the call’s siblings keep running. When the run itself cannot go on (the model call fails, ctx is canceled, a budget runs out) Generate returns a *weft.RunError carrying the partial transcript.

A handler gives the model a code to branch on with a *weft.ToolError, from concepts/errors.go:

concepts/errors.go
return weft.Tool("lookup_order", "Look up an order by ID.",
func(ctx context.Context, in OrderLookup) (string, error) {
if in.OrderID != "1234" {
return "", &weft.ToolError{
Code: "ORDER_NOT_FOUND",
Message: "order " + in.OrderID + " does not exist",
Err: errNoRows, // for middleware and logs; the model never sees it
}
}
return "order 1234: shipped", nil
})

concepts/errors.go on GitHub

For order 42 the model reads ORDER_NOT_FOUND: order 42 does not exist. The database error in Err stays out of the model’s sight.

Every tool call ends in a weft.ToolResultPart. A failure sets IsError: true and puts the failure’s text in Content, so the model can correct course: retry with other arguments, try another tool, or tell the user. The run fails only for conditions the model cannot fix by itself, and then the caller decides.

FailureBecomesThe run
Handler returns an error, or panicsAn error resultcontinues
Unknown tool, undecodable argumentsAn error result with a codecontinues
Tool Timeout expiresAn error resultcontinues
A step hit max_tokens with tool callsAn error result per callcontinues
Model stream fails or breaks its contract*RunErrorfails
ctx canceled or past its deadline*RunErrorfails
MaxSteps, UsageLimit, MaxModelRetries, DetectLoops breached*RunErrorfails
A ToolSource snapshot with a nil tool or a duplicate name*RunErrorfails
The ops-probe run of rw.flaky-infra on the waterfall: inventory_api marked retry 1/3, tax_service RATE_LIMITED, shipping_quote timed out at 300 ms and legacy_billing panicked, with the selected call's details in the drawerThe ops-probe run of rw.flaky-infra on the waterfall: inventory_api marked retry 1/3, tax_service RATE_LIMITED, shipping_quote timed out at 300 ms and legacy_billing panicked, with the selected call's details in the drawer
Studio's run page for a run whose tools fail four ways — a retry, a coded error, a timeout and a panic — each recorded as that call's result.

A handler that returns a plain error produces a result whose text is err.Error(). A handler that returns a *weft.ToolError produces CODE: Message:

FieldRole
CodeA stable code the model can branch on, SCREAMING_SNAKE by convention (ORDER_NOT_FOUND). Not validated.
MessageWhat the model reads after the code. With no message the result is the code alone.
ErrThe internal cause, for middleware and logs through errors.Is, errors.As and Unwrap. Never shown to the model.

ToolError.Error returns that model-visible text. weft.Errorf(code, format, args...) builds one with a formatted message: a %w verb sets Err as fmt.Errorf would, and several %w verbs keep every cause reachable. The wrapped error’s text is part of the formatted message, so wrap only what the model may read. mw.MapErrors codes plain errors centrally instead of in each handler (Add behaviour with middleware).

The loop renders its own failures in the same shape. One step of concepts/errors.go fails three ways next to a call that succeeds:

concepts/errors.go
model := wefttest.Script(
wefttest.ToolCalls(
wefttest.Call{Name: "lookup_order", Args: `{"order_id":"42"}`}, // the handler's ToolError
wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`}, // succeeds
wefttest.Call{Name: "lookup_order", Args: `{"order_id":1234}`}, // a number, not a string
wefttest.Call{Name: "refund_order", Args: `{}`}, // no such tool
),
wefttest.Say("Order 1234 has shipped; order 42 does not exist."),
)
res, err := weft.New(model, lookup).Generate(ctx, weft.Prompt("Where are orders 42 and 1234?"))
if err != nil {
return err // never reached: tool failures are results, the run succeeds
}
for _, r := range res.Steps[0].Results {
fmt.Fprintf(w, "error=%-5v %s\n", r.IsError, r.Content)
}

concepts/errors.go on GitHub

error=true ORDER_NOT_FOUND: order 42 does not exist
error=false order 1234: shipped
error=true INVALID_INPUT: tool "lookup_order": field "order_id": expected string, got number
error=true NO_SUCH_TOOL: no tool named "refund_order"

Under the code, the loop’s failures still match their sentinels: an unknown tool wraps weft.ErrNoSuchTool and bad arguments wrap weft.ErrInvalidToolInput, so middleware branches with errors.Is. agt.CallTool returns the same errors to its caller instead of rendering them.

Containment produces two more texts, neither of them coded: a panic becomes tool "X" panicked: <value> and an expired weft.Timeout becomes tool "X" timed out after 10s, with the configured duration. A result longer than MaxResultBytes (64 KiB by default) is cut on a rune boundary and ends with …[truncated N bytes], where N is the number of bytes the model did not receive.

The package example ExampleToolError shows a coded error and an invalid-input result side by side.

The codes the loop writes are exported constants, so policy middleware produces the same strings without copying them:

ConstantTextWritten for
weft.CodeInvalidInputINVALID_INPUTArguments that do not decode into the tool’s input struct.
weft.CodeNoSuchToolNO_SUCH_TOOLA call naming a tool the agent does not have.
weft.CodeDeniedDENIEDA call refused at the approval boundary (DENIED: <reason>, or DENIED: no decision) or by a policy middleware such as mw.Allow. A refused call carries the same DENIED code whoever refused it; the message after it differs.
weft.CodeRetryRETRYweft.ModelRetry: an instruction to try again, not a failure report.

The package examples ExampleCodeDenied and ExampleCodeNoSuchTool print the exact strings.

Bad arguments come back in the schema’s own words: INVALID_INPUT: tool "lookup_order": field "order_id": expected string, got number. The expected type is read from the schema the tool advertised, walked along the field’s path, so the message never names a Go type the model was not shown: a []byte field says expected string, and an integer tagged ,string says expected string, got number.

Other decode failures name their rule:

  • Malformed JSON: invalid JSON at offset N: …, or invalid JSON: unexpected end of input for cut-off arguments.
  • Anything after the first JSON value: trailing data after the JSON arguments.
  • Valid JSON that is not an object, such as [1] or "x": expected object at the top level, got <kind>, where <kind> is array, string, number or bool. So [1] reads INVALID_INPUT: tool "lookup_order": expected object at the top level, got array. Empty or null arguments are not refused: they decode as {}.
  • An undeclared field under weft.StrictInput: unknown field "x": not in the schema.

Undeclared fields are ignored by default, as encoding/json ignores them, because models add stray keys and a rejection costs a round trip. Turn on StrictInput where an ignored field would be a silent misreading of the call.

weft.ModelRetry(hint) is a tool error that asks the model to call again with the hint applied. It renders RETRY: <hint>. Return it when the arguments decode but are wrong in a way the model can fix: an ambiguous date, an id missing its prefix.

concepts/errors.go
return weft.Tool("track_shipment", "Track a shipment by its ship date.",
func(ctx context.Context, in TrackInput) (string, error) {
if _, err := time.Parse(time.DateOnly, in.Date); err != nil {
return "", weft.ModelRetry("date must be ISO-8601, like 2026-10-18")
}
return "in transit", nil
})

concepts/errors.go on GitHub

Given 18/10/2026, the model reads RETRY: date must be ISO-8601, like 2026-10-18; the corrected call returns in transit.

The loop counts RETRY results per tool name since that tool’s last successful result: a success resets the count, and other error results neither count nor reset it. When a tool’s count passes weft.MaxModelRetries (3 by default), the run fails with ErrModelRetriesExceeded at the next continuation point: with the default, the fourth RETRY since the tool last succeeded. Two parallel calls to the same tool that both retry count as two, and a RETRY from middleware counts like a handler’s. How does a run stop? has the budget side.

Every run failure is a *weft.RunError, and Generate returns a nil result beside it:

FieldWhat it holds
StepThe step at which the run failed. For ErrMaxSteps it is the step that would have come next: n for MaxSteps(n), one past the last step’s index.
ErrThe cause. RunError unwraps to it, so errors.Is(err, weft.ErrMaxSteps) works on the returned error.
ResultThe RunResult up to the failure: transcript, steps, usage, and any calls still pending. Partial work is never lost.
concepts/errors.go
_, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))
var re *weft.RunError
if errors.As(err, &re) {
fmt.Fprintln(w, err)
fmt.Fprintln(w, "the provider's error:", errors.Is(err, errProviderDown))
fmt.Fprintln(w, "kept:", len(re.Result.Messages), "messages,", re.Result.NumSteps(), "step(s)")
}

concepts/errors.go on GitHub

weft: run failed at step 1: model stream: provider unavailable
the provider's error: true
kept: 3 messages, 1 step(s)

The first step’s tool call and its result survive on re.Result. Branch on the cause with errors.Is against the sentinels (ErrMaxSteps, ErrUsageLimit, ErrModelContract, context.Canceled, …), never by matching the text.

weft.ErrContextOverflow is the run error for a request that exceeds the model’s context window. The OpenAI, Anthropic and Google adapters all wrap their provider’s overflow error in it, keeping both links: errors.Is finds the sentinel and errors.As still reaches the vendor SDK’s error. The same bytes can never succeed, so mw.Retry never retries it; weft/thread answers it by compacting the session and re-running once (Keep long sessions inside the context window).

  • A tool error never fails the run by itself. Only the budgets above turn repeated tool failures into a run failure; otherwise the model decides what a failure means.
  • The cause never reaches the model. ToolError.Err and a plain error’s wrapped chain are for your logs; only the rendered text is sent.
  • A run error is not retried. Retrying a failed model call is mw.Retry’s job, inside the model chain, before the step fails.

concepts/errors.go runs the four tool outcomes, a corrected and an uncorrected retry, and a run whose model fails:

concepts/errors.go
package main
import (
"context"
"errors"
"fmt"
"io"
"time"
"github.com/weftgo/weft"
"github.com/weftgo/weft/wefttest"
)
// errNoRows stands in for a database's not-found error.
var errNoRows = errors.New("pg: no rows in result set")
// errProviderDown stands in for a provider outage.
var errProviderDown = errors.New("provider unavailable")
// TrackInput is track_shipment's input.
type TrackInput struct {
Date string `json:"date" jsonschema:"the ship date, YYYY-MM-DD"`
}
// failingLookup is lookup_order with a coded failure for unknown orders.
func failingLookup() *weft.ToolDef {
return weft.Tool("lookup_order", "Look up an order by ID.",
func(ctx context.Context, in OrderLookup) (string, error) {
if in.OrderID != "1234" {
return "", &weft.ToolError{
Code: "ORDER_NOT_FOUND",
Message: "order " + in.OrderID + " does not exist",
Err: errNoRows, // for middleware and logs; the model never sees it
}
}
return "order 1234: shipped", nil
})
}
// toolFailures runs one step with three failing calls beside one success.
func toolFailures(ctx context.Context, w io.Writer) error {
lookup := failingLookup()
model := wefttest.Script(
wefttest.ToolCalls(
wefttest.Call{Name: "lookup_order", Args: `{"order_id":"42"}`}, // the handler's ToolError
wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`}, // succeeds
wefttest.Call{Name: "lookup_order", Args: `{"order_id":1234}`}, // a number, not a string
wefttest.Call{Name: "refund_order", Args: `{}`}, // no such tool
),
wefttest.Say("Order 1234 has shipped; order 42 does not exist."),
)
res, err := weft.New(model, lookup).Generate(ctx, weft.Prompt("Where are orders 42 and 1234?"))
if err != nil {
return err // never reached: tool failures are results, the run succeeds
}
for _, r := range res.Steps[0].Results {
fmt.Fprintf(w, "error=%-5v %s\n", r.IsError, r.Content)
}
return nil
}
// trackShipment is a tool that asks the model to fix its arguments.
func trackShipment() *weft.ToolDef {
return weft.Tool("track_shipment", "Track a shipment by its ship date.",
func(ctx context.Context, in TrackInput) (string, error) {
if _, err := time.Parse(time.DateOnly, in.Date); err != nil {
return "", weft.ModelRetry("date must be ISO-8601, like 2026-10-18")
}
return "in transit", nil
})
}
// retries shows a corrected retry, then a model that never corrects itself.
func retries(ctx context.Context, w io.Writer) error {
fixes := wefttest.Script(
wefttest.ToolCalls(wefttest.Call{Name: "track_shipment", Args: `{"date":"18/10/2026"}`}),
wefttest.ToolCalls(wefttest.Call{Name: "track_shipment", Args: `{"date":"2026-10-18"}`}),
wefttest.Say("Your shipment is in transit."),
)
res, err := weft.New(fixes, trackShipment()).Generate(ctx, weft.Prompt("Where is my parcel?"))
if err != nil {
return err
}
fmt.Fprintln(w, res.Steps[0].Results[0].Content)
fmt.Fprintln(w, res.Steps[1].Results[0].Content)
stuck := wefttest.Script(
wefttest.ToolCalls(wefttest.Call{Name: "track_shipment", Args: `{"date":"yesterday"}`}),
wefttest.ToolCalls(wefttest.Call{Name: "track_shipment", Args: `{"date":"last week"}`}),
wefttest.ToolCalls(wefttest.Call{Name: "track_shipment", Args: `{"date":"soon"}`}),
wefttest.Say("never reached"),
)
_, err = weft.New(stuck, trackShipment(), weft.MaxModelRetries(2)).Generate(ctx, weft.Prompt("Where is my parcel?"))
fmt.Fprintln(w, "ErrModelRetriesExceeded:", errors.Is(err, weft.ErrModelRetriesExceeded))
return nil
}
// runFailure shows a run error and the partial transcript it carries.
func runFailure(ctx context.Context, w io.Writer) error {
model := wefttest.Script(
wefttest.ToolCalls(wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`}),
wefttest.Fail(errProviderDown), // the second model call fails
)
agt := weft.New(model, failingLookup())
_, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))
var re *weft.RunError
if errors.As(err, &re) {
fmt.Fprintln(w, err)
fmt.Fprintln(w, "the provider's error:", errors.Is(err, errProviderDown))
fmt.Fprintln(w, "kept:", len(re.Result.Messages), "messages,", re.Result.NumSteps(), "step(s)")
}
return nil
}
// demoErrors runs the tool failures, the retries and a failed run.
func demoErrors(ctx context.Context, w io.Writer) error {
if err := toolFailures(ctx, w); err != nil {
return err
}
if err := retries(ctx, w); err != nil {
return err
}
return runFailure(ctx, w)
}

View concepts/errors.go on GitHub

Run it from docs-site/examples:

Terminal window
go run ./concepts errors
go test ./concepts
error=true ORDER_NOT_FOUND: order 42 does not exist
error=false order 1234: shipped
error=true INVALID_INPUT: tool "lookup_order": field "order_id": expected string, got number
error=true NO_SUCH_TOOL: no tool named "refund_order"
RETRY: date must be ISO-8601, like 2026-10-18
in transit
ErrModelRetriesExceeded: true
weft: run failed at step 1: model stream: provider unavailable
the provider's error: true
kept: 3 messages, 1 step(s)
  • Give the model a code for every failure it should handle. A ToolError code is a stable string to branch on; a plain error’s text may change with a library upgrade. (Source: weft/core/errors.go:135-148)
  • Keep secrets out of Message and out of %w causes in weft.Errorf. Both become model-visible text; only Err set directly stays hidden. (Source: weft/core/errors.go:163-180)
  • Use ModelRetry for fixable arguments, a coded error for facts. RETRY counts toward MaxModelRetries; ORDER_NOT_FOUND does not. (Source: weft/core/errors.go:198-214)
  • Read RunError.Result, not the nil res. The partial transcript is only on the error. (Source: weft/core/loop.go:264-274)
  • Use the exported codes in policy middleware. weft.CodeDenied keeps a refusal identical to the approval boundary’s. (Source: CHANGELOG 0.2.0, weft/core/tool.go:266-283)

Symbols used: weft.ToolError · weft.Errorf · weft.ModelRetry · weft.MaxModelRetries · weft.RunError · weft.ToolResultPart · weft.CodeInvalidInput · weft.CodeNoSuchTool · weft.CodeDenied · weft.CodeRetry · weft.ErrNoSuchTool · weft.ErrInvalidToolInput · weft.ErrModelRetriesExceeded · weft.ErrContextOverflow · weft.StrictInput · weft.Timeout · wefttest.Fail