Build a Local AI Agent with LlamaIndex and Ollama

LlamaIndex started as a toolkit for connecting language models to private data. That focus makes it a natural fit for local agents: point it at your files, give it a few tools, and a model running on your own machine does the work. No API key, and nothing you ask leaves your laptop.

This guide builds that setup end to end. You will wire Ollama into LlamaIndex, create an agent that can call a Python function, give it memory across turns, and add retrieval over your own documents. The same agent code keeps working if you later swap Ollama for a hosted model or a faster inference server.


Ollama runs models locally and serves them through a local API. Source: Easton Dev

Prerequisites

  • Python 3.9 or newer
  • Ollama installed on macOS, Windows, or Linux
  • A machine with enough memory for an 8B model. The official LlamaIndex tutorial suggests around 32 GB of RAM for its llama3.1 8B setup. If your machine has less, swap in a smaller model such as llama3.2:3b and the steps below still work.

Step 1: Install Ollama and Pull a Model

Download Ollama from ollama.com and install it, then pull the model this guide uses:

ollama pull llama3.1
ollama list

The second command should show llama3.1 in your local library. Tool calling strains small models, so an 8B model is a sensible floor here. A 3B model runs the code but fumbles tool calls more often.

Step 2: Install the LlamaIndex Packages

LlamaIndex ships as a collection of packages, so install the core plus the two integrations this guide needs: the Ollama LLM integration and the Hugging Face embeddings integration.

pip install llama-index llama-index-llms-ollama llama-index-embeddings-huggingface

The package names spell out their imports, which makes the next step easy to remember.

Step 3: Build Your First Agent

Create a file called starter.py. It defines one tool, a plain Python function, and hands it to a FunctionAgent backed by Ollama:

import asyncio
from llama_index.core.agent.workflow import FunctionAgent
from llama_index.llms.ollama import Ollama

# Define a simple calculator tool
def multiply(a: float, b: float) -> float:
    """Useful for multiplying two numbers."""
    return a * b

# Create an agent workflow with our calculator tool
agent = FunctionAgent(
    tools=[multiply],
    llm=Ollama(
        model="llama3.1",
        request_timeout=360.0,
        # Manually set the context window to limit memory usage
        context_window=8000,
    ),
    system_prompt="You are a helpful assistant that can multiply two numbers.",
)

async def main():
    # Run the agent
    response = await agent.run("What is 1234 * 4567?")
    print(str(response))

# Run the agent
if __name__ == "__main__":
    asyncio.run(main())

Two details matter here. First, the function's docstring becomes the tool description the model reads, so write it plainly: what the tool does, nothing more. Second, request_timeout=360.0 gives a local model room to think, since a cold model on a laptop can be slow on its first call.

Step 4: Run It

python starter.py

You should see something like:

The answer to 1234 * 4567 is 5635678.

Behind that one line, the agent read the question, picked the multiply tool, filled in the arguments, and folded the result into a sentence. That loop (read, pick a tool, use the result) is the whole mechanism, and everything after this step adds more tools or more context to it.

Step 5: Give the Agent Memory

Out of the box, each agent.run() call starts fresh. A Context object carries the conversation across calls:

from llama_index.core.workflow import Context

# create context
ctx = Context(agent)

# run agent with context
response = await agent.run("My name is Logan", ctx=ctx)
response = await agent.run("What is my name?", ctx=ctx)

The second call answers from the first. Memory here lives in the Context object, so it disappears when the script exits. That is fine for a chat session, and if you need memory that survives restarts, our guide to giving your AI agent memory with Mem0 and Ollama covers the persistent version.

LlamaIndex and Ollama wired together in a Python project. Source: Decrypt

Step 6: Add RAG Over Your Own Files

Tools are not limited to calculations. The agent can also search documents, which is where LlamaIndex earns its keep. Grab a sample file and build an index over it:

mkdir data
wget https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt -O data/paul_graham_essay.txt

Then extend starter.py. The embedding model runs locally too (BAAI/bge-base-en-v1.5 from Hugging Face), so indexing needs no API key either:

from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Settings
from llama_index.core.agent.workflow import AgentWorkflow
from llama_index.llms.ollama import Ollama
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
import asyncio

# Settings control global defaults
Settings.embed_model = HuggingFaceEmbedding(model_name="BAAI/bge-base-en-v1.5")
Settings.llm = Ollama(
    model="llama3.1",
    request_timeout=360.0,
    # Manually set the context window to limit memory usage
    context_window=8000,
)

# Create a RAG tool using LlamaIndex
documents = SimpleDirectoryReader("data").load_data()
index = VectorStoreIndex.from_documents(documents)
query_engine = index.as_query_engine()

def multiply(a: float, b: float) -> float:
    """Useful for multiplying two numbers."""
    return a * b

async def search_documents(query: str) -> str:
    """Useful for answering natural language questions about an essay written by Paul Graham."""
    response = await query_engine.aquery(query)
    return str(response)

# Create an enhanced workflow with both tools
agent = AgentWorkflow.from_tools_or_functions(
    [multiply, search_documents],
    llm=Settings.llm,
    system_prompt="""You are a helpful assistant that can perform calculations
and search through documents to answer questions.""",
)

# Now we can ask questions about the documents or do calculations
async def main():
    response = await agent.run(
        "What did the author do in college? Also, what's 7 * 8?"
    )
    print(response)

# Run the agent
if __name__ == "__main__":
    asyncio.run(main())

Ask a question that needs both tools and watch the agent switch between them: it searches the essay for the college question and calls the calculator for the arithmetic, then answers both in one reply. Swap the essay for your own files (notes, manuals, meeting transcripts) and the same code becomes a private research assistant. Our local RAG guide with Ollama and Qdrant shows how to scale this with a dedicated vector database once your document pile grows.

Step 7: Persist the Index

Rebuilding the index on every run wastes time. Save it to disk once, then load it back:

# Save the index
index.storage_context.persist("storage")

# Later, load the index
from llama_index.core import StorageContext, load_index_from_storage

storage_context = StorageContext.from_defaults(persist_dir="storage")
index = load_index_from_storage(storage_context)

One rule: load the index with the same embedding model you built it with, or retrieval quality drops. Keep the model name in one place (Settings.embed_model) and you will not trip over this.

Troubleshooting

  • Requests time out or the first reply is very slow. The first call loads the model into memory, so it is always the slowest. The 360-second timeout here is generous on purpose. If timeouts persist, check that Ollama is running with ollama list.
  • "Model not found" errors. Run ollama pull llama3.1 again and confirm the name matches exactly. Tags matter, and llama3.1 is not the same as llama3.1:8b in every setup.
  • The agent ignores the tool or makes up numbers. This is usually the model, not your code. Small models guess instead of calling tools. Move up to an 8B model, keep tool docstrings short and specific, and avoid giving the agent five tools when one will do.
  • Out of memory. Lower context_window to 4096, or switch to a smaller model. The context window is the biggest memory lever you have.
  • Embedding download stalls. The first run downloads the BGE embedding model, a few hundred MB. Let it finish once; later runs reuse the cached copy.

When LlamaIndex Is the Right Pick

Every agent framework can call tools. LlamaIndex stands out when the agent's job is mostly answering questions over documents, because indexing and retrieval are built into the framework from the start. If your agent is mostly branching workflows with human approval steps, a graph-based framework may fit better — our LangGraph vs CrewAI vs AutoGen comparison lays out that trade-off. And if you want to see the same local-agent idea in a different framework, our Pydantic AI with Ollama guide builds a comparable agent with a different style of tool definition.

What you have now is a small, private agent: it calculates, remembers a conversation, and answers from your own files. From here, the natural next steps are adding tools (a web search, a file writer, a shell command) and pointing the RAG index at documents you actually care about. Every tool you add makes the same loop more useful.

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