Reference

Search

Search every guide, the glossary, and the site’s other pages by title, description, and heading.

Every page

Basics

  • Getting set upWhat you need before the first example runs. Go 1.27, the companion code and how it is laid out, the switch between offline replays and a live model, and the newer Go features the code relies on.
  • What an agent isAn agent is a program where the model picks each next step and your Go code carries it out. This page follows one agent through a failing test, compares it with chatbots and workflows, and lists the parts you write.
  • The agent loopAn agent is a model inside a loop, and the loop is plain Go. This page reads the whole loop, about 30 lines, stage by stage, along with the rules that keep it correct.
  • Your first model callBefore an agent, one call. Create an OpenRouter account and API key, send a single request with curl, and read every part of the reply that comes back, from the answer itself to what it cost.
  • Messages and rolesA conversation with a model is an ordered list of messages, each with a role. What system, user, assistant, and tool messages are for and who writes each, the Go type that holds them, and how to write a system prompt for an agent, with a real one taken apart.
  • Calling a model from GoUnder two hundred lines of standard-library Go make a client for an OpenAI-compatible chat completions API, with a per-call deadline that records its cause, errors checked in every place they can appear, and the finish reason passed back to the caller.
  • Common first errorsThe errors a first agent usually runs into, what each one looks like, and the fix. A missing key, no credit, a bad model ID, rate limits and server errors, a reply cut off partway, a reasoning model that spent its whole reply thinking, and two Go traps.
  • Tool calling on the wireWhat a tool call looks like as JSON on an OpenAI-compatible chat completions API, how a Go client sends tool definitions and reads calls back, and the rules that keep a conversation valid.
  • Tokens, cost, and contextAn agent’s requests grow with every turn. This page shows that growth in recorded numbers, what a run costs, which tokens you pay for before the model reads the task, and why the size of the context window is a poor planning target.
  • How models pick the next tokenA language model gives every possible next token a probability and picks one. A toy model in Go shows why answers vary, why temperature matters, why fluent text can be false, why code costs more tokens than English, and why a tool call is text the model writes.
  • Choosing a modelWhat an agent needs from a model, how to read a model ID, why the price per token misleads and the cost per finished task doesn’t, what reasoning models add and cost, when a local model makes sense, and how to compare candidates on your own task.

Go in depth

  • Interfaces and genericsHow a Go agent’s parts fit together with interfaces and generics. A one-method Model interface with four implementations, interfaces declared where they are used, adapters between a whole reply and a stream, a function type that satisfies an interface, wrappers for retries and tracing, a slice type that is a policy, optional behavior found with a type assertion, compile-time checks, and generic tools whose schema comes from a struct.
  • context.Context in an agentHow context.Context works and how an AI agent in Go uses it. The interface and the tree of contexts, stopping a run on Ctrl-C, waiting on ctx.Done in your own code, a deadline for each model call, saying why a run stopped with WithTimeoutCause and context.Cause, cancelling the commands tools start, an idle timer on a stream, work that must finish with WithoutCancel, testing timeouts with synctest, and the common mistakes.
  • Errors in an agentError handling in an AI agent written in Go. Wrapping with what each function was doing, sentinel errors grouped into families, error types that carry data and behavior, errors.AsType, errors.Join, the errors a model reads and fixes versus the ones that stop the run, panics recovered at the tool boundary, and the common mistakes.
  • JSON v2 for model APIsUsing Go’s encoding/json/v2 and jsontext for model APIs and tool calls. Why switch, with a benchmark, what changed from encoding/json, each behavior checked in Go 1.27, wire types with omitzero and jsontext.Value, invalid UTF-8 from tools, strict tool arguments, a field with two shapes, key order, deterministic output, and options for saving a run.
  • An HTTP client for model APIsThe net/http details that a model API client in Go gets right or wrong. One shared client, why the deadline belongs on the context and not on http.Client.Timeout, reading replies with a size limit, errors inside a 200, API errors with Retry-After, connection reuse, and RoundTrippers for tests and fault injection.
  • Streams in GoHow to read and write a stream in Go, for an agent that streams a model’s reply. What io.Reader promises, reading lines with bufio.Scanner and its size limit, the server-sent events format and the [DONE] marker, a reader that turns a stream into an iterator, stopping a stream with the context and an idle timeout, writing a stream from a server with http.Flusher and http.ResponseController, and the mistakes.
  • Goroutines with an ownerConcurrency in a Go agent, with every goroutine owned and stoppable. sync.WaitGroup.Go, merging several agent runs into one stream without leaking a goroutine, requests in flight with their cancel functions behind a mutex, shutting down in order, limiting how much runs at once, and finding leaks with the race detector and the goroutine leak profile.
  • Iterators in an agentHow range-over-func iterators fit an AI agent in Go. What iter.Seq and iter.Seq2 are, how yield and break work, writing an iterator that adapts a whole reply into a stream, consuming a stream of values and errors, wrapping one as middleware with cleanup in a defer, stopping a run by breaking out of the loop, and the mistakes, from the runtime panic to an iterator ranged twice.
  • Commands and filesHow an AI agent’s tools in Go run commands and touch files. exec.CommandContext and what cancelling does, WaitDelay for pipes a child holds open, killing a whole process group on Unix, combined output with a size cap, a non-zero exit as a result the model reads, an environment built from scratch so keys never reach test code, os.Root for file tools that can’t leave the workspace, and what none of it protects against.

Build

  • Build your first agentA complete agent in standard-library Go, in a handful of short files. The message types, a client for a chat completions API, the loop, two tools confined to one directory, and a system prompt; run it offline from a recorded run, then live on your own files.
  • Workflow or agent?Programs that call a model come in five main shapes, from a fixed sequence of calls to several cooperating agents. Pick the simplest one that handles the task, go further only when the task forces you to, and mix shapes when a task has a routine part and an open-ended part.
  • Patterns by nameThe names people use for agent designs come from a handful of sources, among them Anthropic’s “Building effective agents”, the ReAct and Reflexion papers, Andrew Ng’s four design patterns, and OpenAI’s guide to building agents. This page maps each name to the Go code and the measured runs on this site that implement it, and says plainly which ones the site doesn’t build.
  • Designing toolsThe caller of an agent’s tools reads a name, a description, and a schema, and never your code. This page covers task-shaped tools, short results, schemas generated from Go structs, strict argument checks, useful errors, and a cheap test of tool choice.
  • Streaming repliesA streamed chat completion arrives as server-sent events. This page reads one with a bufio.Scanner and an iterator, reassembles tool calls from their fragments, and stops a stream that stops sending.
  • Structured outputIf a program reads an agent’s answer, prose is a poor format, since a parser breaks the first time the wording changes. A final tool, whose arguments are the answer, gives you a typed result from any tool-calling model and a place to check the answer before you accept it.
  • Context managementEach turn, an agent resends everything so far, so long runs get expensive and then hard for the model to follow. This page shows five context policies in Go (prompt caching, clearing old tool results, trimming turns, compaction, and notes) and what each did on a 99-report batch.
  • Parallel tool callsA single model reply often requests several tools. This page covers which of those calls can safely overlap, a runner built on sync.WaitGroup.Go and a semaphore that bounds concurrency, and per-call slots that return answers in the model’s order, and why the time it saves on a coding agent is measured in milliseconds.
  • Sub-agentsA sub-agent is your agent loop run again from inside a tool, with an empty history, to answer one self-contained question. This page covers building one in Go, reporting one that ran out of turns, limiting nesting to one level, and a measured case where it didn’t pay off.
  • MCP in GoThe Model Context Protocol lets any agent use tools a separate program offers. What the protocol is on the wire, how a Go client matches responses to calls and stops a server in the order the protocol asks, what the extra process costs, how much to trust another program’s tools, and when to use the official Go SDK.
  • RAG in GoAnswer questions from your own documents by finding the passages that match a question and sending them to the model with it. Chunking by heading, embeddings through OpenRouter, an in-memory vector search with cosine similarity, and the prompt, in standard-library Go, measured on 16 questions.
  • RAG or agentic search?Three ways to answer questions from a set of documents, each asked the same 16 questions. One-shot RAG, retrieval as a tool in an agent loop, and an agent that lists and reads the files itself. All three answered every question; what differed was the cost, the calls, and the tokens, and why.
  • Memory between sessionsGive an agent a memory across conversations in standard-library Go. Short notes it saves with a tool and replaces when facts change, recalled into the prompt by meaning, with limits on what it may save. Measured over eight sessions against no memory and against carrying the whole conversation.

Production

  • Why the agent stoppedA production agent loop names every way a run can end. API errors become a type that says whether to retry, sentinels form a tree checked with errors.Is, a dollar budget is checked before each call, replies are checked before they are kept, and cancellation still answers every tool call.
  • Retries and observabilityWhich failures deserve a retry and which never do, full-jitter backoff measured against plain backoff, a retry budget and circuit breaker shared across agents, tool retries limited to tools that are safe to repeat, and logs and OpenTelemetry GenAI spans that show where a run’s time and money went.
  • Testing an agent offlineAn agent’s tests should never call a live model. Use a scripted model for the loop’s rules, an http.RoundTripper that replays recorded API calls for the client and tools, hand-written fixtures for failures you can’t trigger, outcome checks in place of transcript checks, and testing/synctest for timeouts.
  • Evals for an agentHow to tell whether an agent is good, and whether a change improved it. A tiered eval set, graders written as code with hidden tests, unscored runs kept out of the pass rate, rates reported with ranges, task-by-task comparisons, and the places a model reviewer and a model judge fit.
  • Prompt injection and sandboxingAn agent that reads strangers’ text, holds keys, edits code, and sends text out is an attractive target. A one-page threat model, a ladder of sandboxes for the code the agent runs, and five layers of defense from strongest to weakest, with what 237 measured runs could and couldn’t show.
  • Human approvalHow to put a person in front of an agent’s risky calls. A gate in tool middleware that the model can’t route around, raw evidence shown safely, a yes tied to a hash of exactly what was shown, denials that hold for the whole run, runs that pause and resume instead of blocking, and an audit log that reveals edits.
  • Agent identityEvery action an agent takes involves three identities, the user it acts for, the agent as software, and the run. How to give an agent narrow, short-lived credentials the model never sees, keep permission in the tools, give sub-agents less than their parent, and record who did what, with Go code you can run.
  • Durable runsHow to make an agent survive a crash without losing its work or doing it twice. What to save, the five moments to save it, a checkpoint write that a crash can’t tear, a lock and a restart limit, resuming by phase, and idempotency keys, attempt markers, and a three-step ladder for calls whose outcome nobody recorded.
  • OAuth and OIDCHow an agent service that people use from a browser signs them in with OpenID Connect and acts for them at other services, in tested Go. Authorization code with PKCE, state, and nonce; ID token checks go-oidc leaves to you; tokens kept server-side behind a session cookie (RFC 10017); each user’s refresh tokens encrypted and bound to them; one refresh at a time under rotation (RFC 9700); revocation on disconnect (RFC 7009); and the settings that matter with Okta.
  • MCP authorizationHow to put an MCP server behind OAuth 2.1 and connect a client to it, following the MCP authorization specification of 2026-07-28, in tested Go with the official MCP Go SDK. Protected Resource Metadata (RFC 9728), PKCE, the resource parameter (RFC 8707), the iss check (RFC 9207), Client ID Metadata Documents, JWT access token validation (RFC 9068), per-tool scopes with step-up, and why a token issued for one server is refused by every other.
  • Agent gatewaysHow to put an MCP gateway between your agents and the MCP servers they use, in tested Go with the official MCP Go SDK. A default-deny policy on every tool call by user, agent, and tool; only approved tools published, with definitions pinned by digest; OAuth token exchange (RFC 8693) so no upstream sees the agent’s token; a tamper-evident audit log; and revocation that cancels calls in flight.
  • An agent as a serviceWhat changes when nobody is watching the agent. A static binary that picks up its own unfinished runs, a shutdown that cancels and saves inside the platform’s grace period, a container that keeps the key out of every environment, and a service that takes crash reports over HTTP, queues work in a directory, keeps its spending on disk, and parks decisions in a review queue.
  • Launch checklistTwenty-four checks for an agent that will run unattended and spend money, grouped by what can go wrong, each with the guide that covers it and, where a recorded run measured one, the failure that shows why it matters.

Go ecosystem

  • Why GoAn agent spends most of its time waiting on a network, running work side by side, and deciding when to stop. Where Go fits that job, from its standard library and build speed to the infrastructure written in it, with numbers from recorded runs, and what Go costs you here.
  • Providers and SDKsHow to run one agent loop against providers whose APIs disagree on almost everything. An official SDK wrapped in your own interface with its retries off and its errors translated, a hand-written client for Anthropic’s Messages API, reasoning that has to return to the provider and host that produced it, and one task run through three clients.
  • How two provider APIs differThe same agent request, sent as OpenAI-style chat completions through OpenRouter and as Anthropic’s Messages API, differs in twelve places, from where the system prompt goes to how a stream ends. A table of each difference, with the chapter and the code that handles it.
  • More providersA reference for writing a third adapter. How the native APIs of Google’s Gemini, Ollama, Amazon Bedrock, and Cohere carry the system prompt, tool calls, tool results, stop reasons, and usage, whether each offers an OpenAI-compatible endpoint, and its official Go library, from each provider’s documentation as of October 18, 2026.
  • Libraries and SDKsThe provider SDKs, the MCP SDK, OpenTelemetry, and the five Go agent frameworks that the book’s code imports or measures, each with its pinned version, what it does well, what it costs, and the part of a harness it stands in for.
  • Go agent frameworks comparedFive Go agent frameworks set against the parts of an agent harness, as their source stood in October 2026, plus one approval-gated task ported to Eino and Genkit, what the code measured, and eight questions to put to any framework.

Examples

  • ch01: A scripted agent loopRun a complete agent loop that fixes a failing Go test, driven by a script of replies recorded from a real model. No API key and no network, with tests that run in milliseconds.
  • ch04: A real agent fixes a failing testThe same 30-line loop, now driven by a real model’s recorded replies, with tools that run go test for real on your machine. Replay two models’ different paths to the same fix, and a run that recovers from three bad tool calls.
  • ch07: Four crash reports, triagedThe crash-triage agent’s first run on a small Go web service, replayed offline. Four crash reports, two already filed, one bug that lives away from the line that crashed; fourteen tools, a final answer in a fixed shape, and a grade from the crash catalog.
  • Streaming to a browserA server written with net/http alone sends an agent’s events, as they happen, to a page that reads them with EventSource. The headers, the flush, a deadline per write, a heartbeat, a client that leaves, and a shutdown that ends open streams, from a tested example.
  • ch10: Filing issues over MCPThe crash-triage agent reaching its issue tracker only through the Model Context Protocol, with the server started as a separate process. Replay the run offline, serve the tracker to any MCP client, and pin the server’s tool definitions so a changed description stops the run.
  • ch16: One task, three implementationsThe same approval-gated diagnosis written on the book’s agent package, on Eino, and on Genkit, run against the same scripted replies through a transport that records every request. Run the comparison, time a cancellation during a retry, and read what each version sends.

Research

  • The finished agentThe crash-triage agent the book ends with, measured on 20 held-out tasks with three models. Pass rates with their ranges, the cost of each passing run, how the failed runs went wrong, and how to point the agent at a Go service of your own.
  • Measured mistakesEvery failure on this page happened in a recorded run of the book’s code, and each comes with its task, its models, how many runs it rests on, the date, and the chapter. What went wrong, how often, and what the code changed because of it.
  • One sentence decided 79 of 80 first movesA sentence added to an MCP tool’s description, a tool the model hadn’t called yet, steered the first move of four models in 79 of 80 replies. A label marking the text as the server’s cut that to 57. What was tested, what it can’t show, and the defenses that work upstream of the model.
  • How a tool error’s wording changed the turnsChapter 4 made a tool fail on every call and changed only the wording of its error. Told “the file is locked”, three of four models kept retrying and hunting for ways around the lock; told that retrying couldn’t help, every model stopped after one attempt.
  • Workflow or agent, measuredChapter 1 fixed one Go bug on four models in two ways, as a three-step workflow written in code and as an agent that picks its own steps. The workflow was cheaper and faster on every model, and its single failure shows what it trades away.
  • Fan-out, measuredChapter 9 triaged a batch of 99 crash reports two ways, with one agent per cause running four at a time and with a single agent over the whole batch. The fan-out took about as long and cost more, though its cost was steadier and its requests stayed small.
  • Two identical runs, 15 points apartChapter 13 ran the same agent twice on each of 20 tasks and scored the second run against the first, as though one were a new version. The second came out 15 points ahead, with nothing changed. How to tell a real improvement from that, with ranges, paired comparisons, and counts.
  • 910 crashes, no duplicatesChapter 15 crashed the agent’s run at every point a crash could land, restarted it, and counted duplicate issues. Saving once per turn duplicated work at 8 of its 18 crash points; idempotency keys removed every duplicate, and attempt markers without keys did too, at the price of 669 questions to a person.

Other pages

  • Beyond crash triageThe book’s agent triages crashes in a Go service, and its parts carry over to agents with other jobs. A support-ticket resolver, a SQL analyst, and a research assistant, each with the shape it needs, what goes wrong without the right parts, and how to measure it.
  • The bookLearn how AI agents work by building one in Go, from the first request to production, using the standard library. A book for Go developers, with every example runnable offline.
  • BooksTwo books on AI agents in Go by Dayna Blackwell. Building AI Agents in Go builds one agent from the first request to production; Running Go Agents in Production, in progress, runs agents for a company.
  • Running Go Agents in ProductionThe second book, in progress. Run Go agents for a company: every call says who it acts for, rules decide what an agent may do, and cost, state, and changes stay bounded as the platform grows.
  • For leadsA short page for whoever approves a team’s time on AI agents in Go. What live runs cost, what the team ends up able to build, the risks and how the material handles each one, what it leaves out, and how to get a team started.
  • GlossaryThe vocabulary of building AI agents, from agent and harness to idempotency key and tool poisoning, each in a sentence or two, with a link to the guide that covers it.
  • All guidesEvery guide on the site in one list, grouped by section, with each guide’s loop stage and skill level, and a filter that shows only the guides for one stage of the loop.
  • What this coversThe ground this site and Building AI Agents in Go cover, the topics the site covers beyond the book, such as retrieval and memory between sessions, the topics both leave out on purpose, such as multi-agent planning, and why, so you can tell before reading whether they answer your question.
  • Start hereFour reading paths through the site, each an ordered list of guides, for learning how agents work, for shipping one at work, for leading a team that builds them, and for the Go an agent depends on.
  • Work with meDayna Blackwell of Blackwell Systems helps teams build, review, measure, and run AI agents in Go. Architecture and production reviews, eval design, AI cost optimization, hands-on team workshops, and AI opportunity assessments.