llmagent.go

Overview

The llmagent.go file implements the LLMAgent, a specialized AI agent that integrates a large language model (LLM) with extensible tools, instructions, and lifecycle callbacks. This agent serves as a central component within the [LLM Integration and Agents](80562) system, providing a configurable interface to execute LLM-driven workflows, handle sub-agent delegation, and interact with session state.

The file defines the configuration schema (Config) for constructing an LLMAgent, the agent’s main struct (llmAgent), callback types for hooking into model and tool invocations, and the primary execution logic. It also manages dynamic instruction injection and stateful output persistence for multi-turn conversational AI scenarios.

Key Entities and Components

Config Struct

Config encapsulates all parameters required to initialize and configure an LLMAgent. It includes:

Callback Types

type BeforeModelCallback func(ctx agent.CallbackContext, llmRequest *model.LLMRequest) (*model.LLMResponse, error)

Called before sending the LLM request. Returning a non-nil response or error skips the actual model call.

type AfterModelCallback func(ctx agent.CallbackContext, llmResponse *model.LLMResponse, llmResponseError error) (*model.LLMResponse, error)

Called after receiving the LLM response. Returning a non-nil response or error replaces the actual model response/error.

type BeforeToolCallback func(ctx tool.Context, tool tool.Tool, args map[string]any) (map[string]any, error)

Called before invoking a tool's Run method. Returning a non-nil result or error short-circuits tool execution.

type AfterToolCallback func(ctx tool.Context, tool tool.Tool, args, result map[string]any, err error) (map[string]any, error)

Called after tool execution regardless of success or failure. Allows modification of the tool’s result or error.

IncludeContents Enum

Controls whether prior conversation history is included in LLM requests:

llmAgent Struct

The core agent struct embedding:

InstructionProvider

type InstructionProvider func(ctx agent.ReadonlyContext) (string, error)

A function type for dynamic generation of instructions at each invocation. Overrides static instructions if provided.

Main Functions and Methods

New(cfg Config) (agent.Agent, error)

Constructor that creates a new LLMAgent instance from the provided configuration.

cfg := llmagent.Config{
    Name:        "example-agent",
    Description: "Handles user queries with LLM",
    Model:       myLLMModel,
    Tools:       []tool.Tool{myTool},
    Instruction: "Answer concisely.",
}
agent, err := llmagent.New(cfg)
if err != nil {
    log.Fatalf("Failed to create agent: %v", err)
}

(a *llmAgent) run(ctx agent.InvocationContext) iter.Seq2[*session.Event, error]

The core execution method invoked when the LLMAgent runs.

(a *llmAgent) maybeSaveOutputToState(event *session.Event)

Conditionally saves the textual output from an LLM response event into the session state under the configured OutputKey.

Implementation Details and Algorithms

Interaction with Other System Components

Visual Diagram of Agent Structure and Relationships

classDiagram
class Config {
+string Name
+string Description
+[]Agent SubAgents
+[]BeforeAgentCallback BeforeAgentCallbacks
+[]AfterAgentCallback AfterAgentCallbacks
+GenerateContentConfig GenerateContentConfig
+[]BeforeModelCallback BeforeModelCallbacks
+model.LLM Model
+[]AfterModelCallback AfterModelCallbacks
+string Instruction
+InstructionProvider InstructionProvider
+string GlobalInstruction
+InstructionProvider GlobalInstructionProvider
+bool DisallowTransferToParent
+bool DisallowTransferToPeers
+IncludeContents IncludeContents
+*genai.Schema InputSchema
+*genai.Schema OutputSchema
+[]BeforeToolCallback BeforeToolCallbacks
+[]tool.Tool Tools
+[]AfterToolCallback AfterToolCallbacks
+[]tool.Toolset Toolsets
+string OutputKey
}
class llmAgent {
+Agent Agent
+State llminternal.State
+[]BeforeModelCallback beforeModelCallbacks
+model.LLM model
+[]AfterModelCallback afterModelCallbacks
+string instruction
+[]BeforeToolCallback beforeToolCallbacks
+[]AfterToolCallback afterToolCallbacks
+*genai.Schema inputSchema
+*genai.Schema outputSchema
+run()
+maybeSaveOutputToState()
}
Config --> llmAgent : Instantiates
llmAgent --> model.LLM : Uses
llmAgent --> tool.Tool : Integrates Tools
llmAgent --> agent.Agent : Embeds Base Agent
llmAgent --> llminternal.State : Maintains State
llmAgent --> BeforeModelCallback : Executes
llmAgent --> AfterModelCallback : Executes
llmAgent --> BeforeToolCallback : Executes
llmAgent --> AfterToolCallback : Executes

This documentation provides a detailed technical description of the llmagent.go file’s purpose, entities, functions, and internal mechanisms, referencing relevant sections of the broader system for context.