An agent loop should finish when Claude has nothing more to do. What is the right check?
Why C is the answer
Continue while stop_reason is tool_use, and stop on the other reasons
stop_reason tells you what happened. Replies can contain text and tool calls together, so reading the text is not a reliable signal.
In detail
- stop_reason is the API's direct signal for why a response ended.
- While it is tool_use, your code runs the tools and sends the results back. Other reasons end the loop or need their own handling.
- A reply can hold text and a tool call together, so the presence of text proves nothing.
- Treat other stop reasons deliberately, such as max_tokens or a refusal.
Use case
An illustrative scenario, not a real incident.
A coding agent writes "I will run the tests now" and requests a tool. Code that stops on text ends the loop, and the tests never run. Continuing while stop_reason is tool_use lets the agent finish.
See it in different ways
stateDiagram-v2 [*] --> Calling Calling --> RunningTools: tool_use RunningTools --> Calling: tool_result Calling --> Done: end_turn RunningTools --> Handoff: turn limit reached Done --> [*] Handoff --> [*]
stateDiagram-v2 state "Call Claude" as s0 state "Run tools" as s1 state "Finished" as s2 [*] --> s0 s0 --> s1: tool_use s1 --> s0: tool_result s0 --> s2: end_turn s2 --> [*]
Key point: Text in a reply tells you nothing about whether the work is done.
Why the other options are wrong
- A. Continue until the model writes the word DONE somewhere in its final answer
- A magic word is fragile, because the model may never write it or may write it too soon.
- B. Stop when the reply contains any text, since text means Claude has finished
- Text can appear in a reply that also requests a tool, so this stops the loop too early.
- D. Stop after one turn, because longer loops always cost more than they return
- Many tasks need several turns. One turn would cut them off.

