Build Your First AI Agent and Multi-Agent App

Write the loop yourself once, and every framework you meet afterward will make sense.

BeginnerIntermediateExpert · 18 min read · Last updated:

In short

An agent is a loop: a model picks the next step, your code checks and runs it, and the result goes back to the model until the goal is met or a limit stops it. In this tutorial you build that loop in plain Python, test it, connect a real model and then share the work between several roles.

What you will learn: how to define a task an agent can finish, how to describe tools, how to write a safe loop, how to test it, how to plug in a real model, and when a team of agents is worth the extra work.
Prerequisites: basic Python (functions, dictionaries, loops) and Python 3.10 or later. The first five steps need no packages and no API key.

Beginner Build it offline, one piece at a time

What you will build

A restocking assistant for a small office kitchen. You ask it to restock coffee if needed. It checks the shelf, works out the shortfall, places an order if the cost is within a limit, and asks for a person if it is not. It is deliberately small, because every part of a large agent is already visible here.

GoalRestock coffee if low
ModelRequests a tool or answers
Your codeValidates, limits, runs
ToolsCheck stock, place order
↺ The tool result goes back to the model for the next decision
The model never touches your systems. It only asks.

Step 1: Define the task before the code

Write five lines before you write any Python. They prevent most early failures.

QuestionAnswer for this agent
What is the goal?Bring one item back up to its minimum level
How do we know it worked?An order exists for exactly the shortfall, or the agent says nothing is needed
What may it do?Read stock levels and create orders
What must it never do?Spend more than $100 in one order without approval
When does it give up?After six steps, on a repeated call, or on an error it cannot fix

If you cannot answer the second row, the agent cannot know when to stop, and neither can you. Agent Limits, Myths and When Not to Use One helps you check that the task needs an agent at all. This one could be written as a fixed script. It is a learning example, chosen so that you can see every step.

Step 2: Set up a folder

Create an empty folder and a virtual environment so that later packages stay isolated.

mkdir first-agent
cd first-agent
python -m venv .venv

# Windows PowerShell
.venv\Scripts\Activate.ps1
# macOS or Linux
source .venv/bin/activate

You will create four files: agent.py, test_agent.py, real_model.py and team.py. A fuller development setup is described in Set Up Your Agent Development Lab.

Step 3: Write the agent

Save this as agent.py. Read it once from top to bottom; the numbered comments match the four parts of every agent.

"""A small restocking agent. Standard library only."""
import json

STOCK = {"coffee": 3, "tea": 40}
MINIMUM = {"coffee": 10, "tea": 15}
PRICE = {"coffee": 8.50, "tea": 4.00}
ORDERS = []
APPROVAL_LIMIT = 100.00

# 1. Tools: ordinary functions that return plain data
def check_stock(item):
    if item not in STOCK:
        return {"error": f"unknown item: {item}"}
    return {"item": item, "on_hand": STOCK[item], "minimum": MINIMUM[item]}

def place_order(item, quantity):
    if item not in PRICE:
        return {"error": f"unknown item: {item}"}
    if not 0 < quantity <= 500:
        return {"error": "quantity must be between 1 and 500"}
    cost = round(PRICE[item] * quantity, 2)
    if cost > APPROVAL_LIMIT:          # the limit lives in code
        return {"error": "approval required", "cost": cost}
    ORDERS.append({"item": item, "quantity": quantity})
    return {"status": "ordered", "item": item, "quantity": quantity, "cost": cost}

# 2. Tool descriptions: what the model is told it may ask for
TOOLS = [
    {"name": "check_stock", "function": check_stock,
     "description": "Get the quantity on hand and the minimum level for one item.",
     "input_schema": {"type": "object",
                      "properties": {"item": {"type": "string"}},
                      "required": ["item"]}},
    {"name": "place_order", "function": place_order,
     "description": "Order more of one item. Large orders need approval.",
     "input_schema": {"type": "object",
                      "properties": {"item": {"type": "string"},
                                     "quantity": {"type": "integer"}},
                      "required": ["item", "quantity"]}},
]

PY_TYPES = {"string": str, "integer": int}

def validate(args, schema):
    """Return an error message, or None when the arguments are acceptable."""
    for key in schema["required"]:
        if key not in args:
            return f"missing argument: {key}"
    for key, value in args.items():
        if key not in schema["properties"]:
            return f"unexpected argument: {key}"
        wanted = PY_TYPES[schema["properties"][key]["type"]]
        if type(value) is not wanted:
            return f"{key} must be of type {wanted.__name__}"
    return None

def run_tool(name, args, tools):
    tool = next((t for t in tools if t["name"] == name), None)
    if tool is None:
        return {"error": f"unknown tool: {name}"}
    problem = validate(args, tool["input_schema"])
    if problem:
        return {"error": problem}
    try:
        return tool["function"](**args)
    except Exception as exc:           # report failures, do not crash the loop
        return {"error": f"tool failed: {exc}"}

# 3. The loop
def run_agent(goal, model, tools=TOOLS, max_steps=6, log=print):
    history = [{"role": "user", "content": goal}]
    seen = set()
    for step in range(1, max_steps + 1):
        decision = model(history, tools)
        if decision["type"] == "final":
            return {"status": "done", "answer": decision["text"], "steps": step - 1}
        name, args = decision["name"], decision["args"]
        signature = (name, json.dumps(args, sort_keys=True))
        if signature in seen:
            return {"status": "stopped", "answer": "Repeated the same call.", "steps": step - 1}
        seen.add(signature)
        result = run_tool(name, args, tools)
        log(f"step {step}: {name}({json.dumps(args)}) -> {json.dumps(result)}")
        history.append({"role": "assistant", "call": decision})
        history.append({"role": "tool", "id": decision["id"], "content": result})
    return {"status": "stopped", "answer": "Step limit reached.", "steps": max_steps}

# 4. A scripted stand-in for the model, so everything runs offline
def scripted_model(history, tools):
    results = [m["content"] for m in history if m["role"] == "tool"]
    call = lambda name, **args: {"type": "tool", "id": f"call_{len(results) + 1}",
                                 "name": name, "args": args}
    if not results:
        return call("check_stock", item="coffee")
    last = results[-1]
    if "error" in last:
        return {"type": "final", "text": "I need a person to help: " + last["error"]}
    if last.get("status") == "ordered":
        return {"type": "final",
                "text": f"Ordered {last['quantity']} {last['item']} for ${last['cost']:.2f}."}
    short = last["minimum"] - last["on_hand"]
    if short <= 0:
        return {"type": "final", "text": "Stock is fine. Nothing to order."}
    return call("place_order", item=last["item"], quantity=short)

if __name__ == "__main__":
    outcome = run_agent("Restock coffee if it is below the minimum.", scripted_model)
    print(outcome["status"], "-", outcome["answer"])

The tools

check_stock only reads. place_order changes something, so it carries the protections: the item must exist, the quantity must be sensible, and the cost must be under the approval limit. Both return dictionaries, including for errors. An error that is returned as data lets the model react to it. An exception that crashes the program does not.

The approval limit sits inside the function. You could also write "never spend more than $100" in the instructions, and you should, because it helps the model plan. But an instruction is a request, while the if statement is a guarantee. This is the most useful habit to take from the tutorial.

The tool descriptions

The model cannot read your functions. It sees only the name, the description and a schema in JSON Schema form. Write the description as you would for a new colleague: what the tool does, when to use it and what may go wrong. Designing Tool Schemas and Contracts goes further.

The loop

Each turn does five things in order:

  1. Ask the model for a decision, giving it the history and the tool list.
  2. If it gives a final answer, return it.
  3. If it repeats an identical call, stop. Repeating the same action and expecting news is the most common way a simple agent wastes money.
  4. Validate the arguments and run the tool.
  5. Record the request and the result in the history.

The history is the agent's memory for this run. The model has none of its own between calls, so anything it should remember must be in what you send. The loop is explored in depth in The Agent Loop: Observe, Reason, Plan, Act, Reflect.

The scripted model

scripted_model is a stand-in that follows hand-written rules. It is not intelligent, and that is the point: you can run, test and debug everything around the model with no cost and the same result every time. Real models plug into the same two arguments and return the same shape of decision.

Step 4: Run it

python agent.py

Output:

step 1: check_stock({"item": "coffee"}) -> {"item": "coffee", "on_hand": 3, "minimum": 10}
step 2: place_order({"item": "coffee", "quantity": 7}) -> {"status": "ordered", "item": "coffee", "quantity": 7, "cost": 59.5}
done - Ordered 7 coffee for $59.50.

Now experiment. Change one thing at a time and predict the result before you run it.

ChangeWhat should happenWhat it teaches
Set coffee stock to 30"Stock is fine" after one stepDoing nothing is a valid outcome
Set the minimum to 60The order costs too much and the agent asks for a personCode enforces the limit and the agent escalates
In scripted_model, check "cocoa" instead of coffeeThe tool returns an error and the agent reports itErrors are information
Set max_steps=1The run stops after checking stockLimits apply even when the work is unfinished

Step 5: Test it

You cannot test whether a model will always choose well. You can test that your code behaves correctly whatever it chooses. Save this as test_agent.py.

import agent

def quiet(_line):
    pass

def always(name, **args):
    """A model that keeps asking for one call: useful for testing limits."""
    return lambda history, tools: {"type": "tool", "id": "x", "name": name, "args": args}

def test_large_order_needs_approval():
    result = agent.run_tool("place_order", {"item": "coffee", "quantity": 50}, agent.TOOLS)
    assert result["error"] == "approval required"

def test_wrong_type_is_rejected():
    result = agent.run_tool("place_order", {"item": "tea", "quantity": "5"}, agent.TOOLS)
    assert "must be of type int" in result["error"]

def test_unknown_tool_is_rejected():
    assert "unknown tool" in agent.run_tool("delete_all", {}, agent.TOOLS)["error"]

def test_repeated_call_stops_the_run():
    outcome = agent.run_agent("loop", always("check_stock", item="tea"), log=quiet)
    assert outcome["status"] == "stopped"
    assert outcome["steps"] == 1

if __name__ == "__main__":
    tests = [f for n, f in list(globals().items()) if n.startswith("test_")]
    for test in tests:
        test()
        print("passed:", test.__name__)
    print(f"{len(tests)} tests passed")
passed: test_large_order_needs_approval
passed: test_wrong_type_is_rejected
passed: test_unknown_tool_is_rejected
passed: test_repeated_call_stops_the_run
4 tests passed

Notice the always helper. It creates a badly behaved model on purpose. Keep adding such cases: a model that sends a negative quantity, invents a tool, or never gives a final answer. Agent Testing: Unit to End-to-End explains how this grows into a full test strategy.

Intermediate Connect a real model

Step 6: Connect a real model

Vendor-specific example

The adapter below uses Anthropic's Python SDK. Other providers and local model servers offer similar tool-calling interfaces with different field names. Only this file changes if you switch; agent.py stays the same. Hosted models are paid services, so set a spending limit first.

Install the package, then set two environment variables: your API key, and the name of a model from the provider's current list. Never write a key into your source code.

pip install anthropic

# Windows PowerShell
$env:ANTHROPIC_API_KEY = "your-key"
$env:AGENT_MODEL = "a-current-model-name"
# macOS or Linux
export ANTHROPIC_API_KEY="your-key"
export AGENT_MODEL="a-current-model-name"

python real_model.py

Save this as real_model.py.

"""Adapter for one provider (Anthropic). Needs: pip install anthropic"""
import json
import os

import anthropic

import agent

SYSTEM = (
    "You are a restocking assistant. Check stock before ordering. "
    "Order only the shortfall. If a tool returns 'approval required', "
    "do not split the order to avoid the limit; report it to the user."
)

def to_api_messages(history):
    messages = []
    for m in history:
        if m["role"] == "user":
            messages.append({"role": "user", "content": m["content"]})
        elif m["role"] == "assistant":
            call = m["call"]
            messages.append({"role": "assistant", "content": [
                {"type": "tool_use", "id": call["id"],
                 "name": call["name"], "input": call["args"]}]})
        else:
            messages.append({"role": "user", "content": [
                {"type": "tool_result", "tool_use_id": m["id"],
                 "content": json.dumps(m["content"]),
                 "is_error": "error" in m["content"]}]})
    return messages

def make_model(client, model_name):
    def model(history, tools):
        response = client.messages.create(
            model=model_name,
            max_tokens=1024,
            system=SYSTEM,
            tools=[{k: t[k] for k in ("name", "description", "input_schema")}
                   for t in tools],
            tool_choice={"type": "auto", "disable_parallel_tool_use": True},
            messages=to_api_messages(history),
        )
        if response.stop_reason == "max_tokens":
            raise RuntimeError("reply was cut off; raise max_tokens")
        for block in response.content:
            if block.type == "tool_use":
                return {"type": "tool", "id": block.id,
                        "name": block.name, "args": dict(block.input)}
        text = "".join(b.text for b in response.content if b.type == "text")
        return {"type": "final", "text": text}
    return model

if __name__ == "__main__":
    client = anthropic.Anthropic()            # reads ANTHROPIC_API_KEY
    model = make_model(client, os.environ["AGENT_MODEL"])
    outcome = agent.run_agent("Restock coffee if it is below the minimum.", model)
    print(outcome["status"], "-", outcome["answer"])

The adapter does two translations. On the way in, it turns your neutral history into the provider's message format, pairing each tool result with the request that caused it by an ID. On the way out, it turns the reply into your small decision dictionary. The provider's tool use documentation describes the fields.

What changes with a real model

  • Answers vary. The wording, and sometimes the order of steps, differs between runs. Judge outcomes, such as which orders exist, more than exact text.
  • Arguments can be wrong. Your validation now earns its place.
  • The model may try to be helpful in the wrong way, for example by splitting one large order into several small ones. The instructions forbid it, but a robust version also tracks total spending per run in code.
  • Calls can fail. Add a timeout, a small number of retries with increasing delay, and a clear message when you give up. See Reliable Tool Execution and Error Recovery.
  • It costs money. Every step sends the whole history again, so long runs grow more expensive with each turn.

Write the instructions with care

The SYSTEM text has a role, an order of work, a rule about the shortfall and a rule for the approval error. That is a good minimum. Add to it only when a test shows a problem, so that each sentence has a reason to exist. Agent System Prompts and Instruction Hierarchy gives a full structure.

Warning: close the loophole

A per-order limit can be passed by ordering many times. Add a running total, for example refuse when the sum of all orders in this run would exceed the limit. As an exercise, write the failing test first, then the code.

Step 7: Your first multi-agent application

A multi-agent system splits work between parts that each have their own instructions, tools or context. Start with the structure, using scripted roles, before spending money on models. This example answers a question from a small set of notes with four roles.

PlannerSplits the question
ResearcherFinds evidence with sources
WriterDrafts from the evidence only
ReviewerChecks every citation
↺ Problems go back to the writer, a limited number of times
The supervisor is plain code that controls order, retries and stopping.

Save this as team.py.

"""A four-role research team in plain Python. Scripted roles, no API key."""

NOTES = {
    "N1": "Remote teams report that written decisions reduce repeated meetings.",
    "N2": "A weekly summary helps new joiners find past decisions.",
    "N3": "Written updates take longer to prepare than spoken ones.",
}

def search(query):
    """Return notes that share a keyword with the query."""
    words = {w for w in query.lower().split() if len(w) > 3}
    return {key: text for key, text in NOTES.items()
            if words & set(text.lower().rstrip(".").split())}

# Each role has one job and a narrow input and output.
def planner(question):
    return ["written decisions benefits", "written updates cost"]

def researcher(subquestion):
    return [{"source": key, "claim": text} for key, text in search(subquestion).items()]

def writer(question, evidence, feedback=None):
    lines = []
    for item in evidence:
        tag = f" [{item['source']}]" if feedback else ""   # first draft forgets citations
        lines.append(item["claim"] + tag)
    return {"question": question, "lines": lines}

def reviewer(report, evidence):
    problems = []
    if not report["lines"]:
        problems.append("the report is empty")
    known = {item["source"] for item in evidence}
    for line in report["lines"]:
        if not any(line.endswith(f"[{key}]") for key in known):
            problems.append("missing citation: " + line[:40])
    return problems

# The supervisor is ordinary code: it decides who runs and when to stop.
def run_team(question, max_revisions=2):
    evidence, used = [], set()
    for sub in planner(question):
        for item in researcher(sub):
            if item["source"] not in used:
                used.add(item["source"])
                evidence.append(item)
    if not evidence:
        return {"status": "needs a person", "reason": "no evidence found"}
    feedback = None
    for attempt in range(max_revisions + 1):
        report = writer(question, evidence, feedback)
        feedback = reviewer(report, evidence)
        print(f"draft {attempt + 1}: {len(feedback)} problem(s)")
        if not feedback:
            return {"status": "approved", "report": report}
    return {"status": "needs a person", "reason": feedback}

if __name__ == "__main__":
    result = run_team("Should our team write decisions down?")
    print(result["status"])
    for line in result.get("report", {}).get("lines", []):
        print("-", line)
draft 1: 3 problem(s)
draft 2: 0 problem(s)
approved
- Remote teams report that written decisions reduce repeated meetings. [N1]
- A weekly summary helps new joiners find past decisions. [N2]
- Written updates take longer to prepare than spoken ones. [N3]

The first draft is written without citations on purpose, so you can watch the review loop work. Three design choices matter more than the number of agents:

  • Narrow hand-offs. Each role receives only what it needs, in a fixed shape. The writer cannot search, so it cannot invent new sources.
  • A checkable review. The reviewer tests a rule that code can verify. A reviewer that only asks "is this good?" tends to approve almost anything.
  • A bounded loop. After two revisions the team hands over to a person.

To use real models, replace the planner, writer and reviewer functions one at a time, and keep the citation check in code even if a model also reviews the text. Note that the check confirms a citation is present and known, not that the note supports the sentence. That deeper check is covered in RAG Evaluation, Grounding and Debugging.

When is a team worth it?

Split whenStay with one agent when
Parts need different permissions, such as read-only research and write accessThe same tools and instructions serve the whole task
Sub-tasks can run independently at the same timeEach step depends on the details of the previous one
One context would fill with material that other steps do not needThe history stays small
You can measure that the team does betterYou are splitting because the diagram looks impressive

Compare both designs in Single-Agent vs Multi-Agent Systems and study the control pattern in Supervisor and Orchestrator-Worker Patterns.

Expert From demo to dependable service

Hardening checklist for real use

AreaIn the tutorialIn production
IdentityNoneAct for an authenticated user; check permissions on every tool call
Repeat safetyDuplicate check inside one runAn idempotency key so a retried order is created once
StateA list in memorySaved after each step so a run can resume
ApprovalAn error messageA real approval screen showing the exact action
LimitsSix stepsSteps, time, tokens and money per run and per user
RecordsPrinted linesStructured traces with personal data removed
Untrusted textNone entersTreat tool results and documents as data that may contain attacks

The last row deserves attention as soon as your agent reads email, web pages or shared documents. Read Prompt Injection Attacks and Defenses before you connect any of them.

Estimate the cost before you scale

Because the history is resent each turn, input grows with the number of steps. Suppose the instructions and tools take 1,000 tokens and each step adds 300. Six model calls send 1,000, 1,300, 1,600, 1,900, 2,200 and 2,500 tokens: 10,500 input tokens in total, not 2,500. These are illustrative numbers; measure your own from the usage figures the provider returns, and multiply by current prices. Agent Cost Model and Token Economics and Reducing Tokens, Tool Calls and Spend show how to control it.

Where frameworks help

Frameworks add saved state, retries, streaming, tracing, approval pauses and connectors. Many also offer a ready-made loop like yours. Add one when you need those features and can still explain what happens at each step. Compare options in Choosing Frameworks: Lock-In, Upgrades and Benchmarks, and consider What Is MCP? Hosts, Clients, Servers and Capabilities when the same tools should serve several applications.

Common problems and fixes

SymptomLikely causeFirst fix
The model never calls a toolVague description, or the task does not seem to need itSay in the description when to use it; check the tools are sent
Wrong argument typesLoose schemaTighten types, add examples to descriptions, return a clear error
Same call again and againThe result does not say anything new or the error is unclearReturn what to do next, and keep the repeat guard
Claims success without actingFinal answer not checked against the worldVerify in code, for example that the order exists
API rejects the historyA tool result without its matching requestKeep request and result together when trimming history
Expert tip

Record every decision from a real run and replay it as a scripted model. You get a free, repeatable test of your code against behavior that actually happened, including the odd cases you would never think to write.

Build checklist

  • The goal and the success test are written down.
  • Each tool validates its inputs and returns errors as data.
  • Limits on risky actions are enforced in code.
  • The loop stops on a final answer, a repeat, a step limit or a hard error.
  • Tests include a badly behaved model.
  • Keys are in environment variables or a secret store, never in code.
  • You can read a trace of any run and explain it.

Frequently asked questions

Do I need a framework to build an agent?

No. The loop in this tutorial is a complete, if small, agent. Frameworks become useful for saved state, approvals, tracing and larger workflows.

Can I do this with a model running on my own computer?

Yes, if the model and server support tool calling. Write an adapter that returns the same decision dictionary. Smaller models choose tools less reliably, so test them against your own cases.

Why does my agent behave differently each run?

Model output is usually sampled, so it can vary. Lower randomness where the provider allows it, and design checks that do not depend on exact wording.

How many tools can one agent have?

There is no fixed number. Quality tends to drop when tools overlap or their descriptions are unclear. Start with two or three and add one only when a task needs it.

References and further reading

Next steps