Building a RAG Knowledge Assistant, Part 1: What We're Building and Why
1. The problem, in one sentence
You have a pile of documents (PDFs, Word files, text files) and you want to ask them questions in plain language and get a trustworthy, cited answer back, instead of opening ten tabs and Ctrl+F-ing through each file.
That's the whole product. A user signs in, creates a knowledge base, uploads a handful of documents into it, and then chats with it. Under the hood, the system goes and finds the most relevant pieces of the documents first, hands those pieces to a language model, and tells the model: "answer using only this evidence, and show your sources." This pattern has a name: Retrieval-Augmented Generation, or RAG, and it's the reason a chatbot can answer questions about documents it was never trained on, without making things up.
"A RAG system is only as good as its retrieval. The model is the easy 20%; the pipeline that feeds it is the hard 80%."
This series walks through every real piece of that pipeline (not a toy version, the actual code) in eight parts:
- Part 1 (this one): the product, the architecture, the tech stack.
- Part 2: the database, object storage, and background jobs: the foundation everything else sits on.
- Part 3: the ingestion pipeline: turning a raw PDF into clean, searchable chunks.
- Part 4: what an embedding actually is, from first principles, and why this project picked the model it did.
- Part 5: semantic search, keyword search, and how Reciprocal Rank Fusion merges them.
- Part 6: reranking and context budgeting: picking the best evidence, not just some evidence.
- Part 7: grounded generation: prompting, citations, and refusing to guess when there's no evidence.
- Part 8: the frontend streaming chat experience, testing strategy, and what's left to build.
2. Why RAG instead of just fine-tuning a model, or just prompting it?
Three options exist for "make an LLM answer questions about my documents":
| Approach | Problem |
|---|---|
| Just ask the base model | It either has no idea about your private documents, or it confidently makes something up (a "hallucination"). |
| Fine-tune a model on your documents | Expensive, slow to update (re-upload a document → retrain?), and the model still can't reliably tell you which document a fact came from. |
| RAG: retrieve relevant passages, then generate an answer grounded in them | New documents are searchable within seconds of upload. Every answer can point back to the exact page it came from. If nothing relevant exists, the system can say so instead of guessing. |
RAG trades a bit of architectural complexity (you now need search, not just a chat endpoint) for something fine-tuning can't give you cheaply: freshness and citations. That trade is why this project is built the way it is.
3. The architecture
Click to view full screen
Four moving parts:
- Next.js UI: the chat interface and document manager the user actually touches.
- FastAPI backend: one API that both serves the UI and runs the RAG logic. Talks to the browser over regular HTTPS, with Server-Sent Events (SSE) for streaming chat answers token-by-token (a one-way stream from server to browser, simpler than a WebSocket when the browser never needs to push data back mid-stream).
- PostgreSQL + pgvector: one database for everything: normal rows (users, conversations, documents) and the vector search index. More on why that's a deliberate choice, not a shortcut, in Part 2.
- Object storage (MinIO locally, S3-compatible in production): the original uploaded files live here, not in the database. Postgres only ever stores the extracted text, chunks, and vectors.
- Background worker (ARQ + Redis): parsing a 40-page PDF and embedding every chunk takes real time. That work happens off the request path, in a separate worker process, so uploading a file returns instantly instead of making the user stare at a spinner.
Notice there's no separate "vector database" service in this stack (no Pinecone, Weaviate, Qdrant, etc.). pgvector is a PostgreSQL extension that adds a vector column type and similarity search directly inside Postgres. One database to run, back up, and reason about transactions in, instead of two systems that can silently drift out of sync.
4. The tech stack
| Layer | Technology | Why this one |
|---|---|---|
| Frontend | Next.js (App Router), React, TypeScript | Good fit for a streaming chat UI with server + client components |
| UI | Tailwind CSS, shadcn/ui, Framer Motion | Fast to build and theme, no fighting a heavy design system |
| Data fetching | TanStack Query | Caching and optimistic updates, useful for streaming message state |
| Backend | FastAPI, Pydantic | Async-first, typed request/response models, good perf without Node |
| Database | PostgreSQL 16 + pgvector | Rows and vectors in one transactional store (Part 2) |
| Background jobs | ARQ (Redis-backed) | Lightweight async job queue, no Celery/RabbitMQ overhead for this scale |
| Object storage | S3-compatible (MinIO locally) | Same API locally and in the cloud, no code branching |
| LLM | Groq, model openai/gpt-oss-120b | Fast inference; swapped in later with zero changes outside one adapter file (see §5) |
| Embeddings | FastEmbed, BAAI/bge-small-en-v1.5 | Runs locally, no per-call API cost or latency (Part 4) |
| Reranker | FlashRank, ms-marco-MiniLM-L-12-v2 | Also local, also free, optional (Part 6) |
| Local deploy | Docker Compose | Postgres, Redis, MinIO, backend, worker, frontend, one up command |
5. Two architecture decisions that shape everything else
Decision 1: a modular monolith, not microservices
Everything backend-side is one deployable FastAPI app, but internally split into clear layers with a strict rule about what each layer is allowed to know about:
- backend/app
- api
- chat.py
- services
- chat_service.py
- repositories
- document_chunk_repository.py
- rag
- ingestion
- retrieval
- generation
- providers
- llm
- embeddings
- reranking
- storage
- workers
api/: thin route handlers. Parse the request, call a service, return a response. No business logic.services/: the actual business logic ("run one chat turn").repositories/: every SQL query lives here, nowhere else.rag/: pure algorithmic code (how retrieval ranking math works, how a prompt gets built). No database import, no HTTP import. You could copy this folder into a completely different project and it would still compile.providers/: see Decision 2 below.
Why not microservices? At this scale, splitting "retrieval" and "generation" into separate deployed services would mean two things to deploy, two things to version together, and a network call where a function call used to be, all to get an isolation benefit this project doesn't need yet. The rag/ folder already gets you the testing benefit of separation (you can unit-test retrieval math with zero database or network involved) without paying the operational cost of separation.
Decision 2: every external dependency sits behind a provider adapter
The LLM, the embedding model, the reranker, and object storage are each accessed through a small interface, never directly:
# app/providers/llm/base.py (shape, simplified)
class LLMProvider(ABC):
@abstractmethod
async def stream_chat(self, messages: list[ChatMessage]) -> AsyncGenerator[StreamEvent]: ...
Groq implements LLMProvider. FastEmbed implements EmbeddingProvider. FlashRank implements RerankerProvider. Nothing in services/ or rag/ imports groq or fastembed directly: they only ever see the interface.
This paid off for real, not just in theory: the project started on a different LLM vendor and switched to Groq entirely by rewriting one file in providers/llm/. Every route, every service, every prompt: untouched. That's the entire point of an adapter: the decision to change vendors becomes cheap, even if you never planned to make it.
6. What's next
Part 2 goes one level down into the foundation: why pgvector instead of a dedicated vector database, why files live in object storage instead of the database, why background jobs exist at all, and the actual data model (users, knowledge bases, documents, chunks, conversations, citations) with the real SQLAlchemy model code.