Intermediate 22 minRAG

Local RAG with ChromaDB and Ollama: tutorial Python

Local RAG with ChromaDB and Ollama: Python tutorial

Building a local ChromaDB/Ollama/Python RAG involves three interlocking pieces: a vector store that persists to disk (ChromaDB), an embeddings model that turns your chunks into vectors (nomic-embed-text via Ollama), and a chat LLM that answers based on the retrieved passages. No API key, no data leakage. This guide takes you from a raw PDF to a chatbot that cites its sources in 22 minutes.

By Mohamed Meguedmi·Update 2026-10-14·Tested on Windows, macOS, and Linux

#Why this stack for a local RAG

Many RAG tutorials start with LangChain or LlamaIndex. These frameworks are powerful but hide what's happening under the hood. Here, we write the pipeline by hand with only three dependencies. You'll understand every step and know what to optimize later.

ChromaDB
Open-source vector store, pure Python, with built-in persistent mode (SQLite + HNSW index). No server to start.
Ollama
Serves both the embeddings model (nomic-embed-text) and the chat LLM (Qwen 3.5, Granite 4.2, Gemma 4). Single HTTP endpoint on localhost:11434.
Native Python
A few functions, no framework. You can add LangChain later if needed, but it is not necessary to get started.
i
What you get
A Python script of about 150 lines that ingests a folder of PDFs, chunks them, indexes them in ChromaDB, and answers questions in French with citations. Fully local, with zero outbound requests.

#Prerequisites

The complete kit for building your own AI copilot.

Benefit from our experience and a guided path to build your local copilot and get comfortable with your coding assistant.

  • Lifetime online access
  • PDF + files
  • Refunded within 30 days
Python 3.10+
ChromaDB requires 3.10 minimum. Check with python --version.
Ollama installed and running
The daemon listens on http://localhost:11434 by default. If you’re starting from scratch, follow the Ollama installation guide first.
8 GB of RAM
16 GB is comfortable. The 9B chat model in Q4 uses ~6 GB, and the embeddings model uses ~300 MB.
A GPU isn't required
CPU inference works, just more slowly. For ingesting a large corpus, a 6 GB+ GPU greatly speeds up embeddings.

#1. Install ChromaDB and prepare Ollama

We create a clean virtual environment, install the three required libraries, and download the models on the Ollama side.

Python environment
python -m venv .venv
source .venv/bin/activate  # sous Windows : .venv\Scripts\activate
pip install chromadb ollama pypdf

Three packages: chromadb for the vector store, ollama for the official Python client, and pypdf for reading PDFs. That's it.

Ollama models
ollama pull nomic-embed-text:v1.5
ollama pull qwen3.5:9b

The workflow uses nomic-embed-text:v1.5 to make the model and its task prefixes explicit. It serves as a starting example; for a French corpus, measure search results and compare BGE-M3 in particular. Quality also depends on chunking and the documents.

→
Verify that Ollama responds
A simple curl http://localhost:11434/api/tags should list your models. If nothing appears, the daemon is not running: run ollama serve in another terminal.

#2. Configure the embeddings model

An embedding is a vector that represents the meaning of a piece of text. Two semantically similar texts have similar vectors. This is what powers RAG: we search for the chunks whose embedding most closely resembles the question’s.

embed.py — quick test
import ollama

resp = ollama.embed(
    model="nomic-embed-text:v1.5",
    input="search_document: Le contrat est résilié en cas de manquement grave.",
)
vec = resp["embeddings"][0]
print(f"Dimension du vecteur : {len(vec)}")
print(f"5 premières valeurs : {vec[:5]}")

You should see Vector dimension: 768. If it fails with model not found, ollama pull nomic-embed-text was not done.

i
Index prefixes and consistency
Nomic v1.5 requires search_document: before each chunk and search_query: before the question. Do not mix vectors produced by other models, dimensions, or conventions in the same collection. The model card does not justify a “top 5 in French” ranking for your corpus.

#3. French PDF ingestion

Ingestion does three things: reads the pages of a PDF, splits the text into reasonably sized chunks, and stores each chunk with its embedding in ChromaDB in persistent mode.

ingest.py
import os
import chromadb
import ollama
from pypdf import PdfReader

client = chromadb.PersistentClient(path="./chroma_db")
# Nouveau nom : un ancien index "docs" peut encore utiliser la distance L2.
collection = client.get_or_create_collection(
    name="docs_nomic_v15_cosine",
    configuration={"hnsw": {"space": "cosine"}},
)

def chunk_text(text, size=800, overlap=100):
    chunks = []
    start = 0
    while start < len(text):
        end = min(start + size, len(text))
        chunk = text[start:end].strip()
        if chunk:
            chunks.append(chunk)
        start += size - overlap
    return chunks

def ingest_pdf(path):
    reader = PdfReader(path)
    name = os.path.basename(path)
    # Ce dossier d'exemple suppose des noms de fichiers uniques.
    # Retire aussi les chunks devenus obsolètes si le PDF a été raccourci.
    collection.delete(where={"source": name})
    count = 0
    for page_num, page in enumerate(reader.pages):
        text = page.extract_text() or ""
        for i, chunk in enumerate(chunk_text(text)):
            emb = ollama.embed(
                model="nomic-embed-text:v1.5",
                input="search_document: " + chunk,
            )["embeddings"][0]
            collection.upsert(
                ids=[f"{name}-p{page_num}-c{i}"],
                embeddings=[emb],
                documents=[chunk],
                metadatas=[{"source": name, "page": page_num + 1}],
            )
            count += 1
    print(f"OK : {name} ({len(reader.pages)} pages, {count} chunks indexés)")

if __name__ == "__main__":
    for f in os.listdir("./pdfs"):
        if f.lower().endswith(".pdf"):
            ingest_pdf(f"./pdfs/{f}")

The chunker splits content into 800-character blocks with 100 characters of overlap. This is a starting point: not too small (lack of context) and not too large (diluted signal). For very dense legal content, reduce it to 500. For well-spaced technical manuals, increase it to 1200.

→
ChromaDB's persistent mode
PersistentClient stores the database on disk. The new name docs_nomic_v15_cosine avoids silently reusing the old L2 index. If you change the model, its prefixes, the dimension, or the distance, create a new collection and re-embed the documents. Back up the PDFs before reindexing: the script first removes the file's old chunks.

Start ingestion on a ./pdfs/ folder containing your documents:

Start ingestion
mkdir -p pdfs
# placez vos PDF dans ./pdfs/
python ingest.py
!
Scanned PDFs = no text
pypdf extracts only native text. If your PDFs are image scans, extract_text() will return nothing. You then need to use OCR (Tesseract, or a vision model such as Qwen 3.5 9B, multimodal, via Ollama) before ingestion.

#4. Top-k search in ChromaDB

The collection above explicitly selects cosine distance, unlike the default L2 setting. The question receives the search_query: prefix, then ChromaDB retrieves the closest passages in this index. get_or_create_collection does not transform an old index merely by changing its variable name.

search.py
import chromadb
import ollama

client = chromadb.PersistentClient(path="./chroma_db")
collection = client.get_collection(name="docs_nomic_v15_cosine")

def search(question, k=4):
    count = collection.count()
    if count == 0:
        return []
    q_emb = ollama.embed(
        model="nomic-embed-text:v1.5",
        input="search_query: " + question,
    )["embeddings"][0]
    results = collection.query(
        query_embeddings=[q_emb],
        n_results=min(k, count),
    )
    chunks = results["documents"][0]
    metas = results["metadatas"][0]
    return list(zip(chunks, metas))

if __name__ == "__main__":
    hits = search("Quelles sont les conditions de résiliation ?")
    for chunk, meta in hits:
        print(f"[{meta['source']} p.{meta['page']}]")
        print(chunk[:200], "...\n")

k=4 is a good default. Too small, and you miss relevant context; too large, and you drown the LLM in noise and blow up the context window. For very precise questions, k=2 is enough. For cross-cutting questions, increase it to 6.

#5. Chat loop with citations

Now let’s put it together: we find the relevant chunks, build a prompt with the context, send it to Qwen 3.5 via Ollama, and ask the model to cite its sources.

chat.py
import ollama
from search import search

SYSTEM = """Tu es un assistant qui répond uniquement à partir du CONTEXTE fourni.
Si la réponse n'est pas dans le contexte, dis-le clairement.
Cite tes sources entre crochets sous la forme [source.pdf p.X]."""

def ask(question):
    hits = search(question, k=4)
    if not hits:
        return "Aucun passage indexé disponible pour répondre."
    context = "\n\n".join(
        f"[{m['source']} p.{m['page']}]\n{c}" for c, m in hits
    )
    prompt = f"CONTEXTE :\n{context}\n\nQUESTION : {question}"
    resp = ollama.chat(
        model="qwen3.5:9b",
        messages=[
            {"role": "system", "content": SYSTEM},
            {"role": "user", "content": prompt},
        ],
        options={"temperature": 0.2, "num_ctx": 8192},
    )
    return resp["message"]["content"]

if __name__ == "__main__":
    while True:
        q = input("\nQuestion (vide pour quitter) > ").strip()
        if not q:
            break
        print("\n" + ask(q))

The num_ctx=8192 context must contain the chunks, question, instructions, and answer; reduce the number of passages if memory is insufficient. The prompt requests citations and an answer grounded in the documents, but does not guarantee the absence of hallucinations: open the cited pages and verify the claims.

→
Streaming for a better UX
Replace ollama.chat with ollama.chat(..., stream=True) and iterate over the response to display tokens as they arrive. This is crucial as soon as you integrate this code into a real interface (FastAPI + WebSocket, or Streamlit).

#6. Concrete example: legal chatbot for contracts

Imagine a firm that wants to query 200 PDF service contracts. With the stack above, in under an hour we have an assistant that can answer questions such as:

Typical question
“Which contracts include a post-termination non-compete clause longer than 12 months?”
What happens
The question embedding retrieves the chunks containing semantically related keywords (non-compete, post-termination, duration). Qwen 3.5 reads these 4 passages and responds with the names of the relevant files.
Confidentiality guarantee
No data leaves the workstation. No API key. No telemetry. That's what distinguishes a local RAG system from an OpenAI wrapper.
!
Limitations to know
A basic RAG handles targeted questions well (“what is clause X?”) and aggregate questions poorly (“how many contracts contain X?”). For the latter, you need either an agent that queries the database in multiple steps or a GraphRAG. That is another story.

#Troubleshooting

ChromaDB is slow during ingestion
Measure PDF extraction, chunking, embedding, and writing time separately. Check model placement with ollama ps. This guide does not establish a universal throughput of 50 or 500 chunks per second.
“model not found”
Ollama can’t find nomic-embed-text. Run ollama pull nomic-embed-text again and check with ollama list.
Responses that fabricate sources
A 9B model still hallucinates sometimes. Move to mistral-small (24B, ~14 GB, very good in French) or qwen3.8:27b if you have the VRAM. Or add a reranker (cross-encoder) after ChromaDB to filter false positives.
Poor-quality embeddings in French
Evaluate the retrieved passages using French questions whose answers you know. BGE-M3 is directly available with ollama pull bge-m3. If you change models, reindex into a separate collection; nomic prefixes must not be reused automatically for all models.
ChromaDB grows without limit
The updated script removes the file's chunks before re-ingesting it and uses stable IDs with upsert. This also removes old pages from a shortened PDF. It remains a simple local example: keep the original documents and a database backup.

#Sources and verification for October 14, 2026

October 14, 2026 revision: code verified with a real ChromaDB index for cosine ranking and a test PDF for re-ingestion. The embedding calls in this test use a local simulation server; the semantic quality and speed of a Ollama model still need to be measured on your corpus.

#Go further

You have a working RAG system. Here are the natural next steps to take it further:

Compare French embedding models
Our guide “The Best French Embedding Models” compares BGE, E5, Solon, and nomic on French-language content.
Improve chunking
“Chunking strategies” covers semantic chunking, chunking by Markdown headings, and chunking by paragraphs—often the approaches that unlock the biggest gains in precision.
Add a reranker
“Add a reranker to your pipeline”: +15% relevance by placing a cross-encoder after Chroma. The logical next step.
Hybrid search
“Hybrid BM25 + vector search” combines lexical and semantic search, which is essential when there's a lot of jargon or many proper names.
Did this guide help you?

Feedback, an error, or a clarification? Let us know—it improves the guide for everyone.