Article · AI in Go · Tool use (function calling)
AI in Go: the official SDK, LangChainGo and MCP in fast services
A map of the AI ecosystem in Go – the official Anthropic SDK, LangChainGo, the MCP Go SDK, pgvector and Ollama – plus SSE streaming with cancellation through context, structured responses, the tool runner, parallel calls with errgroup and tests with httptest.
Go is rarely the first language someone prototypes a language model in – but very often the one that runs the service handling production traffic. Model gateways, rate-limiting proxies, MCP servers, workers processing thousands of documents: these are jobs where concurrency, predictable memory use and a single static binary matter. This guide shows how to build such a service from the Go ecosystem – from the first call to the tests.
- 1
- context.Context – cancels the model call when the client disconnects or the deadline passes
- 8
- parallel calls – errgroup with a limit instead of hundreds of goroutines at once
- 0
- runtime dependencies – one static binary with the service and an MCP server
The problem: a goroutine per ticket
Halina's Pierogi has a Go service that processes customer reviews. Someone added review classification with a model: for every new review, go classify(review). It worked until one Friday evening a batch of 5,000 reviews arrived from an import. Five thousand goroutines sent requests to the API at once, most got a 429 error (rate limit), retries turned it into an avalanche, and because nobody passed a context, shutting the service down during a deployment did not stop the calls in flight – they simply died halfway.
A separate chat endpoint sent the answer only after it was fully generated and ignored the customer closing the tab – we paid for tokens nobody read.
Go has idiomatic answers to both problems. You just have to use them.
Ecosystem map
| Layer | Packages | What for |
|---|---|---|
| Provider SDKs | github.com/anthropics/anthropic-sdk-go/v2, github.com/openai/openai-go | the full API: streaming, structured outputs, tool runner, caching, batch, files |
| Framework | github.com/tmc/langchaingo | a common model interface, embeddings, vector stores, RAG chains, agents |
| Protocol | github.com/modelcontextprotocol/go-sdk | MCP servers and clients |
| Vector stores | github.com/pgvector/pgvector-go, the Qdrant client, LangChainGo modules | semantic search – see embeddings and vector databases |
| Local models | Ollama (client in LangChainGo or its own API), OpenAI-compatible servers | models and embeddings on your own hardware – see local LLMs |
| Concurrency | golang.org/x/sync/errgroup, context | parallel calls with a limit, cancellation, deadlines |
| Observability and tests | log/slog, OpenTelemetry, net/http/httptest | usage logging, tracing, a fake API in tests |
go: github.com/anthropics/anthropic-sdk-go/v2
go: github.com/tmc/langchaingo
The official SDK: an SSE stream and a structured response
The Go SDK is generated from the same specification as the others, so field names match the API, and unions (content blocks, stream events) are unpacked with AsAny() and a type switch. Two examples: an HTTP handler streaming the answer to the browser and order extraction with an enforced JSON schema.
An SSE handler and order extraction
package support
import (
"encoding/json"
"fmt"
"log/slog"
"net/http"
"github.com/anthropics/anthropic-sdk-go/v2"
)
// ChatHandler streams the model's answer to the browser as server-sent events.
func ChatHandler(client anthropic.Client) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/event-stream")
// r.Context() is cancelled when the client disconnects - the API stream stops too.
stream := client.Messages.NewStreaming(r.Context(), anthropic.MessageNewParams{
Model: "claude-opus-5-5",
MaxTokens: 64000,
System: []anthropic.TextBlockParam{{Text: "You are the support assistant of Halina's Pierogi."}},
Messages: []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock(r.FormValue("q"))),
},
})
defer stream.Close()
message := anthropic.Message{}
for stream.Next() {
event := stream.Current()
_ = message.Accumulate(event) // keep the full message for usage logging
if delta, ok := event.AsAny().(anthropic.ContentBlockDeltaEvent); ok {
if text, ok := delta.Delta.AsAny().(anthropic.TextDelta); ok {
payload, _ := json.Marshal(map[string]string{"text": text.Text})
fmt.Fprintf(w, "data: %s\n\n", payload)
flusher.Flush()
}
}
}
if err := stream.Err(); err != nil {
slog.Error("stream failed", "err", err)
return
}
slog.Info("chat done", "stop", message.StopReason,
"in", message.Usage.InputTokens, "out", message.Usage.OutputTokens)
}
}package support
import (
"context"
"encoding/json"
"fmt"
"github.com/anthropics/anthropic-sdk-go/v2"
)
type OrderDraft struct {
Lines []struct {
Dish string `json:"dish"`
Quantity int `json:"quantity"`
} `json:"lines"`
PickupTime *string `json:"pickup_time"` // nil when the customer gave no time
}
var orderSchema = map[string]any{
"type": "object",
"properties": map[string]any{
"lines": map[string]any{"type": "array", "items": map[string]any{
"type": "object",
"properties": map[string]any{
"dish": map[string]any{"type": "string", "enum": []string{"ruskie", "cabbage", "meat", "spinach"}},
"quantity": map[string]any{"type": "integer"},
},
"required": []string{"dish", "quantity"},
"additionalProperties": false,
}},
"pickup_time": map[string]any{
"anyOf": []any{map[string]any{"type": "string"}, map[string]any{"type": "null"}},
"description": "HH:MM, or null when not given",
},
},
"required": []string{"lines", "pickup_time"},
"additionalProperties": false,
}
func ExtractOrder(ctx context.Context, client anthropic.Client, text string) (*OrderDraft, error) {
resp, err := client.Messages.New(ctx, anthropic.MessageNewParams{
Model: "claude-opus-5-5",
MaxTokens: 16000,
System: []anthropic.TextBlockParam{{Text: "Turn the message into an order draft. Do not invent dishes."}},
Messages: []anthropic.MessageParam{anthropic.NewUserMessage(anthropic.NewTextBlock(text))},
OutputConfig: anthropic.OutputConfigParam{
Effort: anthropic.OutputConfigEffortLow,
Format: anthropic.JSONOutputFormatParam{Schema: orderSchema}, // structured output
},
})
if err != nil {
return nil, err
}
if resp.StopReason != anthropic.StopReasonEndTurn {
return nil, fmt.Errorf("unexpected stop reason %q", resp.StopReason)
}
var draft OrderDraft
for _, block := range resp.Content {
if t, ok := block.AsAny().(anthropic.TextBlock); ok {
if err := json.Unmarshal([]byte(t.Text), &draft); err != nil {
return nil, err
}
}
}
return &draft, nil
}The rest of this article is for members
Create a free account or sign in to read it all. Still ahead:
- Tools and MCP
- Concurrency: errgroup, a limit and one deadline
- RAG with LangChainGo, pgvector and Ollama
- Testing: a fake API with httptest
- SDK or framework?
- Checklist
- Test yourself
- What's next