How to Build Your First AI Agent in Python

If you want an AI model to look things up instead of guessing, give it tools. When you build an AI agent in Python, the model calls your own functions for facts such as an order’s status or a sales tax amount.

The whole trick is a short loop. You’ll save the full version as agent.py and run it in the VS Code terminal; this is its core:

for step in range(1, max_steps + 1):
    response = client.responses.create(
        model=MODEL, input=history, tools=TOOLS)
    history += response.output
    calls = [i for i in response.output if i.type == "function_call"]
    if not calls:
        return response.output_text   # no tool needed: final answer
    # run each tool, send its result back, go around again

In this tutorial, I’ll show you how to build an AI agent in Python with the plain OpenAI SDK: no framework, two small tools, a max-steps guard, and a safe way to handle bad tool arguments.

I ran all of it on Python Python 3.12.5 with openai 3.61.0 and gpt-6-luna, OpenAI’s smallest and lowest-cost model right now. The screenshots are real VS Code runs on Windows.

Here’s what we’re building. The agent answers both questions in one go, and every number in its reply came from a tool:

VS Code terminal running a Python AI agent that calls an order status tool and a sales tax tool, then answers the shopper
The finished agent: two tool calls, then a plain-English answer with the $15.62 tax.
  • Model: gpt-6-luna, through the OpenAI Responses API, decides what happens next.
  • Tools: get_order_status() and calculate_sales_tax(), two plain Python functions.
  • Loop: run_agent() runs the requested tools and stops at an answer or after 5 steps.

What Is an AI Agent in Python?

An AI agent is a program where a language model decides the next step, instead of you hard-coding it. In Python, that comes down to three parts working together: a model, a set of tools, and a loop.

The tools are ordinary functions, the kind you’d write after any Python function tutorial. You describe each one to the model. When a question needs it, the model replies with a request: run this function with these arguments.

Your loop runs that function, hands the result back and asks the model again. It repeats until the model answers in plain text or a step limit kicks in. Agent frameworks add features, but this loop sits under all of them.

A plain chatbot can only answer from what it learned in training. An agent can tell you today’s order status, because your Python code does the checking.

What You Need to Build the Python AI Agent

You’ll need a recent Python 3 (I used 3.12), VS Code, and an OpenAI API key from a platform account with billing turned on. All the runs for this post together used only a few thousand tokens.

PyCharm or a Jupyter notebook work fine too, but the screenshots here come from VS Code, and the API calls go to the OpenAI platform.

Our running sample is Cedar Ridge Outdoor, a made-up online store. Its order table holds three orders:

Order IDStatusCarrierETAShip to
PG-10482shippedUPS2026-12-04Austin, TX
PG-10511processing–2026-12-08Denver, CO
PG-10537deliveredUSPS2026-11-28Columbus, OH

The tax tool knows seven statewide base rates: TX 6.25%, CA 7.25%, NY 4%, FL 6%, WA 6.5%, OH 5.75% and CO 2.9%. Real checkouts add city and county tax, so treat these as demo numbers.

Set up the project once:

  1. Create a folder named ai-agent and open it in VS Code with File > Open Folder.
  2. Open the terminal with View > Terminal, run python -m venv .venv, then .venv\Scripts\activate.
  3. Install the two packages with the pip command below.
  4. Create a file named .env in the folder and paste in the key line shown below.
  5. Add .env to .gitignore so the key never ends up on GitHub.

Type this in the VS Code terminal:

pip install openai python-dotenv

Then paste this one line into the .env file, with your real key after the equals sign:

OPENAI_API_KEY=paste-your-key-here

If virtual environments are new to you, my Python virtual environments tutorial walks through them. Environment variables in Python explains why keys belong in the environment, not in code.

Step 1: Make Your First OpenAI Call from Python

Before adding tools, confirm Python can reach the model. This check also shows which model answered and how many tokens it used.

Save this as first_call.py in the project folder, then run python first_call.py in the VS Code terminal:

import os
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()                       # reads OPENAI_API_KEY from .env
client = OpenAI()                   # picks the key up from the environment
MODEL = "gpt-6-luna"                # small, low-cost model

response = client.responses.create(
    model=MODEL,
    input="In one sentence, what does a US online store's support desk do?",
)
print("Key loaded:", bool(os.environ.get("OPENAI_API_KEY")))
print("Model:", response.model)
print("Answer:", response.output_text)
print("Tokens used:", response.usage.total_tokens)

Output:

Key loaded: True
Model: gpt-6-luna
Answer: A US online store’s support desk helps customers with orders, payments, shipping, returns, and other questions or problems.
Tokens used: 79
VS Code running a first OpenAI Responses API call from Python with gpt-6-luna and printing the token count
The key loads, gpt-6-luna answers, and the call used 79 tokens.

Checkpoint: you should see Key loaded: True, the model name and a token count (79 in my run). An AuthenticationError here means the .env file isn’t being read.

load_dotenv() copies the key from .env into the environment, and OpenAI() reads it from there. Your key never appears in the code.

Step 2: Write the Two Store Tools as Plain Python Functions

Tools are just functions that take simple arguments and return a dictionary. Neither of these knows anything about AI, so you can test them on their own.

Save this as store_tools.py next to first_call.py and run python store_tools.py in the VS Code terminal:

# Two small tools for Cedar Ridge Outdoor, a made-up US online store
ORDERS = {
    "PG-10482": {"status": "shipped", "carrier": "UPS",
                 "eta": "2026-12-04", "ship_to": "Austin, TX"},
    "PG-10511": {"status": "processing", "carrier": None,
                 "eta": "2026-12-08", "ship_to": "Denver, CO"},
    "PG-10537": {"status": "delivered", "carrier": "USPS",
                 "eta": "2026-11-28", "ship_to": "Columbus, OH"},
}

# statewide base rates only (no city or county tax) - demo data
TAX_RATES = {"TX": 0.0625, "CA": 0.0725, "NY": 0.04, "FL": 0.06,
             "WA": 0.065, "OH": 0.0575, "CO": 0.029}


def get_order_status(order_id):
    order = ORDERS.get(order_id.strip().upper())
    if order is None:
        return {"error": f"no order {order_id}; IDs look like PG-10482"}
    return order


def calculate_sales_tax(state, amount):
    rate = TAX_RATES.get(state.strip().upper())
    if rate is None:
        return {"error": f"no rate on file for {state}"}
    amount = float(amount)
    if amount <= 0:
        return {"error": "amount must be more than 0"}
    tax = round(amount * rate, 2)
    return {"state": state.upper(), "rate_percent": round(rate * 100, 2),
            "tax": tax, "total": round(amount + tax, 2)}


if __name__ == "__main__":
    print(get_order_status("PG-10482"))
    print(calculate_sales_tax("TX", 249.99))
    print(get_order_status("PG-99999"))

Output:

{'status': 'shipped', 'carrier': 'UPS', 'eta': '2026-12-04', 'ship_to': 'Austin, TX'}
{'state': 'TX', 'rate_percent': 6.25, 'tax': 15.62, 'total': 265.61}
{'error': 'no order PG-99999; IDs look like PG-10482'}
VS Code running the two Python agent tools by hand: an order status lookup, a Texas sales tax result and a missing order error
Order PG-10482 is shipped, Texas tax on $249.99 is $15.62, and PG-99999 returns an error dictionary.

Checkpoint: PG-10482 shows as shipped by UPS, Texas tax on $249.99 is $15.62 for a $265.61 total, and PG-99999 comes back as an error dictionary instead of a crash.

Returning an error dictionary instead of raising is deliberate: the model reads the message and can tell the shopper what went wrong. The dictionary get() method is what makes a missing order return None quietly.

One snag showed up in my first run. The Colorado rate printed as 2.9000000000000004, a normal float quirk, so the rate is now rounded to two places.

Step 3: Describe the Agent Tools with JSON Schema

The model never sees your Python code. It sees a name, a description and a JSON Schema for the arguments, and it picks a tool based on those.

Create tool_specs.py in the same folder and paste this list into the file:

# What the model sees: a name, a description and a JSON Schema per tool
TOOLS = [
    {
        "type": "function",
        "name": "get_order_status",
        "description": "Look up a Cedar Ridge Outdoor order by its ID.",
        "parameters": {
            "type": "object",
            "properties": {
                "order_id": {"type": "string",
                             "description": "Order ID such as PG-10482"},
            },
            "required": ["order_id"],
            "additionalProperties": False,
        },
        "strict": True,
    },
    {
        "type": "function",
        "name": "calculate_sales_tax",
        "description": "Sales tax and total for a US state, in USD.",
        "parameters": {
            "type": "object",
            "properties": {
                "state": {"type": "string",
                          "description": "Two-letter US state code, e.g. TX"},
                "amount": {"type": "number",
                           "description": "Pre-tax amount in USD"},
            },
            "required": ["state", "amount"],
            "additionalProperties": False,
        },
        "strict": True,
    },
]

"strict": True makes the model’s arguments follow the schema exactly. Strict mode needs additionalProperties: False on each object and every property listed in required.

Now check what the model sends back for one question. Save this as one_turn.py and run it in the