File size: 8,172 Bytes
35fbb15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6aa66a
 
35fbb15
c6aa66a
 
 
 
 
 
35fbb15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6aa66a
35fbb15
 
c6aa66a
 
 
 
 
35fbb15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6aa66a
 
 
 
35fbb15
 
 
c6aa66a
35fbb15
c6aa66a
35fbb15
 
 
 
 
 
 
 
 
 
 
 
c6aa66a
35fbb15
 
c6aa66a
 
 
 
 
 
 
 
 
 
 
 
35fbb15
 
 
 
 
 
 
 
 
 
 
 
c6aa66a
35fbb15
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
---
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://<project-ref>.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/<user>/<space-name>
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://<user>-<space-name>.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 <token>` 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` |