Machine Learning Mastery

How to Build Tool-Calling Local AI Agents in Python

In this article, you will learn how to build a local AI agent in Python that uses Ollama and Qwen3 to call tools that search, read, and remember information in a project folder.

Topics we will cover include:

  • How to set up Ollama with a tool-capable model and a context length large enough for agent workflows.
  • How the tool-calling exchange works, and how to write safe, size-limited tools as plain Python functions.
  • How to build the agent loop and add short-term and long-term memory to the assistant.

Introduction

A language model can generate text, reason through a problem, and follow instructions. To work with files on your computer, though, it needs a way to interact with them.

Tool calling provides that connection. It lets a model request an action, such as searching a folder or reading a document, and use the result to decide what to do next. Put that capability inside a loop, and you have the foundation of an AI agent.

In this article, we'll build one from scratch: a project assistant that runs locally using Python and Ollama. It will search and read files, keep track of useful information, and use memory across interactions.

The model, files, and conversation all stay on your machine, with no API key required.

This article covers:

  • Setting up Ollama, including the context length setting that agents depend on
  • Understanding how the tool-calling exchange works
  • Designing and writing tools to search, read, and remember
  • Building the agent loop, adding short-term and long-term memory, and testing the result

You can get the code from this GitHub repository.

Step 1: Setting Up Ollama and a Model That Can Use Tools

Ollama lets you download and run open models locally. We will use it to run Qwen3, while the Ollama Python package will handle communication between the model and our code.

Start by installing Ollama from its official download page. Make sure you have a recent version of Python installed, preferably Python 3.10 or newer.

Next, download Qwen3 with 4B parameters:

ollama pull qwen3:4b

Qwen3 supports tool calling. The download is approximately 2.5 GB.

Once the download finishes, start a chat to verify that the model is working:

ollama run qwen3:4b

You should now be able to interact with the model in your terminal. Type /bye when you are ready to exit.

With the model installed, create a project directory and set up a virtual environment:

mkdir local-agent && cd local-agent
python -m venv .venv
source .venv/bin/activate
pip install ollama

The virtual environment keeps the project's Python dependencies separate from the rest of your system. The ollama package provides the client our code will use to send messages and handle tool calls.

By default, the client connects to the Ollama server at localhost:11434. If your Python script reports a connection error, open another terminal, start the server with ollama serve, and run the script again.

Configuring the Context Length

Context length determines how much text the model can process in a single conversation. This matters when building an agent because the conversation includes tool definitions, previous messages, and tool results. As these accumulate, the context window fills up.

Ollama selects a default context length based on available GPU memory:

  • On systems with less than 24 GiB of VRAM, the default is 4K tokens.
  • For agent workflows, Ollama recommends a larger context length of at least 64K tokens.

However, Qwen3-4B has a native context of 32,768 tokens, so we will set it to 32K. This is enough for this assistant, because its tool results are size-limited and it keeps only the last six turns of conversation.

You can adjust this using the context length setting in the Ollama app. Alternatively, stop any running Ollama server and restart it with the desired context length:

OLLAMA_CONTEXT_LENGTH=32000 ollama serve

This sets the context length to 32K tokens for that server session.

A larger context window requires more memory, so check how the model is running after it loads:

ollama ps

Look at the PROCESSOR column to confirm that the model is using the GPU. If your hardware cannot accommodate a 32K-token context, use the largest context length your system can support. Keeping tool outputs concise will also help manage memory usage and leave more room for the conversation.

Step 2: Understanding the Tool-Calling Exchange

The model does not run anything itself. When it decides a tool would help, it replies with a structured request that names the tool and its arguments, your code runs the function, and the result goes back to the model as a new message.

The following four message roles make up the conversation:

Role Written by Purpose
system You Sets the assistant's behavior
user The person Asks a question or gives an instruction
assistant The model Answers, or requests tool calls in tool_calls
tool Your code Returns the result of one tool call

Each tool call carries a name and an arguments dictionary, and a single reply can contain several calls, each of which needs its own result.

A turn can also cycle through the last two roles many times: the model searches, reads what the search found, searches again, and only then answers. The loop in Step 5 handles that cycle.

Step 3: Designing Tools for a Project Assistant

The assistant answers questions about a folder that holds a small Python project: its code, README, changelog, and notes. I suggest you first try this assistant on a project with a similar structure, or create one and code along.

The model should find the right lines without ever receiving the whole folder, so we give it the following five tools:

  • list_files shows what is in a folder.
  • search_files finds lines that contain a word or phrase.
  • read_file reads a range of lines from one file.
  • recent_files lists what changed in the last few days.
  • remember stores a fact for future sessions.

The following principles decide how we write them. The model supplies the paths, so every path is checked against the root folder before use. Only remember writes anything, and it writes one small file outside your project, which leaves the other four read-only.

A limit on matches, lines, and characters bounds every result, so the context window cannot fill up from a single call. And every failure comes back as text, such as "that path is outside the folder", which gives the model a chance to correct itself.

Step 4: Writing the Tools

Ollama's Python library builds each tool's schema from the function's name, type hints, and docstring, so plain functions work as tools. The model chooses a tool from that description alone, which makes the docstring the most important part of each function: say what the tool returns and describe every argument.

The subsections below build assistant.py from the top.

Setting Up the File and Its Settings

Start the file with the imports and a handful of settings that the tools share:

import json
import sys
import time
from datetime import datetime
from pathlib import Path
from ollama import chat
MODEL = "qwen3:4b"
ROOT = Path(".").resolve()
MEMORY_FILE = Path.home() / ".doc_assistant_memory.json"
TEXT_SUFFIXES = {".md", ".txt", ".csv", ".json", ".py", ".rst"}
MAX_RESULTS = 20
MAX_TOOL_CHARS = 3000

ROOT is the folder the assistant may work with. It defaults to the current directory, and main replaces it with the folder you pass on the command line. TEXT_SUFFIXES lists the file types the tools will read, so add other plain-text formats there.

MEMORY_FILE sits in your home directory, outside the project folder, so a search never finds it. MAX_RESULTS and MAX_TOOL_CHARS are limits I chose for how many matches and how many characters a single tool result can carry, and you should tune them to your context window.

Keeping the Model Inside the Folder

The model writes the paths it passes to tools, and nothing stops it from writing ../../secrets.txt or an absolute path. Two helpers keep every file operation inside the root:

def safe_path(relative: str) -> Path:
    path = (ROOT / relative).resolve()
    if not path.is_relative_to(ROOT):
        raise ValueError("that path is outside the folder")
    return path

def text_files():
    for path in sorted(ROOT.rglob("*")):
        parts = path.relative_to(ROOT).parts
        if any(part.startswith(".") for part in parts):
            continue
        if path.is_file() and path.suffix.lower() in TEXT_SUFFIXES:
            if path.resolve().is_relative_to(ROOT):
                yield path

safe_path joins the requested path to the root and resolves it, which collapses .. and follows symbolic links, and then rejects any result that falls outside ROOT. An absolute path replaces the root when joined, so it fails the same check.

text_files walks the whole folder in sorted order so results are stable, and skips hidden directories, files with other extensions, and files whose symlink leads outside the root. The search and recent-files tools both use it.

Listing Files

The first tool gives the model a way to look around before it searches:

def list_files(subdirectory: str = ".") -> str:
    """List the folders and text files directly inside a folder, with file sizes.
    Args:
        subdirectory: The folder to list, relative to the root. Use "." for the top level.
    """
    try:
        folder = safe_path(subdirectory)
    except ValueError as error:
        return f"Error: {error}."
    if not folder.is_dir():
        return f"Error: '{subdirectory}' is not a folder."
    lines = []
    for path in sorted(folder.iterdir()):
        if path.name.startswith(".") or not path.resolve().is_relative_to(ROOT):
            continue
        if path.is_dir():
            lines.append(f"{path.name}/")
        elif path.suffix.lower() in TEXT_SUFFIXES:
            lines.append(f"{path.name} ({path.stat().st_size} bytes)")
    return "\n".join(lines) or "The folder has no readable files."

It returns only the direct children of one folder, with a trailing slash on directories and a size for each readable file. Hidden entries and links that leave the root are left out, and the docstring tells the model to pass "." for the top level because the schema requires an argument.

Errors come back as strings in the same way, so the loop passes them to the model like any other result.

Searching Across Files

Search is the tool the model will use most, and it needs to return enough to cite without returning everything:

def search_files(query: str, extension: str = "") -> str:
    """Search every text file for lines that contain a word or phrase, ignoring case.
    Each match is returned as path:line: text.
    Args:
        query: The word or phrase to look for
        extension: Optional file type filter such as ".md". Leave empty to search all text files.
    """
    needle = query.strip().lower()
    if not needle:
        return "Error: the query is empty."
    matches = []
    for path in text_files():
        if extension and path.suffix.lower() != extension.lower():
            continue
        text = path.read_text(errors="replace")
        for number, line in enumerate(text.splitlines(), start=1):
            if needle in line.lower():
                matches.append(f"{path.relative_to(ROOT)}:{number}: {line.strip()[:160]}")
        if len(matches) == MAX_RESULTS:
            return "\n".join(matches) + "\n[stopped at the match limit; narrow the query]"
    return "\n".join(matches) or f"No line contains '{query}'."

The match is a case-insensitive substring test, which is less clever than a regular expression and far easier for a small model to use correctly. Each hit comes back as path:line: text, with the text cut to 160 characters, and when the results reach MAX_RESULTS the function stops and appends a note asking for a narrower query, so the limit itself tells the model what to do next.

An empty query is rejected, since it would match every line. Because each hit carries a file and line number, the model can cite it, and the same tool answers code questions such as where a function is used.

Reading a Range of Lines

Once a search has found the right file, the model reads only the part it needs:

def read_file(path: str, start_line: int = 1, max_lines: int = 80) -> str:
    """Read part of a text file, with line numbers.
    Args:
        path: The file path relative to the root, as shown by list_files or search_files
        start_line: The first line to read, counting from 1
        max_lines: The most lines to return
    """
    try:
        file = safe_path(path)
    except ValueError as error:
        return f"Error: {error}."
    if not file.is_file() or file.suffix.lower() not in TEXT_SUFFIXES:
        return f"Error: '{path}' is not a readable text file."
    lines = file.read_text(errors="replace").splitlines()
    start = max(int(start_line), 1)
    chunk = lines[start - 1 : start - 1 + int(max_lines)]
    if not chunk:
        return f"No lines at that position. The file has {len(lines)} lines."
    numbered = "\n".join(f"{start + i}: {line}" for i, line in enumerate(chunk))
    return f"{numbered}\n[lines {start}-{start + len(chunk) - 1} of {len(lines)}]"

The result carries line numbers and a footer that gives the range returned and the file length, such as [lines 15-22 of 22], so the model knows whether more of the file exists and can ask for the next range.

The int() calls guard against a model that passes numbers as text, and run_tool in Step 5 turns a conversion failure into an error message. A start position past the end of the file gets its own message, which saves a confusing empty result.

Finding Recent Changes

Some questions depend on time, and a text search cannot answer them:

def recent_files(days: int = 7) -> str:
    """List the text files changed within the last number of days, newest first.
    Args:
        days: How many days back to look
    """
    cutoff = time.time() - int(days) * 86400
    found = [(p.stat().st_mtime, p) for p in text_files() if p.stat().st_mtime >= cutoff
Read on Machine Learning Mastery ↗ ← Back to News

Comments

No comments yet. Start the discussion.