Agents & Tool Use
Agentic Loops and stop_reason Handling
The agentic loop lifecycle - sending requests, inspecting stop_reason, executing tools, and appending results. The foundation of every autonomous Claude agent.
intermediate · 8 min read
The agentic loop is the fundamental control structure for autonomous Claude agents. It determines how an agent decides what to do next, when to call tools, and when to stop.
The Loop Lifecycle
- Send a request to Claude with the system prompt, user message, and conversation history
- Receive the response and inspect the
stop_reasonfield - If
stop_reasonis"tool_use": execute the requested tool(s), append results to conversation history, and loop back to step 1 - If
stop_reasonis"end_turn": present the final response to the user - the task is complete
The model itself decides when to call tools and when to stop. This is model-driven decision-making: Claude reasons about which tool to call next based on context, rather than following a pre-configured decision tree.
Anti-Patterns
Three patterns to avoid when implementing agentic loops:
Parsing natural language signals for termination. The model may phrase completion differently each time ("I'm done," "That's all," "Here's the result"). Relying on text parsing is fragile. Use stop_reason instead.
Arbitrary iteration caps as the primary stop mechanism. Setting a hard cap of 5 iterations may cut off legitimate multi-step reasoning. The model signals completion via "end_turn" - trust that signal.
Checking for assistant text content as completion. The model can include text alongside tool calls. The presence of text does not mean the task is complete; only stop_reason: "end_turn" does.
Tool Results in Context
After executing a tool, its result must be appended to the conversation history before the next API call. This allows the model to:
- Reason about new information from the tool
- Decide whether more tools are needed
- Integrate multiple tool results into a coherent response
Without appending tool results, the model cannot see what happened and will re-request the same tools.