# saidibnerradi603/pdf-rag-chatbot architecture

> Architecture diagram of the GitHub repository saidibnerradi603/pdf-rag-chatbot, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-05-28). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/saidibnerradi603/pdf-rag-chatbot
- Repository: https://github.com/saidibnerradi603/pdf-rag-chatbot

## Overview

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: [`backend/src/services`](https://github.com/saidibnerradi603/pdf-rag-chatbot/tree/master/backend/src/services) (Services), [`backend/src/api/v1/router.py`](https://github.com/saidibnerradi603/pdf-rag-chatbot/blob/master/backend/src/api/v1/router.py) (API router), [`frontend/src/pages`](https://github.com/saidibnerradi603/pdf-rag-chatbot/tree/master/frontend/src/pages) (Pages), [`backend/src/core`](https://github.com/saidibnerradi603/pdf-rag-chatbot/tree/master/backend/src/core) (Core)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_frontend["Frontend"]
  node_spa["SPA<br/>react-vite app<br/>[main.jsx]"]
  node_pages["Pages<br/>route views"]
  node_auth_ui["Auth UI<br/>auth components<br/>[AuthForm.jsx]"]
  node_chat_ui["Chat UI<br/>chat components"]
  node_docs_ui["Docs UI<br/>document components"]
  node_auth_ctx(("Auth context<br/>state context<br/>[AuthContext.jsx]"))
  node_hooks(("Hooks"))
  node_api_client["API clients<br/>axios clients"]
end

subgraph group_backend["Backend"]
  node_app_entry["App entry<br/>fastapi app<br/>[main.py]"]
  node_api_router["API router<br/>v1 routing<br/>[router.py]"]
  node_auth_api["Auth API<br/>endpoint<br/>[auth.py]"]
  node_docs_api["Docs API<br/>endpoint<br/>[document.py]"]
  node_pipeline_api["Pipeline API<br/>endpoint group"]
  node_chat_api["Chat API<br/>endpoint<br/>[chat.py]"]
  node_services["Services<br/>business logic"]
  node_schemas["Schemas<br/>pydantic models"]
  node_core["Core<br/>config and clients"]
  node_db_schema[("DB schema<br/>sql schema<br/>[db.sql]")]
  node_file_utils["File utils<br/>helpers<br/>[file_utils.py]"]
end

subgraph group_external["External services"]
  node_supabase[("Supabase<br/>auth storage db")]
  node_llamaparse["LlamaParse<br/>pdf parsing"]
  node_cohere{{"Cohere<br/>embeddings"}}
  node_gemini{{"Gemini<br/>LLM generation"}}
end

node_spa -->|"renders"| node_pages
node_pages -->|"uses"| node_auth_ui
node_pages -->|"uses"| node_chat_ui
node_pages -->|"uses"| node_docs_ui
node_spa -->|"shares state"| node_auth_ctx
node_spa -->|"orchestrates"| node_hooks
node_hooks -->|"calls"| node_api_client
node_api_client -->|"requests"| node_app_entry
node_app_entry -->|"mounts"| node_api_router
node_api_router -->|"routes"| node_auth_api
node_api_router -->|"routes"| node_docs_api
node_api_router -->|"routes"| node_pipeline_api
node_api_router -->|"routes"| node_chat_api
node_auth_api -->|"verifies identity"| node_supabase
node_docs_api -->|"validates"| node_file_utils
node_docs_api -->|"delegates"| node_services
node_pipeline_api -->|"delegates"| node_services
node_chat_api -->|"delegates"| node_services
node_services -->|"uses"| node_schemas
node_services -->|"uses"| node_core
node_services -->|"persists"| node_supabase
node_core -->|"creates client"| node_llamaparse
node_core -->|"creates client"| node_cohere
node_core -->|"creates client"| node_gemini
node_services -->|"parses with"| node_llamaparse
node_services -->|"embeds with"| node_cohere
node_services -->|"generates with"| node_gemini
node_services -.->|"matches"| node_db_schema

click node_spa "https://github.com/saidibnerradi603/pdf-rag-chatbot/blob/master/frontend/src/main.jsx"
click node_pages "https://github.com/saidibnerradi603/pdf-rag-chatbot/tree/master/frontend/src/pages"
click node_auth_ui "https://github.com/saidibnerradi603/pdf-rag-chatbot/blob/master/frontend/src/components/auth/AuthForm.jsx"
click node_chat_ui "https://github.com/saidibnerradi603/pdf-rag-chatbot/tree/master/frontend/src/components/chat"
click node_docs_ui "https://github.com/saidibnerradi603/pdf-rag-chatbot/tree/master/frontend/src/components/documents"
click node_auth_ctx "https://github.com/saidibnerradi603/pdf-rag-chatbot/blob/master/frontend/src/context/AuthContext.jsx"
click node_hooks "https://github.com/saidibnerradi603/pdf-rag-chatbot/tree/master/frontend/src/hooks"
click node_api_client "https://github.com/saidibnerradi603/pdf-rag-chatbot/tree/master/frontend/src/api"
click node_app_entry "https://github.com/saidibnerradi603/pdf-rag-chatbot/blob/master/backend/src/main.py"
click node_api_router "https://github.com/saidibnerradi603/pdf-rag-chatbot/blob/master/backend/src/api/v1/router.py"
click node_auth_api "https://github.com/saidibnerradi603/pdf-rag-chatbot/blob/master/backend/src/api/v1/endpoints/auth.py"
click node_docs_api "https://github.com/saidibnerradi603/pdf-rag-chatbot/blob/master/backend/src/api/v1/endpoints/document.py"
click node_pipeline_api "https://github.com/saidibnerradi603/pdf-rag-chatbot/tree/master/backend/src/api/v1/endpoints"
click node_chat_api "https://github.com/saidibnerradi603/pdf-rag-chatbot/blob/master/backend/src/api/v1/endpoints/chat.py"
click node_services "https://github.com/saidibnerradi603/pdf-rag-chatbot/tree/master/backend/src/services"
click node_schemas "https://github.com/saidibnerradi603/pdf-rag-chatbot/tree/master/backend/src/schemas"
click node_core "https://github.com/saidibnerradi603/pdf-rag-chatbot/tree/master/backend/src/core"
click node_db_schema "https://github.com/saidibnerradi603/pdf-rag-chatbot/blob/master/backend/src/sql/db.sql"
click node_file_utils "https://github.com/saidibnerradi603/pdf-rag-chatbot/blob/master/backend/src/utils/file_utils.py"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_spa,node_pages,node_auth_ui,node_chat_ui,node_docs_ui,node_auth_ctx,node_hooks,node_api_client toneBlue
class node_app_entry,node_api_router,node_auth_api,node_docs_api,node_pipeline_api,node_chat_api,node_services,node_schemas,node_core,node_db_schema,node_file_utils toneAmber
class node_supabase,node_llamaparse,node_cohere,node_gemini toneMint
```

## Components

### Frontend

React/Vite SPA for authentication, document management, and chat UX

- [SPA](https://github.com/saidibnerradi603/pdf-rag-chatbot/blob/master/frontend/src/main.jsx): react-vite app · Client-side application shell and route composition · `frontend/src/main.jsx`
- [Pages](https://github.com/saidibnerradi603/pdf-rag-chatbot/tree/master/frontend/src/pages): route views · Login, signup, and dashboard screens · `frontend/src/pages`
- [Auth UI](https://github.com/saidibnerradi603/pdf-rag-chatbot/blob/master/frontend/src/components/auth/AuthForm.jsx): auth components · Login and signup form components · `frontend/src/components/auth/AuthForm.jsx`
- [Chat UI](https://github.com/saidibnerradi603/pdf-rag-chatbot/tree/master/frontend/src/components/chat): chat components · Conversation view, input, rendering, and citations · `frontend/src/components/chat`
- [Docs UI](https://github.com/saidibnerradi603/pdf-rag-chatbot/tree/master/frontend/src/components/documents): document components · Upload, listing, status, and document cards · `frontend/src/components/documents`
- [Auth context](https://github.com/saidibnerradi603/pdf-rag-chatbot/blob/master/frontend/src/context/AuthContext.jsx): state context · Client auth session and user state · `frontend/src/context/AuthContext.jsx`
- [Hooks](https://github.com/saidibnerradi603/pdf-rag-chatbot/tree/master/frontend/src/hooks): data hooks · Chat, documents, conversations, and processing orchestration · `frontend/src/hooks`
- [API clients](https://github.com/saidibnerradi603/pdf-rag-chatbot/tree/master/frontend/src/api): axios clients · REST client modules for auth, documents, conversations, and streaming · `frontend/src/api`

### Backend

FastAPI API and RAG orchestration layer

- [App entry](https://github.com/saidibnerradi603/pdf-rag-chatbot/blob/master/backend/src/main.py): fastapi app · FastAPI application setup, CORS, root, and health endpoints · `backend/src/main.py`
- [API router](https://github.com/saidibnerradi603/pdf-rag-chatbot/blob/master/backend/src/api/v1/router.py): v1 routing · Versioned endpoint aggregation and request routing · `backend/src/api/v1/router.py`
- [Auth API](https://github.com/saidibnerradi603/pdf-rag-chatbot/blob/master/backend/src/api/v1/endpoints/auth.py): endpoint · Authentication and token-protected identity routes · `backend/src/api/v1/endpoints/auth.py`
- [Docs API](https://github.com/saidibnerradi603/pdf-rag-chatbot/blob/master/backend/src/api/v1/endpoints/document.py): endpoint · Document upload and metadata endpoints · `backend/src/api/v1/endpoints/document.py`
- [Pipeline API](https://github.com/saidibnerradi603/pdf-rag-chatbot/tree/master/backend/src/api/v1/endpoints): endpoint group · Parse, chunk, embed, process, and retrieve endpoints · `backend/src/api/v1/endpoints`
- [Chat API](https://github.com/saidibnerradi603/pdf-rag-chatbot/blob/master/backend/src/api/v1/endpoints/chat.py): endpoint · Grounded chat and streaming response endpoints · `backend/src/api/v1/endpoints/chat.py`
- [Services](https://github.com/saidibnerradi603/pdf-rag-chatbot/tree/master/backend/src/services): business logic · Auth, document, parsing, chunking, embedding, retrieval, chat, and process services · `backend/src/services`
- [Schemas](https://github.com/saidibnerradi603/pdf-rag-chatbot/tree/master/backend/src/schemas): pydantic models · Validation and serialization models for API and pipeline payloads · `backend/src/schemas`
- [Core](https://github.com/saidibnerradi603/pdf-rag-chatbot/tree/master/backend/src/core): config and clients · Settings and external client factories · `backend/src/core`
- [DB schema](https://github.com/saidibnerradi603/pdf-rag-chatbot/blob/master/backend/src/sql/db.sql): sql schema · Users, documents, chunks, conversations, messages, and citations tables · `backend/src/sql/db.sql`
- [File utils](https://github.com/saidibnerradi603/pdf-rag-chatbot/blob/master/backend/src/utils/file_utils.py): helpers · File validation and hashing helpers · `backend/src/utils/file_utils.py`

### External services

Persistence, auth, and AI provider boundaries

- **Supabase**: auth storage db · PostgreSQL, pgvector, storage, auth, and row-level security
- **LlamaParse**: pdf parsing · PDF to text/markdown extraction
- **Cohere**: embeddings · Text embedding generation for chunks and queries
- **Gemini**: LLM generation · Grounded answer generation and streaming tokens

## Connections

- 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
