main.go

Overview

The main.go file serves as the entry point for an interactive command-line application that integrates an AI agent with artifact management and session handling capabilities. Its primary purpose is to create and configure a Large Language Model (LLM)–based agent, manage user sessions, load artifacts (such as images and text files), and enable conversational interactions with the agent. The agent is specifically designed to answer questions about artifacts by loading and describing them on demand.

This file orchestrates the initialization and connection of multiple core components:


Detailed Components

Package and Imports


func main()

The main function runs the entire application workflow:

Context Creation

ctx := context.Background()

Creates a root context for all subsequent calls, enabling cancellation and deadlines if extended.

Model Initialization

model, err := gemini.NewModel(ctx, "gemini-2.5-flash", &genai.ClientConfig{
    APIKey: os.Getenv("GOOGLE_API_KEY"),
})

LLM Agent Setup

llmagent, err := llmagent.New(llmagent.Config{
    Name:        "artifact_describer",
    Model:       model,
    Description: "Agent to answer questions about artifacts.",
    Instruction: "When user asks about the artifact, load them and describe them.",
    Tools: []tool.Tool{
        loadartifactstool.New(),
    },
})

Session and Artifact Service Initialization

userID, appName := "test_user", "test_app"
sessionService := session.InMemoryService()

Session creation:

resp, err := sessionService.Create(ctx, &session.CreateRequest{
    AppName: appName,
    UserID:  userID,
})
session := resp.Session

Artifact service:

artifactService := artifact.InMemoryService()

Artifact Loading and Saving

imageBytes, err := os.ReadFile("animal_picture.png")

Saving the image artifact:

_, err = artifactService.Save(ctx, &artifact.SaveRequest{
    AppName:   appName,
    UserID:    userID,
    SessionID: session.ID(),
    FileName:  "animal_picture.png",
    Part:      genai.NewPartFromBytes(imageBytes, "image/png"),
})

Saving a text artifact (haiku.txt):

_, err = artifactService.Save(ctx, &artifact.SaveRequest{
    AppName:   appName,
    UserID:    userID,
    SessionID: session.ID(),
    FileName:  "haiku.txt",
    Part: genai.NewPartFromText(
        "An old silent pond..." +
        "A frog jumps into the pond," +
        "splash! Silence again."),
})

Any errors during artifact saving cause the program to exit with a fatal log.

Runner Initialization

r, err := runner.New(runner.Config{
    AppName:         appName,
    Agent:           llmagent,
    SessionService:  sessionService,
    ArtifactService: artifactService,
})

Interactive User Input Loop

reader := bufio.NewReader(os.Stdin)
for {
    fmt.Print("\nUser -> ")

    userInput, err := reader.ReadString('\n')
    ...
    userMsg := genai.NewContentFromText(userInput, genai.RoleUser)

Agent Run and Response Streaming

streamingMode := agent.StreamingModeSSE
for event, err := range r.Run(ctx, userID, session.ID(), userMsg, agent.RunConfig{
    StreamingMode: streamingMode,
}) {
    if err != nil {
        fmt.Printf("\nAGENT_ERROR: %v\n", err)
    } else {
        if event.LLMResponse.Content == nil {
            continue
        }
        for _, p := range event.LLMResponse.Content.Parts {
            if streamingMode != agent.StreamingModeSSE || event.LLMResponse.Partial {
                fmt.Print(p.Text)
            }
        }
    }
}

Important Implementation Details


Interactions with Other System Components


Usage Example

To use the program, the environment variable GOOGLE_API_KEY must be set with a valid API key. The user runs the program and types queries about the artifacts (e.g., "Describe the animal picture" or "What is the haiku about?"). The agent processes these inputs, loads the relevant artifacts, and streams descriptive responses back to the console.


Mermaid Diagram: Flowchart of Main Functional Workflow

flowchart TD
A["Start: main()"] --> B[Create Context]
B --> C[Initialize Gemini Model]
C --> D[Create LLM Agent with loadartifactstool]
D --> E[Initialize Session Service]
E --> F[Create User Session]
F --> G[Initialize Artifact Service]
G --> H[Read & Save Image Artifact]
H --> I[Save Text Artifact]
I --> J[Create Runner with Agent and Services]
J --> K[Start User Input Loop]
K --> L[Read User Input]
L --> M[Convert Input to genai.Content]
M --> N[Run Agent via Runner]
N --> O[Stream Agent Response]
O --> K

Reference to Related Topics