How to Build an AI Agent: A Beginner's Step-by-Step Guide

Build a small, safe AI agent in Python: choose one task, define its tools, add a step limit and human approval, then test and monitor it. Runnable code included.

How to Build an AI Agent: A Beginner's Step-by-Step Guide

To build an AI agent, pick one narrow task, list the few tools it may call, write a loop that lets a model choose a tool, run it and read the result, then add a step limit and a human approval gate before anything irreversible. Start with a stubbed model so you can test the loop for free, then swap in a real model call.

Key takeaways

  • A first agent is a loop of four parts: a goal, a model that picks the next action, tools that run it and a stop rule.
  • Choose a task where mistakes are cheap and reversible. Reading files and filling a spreadsheet are good starts; sending money is not.
  • Write the tool list and the approval rules before you write any prompt.
  • Test with a fixed set of example tasks and log every tool call, so you can see why a run went wrong.

On this page:

Candidate first agent (illustrative)Tools it needsRisk if it errsGood first build?
Study-notes summariserRead a file, write a summaryLow: a poor summaryYes
Expense categoriserRead a CSV, write a new columnLow: a wrong label you can correctYes
Job-application trackerRead an inbox, update a sheetMedium: a missed or mislabelled mailAfter the first two
Refund helperRead orders, issue refundsHigh: money movesOnly with a mock system and approval
Auto-reply to recruitersRead mail, send mailHigh: messages go out in your nameNot yet

How do I choose a single-purpose agent?

Choose an agent with one job, one input type and one clear finish line. A narrow agent is easier to test, and you will learn the loop faster.

Write the job as a sentence a stranger could check: "Read a CSV of bank transactions and add a category column using these ten categories." That sentence tells you the input, the output and what "done" means. "Help me with my finances" does not.

Use these three questions to pick:

  • Can I check the result in under a minute?
  • Is every action undoable, or at least visible before it takes effect?
  • Do I have five to ten real examples to test with?

If you are still deciding between a chatbot and an agent for your idea, read AI agent vs chatbot first. For project ideas, our list of agentic AI projects for beginners is a good source.

Which tools and actions should the agent be allowed?

A tool is an ordinary function the agent is allowed to call, and the allowed list is your main safety control. Keep it short, give each tool a clear name and make each one do a single thing.

For the expense categoriser, the tools could be:

  • read_rows(start, count): returns a few transactions, read-only
  • set_category(row_id, category): writes one label, only from the approved list of ten
  • finish(summary): ends the run

Notice what is missing: no delete, no file access outside one folder, no network. If the model asks for a tool that is not on the list, your code should refuse it. Also validate the arguments. If the model returns a category that is not one of the ten, reject the call instead of writing it.

Frameworks such as the ones in our guide to agentic AI tools and frameworks wrap this pattern for you. Build the loop by hand once, though. You will understand every framework better afterwards.

How do I build, test and add human approval?

Build the loop with a stubbed model first, add a step limit and an approval check, and only then connect a real model. This order lets you test the control flow without paying for a single model call.

The program below is a complete, runnable agent skeleton for the late-order refund task. fake_model stands in for a language model and returns the next action in the same JSON-like shape you would ask a real model to produce. It uses only the Python standard library.

import json

ORDERS = {"4821": {"status": "shipped", "days_late": 6}}

def get_order(order_id):
    return ORDERS.get(order_id, {"error": "not found"})

def create_refund(order_id):
    return {"refund": "created", "order": order_id}

TOOLS = {"get_order": get_order, "create_refund": create_refund}
NEEDS_APPROVAL = {"create_refund"}

def fake_model(history):
    last = history[-1]
    if last["role"] == "user":
        return {"tool": "get_order", "args": {"order_id": "4821"}}
    if "days_late" in last["content"]:
        if json.loads(last["content"])["days_late"] > 5:
            return {"tool": "create_refund", "args": {"order_id": "4821"}}
        return {"final": "Not eligible for a refund yet."}
    return {"final": "Refund processed."}

def run(goal, max_steps=5):
    history = [{"role": "user", "content": goal}]
    for _ in range(max_steps):
        action = fake_model(history)
        if "final" in action:
            return action["final"]
        name, args = action["tool"], action["args"]
        if name not in TOOLS:
            return "Blocked: unknown tool"
        if name in NEEDS_APPROVAL and input(f"Approve {name}{args}? [y/n] ") != "y":
            return "Stopped: approval denied"
        history.append({"role": "tool", "content": json.dumps(TOOLS[name](**args))})
    return "Stopped: step limit reached"

print(run("Order 4821 is late, refund it"))

Run it and type y at the prompt: the agent fetches the order, sees six days of delay, asks you to approve the refund and prints "Refund processed." Type n and it stops. To connect a real model, replace fake_model with a function that sends the history and tool descriptions to your model provider and parses the reply into the same shape.

Then test. Keep a table of ten tasks with the expected final result, run all of them after every change and note which ones fail. Add edge cases: an unknown order, a delay of exactly five days and an empty goal.

How do I deploy and monitor the agent?

Deploying an agent means running the same loop where others can use it, with logging, limits and a way to switch it off. The loop does not change; the safety around it does.

Before you share it, check this list:

  • Secrets: keep API keys in environment variables, never in the code or the repository.
  • Logs: record every model call, tool call, argument and result with a timestamp.
  • Limits: cap steps per run and runs per hour. Add a spend limit on the model account.
  • Approval: keep the human gate for any write that is hard to undo.
  • Kill switch: one setting that stops the agent from taking new tasks.

Once it is live, read the logs weekly. Look for repeated tool calls, refused calls and tasks that hit the step limit. Each is a clue to a vague tool description or a missing rule. Tools exposed over a shared protocol are covered in our MCP guide for developers.

A built, tested and logged agent in a public repository, with a README that shows the ten test tasks, is useful evidence of skill. Our agentic AI roadmap shows what to learn after this first project.

Next step: If you want mentored practice on projects like this, see the Leap AI Residency Cohort by Masai or the AI Officer Programme from Vishlesan i-Hub, IIT Patna. Check each page for the current batch date and eligibility.

Frequently asked questions

What should a beginner know before building an AI agent?

Know basic Python, how to call an API and how to read JSON. You also need to understand that a model only suggests the next step. Your code decides what actually runs.

Can I build an AI agent without a framework?

Yes. A loop, a dictionary of tools, a step limit and an approval check, as shown above, is a working agent. Frameworks save time later but hide details that are worth learning first.

How much does it cost to build a first AI agent?

The loop itself costs nothing. A real model charges per use, and prices change, so check your provider's current pricing page and set a spending limit on the account.

How do I stop an agent from doing something harmful?

Limit the tools, validate arguments, require human approval for irreversible actions, cap the number of steps and log every call. Never give an agent more access than the task needs.

How do I know my AI agent works?

Write ten to twenty realistic tasks with expected results and run them after every change. Track task success, wrong tool calls and runs that hit the step limit.

×

Our Courses

Practice-Based Learning Tracks, Supercharged By A.I.