Step-by-step builds

AI Agent Project for Beginners: Build a Tool-Using Agent in Python From Scratch

Satvik ParamkushamUpdated October 5, 202613 min read

Quick answer

A beginner AI agent project is a Python program where an LLM decides which tool to use, such as a calculator, a Wikipedia lookup or a file reader, runs it, reads the result and repeats until it can answer. The core is a loop of about 25 lines with a step limit, built on any chat model that supports tool calling.

"AI agent" is the most hyped term in tech right now, and also one of the least understood. Strip away the buzz and an agent is surprisingly simple: a language model in a loop that can call functions you give it. Build one yourself and you will understand agent frameworks, interview questions about agentic AI and most of the news headlines in one go.

This guide builds a working agent from scratch in plain Python, with no framework. The agent gets three tools (a safe calculator, a Wikipedia lookup and a reader for your own notes), decides which one a task needs, and stops after a fixed number of steps so it can never loop forever. You will see every line, then the guardrails, the tests and the project ideas that turn it into a strong submission.

New to the idea? Read what an AI agent is first; it takes five minutes and makes the code below obvious.

What is an AI agent project?

An AI agent project is a program where a language model chooses actions (tool calls) to complete a goal, instead of only replying with text. The model plans, the code acts, and the result goes back to the model for the next decision.

Compare three things you might build:

  • A chatbot answers from what the model already knows.
  • A RAG chatbot retrieves passages from your documents first, then answers.
  • An agent decides for itself which tool to call, how many times, and when it is done.

That last part, the model choosing the next step, is what makes it an agent. A simple example of an agent in AI: ask "How many years before 2026 was the Taj Mahal commissioned?" The agent looks up the Taj Mahal on Wikipedia, reads that it was commissioned in 1631, calls the calculator with 2026 - 1631, then answers. Nobody wrote that sequence; the model chose it.

If you are unsure where single agents end and multi-agent systems begin, see AI agents vs agentic AI.

What do you need to build an AI agent in Python?

You need Python 3.10 or newer, the OpenAI Python SDK and an API key for a chat model that supports tool calling (also called function calling). No GPU and no agent framework are required.

PartWhat we useWhy
LanguagePython 3.10+Standard library covers the tools
LLM accessopenai Python SDKIts tool-calling format is widely copied by other providers
ModelAny tool-calling chat model, set by an environment variableSwap models without touching code
Toolsast, urllib, pathlibAll built into Python
Wikipedia dataWikipedia REST summary endpointFree, no key needed

You should be comfortable with Python functions, dictionaries and loops, and with reading JSON. If LLMs are still a black box to you, spend a few minutes there first.

How does a tool-using AI agent work? (architecture)

A tool-using agent works as a loop: the model either answers or asks for a tool, your code runs the tool and sends back the result, and the loop repeats until the model answers or a step limit is hit.

  1. You send the task plus a list of tool descriptions (name, purpose, parameters as JSON Schema).
  2. The model replies with either a final answer or one or more tool calls, each with a tool name and JSON arguments.
  3. Your code runs each requested function and appends the result to the conversation as a message with role "tool", linked by the tool call's id.
  4. The model sees the results and decides the next step.
  5. The loop ends when the model answers without a tool call, or when you reach max_steps.

The model never runs code itself. It only asks; your program decides whether and how to run anything. That separation is where all the safety in an agent lives.

How to build an AI agent in Python, step by step

  1. Step 1. Set up the project

    Create a folder, a virtual environment and install one package.

    mkdir ai-agent && cd ai-agent
    python -m venv .venv
    # Windows: .venv\Scripts\activate    macOS/Linux: source .venv/bin/activate
    pip install openai
    mkdir notes

    Put two or three small .txt files in the notes folder, for example exam dates or a reading list. Set two environment variables: OPENAI_API_KEY with your key, and LLM_MODEL with any current tool-calling model from your provider's documentation. Never paste the key into code you upload to GitHub.

  2. Step 2. Write the three tools

    Tools are ordinary Python functions that take simple arguments and return a string. Each one is written defensively, because the model, not you, chooses the inputs.

    # tools.py
    import ast, json, operator, urllib.parse, urllib.request
    from pathlib import Path
    
    OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul,
           ast.Div: operator.truediv, ast.Pow: operator.pow, ast.USub: operator.neg}
    
    def calculator(expression: str) -> str:
        def ev(node):
            if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
                return node.value
            if isinstance(node, ast.BinOp) and type(node.op) in OPS:
                return OPS[type(node.op)](ev(node.left), ev(node.right))
            if isinstance(node, ast.UnaryOp) and type(node.op) in OPS:
                return OPS[type(node.op)](ev(node.operand))
            raise ValueError("only numbers and + - * / ** are allowed")
        return str(ev(ast.parse(expression, mode="eval").body))
    
    def wikipedia_summary(topic: str) -> str:
        title = urllib.parse.quote(topic.replace(" ", "_"))
        url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{title}"
        req = urllib.request.Request(url, headers={"User-Agent": "student-agent/0.1"})
        with urllib.request.urlopen(req, timeout=10) as r:
            return json.load(r).get("extract", "No summary found.")
    
    NOTES = Path("notes").resolve()
    
    def read_file(name: str) -> str:
        path = (NOTES / name).resolve()
        if path.parent != NOTES or path.suffix != ".txt":
            return "Error: only .txt files inside the notes folder can be read."
        return path.read_text(encoding="utf-8")[:4000]

    The calculator walks the expression tree instead of calling eval, so an input like an import statement is rejected. The file reader resolves the path and refuses anything outside the notes folder, which blocks tricks such as ../../ paths.

  3. Step 3. Describe the tools to the model

    The model only knows what your tool descriptions tell it. Each tool needs a name, a one-line description of when to use it, and its parameters as JSON Schema.

    # agent.py
    import json, os
    from openai import OpenAI
    from tools import calculator, wikipedia_summary, read_file
    
    client = OpenAI()  # reads OPENAI_API_KEY from the environment
    MODEL = os.environ.get("LLM_MODEL", "gpt-4o-mini")  # any current tool-calling model
    
    def fn(name, description, param, param_desc):
        return {"type": "function", "function": {
            "name": name, "description": description,
            "parameters": {"type": "object",
                           "properties": {param: {"type": "string", "description": param_desc}},
                           "required": [param]}}}
    
    TOOLS = [
        fn("calculator", "Do arithmetic. Use for any maths.", "expression", "e.g. 18 * 4.5"),
        fn("wikipedia_summary", "Get facts about a person, place or topic.", "topic", "Wikipedia article title"),
        fn("read_file", "Read one of the user's .txt notes.", "name", "file name, e.g. exams.txt"),
    ]
    REGISTRY = {"calculator": calculator, "wikipedia_summary": wikipedia_summary, "read_file": read_file}

    Good descriptions do most of the work. If the agent picks the wrong tool, improve the description before you touch anything else.

  4. Step 4. Write the agent loop with a step limit

    The loop sends the conversation, runs any tool calls, appends each result as a "tool" message with the matching tool_call_id, and stops at max_steps.

    # agent.py (continued)
    SYSTEM = ("You are a helpful agent. Use a tool whenever it helps. "
              "Never guess numbers or facts you can look up. Answer briefly.")
    
    def run_agent(task, max_steps=5):
        messages = [{"role": "system", "content": SYSTEM},
                    {"role": "user", "content": task}]
        for step in range(1, max_steps + 1):
            reply = client.chat.completions.create(
                model=MODEL, messages=messages, tools=TOOLS)
            msg = reply.choices[0].message
            if not msg.tool_calls:           # no tool requested: final answer
                return msg.content
            messages.append(msg)             # keep the model's tool request
            for call in msg.tool_calls:
                name, args = call.function.name, {}
                try:
                    args = json.loads(call.function.arguments or "{}")
                    tool = REGISTRY.get(name)
                    result = tool(**args) if tool else f"Error: unknown tool {name}"
                except Exception as e:       # bad arguments or a failing tool
                    result = f"Error: {e}"
                print(f"  step {step}: {name}({args}) returned {str(result)[:80]}")
                messages.append({"role": "tool", "tool_call_id": call.id,
                                 "content": str(result)})
        return "Stopped: reached the step limit without a final answer."
    
    if __name__ == "__main__":
        print(run_agent(input("Task: ")))

    Two details matter. First, every tool call must get exactly one "tool" message back with its id, or the API rejects the next request. Second, errors are returned to the model as text instead of crashing, so the agent can read "Error: ..." and try something else.

  5. Step 5. Run it and read the trace

    Run python agent.py and try tasks that need zero, one and several tools:

    • "What is 17.5 percent of 2,340?" (calculator only)
    • "Where is ISRO headquartered?" (Wikipedia only)
    • "How many days are left between the two exam dates in exams.txt?" (file, then calculator)
    • "Say hello." (no tool at all)

    Watch the printed trace. The step lines show which tool the model picked, with what arguments, and what came back. Reading traces is the most important debugging skill for agents: when an answer is wrong, the trace tells you whether the model chose the wrong tool, passed bad arguments, or misread a correct result.

  6. Step 6. Add guardrails before you add tools

    Guardrails are the rules your code enforces no matter what the model asks for. You already have four: a step limit, a tool allowlist (REGISTRY), a sandboxed file path, and no eval. Add a human check before any tool that changes something:

    RISKY = {"write_file", "send_email"}
    
    def approved(name, args):
        if name not in RISKY:
            return True
        answer = input(f"Agent wants to run {name} with {args}. Allow? (y/n) ")
        return answer.strip().lower() == "y"

    Call approved(name, args) inside the loop before running a tool, and return "Error: the user declined" when it is False. Also cap tool output length (the file reader already cuts at 4,000 characters) so one huge result cannot flood the context. Read more on AI guardrails.

  7. Step 7. Test the agent and measure it

    Write 15 tasks with known answers: 5 that need no tool, 5 that need one tool, and 5 that need two. Run each one and record four things in a spreadsheet:

    1. Right tool chosen: did it call the tools you expected?
    2. Correct answer: was the final answer right?
    3. Steps used: how many loop steps did it take?
    4. Hit the limit: did it ever stop at max_steps?

    Your report line then reads like "correct tool choice 14 of 15, correct answers 13 of 15, average 2.1 steps, 0 step-limit stops". Run the same tasks with two different models by changing LLM_MODEL, and you have a comparison table most student projects do not have.

What are good AI agent project ideas for beginners?

Good beginner AI agent projects give the model two to four safe tools around one clear job. Keep the loop from this guide and change the tools:

  • Study planner agent: reads your syllabus notes, counts days to each exam with the calculator, and drafts a revision timetable.
  • Expense helper: reads a CSV of your spending, totals categories, and answers "how much did I spend on food in March?"
  • Weather and travel helper: calls a free weather API and a distance calculator to suggest when to leave.
  • Placement prep agent: looks up a company on Wikipedia, reads your resume file, and drafts five likely interview questions.
  • Research assistant: searches Wikipedia, collects summaries for three related topics, and writes a short comparison with sources.
  • Unit converter and quiz bot: converts units, then quizzes you and checks your answers with the calculator.

For a final-year version, add one serious upgrade: retrieval over your own documents as a tool (combine with the RAG chatbot project), a memory file, a second agent that reviews the first agent's answer, or exposing your tools through a standard protocol by building an MCP server.

How do I explain my AI agent project in a viva or interview?

Start with one sentence: "My project is an LLM in a loop that chooses between a calculator, a Wikipedia lookup and a file reader, runs the chosen tool through my code, and stops when it can answer or after five steps."

Then expect these follow-ups:

  • What makes this an agent and not a chatbot? (The model chooses actions and sees their results.)
  • How does tool calling work? (The model returns a tool name and JSON arguments; my code runs the function and sends the result back with the tool call id.)
  • What stops it from looping forever? (max_steps, plus a clear final-answer condition.)
  • What if the model asks for a dangerous action? (Allowlist, sandboxed paths, no eval, human approval for risky tools.)
  • How did you evaluate it? (Show your 15-task results.)
  • How is this different from agentic AI? (Read AI agents vs agentic AI.)

Our agentic AI interview questions page has model answers for these and many more.

Common mistakes in beginner AI agent projects

Most broken agent projects fail in the same six places:

  1. No step limit. A confused model can call the same tool forever and burn your API credit. Always cap the loop.
  2. Running eval on model output. One bad expression and the model can run any Python on your machine. Parse safely or use a maths library.
  3. Missing tool messages. Every tool call needs a reply with its tool_call_id, even when the tool fails.
  4. Crashing on errors. Return errors as text so the model can recover, instead of letting one exception kill the run.
  5. Trusting tool output blindly. Web pages and files can contain instructions aimed at the model (prompt injection). Treat tool results as data, never as commands.
  6. Too many tools too soon. Ten vague tools confuse the model. Start with three precise ones and add more only when tests show a need.

Fix these and your agent will already behave better than many demo videos.

Frequently asked questions

How do I create an AI agent as a beginner?

Start with plain Python and one chat model that supports tool calling. Write two or three small functions as tools, describe them in JSON Schema, and run a loop that calls the model, executes any requested tool and sends back the result, with a step limit. Learn frameworks only after this works.

Do I need LangChain or another framework to build an AI agent?

No. A basic agent is about 25 lines of loop code plus your tool functions. Frameworks such as LangChain, LlamaIndex or the OpenAI Agents SDK help with bigger projects, but building the loop yourself first means you can explain exactly what the framework does for you.

Can I build an AI agent project for free?

Mostly. Python, the tools in this guide and the Wikipedia endpoint are free. The model calls need an API; several providers offer free tiers with limits, and some open models can run locally through tools that copy the OpenAI tool-calling format. Check each provider's current pricing page.

What is an example of an agent in AI?

A simple example is a research helper that, asked how many years before 2026 the Taj Mahal was commissioned, looks it up on Wikipedia, reads the year 1631, calls a calculator and answers. Larger examples include coding agents that edit and test code, and support agents that look up orders.

Is an AI agent a good final-year project?

Yes, if it solves one real task and you can show results. Add an evaluation set of tasks, safety guardrails, and one upgrade such as retrieval over your documents, memory or a reviewer agent. Examiners value a clear trace of how the agent decided, not just a final answer.

References