agent.go

Overview

The agent.go file defines the core framework for creating, configuring, and running AI agents within the system. It establishes the foundational Agent interface and provides an implementation that supports hierarchical composition of agents, lifecycle callbacks, event streaming, and integration with session state, artifacts, and memory. This file is a central part of the AI Agent Framework, enabling custom agent behaviors with before- and after-execution hooks, delegation to sub-agents, and asynchronous event generation.

Key responsibilities include:

This file underpins higher-level agent types such as LLM agents, workflow agents, and remote agents by establishing a consistent execution model and lifecycle.


Detailed Explanations

Agent Interface

type Agent interface {
    Name() string
    Description() string
    Run(InvocationContext) iter.Seq2[*session.Event, error]
    SubAgents() []Agent
    internal() *agent
}

Agent Creation: New

func New(cfg Config) (Agent, error)
agent, err := agent.New(agent.Config{
    Name:        "example_agent",
    Description: "An example AI agent",
    Run: func(ctx agent.InvocationContext) iter.Seq2[*session.Event, error] {
        return func(yield func(*session.Event, error) bool) {
            yield(&session.Event{
                Author: "example_agent",
                LLMResponse: model.LLMResponse{
                    Content: genai.NewContentFromText("Hello from example agent", genai.RoleModel),
                },
            }, nil)
        }
    },
})

Config Struct

type Config struct {
    Name                 string
    Description          string
    SubAgents            []Agent
    BeforeAgentCallbacks []BeforeAgentCallback
    Run                  func(InvocationContext) iter.Seq2[*session.Event, error]
    AfterAgentCallbacks  []AfterAgentCallback
}

Lifecycle Callback Types

type BeforeAgentCallback func(CallbackContext) (*genai.Content, error)
type AfterAgentCallback func(CallbackContext) (*genai.Content, error)

Callbacks receive a CallbackContext that provides access to session state, artifacts, invocation metadata, and methods to modify state.


Artifacts and Memory Interfaces

type Artifacts interface {
    Save(ctx context.Context, name string, data *genai.Part) (*artifact.SaveResponse, error)
    List(context.Context) (*artifact.ListResponse, error)
    Load(ctx context.Context, name string) (*artifact.LoadResponse, error)
    LoadVersion(ctx context.Context, name string, version int) (*artifact.LoadResponse, error)
}

type Memory interface {
    AddSession(context.Context, session.Session) error
    Search(ctx context.Context, query string) (*memory.SearchResponse, error)
}

These interfaces allow agents to persist and retrieve data relevant to the session or user.


Internal agent Struct and Methods

type agent struct {
    agentinternal.State

    name, description string
    subAgents         []Agent

    beforeAgentCallbacks []BeforeAgentCallback
    run                  func(InvocationContext) iter.Seq2[*session.Event, error]
    afterAgentCallbacks  []AfterAgentCallback
}

Agent Run Method Workflow

The Run method orchestrates the invocation lifecycle as follows:

  1. Creates a wrapped InvocationContext (invocationContext) that embeds the original context plus accessors for artifacts, memory, and session.

  2. Executes runBeforeAgentCallbacks:

    • Iterates over beforeAgentCallbacks.

    • If any callback returns non-nil content or error, yields an event constructed from that content/error and ends invocation early.

  3. If invocation is not ended, runs the core run function, yielding events.

  4. Automatically assigns the event author to the agent's name if not set.

  5. If invocation is still active, executes runAfterAgentCallbacks:

    • Runs after callbacks sequentially.

    • If any returns content or error, yields an event with that content/error.

  6. Yields events via the returned iterator until completion or early termination.


Callback Execution Helpers


Callback Context

type callbackContext struct {
    context.Context
    invocationContext InvocationContext
    actions           *session.EventActions
}

Invocation Context Internal Wrapper

type invocationContext struct {
    context.Context

    agent     Agent
    artifacts Artifacts
    memory    Memory
    session   session.Session

    invocationID  string
    branch        string
    userContent   *genai.Content
    runConfig     *RunConfig
    endInvocation bool
}

Event Authoring Logic

func getAuthorForEvent(ctx InvocationContext, event *session.Event) string {
    if event.LLMResponse.Content != nil && event.LLMResponse.Content.Role == genai.RoleUser {
        return genai.RoleUser
    }
    return ctx.Agent().Name()
}

Important Implementation Details and Algorithms


Interactions with Other System Components


Visual Diagram: Agent Structure and Lifecycle Flow

classDiagram
class Agent {
+Name()
+Description()
+Run()
+SubAgents()
+internal()
}
class agent {
-name: string
-description: string
-subAgents: []Agent
-beforeAgentCallbacks: []BeforeAgentCallback
-run: func(InvocationContext) iter.Seq2[*session.Event, error]
-afterAgentCallbacks: []AfterAgentCallback
+Name()
+Description()
+Run()
+SubAgents()
+internal()
}
Agent <|.. agent
agent o-- "0..*" Agent : subAgents
agent : +runBeforeAgentCallbacks()
agent : +runAfterAgentCallbacks()

flowchart TD
Start[Start Run Invocation]
BeforeCB[Run BeforeAgentCallbacks]
CheckBefore{Before callback returns content/error?}
SkipRun[Skip main agent Run]
RunMain[Run agent's Run function]
AfterCB[Run AfterAgentCallbacks]
EmitEvent[Yield Event]
End[End Invocation]
Start --> BeforeCB --> CheckBefore
CheckBefore -- Yes --> EmitEvent --> SkipRun --> End
CheckBefore -- No --> RunMain --> AfterCB --> EmitEvent --> End

Summary of Key Types and Interfaces

Type

Description

Agent

Interface for AI agents defining identity, behavior, and sub-agents.

agent

Concrete implementation of Agent supporting lifecycle and callbacks.

Config

Configuration struct for creating custom agents.

InvocationContext

Context interface providing runtime data/services during invocation.

CallbackContext

Interface passed to lifecycle callbacks for state and metadata access.

BeforeAgentCallback

Function type for pre-run lifecycle callbacks.

AfterAgentCallback

Function type for post-run lifecycle callbacks.

Artifacts

Interface for managing session artifacts.

Memory

Interface for accessing user-scoped memory.


For further details on invocation context and lifecycle callbacks, see the subtopics Agent Invocation Context and Agent Lifecycle and Callbacks. For usage patterns involving session management and artifact integration, refer to Session Management and Artifact Management.