Building a Local RAG Agent with Python, Ollama (Llama 3), and CPU

August 01, 20265 min read
PythonAIRAGOllamaLangChain

Introduction

Nowadays, information security is one of the biggest concerns for companies, especially when dealing with generative artificial intelligence. Sending confidential corporate data (such as audit reports, ISO compliance policies, or financial statements) to external proprietary APIs can violate strict data governance policies.

The solution? 100% Local RAG (Retrieval-Augmented Generation).

In this article, we will build a local RAG agent step-by-step that runs entirely on your machine (even using only CPU) using Python, Ollama (with the Llama 3 model), and LangChain/ChromaDB.


What is RAG (Retrieval-Augmented Generation)?

RAG is an architecture that extends the capabilities of a Large Language Model (LLM) without the need to retrain it (fine-tuning). It works in three main steps:

  1. Retrieval: The system searches for relevant documents from a local knowledge base based on the user's question.
  2. Augmentation: The user's question and the found document fragments are combined into a "rich prompt."
  3. Generation: The LLM reads the provided context and generates a response based on the content of the provided documents.

Requirements and Environment Setup

1. Install Ollama

Access ollama.com and install the software on your system (Linux, macOS, or Windows). After installation, open the terminal and pull Llama 3 8B (the llama3 tag) and the embedding model:

ollama pull llama3
ollama pull nomic-embed-text

nomic-embed-text is a lightweight, high-performance embedding model to convert text into mathematical vectors.

2. Python Dependencies

Create a virtual environment and install the dependencies. Since LangChain 1.0, the Ollama and Chroma integrations live in their own packages:

python -m venv venv
source venv/bin/activate
pip install langchain-core langchain-text-splitters langchain-ollama langchain-chroma

The Local RAG Agent Code

Below is the complete script that reads a local document (a text file here; for PDFs, extract the text first with pypdf), creates the local vector database (ChromaDB), and executes local inference using Ollama.

from pathlib import Path
from langchain_core.documents import Document
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_ollama import OllamaEmbeddings, OllamaLLM
from langchain_chroma import Chroma
from langchain_core.prompts import PromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough

# 1. Load the local knowledge document.
# Create the sample only when the file is missing: "w" would erase a real manual.
manual = Path("ims_manual.txt")
if not manual.exists():
    manual.write_text("""
    INTEGRATED MANAGEMENT SYSTEM (IMS) MANUAL - ALEX FERRAZ TECNOLOGIA
    Section 4.2 - Corporate Network Security Policy:
    All servers on AWS must use public/private SSH key authentication (RSA 4096).
    Direct root access over SSH is forbidden. Only the 'deploy' user has access to the production environment.
    Database passwords must be rotated every 30 days using AWS Secrets Manager.
    """, encoding="utf-8")

documents = [Document(page_content=manual.read_text(encoding="utf-8"), metadata={"source": "ims_manual.txt"})]

# 2. Partition the text into smaller blocks (Chunking)
text_splitter = RecursiveCharacterTextSplitter(chunk_size=300, chunk_overlap=50)
texts = text_splitter.split_documents(documents)

# 3. Build embeddings and reopen a Chroma directory that already exists.
# Calling from_documents again on the same directory duplicates the chunks.
embeddings = OllamaEmbeddings(model="nomic-embed-text")
persist = "./chroma_db"
if Path(persist).exists():
    vector_store = Chroma(persist_directory=persist, embedding_function=embeddings)
else:
    vector_store = Chroma.from_documents(
        documents=texts,
        embedding=embeddings,
        persist_directory=persist,
    )

# 4. Create the Custom Prompt to Guarantee Scope Limitation
template = """Use the following pieces of context to answer the question at the end.
If you don't know the answer, just say that you don't know; don't try to make up an answer.
Keep the answer short, direct, and strictly based on the context.

Context:
{context}

Question: {question}
Helpful answer:"""

custom_prompt = PromptTemplate.from_template(template)

# 5. Configure Llama 3 in Ollama and the question-answering chain
llm = OllamaLLM(model="llama3", temperature=0.1)
retriever = vector_store.as_retriever(search_kwargs={"k": 2})

def format_context(docs):
    return "\n\n".join(doc.page_content for doc in docs)

qa_chain = (
    {"context": retriever | format_context, "question": RunnablePassthrough()}
    | custom_prompt
    | llm
    | StrOutputParser()
)

# 6. Ask the Question
question = "Which user has access to the production environment, and what is the SSH key policy?"
answer = qa_chain.invoke(question)

print("--- QUESTION ---")
print(question)
print("\n--- AGENT ANSWER ---")
print(answer)

CPU Performance Analysis

  • Embeddings: The nomic-embed-text model generates embeddings almost instantaneously on the CPU, as it has few parameters.
  • Semantic Search: ChromaDB is extremely lightweight and retrieves snippets in milliseconds.
  • Generation (Llama 3 8B): On a modern CPU (e.g., AMD Ryzen 7 or Intel Core i7), generation takes about 10 to 20 seconds per response. Using 4-bit quantization (Ollama default), RAM consumption is around 4.8 GB.

This tutorial stores the index in Chroma, on the same machine. If the company already runs PostgreSQL, the pgvector path is in the local RAG and ISO article.

Commands before the script

The script above assumes Ollama is already answering. These commands are the check I run before starting the agent, including on a CPU-only machine. ss is Linux. On macOS, use lsof -nP -iTCP:11434 -sTCP:LISTEN.

ollama pull llama3
ollama pull nomic-embed-text
ollama list
curl -s http://127.0.0.1:11434/api/tags
ss -ltn | grep 11434

api/tags must list llama3. ss must show Ollama listening on 127.0.0.1:11434. If it shows 0.0.0.0:11434 (or *:11434), the model is exposed on the network and the ISO 27001 argument (and the SOC 2 access-control argument) falls apart.


Conclusion and Governance

This architecture demonstrates that it is feasible to build robust corporate AI assistants without relying on the internet (once the models are downloaded) or exposing industrial secrets. For systems requiring ISO 27001 (Information Security) compliance, local RAG removes the risk of leaking data to external AI providers, as long as the Ollama port stays closed to the network.

Did you like the tutorial? If you are planning to implement local Generative AI in your infrastructure, share your questions on my LinkedIn!

Related Articles