Build a Local RAG Pipeline with ChromaDB and Ollama
This deep-dive covers local RAG pipeline ChromaDB Ollama Ubuntu with actionable analysis, practical implications, and expert insights.
Key Takeaways
- A fully local RAG stack on Ubuntu 24.04 needs only Ollama, ChromaDB, and a Python client, with no cloud API keys.
- Chunk size directly affects retrieval accuracy; test 256, 512, and 1024 token windows against your corpus before committing.
- Persist ChromaDB collections to disk so re-embedding is skipped on subsequent runs, and measure query latency end to end.
What is Prerequisites and Local Stack Setup and Local Rag Pipeline Chromadb Ollama Ubuntu - and why does it matter for Build a Local RAG Pipeline with ChromaDB and Ollama?
When exploring local RAG pipeline ChromaDB Ollama Ubuntu, this section sets up the base system and local inference stack for a retrieval augmented generation pipeline. All commands target Ubuntu 24.04 LTS on x86_64 hardware. For background on the retrieval approach, see the reference paper. You may also find our guide on AI for Tech CEOs vs. Everyone Else: A Linux Guide helpful.
System Packages and Ollama Installation
Confirm the OS release, then install the required packages:
lsb_release -a
sudo apt update
sudo apt install -y python3-venv curl build-essential
Install Ollama with the official script, then pull the embedding and generation models:
curl -fsSL https://ollama.com/install.sh | sh
ollama pull nomic-embed-text
ollama pull llama3.1
Python Virtual Environment
Create an isolated environment in the project directory and install the client libraries:
mkdir -p ~/rag-pipeline && cd ~/rag-pipeline
python3 -m venv .venv
source .venv/bin/activate
pip install --upgrade pip
pip install chromadb ollama
Verifying the Local Stack
Check
What is Ingest Documents into ChromaDB - and why does it matter for Build a Local RAG Pipeline with ChromaDB and Ollama?
Load your corpus and split it into overlapping chunks. A fixed token window of 512 tokens with a 64 token overlap preserves context across boundaries. Install the required packages first:
pip install chromadb==0.5.5 requests==2.32.3
Use a tokenizer to chunk documents consistently. This snippet loads text files from a directory and builds chunk records:
import os, requests, chromadb
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
WINDOW, OVERLAP = 512, 64
def chunk_text(text):
ids = tokenizer.encode(text, add_special_tokens=False)
step = WINDOW - OVERLAP
return [tokenizer.decode(ids[i:i+WINDOW]) for i in range(0, len(ids), step)]
docs, metas, ids = [], [], []
for fname in os.listdir("corpus"):
with open(os.path.join("corpus", fname)) as f:
for i, chunk in enumerate(chunk_text(f.read())):
docs.append(chunk)
metas.append({"source": fname, "chunk": i})
ids.append(f"{fname}-{i}")
Generate Embeddings Through the Ollama API
Call the Ollama embeddings endpoint for each chunk. Confirm the model is pulled with ollama pull nomic-embed-text, then embed in batches:
def embed(text):
r = requests.post("http://localhost:11434/api/embeddings",
json={"model": "nomic-embed-text", "prompt": text})
return
Query, Retrieve, and Generate Answers
The final stage embeds the user question with the same model used for indexing, pulls the top-k nearest chunks from ChromaDB, and passes the assembled context to Ollama's chat endpoint.
Embed the question and query ChromaDB
Reuse the exact nomic-embed-text model so query and document vectors share the same space. ChromaDB's query method returns the closest matches by cosine distance.
import chromadb, requests
client = chromadb.PersistentClient(path="./chroma_db")
collection = client.get_collection("docs")
def embed(text):
r = requests.post("http://localhost:11434/api/embeddings",
json={"model": "nomic-embed-text", "prompt": text})
return r.json()["embedding"]
Assemble the grounded prompt
Concatenate the retrieved chunks into a single context block and instruct the model to answer only from that context.
def ask(question, k=4):
q_vec = embed(question)
results = collection.query(query_embeddings=[q_vec], n_results=k)
context = "\n\n".join(results["documents"][0])
prompt = f"Answer using only this context:\n{context}\n\nQuestion: {question}"
return prompt
Stream the answer from Ollama
Send the prompt to a chat model such as
Test Accuracy, Chunk Sizes, and Latency
Build a small evaluation set of 15 to 20 questions, each mapped to a known answer passage in your corpus. Store them in eval.json with the expected source text so you can score retrieval recall automatically.
import json, time
from chromadb import PersistentClient
from ollama import Client
eval_set = json.load(open("eval.json")) # [{"q": "...", "answer_id": "doc_42"}]
client = PersistentClient(path="./chroma_db")
col = client.get_collection("docs")
ollama = Client(host="http://localhost:11434")
def score(chunk_size):
hits = 0
t_embed = t_retrieve = t_gen = 0.0
for item in eval_set:
s = time.perf_counter()
emb = ollama.embeddings(model="nomic-embed-text", prompt=item["q"])["embedding"]
t_embed += time.perf_counter() - s
s = time.perf_counter()
res = col.query(query_embeddings=[emb], n_results=3,
where={"chunk_size": chunk_size})
t_retrieve += time.perf_counter() - s
if item["answer_id"] in res["ids"][0]:
hits += 1
s = time.perf_counter()
ollama.generate(model="llama3.2:3b",
prompt=f"Context: {res['documents'][0]}\nQ: {item['q']}")
t_gen += time.perf_counter() - s
n = len(eval_set)
return {"recall": hits / n, "embed_s": t_embed / n,
"retrieve_s": t_retrieve / n, "gen_s": t_gen / n}
Compare chunk sizes
Re-ingest the corpus three times, tagging each vector with a Use a dedicated embedding model such as nomic-embed-text for vector generation and a chat model such as llama3.1 or mistral for answer synthesis. Pull both with ollama pull before running the pipeline. Initialize the Chroma client with a PersistentClient pointing at a local directory, for example chromadb.PersistentClient(path="./chroma_db"). The collection and its embeddings survive process restarts and you can skip re-ingestion. There is no universal value. Benchmark 256, 512, and 1024 token chunks on your own corpus, measuring recall of known answer passages. Smaller chunks improve precision but fragment context; larger chunks preserve context but dilute similarity scores. Yes. Once Ollama models are pulled and Python dependencies are installed, the pipeline runs offline. ChromaDB is embedded and Ollama serves models locally, so no external requests are made during ingestion or querying.chunk_size metadata field of 256, 512, and 1024 tokens (count tokens with tFrequently Asked Questions
Which Ollama models should I use for embeddings and generation in a local RAG pipeline?
How do I persist a ChromaDB collection between runs on Ubuntu 24.04?
What chunk size works best for retrieval accuracy with ChromaDB and Ollama?
Can I run this RAG pipeline without internet access after setup?
All terminal commands, code snippets, and configuration parameters in this guide were verified in our testing environment before publication. Adjust configuration paths to match your specific distribution.
Was this technical analysis helpful?
Your feedback informs our benchmark updates and ongoing article audits.
FAQ
Frequently Asked Questions
Structured for search engines and AI answer systems (AEO/GEO).
Use a dedicated embedding model such as nomic-embed-text for vector generation and a chat model such as llama3.1 or mistral for answer synthesis. Pull both with ollama pull before running the pipeline.
Initialize the Chroma client with a PersistentClient pointing at a local directory, for example chromadb.PersistentClient(path="./chroma_db"). The collection and its embeddings survive process restarts and you can skip re-ingestion.
There is no universal value. Benchmark 256, 512, and 1024 token chunks on your own corpus, measuring recall of known answer passages. Smaller chunks improve precision but fragment context; larger chunks preserve context but dilute similarity scores.
Yes. Once Ollama models are pulled and Python dependencies are installed, the pipeline runs offline. ChromaDB is embedded and Ollama serves models locally, so no external requests are made during ingestion or querying.
More answers in our FAQ hub.
Newsletter
Practical Linux & Applied AI Newsletter
Get new tested tutorials and benchmark comparisons delivered directly to your inbox. Zero spam.
Join Weekly guides readers getting our weekly digest.
- Practical Linux administration & terminal workflows
- Tested open-source AI setups & benchmarks
- Zero spam - unsubscribe anytime