Technical Documentation · v1.0

DocuMind RAG System

A production-grade Retrieval-Augmented Generation system with hybrid search, local LLM support, and semantic caching.


§1 — Abstract

DocuMind is a self-hosted, zero-cost document intelligence system. Users upload PDF, DOCX, TXT, or Markdown files; the system chunks, embeds, and indexes them into a persistent ChromaDB vector store. At query time, a hybrid retrieval pipeline combining dense cosine similarity search with global BM25 sparse retrieval is fused via Reciprocal Rank Fusion and reranked by a cross-encoder. The top passages are injected into a prompt served to a locally running Ollama LLM. Responses are streamed token-by-token via Server-Sent Events. Conversation history persists across server restarts in SQLite.

All inference runs locally. No API keys are required for core functionality. No data leaves the machine.

§2 — Introduction

Retrieval-Augmented Generation addresses the fundamental limitation of large language models: their knowledge is frozen at training time and they cannot cite primary sources. By grounding every answer in passages retrieved directly from user-supplied documents, hallucination is structurally constrained.

DocuMind extends the basic RAG pattern with three enhancements: (1) a true hybrid retrieval system that runs dense and sparse search independently over the full corpus before fusion, (2) a cross-encoder reranker that provides a second, more expensive pass to sharpen the final context window, and (3) a semantic cache that short-circuits the entire pipeline for semantically equivalent repeated queries.

Design Goals

§3 — Architecture

The system is composed of four independent layers that communicate over HTTP.

┌─────────────────────────────────────────┐
│         React Frontend  :5173           │
│  (Vite, SSE consumer, drag-drop UI)     │
└────────────────┬────────────────────────┘
                 │ HTTP / SSE
┌────────────────▼────────────────────────┐
│       FastAPI Backend  :8000            │
│  /upload  /query  /documents  /health   │
│                                         │
│  ┌──────────┐  ┌──────────┐  ┌───────┐  │
│  │ ingestor │  │retriever │  │ gen.  │  │
│  └────┬─────┘  └────┬─────┘  └───┬───┘  │
└───────┼─────────────┼────────────┼──────┘
        │             │            │
   ChromaDB       BM25.pkl     Ollama
   vectorstore    (disk)       :11434
   + SQLite
ComponentTechnologyRole
BackendFastAPI + UvicornREST API, SSE streaming
FrontendReact + ViteChat UI, file upload, benchmark
Vector storeChromaDB (persistent)Dense embeddings + semantic cache
Sparse indexrank_bm25 (pickled)Keyword retrieval over full corpus
History storeSQLitePersistent conversation memory
LLMOllamaLocal inference, zero cost
File parsingPyMuPDF + python-docxPDF, DOCX, TXT, MD ingestion

§4 — Retrieval Pipeline

Every query passes through a five-stage pipeline before reaching the LLM.

  1. Query embedding — The query is encoded by all-MiniLM-L6-v2 into a 384-dimensional vector.
  2. Dense search — ChromaDB performs approximate nearest-neighbour search using cosine similarity, returning the top min(3K, 30) candidates.
  3. BM25 sparse search — The pre-built global BM25 index scores the query against the entire corpus. Top candidates with score > 0 are kept.
  4. RRF fusion — Both ranked lists are merged via Reciprocal Rank Fusion with k=60. Any BM25-exclusive hits are fetched from ChromaDB by ID before the next stage.
  5. Cross-encoder reranking — The fused set is reranked by ms-marco-MiniLM-L-6-v2. The top-K (default 5) passages are returned.

Stage 3 runs against the full corpus independently of stage 2. This is what makes the hybrid approach meaningful — BM25 can surface exact-match documents that dense search misses entirely.

§5 — Embedding & Indexing

Documents are chunked using LangChain's RecursiveCharacterTextSplitter with a chunk size of 600 characters and 120-character overlap. Each chunk is embedded by sentence-transformers/all-MiniLM-L6-v2, a 22M parameter model that produces 384-dimensional vectors with strong semantic quality for its size.

Chunk metadata

{
  "filename":   "report.pdf",
  "page_number": 4,
  "chunk_index": 2,
  "timestamp":   1718500000,
  "file_hash":  "sha256..."
}

Deduplication is performed at ingestion time by checking for existing chunks with matching filename. After ingestion, build_bm25_index() rebuilds the global BM25 pickle from the entire ChromaDB collection and caches it in-memory.

PDF parsing

PyMuPDF (fitz) is used in preference to PyPDF2. It handles complex layouts, multi-column text, and embedded fonts significantly more reliably, producing cleaner chunks and therefore better retrieval quality.

§7 — Reranking

The fused candidate set is passed to cross-encoder/ms-marco-MiniLM-L-6-v2. Unlike bi-encoder models (used for dense retrieval), a cross-encoder accepts the query and document together as a single input, enabling full attention across both sequences.

This produces a single relevance score that is significantly more accurate than cosine similarity. The cost is quadratic in sequence length — which is why reranking is applied only to the small fused set, not the full corpus.

Both all-MiniLM-L6-v2 and ms-marco-MiniLM-L-6-v2 are pre-loaded at server startup via the FastAPI lifespan event, eliminating cold-start latency on the first request.

§8 — Generation

Retrieved chunks are formatted into a numbered context block and injected into a system-prompted message list alongside the conversation history (last 5 turns, persisted in SQLite). The assembled prompt is sent to the Ollama chat completion API with stream: true.

System prompt

You are a precise document-grounded assistant.

RULES:
1. Answer ONLY using the context passages provided.
2. If the answer is not found, respond exactly:
   "I could not find this in the uploaded documents."
3. Never fabricate facts, statistics, or citations.
4. Be concise but complete. Use bullet points where helpful.
5. Do NOT mention that you were given context.

Streaming

The FastAPI /query endpoint returns a StreamingResponse with media_type="text/event-stream". Each chunk is a JSON-encoded SSE event with a type field: token, metadata, error, or done. The React frontend consumes this with the native ReadableStream API.

§9 — Semantic Cache

Before invoking the LLM, the assembled prompt string is embedded and queried against a dedicated semantic_cache ChromaDB collection. If a semantically equivalent prompt exists with cosine distance < 0.02, the cached answer is returned immediately — bypassing retrieval, reranking, and generation entirely.

New answers are written to the cache after generation. The 0.02 threshold is conservative, activating only for near-identical queries, which avoids serving stale answers to genuinely different questions.

Cache hits reduce response latency from ~3–8 seconds (LLM generation) to <200ms (vector lookup). On repeated benchmark runs or demos, the difference is immediately perceptible.

§10 — Deployment

Prerequisites

Local setup

# Clone and enter the project
git clone https://github.com/Arjunx156/rag-system.git
cd rag-system

# Create virtual environment
python -m venv .venv
.venv\Scripts\activate        # Windows
# source .venv/bin/activate   # macOS / Linux

# Install dependencies
pip install -r requirements.txt

# Copy and configure environment
cp .env.example .env
# Edit .env — set LLM_PROVIDER=ollama, LLM_MODEL=llama3

Start services

# Terminal 1 — Backend
.venv\Scripts\uvicorn.exe backend.main:app --host 0.0.0.0 --port 8000

# Terminal 2 — React frontend
cd frontend-react
npm install
npm run dev

Backend: http://localhost:8000 · Frontend: http://localhost:5173 · API docs: http://localhost:8000/docs

Environment variables

VariableDefaultDescription
LLM_PROVIDERollamaProvider: ollama or openai
LLM_MODELllama3Model tag passed to provider
OLLAMA_BASE_URLhttp://localhost:11434Ollama server URL
CHROMA_PERSIST_DIR./vectorstoreChromaDB data directory
UPLOAD_DIR./data/uploadsUploaded file storage
CHUNK_SIZE600Characters per chunk
CHUNK_OVERLAP120Overlap between chunks
TOP_K5Chunks returned per query

§11 — API Reference

MethodEndpointDescription
POST/uploadIngest a document (multipart/form-data)
POST/queryAsk a question — returns SSE stream
GET/documentsList all ingested documents
DELETE/documents/{filename}Remove a document and its chunks
DELETE/sessions/{session_id}Clear conversation history
GET/healthService readiness check

Query request body

{
  "question":   "What does the document say about X?",
  "session_id": "uuid-string",       // optional
  "top_k":      5,                   // optional
  "model":      "llama3",            // optional override
  "provider":   "ollama"             // optional override
}

SSE event types

data: {"type": "token",    "data": "partial text..."}
data: {"type": "metadata", "data": {"session_id": "...", "chunks_retrieved": 5, ...}}
data: {"type": "error",    "data": "error message"}
data: {"type": "done"}

§12 — References