
A scripted agent loop, no model needed
A complete agent loop that fixes a failing test from a script. No key, no network.
On the agent compass The whole loop, all four stagesThis program runs the whole agent loop, with four tools and a small Go project with a bug a test would catch, against a model that is a script.
The script is a copy of what a real model, anthropic/claude-haiku-5.5, replied when it fixed the bug in October 2026, so the run has the shape of a real one while nothing leaves your machine.
It is the smallest complete agent in the companion code, and every later example grows from it.
What it shows
- The loop’s four stages in about 30 lines of Go: assemble a request, send it to the model, execute any tool calls, and choose whether to go around again. The agent loop in Go walks through them.
- A
Modelinterface with one method, which a script satisfies as well as a real client does. - Tools as a definition the model sees plus a Go function it never sees.
- Errors from tools going back to the model as messages, so they never stop the run.
Run it
From the code directory of a clone of go-agents-book-code, with Go 1.27 or later:
$ go run ./ch01
The output, turn by turn:
task: The tests in this project fail. Find out why and fix it.
turn 1
model asks: run_tests {}
model asks: list_files {}
tool result: --- FAIL: TestParse (0.00s) (5 lines)
tool result: duration.go, duration_test.go
turn 2
model asks: read_file {"path": "duration.go"}
model asks: read_file {"path": "duration_test.go"}
tool result: // Package duration parses durations suc... (44 lines)
tool result: package duration (36 lines)
turn 3
model asks: edit_file
path: "duration.go"
old: "'m': time.Second,"
new: "'m': time.Minute,"
model asks: run_tests {}
tool result: edited duration.go
tool result: ok duration 0.002s
turn 4
model says: The tests now pass. The cause was a typo in the unit table in
duration.go: the 'm' (minute) entry mapped to time.Second. So
"45m" parsed as 45 seconds, and "1h30m" parsed as 1h + 30
seconds. I changed it to time.Minute.
Read the middle of each turn as requests: every model asks line is a tool call, and every tool result line is your program doing the work.
In turns 1 to 3 the model asks for two things at once, and the loop runs them in the order asked, which matters in turn 3, where the edit has to land before the tests run.
Turn 4 has no tool calls, so the loop stops.
Nothing touched your disk.
The project lives in an in-memory file system, a map from names to contents, and run_tests is a stand-in that checks for the fixed line; the ch04 example swaps in a real go test.
The script
The replies are plain Go values, built with three small helpers:
// script holds the replies from the run at the start of the chapter,
// recorded from claude-haiku-5.5, so the loop can replay it without a
// model. The model's IDs are shortened, and its text before tool calls
// is left out.
var script = []agent.Message{
agent.Calls(
agent.Call("call_1", "run_tests", `{}`),
agent.Call("call_2", "list_files", `{}`),
),
agent.Calls(
agent.Call("call_3", "read_file", `{"path": "duration.go"}`),
agent.Call("call_4", "read_file",
`{"path": "duration_test.go"}`),
),
agent.Calls(
agent.Call("call_5", "edit_file", `{
"path": "duration.go",
"old": "'m': time.Second,",
"new": "'m': time.Minute,"
}`),
agent.Call("call_6", "run_tests", `{}`),
),
agent.Says("The tests now pass. The cause was a typo in the unit " +
"table in duration.go: the 'm' (minute) entry mapped to " +
"time.Second. So \"45m\" parsed as 45 seconds, and \"1h30m\" " +
"parsed as 1h + 30 seconds. I changed it to time.Minute."),
}
Calls builds a reply that requests tools, Call builds one tool call whose arguments are JSON (the backtick strings, such as {} for “no arguments”, are Go raw strings holding that JSON), for Calls to wrap, and Says builds a reply that only contains text; a reply without tool calls counts as the answer.
To decide which reply comes next, the scripted model counts how many of the model’s own replies (the messages with the assistant role, the ones the model wrote; Messages and roles explains the roles) the conversation already holds. A loop that lost a message or put one in the wrong place would knock the script out of step, and the tests would fail.
Run the tests
$ go test ./ch01/...
Each test in ch01/agent pins down a single rule of the loop.
An answer ends the run, and so does reaching the turn limit.
Each tool call is answered by exactly one tool message, even when one reply holds several calls.
A tool that fails sends its error back flagged as an error, and a call to a tool that doesn’t exist gets an error naming the tools that do exist.
The whole suite finishes in milliseconds without touching the network, and that is why the loop is written before it is connected to a real model.
Things to try
Each of these is a change of a line or two; run go run ./ch01 after it.
Misspell a tool. In script.go, change the tool name in call_3, the read_file call in turn 2, to read_files.
Turn 2 now prints a tool error whose text starts with no tool named "read_files" (the printer cuts long results short, so the list of real tools is cut off on screen), and the run keeps going, because the loop hands the error back to the model.
With a real model, the next reply would usually correct the name.
Lower the turn limit. In main.go, set MaxTurns to 3.
The run prints three turns, then ends with run agent: agent: max turns reached.
Run still returns the conversation so far, which is how the program prints those three turns.
Cancel before it starts. In main.go, the run function starts with func run(ctx context.Context, w io.Writer) error {.
Add two lines directly after that one:
ctx, cancel := context.WithTimeout(ctx, 0) // a deadline of zero seconds
defer cancel()
WithTimeout gives back a copy of ctx that is cancelled after the given time, and zero means the deadline has already passed.
Run checks ctx at the top of every turn, so it stops before the first model call.
The program ends with run agent: run: context deadline exceeded.
In code, errors.Is(err, context.DeadlineExceeded) is how you ask whether that is the reason the error occurred, even when other errors have wrapped it.
When you are done experimenting, undo your edits from the code directory with git restore . (or git checkout -- .).
Key files
| File | What it holds |
|---|---|
ch01/agent/types.go |
Model, Request, Message, ToolDef, ToolCall, Tool, Limits, Result |
ch01/agent/loop.go |
Run, the loop, and runTool |
ch01/agent/fake.go |
The scripted model and its helpers |
ch01/agent/tools.go |
read_file, list_files, edit_file, run_tests, and the argument decoder |
ch01/agent/memfs.go |
The in-memory project |
ch01/main.go, ch01/script.go |
The program: Ctrl-C handling, the task, and the script |
ch01/testdata/duration |
The duration package with its bug |
Next
A real agent that fixes a failing test runs the same Run against a real model’s recorded replies, with a real go test behind run_tests.
var script = []agent.Message{ ...
script holds the replies from the run at the start of the chapter, recorded from claude-haiku-5.5, so the loop can replay it without a model.
script holds the replies from the run at the start of the chapter, recorded from claude-haiku-5.5, so the loop can replay it without a model. var script = []agent.Message{ .... In ch01/script.go, line 11.
package agent ("github.com/blackwell-systems/go-agents-book/code/ch01/agent")
Package agent is the agent loop and the types it works with.
Package agent is the agent loop and the types it works with. package agent ("github.com/blackwell-systems/go-agents-book/code/ch01/agent"). In ch01/agent.
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 Calls(calls ...ToolCall) Message
Calls is a scripted reply that calls tools.
Calls is a scripted reply that calls tools. func Calls(calls ...ToolCall) Message. In ch01/agent/fake.go, line 48.
func Call(id, name, args string) ToolCall
Call is one scripted tool call; args is JSON.
Call is one scripted tool call; args is JSON. func Call(id, name, args string) ToolCall. In ch01/agent/fake.go, line 53.
func Says(text string) Message
Says is a scripted reply with text and no tool calls: an answer.
Says is a scripted reply with text and no tool calls: an answer. func Says(text string) Message. In ch01/agent/fake.go, line 43.

