main.go
Overview
The main.go file serves as the entry point for launching a multi-agent application designed to answer questions about time and weather in a city, generate images, and audit large language model (LLM) interactions. It configures and initializes LLM-based agents, session and artifact services, and establishes an agent loader that manages multiple agents. The file also sets up a launcher that integrates these components into a runnable command-line executable.
This file orchestrates the integration of agents built on the Gemini LLM model with various tools, manages user authentication for agent-to-agent (A2A) communication, and handles the lifecycle and storage of artifacts generated during agent execution.
Main Components
1. saveReportfunc
func saveReportfunc(ctx agent.CallbackContext, llmResponse *model.LLMResponse, llmResponseError error) (*model.LLMResponse, error)
Purpose:
This callback function is registered as anAfterModelCallbackfor the root LLM agent. It processes the LLM response after completion to save each part of the response content as an artifact.Parameters:
ctx: The callback context providing access to artifact services and session info (Agent Invocation Context).llmResponse: The response received from the LLM model.llmResponseError: Any error encountered during the LLM invocation.
Returns:
The same or modified
llmResponse.An error if artifact saving fails.
Behavior:
If the LLM response or its content is nil, or if there is an error, it immediately returns. Otherwise, it iterates over each part of the response content, saving it as an artifact with a unique UUID. If any save operation fails, it returns the error.Usage Example:
Registered in the root agent configuration to persist response parts automatically after model generation.
2. AuthInterceptor Struct and Methods
type AuthInterceptor struct {
a2asrv.PassthroughCallInterceptor
}
Purpose:
Implements a call interceptor that injects a fixed authenticated user identity into A2A calls. This facilitates user context propagation in agent-to-agent communication sessions (Remote Agent Communication (A2A)).Method:
func (a *AuthInterceptor) Before(ctx context.Context, callCtx *a2asrv.CallContext, req *a2asrv.Request) (context.Context, error)
Parameters:
ctx: The base context for the call.callCtx: Contains metadata about the call including user information.req: The incoming request being handled.
Returns:
The (possibly modified) context.
An error if any.
Behavior:
Sets theUserfield of the call context to a static user with username"user". This user identity is necessary for session and authorization logic shared by both A2A and web UI launchers (REST API and Web Launchers).
3. main Function
func main()
Purpose:
Initializes all core components and launches the agent framework executable.Detailed Steps:
Context and API Key Setup:
Creates a root background context and loads theGOOGLE_API_KEYenvironment variable for authentication with Gemini LLM services.Model Initialization:
Instantiates a Gemini LLM model named"gemini-2.5-flash"using the provided API key. This model is configured via thegenai.ClientConfig(LLM Integration and Agents).Session Service:
Creates an in-memory session service to manage user-agent interaction sessions (Session Management).Root Agent Creation:
Builds an LLM agent named"weather_time_agent"with a description and instruction about answering time and weather questions. The agent is equipped with the Google Search tool (geminitool.GoogleSearch{}) for real-time information retrieval (Google Search Tool, LLM Agent Configuration). ThesaveReportfuncis assigned as an after-model callback to persist responses.Additional Agents:
Initializes two other agents:llmAuditor: An agent dedicated to auditing LLM interactions.imageGeneratorAgent: An agent capable of generating images.
These are retrieved via helper functions from theagentspackage and share the same Gemini LLM model.
Agent Loader:
Combines multiple agents into aMultiLoaderto facilitate coordinated loading and invocation (AI Agent Framework).Artifact Service:
Uses an in-memory artifact service for storing generated artifacts during agent runs (Artifact Management, In-Memory Artifact Service).Launcher Configuration and Execution:
Prepares a launcher configuration that includes the artifact and session services, the agent loader, and A2A options with theAuthInterceptor.
Callsfull.NewLauncher().Execute()to start the application, passing command-line arguments.
If execution fails, logs the error and shows the correct command-line syntax.
Important Implementation Details
Artifact Persistence:
The integration ofsaveReportfuncwith agent callbacks ensures that all parts of the LLM's output are saved as artifacts immediately after generation, providing durable storage and later retrieval (Artifact Management).User Identity Injection:
TheAuthInterceptorenforces a static user identity for all A2A requests, simplifying authentication and session association across distributed agent communication (Remote Agent Communication (A2A)).Multi-Agent Composition:
The use ofagent.NewMultiLoaderenables the application to manage multiple specialized agents concurrently, facilitating complex workflows including auditing and image generation alongside the root weather/time agent (AI Agent Framework).Tool Integration:
The root agent is configured with the Google Search tool (geminitool.GoogleSearch{}), enabling real-time web search capabilities embedded within the LLM's reasoning process (Google Search Tool).In-Memory Services:
Both session and artifact services are in-memory implementations, appropriate for testing or transient runtime environments without persistent storage (Session Management, Artifact Management).
Interactions with Other System Components
Agents and Tools:
Relies on thellmagentpackage to create and manage LLM-based agents with lifecycle callbacks (LLM Integration and Agents, LLM Agent Configuration).Session and Artifact Management:
Uses in-memory implementations of session and artifact services to store session state and generated data (Session Management, Artifact Management).Agent-To-Agent Communication:
Integrates with the A2A protocol viaa2asrvto enable distributed multi-agent calls, using theAuthInterceptorfor user authentication (Remote Agent Communication (A2A)).Tools and Utilities:
Employs tools such as Google Search via the Gemini toolset to augment answer generation (Google Search Tool).Launcher Framework:
Utilizes thelauncherandfullpackages to parse command-line arguments, configure services, and run the agent application with proper lifecycle management (REST API and Web Launchers).
Visual Diagram: Flowchart of Main Function and Key Interactions
flowchart TD
A[Start main] --> B[Load GOOGLE_API_KEY]
B --> C[Create Gemini LLM Model]
C --> D[Create In-Memory Session Service]
D --> E[Create Root LLM Agent]
E --> F[Add Google Search Tool]
F --> G[Attach saveReportfunc Callback]
G --> H[Create LLM Auditor Agent]
H --> I[Create Image Generator Agent]
I --> J[Create MultiLoader with Agents]
J --> K[Create In-Memory Artifact Service]
K --> L[Configure Launcher with Services & AuthInterceptor]
L --> M[Execute Launcher]
M --> N{Execution Success?}
N -- Yes --> O[Run Application]
N -- No --> P[Log Error & Show Usage]
Summary of Functions and Structures
Name | Type | Description |
|---|---|---|
| Function | Callback to save LLM response parts as artifacts after model call. |
| Struct | Call interceptor injecting a static user identity into A2A calls. |
Method | Sets authenticated user in call context before A2A request. | |
| Function | Initializes services, agents, loaders, and launches the application. |
Usage Notes
The application expects the
GOOGLE_API_KEYenvironment variable to be set for Gemini LLM authentication.Command-line arguments passed to the executable are handled by the full.Launcher which supports various subcommands and options.
The root agent is specifically designed to answer questions about weather and time, enhanced by web search capabilities.
The artifact and session services are in-memory and thus ephemeral; for production use, persistent implementations should be integrated.
The static user identity
"user"is a placeholder for authentication; in multi-user scenarios, this should be replaced with dynamic authentication logic.
References to Related Topics
LLM Integration and Agents ([80562]) for agent creation and model configuration.
Agent Invocation Context ([80572]) for callback context and artifact saving.
Artifact Management ([80557]) for artifact service usage.
Remote Agent Communication (A2A) ([80565]) for call interception and user identity injection.
Session Management ([80559]) for session service handling.
Google Search Tool ([80576]) for tool integration.
REST API and Web Launchers ([80564]) for launcher configuration and execution.