RAG Knowledge Assistant
Tech Stack
- Next.js
- React
- TypeScript
- Tailwind CSS
- TanStack Query
- FastAPI
- PostgreSQL
- pgvector
- ARQ (Redis)
- FastEmbed
- FlashRank
- Groq
- Docker Compose
About the Project
This is a "chat with your own documents" app. You sign in, create a knowledge base, upload a few PDFs or Word docs, and then ask questions in plain language. Instead of guessing, it finds the most relevant pieces of your documents first, hands those to an LLM, and asks it to answer only using that evidence — with citations pointing back to the exact page it came from. If it can't find anything relevant, it says so instead of making something up.
Timeline
Nov 2026
Platforms
Web
Things Learnt in this Project
- Put the LLM, the embedding model, and the reranker behind small adapter interfaces — swapping the LLM provider mid-project touched exactly one folder
- Used Reciprocal Rank Fusion to merge semantic and keyword search results, so two differently-scaled ranking methods never need score normalization
- Kept rag/ (retrieval math, prompt building) free of any database or HTTP dependency, so the hybrid-search ranking formula is unit-testable on its own
- Deleted and re-inserted all of a document's chunks in one transaction, so a crashed and retried ingestion job can never leave duplicate or half-written chunks
- Made abstention deterministic in code — if retrieval returns nothing, the app returns a fixed 'no relevant info' message without even calling the LLM
- Sent the citation list before the answer text over the SSE stream, so the UI can show its sources while the answer is still being typed out
The Big Picture
The interesting part of this project isn't the chat UI — it's everything that happens between "user uploads a PDF" and "user gets a trustworthy, cited answer." It's a modular monolith, not microservices: one deployable FastAPI backend, but split into clear internal layers — thin API routes, a service layer with the real business logic, repositories that own every database query, a pure rag/ module with no database or HTTP dependency at all, swappable provider adapters for the LLM/embeddings/reranker, and background workers for anything too slow to run inside a request.
Ingestion: What Happens When You Upload a Document
"Parse the PDF and embed it" sounds like one step; in practice it's a small pipeline with its own failure modes. The API saves the raw bytes to object storage and hands the job to a background worker immediately, so nobody waits for a 40-page PDF to finish processing. A format-specific parser turns the file into text blocks with page numbers and headings. A cleaning step then detects repeated headers and footers — short text that shows up as the first or last block on at least half the pages is almost certainly junk, and gets dropped. The cleaned text is split into token-aware chunks that each remember which heading they fell under, embedded in batches, and only written to Postgres once every earlier step has succeeded — as one transaction that deletes all of that document's old chunks and inserts the new ones. That delete-then-insert trick is what makes a crashed, retried job safe: there's never a risk of ending up with duplicate or half-written chunks.
Retrieval: Finding the Right Pieces of Your Documents
Given a question, it first checks if this is a follow-up in an ongoing conversation and, if so, asks the LLM to rewrite it into a standalone query that resolves vague references like "the 2023 one." That query then runs through two searches in parallel: semantic search over pgvector, which catches meaning ("annual revenue" matching "yearly income"), and Postgres full-text search, which catches exact strings embeddings are bad at — product codes, invoice numbers, acronyms. The two ranked lists score things on completely different scales, so instead of normalizing scores, Reciprocal Rank Fusion combines them using each chunk's rank position in each list — a chunk near the top of either list scores highly. An optional cross-encoder reranker can then re-score the fused list by looking at the query and each chunk together instead of independently, though it's off by default and falls back to a no-op that just preserves the fused order. Finally, ranked chunks are greedily added to the context until a token budget or chunk-count limit is hit — every one of these numbers is a config setting, not a hardcoded value.
Generation: Turning Chunks Into a Trustworthy Answer
Having the right chunks doesn't automatically mean the LLM uses them correctly. The system prompt is explicit about grounding — answer only from the retrieved context, cite inline with [1], [2] markers, never invent a source — and retrieved content is wrapped as clearly data-only so a weird or malicious document can't smuggle in instructions. Abstention is handled in code, not left to the model's judgment: if retrieval returns zero candidates, the app returns a fixed "couldn't find anything relevant" message without calling the LLM at all. The answer streams back over Server-Sent Events, with the citation list sent before the answer text — so the UI can show what it's drawing from while the response is still being typed out.
The Data Model
Documents, ingestion jobs, and chunks each track their own status and progress. Citations deliberately copy the document name and excerpt onto the message instead of linking live to the chunk, with foreign keys set to ON DELETE SET NULL: a citation is a historical receipt of what the user was shown, and it has to survive even if the source document is later deleted or re-indexed. If citations joined live instead, re-indexing a document could silently rewrite history.
Where It Stands
Done: auth and sessions, knowledge base and document management, streaming chat, async ingestion for PDF/DOCX/TXT/HTML/Markdown, hybrid retrieval with RRF, optional reranking, grounded generation with citations, and deterministic abstention. The pipeline is wired up end to end but still needs automated tests for the fusion math, the reranker, and the citation-writing path — that's next, before answer-quality evaluation, conversation summaries, and shareable read-only conversation links.