main.go
Overview
The main.go file serves as an entry point for a server application demonstrating direct integration with the ADK REST API handler using Go's standard net/http package. It sets up an AI agent capable of answering questions related to time and weather in a city by leveraging a Gemini language model and Google Search tool. This example bypasses specialized HTTP routers, showcasing how to use ADK's REST API in a minimalistic HTTP server setup.
The file covers the following core functionalities:
Creating and configuring a Gemini language model.
Instantiating an LLM-based agent with specific instructions and tools.
Configuring the ADK REST API handler.
Setting up HTTP routes for the API and a health check.
Running the HTTP server on port 8080.
Detailed Explanation of Components
main Function
The main function orchestrates the entire setup and execution of the server.
Step-by-step Breakdown:
Context Creation
ctx := context.Background()Creates a background context to be used in model and agent creation.
Gemini Model Creation
model, err := gemini.NewModel(ctx, "gemini-2.5-flash", &genai.ClientConfig{ APIKey: os.Getenv("GOOGLE_API_KEY"), })Uses
gemini.NewModelto instantiate a Gemini model named"gemini-2.5-flash".The model configuration includes an API key loaded from the environment variable
GOOGLE_API_KEY.On failure, logs a fatal error and exits.
Purpose: Provides the language model backend for the agent to generate responses.
Agent Initialization
a, err := llmagent.New(llmagent.Config{ Name: "weather_time_agent", Model: model, Description: "Agent to answer questions about the time and weather in a city.", Instruction: "I can answer your questions about the time and weather in a city.", Tools: []tool.Tool{ geminitool.GoogleSearch{}, }, })Creates an LLM agent with:
A descriptive name and purpose.
The previously created Gemini model.
Instruction text guiding the agent's behavior.
A list of tools, currently including the Gemini-native Google Search tool (
geminitool.GoogleSearch{}).
On failure, logs a fatal error.
Usage: The agent uses the model and tools to answer queries about weather and time by potentially searching the web.
ADK REST API Configuration
config := &launcher.Config{ AgentLoader: agent.NewSingleLoader(a), SessionService: session.InMemoryService(), }Configures the REST API launcher with:
A single agent loader wrapping the created agent (
agent.NewSingleLoader(a)).An in-memory session service (
session.InMemoryService()) for managing interaction sessions.
This configuration is essential for the ADK REST API to manage agent sessions and lifecycle.
REST API Handler Creation
apiHandler := adkrest.NewHandler(config)Constructs an HTTP handler (
http.Handler) for the ADK REST API using the above configuration.This handler manages all REST API requests routed to it.
HTTP Multiplexer Setup
mux := http.NewServeMux()Creates a new HTTP request multiplexer (router) using Go's standard library.
Registering API Endpoint
mux.Handle("/api/", http.StripPrefix("/api", apiHandler))Registers the ADK REST API handler at the
/api/path.Uses
http.StripPrefixto remove the/apiprefix before forwarding requests to the handler.
This decouples the API base path from the handler's internal routing.
Health Check Endpoint
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) if _, err := w.Write([]byte("OK")); err != nil { log.Printf("Failed to write response: %v", err) } })Adds a simple health check HTTP handler at
/health.Responds with HTTP 200 OK and body "OK".
Logs any errors when writing the response.
Starting the HTTP Server
if err := http.ListenAndServe(":8080", mux); err != nil { log.Fatalf("Server failed: %v", err) }Starts the HTTP server on port 8080, using the configured multiplexer.
Logs and exits on server failure.
External Dependencies and Interactions
Gemini Model (
gemini.NewModel): The Gemini model is part of thegoogle.golang.org/adk/model/geminipackage, which provides a Gemini LLM integration. This model client requires a Google API key for authentication.LLM Agent (
llmagent.New): Constructs an agent using the LLM Integration and Agents framework80562, which manages agent behavior, tools, and instructions.Tools (
geminitool.GoogleSearch): The Google Search tool wraps search capabilities, enabling the agent to query the web seamlessly. This tool is part of the tooling system80556and the Gemini toolset80576.Session Service (
session.InMemoryService): Manages sessions in-memory, facilitating stateful agent interactions80559.ADK REST API Handler (
adkrest.NewHandler): Implements the HTTP REST API interface for interacting with agents, sessions, and workflows80564.Agent Loader (
agent.NewSingleLoader): Wraps the created agent in a loader interface that the REST API uses to load agents on demand80562.
This file interacts primarily with the ADK core framework components for AI agents, session management, tooling, and REST API serving.
Usage Example
After compilation and setting the GOOGLE_API_KEY environment variable, run the server:
GOOGLE_API_KEY="your_api_key" go run main.go
The server starts on http://localhost:8080 with:
REST API available under
http://localhost:8080/api/Health check endpoint at
http://localhost:8080/health
Clients can interact with the REST API to invoke the weather_time_agent for queries about city time and weather.
Important Implementation Details
The example explicitly uses the standard
net/httppackage andhttp.ServeMuxrather than complex third-party routers, demonstrating flexibility in integrating the ADK REST API.The agent is configured with a single Gemini LLM model and a Google Search tool, illustrating a modular approach to building AI agents with pluggable capabilities.
Session data is stored in memory, suitable for testing or ephemeral use; production usage would require a more persistent session service as described in
80559 - Session Management.The REST API handler is mounted with a prefix-stripping middleware to isolate routing concerns.
Mermaid Diagram: Flowchart of Main Functions and Interactions
flowchart TD
A[main] --> B[Create Gemini Model]
B -->|Uses| C[gemini.NewModel]
A --> D[Create Agent]
D -->|Uses| E[llmagent.New]
E --> F[Configure Agent with Tools]
F --> G[geminitool.GoogleSearch]
A --> H[Configure ADK REST API]
H --> I[launcher.Config with AgentLoader & SessionService]
A --> J[Create ADK REST API Handler]
J --> K[adkrest.NewHandler]
A --> L[Setup HTTP Server]
L --> M[http.NewServeMux]
M --> N[Register /api/ -> ADK Handler]
M --> O[Register /health -> Health Check Handler]
L --> P[Start HTTP ListenAndServe on :8080]
This diagram outlines the main flow of operations in the main.go file, showing the sequence from model creation through server startup, and the main components involved.
This documentation references relevant topics including the ADK REST API and web launchers 80564, LLM integration and agents 80562, tooling system 80556, and session management 80559 without repeating their content.