Class LoopAgent

All Implemented Interfaces:
Node

public class LoopAgent extends BaseAgent
An agent that runs its sub-agents sequentially in a loop.

The loop continues until a sub-agent escalates, or until the maximum number of iterations is reached (if specified).

Composition with LlmAgents: a LoopAgent does not transfer control back to a parent LlmAgent. To react to loop results, place the LoopAgent and the follow-up LlmAgent as siblings inside a SequentialAgent. Loop sub-agents publish via outputKey and the follow-up reads via {key} placeholders in its instruction:

var refiner =
    LlmAgent.builder()
        .name("refiner")
        .model("gemini-flash-latest")
        .instruction("Refine: {draft?}")
        .outputKey("draft")
        .build();
var publisher =
    LlmAgent.builder()
        .name("publisher")
        .model("gemini-flash-latest")
        .instruction("Publish: {draft}")
        .build();
var loop =
    LoopAgent.builder().name("loop").subAgents(refiner).maxIterations(3).build();
var root = SequentialAgent.builder().name("root").subAgents(loop, publisher).build();

Persistence: in BaseAgent.runAsync(InvocationContext), each sub-agent starts only after the Runner has saved the previous sub-agent's events to the session, so it sees their state changes. An agent that wraps this one and drops, holds back, buffers or changes the id of those events can make this agent wait forever; to use its output inside your own agent, run this agent with a separate Runner and session.

  • Method Details

    • builder

      public static LoopAgent.Builder builder()
    • fromConfig

      public static LoopAgent fromConfig(LoopAgentConfig config, String configAbsPath) throws ConfigAgentUtils.ConfigurationException
      Creates a LoopAgent from configuration.
      Parameters:
      config - The agent configuration.
      configAbsPath - The absolute path to the agent config file.
      Returns:
      the configured LoopAgent
      Throws:
      ConfigAgentUtils.ConfigurationException - if the configuration is invalid
    • runAsyncImpl

      protected io.reactivex.rxjava3.core.Flowable<Event> runAsyncImpl(InvocationContext invocationContext)
      Description copied from class: BaseAgent
      Agent-specific asynchronous logic.
      Specified by:
      runAsyncImpl in class BaseAgent
      Parameters:
      invocationContext - Current invocation context.
      Returns:
      stream of agent-generated events.
    • runLiveImpl

      protected io.reactivex.rxjava3.core.Flowable<Event> runLiveImpl(InvocationContext invocationContext)
      Description copied from class: BaseAgent
      Agent-specific synchronous logic.
      Specified by:
      runLiveImpl in class BaseAgent
      Parameters:
      invocationContext - Current invocation context.
      Returns:
      stream of agent-generated events.
    • maxIterations

      public @Nullable Integer maxIterations()