{"slug": "how-to-build-tool-calling-local-ai-agents-in-python", "title": "How to Build Tool-Calling Local AI Agents in Python", "summary": "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.", "body_md": "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.\n\nTopics we will cover include:\n\n- How to set up Ollama with a tool-capable model and a context length large enough for agent workflows.\n- How the tool-calling exchange works, and how to write safe, size-limited tools as plain Python functions.\n- How to build the agent loop and add short-term and long-term memory to the assistant.\n\n## Introduction\n\nA 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.\n\nPut 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.\n\nThis article covers:\n\n- Setting up Ollama, including the context length setting that agents depend on\n- Understanding how the tool-calling exchange works\n- Designing and writing tools to search, read, and remember\n- Building the agent loop, adding short-term and long-term memory, and testing the result\n\nYou can get the code from [this GitHub repository](https://github.com/balapriyac/tool-calling-local-ai-agent).\n\n## Step 1: Setting Up Ollama and a Model That Can Use Tools\n\nOllama 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.\n\nStart 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.\n\nNext, download Qwen3 with 4B parameters:\n\n```\nollama pull qwen3:4b\n\n1\n\nollama pull qwen3:4b\n```\n\nQwen3 supports tool calling. The download is approximately 2.5 GB.\n\nOnce the download finishes, start a chat to verify that the model is working:\n\n```\nollama run qwen3:4b\n\n1\n\nollama run qwen3:4b\n```\n\nYou should now be able to interact with the model in your terminal. Type `/bye` when you are ready to exit.\n\nWith the model installed, create a project directory and set up a virtual environment:\n\n```\nmkdir local-agent && cd local-agent\npython -m venv .venv\nsource .venv/bin/activate\npip install ollama\n\n1234\n\nmkdir local-agent && cd local-agentpython -m venv .venvsource .venv/bin/activatepip install ollama\n```\n\nThe 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.\n\nBy 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.\n\n### Configuring the Context Length\n\nContext 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.\n\nOllama selects a [default context length based on available GPU memory](https://docs.ollama.com/context-length):\n\n- On systems with less than 24 GiB of VRAM, the default is 4K tokens.\n- 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.\n\nYou 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:\n\n```\nOLLAMA_CONTEXT_LENGTH=32000 ollama serve\n\n1\n\nOLLAMA_CONTEXT_LENGTH=32000 ollama serve\n```\n\nThis sets the context length to 32K tokens for that server session.\n\nA larger context window requires more memory, so check how the model is running after it loads:\n\n```\nollama ps\n\n1\n\nollama ps\n```\n\n[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.\n\n## Step 2: Understanding the Tool-Calling Exchange\n\nThe 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.\n\nThe following four message roles make up the conversation:\n\n| Role | Written by | Purpose | \n|---|---|---|\n| system | You | Sets the assistant’s behavior | \n| user | The person | Asks a question or gives an instruction | \n| assistant | The model | Answers, or requests tool calls in tool_calls | \n| tool | Your code | Returns the result of one tool call | \n\nEach 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.\n\n## Step 3: Designing Tools for a Project Assistant\n\nThe 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:\n\n- `list_files` shows what is in a folder.\n- `search_files` finds lines that contain a word or phrase.\n- `read_file` reads a range of lines from one file.\n- `recent_files` lists what changed in the last few days.\n- `remember` stores a fact for future sessions.\n\nThe 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.\n\n## Step 4: Writing the Tools\n\nOllama’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)\n\n### Setting Up the File and Its Settings\n\nStart the file with the imports and a handful of settings that the tools share:\n\n``` python\nimport json\nimport sys\nimport time\nfrom datetime import datetime\nfrom pathlib import Path\n\nfrom ollama import chat\n\nMODEL = \"qwen3:4b\"\nROOT = Path(\".\").resolve()\nMEMORY_FILE = Path.home() / \".doc_assistant_memory.json\"\nTEXT_SUFFIXES = {\".md\", \".txt\", \".csv\", \".json\", \".py\", \".rst\"}\nMAX_RESULTS = 20\nMAX_TOOL_CHARS = 3000\n\n1234567891011121314\n\nimport 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\n```\n\n`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.\n\n### Keeping the Model Inside the Folder\n\nThe 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:\n\n``` php\ndef safe_path(relative: str) -> Path:\n    path = (ROOT / relative).resolve()\n    if not path.is_relative_to(ROOT):\n        raise ValueError(\"that path is outside the folder\")\n    return path\n\ndef text_files():\n    for path in sorted(ROOT.rglob(\"*\")):\n        parts = path.relative_to(ROOT).parts\n        if any(part.startswith(\".\") for part in parts):\n            continue\n        if path.is_file() and path.suffix.lower() in TEXT_SUFFIXES:\n            if path.resolve().is_relative_to(ROOT):\n                yield path\n\n123456789101112131415\n\ndef 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\n```\n\n`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.\n\n### Listing Files\n\nThe first tool gives the model a way to look around before it searches:\n\n``` php\ndef list_files(subdirectory: str = \".\") -> str:\n    \"\"\"List the folders and text files directly inside a folder, with file sizes.\n\n    Args:\n        subdirectory: The folder to list, relative to the root. Use \".\" for the top level.\n    \"\"\"\n    try:\n        folder = safe_path(subdirectory)\n    except ValueError as error:\n        return f\"Error: {error}.\"\n    if not folder.is_dir():\n        return f\"Error: '{subdirectory}' is not a folder.\"\n    lines = []\n    for path in sorted(folder.iterdir()):\n        if path.name.startswith(\".\") or not path.resolve().is_relative_to(ROOT):\n            continue\n        if path.is_dir():\n            lines.append(f\"{path.name}/\")\n        elif path.suffix.lower() in TEXT_SUFFIXES:\n            lines.append(f\"{path.name}  ({path.stat().st_size} bytes)\")\n    return \"\\n\".join(lines) or \"The folder has no readable files.\"\n\n123456789101112131415161718192021\n\ndef 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.\"\n```\n\nIt 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.\n\n### Searching Across Files\n\nSearch is the tool the model will use most, and it needs to return enough to cite without returning everything:\n\n``` php\ndef search_files(query: str, extension: str = \"\") -> str:\n    \"\"\"Search every text file for lines that contain a word or phrase, ignoring case.\n    Each match is returned as path:line: text.\n\n    Args:\n        query: The word or phrase to look for\n        extension: Optional file type filter such as \".md\". Leave empty to search all text files.\n    \"\"\"\n    needle = query.strip().lower()\n    if not needle:\n        return \"Error: the query is empty.\"\n    matches = []\n    for path in text_files():\n        if extension and path.suffix.lower() != extension.lower():\n            continue\n        text = path.read_text(errors=\"replace\")\n        for number, line in enumerate(text.splitlines(), start=1):\n            if needle in line.lower():\n                matches.append(f\"{path.relative_to(ROOT)}:{number}: {line.strip()[:160]}\")\n                if len(matches) == MAX_RESULTS:\n                    return \"\\n\".join(matches) + \"\\n[stopped at the match limit; narrow the query]\"\n    return \"\\n\".join(matches) or f\"No line contains '{query}'.\"\n\n12345678910111213141516171819202122\n\ndef 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}'.\"\n```\n\nThe 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.\n\n### Reading a Range of Lines\n\nOnce a search has found the right file, the model reads only the part it needs:\n\n``` php\ndef read_file(path: str, start_line: int = 1, max_lines: int = 80) -> str:\n    \"\"\"Read part of a text file, with line numbers.\n\n    Args:\n        path: The file path relative to the root, as shown by list_files or search_files\n        start_line: The first line to read, counting from 1\n        max_lines: The most lines to return\n    \"\"\"\n    try:\n        file = safe_path(path)\n    except ValueError as error:\n        return f\"Error: {error}.\"\n    if not file.is_file() or file.suffix.lower() not in TEXT_SUFFIXES:\n        return f\"Error: '{path}' is not a readable text file.\"\n    lines = file.read_text(errors=\"replace\").splitlines()\n    start = max(int(start_line), 1)\n    chunk = lines[start - 1 : start - 1 + int(max_lines)]\n    if not chunk:\n        return f\"No lines at that position. The file has {len(lines)} lines.\"\n    numbered = \"\\n\".join(f\"{start + i}: {line}\" for i, line in enumerate(chunk))\n    return f\"{numbered}\\n[lines {start}-{start + len(chunk) - 1} of {len(lines)}]\"\n\n123456789101112131415161718192021\n\ndef 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)}]\"\n```\n\nThe 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.\n\n### Finding Recent Changes\n\nSome questions depend on time, and a text search cannot answer them:\n\n``` php\ndef recent_files(days: int = 7) -> str:\n    \"\"\"List the text files changed within the last number of days, newest first.\n\n    Args:\n        days: How many days back to look\n    \"\"\"\n    cutoff = time.time() - int(days) * 86400\n    found = [(p.stat().st_mtime, p) for p in text_files() if p.stat().st_mtime >= cutoff]\n    found.sort(reverse=True)\n    lines = [\n        f\"{datetime.fromtimestamp(stamp):%Y-%m-%d %H:%M}  {path.relative_to(ROOT)}\"\n        for stamp, path in found[:MAX_RESULTS]\n    ]\n    return \"\\n\".join(lines) or f\"No files changed in the last {days} days.\"\n\n1234567891011121314\n\ndef 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.\"\n```\n\nThe 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.\n\n### Storing Facts\n\nThe last tool is the only one that writes:\n\n``` php\ndef load_memory() -> list:\n    if MEMORY_FILE.exists():\n        return json.loads(MEMORY_FILE.read_text())\n    return []\n\ndef remember(fact: str) -> str:\n    \"\"\"Store a fact about the user or their work so it is available in future sessions.\n\n    Args:\n        fact: One short, self-contained statement, such as \"The tests run with pytest -q\"\n    \"\"\"\n    facts = load_memory()\n    if fact not in facts:\n        facts.append(fact)\n        MEMORY_FILE.write_text(json.dumps(facts, indent=2))\n    return \"Remembered.\"\n\n1234567891011121314151617\n\ndef 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.\"\n```\n\n`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.\n\n### Registering the Tools\n\nA dictionary from tool name to function ties the five tools together:\n\n```\nTOOLS = {\n    function.__name__: function\n    for function in [list_files, search_files, read_file, recent_files, remember]\n}\n\n1234\n\nTOOLS = {    function.__name__: function    for function in [list_files, search_files, read_file, recent_files, remember]}\n```\n\nThe 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.\n\n## Step 5: Building the Agent Loop\n\nWith 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:\n\n``` php\ndef clip(text: str) -> str:\n    if len(text) <= MAX_TOOL_CHARS:\n        return text\n    return text[:MAX_TOOL_CHARS] + \"\\n[output cut; ask for a narrower range]\"\n\ndef run_tool(name: str, arguments: dict) -> str:\n    function = TOOLS.get(name)\n    if function is None:\n        return f\"Error: unknown tool '{name}'. Available tools: {', '.join(TOOLS)}.\"\n    try:\n        return clip(str(function(**arguments)))\n    except (TypeError, ValueError) as error:\n        return f\"Error: bad arguments ({error}).\"\n\n1234567891011121314\n\ndef 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}).\"\n```\n\n`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.\n\nNow the loop itself:\n\n``` php\ndef run_turn(messages: list, max_steps: int = 8) -> str:\n    for _ in range(max_steps):\n        response = chat(\n            model=MODEL,\n            messages=messages,\n            tools=list(TOOLS.values()),\n            options={\"temperature\": 0},\n        )\n        messages.append(response.message)\n\n        if not response.message.tool_calls:\n            return response.message.content\n\n        for call in response.message.tool_calls:\n            name = call.function.name\n            arguments = call.function.arguments\n            print(f\"  [tool] {name}({arguments})\")\n            messages.append(\n                {\"role\": \"tool\", \"tool_name\": name, \"content\": run_tool(name, arguments)}\n            )\n\n    return \"Stopped: the agent used too many tool steps.\"\n\n12345678910111213141516171819202122\n\ndef 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.\"\n```\n\n`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.\n\n## Step 6: Adding Memory\n\nA model keeps nothing between calls, so memory is the history your code sends back each time. This assistant uses two simple memory mechanisms.\n\nShort-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:\n\n``` php\ndef role_of(message) -> str:\n    return message[\"role\"] if isinstance(message, dict) else message.role\n\ndef trim(messages: list, keep_turns: int = 6) -> list:\n    user_positions = [i for i, m in enumerate(messages) if role_of(m) == \"user\"]\n    if len(user_positions) <= keep_turns:\n        return messages\n    return [messages[0]] + messages[user_positions[-keep_turns]:]\n\n123456789\n\ndef 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]:]\n```\n\n`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.\n\nLong-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:\n\n``` php\ndef build_system_prompt() -> str:\n    prompt = (\n        \"You are an assistant for a folder of the user's own project files. \"\n        \"Search before you read, and read only the lines you need. \"\n        \"Answer from what the files say, and cite each claim as path:line. \"\n        \"If the files do not contain the answer, say so. \"\n        \"You can call several tools in one turn, and you can keep calling tools \"\n        \"until you have what you need. \"\n        \"Call remember only when the user asks you to remember something.\"\n    )\n    facts = load_memory()\n    if facts:\n        prompt += \"\\n\\nWhat you know about the user:\\n\" + \"\\n\".join(f\"- {f}\" for f in facts)\n    return prompt\n\n1234567891011121314\n\ndef 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\n```\n\nThe 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.\n\nFinish with the entry point, which takes the folder to search as an optional argument:\n\n``` python\ndef main():\n    global ROOT\n    if len(sys.argv) > 1:\n        ROOT = Path(sys.argv[1]).resolve()\n    print(f\"Assistant ready. Folder: {ROOT}\")\n    messages = [{\"role\": \"system\", \"content\": build_system_prompt()}]\n    while True:\n        user_input = input(\"You: \").strip()\n        if user_input in {\"exit\", \"quit\"}:\n            break\n        messages.append({\"role\": \"user\", \"content\": user_input})\n        print(\"Agent:\", run_turn(messages))\n        messages[:] = trim(messages)\n\nif __name__ == \"__main__\":\n    main()\n\n1234567891011121314151617\n\ndef 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()\n```\n\n`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.\n\n## Step 7: Running and Testing the Assistant\n\nEverything is in place, so point the assistant at a project folder and run it:\n\n```\npython assistant.py ~/my-project\n\n1\n\npython assistant.py ~/my-project\n```\n\nThen 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.\n\nSmall 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.\n\n## Wrapping Up\n\nYou 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.\n\nPointing 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:\n\n- 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.\n- 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.\n- 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) .\n\nFinally, run your test prompts against a few local models and keep the one that chooses tools most reliably on your hardware.", "url": "https://wpnews.pro/news/how-to-build-tool-calling-local-ai-agents-in-python", "canonical_source": "https://machinelearningmastery.com/how-to-build-tool-calling-local-ai-agents-in-python/", "published_at": "2026-11-23 11:00:23+00:00", "updated_at": "2026-11-23 13:46:03.359382+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "large-language-models", "developer-tools"], "entities": ["Ollama", "Qwen3", "Qwen3-4B", "Python", "GitHub"], "also_reported_by": [], "takeaway": "Ollama defaults to a 4K-token context on systems with under 24 GiB of VRAM, so raise it to at least 64K for agent workflows even though Qwen3-4B's native context is 32,768 tokens.", "recommendation": {"advice": "Raise Ollama's context length to at least 64K tokens before running tool-calling agents, since the 4K default on systems under 24 GiB of VRAM fills up with tool definitions and results.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/how-to-build-tool-calling-local-ai-agents-in-python", "markdown": "https://wpnews.pro/news/how-to-build-tool-calling-local-ai-agents-in-python.md", "text": "https://wpnews.pro/news/how-to-build-tool-calling-local-ai-agents-in-python.txt", "jsonld": "https://wpnews.pro/news/how-to-build-tool-calling-local-ai-agents-in-python.jsonld"}}