Anti-Pattern: Arbitrary Iteration Caps
Caps are a safety net, not a stopping mechanism.
The Tempting Shortcut
You build an agentic loop. To feel safe, you write for i in range(5) and call it done. The agent stops after 5 turns.
This feels responsible. It is actually an anti-pattern. An arbitrary iteration cap as your primary stop mechanism cuts the model off mid-thought and produces incomplete work.
This lesson shows you the right mental model: a cap is a safety net, never the thing that decides when the task is finished.
How the Loop Actually Ends
The agentic loop is simple: send a request, inspect stop_reason, and react.
tool_use→ run the tools, append results to history, loop againend_turn→ the model is finished; you stop
The model signals completion via stop_reason. Your job is to listen for that signal, not to guess a turn count in advance.
resp = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
messages=messages,
tools=tools,
)
if resp.stop_reason == "tool_use":
# run tools, append results, loop again
pass
elif resp.stop_reason == "end_turn":
# task complete -- this is the real stop
passAll lessons in this course
- The Core Loop
- Terminating on stop_reason
- Anti-Pattern: Parsing Text for Completion
- Anti-Pattern: Arbitrary Iteration Caps