Running Go natively in the cloud: multi-stage Dockerfiles with distroless images, 12-factor configuration with clean liveness and readiness endpoints, Kubernetes automation with client-go, operators built on controller-runtime and kubebuilder, and sidecars, webhooks & CRDs as extension patterns.
When integrating LLMs into production Go applications, the biggest challenge isn't sending the request, but the reliability of the response. At its core, an LLM returns text. For software, however, "unfiltered text" is risky because it is unpredictable. We therefore treat communication with an OpenAI-compatible API as a strict data contract.
Instead of relying on heavy SDKs, we use the Go standard library. This keeps the code transparent and easy to maintain. The core approach is to define structs that exactly mirror the API's JSON schema. Using json:"..." tags, we control serialization and ensure that Go types (such as float64 for temperature or int for token limits) are transmitted correctly.
JSON Mapping as a Prompt Contract
In Go, we define the API interface via structs. The JSON schema serves as a "contract": we request the model (often via the system prompt) to provide the response in a specific format, and map this directly into Go types to ensure type safety within the application.
Here is the basic structure for a chat completion without external dependencies:
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
// ChatMessage represents a single message in the chat history
type ChatMessage struct {
Role string `json:"role"` // "system", "user", "assistant"
Content string `json:"content"`
}
// ChatRequest is the body for the /v1/chat/completions API
type ChatRequest struct {
Model string `json:"model"`
Messages []ChatMessage `json:"messages"`
MaxTokens int `json:"max_tokens,omitempty"`
Temp float64 `json:"temperature"`
}
// ChatResponse maps the API response
type ChatResponse struct {
Choices []struct {
Message ChatMessage `json:"message"`
Finish string `json:"finish_reason"`
} `json:"choices"`
}
To get a response, we must send a POST request to the API endpoint. Key here is the correct handling of the Content-Type and the efficient decoding of the response using json.NewDecoder. The latter is more performant than json.Unmarshal because it reads directly from the network stream without first caching the entire body in a byte slice.
A critical point in integration is managing the context window. Every message in the Messages slice consumes tokens. If the history becomes too long, the API will truncate the oldest messages or return an error. In Go, we control this via MaxTokens and manual slice management.
func getCompletion(apiKey, model, prompt string) (string, error) {
url := "https://api.openai.com/v1/chat/completions"
reqBody := ChatRequest{
Model: model,
Messages: []ChatMessage{
{Role: "system", Content: "You are a precise Go expert."},
{Role: "user", Content: prompt},
},
MaxTokens: 500,
Temp: 0.7,
}
jsonData, _ := json.Marshal(reqBody)
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+apiKey)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("API Error: %s", resp.Status)
}
var chatResp ChatResponse
if err := json.NewDecoder(resp.Body).Decode(&chatResp); err != nil {
return "", err
}
if len(chatResp.Choices) == 0 {
return "", fmt.Errorf("no choices returned")
}
return chatResp.Choices[0].Message.Content, nil
}
⚠ Common mistake: For brevity this example swallows the errors from
json.Marshalandhttp.NewRequestwith_. In production that backfires: ifhttp.NewRequestfails,reqisnilafterwards, and the very next access toreq.Headercrashes the program. Always check errors at such a boundary and pass them on withreturn nil, err.
For a good user experience (UX), it is often undesirable for the user to wait seconds until the entire response has been generated. This is where Server-Sent Events (SSE) come into play. The API sends the response in small chunks, starting with data: { ... }.
In Go, we implement this using a bufio.Scanner that reads the response body line by line. We must remove the data: prefixes and parse the remaining JSON fragment. If we forward this response to a browser, we must cast the http.ResponseWriter to an http.Flusher to send the data immediately instead of keeping it in the buffer.
import (
"bufio"
"strings"
)
// StreamCompletion reads a streaming response from the API
func StreamCompletion(resp *http.Response) {
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
line := scanner.Text()
if line == "" {
continue
}
// SSE format: "data: { ... }"
if strings.HasPrefix(line, "data: ") {
data := strings.TrimPrefix(line, "data: ")
if data == "[DONE]" {
break
}
// Here you would decode the fragment into a struct
// and send it to the client, e.g., via fmt.Print or WebSocket
fmt.Println("Chunk received:", data)
// → Chunk received: {"choices":[{"delta":{"content":"Hi"}}]}
}
}
}
A practical note: streaming is more complex to implement because error handling (such as connection drops mid-stream) must be managed separately. For simple backend tasks, the classic request-response cycle is completely sufficient.
Check: Why is using json.NewDecoder(resp.Body).Decode(&v) preferred over json.Unmarshal(body, &v) in this context?
Answer: Because it is more efficient to read directly from the stream without buffering the entire body
json.NewDecoder reads data incrementally from an io.Reader. For large LLM responses, this saves memory as the entire response does not need to reside in a []byte slice in RAM first.
Takeaways:
json.NewDecoder for efficient processing of network responses.Messages slice.bufio.Scanner when the latency of the first response (Time to First Token) is critical.When we want to feed LLMs with our own data, we quickly hit the context limit. We cannot copy the entire company handbook into every prompt. The solution is RAG (Retrieval Augmented Generation): we retrieve only the relevant text passages and pass them as context.
The heart of this process is Embeddings. An embedding is essentially nothing more than a list of numbers ([]float64) that represents the semantic meaning of a text. Texts with similar meanings end up close to each other in a high-dimensional space.
In Go, we typically use external APIs (such as OpenAI or local models via Ollama) to obtain these vectors. Since this is a simple HTTP request, net/http is sufficient.
What is an Embedding?
An embedding maps text to a vector in a vector space. Instead of searching for exact keywords, RAG compares the "direction" of these vectors to find concepts that are thematically related, even if they use different words.
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
// EmbeddingResponse reflects the typical API response
type EmbeddingResponse struct {
Data []struct {
Embedding []float64 `json:"embedding"`
} `json:"data"`
}
func getEmbedding(text string, apiKey string) ([]float64, error) {
url := "https://api.openai.com/v1/embeddings"
payload, _ := json.Marshal(map[string]interface{}{
"input": text,
"model": "text-embedding-3-small",
})
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(payload))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+apiKey)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var res EmbeddingResponse
if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
return nil, err
}
if len(res.Data) == 0 {
return nil, fmt.Errorf("no embedding received")
}
return res.Data[0].Embedding, nil
}
Once we have vectors, we need to know which vector from a search query is closest to a stored document. The standard for this is Cosine Similarity. It measures the angle between two vectors: a value of 1.0 means identical direction (maximum similarity), while 0.0 means orthogonal (no relationship).
For production use, you would use vector databases like Pinecone, Milvus, or pgvector. However, for small datasets or prototypes, a simple in-memory store is enough.
import "math"
// CosineSimilarity calculates the similarity between two vectors
func CosineSimilarity(a, b []float64) float64 {
if len(a) != len(b) {
return 0
}
var dotProduct, normA, normB float64
for i := 0; i < len(a); i++ {
dotProduct += a[i] * b[i]
normA += a[i] * a[i]
normB += b[i] * b[i]
}
if normA == 0 || normB == 0 {
return 0
}
return dotProduct / (math.Sqrt(normA) * math.Sqrt(normB))
}
type Document struct {
Text string
Vector []float64
}
type VectorStore struct {
Docs []Document
}
func (s *VectorStore) Search(queryVec []float64, topK int) []Document {
// ponytail: linear search O(n). Switch to HNSW or FAISS for >10k documents.
type scoreDoc struct {
doc Document
score float64
}
results := make([]scoreDoc, 0, len(s.Docs))
for _, doc := range s.Docs {
results = append(results, scoreDoc{doc, CosineSimilarity(queryVec, doc.Vector)})
}
// Normally you would sort here and return the topK
// (Simplified: we return the first one; in practice, sorted by score DESC)
return []Document{results[0].doc}
}
An LLM cannot handle a 50-page PDF. We must break the text into smaller pieces (Chunks). A simple but honest heuristic is splitting by paragraphs or a fixed number of characters with a slight overlap, so context is not lost at the boundaries.
The complete pipeline looks like this:
func simpleChunker(text string, chunkSize int) []string {
var chunks []string
for len(text) > 0 {
end := chunkSize
if len(text) < chunkSize {
end = len(text)
}
chunks = append(chunks, text[:end])
// ponytail: simple slice without overlap; for better quality
// add 10-20% of the chunk as overlap with the next one.
text = text[end:]
}
return chunks
}
func GenerateRAGPrompt(query string, context []Document) string {
var contextText string
for _, doc := range context {
contextText += "- " + doc.Text + "\n"
}
return fmt.Sprintf(
"You are a helpful assistant. Use only the following context to answer the question.\n\nContext:\n%s\n\nQuestion: %s\nAnswer:",
contextText, query,
)
}
Check: Why is cosine similarity used in RAG instead of Euclidean distance?
Answer: Because it evaluates direction (meaning), regardless of vector length.
The length of a vector can be influenced by the text length. Cosine similarity normalizes this and focuses on the angle, which is semantically more precise.
Takeaways:
[]float64) that represent meaning.Up until now, we have primarily used LLMs as text generators. The problem: while a model can explain how to check the weather in Berlin, it cannot actually call an API to determine the current value. This is where Function Calling (or Tool Use) comes in.
It is important to understand: the model does not execute the Go code itself. It simply decides, based on a provided function description, that a function should be called and which parameters are required for it. It returns a structured JSON to us, and we—the developers—execute the function in our Go runtime and send the result back to the model.
The JSON Schema Principle
To let the model know which tools are available, we pass a list of definitions. These contain the function name, a description (which serves as an "instruction manual" for the model), and a JSON schema of the parameters. This is the only way the model knows that get_weather expects a location argument of type string.
// Example of a tool definition as sent to the API
type Tool struct {
Type string `json:"type"` // Usually "function"
Function struct {
Name string `json:"name"`
Description string `json:"description"`
Parameters struct {
Type string `json:"type"` // "object"
Properties map[string]interface{} `json:"properties"`
Required []string `json:"required"`
} `json:"parameters"`
} `json:"function"`
}
func weatherTool() Tool {
return Tool{
Type: "function",
Function: struct {
Name string `json:"name"`
Description string `json:"description"`
Parameters struct {
Type string `json:"type"`
Properties map[string]interface{} `json:"properties"`
Required []string `json:"required"`
} `json:"parameters"`
}{
Name: "get_weather",
Description: "Retrieves the current weather for a city",
Parameters: struct {
Type string `json:"type"`
Properties map[string]interface{} `json:"properties"`
Required []string `json:"required"`
}{
Type: "object",
Properties: map[string]interface{}{
"location": map[string]string{"type": "string", "description": "The city, e.g., Berlin"},
},
Required: []string{"location"},
},
},
}
}
A simple API call is a linear interaction. An Agent, however, operates in a loop until the goal is achieved. This process typically follows the pattern: Plan Act Observe Reflect.
In Go, we implement this using a for loop that runs until the model generates a final response or a safety limit is reached. We must send the entire history (including tool calls and their results) because the model has no memory of the individual loop iterations.
Typed Tool Results
Since different tools return different data types, we often use an interface or a struct with a Value field of type any in Go. To process results cleanly, a type switch or a central ToolResult structure that links the name of the called tool with the result is recommended.
type ToolResult struct {
ToolName string
Content string // The result as a string, since LLMs process text
}
// Simplified Agent Loop
func RunAgent(ctx context.Context, userPrompt string) (string, error) {
messages := []Message{{Role: "user", Content: userPrompt}}
maxIterations := 8 // Guardrail against infinite loops
for i := 0; i < maxIterations; i++ {
// 1. Call the model
resp, err := callLLM(ctx, messages)
if err != nil {
return "", err
}
// 2. Check if the model wants to call a tool
if len(resp.ToolCalls) == 0 {
return resp.Content, nil // Final text reached
}
// 3. Execute tool calls
for _, tc := range resp.ToolCalls {
result := executeTool(tc.Name, tc.Arguments)
// Append result to history
messages = append(messages, Message{
Role: "tool",
ToolID: tc.ID,
Content: result,
})
}
// Supplement history with the tool request before the next loop starts
messages = append(messages, resp.ToMessage())
}
return "", errors.New("max iterations reached: agent is looping")
}
func executeTool(name string, args string) string {
switch name {
case "get_weather":
// Real API logic would go here
return "The weather in Berlin is 18 degrees and sunny."
default:
return "Tool not found."
}
}
Agent systems are inherently unstable. There are three classic error patterns that we must handle in Go:
maxIterations counter (as seen in the code above) is mandatory here.context.WithTimeout to limit the total duration of the agent run.A honest tip: the more complex the tool chain, the higher the chance that the model "goes off track." It is often more efficient to break the agent into small, specialized sub-agents rather than providing 20 different tools to a single loop.
// Example of a robust execution with timeout
func SafeAgentRun(prompt string) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
res, err := RunAgent(ctx, prompt)
if err != nil {
log.Printf("Agent failed: %v", err)
return
}
fmt.Println("Result:", res)
}
Check: Why is a 'maxIterations' counter critical in an agent loop?
Answer: To prevent infinite loops during repetitive tool calls
LLMs can enter a state where they repeatedly send the same tool call if the result does not satisfy them. Without a limit, the process would run indefinitely and drive up API costs.
Takeaways:
In practice, AI applications often face the problem of latency. If you need to convert 1,000 documents into vectors (embeddings) to store them in a vector database, a sequential run with an API response time of 200ms per request would take about 3.3 minutes. This is inefficient, as the majority of that time is spent on I/O (waiting for the API).
This is where Go shines: Goroutines allow us to implement a "fan-out" pattern. We distribute the requests across many workers running in parallel. To avoid losing control—for instance, if a request triggers a fatal error or the program needs to be terminated—we use errgroup.Group from the golang.org/x/sync/errgroup package. This is an extension of sync.WaitGroup that additionally returns the first error encountered and signals all other Goroutines to abort via a context.Context.
Fan-out & errgroup
Fan-out distributes tasks across multiple parallel workers. errgroup coordinates these workers: as soon as one worker returns an error, the context for all others becomes invalid, which conserves resources and enables fast error responses.
package main
import (
"context"
"fmt"
"log"
"golang.org/x/sync/errgroup"
)
// Simulates an embedding API call
func getEmbedding(ctx context.Context, text string) (string, error) {
// In reality: http.NewRequestWithContext(ctx, ...)
return fmt.Sprintf("vec(%s)", text), nil
}
func main() {
texts := []string{"Go is great", "AI is exciting", "Pipelines are efficient"}
// errgroup.WithContext creates a context that is canceled
// as soon as one Goroutine returns an error.
g, ctx := errgroup.WithContext(context.Background())
results := make(chan string, len(texts))
for _, t := range texts {
text := t // Capture loop variable
g.Go(func() error {
emb, err := getEmbedding(ctx, text)
if err != nil {
return err
}
results <- emb
return nil
})
}
// Wait until all are finished or one throws an error
if err := g.Wait(); err != nil {
log.Fatalf("Pipeline failed: %v", err)
}
close(results)
for res := range results {
fmt.Println("Result:", res)
// → Result: vec(Go is great) — order varies
}
}
⚠ Common mistake: If
resultswere unbuffered here (make(chan string)), the workers would block on sending whileg.Wait()waits for them to finish — a deadlock, and the pipeline hangs silently forever. Thelen(texts)buffer decouples sending from receiving; alternatively drain the channel in its own goroutine before callingg.Wait().
Blindly unleashing thousands of Goroutines on an external API like OpenAI or HuggingFace will quickly result in an HTTP 429 Too Many Requests response. Parallel execution does not mean ignoring API limits. We must throttle the "speed" of our pipeline.
The standard tool for this is the Token Bucket algorithm, implemented in golang.org/x/time/rate. A rate.Limiter allows us to define a maximum number of requests per second (RPS). Before a worker starts an API call, it must request a "token" from the limiter. If no tokens are available, the worker blocks until the limiter releases capacity again. This happens synchronously and respects the context.Context, so a timeout of the entire pipeline also ends the waiting state at the limiter.
Token-Bucket Rate Limiting
Imagine a bucket that is steadily filled with tokens. Every request requires one token. If the bucket is empty, the request must wait. This prevents load spikes and ensures a steady data flow (smoothing).
package main
import (
"context"
"fmt"
"golang.org/x/time/rate"
"time"
)
func main() {
// Allow 5 requests per second, with a maximum burst of 2
limiter := rate.NewLimiter(rate.Every(time.Second/5), 2)
ctx := context.Background()
for i := 1; i <= 10; i++ {
// Blocks until a token is available or ctx is canceled
if err := limiter.Wait(ctx); err != nil {
fmt.Println("Limiter error:", err)
return
}
fmt.Printf("Request %d sent at %s\n", i, time.Now().Format("15:04:05.000"))
}
}
Despite rate limiting, network fluctuations or temporary server overloads (HTTP 5xx) can occur. A robust pipeline therefore implements "retries." A simple loop is often insufficient; "Exponential Backoff" is typically used. In this approach, the wait time between attempts is increased exponentially (e.g., 1s, 2s, 4s...), giving the server time to recover.
A critical point in concurrent pipelines is access to shared resources. If workers write results into a slice instead of using a channel, you risk "Data Races." In Go, it is essential to use the race detector. Always start your tests with go test -race ./.... The detector analyzes at runtime whether two Goroutines are accessing the same memory area simultaneously, where at least one of the accesses is a write.
// Example of a simple retry mechanism
func callAPIWithRetry(ctx context.Context, text string) (string, error) {
backoff := time.Second
for i := 0; i < 3; i++ { // Max 3 attempts
res, err := getEmbedding(ctx, text)
if err == nil {
return res, nil
}
// Only wait on temporary errors (e.g., 429 or 503)
fmt.Printf("Attempt %d failed, waiting %v...\n", i+1, backoff)
select {
case <-time.After(backoff):
backoff *= 2 // Exponential increase
case <-ctx.Done():
return "", ctx.Err()
}
}
return "", fmt.Errorf("maximum number of retries reached")
}
Check: Why is using errgroup.WithContext in an AI pipeline more advantageous than a simple sync.WaitGroup?
Answer: It allows all running workers to be stopped immediately if one reports an error.
A sync.WaitGroup stubbornly waits until everyone is finished. errgroup with Context, however, propagates errors and cancels all other operations, which saves unnecessary costs and time with expensive API calls.
Takeaways:
errgroup for fan-out patterns to manage errors centrally and control Goroutines via the context.rate.Limiter to respect API limits and proactively avoid 429 errors.go test -race to rule out hard-to-find memory corruption bugs.In the previous lessons, we learned how to integrate LLMs, handle streams, and build agents. But anyone who has "optimized" a prompt knows the problem: you fix a bug in one place, only to find that three other responses, which were previously perfect, have suddenly become unstable. In software development, we call this a regression. With LLMs, the risk is extremely high because outputs are stochastic.
The solution isn't "more hope," but a systematic evaluation process (Eval). We don't treat prompts as text files, but as code that must pass automated tests. Go is predestined for this: its strength in table-driven tests translates one-to-one to LLM evals.
A "golden dataset" is a curated list of inputs and their corresponding ideal outputs. Instead of manually checking in a chat interface whether a new version of the prompt works, we write a test that runs through hundreds of examples in seconds.
We define a structure for our test cases that stores both the input and the expected criteria (e.g., specific keywords or a certain JSON format).
Golden Dataset Eval
A fixed set of pairs (Input Expected Output) that serve as a benchmark. Every prompt change triggers a run across this set to ensure quality does not degrade.
type EvalCase struct {
Name string
Input string
Expected string // Or a validation function
}
func TestPromptRegression(t *testing.T) {
goldenSet := []EvalCase{
{
Name: "Simple Extraction",
Input: "I live in Berlin and I am 30 years old.",
Expected: `{"city": "Berlin", "age": 30}`,
},
{
Name: "Complex Context",
Input: "My location is Hamburg, age was not mentioned.",
Expected: `{"city": "Hamburg", "age": null}`,
},
}
for _, tc := range goldenSet {
t.Run(tc.Name, func(t *testing.T) {
got, err := callLLM(tc.Input) // Helper function for API call
if err != nil {
t.Fatalf("API Error: %v", err)
}
if got != tc.Expected {
t.Errorf("Regression! \nInput: %s\nWill: %s\nGot: %s", tc.Input, tc.Expected, got)
}
})
}
}
When go test turns red, we know immediately: the new prompt is worse than the old one, regardless of how "convincing" the first three manual tests in the playground seemed.
An LLM might claim to provide JSON, but then add an explanatory sentence before it or invent fields. In a production environment, this leads to crashes. We use Go's strict type system as a "guardrail."
Instead of simply accepting the output as a string, we force it through json.Unmarshal into a defined struct. During this process, we explicitly check if the response is complete.
Schema-Enforcement
The practice of immediately validating LLM outputs against a strict data schema before passing them to the business logic. Unmarshal errors are treated as "hallucinations" and trigger a retry or an error.
type UserProfile struct {
City string `json:"city"`
Age *int `json:"age"` // Pointer for optional/null
}
func validateOutput(raw string) (*UserProfile, error) {
var profile UserProfile
// We use a decoder to potentially detect unknown fields
decoder := json.NewDecoder(strings.NewReader(raw))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&profile); err != nil {
return nil, fmt.Errorf("schema violation: %w", err)
}
// Additional logic check (e.g., age cannot be negative)
if profile.Age != nil && *profile.Age < 0 {
return nil, errors.New("implausible age in LLM response")
}
return &profile, nil
}
For particularly critical parsers, we can also use go test -fuzz. Fuzzing generates semi-random, often extremely ugly inputs to see if our parsing code (which processes the LLM response) panics or exhibits security vulnerabilities.
A "better" prompt that consumes 2,000 more tokens and increases response time from 1s to 5s is often a worse prompt in production. We integrate the measurement of token counts and time directly into our test suite.
We define budgets per request. If a test case exceeds the latency limit, the test is considered failed, even if the answer is content-correct.
func TestPerformanceBudget(t *testing.T) {
start := time.Now()
resp, err := callLLM("Analyze this long text...")
duration := time.Since(start)
if duration > 3*time.Second {
t.Errorf("latency budget exceeded: %v > 3s", duration)
}
tokenCount := countTokens(resp) // e.g., via tiktoken-go
if tokenCount > 500 {
t.Errorf("token budget exceeded: %d > 500", tokenCount)
}
}
This concludes Module 4. We have traveled the path from simple API calls and structured prompt strategies to production safeguarding.
The most important takeaway: AI development is not "writing text," but an iterative engineering process. The go test loop is your most important tool. If you make a change to a prompt without having a corresponding test case in the golden dataset, you are building technical debt.
Weekly Check: Have you mastered the following points?
Check: Why is using
decoder.DisallowUnknownFields()useful when validating LLM outputs?Answer: It detects when the LLM invents fields that are not defined in the spec.
LLMs tend to generate 'helpful' additional fields. By using DisallowUnknownFields, we ensure that the model adheres exactly to our schema and does not leak unexpected data into the system.
Takeaways:
json.Unmarshal as guardrails against hallucinations.Course navigation: ← Module 3 · All 20 modules · Module 5 →