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

Share Post Share 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.
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.
You can get the code from this GitHub repository.
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:
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:
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:
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.
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:
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:
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:
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.
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:
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.
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:
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.
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.
Start the file with the imports and a handful of settings that the tools share:
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.
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:
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.
The first tool gives the model a way to look around before it searches:
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.
Search is the tool the model will use most, and it needs to return enough to cite without returning everything:
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.
Once a search has found the right file, the model reads only the part it needs:
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.
Some questions depend on time, and a text search cannot answer them:
The function compares each file’s modification time with a cutoff and returns the newest files first, capped at MAX_RESULTS, which answers “what was I working on this week?” without the model guessing at filenames.
The last tool is the only one that writes:
remember appends a short fact to a JSON list and skips duplicates, and load_memory reads the list back. The docstring asks for one self-contained statement, because a fact that depends on the current conversation will not make sense in a later session. Step 6 shows how the facts reach the model.
A dictionary from tool name to function ties the five tools together:
The values go to the model as the list of tools in every chat call, and the keys let the loop find the function that matches each tool request.
With the tools written, the loop connects them to the model. It calls the model, runs any tools the model requests, and calls the model again with the results, until a reply arrives with no tool calls. We write two helpers to make that safe: clip cuts any result that exceeds the character budget, and run_tool turns every failure into a message the model can read:
run_tool covers three failures: an unknown tool name (the error lists the tools that exist), arguments with the wrong names, and arguments with the wrong types. In each case the model receives an error string and can try again while the program keeps running.
run_turn appends the model’s reply to messages first, because a tool message only makes sense after the assistant message that requested it. It then handles every entry in tool_calls, so parallel requests work, and each result carries a tool_name that ties it to its call. The [tool] line prints each request, which is how you spot invented arguments. Setting temperature to 0 through options makes tool choices more repeatable, and max_steps stops a model that keeps calling tools and never answers.
A model keeps nothing between calls, so memory is the history your code sends back each time. This assistant uses two simple memory mechanisms.
Short-term memory is the messages list. Because the loop appends to it, the model can answer a follow-up such as “and what did that file say about the deadline?” The list grows with every turn, so a trim function keeps the system prompt and the last few user turns:
trim cuts only at a user message, so a tool request stays together with its result. Cutting between the two would leave the model with a result that no request explains. Six turns is a starting point, and a larger context length lets you keep more.
Long-term memory is the facts file. The system prompt reads it at startup, so facts saved in one session are in the model’s context from the first message of the next:
The prompt also sets the assistant’s behavior: search first, read only what is needed, cite path:line, and say so when the files lack the answer. It tells the model it can call several tools and keep going until it has what it needs.
Finish with the entry point, which takes the folder to search as an optional argument:
main sets the root, builds the system prompt, and reads input in a loop. After each answer it trims the history, so a long session stays inside the context window.
Everything is in place, so point the assistant at a project folder and run it:
Then try prompts that exercise each tool, and compare the [tool] lines the assistant prints with what you expect. The [tool] lines are the part to watch, since they show which tool the model chose and what it passed. The model’s wording will vary from run to run, and the tool lines show whether its choices make sense.
Small local models make more mistakes with tools than large hosted ones, so a few habits help. Read the tool log after each question and compare the arguments with what you asked. When the model picks the wrong tool, rewrite that tool’s docstring before you modify the prompt, and keep the tool list short, since a handful of tools with distinct jobs are easier to choose from than twelve that overlap. Also keep a short list of prompts with the tool each should trigger, and rerun it after any change to the model, prompt, or docstrings. If you add a tool that edits or deletes files, ask the user for approval inside run_tool before the function runs.
You now have a working local agent, albeit a simple one. The tools check their paths, bound their results, and describe themselves. The loop runs every requested tool and turns failures into text the model can act on. Memory comes in two forms: a trimmed message list for the current session and a facts file that the system prompt loads for the next one.
Pointing the assistant at another project you’re working on is the best next test, and your tool log will show where the docstrings need work. From there, a few extensions fit naturally:
Finally, run your test prompts against a few local models and keep the one that chooses tools most reliably on your hardware.