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 content refinement system that iteratively improves writing until it meets quality standards:

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

// Step 1: Content improver that refines the current draft
const contentImprover = new LlmAgent({
  name: "content-improver",
  model: "gemini-2.5-flash",
  instruction: `
    Improve the current content by:
    - Enhancing clarity and readability
    - Strengthening arguments and evidence
    - Improving flow and structure
    - Fixing grammar and style issues
    
    Provide the improved version as your output.
  `,
  outputKey: "current_draft",
});

// Step 2: Quality evaluator that decides if we're done
const qualityEvaluator = new LlmAgent({
  name: "quality-evaluator",
  model: "gemini-2.5-flash",
  instruction: `
    Evaluate the current draft quality on a scale of 1-10:
    - Clarity and readability (1-10)
    - Argument strength (1-10) 
    - Professional tone (1-10)
    - Grammar and style (1-10)
    
    If ALL scores are 8 or higher, respond with "QUALITY_ACHIEVED".
    Otherwise, provide specific feedback for improvement.
  `,
  outputKey: "quality_assessment",
});

// Step 3: Stop condition checker
const stopConditionChecker = new (class extends LlmAgent {
  constructor() {
    super({
      name: "stop-checker",
      description: "Stops loop when quality is achieved",
    });
  }

  protected async *runAsyncImpl(ctx: any) {
    const assessment = ctx.session.state.get("quality_assessment", "");
    const qualityAchieved = assessment.includes("QUALITY_ACHIEVED");

    yield new Event({
      author: this.name,
      actions: new EventActions({ escalate: qualityAchieved }),
    });
  }
})();

// Iterative refinement loop - up to 5 improvement cycles
const contentRefinementLoop = new LoopAgent({
  name: "content-refinement-loop",
  description: "Iteratively improves content until quality standards are met",
  subAgents: [contentImprover, qualityEvaluator, stopConditionChecker],
  maxIterations: 5,
});

// Usage: Transform rough draft into polished content
const result = await contentRefinementLoop.run({
  message:
    "Please refine this draft: 'AI is good for business because it helps with stuff.'",
});

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?