
Calling a model’s API from Go with net/http
A chat completions client in standard-library Go, with deadlines, error checks, and finish reasons.
On the agent compass Stage 2 of 4 · Call the modelTo a Go program, a model is a web service: you POST some JSON and decode the JSON that comes back.
net/http and encoding/json/v2 cover all of it.
The big providers do publish official Go SDKs (software development kits: libraries that wrap an API in ready-made Go types and functions; see the glossary), which bring typed options, built-in retries, and streaming helpers.
The catch for an agent is that an SDK makes some choices on your behalf that an agent should make on purpose, such as the timeout for a call, whether a failure gets retried, and what happens to a reply that ended before it was done.
Building the client yourself once puts each of those choices in front of you; a later project can switch to an SDK where one is useful.
The client shown here comes from the companion code, and we’ll follow one call from request to decoded reply.
One endpoint
Every request the client sends goes here:
POST https://openrouter.ai/api/v1/chat/completions
OpenRouter is a single front door to many model providers: one API, one key, and one invoice, with the model named in the request and OpenRouter passing it to a provider that hosts it.
The request format is OpenAI’s chat completions format, which has become the common one: most other hosted services and local model servers accept it as well.
That makes the base URL just another setting.
Change it to a local server’s address, for example Ollama’s http://localhost:11434/v1, and the client works against that server unchanged.
The request body names the model and carries the conversation. The response carries the model’s message plus metadata: the reason it stopped writing and what the call used.
Wire types, kept apart
The JSON the API speaks lives in wire types: Go structs that match the JSON sent over the network, field for field.
They are unexported (their names start with a lowercase letter, so only the client package can use them) and separate from the agent’s own Message:
type chatRequest struct {
Model string `json:"model"`
Messages []chatMessage `json:"messages"`
MaxTokens int `json:"max_tokens,omitzero"`
}
type chatMessage struct {
Role string `json:"role"`
Content string `json:"content"`
}
Separate types let each side evolve on its own schedule. The API has its own field names and extra fields an agent never reads, and the agent’s types are shaped around the agent. With the translation in one file, the rest of the program never learns the API’s conventions, and swapping in an API with another shape later means writing another translation file.
Each field carries a json tag, a short string after the field that names its JSON key (struct tags).
encoding/json/v2, which Go 1.27 ships in the standard library, compares names case-sensitively, so every field needs one.
Why MaxTokens is omitzero.
MaxTokens is marked omitzero rather than omitempty.
Under v2, omitempty drops a field only when its encoded JSON is empty, like "" or [], and the number 0 doesn’t count as empty.
With omitempty, every request would include "max_tokens": 0, asking the model for a reply no longer than zero tokens.
The call
The client’s zero values are useful: leave the base URL empty and it uses OpenRouter; leave the *http.Client nil (you didn’t supply one) and it uses http.DefaultClient, the ready-made client in net/http; leave the timeout at zero and it allows two minutes.
Generate is the single method that makes the client a Model the agent loop can use:
// Generate sends the conversation to the model and returns its reply.
func (c *Client) Generate(ctx context.Context,
req agent.Request) (agent.Reply, error) {
ctx, cancel := context.WithTimeoutCause(ctx, c.timeout(),
ErrCallTimeout)
defer cancel()
body, err := json.Marshal(c.wireRequest(req))
if err != nil {
return agent.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 agent.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 agent.Reply{}, fmt.Errorf("send request: %w",
callError(ctx, err))
}
defer resp.Body.Close()
return readReply(ctx, resp)
}
Everything else is standard net/http.
NewRequestWithContext binds the request to ctx, so a cancelled run abandons the call, including while the body is still arriving.
The API key travels in the Authorization header as Bearer <key>, called a bearer token because whoever holds it can make calls on your account.
defer resp.Body.Close() gives the connection back no matter how the function returns.
A deadline with a reason
The default http.Client will wait forever, and a healthy model call can take over a minute, so the client needs some limit.
http.Client.Timeout is the built-in setting for one, but it applies to every request through that client, and clients are usually shared by much of a program.
It also gives no way to say which limit expired.
The client instead sets a deadline on the context for each call. The takeaway: a slow model can’t hang the program, because every call has a time limit, and the error that comes back says why the call stopped.
How the deadline works.
The client derives the deadline from ctx for each call.
That deadline belongs to one call only; it stacks with any deadline the caller already set (the sooner of the two fires); and it can carry a reason.
context.WithTimeoutCause attaches ErrCallTimeout to the cancellation, and context.Cause retrieves it.
A caller can then test the error two ways: errors.Is(err, context.DeadlineExceeded) says a deadline fired, and ErrCallTimeout says it was this client’s.
net/http doesn’t consistently preserve both, and which one survives depends on whether the connection is HTTP/1.1 or HTTP/2.
So the client wraps in whatever is missing using %w: %w, which wraps two errors in one, and its tests verify the result over both protocol versions.
Where two minutes comes from. The two-minute figure is measured, from the recorded runs in the companion code:
| Measurement | Result |
|---|---|
| Longest single call | 76 seconds (z-ai/glm-5.3-flash, producing 2,880 reasoning tokens) |
| Calls that returned in under three seconds, in the bug-fix runs | 90% |
Two minutes covers the slow reasoning case and still catches a call that is stuck.
The two official Go SDKs pick very different defaults: openai-go has no timeout unless you set one, and anthropic-sdk-go allows a non-streaming call ten minutes.
Reading the reply
There are four distinct ways a call can fail, and the client looks for each one:
- A status other than 200. The API turned the request down, for reasons like an invalid key (401), an empty account (402), a request bigger than the model accepts, or a provider outage. The returned error includes the status and the message the API sent.
- An error object inside a 200. OpenRouter took the request, but the provider broke down before it produced a reply.
- A finish reason of
error. The provider started replying and then broke down. - A 200 whose body isn’t the expected JSON. A proxy’s HTML error page or a body cut off mid-transfer fails to decode, and the client returns a decode error.
The client reads the body through io.LimitReader with a 16 MB ceiling, so a misbehaving server can’t keep it reading without end.
Once the reply checks out, the client copies the parts the agent uses: the message, the usage (input and output tokens, cached and reasoning tokens, and the dollar cost OpenRouter includes in every reply), and the finish reason:
| Value | Meaning |
|---|---|
stop |
The model finished its reply |
length |
It reached the output limit; the text is cut off |
tool_calls |
It is asking for tools |
content_filter |
A safety filter blocked or cut the reply |
error |
The provider failed partway through |
A length reply is returned normally, with the reason in a field.
The text is truncated, but it is still text, and only the caller knows whether to keep it, ask again with a larger limit, or stop.
The agent loop built on top should be stricter than the client and refuse to treat a truncated reply as a finished answer.
What it deliberately leaves out
Each call gets exactly one attempt. Failures are routine with model APIs: 429 rate limits, 502 and 503 from overloaded providers, connections that drop halfway through a reply. The official Go SDKs handle this by retrying twice by default. That’s handy, but the caller can’t see it happen: one call just looks slow, and any budget that counts calls misses the extra attempts. Put retries in the agent loop instead, so every attempt is visible in the logs, counts against the budget, and stops when the run is cancelled.
Run it
From the code directory of a clone of the companion repository:
$ go run ./ch02
If OPENROUTER_API_KEY is unset, the program plays back a three-turn chat recorded from the real API and prints the cost of each call.
The client sends its requests through an HTTP transport, the part of net/http that actually carries a request; here the program swaps in a transport that reads the saved responses from files instead of using the network, and to the client they look exactly like real replies.
The start of that replay looks like this:
No OPENROUTER_API_KEY: replaying a saved conversation.
> What is a goroutine?
A goroutine is a lightweight thread of execution managed by the Go
runtime rather than the operating system. You start one by placing the
`go` keyword before a function call, such as `go doSomething()`, and
it runs concurrently with the rest of your program. Goroutines are
cheap to create (they start with a small, growable stack), so a Go
program can run thousands or even millions of them at once.
[43 tokens in, 122 out, $0.000065; total $0.000065]
If the key is set, you get a live chat with the default model.
For a local server, set OPENROUTER_BASE_URL and OPENROUTER_MODEL, and give OPENROUTER_API_KEY any non-empty value, because an empty key means replay.
type chatRequest struct {
Model string `json:"model"`
Messages []chatMessage `json:"messages"`
MaxTokens int `json:"max_tokens,omitzero"`
}
type chatRequest struct { Model string `json:"model"` Messages []chatMessage `json:"messages"` MaxTokens int `json:"max_tokens,omitzero"` }. In ch02/openrouter/wire.go, line 11.
field Model string `json:"model"`
field Model string `json:"model"`. In ch02/openrouter/wire.go, line 12.
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 Messages []chatMessage `json:"messages"`
field Messages []chatMessage `json:"messages"`. In ch02/openrouter/wire.go, line 13.
type chatMessage struct {
Role string `json:"role"`
Content string `json:"content"`
}
type chatMessage struct { Role string `json:"role"` Content string `json:"content"` }. In ch02/openrouter/wire.go, line 17.
field MaxTokens int `json:"max_tokens,omitzero"`
field MaxTokens int `json:"max_tokens,omitzero"`. In ch02/openrouter/wire.go, line 14.
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 Role string `json:"role"`
field Role string `json:"role"`. In ch02/openrouter/wire.go, line 18.
field Content string `json:"content"`
field Content string `json:"content"`. In ch02/openrouter/wire.go, line 19.
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 call; 2 minutes if zero
}
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 call; 2 minutes if zero }. In ch02/openrouter/client.go, line 38.
func (c *Client) Generate(ctx context.Context,
req agent.Request) (agent.Reply, error)
Generate sends the conversation to the model and returns its reply.
Generate sends the conversation to the model and returns its reply. func (c *Client) Generate(ctx context.Context, req agent.Request) (agent.Reply, error). In ch02/openrouter/client.go, line 51.
var ctx context.Context
var ctx context.Context. In ch02/openrouter/client.go, line 51.
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 req agent.Request
var req agent.Request. In ch02/openrouter/client.go, line 52.
package agent ("github.com/blackwell-systems/go-agents-book/code/ch02/agent")
Package agent is the agent loop and the types it works with.
Package agent is the agent loop and the types it works with. package agent ("github.com/blackwell-systems/go-agents-book/code/ch02/agent"). In ch02/agent.
type Request struct {
Messages []Message
Tools []ToolDef
MaxTokens int // longest reply; 0 means the provider's default
}
Request is what the harness sends the model on each turn.
Request is what the harness sends the model on each turn. type Request struct { Messages []Message Tools []ToolDef MaxTokens int // longest reply; 0 means the provider's default }. In ch02/agent/types.go, line 24.
type Reply struct {
Message Message // the assistant's text, tool calls, or both
FinishReason string // why the model stopped: "stop", "length", ...
Usage Usage // tokens counted for this call, and its cost
}
Reply is the model's answer to one Request.
Reply is the model's answer to one Request. type Reply struct { Message Message // the assistant's text, tool calls, or both FinishReason string // why the model stopped: "stop", "length", ... Usage Usage // tokens counted for this call, and its cost }. In ch02/agent/types.go, line 64.
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.
var cancel context.CancelFunc
var cancel context.CancelFunc. In ch02/openrouter/client.go, line 53.
func WithTimeoutCause(parent Context, timeout time.Duration, cause error) (Context, CancelFunc)
WithTimeoutCause behaves like [WithTimeout] but also sets the cause of the returned Context when the timeout expires.
WithTimeoutCause behaves like [WithTimeout] but also sets the cause of the returned Context when the timeout expires. func WithTimeoutCause(parent Context, timeout time.Duration, cause error) (Context, CancelFunc). Documented at pkg.go.dev, context.WithTimeoutCause.
func (c *Client) timeout() time.Duration
func (c *Client) timeout() time.Duration. In ch02/openrouter/client.go, line 201.
var ErrCallTimeout = errors.New("openrouter: model call timed out")
ErrCallTimeout is the cause recorded when a call runs past Client.Timeout.
ErrCallTimeout is the cause recorded when a call runs past Client.Timeout. var ErrCallTimeout = errors.New("openrouter: model call timed out"). In ch02/openrouter/client.go, line 24.
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.
func (c *Client) wireRequest(req agent.Request) chatRequest
wireRequest turns the agent's request into the API's JSON shape.
wireRequest turns the agent's request into the API's JSON shape. func (c *Client) wireRequest(req agent.Request) chatRequest. In ch02/openrouter/client.go, line 84.
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 ch02/openrouter/client.go, line 61.
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.
func (c *Client) baseURL() string
func (c *Client) baseURL() string. In ch02/openrouter/client.go, line 187.
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 ch02/openrouter/client.go, line 40.
var resp *http.Response
var resp *http.Response. In ch02/openrouter/client.go, line 69.
func (c *Client) httpClient() *http.Client
func (c *Client) httpClient() *http.Client. In ch02/openrouter/client.go, line 194.
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 ch02/openrouter/client.go, line 172.
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(ctx context.Context,
resp *http.Response) (agent.Reply, error)
readReply decodes a response into a Reply.
readReply decodes a response into a Reply. func readReply(ctx context.Context, resp *http.Response) (agent.Reply, error). In ch02/openrouter/client.go, line 100.
type Client struct {
// Transport specifies the mechanism by which individual
// HTTP requests are made.
// If nil, DefaultTransport is used.
Transport RoundTripper
// CheckRedirect specifies the policy for handling redirects.
// If CheckRedirect is not nil, the client calls it before
// following an HTTP redirect. The arguments req and via are
// the upcoming request and the requests made already, oldest
// ...
}
A Client is an HTTP client.
A Client is an HTTP client. type Client struct { // Transport specifies the mechanism by which individual // HTTP requests are made. // If nil, DefaultTransport is used. Transport RoundTripper // CheckRedirect specifies the policy for handling redirects. // If CheckRedirect is not nil, the client calls it before // following an HTTP redirect. The arguments req and via are // the upcoming request and the requests made already, oldest // ... }. Documented at pkg.go.dev, net/http.Client.
var DefaultClient = &Client{}
DefaultClient is the default [Client] and is used by [Get], [Head], and [Post].
DefaultClient is the default [Client] and is used by [Get], [Head], and [Post]. var DefaultClient = &Client{}. Documented at pkg.go.dev, net/http.DefaultClient.
field Timeout time.Duration
Timeout specifies a time limit for requests made by this Client.
Timeout specifies a time limit for requests made by this Client. field Timeout time.Duration. Documented at pkg.go.dev, net/http.Client.Timeout.
func Cause(c Context) error
Cause returns a non-nil error explaining why c was canceled.
Cause returns a non-nil error explaining why c was canceled. func Cause(c Context) error. Documented at pkg.go.dev, context.Cause.

