{"slug": "building-your-first-ai-agent-fully-locally-tool-calling-from-scratch-with-ollama", "title": "Building Your First AI Agent Fully Locally: Tool Calling from Scratch with Ollama", "summary": "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.", "body_md": "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.\n\nBut 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.\n\nSo 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.\n\nIn 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.\n\nLet’s get into it.\n\nStrip away all the hype and an agent is just three things:\n\nThe 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.\n\nNow here is the most important idea in this entire article, and honestly something that took me a while to really get.\n\n**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.\n\nThe LLM is the brain. Your loop is the hands.\n\nOnce this clicks, agents stop feeling like magic. Everything else in this article is just building towards that loop, one piece at a time.\n\nThe 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.\n\nBut 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.\n\nNot 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.\n\nI 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.\n\nOnce you have pulled the model (ollama pull qwen3:4b) and installed the Python library (pip install ollama), the setup is just a few lines:\n\n``` python\nimport ollamaMODEL = \"qwen3:4b\"THINK = TrueOPTIONS = {    \"num_ctx\": 8192,     # context window    \"temperature\": 0,    # same input, same output}\n```\n\n**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.\n\n**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.\n\nBefore adding any tools, lets just talk to the model and understand how a chat call works.\n\nA chat call takes a **list of messages**. Every message has a role, which tells the model who wrote it:\n\nOne 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.\n\n```\nresponse = 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)\n```\n\nOutput:\n\n```\nTHINKING: 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?\n```\n\nNotice 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.\n\nA 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.\n\n```\nFAKE_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\"\n```\n\nNotice 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.\n\nNow 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:\n\n```\nget_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\"],        },    },}\n```\n\nThis 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.\n\nA 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.\n\nThis 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.\n\nHere is the whole round trip at a glance before we go through it piece by piece:\n\n```\nmessages = [              {\"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)\nthinking  : 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'}))]\n```\n\nLook closely at what came back:\n\nYou can even read in the thinking trace how the model looked at the available tools and decided this one fits.\n\nNow our code steps in and does the actual work.\n\n```\n# 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),    })\nModel asked for: get_temperature({'city': 'Paris'})Result: 75°F\n```\n\nWe 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.\n\nSecond, 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.\n\n```\nfinal = ollama.chat(    model=MODEL,    messages=messages,    tools=[get_temperature_schema],    think=THINK,    options=OPTIONS,)print(final.message.content)\nThe current temperature in Paris is 75°F.\n```\n\nThis 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.\n\n```\n[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.\n```\n\nIf 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.\n\nHere is what actually happens behind the scenes:\n\nSo “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.\n\nYou can see this template yourself by running ollama show qwen3:4b --template in your terminal. Look for the <tools> and <tool_call> tags, that is exactly where your schemas go in and where the model's requests come out.\n\nNow we take Steps A, B and C and repeat them until the model stops asking for tools. **That loop is the agent.**\n\nWe call it a loop and not just one round because the model might need several rounds. It might look something up, then use that result in another tool, then decide it has enough to answer. We can’t know in advance how many steps a question will take.\n\n``` python\nclass Agent:    def __init__(self, model, tools, system=\"\", think=THINK, max_steps=8, verbose=True):        self.model = model        self.tools = {fn.__name__: fn for fn in tools}   # registry: name -> function        self.think = think        self.max_steps = max_steps        self.verbose = verbose        self.messages = []        if system:            self.messages.append({\"role\": \"system\", \"content\": system})    def __call__(self, user_message):        self.messages.append({\"role\": \"user\", \"content\": user_message})        return self.run()    def run(self):        for step in range(1, self.max_steps + 1):            response = ollama.chat(                model=self.model,                messages=self.messages,                tools=list(self.tools.values()),   # Ollama builds the schemas                think=self.think,                options=OPTIONS,            )            msg = response.message            self.messages.append(msg)               # always keep the model's turn            if self.verbose and msg.thinking:                print(f\">>THINKING step {step}: {msg.thinking.strip()[:300]}...\")            # No tool requests means this is the final answer            if not msg.tool_calls:                return msg.content            # Otherwise run every requested tool and feed the results back            for call in msg.tool_calls:                result = self.run_tool(call)                if self.verbose:                    print(f\">>EXECUTE step {step}: {call.function.name}({call.function.arguments}) -> {result}\")                self.messages.append({                    \"role\": \"tool\",                    \"tool_name\": call.function.name,                    \"content\": result,                })        return f\"(Stopped after {self.max_steps} steps without a final answer.)\"    def run_tool(self, call):        name, args = call.function.name, call.function.arguments        fn = self.tools.get(name)        if fn is None:            return f\"Error: unknown tool '{name}'. Available tools: {list(self.tools)}\"        try:            return str(fn(**args))        except Exception as e:            # Give the error to the model instead of crashing            return f\"Error running {name}: {type(e).__name__}: {e}\"\n```\n\nIf you compare this with a lot of agent code you will find online, there are four design choices here that I want to point out, because each one fixes a real problem.\n\n**An explicit tool registry.** A common shortcut is to look up tools by name in Python’s globals(). The problem is that the model can then call *any* function that happens to exist in your notebook. With a registry, the model can only call what you deliberately gave it.\n\n**Errors go back to the model instead of crashing.** If the model calls a tool that doesn’t exist, or passes a wrong argument, we don’t crash. We send the error message back as the tool result. The model reads it and can fix its arguments or try something else. This ability to self-correct is a big part of what makes agents actually work.\n\n**A step limit.** A while True loop sounds fine until a small model gets stuck calling the same tool over and over. max_steps makes sure the agent always stops.\n\n**Every assistant message goes into history.** Including the final answer. Without it, a follow-up question like “and what about tomorrow?” would have no context to work with.\n\nWith just one tool, the agent can only ever do one thing. Adding a second one lets us watch something much more interesting. The model chaining tool calls, where the output of one becomes the input of the next.\n\n``` php\ndef fahrenheit_to_celsius(fahrenheit: float) -> str:    '''    Convert a temperature from Fahrenheit to Celsius.    Args:      fahrenheit: Temperature in degrees Fahrenheit, e.g. 72    '''    # Don't trust the model's types: small models often send \"72\" or \"72°F\"    value = float(str(fahrenheit).replace(\"°F\", \"\").strip())    return f\"{round((value - 32) * 5 / 9, 1)}°C\"\n```\n\nNever trust the model’s inputs blindly. Clean them up inside the tool.\n\nAnd finally a system prompt and a small helper to create fresh agents:\n\n```\nSYSTEM = (    \"You are a helpful assistant. Use the tools when they help answer the question. \"    \"Never guess temperatures; always look them up.\")def new_agent():    return Agent(MODEL, tools=[get_temperature, fahrenheit_to_celsius], system=SYSTEM)\n```\n\nNow the fun part. In each of these, read the >>THINKING and >>EXECUTE lines. That’s the agent’s decision process, step by step.\n\n```\nagent = new_agent()print(agent(\"What's the temperature in San Francisco?\"))\n>>THINKING step 1: Okay, the user is asking for the temperature in San Francisco. Let mecheck the tools provided. First, there's a function called get_temperature...>>EXECUTE step 1: get_temperature({'city': 'San Francisco'}) -> 72°F>>THINKING step 2: The user asked for the temperature in San Francisco. I called theget_temperature function... and the response was 72°F...The current temperature in San Francisco is 72°F.\n```\n\nTwo steps. Ask for the tool, then answer. Exactly what we did by hand earlier, except now the loop handles it.\n\nNow a follow up question on the same agent.\n\n```\nprint(agent(\"And what is that in Celsius?\"))\n>>THINKING step 1: Okay, the user just asked, \"And what is that in Celsius?\" after I toldthem the temperature in San Francisco is 72°F. So I need to convert 72°F to Celsius...>>EXECUTE step 1: fahrenheit_to_celsius({'fahrenheit': 72}) -> 22.2°C>>THINKING step 2: ...The temperature in San Francisco is currently 72°F, which converts to 22.2°C.\n```\n\n“What is *that*” only makes sense because the earlier conversation is still sitting in agent.messages. There is no separate memory system here. Remember, the message list is the memory.\n\n```\nagent = new_agent()print(agent(\"What's the temperature in Tokyo in Celsius?\"))\n>>THINKING step 1: The user is asking for the temperature in Tokyo in Celsius... There's a function called get_temperature that gives the current temperature in Fahrenheit for a city. Then there's fahrenheit_to_celsius...>>EXECUTE step 1: get_temperature({'city': 'Tokyo'}) -> 73°F>>THINKING step 2: I first called the get_temperature function for Tokyo, which returned 73°F. Now I need to convert that to Celsius...>>EXECUTE step 2: fahrenheit_to_celsius({'fahrenheit': 73}) -> 22.8°C>>THINKING step 3: ...The current temperature in Tokyo is 22.8°C.\n```\n\nThe model cannot do both calls at once because it doesn’t know what numbers to convert until the first tool returns. So it plans it out in its thinking , makes the first call, read the results and only then makes the second call.\n\n```\nagent = new_agent()print(agent(\"Which is warmer right now, Paris or Tokyo?\"))\n>>THINKING step 1: The user is asking which city is warmer right now between Paris andTokyo. To answer this, I need to get the current temperatures for both cities...>>EXECUTE step 1: get_temperature({'city': 'Paris'}) -> 75°F>>EXECUTE step 1: get_temperature({'city': 'Tokyo'}) -> 73°F>>THINKING step 2: I called the get_temperature function for Paris and got 75°F. Then forTokyo, it was 73°F... So Paris is warmer.Paris is warmer right now at 75°F compared to Tokyo's 73°F.\n```\n\nNotice that both calls happen in **step 1**. These two lookups don’t depend on each other, so the model asked for both in a single turn. Compare this with the Tokyo example above, where the second call depended on the first. The model figured out the difference by itself.\n\n```\nagent = new_agent()print(agent(\"What is the capital of France?\"))\n>>THINKING step 1: The user is asking for the capital of France. The tools provided are forgetting the current temperature... Neither of these tools can answer the capitalcity question...The question asks for the capital of France, but the provided tools only supporttemperature lookups and unit conversions. I don't have access to geographic orpolitical data through these tools. The capital of France is Paris, but I cannotretrieve this information using the available functions.\n```\n\nThis is the most interesting output in the whole experiment, and it’s exactly the kind of thing a small model shows you that a big model hides.\n\nThe good part: the model correctly realised no tool was relevant and didn’t call one. Calling a tool is a *decision*, not a reflex.\n\nThe weird part: it gave the right answer, but wrapped it in an apology about not having the right tools. Why? Look at our system prompt again. We told it to use tools and to never guess. A 4B model took that a bit too literally and started treating its tool list as the boundary of what it’s allowed to know.\n\nThe fix is a one line change in the system prompt, something like “If no tool is relevant, answer from your own knowledge.” Try it yourself and see how the answer changes. The bigger lesson here is that the system prompt is not decoration. It is part of your agent’s design, just like the tools and the loop.\n\n```\nagent = new_agent()print(agent(\"What's the temperature in Kolkata?\"))\n>>THINKING step 1: The user is asking for the temperature in Kolkata... So I need to callthat with Kolkata as the city...>>EXECUTE step 1: get_temperature({'city': 'Kolkata'}) -> No temperature data available for 'Kolkata'.>>THINKING step 2: I called the get_temperature function with Kolkata as the city, but theresponse says no temperature data is available...The current temperature data for Kolkata is not available. I cannot retrievetemperature information for this city. Would you like to try a different city?\n```\n\nRemember the design choice in our tool, returning an honest “no data” message instead of a default number? This is where it pays off. The model got a clear signal and passed it on honestly, instead of making up a temperature for Kolkata.\n\nIn this article, we built a tool calling AI agent completely from scratch, running fully on a local 6GB GPU. We started by talking to a plain LLM, gave it a tool, did one tool call by hand to understand every step, and then wrapped it all in a loop that turned out to be the entire agent. Along the way we saw the model chain calls, make parallel calls, decide when no tool is needed, and handle missing data honestly. We also saw how a small model can take a system prompt a little too literally.\n\nStay tuned for the next tutorial on agents, where we will make an Agentic RAG system for which retrieval is just another tool that the agent decides when to use.\n\nFind the code used here in the GitHub link here: [https://github.com/chakiAunkit/Simple-tool-calling-Agent](https://github.com/chakiAunkit/Simple-tool-calling-Agent)\n\nFeel free to reach out on LinkedIn if you have any questions.\n\nHappy Learning!\n\nAunkit Chaki\n\nchakiaunkit[@gmail.com](mailto:chaki18081999@gmail.com)\n\n[https://www.linkedin.com/in/aunkit-chaki-38807b174/](https://www.linkedin.com/in/aunkit-chaki-38807b174/)\n\n[Building Your First AI Agent Fully Locally: Tool Calling from Scratch with Ollama](https://pub.towardsai.net/building-your-first-ai-agent-fully-locally-tool-calling-from-scratch-with-ollama-674c45cb5f83) was originally published in [Towards AI](https://pub.towardsai.net) on Medium, where people are continuing the conversation by highlighting and responding to this story.", "url": "https://wpnews.pro/news/building-your-first-ai-agent-fully-locally-tool-calling-from-scratch-with-ollama", "canonical_source": "https://pub.towardsai.net/building-your-first-ai-agent-fully-locally-tool-calling-from-scratch-with-ollama-674c45cb5f83?source=rss----98111c9905da---4", "published_at": "2026-11-26 00:01:02+00:00", "updated_at": "2026-11-26 00:12:55.235875+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "large-language-models", "ai-products", "developer-tools"], "entities": ["Ollama", "qwen3:4b", "LangChain", "LlamaIndex", "LinkedIn"], "also_reported_by": [], "takeaway": "Run a tool-calling agent locally with qwen3:4b on Ollama at num_ctx 8192 and temperature 0, and set the context window explicitly because Ollama silently drops the oldest tokens — including system prompt and tool definitions — on overflow instead of raising an error.", "recommendation": {"advice": "Set num_ctx explicitly (8192 here) when serving tool-calling models on Ollama, since overflow silently drops the oldest tokens, which can include your system prompt and tool definitions.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/building-your-first-ai-agent-fully-locally-tool-calling-from-scratch-with-ollama", "markdown": "https://wpnews.pro/news/building-your-first-ai-agent-fully-locally-tool-calling-from-scratch-with-ollama.md", "text": "https://wpnews.pro/news/building-your-first-ai-agent-fully-locally-tool-calling-from-scratch-with-ollama.txt", "jsonld": "https://wpnews.pro/news/building-your-first-ai-agent-fully-locally-tool-calling-from-scratch-with-ollama.jsonld"}}