How saidibnerradi603/pdf-rag-chatbot works
1. System shape
- This is a two-tier app: a React/Vite SPA on the client side and a FastAPI backend on the server side.
- The backend is not just a CRUD API; it also orchestrates a full PDF RAG pipeline and talks to multiple external AI services and Supabase.
2. Frontend boundary
- The frontend lives under frontend/src and is organized around pages, feature components (auth, chat, documents), API clients, custom hooks, and an AuthContext.
- Data access is centralized through Axios-based API modules plus a separate streaming client for chat responses, so the UI is mostly a thin orchestration layer over backend endpoints.
3. Backend entry and API surface
- backend/src/main.py is the FastAPI entry point, with CORS and health/root endpoints.
- Versioned routes are grouped under backend/src/api/v1, with separate endpoint modules for auth, documents, parse, chunk, embed, process, retrieve, and chat.
4. Backend layering
- The backend is explicitly split into:
- API endpoints: request/response handling
- services: business logic
- schemas: Pydantic models for validation and serialization
- core: settings and external client factories
- utils: shared helpers like file validation and hashing
- This creates a clean boundary between transport concerns and RAG/business logic.
5. Authentication and access control
- Auth is delegated to Supabase Auth, but the backend verifies JWTs itself using JWKS / ES256.
- Protected routes depend on authenticated user context, and the database also enforces row-level security so access control exists at both the API and storage layers.
6. Document storage and metadata
- Uploaded PDFs are stored in Supabase Storage under per-user paths.
- Document metadata, status, and ownership live in Supabase PostgreSQL tables, with the documents record acting as the anchor for the rest of the pipeline.
- File validation and SHA-256 hashing are used to reject invalid or duplicate uploads before processing.
7. Ingestion pipeline
- The core ingestion path is: upload → parse → chunk → embed → store.
- ProcessService coordinates the workflow, while specialized services handle each step:
- ParseService uses LlamaParse to convert PDFs into markdown/text
- ChunkService splits parsed content into semantic chunks
- EmbedService calls Cohere embeddings
- results are written into Supabase with vector support
- Document status transitions are tracked so the UI can poll progress and prevent duplicate processing.
8. Retrieval and chat pipeline
- Query-time flow is: user question → query embedding → vector search → prompt assembly → Gemini response.
- RetrievalService performs semantic search against pgvector using a document-scoped search function.
- ChatService combines retrieved chunks, conversation history, and prompt templates, then calls Gemini 2.5 Flash to produce grounded answers.
- Chat can be returned as normal JSON or as SSE streaming, which the frontend consumes for real-time token display.
9. Database and persistence model
- The SQL schema in backend/src/sql/db.sql defines the main entities:
- users
- documents
- chunks
- conversations
- messages
- citations
- chunks.embedding is stored as a 1024-dim vector and indexed for similarity search.
- Citations are first-class records, so responses can be traced back to source chunks and similarity scores.
10. Operational and external service boundaries
- The backend depends on three external AI services with distinct roles:
- LlamaParse for document parsing
- Cohere for embeddings
- Gemini for generation
- Supabase is the persistence and auth substrate: PostgreSQL, pgvector, storage, and authentication all live there.
- This means the app’s critical runtime boundaries are: browser ↔ FastAPI, FastAPI ↔ Supabase, and FastAPI ↔ AI providers.
11. Frontend state and interaction model
- The frontend uses hooks like useChat, useConversations, useDocuments, and useProcessing to encapsulate server interaction and UI state.
- Pages are centered around login/signup and a dashboard that combines document management with chat.
- The chat UI includes markdown rendering, citations display, and typing/streaming feedback, reflecting the backend’s grounded-response design.
12. Deployment/runtime implications
- The repo is set up for local development with uvicorn for FastAPI and Vite for the frontend dev server.
- The frontend expects the backend API base URL via VITE_API_BASE_URL; the backend expects Supabase and AI provider credentials via environment variables.
- For an architecture diagram, the most important deployment assumption is that the frontend is a standalone SPA calling a separate API server, not server-rendered.
Main entry points: services Services · router.py API router · pages Pages · core Core
Components 23
Frontend
React/Vite SPA for authentication, document management, and chat UX
- SPA · Client-side application shell and route composition
frontend/src/main.jsx - Pages · Login, signup, and dashboard screens
frontend/src/pages - Auth UI · Login and signup form components
frontend/src/components/auth/AuthForm.jsx - Chat UI · Conversation view, input, rendering, and citations
frontend/src/components/chat - Docs UI · Upload, listing, status, and document cards
frontend/src/components/documents - Auth context · Client auth session and user state
frontend/src/context/AuthContext.jsx - Hooks · Chat, documents, conversations, and processing orchestration
frontend/src/hooks - API clients · REST client modules for auth, documents, conversations, and streaming
frontend/src/api
Backend
FastAPI API and RAG orchestration layer
- App entry · FastAPI application setup, CORS, root, and health endpoints
backend/src/main.py - API router · Versioned endpoint aggregation and request routing
backend/src/api/v1/router.py - Auth API · Authentication and token-protected identity routes
backend/src/api/v1/endpoints/auth.py - Docs API · Document upload and metadata endpoints
backend/src/api/v1/endpoints/document.py - Pipeline API · Parse, chunk, embed, process, and retrieve endpoints
backend/src/api/v1/endpoints - Chat API · Grounded chat and streaming response endpoints
backend/src/api/v1/endpoints/chat.py - Services · Auth, document, parsing, chunking, embedding, retrieval, chat, and process services
backend/src/services - Schemas · Validation and serialization models for API and pipeline payloads
backend/src/schemas - Core · Settings and external client factories
backend/src/core - DB schema · Users, documents, chunks, conversations, messages, and citations tables
backend/src/sql/db.sql - File utils · File validation and hashing helpers
backend/src/utils/file_utils.py
External services
Persistence, auth, and AI provider boundaries
- Supabase · PostgreSQL, pgvector, storage, auth, and row-level security
- LlamaParse · PDF to text/markdown extraction
- Cohere · Text embedding generation for chunks and queries
- Gemini · Grounded answer generation and streaming tokens
Connections 28
- SPA → Pages: renders · SPA composes the main page routes
- Pages → Auth UI: uses · Login and signup pages use auth forms
- Pages → Chat UI: uses · Dashboard surfaces chat interaction
- Pages → Docs UI: uses · Dashboard surfaces document management
- SPA → Auth context: shares state · App-wide authentication session state
- SPA → Hooks: orchestrates · UI behavior is driven through custom hooks
- Hooks → API clients: calls · Hooks delegate server communication to API modules
- API clients → App entry: requests · Browser talks to the FastAPI server
- App entry → API router: mounts · Main app exposes versioned API routes
- API router → Auth API: routes · Auth endpoints are grouped under v1
- API router → Docs API: routes · Document endpoints are grouped under v1
- API router → Pipeline API: routes · Ingestion and retrieval endpoints are grouped under v1
- API router → Chat API: routes · Chat endpoints are grouped under v1
- Auth API → Supabase: verifies identity · JWT verification and user lookup rely on Supabase auth
- Docs API → File utils: validates · Uploads are checked and deduplicated before processing
- Docs API → Services: delegates · Document operations are handled by services
- Pipeline API → Services: delegates · Parse, chunk, embed, process, and retrieve logic lives in services
- Chat API → Services: delegates · Chat orchestration and retrieval are service-backed
- Services → Schemas: uses · Services exchange typed payloads through Pydantic models
- Services → Core: uses · Services consume config and provider clients
- Services → Supabase: persists · Documents, chunks, conversations, messages, and citations are stored in Supabase
- Core → LlamaParse: creates client · Parsing client integration
- Core → Cohere: creates client · Embedding client integration
- Core → Gemini: creates client · Generation client integration
- Services → LlamaParse: parses with · Parse service extracts PDF content through LlamaParse
- Services → Cohere: embeds with · Embedding service calls Cohere
- Services → Gemini: generates with · Chat service produces grounded answers with Gemini
- Services → DB schema: matches · Service behavior follows the defined persistence model