TypeScriptADK-TS

Loop Agents

Repeat agent execution until conditions are met

Loop agents create powerful iterative workflows that keep improving until they reach the desired outcome. Think of it as your AI perfectionist - it won't stop until the work meets quality standards or maximum attempts are reached.

Perfect for scenarios where "good enough" isn't good enough. Whether you're refining content, debugging code, or iterating on creative work, loop agents ensure continuous improvement through repeated cycles of execution and evaluation.

Unlike sequential agents that run once, or parallel agents that run simultaneously, loop agents focus on iterative refinement and progressive enhancement.

Iterative Excellence

  • Key benefit: Keep improving until you hit quality standards or resource limits.
  • Perfect for: Content refinement, problem solving, creative iteration, and quality convergence.

Quick Start Example

Here's a research synthesis agent that iteratively gathers and refines information until a comprehensive understanding is achieved:

import { LlmAgent, LoopAgent, Event, EventActions } from "@iqai/adk";

// Research question generator
const researchPlannerAgent = new LlmAgent({
  name: "research_planner_agent",
  model: "gemini-2.5-flash",
  description: "Generates focused research questions and search strategies",
  instruction:
    "Break down the research topic into specific, answerable questions. Prioritize the most important questions to investigate.",
  outputKey: "research_questions", // Key for storing generated questions
});

// Information gatherer using search
const infoGathererAgent = new LlmAgent({
  name: "info_gatherer_agent",
  model: "gemini-2.5-flash",
  description: "Gathers information from various sources",
  instruction:
    "Search for and collect relevant information to answer the research questions. Be thorough but focused.",
  outputKey: "gathered_info", // Key for storing gathered information
});

// Synthesis and gap analyzer
const synthesisAgent = new LlmAgent({
  name: "synthesis_agent",
  model: "gemini-2.5-flash",
  description: "Synthesizes information and identifies knowledge gaps",
  instruction:
    "Analyze the gathered information. Synthesize key findings and identify what important questions remain unanswered.",
  outputKey: "synthesis_analysis", // Key for storing synthesis results
});

// Research completion checker
const researchCompleterAgent = new (class extends LlmAgent {
  constructor() {
    super({
      name: "research_completer_agent",
      description: "Determines if research is sufficiently complete",
    });
  }

  protected async *runAsyncImpl(ctx: any) {
    const synthesis = ctx.session.state.get("synthesis_analysis", "");
    const questions = ctx.session.state.get("research_questions", "");

    // Check if major knowledge gaps remain
    const hasMajorGaps =
      synthesis.toLowerCase().includes("major gap") ||
      synthesis.toLowerCase().includes("insufficient") ||
      synthesis.toLowerCase().includes("unclear");

    // Emit event indicating whether to escalate (continue research) or not
    yield new Event({
      author: this.name,
      actions: new EventActions({ escalate: !hasMajorGaps }),
    });
  }
})();

// Research synthesis loop - iterative research refinement
const researchSynthesisAgent = new LoopAgent({
  name: "research_synthesis_agent",
  description:
    "Iteratively researches and synthesizes information until comprehensive understanding is achieved",
  subAgents: [
    researchPlannerAgent,
    infoGathererAgent,
    synthesisAgent,
    researchCompleterAgent,
  ],
  maxIterations: 4,
});

// Export the loop agent for use
export { researchSynthesisAgent };

Visual Flow

How Loop Processing Works

Loop agents create iterative cycles where each iteration can build upon and improve previous results:

🔄 Iteration Cycle

  1. Execute sub-agents - Run all agents in sequence (like sequential agents)
  2. Evaluate conditions - Check if stopping criteria are met
  3. Continue or stop - Either start next iteration or exit loop
  4. Progressive improvement - Each cycle can reference and improve previous results

🚪 Termination Strategies

Maximum Iterations (Safety Net)

maxIterations: 5; // Prevents infinite loops

Quality-Based Stopping (Smart Exit)

// Agent evaluates quality and signals when done
yield new Event({
  actions: new EventActions({ escalate: qualityMet }),
});

📊 Progressive Enhancement Each iteration sees the full session history, allowing agents to:

  • Reference previous attempts
  • Learn from past iterations
  • Build incrementally toward the goal
  • Avoid repeating unsuccessful approaches

Loop Safety

Always set maxIterations as a safety net! Even with smart stopping conditions, having a maximum prevents runaway loops and unexpected resource consumption.

Real-World Use Cases

📝 Content Refinement Loop
Draft → Improve → Evaluate → Repeat until quality standards met

🔍 Research Deep-Dive
Initial Research → Analyze Gaps → Research More → Repeat until comprehensive

🛠️ Code Optimization
Generate Code → Test Performance → Optimize → Repeat until benchmarks hit

🎨 Creative Iteration
Generate Ideas → Evaluate Creativity → Refine → Repeat until breakthrough

🐛 Problem Debugging
Try Solution → Test → Debug Issues → Repeat until tests pass

🎯 Marketing Copy Testing
Write Copy → A/B Test → Analyze Results → Improve → Repeat

When to Choose Loop Agents

Perfect For Iterative Improvement

  • Use when: You need progressive refinement and have clear quality criteria
  • Benefit: Achieve higher quality results through iterative enhancement

✅ Choose Loop When:

  • Quality matters more than speed - Need excellent results, not just "good enough"
  • Clear success criteria - You can define "done" or "good enough"
  • Improvable processes - Each iteration can meaningfully build on the last
  • Resource tolerance - Can afford multiple processing cycles
  • Learning from attempts - Previous tries inform better approaches

❌ Don't Use Loop When:

  • Single execution produces sufficient results
  • No clear improvement path exists between iterations
  • Time/cost constraints prevent multiple cycles
  • Risk of infinite loops without proper safeguards
  • Tasks are already optimized and won't benefit from repetition

Always Set Limits

  • Critical: Always set maxIterations to prevent runaway loops.
  • Monitor: Watch resource usage during extended iterations.
  • Test: Validate your stopping conditions work reliably.

How is this guide?