Building AI Agents From Scratch: How Local Tool Calling Works Without Frameworks
A deep dive into building bare-metal tool-calling AI agents with local 4B models, Ollama, and raw Python loops without relying on third-party frameworks.

AI developer tutorials often rely on high-level frameworks like LangChain or paid cloud API subscriptions to demonstrate autonomous agents. However, building a tool-calling AI agent from scratch requires nothing more than a local open-source model, standard Python functions, and a basic execution loop. Running a 4B parameter model such as qwen3:4b via Ollama on a GPU with just 6GB of VRAM offers a practical way to understand the underlying mechanics of function execution without third-party frameworks or recurring API bills.
Demystifying tool calling and the agent loop
Strip away the marketing terminology and an AI agent consists of three core elements: a large language model that processes text, standard functions acting as tools, and a control loop sitting between them. A frequent misconception in agent design is that language models directly execute code. In reality, models are strictly text generators. When a model appears to call a function, it simply generates structured text indicating its desire to invoke a specific tool with particular arguments. The developer's loop parses that text, runs the function, and feeds the resulting output back to the model.
For tool calling to function reliably, a model must be fine-tuned to produce structured tool requests inside its chat template. Ollama embeds defined tool schemas directly into the prompt as plain text. When qwen3:4b determines it requires external data, it outputs formatted text containing tags such as <tool_call>, which Ollama then parses into structured objects.
Context management is essential when running agents locally. Ollama defaults to a relatively small context window, which can easily be exhausted by tool definitions, reasoning traces, and conversation history. Developers must explicitly set parameters like num_ctx to 8192. If the context window overflows, Ollama silently drops the oldest tokens without raising an error, causing the agent to forget its system prompt or available tools. Setting temperature to zero is also recommended during initial development to ensure deterministic, repeatable outputs.
Defensive design for agent execution
Writing a raw execution loop requires defensive coding choices to handle model mistakes. Using an explicit tool registry to map function names to callable objects ensures the model can only invoke explicitly provided code, avoiding unsafe lookups in global code environments.
Error handling inside the loop is equally critical. Rather than allowing standard Python exceptions to crash the program, execution errors should be caught and returned directly to the model as a text string under the tool role. This allows the model to analyze its error—such as passing invalid argument types or requesting unlisted data—and correct its parameters in the next step. Additionally, enforcing a step limit (such as max_steps = 8) prevents small models from entering infinite execution loops.
Local testing with compact models also highlights the importance of precise prompt engineering. In tests using tools like get_temperature and fahrenheit_to_celsius, strict system prompts instructing the model not to guess can cause a 4B model to decline answering general knowledge questions, mistaking its tools for the absolute limit of its knowledge. Inspecting reasoning traces (thinking) helps developers refine system instructions and observe how small prompt changes alter agent behavior.
What it means for developers
Building an agent without abstraction layers clarifies how agentic workflows operate. Developers quickly learn that the conversation message history serves as the agent's complete memory state. Because language models are inherently stateless, every step in a multi-turn tool interaction requires resending the complete history—including system instructions, user messages, model calls, and tool outputs.
Using smaller local models like qwen3:4b provides an effective environment for learning and debugging. Smaller models fail more predictably when faced with ambiguous tool descriptions or flawed loop logic, whereas massive frontier models can obscure underlying system flaws by compensating for poor prompts. Local execution also ensures data privacy and zero usage costs during initial development.
While local environments excel for offline iteration, developers who want to transition to production or evaluate larger commercial models can try top AI models cheaply through one API at https://apixoai.online. Mastering raw tool-calling loops locally gives developers the foundational knowledge required to design reliable, framework-agnostic AI applications across any deployment target.
Source: Building Your First AI Agent Fully Locally: Tool Calling from Scratch with Ollama — Towards AI. Written by the Apixo team from that report.
One key for Claude, GPT, GLM, DeepSeek and more. Pay per token with crypto.
Get your API key

