---
title: Tool errors are data, run errors are yours
description: A failing tool call becomes an error result the model reads and the run continues; a model failure, cancellation or budget breach returns a *weft.RunError to the caller.
url: https://weftgo.dev/docs/concepts/errors/
type: concept
sources:
  - weft/AGENTS.md:36-41 (bad arguments, ToolError, ModelRetry), rule 1
  - weft/docs/adr/0002-error-model.md
  - weft/docs/agent-loop-deep-dive.md:651-820 (tool failure)
  - weft/README.md:144-146
  - weft/core/errors.go:8-16 (the rule), 41-50 (ErrNoSuchTool, ErrInvalidToolInput), 118-125 (ErrContextOverflow), 135-214 (ToolError, Errorf, RunError, CodeRetry, ModelRetry)
  - weft/core/tool.go:266-298 (CodeInvalidInput, CodeNoSuchTool, CodeDenied; invalidInput, noSuchTool), 300-343 (describeDecodeError), 524-532 (StrictInput)
  - 'weft/core/tool.go:315-316 (the top-level form: expected <type> at the top level, got <kind>), 200-204 (empty or null arguments decode as {})'
  - weft/core/loop.go:1683-1685 (deniedResult), 1818-1960 (callTool — every failure a result), 1974-2001 (timeout and panic text), 2206-2222 (truncation marker), 1102-1108 (MaxModelRetries guard)
  - weft/core/agent.go:189-196 (MaxModelRetries)
  - weft/CHANGELOG.md:5101, 6297, 6427, 6530, 6549, 6629, 6652
  - weft/example_test.go ExampleToolError, ExampleCodeDenied, ExampleCodeNoSuchTool
  - docs-site/examples/concepts/errors.go, concepts_test.go TestToolFailuresAreResults, TestModelRetriesDefault
---

# 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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) carrying the partial transcript.

A handler gives the model a code to branch on with a [`*weft.ToolError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolError), from `concepts/errors.go`:

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

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

Every tool call ends in a [`weft.ToolResultPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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 |

![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 drawer](https://weftgo.dev/docs/_astro/studio-run-flaky.light.esXYYcMg.webp)

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

## 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`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ToolError.Unwrap). Never shown to the model. |

[`ToolError.Error`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ToolError.Error) returns that model-visible text. [`weft.Errorf(code, format, args...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Errorf) 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](https://weftgo.dev/docs/guides/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:

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

```text
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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrNoSuchTool) and bad arguments wrap [`weft.ErrInvalidToolInput`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-ToolError) shows a coded error and an invalid-input result side by side.

## 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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CodeInvalidInput) | `INVALID_INPUT` | Arguments that do not decode into the tool's input struct. |
| [`weft.CodeNoSuchTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CodeNoSuchTool) | `NO_SUCH_TOOL` | A call naming a tool the agent does not have. |
| [`weft.CodeDenied`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CodeRetry) | `RETRY` | `weft.ModelRetry`: an instruction to try again, not a failure report. |

The package examples [`ExampleCodeDenied`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-CodeDenied) and [`ExampleCodeNoSuchTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-CodeNoSuchTool) print the exact strings.

## 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: …`, 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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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

[`weft.ModelRetry(hint)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRetry) 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.

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

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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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?](https://weftgo.dev/docs/concepts/budgets-and-stopping/#model-retries) has the budget side.

## Run errors

Every run failure is a [`*weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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. |

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

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

## Context overflow

[`weft.ErrContextOverflow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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](https://weftgo.dev/docs/sessions/compaction/)).

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

## Complete example

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

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

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

Run it from `docs-site/examples`:

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

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

## Best practices & gotchas

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

## See also

- [Add behaviour with middleware (the two seams)](https://weftgo.dev/docs/guides/middleware/)
- [Retry and fall back when a provider fails](https://weftgo.dev/docs/guides/retries-and-fallback/)
- [How does a run stop?](https://weftgo.dev/docs/concepts/budgets-and-stopping/)
- [Survive flaky infrastructure](https://weftgo.dev/docs/examples/flaky-infrastructure/)

Symbols used: [`weft.ToolError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolError) · [`weft.Errorf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Errorf) · [`weft.ModelRetry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRetry) · [`weft.MaxModelRetries`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxModelRetries) · [`weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) · [`weft.ToolResultPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolResultPart) · [`weft.CodeInvalidInput`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CodeInvalidInput) · [`weft.CodeNoSuchTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CodeNoSuchTool) · [`weft.CodeDenied`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CodeDenied) · [`weft.CodeRetry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CodeRetry) · [`weft.ErrNoSuchTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrNoSuchTool) · [`weft.ErrInvalidToolInput`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrInvalidToolInput) · [`weft.ErrModelRetriesExceeded`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrModelRetriesExceeded) · [`weft.ErrContextOverflow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrContextOverflow) · [`weft.StrictInput`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StrictInput) · [`weft.Timeout`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Timeout) · [`wefttest.Fail`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Fail)
