CHAPTER 02 · The Agent Loop Pattern · 3 / 8
Termination and the safety cap
The loop needs two stopping conditions:
- Natural termination: the model produces a final answer with no tool calls.
- A hard iteration cap: a maximum number of loop turns (commonly 5–15).
The cap is non-negotiable. Without it, a confused model can loop forever, calling a tool, getting a result it doesn't like, calling again, ad infinitum, burning tokens and money. The cap converts "infinite loop" into "bounded, eventually-terminating process." When the cap is hit, return whatever the model has produced so far (or a graceful "I wasn't able to complete this") rather than erroring.
A second guard worth considering: detect non-productive loops: the same tool called with the same arguments repeatedly, and break early. The model is signalling it's stuck.