← All posts

Tutorial

Build an AI Agent in Python With Tool Calling (No Framework)

Build an AI agent in Python from scratch. A short tool-calling loop on a local model, with working code, guardrails and no framework required.

12 min read

Copy this article

Clipboard access is unavailable. Select the Markdown and copy it, then paste it into your chat.

Quick answer

An AI agent is a loop. The model looks at a request, decides whether it needs a tool, your code runs that tool, and the result goes back to the model until it can answer. That is the whole idea, and you can build an AI agent in Python with a short loop and no framework.

This tutorial builds that loop against a local model served by Ollama, so it needs no hosted API fee. If you have not set that up yet, start with Run a Local LLM with Ollama.

How tool calling works

A language model cannot run code or look things up on its own. Tool calling is the agreement that lets it ask you to.

  1. You send your question plus a list of tools, each described with a name, a description and a JSON schema for its arguments.
  2. The model either answers directly or replies with a request such as “call add with a=17, b=25”.
  3. You run the function yourself and send the result back as a message with the role tool.
  4. The model reads the result and writes the final answer, or asks for another tool.

The model never executes anything. Your code stays in control, which is exactly where you want it. The message formats are documented in the Ollama tool calling guide.

Before you start

You need Ollama running, Python 3.9 or newer, a model that supports tools, and the requests package. This tutorial uses llama3.2, which supports tool calling at the time of writing. Check the tools filter in the model library if you want a different model.

ollama pull llama3.2
pip install requests

Step 1: Write two simple tools

Tools are ordinary Python functions. Start with two harmless ones:

import math

import requests

OLLAMA_URL = "http://localhost:11434/api/chat"
MODEL = "llama3.2"


def add(a: float, b: float) -> float:
    if any(type(value) not in (int, float) or not math.isfinite(value) for value in (a, b)):
        raise ValueError("a and b must be finite JSON numbers")
    result = a + b
    if not math.isfinite(result):
        raise ValueError("sum must be finite")
    return result


def word_count(text: str) -> int:
    if not isinstance(text, str):
        raise ValueError("text must be a string")
    return len(text.split())


TOOL_FUNCTIONS = {"add": add, "word_count": word_count}

Step 2: Describe the tools to the model

The model only sees the descriptions, so write them clearly. A vague description can make it harder for a model to pick the right tool.

TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "add",
            "description": "Add two numbers and return the sum.",
            "parameters": {
                "type": "object",
                "properties": {
                    "a": {"type": "number", "description": "First number"},
                    "b": {"type": "number", "description": "Second number"},
                },
                "required": ["a", "b"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "word_count",
            "description": "Count the words in a piece of text.",
            "parameters": {
                "type": "object",
                "properties": {
                    "text": {"type": "string", "description": "The text to count"},
                },
                "required": ["text"],
            },
        },
    },
]

Step 3: Write the agent loop

This is the core of every agent. Read it slowly, because everything else is detail.

def run_agent(question: str, max_steps: int = 5) -> str:
    if type(max_steps) is not int or max_steps < 1:
        raise ValueError("max_steps must be a positive integer")
    messages = [{"role": "user", "content": question}]

    for _ in range(max_steps):
        response = requests.post(
            OLLAMA_URL,
            json={
                "model": MODEL,
                "messages": messages,
                "tools": TOOLS,
                "stream": False,
            },
            timeout=120,
        )
        response.raise_for_status()
        message = response.json()["message"]
        messages.append(message)

        tool_calls = message.get("tool_calls")
        if not tool_calls:
            return message["content"]  # No tool needed: this is the answer.

        for call in tool_calls:
            name = "invalid_tool_call"
            try:
                name = call["function"]["name"]
                arguments = call["function"]["arguments"]
                if not isinstance(name, str) or not isinstance(arguments, dict):
                    raise ValueError("tool name must be text and arguments must be an object")
                function = TOOL_FUNCTIONS.get(name)
                result = function(**arguments) if function else f"Unknown tool: {name}"
            except Exception as error:  # Report failures back to the model.
                result = f"Tool error: {error}"
            messages.append(
                {"role": "tool", "tool_name": name if isinstance(name, str) else "invalid_tool_call", "content": str(result)}
            )

    return "Stopped: the agent used too many steps."

Run it:

print(run_agent("What is 17 plus 25?"))
print(run_agent("How many words are in: the quick brown fox?"))

You should see the model call a tool, receive the result, and answer in plain language. Small models occasionally ignore a tool and guess, so run each question more than once while you experiment.

Why the guardrails matter

Four details in that loop are easy to skip and expensive to forget:

  • max_steps stops a confused model from looping forever and wasting time. With a hosted model it would waste money too.
  • Validate arguments inside each tool. Ollama passes along whatever the model produced, and nothing checks it against your schema for you. The tools above reject wrong types and nonfinite numbers instead of silently converting them.
  • Error messages go back to the model instead of crashing the program, which lets it correct a bad argument and try again.
  • Unknown tool names are handled. Models sometimes invent tools that do not exist.

If a tool can change the outside world, such as sending an email or deleting a file, add a confirmation step before it runs. Treat every argument the model produces as untrusted input.

Do you need an agent framework?

Not to get started. Frameworks help once you have many tools, long-running tasks, tracing or multiple agents. Building the loop yourself first means you will understand what a framework is doing, and you will know when you actually need one.

FAQ

How do you build an AI agent in Python without a framework?

An AI agent is a loop. The model looks at a request, decides whether it needs a tool, your code runs that tool, and the result goes back to the model until it can answer. You write two simple tools, describe them to the model, and then write the agent loop against a local model served by Ollama, so no hosted API fee is needed.

What is tool calling in an AI agent?

A language model cannot run code or look things up on its own, and tool calling is the agreement that lets it ask you to. You send your question plus a list of tools, each with a name, a description and a JSON schema for its arguments. The model replies with a request to call one, you run the function yourself and send the result back as a message with the role tool. The model never executes anything, so your code stays in control.

What do you need to get started building a Python AI agent?

You need Ollama running, Python 3.9 or newer, a model that supports tools, and the requests package. The tutorial uses llama3.2, which supports tool calling at the time of writing. Install the pieces with ollama pull llama3.2 and pip install requests, then check the tools filter in the model library if you want a different model.

Why do AI agents need guardrails like max_steps?

max_steps stops a confused model from looping forever and wasting time, and with a hosted model it would waste money too. Ollama passes along whatever the model produced and nothing checks it against your schema for you, so each tool should validate its own arguments. Error messages go back to the model instead of crashing the program, and unknown tool names are handled because models sometimes invent tools that do not exist.

Is it safe to let an AI agent send emails or delete files?

If a tool can change the outside world, such as sending an email or deleting a file, add a confirmation step before it runs. Treat every argument the model produces as untrusted input. Small models also occasionally ignore a tool and guess, so run each question more than once while you experiment.

Do you need an agent framework to build an AI agent?

Not to get started. Frameworks help once you have many tools, long-running tasks, tracing or multiple agents. Building the loop yourself first means you will understand what a framework is doing, and you will know when you actually need one.

Where to go next

  • #ai-agents
  • #python
  • #tool-calling