By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
A checkout assistant retried a failed payment tool on its own. The retry succeeded, and the customer was charged twice. The user saw one clean confirmation, because the second charge happened inside a loop that nobody had bounded or logged.
The loop was four lines long: call the model, run the tools, append the results, call the model again. It had no step budget, no duplicate-call check and no stop condition beyond hoping the model would finish. Every gap is a loop bug, and the exam tests all three.
An agent loop is small. Call the model, read stop_reason, execute every tool_use block, append the assistant message, append one user message of tool_result blocks keyed by the tool_use ids, and repeat.
stop_reason is the field that says why generation ended. tool_use means the model is waiting on your code. end_turn means it has finished. A tool_result is your reply to one call, matched by the id on the tool_use block.
| stop_reason | What it means | What your loop does |
|---|---|---|
tool_use | The model wants one or more tools run before it continues | Execute every block, return every result, loop |
end_turn | The model has finished its answer | Stop, then validate and return the content |
max_tokens | Generation hit the output limit and was cut off | Do not act on the content; retry with more room |
refusal | The model declined the request | Hand off to a person or a fallback, and log it |
Read the reason first, because it decides the next move. Content only means something once you know the reason. A friendly sentence next to two tool calls is a status line, not the answer.
Two mistakes cause most loop bugs. The first is acting on the text while tool_use blocks are pending. The second is appending only the blocks you understood, which breaks the pairing the next request depends on.
The pairing is strict. Every tool_use block needs exactly one tool_result with the same id, inside the next user message. A missing result is rejected. A result with an unknown id is rejected too. One message with all results is the shape the API expects, not one message per result.
The Claude Agent SDK runs this loop for you. You call its query entry point with a prompt and options, and you receive a stream of messages until the run finishes. The options cover the system prompt, the allowed tools, the permission mode, a turn limit and which settings to load.
That removes the bookkeeping, not the decisions. You still choose the stop conditions, the tool allow-list, the approval policy and the failure path. A run that ends because it hit the turn limit is a failure, and your code must say so.
The snippet below runs a scripted stand-in for the model. There is no key and no network. The trace shows the invariant the loop protects: every tool_use id gets one result, and the loop ends only on end_turn.
SCRIPT = [
{
"stop_reason": "tool_use",
"content": [
{"type": "tool_use", "id": "tu_1", "name": "get_order",
"input": {"order_id": "A17"}},
{"type": "tool_use", "id": "tu_2", "name": "get_customer",
"input": {"customer_id": "C-88"}},
],
},
{
"stop_reason": "tool_use",
"content": [
{"type": "tool_use", "id": "tu_3", "name": "issue_refund",
"input": {"order_id": "A17", "amount": 42}},
],
},
{
"stop_reason": "end_turn",
"content": [{"type": "text", "text": "Refund R-9001 issued."}],
},
]
TOOLS = {
"get_order": lambda args: {"status": "delivered", "total": 42},
"get_customer": lambda args: {"tier": "gold"},
"issue_refund": lambda args: {"refund_id": "R-9001"},
}
def run_tools(reply):
"""Execute every tool_use block. A failure is a result, not a skip."""
results = []
for block in reply["content"]:
if block["type"] != "tool_use":
continue
tool = TOOLS.get(block["name"])
if tool is None:
results.append({
"type": "tool_result",
"tool_use_id": block["id"],
"is_error": True,
"content": "unknown tool",
})
continue
results.append({
"type": "tool_result",
"tool_use_id": block["id"],
"content": tool(block["input"]),
})
return results
def agent_loop(script, max_steps=6):
"""One turn: read the reason, append, execute, append results, repeat."""
messages, trace = [], []
for step in range(1, max_steps + 1):
reply = script[step - 1]
messages.append({"role": "assistant", "content": reply["content"]})
trace.append(f"step {step}: stop_reason={reply['stop_reason']}")
if reply["stop_reason"] == "end_turn":
return trace, messages
if reply["stop_reason"] in ("max_tokens", "refusal"):
trace.append("escalate to a person")
return trace, messages
results = run_tools(reply)
trace.append("results: " + ", ".join(r["tool_use_id"] for r in results))
messages.append({"role": "user", "content": results})
trace.append("step budget exhausted")
return trace, messages
trace, messages = agent_loop(SCRIPT)
print("\n".join(trace))
print("messages in transcript:", len(messages))Two stop reasons need a branch of their own. max_tokens means generation was cut off by the output limit. refusal means the model declined. Neither is a finished answer, and neither should reach your user as one.
On max_tokens, do not act on the content. A tool_use block can arrive truncated, so its input may parse and still be wrong. Raise the output budget, narrow the request, or ask for a shorter answer. On refusal, hand off to a person and log the trigger.
Predict the trace before you run anything.
refusal branch to the snippet that returns a handoff record instead of a trace, and decide who receives it.SCRIPT so the first reply carries one block and the second carries two. Write the trace you expect, then check it.tool_use id received exactly one result and that no result is orphaned. Keep it as a unit test.Key takeaways
stop_reason chooses the next move: loop on tool_use, stop on end_turn, escalate on max_tokens and refusal.
Execute every tool_use block and return one tool_result per id in a single user message.
Append the assistant message unchanged before you send the results.
A failed tool is a result with is_error, not an omission.
The Agent SDK runs the loop; the stop conditions, allow-list and failure path stay yours.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.