Pradeep Verma commited on
Commit
12bb39f
·
0 Parent(s):

Deploy PolicyAI chatbot to Hugging Face Spaces

Browse files
.gitignore ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ .env
2
+ .venv
3
+ __pycache__
4
+ qdrant_data/
5
+ data/
6
+ *.pyc
README.md ADDED
@@ -0,0 +1,381 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: PolicyAI
3
+ emoji: 🤖
4
+ colorFrom: blue
5
+ colorTo: indigo
6
+ sdk: gradio
7
+ sdk_version: "6.17.3"
8
+ app_file: chatbot/app.py
9
+ pinned: false
10
+ ---
11
+
12
+ # PolicyAI 🤖📄
13
+
14
+ > **"Your company's policies, finally answerable in seconds."**
15
+
16
+ An AI-powered policy intelligence system that reads your company's PDF documents and answers employee questions instantly — with exact citations, zero hallucination, and zero manual searching.
17
+
18
+ Built **three ways**:
19
+ - **`vanilla_rag/`** — pure Python, no frameworks, every step explicit
20
+ - **`langchain_rag/`** — same pipeline via LangChain + LCEL abstractions
21
+ - **`chatbot/`** — professional Gradio chat UI on top of the LangChain pipeline, deployable to Hugging Face Spaces
22
+
23
+ ---
24
+
25
+ ## 🚨 The Problem
26
+
27
+ Every company has the same invisible crisis.
28
+
29
+ Hundreds of policy documents sit in shared drives, intranets, and email attachments — unread, unsearchable, and impossible to navigate when someone urgently needs an answer.
30
+
31
+ **Without PolicyAI — the daily reality:**
32
+
33
+ ```
34
+ 9:00 AM — New hire asks HR: "How many sick leaves do I get?"
35
+ HR opens a 120-page PDF, searches manually...
36
+ 25 minutes later replies with an answer.
37
+
38
+ 2:00 PM — Site manager asks Safety: "What PPE is needed for excavation?"
39
+ Safety officer searches OSHA manual + internal doc...
40
+ 40 minutes wasted.
41
+
42
+ 4:00 PM — Finance asks: "What is the vendor payment approval limit?"
43
+ Three people CC'd on email. Nobody has the right version.
44
+ ```
45
+
46
+ **500 employees × 3 questions × every week = 1,500 manual searches. Every. Single. Week.**
47
+
48
+ ---
49
+
50
+ ## ✅ The Solution — PolicyAI
51
+
52
+ **With PolicyAI — the same reality:**
53
+
54
+ ```
55
+ Employee → "How many sick leaves do I get?"
56
+
57
+ PolicyAI → Employees are entitled to 18 Earned Leaves per calendar year.
58
+ Leave is calculated on a pro-rata basis for mid-year joiners.
59
+ Sick leave beyond 3 consecutive days requires a medical certificate.
60
+
61
+ 📄 Source: HR-Policy.pdf — Page 3
62
+ ⏱ Time: 3 seconds
63
+ ```
64
+
65
+ ---
66
+
67
+ ## 🔀 Three Implementations — Same Pipeline
68
+
69
+ | Step | 🐍 vanilla_rag | 🦜 langchain_rag | 💬 chatbot |
70
+ |---|---|---|---|
71
+ | **PDF Loading** | `requests` + `PyMuPDF` | `PyMuPDFLoader` | via langchain_rag |
72
+ | **Chunking** | Custom 100-word window | `RecursiveCharacterTextSplitter` | via langchain_rag |
73
+ | **Embedding** | `SentenceTransformer.encode()` | `HuggingFaceEmbeddings` | via langchain_rag |
74
+ | **Vector Store** | Manual `PointStruct` + `upsert()` | `QdrantVectorStore` | via langchain_rag |
75
+ | **Retrieval** | Manual `query_points()` | `vectorstore.as_retriever()` | via langchain_rag |
76
+ | **LLM** | Raw `groq.chat.completions` | `ChatGroq` | via langchain_rag |
77
+ | **Pipeline** | Manual `rag()` function | LCEL chain `\|` | via langchain_rag |
78
+ | **UI** | CLI / terminal | CLI / terminal | Gradio web app |
79
+ | **Deploy** | Local only | Local only | Hugging Face Spaces |
80
+
81
+ ---
82
+
83
+ ## 🏗️ How PolicyAI Works
84
+
85
+ ```
86
+ ┌─────────────────────────────────────────────────────────────┐
87
+ │ INGESTION PHASE │
88
+ │ (run once per document) │
89
+ │ │
90
+ │ PDF Document (URL or local file) │
91
+ │ ↓ │
92
+ │ Extract text page by page [PyMuPDF / PyMuPDFLoader] │
93
+ │ ↓ │
94
+ │ Split into chunks [word window / splitter] │
95
+ │ ↓ │
96
+ │ Convert each chunk → vector [all-MiniLM-L6-v2, 384-dim]│
97
+ │ ↓ │
98
+ │ Store vector + text + page [Qdrant local file store] │
99
+ └─────────────────────────────────────────────────────────────┘
100
+
101
+ ┌─────────────────────────────────────────────────────────────┐
102
+ │ QUERY PHASE │
103
+ │ (runs on every question) │
104
+ │ │
105
+ │ Employee question (plain English) │
106
+ │ ↓ │
107
+ │ Convert question → vector [same embedding model] │
108
+ │ ↓ │
109
+ │ Semantic search — top 5 chunks [Qdrant HNSW index] │
110
+ │ ↓ │
111
+ │ Build context block with citations │
112
+ │ ↓ │
113
+ │ Generate grounded answer [Groq — llama-3.1-8b] │
114
+ │ ↓ │
115
+ │ Answer + Source Document + Page Number │
116
+ └─────────────────────────────────────────────────────────────┘
117
+ ```
118
+
119
+ ---
120
+
121
+ ## 📁 Project Structure
122
+
123
+ ```
124
+ PolicyAI/
125
+ │
126
+ ├── vanilla_rag/ ← Pure Python — no frameworks
127
+ │ ├── ingestion/
128
+ │ │ ├── 01_doc_loader.py ← fetch PDF, extract pages with PyMuPDF
129
+ │ │ ├── 02_chunker.py ← split pages into 100-word chunks
130
+ │ │ ├── 03_embedder.py ← embed chunks with sentence-transformers
131
+ │ │ └── __init__.py ← re-exports all functions cleanly
132
+ │ ├── config.py ← all constants and env vars
133
+ │ ├── 01_ingest.py ← orchestrates the ingestion pipeline
134
+ │ ├── 02_query.py ← retrieve() + build_context() + rag()
135
+ │ └── 03_demo.py ← runs 5 sample questions end-to-end
136
+ │
137
+ ├── langchain_rag/ ← Same pipeline via LangChain abstractions
138
+ │ ├── config.py ← all constants and env vars
139
+ │ ├── 01_ingest.py ← PyMuPDFLoader + splitter + QdrantVectorStore
140
+ │ ├── 02_query.py ← retriever + ChatGroq + LCEL chain
141
+ │ └── 03_demo.py ← runs 5 sample questions end-to-end
142
+ │
143
+ ├── chatbot/ ← Gradio chat UI (Hugging Face Spaces ready)
144
+ │ ├── app.py ← entry point: path bootstrap + launch()
145
+ │ ├── pipeline.py ← ensure_indexed() + exposes rag()
146
+ │ ├── handlers.py ← respond() + clear_chat() handlers
147
+ │ ├── styles.py ← dark-theme CSS
148
+ │ └── ui.py ← Gradio layout + event wiring
149
+ │
150
+ ├── data/ ← PDFs downloaded here (gitignored)
151
+ ├── .env ← GROQ_API_KEY (never commit this)
152
+ ├── .gitignore
153
+ ├── requirements.txt
154
+ └── README.md
155
+ ```
156
+
157
+ ---
158
+
159
+ ## 🛠️ Tech Stack
160
+
161
+ | Layer | Technology | Why |
162
+ |---|---|---|
163
+ | **PDF Extraction** | PyMuPDF 1.27.2 | Fast, reliable, page-level metadata |
164
+ | **Chunking** | Word window / RecursiveCharacterTextSplitter | Preserves context, respects token limits |
165
+ | **Embeddings** | all-MiniLM-L6-v2 (sentence-transformers) | 384-dim semantic vectors, runs fully offline |
166
+ | **Vector Database** | Qdrant 1.18.0 | Local file-based, no Docker or server needed |
167
+ | **Search Index** | HNSW (Hierarchical Navigable Small World) | Millisecond semantic search |
168
+ | **LLM Inference** | Groq — llama-3.1-8b-instant | Free tier, ultra-fast inference |
169
+ | **Framework** | LangChain + LCEL | Industry-standard RAG abstractions |
170
+ | **Chat UI** | Gradio 6 | Web interface, one-command HF Spaces deploy |
171
+ | **Language** | Python 3.10+ | |
172
+
173
+ ---
174
+
175
+ ## 🤔 Why RAG — Not Just Asking GPT?
176
+
177
+ | Challenge | GPT Alone | PolicyAI (RAG) |
178
+ |---|---|---|
179
+ | Your private HR manual | ❌ Has never seen it | ✅ Fully indexed and searchable |
180
+ | 200-page PDF | ❌ Context window too small | ✅ Retrieves only the relevant chunks |
181
+ | Policy updated last week | ❌ Training cutoff months ago | ✅ Re-index in minutes |
182
+ | Cited, verifiable answer | ❌ Confident but unverifiable | ✅ Exact page number and section |
183
+ | Private company data | ❌ Data sent to external servers | ✅ Everything runs locally |
184
+
185
+ ---
186
+
187
+ ## 🚀 Getting Started
188
+
189
+ ### Prerequisites
190
+
191
+ - Python 3.10 or higher
192
+ - Groq API key — free at [console.groq.com](https://console.groq.com)
193
+
194
+ ### Installation
195
+
196
+ ```bash
197
+ # Clone the repository
198
+ git clone https://github.com/your-username/PolicyAI.git
199
+ cd PolicyAI
200
+
201
+ # Create and activate virtual environment
202
+ python -m venv .venv
203
+
204
+ # Windows
205
+ .venv\Scripts\activate
206
+ # Mac / Linux
207
+ source .venv/bin/activate
208
+
209
+ # Install all dependencies
210
+ pip install -r requirements.txt
211
+ ```
212
+
213
+ ### Configuration
214
+
215
+ Create a `.env` file in the project root:
216
+
217
+ ```
218
+ GROQ_API_KEY=your_groq_api_key_here
219
+ ```
220
+
221
+ ---
222
+
223
+ ## ▶️ Running the Project
224
+
225
+ ### 💬 Chatbot UI (Recommended)
226
+
227
+ The fastest way to experience PolicyAI — a professional dark-theme web interface with a chat panel and a live sources panel.
228
+
229
+ ```bash
230
+ python chatbot\app.py
231
+ ```
232
+
233
+ Then open **http://localhost:7860** in your browser.
234
+
235
+ On first run, the app automatically downloads the HR Policy PDF and indexes it (~30 seconds). Every subsequent start skips this step.
236
+
237
+ ---
238
+
239
+ ### 🐍 Vanilla RAG (CLI)
240
+
241
+ ```bash
242
+ # Step 1 — ingest the PDF (run once)
243
+ python vanilla_rag\01_ingest.py
244
+
245
+ # Step 2 — ask a question interactively
246
+ python vanilla_rag\02_query.py
247
+
248
+ # Step 3 — run the full demo with 5 sample questions
249
+ python vanilla_rag\03_demo.py
250
+ ```
251
+
252
+ ### 🦜 LangChain RAG (CLI)
253
+
254
+ ```bash
255
+ # Step 1 — ingest the PDF (run once)
256
+ python langchain_rag\01_ingest.py
257
+
258
+ # Step 2 — ask a question interactively
259
+ python langchain_rag\02_query.py
260
+
261
+ # Step 3 — run the full demo with 5 sample questions
262
+ python langchain_rag\03_demo.py
263
+ ```
264
+
265
+ ---
266
+
267
+ ## 🌐 Deploy to Hugging Face Spaces
268
+
269
+ 1. **Push this repo to GitHub**
270
+
271
+ 2. **Create a new Space** at [huggingface.co/new-space](https://huggingface.co/new-space)
272
+ - SDK: **Gradio**
273
+ - Link your GitHub repository
274
+
275
+ 3. **Set your API key** — Space Settings → Variables and Secrets → add `GROQ_API_KEY`
276
+
277
+ 4. **Add the Space config** — prepend this block to `README.md` in your Space:
278
+
279
+ ```yaml
280
+ ---
281
+ title: PolicyAI
282
+ emoji: 🤖
283
+ colorFrom: blue
284
+ colorTo: indigo
285
+ sdk: gradio
286
+ sdk_version: "6.17.3"
287
+ app_file: chatbot/app.py
288
+ pinned: false
289
+ ---
290
+ ```
291
+
292
+ On cold start, the Space automatically downloads and indexes the PDF (~60 seconds), then serves queries instantly.
293
+
294
+ ---
295
+
296
+ ## 💡 Sample Questions
297
+
298
+ ```
299
+ HR Domain
300
+ ─────────────────────────────────────
301
+ "What are the leave entitlements for employees?"
302
+ "What is the maternity leave policy?"
303
+ "How does the performance appraisal process work?"
304
+ "What are the travel expense reimbursement rules?"
305
+ "What are the disciplinary action procedures?"
306
+
307
+ IT & Security Domain
308
+ ─────────────────────────────────────
309
+ "Can employees use personal devices for work?"
310
+ "What should I do if I suspect a security breach?"
311
+ "What is the password policy?"
312
+ ```
313
+
314
+ ---
315
+
316
+ ## 🧠 Key Concepts Demonstrated
317
+
318
+ **RAG (Retrieval-Augmented Generation)** — instead of asking the LLM from memory, we retrieve the most relevant document chunks first, then ask the LLM to answer using only those chunks. This prevents hallucination and makes every answer verifiable.
319
+
320
+ **Semantic search** — questions are matched to chunks by *meaning*, not keywords. *"How many days off do I get?"* finds the leave policy even though it doesn't use the word "leave".
321
+
322
+ **LCEL chain (LangChain)** — LangChain Expression Language lets you declare the entire RAG pipeline with the `|` operator:
323
+
324
+ ```python
325
+ rag_chain = (
326
+ {"context": retriever | format_docs, "question": RunnablePassthrough()}
327
+ | RAG_PROMPT
328
+ | llm
329
+ | StrOutputParser()
330
+ )
331
+ ```
332
+
333
+ **Same embedding model at ingestion and query time** — vectors are only comparable when produced by the same model. Using a different model at query time returns meaningless results.
334
+
335
+ **Separation of concerns (chatbot/)** — each file has exactly one responsibility: `pipeline.py` owns RAG init, `handlers.py` owns Gradio callbacks, `styles.py` owns CSS, `ui.py` owns layout, `app.py` is the entry point.
336
+
337
+ ---
338
+
339
+ ## 🗺️ Roadmap
340
+
341
+ ```
342
+ Phase 1 — Complete ✅
343
+ ✅ HR Policy document ingestion and Q&A
344
+ ✅ Page-level citations
345
+ ✅ Semantic search with Qdrant
346
+ ✅ Groq LLM grounded answers
347
+ ✅ vanilla_rag — pure Python, no frameworks
348
+ ✅ langchain_rag — LangChain + LCEL chain
349
+ ✅ chatbot/ — Gradio UI, Hugging Face Spaces ready
350
+
351
+ Phase 2 — Next 🔲
352
+ 🔲 Multi-domain support (HR + Safety + IT + Legal)
353
+ 🔲 Source filtering (HR questions → search only HR docs)
354
+ 🔲 Upgrade PDF parsing to Docling (hierarchical chunking)
355
+
356
+ Phase 3 — Future 🔲
357
+ 🔲 REST API via FastAPI
358
+ 🔲 Slack bot integration
359
+ 🔲 Role-based access — employees only see permitted documents
360
+ 🔲 Conflict detection — "Do these two policies contradict each other?"
361
+ 🔲 Auto-refresh — re-index when a document is updated
362
+ ```
363
+
364
+ ---
365
+
366
+ ## 📝 License
367
+
368
+ MIT License — free to use, modify, and distribute.
369
+
370
+ ---
371
+
372
+ ## 🙏 Acknowledgements
373
+
374
+ - [Qdrant](https://qdrant.tech) — open-source vector database
375
+ - [Sentence Transformers](https://www.sbert.net) — all-MiniLM-L6-v2 embedding model
376
+ - [Groq](https://console.groq.com) — fast LLM inference
377
+ - [LangChain](https://python.langchain.com) — LLM application framework
378
+ - [Gradio](https://gradio.app) — web UI framework for ML apps
379
+
380
+ ---
381
+
chatbot/app.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ app.py — PolicyAI Chatbot entry point
3
+
4
+ Responsibilities (and ONLY these)
5
+ -----------------------------------
6
+ 1. Bootstrap the Python path so sibling modules can import from langchain_rag/.
7
+ 2. Import the pre-built Gradio demo from ui.py.
8
+ 3. Call demo.launch() with server settings and the CSS theme.
9
+
10
+ Run locally
11
+ -----------
12
+ cd D:\\...\\PolicyAI
13
+ python chatbot\\app.py
14
+
15
+ Hugging Face Spaces
16
+ -------------------
17
+ Set GROQ_API_KEY as a Space secret.
18
+ README.md frontmatter: app_file: chatbot/app.py
19
+ """
20
+
21
+ import os
22
+ import sys
23
+ from pathlib import Path
24
+
25
+ # ── Path bootstrap (must happen before any project imports) ───────────────────
26
+ # ROOT = PolicyAI/ (one level above chatbot/)
27
+ ROOT = Path(__file__).parent.parent
28
+
29
+ # Anchor relative paths (./qdrant_data, ./data/) to the project root
30
+ os.chdir(ROOT)
31
+
32
+ # Allow `from config import ...` and `import 02_query` to resolve from langchain_rag/
33
+ sys.path.insert(0, str(ROOT / "langchain_rag"))
34
+
35
+ # ── Application imports (after path bootstrap) ────────────────────────────────
36
+ from ui import demo # builds the Gradio layout + wires events
37
+ from styles import CSS # dark-theme stylesheet
38
+
39
+
40
+ # ── Launch ────────────────────────────────────────────────────────────────────
41
+ if __name__ == "__main__":
42
+ demo.launch(
43
+ server_name="0.0.0.0", # bind all interfaces (required for HF Spaces)
44
+ server_port=7860, # HF Spaces default port
45
+ share=False,
46
+ css=CSS,
47
+ )
chatbot/handlers.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ handlers.py — Gradio event handlers for PolicyAI Chatbot
3
+
4
+ Functions
5
+ ---------
6
+ respond(message, history) : run the RAG pipeline and append to chat history.
7
+ clear_chat() : reset chat, input, and sources to empty state.
8
+ """
9
+
10
+ from pipeline import rag
11
+
12
+
13
+ def respond(message: str, history: list) -> tuple[list, str]:
14
+ """
15
+ Called on every user message (Send button or Enter key).
16
+
17
+ Parameters
18
+ ----------
19
+ message : plain-text question from the user.
20
+ history : current Gradio chat history (list of role/content dicts).
21
+
22
+ Returns
23
+ -------
24
+ updated_history : history with the new user + assistant turn appended.
25
+ context : retrieved source chunks — displayed in the Sources panel.
26
+ """
27
+ if not message.strip():
28
+ return history, ""
29
+
30
+ answer, context = rag(message)
31
+
32
+ updated_history = history + [
33
+ {"role": "user", "content": message},
34
+ {"role": "assistant", "content": answer},
35
+ ]
36
+ return updated_history, context
37
+
38
+
39
+ def clear_chat() -> tuple[list, str, str]:
40
+ """Reset the chat, input field, and sources panel."""
41
+ return [], "", ""
chatbot/pipeline.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pipeline.py — RAG pipeline initialisation for PolicyAI Chatbot
3
+
4
+ Responsibilities
5
+ ----------------
6
+ - ensure_indexed() : download the HR Policy PDF and build the Qdrant index
7
+ on first run; skipped on every subsequent start.
8
+ - rag : the callable imported from langchain_rag/02_query.py.
9
+ Exposed here so the rest of the chatbot imports from
10
+ one place instead of reaching into langchain_rag directly.
11
+
12
+ NOTE: sys.path and os.chdir are set by app.py *before* this module is
13
+ imported, so `from config import ...` resolves to langchain_rag/config.py.
14
+ """
15
+
16
+ import importlib
17
+ from pathlib import Path
18
+
19
+ from qdrant_client import QdrantClient
20
+ from config import (
21
+ QDRANT_PATH, COLLECTION_NAME, PDF_URL,
22
+ EMBEDDING_MODEL, CHUNK_SIZE, CHUNK_OVERLAP,
23
+ )
24
+
25
+
26
+ def ensure_indexed() -> None:
27
+ """
28
+ Check whether the Qdrant collection already exists.
29
+ If not: download the PDF, chunk it, embed it, and store it in Qdrant.
30
+ """
31
+ client = QdrantClient(path=QDRANT_PATH)
32
+ exists = client.collection_exists(COLLECTION_NAME)
33
+ client.close()
34
+
35
+ if exists:
36
+ print(f"[pipeline] Collection '{COLLECTION_NAME}' ready.")
37
+ return
38
+
39
+ print(f"[pipeline] Collection not found — indexing PDF...")
40
+
41
+ import requests
42
+ from langchain_community.document_loaders import PyMuPDFLoader
43
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
44
+ from langchain_huggingface import HuggingFaceEmbeddings
45
+ from langchain_qdrant import QdrantVectorStore
46
+
47
+ root = Path(__file__).parent.parent
48
+ pdf_path = root / "data" / "HR-Policy.pdf"
49
+ pdf_path.parent.mkdir(parents=True, exist_ok=True)
50
+
51
+ if not pdf_path.exists():
52
+ print("[pipeline] Downloading PDF...")
53
+ resp = requests.get(PDF_URL, timeout=60)
54
+ resp.raise_for_status()
55
+ pdf_path.write_bytes(resp.content)
56
+
57
+ pages = PyMuPDFLoader(str(pdf_path)).load()
58
+ chunks = RecursiveCharacterTextSplitter(
59
+ chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP
60
+ ).split_documents(pages)
61
+ embedder = HuggingFaceEmbeddings(
62
+ model_name=f"sentence-transformers/{EMBEDDING_MODEL}"
63
+ )
64
+ QdrantVectorStore.from_documents(
65
+ documents=chunks, embedding=embedder,
66
+ path=QDRANT_PATH, collection_name=COLLECTION_NAME,
67
+ force_recreate=True,
68
+ )
69
+ print(f"[pipeline] Indexed {len(chunks)} chunks into '{COLLECTION_NAME}'.")
70
+
71
+
72
+ def _load_rag():
73
+ """Import and return the rag() function from langchain_rag/02_query.py."""
74
+ module = importlib.import_module("02_query")
75
+ return module.rag
76
+
77
+
78
+ # Run ingestion check at import time, then expose rag()
79
+ ensure_indexed()
80
+ rag = _load_rag()
chatbot/styles.py ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ styles.py — CSS theme for PolicyAI Chatbot
3
+ """
4
+
5
+ CSS = """
6
+ /* ─────────────────────── Google Font ─────────────────────── */
7
+ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
8
+
9
+ /* ─────────────────────── Design tokens ───────────────────── */
10
+ :root {
11
+ --bg-base : #070b14;
12
+ --bg-panel : #0d1422;
13
+ --bg-raised : #111c2e;
14
+ --border : rgba(99,130,188,0.12);
15
+ --border-lit : rgba(99,130,188,0.28);
16
+ --accent : #3b82f6;
17
+ --accent-dim : rgba(59,130,246,0.18);
18
+ --accent-glow: rgba(59,130,246,0.35);
19
+ --text-hi : #f0f4ff;
20
+ --text-mid : #8fa3c8;
21
+ --text-lo : #3d546e;
22
+ --radius-lg : 18px;
23
+ --radius-md : 12px;
24
+ --radius-sm : 8px;
25
+ --font : 'Inter', ui-sans-serif, system-ui, sans-serif;
26
+ --mono : 'JetBrains Mono', 'Fira Code', 'Courier New', monospace;
27
+ }
28
+
29
+ /* ─────────────────────── Page / container ─────────────────── */
30
+ body,
31
+ .gradio-container {
32
+ background : var(--bg-base) !important;
33
+ font-family: var(--font) !important;
34
+ color : var(--text-hi) !important;
35
+ }
36
+
37
+ .gradio-container {
38
+ max-width: 1380px !important;
39
+ padding : 28px 24px !important;
40
+ margin : 0 auto !important;
41
+ }
42
+
43
+ /* ─────────────────────── Strip Gradio chrome ──────────────── */
44
+ footer,
45
+ .footer { display : none !important; }
46
+ .block,
47
+ .form { background : transparent !important;
48
+ border : none !important;
49
+ box-shadow : none !important;
50
+ padding : 0 !important; }
51
+ label > span { display : none !important; }
52
+
53
+ /* ─────────────────────── Header card ─────────────────────── */
54
+ #policyai-header {
55
+ background : linear-gradient(135deg, #0d1730 0%, #0f1d36 60%, #10172b 100%);
56
+ border : 1px solid var(--border-lit);
57
+ border-radius: var(--radius-lg);
58
+ padding : 30px 36px 26px;
59
+ margin-bottom: 20px;
60
+ position : relative;
61
+ overflow : hidden;
62
+ }
63
+
64
+ #policyai-header::before {
65
+ content : '';
66
+ position: absolute;
67
+ inset : 0;
68
+ background: radial-gradient(ellipse 60% 80% at 80% 30%,
69
+ rgba(59,130,246,0.07) 0%, transparent 70%),
70
+ radial-gradient(ellipse 40% 60% at 10% 80%,
71
+ rgba(129,140,248,0.05) 0%, transparent 60%);
72
+ pointer-events: none;
73
+ }
74
+
75
+ .header-logo {
76
+ font-size : 2.2rem;
77
+ font-weight: 700;
78
+ line-height: 1.15;
79
+ margin-bottom: 4px;
80
+ }
81
+
82
+ /* Emoji rendered normally — gradient clip breaks emoji rendering */
83
+ .logo-icon {
84
+ display : inline-block;
85
+ -webkit-text-fill-color: initial;
86
+ background : none;
87
+ }
88
+
89
+ /* Only the text word gets the shimmer gradient */
90
+ .logo-text {
91
+ background : linear-gradient(110deg, #60a5fa 20%, #a78bfa 55%, #60a5fa 90%);
92
+ background-size : 200% 100%;
93
+ -webkit-background-clip: text;
94
+ -webkit-text-fill-color: transparent;
95
+ background-clip : text;
96
+ animation : shimmer 5s linear infinite;
97
+ }
98
+
99
+ @keyframes shimmer {
100
+ 0% { background-position: 100% 0; }
101
+ 100% { background-position: -100% 0; }
102
+ }
103
+
104
+ .header-sub {
105
+ font-size : 0.9rem;
106
+ color : var(--text-mid);
107
+ margin : 0 0 18px;
108
+ font-weight: 400;
109
+ }
110
+
111
+ .badge-row { display: flex; gap: 8px; flex-wrap: wrap; }
112
+
113
+ .badge {
114
+ display : inline-flex;
115
+ align-items : center;
116
+ gap : 5px;
117
+ padding : 4px 11px;
118
+ border-radius: 20px;
119
+ font-size : 11.5px;
120
+ font-weight : 500;
121
+ letter-spacing: 0.02em;
122
+ user-select : none;
123
+ }
124
+ .badge-b { background: rgba(59,130,246,0.14); border: 1px solid rgba(59,130,246,0.3); color: #93c5fd; }
125
+ .badge-g { background: rgba(52,211,153,0.12); border: 1px solid rgba(52,211,153,0.3); color: #6ee7b7; }
126
+ .badge-v { background: rgba(129,140,248,0.13); border: 1px solid rgba(129,140,248,0.3); color: #c4b5fd; }
127
+ .badge-o { background: rgba(251,191,36,0.11); border: 1px solid rgba(251,191,36,0.28); color: #fde68a; }
128
+
129
+ /* ─────────────────────── Chat panel ──────────────────────── */
130
+ #policyai-chat {
131
+ background : var(--bg-panel) !important;
132
+ border : 1px solid var(--border) !important;
133
+ border-radius: var(--radius-lg) !important;
134
+ padding : 6px !important;
135
+ }
136
+
137
+ /* User bubble — container + all text */
138
+ #policyai-chat .message.user,
139
+ #policyai-chat [data-testid="user-message"],
140
+ #policyai-chat .user-row .message-bubble-border {
141
+ background : linear-gradient(135deg, #1d4ed8, #2563eb) !important;
142
+ border-radius: 16px 16px 4px 16px !important;
143
+ box-shadow : 0 4px 18px rgba(37,99,235,0.3) !important;
144
+ border : none !important;
145
+ padding : 12px 16px !important;
146
+ }
147
+
148
+ #policyai-chat .message.user,
149
+ #policyai-chat .message.user *,
150
+ #policyai-chat [data-testid="user-message"],
151
+ #policyai-chat [data-testid="user-message"] * {
152
+ color: #ffffff !important;
153
+ }
154
+
155
+ /* Bot bubble — container */
156
+ #policyai-chat .message.bot,
157
+ #policyai-chat [data-testid="bot-message"],
158
+ #policyai-chat .bot-row .message-bubble-border {
159
+ background : #1a2744 !important;
160
+ border : 1px solid rgba(99,130,188,0.22) !important;
161
+ border-radius: 16px 16px 16px 4px !important;
162
+ box-shadow : 0 2px 14px rgba(0,0,0,0.3) !important;
163
+ padding : 12px 16px !important;
164
+ }
165
+
166
+ /* Bot bubble — force all text visible */
167
+ #policyai-chat .message.bot,
168
+ #policyai-chat .message.bot p,
169
+ #policyai-chat .message.bot span,
170
+ #policyai-chat .message.bot li,
171
+ #policyai-chat .message.bot ul,
172
+ #policyai-chat .message.bot ol,
173
+ #policyai-chat .message.bot strong,
174
+ #policyai-chat .message.bot em,
175
+ #policyai-chat .message.bot code,
176
+ #policyai-chat .message.bot a,
177
+ #policyai-chat .message.bot h1,
178
+ #policyai-chat .message.bot h2,
179
+ #policyai-chat .message.bot h3,
180
+ #policyai-chat [data-testid="bot-message"],
181
+ #policyai-chat [data-testid="bot-message"] * {
182
+ color: #dde6f5 !important;
183
+ }
184
+
185
+ /* ─────────────────────── Input bar ────────────────────────── */
186
+ #policyai-input-row {
187
+ display : flex !important;
188
+ align-items : flex-end !important;
189
+ gap : 10px !important;
190
+ background : var(--bg-panel) !important;
191
+ border : 1px solid var(--border-lit) !important;
192
+ border-radius: var(--radius-lg) !important;
193
+ padding : 10px 12px !important;
194
+ margin-top : 10px !important;
195
+ transition : border-color .2s !important;
196
+ }
197
+
198
+ #policyai-input-row:focus-within {
199
+ border-color : var(--accent) !important;
200
+ box-shadow : 0 0 0 3px var(--accent-dim) !important;
201
+ }
202
+
203
+ #policyai-msg textarea {
204
+ background : transparent !important;
205
+ border : none !important;
206
+ box-shadow : none !important;
207
+ color : var(--text-hi) !important;
208
+ font-family : var(--font) !important;
209
+ font-size : 14.5px !important;
210
+ line-height : 1.55 !important;
211
+ resize : none !important;
212
+ padding : 4px 0 !important;
213
+ }
214
+
215
+ #policyai-msg textarea::placeholder { color: var(--text-lo) !important; }
216
+ #policyai-msg .wrap { background: transparent !important; border: none !important; }
217
+
218
+ /* ─────────────────────── Send button ─────────────────────── */
219
+ #policyai-send {
220
+ background : linear-gradient(135deg, #2563eb, #1d4ed8) !important;
221
+ border : none !important;
222
+ border-radius: var(--radius-md) !important;
223
+ color : #fff !important;
224
+ font-family : var(--font) !important;
225
+ font-size : 13.5px !important;
226
+ font-weight : 600 !important;
227
+ padding : 10px 20px !important;
228
+ min-width : 78px !important;
229
+ cursor : pointer !important;
230
+ transition : all .2s ease !important;
231
+ box-shadow : 0 4px 14px rgba(37,99,235,0.4) !important;
232
+ flex-shrink : 0 !important;
233
+ }
234
+
235
+ #policyai-send:hover {
236
+ background : linear-gradient(135deg, #3b82f6, #2563eb) !important;
237
+ transform : translateY(-1px) !important;
238
+ box-shadow : 0 6px 22px rgba(59,130,246,0.5) !important;
239
+ }
240
+
241
+ #policyai-send:active { transform: translateY(0) !important; }
242
+
243
+ /* ─────────────────────── Clear button ────────────────────── */
244
+ #policyai-clear {
245
+ background : rgba(239,68,68,0.08) !important;
246
+ border : 1px solid rgba(239,68,68,0.2) !important;
247
+ border-radius: var(--radius-md) !important;
248
+ color : #f87171 !important;
249
+ font-size : 13px !important;
250
+ font-weight : 500 !important;
251
+ padding : 10px 14px !important;
252
+ flex-shrink : 0 !important;
253
+ transition : all .2s ease !important;
254
+ }
255
+
256
+ #policyai-clear:hover {
257
+ background : rgba(239,68,68,0.16) !important;
258
+ border-color : rgba(239,68,68,0.45) !important;
259
+ }
260
+
261
+ /* ─────────────────────── Right panel ─────────────────────── */
262
+ .panel-section {
263
+ background : var(--bg-panel);
264
+ border : 1px solid var(--border);
265
+ border-radius: var(--radius-lg);
266
+ overflow : hidden;
267
+ margin-bottom: 12px;
268
+ }
269
+
270
+ .panel-title {
271
+ font-size : 10.5px;
272
+ font-weight : 600;
273
+ letter-spacing: 0.1em;
274
+ text-transform: uppercase;
275
+ color : var(--text-lo);
276
+ padding : 14px 16px 10px;
277
+ border-bottom: 1px solid var(--border);
278
+ }
279
+
280
+ .panel-body { padding: 10px 10px 12px; }
281
+
282
+ /* Question buttons */
283
+ .q-btn button {
284
+ background : transparent !important;
285
+ border : 1px solid var(--border) !important;
286
+ border-radius: var(--radius-sm) !important;
287
+ color : #7da8e0 !important;
288
+ font-family : var(--font) !important;
289
+ font-size : 13px !important;
290
+ font-weight : 400 !important;
291
+ text-align : left !important;
292
+ padding : 9px 13px !important;
293
+ width : 100% !important;
294
+ margin-bottom: 5px !important;
295
+ transition : all .18s ease !important;
296
+ line-height : 1.4 !important;
297
+ white-space : normal !important;
298
+ }
299
+
300
+ .q-btn button:hover {
301
+ background : var(--accent-dim) !important;
302
+ border-color : rgba(59,130,246,0.4) !important;
303
+ color : #bfdbfe !important;
304
+ padding-left : 17px !important;
305
+ }
306
+
307
+ /* ─────────────────────── Sources box ─────────────────────── */
308
+ #policyai-sources textarea {
309
+ background : transparent !important;
310
+ border : none !important;
311
+ box-shadow : none !important;
312
+ color : #6b8aad !important;
313
+ font-family : var(--mono) !important;
314
+ font-size : 11.5px !important;
315
+ line-height : 1.65 !important;
316
+ padding : 14px 16px !important;
317
+ resize : none !important;
318
+ }
319
+ #policyai-sources textarea::placeholder { color: var(--text-lo) !important; }
320
+ #policyai-sources .wrap { background: transparent !important; border: none !important; }
321
+
322
+ /* ─────────────────────── App footer ──────────────────────── */
323
+ #policyai-footer {
324
+ text-align : center;
325
+ font-size : 11.5px;
326
+ color : var(--text-lo);
327
+ padding : 14px 0 2px;
328
+ border-top : 1px solid var(--border);
329
+ margin-top : 6px;
330
+ }
331
+
332
+ #policyai-footer a { color: #3d546e; text-decoration: none; transition: color .15s; }
333
+ #policyai-footer a:hover { color: var(--accent); }
334
+ #policyai-footer .sep { margin: 0 8px; opacity: .4; }
335
+
336
+ /* ─────────────────────── Scrollbar ────────────────────────── */
337
+ ::-webkit-scrollbar { width: 3px; height: 3px; }
338
+ ::-webkit-scrollbar-track { background: transparent; }
339
+ ::-webkit-scrollbar-thumb { background: rgba(99,130,188,0.2); border-radius: 3px; }
340
+ ::-webkit-scrollbar-thumb:hover { background: rgba(99,130,188,0.4); }
341
+ """
chatbot/ui.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ui.py — Gradio layout and event wiring for PolicyAI Chatbot
3
+
4
+ Exports
5
+ -------
6
+ demo : gr.Blocks instance — passed to demo.launch() in app.py.
7
+ """
8
+
9
+ import gradio as gr
10
+
11
+ from handlers import respond, clear_chat
12
+
13
+ SAMPLE_QUESTIONS = [
14
+ "What are the leave entitlements for employees?",
15
+ "What is the maternity leave policy?",
16
+ "How does performance appraisal work?",
17
+ "What are the travel expense reimbursement rules?",
18
+ "What are the disciplinary action procedures?",
19
+ ]
20
+
21
+ # ── Layout ─────────────────────────────────────────────────────────────────────
22
+ with gr.Blocks(title="PolicyAI — HR Intelligence") as demo:
23
+
24
+ # ── Header ─────────────────────────────────────────────────────────────────
25
+ gr.HTML("""
26
+ <div id="policyai-header">
27
+ <div class="header-logo">
28
+ <span class="logo-icon">🤖</span>
29
+ <span class="logo-text">PolicyAI</span>
30
+ </div>
31
+ <p class="header-sub">
32
+ AI-powered HR policy intelligence &mdash; instant answers grounded in your
33
+ official documents with exact page citations.
34
+ </p>
35
+ <div class="badge-row">
36
+ <span class="badge badge-b">⚡ Groq &middot; llama-3.1-8b</span>
37
+ <span class="badge badge-g">&#10003; Zero hallucination</span>
38
+ <span class="badge badge-v">&#128196; Page-level citations</span>
39
+ <span class="badge badge-o">&#128274; Runs locally</span>
40
+ </div>
41
+ </div>
42
+ """)
43
+
44
+ # ── Main two-column layout ──────────────────────────────────────────────────
45
+ with gr.Row(equal_height=False):
46
+
47
+ # ── Left — chat interface ───────────────────────────────────────────
48
+ with gr.Column(scale=63):
49
+
50
+ chatbot = gr.Chatbot(
51
+ value=[],
52
+ height=500,
53
+ show_label=False,
54
+ layout="bubble",
55
+ elem_id="policyai-chat",
56
+ placeholder=(
57
+ "<div style='text-align:center;padding:70px 20px;'>"
58
+ "<div style='font-size:44px;margin-bottom:14px;'>🤖</div>"
59
+ "<div style='font-size:15px;font-weight:600;color:#2a3f5a;'>"
60
+ "Ask PolicyAI anything</div>"
61
+ "<div style='font-size:13px;margin-top:8px;color:#1e2f42;'>"
62
+ "Select a quick question on the right, or type your own below.</div>"
63
+ "</div>"
64
+ ),
65
+ )
66
+
67
+ with gr.Row(elem_id="policyai-input-row"):
68
+ msg_input = gr.Textbox(
69
+ placeholder="Ask a policy question…",
70
+ show_label=False,
71
+ scale=6,
72
+ autofocus=True,
73
+ lines=1,
74
+ max_lines=5,
75
+ container=False,
76
+ elem_id="policyai-msg",
77
+ )
78
+ send_btn = gr.Button(
79
+ "Send ➤",
80
+ variant="primary",
81
+ scale=1,
82
+ min_width=78,
83
+ elem_id="policyai-send",
84
+ )
85
+ clear_btn = gr.Button(
86
+ "✕ Clear",
87
+ variant="secondary",
88
+ scale=1,
89
+ min_width=72,
90
+ elem_id="policyai-clear",
91
+ )
92
+
93
+ # ── Right — quick questions + sources ───────────────────────────────
94
+ with gr.Column(scale=37, min_width=260):
95
+
96
+ # Quick questions card
97
+ gr.HTML("""
98
+ <div class="panel-section">
99
+ <div class="panel-title">&#128161; &nbsp;Quick Questions</div>
100
+ <div class="panel-body">
101
+ """)
102
+ for q in SAMPLE_QUESTIONS:
103
+ gr.Button(q, variant="secondary", size="sm", elem_classes="q-btn").click(
104
+ fn=lambda question=q: question,
105
+ outputs=msg_input,
106
+ )
107
+ gr.HTML("</div></div>")
108
+
109
+ # Sources card
110
+ gr.HTML("""
111
+ <div class="panel-section" style="margin-top:12px;">
112
+ <div class="panel-title">&#128196; &nbsp;Retrieved Sources</div>
113
+ """)
114
+ sources_box = gr.Textbox(
115
+ value="",
116
+ placeholder="Source chunks will appear here after your first question...",
117
+ interactive=False,
118
+ lines=13,
119
+ max_lines=22,
120
+ show_label=False,
121
+ container=False,
122
+ elem_id="policyai-sources",
123
+ )
124
+ gr.HTML("</div>")
125
+
126
+ # ── Footer ──────────────────────────────────────────────────────────────────
127
+ gr.HTML("""
128
+ <div id="policyai-footer">
129
+ Powered by
130
+ <a href="https://groq.com" target="_blank">Groq</a>
131
+ <span class="sep">&middot;</span>
132
+ <a href="https://qdrant.tech" target="_blank">Qdrant</a>
133
+ <span class="sep">&middot;</span>
134
+ <a href="https://python.langchain.com" target="_blank">LangChain</a>
135
+ <span class="sep">&middot;</span>
136
+ <a href="https://gradio.app" target="_blank">Gradio</a>
137
+ <span class="sep">|</span>
138
+ Codebasics AI Engineering Bootcamp
139
+ </div>
140
+ """)
141
+
142
+ # ── Event wiring ────────────────────────────────────────────────────────────
143
+ send_btn.click(
144
+ fn=respond,
145
+ inputs=[msg_input, chatbot],
146
+ outputs=[chatbot, sources_box],
147
+ ).then(fn=lambda: "", outputs=msg_input)
148
+
149
+ msg_input.submit(
150
+ fn=respond,
151
+ inputs=[msg_input, chatbot],
152
+ outputs=[chatbot, sources_box],
153
+ ).then(fn=lambda: "", outputs=msg_input)
154
+
155
+ clear_btn.click(
156
+ fn=clear_chat,
157
+ outputs=[chatbot, msg_input, sources_box],
158
+ )
langchain_rag/01_ingest.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 01_ingest.py — Ingestion Pipeline (LangChain)
3
+
4
+ Same goal as vanilla_rag/01_ingest.py but using LangChain abstractions:
5
+
6
+ vanilla_rag langchain_rag
7
+ ────────────────────────────────── ──────────────────────────────────────
8
+ requests + fitz (manual) → PyMuPDFLoader
9
+ custom word-window loop → RecursiveCharacterTextSplitter
10
+ SentenceTransformer + PointStruct → HuggingFaceEmbeddings + QdrantVectorStore
11
+
12
+ LangChain wraps all of this behind a common Document interface, so every
13
+ loader, splitter, embedder, and vector store speaks the same language.
14
+
15
+ Run once before querying:
16
+ cd langchain_rag
17
+ python 01_ingest.py
18
+ """
19
+
20
+ import requests
21
+ from pathlib import Path
22
+
23
+ from langchain_community.document_loaders import PyMuPDFLoader
24
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
25
+ from langchain_huggingface import HuggingFaceEmbeddings
26
+ from langchain_qdrant import QdrantVectorStore
27
+
28
+ from config import PDF_URL, COLLECTION_NAME, QDRANT_PATH, EMBEDDING_MODEL, CHUNK_SIZE, CHUNK_OVERLAP
29
+
30
+ # ── Step 1 — Download & Load PDF ───────────────────────────────────────────────
31
+ #
32
+ # PyMuPDFLoader is LangChain's wrapper around PyMuPDF (fitz).
33
+ # It reads each page and returns a list of Document objects.
34
+ #
35
+ # A Document is LangChain's standard data container:
36
+ # doc.page_content → the extracted text of that page
37
+ # doc.metadata → dict with "source" (file path) and "page" (0-based index)
38
+ #
39
+ # We download the PDF once and save it to data/ so subsequent runs skip the download.
40
+
41
+ # __file__ is the script's absolute path — resolves correctly regardless of
42
+ # which directory you run python from
43
+ pdf_path = Path(__file__).parent.parent / "data" / "HR-Policy.pdf"
44
+
45
+ if not pdf_path.exists():
46
+ print(f"Downloading PDF from {PDF_URL} ...")
47
+ response = requests.get(PDF_URL, timeout=30)
48
+ response.raise_for_status()
49
+ pdf_path.write_bytes(response.content)
50
+ print(f"Saved to {pdf_path}")
51
+ else:
52
+ print(f"Using cached PDF: {pdf_path}")
53
+
54
+ loader = PyMuPDFLoader(str(pdf_path))
55
+ docs = loader.load() # returns List[Document], one per page
56
+
57
+ print(f"Loaded {len(docs)} pages")
58
+ print(f"Sample metadata : {docs[0].metadata}")
59
+ print(f"Sample content : {docs[0].page_content[:300]}")
60
+
61
+
62
+ # ── Step 2 — Split into Chunks ─────────────────────────────────────────────────
63
+ #
64
+ # RecursiveCharacterTextSplitter is LangChain's most versatile splitter.
65
+ # It tries to split on paragraphs (\n\n), then sentences (\n), then words (" "),
66
+ # falling back to characters — always preferring the most natural boundary.
67
+ #
68
+ # Key parameters:
69
+ # chunk_size → max characters per chunk (we use 500, set in config.py)
70
+ # chunk_overlap → characters shared between adjacent chunks (50)
71
+ # Overlap prevents an answer from being cut across two chunks.
72
+ #
73
+ # split_documents() preserves the metadata from each source Document,
74
+ # so every chunk still knows its source file and page number.
75
+
76
+ splitter = RecursiveCharacterTextSplitter(
77
+ chunk_size=CHUNK_SIZE,
78
+ chunk_overlap=CHUNK_OVERLAP,
79
+ )
80
+ chunks = splitter.split_documents(docs)
81
+
82
+ print(f"\nTotal chunks : {len(chunks)}")
83
+ print(f"Chunk size : ~{CHUNK_SIZE} chars | Overlap: {CHUNK_OVERLAP} chars")
84
+
85
+ # Inspect a couple of chunks
86
+ for chunk in chunks[:2]:
87
+ print("-" * 55)
88
+ print(f"Page : {chunk.metadata.get('page')}")
89
+ print(f"Content : {chunk.page_content[:200]}")
90
+
91
+
92
+ # ── Step 3 — Embed & Store in Qdrant ──────────────────────────────────────────
93
+ #
94
+ # HuggingFaceEmbeddings is LangChain's wrapper around sentence-transformers.
95
+ # It exposes the same model (all-MiniLM-L6-v2) but through the LangChain
96
+ # Embeddings interface — so it can be swapped for OpenAI / Cohere / etc.
97
+ # without changing any other code.
98
+
99
+ embedder = HuggingFaceEmbeddings(model_name=f"sentence-transformers/{EMBEDDING_MODEL}")
100
+ print(f"\nEmbedding model loaded: {EMBEDDING_MODEL}")
101
+
102
+ # QdrantVectorStore.from_documents() does three things in one call:
103
+ # 1. Embeds every chunk using the provided embedder
104
+ # 2. Creates (or recreates) the Qdrant collection
105
+ # 3. Upserts all vectors + metadata into it
106
+ #
107
+ # Compare to vanilla_rag where we did these three steps manually.
108
+ # The metadata (source, page) from each Document is automatically stored
109
+ # in the Qdrant payload — no manual PointStruct construction needed.
110
+
111
+ print(f"Embedding {len(chunks)} chunks and indexing in Qdrant ...")
112
+
113
+ vectorstore = QdrantVectorStore.from_documents(
114
+ documents=chunks,
115
+ embedding=embedder,
116
+ path=QDRANT_PATH,
117
+ collection_name=COLLECTION_NAME,
118
+ force_recreate=True, # drop and rebuild on re-runs, same as vanilla_rag
119
+ )
120
+
121
+ print(f"Indexed {len(chunks)} chunks into collection '{COLLECTION_NAME}'")
122
+ print("\nIngestion complete. Ready to query.")
langchain_rag/02_query.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 02_query.py — Query Pipeline (LangChain)
3
+
4
+ Same goal as vanilla_rag/02_query.py but using LangChain abstractions.
5
+
6
+ The biggest difference here is the LCEL chain (LangChain Expression Language).
7
+ In vanilla_rag, rag() was a manual function with explicit steps.
8
+ In LangChain, those steps are declared as a pipeline using the | operator:
9
+
10
+ rag_chain = retriever | format_docs | prompt | llm
11
+
12
+ Each | passes the output of the left side as input to the right side.
13
+ LangChain wires everything together — no manual step-by-step code needed.
14
+
15
+ Run interactively:
16
+ cd langchain_rag
17
+ python 02_query.py
18
+
19
+ Or import rag() into 03_demo.py.
20
+ """
21
+
22
+ from langchain_huggingface import HuggingFaceEmbeddings
23
+ from langchain_qdrant import QdrantVectorStore
24
+ from langchain_groq import ChatGroq
25
+ from langchain_core.prompts import ChatPromptTemplate
26
+ from langchain_core.runnables import RunnablePassthrough
27
+ from langchain_core.output_parsers import StrOutputParser
28
+
29
+ from config import (
30
+ COLLECTION_NAME, EMBEDDING_MODEL, GROQ_MODEL,
31
+ TOP_K, QDRANT_PATH, GROQ_API_KEY,
32
+ )
33
+
34
+ # ── Embedder ───────────────────────────────────────────────────────────────────
35
+ #
36
+ # Must be the SAME model used during ingestion.
37
+ # Vectors are only comparable when produced by the same model.
38
+
39
+ embedder = HuggingFaceEmbeddings(model_name=f"sentence-transformers/{EMBEDDING_MODEL}")
40
+
41
+
42
+ # ── Vector store + Retriever ───────────────────────────────────────────────────
43
+ #
44
+ # from_existing_collection() connects to an already-indexed Qdrant collection.
45
+ # Compare to from_documents() in 01_ingest.py which created and populated it.
46
+ #
47
+ # as_retriever() wraps the vector store in LangChain's Retriever interface.
48
+ # A Retriever exposes a single method: .invoke(query) → List[Document]
49
+ # This is what the LCEL chain calls automatically during retrieval.
50
+ #
51
+ # search_kwargs={"k": TOP_K} → return top 5 most similar chunks per query.
52
+
53
+ vectorstore = QdrantVectorStore.from_existing_collection(
54
+ embedding=embedder,
55
+ path=QDRANT_PATH,
56
+ collection_name=COLLECTION_NAME,
57
+ )
58
+
59
+ retriever = vectorstore.as_retriever(search_kwargs={"k": TOP_K})
60
+
61
+
62
+ # ── LLM ────────────────────────────────────────────────────────────────────────
63
+ #
64
+ # ChatGroq is LangChain's wrapper around the Groq API.
65
+ # It implements the same ChatModel interface as ChatOpenAI, ChatAnthropic etc.
66
+ # Swapping the LLM provider = change one line here, nothing else changes.
67
+
68
+ llm = ChatGroq(
69
+ model=GROQ_MODEL,
70
+ api_key=GROQ_API_KEY,
71
+ temperature=0.2, # low = factual, deterministic answers
72
+ )
73
+
74
+
75
+ # ── Prompt Template ────────────────────────────────────────────────────────────
76
+ #
77
+ # ChatPromptTemplate.from_messages() builds a reusable prompt with named slots.
78
+ # {context} and {question} are filled in at runtime by the LCEL chain.
79
+ #
80
+ # Splitting into system + human messages gives the LLM a clear role boundary:
81
+ # system message → sets behaviour ("only use the context, cite sources")
82
+ # human message → provides the actual data + question
83
+
84
+ RAG_PROMPT = ChatPromptTemplate.from_messages([
85
+ (
86
+ "system",
87
+ "You are a helpful HR policy assistant.\n"
88
+ "Answer the question using ONLY the information in the context below.\n"
89
+ "Write a clear, direct answer in plain language — do NOT copy source labels, "
90
+ "page numbers, or document names into your answer. "
91
+ "Those are shown separately to the user.\n"
92
+ "If the answer is not in the context, say so honestly.",
93
+ ),
94
+ (
95
+ "human",
96
+ "Context:\n{context}\n\nQuestion: {question}",
97
+ ),
98
+ ])
99
+
100
+
101
+ # ── Document formatter ─────────────────────────────────────────────────────────
102
+ #
103
+ # The retriever returns a List[Document].
104
+ # The prompt expects a plain string for {context}.
105
+ # format_docs() bridges that gap — it's the only manual step in the chain.
106
+ #
107
+ # doc.metadata["source"] and doc.metadata["page"] come free from PyMuPDFLoader
108
+ # (set automatically during ingestion — no manual tracking needed).
109
+
110
+ def format_docs(docs: list) -> str:
111
+ """Convert a list of retrieved Documents into a cited context string."""
112
+ parts = []
113
+ for i, doc in enumerate(docs, 1):
114
+ source = doc.metadata.get("source", "unknown").split("\\")[-1]
115
+ page = doc.metadata.get("page", "?")
116
+ parts.append(f"[Source {i} | {source} — Page {page}]\n{doc.page_content}")
117
+ return "\n\n---\n\n".join(parts)
118
+
119
+
120
+ # ── LCEL Chain ─────────────────────────────────────────────────────────────────
121
+ #
122
+ # This is the core LangChain concept — LangChain Expression Language (LCEL).
123
+ # The | operator chains Runnables together into a pipeline.
124
+ #
125
+ # How it works step by step:
126
+ #
127
+ # Input: a plain string question e.g. "What is the leave policy?"
128
+ #
129
+ # Step 1 — The dict {"context": ..., "question": ...} splits the input:
130
+ # "context" branch: retriever fetches top-5 chunks → format_docs() converts to string
131
+ # "question" branch: RunnablePassthrough() passes the question through unchanged
132
+ #
133
+ # Step 2 — RAG_PROMPT fills {context} and {question} into the template
134
+ #
135
+ # Step 3 — llm generates the answer (returns an AIMessage object)
136
+ #
137
+ # Step 4 — StrOutputParser() extracts just the .content string from AIMessage
138
+ #
139
+ # Output: a plain string answer
140
+ #
141
+ # Compare to vanilla_rag where we wrote all these steps manually inside rag().
142
+
143
+ rag_chain = (
144
+ {
145
+ "context": retriever | format_docs, # retrieve → format
146
+ "question": RunnablePassthrough(), # pass question through as-is
147
+ }
148
+ | RAG_PROMPT # fill template slots
149
+ | llm # generate answer
150
+ | StrOutputParser() # extract .content string from AIMessage
151
+ )
152
+
153
+
154
+ # ── rag() wrapper ──────────────────────────────────────────────────────────────
155
+ #
156
+ # A thin wrapper so 03_demo.py can call rag(question) just like vanilla_rag.
157
+ # Returns (answer, context) tuple to keep the same interface.
158
+
159
+ def rag(query: str) -> tuple[str, str]:
160
+ """
161
+ Run the full RAG pipeline for a question.
162
+
163
+ Returns:
164
+ answer : LLM-generated answer grounded in retrieved policy chunks.
165
+ context : The formatted context string sent to the LLM (for debugging).
166
+ """
167
+ # Retrieve docs separately so we can return the context for inspection
168
+ docs = retriever.invoke(query)
169
+ context = format_docs(docs)
170
+ answer = str(rag_chain.invoke(query)) # TextAccessor → plain str
171
+ return answer, context
172
+
173
+
174
+ # ── Run interactively ──────────────────────────────────────────────────────────
175
+ if __name__ == "__main__":
176
+ question = input("Ask a policy question: ").strip()
177
+
178
+ if question:
179
+ answer, context = rag(question)
180
+ print(f"\n{'-' * 55}")
181
+ print(answer)
182
+ print(f"\n{'-' * 55}\nSOURCES:\n{context}")
langchain_rag/03_demo.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 03_demo.py — Demo Script (LangChain)
3
+
4
+ Runs the same 5 sample questions as vanilla_rag/03_demo.py through the
5
+ LangChain RAG pipeline so you can compare answers side by side.
6
+
7
+ Usage:
8
+ cd langchain_rag
9
+ python 03_demo.py
10
+ """
11
+
12
+ import importlib
13
+
14
+ # Python cannot import modules whose names start with a digit via normal syntax.
15
+ # importlib.import_module() handles this cleanly.
16
+ _query = importlib.import_module("02_query")
17
+ rag = _query.rag
18
+
19
+ # ── Sample questions ───────────────────────────────────────────────────────────
20
+ SAMPLE_QUESTIONS = [
21
+ "What are the leave entitlements for employees?",
22
+ "What is the maternity leave policy?",
23
+ "How does the performance appraisal process work?",
24
+ "What are the travel expense reimbursement rules?",
25
+ "What are the disciplinary action procedures?",
26
+ ]
27
+
28
+ # ── Run demo ───────────────────────────────────────────────────────────────────
29
+ print("=" * 60)
30
+ print(" PolicyAI (LangChain RAG) — Full Pipeline Demo")
31
+ print("=" * 60)
32
+
33
+ for i, question in enumerate(SAMPLE_QUESTIONS, start=1):
34
+ print(f"\n[{i}/{len(SAMPLE_QUESTIONS)}] {question}")
35
+ print("-" * 60)
36
+
37
+ answer, context = rag(question)
38
+
39
+ print(answer)
40
+ print(f"\nSOURCES:\n{context}")
41
+ print()
42
+
43
+ print("=" * 60)
44
+ print(" Demo complete.")
45
+ print("=" * 60)
langchain_rag/config.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ config.py — Central configuration for PolicyAI (LangChain implementation)
3
+
4
+ Rules:
5
+ - Secrets (API keys) → .env file only, never hardcoded here
6
+ - App config (models, DB) → this file
7
+ - All other files import from here — nothing else defines these constants
8
+ """
9
+
10
+ import os
11
+ from pathlib import Path
12
+ from dotenv import load_dotenv
13
+
14
+ # .env lives at the project root — resolve relative to this file, not cwd
15
+ load_dotenv(Path(__file__).parent.parent / ".env")
16
+
17
+ # ── Secrets ────────────────────────────────────────────────────────────────────
18
+ GROQ_API_KEY: str = os.getenv("GROQ_API_KEY", "")
19
+
20
+ # ── LLM ────────────────────────────────────────────────────────────────────────
21
+ GROQ_MODEL: str = "llama-3.1-8b-instant"
22
+
23
+ # ── Embedding ──────────────────────────────────────────────────────────────────
24
+ EMBEDDING_MODEL: str = "all-MiniLM-L6-v2" # 384-dim, runs fully offline
25
+
26
+ # ── Vector database ────────────────────────────────────────────────────────────
27
+ QDRANT_PATH: str = "./qdrant_data" # local folder, no server needed
28
+ COLLECTION_NAME: str = "policies_lc" # separate collection from vanilla_rag
29
+
30
+ # ── Chunking ───────────────────────────────────────────────────────────────────
31
+ CHUNK_SIZE: int = 500 # characters per chunk (LangChain uses chars, not words)
32
+ CHUNK_OVERLAP: int = 50 # overlap between chunks to preserve context at boundaries
33
+
34
+ # ── Retrieval ──────────────────────────────────────────────────────────────────
35
+ TOP_K: int = 5 # number of chunks returned per query
36
+
37
+ # ── Source document ────────────────────────────────────────────────────────────
38
+ PDF_URL: str = "https://rikalp.in/wp-content/uploads/2024/07/HR-Policy.pdf"
requirements.txt ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ── Vanilla RAG dependencies ───────────────────────────────────────────────────
2
+ pymupdf==1.27.2 # PDF text extraction
3
+ sentence-transformers==5.5.1 # local embedding model (all-MiniLM-L6-v2)
4
+ qdrant-client==1.18.0 # vector database (local file mode)
5
+ groq==1.1.1 # Groq LLM API client
6
+ python-dotenv # loads .env into os.environ
7
+ requests # HTTP — fetches PDFs from URLs
8
+
9
+ # ── LangChain RAG dependencies ─────────────────────────────────────────────────
10
+ langchain # core abstractions (Document, chains, runnables)
11
+ langchain-community # document loaders (PyMuPDFLoader, WebBaseLoader etc.)
12
+ langchain-huggingface # HuggingFaceEmbeddings wrapper
13
+ langchain-qdrant # QdrantVectorStore integration
14
+ langchain-groq # ChatGroq LLM wrapper
15
+ langchain-text-splitters # RecursiveCharacterTextSplitter etc.
16
+
17
+ # ── Chatbot UI ─────────────────────────────────────────────────────────────────
18
+ gradio # web UI — runs locally and on Hugging Face Spaces
vanilla_rag/01_ingest.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 01_ingest.py — Ingestion Pipeline
3
+
4
+ Orchestrates the full ingestion flow:
5
+ 1. Load PDF → ingestion/01_doc_loader.py
6
+ 2. Chunk text → ingestion/02_chunker.py
7
+ 3. Embed chunks → ingestion/03_embedder.py
8
+ 4. Store vectors → Qdrant (local file store)
9
+
10
+ Run this once per document before querying:
11
+ cd vanilla_rag
12
+ python 01_ingest.py
13
+ """
14
+
15
+ from ingestion import load_pdf, extract_pages, chunk_pages, embed_chunks, get_embedder
16
+ from qdrant_client import QdrantClient
17
+ from qdrant_client.models import Distance, VectorParams, PointStruct
18
+ from config import PDF_URL, COLLECTION_NAME, QDRANT_PATH
19
+
20
+ SOURCE_NAME = PDF_URL.split("/")[-1]
21
+
22
+ # ── Step 1 — Load PDF ──────────────────────────────────────────────────────────
23
+ pdf_bytes = load_pdf(PDF_URL)
24
+ pages = extract_pages(pdf_bytes, SOURCE_NAME)
25
+
26
+ # Sanity check — print the first 300 chars of page 1
27
+ print(pages[0]["text"][:300])
28
+
29
+ # ── Step 2 — Chunk ─────────────────────────────────────────────────────────────
30
+ chunks = chunk_pages(pages)
31
+
32
+ # Inspect a couple of chunks to verify the output looks correct
33
+ for chunk in chunks[:2]:
34
+ print("-" * 55)
35
+ print(f"Page : {chunk['page']}")
36
+ print(f"Content : {chunk['content'][:200]}")
37
+
38
+ # ── Step 3 — Embed ─────────────────────────────────────────────────────────────
39
+ embeddings = embed_chunks(chunks)
40
+
41
+ # ── Step 4 — Store in Qdrant ───────────────────────────────────────────────────
42
+ # path= stores everything in a local folder — no Docker or server required
43
+ client = QdrantClient(path=QDRANT_PATH)
44
+ DIM = get_embedder().get_embedding_dimension() # 384
45
+
46
+ # Drop and rebuild so re-runs always start from a clean state
47
+ if client.collection_exists(COLLECTION_NAME):
48
+ client.delete_collection(COLLECTION_NAME)
49
+ client.create_collection(
50
+ collection_name=COLLECTION_NAME,
51
+ vectors_config=VectorParams(size=DIM, distance=Distance.COSINE),
52
+ )
53
+ print("Collection created.")
54
+
55
+ # Each PointStruct holds: a unique ID, the embedding vector, and a payload
56
+ # with the chunk text + citation metadata (source filename + page number)
57
+ points = [
58
+ PointStruct(
59
+ id=idx,
60
+ vector=embedding.tolist(),
61
+ payload={
62
+ "content": chunk["content"],
63
+ "page": chunk["page"],
64
+ "source": chunk["source"],
65
+ },
66
+ )
67
+ for idx, (chunk, embedding) in enumerate(zip(chunks, embeddings))
68
+ ]
69
+
70
+ # wait=True blocks until Qdrant finishes indexing before returning
71
+ result = client.upsert(collection_name=COLLECTION_NAME, points=points, wait=True)
72
+ print(f"Indexed {len(points)} points — status: {result.status}")
73
+ print("\nIngestion complete. Ready to query.")
vanilla_rag/02_query.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 02_query.py — Query Pipeline
3
+
4
+ Exposes a single rag() function that takes a plain-English question,
5
+ finds the most relevant policy chunks via semantic search, and returns
6
+ a grounded answer with exact document and page citations.
7
+
8
+ Run interactively:
9
+ cd vanilla_rag
10
+ python 02_query.py
11
+
12
+ Or import rag() into other scripts (e.g. 03_demo.py).
13
+ """
14
+
15
+ from sentence_transformers import SentenceTransformer
16
+ from qdrant_client import QdrantClient
17
+ from groq import Groq
18
+ from config import COLLECTION_NAME, EMBEDDING_MODEL, GROQ_MODEL, TOP_K, QDRANT_PATH, GROQ_API_KEY
19
+
20
+ # System prompt constrains the LLM to the retrieved context only,
21
+ # preventing hallucination on topics not covered by the indexed documents
22
+ SYSTEM_PROMPT = """You are a helpful HR policy assistant.
23
+ Answer the user's question using ONLY the context provided below.
24
+ Always cite the source document and page number when referencing specific information.
25
+ If the context does not contain enough information, say so — do not make things up."""
26
+
27
+ # ── Clients ────────────────────────────────────────────────────────────────────
28
+ # Both clients are created once at module load and reused across all calls
29
+ embedder = SentenceTransformer(EMBEDDING_MODEL)
30
+ qdrant = QdrantClient(path=QDRANT_PATH)
31
+ groq_client = Groq(api_key=GROQ_API_KEY)
32
+
33
+
34
+ # ── Retrieval ──────────────────────────────────────────────────────────────────
35
+ def retrieve(query: str, top_k: int = TOP_K) -> list[dict]:
36
+ """
37
+ Convert the query into an embedding vector and search Qdrant for the
38
+ top-k most semantically similar chunks.
39
+
40
+ The same embedding model used during ingestion must be used here —
41
+ vectors are only comparable when produced by the same model.
42
+
43
+ Returns a list of payload dicts with an extra "score" field (cosine similarity).
44
+ """
45
+ # Encode the question into the same 384-dim vector space as the stored chunks
46
+ query_vector = embedder.encode(query).tolist()
47
+
48
+ hits = qdrant.query_points(
49
+ collection_name=COLLECTION_NAME,
50
+ query=query_vector,
51
+ limit=top_k,
52
+ with_payload=True, # include text + citation metadata in results
53
+ )
54
+
55
+ return [
56
+ {**hit.payload, "score": round(hit.score, 4)}
57
+ for hit in hits.points
58
+ ]
59
+
60
+
61
+ # ── Context builder ────────────────────────────────────────────────────────────
62
+ def build_context(chunks: list[dict]) -> str:
63
+ """
64
+ Format the retrieved chunks into a numbered context block for the LLM prompt.
65
+
66
+ Each chunk is prefixed with its source document and page number so the LLM
67
+ can include accurate citations in its answer.
68
+
69
+ Example output:
70
+ [Source 1 | HR-Policy.pdf — Page 12]
71
+ Employees are entitled to 10 days of sick leave per year...
72
+
73
+ ---
74
+
75
+ [Source 2 | HR-Policy.pdf — Page 13]
76
+ Sick leave beyond 3 consecutive days requires a medical certificate...
77
+ """
78
+ parts = []
79
+ for i, chunk in enumerate(chunks, 1):
80
+ parts.append(
81
+ f"[Source {i} | {chunk['source']} — Page {chunk['page']}]\n{chunk['content']}"
82
+ )
83
+ return "\n\n---\n\n".join(parts)
84
+
85
+
86
+ # ── RAG pipeline ───────────────────────────────────────────────────────────────
87
+ def rag(query: str, top_k: int = TOP_K) -> tuple[str, str]:
88
+ """
89
+ End-to-end Retrieval-Augmented Generation pipeline.
90
+
91
+ Steps:
92
+ 1. Retrieve — find the top-k most relevant chunks from Qdrant
93
+ 2. Build context — format chunks into a cited context block
94
+ 3. Generate — send system prompt + context + question to Groq LLM
95
+
96
+ Args:
97
+ query : Plain-English question from the user.
98
+ top_k : How many chunks to retrieve (more = broader context, higher cost).
99
+
100
+ Returns:
101
+ answer : LLM-generated answer grounded in the retrieved context.
102
+ context : The raw context block sent to the LLM (useful for debugging).
103
+ """
104
+ # Step 1 — Retrieve the most relevant chunks
105
+ chunks = retrieve(query, top_k=top_k)
106
+ if not chunks:
107
+ return "No relevant content found in the policy documents.", ""
108
+
109
+ # Step 2 — Format chunks into a context block with citations
110
+ context = build_context(chunks)
111
+
112
+ # Step 3 — Build the prompt and call the LLM
113
+ # Splitting into system + user messages gives the LLM a clear role boundary:
114
+ # the system message sets behaviour, the user message provides data + question
115
+ user_message = f"Context:\n{context}\n\nQuestion: {query}"
116
+
117
+ response = groq_client.chat.completions.create(
118
+ model=GROQ_MODEL,
119
+ messages=[
120
+ {"role": "system", "content": SYSTEM_PROMPT},
121
+ {"role": "user", "content": user_message},
122
+ ],
123
+ temperature=0.2, # low temperature = factual, deterministic answers
124
+ )
125
+
126
+ return response.choices[0].message.content, context
127
+
128
+
129
+ # ── Run interactively ──────────────────────────────────────────────────────────
130
+ if __name__ == "__main__":
131
+ question = input("Ask a policy question: ").strip()
132
+
133
+ if question:
134
+ answer, context = rag(question)
135
+ print(f"\n{'-' * 55}")
136
+ print(answer)
137
+ print(f"\n{'-' * 55}\nSOURCES:\n{context}")
vanilla_rag/03_demo.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 03_demo.py — Demo Script
3
+
4
+ Runs a curated set of sample HR policy questions through the full RAG pipeline
5
+ and prints each answer with its source citations.
6
+
7
+ Use this to verify the pipeline end-to-end after running 01_ingest.py.
8
+
9
+ Usage:
10
+ cd vanilla_rag
11
+ python 03_demo.py
12
+ """
13
+
14
+ import importlib
15
+
16
+ # Standard Python imports cannot reference modules whose names start with a digit.
17
+ # importlib.import_module() handles this case cleanly.
18
+ _query = importlib.import_module("02_query")
19
+ rag = _query.rag # bring rag() into local scope
20
+
21
+ # ── Sample questions ───────────────────────────────────────────────────────────
22
+ # These cover the most common policy topics employees ask about.
23
+ # Extend this list to test additional domains (IT, Safety, Finance, etc.)
24
+ SAMPLE_QUESTIONS = [
25
+ "What are the leave entitlements for employees?",
26
+ "What is the maternity leave policy?",
27
+ "How does the performance appraisal process work?",
28
+ "What are the travel expense reimbursement rules?",
29
+ "What are the disciplinary action procedures?",
30
+ ]
31
+
32
+ # ── Run demo ───────────────────────────────────────────────────────────────────
33
+ print("=" * 60)
34
+ print(" PolicyAI (Vanilla RAG) — Full Pipeline Demo")
35
+ print("=" * 60)
36
+
37
+ for i, question in enumerate(SAMPLE_QUESTIONS, start=1):
38
+ print(f"\n[{i}/{len(SAMPLE_QUESTIONS)}] {question}")
39
+ print("-" * 60)
40
+
41
+ # rag() returns (answer, context) — context holds the raw source chunks
42
+ answer, context = rag(question)
43
+
44
+ print(answer)
45
+ print(f"\nSOURCES:\n{context}")
46
+ print()
47
+
48
+ print("=" * 60)
49
+ print(" Demo complete.")
50
+ print("=" * 60)
vanilla_rag/config.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ config.py — Central configuration for PolicyAI
3
+
4
+ Rules:
5
+ - Secrets (API keys) → .env file only, never hardcoded here
6
+ - App config (models, DB) → this file
7
+ - All other files import from here — nothing else defines these constants
8
+ """
9
+
10
+ import os
11
+ from pathlib import Path
12
+ from dotenv import load_dotenv
13
+
14
+ # .env lives at the project root — resolve relative to this file, not cwd
15
+ load_dotenv(Path(__file__).parent.parent / ".env")
16
+
17
+ # ── Secrets ────────────────────────────────────────────────────────────────────
18
+ GROQ_API_KEY: str = os.getenv("GROQ_API_KEY", "")
19
+
20
+ # ── LLM ────────────────────────────────────────────────────────────────────────
21
+ GROQ_MODEL: str = "llama-3.1-8b-instant"
22
+
23
+ # ── Embedding ──────────────────────────────────────────────────────────────────
24
+ EMBEDDING_MODEL: str = "all-MiniLM-L6-v2" # 384-dim, runs fully offline
25
+
26
+ # ── Vector database ────────────────────────────────────────────────────────────
27
+ QDRANT_PATH: str = "./qdrant_data" # local folder, no server needed
28
+ COLLECTION_NAME: str = "policies"
29
+
30
+ # ── Chunking ───────────────────────────────────────────────────────────────────
31
+ CHUNK_SIZE: int = 100 # words per chunk
32
+ CHUNK_MIN_WORDS: int = 10 # discard trailing fragments shorter than this
33
+
34
+ # ── Retrieval ──────────────────────────────────────────────────────────────────
35
+ TOP_K: int = 5 # number of chunks returned per query
36
+
37
+ # ── Source document ────────────────────────────────────────────────────────────
38
+ PDF_URL: str = "https://rikalp.in/wp-content/uploads/2024/07/HR-Policy.pdf"
vanilla_rag/ingestion/01_doc_loader.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 01_doc_loader.py — PDF fetching and text extraction
3
+
4
+ RAG Step 1 of 3: Load the document.
5
+
6
+ Responsibilities:
7
+ - Download a PDF from a remote URL
8
+ - Open it in memory (no temp files)
9
+ - Extract raw text from every page, preserving page numbers for citations
10
+ """
11
+
12
+ import requests
13
+ import fitz # PyMuPDF — fast, reliable PDF text extraction
14
+ from io import BytesIO
15
+
16
+
17
+ def load_pdf(url: str) -> BytesIO:
18
+ """
19
+ Download a PDF from a remote URL and return it as an in-memory byte stream.
20
+
21
+ Using BytesIO avoids writing a temp file to disk — fitz can open it
22
+ directly from memory via the stream= argument.
23
+
24
+ Raises:
25
+ requests.HTTPError — if the server returns 4xx or 5xx
26
+ """
27
+ print(f"Fetching PDF: {url}")
28
+ response = requests.get(url, timeout=30)
29
+ response.raise_for_status()
30
+ return BytesIO(response.content)
31
+
32
+
33
+ def extract_pages(pdf_bytes: BytesIO, source_name: str) -> list[dict]:
34
+ """
35
+ Open the PDF from a byte stream and extract the text of every page.
36
+
37
+ Args:
38
+ pdf_bytes : In-memory PDF content returned by load_pdf().
39
+ source_name : Filename used as the citation label (e.g. "HR-Policy.pdf").
40
+
41
+ Returns:
42
+ List of page dicts:
43
+ { "page": int, — 1-based page number
44
+ "text": str, — raw extracted text
45
+ "source": str } — source filename for citations
46
+
47
+ Pages with no extractable text (e.g. scanned images) are skipped.
48
+ """
49
+ doc = fitz.open(stream=pdf_bytes, filetype="pdf")
50
+ pages = []
51
+
52
+ for page_num, page in enumerate(doc, start=1):
53
+ text = page.get_text().strip()
54
+ if text:
55
+ pages.append({
56
+ "page": page_num,
57
+ "text": text,
58
+ "source": source_name,
59
+ })
60
+
61
+ print(f"Extracted {len(pages)} pages from '{source_name}'")
62
+ return pages
vanilla_rag/ingestion/02_chunker.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 02_chunker.py — Text chunking
3
+
4
+ RAG Step 2 of 3: Prepare the data.
5
+
6
+ Splits page text into fixed-size word windows so each chunk fits within
7
+ the embedding model's token limit and carries enough context to be useful.
8
+ """
9
+
10
+ from config import CHUNK_SIZE, CHUNK_MIN_WORDS
11
+
12
+
13
+ def chunk_pages(pages: list[dict], chunk_size: int = CHUNK_SIZE) -> list[dict]:
14
+ """
15
+ Split each page's text into non-overlapping word windows of `chunk_size` words.
16
+
17
+ Why word-based chunking?
18
+ - Predictable size regardless of sentence length.
19
+ - 100 words fits comfortably within the all-MiniLM-L6-v2 token limit (256 tokens).
20
+
21
+ Each chunk inherits the page number and source filename from its parent page
22
+ so citations remain accurate after retrieval.
23
+
24
+ Args:
25
+ pages : Output of 01_doc_loader.extract_pages().
26
+ chunk_size : Number of words per chunk. Defaults to CHUNK_SIZE.
27
+
28
+ Returns:
29
+ List of chunk dicts:
30
+ { "chunk_index": int, — sequential ID across all chunks
31
+ "content": str, — chunk text
32
+ "page": int, — page this chunk came from
33
+ "source": str } — source filename
34
+ """
35
+ chunks = []
36
+
37
+ for page in pages:
38
+ words = page["text"].split()
39
+
40
+ for i in range(0, len(words), chunk_size):
41
+ chunk_words = words[i : i + chunk_size]
42
+
43
+ # Skip very small trailing fragments — not enough context to be useful
44
+ if len(chunk_words) < CHUNK_MIN_WORDS:
45
+ continue
46
+
47
+ chunks.append({
48
+ "chunk_index": len(chunks),
49
+ "content": " ".join(chunk_words),
50
+ "page": page["page"],
51
+ "source": page["source"],
52
+ })
53
+
54
+ print(f"Created {len(chunks)} chunks")
55
+ return chunks
vanilla_rag/ingestion/03_embedder.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 03_embedder.py — Text embedding
3
+
4
+ RAG Step 3 of 3: Convert chunks into vectors.
5
+
6
+ Converts text chunks into 384-dimensional vectors using all-MiniLM-L6-v2.
7
+ The model runs fully offline after the first download (~90 MB, cached locally).
8
+ """
9
+
10
+ import numpy as np
11
+ from sentence_transformers import SentenceTransformer
12
+ from config import EMBEDDING_MODEL
13
+
14
+ # Module-level singleton — model is loaded once and reused across all calls.
15
+ # Recreating SentenceTransformer on every call would add ~2 s of overhead each time.
16
+ _embedder: SentenceTransformer | None = None
17
+
18
+
19
+ def get_embedder() -> SentenceTransformer:
20
+ """
21
+ Return the embedding model, loading it on the first call only.
22
+
23
+ Subsequent calls return the already-loaded instance from module memory,
24
+ so ingestion and query both share the same model without reloading.
25
+ """
26
+ global _embedder
27
+ if _embedder is None:
28
+ print(f"Loading embedding model '{EMBEDDING_MODEL}'...")
29
+ _embedder = SentenceTransformer(EMBEDDING_MODEL)
30
+ return _embedder
31
+
32
+
33
+ def embed_chunks(chunks: list[dict]) -> np.ndarray:
34
+ """
35
+ Encode a list of chunk dicts into embedding vectors.
36
+
37
+ Args:
38
+ chunks : List of chunk dicts with a "content" key (output of 02_chunker.py).
39
+
40
+ Returns:
41
+ numpy array of shape (len(chunks), 384) — one vector per chunk.
42
+ show_progress_bar is shown only for bulk ingestion (more than 1 chunk).
43
+ """
44
+ embedder = get_embedder()
45
+ texts = [c["content"] for c in chunks]
46
+
47
+ print(f"Embedding {len(texts)} chunks...")
48
+ embeddings = embedder.encode(texts, show_progress_bar=len(texts) > 1)
49
+
50
+ print(f"Shape: {embeddings.shape}")
51
+ return embeddings
vanilla_rag/ingestion/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ingestion/__init__.py
3
+
4
+ Re-exports all public functions from the numbered ingestion modules so the
5
+ rest of the codebase can import cleanly:
6
+
7
+ from ingestion import load_pdf, extract_pages, chunk_pages, embed_chunks
8
+
9
+ Python's import statement cannot reference module names that start with a digit,
10
+ so importlib.import_module() is used here to load them by string name.
11
+ """
12
+
13
+ import importlib
14
+
15
+ _doc_loader = importlib.import_module("ingestion.01_doc_loader")
16
+ _chunker = importlib.import_module("ingestion.02_chunker")
17
+ _embedder = importlib.import_module("ingestion.03_embedder")
18
+
19
+ # Document loading
20
+ load_pdf = _doc_loader.load_pdf
21
+ extract_pages = _doc_loader.extract_pages
22
+
23
+ # Chunking
24
+ chunk_pages = _chunker.chunk_pages
25
+
26
+ # Embedding
27
+ get_embedder = _embedder.get_embedder
28
+ embed_chunks = _embedder.embed_chunks