The idea
An agent is tool calling inside a while loop. Each iteration: send the conversation to the model; if it asks for tools, run them and append the results; if it returns a final answer, stop. The conversation grows with every step, so the model always sees what it already tried.
The loop needs guards: a maximum number of steps, a token or money budget, a timeout and error handling that feeds tool errors back to the model so it can try something else instead of crashing.
Anthropic’s advice is to start with the simplest thing that works. Many tasks need a fixed workflow (step A, then B, then C) rather than an open loop. Use an agent loop when the number and order of steps cannot be known in advance.
Every agent framework is a version of this loop. Writing it yourself once makes all of them easy to understand and debug.
Picture it
Words to know
- Step / turnOne model call plus any tool executions it requested.
- Workflow vs agentFixed code-defined steps vs model-decided steps.
Try it without code
Be the loop
- Give a chat app a task and tell it: "Ask me for one search at a time, I will paste results."
- Paste search results as it asks.
- You are acting as the tool runner in an agent loop.
Use it in code
A reusable agent loop with a step limit and error feedback.
import anthropic, json
client = anthropic.Anthropic()
def run_agent(task, tools, handlers, max_steps=8, model="claude-sonnet-5-5"):
messages = [{"role": "user", "content": task}]
for step in range(max_steps):
msg = client.messages.create(model=model, max_tokens=1500, tools=tools, messages=messages)
messages.append({"role": "assistant", "content": msg.content})
if msg.stop_reason != "tool_use":
return "".join(b.text for b in msg.content if b.type == "text")
results = []
for b in msg.content:
if b.type != "tool_use":
continue
try:
out = handlers[b.name](**b.input)
results.append({"type": "tool_result", "tool_use_id": b.id, "content": json.dumps(out)[:4000]})
except Exception as e:
results.append({"type": "tool_result", "tool_use_id": b.id, "content": f"Error: {e}", "is_error": True})
messages.append({"role": "user", "content": results})
return "Stopped: step limit reached."Use run_agent with a file-listing tool and a file-reading tool to answer "Which Python file in this folder is the longest and what does it do?"
Common mistakes
- No step limit.
- Crashing on tool errors instead of reporting them back.
- Building an agent for a task a 3-step script would do.