
Build your first AI agent in Go, start to finish
A complete agent in a few short files of standard-library Go, run offline and then on your own files.
On the agent compass The whole loop, all four stagesThis page builds a whole agent and runs it.
It answers questions about the files in one directory: you ask “which release added rate limiting?”, and it lists the files, reads the ones that look relevant, and answers from what they say.
Every piece is here, from the types that hold the conversation to the program’s main, and nothing comes from a framework or an SDK.
The task is deliberately safe. The agent’s two tools only read, and only inside the directory you give it, so you can point it at your own notes without worrying about what it might change.
It assumes you’ve read what an agent is and made a first model call, but nothing more.
Run it first
The program is firstagent in the companion code.
From the repository’s code directory, with no API key:
$ go run ./firstagent
Without a key, it replays a run recorded from a live model, xiaomi/mimo-v2.6-pro, on October 19, 2026, while the tools read the files of a small sample project for real.
This is what it prints:
question: Which release added rate limiting, and what is the default limit?
turn 1: list_files {}
turn 2: read_file {"path": "CHANGELOG.md"}
turn 2: read_file {"path": "config/defaults.yaml"}
3 model calls, 969 tokens in, 179 out, $0.0005
**Release:** v1.3.0 (2026-08-02) added per-client rate limiting, according to `CHANGELOG.md`. Each client is identified by IP address and the limit is set by `rate_limit.requests_per_minute`.
**Default limit:** 120 requests per minute (with a burst of 20), per `config/defaults.yaml`.
8 messages
Three calls to the model. On the first, it asked to see the files. On the second, it asked to read two of them at once. On the third, it had what it needed and answered, naming the file each fact came from. The whole run cost about five hundredths of a cent.
The rest of this page builds that program, one file at a time.
The files import only the standard library, so you can copy the firstagent directory into a module of your own and change it from there.
To try that, from the code directory:
$ mkdir ../myagent
$ cp -r firstagent/. ../myagent/
$ cd ../myagent
$ go mod init example.com/myagent
$ go run .
The testdata folder comes along, which is what lets it run with no key; go run . runs the package in the current directory.
The package is main and imports nothing from the rest of the repository, so no import paths change.
Use Go 1.27 or later, since the code relies on encoding/json/v2.
The types
Four types carry everything: a message, a tool call inside a message, a tool, and, in the next section, the client.
// Message is one entry in the conversation. Its JSON tags match the
// chat completions API, so the client sends and receives it as is.
type Message struct {
Role string `json:"role"` // system, user, assistant, tool
Content string `json:"content,omitzero"`
ToolCalls []ToolCall `json:"tool_calls,omitzero"`
ToolCallID string `json:"tool_call_id,omitzero"`
// Reasoning some models return, sent back unchanged.
Reasoning jsontext.Value `json:"reasoning_details,omitzero"`
}
// ToolCall is the model asking to run one tool.
type ToolCall struct {
ID string `json:"id"`
Type string `json:"type"` // always "function"
Function struct {
Name string `json:"name"`
Arguments string `json:"arguments"` // JSON, in a string
} `json:"function"`
}
// Tool is something the agent can do: a definition the model reads,
// and a Go function the model never sees.
type Tool struct {
Name string
Description string
Parameters jsontext.Value // a JSON Schema for the arguments
Run func(ctx context.Context, args string) (string, error)
}
Message has the same fields, with the same JSON names, as a message in the chat completions API, so the client can send the conversation as it is and decode the model’s reply straight into one.
That keeps this program short.
The companion code keeps its own types apart from the wire format instead, which lets one agent talk to providers whose formats differ; calling a model from Go shows that design.
Two fields need a word.
A tool call’s Arguments is a string that holds JSON, not a JSON object, so each tool decodes its own.
Reasoning holds the reasoning some models return with a reply; a model that returns it expects it back, unchanged, with the next request, and keeping it on the message does that without any extra code.
A Tool has two halves: the name, description, and parameter schema that the model reads, and a Go function, Run, that the model never sees.
The client
The client turns the conversation and the tools into one HTTP request, and the response into a reply:
// Chat sends the conversation and the tool definitions, and returns
// the model's reply. Each call gets two minutes at most.
func (c *Client) Chat(ctx context.Context, msgs []Message,
tools []Tool) (Reply, error) {
ctx, cancel := context.WithTimeout(ctx, 2*time.Minute)
defer cancel()
req := chatRequest{Model: c.Model, Messages: msgs}
for _, t := range tools {
var d toolDef
d.Type = "function"
d.Function.Name = t.Name
d.Function.Description = t.Description
d.Function.Parameters = t.Parameters
req.Tools = append(req.Tools, d)
}
body, err := json.Marshal(req)
if err != nil {
return Reply{}, fmt.Errorf("encode request: %w", err)
}
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost,
c.BaseURL+"/chat/completions", bytes.NewReader(body))
if err != nil {
return Reply{}, 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 Reply{}, fmt.Errorf("send request: %w", err)
}
defer resp.Body.Close()
return readReply(resp)
}
Each call gets a deadline of two minutes, so a request that never comes back can’t hang the agent, and Ctrl-C reaches the HTTP request through ctx.
The tool definitions go out with every request; the model has no memory of them between calls.
Reading the response is where most of the care goes, because the API can report failure in several ways:
// readReply decodes a response, turning every kind of failure the API
// can report into an error.
func readReply(resp *http.Response) (Reply, error) {
data, err := io.ReadAll(io.LimitReader(resp.Body, 16<<20))
if err != nil {
return Reply{}, fmt.Errorf("read response: %w", err)
}
var r chatResponse
err = json.Unmarshal(data, &r)
switch {
case resp.StatusCode != http.StatusOK && r.Error != nil:
return Reply{}, fmt.Errorf("model API: %s: %s", resp.Status,
r.Error.Message)
case resp.StatusCode != http.StatusOK:
return Reply{}, fmt.Errorf("model API: %s", resp.Status)
case err != nil:
return Reply{}, fmt.Errorf("decode response: %w", err)
case r.Error != nil: // a 200 that carries an error
return Reply{}, fmt.Errorf("model API: %s", r.Error.Message)
case len(r.Choices) == 0:
return Reply{}, errors.New("model API: reply has no choices")
}
ch := r.Choices[0]
if s := string(ch.Message.Reasoning); s == "null" || s == "[]" {
ch.Message.Reasoning = nil // nothing worth sending back
}
return Reply{Message: ch.Message, FinishReason: ch.FinishReason,
Usage: r.Usage}, nil
}
A non-200 status, an error object inside a 200, and a reply with no choices all become errors. Common first errors shows what each looks like on the wire.
The loop
This is the agent:
// Run sends the conversation to the model, runs the tools it asks for,
// and repeats until the model answers or maxTurns runs out. It returns
// the answer and the whole conversation, and reports each step to log.
func Run(ctx context.Context, c *Client, tools []Tool, msgs []Message,
maxTurns int, log io.Writer) (string, []Message, error) {
var calls int
var spent Usage
defer func() { // what the run cost, however it ended
fmt.Fprintf(log, "%d model calls, %d tokens in, %d out, $%.4f\n",
calls, spent.PromptTokens, spent.CompletionTokens, spent.Cost)
}()
for turn := range maxTurns {
reply, err := c.Chat(ctx, msgs, tools)
if err != nil {
return "", msgs, fmt.Errorf("turn %d: %w", turn+1, err)
}
calls++
spent.PromptTokens += reply.Usage.PromptTokens
spent.CompletionTokens += reply.Usage.CompletionTokens
spent.Cost += reply.Usage.Cost
if reply.FinishReason == "length" {
return "", msgs, errCutOff
}
msgs = append(msgs, reply.Message) // the reply first, then results
if len(reply.Message.ToolCalls) == 0 {
return reply.Message.Content, msgs, nil // no tools: the answer
}
for _, call := range reply.Message.ToolCalls {
fmt.Fprintf(log, "turn %d: %s %s\n", turn+1,
call.Function.Name, call.Function.Arguments)
msgs = append(msgs, Message{
Role: "tool",
ToolCallID: call.ID,
Content: runTool(ctx, tools, call),
})
}
}
return "", msgs, ErrMaxTurns
}
Each pass is one turn: send the conversation, append the reply, and either stop or run the tools.
A reply with no tool calls is the answer.
A reply with tool calls gets one tool message for each call, tagged with the call’s ID, and the loop goes around again with everything so far.
The order of the appends matters. The model’s reply goes into the conversation before its tools run, so every tool result answers a call the conversation already holds; the API refuses a request that holds a tool result whose call ID isn’t in the conversation.
The loop stops in three ways: an answer, a reply cut off by finish_reason: length, which is never treated as an answer, or the turn limit.
The deferred line reports what the run cost however it ended.
The agent loop goes through each of these rules in more depth.
Running one call is a small function of its own:
// runTool runs one call and returns what to tell the model. A failure
// becomes text the model can read and act on, so the run goes on.
func runTool(ctx context.Context, tools []Tool, call ToolCall) string {
var names []string
for _, t := range tools {
if t.Name == call.Function.Name {
out, err := t.Run(ctx, call.Function.Arguments)
if err != nil {
return "Error: " + err.Error()
}
if out == "" {
return "(no output)"
}
return out
}
names = append(names, t.Name)
}
return fmt.Sprintf("Error: no tool named %q. The tools are: %s.",
call.Function.Name, strings.Join(names, ", "))
}
A tool that fails doesn’t stop the run. Its error goes back to the model as the tool’s result, worded so the model can do something about it, and an unknown tool name gets the list of real ones. Models misspell tool names and send arguments in the wrong shape more often than you’d expect, and most of them correct the call when the error says how.
The tools
// fileTools returns the agent's two tools, which read only from
// files. Give it os.Root's FS: a root refuses any path that leads
// outside its directory, through ".." or a symbolic link.
func fileTools(files fs.FS) []Tool {
return []Tool{{
Name: "list_files",
Description: "List every file in the directory, one path per line.",
Parameters: []byte(`{"type": "object", "properties": {}}`),
Run: func(context.Context, string) (string, error) {
return listFiles(files)
},
}, {
Name: "read_file",
Description: "Read one file. path is relative to the directory, " +
"as list_files prints it.",
Parameters: []byte(`{"type": "object", "properties": {"path":
{"type": "string"}}, "required": ["path"]}`),
Run: func(_ context.Context, args string) (string, error) {
var a struct {
Path string `json:"path"`
}
if err := json.Unmarshal([]byte(args), &a); err != nil {
return "", fmt.Errorf("arguments: %w", err)
}
return readFile(files, a.Path)
},
}}
}
Both tools read through an fs.FS (the standard library’s interface for a read-only tree of files), and main builds that from an os.Root, which refuses any path that leads out of the directory, whether through .. or a symbolic link.
That makes the confinement a property of the code: the model can ask for ../../.ssh/id_rsa, and the read simply fails.
The read is capped at 20,000 bytes, so one large file can’t fill the conversation.
The descriptions are written for the model, which reads nothing else about a tool.
read_file’s says that paths come from list_files, which steers the model to list before it reads.
Designing tools covers writing tools a model uses well.
The prompt and main
const systemPrompt = `You answer questions about the files in one
directory. Use list_files to see what is there and read_file to read
a file. Answer only from what the files say, name the files you used,
and if the files don't answer the question, say so.`
The system prompt names the job, the tools and when to use them, and how to answer, including what to do when the files don’t have the answer. That last line matters more than it looks: without it, a model asked something the files can’t answer is inclined to answer anyway, from its general knowledge. Messages, roles, and the system prompt has more on writing one.
// run sets up the client, the tools, and the conversation, and runs
// the agent.
func run(ctx context.Context, getenv func(string) string, dir, record,
question string, out io.Writer) error {
c := &Client{
BaseURL: "https://openrouter.ai/api/v1",
APIKey: getenv("OPENROUTER_API_KEY"),
Model: cmp.Or(getenv("OPENROUTER_MODEL"), defaultModel),
}
rec, err := setTransport(c, record, question)
if err != nil {
return err
}
files, closeFiles, err := openDir(dir)
if err != nil {
return err
}
defer closeFiles()
msgs := []Message{
{Role: "system", Content: systemPrompt},
{Role: "user", Content: question},
}
fmt.Fprintf(out, "question: %s\n", question)
answer, msgs, err := Run(ctx, c, fileTools(files), msgs, 10, out)
if rec != nil {
err = errors.Join(err, rec.save(record))
}
if err != nil {
return err
}
fmt.Fprintf(out, "\n%s\n\n%d messages\n", answer, len(msgs))
return nil
}
run takes getenv func(string) string as a parameter, and main passes it os.Getenv; a test can pass a function that returns whatever it likes, so it never has to touch the real environment.
cmp.Or(a, b) returns the first of its arguments that isn’t empty, which is how an unset OPENROUTER_MODEL falls back to the default model.
errors.Join(err, other) combines two errors into one, used here so a failure to save the recording doesn’t hide the run’s own error.
If any of these are new, the New to Go? box covers related ground.
run builds the client, picks how it reaches the network, opens the directory, and starts the conversation with the system prompt and the question.
With no key, setTransport gives the client a transport that answers from the recording; with -record, one that saves the run.
Because the switch happens at the HTTP layer, the agent’s code is identical online and offline, and the tests use the same idea with a fake server.
Run it on your own files
Set a key, as your first model call describes, and point the agent at a directory:
$ export OPENROUTER_API_KEY=sk-or-...
$ go run ./firstagent -dir ~/notes "What did I decide about the cache?"
OPENROUTER_MODEL picks another model, and choosing a model covers which.
-record run.json saves the run’s API calls, so you can read exactly what was sent and what came back.
What it leaves out
This agent is complete, but it is not ready to run unattended. Each of these is a page of its own:
- Retries. A 429 or a 503 ends the run here. Retries and observability
- A budget. It stops at ten turns, but nothing caps what it spends. Why the agent stopped
- Tests of the agent’s behavior. The program’s own tests use a fake server; testing what an agent decides is a different job. Testing an agent offline
- Long conversations. Every file it reads stays in the conversation, and a run over a big directory grows expensive. Context management
- Tools that change things. Writing files, running commands, or calling APIs needs a sandbox and, for some actions, a person’s approval. Prompt injection and sandboxing and human approval
- Streaming. It prints nothing until each reply is complete. Streaming replies
type Message struct {
Role string `json:"role"` // system, user, assistant, tool
Content string `json:"content,omitzero"`
ToolCalls []ToolCall `json:"tool_calls,omitzero"`
ToolCallID string `json:"tool_call_id,omitzero"`
// Reasoning some models return, sent back unchanged.
Reasoning jsontext.Value `json:"reasoning_details,omitzero"`
}
Message is one entry in the conversation.
Message is one entry in the conversation. type Message struct { Role string `json:"role"` // system, user, assistant, tool Content string `json:"content,omitzero"` ToolCalls []ToolCall `json:"tool_calls,omitzero"` ToolCallID string `json:"tool_call_id,omitzero"` // Reasoning some models return, sent back unchanged. Reasoning jsontext.Value `json:"reasoning_details,omitzero"` }. In firstagent/agent.go, line 16.
field Role string `json:"role"`
system, user, assistant, tool
system, user, assistant, tool field Role string `json:"role"`. In firstagent/agent.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 Content string `json:"content,omitzero"`
field Content string `json:"content,omitzero"`. In firstagent/agent.go, line 18.
field ToolCalls []ToolCall `json:"tool_calls,omitzero"`
field ToolCalls []ToolCall `json:"tool_calls,omitzero"`. In firstagent/agent.go, line 19.
type ToolCall struct {
ID string `json:"id"`
Type string `json:"type"` // always "function"
Function struct {
Name string `json:"name"`
Arguments string `json:"arguments"` // JSON, in a string
} `json:"function"`
}
ToolCall is the model asking to run one tool.
ToolCall is the model asking to run one tool. type ToolCall struct { ID string `json:"id"` Type string `json:"type"` // always "function" Function struct { Name string `json:"name"` Arguments string `json:"arguments"` // JSON, in a string } `json:"function"` }. In firstagent/agent.go, line 26.
field ToolCallID string `json:"tool_call_id,omitzero"`
field ToolCallID string `json:"tool_call_id,omitzero"`. In firstagent/agent.go, line 20.
field Reasoning jsontext.Value `json:"reasoning_details,omitzero"`
Reasoning some models return, sent back unchanged.
Reasoning some models return, sent back unchanged. field Reasoning jsontext.Value `json:"reasoning_details,omitzero"`. In firstagent/agent.go, line 22.
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.
field ID string `json:"id"`
field ID string `json:"id"`. In firstagent/agent.go, line 27.
field Type string `json:"type"`
always "function"
always "function" field Type string `json:"type"`. In firstagent/agent.go, line 28.
field Function struct {
Name string `json:"name"`
Arguments string `json:"arguments"` // JSON, in a string
} `json:"function"`
field Function struct { Name string `json:"name"` Arguments string `json:"arguments"` // JSON, in a string } `json:"function"`. In firstagent/agent.go, line 29.
field Arguments string
field Arguments string. In firstagent/agent.go, line 31.
type Tool struct {
Name string
Description string
Parameters jsontext.Value // a JSON Schema for the arguments
Run func(ctx context.Context, args string) (string, error)
}
Tool is something the agent can do: a definition the model reads, and a Go function the model never sees.
Tool is something the agent can do: a definition the model reads, and a Go function the model never sees. type Tool struct { Name string Description string Parameters jsontext.Value // a JSON Schema for the arguments Run func(ctx context.Context, args string) (string, error) }. In firstagent/agent.go, line 37.
field Description string
field Description string. In firstagent/agent.go, line 39.
field Parameters jsontext.Value
a JSON Schema for the arguments
a JSON Schema for the arguments field Parameters jsontext.Value. In firstagent/agent.go, line 40.
field Run func(ctx context.Context, args string) (string, error)
field Run func(ctx context.Context, args string) (string, error). In firstagent/agent.go, line 41.
var ctx context.Context
var ctx context.Context. In firstagent/agent.go, line 41.
package context ("context")
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes. package context ("context"). Documented at pkg.go.dev, context.
type Context interface {
// Deadline returns the time when work done on behalf of this context
// should be canceled. Deadline returns ok==false when no deadline is
// set. Successive calls to Deadline return the same results.
Deadline() (deadline time.Time, ok bool)
// Done returns a channel that's closed when work done on behalf of this
// context should be canceled. Done may return nil if this context can
// never be canceled. Successive calls to Done return the same value.
// The close of the Done channel may happen asynchronously,
// ...
}
A Context carries a deadline, a cancellation signal, and other values across API boundaries.
A Context carries a deadline, a cancellation signal, and other values across API boundaries. type Context interface { // Deadline returns the time when work done on behalf of this context // should be canceled. Deadline returns ok==false when no deadline is // set. Successive calls to Deadline return the same results. Deadline() (deadline time.Time, ok bool) // Done returns a channel that's closed when work done on behalf of this // context should be canceled. Done may return nil if this context can // never be canceled. Successive calls to Done return the same value. // The close of the Done channel may happen asynchronously, // ... }. Documented at pkg.go.dev, context.Context.
type 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.
type Client struct {
BaseURL string // such as https://openrouter.ai/api/v1
APIKey string // sent as a bearer token
Model string // such as anthropic/claude-haiku-5.5
HTTP *http.Client // http.DefaultClient if nil
}
Client calls a model through an OpenAI-compatible chat completions API, such as OpenRouter's.
Client calls a model through an OpenAI-compatible chat completions API, such as OpenRouter's. type Client struct { BaseURL string // such as https://openrouter.ai/api/v1 APIKey string // sent as a bearer token Model string // such as anthropic/claude-haiku-5.5 HTTP *http.Client // http.DefaultClient if nil }. In firstagent/client.go, line 19.
func (c *Client) Chat(ctx context.Context, msgs []Message,
tools []Tool) (Reply, error)
Chat sends the conversation and the tool definitions, and returns the model's reply.
Chat sends the conversation and the tool definitions, and returns the model's reply. func (c *Client) Chat(ctx context.Context, msgs []Message, tools []Tool) (Reply, error). In firstagent/client.go, line 74.
var ctx context.Context
var ctx context.Context. In firstagent/client.go, line 74.
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 Reply struct {
Message Message
FinishReason string // stop, tool_calls, or length
Usage Usage
}
Reply is one answer from the model, with what it cost.
Reply is one answer from the model, with what it cost. type Reply struct { Message Message FinishReason string // stop, tool_calls, or length Usage Usage }. In firstagent/client.go, line 27.
var cancel context.CancelFunc
var cancel context.CancelFunc. In firstagent/client.go, line 76.
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)
WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).
WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)). func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc). Documented at pkg.go.dev, context.WithTimeout.
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.
const Minute = 60 * Second
const Minute = 60 * Second. Documented at pkg.go.dev, time.Minute.
type chatRequest struct {
Model string `json:"model"`
Messages []Message `json:"messages"`
Tools []toolDef `json:"tools,omitzero"`
}
The request and response, as JSON.
The request and response, as JSON. type chatRequest struct { Model string `json:"model"` Messages []Message `json:"messages"` Tools []toolDef `json:"tools,omitzero"` }. In firstagent/client.go, line 44.
field Model string `json:"model"`
field Model string `json:"model"`. In firstagent/client.go, line 45.
field Model string
such as anthropic/claude-haiku-5.5
such as anthropic/claude-haiku-5.5 field Model string. In firstagent/client.go, line 22.
field Messages []Message `json:"messages"`
field Messages []Message `json:"messages"`. In firstagent/client.go, line 46.
type toolDef struct {
Type string `json:"type"` // always "function"
Function struct {
Name string `json:"name"`
Description string `json:"description"`
Parameters jsontext.Value `json:"parameters"`
} `json:"function"`
}
type toolDef struct { Type string `json:"type"` // always "function" Function struct { Name string `json:"name"` Description string `json:"description"` Parameters jsontext.Value `json:"parameters"` } `json:"function"` }. In firstagent/client.go, line 50.
field Type string `json:"type"`
always "function"
always "function" field Type string `json:"type"`. In firstagent/client.go, line 51.
field Function struct {
Name string `json:"name"`
Description string `json:"description"`
Parameters jsontext.Value `json:"parameters"`
} `json:"function"`
field Function struct { Name string `json:"name"` Description string `json:"description"` Parameters jsontext.Value `json:"parameters"` } `json:"function"`. In firstagent/client.go, line 52.
field Description string
field Description string. In firstagent/client.go, line 54.
field Parameters jsontext.Value
field Parameters jsontext.Value. In firstagent/client.go, line 55.
field Tools []toolDef `json:"tools,omitzero"`
field Tools []toolDef `json:"tools,omitzero"`. In firstagent/client.go, line 47.
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 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.
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 firstagent/client.go, line 91.
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 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.
field BaseURL string
such as https://openrouter.ai/api/v1
such as https://openrouter.ai/api/v1 field BaseURL string. In firstagent/client.go, line 20.
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 firstagent/client.go, line 21.
var resp *http.Response
var resp *http.Response. In firstagent/client.go, line 98.
func (c *Client) httpClient() *http.Client
func (c *Client) httpClient() *http.Client. In firstagent/client.go, line 142.
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.
field Body io.ReadCloser
Body represents the response body.
Body represents the response body. field Body io.ReadCloser. Documented at pkg.go.dev, net/http.Response.Body.
func (Closer) Close() error
func (Closer) Close() error. Documented at pkg.go.dev, io.Closer.Close.
func readReply(resp *http.Response) (Reply, error)
readReply decodes a response, turning every kind of failure the API can report into an error.
readReply decodes a response, turning every kind of failure the API can report into an error. func readReply(resp *http.Response) (Reply, error). In firstagent/client.go, line 112.
var resp *http.Response
var resp *http.Response. In firstagent/client.go, line 112.
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.
package io ("io")
Package io provides basic interfaces to I/O primitives.
Package io provides basic interfaces to I/O primitives. package io ("io"). Documented at pkg.go.dev, io.
func ReadAll(r Reader) ([]byte, error)
ReadAll reads from r until an error or EOF and returns the data it read.
ReadAll reads from r until an error or EOF and returns the data it read. func ReadAll(r Reader) ([]byte, error). Documented at pkg.go.dev, io.ReadAll.
func LimitReader(r Reader, n int64) Reader
LimitReader returns a Reader that reads from r but stops with EOF after n bytes.
LimitReader returns a Reader that reads from r but stops with EOF after n bytes. func LimitReader(r Reader, n int64) Reader. Documented at pkg.go.dev, io.LimitReader.
type chatResponse struct {
Choices []struct {
FinishReason string `json:"finish_reason"`
Message Message `json:"message"`
} `json:"choices"`
Usage Usage `json:"usage"`
Error *struct {
Message string `json:"message"`
} `json:"error"`
}
type chatResponse struct { Choices []struct { FinishReason string `json:"finish_reason"` Message Message `json:"message"` } `json:"choices"` Usage Usage `json:"usage"` Error *struct { Message string `json:"message"` } `json:"error"` }. In firstagent/client.go, line 59.
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.
field StatusCode int
e.g.
e.g. field StatusCode int. Documented at pkg.go.dev, net/http.Response.StatusCode.
const StatusOK = 200
RFC 9110, 15.3.1
RFC 9110, 15.3.1 const StatusOK = 200. Documented at pkg.go.dev, net/http.StatusOK.
field Error *struct {
Message string `json:"message"`
} `json:"error"`
field Error *struct { Message string `json:"message"` } `json:"error"`. In firstagent/client.go, line 65.
field Status string
e.g.
e.g. field Status string. Documented at pkg.go.dev, net/http.Response.Status.
func len(v Type) int
The len built-in function returns the length of v, according to its type:
The len built-in function returns the length of v, according to its type: func len(v Type) int. Documented at pkg.go.dev, builtin.len.
field Choices []struct {
FinishReason string `json:"finish_reason"`
Message Message `json:"message"`
} `json:"choices"`
field Choices []struct { FinishReason string `json:"finish_reason"` Message Message `json:"message"` } `json:"choices"`. In firstagent/client.go, line 60.
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 ch struct{FinishReason string "json:\"finish_reason\""; Message Message "json:\"message\""}
var ch struct{FinishReason string "json:\"finish_reason\""; Message Message "json:\"message\""}. In firstagent/client.go, line 132.
field Message Message
field Message Message. In firstagent/client.go, line 62.
field Message Message
field Message Message. In firstagent/client.go, line 28.
field FinishReason string
stop, tool_calls, or length
stop, tool_calls, or length field FinishReason string. In firstagent/client.go, line 29.
field FinishReason string
field FinishReason string. In firstagent/client.go, line 61.
field Usage Usage `json:"usage"`
field Usage Usage `json:"usage"`. In firstagent/client.go, line 64.
func Run(ctx context.Context, c *Client, tools []Tool, msgs []Message,
maxTurns int, log io.Writer) (string, []Message, error)
Run sends the conversation to the model, runs the tools it asks for, and repeats until the model answers or maxTurns runs out.
Run sends the conversation to the model, runs the tools it asks for, and repeats until the model answers or maxTurns runs out. func Run(ctx context.Context, c *Client, tools []Tool, msgs []Message, maxTurns int, log io.Writer) (string, []Message, error). In firstagent/agent.go, line 57.
var ctx context.Context
var ctx context.Context. In firstagent/agent.go, line 57.
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.
package io ("io")
Package io provides basic interfaces to I/O primitives.
Package io provides basic interfaces to I/O primitives. package io ("io"). Documented at pkg.go.dev, io.
type Writer interface {
Write(p []byte) (n int, err error)
}
Writer is the interface that wraps the basic Write method.
Writer is the interface that wraps the basic Write method. type Writer interface { Write(p []byte) (n int, err error) }. Documented at pkg.go.dev, io.Writer.
type Usage struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
Cost float64 `json:"cost"` // in dollars
}
Usage is the size and price of one call.
Usage is the size and price of one call. type Usage struct { PromptTokens int `json:"prompt_tokens"` CompletionTokens int `json:"completion_tokens"` Cost float64 `json:"cost"` // in dollars }. In firstagent/client.go, line 34.
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 Fprintf(w io.Writer, format string, a ...any) (n int, err error)
Fprintf formats according to a format specifier and writes to w.
Fprintf formats according to a format specifier and writes to w. func Fprintf(w io.Writer, format string, a ...any) (n int, err error). Documented at pkg.go.dev, fmt.Fprintf.
field PromptTokens int `json:"prompt_tokens"`
field PromptTokens int `json:"prompt_tokens"`. In firstagent/client.go, line 35.
field CompletionTokens int `json:"completion_tokens"`
field CompletionTokens int `json:"completion_tokens"`. In firstagent/client.go, line 36.
field Cost float64 `json:"cost"`
in dollars
in dollars field Cost float64 `json:"cost"`. In firstagent/client.go, line 37.
var errCutOff = errors.New("firstagent: reply cut off")
errCutOff means the model ran out of room partway through a reply.
errCutOff means the model ran out of room partway through a reply. var errCutOff = errors.New("firstagent: reply cut off"). In firstagent/agent.go, line 50.
func runTool(ctx context.Context, tools []Tool, call ToolCall) string
runTool runs one call and returns what to tell the model.
runTool runs one call and returns what to tell the model. func runTool(ctx context.Context, tools []Tool, call ToolCall) string. In firstagent/agent.go, line 100.
var ErrMaxTurns = errors.New("firstagent: turn limit reached")
ErrMaxTurns means the run used every turn without an answer.
ErrMaxTurns means the run used every turn without an answer. var ErrMaxTurns = errors.New("firstagent: turn limit reached"). In firstagent/agent.go, line 47.
var ctx context.Context
var ctx context.Context. In firstagent/agent.go, line 100.
func (error).Error() string
func (error).Error() string.
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.
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 fileTools(files fs.FS) []Tool
fileTools returns the agent's two tools, which read only from files.
fileTools returns the agent's two tools, which read only from files. func fileTools(files fs.FS) []Tool. In firstagent/tools.go, line 20.
package fs ("io/fs")
Package fs defines basic interfaces to a file system.
Package fs defines basic interfaces to a file system. package fs ("io/fs"). Documented at pkg.go.dev, io/fs.
type FS interface {
// Open opens the named file.
// [File.Close] must be called to release any associated resources.
//
// When Open returns an error, it should be of type *PathError
// with the Op field set to "open", the Path field set to name,
// and the Err field describing the problem.
//
// Open should reject attempts to open names that do not satisfy
// ValidPath(name), returning a *PathError with Err set to
// ...
}
An FS provides access to a hierarchical file system.
An FS provides access to a hierarchical file system. type FS interface { // Open opens the named file. // [File.Close] must be called to release any associated resources. // // When Open returns an error, it should be of type *PathError // with the Op field set to "open", the Path field set to name, // and the Err field describing the problem. // // Open should reject attempts to open names that do not satisfy // ValidPath(name), returning a *PathError with Err set to // ... }. Documented at pkg.go.dev, io/fs.FS.
type byte = uint8
byte is an alias for uint8 and is equivalent to uint8 in all ways.
byte is an alias for uint8 and is equivalent to uint8 in all ways. type byte = uint8. Documented at pkg.go.dev, builtin.byte.
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.
func listFiles(files fs.FS) (string, error)
listFiles walks the directory and returns its files' paths.
listFiles walks the directory and returns its files' paths. func listFiles(files fs.FS) (string, error). In firstagent/tools.go, line 49.
var a struct{Path string "json:\"path\""}
var a struct{Path string "json:\"path\""}. In firstagent/tools.go, line 35.
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.
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 readFile(files fs.FS, path string) (string, error)
readFile returns one file's text, cut to maxRead bytes.
readFile returns one file's text, cut to maxRead bytes. func readFile(files fs.FS, path string) (string, error). In firstagent/tools.go, line 68.
const systemPrompt = `You answer questions about the files in one ...
const systemPrompt = `You answer questions about the files in one .... In firstagent/main.go, line 41.
func run(ctx context.Context, getenv func(string) string, dir, record,
question string, out io.Writer) error
run sets up the client, the tools, and the conversation, and runs the agent.
run sets up the client, the tools, and the conversation, and runs the agent. func run(ctx context.Context, getenv func(string) string, dir, record, question string, out io.Writer) error. In firstagent/main.go, line 69.
var ctx context.Context
var ctx context.Context. In firstagent/main.go, line 69.
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 getenv func(string) string
var getenv func(string) string. In firstagent/main.go, line 69.
package io ("io")
Package io provides basic interfaces to I/O primitives.
Package io provides basic interfaces to I/O primitives. package io ("io"). Documented at pkg.go.dev, io.
package cmp ("cmp")
Package cmp provides types and functions related to comparing ordered values.
Package cmp provides types and functions related to comparing ordered values. package cmp ("cmp"). Documented at pkg.go.dev, cmp.
func Or[T comparable](vals ...T) T
Or returns the first of its arguments that is not equal to the zero value.
Or returns the first of its arguments that is not equal to the zero value. func Or[T comparable](vals ...T) T. Documented at pkg.go.dev, cmp.Or.
const defaultModel = "xiaomi/mimo-v2.6-pro"
const defaultModel = "xiaomi/mimo-v2.6-pro". In firstagent/main.go, line 28.
func setTransport(c *Client, record, question string) (*recorder,
error)
setTransport makes the client replay the recorded run when there is no key, and record the run when asked to.
setTransport makes the client replay the recorded run when there is no key, and record the run when asked to. func setTransport(c *Client, record, question string) (*recorder, error). In firstagent/main.go, line 107.
func openDir(dir string) (fs.FS, func(), error)
openDir returns the files the agent may read: dir through an os.Root, or the embedded sample project when dir is empty.
openDir returns the files the agent may read: dir through an os.Root, or the embedded sample project when dir is empty. func openDir(dir string) (fs.FS, func(), error). In firstagent/main.go, line 130.
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 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 (r *recorder) save(file string) error
func (r *recorder) save(file string) error. In firstagent/replay.go, line 98.

