# 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.

Author: Steven Phan
Published: 2026-10-05
Article: https://stevenphan.ca/blog/build-an-ai-agent-in-python/

## 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](https://stevenphan.ca/blog/run-a-local-llm-with-ollama/).

<nav class="toc" aria-label="Table of contents">
<p><strong>On this page</strong></p>
<ol>
<li><a href="#how-tool-calling-works">How tool calling works</a></li>
<li><a href="#before-you-start">Before you start</a></li>
<li><a href="#step-1-write-two-simple-tools">Step 1: Write two simple tools</a></li>
<li><a href="#step-2-describe-the-tools-to-the-model">Step 2: Describe the tools to the model</a></li>
<li><a href="#step-3-write-the-agent-loop">Step 3: Write the agent loop</a></li>
<li><a href="#why-the-guardrails-matter">Why the guardrails matter</a></li>
<li><a href="#do-you-need-an-agent-framework">Do you need an agent framework?</a></li>
<li><a href="#faq">FAQ</a></li>
<li><a href="#where-to-go-next">Where to go next</a></li>
</ol>
</nav>

## 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](https://docs.ollama.com/capabilities/tool-calling).

## 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](https://ollama.com/search?c=tool) if you want a different model.

```bash
ollama pull llama3.2
pip install requests
```

## Step 1: Write two simple tools

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

```python
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.

```python
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.

```python
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:

```python
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

- Swap the toy tools for useful ones, such as reading a file from a folder or searching your notes with [Semantic Search in Python With Embeddings](https://stevenphan.ca/blog/semantic-search-with-embeddings-python/).
- Make the model return reliable data for your code with [Get Structured JSON From an LLM](https://stevenphan.ca/blog/structured-output-from-llm-json-schema/).
- Read [How to Ship Small AI Projects](https://stevenphan.ca/blog/shipping-small-ai-projects/) for a way to keep agent experiments small enough to finish.
