The Agent Loop
You already know how to call a model and read its response. An agent adds one thing: the model can ask for a tool, and your code runs it and reports back. Everything else in agentic systems is a detail hung on that cycle, so this lesson builds the cycle by hand before any framework enters the picture.
The cycle
Every tool-using agent runs the same loop. Your application sends the conversation and the tool definitions to the model. The model answers in one of two ways. It either requests a tool, which sets stop_reason to tool_use, or it finishes, which sets stop_reason to end_turn (stop reasons documentation). On tool_use, your code runs the requested tool, appends the result as a tool_result message, and calls the model again.
messages = [user_request]
steps = 0
while True:
response = model.create(
model="claude-sonnet-5-5",
messages=messages,
tools=tool_definitions,
)
messages.append(response.content)
if response.stop_reason == "end_turn":
return response.text # the model decided it is done
if response.stop_reason == "tool_use":
steps += 1
if steps > MAX_STEPS: # your guardrail, not the model's
return "Stopped: step limit reached"
results = [run_tool(block) for block in response.tool_use_blocks]
messages.append(tool_results(results))
Who owns what
The model chooses which tool to request and when to stop. It does not run the tool, count the steps, or enforce a budget. Those belong to your code.
| Responsibility | Owner |
|---|---|
| Choose the next tool and its arguments | Model |
| Execute the tool and handle its errors | Your code |
| Decide the run is complete | Model signals it, your code acts on it |
| Cap steps, cost, and time | Your code |
| Approve risky actions | Your code, or a human through it |
Practice
- Using the pseudocode above, add a
MAX_STEPSguardrail set to 10. Confirm that a model stuck in a loop stops at the limit and returns a clear message. - Log each tool name and its input in the order the model requested them. Compare the log with the transcript to confirm the order matches.
- Make one tool throw an exception. Decide whether the error goes back to the model as a
tool_resultmarked as an error, or stops the run. Write down which you chose and why.
Retrieval check
In a standard tool-use loop, which party executes the tool?
Correct. The model requests a tool and your code executes it, then returns the result as a tool_result.
Not quite. The model only requests the tool. Your application runs it and sends the output back in the next message.
What stop reason tells your loop that the model has nothing left to request?
Correct. end_turn means the model finished its answer. Your loop should return it.
Not quite. Only the model's end_turn signal means it is done. A step counter is your guardrail, and a tool_result is an input to the next call.