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.
- 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.
- Turn 2: it reads duration.go, 44 lines, and duration_test.go, 36 lines.
- 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.
- 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.
anthropic/claude-haiku-5.5, replayedThe 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
- Build the request
Decide what the model sees: instructions, the conversation so far, tool results, and the tools it may call.
- Call the model
Send the request and read the reply, with a deadline and a count of what it cost.
- Run the tools
Carry out the calls the model asked for, and add each result to the conversation.
- Decide
Stop with an answer, stop at a limit, or go around again.
- What each call sends
- Call 1 sent the tool list and 1 message: 583 tokens.
- Call 2 sent the tool list and 4 messages, 3 of them new: 834 tokens.
- Call 3 sent the tool list and 7 messages, 3 of them new: 1,846 tokens.
- Call 4 sent the tool list and 10 messages, 3 of them new: 2,164 tokens.
- In all, the four calls sent 5,427 tokens.
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:
// 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:
// 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:
// 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:
$ 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.
-
Basics
How AI agents work, from the ground up: what an agent is, the loop at its center, calling a model from Go, tool calling, what each turn costs, and how a model picks its next token.
-
Go in depth
The Go an AI agent leans on, one page each, from interfaces and generics, context.Context, and error handling to JSON v2, the HTTP client, streams, goroutines, iterators, and running commands, each tied to the agent code it comes from.
-
Build
Designing an agent once the loop runs: its shape, its tools, its replies, its context, and what it knows.
-
Production
What an agent needs before you leave it running: clear stop reasons, safe retries, traces, offline tests, evals, injection defenses, approval, credentials scoped to one user and one run, runs that survive a crash, and running it as a service.
-
Go ecosystem
Why Go for agents, model APIs and official SDKs, how providers differ, and the libraries and Go agent frameworks you can adopt, each placed against the part of a harness you can write yourself.
-
Examples
Runnable Go programs from the free, open-source companion code of Building AI Agents in Go, one for each chapter plus a few extras, each with what it shows and the command that runs it offline.
-
Research
Measured results from the book’s recorded runs, each with its method, its sample size, and what it can’t show.
Common questions
Each links to the guide that answers it, with Go code you can run.
- What do I need to get started?Go 1.27, the companion code, and examples that run with no API key.
- What is an AI agent, and how is it different from a chatbot?A program where the model picks each next step and your Go code carries it out.
- How do I make my first LLM API call?An API key, one request with curl, and every part of the reply, including its cost.
- What are messages, roles, and the system prompt?The four roles in a conversation, and how to write instructions for an agent.
- How does tool calling work?The JSON a tool call is made of, and how a Go client sends and reads it.
- How do I build my first agent in Go?A complete agent in a few short files of standard-library Go, start to finish.
- Which model should I use for an agent?Tool support, cost per finished task, reasoning models, and local models.
- Should I use a Go agent framework?ADK, Eino, Genkit, LangChainGo, and trpc-agent-go, set against the parts of a harness.
type Model interface {
Generate(ctx context.Context, req Request) (Reply, error)
}
Model is anything that can produce the next reply in a conversation: the scripted fake in this chapter, a real model from chapter 2.
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) }. In ch01/agent/types.go, line 13.
func (Model) Generate(ctx context.Context, req Request) (Reply, error)
func (Model) Generate(ctx context.Context, req Request) (Reply, error). In ch01/agent/types.go, line 14.
var ctx context.Context
var ctx context.Context. In ch01/agent/types.go, line 14.
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.
func Run(ctx context.Context, m Model, tools []Tool,
msgs []Message, lim Limits) (Result, error)
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.
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. func Run(ctx context.Context, m Model, tools []Tool, msgs []Message, lim Limits) (Result, error). In ch01/agent/loop.go, line 22.
var ctx context.Context
var ctx context.Context. In ch01/agent/loop.go, line 22.
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 Tool struct {
Def ToolDef
Run func(ctx context.Context, args jsontext.Value) (string, error)
}
Tool is the harness's side of a tool: the definition the model sees, and the Go function that runs it.
Tool is the harness's side of a tool: the definition the model sees, and the Go function that runs it. type Tool struct { Def ToolDef Run func(ctx context.Context, args jsontext.Value) (string, error) }. In ch01/agent/types.go, line 65.
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.
type Limits struct {
MaxTurns int
}
Limits holds the settings that bound a run.
Limits holds the settings that bound a run. type Limits struct { MaxTurns int }. In ch01/agent/types.go, line 75.
type Result struct {
Messages []Message
}
Result is what a run produced, whether or not it ended in an error.
Result is what a run produced, whether or not it ended in an error. type Result struct { Messages []Message }. In ch01/agent/types.go, line 80.
var byName map[string]Tool
var byName map[string]Tool. In ch01/agent/loop.go, line 24.
func index(tools []Tool) ([]ToolDef, map[string]Tool)
index splits tools into the definitions the model sees and the tools the harness looks up by name.
index splits tools into the definitions the model sees and the tools the harness looks up by name. func index(tools []Tool) ([]ToolDef, map[string]Tool). In ch01/agent/loop.go, line 52.
package slices ("slices")
Package slices defines various functions useful with slices of any type.
Package slices defines various functions useful with slices of any type. package slices ("slices"). Documented at pkg.go.dev, slices.
func Clone[S ~[]E, E any](s S) S
Clone returns a copy of the slice.
Clone returns a copy of the slice. func Clone[S ~[]E, E any](s S) S. Documented at pkg.go.dev, slices.Clone.
func (Context) Err() error
If Done is not yet closed, Err returns nil.
If Done is not yet closed, Err returns nil. func (Context) Err() error. Documented at pkg.go.dev, context.Context.Err.
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.
field Messages []Message
field Messages []Message. In ch01/agent/types.go, line 81.
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.
field Messages []Message
field Messages []Message. In ch01/agent/types.go, line 23.
func append(slice []Type, elems ...Type) []Type
The append built-in function appends elements to the end of a slice.
The append built-in function appends elements to the end of a slice. func append(slice []Type, elems ...Type) []Type. Documented at pkg.go.dev, builtin.append.
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.
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.
field ToolCalls []ToolCall
set on assistant messages that call tools
set on assistant messages that call tools field ToolCalls []ToolCall. In ch01/agent/types.go, line 31.
func runTool(ctx context.Context, byName map[string]Tool,
call ToolCall) Message
runTool runs one tool call and returns the tool message that answers it.
runTool runs one tool call and returns the tool message that answers it. func runTool(ctx context.Context, byName map[string]Tool, call ToolCall) Message. In ch01/agent/loop.go, line 69.
var ErrMaxTurns = errors.New("agent: max turns reached")
ErrMaxTurns means the run stopped because it reached Limits.MaxTurns without an answer.
ErrMaxTurns means the run stopped because it reached Limits.MaxTurns without an answer. var ErrMaxTurns = errors.New("agent: max turns reached"). In ch01/agent/loop.go, line 14.
type ToolDef struct {
Name string
Description string
Parameters jsontext.Value // a JSON Schema
}
ToolDef describes a tool to the model.
ToolDef describes a tool to the model. type ToolDef struct { Name string Description string Parameters jsontext.Value // a JSON Schema }. In ch01/agent/types.go, line 41.
type string string
string is the set of all strings of 8-bit bytes, conventionally but not necessarily representing UTF-8-encoded text.
string is the set of all strings of 8-bit bytes, conventionally but not necessarily representing UTF-8-encoded text. type string string. Documented at pkg.go.dev, builtin.string.
func make(t Type, size ...IntegerType) Type
The make built-in function allocates and initializes an object of type slice, map, or chan (only).
The make built-in function allocates and initializes an object of type slice, map, or chan (only). func make(t Type, size ...IntegerType) Type. Documented at pkg.go.dev, builtin.make.
var byName map[string]Tool
var byName map[string]Tool. In ch01/agent/loop.go, line 54.
func panic(v any)
The panic built-in function stops normal execution of the current goroutine.
The panic built-in function stops normal execution of the current goroutine. func panic(v any). Documented at pkg.go.dev, builtin.panic.
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.
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.

