Skip to content

Change an agent's configuration for one run

View as Markdown

An agent is an immutable value, so to change one run you pass the change to Generate or Stream as a run option. weft.Instructions, weft.MaxSteps, weft.Parallelism, weft.Params and weft.ToolChoice work on weft.New and on a run; weft.OnlyTools and weft.UseModel work on a run only. The agent’s own values are unchanged for every other run.

One run with its own prompt and a smaller budget, in runoptions/main.go:

runoptions/main.go
agt := weft.New(model,
weft.Instructions("You are a support agent."), // every run's default
weft.MaxSteps(10),
weft.Parallelism(4),
)
// One run, its own prompt and a smaller budget; the agent is unchanged.
_, err := agt.Generate(ctx,
weft.Instructions("Answer in one word."),
weft.MaxSteps(3),
weft.Parallelism(1),
weft.Prompt("Where is order 1234?"),
)
if err != nil {
return err
}
fmt.Fprintf(w, "system sent: %q\n", model.LastRequest().System)
// A raise is refused before any model call.
_, err = agt.Generate(ctx, weft.MaxSteps(20), weft.Prompt("Where is order 1234?"))
fmt.Fprintln(w, "invalid run option:", errors.Is(err, weft.ErrInvalidRunOption))
fmt.Fprintln(w, err)

runoptions/main.go on GitHub

The second Generate asks for 20 steps on an agent built with 10, and fails before any model call.

Each option sets a value on the run’s configuration; the loop resolves the run’s effective values once, before step 0, and reads those instead of the agent’s fields. A value given to the run replaces the agent’s; a value not given keeps it. Nothing is merged and nothing is written back to the agent, so concurrent runs of one agent can each carry different options.

OptionOn NewOn a runRule per run
Instructions(text)default system promptreplaces itany text
MaxSteps(n)budget, default 10lowers ita raise is ErrInvalidRunOption
Parallelism(n)width, default 4lowers ita raise is ErrInvalidRunOption
OnlyTools(names...)—narrows the toolsan unknown name is ErrInvalidRunOption
UseModel(m)—replaces the modela nil model is ignored
Params(p)default samplingreplaces the struct wholea negative MaxTokens fails the run
ToolChoice(cfg)default choicereplaces itan unsatisfiable choice fails the run
Thinking(cfg)default levelreplaces itsee Control reasoning

ParkOn and ParkAllExcept are run options too; they park calls at the approval boundary and are covered in Require human approval for a tool. The agent’s Manifest, Agent.Tools and Agent.Model keep describing the agent as built: they describe the code, not one run.

Change instructions and budgets for one run

Section titled “Change instructions and budgets for one run”

Instructions, MaxSteps and Parallelism return weft.InstructionsOption, weft.MaxStepsOption and weft.ParallelismOption. Each of these interfaces is both an Option and a RunOption, so one constructor works in both places. This is the shape weft.Thinking already had.

A run may replace the instructions with any text. The two limits may only go down: per run they are safety knobs, and a raise would be the budget escaping. A raise fails with ErrInvalidRunOption at step 0, before any model call and before any resumed call runs. Values below 1 are ignored, as on New.

OnlyTools keeps the named tools among the agent’s registered ones and drops the rest for this run. The step advertises and dispatches against the same narrowed list, so what the model was shown is exactly what runs:

runoptions/main.go
_, err := agt.Generate(ctx, weft.OnlyTools("lookup"), weft.Prompt("Where is order 1234?"))
if err != nil {
return err
}
fmt.Fprintln(w, "advertised:", model.LastRequest().ToolNames())
_, err = agt.Generate(ctx, weft.OnlyTools("cancel"), weft.Prompt("Cancel order 1234."))
fmt.Fprintln(w, err)
res, err := agt.Generate(ctx, weft.UseModel(alt), weft.Prompt("Where is order 1234?"))
if err != nil {
return err
}
fmt.Fprintln(w, "answer:", res.Text())

runoptions/main.go on GitHub

OnlyTools narrows; it cannot add, because a new tool is code. A name the agent does not have fails the run before any model call, as the second Generate shows. With a ToolSource, the names are checked against the step-0 snapshot and the narrowing applies to each step’s fresh snapshot; a narrowed tool the source later drops fails as unknown when called. Several OnlyTools options add up: the run keeps every tool any of them names. An Output[T] agent’s submit_output is narrowed like any tool, so name it too: OnlyTools("lookup") alone drops it, the model’s submission reads NO_SUCH_TOOL: no tool named "submit_output", and GenerateAs returns ErrNoOutput (structured output). The package example is ExampleOnlyTools.

UseModel(m) replaces the agent’s model for this run and rebuilds the WrapModel chain over it, first registered outermost, as New does. The run’s model calls go through the same middleware, over m. RunStart.Model and the chat spans name the run’s model, because middleware forwards Info; Agent.Model and the manifest keep naming the agent’s own. In the example above, the third run answers from alt. A nil model is ignored.

Params sets the sampling knobs of a weft.RequestParams: Temperature, TopP, MaxTokens, Stop and Seed. It returns a weft.ParamsOption, accepted by New and by a run:

runoptions/main.go
agt := weft.New(model, weft.Params(weft.RequestParams{
Temperature: ptr(0.2),
MaxTokens: ptr(512),
}))
if _, err := agt.Generate(ctx, weft.Prompt("Classify this ticket.")); err != nil {
return err
}
// The run's Params replaces the agent's struct: MaxTokens is not kept.
creative := weft.Params(weft.RequestParams{Temperature: ptr(0.9), Seed: ptr(int64(7))})
if _, err := agt.Generate(ctx, creative, weft.Prompt("Draft a reply.")); err != nil {
return err
}
for i, req := range model.Requests() {
fmt.Fprintf(w, "run %d: %s\n", i+1, describe(req.Params))
}
_, err := agt.Generate(ctx, weft.Params(weft.RequestParams{MaxTokens: ptr(-1)}), weft.Prompt("x"))
fmt.Fprintln(w, err)

runoptions/main.go on GitHub

TopP is a *float64 like Temperature: nil keeps the adapter’s TopP option, a set value overrides it for one call. Stop is a []string of stop sequences: an empty slice keeps the adapter’s Stop option.

Every field is a pointer or a slice, so three states stay apart. Nil or empty keeps the adapter’s construction default (its own Temperature option, and so on). A set value overrides it for this request. A set pointer to 0 is a value: a temperature of exactly 0 is sent. MaxTokens is the exception on two adapters. On anthropic a MaxTokens of 0 falls to the adapter’s construction value, else its default, because the API requires a positive value. On google a 0 keeps the construction value, and with none set the field is left out, so Gemini’s own default applies. Only openai sends a MaxTokens of 0 as a value.

A run’s Params replaces the agent’s struct whole; it does not merge field by field. In the output, run 2 loses the agent’s max_tokens=512 because its struct does not set it. Start from agt.Params(), a copy, when an override should keep the other knobs.

A negative MaxTokens fails the run at the step that carries it, with the text shown in the output. Adapters drop knobs their provider lacks: anthropic has no seed. google sends MaxTokens and Seed as int32 and fails with ErrUnsupported past that ceiling. For a vendor knob weft has no field for, every adapter has ExtraBody and ExtraHeaders (Connect a model provider). To change sampling per step, edit req.Params in a PrepareStep function; the package example ExampleParams runs the classifying step cold and the drafting step at 0.9.

ToolChoice takes a weft.ToolChoiceConfig with a Mode and a Name, and returns a weft.ToolChoiceOption. The weft.ToolChoiceMode values:

ModeValueEffectopenaianthropicgoogle
ToolChoiceAuto""provider default; nothing is sent———
ToolChoiceAny"any"the provider is asked to call some toolrequiredanyANY
ToolChoiceNamed"tool"the provider is asked to call the tool Namenamed functiontoolANY + allowedFunctionNames
ToolChoiceNone"none"the provider is asked for no call; the catalogue stays advertisednonenoneNONE

The adapter columns are what each one sends; the shared conformance case tool_choice_forcing checks the request bytes carry the provider’s field (Run the adapter conformance suite).

Every mode is a request to the provider, not a rule the loop enforces. The loop validates the choice, but it never filters the calls that come back: a call the model emits anyway runs, under ToolChoiceNone too, because the model was shown the tool. The first-party adapters send the field; an OpenAI-compatible server that ignores tool_choice may not. Enforce a choice shows how to make sure a call does not run.

runoptions/main.go
agt := weft.New(model, lookupTool(), refundTool())
// Every step of this run must call lookup.
named := weft.ToolChoice(weft.ToolChoiceConfig{Mode: weft.ToolChoiceNamed, Name: "lookup"})
if _, err := agt.Generate(ctx, named, weft.Prompt("Where is order 1234?")); err != nil {
return err
}
// None forbids calls and keeps the catalogue advertised.
none := weft.ToolChoice(weft.ToolChoiceConfig{Mode: weft.ToolChoiceNone})
if _, err := agt.Generate(ctx, none, weft.Prompt("Summarise our refund policy.")); err != nil {
return err
}
last := model.LastRequest()
fmt.Fprintf(w, "mode=%s tools=%v\n", last.ToolChoice.Mode, last.ToolNames())
// A choice the step's tools cannot satisfy fails the run.
bad := weft.ToolChoice(weft.ToolChoiceConfig{Mode: weft.ToolChoiceNamed, Name: "cancel"})
_, err := agt.Generate(ctx, bad, weft.Prompt("Cancel order 1234."))
fmt.Fprintln(w, err)

runoptions/main.go on GitHub

A run-level choice applies to every step of the run: in the output, requests 1 and 2 of the first run both carry mode="tool". A scripted model ignores it; a real one forced to call lookup on every step keeps calling it until the step budget ends the run. To force only the first step, set req.ToolChoice on step 0 in a PrepareStep function, as the package example ExampleToolChoice does with a classify router.

ToolChoiceNone exists for prompt caching. Removing tools from the request to stop calls changes the cached prefix; none keeps the tool definitions in the request and asks the provider not to call them.

The loop checks the choice at each step, after PrepareStep, against the tools that step advertises. Name is required under ToolChoiceNamed and must be empty under every other mode. A named tool the step does not advertise, any forced mode with no tools, or an unknown mode fails the run with a descriptive error. Those failures are programming errors, reported in the text, with no sentinel.

Where a call must not run, whatever the provider does, pair the choice with a rule the loop applies to the calls that come back. OnlyTools and ParkOn are run options; mw.Allow is tool middleware, given to weft.New:

AddWhat happens to a call it rules outCatalogue
weft.OnlyTools(names...)The tools not named are dropped for the run; a call to one reads NO_SUCH_TOOL: no tool named "refund"Narrowed, so the cached prefix changes
weft.WrapTools(mw.Allow(permit))A call permit rejects never runs; the model sees DENIED: tool "refund" is not allowedKept
weft.ParkOn(names...)The call parks at the approval boundary on res.Pending, for Approve or DenyKept

Each one rules calls out. Nothing makes a model call a tool it chose not to call: under ToolChoiceAny or ToolChoiceNamed, a reply with no call still ends the step as a plain answer.

A run that a run option changed carries the change on its invoke_agent span. weft.override.hash is a sha256 over the canonical JSON of every changed value, and one weft.override.* attribute names each knob: instructions (true; the text itself is content and never on a span), tools, model, thinking, tool_choice, params, max_steps, parallelism, park_on and park_all_except. A plain run carries none of them.

“Changed” means a run option was applied, even when its value equals the agent’s: the fingerprint records what the run carried, not a diff. Tool names in tools, park_on and park_all_except are a sorted, de-duplicated set, so equal experiments hash equal whatever order the names came in. TestOverrideFingerprint in the example package pins three of these rules against a recording tracer: no attribute on a plain run, the order-independent tool set, and the instructions flag with its own hash; the rest are in core/run.go:878-978. The hash is an experiment’s fingerprint: two sibling runs with equal changes carry equal hashes, which is how a reader groups them (Run experiments in the playground).

weft.ErrInvalidRunOption marks a per-run configuration the agent refuses: an unknown name in OnlyTools, or a MaxSteps or Parallelism raise. It comes wrapped in a *weft.RunError before any model call, so a run that would misconfigure itself does not start. Branch on it with errors.Is(err, weft.ErrInvalidRunOption).

The Params and ToolChoice failures are not this sentinel. They are checked per step, because PrepareStep can change both, and an agent default, a run option and a PrepareStep edit fail alike.

runoptions/main.go runs each region against scripted models:

runoptions/main.go
// Command runoptions runs the examples of the guide "Change an agent's
// configuration for one run": go run ./runoptions. Every model is
// scripted with wefttest, so it runs offline.
package main
import (
"context"
"errors"
"fmt"
"io"
"os"
"strings"
"github.com/weftgo/weft"
"github.com/weftgo/weft/wefttest"
)
func ptr[T any](v T) *T { return &v }
type lookupInput struct {
OrderID string `json:"order_id" jsonschema:"the order to look up"`
}
func lookupTool() *weft.ToolDef {
return weft.Tool("lookup", "Look up an order.",
func(_ context.Context, in lookupInput) (string, error) {
return "order " + in.OrderID + " has shipped", nil
})
}
func refundTool() *weft.ToolDef {
return weft.Tool("refund", "Refund an order.",
func(_ context.Context, in lookupInput) (string, error) {
return "refunded " + in.OrderID, nil
})
}
// dual: Instructions, MaxSteps and Parallelism per run.
func dual(ctx context.Context, w io.Writer) error {
model := wefttest.Script(wefttest.Say("Shipped."))
agt := weft.New(model,
weft.Instructions("You are a support agent."), // every run's default
weft.MaxSteps(10),
weft.Parallelism(4),
)
// One run, its own prompt and a smaller budget; the agent is unchanged.
_, err := agt.Generate(ctx,
weft.Instructions("Answer in one word."),
weft.MaxSteps(3),
weft.Parallelism(1),
weft.Prompt("Where is order 1234?"),
)
if err != nil {
return err
}
fmt.Fprintf(w, "system sent: %q\n", model.LastRequest().System)
// A raise is refused before any model call.
_, err = agt.Generate(ctx, weft.MaxSteps(20), weft.Prompt("Where is order 1234?"))
fmt.Fprintln(w, "invalid run option:", errors.Is(err, weft.ErrInvalidRunOption))
fmt.Fprintln(w, err)
fmt.Fprintln(w, "model calls:", len(model.Requests()))
return nil
}
// onlyTools narrows the catalogue and swaps the model for one run.
func onlyTools(ctx context.Context, w io.Writer) error {
model := wefttest.Script(wefttest.Say("from the agent's model"))
alt := wefttest.Script(wefttest.Say("from the alternate model"))
agt := weft.New(model, lookupTool(), refundTool())
_, err := agt.Generate(ctx, weft.OnlyTools("lookup"), weft.Prompt("Where is order 1234?"))
if err != nil {
return err
}
fmt.Fprintln(w, "advertised:", model.LastRequest().ToolNames())
_, err = agt.Generate(ctx, weft.OnlyTools("cancel"), weft.Prompt("Cancel order 1234."))
fmt.Fprintln(w, err)
res, err := agt.Generate(ctx, weft.UseModel(alt), weft.Prompt("Where is order 1234?"))
if err != nil {
return err
}
fmt.Fprintln(w, "answer:", res.Text())
fmt.Fprintln(w, "agent's tools:", len(agt.Tools()))
return nil
}
// params sets sampling for the agent, overrides it for a run, and shows
// that the run's struct replaces the agent's whole.
func params(ctx context.Context, w io.Writer) error {
model := wefttest.Script(wefttest.Say("a"), wefttest.Say("b"), wefttest.Say("c"))
agt := weft.New(model, weft.Params(weft.RequestParams{
Temperature: ptr(0.2),
MaxTokens: ptr(512),
}))
if _, err := agt.Generate(ctx, weft.Prompt("Classify this ticket.")); err != nil {
return err
}
// The run's Params replaces the agent's struct: MaxTokens is not kept.
creative := weft.Params(weft.RequestParams{Temperature: ptr(0.9), Seed: ptr(int64(7))})
if _, err := agt.Generate(ctx, creative, weft.Prompt("Draft a reply.")); err != nil {
return err
}
for i, req := range model.Requests() {
fmt.Fprintf(w, "run %d: %s\n", i+1, describe(req.Params))
}
_, err := agt.Generate(ctx, weft.Params(weft.RequestParams{MaxTokens: ptr(-1)}), weft.Prompt("x"))
fmt.Fprintln(w, err)
return nil
}
// describe prints the set knobs of a RequestParams.
func describe(rp weft.RequestParams) string {
var parts []string
if rp.Temperature != nil {
parts = append(parts, fmt.Sprintf("temperature=%g", *rp.Temperature))
}
if rp.TopP != nil {
parts = append(parts, fmt.Sprintf("top_p=%g", *rp.TopP))
}
if rp.MaxTokens != nil {
parts = append(parts, fmt.Sprintf("max_tokens=%d", *rp.MaxTokens))
}
if len(rp.Stop) > 0 {
parts = append(parts, fmt.Sprintf("stop=%q", rp.Stop))
}
if rp.Seed != nil {
parts = append(parts, fmt.Sprintf("seed=%d", *rp.Seed))
}
return strings.Join(parts, " ")
}
// toolChoice forces, names and forbids tool calls.
func toolChoice(ctx context.Context, w io.Writer) error {
model := wefttest.Script(
wefttest.ToolCalls(wefttest.Call{Name: "lookup", Args: `{"order_id":"1234"}`}),
wefttest.Say("Order 1234 has shipped."),
wefttest.Say("I can answer without tools."),
)
agt := weft.New(model, lookupTool(), refundTool())
// Every step of this run must call lookup.
named := weft.ToolChoice(weft.ToolChoiceConfig{Mode: weft.ToolChoiceNamed, Name: "lookup"})
if _, err := agt.Generate(ctx, named, weft.Prompt("Where is order 1234?")); err != nil {
return err
}
// None forbids calls and keeps the catalogue advertised.
none := weft.ToolChoice(weft.ToolChoiceConfig{Mode: weft.ToolChoiceNone})
if _, err := agt.Generate(ctx, none, weft.Prompt("Summarise our refund policy.")); err != nil {
return err
}
last := model.LastRequest()
fmt.Fprintf(w, "mode=%s tools=%v\n", last.ToolChoice.Mode, last.ToolNames())
// A choice the step's tools cannot satisfy fails the run.
bad := weft.ToolChoice(weft.ToolChoiceConfig{Mode: weft.ToolChoiceNamed, Name: "cancel"})
_, err := agt.Generate(ctx, bad, weft.Prompt("Cancel order 1234."))
fmt.Fprintln(w, err)
for i, req := range model.Requests() {
fmt.Fprintf(w, "request %d: mode=%q name=%q\n", i+1, req.ToolChoice.Mode, req.ToolChoice.Name)
}
return nil
}
func run(ctx context.Context, w io.Writer) error {
steps := []struct {
title string
fn func(context.Context, io.Writer) error
}{
{"dual options", dual},
{"only tools and use model", onlyTools},
{"params", params},
{"tool choice", toolChoice},
}
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 runoptions/main.go on GitHub

View on GitHub · run it from docs-site/examples:

Terminal window
go run ./runoptions
go test ./runoptions
== dual options
system sent: "Answer in one word."
invalid run option: true
weft: run failed at step 0: weft: invalid run option: max_steps 20 raises the agent's 10; per run it may only lower
model calls: 1
== only tools and use model
advertised: [lookup]
weft: run failed at step 0: weft: invalid run option: tool "cancel" is not registered on this agent; OnlyTools narrows, it cannot add
answer: from the alternate model
agent's tools: 2
== params
run 1: temperature=0.2 max_tokens=512
run 2: temperature=0.9 seed=7
weft: run failed at step 0: params: MaxTokens -1 is negative; a token budget cannot be
== tool choice
mode=none tools=[lookup refund]
weft: run failed at step 0: tool_choice names "cancel" but the step advertises no such tool
request 1: mode="tool" name="lookup"
request 2: mode="tool" name="lookup"
request 3: mode="none" name=""
  • Set every knob a Params override should carry. A run’s struct replaces the agent’s whole; start from agt.Params() to keep the rest. (Source: weft/core/run.go:611-620, weft/core/agent.go:970-984)
  • RequestParams has no TopK. Its knobs are Temperature, TopP, MaxTokens, Stop and Seed; weft leaves TopK out because Chat Completions has none. Send it at construction with the adapter’s ExtraBody, under the provider’s own name (top_k on the Anthropic Messages API, topK inside generationConfig for Gemini); it then applies to every call, not per run. (Source: weft/core/model.go:141-147, weft/anthropic/doc.go:25-32, ADR 0013 docs/adr/0013-adapter-contract.md:426)
  • Do not use a run option to raise a budget. MaxSteps and Parallelism only lower per run; build an agent with the larger value instead. (Source: weft/core/loop.go:356-366, ADR 0024 D5)
  • Force one step with PrepareStep, not a run-level ToolChoice. A run-level choice forces every step. (Source: weft/core/agent.go:357-365, ExampleToolChoice)
  • Prefer ToolChoiceNone to removing tools on a final step. It keeps the cached prompt prefix. (Source: weft/core/model.go:106-112)
  • Do not rely on ToolChoice alone to stop a call. A call the provider emits anyway runs, whatever the mode, and a compatible server that ignores tool_choice emits them. Where a call must not run, add OnlyTools, mw.Allow or ParkOn (Enforce a choice). (Source: weft/core/model.go:185-192; scratch proof in sources)
  • Expect RunStart.Model to name the UseModel model. Agent.Model and the manifest still name the agent’s. (Source: weft/core/run.go:289-296)

Symbols used: weft.Instructions · weft.InstructionsOption · weft.MaxSteps · weft.MaxStepsOption · weft.Parallelism · weft.ParallelismOption · weft.OnlyTools · weft.UseModel · weft.Params · weft.ParamsOption · weft.RequestParams · weft.ToolChoice · weft.ToolChoiceOption · weft.ToolChoiceConfig · weft.ToolChoiceMode · weft.ParkOn · weft.WrapTools · mw.Allow · weft.ErrInvalidRunOption · weft.RunError · Agent.Params · Agent.Tools · Agent.Model · weft.Manifest · weft.Tool · weft.New · weft.Prompt · wefttest.Script · ExampleOnlyTools · ExampleParams · ExampleToolChoice