Building Your First AI Agent Fully Locally: Tool Calling from Scratch with Ollama A developer built a working tool-calling AI agent entirely on a local machine using the open-source qwen3:4b model served by Ollama on a GPU with 6GB of VRAM, with no API key, no cloud calls and no agent framework such as LangChain or LlamaIndex. The write-up stresses that the LLM never executes functions itself — it emits text requesting a call, and the developer's own loop runs the tool and reports the result back — and warns that Ollama silently drops the oldest tokens when the 8192-token context window overflows, potentially discarding the system prompt or tool definitions. The author argues small models are better for learning because a 4B model fails visibly on badly written tool descriptions or sloppy loops that a frontier model would paper over. If you have spent any time on LinkedIn or tech Twitter lately, you must have noticed that everything is an “agent” now. Coding agents, research agents, browser agents, agents that book your flights and agents that reply to your emails. But the moment you sit down to actually build one, almost every tutorial starts the same way. Create an account, generate an API key, add your card. I ran into exactly this. I had a notebook ready to go, and the provider told me I needed credits to run it. So I rebuilt the whole thing to run on my own machine. An open source model, served by Ollama, running on a GPU with just 6GB of VRAM. No API key, nothing leaves my laptop, and I can run it as many times as I want without thinking about a bill. In this article, lets build a tool calling AI agent completely from scratch. No LangChain, no LlamaIndex, no agent framework of any kind. Just the raw loop, so you can see exactly what happens at every single step. By the end you will understand what an agent really is, how an LLM “calls” a function spoiler: it doesn’t , and you will have a small working agent that you can build on. Let’s get into it. Strip away all the hype and an agent is just three things: The LLM decides what needs to be done. Your code actually does it. Then you tell the LLM what happened, and it decides what to do next. This goes on until the LLM has enough information to give a final answer. Now here is the most important idea in this entire article, and honestly something that took me a while to really get. The LLM never executes anything. It can’t. It is a text generator. When people say “the model called a function”, what actually happened is the model wrote a piece of text saying “I would like this function to be called with these arguments”. Your code reads that text, decides whether to run it, runs it, and then reports the result back. The LLM is the brain. Your loop is the hands. Once this clicks, agents stop feeling like magic. Everything else in this article is just building towards that loop, one piece at a time. The obvious reasons first. It’s free, so you can run your agent a hundred times while debugging without a second thought. And it’s private, which starts to matter a lot once your tools touch your own files and data. But there is a third reason which I think is underrated. Small models fail more, and that’s actually great for learning. A huge frontier model will often cover up a badly written tool description or a sloppy loop and still give you a decent answer. A 4B model won’t. When something is off in your design, you see it immediately. And you learn way more about how agents work from watching them break than from watching them succeed. Not every model can call tools. A model has to be specifically trained to produce tool requests in a structured format that can be parsed reliably. On Ollama’s model library, look for the tools tag on the model page. I went with qwen3:4b . At around 2.5GB it fits comfortably in 6GB of VRAM with room left over for context, it supports tool calling, and it supports thinking , which means it writes a separate reasoning trace before giving its answer. That trace turns out to be super useful, because you get to read why the agent made a particular decision. Once you have pulled the model ollama pull qwen3:4b and installed the Python library pip install ollama , the setup is just a few lines: python import ollamaMODEL = "qwen3:4b"THINK = TrueOPTIONS = { "num ctx": 8192, context window "temperature": 0, same input, same output} num ctx is the context window, basically how many tokens the model can see at once. Ollama's default is small. Tool definitions, reasoning traces and chat history all eat into it. And here is the nasty part : when it overflows, Ollama doesn't throw an error. It silently drops the oldest tokens, which might include your system prompt or your tool definitions. Your agent suddenly "forgets" it has tools and nothing tells you why. 8192 is a safe size for a 4B model on 6GB. temperature: 0 makes the model deterministic. While learning, you want the same question to produce the same behavior every time. Otherwise you can never tell whether the agent behaved differently because of a change you made, or just because of randomness. Before adding any tools, lets just talk to the model and understand how a chat call works. A chat call takes a list of messages . Every message has a role, which tells the model who wrote it: One thing to keep in mind: the model is completely stateless . It remembers nothing between two calls. Every single time, you send the whole list of messages again. Which means the message list is the agent’s memory. We will come back to this. response = ollama.chat model=MODEL, messages= {"role": "user", "content": "are you sentient?"} , think=THINK, options=OPTIONS, print "THINKING:\n", response.message.thinking print "\nANSWER:\n", response.message.content Output: THINKING: Okay, the user is asking if I'm sentient. Hmm, this is a pretty deep question. First, I need to recall what sentience means. Sentience usually refers to the capacity to feel, perceive, or experience subjectively... But I'm Qwen, a large language model developed by Tongyi Lab. I don't have consciousness or self-awareness...ANSWER: No, I'm not sentient. I'm a large language model developed by Tongyi Lab, which means I don't have consciousness, self-awareness, or the ability to experience feelings. My responses are generated based on patterns in data and my training, but I don't have personal experiences or emotions.How can I assist you today? Notice that the response has two separate fields. thinking is the model reasoning to itself, and content is the actual answer meant for the user. Keep an eye on the thinking field, it becomes really interesting once tools come into the picture. A tool is just a normal Python function. For this article we will use a fake weather lookup, because the point is to understand the mechanics, not to call a real weather API. FAKE TEMPS F = {"san francisco": 72, "paris": 75, "tokyo": 73}def get temperature city: str - str: ''' Get the current temperature in Fahrenheit for a city. Args: city: The name of the city, e.g. "Paris" ''' temp = FAKE TEMPS F.get city.strip .lower if temp is None: return f"No temperature data available for '{city}'." return f"{temp}°F" Notice what happens when the city is not in our data. We don’t return some default number. We return a clear message saying we don’t have the data. This small detail matters more than it looks. If your tool makes up a number, the model will happily repeat it to the user as a fact. Tools need to be honest so that the model can be honest. Now here is the catch. The model cannot see your Python code. It has no idea how get temperature works internally. All it ever sees is a schema , a JSON description of the tool's name, what it does, and what arguments it takes: get temperature schema = { "type": "function", "function": { "name": "get temperature", "description": "Get the current temperature in Fahrenheit for a city.", "parameters": { "type": "object", "properties": { "city": { "type": "string", "description": 'The name of the city, e.g. "Paris"' } }, "required": "city" , }, },} This schema is the tool’s entire interface to the model. The model decides whether to use the tool, when to use it, and what arguments to pass, purely based on the name and these descriptions. Write a vague description and you get bad tool use, no matter how good the code behind it is. I like to think of it as prompt engineering, but for a function. A small shortcut worth knowing: Ollama can build this schema for you if you pass the function itself instead of the schema. It reads the type hints and the Args: section of the docstring, which is exactly why the function above is written that way. We will write the schema by hand once, so you know what is happening, and then use the shortcut. This is the most important section of the article. We are going to do one full round trip manually, step by step. The agent we build later just automates these exact steps, so if this section makes sense, the rest will too. Here is the whole round trip at a glance before we go through it piece by piece: messages = {"role": "user", "content": "What's the temperature in Paris right now?"} response = ollama.chat model=MODEL, messages=messages, tools= get temperature schema , think=THINK, options=OPTIONS, msg = response.messageprint "thinking :", msg.thinking print "content :", repr msg.content print "tool calls:", msg.tool calls thinking : Okay, the user is asking for the current temperature in Paris. Let me check the tools provided. There's a function called get temperature that takes a city name as a string. The city here is Paris. So I need to call that function with city set to "Paris"...content : ''tool calls: ToolCall function=Function name='get temperature', arguments={'city': 'Paris'} Look closely at what came back: You can even read in the thinking trace how the model looked at the available tools and decided this one fits. Now our code steps in and does the actual work. 1. Keep the model's request in the historymessages.append msg 2. Run each requested tool and add the result as a 'tool' messagefor call in msg.tool calls: name = call.function.name args = call.function.arguments print f"Model asked for: {name} {args} " result = get temperature args the ONLY place code actually runs print f"Result: {result}" messages.append { "role": "tool", "tool name": name, "content": str result , } Model asked for: get temperature {'city': 'Paris'} Result: 75°F We are doing 2 things here. First, the model’s own request. If we skip this, the model will see a tool result appear out of nowhere in the next call, with no memory of having asked for it. That confuses it. Second, the result itself, with the role tool. The tool name tells the model which request this result belongs to, and the content is converted to a string because messages can only carry text. final = ollama.chat model=MODEL, messages=messages, tools= get temperature schema , think=THINK, options=OPTIONS, print final.message.content The current temperature in Paris is 75°F. This time the model sees the full picture: the question, its own tool request, and the tool’s answer. It has everything it needs, so it writes a normal text reply instead of asking for another tool. user What's the temperature in Paris right now? assistant → CALL get temperature {'city': 'Paris'} tool:get temperature 75°F assistant The current temperature in Paris is 75°F. If the model only generates text, how does that text turn into a neat tool calls object? This was the part I was most curious about. Here is what actually happens behind the scenes: So “tool calling” is really just a prompt format, plus some fine-tuning, plus a parser. There is no special function calling machinery inside the model. This is also exactly why model choice matters so much. A model that was never trained on this format simply cannot do it reliably, no matter how cleverly you prompt it. You can see this template yourself by running ollama show qwen3:4b --template in your terminal. Look for the