Part 18 / Topic 2 of 6
The agent loop
An agent is a loop: the model acts, sees the result, acts again — until it answers or hits a limit.
# examples/01_a_tool_using_agent_loop_with.py (ran against the local mock)
messages = [{"role": "user", "content": "Where is my order A1001?"}]
for step in range(5): # hard limit on agent steps
response = client.messages.create(model="claude-opus-5-5", max_tokens=16000,
tools=tools, messages=messages)
if response.stop_reason != "tool_use":
break
messages.append({"role": "assistant", "content": response.content})
results = []
for block in response.content:
if block.type == "tool_use":
results.append({"type": "tool_result", "tool_use_id": block.id,
"content": get_order_status(**block.input)})
messages.append({"role": "user", "content": results}) # all results in one message
# step 0: model called get_order_status({'order_id': 'placeholder'})
# final: [mock reply]
The anatomy: stop_reason == "tool_use" signals a request; the assistant's full blocks go into history; each result is a tool_result tied to its tool_use_id; and the step limit is non-negotiable — a loop with no budget is an incident waiting to happen. (This run used the local mock, hence the placeholder argument.)
🧪 Quick quiz
- How do you know the model wants a tool run, and why cap the steps?
Show the answer
stop_reason == "tool_use" with tool_use blocks in the content (verified against the SDK). The cap stops runaway loops that burn tokens and time — production agents also carry budgets, timeouts and logs.
Done here? The practice set for Part 18 — 4 exercises with solutions — is on the part page.