
Testing an AI agent offline with recorded replies
Testing an agent without a live model: scripted models, replayed HTTP, and outcome checks.
On the agent compass The whole loop, all four stagesLive models make poor test dependencies.
The same prompt can produce a different reply on every call.
Every call is billed and takes seconds.
Providers also retire models, so a test written against one of them stops working when it goes away.
go test should depend on none of that.
In the companion code, all tests run without a network, and each example program falls back to recorded replies when it finds no API key.
This page walks through how that works, using ch02/replay and the tests that use it.
Three sources of model replies and what each one shows
| Kind | What it tests | What it can’t |
|---|---|---|
| A scripted model | The loop’s rules, exactly and for free | Anything about choosing tools |
| Recorded replies | The client and the tools against real JSON, real token counts, and the model’s real mistakes, with no network | How a model behaves on a new input |
| Live runs | How a model actually behaves | Anything exact: they vary and cost money |
The test suite uses only the first two rows. The third row belongs to evals, where you deliberately run a real model many times and score the runs as a pass rate.
A scripted model
The loop only knows a model through one method, Generate(ctx, req).
A Fake implements it with a list of canned replies:
// Fake is a Model that replays a script of replies. It picks the next
// reply by counting the assistant messages already in the conversation,
// so it stays in step with the loop.
type Fake struct {
Script []Message
}
// Generate returns the next scripted reply.
func (f *Fake) Generate(_ context.Context, req Request) (Reply, error) {
n := 0
for _, m := range req.Messages {
if m.Role == "assistant" {
n++
}
}
if n >= len(f.Script) {
return Reply{}, fmt.Errorf("reply %d: %w",
n+1, ErrScriptExhausted)
}
return Reply{Message: f.Script[n]}, nil
}
To choose which reply comes next, Fake counts how many assistant messages the request already holds.
A real model also sees nothing but the request, so this keeps the fake honest.
It also turns the fake into a check on the loop: drop a message or put two in the wrong order, and the fake answers with the wrong reply, so the test fails.
That is enough to pin down each rule of the loop with its own test.
An answer ends the run.
So does reaching the turn limit.
Each tool call gets one tool message, never zero or two.
A failing tool’s result goes back flagged as an error.
Replaying recorded calls
The scripted model sits above the HTTP client, so it never exercises the client.
To test the client, the companion code replaces what sits below it.
In Go, every HTTP request passes through an http.RoundTripper.
Hand http.Client a round tripper that reads its responses from files, and the client behaves exactly as it would on the network:
// Transport is an http.RoundTripper that answers each request with the
// next saved response for its script, read from Files.
type Transport struct {
Files fs.FS // saved calls, such as an embedded testdata directory
calls counter
}
// RoundTrip serves the next saved response.
func (t *Transport) RoundTrip(
req *http.Request) (*http.Response, error) {
if _, err := drain(req); err != nil {
return nil, err
}
ctx := req.Context()
if err := context.Cause(ctx); err != nil {
return nil, fmt.Errorf("replay: %w", err)
}
script := scriptOf(ctx)
n := t.calls.next(script)
rec, err := load(t.Files, script, n)
if err != nil {
return nil, err
}
return rec.response(req), nil
}
Recorded calls belong to scripts, and each script is a numbered series of files such as fix-01.json and fix-02.json.
A single client can serve calls from several scripts, which rules out storing the script name on the transport.
The program passes the name along with the request, so the transport can read it when the request arrives.
The program puts the name in the request’s context instead, under a key of an unexported type so that no other package can use the same key.
This is exactly the case context values exist for: a value scoped to one request that has to pass from the program, through the client and http.Client, down to the transport.
The transport keeps the RoundTripper rules.
It closes the request body, leaves the request unmodified, and returns an error for a request whose context is already cancelled, just as a real network round trip would.
When a test makes more calls than a script holds, the transport returns an error that names both the call and the script. An unexpected extra call then fails the test immediately; it can’t hang and it can’t go out to the network.
Recording a live run
For capturing new recordings, the package also has a recording transport.
It passes each request through to the real API and writes three things to disk: the request body, the response status, and the response body.
Headers are never saved, so the key can’t end up in a recording.
You name the run and pick a directory, run it once with a key, and copy the files into testdata/replies.
From then on, with no key set, the program replays that run while its tools execute for real.
Fixtures for failures you can’t produce
Many failures can’t be triggered on request.
There is no way to ask the API for a 503, or to get a model to reuse a tool-call ID, at the moment a test needs one.
The alternative is to write those saved runs by hand.
Each is a short list of turns, and each turn is either an HTTP status or a reply: some text, some tool calls, an odd finish reason, or two calls sharing an ID.
An opt-in test turns the lists into recordings.
It serves each one from an httptest server that speaks the chat completions format OpenRouter uses, points the real program at that server, and captures the traffic with the recording transport, so the saved requests match what the client really sends.
That produces a saved run for every stop reason and for every status code, and a table test replays each one and checks that the error belongs to the expected family.
Check outcomes, not transcripts
The same task, run twice on the same model, can follow two different routes, and two models can reach the same fix in different ways.
The tests for the real agent therefore check results and ignore wording.
An outcome test replays every saved run and asks three questions.
Does duration.go hold the fix?
Did the tests run after the final edit?
Did the run end with an answer?
It doesn’t look at which files the agent opened, the order it opened them in, or the text of its answer.
A live run on some other model that takes yet another route is judged by the same three questions.
That test has a gap worth noticing. It doesn’t check that the test file is unchanged, and an agent told to make failing tests pass has an easy shortcut: weaken the tests. An eval grader covers this. A run that deletes or skips a test fails its task, and separate hidden tests, which the agent never sees, check that the fix actually works.
Timeouts without waiting
The client gives each call two minutes.
Nobody runs a test that sits idle for two minutes.
testing/synctest, added in Go 1.25, solves this by running the test inside a bubble that has its own fake clock.
Inside the bubble the two-minute deadline arrives immediately, and the whole test takes a few milliseconds.
A goroutine is durably blocked when only another goroutine in the bubble could wake it, for example by waiting on a channel or on the request’s context. Once all of the bubble’s goroutines are durably blocked, the fake clock moves forward. The test’s transport never responds; it just waits on the request’s context. Inside the bubble, the two-minute deadline arrives immediately. The test then checks the returned error and confirms that the fake clock moved forward by exactly two minutes.
The same approach works for streams that stop sending and for retries with backoff. Streams get one extra test that is worth borrowing. The network can split a response into pieces at any byte, so the test feeds one recorded stream to the reader again and again, split at every possible position, and expects the same result each time.
What the tests cover
The following are all tested with no network calls:
- the request the client builds, checked against an
httptestserver - every saved reply and every saved status
- the per-call deadline and caller cancellation, over both HTTP/1.1 and HTTP/2
- scripts that fail when a test makes one call too many
- recordings, checked to contain no API key
- the real
go testtool on projects that pass, fail, and don’t build, with the key hidden from the code under test - every stop reason, replayed
How rare the failures are
How often do live runs produce the rare replies these hand-written fixtures stand in for? In the recorded evidence runs, never. Across those runs that set no token limit, 686 replies carried 617 tool calls, and none of the replies was truncated, blocked by a filter, broken off by its provider, or missing or repeating an ID. That is why the fixtures are written by hand: a test that waits for the real thing never runs, and the handling code it should cover is the code most likely to be wrong when the day comes.
Steps for your own agent
- Put the model behind a one-method interface, and test the loop’s rules with a scripted fake that picks its reply from the request.
- Give your HTTP client an
http.RoundTripperthat replays saved responses by script and call number, and fails on a call the script doesn’t have. - Record a few real runs with a recording transport that never saves headers, and replay them in every test.
- For each failure you can’t trigger on demand, write its replies by hand, serve them from
httptest, and record them through the real client. - Check outcomes (the file holds the fix, the tests ran after the last edit, the run ended with an answer), never the model’s wording.
- Run anything that waits on a clock under
testing/synctest. - Keep live runs out of
go test: they belong to evals, which measure a rate on purpose.
When to use it
Reach for it
- Every change to the harness. The loop’s failure handling covers replies that live runs almost never send: none of 686 recorded replies was cut off, filtered, or carried a bad ID.
- More than one model or route. A test that checks outcomes holds for any run that fixes the bug, whichever files it read on the way.
Leave it out
- Measuring how good the agent is. Saved replies show your code handles a reply, not how often a model sends a good one; that takes many live runs, scored.
Try it
From the code directory of a clone of the companion repository:
$ go test ./ch05/...
$ go run ./ch05 -replay dup-id
The first command runs every test for chapter 5’s agent, the loop hardened against bad replies, without a network or a key; the run_tests tool runs the real go test, so expect it to take a minute or two on a cold build cache.
The second replays a hand-written failure: a reply whose two tool calls share an ID.
Making a recording of your own is the one step that needs a key and spends money: -record names a directory to save the calls in and -replay names the run, so the calls are saved as <name>-01.json, <name>-02.json, and so on.
type Fake struct {
Script []Message
}
Fake is a Model that replays a script of replies.
Fake is a Model that replays a script of replies. type Fake struct { Script []Message }. In ch01/agent/fake.go, line 19.
type Message struct {
Role string // "system", "user", "assistant", or "tool"
Content string // empty when the message has tool calls
ToolCalls []ToolCall // set on assistant messages that call tools
ToolCallID string // on tool messages: the call this answers
IsError bool // set on tool messages that report a failure
}
Message is one entry in the conversation.
Message is one entry in the conversation. type Message struct { Role string // "system", "user", "assistant", or "tool" Content string // empty when the message has tool calls ToolCalls []ToolCall // set on assistant messages that call tools ToolCallID string // on tool messages: the call this answers IsError bool // set on tool messages that report a failure }. In ch01/agent/types.go, line 28.
func (f *Fake) Generate(_ context.Context, req Request) (Reply, error)
Generate returns the next scripted reply.
Generate returns the next scripted reply. func (f *Fake) Generate(_ context.Context, req Request) (Reply, error). In ch01/agent/fake.go, line 24.
package context ("context")
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes. package context ("context"). Documented at pkg.go.dev, context.
type Context interface {
// Deadline returns the time when work done on behalf of this context
// should be canceled. Deadline returns ok==false when no deadline is
// set. Successive calls to Deadline return the same results.
Deadline() (deadline time.Time, ok bool)
// Done returns a channel that's closed when work done on behalf of this
// context should be canceled. Done may return nil if this context can
// never be canceled. Successive calls to Done return the same value.
// The close of the Done channel may happen asynchronously,
// ...
}
A Context carries a deadline, a cancellation signal, and other values across API boundaries.
A Context carries a deadline, a cancellation signal, and other values across API boundaries. type Context interface { // Deadline returns the time when work done on behalf of this context // should be canceled. Deadline returns ok==false when no deadline is // set. Successive calls to Deadline return the same results. Deadline() (deadline time.Time, ok bool) // Done returns a channel that's closed when work done on behalf of this // context should be canceled. Done may return nil if this context can // never be canceled. Successive calls to Done return the same value. // The close of the Done channel may happen asynchronously, // ... }. Documented at pkg.go.dev, context.Context.
type Request struct {
Messages []Message
Tools []ToolDef
}
Request is what the harness sends the model on each turn.
Request is what the harness sends the model on each turn. type Request struct { Messages []Message Tools []ToolDef }. In ch01/agent/types.go, line 22.
type Reply struct {
Message Message // the assistant's message: text, tool calls, or both
}
Reply is the model's answer to one Request.
Reply is the model's answer to one Request. type Reply struct { Message Message // the assistant's message: text, tool calls, or both }. In ch01/agent/types.go, line 57.
type error interface {
Error() string
}
The error built-in interface type is the conventional interface for representing an error condition, with the nil value representing no error.
The error built-in interface type is the conventional interface for representing an error condition, with the nil value representing no error. type error interface { Error() string }. Documented at pkg.go.dev, builtin.error.
field Messages []Message
field Messages []Message. In ch01/agent/types.go, line 23.
field Role string
"system", "user", "assistant", or "tool"
"system", "user", "assistant", or "tool" field Role string. In ch01/agent/types.go, line 29.
func len(v Type) int
The len built-in function returns the length of v, according to its type:
The len built-in function returns the length of v, according to its type: func len(v Type) int. Documented at pkg.go.dev, builtin.len.
package fmt ("fmt")
Package fmt implements formatted I/O with functions analogous to C's printf and scanf.
Package fmt implements formatted I/O with functions analogous to C's printf and scanf. package fmt ("fmt"). Documented at pkg.go.dev, fmt.
func Errorf(format string, a ...any) (err error)
Errorf formats according to a format specifier and returns the string as a value that satisfies error.
Errorf formats according to a format specifier and returns the string as a value that satisfies error. func Errorf(format string, a ...any) (err error). Documented at pkg.go.dev, fmt.Errorf.
var ErrScriptExhausted = errors.New("fake model: script exhausted")
ErrScriptExhausted means a Fake was asked for more replies than its script holds.
ErrScriptExhausted means a Fake was asked for more replies than its script holds. var ErrScriptExhausted = errors.New("fake model: script exhausted"). In ch01/agent/fake.go, line 12.
field Message Message
the assistant's message: text, tool calls, or both
the assistant's message: text, tool calls, or both field Message Message. In ch01/agent/types.go, line 58.
var nil Type
nil is a predeclared identifier representing the zero value for a pointer, channel, func, interface, map, or slice type.
nil is a predeclared identifier representing the zero value for a pointer, channel, func, interface, map, or slice type. var nil Type. Documented at pkg.go.dev, builtin.nil.
type Transport struct {
Files fs.FS // saved calls, such as an embedded testdata directory
calls counter
}
Transport is an http.RoundTripper that answers each request with the next saved response for its script, read from Files.
Transport is an http.RoundTripper that answers each request with the next saved response for its script, read from Files. type Transport struct { Files fs.FS // saved calls, such as an embedded testdata directory calls counter }. In ch02/replay/replay.go, line 89.
field Files fs.FS
saved calls, such as an embedded testdata directory
saved calls, such as an embedded testdata directory field Files fs.FS. In ch02/replay/replay.go, line 90.
package fs ("io/fs")
Package fs defines basic interfaces to a file system.
Package fs defines basic interfaces to a file system. package fs ("io/fs"). Documented at pkg.go.dev, io/fs.
type FS interface {
// Open opens the named file.
// [File.Close] must be called to release any associated resources.
//
// When Open returns an error, it should be of type *PathError
// with the Op field set to "open", the Path field set to name,
// and the Err field describing the problem.
//
// Open should reject attempts to open names that do not satisfy
// ValidPath(name), returning a *PathError with Err set to
// ...
}
An FS provides access to a hierarchical file system.
An FS provides access to a hierarchical file system. type FS interface { // Open opens the named file. // [File.Close] must be called to release any associated resources. // // When Open returns an error, it should be of type *PathError // with the Op field set to "open", the Path field set to name, // and the Err field describing the problem. // // Open should reject attempts to open names that do not satisfy // ValidPath(name), returning a *PathError with Err set to // ... }. Documented at pkg.go.dev, io/fs.FS.
type counter struct {
mu sync.Mutex
n map[string]int
}
A counter numbers calls per script.
A counter numbers calls per script. type counter struct { mu sync.Mutex n map[string]int }. In ch02/replay/replay.go, line 69.
func (t *Transport) RoundTrip(
req *http.Request) (*http.Response, error)
RoundTrip serves the next saved response.
RoundTrip serves the next saved response. func (t *Transport) RoundTrip( req *http.Request) (*http.Response, error). In ch02/replay/replay.go, line 95.
var req *http.Request
var req *http.Request. In ch02/replay/replay.go, line 96.
package http ("net/http")
Package http provides HTTP client and server implementations.
Package http provides HTTP client and server implementations. package http ("net/http"). Documented at pkg.go.dev, net/http.
type Request struct {
// Method specifies the HTTP method (GET, POST, PUT, etc.).
// For client requests, an empty string means GET.
Method string
// URL specifies either the URI being requested (for server
// requests) or the URL to access (for client requests).
//
// For server requests, the URL is parsed from the URI
// supplied on the Request-Line as stored in RequestURI. For
// ...
}
A Request represents an HTTP request received by a server or to be sent by a client.
A Request represents an HTTP request received by a server or to be sent by a client. type Request struct { // Method specifies the HTTP method (GET, POST, PUT, etc.). // For client requests, an empty string means GET. Method string // URL specifies either the URI being requested (for server // requests) or the URL to access (for client requests). // // For server requests, the URL is parsed from the URI // supplied on the Request-Line as stored in RequestURI. For // ... }. Documented at pkg.go.dev, net/http.Request.
type Response struct {
Status string // e.g. "200 OK"
StatusCode int // e.g. 200
Proto string // e.g. "HTTP/1.0"
ProtoMajor int // e.g. 1
ProtoMinor int // e.g. 0
// Header maps header keys to values. If the response had multiple
// headers with the same key, they may be concatenated, with comma
// delimiters. (RFC 7230, section 3.2.2 requires that multiple headers
// ...
}
Response represents the response from an HTTP request.
Response represents the response from an HTTP request. type Response struct { Status string // e.g. "200 OK" StatusCode int // e.g. 200 Proto string // e.g. "HTTP/1.0" ProtoMajor int // e.g. 1 ProtoMinor int // e.g. 0 // Header maps header keys to values. If the response had multiple // headers with the same key, they may be concatenated, with comma // delimiters. (RFC 7230, section 3.2.2 requires that multiple headers // ... }. Documented at pkg.go.dev, net/http.Response.
func drain(req *http.Request) ([]byte, error)
drain reads and closes the request body, as the RoundTripper contract requires, and returns what it read.
drain reads and closes the request body, as the RoundTripper contract requires, and returns what it read. func drain(req *http.Request) ([]byte, error). In ch02/replay/replay.go, line 146.
var ctx context.Context
var ctx context.Context. In ch02/replay/replay.go, line 100.
func (r *Request) Context() context.Context
Context returns the request's context.
Context returns the request's context. func (r *Request) Context() context.Context. Documented at pkg.go.dev, net/http.Request.Context.
package context ("context")
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes. package context ("context"). Documented at pkg.go.dev, context.
func Cause(c Context) error
Cause returns a non-nil error explaining why c was canceled.
Cause returns a non-nil error explaining why c was canceled. func Cause(c Context) error. Documented at pkg.go.dev, context.Cause.
package fmt ("fmt")
Package fmt implements formatted I/O with functions analogous to C's printf and scanf.
Package fmt implements formatted I/O with functions analogous to C's printf and scanf. package fmt ("fmt"). Documented at pkg.go.dev, fmt.
func scriptOf(ctx context.Context) string
func scriptOf(ctx context.Context) string. In ch02/replay/replay.go, line 53.
func (c *counter) next(script string) int
next returns the number of this call in script, starting at 1.
next returns the number of this call in script, starting at 1. func (c *counter) next(script string) int. In ch02/replay/replay.go, line 75.
func load(files fs.FS, script string, n int) (recording, error)
load reads the nth saved call of a script.
load reads the nth saved call of a script. func load(files fs.FS, script string, n int) (recording, error). In ch02/replay/replay.go, line 116.
func (rec recording) response(req *http.Request) *http.Response
response rebuilds the saved response as an answer to req.
response rebuilds the saved response as an answer to req. func (rec recording) response(req *http.Request) *http.Response. In ch02/replay/replay.go, line 133.
type Client struct {
// Transport specifies the mechanism by which individual
// HTTP requests are made.
// If nil, DefaultTransport is used.
Transport RoundTripper
// CheckRedirect specifies the policy for handling redirects.
// If CheckRedirect is not nil, the client calls it before
// following an HTTP redirect. The arguments req and via are
// the upcoming request and the requests made already, oldest
// ...
}
A Client is an HTTP client.
A Client is an HTTP client. type Client struct { // Transport specifies the mechanism by which individual // HTTP requests are made. // If nil, DefaultTransport is used. Transport RoundTripper // CheckRedirect specifies the policy for handling redirects. // If CheckRedirect is not nil, the client calls it before // following an HTTP redirect. The arguments req and via are // the upcoming request and the requests made already, oldest // ... }. Documented at pkg.go.dev, net/http.Client.
type RoundTripper interface {
// RoundTrip executes a single HTTP transaction, returning
// a Response for the provided Request.
//
// RoundTrip should not attempt to interpret the response. In
// particular, RoundTrip must return err == nil if it obtained
// a response, regardless of the response's HTTP status code.
// A non-nil err should be reserved for failure to obtain a
// response. Similarly, RoundTrip should not attempt to
// handle higher-level protocol details such as redirects,
// ...
}
RoundTripper is an interface representing the ability to execute a single HTTP transaction, obtaining the [Response] for a given [Request].
RoundTripper is an interface representing the ability to execute a single HTTP transaction, obtaining the [Response] for a given [Request]. type RoundTripper interface { // RoundTrip executes a single HTTP transaction, returning // a Response for the provided Request. // // RoundTrip should not attempt to interpret the response. In // particular, RoundTrip must return err == nil if it obtained // a response, regardless of the response's HTTP status code. // A non-nil err should be reserved for failure to obtain a // response. Similarly, RoundTrip should not attempt to // handle higher-level protocol details such as redirects, // ... }. Documented at pkg.go.dev, net/http.RoundTripper.

