---
title: Rewrite the request each step (PrepareStep)
description: Install weft.PrepareStep to trim messages, change the tools, the system prompt, tool choice or sampling for each model call, without touching the transcript.
url: https://weftgo.dev/docs/guides/prepare-step/
type: how-to
sources:
  - weft/core/agent.go:143-178 (PrepareStep and its godoc)
  - weft/core/loop.go:487-569 (the request built per step, the deep copies, the chain, validateSnapshot, validateToolChoice, validateParams, composeSystem)
  - weft/core/loop.go:1662-1675 (composeSystem)
  - weft/core/loop.go:183-207 (a panic in user code re-panics after the run span ends)
  - weft/core/run.go:784-804 (Stream runs the loop on its own goroutine), 849-858 (Generate on the caller's)
  - weft/core/agent.go:826-854 (validateSnapshot, validateParams)
  - weft/core/model.go:150-200 (ModelRequest)
  - 'weft/docs/adr/0006-seams.md:150-194 (amendment: PrepareStep is the one loop knob)'
  - weft/docs/adr/0012-manifest-format.md:117-118 (PrepareStep is not described)
  - weft/docs/record-contract.md:635-639 (the request record's prepared)
  - weft/core/steer.go:33-36 (steered messages are in the transcript before PrepareStep runs)
  - weft/AGENTS.md:75 (block 2)
  - weft/CHANGELOG.md:6277-6286 (0.2.0)
  - weft/example_test.go:689 (ExamplePrepareStep), 800 (ExampleToolChoice), 828 (ExampleParams)
  - weft/core/contract_test.go:2454 (TestPrepareStepCopiesDefendTheRun), 3859 (TestPrepareStepSubsetsToolsPerStep), 3899 (TestPrepareStepTrimsRequestNotTranscript), 3923 (TestPrepareStepErrorFailsRun), 3941 (TestPrepareStepComposesSnippetsAfter), 3969 (TestPrepareStepChainsInOrder), 3996 (TestPrepareStepRunsBeforeModelSeam), 4019 (TestPrepareStepDuplicateToolFailsRun), 4042 (TestPrepareStepOverToolSource)
  - docs-site/examples/preparestep/main.go, main_test.go TestPrepareStep, TestKeepLastSkipsToolResults, TestTrimLeavesTranscript
---

# Rewrite the request each step (PrepareStep)

[`weft.PrepareStep`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#PrepareStep) installs a function the loop calls before every model call, with the [`weft.ModelRequest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRequest) it built for that step. The request your function returns is what the step sends: trimmed messages, a subset of tools, a rewritten system prompt, a different tool choice or sampling. The transcript in the run's result is never changed.

A function that sends the model at most the last `n` messages, from `preparestep/main.go`:

```go title="preparestep/main.go"
// keepLast returns a PrepareStep function that sends the model at most the
// last n messages. The cut moves forward to a user message, so the window
// never opens on a tool result whose call was cut away.
func keepLast(n int) func(context.Context, int, weft.ModelRequest) (weft.ModelRequest, error) {
	return func(_ context.Context, _ int, req weft.ModelRequest) (weft.ModelRequest, error) {
		if len(req.Messages) <= n {
			return req, nil
		}
		window := req.Messages[len(req.Messages)-n:]
		for len(window) > 1 && window[0].Role != weft.RoleUser {
			window = window[1:]
		}
		req.Messages = window
		return req, nil
	}
}
```

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

Install it on the agent:

```go title="preparestep/main.go"
agt := weft.New(model,
	weft.Instructions("You are a support agent."),
	weft.PrepareStep(keepLast(3)),
)
```

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

With four messages of history and a new prompt, the model sees the last three; `res.Messages` still holds all six. The cut moves forward to a `user` message so the window never opens on a tool result whose call was cut away ([rule 2](https://github.com/weftgo/weft/blob/v0.20.2/AGENTS.md#the-rules-do-not-break-these-tests-pin-them): every tool call is paired with its result).

## How it works

The loop builds each step's request from the agent's instructions, the transcript so far, the step's tool snapshot, and the run's thinking, tool choice and sampling. Then it runs the `PrepareStep` chain:

1. The request your function receives is a copy. Message parts, tool-call argument bytes and tool definitions are deep-copied before the chain runs, so writing into them in place reaches neither the transcript nor the agent's registered tools (`TestPrepareStepCopiesDefendTheRun`).
2. Several `PrepareStep` options run in the order you passed them, each receiving the previous one's result. A nil function is ignored.
3. The tools the chain returns become the step's snapshot: what the step advertises and what it dispatches against. They are validated like a `ToolSource` snapshot, so a duplicate name fails the run with [`weft.ErrDuplicateTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrDuplicateTool) and a nil entry with [`weft.ErrNilTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrNilTool).
4. The tool choice and the sampling params are validated against that snapshot. A named choice for a tool the function removed fails the run; so does a negative `MaxTokens`.
5. [Prompt snippets](https://weftgo.dev/docs/guides/tool-policy/) are composed into the system prompt after the chain, from the tools it returned. Your function sees the raw instructions, never the composed text.
6. The request goes through the [`WrapModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapModel) chain to the model, so model middleware sees the prepared request.

`PrepareStep` is a loop knob, in the same category as `StopWhen`, not a third seam ([ADR 0006, amendment](https://github.com/weftgo/weft/blob/v0.20.2/docs/adr/0006-seams.md)). Model middleware can rewrite a request too, but it cannot make the loop dispatch against the tools it removed; `PrepareStep` runs before the snapshot is fixed, so the two always agree. The package example [`ExamplePrepareStep`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-PrepareStep) shows phased tool exposure.

## Offer a tool only from a later step

The `step` argument is the zero-based step index. Remove a tool from `req.Tools` on the steps where the model must not call it:

```go title="preparestep/main.go"
investigateFirst := func(_ context.Context, step int, req weft.ModelRequest) (weft.ModelRequest, error) {
	if step == 0 {
		req.Tools = slices.DeleteFunc(req.Tools, func(t *weft.ToolDef) bool { return t.Name == "refund" })
	}
	return req, nil
}
agt := weft.New(model, weft.Instructions("You are a support agent."),
	lookup, refund, weft.PrepareStep(investigateFirst))
```

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

The scripted model calls `refund` on step 0 anyway. That call fails as an unknown tool, `NO_SUCH_TOOL: no tool named "refund"`, because the step did not offer it; on step 1 the same call runs. The refund tool's snippet, `Refund only after a lookup.`, is absent from step 0's system prompt and present from step 1: removing a tool removes its snippet.

## Change the system prompt, tool choice or sampling per step

Every field of the request is yours to rewrite: [`System`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ModelRequest.System), [`Messages`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ModelRequest.Messages), [`Tools`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ModelRequest.Tools), [`ToolChoice`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ModelRequest.ToolChoice), [`Params`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ModelRequest.Params), [`Thinking`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ModelRequest.Thinking) and [`SequentialTools`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ModelRequest.SequentialTools). Two package examples use it this way: [`ExampleToolChoice`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-ToolChoice) forces a `classify` call on step 0 only, and [`ExampleParams`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Params) sets the temperature to 0 for the classifying step. The agent-wide and per-run forms of those knobs are in [Change an agent's configuration for one run](https://weftgo.dev/docs/guides/run-options/).

The request record of each step names what the chain changed (`prepared`: `system`, `messages`, `tools`, `tool_choice`, `params`, `thinking`, `sequential_tools`), names only, so a reader can see a rewrite even with content off ([record contract](https://weftgo.dev/docs/reference/record-contract/)).

## Fail the run from PrepareStep

Return an error to stop the run before the step's model call. The run fails with a [`*weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) that wraps your error, so `errors.Is` finds your sentinel:

```go title="preparestep/main.go"
var errNoTenant = errors.New("no tenant on the request")

func requireTenant(ctx context.Context, _ int, req weft.ModelRequest) (weft.ModelRequest, error) {
	if weft.MetadataFromContext(ctx)["tenant"] == "" {
		return req, errNoTenant // fails the run before the model is called
	}
	return req, nil
}
```

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

The function receives the run's context, so it can read the run's [metadata](https://weftgo.dev/docs/guides/metadata/) as this one does. A panic is different from an error: the loop closes the run's span and re-panics. Under `agt.Generate` the run is on your goroutine, so the panic reaches your caller. Under `agt.Stream` the run has its own goroutine, so the panic crashes the program and no caller can recover it.

## Complete example

`preparestep/main.go` runs the three cases against scripted models:

```go title="preparestep/main.go"
// Command preparestep runs the examples of the guide "Rewrite the request
// each step (PrepareStep)": go run ./preparestep. Every model is scripted
// with wefttest, so it runs offline; swap in a provider adapter for a real
// one.
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"os"
	"slices"

	"github.com/weftgo/weft"
	"github.com/weftgo/weft/wefttest"
)

// keepLast returns a PrepareStep function that sends the model at most the
// last n messages. The cut moves forward to a user message, so the window
// never opens on a tool result whose call was cut away.
func keepLast(n int) func(context.Context, int, weft.ModelRequest) (weft.ModelRequest, error) {
	return func(_ context.Context, _ int, req weft.ModelRequest) (weft.ModelRequest, error) {
		if len(req.Messages) <= n {
			return req, nil
		}
		window := req.Messages[len(req.Messages)-n:]
		for len(window) > 1 && window[0].Role != weft.RoleUser {
			window = window[1:]
		}
		req.Messages = window
		return req, nil
	}
}

// trim feeds a long history back and trims what each step sends.
func trim(ctx context.Context, w io.Writer) error {
	model := wefttest.Script(wefttest.Say("Order 9012 is out for delivery."))
	agt := weft.New(model,
		weft.Instructions("You are a support agent."),
		weft.PrepareStep(keepLast(3)),
	)
	history := []weft.Message{
		weft.User("Where is order 1234?"),
		weft.Assistant("Order 1234 shipped yesterday."),
		weft.User("And order 5678?"),
		weft.Assistant("Order 5678 is still pending."),
	}
	res, err := agt.Generate(ctx, weft.Messages(history...), weft.Prompt("And order 9012?"))
	if err != nil {
		return err
	}
	req := model.LastRequest()
	fmt.Fprintf(w, "the model saw %d of %d messages, starting with %q\n",
		len(req.Messages), len(history)+1, req.Messages[0].Text())
	fmt.Fprintf(w, "the transcript keeps all %d messages\n", len(res.Messages))
	return nil
}

// phased offers refund only after the first step, and shows that the
// returned tools are what the step advertises, dispatches and composes
// snippets from.
func phased(ctx context.Context, w io.Writer) error {
	lookup := weft.Tool("lookup", "Look up an order.", func(_ context.Context, _ struct{}) (string, error) {
		return "order 1234: broken item", nil
	})
	refund := weft.Tool("refund", "Refund an order.", func(_ context.Context, _ struct{}) (string, error) {
		return "refunded", nil
	}, weft.PromptSnippet("Refund only after a lookup."))
	model := wefttest.Script(
		wefttest.ToolCalls(wefttest.Call{Name: "refund"}), // not advertised in step 0
		wefttest.ToolCalls(wefttest.Call{Name: "refund"}), // advertised from step 1
		wefttest.Say("Refunded order 1234."),
	)
	investigateFirst := func(_ context.Context, step int, req weft.ModelRequest) (weft.ModelRequest, error) {
		if step == 0 {
			req.Tools = slices.DeleteFunc(req.Tools, func(t *weft.ToolDef) bool { return t.Name == "refund" })
		}
		return req, nil
	}
	agt := weft.New(model, weft.Instructions("You are a support agent."),
		lookup, refund, weft.PrepareStep(investigateFirst))
	res, err := agt.Generate(ctx, weft.Prompt("Refund order 1234."))
	if err != nil {
		return err
	}
	for i, req := range model.Requests() {
		var names []string
		for _, t := range req.Tools {
			names = append(names, t.Name)
		}
		fmt.Fprintf(w, "step %d: tools %v, system %q\n", i, names, req.System)
	}
	for _, s := range res.Steps[:2] {
		fmt.Fprintf(w, "step %d result: %s\n", s.Index, s.Results[0].Content)
	}
	return nil
}

var errNoTenant = errors.New("no tenant on the request")

func requireTenant(ctx context.Context, _ int, req weft.ModelRequest) (weft.ModelRequest, error) {
	if weft.MetadataFromContext(ctx)["tenant"] == "" {
		return req, errNoTenant // fails the run before the model is called
	}
	return req, nil
}

// failing shows that a PrepareStep error fails the run with the caller's
// sentinel reachable through errors.Is, before any model call.
func failing(ctx context.Context, w io.Writer) error {
	model := wefttest.Script(wefttest.Say("unused"))
	agt := weft.New(model, weft.PrepareStep(requireTenant))
	_, err := agt.Generate(ctx, weft.Prompt("hi"))
	var runErr *weft.RunError
	fmt.Fprintf(w, "errors.Is(err, errNoTenant): %t\n", errors.Is(err, errNoTenant))
	fmt.Fprintf(w, "a *RunError: %t, model calls: %d\n", errors.As(err, &runErr), len(model.Requests()))
	return nil
}

func run(ctx context.Context, w io.Writer) error {
	steps := []struct {
		title string
		fn    func(context.Context, io.Writer) error
	}{
		{"trim", trim},
		{"phased tools", phased},
		{"error", failing},
	}
	for _, s := range steps {
		fmt.Fprintf(w, "== %s\n", s.title)
		if err := s.fn(ctx, w); err != nil {
			return fmt.Errorf("%s: %w", s.title, err)
		}
	}
	return nil
}

func main() {
	if err := run(context.Background(), os.Stdout); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
```

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

[View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/preparestep) · run it from `docs-site/examples`:

```sh
go run ./preparestep
go test ./preparestep
```

```text
== trim
the model saw 3 of 5 messages, starting with "And order 5678?"
the transcript keeps all 6 messages
== phased tools
step 0: tools [lookup], system "You are a support agent."
step 1: tools [lookup refund], system "You are a support agent.\n\nRefund only after a lookup."
step 2: tools [lookup refund], system "You are a support agent.\n\nRefund only after a lookup."
step 0 result: NO_SUCH_TOOL: no tool named "refund"
step 1 result: refunded
== error
errors.Is(err, errNoTenant): true
a *RunError: true, model calls: 0
```

## Best practices & gotchas

- **Trim deliberately: a rewrite can break a prompt-cache prefix.** `PrepareStep` and `ToolSource` are the two knobs that can change the bytes a provider caches. (Source: `weft/core/agent.go:174-175`)
- **Rewrite the request, not the transcript.** What you send is not what the run keeps; the transcript, the record's messages and the next turn see every message. To add a user message mid-run, use [steering](https://weftgo.dev/docs/guides/steering/), whose messages join the transcript before the next step's chain runs. (Source: ADR 0019 "Rejected", `weft/core/steer.go:33-36`)
- **Keep the tool choice consistent with the tools you return.** A `ToolChoiceNamed` for a tool your function dropped fails the run at that step. (Source: `weft/core/loop.go:554-563`)
- **Do not expect the manifest to describe it.** `PrepareStep` is code, like middleware; `weft.json` does not mention it. (Source: ADR 0012, amendment 2026-09-19)
- **Order several functions on purpose.** They chain in option order, each seeing the previous one's output. (Source: `TestPrepareStepChainsInOrder`)

## See also

- [What happens in one step?](https://weftgo.dev/docs/concepts/the-loop/)
- [Change an agent's configuration for one run](https://weftgo.dev/docs/guides/run-options/)
- [Define tools at runtime: RawTool and ToolSource](https://weftgo.dev/docs/guides/dynamic-tools/)
- [Steer a running turn](https://weftgo.dev/docs/guides/steering/)
- [Add behaviour with middleware](https://weftgo.dev/docs/guides/middleware/)

Symbols used: [`weft.PrepareStep`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#PrepareStep) · [`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) · [`ModelRequest.SequentialTools`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ModelRequest.SequentialTools) · [`weft.ModelRequest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRequest) · [`weft.ErrDuplicateTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrDuplicateTool) · [`weft.ErrNilTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrNilTool) · [`weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) · [`weft.WrapModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapModel) · [`weft.PromptSnippet`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#PromptSnippet) · [`weft.MetadataFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MetadataFromContext) · [`weft.Instructions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Instructions) · [`weft.Messages`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Messages) · [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) · [`weft.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#New) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) · [`ExamplePrepareStep`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-PrepareStep)
