Rewrite the request each step (PrepareStep)
weft.PrepareStep installs a function the loop calls before every model call, with the weft.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:
// 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 }}Install it on the agent:
agt := weft.New(model, weft.Instructions("You are a support agent."), weft.PrepareStep(keepLast(3)),)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: every tool call is paired with its result).
How it works
Section titled “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:
- 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). - Several
PrepareStepoptions run in the order you passed them, each receiving the previous one’s result. A nil function is ignored. - The tools the chain returns become the step’s snapshot: what the step advertises and what it dispatches against. They are validated like a
ToolSourcesnapshot, so a duplicate name fails the run withweft.ErrDuplicateTooland a nil entry withweft.ErrNilTool. - 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. - Prompt snippets are composed into the system prompt after the chain, from the tools it returned. Your function sees the raw instructions, never the composed text.
- The request goes through the
WrapModelchain 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). 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 shows phased tool exposure.
Offer a tool only from a later step
Section titled “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:
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))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
Section titled “Change the system prompt, tool choice or sampling per step”Every field of the request is yours to rewrite: System, Messages, Tools, ToolChoice, Params, Thinking and SequentialTools. Two package examples use it this way: ExampleToolChoice forces a classify call on step 0 only, and ExampleParams 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.
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).
Fail the run from PrepareStep
Section titled “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 that wraps your error, so errors.Is finds your sentinel:
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}The function receives the run’s context, so it can read the run’s 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
Section titled “Complete example”preparestep/main.go runs the three cases against scripted models:
// 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) }}View on GitHub · run it from docs-site/examples:
go run ./preparestepgo test ./preparestep== trimthe model saw 3 of 5 messages, starting with "And order 5678?"the transcript keeps all 6 messages== phased toolsstep 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== errorerrors.Is(err, errNoTenant): truea *RunError: true, model calls: 0Best practices & gotchas
Section titled “Best practices & gotchas”- Trim deliberately: a rewrite can break a prompt-cache prefix.
PrepareStepandToolSourceare 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, 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
ToolChoiceNamedfor 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.
PrepareStepis code, like middleware;weft.jsondoes 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
Section titled “See also”- What happens in one step?
- Change an agent’s configuration for one run
- Define tools at runtime: RawTool and ToolSource
- Steer a running turn
- Add behaviour with middleware
Symbols used: weft.PrepareStep · Agent.Generate · Agent.Stream · ModelRequest.SequentialTools · weft.ModelRequest · weft.ErrDuplicateTool · weft.ErrNilTool · weft.RunError · weft.WrapModel · weft.PromptSnippet · weft.MetadataFromContext · weft.Instructions · weft.Messages · weft.Tool · weft.New · wefttest.Script · ExamplePrepareStep