Skip to main content

Module 20: Cyclic Workflows - Iteration and Self-Correction

๐Ÿงญ Where We Are in Part 3: Here in Module 20, we conclude Chapter B (Graph & Code Workflows)! Using the exact same @node + await ctx.run_node(...) pattern from Module 18, you add a bounded Python for loop so agents can iteratively critique and refine their own output until quality passes!

Cyclic Workflows Hero (Light) Cyclic Workflows Hero (Dark) Figure: Iterative critique, evaluation, and self-correction loops with strict iteration guardrails.

Theoryโ€‹

Iterative Refinement in ADK 2.0โ€‹

Many real-world AI tasks โ€” writing code, drafting legal summaries, or crafting essays โ€” rarely produce a perfect result on the first try. Instead of accepting the first draft, you can let one agent critique the work and another agent improve it in a loop until it meets your quality bar.

In ADK 2.0, you build cyclic workflows using a @node Dynamic Workflow (from Module 18) with a standard Python for or while loop. Because the loop is plain Python, you have total control over termination conditions and safety guardrails like max_iterations.

The Evaluator โ†’ Optimizer Loop Patternโ€‹

Evaluator-Optimizer Iteration Loop (Light) Evaluator-Optimizer Iteration Loop (Dark) Figure: Generator-Evaluator feedback architecture showing draft critique, rubric scoring thresholding, and iteration limits.

The most common iterative architecture is the Evaluator โ†’ Optimizer loop (for example, a Code Auditor โ†’ Code Fixer pipeline):

from pydantic import BaseModel
from google.adk import Agent, Context, Workflow
from google.adk.workflow import node

class AuditResult(BaseModel):
passed: bool
issues: str

# 1. Define the specialist agents
# Every child Agent invoked dynamically via ctx.run_node() inside
# @node(rerun_on_resume=True) must also set rerun_on_resume=True!
code_auditor = Agent(
name="code_auditor",
model="gemini-3.8-flash",
rerun_on_resume=True,
instruction="Check the Python snippet for bugs or security issues. Set passed=True only if clean.",
output_schema=AuditResult,
)
code_fixer = Agent(
name="code_fixer",
model="gemini-3.8-flash",
rerun_on_resume=True,
instruction="Fix the provided Python snippet based on the listed issues. Return only the corrected code.",
)

# 2. Define the Orchestrator Node with a bounded Python loop
@node(rerun_on_resume=True)
async def code_review_loop(ctx: Context, node_input: str):
current_code = node_input

# Bounded loop (max 5 iterations) prevents infinite loops and runaway API costs
for i in range(5):
print(f"--- Review Iteration {i + 1} ---")

# Ask the Auditor to review the current code (returns a plain dict)
audit = await ctx.run_node(code_auditor, current_code)

# Structured, reliable early exit condition
if audit["passed"]:
break

# Ask the Fixer to improve the code using the Auditor's feedback
current_code = await ctx.run_node(
code_fixer, f"CODE:\n{current_code}\n\nISSUES:\n{audit['issues']}"
)

return current_code

# 3. Register the orchestrator in a Workflow
root_agent = Workflow(
name="CodeReviewSystem",
edges=[("START", code_review_loop)],
)

Pro Tip โ€” Prefer Structured Pydantic output_schema Over String Matching: Notice how code_auditor uses output_schema=AuditResult and await ctx.run_node(code_auditor, current_code) returns a validated Python dict (audit["passed"], audit["issues"])โ€”not a raw JSON string or a BaseModel instance! Avoid plain-text substring checks like if "APPROVED" in feedback:โ€”if the model replies "NOT APPROVED: needs more detail", "APPROVED" in feedback evaluates to True and exits early on a failed draft! Always prefer a boolean field on a Pydantic output_schema (as you will build in Lab 20).

Why Use Python Loops in @node Workflows?โ€‹

  1. Zero Boilerplate: Just write a normal Python for or while loop โ€” no special loop DSL required.
  2. Flexible Exit Conditions: Stop on "APPROVED", on a structured numeric score (score >= 0.8), or when the draft stops changing.
  3. Built-in Cost Guardrails: for i in range(max_iterations) guarantees the loop always terminates, even if the Critic is never satisfied.
  4. Full Trace Visibility: In the Dev UI, every ctx.run_node() call inside the loop shows up as its own trace step, letting you watch the draft improve iteration by iteration.
๐ŸŽฏ Knowledge CheckSelect Best Answer

Why should you avoid loose substring checks like `if 'APPROVED' in feedback: break` when terminating an iterative Critic -> Refiner loop?

Key Takeawaysโ€‹

  • Iterative tasks require multiple passes of review and refinement.
  • Dynamic Workflows (@node) are the modern way to implement loops in ADK 2.0.
  • Safety First: Always use a max_iterations limit to prevent infinite loops and excessive API costs.
  • Node-to-Node passing: The output of one iteration is manually passed as the input to the next via ctx.run_node().
๐Ÿ“–

20: Cyclic Workflows & Loops(Theory & Overview)

Part 3: Multi-Agent Systems โ€ข Module 20

Overall Course Progress:
0%(0/98)
Next Step: Challenge Lab ๐Ÿงช โ†’