Build a Python AI Agent That Does Real Work

Build a Python AI agent that does real work: a yellow robot snake coiled around a report with checkmarks and a bar chart, next to a laptop

Most agent tutorials end at a chatbot. You ask a question, it answers, and nothing in the world changes. This one is different. By the end of it you will have an agent that does a job from start to finish: it reads a file, checks numbers against a budget, and writes a report you can actually use.

And you will not need a framework to do it. The whole agent is a loop of about 50 lines, and it is the same loop that LangChain, CrewAI and the OpenAI Agents SDK wrap in thousands of lines of their own code. Once you have written it yourself, every framework makes sense — because you know what it is hiding from you.

3
Tools
~50
Lines of loop code
0
Frameworks
10
Max steps, then it stops

The job: an expense-report agent

Here is the job. You have a file of this month's expenses and a file of monthly budgets. The agent reads both, adds up each category, flags anything over budget, and writes a short Markdown report. Boring work — which is exactly the point. If an agent can do the boring job reliably, it can do the interesting ones too.

You need two input files. First, expenses.csv:

expenses.csv
date,description,amount,category
2026-11-02,Groceries,42.50,Food
2026-11-05,Team lunch,18.90,Food
2026-11-08,Fuel,35.00,Transport
2026-11-12,Cloud storage,49.00,Software
2026-11-15,Design tool,89.00,Software
2026-11-20,Parking,12.50,Transport

Second, budgets.json:

budgets.json
{"Food": 150, "Transport": 60, "Software": 100}

The agent gets three tools — plain Python functions it can call:

ToolWhat it doesWhat the model sees
read_expensesReads the CSV fileEvery row, as JSON
check_budgetTotals one category against its limitSpent, limit, and how much over
write_reportWrites the Markdown reportA confirmation that the file was written

Step 1: Set up

You need Python 3.10 or newer and one package, the official OpenAI SDK. The code uses the Responses API, which OpenAI now recommends for all new projects. Your API key lives in an environment variable — never in your code.

Terminal
pip install openai
export OPENAI_API_KEY="sk-..."

Step 2: Give the agent its tools

A tool is two things: a Python function that does the work, and a JSON Schema description that tells the model when to use it. The description matters more than the types — it is the model's only guide for deciding which tool to call and what to put in each argument. Write it like you are explaining the tool to a new colleague.

Here is the budget checker, both halves:

tools.py
import csv, json

def read_expenses(path):
    with open(path, newline="") as f:
        return json.dumps(list(csv.DictReader(f)))

def check_budget(category):
    budgets = json.load(open("budgets.json"))
    rows = json.loads(read_expenses("expenses.csv"))
    total = sum(float(r["amount"]) for r in rows
                if r["category"] == category)
    limit = budgets[category]
    return json.dumps({"category": category, "spent": total,
                       "limit": limit, "over_by": round(total - limit, 2)})

def write_report(filename, content):
    with open(filename, "w") as f:
        f.write(content)
    return f"Wrote {filename}."

FUNCTIONS = {
    "read_expenses": read_expenses,
    "check_budget": check_budget,
    "write_report": write_report,
}

And the descriptions the model reads. Keep strict on and additionalProperties off, so the arguments the model sends always match the schema:

tools.py — continued
TOOLS = [
    {
        "type": "function",
        "name": "read_expenses",
        "description": "Read the expenses CSV file and return every row.",
        "parameters": {
            "type": "object",
            "properties": {
                "path": {"type": "string",
                         "description": "Path to the CSV file."}
            },
            "required": ["path"],
            "additionalProperties": False,
        },
        "strict": True,
    },
    {
        "type": "function",
        "name": "check_budget",
        "description": "Total one category and compare it with its budget limit.",
        "parameters": {
            "type": "object",
            "properties": {
                "category": {"type": "string",
                             "description": "Category name, e.g. Software."}
            },
            "required": ["category"],
            "additionalProperties": False,
        },
        "strict": True,
    },
    {
        "type": "function",
        "name": "write_report",
        "description": "Write the finished report to a Markdown file.",
        "parameters": {
            "type": "object",
            "properties": {
                "filename": {"type": "string"},
                "content": {"type": "string",
                            "description": "The full report in Markdown."}
            },
            "required": ["filename", "content"],
            "additionalProperties": False,
        },
        "strict": True,
    },
]

Step 3: The agent loop

This is the whole agent. Four steps, repeated: send the conversation and the tool list to the model; check whether it asked for a tool; run the tool yourself; send the result back. When the model stops asking for tools, its reply is the answer. The loop is capped at 10 steps, so a confused model cannot run forever — that cap is a safety feature, not a detail.

agent.py
import json
from openai import OpenAI
from tools import TOOLS, FUNCTIONS

client = OpenAI()  # reads OPENAI_API_KEY from the environment

def run_agent(task, max_steps=10):
    items = [{"role": "user", "content": task}]
    for step in range(max_steps):
        response = client.responses.create(
            model="gpt-6.2-sol",
            input=items,
            tools=TOOLS,
        )
        items += response.output
        calls = [o for o in response.output
                 if o.type == "function_call"]
        if not calls:
            return response.output_text
        for call in calls:
            print(f"Step {step + 1}: calling {call.name}")
            args = json.loads(call.arguments)
            result = FUNCTIONS[call.name](**args)
            items.append({
                "type": "function_call_output",
                "call_id": call.call_id,
                "output": result,
            })
    return "Stopped after 10 steps — the agent was going in circles."

print(run_agent("Summarize this month's spending and "
                "flag anything over budget."))

Two details in that loop are easy to get wrong. First, send back the whole response.output, not just the tool calls — reasoning models need their reasoning items returned alongside the tool results. Second, the model never runs your code. It only asks for a tool and fills in the arguments. Your loop runs the function, reads the result, and decides what happens next.

THE ONE THING TO REMEMBER: The model never runs your code. It only asks. Your loop does the work — and that is what makes it an agent instead of a chatbot.

Step 4: Run it and check the output

Run it with python agent.py. Your agent may check the categories in a different order — the report is what matters, not the order. Here is what a run looks like:

Terminal
$ python agent.py
Step 1: calling read_expenses
Step 2: calling check_budget
Step 3: calling check_budget
Step 4: calling check_budget
Step 5: calling write_report
Done. Spent $246.90 across 3 categories.
Software is over budget by $38.00.

And report.md, the file it wrote, should say the same thing in plain words: $246.90 spent in total — Food $61.40 of a $150 limit, Transport $47.50 of $60, Software $138.00 of $100, over by $38.00. Check the arithmetic yourself the first time you run it. That is the whole point of an agent that writes things down: you can verify its work instead of trusting it.

TIP: Keep the input small. The whole CSV comes back as a tool result, so every step re-sends it to the model. For a big file, have the tool return totals instead of every row — your token bill will thank you.

What this agent does not do

Three honest limits before you build on it.

SCOPE: This agent has no memory between runs — each run starts fresh. It has no schedule, and it writes the report the moment the model asks, with no approval step. Add a confirmation before any tool that changes something, and read the report before acting on it: the model can still misread a number.

A run like this costs pennies — a handful of API calls on gpt-6.2-sol, the lower-cost flagship. Swap in gpt-6.2-astra for harder tasks. And if you would rather not send data to OpenAI at all, any OpenAI-compatible endpoint works: point the client at it with a base_url and the rest of the code stays the same.

What you have now is the layer underneath every agent framework. Add a framework when you need what it actually buys you — memory, retries, or several agents working together. Until then, you have an agent that does real work in about 50 lines, and you understand every one of them.

Frequently asked questions

Do I need LangChain or CrewAI?

No. The loop in this tutorial is the same one they wrap. Add a framework when you need memory, retries, or multi-agent routing — not before.

How much does a run cost?

Pennies. Each step is one API call, and this job takes about five of them. The cost grows with the size of the files you send, so keep tool results small.

Can I use a local model?

Yes. Any endpoint that follows the OpenAI API spec works — set a base_url on the client and the rest of the code stays the same.

What if the agent makes a mistake?

The report is a file you read before acting on it, so a mistake costs you a minute, not money. Keep a human in the loop for anything that moves money or deletes data.

Sources: DataAspirant Responses API tutorial, DEV 50-line agent loop, Neurals function calling guide, OpenCode Responses API skill.