How to Build Tool-Calling Local AI Agents in Python A tutorial published on GitHub (balapriyac/tool-calling-local-ai-agent) shows developers how to build a local tool-calling AI agent in Python using Ollama and the 4B-parameter Qwen3 model, which supports tool calling and downloads at approximately 2.5 GB. The guide instructs users to set a context length of at least 64K tokens for agent workflows, noting Ollama defaults to 4K tokens on systems with less than 24 GiB of VRAM while Qwen3-4B has a native context of 32,768 tokens. The agent searches, reads and remembers files in a project folder, with the model, files and conversation staying on the user's machine and no API key required. 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 https://www.ibm.com/think/topics/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 https://cloud.google.com/discover/what-are-ai-agents . In this article, we’ll build one from scratch: a project assistant that runs locally using Python and Ollama https://ollama.com/ . 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 https://github.com/balapriyac/tool-calling-local-ai-agent . 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 https://ollama.com/download . 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 1 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 1 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 1234 mkdir local-agent && cd local-agentpython -m venv .venvsource .venv/bin/activatepip 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 https://docs.ollama.com/context-length : - 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 https://huggingface.co/Qwen/Qwen3-4B , 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 https://docs.ollama.com/context-length setting-context-length . Alternatively, stop any running Ollama server and restart it with the desired context length: OLLAMA CONTEXT LENGTH=32000 ollama serve 1 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 1 ollama ps Look at the PROCESSOR column to confirm that the model is using the GPU https://docs.ollama.com/context-length check-allocated-context-length-and-model-offloading . 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 https://github.com/balapriyac/tool-calling-local-ai-agent/blob/main/assistant.py Setting Up the File and Its Settings Start the file with the imports and a handful of settings that the tools share: python 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 1234567891011121314 import jsonimport sysimport timefrom datetime import datetimefrom 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 = 20MAX 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: php 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 123456789101112131415 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: php 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." 123456789101112131415161718192021 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: php 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}'." 12345678910111213141516171819202122 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: php 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 } " 123456789101112131415161718192021 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: php 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 found.sort reverse=True lines = f"{datetime.fromtimestamp stamp :%Y-%m-%d %H:%M} {path.relative to ROOT }" for stamp, path in found :MAX RESULTS return "\n".join lines or f"No files changed in the last {days} days." 1234567891011121314 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 found.sort reverse=True lines = f"{datetime.fromtimestamp stamp :%Y-%m-%d %H:%M} {path.relative to ROOT }" for stamp, path in found :MAX RESULTS return "\n".join lines or f"No files changed in the last {days} days." 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. Storing Facts The last tool is the only one that writes: php def load memory - list: if MEMORY FILE.exists : return json.loads MEMORY FILE.read text return def remember fact: str - str: """Store a fact about the user or their work so it is available in future sessions. Args: fact: One short, self-contained statement, such as "The tests run with pytest -q" """ facts = load memory if fact not in facts: facts.append fact MEMORY FILE.write text json.dumps facts, indent=2 return "Remembered." 1234567891011121314151617 def load memory - list: if MEMORY FILE.exists : return json.loads MEMORY FILE.read text return def remember fact: str - str: """Store a fact about the user or their work so it is available in future sessions. Args: fact: One short, self-contained statement, such as "The tests run with pytest -q" """ facts = load memory if fact not in facts: facts.append fact MEMORY FILE.write text json.dumps facts, indent=2 return "Remembered." 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. Registering the Tools A dictionary from tool name to function ties the five tools together: TOOLS = { function. name : function for function in list files, search files, read file, recent files, remember } 1234 TOOLS = { function. name : function for function in list files, search files, read file, recent files, remember } 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. Step 5: Building the Agent Loop 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: php def clip text: str - str: if len text <= MAX TOOL CHARS: return text return text :MAX TOOL CHARS + "\n output cut; ask for a narrower range " def run tool name: str, arguments: dict - str: function = TOOLS.get name if function is None: return f"Error: unknown tool '{name}'. Available tools: {', '.join TOOLS }." try: return clip str function arguments except TypeError, ValueError as error: return f"Error: bad arguments {error} ." 1234567891011121314 def clip text: str - str: if len text <= MAX TOOL CHARS: return text return text :MAX TOOL CHARS + "\n output cut; ask for a narrower range " def run tool name: str, arguments: dict - str: function = TOOLS.get name if function is None: return f"Error: unknown tool '{name}'. Available tools: {', '.join TOOLS }." try: return clip str function arguments except TypeError, ValueError as error: return f"Error: bad arguments {error} ." 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. Now the loop itself: php def run turn messages: list, max steps: int = 8 - str: for in range max steps : response = chat model=MODEL, messages=messages, tools=list TOOLS.values , options={"temperature": 0}, messages.append response.message if not response.message.tool calls: return response.message.content for call in response.message.tool calls: name = call.function.name arguments = call.function.arguments print f" tool {name} {arguments} " messages.append {"role": "tool", "tool name": name, "content": run tool name, arguments } return "Stopped: the agent used too many tool steps." 12345678910111213141516171819202122 def run turn messages: list, max steps: int = 8 - str: for in range max steps : response = chat model=MODEL, messages=messages, tools=list TOOLS.values , options={"temperature": 0}, messages.append response.message if not response.message.tool calls: return response.message.content for call in response.message.tool calls: name = call.function.name arguments = call.function.arguments print f" tool {name} {arguments} " messages.append {"role": "tool", "tool name": name, "content": run tool name, arguments } return "Stopped: the agent used too many tool steps." 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. Step 6: Adding Memory 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: php def role of message - str: return message "role" if isinstance message, dict else message.role def trim messages: list, keep turns: int = 6 - list: user positions = i for i, m in enumerate messages if role of m == "user" if len user positions <= keep turns: return messages return messages 0 + messages user positions -keep turns : 123456789 def role of message - str: return message "role" if isinstance message, dict else message.role def trim messages: list, keep turns: int = 6 - list: user positions = i for i, m in enumerate messages if role of m == "user" if len user positions <= keep turns: return messages return messages 0 + messages user positions -keep 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: php def build system prompt - str: prompt = "You are an assistant for a folder of the user's own project files. " "Search before you read, and read only the lines you need. " "Answer from what the files say, and cite each claim as path:line. " "If the files do not contain the answer, say so. " "You can call several tools in one turn, and you can keep calling tools " "until you have what you need. " "Call remember only when the user asks you to remember something." facts = load memory if facts: prompt += "\n\nWhat you know about the user:\n" + "\n".join f"- {f}" for f in facts return prompt 1234567891011121314 def build system prompt - str: prompt = "You are an assistant for a folder of the user's own project files. " "Search before you read, and read only the lines you need. " "Answer from what the files say, and cite each claim as path:line. " "If the files do not contain the answer, say so. " "You can call several tools in one turn, and you can keep calling tools " "until you have what you need. " "Call remember only when the user asks you to remember something." facts = load memory if facts: prompt += "\n\nWhat you know about the user:\n" + "\n".join f"- {f}" for f in facts return prompt 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: python def main : global ROOT if len sys.argv 1: ROOT = Path sys.argv 1 .resolve print f"Assistant ready. Folder: {ROOT}" messages = {"role": "system", "content": build system prompt } while True: user input = input "You: " .strip if user input in {"exit", "quit"}: break messages.append {"role": "user", "content": user input} print "Agent:", run turn messages messages : = trim messages if name == " main ": main 1234567891011121314151617 def main : global ROOT if len sys.argv 1: ROOT = Path sys.argv 1 .resolve print f"Assistant ready. Folder: {ROOT}" messages = {"role": "system", "content": build system prompt } while True: user input = input "You: " .strip if user input in {"exit", "quit"}: break messages.append {"role": "user", "content": user input} print "Agent:", run turn messages messages : = trim messages if name == " main ": main 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. Step 7: Running and Testing the Assistant Everything is in place, so point the assistant at a project folder and run it: python assistant.py ~/my-project 1 python assistant.py ~/my-project 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. Wrapping Up 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: - Substring search misses paraphrases, and Ollama serves embedding models through its embed call, so a tool that finds passages by similarity would cover that gap. - A write tool, such as appending to a notes file with an approval prompt before each write, would make the assistant useful for capture as well as retrieval. - Streaming lets long answers appear as they are generated, and the Ollama docs show how to collect the thinking, content, and tool calls from a stream https://docs.ollama.com/capabilities/streaming . Finally, run your test prompts against a few local models and keep the one that chooses tools most reliably on your hardware.