---
title: Change an agent's configuration for one run
description: Pass Instructions, MaxSteps, Parallelism, OnlyTools, UseModel, Params or ToolChoice to Generate to change one run of an immutable agent, without building a second one.
url: https://weftgo.dev/docs/guides/run-options/
type: how-to
sources:
  - weft/core/agent.go:57-76 (InstructionsOption, Instructions), 78-108 (MaxStepsOption, MaxSteps), 198-226 (ParallelismOption, Parallelism), 332-366 (ToolChoiceOption, ToolChoice), 368-399 (ParamsOption, Params), 849-854 (validateParams), 862-888 (validateToolChoice)
  - 'weft/core/agent.go:1013-1028 (narrowTools keeps the named tools, submit_output no exception); scratch proof (weft v0.17.0): OnlyTools("lookup") and a ToolSource without it each gave ErrNoOutput with the NO_SUCH_TOOL result; OnlyTools("lookup", "submit_output") and a source appending agt.Tools()''s submit_output each decoded the value'
  - weft/core/run.go:267-279 (OnlyTools), 289-296 (UseModel), 611-620 (effectiveParams), 860-978 (the weft.override.* attributes)
  - weft/core/loop.go:356-380 (the lower-only and narrowing checks), 556-569 (tool choice and params validated per step)
  - weft/core/model.go:97-124 (ToolChoiceMode, ToolChoiceConfig), 125-148 (RequestParams)
  - 'weft/core/model.go:185-192 (ModelRequest.ToolChoice: it constrains what the provider is asked to emit, never execution; a call the provider emits anyway runs)'
  - 'weft/core/run.go:267-279 (OnlyTools: advertisement and dispatch resolve against the same narrowed snapshot), 306-318 (ParkOn); weft/core/mw/tool.go:16-25 (Allow: a denied call never runs, DENIED result)'
  - 'scratch proof (weft v0.17.0): a script emitting refund ran it under ToolChoiceNone and under ToolChoiceNamed lookup; adding OnlyTools("lookup") gave NO_SUCH_TOOL, mw.Allow gave DENIED: tool "refund" is not allowed, ParkOn("refund") left it on res.Pending; none of the three ran the handler; a scripted Say under ToolChoiceAny ended the run with err nil, 1 step, the plain text'
  - weft/core/errors.go:128-133 (ErrInvalidRunOption)
  - weft/openai/convert.go:101-111, weft/anthropic/convert.go:94-107, weft/google/convert.go:117-132 (tool choice per provider)
  - weft/anthropic/convert.go:16-37 (a request MaxTokens of 0 keeps the construction value, else defaultMaxTokens)
  - weft/google/convert.go:173-189 (a request MaxTokens of 0 keeps the construction value; none set leaves MaxOutputTokens out; only openai sends 0)
  - weft/openai/convert.go:140-141 (MaxCompletionTokens sent as set, 0 included)
  - weft/google/convert.go:154-202 (int32 MaxOutputTokens and Seed), weft/anthropic/model.go:86 (no seed)
  - weft/AGENTS.md:81-83 (block 2), 123-134 (block 3)
  - weft/README.md:900-905
  - weft/core/wefttest/conformance/conformance.go:385 (tool_choice_forcing)
  - weft/CHANGELOG.md:3221, 4833, 4836, 4841, 4847, 5981, 5994
  - weft/example_test.go:800 (ExampleToolChoice), 828 (ExampleParams), 997 (ExampleOnlyTools)
  - docs-site/examples/runoptions/main.go, main_test.go TestRunOptions, TestParallelismRaiseRefused, TestAgentUnchanged, TestOverrideFingerprint
  - 'weft/core/model.go:141-147 (RequestParams: no TopK); weft/anthropic/doc.go:25-32 (TopK stays out); weft/docs/adr/0013-adapter-contract.md:426; weft/google/model.go:102-113, weft/anthropic/model.go:146-156 (ExtraBody, deep-merged, construction-time)'
---

# Change an agent's configuration for one run

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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Instructions), [`weft.MaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxSteps), [`weft.Parallelism`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Parallelism), [`weft.Params`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Params) and [`weft.ToolChoice`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolChoice) work on `weft.New` and on a run; [`weft.OnlyTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#OnlyTools) and [`weft.UseModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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`:

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

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

## How it works

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.

| Option | On `New` | On a run | Rule per run |
|---|---|---|---|
| `Instructions(text)` | default system prompt | replaces it | any text |
| `MaxSteps(n)` | budget, default 10 | lowers it | a raise is `ErrInvalidRunOption` |
| `Parallelism(n)` | width, default 4 | lowers it | a raise is `ErrInvalidRunOption` |
| `OnlyTools(names...)` | — | narrows the tools | an unknown name is `ErrInvalidRunOption` |
| `UseModel(m)` | — | replaces the model | a nil model is ignored |
| `Params(p)` | default sampling | replaces the struct whole | a negative `MaxTokens` fails the run |
| `ToolChoice(cfg)` | default choice | replaces it | an unsatisfiable choice fails the run |
| `Thinking(cfg)` | default level | replaces it | see [Control reasoning](https://weftgo.dev/docs/guides/thinking/) |

`ParkOn` and `ParkAllExcept` are run options too; they park calls at the approval boundary and are covered in [Require human approval for a tool](https://weftgo.dev/docs/guides/approvals/). The agent's [`Manifest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Manifest), [`Agent.Tools`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Tools) and [`Agent.Model`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Model) keep describing the agent as built: they describe the code, not one run.

## Change instructions and budgets for one run

`Instructions`, `MaxSteps` and `Parallelism` return [`weft.InstructionsOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#InstructionsOption), [`weft.MaxStepsOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxStepsOption) and [`weft.ParallelismOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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`.

## Narrow the tools

`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:

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

`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](https://weftgo.dev/docs/guides/structured-output/#best-practices--gotchas)). The package example is [`ExampleOnlyTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-OnlyTools).

## Swap the model

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

## Set sampling parameters

`Params` sets the sampling knobs of a [`weft.RequestParams`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RequestParams): [`Temperature`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#RequestParams.Temperature), [`TopP`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#RequestParams.TopP), [`MaxTokens`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#RequestParams.MaxTokens), [`Stop`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#RequestParams.Stop) and [`Seed`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#RequestParams.Seed). It returns a [`weft.ParamsOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParamsOption), accepted by `New` and by a run:

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

`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()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.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](https://weftgo.dev/docs/guides/providers/)). To change sampling per step, edit `req.Params` in a [`PrepareStep`](https://weftgo.dev/docs/guides/prepare-step/) function; the package example [`ExampleParams`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Params) runs the classifying step cold and the drafting step at 0.9.

## Force or forbid tool calls

`ToolChoice` takes a [`weft.ToolChoiceConfig`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolChoiceConfig) with a [`Mode`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ToolChoiceConfig.Mode) and a [`Name`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ToolChoiceConfig.Name), and returns a [`weft.ToolChoiceOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolChoiceOption). The [`weft.ToolChoiceMode`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolChoiceMode) values:

| Mode | Value | Effect | openai | anthropic | google |
|---|---|---|---|---|---|
| [`ToolChoiceAuto`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolChoiceAuto) | `""` | provider default; nothing is sent | — | — | — |
| [`ToolChoiceAny`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolChoiceAny) | `"any"` | the provider is asked to call some tool | `required` | `any` | `ANY` |
| [`ToolChoiceNamed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolChoiceNamed) | `"tool"` | the provider is asked to call the tool `Name` | named function | `tool` | `ANY` + `allowedFunctionNames` |
| [`ToolChoiceNone`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolChoiceNone) | `"none"` | the provider is asked for no call; the catalogue stays advertised | `none` | `none` | `NONE` |

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](https://weftgo.dev/docs/testing/conformance/)).

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](#enforce-a-choice) shows how to make sure a call does not run.

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

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

### Enforce a choice

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`:

| Add | What happens to a call it rules out | Catalogue |
|---|---|---|
| [`weft.OnlyTools(names...)`](#narrow-the-tools) | 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))`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Allow) | A call `permit` rejects never runs; the model sees `DENIED: tool "refund" is not allowed` | Kept |
| [`weft.ParkOn(names...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParkOn) | The call parks at the [approval boundary](https://weftgo.dev/docs/guides/approvals/) on `res.Pending`, for `Approve` or `Deny` | Kept |

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.

## Read the override fingerprint

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](https://weftgo.dev/docs/observe/playground/experiments/)).

## Handle a refused run option

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

## Complete example

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

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

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

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

```sh
go run ./runoptions
go test ./runoptions
```

```text
== 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=""
```

## Best practices & gotchas

- **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](#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`)

## See also

- [What is an agent in weft?](https://weftgo.dev/docs/concepts/agents/)
- [Rewrite the request each step (PrepareStep)](https://weftgo.dev/docs/guides/prepare-step/)
- [Control reasoning (thinking)](https://weftgo.dev/docs/guides/thinking/)
- [Require human approval for a tool](https://weftgo.dev/docs/guides/approvals/): `ParkOn`, `ParkAllExcept`
- [Run experiments in the playground](https://weftgo.dev/docs/observe/playground/experiments/)

Symbols used: [`weft.Instructions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Instructions) · [`weft.InstructionsOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#InstructionsOption) · [`weft.MaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxSteps) · [`weft.MaxStepsOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxStepsOption) · [`weft.Parallelism`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Parallelism) · [`weft.ParallelismOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParallelismOption) · [`weft.OnlyTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#OnlyTools) · [`weft.UseModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#UseModel) · [`weft.Params`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Params) · [`weft.ParamsOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParamsOption) · [`weft.RequestParams`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RequestParams) · [`weft.ToolChoice`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolChoice) · [`weft.ToolChoiceOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolChoiceOption) · [`weft.ToolChoiceConfig`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolChoiceConfig) · [`weft.ToolChoiceMode`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolChoiceMode) · [`weft.ParkOn`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParkOn) · [`weft.WrapTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapTools) · [`mw.Allow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Allow) · [`weft.ErrInvalidRunOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrInvalidRunOption) · [`weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) · [`Agent.Params`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Params) · [`Agent.Tools`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Tools) · [`Agent.Model`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Model) · [`weft.Manifest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Manifest) · [`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) · [`weft.Prompt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Prompt) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) · [`ExampleOnlyTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-OnlyTools) · [`ExampleParams`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Params) · [`ExampleToolChoice`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-ToolChoice)
