How to Build a Local RAG System with Ollama and Qdrant

What RAG Is and Why Run It Locally

A large language model has two weaknesses: it cannot see your private documents, and it invents answers when it does not know one. Retrieval-Augmented Generation, or RAG, fixes both. You first search your own documents for the passages most relevant to the question, then hand those passages to the model. The model answers from evidence it can see, so responses become more accurate and easier to check.

Running it locally has three payoffs. Your documents never leave your machine, which matters for notes, contracts, and code you would not paste into a cloud chatbot. There is no per-token API bill. And once the models are downloaded, the system works offline. This guide builds it with Ollama and Qdrant. If you have not installed Ollama yet, start with our Ollama quickstart guide first.

How the Pipeline Works

Every RAG system runs the same five stages. First, documents are split into small chunks, a few hundred words each, because whole documents are too coarse to search precisely. Second, each chunk is converted into an embedding, a list of numbers capturing its meaning, so passages on the same topic sit close together in vector space. Third, those vectors are stored in a vector database. Fourth, when a question arrives, it is embedded the same way and the database returns the nearest chunks. Fifth, the question plus the retrieved chunks are sent to the language model, which writes an answer grounded in your documents.

Two details decide most of the quality: chunk size, and a prompt that tells the model to answer only from the retrieved passages.



Source: Aman's AI Journal (aman.ai)
 


Prerequisites

  • Python 3.10 or newer, with pip
  • Docker, for running Qdrant
  • Ollama installed and running
  • A folder of plain-text or Markdown documents to ask questions about (start with 5–20 files)

Install the Python dependencies:

pip install qdrant-client requests

Step 1: Pull the Models

RAG needs two models: one to embed text into vectors, one to write answers. Pull both:

ollama pull nomic-embed-text
ollama pull llama3.2

We use nomic-embed-text for embeddings because it is small, fast, and produces 768-dimensional vectors — a number that matters in Step 4, where the collection must be created with exactly that size. We use llama3.2 for answers because it runs on a typical laptop and follows grounding instructions well.

Step 2: Start Qdrant

Run Qdrant in Docker with persistent storage so indexed documents survive restarts:

docker run -d --name qdrant \
  -p 6333:6333 -p 6334:6334 \
  -v qdrant_data:/qdrant/storage \
  qdrant/qdrant

Verify it is up by opening http://localhost:6333/dashboard in your browser. Port 6333 serves the REST API and dashboard; 6334 serves gRPC. If the container name is taken, remove the old container with docker rm -f qdrant first.

Step 3: Chunk Your Documents

Save the following as local_rag.py. The chunking function splits text into ~1,000-character pieces with 150 characters of overlap, breaking at paragraph or sentence boundaries so a sentence straddling a boundary stays intact in at least one chunk.

import os
import sys
import uuid

import requests
from qdrant_client import QdrantClient
from qdrant_client.models import Distance, PointStruct, VectorParams

OLLAMA_BASE = "http://localhost:11434"
EMBED_MODEL = "nomic-embed-text"
CHAT_MODEL = "llama3.2"
COLLECTION = "docs"

def chunk_text(text, size=1000, overlap=150):
    chunks = []
    start = 0
    while start < len(text):
        end = min(start + size, len(text))
        if end < len(text):
            # Prefer a clean break at a paragraph or sentence boundary.
            cut = max(text.rfind("\n\n", start, end),
                      text.rfind(". ", start, end))
            if cut > start + size // 2:
                end = cut + 1
        piece = text[start:end].strip()
        if piece:
            chunks.append(piece)
        start = end - overlap if end < len(text) else end
    return chunks
    
def load_documents(folder):
    docs = []
    for name in sorted(os.listdir(folder)):
        if name.endswith((".txt", ".md")):
            with open(os.path.join(folder, name), encoding="utf-8") as f:
                docs.append((name, f.read()))
    return docs

Markdown and plain text are the easiest starting point. For PDFs, add a loader such as PyMuPDF later; the rest stays the same.

Step 4: Embed and Index


Source: Memgraph

Next, add the embedding and indexing functions. Embeddings go through Ollama's /api/embed endpoint, which accepts a batch of texts in one request. The collection is created with size=768 to match nomic-embed-text, and cosine distance, the standard choice for comparing text embeddings. Each point stores chunk text plus its source filename, so answers stay traceable.

def embed(texts):
    resp = requests.post(
        f"{OLLAMA_BASE}/api/embed",
        json={"model": EMBED_MODEL, "input": texts},
    )
    resp.raise_for_status()
    return resp.json()["embeddings"]
    
def index_docs(folder):
    client = QdrantClient(url="http://localhost:6333")
    client.recreate_collection(
        collection_name=COLLECTION,
        vectors_config=VectorParams(size=768, distance=Distance.COSINE),
    )
    points = []
    for filename, text in load_documents(folder):
        chunks = chunk_text(text)
        vectors = embed(chunks)
        for chunk, vector in zip(chunks, vectors):
            points.append(PointStruct(
                id=str(uuid.uuid4()),
                vector=vector,
                payload={"text": chunk, "source": filename},
            ))
    client.upsert(collection_name=COLLECTION, points=points)
    print(f"Indexed {len(points)} chunks from {folder}")

Note: recreate_collection wipes an existing collection — fine while iterating; in production, create once and upsert incrementally.

Step 5: Retrieve and Generate

The question path mirrors indexing: embed the question, fetch the five nearest chunks, and prompt the model to answer from that context only — and to say so when the answer is not in it. That second clause is the best guard against hallucination in a RAG system.

def ask(question):
    client = QdrantClient(url="http://localhost:6333")
    query_vector = embed([question])[0]
    hits = client.query_points(
        collection_name=COLLECTION,
        query=query_vector,
        limit=5,
        with_payload=True,
    )
    context = "\n\n".join(hit.payload["text"] for hit in hits.points)
    print("--- Retrieved sources ---")
    for hit in hits.points:
        print(f"score={hit.score:.3f}  source={hit.payload['source']}")
    prompt = (
        "Answer the question using ONLY the context below. "
        "If the context does not contain the answer, say so explicitly.\n\n"
        f"Context:\n{context}\n\nQuestion: {question}"
    )
    resp = requests.post(
        f"{OLLAMA_BASE}/api/chat",
        json={
            "model": CHAT_MODEL,
            "messages": [{"role": "user", "content": prompt}],
            "stream": False,
        },
    )
    resp.raise_for_status()
    print("\n--- Answer ---")
    print(resp.json()["message"]["content"])
    
if __name__ == "__main__":
    if sys.argv[1] == "index":
        index_docs(sys.argv[2] if len(sys.argv) > 2 else "docs")
    elif sys.argv[1] == "ask":
        ask(" ".join(sys.argv[2:]))

Step 6: Try It

Put a few documents in a folder named docs, index them, and ask a question answered by those documents:

python local_rag.py index docs
python local_rag.py ask "What is the refund policy?"

The first run is slow while Ollama loads the models; later queries are faster. Check the printed sources: right chunks but a wrong answer means the prompt or chat model is at fault; wrong chunks means chunking or embedding is. That separation is what makes RAG debuggable.

Troubleshooting

  • Connection refused from Qdrant: confirm the container is running with docker ps. If it exited, check docker logs qdrant for a port conflict.
  • Dimension mismatch error: the collection size must equal the embedding model's output (768 for nomic-embed-text). Switching models means recreating the collection and re-indexing.
  • Answers ignore the documents: print the retrieved chunks. If they contain the answer, strengthen the prompt or use a larger chat model. If not, try smaller chunks or a higher limit.
  • Everything is slow: embedding a large corpus takes a while on CPU. Index once, then reuse the collection.

Five Ways to Make It Better

  • Metadata filters: store author, date, or document type in the payload, then filter with Qdrant's query_filter so one project's files never leak into another project's answers.
  • Tune chunk size: 1,000 characters is a starting point. Dense technical docs often work better at 600–800 characters; narrative documents can go longer. Measure with a fixed set of test questions.
  • Hybrid search: combine vector search with keyword search so exact terms and error codes are never missed.
  • Reranking: retrieve ten or twenty candidates, score them with a small reranker, and keep the best five for generation — usually the cheapest quality upgrade available.
  • Evaluation set: write twenty questions with known answers from your documents and re-run them after every change. Without that, tuning is guesswork.

Closing

You now have a private question-answering system over your own documents, with no data leaving your machine. When you outgrow a single machine, the next decision is where the models run — see how Ollama compares with vLLM, llama.cpp, and SGLang for that choice, and our guide to serving a model with vLLM when you need high-throughput inference behind your RAG service. Start small, and let retrieval quality — not model size — drive your next upgrade.

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