Tool errors are data, run errors are yours
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:
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 })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.
How it works
Section titled “How it works”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.
| Failure | Becomes | The run |
|---|---|---|
| Handler returns an error, or panics | An error result | continues |
| Unknown tool, undecodable arguments | An error result with a code | continues |
Tool Timeout expires | An error result | continues |
A step hit max_tokens with tool calls | An error result per call | continues |
| Model stream fails or breaks its contract | *RunError | fails |
ctx canceled or past its deadline | *RunError | fails |
MaxSteps, UsageLimit, MaxModelRetries, DetectLoops breached | *RunError | fails |
A ToolSource snapshot with a nil tool or a duplicate name | *RunError | fails |


Tool errors
Section titled “Tool errors”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:
| Field | Role |
|---|---|
Code | A stable code the model can branch on, SCREAMING_SNAKE by convention (ORDER_NOT_FOUND). Not validated. |
Message | What the model reads after the code. With no message the result is the code alone. |
Err | The 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:
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)}error=true ORDER_NOT_FOUND: order 42 does not existerror=false order 1234: shippederror=true INVALID_INPUT: tool "lookup_order": field "order_id": expected string, got numbererror=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.
Result codes
Section titled “Result codes”The codes the loop writes are exported constants, so policy middleware produces the same strings without copying them:
| Constant | Text | Written for |
|---|---|---|
weft.CodeInvalidInput | INVALID_INPUT | Arguments that do not decode into the tool’s input struct. |
weft.CodeNoSuchTool | NO_SUCH_TOOL | A call naming a tool the agent does not have. |
weft.CodeDenied | DENIED | A 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.CodeRetry | RETRY | weft.ModelRetry: an instruction to try again, not a failure report. |
The package examples ExampleCodeDenied and ExampleCodeNoSuchTool print the exact strings.
Invalid arguments
Section titled “Invalid arguments”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: …, orinvalid JSON: unexpected end of inputfor 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>isarray,string,numberorbool. So[1]readsINVALID_INPUT: tool "lookup_order": expected object at the top level, got array. Empty ornullarguments 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.
Ask the model to retry
Section titled “Ask the model to retry”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.
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 })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.
Run errors
Section titled “Run errors”Every run failure is a *weft.RunError, and Generate returns a nil result beside it:
| Field | What it holds |
|---|---|
Step | The 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. |
Err | The cause. RunError unwraps to it, so errors.Is(err, weft.ErrMaxSteps) works on the returned error. |
Result | The RunResult up to the failure: transcript, steps, usage, and any calls still pending. Partial work is never lost. |
_, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))var re *weft.RunErrorif 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)")}weft: run failed at step 1: model stream: provider unavailablethe provider's error: truekept: 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.
Context overflow
Section titled “Context overflow”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).
What it does not do
Section titled “What it does not do”- 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.Errand 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.
Complete example
Section titled “Complete example”concepts/errors.go runs the four tool outcomes, a corrected and an uncorrected retry, and a run whose model fails:
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)}Run it from docs-site/examples:
go run ./concepts errorsgo test ./conceptserror=true ORDER_NOT_FOUND: order 42 does not existerror=false order 1234: shippederror=true INVALID_INPUT: tool "lookup_order": field "order_id": expected string, got numbererror=true NO_SUCH_TOOL: no tool named "refund_order"RETRY: date must be ISO-8601, like 2026-10-18in transitErrModelRetriesExceeded: trueweft: run failed at step 1: model stream: provider unavailablethe provider's error: truekept: 3 messages, 1 step(s)Best practices & gotchas
Section titled “Best practices & gotchas”- Give the model a code for every failure it should handle. A
ToolErrorcode 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
Messageand out of%wcauses inweft.Errorf. Both become model-visible text; onlyErrset directly stays hidden. (Source:weft/core/errors.go:163-180) - Use
ModelRetryfor fixable arguments, a coded error for facts.RETRYcounts towardMaxModelRetries;ORDER_NOT_FOUNDdoes not. (Source:weft/core/errors.go:198-214) - Read
RunError.Result, not the nilres. The partial transcript is only on the error. (Source:weft/core/loop.go:264-274) - Use the exported codes in policy middleware.
weft.CodeDeniedkeeps a refusal identical to the approval boundary’s. (Source: CHANGELOG 0.2.0,weft/core/tool.go:266-283)
See also
Section titled “See also”- Add behaviour with middleware (the two seams)
- Retry and fall back when a provider fails
- How does a run stop?
- Survive flaky infrastructure
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