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:

Detailed Explanation of Components

main Function

The main function orchestrates the entire setup and execution of the server.

Step-by-step Breakdown:

  1. Context Creation

    ctx := context.Background()
    

    Creates a background context to be used in model and agent creation.

  2. Gemini Model Creation

    model, err := gemini.NewModel(ctx, "gemini-2.5-flash", &genai.ClientConfig{
        APIKey: os.Getenv("GOOGLE_API_KEY"),
    })
    
    • Uses gemini.NewModel to 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.

  3. 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.

  4. 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.

  5. 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.

  6. HTTP Multiplexer Setup

    mux := http.NewServeMux()
    
    • Creates a new HTTP request multiplexer (router) using Go's standard library.

  7. Registering API Endpoint

    mux.Handle("/api/", http.StripPrefix("/api", apiHandler))
    
    • Registers the ADK REST API handler at the /api/ path.

    • Uses http.StripPrefix to remove the /api prefix before forwarding requests to the handler.

    This decouples the API base path from the handler's internal routing.

  8. 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.

  9. 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

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:

Clients can interact with the REST API to invoke the weather_time_agent for queries about city time and weather.

Important Implementation Details

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.