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
- Zero ongoing cost — all models run locally via Ollama
- Production-grade reliability — persistent storage, graceful error handling
- Retrieval quality over retrieval speed — cross-encoder reranking is expensive but accurate
- Developer-friendly — FastAPI + React, SSE streaming, documented REST API
§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
| Component | Technology | Role |
|---|---|---|
| Backend | FastAPI + Uvicorn | REST API, SSE streaming |
| Frontend | React + Vite | Chat UI, file upload, benchmark |
| Vector store | ChromaDB (persistent) | Dense embeddings + semantic cache |
| Sparse index | rank_bm25 (pickled) | Keyword retrieval over full corpus |
| History store | SQLite | Persistent conversation memory |
| LLM | Ollama | Local inference, zero cost |
| File parsing | PyMuPDF + python-docx | PDF, DOCX, TXT, MD ingestion |
§4 — Retrieval Pipeline
Every query passes through a five-stage pipeline before reaching the LLM.
- Query embedding — The query is encoded by
all-MiniLM-L6-v2into a 384-dimensional vector. - Dense search — ChromaDB performs approximate nearest-neighbour search using cosine similarity, returning the top
min(3K, 30)candidates. - BM25 sparse search — The pre-built global BM25 index scores the query against the entire corpus. Top candidates with score > 0 are kept.
- 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. - 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.
§6 — Hybrid Search
The BM25 index is built over the full document corpus using rank_bm25.BM25Okapi and serialised to vectorstore/bm25_index.pkl. It is loaded into memory at startup and rebuilt whenever a document is ingested or deleted.
Reciprocal Rank Fusion
RRF combines rankings from heterogeneous retrieval systems without requiring score normalisation. For each document appearing in any ranked list, its RRF score is:
score(d) = Σ 1 / (k + rank(d, list_i))
i
With k=60 (following the original paper), this formula dampens the impact of very high ranks and rewards documents that appear consistently across multiple lists. A document ranked 1st in dense search and 3rd in BM25 will outscore a document ranked 1st in only one list.
§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
- Python 3.10–3.14
- Ollama installed and running locally
- A model pulled:
ollama pull llama3
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
| Variable | Default | Description |
|---|---|---|
LLM_PROVIDER | ollama | Provider: ollama or openai |
LLM_MODEL | llama3 | Model tag passed to provider |
OLLAMA_BASE_URL | http://localhost:11434 | Ollama server URL |
CHROMA_PERSIST_DIR | ./vectorstore | ChromaDB data directory |
UPLOAD_DIR | ./data/uploads | Uploaded file storage |
CHUNK_SIZE | 600 | Characters per chunk |
CHUNK_OVERLAP | 120 | Overlap between chunks |
TOP_K | 5 | Chunks returned per query |
§11 — API Reference
| Method | Endpoint | Description |
|---|---|---|
POST | /upload | Ingest a document (multipart/form-data) |
POST | /query | Ask a question — returns SSE stream |
GET | /documents | List all ingested documents |
DELETE | /documents/{filename} | Remove a document and its chunks |
DELETE | /sessions/{session_id} | Clear conversation history |
GET | /health | Service 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
- Lewis et al. (2020). Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks. NeurIPS.
- Robertson & Zaragoza (2009). The Probabilistic Relevance Framework: BM25 and Beyond. Foundations and Trends in IR.
- Cormack et al. (2009). Reciprocal Rank Fusion Outperforms Condorcet and Individual Rank Learning Methods. SIGIR.
- Reimers & Gurevych (2019). Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks. EMNLP.
- ChromaDB Documentation
- Ollama Model Library
- FastAPI Documentation