Google ADKgoogle-adk 2.8 · Python 3.10+
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
28 small wins to finish your pathNext lesson

Doing it again until it is right

A LoopAgent runs its sub agents over and over. Two things can stop it: a limit you set, or an agent saying it is done.

The way out

python
def good_enough(tool_context: ToolContext) -> dict:
    """Stop the loop: the draft is good enough to send."""
    tool_context.actions.escalate = True
    return {"status": "done"}

One line does it. escalate on the actions is how anything inside a loop says the work is finished, and it is the same actions object from lesson 6.

python
writer = LlmAgent(
    name="writer",
    model=PretendModel(replies=[say("draft 1"), say("draft 2"),
                                call("good_enough"), say("that will do")]),
    instruction="Improve the reply. Call good_enough when it is ready.",
    tools=[good_enough],
    output_key="text",
)

The scripted replies are the interesting part: two drafts, then the tool call. A real model would decide that for itself, and this makes the shape visible.

python
until_good = LoopAgent(name="until_good", sub_agents=[writer], max_iterations=5)
Example
session = await run(until_good, "Write a reply about a late order")
print("state:", dict(session.state))

Three passes, not five. The first two produced drafts, the third called the tool, and the escalation ended the loop early. Without that tool it would have run all five times.

Running this prints a deprecation warning: as of ADK 2.x the three template workflow agents are deprecated in favour of a newer Workflow API. Lesson 20 covers the newer way and when each is right.

The two ways out, and why you want both

StopSet byWhat it means
max_iterationsYou, on the loopA ceiling, so a stuck loop is not an unbounded bill
actions.escalateA tool, mid-runThe work is finished, stop early

A loop with only a limit always runs the full number of times. A loop with only an escalation runs forever when the escalation never comes. Real loops have both.

  • Improve until it passes a check. Draft, review, revise, with a reviewer deciding.
  • Try until it works. A tool that sometimes fails, with a limited number of attempts.
  • Refine a number. Search, evaluate, narrow, repeat.
Two agents in the loop
The reviewer is usually a separate agent in the same loop, holding the escalating tool. Asking one agent both to write and to judge its own writing tends to end at the first iteration.
Try it yourself
  • Take the tool away and watch it run the full five iterations.
  • Add a reviewer agent in the loop that holds the stopping tool.

This is what real progress feels like.