Back to blog
Tutorial2026-05-29

Build Your First AI Agent in Python (Step-by-Step)

Build Your First AI Agent in Python

In this tutorial, you'll build a working AI agent from scratch using Python and the Anthropic Claude API. By the end, you'll have an agent that can reason about tasks and use tools to accomplish goals.

Prerequisites

  • Python 3.10+ installed
  • Basic Python knowledge (variables, functions, loops)
  • An Anthropic API key (free tier available at console.anthropic.com)

Step 1: Install Dependencies

pip install anthropic

Step 2: Create Your Agent

import anthropic

client = anthropic.Anthropic(api_key="your-key-here")

def simple_agent(task: str) -> str:
    response = client.messages.create(
        model="claude-sonnet-4-20250514",
        max_tokens=2048,
        system="You are a helpful assistant. Think step by step.",
        messages=[{"role": "user", "content": task}]
    )
    return response.content[0].text

# Test it
result = simple_agent("What are the 3 most important things to know about RAG?")
print(result)

Step 3: Add Tool Use

A real agent needs tools. Let's add a calculator tool:

import json

tools = [{
    "name": "calculate",
    "description": "Perform mathematical calculations",
    "input_schema": {
        "type": "object",
        "properties": {
            "expression": {"type": "string", "description": "Math expression to evaluate"}
        },
        "required": ["expression"]
    }
}]

def execute_tool(name, inputs):
    if name == "calculate":
        return {"result": eval(inputs["expression"])}

def agent_with_tools(task: str) -> str:
    messages = [{"role": "user", "content": task}]
    
    while True:
        response = client.messages.create(
            model="claude-sonnet-4-20250514",
            max_tokens=2048,
            tools=tools,
            messages=messages
        )
        
        if response.stop_reason == "tool_use":
            tool_block = next(b for b in response.content if b.type == "tool_use")
            result = execute_tool(tool_block.name, tool_block.input)
            
            messages.append({"role": "assistant", "content": response.content})
            messages.append({"role": "user", "content": [{
                "type": "tool_result",
                "tool_use_id": tool_block.id,
                "content": json.dumps(result)
            }]})
        else:
            return response.content[0].text

Step 4: Test Your Agent

print(agent_with_tools("What is 1547 * 382 + 99?"))
# The agent will use the calculator tool and return the correct answer

Next Steps

You've built a working agent! To go further, add more tools (web search, file operations, database queries), implement memory (conversation history), and add error handling. Our full course covers all of this in depth across 30+ lessons.

Ready to go deeper?

This topic is covered in detail in our structured course. 30+ lessons, quizzes, and projects.

Start the Course Free →