Home › Guides › AI Agents
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

  1. Set up a Python project and install the Anthropic SDK.
  2. Define your tools (name, description, input schema) and a dispatcher that runs them.
  3. Write the loop: send the task + system prompt + tools, get a response.
  4. If stop_reason is tool_use, run the requested tools and append results as a tool_result message, then loop.
  5. If stop_reason is end_turn, return the final answer.
  6. 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