Skip to content
Blog

LoopAgent: Iterative Refinement and Bounded Self-Correcting Loops

Build self-correcting agent loops with Google ADK's LoopAgent, bounded iteration limits, and EventActions escalation to achieve flawless task outputs.

Published on • November 29, 2026

AI Assistant

In complex engineering tasks—such as code generation, unit test writing, SQL optimization, and formal copy editing—generating a perfect solution on the very first try is rare. A human engineer writes code, runs the test suite, inspects compiler or linter errors, refines the implementation, and repeats until the build passes.

In Google Agent Development Kit (ADK), this iterative refinement cycle is realized through LoopAgent.

In this tutorial, we will explore how LoopAgent cycles through sub-agents, how to implement an EscalationChecker custom agent that signals loop completion via EventActions(escalate=True), and how to enforce hard iteration bounds to prevent runaway token costs.


1. Mechanics of the LoopAgent Cycle

A LoopAgent repeatedly executes its ordered list of sub_agents in a loop until one of two conditions is satisfied:

  1. An event is yielded with actions=EventActions(escalate=True) (Exit Success).
  2. The loop counter reaches max_iterations (Exit Boundary).
                 [Start Task: Write Python Function]
                                 │
                                 ▼
┌─────────────────────────────────────────────────────────────┐
│ LoopAgent: "refinement_engine" (max_iterations=4)           │
│                                                             │
│   Step 1: Coder Agent                                       │
│     - Writes or refines code -> session.state["code"]       │
│                                                             │
│   Step 2: Linter & Test Runner Agent                        │
│     - Runs pytest / ruff -> session.state["test_output"]    │
│                                                             │
│   Step 3: EscalationChecker (Custom BaseAgent)              │
│     - If test passed:                                       │
│         yield Event(actions=EventActions(escalate=True))    │
│         ==> LOOPS EXITS IMMEDIATELY!                        │
│     - Else:                                                 │
│         yield Event() ==> Loops back to Step 1              │
└─────────────────────────────────────────────────────────────┘
                                 │
                                 ▼
                  [Final Validated Solution]

2. Implementing the EscalationChecker

To signal to LoopAgent that the exit condition has been met, we inherit from ADK’s BaseAgent and emit an Event with escalate=True:

from typing import AsyncGenerator
from google.adk.agents import BaseAgent
from google.adk.agents.invocation_context import InvocationContext
from google.adk.events import Event, EventActions

class TestPassEscalationChecker(BaseAgent):
    """Inspects session state and halts the LoopAgent if tests pass."""

    async def _run_async_impl(
        self, ctx: InvocationContext
    ) -> AsyncGenerator[Event, None]:
        test_result = ctx.session.state.get("test_result", {})
        all_passed = test_result.get("passed", False)
        iteration = ctx.session.state.get("_loop_iteration", 0) + 1
        ctx.session.state["_loop_iteration"] = iteration

        if all_passed:
            print(f"✅ EscalationChecker: Tests passed on iteration {iteration}. Halting loop.")
            yield Event(
                author=self.name,
                content="Verification complete: all tests passed.",
                actions=EventActions(escalate=True)
            )
        else:
            errors = test_result.get("error_message", "Unknown test failure")
            print(f"⚠️ EscalationChecker: Iteration {iteration} failed with: '{errors}'. Refining...")
            yield Event(
                author=self.name,
                content=f"Tests failed: {errors}. Please correct the issues in the next iteration."
            )

3. Implementing Mock Testing and Code Generation Agents

Let’s define a tool that executes unit tests against the generated code:

from typing import Dict, Any
from pydantic import BaseModel, Field
from google.adk.agents import Agent

class CodeExecutionInput(BaseModel):
    code: str = Field(description="The complete Python implementation to test.")

def run_unit_tests(input_data: CodeExecutionInput) -> Dict[str, Any]:
    """Runs a simulated automated test suite against the agent's code."""
    # Example validation rule: check if function handles empty list and negative numbers
    code = input_data.code

    errors = []
    if "def calculate_median" not in code:
        errors.append("Missing function definition 'calculate_median'.")
    if "raise ValueError" not in code and "len(" in code and "== 0" not in code:
        errors.append("Edge case failure: calculate_median must raise ValueError on empty list.")
    if "sorted(" not in code and ".sort()" not in code:
        errors.append("Logic failure: Median calculation requires sorted elements.")

    if errors:
        return {"passed": False, "error_message": "; ".join(errors)}

    return {"passed": True, "error_message": None}

Now let’s wire the coder agent:

# Coder Agent
coder_agent = Agent(
    name="python_coder",
    model="gemini-3.8-flash",
    instruction="""
    You are an expert Python software engineer.
    Write a function `calculate_median(numbers: list[float]) -> float`.
    Requirements:
    1. Raise ValueError if the list is empty.
    2. Sort the input numbers.
    3. Calculate the median correctly for both odd and even length lists.
    Check the previous test errors in the conversation to correct your mistakes.
    Save your code clearly.
    """,
    output_key="current_code",
)

# Tester Agent that calls the verification tool
def test_evaluation_tool(code: str) -> Dict[str, Any]:
    return run_unit_tests(CodeExecutionInput(code=code))

tester_agent = Agent(
    name="test_runner",
    model="gemini-3.8-flash",
    instruction="""
    Extract the Python code from {current_code} and call `test_evaluation_tool`.
    Summarize the test results accurately.
    """,
    tools=[test_evaluation_tool],
    output_key="test_result_summary",
)

4. Assembling and Running the LoopAgent

import asyncio
from google.adk.agents import LoopAgent
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService

# Construct the custom evaluator that bridges test results into state
class SyncTestStateBridge(BaseAgent):
    """Executes the test directly into session state for reliable checking."""
    async def _run_async_impl(self, ctx: InvocationContext) -> AsyncGenerator[Event, None]:
        code = ctx.session.state.get("current_code", "")
        res = run_unit_tests(CodeExecutionInput(code=code))
        ctx.session.state["test_result"] = res
        yield Event(author=self.name, content=f"Test executed. Passed: {res['passed']}")

# Assemble LoopAgent
refinement_loop = LoopAgent(
    name="code_refinement_loop",
    sub_agents=[
        coder_agent,
        SyncTestStateBridge(name="tester_bridge"),
        TestPassEscalationChecker(name="escalation_checker"),
    ],
    max_iterations=4,  # Hard guardrail against infinite loops
)

async def main():
    session_service = InMemorySessionService()
    runner = Runner(agent=refinement_loop, session_service=session_service)
    session = await session_service.get_or_create("refinement_session")

    print("Beginning iterative code refinement...")
    async for event in runner.run_async(session=session, message="Please implement the calculate_median function."):
        pass

    print("\n--- Final Generated Code ---")
    print(session.state.get("current_code"))

if __name__ == "__main__":
    asyncio.run(main())

5. Critical Best Practices for Loop Agents

  1. Always Set max_iterations: Never create a LoopAgent without an explicit max_iterations bound (typically 3 to 5). Without this, an unresolvable error will burn API quotas indefinitely.
  2. Deterministic Evaluators: Do not rely solely on an LLM to evaluate another LLM’s output in a loop, as conversational drift can cause cyclic hallucination. Wherever possible, use deterministic tools (compiler, unit tests, linter, regex, AST validator) as the judge.
  3. Preserve Context State: Ensure each iteration’s failure reasons remain visible in the history so the refining agent knows what went wrong and does not repeat the identical mistake.

Takeaway: LoopAgent provides the foundational building block for self-correcting agent architectures in Google ADK, delivering verified software and validated documents through bounded iterative refinement.

Sources