Anti-Pattern: Parsing Text for Completion
Why scanning output for 'done' is fragile and wrong.
The Trap
You build an agent. It runs tools, thinks, replies. Now you need to know when it's done. A tempting shortcut: scan the model's text for a word like done, finished, or complete, and stop the loop when you see it.
This is the anti-pattern Parsing Text for Completion. It feels intuitive, but it is fragile and wrong. The Claude API already hands you a precise, structured completion signal. In this lesson you'll learn why text-scanning breaks and what to use instead.
How the Agentic Loop Really Works
The agentic loop is driven by one field on the response: stop_reason. The loop is simple and deterministic:
- Send the request (with the full message history every turn).
- Inspect
stop_reason. - If it is
tool_use, run the tools, append the results to history, and repeat. - If it is
end_turn, the task is complete. Stop.
The model itself tells you, through structured metadata, whether it wants to keep going or is finished. You never have to guess by reading prose.
while True:
response = client.messages.create(
model="claude-opus-4-8",
max_tokens=16000,
tools=tools,
messages=messages,
)
if response.stop_reason == "end_turn":
break # complete
# else: tool_use -> run tools, append results, loopAll lessons in this course
- The Core Loop
- Terminating on stop_reason
- Anti-Pattern: Parsing Text for Completion
- Anti-Pattern: Arbitrary Iteration Caps