If you have ever run an AI model locally with Ollama, you already know how fun it is to have a "personal ChatGPT" on your own computer. Sooner or later, though, you will hit one limitation: the model knows nothing about your documents.
Try asking it about your company's internal handbook, your project notes, or the documentation of an app you built. The model will say it doesn't know, or worse, make up an answer that sounds convincing but is wrong. That's expected, because a model only knows the data it was trained on.
This is where RAG (Retrieval-Augmented Generation) comes in. With RAG, we first look up the pieces of your documents that are relevant, then hand them to the model as material for its answer. As a result, the model can answer questions based on your own documents, with no retraining required.
In this article, we will cover how to build a local RAG with Ollama, Python, and ChromaDB, from understanding how RAG and embeddings work, preparing documents, and writing the indexing script, to building a chatbot that answers from your documents and cites its sources. Let's get started!
What is RAG?
RAG (Retrieval-Augmented Generation) is a technique for giving a language model access to knowledge outside its training data. The system retrieves relevant information from a collection of documents, augments the prompt with it, and then the model generates an answer based on that information.
Think of it like an exam. A regular model takes a closed-book exam: it relies on memory alone. With RAG, the model takes an open-book exam: before answering, it is handed the pages most relevant to the question.
What is an Embedding?
So how does a computer know which piece of a document is "relevant" to a question? The answer is embeddings.
An embedding is a representation of text as a list of numbers (a vector) that captures the meaning of that text. Two texts with similar meanings produce vectors that are close together, even when the words are different. For example, "the cat is sleeping on the sofa" and "a kitten is dozing on the chair" end up closer to each other than to "stock prices rose today".
These vectors are stored in a vector database, a database designed specifically to find the most similar vectors quickly. In this article we use ChromaDB, an open source vector database that runs right inside your Python script, with no separate server to install.
How RAG Works
A RAG system has two stages. The first is indexing, which you run once (and again whenever your documents change):
- Documents are split into small pieces called chunks.
- Each chunk is turned into a vector by an embedding model.
- The vectors are stored in the vector database along with the original text.
The second stage is question answering, which happens every time a question comes in:
- The question is turned into a vector with the same embedding model.
- The vector database finds the chunks whose vectors are most similar to the question.
- Those chunks are inserted into the prompt as context.
- The chat model writes an answer based on that context.
So there are two models at work: an embedding model for searching, and a chat model for writing the answer.
Why Build RAG Locally?
There are plenty of cloud-based RAG services, but running it on your own machine has some real advantages:
- Your documents stay put: both embedding and question answering run on your computer. That makes it a good fit for office documents, contracts, or personal notes.
- Free: there is no per-token cost, for embeddings or for chat.
- No retraining: just add new documents and run indexing again, and your AI's knowledge grows right away.
- Traceable answers: we can show which document an answer came from, so it is easier to verify.
- You understand how it works: by building it from scratch without a big framework, you really see what happens at each stage.
Drawbacks You Should Know
To be fair, RAG is not a magic bullet:
- Answer quality depends on the search: if the retrieved chunks are not relevant, the model's answer will miss the mark too.
- Small models still make mistakes: even with context, a small local model sometimes draws the wrong conclusion or adds information that isn't there.
- Not great for whole-collection questions: a question like "summarize all of these documents" is hard to answer, because the model only sees a few chunks.
Preparation
Before we begin, make sure you have:
- Ollama installed and running, at least version 0.11.10, because the embedding model we use requires it. If you don't have it yet, follow the guide on how to install Ollama on Ubuntu.
- Python 3.9 or newer. The commands in this article are intended for Ubuntu 24.04 LTS and 26.04 LTS, but the Python code runs the same way on macOS and Windows.
- At least 8 GB of RAM and about 3 GB of free disk space for the two models we will download.
- A basic understanding of the Ollama Python library. If you have never used it, read how to use Ollama with Python first.
Here are the components we will use and what each one does:
| Component | Role | Notes |
|---|---|---|
| embeddinggemma | Embedding model | ±622 MB, 768-dimension vectors, trained on 100+ languages |
| llama3.2 | Chat model | ±2 GB, light and responsive on CPU |
| ChromaDB | Vector database | Runs inside Python, data is stored in a single folder |
ollama library |
Connects Python to Ollama | The official library from Ollama |
The model sizes above are the figures in the Ollama library at the time of writing and may change when the models are updated.
How to Build a Local RAG with Ollama and ChromaDB
Step #1: Download the Chat Model and the Embedding Model
First, download the two models we need. You may already have the llama3.2 chat model from a previous tutorial.
ollama pull llama3.2
ollama pull embeddinggemmaEmbeddingGemma is an embedding model from Google that is small and supports many languages. That matters if your documents are not in English, because not every embedding model handles other languages well.
Make sure both models are available with the following command:
ollama listIf llama3.2 and embeddinggemma appear in the list, we are ready to continue.
Step #2: Create the Project and Install the Libraries
Create a new project folder along with a dokumen folder to hold the files you want to ask about:
mkdir -p ~/rag-lokal/dokumen
cd ~/rag-lokalCreate a virtual environment and activate it, so the libraries you install don't mix with the system Python:
python3 -m venv .venv
source .venv/bin/activateIf the
python3 -m venvcommand fails on Ubuntu, install the supporting packages first withsudo apt install -y python3-venv python3-pip.
Then install the ollama and chromadb libraries with the following command:
pip install ollama chromadbThis takes a little longer than usual, because ChromaDB pulls in quite a few dependencies. At the time of writing, the installed versions are ollama 0.6.x and chromadb 1.x.
Step #3: Prepare the Documents
To make the result easy to prove, we will use a document the model definitely doesn't know: an employee handbook from a fictional company. Create the file dokumen/panduan-karyawan.txt:
nano dokumen/panduan-karyawan.txtPaste in the following text, then save with Ctrl+X, Y, and Enter:
Employee Handbook of Nusantara Prosperous Technology Ltd.
Office hours are Monday to Friday, 08:30 to 17:30, with a one-hour break. Employees may work from home (WFH) every Tuesday and Thursday, as long as they attend the daily meeting at 09:00 via video call.
Every permanent employee gets 14 working days of annual leave. Leave requests are submitted through the HR app at least three working days in advance. Unused leave can be carried over to the following year, up to a maximum of 5 days.
The company provides an internet allowance of Rp200,000 per month for employees who work from home. This allowance is paid together with the salary on the 25th of each month.
Office laptops must use disk encryption and a password of at least 12 characters. If a laptop is lost, the employee must report it to the IT team within 24 hours by email at [email protected].
Business travel costs are fully reimbursed by the company. Reimbursement claims are submitted no later than 14 days after the trip ends, with a photo of the receipt attached.Of course, you are free to put other .txt or .md files in this folder. The more files you have, the more useful RAG becomes.
Step #4: Try Embeddings with Python
Before building the full system, let's see what an embedding actually looks like. Create a file named coba_embedding.py:
import ollama
kalimat = [
"The cat is sleeping on the sofa.",
"A kitten is dozing on the chair.",
"Stock prices rose sharply today.",
]
hasil = ollama.embed(model="embeddinggemma", input=kalimat)
a, b, c = hasil["embeddings"]
def kemiripan(x, y):
"""Cosine similarity for vectors that are already normalized."""
return sum(i * j for i, j in zip(x, y))
print(f"Vector length: {len(a)}")
print(f"Sentence 1 vs 2: {kemiripan(a, b):.2f}")
print(f"Sentence 1 vs 3: {kemiripan(a, c):.2f}")The ollama.embed() function accepts a single text or a list of texts, and returns a list of vectors in the embeddings field. Run the script:
python coba_embedding.pyThe first line of output shows Vector length: 768, meaning each sentence is represented by 768 numbers. The next two lines are more interesting: the similarity of sentences 1 and 2 (both about a sleeping cat) should be clearly higher than that of sentences 1 and 3, even though almost all of the words are different. Interesting, right?
Vectors from Ollama are already normalized (their length is 1), so cosine similarity can be computed simply by summing the products of their elements. A value close to 1 means the meanings are very similar.
Step #5: Write the Indexing Script
Now let's write the script that reads all documents, splits them into chunks, and stores them in ChromaDB. Create a file named indeks.py:
from pathlib import Path
import chromadb
import ollama
FOLDER_DOKUMEN = Path("dokumen")
MODEL_EMBEDDING = "embeddinggemma"
UKURAN_CHUNK = 800 # maximum number of characters per chunk
def potong_teks(teks, ukuran=UKURAN_CHUNK):
"""Merge paragraphs into chunks of roughly `ukuran` characters."""
paragraf = [p.strip() for p in teks.split("\n\n") if p.strip()]
chunks = []
sekarang = ""
for p in paragraf:
if sekarang and len(sekarang) + len(p) > ukuran:
chunks.append(sekarang)
sekarang = p
else:
sekarang = f"{sekarang}\n\n{p}" if sekarang else p
if sekarang:
chunks.append(sekarang)
return chunks
client = chromadb.PersistentClient(path="chroma_db")
koleksi = client.get_or_create_collection(
name="dokumen",
embedding_function=None,
configuration={"hnsw": {"space": "cosine"}},
)
daftar_berkas = sorted(FOLDER_DOKUMEN.glob("*.txt")) + sorted(FOLDER_DOKUMEN.glob("*.md"))
for berkas in daftar_berkas:
chunks = potong_teks(berkas.read_text(encoding="utf-8"))
if not chunks:
continue
# Turn all chunks into vectors in a single call
hasil = ollama.embed(model=MODEL_EMBEDDING, input=chunks)
# Remove old data from the same file, then store the new data
koleksi.delete(where={"sumber": berkas.name})
koleksi.add(
ids=[f"{berkas.name}-{i}" for i in range(len(chunks))],
documents=chunks,
embeddings=hasil["embeddings"],
metadatas=[{"sumber": berkas.name} for _ in chunks],
)
print(f"{berkas.name}: {len(chunks)} chunk")
print(f"Done. Total chunks in the database: {koleksi.count()}")Let's go through the important parts:
potong_teks(): splits a document by paragraph (separated by blank lines), then merges paragraphs until they approach 800 characters. Cutting at paragraph boundaries keeps the meaning of each chunk intact.PersistentClient(path="chroma_db"): stores the database in thechroma_dbfolder, so the indexing result survives after the script exits.embedding_function=None: tells ChromaDB that we supply the vectors ourselves (from Ollama). Without it, ChromaDB would use its own built-in embedding model."space": "cosine": sets the way distance between vectors is measured to cosine, as the Ollama documentation recommends for semantic search. ChromaDB's default isl2.metadatas: stores the source file name of each chunk, so we can show where an answer came from later.
Run the indexing script with the following command:
python indeks.pyWith the sample document above, the output looks roughly like this:
panduan-karyawan.txt: 2 chunk
Done. Total chunks in the database: 2If you see the chunk count with no error message, your documents are now stored as vectors in the chroma_db folder. Whenever the contents of the dokumen folder change, just run this script again.
Step #6: Write the Question Answering Script
This is the core part. Create a file named tanya.py:
import chromadb
import ollama
MODEL_EMBEDDING = "embeddinggemma"
MODEL_CHAT = "llama3.2"
JUMLAH_CHUNK = 3
PROMPT_SISTEM = (
"You are an assistant that answers questions ONLY based on the provided context. "
"If the answer is not in the context, say honestly that the information was not "
"found in the documents. Answer briefly and clearly."
)
client = chromadb.PersistentClient(path="chroma_db")
koleksi = client.get_collection(name="dokumen", embedding_function=None)
print("Ask anything about your documents. Type 'exit' to quit.")
while True:
pertanyaan = input("\nYou: ").strip()
if not pertanyaan:
continue
if pertanyaan.lower() in ("keluar", "exit"):
break
# 1. Retrieval: find the chunks most similar to the question
vektor = ollama.embed(model=MODEL_EMBEDDING, input=pertanyaan)
hasil = koleksi.query(
query_embeddings=vektor["embeddings"],
n_results=JUMLAH_CHUNK,
)
potongan = hasil["documents"][0]
sumber = [meta["sumber"] for meta in hasil["metadatas"][0]]
# 2. Augmentation: insert those chunks into the prompt
konteks = "\n\n---\n\n".join(potongan)
pesan = [
{"role": "system", "content": PROMPT_SISTEM},
{"role": "user", "content": f"Context:\n{konteks}\n\nQuestion: {pertanyaan}"},
]
# 3. Generation: ask the model to answer, streamed
print("AI: ", end="", flush=True)
for bagian in ollama.chat(model=MODEL_CHAT, messages=pesan, stream=True):
print(bagian["message"]["content"], end="", flush=True)
print(f"\n(Source: {', '.join(sorted(set(sumber)))})")Notice that the three comments in the code follow the three words in the RAG acronym exactly:
- Retrieval: the question is turned into a vector with the same embedding model used for indexing, then
koleksi.query()returns the 3 closest chunks. The result is a list inside a list (one list per question), which is why we take index[0]. - Augmentation: the chunks that were found are joined into a single context text, then placed in the user message together with the question.
- Generation: the chat model answers based on that context. The system prompt plays an important role here, because it instructs the model not to make things up when the answer is not in the context.
Step #7: Test the RAG with Questions
Time to try it out. Run the question answering script:
python tanya.pyThen ask a question whose answer is in the document. The conversation goes roughly like this (the model's wording can differ on every run):
Ask anything about your documents. Type 'exit' to quit.
You: How many days of annual leave do I get?
AI: Every permanent employee gets 14 working days of annual leave.
(Source: panduan-karyawan.txt)
You: Which days can I work from home?
AI: Employees may work from home every Tuesday and Thursday.
(Source: panduan-karyawan.txt)Cool, right? The llama3.2 model was never trained on that employee handbook, yet it can answer correctly because we handed it the right piece of the document.
Also try a question whose answer is not in the document, such as "How big is the year-end bonus?". If the system prompt is doing its job, the model will say the information was not found instead of inventing a number.
Our sample document only produces 2 chunks, fewer than
JUMLAH_CHUNK. In that case ChromaDB simply returns the chunks it has, and may print a warning that the number of requested results is greater than the number of items in the database. The warning goes away once you add more documents.
The Source line shows the files the retrieved chunks came from. It is not a guarantee that the model's answer is correct. For anything important, still check the original document.
Tips for More Accurate RAG Answers
Tip #1: Adjust the Chunk Size
Chunk size is the setting with the biggest impact. Chunks that are too large mix many topics, which makes the search less sharp, while chunks that are too small lose context. A value of 500–1,000 characters is a reasonable starting point for paragraph-style documents. Change UKURAN_CHUNK, rerun indeks.py, and compare the results.
Keep in mind that EmbeddingGemma only reads about 2,000 tokens per text. By default, Ollama truncates text that is longer than that limit, so the tail end of an overly long chunk is not represented in its vector.
Tip #2: Tune the Number of Retrieved Chunks
The JUMLAH_CHUNK value decides how many pieces are given to the model. Too few, and important information can be missed. Too many, and the prompt gets long, answers get slower, and a small model gets "confused" more easily. For a model like llama3.2, a value of 3 to 5 is usually enough.
Tip #3: Inspect the Search Results When an Answer Is Off
If the model's answer is wrong, check what the search found before blaming the model. Add the following lines to tanya.py after koleksi.query():
for teks, jarak in zip(hasil["documents"][0], hasil["distances"][0]):
print(f"[distance {jarak:.3f}] {teks[:80]}...")A smaller distance means the chunk is more similar to the question. If the correct chunk doesn't show up at all, the problem is in the retrieval stage (chunk size or embedding model), not in the chat model.
Tip #4: Use the EmbeddingGemma Prompt Format
According to its official model card, EmbeddingGemma can produce more optimized embeddings when the text is prefixed according to its task. For search, the format is task: search result | query: in front of the question, and title: none | text: in front of a document.
If you want to try it, change the two ollama.embed() calls as follows. In indeks.py:
hasil = ollama.embed(
model=MODEL_EMBEDDING,
input=[f"title: none | text: {c}" for c in chunks],
)And in tanya.py:
vektor = ollama.embed(
model=MODEL_EMBEDDING,
input=f"task: search result | query: {pertanyaan}",
)Don't forget to rerun indeks.py after changing it. This format is specific to EmbeddingGemma, so don't use it with other embedding models.
Tip #5: Try Other Embedding Models
EmbeddingGemma is not the only option. Here are some popular embedding models in the Ollama library at the time of writing:
| Model | Download Size | Notes |
|---|---|---|
embeddinggemma |
±622 MB | Multilingual (100+ languages), 2,000-token context |
bge-m3 |
±1.2 GB | Multilingual (100+ languages), supports documents up to 8,192 tokens |
nomic-embed-text |
±274 MB | The lightest of the three |
Important: vectors from different embedding models cannot be mixed. Every time you change
MODEL_EMBEDDING, delete thechroma_dbfolder withrm -r chroma_db, then rerunindeks.py.
Troubleshooting Common Problems
Here are some problems you may run into, along with their solutions:
| Problem | Likely Cause | Solution |
|---|---|---|
ModuleNotFoundError: No module named 'chromadb' |
The script was run outside the venv | Activate the venv with source .venv/bin/activate |
| Connection error to Ollama | The Ollama server is not running | Check with systemctl status ollama or curl http://localhost:11434 |
model ... not found error |
The model has not been downloaded | Run ollama pull embeddinggemma and ollama pull llama3.2 |
Error saying the dokumen collection does not exist when running tanya.py |
Indexing has not been run | Run python indeks.py first |
| Embedding dimension mismatch error | The embedding model was changed after indexing | Delete the chroma_db folder, then rerun indeks.py |
| Answers don't match the documents | The retrieved chunks are not relevant | Follow Tip #1 through Tip #3 above |
Conclusion
From this article, we can conclude that building a local RAG is not as complicated as it sounds. With Ollama, ChromaDB, and fewer than 100 lines of Python, you now have an AI that can answer questions based on your own documents, without sending a single line to the internet.
Things to Remember
- RAG uses two models: an embedding model for searching, and a chat model for answering.
- The embedding model used for indexing and for asking must be the same. If you change it, reindex from scratch.
- Answer quality is largely determined by search quality. When an answer is off, check the retrieved chunks first.
- A firm system prompt helps prevent the model from making things up, but it doesn't guarantee it.
Next Steps
From here, you can take this system further: add PDF support, combine RAG with conversation history, or wrap it in an API. If you want this script to run continuously on a server, check out the guide on how to create a systemd service on Linux.
Resources and Useful Links
- Ollama embeddings documentation
- EmbeddingGemma in the Ollama library
- ChromaDB documentation
- Ollama Python library on GitHub
If you have questions or run into trouble while following this tutorial, feel free to ask. Stay tuned to Teknotut!
I hope this article helps.



