Dated and sourced
SVLStack Verdict Lab

Web, AI, DevOps and Cloud Guides

Agentic AITutorial

How to Build Your First AI Agent in Python (Step by Step)

By

Founder and Developer, Stack Verdict Lab

Updated • 9 min read

Key Takeaways

  • ▪An AI agent is a loop: the model asks for a tool, your code runs it, and the result goes back until the model answers.
  • ▪You need no framework. A tool list, one loop and a step limit are enough for a first agent.
  • ▪Your code, not the model, decides what a tool is allowed to touch. Keep paths and permissions narrow.
  • ▪Return tool errors as text so the model can recover instead of crashing the run.
In this guide
  1. What you need before you start
  2. What the agent does
  3. Step 1: define the tools
  4. Step 2: write the tools, with a sandbox
  5. Step 3: write the loop
  6. Why each part is there
  7. How we checked the loop
  8. What to add next
  9. When a plain prompt is better
  10. Frequently asked questions
  11. Sources

To build your first AI agent in Python, write a loop that sends a goal and a list of tools to a language model, runs whichever tool the model asks for, sends the result back, and stops when the model gives a final answer. The version below is about 90 lines, needs no framework, and has a step limit and a file sandbox so it cannot run away or wander through your disk.

What you need before you start

  • Python 3.10 or newer.
  • An Anthropic API key in the ANTHROPIC_API_KEY environment variable. The key is yours and is billed by use, so a run of eight steps costs a small but real amount.
  • The official SDK: pip install anthropic.

The model name is a constant at the top of the file. Swap it for any current model your account can use. The idea works the same with other providers, but the message shapes differ, so the code below is written for Anthropic's API.

What the agent does

It answers questions about a project folder, for example "What does this project do?". It has two tools: one lists files, one reads a file. The model decides which to call and in what order. That choice, repeated until the job is done, is what makes it an agent and not a single prompt. If the difference is new to you, read Agentic AI explained for developers first.

Step 1: define the tools

A tool is a name, a plain-English description and a JSON schema for its inputs. The model never runs code. It only asks for a tool by name with arguments, and your program does the work.

TOOLS = [
    {
        "name": "list_files",
        "description": "List the files in a folder inside the project. Use '.' for the top folder.",
        "input_schema": {
            "type": "object",
            "properties": {"folder": {"type": "string", "description": "Relative folder path"}},
            "required": ["folder"],
        },
    },
    {
        "name": "read_file",
        "description": "Read a text file inside the project and return its first 4000 characters.",
        "input_schema": {
            "type": "object",
            "properties": {"path": {"type": "string", "description": "Relative file path"}},
            "required": ["path"],
        },
    },
]

The description is part of the prompt. A vague description produces wrong tool calls, so say what the tool does and when to use it.

Step 2: write the tools, with a sandbox

These are the two functions that actually run. The important part is safe_path: the model chooses the path, so your code must refuse anything outside the folder you meant to expose.

from pathlib import Path

ROOT = Path(".").resolve()  # the agent may only look inside this folder

def safe_path(relative: str) -> Path:
    """Resolve a path and refuse anything outside ROOT."""
    target = (ROOT / relative).resolve()
    if ROOT != target and ROOT not in target.parents:
        raise ValueError("path is outside the project folder")
    return target

def run_tool(name: str, args: dict) -> str:
    try:
        if name == "list_files":
            folder = safe_path(args["folder"])
            return "\n".join(sorted(p.name for p in folder.iterdir())[:50])
        if name == "read_file":
            return safe_path(args["path"]).read_text(encoding="utf-8")[:4000]
        return f"Unknown tool: {name}"
    except Exception as error:  # tell the model what went wrong so it can adjust
        return f"Error: {error}"

Two details matter. Errors come back as text, so a wrong path becomes information the model can act on instead of a crash. And output is capped (50 names, 4,000 characters) so one big file cannot fill the model's context.

Step 3: write the loop

This is the whole agent. Each pass sends the conversation so far, checks why the model stopped, runs any requested tools and appends the results.

import json
import anthropic

MODEL = "claude-opus-5-5"
MAX_STEPS = 8

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

    for step in range(1, MAX_STEPS + 1):
        response = client.messages.create(
            model=MODEL,
            max_tokens=4000,
            system="You are a careful assistant that answers questions about a code project. "
                   "Use the tools to look at real files before answering.",
            tools=TOOLS,
            messages=messages,
        )

        if response.stop_reason == "refusal":
            return "The model declined this request."
        if response.stop_reason != "tool_use":
            return "".join(b.text for b in response.content if b.type == "text")

        messages.append({"role": "assistant", "content": response.content})
        results = []
        for block in response.content:
            if block.type == "tool_use":
                print(f"step {step}: {block.name}({json.dumps(block.input)})")
                results.append({
                    "type": "tool_result",
                    "tool_use_id": block.id,
                    "content": run_tool(block.name, block.input),
                })
        messages.append({"role": "user", "content": results})

    return "Stopped: reached the step limit before finishing."

Add the entry point, save everything as agent.py, and run it from the folder you want to explore:

import sys

if __name__ == "__main__":
    print(run_agent(" ".join(sys.argv[1:]) or "What does this project do?"))
python agent.py "What does this project do?"

You will see one line per tool call, then the answer.

Why each part is there

PartWhat it prevents
MAX_STEPSAn endless loop and a surprise bill. When the limit is hit, the function says so instead of hanging.
safe_pathThe model reading files outside the project, such as keys or system files.
Errors returned as textA single bad argument ending the run.
Output capsOne large file using up the context window.
refusal checkTreating a declined request as an empty answer.
tool_use_id on every resultA mismatch error: each result must point at the tool call it answers.

How we checked the loop

We replaced the API with a scripted object that returns a list-files call, then two read calls, then a final answer. The loop produced the answer in three steps. One of the read calls asked for ../agent.py, and safe_path returned "path is outside the project folder" to the model as a tool result. A second scripted model that asked for a tool forever stopped after exactly eight steps with the step-limit message. That tests your code. It does not test how well a real model chooses tools, which depends on the model and your descriptions.

What to add next

  1. Logging. Save every message and tool call to a file so you can replay a bad run.
  2. A cost cap. Track response.usage and stop when the total passes a budget.
  3. Approval for risky tools. Before a tool writes a file, sends an email or runs a command, ask a human and return "declined" if they say no.
  4. Tests for tool functions. They are normal functions, so test them like any other code.
  5. A framework, only if you need one. Anthropic's own advice is to start with direct API calls and add structure when the problem needs it.

When a plain prompt is better

If the steps are known in advance, such as "summarize this text" or "extract these three fields", a single call or a fixed sequence is cheaper, faster and easier to test. Use an agent when the number and order of steps depend on what the model finds along the way.

Frequently asked questions

Do I need LangChain or another framework to build an AI agent?

No. The agent above is plain Python with the provider's SDK. A framework can help with tracing, memory and several cooperating agents, but it also adds code you must learn and debug. Build the loop once by hand so you understand what a framework is doing for you.

How is an AI agent different from a chatbot?

A chatbot answers one message at a time. An agent is given a goal and decides its own steps, calling tools and reading the results until it can finish. The loop in this guide is that difference in code.

How do I stop an agent from running forever?

Set a step limit and also a cost or time limit. The MAX_STEPS constant ends the loop after eight rounds. For production, add a token budget read from response.usage.

How do I stop the model from doing something dangerous?

Do not rely on the prompt. Limit what each tool can do in code: a sandboxed path, read-only access, no shell. Require human approval for anything irreversible.

Can I use a different model or provider?

Yes. Change MODEL for another Anthropic model. For another provider, keep the loop and rewrite the request and message handling to that provider's tool-calling format.

Sources

Facts checked on 3 December 2026.

Update history

  • First published.

About the author

Shubham Handore founded Stack Verdict Lab in 2024 and writes its guides on web development, software engineering, AI and agentic AI, DevOps and cloud.

View author profile
AI agentsPythonTool useAgentic AI