◂ All posts

Blog ·

How to build an AI agent, step by step

To build an AI agent, you write tools as plain functions, describe them to an AI model, and write a loop that runs each tool the model asks for until the job is done. Here is every step in plain Python, from choosing the job to testing it, with programs you can run without an account or an API key.

The short answer

To build an AI agent, you write a program with four parts: a model that picks the next step, instructions that tell it the job, tools (functions your program runs when the model asks for them), and a loop that hands each result back to the model until the job is done. If you'd like to know what an agent is first, What is an AI agent? explains it. This page is about making one.

OpenAI's guide to building agents names the first three as an agent's "three core components", and describes the run as "typically implemented as a loop that lets agents operate until an exit condition is reached". Here are the four parts in the agent this page builds, a help desk for a made-up library:

PartWhat it doesIn the library agent
Modelreads the goal and picks the next stepa stand-in function with fixed rules
Instructionstell the model its job and its limitsthe job card in step 1
Toolsfunctions your program runs when the model askscheck_shelf, check_due, charge_fine
Loophands each result back until the job is donerun_agent, at most four turns

The steps:

  1. Pick one small job, and decide what "done" means.
  2. Write the tools as plain Python functions.
  3. Describe each tool so the model knows what it can ask for.
  4. Read the reply: words, or a request to run a tool.
  5. Run it in a loop, with a limit on turns.
  6. Send errors back instead of crashing.
  7. Ask a person before anything risky.
  8. Test it on goals where you know the answer.
  9. Swap in a real model.

Every program on this page runs exactly as shown in Python 3, with no internet connection, no account and no extra packages. If you have never run Python, install it from python.org, then open IDLE, Python's own editor: choose File > New File, paste a program in, and choose Run > Run Module (or press F5). The one part that isn't real is the model. A short stand-in function with fixed rules plays its part, so every run prints the same thing, and step 9 says what changes when a real model takes over.

Step 1: pick one small job

Before any code, write down what the agent is for. IBM's guide says that at any skill level, building an agent "should begin the same way: by carefully defining your AI agent's purpose and identifying the tools and information needed to achieve that purpose." Keep it small. OpenAI's guide says it is tempting to build a fully autonomous agent with a complex design straight away, but "customers typically achieve greater success with an incremental approach."

The agent on this page works the front desk of a made-up library. Its job card:

  • The job: answer a question about a book: is it on the shelf, and if not, when is it due back. Charge a late fine when asked.
  • The tools it needs: one that checks the shelf, one that looks up when a book is due back, and one that charges a fine.
  • Done means: it has answered in words, using only what the tools said, or it has said plainly that it can't help.
  • Ask first: a fine takes a member's money, so a person must say yes before one is charged.
  • The limit: four turns at most, then stop and say so.

It's the note you'd leave for someone covering the front desk for an afternoon: what the job is, which drawers they may open, what to check with you first, and when to stop. With a real model, much of this card becomes the instructions you send with every request.

One question to ask before you start: does this need an agent at all? Anthropic's advice is "finding the simplest solution possible, and only increasing complexity when needed." If the steps are the same every time, a plain program that runs them in order may do the job better (the difference between an agent and a workflow is in the questions at the end). This job is small on purpose, so that every part of an agent fits on one page.

Step 2: write the tools as plain Python

A tool is an ordinary function. The model never runs it, and never even sees its code: it asks for a tool by name, and your program runs it. So write each tool first and check it works on its own, with no AI involved.

BOOKS = {
    12: {"title": "The Clockwork Heron", "due": None},
    27: {"title": "Nine Rainy Saturdays", "due": "4 December"},
    31: {"title": "A Map of Elsewhere", "due": "11 December"},
}

def check_shelf(book):
    if BOOKS[book]["due"] is None:
        return BOOKS[book]["title"] + " is on the shelf."
    return BOOKS[book]["title"] + " is out on loan."

def check_due(book):
    if BOOKS[book]["due"] is None:
        return BOOKS[book]["title"] + " is not out on loan."
    return BOOKS[book]["title"] + " is due back on " + BOOKS[book]["due"] + "."

print(check_shelf(12))
print(check_shelf(27))
print(check_due(27))

Output

The Clockwork Heron is on the shelf.
Nine Rainy Saturdays is out on loan.
Nine Rainy Saturdays is due back on 4 December.
  • BOOKS is the library's catalogue, looked up by book number. None in "due" means the book isn't out on loan.
  • Each tool returns a short sentence, because its result goes back to the model as text.
  • Each tool works without the model, so check each one on its own first. When something goes wrong later, you'll know the tools themselves work.

Step 3: describe each tool to the model

The model can't read your function. All it gets is a description you write: Anthropic's docs say Claude "only receives the schema you provided and the result you returned." Think of a restaurant menu: diners order from what the menu says, and never see the kitchen.

Here is a description of check_due, in the shape OpenAI documents for its Responses API (one of the ways to call its models):

{
  "type": "function",
  "name": "check_due",
  "description": "Says when a library book that is out on loan is due back. Use it when someone asks when they can borrow a book that is out. The book is given by its catalogue number. It does not say whether the book is on the shelf.",
  "parameters": {
    "type": "object",
    "properties": {
      "book": {
        "type": "integer",
        "description": "The book's catalogue number, such as 27."
      }
    },
    "required": ["book"],
    "additionalProperties": false
  },
  "strict": true
}
  • type is "function" for a tool you wrote yourself.
  • name is what the model will ask for, and what your code checks. Keep it short, with no spaces.
  • description says what the tool does, when to use it and what it won't do. Anthropic's docs say detailed descriptions are "by far the most important factor in tool performance", and suggest at least three or four sentences each. OpenAI suggests the intern test: "Can an intern/human correctly use the function given nothing but what you gave the model?"
  • parameters lists the inputs as a JSON Schema: each input's name and type under "properties", and the ones it must have under "required". The types are JSON's names, such as "integer", "number", "string" and "boolean", not Python's int or str.
  • strict makes the model's calls match your schema. OpenAI says it "will ensure function calls reliably adhere to the function schema" and that "We recommend always enabling strict mode." It needs "additionalProperties": false and every input listed as required.

Anthropic's Messages API takes the same description with two differences: the schema goes under input_schema instead of parameters, and there is no "type": "function" line.

The programs below write their descriptions as Python dictionaries with the same keys (leaving out strict), kept to one line each so the page stays short. The stand-in model doesn't read them. A real one does, so write yours out in full.

Step 4: the reply is words or a tool call

Send the model the goal and the tool descriptions, and its reply is one of two things:

  • Words, when it can answer, or when no tool fits.
  • A tool call: a request to run one of your tools, with the arguments to give it. It is only a request. Anthropic's docs put it plainly: "The model never runs anything on its own."

Here is a tool call in the shape OpenAI documents. The arguments arrive as JSON written out as text, so your code reads them with json.loads:

{
  "type": "function_call",
  "id": "fc_1",
  "call_id": "call_1",
  "name": "check_due",
  "arguments": "{\"book\": 27}"
}

Your code runs check_due(27). Then it sends the model a new request holding everything so far: the goal, the call the model made, and this result:

{
  "type": "function_call_output",
  "call_id": "call_1",
  "output": "Nine Rainy Saturdays is due back on 4 December."
}

The call_id pairs the result with its call, the way a cloakroom ticket matches a coat to its owner. Pair on call_id, not id: OpenAI's docs say the call_id is "used later to submit the function result".

Anthropic's Messages API works the same way, under other names:

OpenAI Responses APIAnthropic Messages API
The model asks for a tool witha function_call item: call_id, name, arguments (JSON as text)a tool_use block: id, name, input (an object)
You send the result back asa function_call_output item: call_id, outputa tool_result block: tool_use_id, content
The result is paired bythe same call_idtool_use_id, set to the call's id
It has finished whenthe reply holds no function_callstop_reason is no longer "tool_use"

One more rule: a reply can hold more than one call, or some words and a call together. OpenAI's docs say: "Since model responses can include zero, one, or multiple calls, it is best practice to assume there are several." So go through every item in the reply, never only the first.

Step 5: run it in a loop, with a limit

An agent is that exchange in a loop: ask the model, run whatever tools it asks for, add each result to the conversation, and ask again, until it answers in words. Here is the whole loop for the library desk, with the stand-in in place of the model. Its messages use the Responses API names from step 4, so a real model can take the stand-in's place later. (A real reply carries more than this, such as an id on each item.) You don't need to copy this one: step 8 has the whole agent in one program.

import json

BOOKS = {
    12: {"title": "The Clockwork Heron", "due": None},
    27: {"title": "Nine Rainy Saturdays", "due": "4 December"},
    31: {"title": "A Map of Elsewhere", "due": "11 December"},
}

def check_shelf(book):
    if BOOKS[book]["due"] is None:
        return BOOKS[book]["title"] + " is on the shelf."
    return BOOKS[book]["title"] + " is out on loan."

def check_due(book):
    if BOOKS[book]["due"] is None:
        return BOOKS[book]["title"] + " is not out on loan."
    return BOOKS[book]["title"] + " is due back on " + BOOKS[book]["due"] + "."

# What the model is told about each tool. Both take one input: a book number.
BOOK_NUMBER = {"type": "object", "properties": {"book": {"type": "integer"}}, "required": ["book"]}
TOOLS = [
    {"type": "function", "name": "check_shelf", "parameters": BOOK_NUMBER,
     "description": "Says whether a library book is on the shelf or out on loan."},
    {"type": "function", "name": "check_due", "parameters": BOOK_NUMBER,
     "description": "Says when a library book that is out on loan is due back."},
]

def stand_in_model(conversation, tools):
    # Not a real model. It follows fixed rules, so every run prints the same.
    goal = conversation[0]["content"].lower()
    for mark in "?.,":
        goal = goal.replace(mark, " ")
    words = goal.split()
    numbers = [int(word) for word in words if word.isdigit()]
    asked = [item["name"] for item in conversation if item.get("type") == "function_call"]
    for tool in tools:
        if tool["name"].split("_")[-1] in words and tool["name"] not in asked:
            # The goal's numbers become the arguments, in the order the tool lists them.
            arguments = dict(zip(tool["parameters"]["properties"], numbers))
            call = {"type": "function_call", "call_id": "call_" + str(len(asked) + 1),
                    "name": tool["name"], "arguments": json.dumps(arguments)}
            return {"output": [call], "output_text": ""}
    results = [item["output"] for item in conversation if item.get("type") == "function_call_output"]
    if not results:
        return {"output": [], "output_text": "Sorry, I have no tool for that."}
    return {"output": [], "output_text": " ".join(results)}

def run_tool(call):
    arguments = json.loads(call["arguments"])
    if call["name"] == "check_shelf":
        return check_shelf(arguments["book"])
    elif call["name"] == "check_due":
        return check_due(arguments["book"])

def run_agent(goal, max_turns=4):
    conversation = [{"role": "user", "content": goal}]
    for turn in range(1, max_turns + 1):
        reply = stand_in_model(conversation, TOOLS)
        conversation += reply["output"]  # keep the model's calls in the record
        calls = [item for item in reply["output"] if item["type"] == "function_call"]
        if not calls:
            return reply["output_text"]
        for call in calls:
            result = run_tool(call)
            print("Turn", turn, "runs", call["name"], call["arguments"])
            print("  and gets:", result)
            conversation.append({"type": "function_call_output", "call_id": call["call_id"], "output": result})
    return "Stopped: I ran out of turns."

print(run_agent("Is book 27 on the shelf? If not, when is it due back?"))
print(run_agent("Is book 31 on the shelf? If not, when is it due back?", max_turns=1))

Output

Turn 1 runs check_shelf {"book": 27}
  and gets: Nine Rainy Saturdays is out on loan.
Turn 2 runs check_due {"book": 27}
  and gets: Nine Rainy Saturdays is due back on 4 December.
Nine Rainy Saturdays is out on loan. Nine Rainy Saturdays is due back on 4 December.
Turn 1 runs check_shelf {"book": 31}
  and gets: A Map of Elsewhere is out on loan.
Stopped: I ran out of turns.

The stand-in follows four fixed rules, simple enough to check by hand:

  1. Go through the tools in order, and pick the first whose name ends in a word from the goal: check_shelf ends in "shelf", check_due in "due".
  2. Give that tool the numbers from the goal, in the order the tool lists its inputs.
  3. Ask for each tool at most once.
  4. When nothing is left to ask for, answer by joining what the tools said, or say there is no tool for it.

It reads only the tools' names and inputs, never their descriptions, and it doesn't understand "if not": it checks the due date either way. A real model reads every description and the whole goal, which is what makes it useful, and also why it can choose wrong.

Read the first run from the top:

  1. Turn 1: the goal says "shelf", so the stand-in asks for check_shelf with book 27. run_agent runs it, and adds the call and its result to conversation.
  2. Turn 2: check_shelf has had its turn, and the goal also says "due", so it asks for check_due.
  3. Turn 3 prints nothing of its own: with no tool left to ask for, the stand-in answers in words, and run_agent hands them back.

The second run is given max_turns=1. It checks the shelf, runs out of turns before it can answer, and says so. The limit matters even more with a real model, which might keep asking. Anthropic's engineers note that "it's also common to include stopping conditions (such as a maximum number of iterations) to maintain control", and in Anthropic's Claude Agent SDK the default for max_turns is "No limit", so you set one yourself. Think of it as a kitchen timer: when it rings, you stop and look, finished or not.

Try this: change the second run's max_turns=1 to max_turns=2, and work out what it will print before you run it.

Two things make the loop work. conversation is made once, before the loop, so each turn adds to it: it is the model's only record of what it has done. And every turn is a new request to the model, which with a real model means every turn costs.

Step 6: when a tool fails, send the error back

Sooner or later a tool will fail: a book number that isn't in the catalogue, a missing argument, a tool name your program doesn't have. If the error crashes your program, the agent stops halfway through the job. Instead, catch it and send the error back as the tool's result, so the model can try again or tell the person what went wrong. It's the shop assistant who says "we don't stock that one" rather than walking off mid-sentence.

import json

BOOKS = {12: {"title": "The Clockwork Heron", "due": None}}

def check_shelf(book):
    if BOOKS[book]["due"] is None:
        return BOOKS[book]["title"] + " is on the shelf."
    return BOOKS[book]["title"] + " is out on loan."

def run_tool(call):
    try:
        arguments = json.loads(call["arguments"])
        if call["name"] == "check_shelf":
            return check_shelf(arguments["book"])
        return "Error: there is no tool called " + call["name"] + ". The only tool is check_shelf."
    except Exception as problem:
        return "Error: " + call["name"] + " failed with " + repr(problem) + ". Check the arguments and try again."

def make_call(name, arguments):
    return {"type": "function_call", "call_id": "call_1", "name": name, "arguments": arguments}

print(run_tool(make_call("check_shelf", '{"book": 12}')))
print(run_tool(make_call("check_shelf", '{"book": 99}')))
print(run_tool(make_call("renew_loan", '{"book": 12}')))

Output

The Clockwork Heron is on the shelf.
Error: check_shelf failed with KeyError(99). Check the arguments and try again.
Error: there is no tool called renew_loan. The only tool is check_shelf.

try and except catch any error inside the tool, and repr(problem) names it: KeyError(99) means there is no book 99 in BOOKS. Each message also says what to try next. Anthropic's docs advise: "Write instructive error messages." Instead of a bare "failed", they say, include what went wrong and what to try next, which "gives Claude the context it needs to recover or adapt without guessing."

Both makers expect failures to go back as results. Anthropic's docs say: "When a client tool fails or a call is invalid, send a tool_result block with is_error set to true." OpenAI's docs say the result "should typically be a string, where the format is up to you (JSON, error codes, plain text, etc.)", so an error message goes in output like any other result.

Anthropic adds a warning: "Claude might then call the tool again with a new tool_use block, so limit how many retries your loop allows." The turn limit from step 5 does that job.

Step 7: ask a person before anything risky

Some actions can't be taken back: charging money, sending a message, deleting something. Before an agent does one, a person should say yes. OpenAI's guide says "Actions that are sensitive, irreversible, or have high stakes should trigger human oversight until confidence in the agent's reliability grows", and its examples include "authorizing large refunds, or making payments". It's how a shop till works: a big refund waits for the supervisor's key.

Charging a fine takes a member's money, so charge_fine goes on a list of tools that need a person first. Here is only the new part of run_tool:

import json

def charge_fine(member, pence):
    return "Member " + str(member) + " was charged a fine of " + str(pence) + "p."

NEEDS_A_PERSON = ["charge_fine"]

def run_tool(call, person_says):
    if call["name"] in NEEDS_A_PERSON:
        print("Asking a person: may I run " + call["name"] + " " + call["arguments"] + "?")
        print("They say:", person_says)
        if person_says != "yes":
            return "Not done: a person said no to " + call["name"] + "."
    # Only charge_fine is shown here; step 8 adds the other tools.
    arguments = json.loads(call["arguments"])
    return charge_fine(arguments["member"], arguments["pence"])

call = {"type": "function_call", "call_id": "call_1", "name": "charge_fine",
        "arguments": '{"member": 5, "pence": 120}'}
print(run_tool(call, "no"))
print(run_tool(call, "yes"))

Output

Asking a person: may I run charge_fine {"member": 5, "pence": 120}?
They say: no
Not done: a person said no to charge_fine.
Asking a person: may I run charge_fine {"member": 5, "pence": 120}?
They say: yes
Member 5 was charged a fine of 120p.

The check is in your code, not in the instructions you give the model, so nothing the model writes can skip it. A "no" goes back to the model as the tool's result, like an error in step 6, so it can tell the member what happened. In a program of your own, person_says would come from asking someone, for example with Python's input(). Here the answer is written in, so the example prints the same thing every time.

Step 8: test it on goals you know the answer to

Here is the whole agent, with steps 6 and 7 folded in and the third tool, charge_fine, added. At the bottom are six goals, each with something its answer must say. It's an answer key: you write the answers before the agent sees the questions.

import json

BOOKS = {
    12: {"title": "The Clockwork Heron", "due": None},
    27: {"title": "Nine Rainy Saturdays", "due": "4 December"},
    31: {"title": "A Map of Elsewhere", "due": "11 December"},
}

# Step 2: the tools.
def check_shelf(book):
    if BOOKS[book]["due"] is None:
        return BOOKS[book]["title"] + " is on the shelf."
    return BOOKS[book]["title"] + " is out on loan."

def check_due(book):
    if BOOKS[book]["due"] is None:
        return BOOKS[book]["title"] + " is not out on loan."
    return BOOKS[book]["title"] + " is due back on " + BOOKS[book]["due"] + "."

def charge_fine(member, pence):
    return "Member " + str(member) + " was charged a fine of " + str(pence) + "p."

# Step 3: what the model is told about each tool.
BOOK_NUMBER = {"type": "object", "properties": {"book": {"type": "integer"}}, "required": ["book"]}
FINE = {"type": "object", "properties": {"member": {"type": "integer"}, "pence": {"type": "integer"}},
        "required": ["member", "pence"]}
TOOLS = [
    {"type": "function", "name": "check_shelf", "parameters": BOOK_NUMBER,
     "description": "Says whether a library book is on the shelf or out on loan."},
    {"type": "function", "name": "check_due", "parameters": BOOK_NUMBER,
     "description": "Says when a library book that is out on loan is due back."},
    {"type": "function", "name": "charge_fine", "parameters": FINE,
     "description": "Charges a library member a late fine, in pence. A person must approve it."},
]

# Step 4: the stand-in model.
def stand_in_model(conversation, tools):
    # Not a real model. It follows fixed rules, so every run prints the same.
    goal = conversation[0]["content"].lower()
    for mark in "?.,":
        goal = goal.replace(mark, " ")
    words = goal.split()
    numbers = [int(word) for word in words if word.isdigit()]
    asked = [item["name"] for item in conversation if item.get("type") == "function_call"]
    for tool in tools:
        if tool["name"].split("_")[-1] in words and tool["name"] not in asked:
            arguments = dict(zip(tool["parameters"]["properties"], numbers))
            call = {"type": "function_call", "call_id": "call_" + str(len(asked) + 1),
                    "name": tool["name"], "arguments": json.dumps(arguments)}
            return {"output": [call], "output_text": ""}
    results = [item["output"] for item in conversation if item.get("type") == "function_call_output"]
    if not results:
        return {"output": [], "output_text": "Sorry, I have no tool for that."}
    return {"output": [], "output_text": " ".join(results)}

# Steps 6 and 7: run a tool safely, and ask a person first when it matters.
NEEDS_A_PERSON = ["charge_fine"]

def a_person_approves(call):
    # A real program would ask here, for example with input(). This person always says no.
    print("  (asked a person about " + call["name"] + " " + call["arguments"] + ": they said no)")
    return False

def run_tool(call):
    if call["name"] in NEEDS_A_PERSON and not a_person_approves(call):
        return "Not done: a person said no to " + call["name"] + "."
    try:
        arguments = json.loads(call["arguments"])
        if call["name"] == "check_shelf":
            return check_shelf(arguments["book"])
        elif call["name"] == "check_due":
            return check_due(arguments["book"])
        elif call["name"] == "charge_fine":
            return charge_fine(arguments["member"], arguments["pence"])
        return "Error: there is no tool called " + call["name"] + "."
    except Exception as problem:
        return "Error: " + call["name"] + " failed with " + repr(problem) + ". Check the arguments and try again."

# Step 5: the loop, with a limit.
def run_agent(goal, max_turns=4):
    conversation = [{"role": "user", "content": goal}]
    for turn in range(1, max_turns + 1):
        reply = stand_in_model(conversation, TOOLS)
        conversation += reply["output"]
        calls = [item for item in reply["output"] if item["type"] == "function_call"]
        if not calls:
            return reply["output_text"]
        for call in calls:
            conversation.append({"type": "function_call_output", "call_id": call["call_id"],
                                 "output": run_tool(call)})
    return "Stopped: I ran out of turns."

# Step 8: goals where you know what the answer must say.
TESTS = [
    ("Is book 12 on the shelf?", "on the shelf"),
    ("Is book 27 on the shelf? If not, when is it due back?", "4 December"),
    ("Is book 99 on the shelf?", "Error"),
    ("Charge member 5 a fine of 120 pence.", "Not done"),
    ("What time does the library open?", "no tool"),
    ("When is book 31 due back, and is book 12 on the shelf?", "The Clockwork Heron"),
]
for goal, must_say in TESTS:
    answer = run_agent(goal)
    if must_say in answer:
        print("PASS", goal)
    else:
        print("FAIL", goal)
        print("  got:", answer)

Output

PASS Is book 12 on the shelf?
PASS Is book 27 on the shelf? If not, when is it due back?
PASS Is book 99 on the shelf?
  (asked a person about charge_fine {"member": 5, "pence": 120}: they said no)
PASS Charge member 5 a fine of 120 pence.
PASS What time does the library open?
FAIL When is book 31 due back, and is book 12 on the shelf?
  got: A Map of Elsewhere is out on loan. A Map of Elsewhere is due back on 11 December.

Five pass. The last one fails, and that is the test doing its job. The goal asks about two books, 31 and 12, but the stand-in gives every tool the goal's first number, so it checked book 31 twice and never looked at book 12. A real model makes mistakes too, in its own ways. Anthropic's advice for tools is to run many example inputs "to see what mistakes the model makes, and iterate."

Each test checks for a fact the answer must contain, not the exact sentence. A real model words its answer differently from one run to the next (OpenAI's docs say "the content generated from a model is non-deterministic"), but "4 December" must be in it every time. IBM's guide puts knowing "how you can objectively measure its performance" in the first and most important step of building an agent.

Keep the tests, and run them after every change: a rewritten description, a new tool, a different model.

Step 9: swap the stand-in for a real model

Everything above runs without an AI model, which is why it is free and prints the same every time. To use a real one, the line reply = stand_in_model(conversation, TOOLS) becomes a request to the model's maker, through its Python library. In OpenAI's library that is client.responses.create(...), given a model's name, your TOOLS and the conversation. Its reply comes back as an object rather than a dictionary, so wherever the loop and run_tool read the reply with square brackets, they use a dot instead: reply.output, item.type, call.name, call.arguments, call.call_id and reply.output_text, as in OpenAI's own examples. Your tools, the turn limit, the list of tools that need a person, and the tests stay as they are.

What comes with a real model:

  • An account and an API key. The key is how the maker knows a request comes from your account. OpenAI's quickstart says to "Store the key in a safe location", and its libraries read it from your computer's environment, so it never has to sit in your code. Treat it like a password: never paste it into a program you share.
  • A cost for every turn. Each turn of the loop is a paid request. Anthropic prices tool use by the tokens (small pieces of text) each request sends and gets back, your tool descriptions included, and OpenAI says function definitions "are billed as input tokens". Every turn sends the whole conversation again, so a long run costs more than a short one, and the turn limit is a spending limit too.
  • A model that reads your descriptions. How well it chooses depends on what you wrote in step 3, and it may write a sentence before its call, which is why the loop checks every item. Run the tests from step 8 again, and expect some to change.

For Anthropic's Messages API, swap in the names from the table in step 4.

Other ways to build an agent

Writing the loop yourself is one of three routes. IBM's guide says coding an agent from scratch "allows for the greatest degree of control, customization and transparency, but also requires the most manual work and technical knowledge." The other two:

  • A no-code platform. IBM says many agent platforms "provide low-code or even no-code user interfaces (UIs), allowing even beginners and non-technical users to build and use AI agents", using templates, and that platforms also host and manage the agents. Each one works differently, so start with its own docs.
  • A framework that runs the loop for you. OpenAI's Agents SDK is a Python library with "a built-in loop that continues until the task is complete", and it can "Turn any Python function into a tool with automatic schema generation", which writes step 3 for you. Its first example has you set your OpenAI API key before running it. Anthropic's Claude Agent SDK "gives you the same tools, agent loop, and context management that power Claude Code, programmable in Python and TypeScript". Its settings include the turn limit and which tools need approval before they run, and its quickstart has you set an API key.

Both makers also describe doing without one. The Agents SDK docs say to call OpenAI's API directly when "you want to own the loop, tool dispatch, and state handling yourself". Anthropic's engineers write: "We suggest that developers start by using LLM APIs directly: many patterns can be implemented in a few lines of code. If you do use a framework, ensure you understand the underlying code." (An LLM, or large language model, is the kind of AI behind chat assistants.) The loop on this page is that underlying code.

If you'd like help writing the code itself, a coding agent can work on the files in a folder for you. Our Claude Code guide and Codex guide start you on a practice folder, where nothing important can break.

Where to go next

To build an agent like this yourself, you need enough Python to read the programs above: functions, lists, dictionaries, loops and if. Agentale is a game that teaches that from your first line of code, then has you build agents in its sixth region, Agent District. Its five quests build an agent one idea at a time, and add one this page leaves out, planning:

  1. Hand Over the Keys: reading a tool call and running the tool.
  2. The Right Tool: writing a tool's description yourself, and following the model's choice.
  3. What Happened Before: sending a result back, paired by its call_id.
  4. Goal, Act, Observe: the loop, with a limit and a plain way to give up.
  5. Think First: asking for a plan before acting on it.

The region ends in a boss project, The Support Desk: an agent that looks orders up, applies refund rules, hands big refunds to a person, and can't be talked out of a rule. Your code is checked against a practice oracle, a stand-in model with fixed rules like the one on this page, and a separate button sends the same code to a real model, which uses credits from a paid plan. Every quest is free to play; saving the rewards on Agent District's quests needs a paid plan. Testing an agent across many cases, and deciding what needs a person's approval, are planned for a later region that is still being built.

See every region in the curriculum, or start playing as a guest, with nothing to install.

Questions people ask

Do I need to know how to code to create an AI agent?

Not if you use a no-code platform, which IBM's guide says even beginners can use, with templates. To build one yourself, as on this page, you need some code. The programs here use only functions, lists, dictionaries, loops and if, which a beginner can learn.

Which programming language should I use to build an AI agent?

Any common language works. IBM says you can code an agent "from scratch in any common programming language, such as Python or Javascript". Python is a good first choice: OpenAI's Agents SDK is a Python library, and Anthropic's Claude Agent SDK is "programmable in Python and TypeScript". Every example on this page is Python.

Can I make an AI agent for free?

You can write and test the whole program for free, as on this page, with a stand-in for the model. Calling a real model through OpenAI's or Anthropic's API is paid: you need an account and an API key, and each request is billed by the tokens (pieces of text) it sends and gets back, tool descriptions included. Every turn of the loop is a request, so a turn limit also caps what one run can cost, and the Claude Agent SDK can stop a run at a spending limit you set (max_budget_usd). Each maker lists its prices on its own site.

Should I use a framework or build an AI agent from scratch?

A small one from scratch, like this page's, shows you what a framework would be doing for you. Anthropic's engineers warn that frameworks "often create extra layers of abstraction that can obscure the underlying prompts and responses, making them harder to debug." A framework earns its place when you want it to run the loop for you: the OpenAI Agents SDK docs suggest it when "you want the runtime to manage turns, tool execution, guardrails, handoffs, or sessions".

What's the difference between an AI agent and a workflow?

Who decides the steps. In a workflow, your code does: Anthropic defines workflows as "systems where LLMs and tools are orchestrated through predefined code paths". In an agent, the model does, choosing tools as it goes: "systems where LLMs dynamically direct their own processes and tool usage". Anthropic says "workflows offer predictability and consistency for well-defined tasks, whereas agents are the better option when flexibility and model-driven decision-making are needed at scale."

How many tools should an AI agent have?

As few as the job needs. OpenAI's function calling guide suggests aiming for "fewer than 20 functions available at the start of a turn", and calls that "just a soft suggestion". Its guide to building agents says the count isn't the whole story: "The issue isn't solely the number of tools, but their similarity or overlap. Some implementations successfully manage more than 15 well-defined, distinct tools while others struggle with fewer than 10 overlapping tools." Anthropic suggests grouping related actions into fewer tools, because "Fewer, more capable tools reduce selection ambiguity".

Sources

Checked against these sources on 28 November 2026.

Learn it by playing

Agentale is a game that teaches Python from zero, up to building your own AI agents. It runs in your browser, with nothing to install.