
Workflow or agent? The shapes, in Go
Five shapes of program that call a model, and how to pick the simplest one that handles the task.
On the agent compass Stage 4 of 4 · DecideCalling a model from Go doesn’t make a program an agent, and many such programs shouldn’t be one. To tell the shapes apart, ask where the decision about the next step is made. In some programs your code makes it, at places you chose when you wrote it. In others the model makes it on every turn, after seeing what the previous step produced. Handing the model more of those decisions makes the program able to do more, and it also makes it slower, more expensive, and harder to test.
The shapes below come from Anthropic’s “Building effective agents”, which names them.
One task, a small bug fix, was built both ways and measured.
This page covers both, and shows the workflow shapes as small Go functions from the companion code’s shapes example.
Five shapes
| Shape | Who picks the next step | A typical use |
|---|---|---|
| A fixed chain | Your code, in a sequence where each call receives the previous call’s output | A job with a known recipe, like writing a summary and then reviewing it |
| Routing | Your code, after one model call has labeled the input | Mixed input where each category gets its own handler, like a support inbox |
| Parallel calls | Your code, which fires several calls together and merges what comes back | Work that splits into unrelated pieces, or a question you want several answers to |
| A single agent | The model, turn by turn, inside one loop | Work where the next move depends on the last result |
| Several agents | Models in separate loops that pass tasks along or delegate to sub-agents | Big jobs that divide into parts that don’t depend on each other |
In the top three rows, a workflow, the plan lives in your code and the model only does the steps. In the bottom two, an agent, the model owns the plan.
Pick the highest row that can do the job, and go lower only when the task leaves you no choice.
The workflow shapes in Go
The shapes example builds the workflow rows, plus one shape the table leaves out, and each fits in one function.
All of them take agent.Model, so any model client plugs in, and all of them treat a reply the model didn’t finish (a finish_reason of length, content_filter, or error) as an error, never as an answer, which is the rule a hardened loop follows.
A fixed chain runs its steps in order, each step’s prompt built from the previous step’s output, and checks each reply in code before the next step sees it:
// Chain runs steps in order, each with the last one's output, starting
// from input, and returns the last step's output. It stops at the first
// call that fails or reply that fails its check, so a bad draft never
// reaches the next step.
//
// Use a chain when the task has steps you know in advance. It costs one
// call per step, made one after another, so its latency is the sum of
// the steps; each step's prompt holds only the last output, which keeps
// the calls small and each one easy to test on its own.
func Chain(ctx context.Context, m agent.Model, input string,
steps []Step) (string, error) {
out := input
for _, s := range steps {
reply, err := ask(ctx, m, s.Prompt(out))
if err != nil {
return "", fmt.Errorf("step %s: %w", s.Name, err)
}
if s.Check != nil {
if err := s.Check(reply); err != nil {
return "", fmt.Errorf("step %s: %w", s.Name, err)
}
}
out = reply
}
return out, nil
}
The check is what keeps a chain honest. Without it, a malformed summary from step one becomes the input of step two, and the error surfaces two calls later, if at all. A chain costs one call per step, made one after another, so its latency is the sum of its steps; in exchange, each call holds only the last output, which keeps it small and easy to test alone.
A router asks a small, cheap model for the input’s kind and hands the input to that kind’s handler, which can be a large model, a small one, or plain code (route.go).
It adds one short call in front of every input, and an input it misfiles gets the wrong treatment, so measure the classifier on inputs someone has labeled before you trust it.
The input also reaches the classifier’s prompt, so a crafted input, a prompt injection, can choose its own kind: no handler should have a permission that the worst possible input must never get.
Parallel calls with a vote ask several voters the same question at once and return the first answer a quorum of them gives. The code runs each call in its own goroutine, a function running at the same time as the rest of the program, and collects the answers through a channel, which passes values between goroutines (Goroutines with an owner):
// Vote asks every voter the same question at once and returns the
// first answer that quorum of them give. Answers are compared as
// strings after trimming space, so ask for a word or a fixed label.
//
// Use a vote when one call's answer isn't reliable enough and a wrong
// answer costs more than several calls: a yes-or-no judgment, a label,
// a function name. Voters can be one model listed several times or
// different models. A vote costs one call per voter; the calls run at
// once, so it takes about as long as the slowest call it waits for.
// The voters must be able to disagree: one model at temperature 0
// answers the same every time, and the vote buys nothing.
func Vote(ctx context.Context, voters []agent.Model, prompt string,
quorum int) (string, error) {
if quorum < 1 || quorum > len(voters) {
panic("shapes: Vote needs 1 <= quorum <= len(voters)")
}
var wg sync.WaitGroup
defer wg.Wait()
ctx, cancel := context.WithCancelCause(ctx)
defer cancel(errDecided)
results := make(chan result, len(voters))
for _, m := range voters {
wg.Go(func() {
answer, err := ask(ctx, m, prompt)
results <- result{strings.TrimSpace(answer), err}
})
}
return tally(results, len(voters), quorum)
}
Once the vote is decided, the calls still running are stopped, and Vote doesn’t return until every call has finished.
The deferred wg.Wait means no voter’s goroutine outlives the call, and cancelling with a cause stops the calls still running once the vote is decided, since their answers can’t change it.
A vote costs one call per voter and takes about as long as the slowest call it waits for.
It only buys something if the voters can disagree: one model at temperature 0 gives the same answer every time.
Answers are compared as strings after trimming space, so ask for a word or a fixed label; in the example’s demo, Yes and yes count as two different answers.
Check and revise is the shape the table leaves out, one model judging another’s output, also used for evals. A writer drafts, a critic judges the draft, and the critic’s notes go back to the writer, up to a limit:
for n := 0; ; n++ {
v, err := critic(ctx, draft)
switch {
case err != nil:
return draft, fmt.Errorf("critique: %w", err)
case v.Pass:
return draft, nil
case n == maxRevisions:
return draft, fmt.Errorf("%w after %d revisions: %s",
ErrNotApproved, n, v.Notes)
}
msgs = append(msgs,
agent.Message{Role: "assistant", Content: draft},
agent.Message{Role: "user", Content: revise + v.Notes})
next, err := complete(ctx, writer, msgs)
if err != nil {
return draft, fmt.Errorf("revise: %w", err)
}
draft = next
}
}
The critic can be code (a length limit, a schema, the tests), a model, or both, with the cheap checks first; AllOf in the same file runs them in that order.
Each round costs a critic call and a writer call, and the writer’s calls grow, since each one carries the conversation so far; maxRevisions bounds both.
Recorded measurements show why the critic deserves suspicion too: a model reviewer spent its whole reasoning budget (the tokens a reasoning model may use to think before it answers) on 10 of 25 reviews and returned nothing usable.
What moving down costs, measured
The same bug was fixed both ways, on four models with ten runs per model. As an agent, the model decided for itself how to use four tools. As a workflow, the program followed three hard-coded steps: run the tests and read the two files involved, ask the model for a single edit in JSON, then apply it and rerun the tests.
On every model the workflow’s cost was between one sixth and one quarter of the agent’s. Its single model call took from under a second to 2.5 seconds; the agent’s runs took 7.5 to 13.5 seconds. The agent passed all 40 runs and the workflow passed 39. Measured mistakes has the failed run and its method. That failure is worth a look: the model put a literal tab character inside a JSON string, so the edit failed to decode, and the workflow had no step that could send the error back and ask again.
So for this bug, the workflow wins. It wins because the author already knew which files mattered and what kind of change was needed. Move the cause into a third file, or make it something only a test run can pin down, and three fixed steps no longer cover the task.
What an agent buys
An agent pays for itself when nobody can say ahead of time what the next step should be, because that depends on the result of the step before. In the bug-fix run, no line of code told the model to open the test file after listing the directory; it decided that after seeing the listing, and it decided on the edit after reading the test output.
A crash-triage agent, the companion code’s agent that reads crash reports from remind (a small practice service with planted bugs), fixes them, and files issues in a tracker, does that kind of work all the time.
The crash catalog is built to mislead: a crash can surface far from the code that caused it, a report can come from an older release whose bug was fixed since, and reports that look alike can have different causes.
There’s no fixed list of files to read, since the right one depends on the stack trace, the source, and the outcome of the latest test run.
Agents need more machinery
Each row you move down also shifts responsibility into the harness, the program around the model. A workflow can only do what its code spells out. An agent can keep going indefinitely unless you add limits:
// Limits holds the settings that bound a run.
type Limits struct {
MaxTurns int
MaxCost float64 // in dollars; 0 means no cost budget (chapter 5)
}
// Result is what a run produced, whether or not it ended in an error.
type Result struct {
Messages []Message
Usage Usage // the run's total, over every model call (chapter 5)
}
The turn limit ends a loop that would otherwise run forever, and the cost budget, checked before every model call, puts a ceiling on spending. Beyond limits, an agent needs its tool calls validated before they execute, tool errors written so the model can respond to them, and tests that judge the result instead of the transcript, because the same task can take a different route each run. The production pages cover all of that.
Combine the shapes
In practice the shapes mix, and a good design often nests one row inside another.
One case study, from beyond crash triage, resolves support tickets.
The outer layer is routing: one model call labels each ticket, and ordinary code handles the common categories with fixed handlers that send a password reset link, fetch an invoice from billing, or fill in a reply template.
Tickets that don’t fit a category are passed to an agent.
It can look up orders, payments, and shipments with three read-only tools, and it has one tool that changes something, issue_refund.
Putting the router in front means most tickets cost a single model call, and those tickets never reach the agent, so the agent can’t mishandle them.
The two halves also get measured in different ways.
The router’s accuracy is a number a program can compute against tickets someone has labeled.
Whether a given refund should have been issued is a business decision, so it takes a human reviewer or a model acting as judge.
And because issue_refund moves money, a person approves each call before it runs, and the call carries an idempotency key (an identifier the payment system uses to ignore a repeat of the same request) so a refund that went out just before a crash isn’t paid twice.
When to use it
For this page, “it” is an agent; leaving it out means writing a workflow.
Reach for it
- Each step depends on what the previous one turned up. On
m2, a crash whose cause was stored long before it, the agent passed three of its six hard-tier runs. - A model reply can fail in ways you can’t list in advance. The workflow’s only failure in 40 runs was a reply it couldn’t decode, which an agent’s loop would have sent back to the model.
Leave it out
- You can write the steps down. As a three-step workflow, the bug fix passed 39 of 40 runs for a quarter to a sixth of the agent’s cost.
- Waiting matters. The workflow’s single call took at most 2.5 seconds; each agent run took 7.5 to 13.5.
A checklist
- Can you write the steps down? Use a fixed chain. Wrap each model step in a retry; the workflow’s single failure above was a decoding error that one more attempt, with the error shown to the model, might have fixed.
- Do inputs fall into kinds? Route them, and give each kind the simplest shape that handles it.
- Are the pieces independent? Call the model for each piece in parallel and merge the results in code.
- Does each step depend on what the last one found? Use an agent, and give it a turn limit, a cost budget, and validated tool calls from the start.
- Does the task split into large independent parts? Several agents may help, but measure first: on a recorded 99-report batch, fan-out finished no faster than one agent and cost more.
Try it
From the code directory of a clone of the companion repository:
$ go run ./shapes
$ go test -race ./shapes
The -race flag turns on Go’s data-race detector, which reports two goroutines touching the same memory without coordination; the second command runs the example’s tests with it.
The first runs each workflow shape on scripted models, on a crash report from the remind service, and prints what each returned and how many calls it made: two calls for the chain, four to the small model and two to the large one for the router, a vote that reaches its quorum and one that doesn’t, and two rounds of writing and critique.
No key is needed.
$ go run ./ch04
This replays the agent version of the bug fix, runs the real go test, and prints the cost: $0.0008 across four model calls.
The ch04 example goes through it step by step.
func Chain(ctx context.Context, m agent.Model, input string,
steps []Step) (string, error)
Chain runs steps in order, each with the last one's output, starting from input, and returns the last step's output.
Chain runs steps in order, each with the last one's output, starting from input, and returns the last step's output. func Chain(ctx context.Context, m agent.Model, input string, steps []Step) (string, error). In shapes/chain.go, line 34.
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.
package agent ("github.com/blackwell-systems/go-agents-book/code/ch06/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/ch06/agent"). In ch06/agent.
type Model interface {
Generate(ctx context.Context, req Request) (Reply, error)
}
Model is anything that can produce the next reply in a conversation: a scripted fake, or a real model such as the OpenRouter client.
Model is anything that can produce the next reply in a conversation: a scripted fake, or a real model such as the OpenRouter client. type Model interface { Generate(ctx context.Context, req Request) (Reply, error) }. In ch06/agent/types.go, line 13.
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.
type Step struct {
Name string
Prompt func(in string) string
Check func(out string) error // nil means no check
}
A Step is one call in a chain: the prompt it sends, built from the last step's output, and a check its reply must pass before the next step sees it.
A Step is one call in a chain: the prompt it sends, built from the last step's output, and a check its reply must pass before the next step sees it. type Step struct { Name string Prompt func(in string) string Check func(out string) error // nil means no check }. In shapes/chain.go, line 15.
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 ask(ctx context.Context, m agent.Model,
prompt string) (string, error)
ask sends one prompt to m and returns the reply's text.
ask sends one prompt to m and returns the reply's text. func ask(ctx context.Context, m agent.Model, prompt string) (string, error). In shapes/call.go, line 33.
field Prompt func(in string) string
field Prompt func(in string) string. In shapes/chain.go, line 17.
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.
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 Check func(out string) error
nil means no check
nil means no check field Check func(out string) error. In shapes/chain.go, line 18.
func Vote(ctx context.Context, voters []agent.Model, prompt string,
quorum int) (string, error)
Vote asks every voter the same question at once and returns the first answer that quorum of them give.
Vote asks every voter the same question at once and returns the first answer that quorum of them give. func Vote(ctx context.Context, voters []agent.Model, prompt string, quorum int) (string, error). In shapes/vote.go, line 37.
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.
package agent ("github.com/blackwell-systems/go-agents-book/code/ch06/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/ch06/agent"). In ch06/agent.
type int int
int is a signed integer type that is at least 32 bits in size.
int is a signed integer type that is at least 32 bits in size. type int int. Documented at pkg.go.dev, builtin.int.
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.
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.
package sync ("sync")
Package sync provides basic synchronization primitives such as mutual exclusion locks.
Package sync provides basic synchronization primitives such as mutual exclusion locks. package sync ("sync"). Documented at pkg.go.dev, sync.
type WaitGroup struct {
noCopy noCopy
// Bits (high to low):
// bits[0:32] counter
// bits[32] flag: synctest bubble membership
// bits[33:64] wait count
state atomic.Uint64
sema uint32
}
A WaitGroup is a counting semaphore typically used to wait for a group of goroutines or tasks to finish.
A WaitGroup is a counting semaphore typically used to wait for a group of goroutines or tasks to finish. type WaitGroup struct { noCopy noCopy // Bits (high to low): // bits[0:32] counter // bits[32] flag: synctest bubble membership // bits[33:64] wait count state atomic.Uint64 sema uint32 }. Documented at pkg.go.dev, sync.WaitGroup.
func (wg *WaitGroup) Wait()
Wait blocks until the [WaitGroup] task counter is zero.
Wait blocks until the [WaitGroup] task counter is zero. func (wg *WaitGroup) Wait(). Documented at pkg.go.dev, sync.WaitGroup.Wait.
var cancel context.CancelCauseFunc
var cancel context.CancelCauseFunc. In shapes/vote.go, line 44.
func WithCancelCause(parent Context) (ctx Context, cancel CancelCauseFunc)
WithCancelCause behaves like [WithCancel] but returns a [CancelCauseFunc] instead of a [CancelFunc].
WithCancelCause behaves like [WithCancel] but returns a [CancelCauseFunc] instead of a [CancelFunc]. func WithCancelCause(parent Context) (ctx Context, cancel CancelCauseFunc). Documented at pkg.go.dev, context.WithCancelCause.
var errDecided = errors.New("shapes: the vote is decided")
errDecided is the cause given to the calls still running when a vote is decided; they are cancelled, since their answers can't change the result.
errDecided is the cause given to the calls still running when a vote is decided; they are cancelled, since their answers can't change the result. var errDecided = errors.New("shapes: the vote is decided"). In shapes/vote.go, line 21.
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.
type result struct {
answer string
err error
}
A result is one voter's answer, or why it has none.
A result is one voter's answer, or why it has none. type result struct { answer string err error }. In shapes/vote.go, line 61.
func (wg *WaitGroup) Go(f func())
Go calls f in a new goroutine and adds that task to the [WaitGroup].
Go calls f in a new goroutine and adds that task to the [WaitGroup]. func (wg *WaitGroup) Go(f func()). Documented at pkg.go.dev, sync.WaitGroup.Go.
package strings ("strings")
Package strings implements simple functions to manipulate UTF-8 encoded strings.
Package strings implements simple functions to manipulate UTF-8 encoded strings. package strings ("strings"). Documented at pkg.go.dev, strings.
func TrimSpace(s string) string
TrimSpace returns a slice (substring) of the string s, with all leading and trailing white space removed, as defined by Unicode.
TrimSpace returns a slice (substring) of the string s, with all leading and trailing white space removed, as defined by Unicode. func TrimSpace(s string) string. Documented at pkg.go.dev, strings.TrimSpace.
func tally(results <-chan result, n, quorum int) (string, error)
tally reads n results and returns the first answer to reach quorum.
tally reads n results and returns the first answer to reach quorum. func tally(results <-chan result, n, quorum int) (string, error). In shapes/vote.go, line 69.
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.
field Pass bool `json:"pass"`
field Pass bool `json:"pass"`. In shapes/revise.go, line 21.
var ErrNotApproved = errors.New("shapes: draft not approved")
ErrNotApproved means the critic still wanted changes when Revise ran out of revisions.
ErrNotApproved means the critic still wanted changes when Revise ran out of revisions. var ErrNotApproved = errors.New("shapes: draft not approved"). In shapes/revise.go, line 15.
field Notes string `json:"notes"`
what to change; empty on a pass
what to change; empty on a pass field Notes string `json:"notes"`. In shapes/revise.go, line 22.
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.
package agent ("github.com/blackwell-systems/go-agents-book/code/ch06/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/ch06/agent"). In ch06/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
// ReasoningDetails is a reasoning model's record of its thinking,
// sent back unchanged with the tool calls it led to (chapter 4).
ReasoningDetails jsontext.Value
}
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 // ReasoningDetails is a reasoning model's record of its thinking, // sent back unchanged with the tool calls it led to (chapter 4). ReasoningDetails jsontext.Value }. In ch06/agent/types.go, line 33.
field Role string
"system", "user", "assistant", or "tool"
"system", "user", "assistant", or "tool" field Role string. In ch06/agent/types.go, line 34.
field Content string
empty when the message has tool calls
empty when the message has tool calls field Content string. In ch06/agent/types.go, line 35.
const revise = "A reviewer asked for changes. Reply with the whole " + ...
revise introduces the critic's notes to the writer.
revise introduces the critic's notes to the writer. const revise = "A reviewer asked for changes. Reply with the whole " + .... In shapes/revise.go, line 92.
func complete(ctx context.Context, m agent.Model,
msgs []agent.Message) (string, error)
complete sends one conversation to m, with no tools, and returns the reply's text.
complete sends one conversation to m, with no tools, and returns the reply's text. func complete(ctx context.Context, m agent.Model, msgs []agent.Message) (string, error). In shapes/call.go, line 15.
type Limits struct {
MaxTurns int
MaxCost float64 // in dollars; 0 means no cost budget (chapter 5)
}
Limits holds the settings that bound a run.
Limits holds the settings that bound a run. type Limits struct { MaxTurns int MaxCost float64 // in dollars; 0 means no cost budget (chapter 5) }. In ch05/agent/types.go, line 110.
field MaxCost float64
in dollars; 0 means no cost budget (chapter 5)
in dollars; 0 means no cost budget (chapter 5) field MaxCost float64. In ch05/agent/types.go, line 112.
type float64 float64
float64 is the set of all IEEE 754 64-bit floating-point numbers.
float64 is the set of all IEEE 754 64-bit floating-point numbers. type float64 float64. Documented at pkg.go.dev, builtin.float64.
type Result struct {
Messages []Message
Usage Usage // the run's total, over every model call (chapter 5)
}
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 Usage Usage // the run's total, over every model call (chapter 5) }. In ch05/agent/types.go, line 116.
field Messages []Message
field Messages []Message. In ch05/agent/types.go, line 117.
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
// ReasoningDetails is a reasoning model's record of its thinking,
// sent back unchanged with the tool calls it led to (chapter 4).
ReasoningDetails jsontext.Value
}
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 // ReasoningDetails is a reasoning model's record of its thinking, // sent back unchanged with the tool calls it led to (chapter 4). ReasoningDetails jsontext.Value }. In ch05/agent/types.go, line 33.
field Usage Usage
the run's total, over every model call (chapter 5)
the run's total, over every model call (chapter 5) field Usage Usage. In ch05/agent/types.go, line 118.
type Usage struct {
PromptTokens int // everything sent, counted in tokens
CompletionTokens int // everything the model wrote
CachedTokens int // prompt tokens served from the cache
ReasoningTokens int // completion tokens spent on reasoning
Cost float64 // in dollars, as the provider reported it
}
Usage is what one model call consumed.
Usage is what one model call consumed. type Usage struct { PromptTokens int // everything sent, counted in tokens CompletionTokens int // everything the model wrote CachedTokens int // prompt tokens served from the cache ReasoningTokens int // completion tokens spent on reasoning Cost float64 // in dollars, as the provider reported it }. In ch05/agent/types.go, line 75.

