AI Agents · How-to
How to Build Your First AI Agent Loop
The four-step loop — perceive, reason, act, observe — in real Python. This is the engine behind every agent.
You'll need: Basic Python and an Anthropic API key.
Steps
- Set up a Python project and install the Anthropic SDK.
- Define your tools (name, description, input schema) and a dispatcher that runs them.
- Write the loop: send the task + system prompt + tools, get a response.
- If stop_reason is tool_use, run the requested tools and append results as a tool_result message, then loop.
- If stop_reason is end_turn, return the final answer.
- Always set a max iteration limit so a stuck agent can't spin forever.
Watch outAppend the model's response verbatim — it carries the tool_use blocks the next call needs. Extract only the text and the loop breaks subtly.
Go deeper: Deploy Your First AI Agent
The AI guide has the complete runnable loop, tool schemas, memory, and deployment paths.
Get the guide