On this article, you’ll discover ways to construct a neighborhood AI agent in Python that makes use of Ollama and Qwen3 to name instruments that search, learn, and keep in mind data in a venture folder.
Matters we are going to cowl embrace:
- Tips on how to arrange Ollama with a tool-capable mannequin and a context size giant sufficient for agent workflows.
- How the tool-calling alternate works, and learn how to write protected, size-limited instruments as plain Python capabilities.
- Tips on how to construct the agent loop and add short-term and long-term reminiscence to the assistant.

Introduction
A language mannequin can generate textual content, cause via an issue, and comply with directions. To work with information in your laptop, although, it wants a solution to work together with them. Device calling offers that connection. It lets a mannequin request an motion, similar to looking out a folder or studying a doc, and use the end result to determine what to do subsequent.
Put that functionality inside a loop, and you’ve got the muse of an AI agent. On this article, we’ll construct one from scratch: a venture assistant that runs regionally utilizing Python and Ollama. It’ll search and browse information, maintain observe of helpful data, and use reminiscence throughout interactions. The mannequin, information, and dialog all keep in your machine, with no API key required.
This text covers:
- Establishing Ollama, together with the context size setting that brokers depend upon
- Understanding how the tool-calling alternate works
- Designing and writing instruments to go looking, learn, and keep in mind
- Constructing the agent loop, including short-term and long-term reminiscence, and testing the end result
You may get the code from this GitHub repository.
Step 1: Setting Up Ollama and a Mannequin That Can Use Instruments
Ollama allows you to obtain and run open fashions regionally. We’ll use it to run Qwen3, whereas the Ollama Python package deal will deal with communication between the mannequin and our code.
Begin by putting in Ollama from its official obtain web page. Ensure you have a current model of Python put in, ideally Python 3.10 or newer.
Subsequent, obtain Qwen3 with 4B parameters:
Qwen3 helps device calling. The obtain is roughly 2.5 GB.
As soon as the obtain finishes, begin a chat to confirm that the mannequin is working:
It is best to now be capable to work together with the mannequin in your terminal. Sort /bye if you find yourself able to exit.
With the mannequin put in, create a venture listing and arrange a digital atmosphere:
|
mkdir native–agent && cd native–agent python –m venv .venv supply .venv/bin/activate pip set up ollama |
The digital atmosphere retains the venture’s Python dependencies separate from the remainder of your system. The ollama package deal offers the shopper our code will use to ship messages and deal with device calls.
By default, the shopper connects to the Ollama server at localhost:11434. In case your Python script stories a connection error, open one other terminal, begin the server with ollama serve, and run the script once more.
Configuring the Context Size
Context size determines how a lot textual content the mannequin can course of in a single dialog. This issues when constructing an agent as a result of the dialog consists of device definitions, earlier messages, and gear outcomes. As these accumulate, the context window fills up.
Ollama selects a default context size primarily based on out there GPU reminiscence:
- On methods with lower than 24 GiB of VRAM, the default is 4K tokens.
- For agent workflows, Ollama recommends a bigger context size of a minimum of 64K tokens. Nevertheless, Qwen3-4B has a local context of 32,768 tokens, so we are going to set it to 32K. That is sufficient for this assistant, as a result of its device outcomes are size-limited and it retains solely the final six turns of dialog.
You possibly can modify this utilizing the context size setting within the Ollama app. Alternatively, cease any working Ollama server and restart it with the specified context size:
|
OLLAMA_CONTEXT_LENGTH=32000 ollama serve |
This units the context size to 32K tokens for that server session.
A bigger context window requires extra reminiscence, so test how the mannequin is working after it hundreds:
Take a look at the PROCESSOR column to substantiate that the mannequin is utilizing the GPU. In case your {hardware} can not accommodate a 32K-token context, use the biggest context size your system can assist. Holding device outputs concise will even assist handle reminiscence utilization and depart extra room for the dialog.
Step 2: Understanding the Device-Calling Trade
The mannequin doesn’t run something itself. When it decides a device would assist, it replies with a structured request that names the device and its arguments, your code runs the perform, and the end result goes again to the mannequin as a brand new message.

The next 4 message roles make up the dialog:
| Function | Written by | Objective |
|---|---|---|
| system | You | Units the assistant’s habits |
| person | The particular person | Asks a query or provides an instruction |
| assistant | The mannequin | Solutions, or requests device calls in tool_calls |
| device | Your code | Returns the results of one device name |
Every device name carries a reputation and an arguments dictionary, and a single reply can include a number of calls, every of which wants its personal end result. A flip can even cycle via the final two roles many instances: the mannequin searches, reads what the search discovered, searches once more, and solely then solutions. The loop in Step 5 handles that cycle.
Step 3: Designing Instruments for a Undertaking Assistant
The assistant solutions questions on a folder that holds a small Python venture: its code, README, changelog, and notes. I recommend you first do this assistant on a venture with an analogous construction, or create one and code alongside. The mannequin ought to discover the precise strains with out ever receiving the entire folder, so we give it the next 5 instruments:
list_filesreveals what’s in a folder.search_filesfinds strains that include a phrase or phrase.read_filereads a spread of strains from one file.recent_fileslists what modified in the previous few days.keep in mindshops a reality for future periods.
The next ideas determine how we write them. The mannequin provides the paths, so each path is checked in opposition to the foundation folder earlier than use. Solely keep in mind writes something, and it writes one small file exterior your venture, which leaves the opposite 4 read-only. A restrict on matches, strains, and characters bounds each end result, so the context window can not replenish from a single name. And each failure comes again as textual content, similar to “that path is exterior the folder”, which provides the mannequin an opportunity to appropriate itself.
Step 4: Writing the Instruments
Ollama’s Python library builds every device’s schema from the perform’s title, kind hints, and docstring, so plain capabilities work as instruments. The mannequin chooses a device from that description alone, which makes the docstring an important a part of every perform: say what the device returns and describe each argument. The subsections under construct assistant.py from the highest.
Setting Up the File and Its Settings
Begin the file with the imports and a handful of settings that the instruments 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.residence() / “.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 match with. It defaults to the present listing, and most important replaces it with the folder you cross on the command line. TEXT_SUFFIXES lists the file varieties the instruments will learn, so add different plain-text codecs there. MEMORY_FILE sits in your house listing, exterior the venture folder, so a search by no means finds it. MAX_RESULTS and MAX_TOOL_CHARS are limits I selected for what number of matches and what number of characters a single device end result can carry, and you need to tune them to your context window.
Holding the Mannequin Contained in the Folder
The mannequin writes the paths it passes to instruments, and nothing stops it from writing ../../secrets and techniques.txt or an absolute path. Two helpers maintain each file operation inside the foundation:
|
def safe_path(relative: str) -> Path: path = (ROOT / relative).resolve() if not path.is_relative_to(ROOT): increase ValueError(“that path is exterior the folder”) return path
def text_files(): for path in sorted(ROOT.rglob(“*”)): components = path.relative_to(ROOT).components if any(half.startswith(“.”) for half in components): proceed if path.is_file() and path.suffix.decrease() in TEXT_SUFFIXES: if path.resolve().is_relative_to(ROOT): yield path |
safe_path joins the requested path to the foundation and resolves it, which collapses .. and follows symbolic hyperlinks, after which rejects any end result that falls exterior ROOT. An absolute path replaces the foundation when joined, so it fails the identical test. text_files walks the entire folder in sorted order so outcomes are secure, and skips hidden directories, information with different extensions, and information whose symlink leads exterior the foundation. The search and recent-files instruments each use it.
Itemizing Recordsdata
The primary device provides the mannequin a means to go searching earlier than it searches:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
def list_files(subdirectory: str = “.”) -> str: “”“Listing the folders and textual content information instantly inside a folder, with file sizes.
Args: subdirectory: The folder to checklist, relative to the foundation. Use “.” for the highest degree. ““” strive: folder = safe_path(subdirectory) besides ValueError as error: return f“Error: {error}.” if not folder.is_dir(): return f“Error: ‘{subdirectory}’ will not be a folder.” strains = [] for path in sorted(folder.iterdir()): if path.title.startswith(“.”) or not path.resolve().is_relative_to(ROOT): proceed if path.is_dir(): strains.append(f“{path.title}/”) elif path.suffix.decrease() in TEXT_SUFFIXES: strains.append(f“{path.title} ({path.stat().st_size} bytes)”) return “n”.be a part of(strains) or “The folder has no readable information.” |
It returns solely the direct kids of 1 folder, with a trailing slash on directories and a dimension for every readable file. Hidden entries and hyperlinks that depart the foundation are neglected, and the docstring tells the mannequin to cross "." for the highest degree as a result of the schema requires an argument. Errors come again as strings in the identical means, so the loop passes them to the mannequin like every other end result.
Looking Throughout Recordsdata
Search is the device the mannequin will use most, and it must return sufficient to quote with out returning every little thing:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
def search_files(question: str, extension: str = “”) -> str: “”“Search each textual content file for strains that include a phrase or phrase, ignoring case. Every match is returned as path:line: textual content.
Args: question: The phrase or phrase to search for extension: Optionally available file kind filter similar to “.md“. Go away empty to go looking all textual content information. ““” needle = question.strip().decrease() if not needle: return “Error: the question is empty.” matches = [] for path in text_files(): if extension and path.suffix.decrease() != extension.decrease(): proceed textual content = path.read_text(errors=“change”) for quantity, line in enumerate(textual content.splitlines(), begin=1): if needle in line.decrease(): matches.append(f“{path.relative_to(ROOT)}:{quantity}: {line.strip()[:160]}”) if len(matches) == MAX_RESULTS: return “n”.be a part of(matches) + “n[stopped at the match limit; narrow the query]” return “n”.be a part of(matches) or f“No line accommodates ‘{question}’.” |
The match is a case-insensitive substring take a look at, which is much less intelligent than an everyday expression and much simpler for a small mannequin to make use of appropriately. Every hit comes again as path:line: textual content, with the textual content lower to 160 characters, and when the outcomes attain MAX_RESULTS the perform stops and appends a notice asking for a narrower question, so the restrict itself tells the mannequin what to do subsequent. An empty question is rejected, since it might match each line. As a result of every hit carries a file and line quantity, the mannequin can cite it, and the identical device solutions code questions similar to the place a perform is used.
Studying a Vary of Traces
As soon as a search has discovered the precise file, the mannequin reads solely the half it wants:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
def read_file(path: str, start_line: int = 1, max_lines: int = 80) -> str: “”“Learn a part of a textual content file, with line numbers.
Args: path: The file path relative to the foundation, as proven by list_files or search_files start_line: The primary line to learn, counting from 1 max_lines: Probably the most strains to return ““” strive: file = safe_path(path) besides ValueError as error: return f“Error: {error}.” if not file.is_file() or file.suffix.decrease() not in TEXT_SUFFIXES: return f“Error: ‘{path}’ will not be a readable textual content file.” strains = file.read_text(errors=“change”).splitlines() begin = max(int(start_line), 1) chunk = strains[start – 1 : start – 1 + int(max_lines)] if not chunk: return f“No strains at that place. The file has {len(strains)} strains.” numbered = “n”.be a part of(f“{begin + i}: {line}” for i, line in enumerate(chunk)) return f“{numbered}n[lines {start}-{start + len(chunk) – 1} of {len(lines)}]” |
The end result carries line numbers and a footer that provides the vary returned and the file size, similar to [lines 15-22 of 22], so the mannequin is aware of whether or not extra of the file exists and might ask for the subsequent vary. The int() calls guard in opposition to a mannequin that passes numbers as textual content, and run_tool in Step 5 turns a conversion failure into an error message. A begin place previous the top of the file will get its personal message, which saves a complicated empty end result.
Discovering Current Adjustments
Some questions depend upon time, and a textual content search can not reply them:
|
def recent_files(days: int = 7) -> str: “”“Listing the textual content information modified inside the final variety of days, latest first.
Args: days: What number of days again to look ““” cutoff = time.time() – int(days) * 86400 discovered = [(p.stat().st_mtime, p) for p in text_files() if p.stat().st_mtime >= cutoff] discovered.kind(reverse=True) strains = [ f“{datetime.fromtimestamp(stamp):%Y-%m-%d %H:%M} {path.relative_to(ROOT)}” for stamp, path in found[:MAX_RESULTS] ] return “n”.be a part of(strains) or f“No information modified within the final {days} days.” |
The perform compares every file’s modification time with a cutoff and returns the most recent information first, capped at MAX_RESULTS, which solutions “what was I engaged on this week?” with out the mannequin guessing at filenames.
Storing Information
The final device is the one one which writes:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
def load_memory() -> checklist: if MEMORY_FILE.exists(): return json.hundreds(MEMORY_FILE.read_text()) return []
def keep in mind(reality: str) -> str: “”“Retailer a reality concerning the person or their work so it’s out there in future periods.
Args: reality: One quick, self-contained assertion, similar to “The exams run with pytest –q“ ““” info = load_memory() if reality not in info: info.append(reality) MEMORY_FILE.write_text(json.dumps(info, indent=2)) return “Remembered.” |
keep in mind appends a brief reality to a JSON checklist and skips duplicates, and load_memory reads the checklist again. The docstring asks for one self-contained assertion, as a result of a proven fact that is determined by the present dialog is not going to make sense in a later session. Step 6 reveals how the info attain the mannequin.
Registering the Instruments
A dictionary from device title to perform ties the 5 instruments collectively:
|
TOOLS = { perform.__name__: perform for perform in [list_files, search_files, read_file, recent_files, remember] } |
The values go to the mannequin because the checklist of instruments in each chat name, and the keys let the loop discover the perform that matches every device request.
Step 5: Constructing the Agent Loop
With the instruments written, the loop connects them to the mannequin. It calls the mannequin, runs any instruments the mannequin requests, and calls the mannequin once more with the outcomes, till a reply arrives with no device calls. We write two helpers to make that protected: clip cuts any end result that exceeds the character funds, and run_tool turns each failure right into a message the mannequin can learn:
|
def clip(textual content: str) -> str: if len(textual content) <= MAX_TOOL_CHARS: return textual content return textual content[:MAX_TOOL_CHARS] + “n[output cut; ask for a narrower range]”
def run_tool(title: str, arguments: dict) -> str: perform = TOOLS.get(title) if perform is None: return f“Error: unknown device ‘{title}’. Obtainable instruments: {‘, ‘.be a part of(TOOLS)}.” strive: return clip(str(perform(**arguments))) besides (TypeError, ValueError) as error: return f“Error: dangerous arguments ({error}).” |
run_tool covers three failures: an unknown device title (the error lists the instruments that exist), arguments with the mistaken names, and arguments with the mistaken varieties. In every case the mannequin receives an error string and might strive once more whereas this system retains working.
Now the loop itself:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
def run_turn(messages: checklist, max_steps: int = 8) -> str: for _ in vary(max_steps): response = chat( mannequin=MODEL, messages=messages, instruments=checklist(TOOLS.values()), choices={“temperature”: 0}, ) messages.append(response.message)
if not response.message.tool_calls: return response.message.content material
for name in response.message.tool_calls: title = name.perform.title arguments = name.perform.arguments print(f” [tool] {title}({arguments})”) messages.append( {“function”: “device”, “tool_name”: title, “content material”: run_tool(title, arguments)} )
return “Stopped: the agent used too many device steps.” |
run_turn appends the mannequin’s reply to messages first, as a result of a device message solely is sensible after the assistant message that requested it. It then handles each entry in tool_calls, so parallel requests work, and every end result carries a tool_name that ties it to its name. The [tool] line prints every request, which is how you notice invented arguments. Setting temperature to 0 via choices makes device decisions extra repeatable, and max_steps stops a mannequin that retains calling instruments and by no means solutions.
Step 6: Including Reminiscence
A mannequin retains nothing between calls, so reminiscence is the historical past your code sends again every time. This assistant makes use of two easy reminiscence mechanisms.

Quick-term reminiscence is the messages checklist. As a result of the loop appends to it, the mannequin can reply a follow-up similar to “and what did that file say concerning the deadline?” The checklist grows with each flip, so a trim perform retains the system immediate and the previous few person turns:
|
def role_of(message) -> str: return message[“role”] if isinstance(message, dict) else message.function
def trim(messages: checklist, keep_turns: int = 6) -> checklist: 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 solely at a person message, so a device request stays along with its end result. Slicing between the 2 would go away the mannequin with a end result that no request explains. Six turns is a place to begin, and a bigger context size allows you to maintain extra.
Lengthy-term reminiscence is the info file. The system immediate reads it at startup, so info saved in a single session are within the mannequin’s context from the primary message of the subsequent:
|
def build_system_prompt() -> str: immediate = ( “You’re an assistant for a folder of the person’s personal venture information. “ “Search earlier than you learn, and browse solely the strains you want. “ “Reply from what the information say, and cite every declare as path:line. “ “If the information don’t include the reply, say so. “ “You possibly can name a number of instruments in a single flip, and you’ll maintain calling instruments “ “till you’ve gotten what you want. “ “Name keep in mind solely when the person asks you to recollect one thing.” ) info = load_memory() if info: immediate += “nnWhat you already know concerning the person:n” + “n”.be a part of(f“- {f}” for f in info) return immediate |
The immediate additionally units the assistant’s habits: search first, learn solely what is required, cite path:line, and say so when the information lack the reply. It tells the mannequin it may well name a number of instruments and maintain going till it has what it wants.
End with the entry level, which takes the folder to go looking as an elective argument:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
def most important(): world ROOT if len(sys.argv) > 1: ROOT = Path(sys.argv[1]).resolve() print(f“Assistant prepared. Folder: {ROOT}”) messages = [{“role”: “system”, “content”: build_system_prompt()}] whereas True: user_input = enter(“You: “).strip() if user_input in {“exit”, “give up”}: break messages.append({“function”: “person”, “content material”: user_input}) print(“Agent:”, run_turn(messages)) messages[:] = trim(messages)
if __name__ == “__main__”: most important() |
most important units the foundation, builds the system immediate, and reads enter in a loop. After every reply it trims the historical past, so an extended session stays contained in the context window.
Step 7: Operating and Testing the Assistant
Every little thing is in place, so level the assistant at a venture folder and run it:
|
python assistant.py ~/my–venture |
Then strive prompts that train every device, and evaluate the [tool] strains the assistant prints with what you anticipate. The [tool] strains are the half to observe, since they present which device the mannequin selected and what it handed. The mannequin’s wording will range from run to run, and the device strains present whether or not its decisions make sense.
Small native fashions make extra errors with instruments than giant hosted ones, so just a few habits assist. Learn the device log after every query and evaluate the arguments with what you requested. When the mannequin picks the mistaken device, rewrite that device’s docstring earlier than you modify the immediate, and maintain the device checklist quick, since a handful of instruments with distinct jobs are simpler to select from than twelve that overlap. Additionally maintain a brief checklist of prompts with the device every ought to set off, and rerun it after any change to the mannequin, immediate, or docstrings. In case you add a device that edits or deletes information, ask the person for approval inside run_tool earlier than the perform runs.
Wrapping Up
You now have a working native agent, albeit a easy one. The instruments test their paths, certain their outcomes, and describe themselves. The loop runs each requested device and turns failures into textual content the mannequin can act on. Reminiscence is available in two types: a trimmed message checklist for the present session and a info file that the system immediate hundreds for the subsequent one.
Pointing the assistant at one other venture you’re engaged on is one of the best subsequent take a look at, and your device log will present the place the docstrings want work. From there, just a few extensions match naturally:
- Substring search misses paraphrases, and Ollama serves embedding fashions via its embed name, so a device that finds passages by similarity would cowl that hole.
- A write device, similar to appending to a notes file with an approval immediate earlier than every write, would make the assistant helpful for seize in addition to retrieval.
- Streaming lets lengthy solutions seem as they’re generated, and the Ollama docs present learn how to acquire the pondering, content material, and gear calls from a stream.
Lastly, run your take a look at prompts in opposition to just a few native fashions and maintain the one which chooses instruments most reliably in your {hardware}.

