How-to guide

How to Build an AI Agent from Scratch in Python

To build an AI agent, write a loop that sends the conversation to a language model, runs the tool the model asks for, appends the result, and repeats until the model answers or a turn limit is reached. Then add, in order: well-described tools, a real model, memory, safety checks, evaluation and a harness.

Last updated · By Rohit Ghumare

Each step below names the free lesson that teaches it. This guide is written by the maintainers of AI Engineering from Scratch, and the lessons it links are ours. Times are the estimates stated on each lesson; this guide adds none of its own.

The whole agent in one file

This runs offline with the Python standard library. The model is a scripted stand-in so you can see the loop work before spending anything on an API.

python
import ast
import json
import operator

NOTES = {"q3-revenue": "Q3 revenue was 1200 thousand dollars.", "q2-revenue": "Q2 revenue was 1000 thousand dollars."}
OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv}


def read_note(name):
    return NOTES[name]


def evaluate(node):
    if isinstance(node, ast.Constant) and type(node.value) in (int, float):
        value = node.value
    elif isinstance(node, ast.BinOp) and type(node.op) in OPS:
        value = OPS[type(node.op)](evaluate(node.left), evaluate(node.right))
    elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub):
        value = -evaluate(node.operand)
    else:
        raise ValueError("only numbers, + - * / and parentheses are allowed")
    if abs(value) > 1e12:
        raise ValueError("number is too large")
    return value


def calculator(expression):
    if len(expression) > 100:
        raise ValueError("expression is too long")
    return str(round(evaluate(ast.parse(expression, mode="eval").body), 2))


TOOLS = {
    "read_note": {"run": read_note, "description": "Read a note by name", "parameters": {"name": "string"}},
    "calculator": {"run": calculator, "description": "Evaluate arithmetic", "parameters": {"expression": "string"}},
}


def scripted_model(messages):
    step = sum(1 for message in messages if message["role"] == "tool")
    plan = [
        {"tool": "read_note", "arguments": {"name": "q3-revenue"}},
        {"tool": "read_note", "arguments": {"name": "q2"}},
        {"tool": "read_note", "arguments": {"name": "q2-revenue"}},
        {"tool": "calculator", "arguments": {"expression": "(1200 - 1000) / 1000 * 100"}},
    ]
    if step < len(plan):
        return plan[step]
    return {"final": f"Revenue grew {messages[-1]['content']}% from Q2 to Q3."}


def run_agent(goal, model, max_turns=8):
    messages = [{"role": "user", "content": goal}]
    for turn in range(max_turns):
        reply = model(messages)
        if "final" in reply:
            return reply["final"], messages
        messages.append({"role": "assistant", "content": json.dumps(reply)})
        try:
            result = TOOLS[reply["tool"]]["run"](**reply["arguments"])
        except Exception as error:
            result = f"error: {type(error).__name__}: {error}"
        messages.append({"role": "tool", "content": result})
    return "stopped: turn budget used up", messages


answer, trace = run_agent("How much did revenue grow from Q2 to Q3?", scripted_model)
for message in trace:
    print(f"{message['role']:>9}: {message['content']}")
print(f"    final: {answer}")
output
     user: How much did revenue grow from Q2 to Q3?
assistant: {"tool": "read_note", "arguments": {"name": "q3-revenue"}}
     tool: Q3 revenue was 1200 thousand dollars.
assistant: {"tool": "read_note", "arguments": {"name": "q2"}}
     tool: error: KeyError: 'q2'
assistant: {"tool": "read_note", "arguments": {"name": "q2-revenue"}}
     tool: Q2 revenue was 1000 thousand dollars.
assistant: {"tool": "calculator", "arguments": {"expression": "(1200 - 1000) / 1000 * 100"}}
     tool: 20.0
    final: Revenue grew 20.0% from Q2 to Q3.

Notice the fifth line of the trace. The second tool call failed, and the failure went back to the model as an observation instead of crashing the program. That one try block is what lets an agent recover.

The calculator parses the arithmetic itself and never calls eval: it accepts numbers, + - * / and parentheses, rejects **, caps the expression at 100 characters and stops when a number passes 1e12.

To make it a real agent, replace scripted_model with a function that sends messages and the tool descriptions to a model API and returns the tool call it chooses. run_agent does not change.

The steps

  1. Check that you need an agent. If you can list the steps in advance, write a workflow: a fixed chain of model calls. Use an agent only when the next step depends on what the last one returned. Lesson: Anthropic's Workflow Patterns: Simple Over Complex (~60 minutes).
  1. Write the loop. Five parts: a message list that grows, a tool registry, a stop condition, a turn budget and a formatter that turns every tool result, including errors, into text the model can read. Lesson: The Agent Loop: Observe, Think, Act (~60 minutes).
  1. Design the tools. Give each tool a clear name, a description that says when to use it, and typed parameters. Split tools into read-only ones, which are safe to call freely, and consequential ones that change state, spend money or touch user data, which need a gate. Lessons: The Tool Interface (~45 minutes), Tool Schema Design (~45 minutes) and Tool Use and Function Calling (~60 minutes).
  1. Connect a real model. Providers share the same loop but differ in field names and in how tool calls and results are matched. Learn the differences once so your agent is not tied to one provider. Lesson: Function Calling Deep Dive: OpenAI, Anthropic, Gemini (~75 minutes).
  1. Add memory. The context window is finite and a long run is not. Keep the working context small and page older material in and out of an external store. Lesson: Agent Memory: Virtual Context and Memory Paging (~75 minutes).
  1. Plan for failure and attack. Agents invent actions, drift from the goal, cascade one error into many and misuse tools. Text the agent retrieves can also carry instructions planted by someone else; treat all retrieved content as untrusted. Lessons: Failure Modes: Why Agents Break (~60 minutes) and Prompt Injection and the PVE Defense (~75 minutes).
  1. Evaluate and trace. Write a small set of tasks with known good outcomes before you tune anything, and re-run it after every change. Record each model call and tool call as a trace so you can find the step where a run went wrong. Lessons: Eval-Driven Agent Development (~60 minutes) and OpenTelemetry GenAI Semantic Conventions (~60 minutes).
  1. Add a verification gate. The agent does not decide that it is finished. A separate check, such as tests passing or a rule report coming back clean, decides. Lesson: Verification Gates (~55 minutes).
  1. Wrap it in a harness. Turn the loop into a state machine with named states, hooks before and after each tool call, and budgets for turns, tool calls and wall-clock time. After this, changing the model or a policy is a registration call, not a rewrite. Lesson: Agent Harness Loop Contract (~90 minutes).
  1. Run it on a real task. Put the harness, a sandbox, the gates, the eval set and the traces together and have the agent fix a small bug in a multi-file project. Lesson: End-to-End Coding Agent on the Harness (~90 minutes).

The fourteen lessons above state 910 minutes in total, about 15 hours. Steps 1 to 4 give you a working agent; steps 5 to 10 make it one you can trust.

Common mistakes

  • Starting with a framework. You will not know which problems are yours and which are the framework's. Write the loop first.
  • No turn budget. A loop without a cap runs, and bills, until someone notices.
  • Crashing on tool errors. Return the error to the model as an observation. It can often fix its own call.
  • Vague tool descriptions. The model picks tools by reading their names and descriptions. Ambiguity there shows up as wrong calls.
  • Too many tools. Every description takes context and adds a way to choose wrongly. Start with the few the task needs.
  • Obeying retrieved text. A web page or file is data. Only the user's instructions are instructions.
  • Judging by one good demo. Run the eval set. A single success says little about a system whose errors compound over steps.
  • Letting the agent grade itself. "Done" should come from a check outside the model.

Frequently asked questions

What is an AI agent, in one sentence?

An AI agent is a program that runs a language model in a loop: the model chooses a tool to call, the program runs it and returns the result, and this repeats until the model gives a final answer or a budget runs out. Everything else is scaffolding around that loop.

Do I need a framework to build an AI agent?

No. The core loop is about a dozen lines of Python with no dependencies, as the code on this page shows. Frameworks add things around the loop, such as checkpointing, tracing and role templates. Build the loop by hand once so you know what a framework is doing for you.

Which language should I use to build an AI agent?

Python is the common choice and the one this guide uses, because model SDKs and examples are plentiful. TypeScript works equally well and several of the linked lessons ship both. The loop itself is language-neutral: a list of messages, a table of tools and a for loop with a cap.

How long does it take to build an AI agent?

The minimal agent on this page takes minutes to run and modify. The fourteen lessons named in the ten steps state about 15 hours of study time in total, 910 minutes by their own estimates. A production agent takes longer, mostly in evaluation, safety and operations, not in the loop.

What is the hardest part of building an agent?

Reliability across many steps. Errors compound: a model that is right 99% of the time on each step, independently of the others, finishes a 70-step task correctly only about half the time. The work is in tool design, treating tool output as untrusted, measuring whole runs, and refusing to let the agent mark its own work done.

Where to go next

Learn it by building

These free lessons teach each step from scratch:

More how-to guides

All how-to guides · All comparisons · Course catalog