New

🤖 AI Agent Tutorial in Python: Build Your First Agent

A hands-on beginner project: a study-helper agent that decides when to use tools, reads the results and stops safely, in about 130 lines of Python.

Beginner ⏱️ ~45 minutes 🧰 Python 3.10+, Anthropic Python SDK
← AI Agents Track

What You'll Build in This AI Agent Tutorial

This AI agent tutorial in Python builds a study helper from scratch, without an agent framework. You ask it a question such as "Using my notes on Ohm's law, what is the voltage at 0.5 A and 220 ohms?". The model decides it should look up your notes, then decides to use a calculator, reads both results and writes the answer. That decide → act → observe → repeat loop is what makes it an agent rather than a chatbot. You will also add the guardrails every real agent needs: a fixed list of allowed tools, a step limit and safe error handling.

Prerequisites

  • Basic Python: functions, dictionaries, lists and for loops.
  • Python 3.10 or newer and a terminal.
  • An Anthropic API key from the Claude Console. API calls are billed per token; this project uses the cheapest current model and a handful of short requests.
  • Helpful: read AI agents for beginners and the first lessons of the AI Agents & Automation track.

Step by Step

1 Set up the project

Create a folder, a virtual environment and install the official SDK. The SDK reads your key from the ANTHROPIC_API_KEY environment variable, so the key never appears in your code (and never ends up on GitHub by accident).

mkdir study-agent && cd study-agent
python3 -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install anthropic
export ANTHROPIC_API_KEY="your-key-here"   # Windows (PowerShell): $env:ANTHROPIC_API_KEY="your-key-here"

Everything below goes into a single file called agent.py, in the order shown.

2 Write the tools as plain Python functions

A tool is just a function your code runs when the model asks for it. We need two: a calculator and a notes lookup. Notice the calculator does not use eval(). The input comes from a model, and a model can be tricked by text it reads, so the function walks Python's syntax tree and only allows numbers and + - * /. Anything else raises an error.

# agent.py - a tiny study-helper AI agent
import ast
import json
import operator

import anthropic

MODEL = "claude-haiku-5-5"  # check the models page for current IDs
MAX_STEPS = 5               # hard stop so the agent can never loop forever

SYSTEM = (
    "You are a study helper. Use the tools for maths and for facts from the "
    "student's notes. If the notes do not cover something, say you do not know."
)

# --- Tool 1: a safe calculator (no eval!) ---------------------------------
_OPS = {
    ast.Add: operator.add,
    ast.Sub: operator.sub,
    ast.Mult: operator.mul,
    ast.Div: operator.truediv,
    ast.USub: operator.neg,
}

def calculate(expression: str) -> str:
    """Evaluate + - * / on plain numbers by walking the syntax tree."""
    def walk(node):
        if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
            return node.value
        if isinstance(node, ast.BinOp) and type(node.op) in _OPS:
            return _OPS[type(node.op)](walk(node.left), walk(node.right))
        if isinstance(node, ast.UnaryOp) and type(node.op) in _OPS:
            return _OPS[type(node.op)](walk(node.operand))
        raise ValueError("only numbers and + - * / are allowed")
    return str(walk(ast.parse(expression, mode="eval").body))

# --- Tool 2: look up the student's notes (read-only) ----------------------
NOTES = {
    "ohms law": "V = I x R. Voltage equals current times resistance.",
    "photosynthesis": "Plants use light, water and CO2 to make glucose and oxygen.",
}

def lookup_note(topic: str) -> str:
    return NOTES.get(topic.lower().strip(), "No note found for that topic.")

3 Describe the tools to the model

The model cannot see your Python code. It only sees a name, a description and an input_schema (a JSON Schema for the arguments) for each tool. Good descriptions matter: they are how the model decides when a tool is useful. The TOOL_FUNCS dictionary is your allowlist, the only functions that can ever run.

TOOLS = [
    {
        "name": "calculate",
        "description": "Evaluate an arithmetic expression with + - * / only, "
                       "e.g. '0.5 * 220'. Use it for every calculation.",
        "input_schema": {
            "type": "object",
            "properties": {
                "expression": {"type": "string", "description": "The expression"}
            },
            "required": ["expression"],
        },
    },
    {
        "name": "lookup_note",
        "description": "Look up the student's own notes on a topic, "
                       "e.g. 'ohms law'. Returns the note text.",
        "input_schema": {
            "type": "object",
            "properties": {
                "topic": {"type": "string", "description": "Topic name"}
            },
            "required": ["topic"],
        },
    },
]

# The allowlist: the ONLY Python functions the model can trigger.
TOOL_FUNCS = {"calculate": calculate, "lookup_note": lookup_note}

4 Write the agent loop

This is the heart of every AI agent. Each turn, we send the conversation and the tool list to the model. If the response's stop_reason is "tool_use", the model wants tools run: each request is a tool_use block with an id, a name and an input dictionary. We run the tool, send the output back in a tool_result block that carries the same tool_use_id, and loop. When the model stops asking for tools, its text is the final answer.

def run_tool(name: str, args: dict) -> tuple[str, bool]:
    """Run one allowlisted tool. Returns (output, is_error)."""
    func = TOOL_FUNCS.get(name)
    if func is None:
        return f"Unknown tool: {name}", True
    try:
        return func(**args), False
    except Exception as exc:  # report the problem to the model, don't crash
        return f"Tool error: {exc}", True


def run_agent(question: str, client=None) -> str:
    client = client or anthropic.Anthropic()  # reads ANTHROPIC_API_KEY
    messages = [{"role": "user", "content": question}]

    for step in range(1, MAX_STEPS + 1):
        response = client.messages.create(
            model=MODEL,
            max_tokens=1024,
            system=SYSTEM,
            tools=TOOLS,
            messages=messages,
        )

        # 1. No tool requested? Then this is the final answer.
        if response.stop_reason != "tool_use":
            return "".join(b.text for b in response.content if b.type == "text")

        # 2. Keep the model's turn (including its tool_use blocks) in history.
        messages.append({"role": "assistant", "content": response.content})

        # 3. Run every requested tool and collect the results.
        results = []
        for block in response.content:
            if block.type != "tool_use":
                continue
            output, is_error = run_tool(block.name, block.input)
            print(f"[step {step}] {block.name}({json.dumps(block.input)}) -> {output}")
            results.append({
                "type": "tool_result",
                "tool_use_id": block.id,
                "content": output,
                "is_error": is_error,
            })

        # 4. Send the observations back and loop.
        messages.append({"role": "user", "content": results})

    return "Stopped: hit the step limit without a final answer."


if __name__ == "__main__":
    print(run_agent("Using my notes on Ohm's law, what is the voltage "
                    "if the current is 0.5 A and the resistance is 220 ohms?"))

Two details beginners often miss. First, you must append the model's whole response (response.content) to messages before the tool results, otherwise the API cannot match each tool_result to its tool_use. Second, tool failures are sent back with "is_error": True instead of crashing your program, so the model can read the error and try something else.

5 Run it and read the trace

Run python agent.py. The exact wording changes from run to run, but you should see the agent pick tools on its own before answering, something like:

[step 1] lookup_note({"topic": "ohms law"}) -> V = I x R. Voltage equals current times resistance.
[step 2] calculate({"expression": "0.5 * 220"}) -> 110.0
Using V = I x R: 0.5 A x 220 ohms = 110 volts.

Now try questions that test the design: ask about a topic that is not in NOTES (it should say it does not know rather than invent a note), or ask it to divide by zero (the calculator error comes back as a tool error and the model explains it). The printed trace is your best debugging tool: it shows exactly what the agent decided and why the answer came out the way it did.

6 Understand the guardrails you just built

Real-world attackers now use AI agents too. The FBI's November 2026 alert on the ARTEX AI hacking tool describes agents that scan and exploit systems at machine speed. The same autonomy that makes your agent useful makes a careless one dangerous, so this tutorial bakes in four habits:

  • Allowlist, not free rein. The model can only trigger functions in TOOL_FUNCS. An invented tool name gets "Unknown tool", never a crash or a surprise.
  • A hard step limit. MAX_STEPS stops a confused agent from looping (and spending money) forever.
  • Read-only, narrow tools. Neither tool can change files, send messages or touch the network. If you later add a tool that does something, such as sending an email, ask a human to approve each call first.
  • No secrets in code. The API key lives in an environment variable. Keep it out of Git and rotate it if it ever leaks.

Treat any text the agent reads (web pages, files, emails) as untrusted: it can contain instructions aimed at your model. Our prompt injection guide explains why.

Practice Task

Extend the agent on your own, then check yourself with the quiz below.

  1. Add a third tool, unit_convert(value, from_unit, to_unit), that only supports a few units you choose (for example mA to A and kΩ to Ω). Write its input_schema and add it to TOOL_FUNCS.
  2. Load NOTES from a notes.json file instead of a dictionary in the code, and make lookup_note handle "Ohm's law" with an apostrophe.
  3. Add a save_note(topic, text) tool that writes to the notes file, but only after the user types y at an input() prompt. This is a human-in-the-loop approval step.
  4. Set MAX_STEPS = 1 and ask a two-step question. What happens, and why is a clear "stopped" message better than a guess?

AI Agent Tutorial Quiz

Five quick questions on this tutorial.

Frequently Asked Questions

Do I need a framework like LangChain to build an AI agent?

No. An agent is a loop around a model that can request tools. Building it by hand first, as in this tutorial, makes frameworks much easier to understand later.

Can I build an AI agent in Python for free?

The code and SDK are free, but calls to a hosted model are billed per token. This tutorial uses the cheapest current model and only a few short requests, so testing costs very little.

What is the difference between an AI agent and a chatbot?

A chatbot replies once with text. An agent decides on actions, runs tools, reads the results and repeats until it reaches an answer or a limit.

How do I stop my AI agent from doing something dangerous?

Give it only the tools it needs, keep tools read-only where possible, set a step limit, never use eval on model output, and require human approval for any tool that changes data or sends messages.

Sources

Code checked against the Anthropic Python SDK 2.10 on November 19, 2026. Model IDs change over time, so check the models page if the one in MODEL is retired.

What to Try Next

Keep learning AI agents

Head back to the AI Agents & Automation track for the full learning path and the hands-on project.

Back to the AI Agents Track