0Pricing
Claude Architect · Lesson

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 again
  • end_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
    pass

All lessons in this course

  1. The Core Loop
  2. Terminating on stop_reason
  3. Anti-Pattern: Parsing Text for Completion
  4. Anti-Pattern: Arbitrary Iteration Caps
← Back to Claude Architect