Lesson 9 / 26
Loops With Exit Conditions and Caps
Every loop needs a way out.
Target and maximum
A while loop repeats steps (revise a draft, retry a tool, ask a clarifying question) until a condition holds. Always pair the condition with a hard cap on iterations, because a model may never satisfy it, and each iteration costs tokens and time. Record the reason the loop ended (target met or cap hit) in state, and handle the cap case explicitly, for example by returning the best attempt with a warning or escalating.
A loop with a target and an iteration cap, run
I ran this with plain Python 3. It is a small model of the workflow idea, not Agent Builder itself, and no model is called. With a reachable target the loop stops after 2 iterations; with an unreachable target it stops at the cap of 5 and reports why.
# A while-loop node with an exit condition AND a hard iteration cap.
def draft(attempt):
return 50 + 15 * attempt # stand-in quality score of a revised draft
for target, cap in [(80, 5), (200, 5)]:
attempt, score = 0, 0
while score < target and attempt < cap:
attempt += 1
score = draft(attempt)
reason = "target met" if score >= target else "hit iteration cap"
print(f"target {target}: stopped after {attempt} iterations, score {score} ({reason})")
Output:
target 80: stopped after 2 iterations, score 80 (target met) target 200: stopped after 5 iterations, score 125 (hit iteration cap)
Log iteration counts
Track the average number of iterations per run; a rise usually means a prompt or tool got worse.
Quick check: Why add a maximum iteration count to a loop?
- Because loops are free
- To make it run forever
- The exit condition may never be met, and each iteration costs time and money
- To remove the exit condition
Answer
The exit condition may never be met, and each iteration costs time and money — Caps bound cost and latency.