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.
In Module 4, we built LLM clients using the standard library (net/http, encoding/json). This works for individual requests — but as soon as you need workflows like Retrieval Augmented Generation (RAG), tool-calling, or agent loops, the code quickly becomes unwieldy. The solution: specialized frameworks that build on Go's ecosystem standards and provide additional abstractions for typical AI workflows.
The Go AI stack currently consists of four layers: official SDKs from providers (OpenAI, Anthropic, Google), workflow frameworks for complex pipelines (LangChainGo, Eino), streaming & integration tools (Genkit), and data infrastructure (vector databases, embedding clients). The good news: All these frameworks build on context.Context, io.Reader/io.Writer, and Go types — there is no magic, only solid interface design.
Interface Design as Go's Strength
Ask a Python developer to explain the differences between LangChain, LlamaIndex, and Microsoft's Semantic Kernel, and you'll get a long list of incompatible classes and magical string workarounds. In Go, three rules suffice: 1) Every AI call receives a context.Context for cancellation and timeouts, 2) responses come as io.Reader or directly as structs, and 3) errors implement error. This makes it easy to swap components — an Embedder interface works with OpenAI embeddings and local Ollama embeddings alike.
Providers have offered official Go SDKs since 2023/24. They abstract the REST API, provide type safety, and save boilerplate — but they only cover the provider's basic functionality.
package main
import (
"context"
"fmt"
"github.com/openai/openai-go"
)
func main() {
client := openai.NewClient("sk-...")
resp, err := client.Chat.Completions.New(
context.Background(),
&openai.ChatCompletionNewParams{
Model: openai.F("gpt-4o-mini"),
Messages: openai.F([]openai.ChatCompletionMessageParamUnion{
&openai.ChatCompletionMessageParam{
Role: openai.F("user"),
Content: openai.F("Explain the Go interface {} in one sentence."),
},
}),
MaxTokens: openai.F(100),
Temperature: openai.F(0.0),
},
)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Response:", *resp.Choices[0].Message.Content)
// → Response: In Go, an interface defines a contract (method + signature) that any type can fulfill by implementing that method with a matching signature.
}
For Anthropic, there is github.com/anthropics/anthropic-sdk-go with a similar API design:
package main
import (
"context"
"fmt"
"github.com/anthropics/anthropic-sdk-go"
)
func main() {
client := anthropic.NewClient("sk_ant_...")
resp, err := client.Messages.New(
context.Background(),
&anthropic.MessageNewParams{
Model: anthropic.F("claude-3-5-sonnet"),
MaxTokens: openai.F(1024),
Messages: anthropic.F([]anthropic.MessageParam{
{Role: anthropic.MessageRoleUser, Content: []anthropic.TextBlockParam{
{Type: "text", Text: "What is the difference between struct and interface in Go?"},
}},
}),
},
)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Response:", resp.Content[0].Text)
// → Response: A struct is a concrete type that groups data fields together, while an interface is a contract that types can satisfy by implementing methods.
}
⚠ Common mistake: The SDKs from 2023/24 often still expect pointers to structs (
openai.F(...)is a helper that returns*T), and the API relies oncontext.Contextfor timeouts. Usingcontext.Background()here without a timeout, while simultaneously launching long-running batch jobs, risks a crashing client request blocking the entire service. Always work withcontext.WithTimeout(context.Background(), 30*time.Second)or better: pass the timeout context from the HTTP handler (r.Context()).
Check: What advantage do official Go SDKs have over a manual net/http call?
Answer: They provide type safety and simpler error handling
Official SDKs abstract the REST API and provide type safety through Go structs. However, they typically only cover the provider's basic functionality. Complex workflows such as RAG or agent loops must be built by developers themselves or require additional frameworks such as LangChainGo.
Takeaways:
context.Context with timeout (e.g., via r.Context() from HTTP handlers), otherwise long-running requests can block the service.context.Context for cancellation, error for error handling.LLMs return text — but text is unpredictable for software. Structured output forces the model to provide its response in a defined format (usually JSON) that can be directly parsed into Go structs. This is not a luxury, but a necessity for survival: Now that LLMs not only provide answers but also call tools and process data, the output must be machine-readable.
LangChainGo (github.com/tmc/langchaingo) is currently the best-known Go framework for AI workflows. It offers a well-thought-out schema package for structured output: With WithStructuredOutput, you can pass a Go struct to the LLM, and the framework automatically generates the appropriate JSON schema for the prompt. The model is then asked to provide the response in this format.
Structured Output = Type Safety in AI Workflows
Structured Output is nothing more than forcing the LLM to return its response in a defined JSON format that can be directly parsed into Go structs. LangChainGo makes this particularly easy by automatically generating the JSON schema from the struct. Important: The LLM can still return invalid JSON — validation of the output remains mandatory!
A practical example: We want the LLM to classify a user request and return the classification in a struct.
package main
import (
"context"
"fmt"
"github.com/tmc/langchaingo/llms/openai"
"github.com/tmc/langchaingo/schema"
)
// Classification is the schema we expect from the LLM
type Classification struct {
Category string `json:"category" description:"The main category of the request: support, sales, bug, feature"`
Priority int `json:"priority" description:"1-5, with 5 being the most urgent"`
Description string `json:"description" description:"Brief summary of the request"`
}
func main() {
llm, _ := openai.New(openai.WithToken("sk-..."), openai.WithModel("gpt-4o-mini"))
resp, err := llm.GenerateContent(
context.Background(),
"Classify: The customer reports that order #4711 has not arrived. What category and priority is this?",
schema.WithStructuredOutput[Classification](),
)
if err != nil {
fmt.Println("Error:", err)
return
}
// The response is directly available as a struct
class := resp.StructuredContent
fmt.Printf("Category: %s, Priority: %d, Description: %s",
class.Category, class.Priority, class.Description)
// → Category: support, Priority: 5, Description: Customer reports missing order #4711
}
With structured output alone, we can already extract specific data from LLM responses. But what if the LLM not only needs to provide answers but also initiate actions? This is where tool-calling comes into play: The LLM decides based on its tool descriptions which tool to call and provides the parameters as JSON.
LangChainGo supports this through its tools package. Each tool implements the Tool interface with Name(), Description(), and Call(ctx, input):
package main
import (
"context"
"fmt"
"github.com/tmc/langchaingo/llms/openai"
"github.com/tmc/langchaingo/schema"
"github.com/tmc/langchaingo/tools"
)
// WetterTool calls a hypothetical weather API
type WetterTool struct{}
func (WetterTool) Name() string { return "get_weather" }
func (WetterTool) Description() string {
return "Retrieves the current weather for a city. Parameter: location (string). Returns the weather as a string."
}
func (WetterTool) Call(ctx context.Context, input string) (string, error) {
// In reality: HTTP call to weather API
return fmt.Sprintf("Weather in %s: sunny, 22°C", input), nil
}
func main() {
llm, _ := openai.New(openai.WithToken("sk-..."))
weatherTool := &WetterTool{}
llmWithTools := llm.WithTools([]tools.Tool{weatherTool})
// The LLM decides for itself whether to call a tool and which one
resp, err := llmWithTools.GenerateContent(
context.Background(),
"What is the weather like today in Berlin?",
schema.WithStructuredOutput[map[string]any](),
)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Response:", resp.Content)
// → Response: get_weather{"location": "Berlin"}
// Now we need to call the tool ourselves (see text for details)
result, _ := WetterTool{}.Call(context.Background(), "Berlin")
fmt.Println("Weather:", result)
// → Weather: Weather in Berlin: sunny, 22°C
}
⚠ Common mistake: Tool-calling, as in the example above, only provides the decision of which call will be invoked. The actual execution (the
Callto the tool) is the developer's responsibility — in a loop (Agent-Loop, see Lesson 70). Many developers expect the LLM to execute the tool directly, but this would be insecure: the LLM has no access to your file system, your database, or your internal APIs. It only decides that a tool should be called.
Even with structured output and tool-calling: The LLM can lie. It can:
Therefore: Always validate! A simple tool is the validator package (e.g., github.com/go-playground/validator/v10):
package main
import (
"context"
"fmt"
"github.com/go-playground/validator/v10"
)
type Classification struct {
Category string `json:"category" validate:"oneof=support sales bug feature"`
Priority int `json:"priority" validate:"min=1,max=5"`
Description string `json:"description"`
}
func validateClass(c Classification) error {
validate := validator.New()
return validate.Struct(c)
}
For comprehensive prompt injection protection and trust boundary definition, we refer to the security architecture on prompt injection and trust boundaries.
Check: Why must the actual tool execution be performed by the developer in tool-calling?
Answer: Because the LLM would otherwise have direct access to the file system, which is a security risk
LLMs run in isolated environments (the provider's API) and have no access to your file system, database, or internal APIs. Tool-calling therefore means: Based on the tool descriptions, the LLM decides WHICH tool should be called with WHICH parameters — the actual execution then takes place in your Go runtime, where you retain control over security, permissions, and validation.
Takeaways:
The first generation of AI applications has a critical drawback: The user waits. With long responses or complex calculations, this can take several seconds. Streaming changes this: Instead of delivering the entire response at once, tokens are sent to the user as quickly as possible — often word by word. This not only improves perceived performance but also enables interactions like "thinking aloud" (Chain-of-Thought) or real-time feedback.
There are two established protocols: Server-Sent Events (SSE) and WebSockets. SSE is the simpler protocol — HTTP-based, unidirectional (Server → Client), excellent for LLM streaming. WebSockets are bidirectional and more complex, but necessary for real-time collaboration (e.g., co-editing with AI support).
SSE vs. WebSockets: Choosing the Right Tool
Server-Sent Events (SSE) is an HTTP-based streaming protocol that establishes a unidirectional connection from the server to the client. Each message is a text line with the prefix data: . SSE works excellently for LLM streaming because the client only receives the answers and does not need to actively communicate with the server. WebSockets, on the other hand, are bidirectional and enable real-time interactions in both directions, but are more complex to implement and maintain.
The OpenAI API supports streaming via SSE. In Go, we implement this with net/http and bufio.Scanner — just like in Module 4, except we need to parse the SSE formats:
package main
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
)
type StreamResponse struct {
Choices []struct {
Delta struct {
Content string `json:"content"`
} `json:"delta"`
FinishReason *string `json:"finish_reason"`
} `json:"choices"`
}
// Proxy handler that forwards OpenAI streaming to the client
func handleStreamProxy(w http.ResponseWriter, r *http.Request) {
// Client API key from header
apiKey := r.Header.Get("X-API-Key")
if apiKey == "" {
http.Error(w, "X-API-Key missing", http.StatusUnauthorized)
return
}
// Prepare OpenAI request
reqBody := map[string]interface{}{
"model": "gpt-4o-mini",
"messages": []map[string]string{{"role": "user", "content": "Tell me a short story."}},
"stream": true,
}
jsonData, _ := json.Marshal(reqBody)
req, _ := http.NewRequestWithContext(r.Context(), "POST",
"https://api.openai.com/v1/chat/completions", bytes.NewBuffer(jsonData))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+apiKey)
resp, err := http.DefaultClient.Do(req)
if err != nil {
http.Error(w, "Stream error", http.StatusInternalServerError)
return
}
defer resp.Body.Close()
// Client: Set SSE headers
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
// Parse OpenAI stream and forward
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
line := scanner.Text()
if line == "" {
continue
}
if strings.HasPrefix(line, "data: ") {
data := strings.TrimPrefix(line, "data: ")
if data == "[DONE]" {
break
}
// Forward as SSE
fmt.Fprintf(w, "data: %s\n\n", data)
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
}
}
}
func main() {
http.HandleFunc("/stream", handleStreamProxy)
fmt.Println("Streaming proxy running on :8080")
http.ListenAndServe(":8080", nil)
}
// Terminal: curl -N http://localhost:8080/stream -H "X-API-Key: sk-..."
// → data: {"id":"chatcmpl-...","object":"chat.completion.chunk","choices":[{"delta":{"content":"Once"}}]}
// → data: {"id":"chatcmpl-...","object":"chat.completion.chunk","choices":[{"delta":{"content":" upon"}}]}
// → data: {"id":"chatcmpl-...","object":"chat.completion.chunk","choices":[{"delta":{"content":" a"}}]}
// → data: [DONE]
For chat applications where clients and servers can send messages to each other simultaneously, WebSockets are the better choice. The github.com/gorilla/websocket package is the de facto standard in Go:
package main
import (
"fmt"
"log"
"net/http"
"time"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { return true }, // In production: check origin!
}
func handleChat(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println("Upgrade error:", err)
return
}
defer conn.Close()
// Receive messages
for {
messageType, p, err := conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
log.Println("WebSocket error:", err)
}
break
}
// Echo: send message back (in reality: call LLM)
if messageType == websocket.TextMessage {
// Simulate a streaming response
messages := []string{"Understood...", "I'm thinking...", "Here's your answer: " + string(p)}
for _, msg := range messages {
if err := conn.WriteMessage(websocket.TextMessage, []byte(msg)); err != nil {
log.Println("Write error:", err)
return
}
time.Sleep(500 * time.Millisecond) // Simulated delay
}
}
}
}
func main() {
http.HandleFunc("/chat", handleChat)
fmt.Println("WebSocket server running on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
// Terminal with websocat (or browser JS):
// → $ websocat ws://localhost:8080/chat
// → > Hello!
// → < Understood...
// → < I'm thinking...
// → < Here's your answer: Hello!
⚠ Common mistake: WebSocket connections can remain open for a very long time — if the client does not properly close the connection, goroutines and memory remain allocated. Always use
defer conn.Close()in the handler function, and prompt the client to close the connection with aCloseframe (e.g., when the user closes the browser window). For a robust vector store addition to streaming services, see Module 6 of the architecture guide on database selection.
Check: Which protocol is best for unidirectional LLM streaming?
Answer: SSE — simple, HTTP-based, and perfect for server→client streaming
Server-Sent Events (SSE) is the ideal protocol for LLM streaming: It is HTTP-based, works through proxies and firewalls, and is specifically optimized for server→client streaming. WebSockets would be overkill and bring unnecessary complexity if only one direction is needed. gRPC is efficient but not universally supported and requires special client implementations.
Takeaways:
bufio.Scanner and http.Flusher.github.com/gorilla/websocket).defer conn.Close()) to avoid resource leaks.In Module 4, we already learned about embeddings as numerical representations of text. For RAG (Retrieval Augmented Generation), they are indispensable: Instead of searching for exact keywords, RAG compares the semantic similarity of vectors. This allows finding documents that are thematically related, even if they use different words.
The challenge: Storing embeddings efficiently and querying them effectively. For small datasets (up to a few thousand documents), an in-memory solution with cosine similarity is sufficient. For production applications, you need specialized vector databases optimized for this task: fast similarity queries over millions of vectors.
Vector Databases: The Index for AI Knowledge
A vector database stores embeddings and enables lightning-fast similarity queries. Instead of searching for exact matches like a traditional database, it finds the "nearest neighbors" in the high-dimensional vector space. The two most established solutions for Go developers are pgvector (PostgreSQL extension) and Qdrant (standalone).
Before we can store vectors, we need to generate them. The OpenAI Embeddings API is the simplest entry point:
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
)
type EmbeddingRequest struct {
Input string `json:"input"`
Model string `json:"model"`
}
type EmbeddingResponse struct {
Data []struct {
Embedding []float64 `json:"embedding"`
} `json:"data"`
}
// getEmbedding generates an embedding for the given text
func getEmbedding(apiKey, text string) ([]float64, error) {
payload, _ := json.Marshal(EmbeddingRequest{
Input: text,
Model: "text-embedding-3-small",
})
req, _ := http.NewRequestWithContext(
context.Background(),
"POST",
"https://api.openai.com/v1/embeddings",
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 result EmbeddingResponse
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, err
}
if len(result.Data) == 0 {
return nil, fmt.Errorf("no embedding received")
}
return result.Data[0].Embedding, nil
}
func main() {
emb, _ := getEmbedding("sk-...", "Go is a statically typed programming language.")
fmt.Printf("Embedding has %d dimensions\n", len(emb))
// → Embedding has 1536 dimensions
}
pgvector is a PostgreSQL extension that enables vector operations directly in the database. The github.com/pgvector/pgvector-go package provides Go bindings:
package main
import (
"context"
"fmt"
"log"
"github.com/jackc/pgx/v5/pgxpool"
_ "github.com/pgvector/pgvector-go"
)
func main() {
// Connect to PostgreSQL with pgvector
conn, err := pgxpool.New(context.Background(),
"postgres://user:password@localhost:5432/vector_db?sslmode=disable")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
// Table for documents with embeddings
_, err = conn.Exec(context.Background(), `
CREATE TABLE IF NOT EXISTS documents (
id SERIAL PRIMARY KEY,
content TEXT,
embedding vector(1536)
)
`)
if err != nil {
log.Fatal(err)
}
// Insert embedding
emb, _ := getEmbedding("sk-...", "Go supports concurrent programming with goroutines.")
_, err = conn.Exec(context.Background(),
"INSERT INTO documents (content, embedding) VALUES ($1, $2)",
"Go supports concurrent programming with goroutines.",
emb,
)
if err != nil {
log.Fatal(err)
}
// Search by similarity (top 3)
queryEmb, _ := getEmbedding("sk-...", "How do goroutines work in Go?")
rows, err := conn.Query(context.Background(), `
SELECT content, embedding <=> $1 as distance
FROM documents
ORDER BY distance ASC
LIMIT 3
`, queryEmb)
if err != nil {
log.Fatal(err)
}
fmt.Println("Hits:")
for rows.Next() {
var content string
var distance float64
rows.Scan(&content, &distance)
fmt.Printf("• %s (Distance: %.4f)\n", content, distance)
}
// → Hits:
// → • Go supports concurrent programming with goroutines. (Distance: 0.1234)
}
Qdrant is a standalone vector database that runs as a separate service. The Go client package github.com/qdrant/go-client provides an idiomatic API:
package main
import (
"context"
"fmt"
"log"
"github.com/qdrant/go-client/qdrant"
)
func main() {
// Connect to local Qdrant (default: :6333)
client := qdrant.NewClient(qdrant.WithHost("localhost"), qdrant.WithPort(6333))
// Create collection (similar to a table)
_, err := client.CreateCollection(context.Background(), &qdrant.CreateCollection{
CollectionName: "go_docs",
VectorsConfig: &qdrant.VectorsConfig{
Size: 1536,
Distance: qdrant.DistanceCosine,
},
})
if err != nil {
log.Fatal(err)
}
// Insert document
emb, _ := getEmbedding("sk-...", "Go has a built-in HTTP server in the net/http package.")
point := &qdrant.PointStruct{
ID: &qdrant.PointID{UUID: qdrant.NewUUID()},
Vector: emb,
Payload: map[string]interface{}{
"content": "Go has a built-in HTTP server in the net/http package.",
},
Collections: []string{"go_docs"},
}
_, err = client.Upsert(context.Background(), &qdrant.UpsertPoints{
CollectionName: "go_docs",
Points: []*qdrant.PointStruct{point},
})
if err != nil {
log.Fatal(err)
}
// Search for similar documents
queryEmb, _ := getEmbedding("sk-...", "How do I build a web server in Go?")
result, err := client.Search(context.Background(), &qdrant.SearchPoints{
CollectionName: "go_docs",
Vector: queryEmb,
Limit: 3,
})
if err != nil {
log.Fatal(err)
}
fmt.Println("Hits:")
for _, scoredPoint := range result.Result {
content := scoredPoint.Payload["content"].(string)
fmt.Printf("• %s (Score: %.4f)\n", content, scoredPoint.Score)
}
// → Hits:
// → • Go has a built-in HTTP server in the net/http package. (Score: 0.8765)
}
⚠ Common mistake: Choosing a vector database based solely on performance. pgvector is ideal if you already use PostgreSQL and want to store data together with relational data — you can conveniently combine vector operations with SQL. Qdrant, on the other hand, offers special features for vector search such as metadata filtering during search (hybrid search) and is easier to scale as a standalone service. For a detailed decision guide, see Module 6 of the architecture guide on database selection.
Check: Which operator is used in pgvector to measure similarity between vectors?
Answer: <=> — Cosine similarity (the smaller, the more similar)
In pgvector, the
<=>operator is used for cosine similarity. The smaller the value, the more similar the vectors are. This is not intuitive (one might expect a similarity value between 0 and 1), but it corresponds to the mathematical definition: cosine similarity = (a • b) / (||a|| * ||b||). In vector space, a small distance here means high similarity.
Takeaways:
github.com/pgvector/pgvector-go) is ideal if you already use PostgreSQL and want to combine relational with vector data.github.com/qdrant/go-client) is a standalone solution with special features for vector search and hybrid search.A simple API call to an LLM is a linear interaction: Request → Response → Done. An agent, on the other hand, operates in a loop and can independently gather information, call tools, and make decisions. The foundations from this module (Lessons 66-69) can now be combined into a complete agent system: The agent uses structured output to make decisions, calls tools (e.g., database queries or external APIs), and iterates until the goal is achieved.
The key is the Agent Loop: Plan → Act → Observe → Reflect. In Go, we implement this as a simple loop where each iteration includes an LLM call, tool executions, and result evaluations.
The Agent Loop: Plan – Act – Observe – Reflect
An agent loop consists of four phases that run in a loop: 1) Planning: The LLM decides what action is most appropriate next. 2) Acting: The agent performs the planned actions (e.g., tool calls). 3) Observing: The results of the actions are collected. 4) Reflecting: The LLM evaluates the results and plans the next iteration. The loop runs until the goal is achieved or an abort criterion (e.g., maximum iterations) is met.
LangChainGo provides a basic agent structure with its agent package. Here's a simplified example:
package main
import (
"context"
"fmt"
"strings"
"github.com/tmc/langchaingo/agents"
"github.com/tmc/langchaingo/llms/openai"
"github.com/tmc/langchaingo/tools"
)
// SearchTool simulates searching for information
type SearchTool struct{}
func (SearchTool) Name() string { return "search" }
func (SearchTool) Description() string {
return "Search for information. Parameter: query (string). Returns search results as a string."
}
func (SearchTool) Call(ctx context.Context, input string) (string, error) {
// In reality: database or API query
return fmt.Sprintf("Search result for '%s': Go is a programming language from Google.", input), nil
}
// CalculateTool simulates a calculation
type CalculateTool struct{}
func (CalculateTool) Name() string { return "calculate" }
func (CalculateTool) Description() string {
return "Perform a mathematical calculation. Parameter: expression (string, e.g., '2+2'). Returns the result as a string."
}
func (CalculateTool) Call(ctx context.Context, input string) (string, error) {
// Simplified: only + and -
parts := strings.Split(input, "+")
if len(parts) == 2 {
return fmt.Sprintf("%d", len(parts[0])+len(parts[1])), nil
}
parts = strings.Split(input, "-")
if len(parts) == 2 {
return fmt.Sprintf("%d", len(parts[0])-len(parts[1])), nil
}
return "Invalid expression", nil
}
func main() {
llm, _ := openai.New(openai.WithToken("sk-..."), openai.WithModel("gpt-4o-mini"))
// Create tools
searchTool := &SearchTool{}
calculateTool := &CalculateTool{}
// Create agent
agent := agents.NewOneShotAgent(
llm,
[]tools.Tool{searchTool, calculateTool},
agents.WithMaxIterations(5), // Guardrail: maximum iterations
)
// Run agent
result, err := agent.Run(context.Background(), "What is 2+2 and how many letters does the result have?")
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Answer:", result)
// → Answer: 2+2 = 4. The word "4" has 1 letter.
}
Agents are powerful, but also risky. Without proper safeguards, they can:
Three essential guardrails are:
The simplest but most effective measure. Every agent should have a limit on the number of loop iterations:
const MaxIterations = 10
func RunAgent(ctx context.Context, userPrompt string) (string, error) {
messages := []Message{{Role: "user", Content: userPrompt}}
for i := 0; i < MaxIterations; i++ {
// Call LLM
resp, err := callLLM(ctx, messages)
if err != nil {
return "", err
}
// Check if tool calls are needed
if len(resp.ToolCalls) == 0 {
return resp.Content, nil
}
// Execute tools and store results
for _, tc := range resp.ToolCalls {
result := executeTool(tc)
messages = append(messages, Message{
Role: "tool",
Content: result,
})
}
messages = append(messages, resp.ToMessage())
}
return "", fmt.Errorf("maximum iterations (%d) reached", MaxIterations)
}
Each iteration should have a time limit to prevent hanging tool calls or LLM calls:
func RunAgentWithTimeout(ctx context.Context, userPrompt string) (string, error) {
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
return RunAgent(ctx, userPrompt)
}
Not all user inputs are suitable for an agent. Validate:
func validateInput(input string) error {
if len(input) > 10000 {
return fmt.Errorf("prompt too long (max: 10000 chars)")
}
// Further validations (e.g., detect harmful content)
return nil
}
func validateToolResult(toolName, result string) error {
// Tool-specific validation
switch toolName {
case "database_query":
if len(result) > 5000 {
return fmt.Errorf("result too large")
}
}
return nil
}
For a comprehensive prompt injection protection strategy and trust boundary definitions, we recommend Module 9 of the Security Architecture.
An agent can function without being correct. Evals (Evaluations) are automated tests that ensure your AI system delivers the desired quality. In Go, we can use table-driven tests for this:
package main
import (
"testing"
)
// Test case for prompt regressions
type EvalCase struct {
Name string
Input string
Expected string // Or a validation function
}
func TestAgentRegression(t *testing.T) {
cases := []EvalCase{
{
Name: "Simple calculation",
Input: "What is 2+2?",
Expected: "4",
},
{
Name: "More complex question",
Input: "How many letters does the word 'programming' have?",
Expected: "14",
},
}
for _, tc := range cases {
t.Run(tc.Name, func(t *testing.T) {
result, err := RunAgent(context.Background(), tc.Input)
if err != nil {
t.Fatalf("Agent error: %v", err)
}
if !strings.Contains(result, tc.Expected) {
t.Errorf("Regression! Input: %s\nExpected: %s\nGot: %s",
tc.Input, tc.Expected, result)
}
})
}
}
// Test for token budgets
func TestTokenBudget(t *testing.T) {
longInput := strings.Repeat("a", 10000)
_, err := RunAgent(context.Background(), longInput)
if err == nil {
t.Error("Expected error for too long input, but none received")
}
}
// Test for iteration budget
func TestIterationBudget(t *testing.T) {
// A prompt that would drive the agent into a loop
loopInput := "Repeat the last tool over and over"
_, err := RunAgent(context.Background(), loopInput)
if err == nil {
t.Error("Expected error for too many iterations, but none received")
}
if !strings.Contains(err.Error(), "maximum iterations") {
t.Errorf("Expected iteration error, but got: %v", err)
}
}
⚠ Common mistake: Running evals only with "happy path" test cases. With agents, it's the edge cases that cause problems in production: empty inputs, very long texts, unexpected tool results, network timeouts. Without tests for these, you won't discover regressions until they're already in production. Table-driven tests make it easy to build a comprehensive test suite — use Go's strength here!
This concludes Module 14 — a journey through the entire Go AI stack. We have learned how to:
This concludes Module 14. The most important insight throughout the AI section: AI development is not "writing text," but an iterative engineering process. Prompts are code, agents are services, and quality assurance is mandatory — not optional.
Week Check: Do you master the following points?
Takeaways:
Course navigation: ← Module 13 · All 20 modules · Module 15 →