The concept
Agent loop: the cycle that turns a chatbot into an agent (Day 36).
- Your code sends the messages plus a list of tools.
- If Claude wants a tool, the reply's stop_reason is "tool_use" and it names the tool and inputs.
- Your code runs that tool and sends back a tool_result.
- Repeat until Claude answers without asking for a tool.
The model never runs anything itself. Your code stays in charge.
Walkthrough: one run on our sample meeting
Input: notes from the bank mobile-app sync (Ana, Raj, Lena, 3 action items).
Turn 1: Claude reads the notes and drafts 3 items. Before answering, it asks for list_open_tasks to check for duplicates.
Turn 2: your code returns the open tasks (today: a fake list).
Turn 3: Claude answers with the JSON from Day 87, ready for a human to approve. Loop ends.
The core, in Python (Anthropic SDK, simplified):
resp = client.messages.create(model=MODEL, system=PROMPT, tools=TOOLS, messages=msgs, max_tokens=2000)
while resp.stop_reason == "tool_use" and turns < 5:
msgs.append({"role": "assistant", "content": resp.content})
msgs.append({"role": "user", "content": run_tools(resp.content)})
resp = client.messages.create(...same arguments...)
turns += 1
run_tools is yours: for each tool_use block, call the matching function and return a tool_result with the same id.
Three habits from day one:
- A turn limit (5 here) so a confused run can't loop forever.
- Log every turn: you'll need it for testing (Day 91) and monitoring (Day 92).
- If a tool fails, send the error back as a tool_result with is_error set to true, so Claude can adjust instead of guessing.
Where you see it at work
- Banking and insurance: the logged loop is your audit trail.
- Product owners: the turn limit and stop rules are product decisions, not just code.
Try it today (10โ15 min)
1. Follow the Claude quickstart: pip install anthropic, set ANTHROPIC_API_KEY (Day 51).
https://platform.claude.com/docs/en/get-started
2. Define one fake tool, list_open_tasks, that returns an empty list.
3. Write the loop above and print stop_reason on every turn.
4. Paste in short sample notes and watch it ask, receive, answer.
The official walkthrough: https://platform.claude.com/docs/en/agents-and-tools/tool-use/build-a-tool-using-agent
In one sentence
The agent loop is plain code: call the model, run the tool it asks for, send back the result, and stop when it's done or hits your limit.
What limit would you set first on an agent at your work? ๐
