
Errors in a Go agent: wrapping, sentinel families, errors.AsType, and what the model reads
Errors for two readers: the program, which decides what to do, and the model, which fixes its next call.
The whole loopMost Go programs have one reader for their errors: the code that called them, and in the end the person who runs the program. An agent has two. A model call that failed, a budget that ran out, or a cancelled run goes to the program, which decides whether to retry, stop, or report. A tool call with bad arguments, or one that names a tool that doesn’t exist, goes to the model, as the tool’s result, and the model fixes its next call. Getting each error to the right reader, in a form that reader can act on, is most of the job.
The functions below are standard Go, several of them recent: errors.Join and wrapping more than one error with fmt.Errorf came in Go 1.20, and errors.AsType in Go 1.26.
All the code is from the companion repository, where it is tested.
Wrap with what you were doing
When a function returns an error from something it called, it adds what it was doing, with %w so the original stays inspectable:
// post sends a request to the chat completions endpoint and returns the
// response, whatever its status.
func (c *Client) post(ctx context.Context,
wire chatRequest) (*http.Response, error) {
body, err := json.Marshal(wire, jsontext.AllowInvalidUTF8(true))
if err != nil {
return nil, fmt.Errorf("encode request: %w", err)
}
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost,
c.baseURL()+"/chat/completions", bytes.NewReader(body))
if err != nil {
return nil, fmt.Errorf("build request: %w", err)
}
httpReq.Header.Set("Authorization", "Bearer "+c.APIKey)
httpReq.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient().Do(httpReq)
if err != nil {
return nil, fmt.Errorf("send request: %w",
callError(ctx, err))
}
return resp, nil
}
Each layer adds a few words, and the message reads as a path from the outside in. In a test whose fake transport never answers, the call ends with this error, every part of it added by a different layer:
send request: context deadline exceeded: Post "https://openrouter.ai/api/v1/chat/completions": blocked: openrouter: model call timed out
send request is this function, Post "…" is net/http, blocked is the fake transport, and the rest is the cancellation and its cause, joined as the context page describes.
The conventions keep that path readable: lowercase, no trailing punctuation, no “failed to” or “error:” prefixes, and the name of what was being done, not of the function.
Use %w when callers may need the cause, and %v to deliberately hide it, at a boundary where the inner error is an implementation detail callers shouldn’t depend on.
Handle each error once: either log it or return it.
Code that does both prints the same failure at every layer it passes through.
Errors callers check: sentinels in families
Conditions a caller needs to recognize are exported sentinel errors, values compared with errors.Is.
An agent has enough of them that grouping helps, so a caller can ask about a family without listing its members:
// The errors Run returns are grouped into families, so a caller can ask
// "was the budget the problem?" with errors.Is(err, ErrBudget) and not
// care which limit it was.
var (
// ErrBudget: the run used up a limit the caller set.
ErrBudget = errors.New("agent: budget exhausted")
ErrMaxTurns = fmt.Errorf("%w: max turns reached", ErrBudget)
ErrBudgetExceeded = fmt.Errorf("%w: cost budget reached", ErrBudget)
// ErrBadReply: the model's reply can't be used as it is.
ErrBadReply = errors.New("agent: bad reply")
ErrBadToolCall = fmt.Errorf("%w: bad tool call", ErrBadReply)
ErrOutputTruncated = fmt.Errorf("%w: cut off at the length limit",
ErrBadReply)
ErrOutputFiltered = fmt.Errorf("%w: blocked by a content filter",
ErrBadReply)
ErrProviderFailed = fmt.Errorf("%w: provider failed partway",
ErrBadReply)
ErrIncompleteResponse = fmt.Errorf("%w: the stream ended early",
ErrBadReply) // chapter 6
ErrNoFinalAnswer = fmt.Errorf("%w: answered without the final tool",
ErrBadReply) // chapter 7
ErrRefused = fmt.Errorf("%w: the model refused", ErrBadReply) // chapter 11
)
Each member wraps its family with fmt.Errorf("%w: ..."), so errors.Is(err, ErrBudget) is true for both the turn limit and the cost budget, and errors.Is(err, ErrMaxTurns) still tells them apart.
A caller that just wants to know “did a limit I set stop this?” checks the family; one that reports which limit checks the member.
Errors that carry data: types and behavior
Some failures need more than a name. An API error has a status, the API’s own message, and sometimes a delay the server asked for. Those are a type, with methods that answer the questions callers ask:
// An APIError is a request the API refused, or a provider failure it
// reported. Callers inspect it with errors.AsType to decide what to do.
type APIError struct {
Status int // HTTP status, or the code in the reply
Message string // the API's own explanation
RetryAfter time.Duration // the wait the API asked for, or 0
}
func (e *APIError) Error() string {
status := strconv.Itoa(e.Status)
if text := http.StatusText(e.Status); text != "" {
status += " " + text
}
return fmt.Sprintf("openrouter: %s: %s", status, e.Message)
}
// Retryable reports whether the same request might succeed if sent
// again later: a timeout (408), too many requests (429), or trouble on
// the provider's side (5xx). Chapter 12 retries these.
func (e *APIError) Retryable() bool {
return e.Status == http.StatusRequestTimeout ||
e.Status == http.StatusTooManyRequests || e.Status >= 500
}
errors.AsType finds the first error in a chain with a given type and returns it, typed: e, ok := errors.AsType[*APIError](err).
The type in square brackets (a type parameter) says which kind of error to look for; AsType returns it already converted to that type, with ok false if the chain has none.
It is the generic form of errors.As, added in Go 1.26; it needs no variable declared in advance, and it can’t be handed a pointer of the wrong shape, a common mistake with errors.As.
The retry code goes one step further and asks about behavior, not type.
It defines small interfaces for what an error can report about itself.
Each interface names one method; any error that has a Retryable method counts, whatever its type.
// Errors that report on themselves: retryable, such as chapter 5's
// *APIError and this chapter's *RetryError; delayed, an error that
// carries the server's requested wait; and timeout, such as a call's
// own deadline or chapter 6's idle stream, and net.Error.
type (
retryable interface {
error
Retryable() bool
}
delayed interface {
error
RetryDelay() time.Duration
}
timeout interface {
error
Timeout() bool
}
)
and checks for them with the same function, given an interface instead of a concrete type:
// Classify decides whether err, from a call made under ctx, the
// caller's context rather than the attempt's, is worth retrying.
func Classify(ctx context.Context, err error) Decision {
switch {
case err == nil:
return Decision{}
case ctx.Err() != nil:
return Decision{Why: "cancelled"}
case errors.Is(err, ErrToolFatal):
return Decision{Why: "fatal"}
}
if r, ok := errors.AsType[retryable](err); ok {
d := Decision{Retry: r.Retryable(), Why: "status"}
if w, ok := errors.AsType[delayed](err); ok {
d.After = w.RetryDelay()
}
return d
}
if timedOut(err) {
return Decision{Retry: true, Why: "timed out"}
}
if transient(err) {
return Decision{Retry: true, Why: "network"}
}
return Decision{Why: "permanent"}
}
Any error that has a Retryable method, from either provider’s client or from the retry code itself, is classified the same way, and the retry code imports none of those packages.
The order of the cases matters: a cancelled run is never retried, whatever the error says, and an error that reports itself is believed before the guesswork of timeouts and network errors.
One type uses that behavior to prevent a mistake.
A call retried until the policy gave up returns a *RetryError, which says it is not retryable, so a retry loop further out doesn’t start the whole series again:
// A RetryError is the last error of a call that was retried until the
// policy gave up. It reports itself as not retryable, so a layer
// outside, another wrapper or the caller's own loop, doesn't retry the
// whole series again and multiply the attempts.
type RetryError struct {
Attempts int
Err error
}
func (e *RetryError) Error() string {
return fmt.Sprintf("gave up after %d attempts: %v",
e.Attempts, e.Err)
}
// Unwrap returns the last attempt's error.
func (e *RetryError) Unwrap() error { return e.Err }
// Retryable is always false: the retries already happened.
func (e *RetryError) Retryable() bool { return false }
Here is the whole chain chapter 12’s code returns when a test server answers every model call with a 429, under a retry policy of three attempts. Step through how it is built, and what each of the two searches finds:
err.Error()generate: gave up after 3 attempts: no attempts left: openrouter: 429 Too Many Requests: Rate limit exceeded- the agent loop
*fmt.wrapError"generate: " + the error below - the retry policy
*agent.RetryError"gave up after 3 attempts: " + the error belowRetryable() false - the retry policy
*fmt.wrapError"no attempts left: " + the error below - the client, from the reply
*openrouter.APIErroropenrouter: 429 Too Many Requests: Rate limit exceededStatus 429 · Retryable() true · RetryAfter 1s
Errors the model reads
Most tool errors don’t stop the run. Such an error becomes the tool’s result, marked as an error, and the model reads it on its next turn. The text has to be written for that reader: what was wrong, and how to make the call correctly. The agent keeps the text for the model separate from the kind of error the program checks:
// ErrTool and its members name problems with one tool call. Run never
// returns them: they become tool messages, and the model tries again.
var (
ErrTool = errors.New("agent: tool call failed")
ErrUnknownTool = fmt.Errorf("%w: unknown tool", ErrTool)
ErrToolArgs = fmt.Errorf("%w: bad arguments", ErrTool)
ErrToolPanic = fmt.Errorf("%w: the tool panicked", ErrTool)
)
// A toolError is a problem with one tool call. Its message is what the
// model reads; its kind is for errors.Is. A tool that wraps a kind with
// fmt.Errorf instead would send the model the kind's text as well.
type toolError struct {
kind error
msg string
}
func (e *toolError) Error() string { return e.msg }
func (e *toolError) Unwrap() error { return e.kind }
Error() returns only the message, so the model reads something like no tool named "read"; the tools are edit_file, list_files, read_file, run_tests, not a chain of package prefixes, while Unwrap still lets the program count unknown-tool errors with errors.Is.
Here is that error being made, with the list of real tools the model needs to fix its call:
// lookupAndRun finds the tool a call names and runs it.
func lookupAndRun(ctx context.Context, byName map[string]Tool,
call ToolCall) (string, error) {
t, ok := byName[call.Name]
if !ok {
names := slices.Sorted(maps.Keys(byName))
return "", &toolError{ErrUnknownTool, fmt.Sprintf(
"no tool named %q; the tools are %s",
call.Name, strings.Join(names, ", "))}
}
return runSafely(ctx, t, call)
}
// runSafely runs a tool and turns a panic inside it into an error the
// model reads, so one broken tool can't crash the whole agent. The
// panic is a bug in the tool, so the message says to try another way.
func runSafely(ctx context.Context, t Tool, call ToolCall) (
out string, err error) {
defer func() {
if p := recover(); p != nil {
out, err = "", &toolError{ErrToolPanic, fmt.Sprintf(
"%s failed with an internal error (%v); "+
"try another way, or report it", call.Name, p)}
}
}()
return t.Run(ctx, call.Arguments)
}
Arguments that don’t decode get the same treatment: the model reads a short message saying which part of its arguments was wrong, followed by the shape of a correct call.
One more detail: encoding/json/v2 deliberately varies the wording of its error messages between runs, so the agent writes its own stable message from the error’s fields, through errors.AsType:
// decodeArgs decodes a tool call's arguments. When they don't decode,
// the error says what was wrong and shows the shape the tool expects,
// so the model can fix its next call.
func decodeArgs[T any](args jsontext.Value, example string) (T, error) {
var v T
err := json.Unmarshal(args, &v,
json.RejectUnknownMembers(true))
if err != nil {
return v, &toolError{ErrToolArgs, fmt.Sprintf(
"bad arguments: %s; send JSON like %s", argError(err), example)}
}
return v, nil
}
// argError says why arguments didn't decode, in the same words every
// time. json/v2 deliberately varies the wording of its errors between
// runs, and this text goes to the model and into saved runs.
func argError(err error) string {
if _, ok := errors.AsType[*jsontext.SyntacticError](err); ok {
return err.Error() // syntax errors read the same every time
}
se, ok := errors.AsType[*json.SemanticError](err)
if !ok || se.GoType == nil {
return "the JSON doesn't fit the arguments"
}
where := "the arguments"
if p := strings.TrimPrefix(string(se.JSONPointer), "/"); p != "" {
where = strconv.Quote(p)
}
if errors.Is(se.Err, json.ErrUnknownName) {
return "unknown field " + where
}
return fmt.Sprintf("%s: got %s, want %s", where,
kindOf(se.JSONKind), goKind(se.GoType.Kind()))
}
Stable wording matters twice here: a model reads it, and recorded runs used as test fixtures would otherwise change from one run to the next.
Errors that stop the run
Some tool failures can’t be fixed by a better call: the workspace the tool works in is gone, or the server behind it died. Sending those to the model just spends turns. They are marked with a sentinel of their own:
// ErrToolFatal means a tool can't run at all, such as when its
// workspace is gone: no retry or change of arguments can help, so the
// loop stops the run instead of sending the model an error to work
// around (chapter 9). A tool wraps it: fmt.Errorf("%w: ...", ErrToolFatal).
var ErrToolFatal = errors.New("agent: a tool can't run")
The code that runs a tool sorts every result into one of three outcomes: an answer, an error for the model, or an error that also stops the run:
// runTool runs one tool call and returns the tool message that answers
// it. Every problem becomes an error message the model can read; a tool
// that can't run at all is also returned as an error, which stops the
// run.
func runTool(ctx context.Context, byName map[string]Tool,
call ToolCall) (Message, error) {
msg := Message{Role: "tool", ToolCallID: call.ID}
ctx = context.WithValue(ctx, callKey{}, call) // for wrappers (chapter 12)
out, err := lookupAndRun(ctx, byName, call)
switch {
case errors.Is(err, ErrToolFatal):
msg.IsError, msg.Content = true, "not run: "+err.Error()
return msg, fmt.Errorf("%s: %w", call.Name, err)
case errors.Is(err, ErrOutcomeUnknown): // chapter 12
msg.IsError, msg.Content = true, "outcome unknown: "+err.Error()
return msg, fmt.Errorf("%s: %w", call.Name, err)
case err != nil: // the model reads it and tries again
msg.IsError, msg.Content = true, err.Error()
default:
msg.Content = out
}
return msg, nil
}
Even a fatal error produces a tool message, because every tool call in a conversation needs an answer; the run then stops with the error, wrapped with the tool’s name.
The second case in the listing, ErrOutcomeUnknown, is for a tool that may have changed something outside the run, such as sending a request, and then stopped without saying whether it did, for example by timing out.
Running it again could do the thing twice, so the run stops instead; Durable runs shows how a resumed run settles the question.
Panics at the tool boundary
A panic is for a programmer’s mistake, not for a failure the program expects. But a tool is code too, and a bug in one tool shouldn’t crash an agent partway through a long run. The tool boundary is the one place the agent recovers, and it turns the panic into an error the model reads:
// runSafely runs a tool and turns a panic inside it into an error the
// model reads, so one broken tool can't crash the whole agent. The
// panic is a bug in the tool, so the message says to try another way.
func runSafely(ctx context.Context, t Tool, call ToolCall) (
out string, err error) {
defer func() {
if p := recover(); p != nil {
out, err = "", &toolError{ErrToolPanic, fmt.Sprintf(
"%s failed with an internal error (%v); "+
"try another way, or report it", call.Name, p)}
}
}()
return t.Run(ctx, call.Arguments)
}
Recovering anywhere else would hide bugs; recovering here keeps one broken tool from losing the run, and the error still names the tool and the panic, for the person reading the log.
Several failures at once: errors.Join
Sometimes two things fail and both matter: a write fails, and putting the files back fails too.
errors.Join returns one error that holds both, and errors.Is and errors.AsType search every branch.
The excerpt is the end of apply, a function in the companion code that writes several files into a tree and puts the originals back if any write, or the build afterward, fails:
before := map[string]file{}
for _, rel := range slices.Sorted(maps.Keys(merged)) {
var err error
if before[rel], err = read(dir, rel); err != nil {
return err
}
if err := write(dir, rel, merged[rel]); err != nil {
return errors.Join(err, restore(dir, before))
}
}
if err := builds(ctx, dir); err != nil {
return errors.Join(err, restore(dir, before))
}
return nil
}
Parallel tool calls are the other common case: when several calls in one reply can’t run at all, the runner joins their errors, so the run reports every one instead of whichever finished first.
The retry code has to look inside joined errors too, when it checks whether any error in a chain is a timeout.
A joined error’s Unwrap returns a slice, Unwrap() []error, so code that walks a chain by hand has to follow both shapes.
The retry code does, because it looks for any error in the chain with a Timeout method that returns true, which errors.AsType can’t express, since it stops at the first error in the chain that has the method, whatever that method returns:
// timedOut reports whether any error in err's chain is a timeout. It
// looks at every one, not the first that has a Timeout method, because
// a *url.Error answers for the error directly inside it only, and the
// client's own timeout is usually wrapped deeper.
func timedOut(err error) bool {
if errors.Is(err, ErrAttemptTimeout) {
return true
}
for err != nil {
//nolint:errorlint // this walks the chain one error at a time
if t, ok := err.(timeout); ok && t.Timeout() {
return true
}
switch u := err.(type) { //nolint:errorlint // the same walk
case interface{ Unwrap() []error }:
return slices.ContainsFunc(u.Unwrap(), timedOut)
case interface{ Unwrap() error }:
err = u.Unwrap()
default:
return false
}
}
return false
}
Mistakes to avoid
- Comparing error strings. Use
errors.Isanderrors.AsType; message text changes between versions and, as withencoding/json/v2, sometimes between runs. The retry code makes one exception:net/httpreports an HTTP/2 stream reset and a closed idle connection with errors it doesn’t export, so the only way to recognize them is their text. - A nil pointer returned as an error. A function that returns
errorand ends withvar e *APIError; return ereturns a non-nil error holding a nil pointer, anderr != nilis true. Returnnilitself. - Logging and returning. The same failure appears at every layer. Pick one.
%wat a boundary you don’t want to commit to. Wrapping makes the inner error part of your API: callers will check for it. Use%vwhere it is an implementation detail.- A Go error string sent to the model as is. “json: cannot unmarshal string into Go struct field” tells a model little. Say what was wrong and what a right call looks like.
- Recovering panics everywhere. Recover at the tool boundary, where a failure has somewhere useful to go, and let real bugs elsewhere crash in tests.
Try it
From the code directory of a clone of the companion repository:
$ go test ./ch12/agent -run 'TestClassify|TestToolPanic|TestToolFatal' -v
- In
TestClassify, add a case for an error that wraps a*RetryErrorin anotherfmt.Errorf, and check that it still isn’t retried. - Make a tool panic on purpose and read the tool message the model would get.
TestToolPanicinch12/agent/final_test.goalready does it: a tool that panics with"boom", run through the loop by a scripted model. Addt.Log(got.Content)after the linegot := res.Messages[2]and rungo test ./ch12/agent -run TestToolPanic -v. You should seeecho failed with an internal error (boom); try another way, or report it. - Change
toolError.Errorto returne.kind.Error() + ": " + e.msg, and look at what the model would read for an unknown tool.
Undo your edits with git restore . in the code directory.
type Client struct {
BaseURL string // DefaultBaseURL if empty
APIKey string // sent as a bearer token
Model string // a model ID from OpenRouter's list
HTTP *http.Client // http.DefaultClient if nil
Timeout time.Duration // per Generate call; 2 minutes if zero
// IdleTimeout is the longest a stream may go without sending a
// byte, including the wait for its headers; 30 seconds if zero
// (chapter 6). Stream doesn't use Timeout.
// ...
}
Client calls a model through OpenRouter.
Client calls a model through OpenRouter. type Client struct { BaseURL string // DefaultBaseURL if empty APIKey string // sent as a bearer token Model string // a model ID from OpenRouter's list HTTP *http.Client // http.DefaultClient if nil Timeout time.Duration // per Generate call; 2 minutes if zero // IdleTimeout is the longest a stream may go without sending a // byte, including the wait for its headers; 30 seconds if zero // (chapter 6). Stream doesn't use Timeout. // ... }. In ch06/openrouter/client.go, line 40.
func (c *Client) post(ctx context.Context,
wire chatRequest) (*http.Response, error)
post sends a request to the chat completions endpoint and returns the response, whatever its status.
post sends a request to the chat completions endpoint and returns the response, whatever its status. func (c *Client) post(ctx context.Context, wire chatRequest) (*http.Response, error). In ch06/openrouter/client.go, line 88.
var ctx context.Context
var ctx context.Context. In ch06/openrouter/client.go, line 88.
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.
var wire chatRequest
var wire chatRequest. In ch06/openrouter/client.go, line 89.
type chatRequest struct {
Model string `json:"model"`
Messages []chatMessage `json:"messages"`
Tools []chatTool `json:"tools,omitzero"`
MaxTokens int `json:"max_tokens,omitzero"`
// Settings for asking about token probabilities (chapter 3).
Temperature *float64 `json:"temperature,omitzero"` // 0 is a setting
Logprobs bool `json:"logprobs,omitzero"`
TopLogprobs int `json:"top_logprobs,omitzero"`
// ...
}
type chatRequest struct { Model string `json:"model"` Messages []chatMessage `json:"messages"` Tools []chatTool `json:"tools,omitzero"` MaxTokens int `json:"max_tokens,omitzero"` // Settings for asking about token probabilities (chapter 3). Temperature *float64 `json:"temperature,omitzero"` // 0 is a setting Logprobs bool `json:"logprobs,omitzero"` TopLogprobs int `json:"top_logprobs,omitzero"` // ... }. In ch06/openrouter/wire.go, line 15.
package http ("net/http")
Package http provides HTTP client and server implementations.
Package http provides HTTP client and server implementations. package http ("net/http"). Documented at pkg.go.dev, net/http.
type Response struct {
Status string // e.g. "200 OK"
StatusCode int // e.g. 200
Proto string // e.g. "HTTP/1.0"
ProtoMajor int // e.g. 1
ProtoMinor int // e.g. 0
// Header maps header keys to values. If the response had multiple
// headers with the same key, they may be concatenated, with comma
// delimiters. (RFC 7230, section 3.2.2 requires that multiple headers
// ...
}
Response represents the response from an HTTP request.
Response represents the response from an HTTP request. type Response struct { Status string // e.g. "200 OK" StatusCode int // e.g. 200 Proto string // e.g. "HTTP/1.0" ProtoMajor int // e.g. 1 ProtoMinor int // e.g. 0 // Header maps header keys to values. If the response had multiple // headers with the same key, they may be concatenated, with comma // delimiters. (RFC 7230, section 3.2.2 requires that multiple headers // ... }. Documented at pkg.go.dev, net/http.Response.
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.
package json ("encoding/json/v2")
Package json implements semantic processing of JSON as specified in RFC 8259.
Package json implements semantic processing of JSON as specified in RFC 8259. package json ("encoding/json/v2"). Documented at pkg.go.dev, encoding/json/v2.
func Marshal(in any, opts ...Options) (out []byte, err error)
Marshal serializes a Go value as a []byte according to the provided marshal and encode options (while ignoring unmarshal or decode options).
Marshal serializes a Go value as a []byte according to the provided marshal and encode options (while ignoring unmarshal or decode options). func Marshal(in any, opts ...Options) (out []byte, err error). Documented at pkg.go.dev, encoding/json/v2.Marshal.
package jsontext ("encoding/json/jsontext")
Package jsontext implements syntactic processing of JSON as specified in RFC 4627, RFC 7159, RFC 7493, RFC 8259, and RFC 8785.
Package jsontext implements syntactic processing of JSON as specified in RFC 4627, RFC 7159, RFC 7493, RFC 8259, and RFC 8785. package jsontext ("encoding/json/jsontext"). Documented at pkg.go.dev, encoding/json/jsontext.
func AllowInvalidUTF8(v bool) Options
AllowInvalidUTF8 specifies that JSON strings may contain invalid UTF-8, which will be mangled as the Unicode replacement character, U+FFFD.
encoding/json/jsontext.AllowInvalidUTF8
AllowInvalidUTF8 specifies that JSON strings may contain invalid UTF-8, which will be mangled as the Unicode replacement character, U+FFFD. func AllowInvalidUTF8(v bool) Options. Documented at pkg.go.dev, encoding/json/jsontext.AllowInvalidUTF8.
const true = 0 == 0
Untyped bool.
Untyped bool. const true = 0 == 0. Documented at pkg.go.dev, builtin.true.
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.
var httpReq *http.Request
var httpReq *http.Request. In ch06/openrouter/client.go, line 94.
func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error)
NewRequestWithContext returns a new [Request] given a method, URL, and optional body.
net/http.NewRequestWithContext
NewRequestWithContext returns a new [Request] given a method, URL, and optional body. func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error). Documented at pkg.go.dev, net/http.NewRequestWithContext.
const MethodPost = "POST"
const MethodPost = "POST". Documented at pkg.go.dev, net/http.MethodPost.
func (c *Client) baseURL() string
func (c *Client) baseURL() string. In ch06/openrouter/client.go, line 267.
package bytes ("bytes")
Package bytes implements functions for the manipulation of byte slices.
Package bytes implements functions for the manipulation of byte slices. package bytes ("bytes"). Documented at pkg.go.dev, bytes.
func NewReader(b []byte) *Reader
NewReader returns a new [Reader] reading from b.
NewReader returns a new [Reader] reading from b. func NewReader(b []byte) *Reader. Documented at pkg.go.dev, bytes.NewReader.
field Header Header
Header contains the request header fields either received by the server or to be sent by the client.
Header contains the request header fields either received by the server or to be sent by the client. field Header Header. Documented at pkg.go.dev, net/http.Request.Header.
func (h Header) Set(key, value string)
Set sets the header entries associated with key to the single element value.
Set sets the header entries associated with key to the single element value. func (h Header) Set(key, value string). Documented at pkg.go.dev, net/http.Header.Set.
field APIKey string
sent as a bearer token
sent as a bearer token field APIKey string. In ch06/openrouter/client.go, line 42.
var resp *http.Response
var resp *http.Response. In ch06/openrouter/client.go, line 101.
func (c *Client) httpClient() *http.Client
func (c *Client) httpClient() *http.Client. In ch06/openrouter/client.go, line 274.
func (c *Client) Do(req *Request) (*Response, error)
Do sends an HTTP request and returns an HTTP response, following policy (such as redirects, cookies, auth) as configured on the client.
Do sends an HTTP request and returns an HTTP response, following policy (such as redirects, cookies, auth) as configured on the client. func (c *Client) Do(req *Request) (*Response, error). Documented at pkg.go.dev, net/http.Client.Do.
func callError(ctx context.Context, err error) error
callError makes the error from a cancelled call carry both the kind of cancellation and its cause.
callError makes the error from a cancelled call carry both the kind of cancellation and its cause. func callError(ctx context.Context, err error) error. In ch06/openrouter/client.go, line 252.
var ErrBudget = errors.New("agent: budget exhausted")
ErrBudget: the run used up a limit the caller set.
ErrBudget: the run used up a limit the caller set. var ErrBudget = errors.New("agent: budget exhausted"). In ch12/agent/errors.go, line 15.
package errors ("errors")
Package errors implements functions to manipulate errors.
Package errors implements functions to manipulate errors. package errors ("errors"). Documented at pkg.go.dev, errors.
func New(text string) error
New returns an error that formats as the given text.
New returns an error that formats as the given text. func New(text string) error. Documented at pkg.go.dev, errors.New.
var ErrMaxTurns = fmt.Errorf("%w: max turns reached", ErrBudget)
var ErrMaxTurns = fmt.Errorf("%w: max turns reached", ErrBudget). In ch12/agent/errors.go, line 16.
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.
var ErrBudgetExceeded = fmt.Errorf("%w: cost budget reached", ErrBudget)
var ErrBudgetExceeded = fmt.Errorf("%w: cost budget reached", ErrBudget). In ch12/agent/errors.go, line 17.
var ErrBadReply = errors.New("agent: bad reply")
ErrBadReply: the model's reply can't be used as it is.
ErrBadReply: the model's reply can't be used as it is. var ErrBadReply = errors.New("agent: bad reply"). In ch12/agent/errors.go, line 20.
var ErrBadToolCall = fmt.Errorf("%w: bad tool call", ErrBadReply)
var ErrBadToolCall = fmt.Errorf("%w: bad tool call", ErrBadReply). In ch12/agent/errors.go, line 21.
var ErrOutputTruncated = fmt.Errorf("%w: cut off at the length limit", ...
var ErrOutputTruncated = fmt.Errorf("%w: cut off at the length limit", .... In ch12/agent/errors.go, line 22.
var ErrOutputFiltered = fmt.Errorf("%w: blocked by a content filter", ...
var ErrOutputFiltered = fmt.Errorf("%w: blocked by a content filter", .... In ch12/agent/errors.go, line 24.
var ErrProviderFailed = fmt.Errorf("%w: provider failed partway", ...
var ErrProviderFailed = fmt.Errorf("%w: provider failed partway", .... In ch12/agent/errors.go, line 26.
var ErrIncompleteResponse = fmt.Errorf("%w: the stream ended early", ...
chapter 6
chapter 6 var ErrIncompleteResponse = fmt.Errorf("%w: the stream ended early", .... In ch12/agent/errors.go, line 28.
var ErrNoFinalAnswer = fmt.Errorf("%w: answered without the final tool", ...
chapter 7
chapter 7 var ErrNoFinalAnswer = fmt.Errorf("%w: answered without the final tool", .... In ch12/agent/errors.go, line 30.
var ErrRefused = fmt.Errorf("%w: the model refused", ErrBadReply)
chapter 11
chapter 11 var ErrRefused = fmt.Errorf("%w: the model refused", ErrBadReply). In ch12/agent/errors.go, line 32.
type APIError struct {
Status int // HTTP status, or the code in the reply
Message string // the API's own explanation
RetryAfter time.Duration // the wait the API asked for, or 0
}
An APIError is a request the API refused, or a provider failure it reported.
An APIError is a request the API refused, or a provider failure it reported. type APIError struct { Status int // HTTP status, or the code in the reply Message string // the API's own explanation RetryAfter time.Duration // the wait the API asked for, or 0 }. In ch06/openrouter/errors.go, line 15.
field Status int
HTTP status, or the code in the reply
HTTP status, or the code in the reply field Status int. In ch06/openrouter/errors.go, line 16.
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.
field Message string
the API's own explanation
the API's own explanation field Message string. In ch06/openrouter/errors.go, line 17.
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.
field RetryAfter time.Duration
the wait the API asked for, or 0
the wait the API asked for, or 0 field RetryAfter time.Duration. In ch06/openrouter/errors.go, line 18.
package time ("time")
Package time provides functionality for measuring and displaying time.
Package time provides functionality for measuring and displaying time. package time ("time"). Documented at pkg.go.dev, time.
type Duration int64
A Duration represents the elapsed time between two instants as an int64 nanosecond count.
A Duration represents the elapsed time between two instants as an int64 nanosecond count. type Duration int64. Documented at pkg.go.dev, time.Duration.
func (e *APIError) Error() string
func (e *APIError) Error() string. In ch06/openrouter/errors.go, line 21.
var status string
var status string. In ch06/openrouter/errors.go, line 22.
package strconv ("strconv")
Package strconv implements conversions to and from string representations of basic data types.
Package strconv implements conversions to and from string representations of basic data types. package strconv ("strconv"). Documented at pkg.go.dev, strconv.
func Itoa(i int) string
Itoa is equivalent to [FormatInt](int64(i), 10).
Itoa is equivalent to [FormatInt](int64(i), 10). func Itoa(i int) string. Documented at pkg.go.dev, strconv.Itoa.
package http ("net/http")
Package http provides HTTP client and server implementations.
Package http provides HTTP client and server implementations. package http ("net/http"). Documented at pkg.go.dev, net/http.
func StatusText(code int) string
StatusText returns a text for the HTTP status code.
StatusText returns a text for the HTTP status code. func StatusText(code int) string. Documented at pkg.go.dev, net/http.StatusText.
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 Sprintf(format string, a ...any) string
Sprintf formats according to a format specifier and returns the resulting string.
Sprintf formats according to a format specifier and returns the resulting string. func Sprintf(format string, a ...any) string. Documented at pkg.go.dev, fmt.Sprintf.
func (e *APIError) Retryable() bool
Retryable reports whether the same request might succeed if sent again later: a timeout (408), too many requests (429), or trouble on the provider's side (5xx).
Retryable reports whether the same request might succeed if sent again later: a timeout (408), too many requests (429), or trouble on the provider's side (5xx). func (e *APIError) Retryable() bool. In ch06/openrouter/errors.go, line 32.
type bool bool
bool is the set of boolean values, true and false.
bool is the set of boolean values, true and false. type bool bool. Documented at pkg.go.dev, builtin.bool.
const StatusRequestTimeout = 408
RFC 9110, 15.5.9
RFC 9110, 15.5.9 const StatusRequestTimeout = 408. Documented at pkg.go.dev, net/http.StatusRequestTimeout.
const StatusTooManyRequests = 429
RFC 6585, 4
net/http.StatusTooManyRequests
RFC 6585, 4 const StatusTooManyRequests = 429. Documented at pkg.go.dev, net/http.StatusTooManyRequests.
type retryable interface {
error
Retryable() bool
}
type retryable interface { error Retryable() bool }. In ch12/agent/classify.go, line 39.
func (retryable) Retryable() bool
func (retryable) Retryable() bool. In ch12/agent/classify.go, line 41.
type delayed interface {
error
RetryDelay() time.Duration
}
type delayed interface { error RetryDelay() time.Duration }. In ch12/agent/classify.go, line 43.
func (delayed) RetryDelay() time.Duration
func (delayed) RetryDelay() time.Duration. In ch12/agent/classify.go, line 45.
package time ("time")
Package time provides functionality for measuring and displaying time.
Package time provides functionality for measuring and displaying time. package time ("time"). Documented at pkg.go.dev, time.
type timeout interface {
error
Timeout() bool
}
type timeout interface { error Timeout() bool }. In ch12/agent/classify.go, line 47.
func (timeout) Timeout() bool
func (timeout) Timeout() bool. In ch12/agent/classify.go, line 49.
func Classify(ctx context.Context, err error) Decision
Classify decides whether err, from a call made under ctx, the caller's context rather than the attempt's, is worth retrying.
Classify decides whether err, from a call made under ctx, the caller's context rather than the attempt's, is worth retrying. func Classify(ctx context.Context, err error) Decision. In ch12/agent/classify.go, line 59.
var ctx context.Context
var ctx context.Context. In ch12/agent/classify.go, line 59.
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 Decision struct {
Retry bool
After time.Duration // the server's requested delay, or 0
Why string // a word for logs and traces
}
A Decision says whether to send a failed call again, and how long the server asked us to wait first.
A Decision says whether to send a failed call again, and how long the server asked us to wait first. type Decision struct { Retry bool After time.Duration // the server's requested delay, or 0 Why string // a word for logs and traces }. In ch12/agent/classify.go, line 19.
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.
field Why string
a word for logs and traces
a word for logs and traces field Why string. In ch12/agent/classify.go, line 22.
package errors ("errors")
Package errors implements functions to manipulate errors.
Package errors implements functions to manipulate errors. package errors ("errors"). Documented at pkg.go.dev, errors.
func Is(err, target error) bool
Is reports whether any error in err's tree matches target.
Is reports whether any error in err's tree matches target. func Is(err, target error) bool. Documented at pkg.go.dev, errors.Is.
var ErrToolFatal = errors.New("agent: a tool can't run")
ErrToolFatal means a tool can't run at all, such as when its workspace is gone: no retry or change of arguments can help, so the loop stops the run instead of sending the model an error to work around (chapter 9).
ErrToolFatal means a tool can't run at all, such as when its workspace is gone: no retry or change of arguments can help, so the loop stops the run instead of sending the model an error to work around (chapter 9). var ErrToolFatal = errors.New("agent: a tool can't run"). In ch12/agent/errors.go, line 67.
func AsType[E error](err error) (E, bool)
AsType finds the first error in err's tree that matches the type E, and if one is found, returns that error value and true.
AsType finds the first error in err's tree that matches the type E, and if one is found, returns that error value and true. func AsType[E error](err error) (E, bool). Documented at pkg.go.dev, errors.AsType.
field After time.Duration
the server's requested delay, or 0
the server's requested delay, or 0 field After time.Duration. In ch12/agent/classify.go, line 21.
func timedOut(err error) bool
timedOut reports whether any error in err's chain is a timeout.
timedOut reports whether any error in err's chain is a timeout. func timedOut(err error) bool. In ch12/agent/classify.go, line 92.
func transient(err error) bool
transient reports whether err is a connection that failed or broke, which a second attempt on a new connection may not hit: a reset, a body cut short, a kept-alive connection the server had closed (EOF, or net/http's "server closed idle connection"), an HTTP/2 stream reset, or a TLS alert such as "bad record MAC".
transient reports whether err is a connection that failed or broke, which a second attempt on a new connection may not hit: a reset, a body cut short, a kept-alive connection the server had closed (EOF, or net/http's "server closed idle connection"), an HTTP/2 stream reset, or a TLS alert such as "bad record MAC". func transient(err error) bool. In ch12/agent/classify.go, line 123.
type RetryError struct {
Attempts int
Err error
}
A RetryError is the last error of a call that was retried until the policy gave up.
A RetryError is the last error of a call that was retried until the policy gave up. type RetryError struct { Attempts int Err error }. In ch12/agent/retry.go, line 44.
func (e *RetryError) Error() string
func (e *RetryError) Error() string. In ch12/agent/retry.go, line 49.
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 (e *RetryError) Unwrap() error
Unwrap returns the last attempt's error.
Unwrap returns the last attempt's error. func (e *RetryError) Unwrap() error. In ch12/agent/retry.go, line 55.
func (e *RetryError) Retryable() bool
Retryable is always false: the retries already happened.
Retryable is always false: the retries already happened. func (e *RetryError) Retryable() bool. In ch12/agent/retry.go, line 58.
const false = 0 != 0
Untyped bool.
Untyped bool. const false = 0 != 0. Documented at pkg.go.dev, builtin.false.
var ErrTool = errors.New("agent: tool call failed")
var ErrTool = errors.New("agent: tool call failed"). In ch12/agent/errors.go, line 42.
var ErrUnknownTool = fmt.Errorf("%w: unknown tool", ErrTool)
var ErrUnknownTool = fmt.Errorf("%w: unknown tool", ErrTool). In ch12/agent/errors.go, line 43.
var ErrToolArgs = fmt.Errorf("%w: bad arguments", ErrTool)
var ErrToolArgs = fmt.Errorf("%w: bad arguments", ErrTool). In ch12/agent/errors.go, line 44.
var ErrToolPanic = fmt.Errorf("%w: the tool panicked", ErrTool)
var ErrToolPanic = fmt.Errorf("%w: the tool panicked", ErrTool). In ch12/agent/errors.go, line 45.
type toolError struct {
kind error
msg string
}
A toolError is a problem with one tool call.
A toolError is a problem with one tool call. type toolError struct { kind error msg string }. In ch12/agent/errors.go, line 51.
func (e *toolError) Error() string
func (e *toolError) Error() string. In ch12/agent/errors.go, line 56.
func (e *toolError) Unwrap() error
func (e *toolError) Unwrap() error. In ch12/agent/errors.go, line 57.
func lookupAndRun(ctx context.Context, byName map[string]Tool,
call ToolCall) (string, error)
lookupAndRun finds the tool a call names and runs it.
lookupAndRun finds the tool a call names and runs it. func lookupAndRun(ctx context.Context, byName map[string]Tool, call ToolCall) (string, error). In ch12/agent/loop.go, line 127.
var ctx context.Context
var ctx context.Context. In ch12/agent/loop.go, line 127.
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.
var byName map[string]Tool
var byName map[string]Tool. In ch12/agent/loop.go, line 127.
type Tool struct {
Def ToolDef
Run func(ctx context.Context, args jsontext.Value) (string, error)
// Safety flags (chapter 7). A tool with neither flag set may change
// something outside the run.
ReadOnly bool // it only looks things up
Idempotent bool // running it twice has the same effect as once
// Final marks the tool that ends the run: once a call to it
// ...
}
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) // Safety flags (chapter 7). A tool with neither flag set may change // something outside the run. ReadOnly bool // it only looks things up Idempotent bool // running it twice has the same effect as once // Final marks the tool that ends the run: once a call to it // ... }. In ch12/agent/types.go, line 140.
type ToolCall struct {
ID string
Name string
Arguments jsontext.Value // JSON the model wrote; may be invalid
}
ToolCall is the model asking the harness to run a tool.
ToolCall is the model asking the harness to run a tool. type ToolCall struct { ID string Name string Arguments jsontext.Value // JSON the model wrote; may be invalid }. In ch12/agent/types.go, line 82.
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 Sorted[E cmp.Ordered](seq iter.Seq[E]) []E
Sorted collects values from seq into a new slice, sorts the slice, and returns it.
Sorted collects values from seq into a new slice, sorts the slice, and returns it. func Sorted[E cmp.Ordered](seq iter.Seq[E]) []E. Documented at pkg.go.dev, slices.Sorted.
package maps ("maps")
Package maps defines various functions useful with maps of any type.
Package maps defines various functions useful with maps of any type. package maps ("maps"). Documented at pkg.go.dev, maps.
func Keys[Map ~map[K]V, K comparable, V any](m Map) iter.Seq[K]
Keys returns an iterator over keys in m.
Keys returns an iterator over keys in m. func Keys[Map ~map[K]V, K comparable, V any](m Map) iter.Seq[K]. Documented at pkg.go.dev, maps.Keys.
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.
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 Join(elems []string, sep string) string
Join concatenates the elements of its first argument to create a single string.
Join concatenates the elements of its first argument to create a single string. func Join(elems []string, sep string) string. Documented at pkg.go.dev, strings.Join.
func runSafely(ctx context.Context, t Tool, call ToolCall) (
out string, err error)
runSafely runs a tool and turns a panic inside it into an error the model reads, so one broken tool can't crash the whole agent.
runSafely runs a tool and turns a panic inside it into an error the model reads, so one broken tool can't crash the whole agent. func runSafely(ctx context.Context, t Tool, call ToolCall) ( out string, err error). In ch12/agent/loop.go, line 144.
var ctx context.Context
var ctx context.Context. In ch12/agent/loop.go, line 144.
func recover() any
The recover built-in function allows a program to manage behavior of a panicking goroutine.
The recover built-in function allows a program to manage behavior of a panicking goroutine. func recover() any. Documented at pkg.go.dev, builtin.recover.
field Run func(ctx context.Context, args jsontext.Value) (string, error)
field Run func(ctx context.Context, args jsontext.Value) (string, error). In ch12/agent/types.go, line 142.
field Arguments jsontext.Value
JSON the model wrote; may be invalid
JSON the model wrote; may be invalid field Arguments jsontext.Value. In ch12/agent/types.go, line 85.
func decodeArgs[T any](args jsontext.Value, example string) (T, error)
decodeArgs decodes a tool call's arguments.
decodeArgs decodes a tool call's arguments. func decodeArgs[T any](args jsontext.Value, example string) (T, error). In ch06/agent/tools.go, line 43.
type any = interface{}
any is an alias for interface{} and is equivalent to interface{} in all ways.
any is an alias for interface{} and is equivalent to interface{} in all ways. type any = interface{}. Documented at pkg.go.dev, builtin.any.
var args jsontext.Value
var args jsontext.Value. In ch06/agent/tools.go, line 43.
package jsontext ("encoding/json/jsontext")
Package jsontext implements syntactic processing of JSON as specified in RFC 4627, RFC 7159, RFC 7493, RFC 8259, and RFC 8785.
Package jsontext implements syntactic processing of JSON as specified in RFC 4627, RFC 7159, RFC 7493, RFC 8259, and RFC 8785. package jsontext ("encoding/json/jsontext"). Documented at pkg.go.dev, encoding/json/jsontext.
type Value []byte
Value represents a single raw JSON value, which may be one of the following:
Value represents a single raw JSON value, which may be one of the following: type Value []byte. Documented at pkg.go.dev, encoding/json/jsontext.Value.
package json ("encoding/json/v2")
Package json implements semantic processing of JSON as specified in RFC 8259.
Package json implements semantic processing of JSON as specified in RFC 8259. package json ("encoding/json/v2"). Documented at pkg.go.dev, encoding/json/v2.
func Unmarshal(in []byte, out any, opts ...Options) (err error)
Unmarshal decodes a []byte input into a Go value according to the provided unmarshal and decode options (while ignoring marshal or encode options).
Unmarshal decodes a []byte input into a Go value according to the provided unmarshal and decode options (while ignoring marshal or encode options). func Unmarshal(in []byte, out any, opts ...Options) (err error). Documented at pkg.go.dev, encoding/json/v2.Unmarshal.
func RejectUnknownMembers(v bool) Options
RejectUnknownMembers specifies that unknown members should be rejected when unmarshaling a JSON object.
encoding/json/v2.RejectUnknownMembers
RejectUnknownMembers specifies that unknown members should be rejected when unmarshaling a JSON object. func RejectUnknownMembers(v bool) Options. Documented at pkg.go.dev, encoding/json/v2.RejectUnknownMembers.
type toolError struct {
kind error
msg string
}
A toolError is a problem with one tool call.
A toolError is a problem with one tool call. type toolError struct { kind error msg string }. In ch06/agent/errors.go, line 47.
var ErrToolArgs = fmt.Errorf("%w: bad arguments", ErrTool)
var ErrToolArgs = fmt.Errorf("%w: bad arguments", ErrTool). In ch06/agent/errors.go, line 41.
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 argError(err error) string
argError says why arguments didn't decode, in the same words every time.
argError says why arguments didn't decode, in the same words every time. func argError(err error) string. In ch06/agent/tools.go, line 57.
package errors ("errors")
Package errors implements functions to manipulate errors.
Package errors implements functions to manipulate errors. package errors ("errors"). Documented at pkg.go.dev, errors.
type SyntacticError struct {
requireKeyedLiterals
nonComparable
// ByteOffset indicates that an error occurred at or after this byte offset.
ByteOffset int64
// JSONPointer indicates that an error occurred within this JSON value
// as indicated using the JSON Pointer notation (see RFC 6901).
JSONPointer Pointer
// ...
}
SyntacticError is a description of an error that occurred when encoding or decoding JSON according to the grammar.
encoding/json/jsontext.SyntacticError
SyntacticError is a description of an error that occurred when encoding or decoding JSON according to the grammar. type SyntacticError struct { requireKeyedLiterals nonComparable // ByteOffset indicates that an error occurred at or after this byte offset. ByteOffset int64 // JSONPointer indicates that an error occurred within this JSON value // as indicated using the JSON Pointer notation (see RFC 6901). JSONPointer Pointer // ... }. Documented at pkg.go.dev, encoding/json/jsontext.SyntacticError.
func (error).Error() string
func (error).Error() string.
var se *json.SemanticError
var se *json.SemanticError. In ch06/agent/tools.go, line 61.
type SemanticError struct {
requireKeyedLiterals
nonComparable
action string // either "marshal" or "unmarshal"
// ByteOffset indicates that an error occurred at or after this byte offset.
ByteOffset int64
// JSONPointer indicates that an error occurred within this JSON value
// as indicated using the JSON Pointer notation (see RFC 6901).
// ...
}
SemanticError describes an error determining the meaning of JSON data as Go data, or vice versa.
encoding/json/v2.SemanticError
SemanticError describes an error determining the meaning of JSON data as Go data, or vice versa. type SemanticError struct { requireKeyedLiterals nonComparable action string // either "marshal" or "unmarshal" // ByteOffset indicates that an error occurred at or after this byte offset. ByteOffset int64 // JSONPointer indicates that an error occurred within this JSON value // as indicated using the JSON Pointer notation (see RFC 6901). // ... }. Documented at pkg.go.dev, encoding/json/v2.SemanticError.
field GoType reflect.Type
GoType is the Go type that could not be handled.
encoding/json/v2.SemanticError.GoType
GoType is the Go type that could not be handled. field GoType reflect.Type. Documented at pkg.go.dev, encoding/json/v2.SemanticError.GoType.
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 TrimPrefix(s, prefix string) string
TrimPrefix returns s without the provided leading prefix string.
TrimPrefix returns s without the provided leading prefix string. func TrimPrefix(s, prefix string) string. Documented at pkg.go.dev, strings.TrimPrefix.
field JSONPointer jsontext.Pointer
JSONPointer indicates that an error occurred within this JSON value as indicated using the JSON Pointer notation (see RFC 6901).
encoding/json/v2.SemanticError.JSONPointer
JSONPointer indicates that an error occurred within this JSON value as indicated using the JSON Pointer notation (see RFC 6901). field JSONPointer jsontext.Pointer. Documented at pkg.go.dev, encoding/json/v2.SemanticError.JSONPointer.
package strconv ("strconv")
Package strconv implements conversions to and from string representations of basic data types.
Package strconv implements conversions to and from string representations of basic data types. package strconv ("strconv"). Documented at pkg.go.dev, strconv.
func Quote(s string) string
Quote returns a double-quoted Go string literal representing s.
Quote returns a double-quoted Go string literal representing s. func Quote(s string) string. Documented at pkg.go.dev, strconv.Quote.
field Err error
Err is the underlying error.
encoding/json/v2.SemanticError.Err
Err is the underlying error. field Err error. Documented at pkg.go.dev, encoding/json/v2.SemanticError.Err.
var ErrUnknownName = errors.New("unknown object member name")
ErrUnknownName indicates that a JSON object member could not be unmarshaled because the name is not known to the target Go struct.
encoding/json/v2.ErrUnknownName
ErrUnknownName indicates that a JSON object member could not be unmarshaled because the name is not known to the target Go struct. var ErrUnknownName = errors.New("unknown object member name"). Documented at pkg.go.dev, encoding/json/v2.ErrUnknownName.
func kindOf(k jsontext.Kind) string
kindOf names a kind of JSON value.
kindOf names a kind of JSON value. func kindOf(k jsontext.Kind) string. In ch06/agent/tools.go, line 79.
field JSONKind jsontext.Kind
JSONKind is the JSON kind that could not be handled.
encoding/json/v2.SemanticError.JSONKind
JSONKind is the JSON kind that could not be handled. field JSONKind jsontext.Kind. Documented at pkg.go.dev, encoding/json/v2.SemanticError.JSONKind.
func goKind(k reflect.Kind) string
goKind names what JSON a kind of Go value takes.
goKind names what JSON a kind of Go value takes. func goKind(k reflect.Kind) string. In ch06/agent/tools.go, line 98.
func (Type) Kind() Kind
Kind returns the specific kind of this type.
Kind returns the specific kind of this type. func (Type) Kind() Kind. Documented at pkg.go.dev, reflect.Type.Kind.
func runTool(ctx context.Context, byName map[string]Tool,
call ToolCall) (Message, error)
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, error). In ch12/agent/runner.go, line 114.
var ctx context.Context
var ctx context.Context. In ch12/agent/runner.go, line 114.
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.
var byName map[string]Tool
var byName map[string]Tool. In ch12/agent/runner.go, line 114.
type Message struct {
Role string // "system", "user", "assistant", or "tool"
Content string // may be empty when the message has tool calls
ToolCalls []ToolCall // set on assistant messages that call tools
ToolCallID string // set on tool messages: which 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 // may be empty when the message has tool calls ToolCalls []ToolCall // set on assistant messages that call tools ToolCallID string // set on tool messages: which 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 ch12/agent/types.go, line 39.
field Role string
"system", "user", "assistant", or "tool"
"system", "user", "assistant", or "tool" field Role string. In ch12/agent/types.go, line 40.
field ToolCallID string
set on tool messages: which call this answers
set on tool messages: which call this answers field ToolCallID string. In ch12/agent/types.go, line 43.
func WithValue(parent Context, key, val any) Context
WithValue returns a derived context that points to the parent Context.
WithValue returns a derived context that points to the parent Context. func WithValue(parent Context, key, val any) Context. Documented at pkg.go.dev, context.WithValue.
type callKey struct{}
callKey carries the tool call a tool is running for, so a wrapper can name it; Tool.Run sees only the arguments.
callKey carries the tool call a tool is running for, so a wrapper can name it; Tool.Run sees only the arguments. type callKey struct{}. In ch12/agent/traced.go, line 14.
package errors ("errors")
Package errors implements functions to manipulate errors.
Package errors implements functions to manipulate errors. package errors ("errors"). Documented at pkg.go.dev, errors.
field IsError bool
set on tool messages that report a failure
set on tool messages that report a failure field IsError bool. In ch12/agent/types.go, line 44.
field Content string
may be empty when the message has tool calls
may be empty when the message has tool calls field Content string. In ch12/agent/types.go, line 41.
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.
var ErrOutcomeUnknown = errors.New("agent: a tool's outcome is unknown")
ErrOutcomeUnknown means a tool that may change something outside the run stopped without saying whether it did, such as one that timed out after it sent its request: running it again could do it twice, so the run stops instead (chapter 15 resolves it).
ErrOutcomeUnknown means a tool that may change something outside the run stopped without saying whether it did, such as one that timed out after it sent its request: running it again could do it twice, so the run stops instead (chapter 15 resolves it). var ErrOutcomeUnknown = errors.New("agent: a tool's outcome is unknown"). In ch12/agent/tooltime.go, line 36.
var before map[string]file
var before map[string]file. In ch12/groups/merge.go, line 103.
type file = []byte
A file is one file's content in a tree; nil means it doesn't exist.
A file is one file's content in a tree; nil means it doesn't exist. type file = []byte. In ch12/groups/merge.go, line 21.
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.
package maps ("maps")
Package maps defines various functions useful with maps of any type.
Package maps defines various functions useful with maps of any type. package maps ("maps"). Documented at pkg.go.dev, maps.
var merged map[string]file
var merged map[string]file. In ch12/groups/merge.go, line 79.
func read(dir, rel string) (file, error)
read returns a file's content in a tree, or nil if it isn't there.
read returns a file's content in a tree, or nil if it isn't there. func read(dir, rel string) (file, error). In ch12/groups/merge.go, line 188.
func write(dir, rel string, content file) error
write sets a file's content in a tree; nil content removes it.
write sets a file's content in a tree; nil content removes it. func write(dir, rel string, content file) error. In ch12/groups/merge.go, line 200.
package errors ("errors")
Package errors implements functions to manipulate errors.
Package errors implements functions to manipulate errors. package errors ("errors"). Documented at pkg.go.dev, errors.
func Join(errs ...error) error
Join returns an error that wraps the given errors.
Join returns an error that wraps the given errors. func Join(errs ...error) error. Documented at pkg.go.dev, errors.Join.
func restore(dir string, before map[string]file) error
restore puts files back as they were before a group's changes.
restore puts files back as they were before a group's changes. func restore(dir string, before map[string]file) error. In ch12/groups/merge.go, line 144.
func builds(ctx context.Context, dir string) error
builds compiles every package's tests in the tree, running none.
builds compiles every package's tests in the tree, running none. func builds(ctx context.Context, dir string) error. In ch12/groups/merge.go, line 129.
var ctx context.Context
var ctx context.Context. In ch12/groups/merge.go, line 74.
var ErrAttemptTimeout = errors.New("reliability: attempt timed out")
ErrAttemptTimeout is the cause set on one attempt's own deadline, so an attempt that ran out of time can be told apart from a caller who gave up: the first is worth another try, the second is not.
ErrAttemptTimeout is the cause set on one attempt's own deadline, so an attempt that ran out of time can be told apart from a caller who gave up: the first is worth another try, the second is not. var ErrAttemptTimeout = errors.New("reliability: attempt timed out"). In ch12/agent/classify.go, line 28.
func (interface).Unwrap() []error
func (interface).Unwrap() []error. In ch12/agent/classify.go, line 102.
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 ContainsFunc[S ~[]E, E any](s S, f func(E) bool) bool
ContainsFunc reports whether at least one element e of s satisfies f(e).
ContainsFunc reports whether at least one element e of s satisfies f(e). func ContainsFunc[S ~[]E, E any](s S, f func(E) bool) bool. Documented at pkg.go.dev, slices.ContainsFunc.
var u interface{Unwrap() []error}
var u interface{Unwrap() []error}. In ch12/agent/classify.go, line 101.
func (interface).Unwrap() error
func (interface).Unwrap() error. In ch12/agent/classify.go, line 104.
var u interface{Unwrap() error}
var u interface{Unwrap() error}. In ch12/agent/classify.go, line 101.
func As(err error, target any) bool
As finds the first error in err's tree that matches target, and if one is found, sets target to that error value and returns true.
As finds the first error in err's tree that matches target, and if one is found, sets target to that error value and returns true. func As(err error, target any) bool. Documented at pkg.go.dev, errors.As.