AI Agents in Go

Learn how AI agents work at the level of every request, reply, and tool call, by building one step by step with Go’s standard library.

For Go developers new to language models. You should be comfortable writing Go: the code uses Go 1.27, with generics and encoding/json/v2.

  • 66 free guides
  • 26 runnable programs
  • 8 experiments
  • no API key needed

The task: The tests in this project fail. Find out why and fix it.

  1. Turn 1: the model calls run_tests, which fails with Parse("45m") = 45s, want 45m0s, and list_files, which lists duration.go and duration_test.go.
  2. Turn 2: it reads duration.go, 44 lines, and duration_test.go, 36 lines.
  3. Turn 3: it says the bug is in the unit table: 'm' is mapped to time.Second instead of time.Minute. It edits duration.go to map 'm' to time.Minute, and run_tests passes.
  4. Turn 4: it answers that the tests now pass, and that the cause was a typo in the unit table in duration.go: the 'm' (minute) entry mapped to time.Second.

In all, 4 model calls, 5427 tokens in, 569 out, $0.0008.

A recorded run of anthropic/claude-haiku-5.5, replayed

The agent compass

An agent is a model (a large language model, reached through an API) inside a harness, the program around it. On every turn the harness passes through the same four stages. Drawn as a ring, they make the agent compass, the model this whole site is built on:

The agent compass

  1. Build the request

    Decide what the model sees: instructions, the conversation so far, tool results, and the tools it may call.

  2. Call the model

    Send the request and read the reply, with a deadline and a count of what it cost.

  3. Run the tools

    Carry out the calls the model asked for, and add each result to the conversation.

  4. Decide

    Stop with an answer, stop at a limit, or go around again.

  1. What each call sends
  2. Call 1 sent the tool list and 1 message: 583 tokens.
  3. Call 2 sent the tool list and 4 messages, 3 of them new: 834 tokens.
  4. Call 3 sent the tool list and 7 messages, 3 of them new: 1,846 tokens.
  5. Call 4 sent the tool list and 10 messages, 3 of them new: 2,164 tokens.
  6. In all, the four calls sent 5,427 tokens.

Every call sends the tool list and the whole conversation again: everything the call before it sent, plus the messages added since.

Then back to stage 1, with everything that just happened in the conversation.

However large an agent grows, every turn it takes passes through these four stages, so the compass is the map for understanding an agent and for reading this site: each guide works on one stage or on the whole loop, and shows its place on the compass under its title. You can browse every guide by stage, for example the Decide guides. When an agent misbehaves, the compass tells you where to look: one that never stops has a Decide problem, and one that forgets what it read has a Build-the-request problem.

The whole loop, in code

You don’t need to follow this code yet; the Start path walks through it step by step. The loop talks to the model through one small interface:

ch01/agent/types.go
// Model is anything that can produce the next reply in a conversation:
// the scripted fake in this chapter, a real model from chapter 2.
type Model interface {
	Generate(ctx context.Context, req Request) (Reply, error)
}

Anything with a Generate method is a Model: a scripted list of replies for tests, or a client for a real model’s API. The loop calls m.Generate once per turn and never needs to know which one it has. Here is the loop as the companion code writes it, each line marked with its stage’s number and color from the ring above:

ch01/agent/loop.go
// Run runs the agent loop: it sends the conversation to the model, runs
// any tools the model asks for, and repeats until the model answers
// without calling a tool, the turn limit is reached, or ctx is done. It
// returns the conversation so far even when it returns an error.
func Run(ctx context.Context, m Model, tools []Tool,
	msgs []Message, lim Limits) (Result, error) {
	defs, byName := index(tools)
	msgs = slices.Clone(msgs)
	for range lim.MaxTurns {
		if err := ctx.Err(); err != nil {
			return Result{Messages: msgs}, fmt.Errorf("run: %w", err)
		}
		req := Request{Messages: msgs, Tools: defs}
		reply, err := m.Generate(ctx, req)
		if err != nil {
			err = fmt.Errorf("generate: %w", err)
			return Result{Messages: msgs}, err
		}
		msgs = append(msgs, reply.Message)
		if len(reply.Message.ToolCalls) == 0 {
			return Result{Messages: msgs}, nil
		}
		for _, call := range reply.Message.ToolCalls {
			msgs = append(msgs, runTool(ctx, byName, call))
		}
	}
	return Result{Messages: msgs}, ErrMaxTurns
}

Its first line calls index, which splits the tools in two: defs, the definitions that go to the model in every request, and byName, which the loop uses to find the Go code for the tool a call names:

ch01/agent/loop.go
// index splits tools into the definitions the model sees and the tools
// the harness looks up by name. Two tools with one name is a mistake in
// the program, not something to recover from, so it panics.
func index(tools []Tool) ([]ToolDef, map[string]Tool) {
	defs := make([]ToolDef, len(tools))
	byName := make(map[string]Tool, len(tools))
	for i, t := range tools {
		if _, dup := byName[t.Def.Name]; dup {
			panic("agent: two tools named " + t.Def.Name)
		}
		defs[i] = t.Def
		byName[t.Def.Name] = t
	}
	return defs, byName
}

The other names are plain types and helpers: a Message is one entry in the conversation, a Request is the messages and tool definitions for one call, Limits holds settings such as MaxTurns, a Result holds the conversation a run ends with, runTool runs one call and turns its output (or its error) into a message for the model, and ErrMaxTurns is the error a run returns when it hits the turn limit.

The loop sends the whole conversation on every call, because the model keeps nothing between calls. It appends the model’s reply to the conversation before running its tools, so each tool result is paired with a tool call the conversation already holds. It stops on an answer, at the turn limit, or when ctx is cancelled. The agent loop in Go explains each line.

Run it with no model at all, from a scripted list of replies:

terminal
$ git clone https://github.com/blackwell-systems/go-agents-book-code
$ cd go-agents-book-code/code
$ go run ./ch01

The output replays a real model’s fix of a failing test, turn by turn. You will see counts of tokens in it; a token is the unit of text a model reads and writes, roughly a short word or a piece of a longer one. Then go run ./ch04 runs the same loop against a real model’s recorded replies, with a real go test behind its run_tests tool. Both need Go 1.27 or later and no API key. New to Go? Finish the Tour of Go first; Getting set up lists what to brush up on. The repository holds 1,664 Go files and 2,746 test functions, and none of them calls a model; Examples lists every program in the repository.

Four ways in

  • Learning how agents work

    For a Go developer who has never built an agent: set up, make a first model call, build an agent from scratch, then learn what it costs, how to design its tools, and how to test it.

    It starts with Getting set up.

  • Shipping an agent at work

    For an engineer who knows the loop and has a deadline: decide between a workflow and an agent, then work down the launch checklist, one guide per item.

    It starts with Workflow or agent?.

  • Leading a team

    For whoever decides whether a team spends its time here: what the work costs, what the team ends up able to build, the risks and how they're handled, and what's left out, mostly without code.

    It starts with For leads.

  • The Go underneath

    For a Go developer who knows the language from the Tour and wants the parts an agent depends on: interfaces and generics, cancellation, errors, JSON, HTTP, streams, concurrency, and files, each shown in tested agent code.

    It starts with Interfaces and generics.

Where to go next

66 guides in 7 sections.

Common questions

Each links to the guide that answers it, with Go code you can run.

The book

Building AI Agents in Go builds the agent this site describes, one chapter at a time, from the first request to production: 17 chapters and 786 pages, standard library first, every example runnable offline.

The PDF in five reading themes, the EPUB, and the companion code, for one permanent price with every update of this edition free.

More about the book

Book 2 · in progress, about 50% complete Running Go Agents in Production starts where this one ends, with what a company needs before it lets agents act for its people: identity, approval, audit, budgets, and a way to stop them.