Agentic Loop Lifecycle
CoreDesign and implement agentic loops for autonomous task execution · Difficulty 2/5
An Agentic Loop is the core pattern for building AI agents: repeatedly calling Claude, executing requested tools, and feeding results back until the task is complete.
The Loop
while True:
response = call_claude(messages)
if response.stop_reason == 'end_turn':
break # Task complete
if response.stop_reason == 'tool_use':
results = execute_tools(response.tool_calls)
messages.append(response)
messages.append(tool_results(results))Loop Control
field (tool_use = continue, end_turn` = stop)Stop Reason Values
| Value | Meaning | Action |
|---|
|-------|---------|--------|
| `end_turn` | Claude finished its response naturally | Present response to user |
|---|---|---|
max_tokens | Hit the max_tokens limit | Response may be truncated; consider increasing limit |
stop_sequence | Hit a custom stop sequence | Parse response up to the stop sequence |
tool_use | Claude wants to use a tool | Execute the tool and return results |
Best Practices
max_tokens stop reason (response may be truncated)Key Takeaways
- ✓stop_reason is the ONLY reliable signal for agentic loop control
- ✓tool_use = continue the loop, end_turn = stop the loop
- ✓Always include a maximum iteration safety guardrail as a backup, not the primary mechanism
- ✓max_tokens indicates potential truncation -- handle gracefully
Glossary Terms
The core pattern for AI agents: call Claude, check stop_reason, if 'tool_use' execute the requested tools and append results, then call Claude again. Repeat until stop_reason is 'end_turn'. The number of loop iterations is determined dynamically by task complexity.
A field in the Claude API response indicating why the model stopped generating. Values: 'end_turn' (natural completion), 'max_tokens' (hit limit), 'stop_sequence' (hit custom stop), 'tool_use' (wants to call a tool). The primary signal for controlling agentic loops.
A stop_reason value indicating Claude finished its response naturally without hitting a limit or requesting a tool. In agentic loops, this signals the loop should stop and the final response should be presented to the user.
Related Concepts
Test Yourself1 of 1
You're implementing the agentic loop for your support agent. After each API call to Claude, you need to determine whether to continue the loop (execute the requested tools and call Claude again) or stop (present the final response to the customer). What determines this decision?