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
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.
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.
until_good = LoopAgent(name="until_good", sub_agents=[writer], max_iterations=5)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
| Stop | Set by | What it means |
|---|---|---|
max_iterations | You, on the loop | A ceiling, so a stuck loop is not an unbounded bill |
actions.escalate | A tool, mid-run | The 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.
- 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.