How to Build a Local AI Agent with LangChain and Ollama

What you will build

By the end of this guide you will have a small AI agent running on your own computer. You ask it a question in plain English, it decides whether it needs a tool, runs that tool, reads the result, and answers. Nothing leaves your machine: the model runs through Ollama, and the tools are plain Python functions on your disk.

The stack is short. Ollama serves the model, and LangChain 1.0 wires it up. LangChain 1.0 shipped on October 22, 2025 with a new one-call entry point, create_agent, which replaces the older hand-rolled ReAct setup. Under the hood it compiles a LangGraph graph, so the same agent can grow into a multi-step workflow later.





A local agent loop: the model reasons, calls a tool, reads the result, and answers. Illustration: NewsCarpenter. 

 


Prerequisites

  • Python 3.10 or newer
  • Ollama installed and running (our Ollama setup guide covers the install)
  • About 6 GB of free disk space and 8 GB of RAM for the model used here
  • A terminal and a text editor

Step 1: Pull a model that can call tools

Not every local model can use tools, and this is the step most people get wrong. A model that was never trained for function calling will answer from memory and quietly ignore your tools. Stick to models with proven tool support: qwen3:8b, llama3.1:8b, or mistral.

ollama pull qwen3:8b
ollama list

The download is around 5 GB. The ollama list output should show qwen3:8b ready to serve on http://localhost:11434, Ollama's default address.

Step 2: Install LangChain and the Ollama integration

python -m venv .venv
source .venv/bin/activate
pip install -U langchain langchain-ollama

Two packages matter here. langchain carries the agent API, and langchain-ollama carries ChatOllama, the chat model that talks to your local Ollama server. On Windows, activate the environment with .venv\Scripts\activate instead of the source line.

Step 3: Connect the model

Create a file called agent.py and start with the model connection:

from langchain_ollama import ChatOllama

llm = ChatOllama(
    model="qwen3:8b",
    temperature=0,
    num_ctx=8192,
)

Temperature 0 keeps answers deterministic while you test, and num_ctx=8192 gives the model an 8,192-token context window instead of Ollama's 4,096-token default. Tool calls, tool results, and conversation history all share that window, so the extra room matters once your agent starts doing real work.

Step 4: Give it two local tools

A tool is a Python function with a docstring. LangChain reads the docstring and the type hints to tell the model what the tool does and what arguments it takes, so write them like you would explain the function to a colleague.

from pathlib import Path
from langchain_core.tools import tool


@tool
def calculator(expression: str) -> str:
    """Evaluate a basic arithmetic expression, e.g. '48 * 12'."""
    allowed = set("0123456789+-*/(). ")
    if not set(expression) <= allowed:
        return "Only numbers and + - * / ( ) are allowed."
    try:
        return str(eval(expression, {"__builtins__": {}}))
    except Exception as e:
        return f"Could not evaluate that: {e}"


@tool
def read_note(filename: str) -> str:
    """Read a plain-text note from the ./notes folder."""
    path = Path("notes") / filename
    if not path.is_file():
        return f"No note named {filename}."
    return path.read_text(encoding="utf-8")[:4000]

The calculator proves the point: the model cannot do arithmetic reliably, but it can hand arithmetic to a tool that can. The note reader shows the other half, letting the agent reach data on your disk. (The calculator uses eval behind an allowlist; treat it as demo code.)

Create a notes folder next to agent.py and drop in a short text file, for example meeting.txt with a line about Friday's plans. The agent will read it in the next step.

Step 5: Build the agent with create_agent

This is the whole assembly. One call takes the model, the tools, and a short system prompt:

from langchain.agents import create_agent

agent = create_agent(
    model=llm,
    tools=[calculator, read_note],
    system_prompt=(
        "You are a helpful local assistant. "
        "Use the tools when a task needs calculation or a file lookup. "
        "If you do not know something, say so."
    ),
)

create_agent is the headline API of LangChain 1.0. It builds the reasoning loop for you: the model reads the question, picks a tool, LangChain runs it, and the result goes back to the model until it has enough to answer.

Step 6: Run it

result = agent.invoke({
    "messages": [{
        "role": "user",
        "content": "What is 15% of 240, and what does my note meeting.txt say about Friday?",
    }]
})
print(result["messages"][-1].content)

A working run looks like this: the agent calls calculator with 240 * 0.15, gets 36.0 back, calls read_note for meeting.txt, then answers with both facts in one reply. Run it from the terminal with python agent.py. If you want to watch the loop happen, swap invoke for agent.stream(...) and print each chunk as it arrives.

How the agent loop works

Each turn follows the same cycle. The model reads the conversation, decides whether a tool would help, and either calls one or answers directly. LangChain runs the function and hands the result back as a new message, and the model either calls another tool or finishes. Small models can loop here: a bad tool result or vague instruction can send the model around the same call twice. A clear system prompt and narrow tools keep the loop short.




A LangChain agent chain wired to a local Ollama model. Source: CodeExplorer project on GitHub. 


Optional: add web search

Everything so far works offline. If you want the agent to answer questions about current events, add one hosted tool. Tavily offers a search API with a free tier for light use:

pip install -U langchain-tavily
import os
from langchain_tavily import TavilySearch

search = TavilySearch(max_results=3)
# set TAVILY_API_KEY in your environment first
agent = create_agent(model=llm, tools=[calculator, read_note, search])

Keep the local tools first in the list. The model tries tools in order when several could fit, and local lookups should win over a web call when both apply.

Troubleshooting

  • The model never calls a tool. The model is the usual suspect. Switch to qwen3:8b, llama3.1:8b, or mistral, all of which support tool calling. A plain chat model will keep answering from memory no matter how good your tools are.
  • Connection refused on localhost:11434. Ollama is not running. Start it with ollama serve in a separate terminal, then check ollama list shows your model.
  • The first answer takes a long time. Ollama loads the model into memory on first use. Later calls in the same session are faster. A smaller model such as qwen3:4b loads quicker if you are short on RAM.
  • Replies include long thinking traces. Qwen3 thinks out loud by default. Pass reasoning=False to ChatOllama if you want direct answers without the trace.
  • Tool results get cut off. The 4,096-token default context fills fast once tools return data. Raise num_ctx to 8192 or 16384 in the ChatOllama call.

Where to go from here

You now have the smallest useful agent: a local model, two tools, and a loop that ties them together. The next steps are memory, so the agent remembers facts between sessions, and more tools, so it can reach your calendar, files, or internal APIs. Our LangGraph tutorial turns this loop into a stateful graph, and our CrewAI guide shows what changes when several agents share the work. Start with one agent that does two things well.

Comments

Popular posts from this blog

Open-Source AI Weekly: Bonsai, GigaChat 4 Lead

Claude Claims Proof of Riemann Hypothesis After 167 Years

How to Build an AI Agent with LangGraph in 30 Minutes