Loop Guards: max_steps & Repeated-Action Halt
An agent that can loop can loop forever. The model gets confused, repeats the same failing tool call, and you wake up to a five-figure bill. Guard rails are not optional - they are the difference between a demo and something you would put in front of a customer. Two guards catch almost everything: a hard step ceiling, and repeated-action detection.
You will build run_with_guard(plan, tools, max_steps). It runs the same kind of plan as before, but instead of just a trace it returns a small report: {"status": ..., "trace": [...]}, where status is one of three outcomes:
"max_steps"- the agent hit the step ceiling before finishing. Stop and flag it."loop_detected"- the agent tried the exact same action (same tool, same args) it has already taken. That is a loop; halt before it spins."done"- the plan completed normally (it ran out of steps or hit a"finish"action).
Track which actions you have seen so repeats are cheap to detect. A dict is not hashable, so turn each action into a hashable key first:
seen = set()
...
key = (action, repr(args)) # repr makes the args dict hashable
if key in seen:
return {"status": "loop_detected", "trace": trace}
seen.add(key)The trace truncates at the halt point: when you stop on max_steps or loop_detected, return the trace of what actually ran up to that moment, not the whole plan. That truncated trace is your incident report - it shows exactly where the agent went off the rails.
Check the step ceiling and the repeat before recording a step, so the counts line up: with max_steps=3 the trace holds at most 3 entries, and a repeated action is caught before it runs a second time. Press Run to watch all three outcomes fire.
Write run_with_guard(plan, tools, max_steps=10) returning {"status": ..., "trace": [...]}. Halt with "max_steps" when the trace reaches max_steps entries, with "loop_detected" when an action repeats exactly (same tool and args), and with "done" when the plan completes or hits "finish". Check the guards before recording each step so the trace truncates at the halt point.
This lesson is locked
Lessons open one at a time. Finish the previous lesson to unlock this one.