agent.go
Overview
The agent.go file defines core internal structures and interfaces for managing large language model (LLM) agents within the system. It encapsulates the state and configuration needed to run an LLM agent, including the selected model, tools, instructions, and schemas for input/output validation. This file establishes the internal representation (State) of an agent and exposes controlled access via the Agent interface and utility functions. It serves as a foundational building block in the LLM Integration and Agents topic, enabling agents to be configured and executed with complex instruction handling and tool integration.
Types and Interfaces
Agent Interface
type Agent interface {
internal() *State
}
Purpose: Abstracts the internal state of an LLM agent.
Method:
internal() *State: Returns a pointer to the agent's internalState. This method is unexported to restrict direct external manipulation but allows controlled access within the package or trusted callers.
Usage: Types implementing
Agentprovide access to their internal state via this method. The exported helperRevealfunction accesses this internal state safely for clients needing introspection or advanced configuration.
State Struct
type State struct {
Model model.LLM
Tools []tool.Tool
Toolsets []tool.Toolset
IncludeContents string
GenerateContentConfig *genai.GenerateContentConfig
Instruction string
InstructionProvider InstructionProvider
GlobalInstruction string
GlobalInstructionProvider InstructionProvider
DisallowTransferToParent bool
DisallowTransferToPeers bool
InputSchema *genai.Schema
OutputSchema *genai.Schema
OutputKey string
}
Purpose: Represents the complete internal state and configuration of an LLM agent.
Properties:
Field
Type
Description
Modelmodel.LLMThe large language model instance to use for generation.
Tools[]tool.ToolList of tools available to the agent for augmenting capabilities (e.g., function calls).
Toolsets[]tool.ToolsetCollections of related tools grouped as toolsets.
IncludeContentsstringContents to be included in prompts or instructions, potentially for context enrichment.
GenerateContentConfig*genai.GenerateContentConfigConfiguration options controlling content generation behavior (e.g., temperature, tokens).
InstructionstringPrimary instruction text template for the agent's LLM prompt.
InstructionProviderInstructionProviderFunction callback returning dynamic instructions based on invocation context.
GlobalInstructionstringGlobal instruction applied across all invocations, often for consistent behavior enforcement.
GlobalInstructionProviderInstructionProviderCallback providing global instructions dynamically.
DisallowTransferToParentboolFlag to prevent transferring control to a parent agent in multi-agent workflows.
DisallowTransferToPeersboolFlag to prevent transferring control to peer agents.
InputSchema*genai.SchemaSchema describing the expected input structure for validation.
OutputSchema*genai.SchemaSchema describing the output structure for validation or serialization.
OutputKeystringKey identifier to extract specific output parts from generated content.
Usage: The
Statestruct is the central configuration holder used internally by agents to configure and manage LLM calls, tool invocation, instruction processing, and input/output validation. It consolidates all aspects affecting the agent's behavior and interaction with the underlying LLM.
InstructionProvider Type
type InstructionProvider func(ctx agent.ReadonlyContext) (string, error)
Purpose: Defines a callback function signature for dynamically providing instructions to the agent at runtime.
Parameters:
ctx agent.ReadonlyContext: Read-only context passed during agent invocation, providing access to session and environment data.
Returns:
string: The dynamically generated instruction text.error: Any error encountered during instruction retrieval or generation.
Usage: Allows instructions to be computed or fetched dynamically based on the current agent context, enabling flexible and adaptive prompt generation.
Functions
(s *State) internal()
func (s *State) internal() *State { return s }
Purpose: Implements the
internal()method of theAgentinterface for theStatetype itself.Returns: The receiver
Statepointer.Usage: Allows
Stateto fulfill theAgentinterface, enabling direct use ofStateas an agent representation internally.
Reveal
func Reveal(a Agent) *State { return a.internal() }
Purpose: Provides safe external access to the internal
Stateof any object implementing theAgentinterface.Parameters:
a Agent: The agent instance whose state is to be revealed.
Returns:
*State: Pointer to the agent's internal state.
Usage: Used when internal state inspection or modification is necessary outside the package scope, while still enforcing interface abstraction.
Important Implementation Details
Encapsulation via Interface: The
Agentinterface abstracts the internal state, exposing only theinternal()method, which is unexported to restrict direct access. This design supports controlled exposure of internal details and safe extensions.Flexible Instruction Handling: By allowing
InstructionProvidercallbacks alongside static instruction strings, agents can adapt prompt instructions dynamically based on real-time context, supporting advanced use cases like session state injection or artifact inclusion as described in Instruction Template Processing.Tool and Toolset Integration: The state holds both individual tools and grouped toolsets from the tooling system (Tooling System), enabling the agent to leverage a rich set of capabilities during execution.
Schema-Based Validation: Input and output schemas based on
genai.Schemaallow structured validation and serialization of data flowing through the agent, essential for robust API and workflow interactions.Transfer Control Flags: Boolean flags
DisallowTransferToParentandDisallowTransferToPeersregulate multi-agent control flow, ensuring that agent invocation respects hierarchical or peer boundaries as described in Agent Selection Logic.Content Inclusion:
IncludeContentscan be used to embed additional context into prompts, facilitating richer or context-aware LLM interactions.
Interaction with Other Components
LLM Model (
model.LLM): The primary interface to the language model instance used to generate content, referenced from themodelpackage.Tools and Toolsets (
tool.Tool,tool.Toolset): The agent state includes references to tools defined in the tooling system (Tooling System), enabling invocation of external capabilities during generation.Instruction Providers: Utilize context interfaces defined in the agent invocation lifecycle (Agent Invocation Context) to generate dynamic instructions.
Content Generation Configuration: Uses
genai.GenerateContentConfigto customize LLM generation parameters.Schema Validation: Input and output schemas integrate with the
genaipackage for validating structured data passed to and returned from the LLM.Agent Transfer Logic: Flags in
Stateinfluence agent orchestration and transfer mechanisms elaborated in Agent Selection Logic.Session and Artifact Interaction: While not directly manipulating sessions or artifacts, the state supports instructions and tools that may interact with those components through dynamic instruction injection (Instruction Template Processing) and artifact loading (Artifact Loading Tool).
Example Usage
// Create a new agent state with a specified LLM and tools
state := &State{
Model: myLLMInstance,
Tools: []tool.Tool{searchTool, calculatorTool},
Instruction: "Answer the user's query based on the provided context.",
InputSchema: userInputSchema,
OutputSchema: outputResponseSchema,
}
// Wrap the state as an Agent
var agent Agent = state
// Retrieve internal state for configuration or inspection
internalState := Reveal(agent)
// Use internalState to modify instructions dynamically if needed
internalState.Instruction = "Updated instruction with new context."
Mermaid Diagram: Agent Internal Structure
classDiagram
class State {
+Model
+Tools
+Toolsets
+IncludeContents
+GenerateContentConfig
+Instruction
+InstructionProvider
+GlobalInstruction
+GlobalInstructionProvider
+DisallowTransferToParent
+DisallowTransferToPeers
+InputSchema
+OutputSchema
+OutputKey
+internal()
}
class Agent {
+internal()
}
Agent <|.. State
This class diagram illustrates the relationship between the Agent interface and the State struct, showing that State implements Agent by providing the internal() method. The properties of State represent the agent's configuration and runtime state components.
This file is a key internal module underpinning the agent framework within the LLM Integration and Agents topic, enabling comprehensive configuration and management of LLM agents with dynamic instruction handling, tool support, and schema validations.