Chapter 1: Introduction to AI Agents and Google ADK for Go
What You Will Learn
Position AI agents as deterministic, observable request processors within existing Go HTTP services rather than autonomous background daemons
Understand the IncidentOps Copilot domain model; incidents, alerts, and services as concrete Go types that persist through all chapters
Establish proper module boundaries using cmd/incidentops for the binary and internal/ for domain logic, agents, and tools
Initialize the baseline HTTP server that accepts alert payloads and logs them, creating the insertion point for ADK agent invocation in Chapter 4
Apply safety and observability constraints as foundational architecture decisions, not retrofit features
Prerequisites
No additional prerequisites beyond those listed in About This Book.
Concept Overview
An AI agent in production backend systems is a request-scoped function. It uses a language model to transform structured input into structured output while maintaining deterministic boundaries. Unlike autonomous background processes, agents in Go services run inside standard HTTP handlers. They consume context, return errors, and participate in the same distributed traces as your database calls and RPC clients.
Google's Agent Development Kit (ADK) for Go provides the runtime, session management, and model integration necessary to build these agents without leaving the Go ecosystem. It embeds directly into existing services. You instantiate a runner within a handler, invoke it with a session, and receive a result. The agent does not own the process lifecycle; your net/http server does. This pattern keeps resource management explicit and allows agents to reuse existing middleware for authentication, rate limiting, and logging.
I once watched a team deploy their triage agent as a separate microservice; the resulting network partitions added 200ms of latency to every alert. Agents do not belong in separate microservices. That pattern creates network partitions and serialization overhead for no benefit. IncidentOps Copilot demonstrates the embedded architecture. It is a multi-agent incident response assistant for cloud service operations that runs inside an existing Go operations service. The system ingests alerts from monitoring systems, triages them through specialized agents, gathers diagnostics, drafts status updates, and requests human approval for sensitive actions such as rollback or customer communication. All agent activity remains inside the service boundary; no separate microservices required.
The domain model centers on three core entities. An Alert represents an incoming signal from a monitoring system with a unique fingerprint and severity. An Incident aggregates related alerts into a tracked operational event with status and ownership. A Service represents the deployable backend component affected by the incident. These types travel through the system as JSON over HTTP initially; later chapters will add ADK-specific wrappers.
Safety and observability are not features you add after deployment. They are constraints that shape the initial structure, determining how you write handlers and manage context from the first line of code. Every agent invocation must accept a context.Context for cancellation. Every decision must emit OpenTelemetry traces, and every sensitive action must pause for human confirmation. Building these hooks into the skeleton prevents retrofitting chaos later.
Step-by-Step Implementation
Step 1: Define Severity and Status Enumerations
Create internal/domain/types.go. Define Severity and Status as iota constants to ensure type safety across the module.
package domain
type Severity int
const (
SeverityUnknown Severity = iota
SeverityLow
SeverityMedium
SeverityHigh
SeverityCritical
)
type Status int
const (
StatusOpen Status = iota
StatusInProgress
StatusResolved
StatusClosed
)
These enumerations prevent string comparison errors in conditional logic. They appear in both database persistence layers and JSON payloads; later chapters will extend them with validation methods.
Step 2: Define Core Domain Structs
Append to internal/domain/types.go after Step 1. Define Incident, Alert, and Service. These structs represent the authoritative data shapes for the IncidentOps Copilot domain.
import "time"
type Incident struct {
ID string `json:"id"`
Severity Severity `json:"severity"`
Status Status `json:"status"`
AffectedService string `json:"affected_service"`
Title string `json:"title"`
CreatedAt time.Time `json:"created_at"`
Owner string `json:"owner"`
}
type Alert struct {
ID string `json:"id"`
Source string `json:"source"`
Fingerprint string `json:"fingerprint"`
Summary string `json:"summary"`
Labels map[string]string `json:"labels"`
Severity Severity `json:"severity"`
ServiceName string `json:"service_name"`
}
type Service struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
Version string `json:"version"`
Labels map[string]string `json:"labels"`
HealthCheck string `json:"health_check"`
}
JSON tags ensure consistent serialization across internal REST clients and external webhooks. The Fingerprint field on Alert provides deduplication logic for monitoring systems that resend identical signals.
Step 3: Configure the Server
Create internal/server/config.go. Define a Config struct to hold server parameters. This separates configuration from construction logic and simplifies testing.
package server
import "time"
type Config struct {
Port string
ReadTimeout time.Duration
WriteTimeout time.Duration
ShutdownTimeout time.Duration
}
Using a struct rather than global variables allows tests to spin up ephemeral servers on random ports without environment variable manipulation.
Step 4: Construct the Server
Create internal/server/server.go. Define the Server struct and a constructor. The server holds dependencies; currently this is only the configuration and a ServeMux, but later chapters will add database pools, ADK runners, and telemetry providers here.
package server
import "net/http"
type Server struct {
config Config
mux *http.ServeMux
}
func NewServer(cfg Config) *Server {
return &Server{
config: cfg,
mux: http.NewServeMux(),
}
}
The constructor pattern ensures the server is always initialized with valid dependencies. It returns a concrete pointer, not an interface, following Go best practices for internal packages.
Step 5: Implement the Alert Handler
Append to internal/server/server.go after Step 4. This handler accepts POST requests containing Alert JSON, creates an Incident, and logs the receipt. This is the precise location where Chapter 4 will insert ADK agent invocation.
import (
"encoding/json"
"log"
"net/http"
"time"
"incidentops/internal/domain"
)
func (s *Server) HandleAlert(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var alert domain.Alert
if err := json.NewDecoder(r.Body).Decode(&alert); err != nil {
http.Error(w, "Invalid alert payload", http.StatusBadRequest)
return
}
// Create incident from alert (persistence added in Chapter 4)
incident := domain.Incident{
ID: alert.Fingerprint,
Severity: alert.Severity,
Status: domain.StatusOpen,
AffectedService: alert.ServiceName,
Title: alert.Summary,
CreatedAt: time.Now(),
}
// Service metadata will be enriched by ADK tools in Chapter 5
var svc domain.Service
log.Printf("Created incident %s for service %s from alert %s",
incident.ID, svc.Name, alert.Fingerprint)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusAccepted)
json.NewEncoder(w).Encode(map[string]string{
"status": "received",
"incident": incident.ID,
})
}
The handler validates HTTP semantics before touching business logic. It returns 202 Accepted immediately. Asynchronous processing fits agent workflows better than synchronous blocking. The domain.Alert reference demonstrates the import path for internal packages.
Step 6: Register Routes
Append to internal/server/server.go after Step 5. Add the RegisterRoutes method to map HTTP paths to handler methods. Keeping registration explicit prevents magic routing tables and makes the API surface visible in one location.
func (s *Server) RegisterRoutes() {
s.mux.HandleFunc("/api/v1/alerts", s.HandleAlert)
}
func (s *Server) Handler() http.Handler {
return s.mux
}
The Handler method exposes the internal mux for use by http.Server in main. This indirection allows middleware injection in later chapters without changing the constructor signature.
Step 7: Create the Entry Point
Create cmd/incidentops/main.go. This file initializes configuration, constructs the server, and manages the process lifecycle with graceful shutdown.
The main function demonstrates standard Go service initialization. It uses the internal/server package, which enforces that no external module can import the server logic. Graceful shutdown ensures in-flight alert processing completes before exit; this becomes critical when agents hold database transactions or await human approvals.
Full Example
The following file tree shows the complete project structure for the baseline IncidentOps Copilot service. Create these files in Visual Studio Code using the integrated terminal.
The server returns {"status":"received","incident":"abc123"}. This baseline confirms the HTTP pipeline works and provides the exact insertion point where ADK runners will invoke agents in Chapter 4.
Common Mistakes
Deploying agents as separate microservices instead of embedded handlers. This introduces network partitions, serialization overhead, and deployment complexity. Keep agents inside the existing Go process; use the ADK runner as a request-scoped dependency within your handlers.
Exposing internal packages to external consumers. Do not place agent logic or domain types in pkg/ or other importable paths unless you explicitly support external usage. Use internal/ to prevent accidental coupling between your service and client libraries.
Ignoring context cancellation in handlers. Always accept context.Context as the first parameter of any function that invokes an agent. Model calls can hang; deadlines prevent goroutine leaks.
Hardcoding configuration values. Avoid constants for ports, timeouts, or model names in source files. Use the Config struct pattern shown above to support environment-specific deployments without recompilation.
Mixing domain logic with HTTP transport concerns. Keep JSON encoding and status code logic inside handlers. Domain functions should return (Result, error) and remain agnostic of HTTP semantics. This separation enables testing business logic without spinning up HTTP servers.
Performance and Production Considerations
Request-scoped agent instantiation keeps memory bounded. Global agent singletons kill testability; instantiate a fresh runner on every request. Each incoming alert creates a new context and runner; resources release when the handler returns.
Set explicit read and write timeouts on the HTTP server. Model inference can be slow; configure timeouts to match your latency service level objectives. Return 202 Accepted for long-running agent work; process asynchronously if the agent requires multiple tool calls or human approval.
The internal/ package boundary provides compile-time enforcement of modularity. The Go compiler prevents external modules from importing these paths, ensuring implementation details do not leak into public APIs.
Structured logging with log.Printf is sufficient for local development, though Chapter 11 will replace this with OpenTelemetry trace propagation. The insertion point is the HandleAlert method. The server structure requires minimal changes because the handler already accepts http.Request which carries context.
Summary
IncidentOps Copilot now runs as a concrete Go service with strict package boundaries. You defined the core domain entities (Incident, Alert, Service) that persist through all chapters. You constructed a baseline HTTP server that accepts alert payloads and logs them, creating the precise insertion point where ADK agents will integrate in Chapter 4.
Agents belong inside handlers, not microservices.
Safety constraints shape structure; they never retrofit cleanly.
The architecture treats agents as request-scoped functions within existing handlers, not autonomous processes. This pattern uses your existing middleware, authentication, and observability infrastructure. Safety and observability constraints are structural; they shape how you write handlers, manage context, and enforce package boundaries from the first line of code.
Key Terms
AI Agent: A request-scoped function that uses a language model to transform structured input into structured output while maintaining deterministic boundaries within an HTTP handler.
ADK (Agent Development Kit): Google's framework for embedding AI agents directly into existing Go services without requiring separate microservices or background processes.
Request-scoped runner: An ADK component instantiated within a single HTTP request lifecycle; it manages agent execution and releases resources when the handler returns.
Domain model: The core entities representing business logic; in IncidentOps Copilot, these are Incident, Alert, and Service.
internal/ package: A Go package path prefix that enforces compile-time visibility restrictions, preventing external modules from importing implementation details.
Graceful shutdown: A pattern using http.Server.Shutdown with a timeout context to ensure in-flight requests complete before process termination.
Context cancellation: Propagation of timeout and cancellation signals through context.Context to prevent goroutine leaks during slow model inference or external calls.
Mini Quiz
An on-call engineer receives a critical alert at 3 AM. The IncidentOps Copilot server ingests the alert payload via HTTP POST. According to the architecture established in this chapter, where should the ADK agent invocation occur to maintain deterministic boundaries and resource safety?
A. In a background goroutine spawned by main() that polls a message queue
B. In an init() function within the internal/domain package
C. As a separate microservice deployed via Kubernetes CronJob
D. Inside the HandleAlert HTTP handler using a request-scoped runner
Examine the Severity enumeration defined in this chapter. Assuming SeverityUnknown starts at iota zero, what is the underlying integer value of SeverityHigh?
A. 2
B. 5
C. 4
D. 3
Why does the HandleAlert method return HTTP 202 Accepted immediately upon receiving an alert payload rather than waiting for agent processing to complete?
A. To reduce memory usage by forcing early connection closure
B. To avoid importing the context package into the handler scope
C. To comply with REST standards that mandate immediate responses for all POST requests
D. To prevent timeout errors during slow model inference and enable asynchronous processing workflows
During a production deployment, the IncidentOps Copilot service receives a SIGTERM signal while actively processing an alert. Which specific mechanism in the provided code ensures the active handler completes before the process exits?
A. The http.Server.Shutdown method invoked with a timeout context
B. The signal.Notify channel buffering capacity
C. The getEnv function checking for shutdown environment variables
D. The json.Decoder error handling within the handler
What is the primary architectural benefit of placing domain types and server implementation logic within the internal/ directory structure?
A. Improved runtime performance through symbol hiding from the Go linker
B. Automatic code generation capabilities provided by the ADK CLI tooling
C. Alphabetical organization of source files within the repository
D. Compile-time enforcement preventing external modules from coupling to implementation details
Which pattern in the main() function prevents potential goroutine leaks and ensures clean resource release during server shutdown?
A. Creating context.WithTimeout for the Shutdown method call
B. Using log.Fatalf for all error conditions
C. Initializing the Config struct with hardcoded default values
D. Registering routes before invoking ListenAndServe
Answers are provided in the Answer Key at the end of the book.
Activity
Extend the IncidentOps Copilot server with alert validation and safe concurrent storage.
Open internal/server/server.go in Visual Studio Code.
Add mu sync.RWMutex and alerts map[string]domain.Alert fields to the Server struct. I've seen production services panic when concurrent handlers write to unprotected maps; don't skip the mutex.
Initialize both fields in NewServer.
Modify HandleAlert to validate that alert.Fingerprint and alert.ServiceName are non-empty strings; return HTTP 400 Bad Request if validation fails.
In HandleAlert, lock mu before storing the alert in the map, then release the lock immediately after.
Implement GetAlert to handle GET requests at /api/v1/alerts/{id}. Lock mu for reading, retrieve the alert, release the lock, then return JSON with HTTP 200 or HTTP 404 if not found.
Register the route using s.mux.HandleFunc("/api/v1/alerts/", s.GetAlert). Note that http.ServeMux treats /api/v1/alerts and /api/v1/alerts/ as distinct patterns; the trailing slash matches all paths with that prefix, while the pattern without the slash matches only that exact path.
Run the server using go run ./cmd/incidentops in the VS Code integrated terminal.
Test validation by posting an alert with an empty fingerprint; verify you receive HTTP 400.
Test retrieval by posting a valid alert, then executing curl http://localhost:8080/api/v1/alerts/alert-001.
Build production-grade AI agents in Go. Not Python prototypes. Not tutorials that stop at "hello world." Real multi-agent systems with observability, safety controls, and deployment patterns your ops team will actually approve.
Google released the Agent Development Kit (ADK) for Go v1.0 in April 2026, and it changes what Go services can do. You now have a first-class agent framework that fits naturally into goroutines, context cancellation, and the concurrency primitives you already use. No Python wrappers. No gRPC bridges. Just Go.
This book walks you through one continuous project across all 14 chapters: IncidentOps Copilot, an operational assistant that evolves from a single triage agent into a resilient multi-agent system with human-in-the-loop approvals, full OpenTelemetry tracing, and production deployments on Cloud Run, Vertex AI Agent Engine, and GKE.
What you will build: - Request-scoped agent runners with explicit timeouts and graceful shutdown
- Agents configured via YAML with validated schemas and environment-aware settings
- Tools with structured Go outputs, defensive error classification, and retry boundaries
- Gemini model integration with safety controls, context caching, and JSON-mode enforcement
- The Agent-to-Agent (A2A) protocol for cross-language interoperability with Python and TypeScript agents
- Workflow orchestration using SequentialAgent, ParallelAgent, and LoopAgent primitives
- Human-in-the-loop approval flows aligned with Google's Safe AI Framework
- Native OpenTelemetry tracing with OTLP exporters for full request visibility
- Deterministic tests for agents, tools, and workflow configurations
- Deployment patterns for Cloud Run, Vertex AI Agent Engine, and GKE with autoscaling
What makes this book different: - Go idioms, not Python ports. Every pattern uses context, channels, error wrapping, and the standard library the way Go engineers actually write services.
- One project, start to finish. No disconnected toy examples. Each chapter advances IncidentOps Copilot from single-agent triage to a production multi-agent system.
- Production-first mindset. Timeout boundaries before model calls. Observability before deployment. Cross-language contracts before orchestration. Cost control before scaling.
- Written by a practitioner. Hard-won lessons from real agent deployments, not repackaged framework documentation.
Covers ADK Go 1.0 released April 2026, including the full agent, runner, and session runtime, A2A protocol implementation, workflow agent primitives, and native OpenTelemetry integration. Includes deployment recipes for all three Google Cloud hosting targets.
Prerequisites: Intermediate Go (1.23 or later). Comfort with goroutines, channels, and context. A Google Cloud account for deployment chapters. No prior agent framework, LLM, or machine learning experience required.
Stop calling AI APIs from your handlers. Start building agents that are observable, testable, and ready for production.
Release DateApril 16, 2026
GenreSoftware & AI Development
ISBN979-8-90377-032-8
Read and listen on the go with the unQbd app.Get the app