---
title: Test an agent with a scripted model
description: Script a model's turns with wefttest.Script (tool calls, text, failures, usage), run the real agent over it, assert on what it did and what it asked, and keep the suite off the network with WEFT_MODEL_REQUESTS=deny.
url: https://weftgo.dev/docs/testing/scripted-models/
type: how-to
sources:
  - weft/core/wefttest/model.go:21 (ErrScriptExhausted), 24-36 (Turn, Say, 10/5 usage), 43-47 (Think), 49-78 (Call, ToolCalls, call_N ids, 10/5 usage), 82-90 (MaxTokens, Fail), 98-107 (Args), 113-125 (Raw, SayThenFail), 127-138 (Turn.WithUsage), 140-155 (Model, Script, Info), 157-205 (Stream; ctx error first, exhausted calls recorded), 207-261 (Requests, Request, HasTool, ToolNames, LastText, LastRequest)
  - weft/core/wefttest/flatten.go:12 (Flatten)
  - weft/core/wefttest/conform.go:15-31 (ConformInfo, ConformInfoT)
  - weft/wefttest/facade.go (every name an alias of or a wrapper around core/wefttest)
  - weft/core/wefttest/example_test.go:15 (ExampleRaw), 49 (ExampleArgs), 96 (ExampleSayThenFail), 116 (ExampleTurn_WithUsage), 141 (ExampleModel_LastRequest)
  - weft/core/env.go:5-18 (ModelRequestsAllowed reads the environment on every call)
  - weft/core/errors.go:79-84 (ErrModelRequestsDenied)
  - weft/facade.go:521 (ModelRequestsAllowed), 589 (ErrModelRequestsDenied)
  - weft/AGENTS.md:637 (test offline with Script), 646-654 (the deny switch, Client(c) bypass, wefttest ignores it)
  - weft/README.md:1039-1051 (Testing, in reach order)
  - weft/Makefile:102-107 (make offline)
  - 'weft/docs/adr/0013-adapter-contract.md (cross-cutting rules: the kill switch)'
  - weft/docs/adr/0017-testing-conventions.md (the scripting helpers table; C1, C3; the ToolChoice amendment, Script records but honours neither field)
  - weft/CHANGELOG.md:6143-6147 (0.2.0 scripting helpers), 6462-6465 (0.2.0 deny green workspace-wide), 6521-6523 (Requests records exhausted calls, ctx.Err first)
  - weft/core/wefttest/conformance/conformance_test.go:20-75 (scripting ErrStreamIdle and provider errors with Fail)
  - weft/core/wefttest/model_test.go:17 (TestScriptPlaysTurnsAndRecordsRequests), 128 (TestScriptYieldsContextErrorWhenDone), 227 (TestRawScriptsContractViolation), 288 (TestLastRequestMatchers), 326 (TestLastRequestZero)
  - docs-site/examples/testing/main.go, scripted_test.go (TestRun, TestScriptADialogue, TestInspectRequests, TestScriptIsConsumedAcrossRuns, TestScriptFailures, TestFlattenNested, TestConformInfo, TestDenySwitch)
---

# Test an agent with a scripted model

[`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) returns a [scripted model](https://weftgo.dev/docs/reference/glossary/#scripted-model): a [`weft.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Model) that plays the turns you write, one per model call, and records every request it receives. Build your real agent over it, run it, and assert on the result and on the requests. Nothing reaches the network, no key is needed, and the same script gives the same run every time.

From `testing/scripted_test.go`, the support agent with its real `lookup_order` tool:

```go title="testing/scripted_test.go"
model := wefttest.Script(
	wefttest.ToolCalls(wefttest.Call{
		Name: "lookup_order",
		Args: wefttest.Args(support.LookupInput{OrderID: "1234"}),
	}),
	wefttest.Say("Order 1234 shipped yesterday."),
)
res, err := support.New(model).Generate(context.Background(), weft.Prompt("Where is order 1234?"))
if err != nil {
	t.Fatal(err)
}
if got, want := res.Text(), "Order 1234 shipped yesterday."; got != want {
	t.Errorf("answer = %q, want %q", got, want)
}
// The tool really ran: its result is in the transcript.
tr := res.Messages[2].Content[0].(weft.ToolResultPart)
if tr.Content != "order 1234 shipped yesterday" || tr.IsError {
	t.Errorf("tool result = %+v", tr)
}
```

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

The first turn asks for a tool call, the loop runs `lookup_order`, and the second turn answers. The tool's result is real, so the test checks your tool and your loop configuration, not the model.

## In reach order

Write the cheapest test that answers your question. The README's order ([`README.md` Testing](https://github.com/weftgo/weft/blob/v0.20.2/README.md#testing): Script, Golden, Record and Replay), extended with Studio and conformance:

| Question | Test | Page |
|---|---|---|
| Does my agent do the right thing when the model says X? | `wefttest.Script` | this page |
| Did the output change? | [`wefttest.Golden`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Golden) | [Golden files](https://weftgo.dev/docs/testing/record-replay/#golden-files) |
| What does my agent do with what a real model said? | `wefttest.Record` once, `wefttest.Replay` in CI | [Record and replay](https://weftgo.dev/docs/testing/record-replay/) |
| Does this run from Studio still pass? | Studio's save as test | [Turn a Studio run into a test](https://weftgo.dev/docs/testing/studio-runs-as-tests/) |
| Does my adapter speak the provider's wire format? | `wefttest/conformance` | [Conformance](https://weftgo.dev/docs/testing/conformance/) |

## Script a dialogue

A script is a list of [`wefttest.Turn`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Turn) values. Each model call plays the next one:

| Builder | The model call… | Usage reported |
|---|---|---|
| [`Say(text)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Say) | streams one text delta, then stops (`stop`) | 10 in / 5 out |
| [`ToolCalls(calls...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#ToolCalls) | requests the tool calls, then stops (`tool_calls`) | 10 in / 5 out |
| [`Think(text, then)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Think) | streams unsigned reasoning, then plays `then` | `then`'s |
| [`MaxTokens(text)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#MaxTokens) | streams `text`, then finishes with `max_tokens` | 10 in / 5 out |
| [`Fail(err)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Fail) | errors with `err` before any event | none |
| [`SayThenFail(text, err)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#SayThenFail) | streams `text`, then errors with `err` | none |
| [`Raw(events...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Raw) | plays exactly these model events, appending nothing | what you script |

A [`wefttest.Call`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Call) names one tool call. [`Name`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2/wefttest#Call.Name) is the tool. [`Args`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2/wefttest#Call.Args) is raw JSON, `{}` when empty. [`ID`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2/wefttest#Call.ID) is optional: within a turn the calls get `call_1`, `call_2`, … in order. [`wefttest.Args(v)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Args) marshals a typed value into `Args`, so the scripted call and the tool's input struct cannot drift apart; a value that does not marshal panics at the call site.

The fixed 10 / 5 usage makes accounting assertable. Two scripted steps report 20 input and 10 output tokens:

```go title="testing/scripted_test.go"
// Every scripted step reports 10 input and 5 output tokens.
if res.Usage.InputTokens != 20 || res.Usage.OutputTokens != 10 {
	t.Errorf("usage = %+v, want 20 in / 10 out over two steps", res.Usage)
}
```

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

[`Turn.WithUsage(u)`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2/wefttest#Turn.WithUsage) replaces a turn's usage, which is how you drive a [`weft.UsageLimit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#UsageLimit) without arithmetic on the defaults. A turn with no finish (`Fail`, a `Raw` stream without one) comes back unchanged.

### Script failures

The failure builders pin how the agent behaves when the model misbehaves. From `testing/scripted_test.go`:

```go title="testing/scripted_test.go"
// Fail: the model call errors before any output. The run fails with a
// *weft.RunError that wraps the cause.
down := errors.New("provider unavailable")
_, err := support.New(wefttest.Script(wefttest.Fail(down))).Generate(ctx, prompt)
var re *weft.RunError
if !errors.As(err, &re) || !errors.Is(err, down) {
	t.Errorf("Fail: err = %v", err)
}

// SayThenFail: text, then the stream errors; the partial turn is discarded.
_, err = support.New(wefttest.Script(wefttest.SayThenFail("Order 12", down))).Generate(ctx, prompt)
if !errors.Is(err, down) {
	t.Errorf("SayThenFail: err = %v", err)
}

// MaxTokens: a truncated reply is a result, not an error.
res, err := support.New(wefttest.Script(wefttest.MaxTokens("Order 1234 sh"))).Generate(ctx, prompt)
if err != nil || res.StopReason != weft.StopMaxTokens {
	t.Errorf("MaxTokens: stop = %q, err = %v", res.StopReason, err)
}

// Raw: exactly these events. No ModelFinish breaks the Model contract.
_, err = support.New(wefttest.Script(wefttest.Raw(weft.ModelTextDelta{Text: "hi"}))).Generate(ctx, prompt)
if !errors.Is(err, weft.ErrModelContract) {
	t.Errorf("Raw: err = %v, want ErrModelContract", err)
}

// WithUsage: replace a turn's usage to drive a budget.
big := wefttest.ToolCalls(wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`}).
	WithUsage(weft.Usage{InputTokens: 900, OutputTokens: 40})
_, err = support.New(wefttest.Script(big, wefttest.Say("unreached")),
	weft.UsageLimit(weft.Usage{OutputTokens: 30})).Generate(ctx, prompt)
if !errors.Is(err, weft.ErrUsageLimit) {
	t.Errorf("WithUsage: err = %v, want ErrUsageLimit", err)
}
```

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

- `Fail` and `SayThenFail` fail the run with a [`*weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) that wraps your error. After `SayThenFail` the loop discards the partial turn; it is also the shape [`mw.Retry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Retry) sees as a failure after output.
- `MaxTokens` is not an error: the run records `StopMaxTokens` on `RunResult.StopReason`.
- `Raw` is the way to break the Model stream contract on purpose. A stream with no `ModelFinish`, two of them, or an event after the finish fails the run wrapping [`weft.ErrModelContract`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrModelContract). It is also how you script a signed reasoning block, which `Think` cannot express.

A scripted model has no idle timer and no HTTP status. To test how your code handles a stalled stream or a provider error, script the error the adapter would yield: `Fail(fmt.Errorf("%w after 60s", weft.ErrStreamIdle))`, as the conformance harness does. Every scripted turn honours the Model contract on cancellation: when ctx is done, the stream yields `ctx.Err()` before anything scripted.

`Think` prefixes a turn with reasoning, which lands as a `weft.ReasoningPart` first in the assistant message:

```go title="testing/scripted_test.go"
// Think prefixes a turn with unsigned reasoning.
res, err = support.New(wefttest.Script(
	wefttest.Think("the user wants a status", wefttest.Say("Order 1234 shipped yesterday.")),
)).Generate(ctx, prompt)
if err != nil {
	t.Fatal(err)
}
if _, ok := res.Messages[1].Content[0].(weft.ReasoningPart); !ok {
	t.Errorf("first part = %T, want ReasoningPart", res.Messages[1].Content[0])
}
```

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

### A script is consumed across runs

One `*wefttest.Model` keeps its position. Run the agent twice over the same model and the second run plays the next turn. A call past the last turn fails the run with [`wefttest.ErrScriptExhausted`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#ErrScriptExhausted), and that call is still recorded:

```go title="testing/scripted_test.go"
model := wefttest.Script(
	wefttest.Say("Hello."),
	wefttest.Say("Order 5678 is still pending."),
)
agt := support.New(model)
first, _ := agt.Generate(context.Background(), weft.Prompt("Hi"))
second, _ := agt.Generate(context.Background(),
	weft.Messages(first.Messages...), weft.Prompt("And order 5678?"))
if second.Text() != "Order 5678 is still pending." {
	t.Errorf("second run = %q: it plays the script's next turn", second.Text())
}
// A third call has no turn left.
_, err := agt.Generate(context.Background(), weft.Prompt("Anything else?"))
if !errors.Is(err, wefttest.ErrScriptExhausted) {
	t.Errorf("err = %v, want ErrScriptExhausted", err)
}
if got := len(model.Requests()); got != 3 { // the exhausted call is recorded too
	t.Errorf("%d requests, want 3", got)
}
```

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

The run error's text says what happened: `wefttest: model script exhausted (agent made more model calls than the script provides)`. It is almost always a test bug, so fail on it. Build a new script per test unless the test is about a conversation.

The package examples show each builder alone: [`ExampleArgs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#example-Args), [`ExampleRaw`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#example-Raw), [`ExampleSayThenFail`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#example-SayThenFail), [`ExampleTurn_WithUsage`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2/wefttest#example-Turn.WithUsage) and [`ExampleModel_LastRequest`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2/wefttest#example-Model.LastRequest).

## Inspect requests

The model records every [`weft.ModelRequest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRequest) the agent sent. Assert on the system prompt, the transcript and the tool catalog the model saw:

```go title="testing/scripted_test.go"
reqs := model.Requests() // every request, in order
if len(reqs) != 2 {
	t.Fatalf("%d model calls, want 2", len(reqs))
}
first := wefttest.Request{ModelRequest: reqs[0]}
if first.System != support.Instructions {
	t.Errorf("system prompt = %q", first.System)
}
if first.LastText() != "Where is order 1234?" || !first.HasTool("lookup_order") {
	t.Errorf("first request: text %q, tools %v", first.LastText(), first.ToolNames())
}
last := model.LastRequest() // the follow-up after the tool step
if last.LastText() != "" {  // its last message is the tool result, not text
	t.Errorf("LastText = %q, want empty after a tool step", last.LastText())
}
if got := len(last.Messages); got != 3 { // user, assistant call, tool result
	t.Errorf("last request carries %d messages, want 3", got)
}
```

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

| Method | Returns |
|---|---|
| [`Model.Requests()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2/wefttest#Model.Requests) | Every request in order, including a call that exhausted the script. Use it to count attempts under `mw.Retry` or `mw.Fallback` |
| [`Model.LastRequest()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2/wefttest#Model.LastRequest) | The most recent request as a [`wefttest.Request`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Request), or the zero `Request` before any call, whose matchers report false and empty |
| [`Request.HasTool(name)`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2/wefttest#Request.HasTool) | Whether the request advertised that tool |
| [`Request.ToolNames()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2/wefttest#Request.ToolNames) | The advertised tool names, sorted |
| [`Request.LastText()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2/wefttest#Request.LastText) | The text of the last text part of the last message: the prompt on the first call, `""` after a tool step |
| [`Model.Info()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2/wefttest#Model.Info) | `{Provider: "wefttest", Name: "script"}`, so `RunStart.Model` and manifests carry a value in tests |

`Request` embeds the request ([`Request.ModelRequest`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2/wefttest#Request)), so every field stays reachable: `req.System`, `req.Messages`, `req.Tools`. A script records `ToolChoice` and `Params` for assertion and honours neither. [`Model.Stream`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2/wefttest#Model.Stream) is the `weft.Model` method the loop calls; a test can call it directly, as the package examples do.

A [subagent](https://weftgo.dev/docs/guides/subagents/)'s events reach the parent's stream wrapped in [`weft.Nested`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Nested). [`wefttest.Flatten`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Flatten) unwraps them, recursively, so you assert on the child's events as the child emitted them:

```go title="testing/scripted_test.go"
researcher := weft.New(wefttest.Script(wefttest.Say("The carrier lost it.")), weft.Name("research"))
lead := support.New(wefttest.Script(
	wefttest.ToolCalls(wefttest.Call{Name: "research", Args: `{"prompt":"why is 1234 late?"}`}),
	wefttest.Say("The carrier lost order 1234."),
), weft.Subagent("research", "Research a question.", researcher))

var evs []weft.Event
for ev, err := range lead.Stream(context.Background(), weft.Prompt("Why is order 1234 late?")).Events() {
	if err != nil {
		t.Fatal(err)
	}
	evs = append(evs, ev)
}
// Flatten unwraps every weft.Nested, so the child's TextDelta is visible.
var texts []string
for _, ev := range wefttest.Flatten(evs) {
	if d, ok := ev.(weft.TextDelta); ok {
		texts = append(texts, d.Text)
	}
}
if !slices.Equal(texts, []string{"The carrier lost it.", "The carrier lost order 1234."}) {
	t.Errorf("texts = %q", texts)
}
```

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

## Check that middleware forwards Info

Model middleware should forward the inner model's identity ([`weft.ModelMiddleware`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelMiddleware)'s convention). [`wefttest.ConformInfo`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#ConformInfo) wraps a scripted model in yours and returns an error when the `Info` changed; [`wefttest.ConformInfoT`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#ConformInfoT) fails the test instead:

```go title="testing/scripted_test.go"
// mw.Retry forwards the inner model's Info: it conforms.
wefttest.ConformInfoT(t, mw.Retry())

// A middleware that wraps the model in a bare struct hides it.
hides := func(next weft.Model) weft.Model { return struct{ weft.Model }{next} }
if err := wefttest.ConformInfo(hides); err == nil {
	t.Error("ConformInfo accepted a middleware that drops Info")
}
```

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

The error reads `middleware core.ModelMiddleware dropped Info: got {Provider: Name:}, want {Provider:wefttest Name:script}`. The type it prints is always `core.ModelMiddleware`, so name the middleware in your test's own message.

## Never reach the network

`WEFT_MODEL_REQUESTS=deny` is the [kill switch](https://weftgo.dev/docs/reference/glossary/#kill-switch). Every first-party adapter checks [`weft.ModelRequestsAllowed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRequestsAllowed) at the top of `Stream` and, when it is false, fails with [`weft.ErrModelRequestsDenied`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrModelRequestsDenied) before any I/O. The function reads the environment on every call, so `t.Setenv` toggles it per test:

```go title="testing/scripted_test.go"
t.Setenv("WEFT_MODEL_REQUESTS", "deny")
if weft.ModelRequestsAllowed() {
	t.Fatal("the switch reads the environment on every call")
}
prompt := weft.Prompt("Where is order 1234?")

// A client the adapter builds from credentials makes no request.
srv := conformance.NoRequestServer(t) // fails the test if anything arrives
built := openai.Model("gpt-5", openai.BaseURL(srv.URL), openai.APIKey("sk-test"))
_, err := support.New(built).Generate(context.Background(), prompt)
if !errors.Is(err, weft.ErrModelRequestsDenied) {
	t.Errorf("built client: err = %v, want ErrModelRequestsDenied", err)
}

// A client injected with Client(c) is a test double: it stays reachable.
stub := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
	w.Header().Set("Content-Type", "text/event-stream")
	_, _ = w.Write([]byte(sse))
}))
defer stub.Close()
c := openaisdk.NewClient(option.WithBaseURL(stub.URL), option.WithAPIKey("test"))
res, err := support.New(openai.Model("gpt-5", openai.Client(&c))).Generate(context.Background(), prompt)
if err != nil || res.Text() != "Order 1234 shipped yesterday." {
	t.Errorf("injected client: %q, %v", res.Text(), err)
}

// wefttest models ignore the switch.
res, err = support.New(wefttest.Script(wefttest.Say("Offline."))).Generate(context.Background(), prompt)
if err != nil || res.Text() != "Offline." {
	t.Errorf("scripted: %q, %v", res.Text(), err)
}
```

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

Three rules decide what the switch blocks:

- **A client the adapter builds from credentials is denied.** `openai.Model("gpt-5", openai.APIKey(…))` yields `weft: model requests denied by WEFT_MODEL_REQUESTS`; [`conformance.NoRequestServer`](https://weftgo.dev/docs/testing/conformance/#fixture-servers) proves no request left.
- **A client you inject with the adapter's `Client(c)` option is not.** It is a test double by construction, so a test pointed at an `httptest` server keeps working under deny.
- **`wefttest` models ignore the switch.** `Script`, `Replay` and `Record` make no request of their own; `Record`'s inner model checks it.

Run your whole suite under `WEFT_MODEL_REQUESTS=deny go test ./...` and a test that would call a provider fails loudly instead. weft's own suites run that way workspace-wide (`make offline`), and this docs module's tests pass under it.

## Complete example

`testing/main.go` runs the support agent over a script and prints the transcript and the requests the model saw:

```go title="testing/main.go"
// Command testing runs the support agent against a scripted model and
// prints what the agent did and what it asked the model: the Testing
// pages' complete example. Its tests (scripted_test.go, replay_test.go,
// conformance_test.go, support/) are the pages' regions.
package main

import (
	"context"
	"fmt"
	"io"
	"os"
	"strings"

	"github.com/weftgo/weft"
	"github.com/weftgo/weft/wefttest"
	"weftgo.dev/docs/examples/testing/support"
)

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

func run(ctx context.Context, w io.Writer) error {
	model := wefttest.Script(
		wefttest.ToolCalls(wefttest.Call{
			Name: "lookup_order",
			Args: wefttest.Args(support.LookupInput{OrderID: "1234"}),
		}),
		wefttest.Say("Order 1234 shipped yesterday."),
	)
	res, err := support.New(model).Generate(ctx, weft.Prompt("Where is order 1234?"))
	if err != nil {
		return err
	}

	fmt.Fprintf(w, "answer: %s\n", res.Text())
	fmt.Fprintf(w, "steps: %d, usage: %d in / %d out\n",
		len(res.Steps), res.Usage.InputTokens, res.Usage.OutputTokens)
	for _, m := range res.Messages {
		fmt.Fprintf(w, "  %-9s %s\n", m.Role, describe(m))
	}
	for i, req := range model.Requests() {
		fmt.Fprintf(w, "request %d: %d messages, tools %v\n",
			i, len(req.Messages), wefttest.Request{ModelRequest: req}.ToolNames())
	}
	return nil
}

// describe renders one message on one line.
func describe(m weft.Message) string {
	var parts []string
	for _, p := range m.Content {
		switch p := p.(type) {
		case weft.TextPart:
			parts = append(parts, fmt.Sprintf("%q", p.Text))
		case weft.ToolCallPart:
			parts = append(parts, fmt.Sprintf("call %s(%s) id=%s", p.Name, p.Args, p.ID))
		case weft.ToolResultPart:
			parts = append(parts, fmt.Sprintf("result %q id=%s", p.Content, p.CallID))
		}
	}
	return strings.Join(parts, " ")
}
```

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

The agent is `testing/support/support.go`: one `lookup_order` tool and a system prompt.

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

```sh
go run ./testing
WEFT_MODEL_REQUESTS=deny go test ./testing/...
```

```text
answer: Order 1234 shipped yesterday.
steps: 2, usage: 20 in / 10 out
  user      "Where is order 1234?"
  assistant call lookup_order({"order_id":"1234"}) id=call_1
  tool      result "order 1234 shipped yesterday" id=call_1
  assistant "Order 1234 shipped yesterday."
request 0: 1 messages, tools [lookup_order]
request 1: 3 messages, tools [lookup_order]
```

## Best practices & gotchas

- **Fail on `ErrScriptExhausted`.** An agent that makes more model calls than you scripted is a bug in the agent or the test; the exhausted call is in `Requests()` so you can see what it asked. (Source: `weft/core/wefttest/model.go:18-21`, `207-216`)
- **Assert `len(Requests()) > 0` before `LastRequest()`.** Before any call it returns the zero `Request`, whose matchers report false and empty, so a test that skips the check passes for the wrong reason. (Source: `weft/core/wefttest/model.go:250-261`, `TestLastRequestZero`)
- **`LastText()` is `""` after a tool step.** It reads the last message, which is the tool result on a follow-up call; read `Messages` for anything else. (Source: ADR 0017 C3, `weft/core/wefttest/model.go:233-252`)
- **Use `wefttest.Args` for typed arguments.** A struct literal stays in step with the tool's input type; hand-written JSON does not. (Source: ADR 0017 T9)
- **A script does not enforce `ToolChoice` or `Params`.** It records them; a test that needs the model to obey a forced choice scripts the call it would make. (Source: ADR 0017, the 2026-09-22 amendment)
- **Set `WEFT_MODEL_REQUESTS=deny` in CI.** It turns an accidental live call into a failing test, and leaves `wefttest` models and injected clients working. (Source: `weft/AGENTS.md:646-654`, `weft/Makefile:102-107`)

## See also

- [Record a real conversation once, replay it forever](https://weftgo.dev/docs/testing/record-replay/)
- [What is a Model?](https://weftgo.dev/docs/concepts/models/)
- [Wrap the model and the tools with middleware](https://weftgo.dev/docs/guides/middleware/)
- [Steer a running turn](https://weftgo.dev/docs/guides/steering/#steer-deterministically-in-tests): `wefttest.NewSteers`

Symbols used: [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) · [`wefttest.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Model) · [`wefttest.Turn`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Turn) · [`wefttest.Say`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Say) · [`wefttest.ToolCalls`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#ToolCalls) · [`wefttest.Call`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Call) · [`wefttest.Args`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Args) · [`wefttest.Think`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Think) · [`wefttest.MaxTokens`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#MaxTokens) · [`wefttest.Fail`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Fail) · [`wefttest.SayThenFail`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#SayThenFail) · [`wefttest.Raw`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Raw) · [`Turn.WithUsage`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2/wefttest#Turn.WithUsage) · [`wefttest.ErrScriptExhausted`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#ErrScriptExhausted) · [`wefttest.Request`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Request) · [`Model.Requests`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2/wefttest#Model.Requests) · [`Model.LastRequest`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2/wefttest#Model.LastRequest) · [`Model.Info`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2/wefttest#Model.Info) · [`Model.Stream`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2/wefttest#Model.Stream) · [`Request.HasTool`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2/wefttest#Request.HasTool) · [`Request.ToolNames`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2/wefttest#Request.ToolNames) · [`Request.LastText`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2/wefttest#Request.LastText) · [`wefttest.Flatten`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Flatten) · [`wefttest.ConformInfo`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#ConformInfo) · [`wefttest.ConformInfoT`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#ConformInfoT) · [`weft.ModelRequestsAllowed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRequestsAllowed) · [`weft.ErrModelRequestsDenied`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrModelRequestsDenied) · [`weft.ErrModelContract`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrModelContract) · [`weft.ErrUsageLimit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrUsageLimit) · [`weft.UsageLimit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#UsageLimit) · [`weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) · [`weft.Nested`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Nested) · [`weft.ModelRequest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRequest) · [`weft.ModelMiddleware`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelMiddleware) · [`mw.Retry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Retry)
