--- title: Docent AI Policy Chatbot emoji: πŸ“š colorFrom: green colorTo: gray sdk: docker app_port: 7860 pinned: false --- # Docent AI β€” NVIDIA RAG Policy Chatbot A production-ready Retrieval-Augmented Generation (RAG) chatbot that answers questions strictly from uploaded policy PDFs. Powered by NVIDIA's `llama-3.3-70b-instruct` and LangChain, with Supabase-backed user accounts and persistent chat history. ## Features - **User authentication** (Supabase email/password) β€” each user has their own private chats - **Admin role** β€” only emails listed in `ADMIN_EMAILS` can upload/manage documents; everyone else can only chat (enforced server-side) - **Persistent chat history** β€” conversations are stored in Supabase and reload on login; rename or delete them from the sidebar - **Conversational memory** β€” follow-up questions ("what about for managers?") are understood using prior turns via a history-aware retriever - **Streaming answers** β€” tokens appear as they are generated (server-sent events), with a stop button to cancel - **Clickable references with PDF preview** β€” every answer cites file + page; clicking a citation opens the PDF in an in-page modal at that exact page with the retrieved passage highlighted (PDF.js) - Answers come **only from the documents** β€” strict context-only prompt, temperature 0, and low-relevance chunks are filtered out before reaching the LLM - **Markdown-rendered answers** (sanitised with DOMPurify) - Upload one or many PDF documents; they are indexed and **persisted** in a FAISS vector store; duplicates are skipped and ingestion runs off the event loop so chat stays responsive - Automatic **fallback to a lighter model** when NVIDIA's free 70B endpoint is congested (504s) ## Project Structure ``` docent-ai-nvidia/ β”œβ”€β”€ .env # NVIDIA API key + Supabase keys β”œβ”€β”€ supabase_schema.sql # Run once in the Supabase SQL editor β”œβ”€β”€ requirements.txt β”œβ”€β”€ documents/ # Uploaded PDFs are stored here β”œβ”€β”€ vector_db/ # Persisted FAISS index β”œβ”€β”€ backend/ β”‚ β”œβ”€β”€ main.py # FastAPI app + auth + history endpoints β”‚ β”œβ”€β”€ rag.py # History-aware RAG engine β”‚ β”œβ”€β”€ db.py # Supabase auth + chat persistence β”‚ └── ingest.py # PDF ingestion + FAISS management └── frontend/ β”œβ”€β”€ index.html β”œβ”€β”€ style.css └── script.js ``` ## Setup ### 1. Install dependencies ```powershell cd c:\docent-ai-nvidia pip install -r requirements.txt ``` ### 2. Verify `.env` The `.env` file should contain: ``` NVIDIA_API_KEY=nvapi-... SUPABASE_URL=https://.supabase.co SUPABASE_ANON_KEY=eyJ... SUPABASE_SERVICE_ROLE_KEY=eyJ... ADMIN_EMAILS=admin@example.com # comma-separated; these users can upload PDFs ``` Optional overrides: `CHAT_MODEL` (default `nvidia/llama-3.3-nemotron-super-49b-v1.5`), `CONDENSE_MODEL` (default `meta/llama-3.1-8b-instruct`, also used as the fallback answer model), and `FIRST_TOKEN_TIMEOUT` (default 25s β€” how long to wait for the primary model before answering with the fallback). ### 3. Set up Supabase (one time) 1. Open your project β†’ **SQL Editor** β†’ **New query**. 2. Paste the contents of `supabase_schema.sql` and click **Run**. This creates the `chat_sessions` and `messages` tables with row-level security. 3. (Recommended for quick testing) Go to **Authentication β†’ Providers β†’ Email** and turn **off** "Confirm email" so new sign-ups can log in immediately. Leave it on in production and users will receive a confirmation email. ### 4. Run the server From the project root: ```powershell cd c:\docent-ai-nvidia run ``` Or double-click `run.bat`. Then open [http://localhost:8000](http://localhost:8000). ### 5. Open the chatbot Go to [http://localhost:8000](http://localhost:8000) in your browser. ## Deploy for free (Hugging Face Spaces) The repo ships a `Dockerfile` and the pre-built `vector_db/`, so the deployed app works out of the box. Hugging Face Spaces' free tier gives 16 GB RAM (enough for the heavy `faiss`/`langchain` deps) with no credit card. 1. Create a free account at [huggingface.co](https://huggingface.co). 2. **New β†’ Space**: pick a name, **SDK = Docker** (Blank template), visibility Public. 3. Push this project to the Space's git repo (or upload the files), e.g.: ```bash git init git add . git commit -m "Docent AI" git remote add origin https://huggingface.co/spaces// git push origin main ``` 4. In the Space β†’ **Settings β†’ Variables and secrets**, add these **secrets**: `NVIDIA_API_KEY`, `SUPABASE_URL`, `SUPABASE_ANON_KEY`, `SUPABASE_SERVICE_ROLE_KEY`. 5. Run `supabase_schema.sql` in the Supabase SQL Editor and turn **off** "Confirm email". 6. The Space builds and serves at `https://-.hf.space`. > `.env` is gitignored and never deployed β€” all keys come from Space secrets. > Runtime PDF uploads are ephemeral on free tiers (they reset on rebuild); the > committed `vector_db/` is what ships. Re-ingest locally and push to update it. ## Usage 1. **Upload PDFs** β€” drag-and-drop or click "Drop PDFs here" in the sidebar and click **Upload**. 2. **Ask questions** β€” type in the chat box and press Enter. 3. **See sources** β€” each answer shows which document and page the information came from. 4. **Add more documents** β€” upload additional PDFs at any time; they are merged into the existing index. ## API Reference All routes except `/` and `/config` require a Supabase access token in the `Authorization: Bearer ` header. | Method | Path | Description | |--------|------|-------------| | `GET` | `/` | Serves the chat UI | | `GET` | `/config` | Public Supabase URL + anon key for the frontend | | `GET` | `/me` | Current user's email + admin flag (auth) | | `GET` | `/docs/{filename}` | Serves an original PDF (used by the reference preview) | | `POST` | `/upload` | Upload one or more PDF files (**admin**) | | `GET` | `/documents` | List all ingested document filenames (**admin**) | | `GET` | `/sessions` | List the user's conversations (auth) | | `POST` | `/sessions` | Create a new conversation (auth) | | `GET` | `/sessions/{id}/messages` | Load a conversation's messages (auth) | | `PATCH` | `/sessions/{id}` | Rename a conversation (auth) | | `DELETE` | `/sessions/{id}` | Delete a conversation (auth) | | `POST` | `/chat` | Send a question, stream the answer + sources (auth) | ### `/chat` request body ```json { "question": "What is the leave policy?", "session_id": "optional-existing-session-uuid" } ``` If `session_id` is omitted, a new conversation is created automatically. ### `/chat` response (server-sent event stream) ``` data: {"type": "meta", "session_id": "…", "title": "…", "sources": [ {"file": "hr-policy.pdf", "page": 4, "snippets": ["…retrieved text…"], "image_urls": []}]} data: {"type": "delta", "text": "According"} data: {"type": "delta", "text": " to the"} ... data: {"type": "done"} ``` `meta` arrives first (session + citations), then `delta` tokens as the model generates, and finally `done`. A `{"type": "error"}` event is sent if the LLM fails mid-stream. The full answer is persisted to Supabase when the stream ends. ## How conversational memory works On each `/chat` call the backend loads the recent turns of that conversation from Supabase and (a) rewrites the follow-up into a standalone question for retrieval, and (b) passes the history to the LLM so references like "it" / "that policy" resolve correctly. The strict "answer only from the documents" rule still applies. ## Tech Stack | Component | Library | |-----------|---------| | LLM | `langchain-nvidia-ai-endpoints` β€” `ChatNVIDIA` (`nvidia/llama-3.3-nemotron-super-49b-v1.5`) | | Embeddings | `NVIDIAEmbeddings` (`nvidia/nv-embedqa-e5-v5`) | | Vector store | `faiss-cpu` (persisted to disk) | | Auth & history | Supabase (Postgres + Auth) | | PDF loading | `pypdf` via `PyPDFLoader` | | Framework | `langchain` | | Backend | `fastapi` + `uvicorn` | | Frontend | HTML + CSS + Vanilla JS + `@supabase/supabase-js` |