agent.go
Overview
This file implements the LoopAgent, a specialized workflow agent that repeatedly executes its sub-agents for a configured number of iterations or indefinitely until a termination condition is met. The LoopAgent is part of the broader Agent Workflow Management system, enabling iterative AI workflows such as progressive refinement, polling, or repetitive processing tasks.
The LoopAgent orchestrates its sub-agents sequentially in each iteration, streaming events generated during their execution back to the caller. It supports early termination if any sub-agent signals an escalation, allowing interruption of the loop for higher-level handling. The agent enforces internal control over the Run method to preserve consistent looping behavior.
Package and Imports
Package:
loopagentImports core packages for iteration handling (
iter), agent interfaces (agent), internal agent state manipulation (agentinternal), and session event types (session).
Types and Structures
Config
type Config struct {
AgentConfig agent.Config
MaxIterations uint
}
Purpose: Configuration parameters for constructing a LoopAgent.
Fields:
AgentConfig: Base configuration for the underlying agent, including sub-agents and metadata.MaxIterations: Maximum number of loop iterations to execute. If zero, the LoopAgent runs indefinitely or until an escalation action occurs.
Usage: Passed to
New()to instantiate a LoopAgent with desired iteration limits and sub-agent setup.
loopAgent (unexported struct)
type loopAgent struct {
maxIterations uint
}
Purpose: Internal implementation of the LoopAgent, holding iteration configuration.
Fields:
maxIterations: Stores maximum iterations from Config for use during runtime.
Responsibilities: Implements the
Runmethod to perform the looping execution logic.
Functions and Methods
New(cfg Config) (agent.Agent, error)
func New(cfg Config) (agent.Agent, error)
Purpose: Factory function to create a new LoopAgent instance based on the provided configuration.
Parameters:
cfg(Config): Configuration specifying sub-agents and iteration count.
Returns:
agent.Agent: A new LoopAgent implementing theagent.Agentinterface.error: Non-nil on failure to create the agent.
Details:
Enforces that the caller does not supply a custom
Runimplementation inAgentConfig(LoopAgent manages execution internally).Assigns the internal
loopAgent.Runmethod as theRunhandler.Wraps the base agent created from
AgentConfig.Uses internal package methods (
agentinternal.Reveal) to set agent type and store config metadata for runtime introspection.
Errors:
Returns an error if a custom
Runis provided.Returns an error if base agent creation fails.
Returns an error if internal type assertion fails.
Usage example:
loopAgent, err := loopagent.New(loopagent.Config{
AgentConfig: agent.Config{
SubAgents: []agent.Agent{subAgent1, subAgent2},
// other config fields...
},
MaxIterations: 5,
})
(a *loopAgent) Run(ctx agent.InvocationContext) iter.Seq2[*session.Event, error]
func (a *loopAgent) Run(ctx agent.InvocationContext) iter.Seq2[*session.Event, error]
Purpose: Implements the LoopAgent's main execution loop, running sub-agents sequentially and repeatedly.
Parameters:
ctx(agent.InvocationContext): Context for the current invocation, providing access to the agent tree, session, and runtime environment.
Returns:
iter.Seq2[*session.Event, error]: An iterator function that yieldssession.Eventobjects and errors asynchronously to the caller.
Logic:
Initializes a counter
countfrommaxIterations.Returns a closure that performs:
Infinite or
count-bounded loop:Iterates over all sub-agents of the current agent (
ctx.Agent().SubAgents()).Runs each sub-agent by invoking their
Run(ctx)method, which is itself an iterator.Yields each event/error pair from the sub-agent's iterator to the caller.
Checks for an escalate action (
event.Actions.Escalate) in any event and terminates the loop early if detected.
Decrements iteration count each full iteration and terminates when zero.
Termination Conditions:
Escalation event from any sub-agent.
Maximum iterations reached (if set).
Early termination requested by the caller via the yield function.
Usage:
Called internally by the agent execution framework.
The iterator pattern allows streaming of events as soon as they are produced, enabling responsive and interactive workflows.
Important Implementation Details
The LoopAgent delegates actual work to its sub-agents, allowing arbitrary agent types (LLM agents, tool agents, other workflow agents) to participate in the loop.
The event streaming approach using an iterator (
iter.Seq2) supports asynchronous consumption and fine-grained control over execution flow, consistent with the design described in Agent Workflow Management.The escalation action flag in events acts as a signal to break out of the loop immediately, facilitating interruptible iterative workflows.
The agent enforces that the
Runmethod cannot be overridden externally, ensuring the loop control logic remains consistent and prevents unexpected behavior.Internal state manipulation via
agentinternalis used to set the agent type toTypeLoopAgentand store configuration, which may be used for diagnostics, telemetry, or tooling integration.
Interaction with Other System Components
Sub-Agents: The LoopAgent manages and invokes its sub-agents sequentially during each iteration. These sub-agents can be any type of agent implementing
agent.Agent, including other workflow agents, enabling nested and complex workflows.Invocation Context: The
agent.InvocationContextpassed toRunprovides access to the current agent instance, session data, and runtime environment, enabling context-aware execution.Session Events: The LoopAgent yields
session.Eventobjects generated by sub-agents back to the caller, enabling incremental event processing and session state updates, as described in Session Management.Agent Framework: The LoopAgent integrates with the core agent framework (
agentpackage) and leverages internal mechanisms (agentinternal) for enhanced control and metadata management.Agent Execution Runner: Typically invoked and managed by the Agent Execution Runner, which orchestrates agent runs, manages cancellation, and handles event persistence.
Escalation Propagation: Honors escalation signals from sub-agents to allow higher-level agents or orchestrators to interrupt looping workflows, enabling responsive and adaptable processing.
Visual Diagram: LoopAgent Class Structure and Execution Flow
classDiagram
class loopAgent {
-maxIterations: uint
+Run(ctx: InvocationContext) Seq2[Event, error]
}
loopAgent ..> agent.Agent : implements
flowchart TD
Start[Start Loop]
IterCheck{MaxIterations reached?}
RunSubs[Run Sub-Agents Sequentially]
YieldEv[Yield Events to Caller]
EscalateCheck{Event Escalate?}
Terminate[Terminate Loop]
NextIter[Next Iteration]
Start --> IterCheck
IterCheck -- No --> RunSubs
RunSubs --> YieldEv
YieldEv --> EscalateCheck
EscalateCheck -- Yes --> Terminate
EscalateCheck -- No --> NextIter
NextIter --> IterCheck
IterCheck -- Yes --> Terminate
This flowchart illustrates the core execution logic of the LoopAgent:
The loop begins and checks if the maximum iteration count (if any) is reached.
If not, it runs all sub-agents sequentially.
Events produced by sub-agents are yielded to the caller.
If any event signals escalation, the loop terminates immediately.
Otherwise, the loop proceeds to the next iteration or terminates if the iteration limit is reached.
References to Related Topics
Agent Workflow Management ([80558]) — Context for workflow agents and their orchestration patterns including sequential and parallel execution.
Session Management ([80559]) — Session event handling and state persistence related to events yielded by agents.
Agent Invocation Context ([80572]) — Context interfaces providing access to agent state and runtime during execution.
Agent Execution Runner ([80560]) — Coordinates invocation and lifecycle of agents including event streaming and cancellation.
Loop Agent ([80569]) — Conceptual overview of looping workflows and agent design patterns.
Agent Tools ([80578]) — For agents that wrap sub-agents and enable composition.
LLM Integration and Agents ([80562]) — Possible types of sub-agents within the loop, especially those leveraging language models.
This documentation covers the purpose, design, and detailed behavior of the LoopAgent as implemented in agent.go, highlighting its role in iterative agent workflows within the broader AI agent framework.