Agentic loops for autonomous task execution
Think of Claude as a capable colleague who cannot touch the keyboard. You give it a task, and each reply is one of two things: "please run this tool for me" or "here is my final answer".
Your program goes round in a loop: run the tools Claude asked for, show it the results, ask again, until Claude says it is finished. How does the program tell the two kinds of reply apart? Not by reading the words. Every response carries a label, stop_reason. tool_use means "run the tools and come back"; end_turn means "done". The loop checks that label.
New terms: agentic loop, tool_use, tool_result, stop_reason
What problem does the loop solve?
A single call to the Messages API gives you one reply from Claude. That is enough to answer a question from what Claude already knows, but not enough to do something in the world: look up an order, read a file, issue a refund. For that, Claude has to ask your program to run a tool, wait for the answer, think about it, and possibly ask for another tool. Nobody knows in advance how many rounds that will take. One order lookup may be enough; a messy refund case may need five tool calls.
The agentic loop is the small piece of control flow that makes this work. It keeps calling the API, runs whatever tools Claude asks for, feeds the results back, and stops only when Claude signals that it has finished. Everything else in Domain 1 (subagents, hooks, sessions) is built on top of this loop, so it is worth understanding line by line.
Step 1: describe the tools Claude may use
Claude cannot see your code. It only sees a tool definition: a name, a description written for the model, and an input_schema (a JSON Schema) that says which arguments the tool takes. You send this list with every request. Claude reads it the way a developer reads API documentation and decides which tool, if any, fits the situation.
TOOLS = [
{
"name": "get_customer",
"description": (
"Look up a customer by email or phone. Returns customer_id, name and "
"account status. Call this before any order or refund action."
),
"input_schema": {
"type": "object",
"properties": {
"email": {"type": "string", "description": "Customer email address"},
"phone": {"type": "string", "description": "E.164, e.g. +14155550100"},
},
},
},
{
"name": "lookup_order",
"description": (
"Get one order by order number (format #12345). Returns status, items, "
"amounts and delivery date. Not for finding who a customer is."
),
"input_schema": {
"type": "object",
"properties": {"order_id": {"type": "string", "description": "e.g. 12345"}},
"required": ["order_id"],
},
},
]
nameThe identifier Claude uses when it asks for the tool. Your code uses the same name to decide which real function to run.descriptionThe most important field. It is the only explanation Claude gets of what the tool does and when to use it. Vague descriptions cause wrong tool choices (Task 2.1).input_schemaA JSON Schema for the arguments. Claude fills in arguments that match it.requiredlists the arguments that must always be present.
Step 2: the loop itself, annotated
The loop below is a complete, minimal agent. Read the comments in order. Notice that the program never inspects Claude's wording to decide what to do next. It only reads stop_reason and the types of the content blocks.
import json
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
MODEL = "claude-sonnet-5-5"
SYSTEM = "You are Acme's support agent. Verify the customer before order actions."
def run_tool(name, args):
"""Run the real function. Return (text_for_claude, failed)."""
try:
if name == "get_customer":
return json.dumps(crm.find_customer(**args)), False
if name == "lookup_order":
return json.dumps(orders.get(args["order_id"])), False
return f"Unknown tool: {name}", True
except TimeoutError:
return json.dumps({"errorCategory": "transient", "isRetryable": True}), True
def run_agent(task, safety_cap=25):
messages = [{"role": "user", "content": task}] # the conversation so far
for _ in range(safety_cap): # safety net, not the stop rule
resp = client.messages.create(
model=MODEL, max_tokens=4096, system=SYSTEM,
tools=TOOLS, messages=messages,
)
# 1. Always keep Claude's full turn, including any tool_use blocks.
messages.append({"role": "assistant", "content": resp.content})
# 2. Decide what to do from stop_reason, never from the text.
if resp.stop_reason == "end_turn":
return "".join(b.text for b in resp.content if b.type == "text")
if resp.stop_reason == "tool_use":
results = []
for block in resp.content: # may hold several tool_use blocks
if block.type == "tool_use":
text, failed = run_tool(block.name, block.input)
results.append({
"type": "tool_result",
"tool_use_id": block.id, # must match the request
"content": text,
"is_error": failed,
})
# 3. All results go back together, as one user turn.
messages.append({"role": "user", "content": results})
continue
if resp.stop_reason == "max_tokens":
raise RuntimeError("Reply was cut off. Raise max_tokens or ask it to continue.")
raise RuntimeError(f"Unhandled stop_reason: {resp.stop_reason}")
raise RuntimeError("Safety cap reached without finishing. Investigate the run.")
How the message list grows
The API is stateless: it remembers nothing between calls. The messages list is the agent's memory. Every iteration appends two entries: Claude's turn (which may contain text and tool requests) and a user turn carrying the tool results. Here is what the list looks like after a short support case:
[0] user "Where is order #12345? My email is ana@example.com"
[1] assistant text "Let me find your account first."
tool_use id=toolu_01 get_customer {"email": "ana@example.com"}
[2] user tool_result toolu_01 {"customer_id": "C-88213", "status": "active"}
[3] assistant tool_use id=toolu_02 lookup_order {"order_id": "12345"}
[4] user tool_result toolu_02 {"status": "shipped", "shipped_at": "2026-10-02"}
[5] assistant text "Your order shipped on 2 October and should arrive..."
stop_reason = "end_turn"
Three things to notice. First, entry [1] contains both text and a tool request. That is normal, and it is why "the response contains text" is not a sign that Claude is done. Second, tool results travel in a user turn: from Claude's point of view, your program is the other side of the conversation. Third, the list only grows. Long tasks make it large, which is why Domain 5 talks about trimming tool output.
tool_result in [2] must carry the same id as the tool_use it answers, and the list only ever grows.The fields that control the loop
stop_reasonWhy Claude stopped generating.tool_usemeans "run the tools I asked for and call me again".end_turnmeans "I have finished".max_tokensmeans the reply was cut off, which is not the same as finished.tool_useblock A request to run a tool. It carries anid(unique per request), the toolname, and theinputarguments that match the schema.tool_resultblock Your answer.tool_use_idmust equal the request'sidso Claude knows which result belongs to which request. Everytool_useneeds a matching result, or the next API call fails.is_errorTells Claude the tool failed, so it can recover (retry, try another route, explain) instead of treating an error message as data.
Every stop_reason value, and what your loop should do
Most of the time you will see only tool_use and end_turn. A production loop still has to handle the other values, because each one means something different and treating them all as "done" silently loses work.
def next_step(resp, messages):
reason = resp.stop_reason
if reason == "end_turn":
return "done" # Claude finished its turn normally
if reason == "tool_use":
run_tools_and_append(resp, messages)
return "continue" # call the API again with the results
if reason == "max_tokens":
# The reply was cut off mid-way. It is NOT finished.
messages.append({"role": "assistant", "content": resp.content})
messages.append({"role": "user", "content": "Continue exactly where you stopped."})
return "continue" # or retry with a larger max_tokens
if reason == "stop_sequence":
return "done" # hit one of YOUR stop_sequences; you chose this
if reason == "pause_turn":
# A long-running server tool (e.g. web search run by Anthropic) paused the turn.
messages.append({"role": "assistant", "content": resp.content})
return "continue" # send it back unchanged so it can resume
if reason == "refusal":
return "refused" # surface to a human; do not loop retrying
raise ValueError(f"unexpected stop_reason: {reason}")
end_turnThe normal finish. The last text block is the answer.tool_useClaude wants one or more tools. Run everytool_useblock in the response, send all results back in one user message, and call again.max_tokensThe output hit themax_tokenslimit you set. The answer is incomplete. Either raise the limit or ask Claude to continue. Treating this as success is a classic bug: the user gets half an answer.stop_sequenceGeneration stopped because it produced a string you listed instop_sequences. You only see this if you configured stop sequences, so your code already knows what it means for your design.pause_turnSome tools run on Anthropic's side (server tools such as web search). If such a turn runs long, the API pauses it. Send the response back as the next assistant turn, unchanged, and the model picks up where it left off.refusalThe model declined for safety reasons. Retrying the same request in a loop will not help; report it or route it to a person.
Model-driven versus pre-configured
In this loop, Claude chooses which tool to call next, based on what it has learned so far. If the customer gives an order number but no email, Claude may decide to ask for the email. That flexibility is what makes it an agent. The alternative is a pre-configured sequence: your code always calls get_customer, then lookup_order, then sends one final prompt. That is a workflow. It is cheaper and more predictable, and it is the right choice when the path never changes. Choose the agent when the next step depends on what was discovered.
How this shows up on the exam
Questions describe a loop that ends too early or runs forever and ask for the cause. The answer is almost always that the loop decides from the wrong signal: it checks for text, looks for a phrase like "task complete", or relies on an iteration cap as the main stop condition. The correct design branches on stop_reason, runs every tool_use block in a response, appends the results to history, and keeps a cap only as a safety net.
An agentic loop is plain control flow around the Messages API. You send the conversation plus tool definitions. Claude either asks for tools or finishes. Your code decides what to do by reading stop_reason, never by reading Claude's prose.
stop_reason. tool_use sends you down the left side: run the tools, append the results, call again. end_turn exits on the right. Any other value (max_tokens, pause_turn, refusal) needs its own handling, never a silent exit.messages = [{"role": "user", "content": task}]
while True:
resp = client.messages.create(model=MODEL, max_tokens=4096,
system=SYSTEM, tools=TOOLS, messages=messages)
messages.append({"role": "assistant", "content": resp.content}) # keep the full turn
if resp.stop_reason == "end_turn":
break # the model decided it is finished
if resp.stop_reason == "tool_use":
results = []
for block in resp.content:
if block.type == "tool_use":
out = run_tool(block.name, block.input)
results.append({"type": "tool_result", "tool_use_id": block.id,
"content": out.text, "is_error": out.failed})
messages.append({"role": "user", "content": results}) # results go back as a user turn
continue
handle_other(resp) # e.g. max_tokens = output truncated; decide to continue or fail
| stop_reason | Meaning | Loop should |
|---|---|---|
end_turn | Model finished its turn | Return the answer |
tool_use | Model wants one or more tools | Run every tool_use block, append the results, call again |
max_tokens | Output hit your max_tokens | Treat as truncated, not done: raise the limit or continue |
stop_sequence | Hit one of your custom stop sequences | Handle per your design |
pause_turn | A long server-tool turn was paused | Send the response back unchanged so it can continue |
refusal | Model declined for safety reasons | Surface it; do not retry blindly |
Key ideas
- Tool results are appended to history. That is how the model "sees" what happened and reasons about the next action. Each
tool_resultmust reference the matchingtool_use_id. - Model-driven vs pre-configured. In an agent, Claude decides which tool to call next from context. A hard-coded decision tree or fixed tool sequence is a workflow, not an agent. Use the agent when the path depends on what is discovered; use fixed code when the path is known.
- A single response can contain text and several
tool_useblocks. Execute all of them before the next call.
- Stopping when the text says "I'm done" or "Task complete" (parsing natural language for termination).
- Using an iteration cap as the primary stop condition. A cap is fine as a safety net, not as the design.
- Treating "the response contains text" as completion. Claude often writes text alongside a tool call.
Your support agent sometimes ends the conversation mid-investigation. The loop exits whenever resp.content[0].type == "text". Claude had written "Let me check your order" and then requested lookup_order. Fix: branch on stop_reason only.
RememberBranch on stop_reason. tool_use → run tools, append results, loop. end_turn → done. Never parse prose to decide.