ADK Loop Agents
A LoopAgent repeatedly runs a sequence of agents until either:
- The specified number of
max_iterationsis reached, or - A termination condition is met (via
tool_context.actions.escalate = Trueinside a tool).
E.g., generate_image and count_food_items running in a loop until the image has the right number of items.
Original Notion page had a diagram of the iteration flow. See
migrated_fromURL.
Example — LinkedIn post generator with refinement loop
"""
LinkedIn Post Generator Root Agent
This module defines the root agent for the LinkedIn post generation application.
It uses a sequential agent with an initial post generator followed by a refinement loop.
"""
from google.adk.agents import LoopAgent, SequentialAgent
from .subagents.post_generator import initial_post_generator
from .subagents.post_refiner import post_refiner
from .subagents.post_reviewer import post_reviewer
# Create the Refinement Loop Agent
refinement_loop = LoopAgent(
name="PostRefinementLoop",
max_iterations=10,
sub_agents=[
post_reviewer,
post_refiner,
],
description="Iteratively reviews and refines a LinkedIn post until quality requirements are met",
)
# Create the Sequential Pipeline
root_agent = SequentialAgent(
name="LinkedInPostGenerationPipeline",
sub_agents=[
initial_post_generator, # Step 1: Generate initial post
refinement_loop, # Step 2: Review and refine in a loop
],
description="Generates and refines a LinkedIn post through an iterative review process",
)Refinement loop
refinement_loop = LoopAgent(
name="PostRefinementLoop",
max_iterations=10,
sub_agents=[
post_reviewer,
post_refiner,
],
description="Iteratively reviews and refines a LinkedIn post until quality requirements are met",
)Post reviewer (the gatekeeper)
from google.adk.agents.llm_agent import LlmAgent
from .tools import count_characters, exit_loop
post_reviewer = LlmAgent(
name="PostReviewer",
model=GEMINI_MODEL,
instruction="""You are a LinkedIn Post Quality Reviewer.
Your task is to evaluate the quality of a LinkedIn post about Agent Development Kit (ADK).
## EVALUATION PROCESS
1. Use the count_characters tool to check the post's length.
Pass the post text directly to the tool.
2. If the length check fails (tool result is "fail"), provide specific feedback on what needs to be fixed.
Use the tool's message as a guideline, but add your own professional critique.
3. If length check passes, evaluate the post against these criteria:
- REQUIRED ELEMENTS:
1. Mentions @aiwithbrandon
2. Lists multiple ADK capabilities (at least 4)
3. Has a clear call-to-action
4. Includes practical applications
5. Shows genuine enthusiasm
- STYLE REQUIREMENTS:
1. NO emojis
2. NO hashtags
3. Professional tone
4. Conversational style
5. Clear and concise writing
## OUTPUT INSTRUCTIONS
# return feedback, because loop agent keeps running
IF the post fails ANY of the checks above:
- Return concise, specific feedback on what to improve
ELSE IF the post meets ALL requirements:
# so you need an exit_loop function (a special case) for the loop agent to break out
- Call the exit_loop function
- Return "Post meets all requirements. Exiting the refinement loop."
Do not embellish your response. Either provide feedback on what to improve OR call exit_loop and return the completion message.
## POST TO REVIEW
{current_post}
""",
description="Reviews post quality and provides feedback on what to improve or exits the loop if requirements are met",
tools=[count_characters, exit_loop],
output_key="review_feedback",
)Post refiner
"""
LinkedIn Post Refiner Agent
This agent refines LinkedIn posts based on review feedback.
"""
from google.adk.agents.llm_agent import LlmAgent
GEMINI_MODEL = "gemini-2.0-flash"
post_refiner = LlmAgent(
name="PostRefinerAgent",
model=GEMINI_MODEL,
instruction="""You are a LinkedIn Post Refiner.
Your task is to refine a LinkedIn post based on review feedback.
## INPUTS
**Current Post:**
{current_post}
**Review Feedback:**
{review_feedback} # from the previous loop iteration
## TASK
Carefully apply the feedback to improve the post.
- Maintain the original tone and theme of the post
- Ensure all content requirements are met:
1. Excitement about learning from the tutorial
2. Specific aspects of ADK learned (at least 4)
3. Brief statement about improving AI applications
4. Mention/tag of @aiwithbrandon
5. Clear call-to-action for connections
- Adhere to style requirements:
- Professional and conversational tone
- Between 1000-1500 characters
- NO emojis
- NO hashtags
- Show genuine enthusiasm
- Highlight practical applications
## OUTPUT INSTRUCTIONS
- Output ONLY the refined post content
- Do not add explanations or justifications
""",
description="Refines LinkedIn posts based on feedback to improve quality",
output_key="current_post",
)The exit-loop tool
The loop agent breaks out when a tool sets tool_context.actions.escalate = True.
def exit_loop(tool_context: ToolContext) -> Dict[str, Any]:
"""
Call this function ONLY when the post meets all quality requirements,
signaling the iterative process should end.
Returns:
Empty dictionary
"""
print("\n----------- EXIT LOOP TRIGGERED -----------")
print("Post review completed successfully")
print("Loop will exit now")
print("------------------------------------------\n")
tool_context.actions.escalate = True
return {}See next
- ADK-Sequential-Agent — looped agents typically run inside a sequential pipeline
- ADK-Tools —
exit_loopis just a custom tool with special side-effects