Spaces:
Sleeping
Sleeping
manasvi63
commited on
Commit
·
bf10662
1
Parent(s):
aee5618
Complete Pipeline
Browse files- .DS_Store +0 -0
- API_USAGE.md +256 -0
- Dockerfile +23 -0
- README.md +146 -8
- __pycache__/api.cpython-312.pyc +0 -0
- api.py +401 -0
- app_api.py +407 -0
- data/.DS_Store +0 -0
- data/pdf/.DS_Store +0 -0
- data/vector_store/.DS_Store +0 -0
- experimental_files/__pycache__/api.cpython-312.pyc +0 -0
- experimental_files/app.py +428 -0
- experimental_files/example_client.py +159 -0
- experimental_files/main.py +6 -0
- launch.sh +149 -0
- notebook/.DS_Store +0 -0
- notebook/1-langchain-document-components.svg +266 -0
- notebook/data/.DS_Store +0 -0
- notebook/document.ipynb +130 -0
- notebook/pdf_loader.ipynb +0 -0
- notebook/pdf_loader2.ipynb +0 -0
- pyproject.toml +25 -0
- requirements.txt +16 -0
- src/__pycache__/rag_pipeline.cpython-310.pyc +0 -0
- src/__pycache__/rag_pipeline.cpython-312.pyc +0 -0
- src/rag_pipeline.py +571 -0
- uv.lock +0 -0
.DS_Store
ADDED
|
Binary file (8.2 kB). View file
|
|
|
API_USAGE.md
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# RAG Pipeline API Usage Guide
|
| 2 |
+
|
| 3 |
+
This API provides a REST interface to the RAG Pipeline system, allowing you to use it from the terminal, build custom UIs, or integrate it into other applications.
|
| 4 |
+
|
| 5 |
+
## Starting the API Server
|
| 6 |
+
|
| 7 |
+
```bash
|
| 8 |
+
# Using uvicorn directly
|
| 9 |
+
uvicorn api:app --reload --host 0.0.0.0 --port 8000
|
| 10 |
+
|
| 11 |
+
# Or using Python
|
| 12 |
+
python api.py
|
| 13 |
+
```
|
| 14 |
+
|
| 15 |
+
The API will be available at `http://localhost:8000`
|
| 16 |
+
|
| 17 |
+
## API Documentation
|
| 18 |
+
|
| 19 |
+
Once the server is running, visit:
|
| 20 |
+
- **Swagger UI**: http://localhost:8000/docs
|
| 21 |
+
- **ReDoc**: http://localhost:8000/redoc
|
| 22 |
+
|
| 23 |
+
## Endpoints
|
| 24 |
+
|
| 25 |
+
### 1. Get API Information
|
| 26 |
+
```bash
|
| 27 |
+
curl http://localhost:8000/
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
### 2. Check System Status
|
| 31 |
+
```bash
|
| 32 |
+
curl http://localhost:8000/status
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
### 3. Upload and Process PDF Documents
|
| 36 |
+
|
| 37 |
+
```bash
|
| 38 |
+
curl -X POST "http://localhost:8000/upload" \
|
| 39 |
+
-F "files=@/path/to/document1.pdf" \
|
| 40 |
+
-F "files=@/path/to/document2.pdf" \
|
| 41 |
+
-F "chunk_size=800" \
|
| 42 |
+
-F "chunk_overlap=200"
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
**Parameters:**
|
| 46 |
+
- `files`: PDF files to upload (can upload multiple)
|
| 47 |
+
- `chunk_size`: Size of text chunks (default: 800)
|
| 48 |
+
- `chunk_overlap`: Overlap between chunks (default: 200)
|
| 49 |
+
- `collection_name`: Optional custom collection name
|
| 50 |
+
- `persist_directory`: Optional custom persist directory
|
| 51 |
+
|
| 52 |
+
### 4. Query Documents
|
| 53 |
+
|
| 54 |
+
```bash
|
| 55 |
+
curl -X POST "http://localhost:8000/query" \
|
| 56 |
+
-H "Content-Type: application/json" \
|
| 57 |
+
-d '{
|
| 58 |
+
"query": "What is attention mechanism?",
|
| 59 |
+
"top_k": 5,
|
| 60 |
+
"use_memory": true
|
| 61 |
+
}'
|
| 62 |
+
```
|
| 63 |
+
|
| 64 |
+
**With session ID (for conversation memory):**
|
| 65 |
+
```bash
|
| 66 |
+
curl -X POST "http://localhost:8000/query" \
|
| 67 |
+
-H "Content-Type: application/json" \
|
| 68 |
+
-d '{
|
| 69 |
+
"query": "Who are the authors?",
|
| 70 |
+
"session_id": "my-session-123",
|
| 71 |
+
"top_k": 5,
|
| 72 |
+
"use_memory": true
|
| 73 |
+
}'
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
**With metadata filters:**
|
| 77 |
+
```bash
|
| 78 |
+
curl -X POST "http://localhost:8000/query" \
|
| 79 |
+
-H "Content-Type: application/json" \
|
| 80 |
+
-d '{
|
| 81 |
+
"query": "What is attention?",
|
| 82 |
+
"top_k": 5,
|
| 83 |
+
"metadata_filters": {
|
| 84 |
+
"source": ["../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf"],
|
| 85 |
+
"page": 1
|
| 86 |
+
}
|
| 87 |
+
}'
|
| 88 |
+
```
|
| 89 |
+
|
| 90 |
+
**Response:**
|
| 91 |
+
```json
|
| 92 |
+
{
|
| 93 |
+
"answer": "The answer from the RAG system...",
|
| 94 |
+
"sources": [
|
| 95 |
+
{
|
| 96 |
+
"score": 0.85,
|
| 97 |
+
"preview": "Document preview...",
|
| 98 |
+
"metadata": {...},
|
| 99 |
+
"id": "doc-id"
|
| 100 |
+
}
|
| 101 |
+
],
|
| 102 |
+
"session_id": "auto-generated-or-provided",
|
| 103 |
+
"message": "Query processed successfully"
|
| 104 |
+
}
|
| 105 |
+
```
|
| 106 |
+
|
| 107 |
+
### 5. Get Chat History
|
| 108 |
+
|
| 109 |
+
```bash
|
| 110 |
+
curl http://localhost:8000/chat-history/{session_id}
|
| 111 |
+
```
|
| 112 |
+
|
| 113 |
+
### 6. Clear Chat History
|
| 114 |
+
|
| 115 |
+
```bash
|
| 116 |
+
curl -X DELETE http://localhost:8000/chat-history/{session_id}
|
| 117 |
+
```
|
| 118 |
+
|
| 119 |
+
### 7. List All Sessions
|
| 120 |
+
|
| 121 |
+
```bash
|
| 122 |
+
curl http://localhost:8000/sessions
|
| 123 |
+
```
|
| 124 |
+
|
| 125 |
+
### 8. Reset System
|
| 126 |
+
|
| 127 |
+
```bash
|
| 128 |
+
curl -X POST http://localhost:8000/reset
|
| 129 |
+
```
|
| 130 |
+
|
| 131 |
+
## Python Client Example
|
| 132 |
+
|
| 133 |
+
```python
|
| 134 |
+
import requests
|
| 135 |
+
|
| 136 |
+
# Base URL
|
| 137 |
+
BASE_URL = "http://localhost:8000"
|
| 138 |
+
|
| 139 |
+
# 1. Upload documents
|
| 140 |
+
with open("document.pdf", "rb") as f:
|
| 141 |
+
files = {"files": f}
|
| 142 |
+
data = {"chunk_size": 800, "chunk_overlap": 200}
|
| 143 |
+
response = requests.post(f"{BASE_URL}/upload", files=files, data=data)
|
| 144 |
+
print(response.json())
|
| 145 |
+
|
| 146 |
+
# 2. Query documents
|
| 147 |
+
query_data = {
|
| 148 |
+
"query": "What is attention mechanism?",
|
| 149 |
+
"session_id": "my-session",
|
| 150 |
+
"top_k": 5,
|
| 151 |
+
"use_memory": True
|
| 152 |
+
}
|
| 153 |
+
response = requests.post(f"{BASE_URL}/query", json=query_data)
|
| 154 |
+
result = response.json()
|
| 155 |
+
print(f"Answer: {result['answer']}")
|
| 156 |
+
print(f"Sources: {result['sources']}")
|
| 157 |
+
|
| 158 |
+
# 3. Continue conversation
|
| 159 |
+
query_data = {
|
| 160 |
+
"query": "Tell me more about it",
|
| 161 |
+
"session_id": "my-session", # Same session ID
|
| 162 |
+
"top_k": 5,
|
| 163 |
+
"use_memory": True
|
| 164 |
+
}
|
| 165 |
+
response = requests.post(f"{BASE_URL}/query", json=query_data)
|
| 166 |
+
print(response.json()["answer"])
|
| 167 |
+
|
| 168 |
+
# 4. Get chat history
|
| 169 |
+
response = requests.get(f"{BASE_URL}/chat-history/my-session")
|
| 170 |
+
print(response.json())
|
| 171 |
+
```
|
| 172 |
+
|
| 173 |
+
## JavaScript/TypeScript Example
|
| 174 |
+
|
| 175 |
+
```javascript
|
| 176 |
+
// Upload documents
|
| 177 |
+
const formData = new FormData();
|
| 178 |
+
formData.append('files', fileInput.files[0]);
|
| 179 |
+
formData.append('chunk_size', '800');
|
| 180 |
+
formData.append('chunk_overlap', '200');
|
| 181 |
+
|
| 182 |
+
const uploadResponse = await fetch('http://localhost:8000/upload', {
|
| 183 |
+
method: 'POST',
|
| 184 |
+
body: formData
|
| 185 |
+
});
|
| 186 |
+
const uploadResult = await uploadResponse.json();
|
| 187 |
+
console.log(uploadResult);
|
| 188 |
+
|
| 189 |
+
// Query documents
|
| 190 |
+
const queryResponse = await fetch('http://localhost:8000/query', {
|
| 191 |
+
method: 'POST',
|
| 192 |
+
headers: {
|
| 193 |
+
'Content-Type': 'application/json',
|
| 194 |
+
},
|
| 195 |
+
body: JSON.stringify({
|
| 196 |
+
query: 'What is attention mechanism?',
|
| 197 |
+
session_id: 'my-session',
|
| 198 |
+
top_k: 5,
|
| 199 |
+
use_memory: true
|
| 200 |
+
})
|
| 201 |
+
});
|
| 202 |
+
const queryResult = await queryResponse.json();
|
| 203 |
+
console.log(queryResult.answer);
|
| 204 |
+
```
|
| 205 |
+
|
| 206 |
+
## Building a Custom Streamlit App
|
| 207 |
+
|
| 208 |
+
You can use the API from your own Streamlit app:
|
| 209 |
+
|
| 210 |
+
```python
|
| 211 |
+
import streamlit as st
|
| 212 |
+
import requests
|
| 213 |
+
|
| 214 |
+
API_URL = "http://localhost:8000"
|
| 215 |
+
|
| 216 |
+
# Query function
|
| 217 |
+
def query_rag(query, session_id=None):
|
| 218 |
+
response = requests.post(
|
| 219 |
+
f"{API_URL}/query",
|
| 220 |
+
json={
|
| 221 |
+
"query": query,
|
| 222 |
+
"session_id": session_id,
|
| 223 |
+
"top_k": 5,
|
| 224 |
+
"use_memory": True
|
| 225 |
+
}
|
| 226 |
+
)
|
| 227 |
+
return response.json()
|
| 228 |
+
|
| 229 |
+
# Use in your Streamlit app
|
| 230 |
+
st.title("My Custom RAG App")
|
| 231 |
+
query = st.text_input("Ask a question")
|
| 232 |
+
if query:
|
| 233 |
+
result = query_rag(query, session_id="my-session")
|
| 234 |
+
st.write(result["answer"])
|
| 235 |
+
```
|
| 236 |
+
|
| 237 |
+
## Features
|
| 238 |
+
|
| 239 |
+
✅ **Document Upload & Processing**: Upload PDFs and process them into chunks
|
| 240 |
+
✅ **RAG Querying**: Query documents with retrieval-augmented generation
|
| 241 |
+
✅ **Conversation Memory**: Maintain conversation history per session
|
| 242 |
+
✅ **Metadata Filtering**: Filter documents by source, page, or custom metadata
|
| 243 |
+
✅ **Concise Memory**: Automatically summarizes answers for efficient memory storage
|
| 244 |
+
✅ **Session Management**: Multiple concurrent chat sessions
|
| 245 |
+
✅ **RESTful API**: Standard REST endpoints for easy integration
|
| 246 |
+
|
| 247 |
+
## Error Handling
|
| 248 |
+
|
| 249 |
+
All endpoints return appropriate HTTP status codes:
|
| 250 |
+
- `200`: Success
|
| 251 |
+
- `400`: Bad Request (invalid input)
|
| 252 |
+
- `404`: Not Found (session/resource not found)
|
| 253 |
+
- `500`: Internal Server Error
|
| 254 |
+
|
| 255 |
+
Error responses include a `detail` field with the error message.
|
| 256 |
+
|
Dockerfile
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Use Python base image
|
| 2 |
+
FROM python:3.10
|
| 3 |
+
|
| 4 |
+
# Create user (required for HF Spaces)
|
| 5 |
+
RUN useradd -m user
|
| 6 |
+
USER user
|
| 7 |
+
ENV PATH="/home/user/.local/bin:$PATH"
|
| 8 |
+
|
| 9 |
+
WORKDIR /home/user/app
|
| 10 |
+
|
| 11 |
+
# Copy all project files
|
| 12 |
+
COPY --chown=user . .
|
| 13 |
+
|
| 14 |
+
# Install dependencies
|
| 15 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 16 |
+
|
| 17 |
+
# Expose ports
|
| 18 |
+
EXPOSE 8000
|
| 19 |
+
EXPOSE 8501
|
| 20 |
+
|
| 21 |
+
# Start FastAPI in background + Streamlit in foreground
|
| 22 |
+
CMD uvicorn api:app --host 0.0.0.0 --port 8000 & \
|
| 23 |
+
streamlit run app_api.py --server.port 8501 --server.address 0.0.0.0
|
README.md
CHANGED
|
@@ -1,10 +1,148 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
---
|
| 9 |
|
| 10 |
-
|
|
|
|
| 1 |
+
# RAG Pipeline - Retrieval-Augmented Generation System
|
| 2 |
+
|
| 3 |
+
A comprehensive RAG (Retrieval-Augmented Generation) pipeline that processes PDF documents, creates embeddings, stores them in a vector database, and enables intelligent querying using Large Language Models with conversation memory.
|
| 4 |
+
|
| 5 |
+
## 🚀 Features
|
| 6 |
+
|
| 7 |
+
- **PDF Document Processing**: Upload and process multiple PDF files with configurable chunking
|
| 8 |
+
- **Semantic Search**: Vector-based document retrieval using ChromaDB for finding relevant content
|
| 9 |
+
- **Conversational AI**: Query documents with conversation memory that remembers previous context
|
| 10 |
+
- **Metadata Filtering**: Filter documents by source file, page number, or custom metadata for faster and more accurate retrieval
|
| 11 |
+
- **Concise Memory**: Automatically summarizes answers to keep conversation history efficient and reduce token usage
|
| 12 |
+
- **REST API**: Full REST API for integration with any application or custom UIs
|
| 13 |
+
- **Streamlit UI**: User-friendly web interface for document upload and interactive querying
|
| 14 |
+
- **Multiple LLM Support**: Currently supports Groq LLM (easily extensible to other providers)
|
| 15 |
+
|
| 16 |
+
## 📦 Installation
|
| 17 |
+
|
| 18 |
+
1. **Clone the repository** and navigate to the project directory
|
| 19 |
+
2. **Install dependencies**: `pip install -r requirements.txt`
|
| 20 |
+
3. **Set up environment**: Create a `.env` file with your `GROQ_API_KEY` (get it from https://console.groq.com/)
|
| 21 |
+
|
| 22 |
+
## 🚀 Quick Start
|
| 23 |
+
|
| 24 |
+
### Streamlit Web App
|
| 25 |
+
Run `streamlit run app.py` and open http://localhost:8501 in your browser. Upload PDFs in the "Upload & Process" tab, then query them in the "Chat" tab.
|
| 26 |
+
|
| 27 |
+
### REST API
|
| 28 |
+
Run `uvicorn api:app --reload` and visit http://localhost:8000/docs for interactive API documentation. Use the API endpoints to upload documents and query them programmatically.
|
| 29 |
+
|
| 30 |
+
### Python Scripts
|
| 31 |
+
Use the core functions from `src/rag_pipeline.py` directly in your Python code, or run `python example_client.py` for a complete example.
|
| 32 |
+
|
| 33 |
+
## 📁 Project Structure
|
| 34 |
+
|
| 35 |
+
- **`src/rag_pipeline.py`**: Core RAG pipeline components (document processing, embeddings, vector store, retrieval, generation)
|
| 36 |
+
- **`app.py`**: Streamlit web application with UI for document upload and chat interface
|
| 37 |
+
- **`api.py`**: FastAPI REST API server for programmatic access
|
| 38 |
+
- **`example_client.py`**: Example Python client demonstrating API usage
|
| 39 |
+
- **`data/pdf/`**: Directory for PDF documents
|
| 40 |
+
- **`data/vector_store/`**: ChromaDB vector store persistence directory
|
| 41 |
+
- **`notebook/`**: Jupyter notebooks for experimentation and development
|
| 42 |
+
|
| 43 |
+
## 💡 How It Works
|
| 44 |
+
|
| 45 |
+
### Document Processing Flow
|
| 46 |
+
|
| 47 |
+
1. **Upload**: PDF files are uploaded and loaded using PyMuPDFLoader
|
| 48 |
+
2. **Chunking**: Documents are split into smaller chunks using RecursiveCharacterTextSplitter with configurable size and overlap
|
| 49 |
+
3. **Embedding**: Each chunk is converted to a vector embedding using SentenceTransformer models
|
| 50 |
+
4. **Storage**: Embeddings and documents are stored in ChromaDB vector database with metadata
|
| 51 |
+
5. **Retrieval**: When querying, the query is embedded and semantically similar documents are retrieved
|
| 52 |
+
6. **Generation**: Retrieved context is combined with the query and conversation history, then sent to the LLM for answer generation
|
| 53 |
+
|
| 54 |
+
### Key Components
|
| 55 |
+
|
| 56 |
+
- **EmbeddingModel**: Manages sentence transformer models for generating document and query embeddings
|
| 57 |
+
- **VectorStore**: Handles ChromaDB operations for storing and querying document embeddings
|
| 58 |
+
- **RagRetriever**: Performs semantic search with optional metadata filtering
|
| 59 |
+
- **RAG Pipeline Functions**: Combine retrieval with LLM generation, supporting conversation memory
|
| 60 |
+
|
| 61 |
+
### Conversation Memory
|
| 62 |
+
|
| 63 |
+
The system maintains conversation history per session, storing:
|
| 64 |
+
- Full user queries for context
|
| 65 |
+
- Concise summaries of assistant answers (extracted key points) to save space
|
| 66 |
+
- Previous conversation context is included in prompts to enable follow-up questions
|
| 67 |
+
|
| 68 |
+
### Metadata Filtering
|
| 69 |
+
|
| 70 |
+
Filter documents before retrieval to:
|
| 71 |
+
- Search only in specific source files
|
| 72 |
+
- Limit to certain page ranges
|
| 73 |
+
- Apply custom metadata filters
|
| 74 |
+
- Improve retrieval speed and accuracy by reducing search space
|
| 75 |
+
|
| 76 |
+
## 📚 Usage
|
| 77 |
+
|
| 78 |
+
### Streamlit App
|
| 79 |
+
|
| 80 |
+
The web interface provides two main tabs:
|
| 81 |
+
- **Upload & Process**: Upload PDF files, configure chunking parameters (chunk size, overlap), and process documents. View system status including document and chunk counts.
|
| 82 |
+
- **Chat**: Interactive chat interface where you can ask questions about uploaded documents. The chat remembers previous conversations within the session. You can enable metadata filtering in the sidebar to narrow down searches.
|
| 83 |
+
|
| 84 |
+
### REST API
|
| 85 |
+
|
| 86 |
+
The API provides endpoints for:
|
| 87 |
+
- **Upload**: Upload and process PDF documents with custom chunking parameters
|
| 88 |
+
- **Query**: Query documents with optional conversation memory and metadata filtering
|
| 89 |
+
- **Chat History**: Retrieve or clear conversation history for specific sessions
|
| 90 |
+
- **Status**: Check system status and document counts
|
| 91 |
+
- **Reset**: Clear all documents and chat histories
|
| 92 |
+
|
| 93 |
+
See `API_USAGE.md` for detailed API documentation and examples.
|
| 94 |
+
|
| 95 |
+
### Python Integration
|
| 96 |
+
|
| 97 |
+
Import functions from `src/rag_pipeline.py` to:
|
| 98 |
+
- Process PDFs from directories
|
| 99 |
+
- Chunk documents with custom parameters
|
| 100 |
+
- Generate embeddings
|
| 101 |
+
- Store in vector database
|
| 102 |
+
- Retrieve relevant documents
|
| 103 |
+
- Generate answers with conversation context
|
| 104 |
+
|
| 105 |
+
## ⚙️ Configuration
|
| 106 |
+
|
| 107 |
+
### Environment Variables
|
| 108 |
+
|
| 109 |
+
Set `GROQ_API_KEY` in your `.env` file to use Groq LLM models.
|
| 110 |
+
|
| 111 |
+
### Customization Options
|
| 112 |
+
|
| 113 |
+
- **Embedding Model**: Change the SentenceTransformer model (default: `all-MiniLM-L6-v2`)
|
| 114 |
+
- **Vector Store**: Customize collection name and persistence directory
|
| 115 |
+
- **LLM Model**: Choose different Groq models or extend to other providers
|
| 116 |
+
- **Chunking**: Adjust chunk size and overlap based on your document types
|
| 117 |
+
- **Retrieval**: Configure top_k results and similarity score thresholds
|
| 118 |
+
|
| 119 |
+
## 🔧 Troubleshooting
|
| 120 |
+
|
| 121 |
+
**Module not found errors**: Ensure all dependencies are installed with `pip install -r requirements.txt`
|
| 122 |
+
|
| 123 |
+
**API key errors**: Verify your `.env` file contains the correct `GROQ_API_KEY`
|
| 124 |
+
|
| 125 |
+
**No documents retrieved**: Check that documents were successfully processed, verify the query matches document content, and try rephrasing
|
| 126 |
+
|
| 127 |
+
**Metadata filtering issues**: Ensure metadata fields exist in your documents and restart the server after code changes
|
| 128 |
+
|
| 129 |
+
**Negative similarity scores**: This is normal for some queries - the system will still return results even with low similarity
|
| 130 |
+
|
| 131 |
+
## 📖 Additional Resources
|
| 132 |
+
|
| 133 |
+
- **API Documentation**: See `API_USAGE.md` for complete REST API usage guide
|
| 134 |
+
- **Interactive API Docs**: Visit http://localhost:8000/docs when the API server is running
|
| 135 |
+
- **Example Client**: Run `python example_client.py` to see a complete usage example
|
| 136 |
+
|
| 137 |
+
## 🛠️ Technology Stack
|
| 138 |
+
|
| 139 |
+
- **LangChain**: Document processing and text splitting
|
| 140 |
+
- **Sentence Transformers**: Embedding generation
|
| 141 |
+
- **ChromaDB**: Vector database for semantic search
|
| 142 |
+
- **Groq**: Fast LLM inference
|
| 143 |
+
- **FastAPI**: REST API framework
|
| 144 |
+
- **Streamlit**: Web UI framework
|
| 145 |
+
|
| 146 |
---
|
| 147 |
|
| 148 |
+
**Built for efficient document querying with AI-powered retrieval and generation.**
|
__pycache__/api.cpython-312.pyc
ADDED
|
Binary file (14.8 kB). View file
|
|
|
api.py
ADDED
|
@@ -0,0 +1,401 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
RAG Pipeline REST API
|
| 3 |
+
A FastAPI-based REST API for the RAG Pipeline system.
|
| 4 |
+
Can be used from terminal, other applications, or to build custom UIs.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from fastapi import FastAPI, UploadFile, File, HTTPException, Form
|
| 8 |
+
from fastapi.responses import JSONResponse
|
| 9 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 10 |
+
from pydantic import BaseModel
|
| 11 |
+
from typing import List, Optional, Dict, Any
|
| 12 |
+
import os
|
| 13 |
+
import tempfile
|
| 14 |
+
import uuid
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
# Import RAG pipeline components
|
| 18 |
+
from src.rag_pipeline import (
|
| 19 |
+
process_pdfs_in_directory,
|
| 20 |
+
documents_chunking,
|
| 21 |
+
EmbeddingModel,
|
| 22 |
+
VectorStore,
|
| 23 |
+
RagRetriever,
|
| 24 |
+
create_groq_llm,
|
| 25 |
+
rag_pipeline_with_memory,
|
| 26 |
+
summarize_answer,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
app = FastAPI(
|
| 30 |
+
title="RAG Pipeline API",
|
| 31 |
+
description="REST API for Retrieval-Augmented Generation with PDF documents",
|
| 32 |
+
version="1.0.0"
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
# Enable CORS for cross-origin requests
|
| 36 |
+
app.add_middleware(
|
| 37 |
+
CORSMiddleware,
|
| 38 |
+
allow_origins=["*"], # In production, specify allowed origins
|
| 39 |
+
allow_credentials=True,
|
| 40 |
+
allow_methods=["*"],
|
| 41 |
+
allow_headers=["*"],
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
# Global state (in production, use a proper state management system)
|
| 45 |
+
global_state = {
|
| 46 |
+
"vectorstore": None,
|
| 47 |
+
"retriever": None,
|
| 48 |
+
"llm": None,
|
| 49 |
+
"embedding_manager": None,
|
| 50 |
+
"documents_processed": False,
|
| 51 |
+
"chat_histories": {} # Store chat histories per session
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# Pydantic models for request/response
|
| 56 |
+
class QueryRequest(BaseModel):
|
| 57 |
+
query: str
|
| 58 |
+
session_id: Optional[str] = None
|
| 59 |
+
top_k: int = 5
|
| 60 |
+
metadata_filters: Optional[Dict[str, Any]] = None
|
| 61 |
+
use_memory: bool = True
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class QueryResponse(BaseModel):
|
| 65 |
+
answer: str
|
| 66 |
+
sources: List[Dict[str, Any]]
|
| 67 |
+
session_id: str
|
| 68 |
+
message: str
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class ProcessDocumentsRequest(BaseModel):
|
| 72 |
+
chunk_size: int = 800
|
| 73 |
+
chunk_overlap: int = 200
|
| 74 |
+
collection_name: Optional[str] = None
|
| 75 |
+
persist_directory: Optional[str] = None
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class ProcessDocumentsResponse(BaseModel):
|
| 79 |
+
success: bool
|
| 80 |
+
message: str
|
| 81 |
+
documents_loaded: int
|
| 82 |
+
chunks_created: int
|
| 83 |
+
vector_store_count: int
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class SystemStatusResponse(BaseModel):
|
| 87 |
+
documents_processed: bool
|
| 88 |
+
vector_store_count: int
|
| 89 |
+
chunks_available: Optional[int]
|
| 90 |
+
embedding_model: Optional[str]
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class ChatHistoryResponse(BaseModel):
|
| 94 |
+
session_id: str
|
| 95 |
+
history: List[Dict[str, str]]
|
| 96 |
+
message_count: int
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def initialize_components():
|
| 100 |
+
"""Initialize RAG components if not already initialized."""
|
| 101 |
+
if global_state["embedding_manager"] is None:
|
| 102 |
+
global_state["embedding_manager"] = EmbeddingModel()
|
| 103 |
+
|
| 104 |
+
if global_state["llm"] is None:
|
| 105 |
+
try:
|
| 106 |
+
global_state["llm"] = create_groq_llm()
|
| 107 |
+
except ValueError as e:
|
| 108 |
+
raise HTTPException(status_code=500, detail=f"Error initializing LLM: {str(e)}")
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
@app.get("/")
|
| 112 |
+
async def root():
|
| 113 |
+
"""API root endpoint with information."""
|
| 114 |
+
return {
|
| 115 |
+
"message": "RAG Pipeline API",
|
| 116 |
+
"version": "1.0.0",
|
| 117 |
+
"endpoints": {
|
| 118 |
+
"POST /upload": "Upload and process PDF documents",
|
| 119 |
+
"POST /query": "Query documents using RAG",
|
| 120 |
+
"GET /status": "Get system status",
|
| 121 |
+
"GET /chat-history/{session_id}": "Get chat history for a session",
|
| 122 |
+
"DELETE /chat-history/{session_id}": "Clear chat history for a session",
|
| 123 |
+
"POST /reset": "Reset the entire system",
|
| 124 |
+
"GET /docs": "API documentation (Swagger UI)"
|
| 125 |
+
}
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
@app.get("/status", response_model=SystemStatusResponse)
|
| 130 |
+
async def get_status():
|
| 131 |
+
"""Get the current status of the RAG system."""
|
| 132 |
+
chunks_available = None
|
| 133 |
+
if global_state.get("chunked_documents"):
|
| 134 |
+
chunks_available = len(global_state["chunked_documents"])
|
| 135 |
+
|
| 136 |
+
vector_store_count = 0
|
| 137 |
+
if global_state["vectorstore"]:
|
| 138 |
+
try:
|
| 139 |
+
vector_store_count = global_state["vectorstore"].collection.count()
|
| 140 |
+
except:
|
| 141 |
+
pass
|
| 142 |
+
|
| 143 |
+
embedding_model = None
|
| 144 |
+
if global_state["embedding_manager"]:
|
| 145 |
+
embedding_model = global_state["embedding_manager"].model_name
|
| 146 |
+
|
| 147 |
+
return SystemStatusResponse(
|
| 148 |
+
documents_processed=global_state["documents_processed"],
|
| 149 |
+
vector_store_count=vector_store_count,
|
| 150 |
+
chunks_available=chunks_available,
|
| 151 |
+
embedding_model=embedding_model
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
@app.post("/upload", response_model=ProcessDocumentsResponse)
|
| 156 |
+
async def upload_and_process_documents(
|
| 157 |
+
files: List[UploadFile] = File(...),
|
| 158 |
+
chunk_size: int = Form(800),
|
| 159 |
+
chunk_overlap: int = Form(200),
|
| 160 |
+
collection_name: Optional[str] = Form(None),
|
| 161 |
+
persist_directory: Optional[str] = Form(None)
|
| 162 |
+
):
|
| 163 |
+
"""
|
| 164 |
+
Upload PDF files and process them for RAG.
|
| 165 |
+
|
| 166 |
+
- **files**: List of PDF files to upload
|
| 167 |
+
- **chunk_size**: Size of text chunks (default: 800)
|
| 168 |
+
- **chunk_overlap**: Overlap between chunks (default: 200)
|
| 169 |
+
- **collection_name**: Optional custom collection name
|
| 170 |
+
- **persist_directory**: Optional custom persist directory
|
| 171 |
+
"""
|
| 172 |
+
if not files:
|
| 173 |
+
raise HTTPException(status_code=400, detail="No files provided")
|
| 174 |
+
|
| 175 |
+
# Create temporary directory for uploaded files
|
| 176 |
+
with tempfile.TemporaryDirectory() as temp_dir:
|
| 177 |
+
# Save uploaded files
|
| 178 |
+
for file in files:
|
| 179 |
+
if not file.filename.endswith('.pdf'):
|
| 180 |
+
raise HTTPException(status_code=400, detail=f"File {file.filename} is not a PDF")
|
| 181 |
+
|
| 182 |
+
file_path = os.path.join(temp_dir, file.filename)
|
| 183 |
+
with open(file_path, "wb") as f:
|
| 184 |
+
content = await file.read()
|
| 185 |
+
f.write(content)
|
| 186 |
+
|
| 187 |
+
try:
|
| 188 |
+
# Process PDFs
|
| 189 |
+
documents = process_pdfs_in_directory(temp_dir)
|
| 190 |
+
if not documents:
|
| 191 |
+
raise HTTPException(status_code=400, detail="No documents were loaded from PDFs")
|
| 192 |
+
|
| 193 |
+
documents_count = len(documents)
|
| 194 |
+
|
| 195 |
+
# Chunk documents
|
| 196 |
+
chunked_documents = documents_chunking(
|
| 197 |
+
documents,
|
| 198 |
+
chunk_size=chunk_size,
|
| 199 |
+
chunk_overlap=chunk_overlap
|
| 200 |
+
)
|
| 201 |
+
global_state["chunked_documents"] = chunked_documents
|
| 202 |
+
|
| 203 |
+
# Initialize components
|
| 204 |
+
initialize_components()
|
| 205 |
+
|
| 206 |
+
# Generate embeddings
|
| 207 |
+
texts = [doc.page_content for doc in chunked_documents]
|
| 208 |
+
embeddings = global_state["embedding_manager"].generate_embedding(texts)
|
| 209 |
+
|
| 210 |
+
# Initialize or get vector store
|
| 211 |
+
if global_state["vectorstore"] is None:
|
| 212 |
+
global_state["vectorstore"] = VectorStore(
|
| 213 |
+
collection_name=collection_name or "pdf_documents",
|
| 214 |
+
persist_directory=persist_directory or "./data/vector_store"
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
# Add documents to vector store
|
| 218 |
+
global_state["vectorstore"].add_documents(
|
| 219 |
+
documents=chunked_documents,
|
| 220 |
+
embeddings=embeddings
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
# Initialize retriever
|
| 224 |
+
global_state["retriever"] = RagRetriever(
|
| 225 |
+
vector_store=global_state["vectorstore"],
|
| 226 |
+
embedding_manager=global_state["embedding_manager"]
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
global_state["documents_processed"] = True
|
| 230 |
+
vector_store_count = global_state["vectorstore"].collection.count()
|
| 231 |
+
|
| 232 |
+
return ProcessDocumentsResponse(
|
| 233 |
+
success=True,
|
| 234 |
+
message="Documents processed successfully",
|
| 235 |
+
documents_loaded=documents_count,
|
| 236 |
+
chunks_created=len(chunked_documents),
|
| 237 |
+
vector_store_count=vector_store_count
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
except Exception as e:
|
| 241 |
+
raise HTTPException(status_code=500, detail=f"Error processing documents: {str(e)}")
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
@app.post("/query", response_model=QueryResponse)
|
| 245 |
+
async def query_documents(request: QueryRequest):
|
| 246 |
+
"""
|
| 247 |
+
Query documents using RAG with optional conversation memory.
|
| 248 |
+
|
| 249 |
+
- **query**: The question to ask
|
| 250 |
+
- **session_id**: Optional session ID for conversation memory (auto-generated if not provided)
|
| 251 |
+
- **top_k**: Number of documents to retrieve (default: 5)
|
| 252 |
+
- **metadata_filters**: Optional metadata filters (e.g., {"source": "file.pdf", "page": 1})
|
| 253 |
+
- **use_memory**: Whether to use conversation history (default: True)
|
| 254 |
+
"""
|
| 255 |
+
if not global_state["documents_processed"]:
|
| 256 |
+
raise HTTPException(
|
| 257 |
+
status_code=400,
|
| 258 |
+
detail="No documents processed. Please upload and process documents first using /upload endpoint."
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
if not global_state["retriever"] or not global_state["llm"]:
|
| 262 |
+
raise HTTPException(
|
| 263 |
+
status_code=500,
|
| 264 |
+
detail="System not properly initialized. Please process documents first."
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
# Generate or use session ID
|
| 268 |
+
session_id = request.session_id or str(uuid.uuid4())
|
| 269 |
+
|
| 270 |
+
# Get or create chat history for this session
|
| 271 |
+
if session_id not in global_state["chat_histories"]:
|
| 272 |
+
global_state["chat_histories"][session_id] = []
|
| 273 |
+
|
| 274 |
+
chat_history = global_state["chat_histories"][session_id]
|
| 275 |
+
|
| 276 |
+
try:
|
| 277 |
+
# Clean and validate metadata filters
|
| 278 |
+
cleaned_filters = None
|
| 279 |
+
if request.metadata_filters:
|
| 280 |
+
cleaned_filters = {}
|
| 281 |
+
for key, value in request.metadata_filters.items():
|
| 282 |
+
# Skip empty values, None, empty dicts, empty lists, empty strings
|
| 283 |
+
if value is None:
|
| 284 |
+
continue
|
| 285 |
+
if isinstance(value, dict) and len(value) == 0:
|
| 286 |
+
continue
|
| 287 |
+
if isinstance(value, list) and len(value) == 0:
|
| 288 |
+
continue
|
| 289 |
+
if isinstance(value, str) and len(value.strip()) == 0:
|
| 290 |
+
continue
|
| 291 |
+
# Only add valid filters
|
| 292 |
+
cleaned_filters[key] = value
|
| 293 |
+
|
| 294 |
+
# If all filters were invalid, set to None
|
| 295 |
+
if len(cleaned_filters) == 0:
|
| 296 |
+
cleaned_filters = None
|
| 297 |
+
|
| 298 |
+
# Retrieve documents
|
| 299 |
+
results = global_state["retriever"].retrieve(
|
| 300 |
+
query=request.query,
|
| 301 |
+
top_k=request.top_k,
|
| 302 |
+
score_threshold=0,
|
| 303 |
+
metadata_filters=cleaned_filters
|
| 304 |
+
)
|
| 305 |
+
|
| 306 |
+
# Prepare sources
|
| 307 |
+
sources = [{
|
| 308 |
+
"score": r.get("score", 0),
|
| 309 |
+
"preview": r.get("document", "")[:300] + "...",
|
| 310 |
+
"metadata": r.get("metadata", {}),
|
| 311 |
+
"id": r.get("id", "")
|
| 312 |
+
} for r in results] if results else []
|
| 313 |
+
|
| 314 |
+
# Get answer using RAG pipeline
|
| 315 |
+
conversation_history = chat_history if request.use_memory else None
|
| 316 |
+
answer = rag_pipeline_with_memory(
|
| 317 |
+
query=request.query,
|
| 318 |
+
retriever=global_state["retriever"],
|
| 319 |
+
llm=global_state["llm"],
|
| 320 |
+
conversation_history=conversation_history,
|
| 321 |
+
top_k=request.top_k,
|
| 322 |
+
metadata_filters=request.metadata_filters
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
# Create concise summary for memory
|
| 326 |
+
concise_answer = summarize_answer(answer, global_state["llm"], max_length=150)
|
| 327 |
+
|
| 328 |
+
# Update chat history
|
| 329 |
+
chat_history.append({
|
| 330 |
+
"role": "user",
|
| 331 |
+
"content": request.query
|
| 332 |
+
})
|
| 333 |
+
chat_history.append({
|
| 334 |
+
"role": "assistant",
|
| 335 |
+
"content": answer,
|
| 336 |
+
"concise": concise_answer,
|
| 337 |
+
"sources": sources
|
| 338 |
+
})
|
| 339 |
+
|
| 340 |
+
return QueryResponse(
|
| 341 |
+
answer=answer,
|
| 342 |
+
sources=sources,
|
| 343 |
+
session_id=session_id,
|
| 344 |
+
message="Query processed successfully"
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
except Exception as e:
|
| 348 |
+
raise HTTPException(status_code=500, detail=f"Error processing query: {str(e)}")
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
@app.get("/chat-history/{session_id}", response_model=ChatHistoryResponse)
|
| 352 |
+
async def get_chat_history(session_id: str):
|
| 353 |
+
"""Get chat history for a specific session."""
|
| 354 |
+
if session_id not in global_state["chat_histories"]:
|
| 355 |
+
raise HTTPException(status_code=404, detail="Session not found")
|
| 356 |
+
|
| 357 |
+
history = global_state["chat_histories"][session_id]
|
| 358 |
+
return ChatHistoryResponse(
|
| 359 |
+
session_id=session_id,
|
| 360 |
+
history=history,
|
| 361 |
+
message_count=len(history)
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
@app.delete("/chat-history/{session_id}")
|
| 366 |
+
async def clear_chat_history(session_id: str):
|
| 367 |
+
"""Clear chat history for a specific session."""
|
| 368 |
+
if session_id in global_state["chat_histories"]:
|
| 369 |
+
global_state["chat_histories"][session_id] = []
|
| 370 |
+
return {"message": f"Chat history cleared for session {session_id}"}
|
| 371 |
+
else:
|
| 372 |
+
raise HTTPException(status_code=404, detail="Session not found")
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
@app.post("/reset")
|
| 376 |
+
async def reset_system():
|
| 377 |
+
"""Reset the entire RAG system (clears all documents and chat histories)."""
|
| 378 |
+
global_state["vectorstore"] = None
|
| 379 |
+
global_state["retriever"] = None
|
| 380 |
+
global_state["llm"] = None
|
| 381 |
+
global_state["embedding_manager"] = None
|
| 382 |
+
global_state["documents_processed"] = False
|
| 383 |
+
global_state["chunked_documents"] = None
|
| 384 |
+
global_state["chat_histories"] = {}
|
| 385 |
+
|
| 386 |
+
return {"message": "System reset successfully"}
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
@app.get("/sessions")
|
| 390 |
+
async def list_sessions():
|
| 391 |
+
"""List all active chat sessions."""
|
| 392 |
+
return {
|
| 393 |
+
"sessions": list(global_state["chat_histories"].keys()),
|
| 394 |
+
"count": len(global_state["chat_histories"])
|
| 395 |
+
}
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
if __name__ == "__main__":
|
| 399 |
+
import uvicorn
|
| 400 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|
| 401 |
+
|
app_api.py
ADDED
|
@@ -0,0 +1,407 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Streamlit App for RAG Pipeline using FastAPI
|
| 3 |
+
This app uses the REST API endpoints instead of calling functions directly.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import streamlit as st
|
| 7 |
+
import requests
|
| 8 |
+
from typing import Dict, Any, Optional
|
| 9 |
+
import os
|
| 10 |
+
|
| 11 |
+
# API Configuration
|
| 12 |
+
API_BASE_URL = os.getenv("API_BASE_URL", "http://localhost:8000")
|
| 13 |
+
|
| 14 |
+
# Page configuration
|
| 15 |
+
st.set_page_config(
|
| 16 |
+
page_title="RAG Pipeline - PDF Query System (API)",
|
| 17 |
+
page_icon="📚",
|
| 18 |
+
layout="wide"
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
# Initialize session state
|
| 22 |
+
if 'session_id' not in st.session_state:
|
| 23 |
+
st.session_state.session_id = None
|
| 24 |
+
if 'documents_processed' not in st.session_state:
|
| 25 |
+
st.session_state.documents_processed = False
|
| 26 |
+
if 'chat_history' not in st.session_state:
|
| 27 |
+
st.session_state.chat_history = []
|
| 28 |
+
if 'system_status' not in st.session_state:
|
| 29 |
+
st.session_state.system_status = None
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def check_api_connection():
|
| 33 |
+
"""Check if API is accessible."""
|
| 34 |
+
try:
|
| 35 |
+
response = requests.get(f"{API_BASE_URL}/", timeout=5)
|
| 36 |
+
return response.status_code == 200
|
| 37 |
+
except:
|
| 38 |
+
return False
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def get_system_status():
|
| 42 |
+
"""Get system status from API."""
|
| 43 |
+
try:
|
| 44 |
+
response = requests.get(f"{API_BASE_URL}/status", timeout=5)
|
| 45 |
+
if response.status_code == 200:
|
| 46 |
+
return response.json()
|
| 47 |
+
return None
|
| 48 |
+
except Exception as e:
|
| 49 |
+
st.error(f"Error connecting to API: {str(e)}")
|
| 50 |
+
return None
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def upload_documents_api(files, chunk_size, chunk_overlap):
|
| 54 |
+
"""Upload and process documents via API."""
|
| 55 |
+
try:
|
| 56 |
+
files_data = []
|
| 57 |
+
for file in files:
|
| 58 |
+
files_data.append(('files', (file.name, file.getvalue(), 'application/pdf')))
|
| 59 |
+
|
| 60 |
+
data = {
|
| 61 |
+
'chunk_size': chunk_size,
|
| 62 |
+
'chunk_overlap': chunk_overlap
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
response = requests.post(
|
| 66 |
+
f"{API_BASE_URL}/upload",
|
| 67 |
+
files=files_data,
|
| 68 |
+
data=data,
|
| 69 |
+
timeout=300 # 5 minutes for large files
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
if response.status_code == 200:
|
| 73 |
+
return response.json()
|
| 74 |
+
else:
|
| 75 |
+
error_detail = response.json().get('detail', 'Unknown error')
|
| 76 |
+
raise Exception(f"API Error: {error_detail}")
|
| 77 |
+
except requests.exceptions.RequestException as e:
|
| 78 |
+
raise Exception(f"Connection error: {str(e)}")
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def query_api(query, session_id, top_k, use_memory, metadata_filters=None):
|
| 82 |
+
"""Query documents via API."""
|
| 83 |
+
payload = {
|
| 84 |
+
"query": query,
|
| 85 |
+
"session_id": session_id,
|
| 86 |
+
"top_k": top_k,
|
| 87 |
+
"use_memory": use_memory
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
if metadata_filters:
|
| 91 |
+
payload["metadata_filters"] = metadata_filters
|
| 92 |
+
|
| 93 |
+
try:
|
| 94 |
+
response = requests.post(
|
| 95 |
+
f"{API_BASE_URL}/query",
|
| 96 |
+
json=payload,
|
| 97 |
+
timeout=60
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
if response.status_code == 200:
|
| 101 |
+
return response.json()
|
| 102 |
+
else:
|
| 103 |
+
error_detail = response.json().get('detail', 'Unknown error')
|
| 104 |
+
raise Exception(f"API Error: {error_detail}")
|
| 105 |
+
except requests.exceptions.RequestException as e:
|
| 106 |
+
raise Exception(f"Connection error: {str(e)}")
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def get_chat_history_api(session_id):
|
| 110 |
+
"""Get chat history from API."""
|
| 111 |
+
try:
|
| 112 |
+
response = requests.get(f"{API_BASE_URL}/chat-history/{session_id}", timeout=5)
|
| 113 |
+
if response.status_code == 200:
|
| 114 |
+
return response.json()
|
| 115 |
+
return None
|
| 116 |
+
except:
|
| 117 |
+
return None
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def clear_chat_history_api(session_id):
|
| 121 |
+
"""Clear chat history via API."""
|
| 122 |
+
try:
|
| 123 |
+
response = requests.delete(f"{API_BASE_URL}/chat-history/{session_id}", timeout=5)
|
| 124 |
+
return response.status_code == 200
|
| 125 |
+
except:
|
| 126 |
+
return False
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def get_metadata_options():
|
| 130 |
+
"""Get available metadata fields from API status or query."""
|
| 131 |
+
# This would require an API endpoint to get metadata fields
|
| 132 |
+
# For now, we'll use a simplified approach
|
| 133 |
+
status = get_system_status()
|
| 134 |
+
if status and status.get('vector_store_count', 0) > 0:
|
| 135 |
+
# We can't directly access vectorstore from API, so we'll use a workaround
|
| 136 |
+
# Try to get metadata from a sample query or add a new API endpoint
|
| 137 |
+
return {}
|
| 138 |
+
return {}
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def main():
|
| 142 |
+
"""Main Streamlit app."""
|
| 143 |
+
st.title("📚 RAG Pipeline - PDF Query System (API)")
|
| 144 |
+
st.markdown("Upload PDF files and query them using Retrieval-Augmented Generation (RAG) via REST API")
|
| 145 |
+
|
| 146 |
+
# Check API connection
|
| 147 |
+
if not check_api_connection():
|
| 148 |
+
st.error(f"❌ Cannot connect to API at {API_BASE_URL}")
|
| 149 |
+
st.info("Please make sure the API server is running:")
|
| 150 |
+
st.code("uvicorn api:app --reload --host 0.0.0.0 --port 8000")
|
| 151 |
+
st.stop()
|
| 152 |
+
|
| 153 |
+
# Get system status
|
| 154 |
+
if st.session_state.system_status is None:
|
| 155 |
+
st.session_state.system_status = get_system_status()
|
| 156 |
+
|
| 157 |
+
# Generate session ID if not exists
|
| 158 |
+
if st.session_state.session_id is None:
|
| 159 |
+
import uuid
|
| 160 |
+
st.session_state.session_id = str(uuid.uuid4())
|
| 161 |
+
|
| 162 |
+
# Sidebar for configuration
|
| 163 |
+
with st.sidebar:
|
| 164 |
+
st.header("⚙️ Configuration")
|
| 165 |
+
|
| 166 |
+
st.subheader("API Settings")
|
| 167 |
+
api_url = st.text_input(
|
| 168 |
+
"API Base URL",
|
| 169 |
+
value=API_BASE_URL,
|
| 170 |
+
help="Base URL of the FastAPI server"
|
| 171 |
+
)
|
| 172 |
+
if api_url != API_BASE_URL:
|
| 173 |
+
st.session_state.api_base_url = api_url
|
| 174 |
+
st.rerun()
|
| 175 |
+
|
| 176 |
+
if st.button("🔄 Refresh Status", type="secondary"):
|
| 177 |
+
st.session_state.system_status = get_system_status()
|
| 178 |
+
st.rerun()
|
| 179 |
+
|
| 180 |
+
st.subheader("Chunking Parameters")
|
| 181 |
+
chunk_size = st.slider(
|
| 182 |
+
"Chunk Size",
|
| 183 |
+
min_value=200,
|
| 184 |
+
max_value=2000,
|
| 185 |
+
value=800,
|
| 186 |
+
step=100,
|
| 187 |
+
help="Size of each text chunk in characters"
|
| 188 |
+
)
|
| 189 |
+
chunk_overlap = st.slider(
|
| 190 |
+
"Chunk Overlap",
|
| 191 |
+
min_value=0,
|
| 192 |
+
max_value=500,
|
| 193 |
+
value=200,
|
| 194 |
+
step=50,
|
| 195 |
+
help="Number of overlapping characters between chunks"
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
st.subheader("Query Parameters")
|
| 199 |
+
top_k = st.slider(
|
| 200 |
+
"Top K Results",
|
| 201 |
+
min_value=1,
|
| 202 |
+
max_value=10,
|
| 203 |
+
value=5,
|
| 204 |
+
help="Number of document chunks to retrieve"
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
st.subheader("🔍 Metadata Filters")
|
| 208 |
+
st.caption("Filter documents by metadata for faster, more accurate retrieval")
|
| 209 |
+
use_filters = st.checkbox("Enable Metadata Filtering", value=False)
|
| 210 |
+
|
| 211 |
+
metadata_filters = {}
|
| 212 |
+
if use_filters:
|
| 213 |
+
st.info("💡 Metadata filtering via API - enter filter values below")
|
| 214 |
+
with st.expander("Advanced: Custom Metadata Filter"):
|
| 215 |
+
filter_key = st.text_input("Metadata Key", placeholder="e.g., source, page")
|
| 216 |
+
filter_value = st.text_input("Metadata Value", placeholder="e.g., document.pdf or 1,2,3")
|
| 217 |
+
if filter_key and filter_value:
|
| 218 |
+
# Try to parse as list if comma-separated
|
| 219 |
+
if ',' in filter_value:
|
| 220 |
+
try:
|
| 221 |
+
# Try to parse as integers
|
| 222 |
+
metadata_filters[filter_key] = [int(v.strip()) for v in filter_value.split(',')]
|
| 223 |
+
except:
|
| 224 |
+
# Keep as strings
|
| 225 |
+
metadata_filters[filter_key] = [v.strip() for v in filter_value.split(',')]
|
| 226 |
+
else:
|
| 227 |
+
try:
|
| 228 |
+
# Try integer
|
| 229 |
+
metadata_filters[filter_key] = int(filter_value)
|
| 230 |
+
except:
|
| 231 |
+
# Keep as string
|
| 232 |
+
metadata_filters[filter_key] = filter_value
|
| 233 |
+
|
| 234 |
+
st.divider()
|
| 235 |
+
|
| 236 |
+
st.subheader("System Status")
|
| 237 |
+
status = st.session_state.system_status
|
| 238 |
+
if status:
|
| 239 |
+
if status.get('documents_processed'):
|
| 240 |
+
st.success("✅ Documents Processed")
|
| 241 |
+
st.info(f"🗄️ {status.get('vector_store_count', 0)} documents in vector store")
|
| 242 |
+
if status.get('chunks_available'):
|
| 243 |
+
st.info(f"📄 {status['chunks_available']} chunks available")
|
| 244 |
+
else:
|
| 245 |
+
st.info("⏳ No documents processed")
|
| 246 |
+
|
| 247 |
+
if status.get('embedding_model'):
|
| 248 |
+
st.caption(f"Model: {status['embedding_model']}")
|
| 249 |
+
else:
|
| 250 |
+
st.warning("⚠️ Could not fetch system status")
|
| 251 |
+
|
| 252 |
+
st.divider()
|
| 253 |
+
|
| 254 |
+
if st.button("🗑️ Clear Chat History", type="secondary"):
|
| 255 |
+
if st.session_state.session_id:
|
| 256 |
+
if clear_chat_history_api(st.session_state.session_id):
|
| 257 |
+
st.session_state.chat_history = []
|
| 258 |
+
st.success("Chat history cleared!")
|
| 259 |
+
st.rerun()
|
| 260 |
+
|
| 261 |
+
if st.button("🔄 Reset System", type="secondary"):
|
| 262 |
+
try:
|
| 263 |
+
response = requests.post(f"{API_BASE_URL}/reset", timeout=5)
|
| 264 |
+
if response.status_code == 200:
|
| 265 |
+
st.session_state.documents_processed = False
|
| 266 |
+
st.session_state.chat_history = []
|
| 267 |
+
st.session_state.system_status = get_system_status()
|
| 268 |
+
st.success("System reset!")
|
| 269 |
+
st.rerun()
|
| 270 |
+
except Exception as e:
|
| 271 |
+
st.error(f"Error resetting system: {str(e)}")
|
| 272 |
+
|
| 273 |
+
# Main content area
|
| 274 |
+
tab1, tab2 = st.tabs(["📤 Upload & Process", "💬 Chat"])
|
| 275 |
+
|
| 276 |
+
with tab1:
|
| 277 |
+
st.header("Upload PDF Files")
|
| 278 |
+
st.markdown("Upload one or more PDF files to process and add to the knowledge base via API.")
|
| 279 |
+
|
| 280 |
+
uploaded_files = st.file_uploader(
|
| 281 |
+
"Choose PDF files",
|
| 282 |
+
type=['pdf'],
|
| 283 |
+
accept_multiple_files=True,
|
| 284 |
+
help="You can upload multiple PDF files at once"
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
if uploaded_files:
|
| 288 |
+
st.info(f"📎 {len(uploaded_files)} file(s) selected")
|
| 289 |
+
|
| 290 |
+
# Display file names
|
| 291 |
+
with st.expander("View uploaded files"):
|
| 292 |
+
for file in uploaded_files:
|
| 293 |
+
st.write(f"- {file.name} ({file.size:,} bytes)")
|
| 294 |
+
|
| 295 |
+
if st.button("🚀 Process Documents", type="primary"):
|
| 296 |
+
with st.spinner("Uploading and processing documents via API..."):
|
| 297 |
+
try:
|
| 298 |
+
result = upload_documents_api(uploaded_files, chunk_size, chunk_overlap)
|
| 299 |
+
if result.get('success'):
|
| 300 |
+
st.success("✅ Documents processed successfully!")
|
| 301 |
+
st.json(result)
|
| 302 |
+
st.session_state.documents_processed = True
|
| 303 |
+
st.session_state.system_status = get_system_status()
|
| 304 |
+
else:
|
| 305 |
+
st.error("❌ Failed to process documents.")
|
| 306 |
+
except Exception as e:
|
| 307 |
+
st.error(f"❌ Error: {str(e)}")
|
| 308 |
+
|
| 309 |
+
with tab2:
|
| 310 |
+
st.header("💬 Chat with Documents")
|
| 311 |
+
st.markdown("Ask questions about the uploaded PDF documents. The chat remembers previous conversations.")
|
| 312 |
+
|
| 313 |
+
# Check if documents are processed
|
| 314 |
+
status = st.session_state.system_status
|
| 315 |
+
if not status or not status.get('documents_processed'):
|
| 316 |
+
st.warning("⚠️ Please upload and process documents first in the 'Upload & Process' tab.")
|
| 317 |
+
else:
|
| 318 |
+
# Display chat history
|
| 319 |
+
chat_container = st.container()
|
| 320 |
+
with chat_container:
|
| 321 |
+
if st.session_state.chat_history:
|
| 322 |
+
for message in st.session_state.chat_history:
|
| 323 |
+
role = message.get("role", "user")
|
| 324 |
+
content = message.get("content", "")
|
| 325 |
+
|
| 326 |
+
if role == "user":
|
| 327 |
+
with st.chat_message("user"):
|
| 328 |
+
st.write(content)
|
| 329 |
+
elif role == "assistant":
|
| 330 |
+
with st.chat_message("assistant"):
|
| 331 |
+
st.write(content)
|
| 332 |
+
# Show sources if available
|
| 333 |
+
if "sources" in message:
|
| 334 |
+
with st.expander("📄 Sources"):
|
| 335 |
+
for i, source in enumerate(message["sources"], 1):
|
| 336 |
+
st.markdown(f"**Source {i}** (Score: {source.get('score', 0):.4f})")
|
| 337 |
+
st.caption(f"Preview: {source.get('preview', '')[:200]}...")
|
| 338 |
+
else:
|
| 339 |
+
st.info("👋 Start a conversation by asking a question below!")
|
| 340 |
+
|
| 341 |
+
# Chat input
|
| 342 |
+
query = st.chat_input(
|
| 343 |
+
"Ask a question about the documents...",
|
| 344 |
+
key="chat_input"
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
# Handle query
|
| 348 |
+
if query:
|
| 349 |
+
# Add user message to chat history
|
| 350 |
+
st.session_state.chat_history.append({
|
| 351 |
+
"role": "user",
|
| 352 |
+
"content": query
|
| 353 |
+
})
|
| 354 |
+
|
| 355 |
+
with st.spinner("Thinking..."):
|
| 356 |
+
try:
|
| 357 |
+
# Query via API
|
| 358 |
+
result = query_api(
|
| 359 |
+
query=query,
|
| 360 |
+
session_id=st.session_state.session_id,
|
| 361 |
+
top_k=top_k,
|
| 362 |
+
use_memory=True,
|
| 363 |
+
metadata_filters=metadata_filters if use_filters and metadata_filters else None
|
| 364 |
+
)
|
| 365 |
+
|
| 366 |
+
# Add assistant response to chat history
|
| 367 |
+
st.session_state.chat_history.append({
|
| 368 |
+
"role": "assistant",
|
| 369 |
+
"content": result["answer"],
|
| 370 |
+
"sources": result.get("sources", [])
|
| 371 |
+
})
|
| 372 |
+
|
| 373 |
+
# Update session ID if API generated a new one
|
| 374 |
+
if result.get("session_id"):
|
| 375 |
+
st.session_state.session_id = result["session_id"]
|
| 376 |
+
|
| 377 |
+
st.rerun()
|
| 378 |
+
|
| 379 |
+
except Exception as e:
|
| 380 |
+
st.error(f"Error processing query: {str(e)}")
|
| 381 |
+
# Remove the user message if there was an error
|
| 382 |
+
if st.session_state.chat_history and st.session_state.chat_history[-1]["role"] == "user":
|
| 383 |
+
st.session_state.chat_history.pop()
|
| 384 |
+
|
| 385 |
+
# Example queries
|
| 386 |
+
if not st.session_state.chat_history:
|
| 387 |
+
st.divider()
|
| 388 |
+
st.subheader("💡 Example Queries")
|
| 389 |
+
example_queries = [
|
| 390 |
+
"What is the main topic of the document?",
|
| 391 |
+
"Summarize the key points",
|
| 392 |
+
"What are the main findings?",
|
| 393 |
+
]
|
| 394 |
+
|
| 395 |
+
cols = st.columns(len(example_queries))
|
| 396 |
+
for i, example in enumerate(example_queries):
|
| 397 |
+
with cols[i]:
|
| 398 |
+
if st.button(f"📝 {example[:30]}...", key=f"example_{i}"):
|
| 399 |
+
st.session_state.chat_history.append({
|
| 400 |
+
"role": "user",
|
| 401 |
+
"content": example
|
| 402 |
+
})
|
| 403 |
+
st.rerun()
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
if __name__ == "__main__":
|
| 407 |
+
main()
|
data/.DS_Store
ADDED
|
Binary file (6.15 kB). View file
|
|
|
data/pdf/.DS_Store
ADDED
|
Binary file (6.15 kB). View file
|
|
|
data/vector_store/.DS_Store
ADDED
|
Binary file (6.15 kB). View file
|
|
|
experimental_files/__pycache__/api.cpython-312.pyc
ADDED
|
Binary file (14.8 kB). View file
|
|
|
experimental_files/app.py
ADDED
|
@@ -0,0 +1,428 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Streamlit App for RAG Pipeline with PDF Upload
|
| 3 |
+
This app allows users to upload PDF files, process them, and query them using RAG.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import streamlit as st
|
| 7 |
+
import os
|
| 8 |
+
import tempfile
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import List
|
| 11 |
+
|
| 12 |
+
# Import RAG pipeline components
|
| 13 |
+
from src.rag_pipeline import (
|
| 14 |
+
process_pdfs_in_directory,
|
| 15 |
+
documents_chunking,
|
| 16 |
+
EmbeddingModel,
|
| 17 |
+
VectorStore,
|
| 18 |
+
RagRetriever,
|
| 19 |
+
create_groq_llm,
|
| 20 |
+
rag_pipeline,
|
| 21 |
+
rag_pipeline_with_memory,
|
| 22 |
+
summarize_answer,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
# Page configuration
|
| 26 |
+
st.set_page_config(
|
| 27 |
+
page_title="RAG Pipeline - PDF Query System",
|
| 28 |
+
page_icon="📚",
|
| 29 |
+
layout="wide"
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
# Initialize session state
|
| 33 |
+
if 'vectorstore' not in st.session_state:
|
| 34 |
+
st.session_state.vectorstore = None
|
| 35 |
+
if 'retriever' not in st.session_state:
|
| 36 |
+
st.session_state.retriever = None
|
| 37 |
+
if 'llm' not in st.session_state:
|
| 38 |
+
st.session_state.llm = None
|
| 39 |
+
if 'embedding_manager' not in st.session_state:
|
| 40 |
+
st.session_state.embedding_manager = None
|
| 41 |
+
if 'documents_processed' not in st.session_state:
|
| 42 |
+
st.session_state.documents_processed = False
|
| 43 |
+
if 'chunked_documents' not in st.session_state:
|
| 44 |
+
st.session_state.chunked_documents = None
|
| 45 |
+
if 'chat_history' not in st.session_state:
|
| 46 |
+
st.session_state.chat_history = []
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def initialize_components():
|
| 50 |
+
"""Initialize RAG components if not already initialized."""
|
| 51 |
+
if st.session_state.embedding_manager is None:
|
| 52 |
+
with st.spinner("Loading embedding model..."):
|
| 53 |
+
st.session_state.embedding_manager = EmbeddingModel()
|
| 54 |
+
|
| 55 |
+
if st.session_state.llm is None:
|
| 56 |
+
try:
|
| 57 |
+
with st.spinner("Initializing Groq LLM..."):
|
| 58 |
+
st.session_state.llm = create_groq_llm()
|
| 59 |
+
except ValueError as e:
|
| 60 |
+
st.error(f"Error initializing LLM: {e}")
|
| 61 |
+
st.info("Please make sure GROQ_API_KEY is set in your .env file.")
|
| 62 |
+
return False
|
| 63 |
+
|
| 64 |
+
return True
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def process_uploaded_pdfs(uploaded_files, chunk_size, chunk_overlap):
|
| 68 |
+
"""Process uploaded PDF files."""
|
| 69 |
+
if not uploaded_files:
|
| 70 |
+
st.warning("Please upload at least one PDF file.")
|
| 71 |
+
return False
|
| 72 |
+
|
| 73 |
+
# Create temporary directory for uploaded files
|
| 74 |
+
with tempfile.TemporaryDirectory() as temp_dir:
|
| 75 |
+
# Save uploaded files to temporary directory
|
| 76 |
+
for uploaded_file in uploaded_files:
|
| 77 |
+
file_path = os.path.join(temp_dir, uploaded_file.name)
|
| 78 |
+
with open(file_path, "wb") as f:
|
| 79 |
+
f.write(uploaded_file.getbuffer())
|
| 80 |
+
|
| 81 |
+
# Process PDFs
|
| 82 |
+
with st.spinner("Loading PDF documents..."):
|
| 83 |
+
documents = process_pdfs_in_directory(temp_dir)
|
| 84 |
+
|
| 85 |
+
if not documents:
|
| 86 |
+
st.error("No documents were loaded. Please check your PDF files.")
|
| 87 |
+
return False
|
| 88 |
+
|
| 89 |
+
st.success(f"Loaded {len(documents)} document(s)")
|
| 90 |
+
|
| 91 |
+
# Chunk documents
|
| 92 |
+
with st.spinner(f"Chunking documents (chunk_size={chunk_size}, overlap={chunk_overlap})..."):
|
| 93 |
+
chunked_documents = documents_chunking(
|
| 94 |
+
documents,
|
| 95 |
+
chunk_size=chunk_size,
|
| 96 |
+
chunk_overlap=chunk_overlap
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
st.session_state.chunked_documents = chunked_documents
|
| 100 |
+
|
| 101 |
+
# Initialize components
|
| 102 |
+
if not initialize_components():
|
| 103 |
+
return False
|
| 104 |
+
|
| 105 |
+
# Generate embeddings
|
| 106 |
+
with st.spinner("Generating embeddings..."):
|
| 107 |
+
texts = [doc.page_content for doc in chunked_documents]
|
| 108 |
+
embeddings = st.session_state.embedding_manager.generate_embedding(texts)
|
| 109 |
+
|
| 110 |
+
# Initialize or get vector store
|
| 111 |
+
if st.session_state.vectorstore is None:
|
| 112 |
+
st.session_state.vectorstore = VectorStore()
|
| 113 |
+
|
| 114 |
+
# Add documents to vector store
|
| 115 |
+
with st.spinner("Adding documents to vector store..."):
|
| 116 |
+
st.session_state.vectorstore.add_documents(
|
| 117 |
+
documents=chunked_documents,
|
| 118 |
+
embeddings=embeddings
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
# Initialize or recreate retriever (to ensure it has latest method signature)
|
| 122 |
+
st.session_state.retriever = RagRetriever(
|
| 123 |
+
vector_store=st.session_state.vectorstore,
|
| 124 |
+
embedding_manager=st.session_state.embedding_manager
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
st.session_state.documents_processed = True
|
| 128 |
+
return True
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def main():
|
| 132 |
+
"""Main Streamlit app."""
|
| 133 |
+
st.title("📚 RAG Pipeline - PDF Query System")
|
| 134 |
+
st.markdown("Upload PDF files and query them using Retrieval-Augmented Generation (RAG)")
|
| 135 |
+
|
| 136 |
+
# Sidebar for configuration
|
| 137 |
+
with st.sidebar:
|
| 138 |
+
st.header("⚙️ Configuration")
|
| 139 |
+
|
| 140 |
+
st.subheader("Chunking Parameters")
|
| 141 |
+
chunk_size = st.slider(
|
| 142 |
+
"Chunk Size",
|
| 143 |
+
min_value=200,
|
| 144 |
+
max_value=2000,
|
| 145 |
+
value=800,
|
| 146 |
+
step=100,
|
| 147 |
+
help="Size of each text chunk in characters"
|
| 148 |
+
)
|
| 149 |
+
chunk_overlap = st.slider(
|
| 150 |
+
"Chunk Overlap",
|
| 151 |
+
min_value=0,
|
| 152 |
+
max_value=500,
|
| 153 |
+
value=200,
|
| 154 |
+
step=50,
|
| 155 |
+
help="Number of overlapping characters between chunks"
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
st.subheader("Query Parameters")
|
| 159 |
+
top_k = st.slider(
|
| 160 |
+
"Top K Results",
|
| 161 |
+
min_value=1,
|
| 162 |
+
max_value=10,
|
| 163 |
+
value=5,
|
| 164 |
+
help="Number of document chunks to retrieve"
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
st.subheader("🔍 Metadata Filters")
|
| 168 |
+
st.caption("Filter documents by metadata for faster, more accurate retrieval")
|
| 169 |
+
use_filters = st.checkbox("Enable Metadata Filtering", value=False)
|
| 170 |
+
|
| 171 |
+
metadata_filters = {}
|
| 172 |
+
if use_filters and st.session_state.vectorstore:
|
| 173 |
+
try:
|
| 174 |
+
# Get sample metadata to show available fields
|
| 175 |
+
sample_results = st.session_state.vectorstore.collection.get(limit=1)
|
| 176 |
+
if sample_results.get('metadatas') and len(sample_results['metadatas']) > 0:
|
| 177 |
+
sample_meta = sample_results['metadatas'][0]
|
| 178 |
+
available_fields = list(sample_meta.keys())
|
| 179 |
+
|
| 180 |
+
# Filter by source file
|
| 181 |
+
if 'source' in available_fields or 'source_file' in available_fields:
|
| 182 |
+
source_field = 'source' if 'source' in available_fields else 'source_file'
|
| 183 |
+
# Get unique sources
|
| 184 |
+
all_results = st.session_state.vectorstore.collection.get()
|
| 185 |
+
unique_sources = set()
|
| 186 |
+
for meta in all_results.get('metadatas', []):
|
| 187 |
+
source = meta.get(source_field) or meta.get('source_file')
|
| 188 |
+
if source:
|
| 189 |
+
unique_sources.add(source)
|
| 190 |
+
|
| 191 |
+
if unique_sources:
|
| 192 |
+
selected_sources = st.multiselect(
|
| 193 |
+
"Filter by Source File",
|
| 194 |
+
options=sorted(unique_sources),
|
| 195 |
+
help="Select one or more source files to search in"
|
| 196 |
+
)
|
| 197 |
+
if selected_sources:
|
| 198 |
+
# Always store as list for consistent handling
|
| 199 |
+
metadata_filters[source_field] = selected_sources if isinstance(selected_sources, list) else [selected_sources]
|
| 200 |
+
|
| 201 |
+
# Filter by page number
|
| 202 |
+
if 'page' in available_fields:
|
| 203 |
+
page_filter = st.text_input(
|
| 204 |
+
"Filter by Page Number (optional)",
|
| 205 |
+
placeholder="e.g., 1, 2, 3 or leave empty",
|
| 206 |
+
help="Enter page numbers separated by commas"
|
| 207 |
+
)
|
| 208 |
+
if page_filter:
|
| 209 |
+
try:
|
| 210 |
+
pages = [int(p.strip()) for p in page_filter.split(',')]
|
| 211 |
+
metadata_filters['page'] = pages if len(pages) > 1 else pages[0]
|
| 212 |
+
except:
|
| 213 |
+
st.warning("Invalid page number format")
|
| 214 |
+
|
| 215 |
+
# Custom metadata filter
|
| 216 |
+
with st.expander("Advanced: Custom Metadata Filter"):
|
| 217 |
+
filter_key = st.text_input("Metadata Key", placeholder="e.g., author, title")
|
| 218 |
+
filter_value = st.text_input("Metadata Value", placeholder="e.g., John Doe")
|
| 219 |
+
if filter_key and filter_value:
|
| 220 |
+
metadata_filters[filter_key] = filter_value
|
| 221 |
+
except Exception as e:
|
| 222 |
+
st.warning(f"Could not load metadata filters: {str(e)}")
|
| 223 |
+
|
| 224 |
+
st.divider()
|
| 225 |
+
|
| 226 |
+
st.subheader("System Status")
|
| 227 |
+
if st.session_state.documents_processed:
|
| 228 |
+
st.success("✅ Documents Processed")
|
| 229 |
+
if st.session_state.chunked_documents:
|
| 230 |
+
st.info(f"📄 {len(st.session_state.chunked_documents)} chunks available")
|
| 231 |
+
if st.session_state.vectorstore:
|
| 232 |
+
try:
|
| 233 |
+
count = st.session_state.vectorstore.collection.count()
|
| 234 |
+
st.info(f"🗄️ {count} documents in vector store")
|
| 235 |
+
except:
|
| 236 |
+
st.warning("⚠️ Could not check vector store count")
|
| 237 |
+
else:
|
| 238 |
+
st.info("⏳ No documents processed")
|
| 239 |
+
|
| 240 |
+
if st.button("🔄 Reset System", type="secondary"):
|
| 241 |
+
st.session_state.vectorstore = None
|
| 242 |
+
st.session_state.retriever = None
|
| 243 |
+
st.session_state.llm = None
|
| 244 |
+
st.session_state.embedding_manager = None
|
| 245 |
+
st.session_state.documents_processed = False
|
| 246 |
+
st.session_state.chunked_documents = None
|
| 247 |
+
st.session_state.chat_history = []
|
| 248 |
+
st.rerun()
|
| 249 |
+
|
| 250 |
+
# Reinitialize retriever if it exists but doesn't have the new method signature
|
| 251 |
+
if st.session_state.retriever and st.session_state.vectorstore and st.session_state.embedding_manager:
|
| 252 |
+
import inspect
|
| 253 |
+
sig = inspect.signature(st.session_state.retriever.retrieve)
|
| 254 |
+
if 'metadata_filters' not in sig.parameters:
|
| 255 |
+
st.session_state.retriever = RagRetriever(
|
| 256 |
+
vector_store=st.session_state.vectorstore,
|
| 257 |
+
embedding_manager=st.session_state.embedding_manager
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
st.divider()
|
| 261 |
+
|
| 262 |
+
if st.button("🗑️ Clear Chat History", type="secondary"):
|
| 263 |
+
st.session_state.chat_history = []
|
| 264 |
+
st.rerun()
|
| 265 |
+
|
| 266 |
+
# Main content area
|
| 267 |
+
tab1, tab2 = st.tabs(["📤 Upload & Process", "💬 Chat"])
|
| 268 |
+
|
| 269 |
+
with tab1:
|
| 270 |
+
st.header("Upload PDF Files")
|
| 271 |
+
st.markdown("Upload one or more PDF files to process and add to the knowledge base.")
|
| 272 |
+
|
| 273 |
+
uploaded_files = st.file_uploader(
|
| 274 |
+
"Choose PDF files",
|
| 275 |
+
type=['pdf'],
|
| 276 |
+
accept_multiple_files=True,
|
| 277 |
+
help="You can upload multiple PDF files at once"
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
if uploaded_files:
|
| 281 |
+
st.info(f"📎 {len(uploaded_files)} file(s) selected")
|
| 282 |
+
|
| 283 |
+
# Display file names
|
| 284 |
+
with st.expander("View uploaded files"):
|
| 285 |
+
for file in uploaded_files:
|
| 286 |
+
st.write(f"- {file.name} ({file.size:,} bytes)")
|
| 287 |
+
|
| 288 |
+
if st.button("🚀 Process Documents", type="primary"):
|
| 289 |
+
success = process_uploaded_pdfs(uploaded_files, chunk_size, chunk_overlap)
|
| 290 |
+
if success:
|
| 291 |
+
st.balloons()
|
| 292 |
+
st.success("✅ Documents processed successfully! You can now chat with them in the Chat tab.")
|
| 293 |
+
else:
|
| 294 |
+
st.error("❌ Failed to process documents. Please check the error messages above.")
|
| 295 |
+
|
| 296 |
+
with tab2:
|
| 297 |
+
st.header("💬 Chat with Documents")
|
| 298 |
+
st.markdown("Ask questions about the uploaded PDF documents. The chat remembers previous conversations.")
|
| 299 |
+
|
| 300 |
+
if not st.session_state.documents_processed:
|
| 301 |
+
st.warning("⚠️ Please upload and process documents first in the 'Upload & Process' tab.")
|
| 302 |
+
else:
|
| 303 |
+
# Display chat history
|
| 304 |
+
chat_container = st.container()
|
| 305 |
+
with chat_container:
|
| 306 |
+
if st.session_state.chat_history:
|
| 307 |
+
for message in st.session_state.chat_history:
|
| 308 |
+
role = message.get("role", "user")
|
| 309 |
+
content = message.get("content", "")
|
| 310 |
+
|
| 311 |
+
if role == "user":
|
| 312 |
+
with st.chat_message("user"):
|
| 313 |
+
st.write(content)
|
| 314 |
+
elif role == "assistant":
|
| 315 |
+
with st.chat_message("assistant"):
|
| 316 |
+
st.write(content)
|
| 317 |
+
# Show sources if available
|
| 318 |
+
if "sources" in message:
|
| 319 |
+
with st.expander("📄 Sources"):
|
| 320 |
+
for i, source in enumerate(message["sources"], 1):
|
| 321 |
+
st.markdown(f"**Source {i}** (Score: {source.get('score', 0):.4f})")
|
| 322 |
+
st.caption(f"Preview: {source.get('preview', '')[:200]}...")
|
| 323 |
+
else:
|
| 324 |
+
st.info("👋 Start a conversation by asking a question below!")
|
| 325 |
+
|
| 326 |
+
# Chat input
|
| 327 |
+
query = st.chat_input(
|
| 328 |
+
"Ask a question about the documents...",
|
| 329 |
+
key="chat_input"
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
# Handle query
|
| 333 |
+
if query:
|
| 334 |
+
if st.session_state.retriever and st.session_state.llm:
|
| 335 |
+
# Add user message to chat history
|
| 336 |
+
st.session_state.chat_history.append({
|
| 337 |
+
"role": "user",
|
| 338 |
+
"content": query
|
| 339 |
+
})
|
| 340 |
+
|
| 341 |
+
with st.spinner("Thinking..."):
|
| 342 |
+
try:
|
| 343 |
+
# First, retrieve documents to check if we have results
|
| 344 |
+
# Use score_threshold=0 to get all results, even with low similarity scores
|
| 345 |
+
# Handle both old and new method signatures
|
| 346 |
+
try:
|
| 347 |
+
results = st.session_state.retriever.retrieve(
|
| 348 |
+
query=query,
|
| 349 |
+
top_k=top_k,
|
| 350 |
+
score_threshold=0, # Get all results, even with low scores
|
| 351 |
+
metadata_filters=metadata_filters if use_filters else None
|
| 352 |
+
)
|
| 353 |
+
except TypeError:
|
| 354 |
+
# Fallback for old method signature (without metadata_filters)
|
| 355 |
+
results = st.session_state.retriever.retrieve(
|
| 356 |
+
query=query,
|
| 357 |
+
top_k=top_k,
|
| 358 |
+
score_threshold=0
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
# Debug: Show retrieval info
|
| 362 |
+
if not results:
|
| 363 |
+
st.warning(f"⚠️ No documents retrieved. Vector store has {st.session_state.vectorstore.collection.count()} documents.")
|
| 364 |
+
|
| 365 |
+
# Prepare sources for display
|
| 366 |
+
sources = [{
|
| 367 |
+
"score": r.get("score", 0),
|
| 368 |
+
"preview": r.get("document", "")[:300] + "..."
|
| 369 |
+
} for r in results] if results else []
|
| 370 |
+
|
| 371 |
+
# Get answer using RAG pipeline with memory
|
| 372 |
+
answer = rag_pipeline_with_memory(
|
| 373 |
+
query=query,
|
| 374 |
+
retriever=st.session_state.retriever,
|
| 375 |
+
llm=st.session_state.llm,
|
| 376 |
+
conversation_history=st.session_state.chat_history[:-1], # Exclude current query
|
| 377 |
+
top_k=top_k,
|
| 378 |
+
metadata_filters=metadata_filters if use_filters else None
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
# Create concise summary for memory (store full answer in message, summary in history)
|
| 382 |
+
concise_answer = summarize_answer(answer, st.session_state.llm, max_length=150)
|
| 383 |
+
|
| 384 |
+
# Add assistant response to chat history
|
| 385 |
+
# Store full answer for display, but concise version for memory
|
| 386 |
+
st.session_state.chat_history.append({
|
| 387 |
+
"role": "assistant",
|
| 388 |
+
"content": answer, # Full answer for display
|
| 389 |
+
"concise": concise_answer, # Concise version for memory
|
| 390 |
+
"sources": sources
|
| 391 |
+
})
|
| 392 |
+
|
| 393 |
+
st.rerun()
|
| 394 |
+
|
| 395 |
+
except Exception as e:
|
| 396 |
+
st.error(f"Error processing query: {str(e)}")
|
| 397 |
+
st.exception(e)
|
| 398 |
+
# Remove the user message if there was an error
|
| 399 |
+
if st.session_state.chat_history and st.session_state.chat_history[-1]["role"] == "user":
|
| 400 |
+
st.session_state.chat_history.pop()
|
| 401 |
+
else:
|
| 402 |
+
st.error("System not properly initialized. Please process documents first.")
|
| 403 |
+
|
| 404 |
+
# Example queries
|
| 405 |
+
if not st.session_state.chat_history:
|
| 406 |
+
st.divider()
|
| 407 |
+
st.subheader("💡 Example Queries")
|
| 408 |
+
example_queries = [
|
| 409 |
+
"What is the main topic of the document?",
|
| 410 |
+
"Summarize the key points",
|
| 411 |
+
"What are the main findings?",
|
| 412 |
+
]
|
| 413 |
+
|
| 414 |
+
cols = st.columns(len(example_queries))
|
| 415 |
+
for i, example in enumerate(example_queries):
|
| 416 |
+
with cols[i]:
|
| 417 |
+
if st.button(f"📝 {example[:30]}...", key=f"example_{i}"):
|
| 418 |
+
# Simulate chat input
|
| 419 |
+
st.session_state.chat_history.append({
|
| 420 |
+
"role": "user",
|
| 421 |
+
"content": example
|
| 422 |
+
})
|
| 423 |
+
st.rerun()
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
if __name__ == "__main__":
|
| 427 |
+
main()
|
| 428 |
+
|
experimental_files/example_client.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Simple example client for the RAG Pipeline API
|
| 4 |
+
Shows how to upload documents and query them
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import requests
|
| 8 |
+
import json
|
| 9 |
+
import sys
|
| 10 |
+
|
| 11 |
+
API_URL = "http://localhost:8000"
|
| 12 |
+
|
| 13 |
+
def check_status():
|
| 14 |
+
"""Check if the API is running and system status."""
|
| 15 |
+
try:
|
| 16 |
+
response = requests.get(f"{API_URL}/status")
|
| 17 |
+
status = response.json()
|
| 18 |
+
print("📊 System Status:")
|
| 19 |
+
print(f" Documents Processed: {status['documents_processed']}")
|
| 20 |
+
print(f" Vector Store Count: {status['vector_store_count']}")
|
| 21 |
+
print(f" Embedding Model: {status.get('embedding_model', 'Not loaded')}")
|
| 22 |
+
return status
|
| 23 |
+
except requests.exceptions.ConnectionError:
|
| 24 |
+
print("❌ Error: Cannot connect to API. Is the server running?")
|
| 25 |
+
print(" Start it with: uvicorn api:app --reload")
|
| 26 |
+
sys.exit(1)
|
| 27 |
+
|
| 28 |
+
def upload_documents(pdf_paths, chunk_size=800, chunk_overlap=200):
|
| 29 |
+
"""Upload and process PDF documents."""
|
| 30 |
+
print(f"\n📤 Uploading {len(pdf_paths)} document(s)...")
|
| 31 |
+
|
| 32 |
+
files = []
|
| 33 |
+
for pdf_path in pdf_paths:
|
| 34 |
+
try:
|
| 35 |
+
files.append(('files', (open(pdf_path, 'rb'))))
|
| 36 |
+
except FileNotFoundError:
|
| 37 |
+
print(f"❌ Error: File not found: {pdf_path}")
|
| 38 |
+
return None
|
| 39 |
+
|
| 40 |
+
data = {
|
| 41 |
+
'chunk_size': chunk_size,
|
| 42 |
+
'chunk_overlap': chunk_overlap
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
try:
|
| 46 |
+
response = requests.post(f"{API_URL}/upload", files=files, data=data)
|
| 47 |
+
|
| 48 |
+
# Close file handles
|
| 49 |
+
for _, file_tuple in files:
|
| 50 |
+
file_tuple[1].close()
|
| 51 |
+
|
| 52 |
+
if response.status_code == 200:
|
| 53 |
+
result = response.json()
|
| 54 |
+
print(f"✅ Success!")
|
| 55 |
+
print(f" Documents Loaded: {result['documents_loaded']}")
|
| 56 |
+
print(f" Chunks Created: {result['chunks_created']}")
|
| 57 |
+
print(f" Vector Store Count: {result['vector_store_count']}")
|
| 58 |
+
return result
|
| 59 |
+
else:
|
| 60 |
+
print(f"❌ Error: {response.status_code}")
|
| 61 |
+
print(response.json())
|
| 62 |
+
return None
|
| 63 |
+
except Exception as e:
|
| 64 |
+
print(f"❌ Error uploading: {str(e)}")
|
| 65 |
+
return None
|
| 66 |
+
|
| 67 |
+
def query(query_text, session_id=None, top_k=5, use_memory=True, metadata_filters=None):
|
| 68 |
+
"""Query the RAG system."""
|
| 69 |
+
print(f"\n❓ Query: {query_text}")
|
| 70 |
+
|
| 71 |
+
payload = {
|
| 72 |
+
"query": query_text,
|
| 73 |
+
"top_k": top_k,
|
| 74 |
+
"use_memory": use_memory
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
if session_id:
|
| 78 |
+
payload["session_id"] = session_id
|
| 79 |
+
|
| 80 |
+
if metadata_filters:
|
| 81 |
+
payload["metadata_filters"] = metadata_filters
|
| 82 |
+
|
| 83 |
+
try:
|
| 84 |
+
response = requests.post(f"{API_URL}/query", json=payload)
|
| 85 |
+
|
| 86 |
+
if response.status_code == 200:
|
| 87 |
+
result = response.json()
|
| 88 |
+
print(f"\n💡 Answer:")
|
| 89 |
+
print(f" {result['answer']}")
|
| 90 |
+
print(f"\n📄 Sources ({len(result['sources'])}):")
|
| 91 |
+
for i, source in enumerate(result['sources'][:3], 1):
|
| 92 |
+
print(f" {i}. Score: {source['score']:.4f}")
|
| 93 |
+
print(f" Preview: {source['preview'][:100]}...")
|
| 94 |
+
print(f"\n🆔 Session ID: {result['session_id']}")
|
| 95 |
+
return result
|
| 96 |
+
else:
|
| 97 |
+
print(f"❌ Error: {response.status_code}")
|
| 98 |
+
print(response.json())
|
| 99 |
+
return None
|
| 100 |
+
except Exception as e:
|
| 101 |
+
print(f"❌ Error querying: {str(e)}")
|
| 102 |
+
return None
|
| 103 |
+
|
| 104 |
+
def get_chat_history(session_id):
|
| 105 |
+
"""Get chat history for a session."""
|
| 106 |
+
try:
|
| 107 |
+
response = requests.get(f"{API_URL}/chat-history/{session_id}")
|
| 108 |
+
if response.status_code == 200:
|
| 109 |
+
return response.json()
|
| 110 |
+
else:
|
| 111 |
+
print(f"❌ Error: {response.status_code}")
|
| 112 |
+
return None
|
| 113 |
+
except Exception as e:
|
| 114 |
+
print(f"❌ Error: {str(e)}")
|
| 115 |
+
return None
|
| 116 |
+
|
| 117 |
+
if __name__ == "__main__":
|
| 118 |
+
print("🚀 RAG Pipeline API Client\n")
|
| 119 |
+
|
| 120 |
+
# Check status
|
| 121 |
+
status = check_status()
|
| 122 |
+
|
| 123 |
+
# If no documents processed, upload some
|
| 124 |
+
if not status['documents_processed']:
|
| 125 |
+
print("\n⚠️ No documents processed. Uploading documents...")
|
| 126 |
+
pdf_paths = ["data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf"]
|
| 127 |
+
upload_result = upload_documents(pdf_paths)
|
| 128 |
+
if not upload_result:
|
| 129 |
+
print("❌ Failed to upload documents. Exiting.")
|
| 130 |
+
sys.exit(1)
|
| 131 |
+
|
| 132 |
+
# Example queries
|
| 133 |
+
session_id = "example-session"
|
| 134 |
+
|
| 135 |
+
print("\n" + "="*60)
|
| 136 |
+
print("Example Queries")
|
| 137 |
+
print("="*60)
|
| 138 |
+
|
| 139 |
+
# Query 1
|
| 140 |
+
result1 = query("What is attention mechanism?", session_id=session_id)
|
| 141 |
+
|
| 142 |
+
# Query 2 (with memory)
|
| 143 |
+
result2 = query("Who are the authors?", session_id=session_id)
|
| 144 |
+
|
| 145 |
+
# Query 3 (follow-up using memory)
|
| 146 |
+
result3 = query("Tell me more about it", session_id=session_id)
|
| 147 |
+
|
| 148 |
+
# Show chat history
|
| 149 |
+
print("\n" + "="*60)
|
| 150 |
+
print("Chat History")
|
| 151 |
+
print("="*60)
|
| 152 |
+
history = get_chat_history(session_id)
|
| 153 |
+
if history:
|
| 154 |
+
print(f"Total messages: {history['message_count']}")
|
| 155 |
+
for i, msg in enumerate(history['history'], 1):
|
| 156 |
+
role = msg.get('role', 'unknown')
|
| 157 |
+
content = msg.get('content', '')[:100]
|
| 158 |
+
print(f"{i}. [{role}]: {content}...")
|
| 159 |
+
|
experimental_files/main.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def main():
|
| 2 |
+
print("Hello from rag-pipeline!")
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
if __name__ == "__main__":
|
| 6 |
+
main()
|
launch.sh
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
# Colors for output
|
| 4 |
+
GREEN='\033[0;32m'
|
| 5 |
+
RED='\033[0;31m'
|
| 6 |
+
YELLOW='\033[1;33m'
|
| 7 |
+
NC='\033[0m' # No Color
|
| 8 |
+
|
| 9 |
+
# Cleanup function
|
| 10 |
+
cleanup() {
|
| 11 |
+
if [ ! -z "$API_PID" ]; then
|
| 12 |
+
echo -e "\n${YELLOW}Shutting down FastAPI server (PID: $API_PID)...${NC}"
|
| 13 |
+
kill $API_PID 2>/dev/null
|
| 14 |
+
wait $API_PID 2>/dev/null
|
| 15 |
+
fi
|
| 16 |
+
echo -e "${GREEN}✅ Cleanup complete${NC}"
|
| 17 |
+
exit 0
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
# Set trap to cleanup on script exit
|
| 21 |
+
trap cleanup SIGINT SIGTERM EXIT
|
| 22 |
+
|
| 23 |
+
echo "🚀 RAG Pipeline Launcher"
|
| 24 |
+
echo "========================"
|
| 25 |
+
|
| 26 |
+
# Step 1: Check if Python exists
|
| 27 |
+
echo -e "\n${YELLOW}Step 1: Checking Python installation...${NC}"
|
| 28 |
+
if ! command -v python3 &> /dev/null && ! command -v python &> /dev/null; then
|
| 29 |
+
echo -e "${RED}❌ Python not found. Please install Python first.${NC}"
|
| 30 |
+
exit 1
|
| 31 |
+
fi
|
| 32 |
+
|
| 33 |
+
# Determine Python command
|
| 34 |
+
if command -v python3 &> /dev/null; then
|
| 35 |
+
PYTHON_CMD="python3"
|
| 36 |
+
else
|
| 37 |
+
PYTHON_CMD="python"
|
| 38 |
+
fi
|
| 39 |
+
|
| 40 |
+
PYTHON_VERSION=$($PYTHON_CMD --version 2>&1)
|
| 41 |
+
echo -e "${GREEN}✅ Found: $PYTHON_VERSION${NC}"
|
| 42 |
+
|
| 43 |
+
# Step 2: Check if requirements.txt exists
|
| 44 |
+
if [ ! -f "requirements.txt" ]; then
|
| 45 |
+
echo -e "${RED}❌ requirements.txt not found!${NC}"
|
| 46 |
+
exit 1
|
| 47 |
+
fi
|
| 48 |
+
|
| 49 |
+
# Step 3: Check if pip exists
|
| 50 |
+
echo -e "\n${YELLOW}Step 2: Checking pip installation...${NC}"
|
| 51 |
+
if ! $PYTHON_CMD -m pip --version &> /dev/null; then
|
| 52 |
+
echo -e "${RED}❌ pip not found. Installing pip...${NC}"
|
| 53 |
+
$PYTHON_CMD -m ensurepip --upgrade
|
| 54 |
+
fi
|
| 55 |
+
|
| 56 |
+
# Step 4: Install requirements
|
| 57 |
+
echo -e "\n${YELLOW}Step 3: Installing/updating dependencies from requirements.txt...${NC}"
|
| 58 |
+
$PYTHON_CMD -m pip install -q -r requirements.txt
|
| 59 |
+
if [ $? -ne 0 ]; then
|
| 60 |
+
echo -e "${RED}❌ Failed to install requirements${NC}"
|
| 61 |
+
exit 1
|
| 62 |
+
fi
|
| 63 |
+
echo -e "${GREEN}✅ Dependencies installed${NC}"
|
| 64 |
+
|
| 65 |
+
# Step 5: Check if key libraries are installed
|
| 66 |
+
echo -e "\n${YELLOW}Step 4: Verifying key libraries...${NC}"
|
| 67 |
+
$PYTHON_CMD -c "import streamlit, fastapi, uvicorn, langchain" 2>/dev/null
|
| 68 |
+
if [ $? -ne 0 ]; then
|
| 69 |
+
echo -e "${RED}❌ Key libraries not found. Please check your installation.${NC}"
|
| 70 |
+
exit 1
|
| 71 |
+
fi
|
| 72 |
+
echo -e "${GREEN}✅ Key libraries found${NC}"
|
| 73 |
+
|
| 74 |
+
# Step 6: Find API file
|
| 75 |
+
echo -e "\n${YELLOW}Step 5: Locating API file...${NC}"
|
| 76 |
+
if [ -f "api.py" ]; then
|
| 77 |
+
API_FILE="api.py"
|
| 78 |
+
elif [ -f "experimental_files/api.py" ]; then
|
| 79 |
+
API_FILE="experimental_files/api.py"
|
| 80 |
+
else
|
| 81 |
+
echo -e "${RED}❌ api.py not found in root or experimental_files directory${NC}"
|
| 82 |
+
exit 1
|
| 83 |
+
fi
|
| 84 |
+
echo -e "${GREEN}✅ Found API file: $API_FILE${NC}"
|
| 85 |
+
|
| 86 |
+
# Step 7: Start FastAPI server in background
|
| 87 |
+
echo -e "\n${YELLOW}Step 6: Starting FastAPI server...${NC}"
|
| 88 |
+
API_PID=""
|
| 89 |
+
if [ "$API_FILE" == "api.py" ]; then
|
| 90 |
+
uvicorn api:app --host 0.0.0.0 --port 8000 > /dev/null 2>&1 &
|
| 91 |
+
API_PID=$!
|
| 92 |
+
else
|
| 93 |
+
# If api.py is in experimental_files, add to PYTHONPATH and run from there
|
| 94 |
+
export PYTHONPATH="${PWD}/experimental_files:${PYTHONPATH}"
|
| 95 |
+
cd experimental_files
|
| 96 |
+
uvicorn api:app --host 0.0.0.0 --port 8000 > /dev/null 2>&1 &
|
| 97 |
+
API_PID=$!
|
| 98 |
+
cd - > /dev/null
|
| 99 |
+
fi
|
| 100 |
+
echo -e "${GREEN}✅ FastAPI server started (PID: $API_PID)${NC}"
|
| 101 |
+
|
| 102 |
+
# Step 8: Check if curl is available for health check
|
| 103 |
+
if ! command -v curl &> /dev/null; then
|
| 104 |
+
echo -e "${YELLOW}⚠️ curl not found. Skipping health check.${NC}"
|
| 105 |
+
echo -e "${YELLOW} Please verify the API is running manually at http://localhost:8000${NC}"
|
| 106 |
+
HEALTH_CHECK_PASSED=true
|
| 107 |
+
else
|
| 108 |
+
# Wait for server to be ready and check health
|
| 109 |
+
echo -e "\n${YELLOW}Step 7: Checking API health status...${NC}"
|
| 110 |
+
MAX_RETRIES=30
|
| 111 |
+
RETRY_COUNT=0
|
| 112 |
+
HEALTH_CHECK_PASSED=false
|
| 113 |
+
|
| 114 |
+
while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
|
| 115 |
+
sleep 1
|
| 116 |
+
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:8000/ 2>/dev/null || echo "000")
|
| 117 |
+
|
| 118 |
+
if [ "$HTTP_CODE" == "200" ]; then
|
| 119 |
+
HEALTH_CHECK_PASSED=true
|
| 120 |
+
break
|
| 121 |
+
fi
|
| 122 |
+
|
| 123 |
+
RETRY_COUNT=$((RETRY_COUNT + 1))
|
| 124 |
+
echo -n "."
|
| 125 |
+
done
|
| 126 |
+
|
| 127 |
+
echo ""
|
| 128 |
+
|
| 129 |
+
if [ "$HEALTH_CHECK_PASSED" = true ]; then
|
| 130 |
+
echo -e "${GREEN}✅ API health check passed!${NC}"
|
| 131 |
+
echo -e "${GREEN} API is running at http://localhost:8000${NC}"
|
| 132 |
+
else
|
| 133 |
+
echo -e "${RED}❌ API health check failed after $MAX_RETRIES seconds${NC}"
|
| 134 |
+
echo -e "${YELLOW} Attempting to kill background process...${NC}"
|
| 135 |
+
kill $API_PID 2>/dev/null
|
| 136 |
+
exit 1
|
| 137 |
+
fi
|
| 138 |
+
fi
|
| 139 |
+
|
| 140 |
+
# Step 9: Launch Streamlit frontend
|
| 141 |
+
echo -e "\n${YELLOW}Step 8: Launching Streamlit frontend...${NC}"
|
| 142 |
+
echo -e "${GREEN}✅ Starting Streamlit app (app_api.py)${NC}"
|
| 143 |
+
echo -e "${GREEN} Frontend will be available at http://localhost:8501${NC}"
|
| 144 |
+
echo -e "\n${YELLOW}Press Ctrl+C to stop both servers${NC}\n"
|
| 145 |
+
|
| 146 |
+
# Launch Streamlit (this will block)
|
| 147 |
+
# When Streamlit exits, the trap will handle cleanup
|
| 148 |
+
streamlit run app_api.py
|
| 149 |
+
|
notebook/.DS_Store
ADDED
|
Binary file (6.15 kB). View file
|
|
|
notebook/1-langchain-document-components.svg
ADDED
|
|
notebook/data/.DS_Store
ADDED
|
Binary file (6.15 kB). View file
|
|
|
notebook/document.ipynb
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "markdown",
|
| 5 |
+
"id": "a909867a",
|
| 6 |
+
"metadata": {},
|
| 7 |
+
"source": [
|
| 8 |
+
"## Data Ingestion\n",
|
| 9 |
+
"Main steps (high level)\n",
|
| 10 |
+
"1. Load data — read files and extract plain text\n",
|
| 11 |
+
"2. Chunking — split text into fixed-size overlapping windows\n",
|
| 12 |
+
"3. Embeddings — generate vector representations for each chunk\n",
|
| 13 |
+
"4. Store in vector db — upsert vectors and metadata into the chosen vector DB\n"
|
| 14 |
+
]
|
| 15 |
+
},
|
| 16 |
+
{
|
| 17 |
+
"cell_type": "code",
|
| 18 |
+
"execution_count": 2,
|
| 19 |
+
"id": "6a7c9d8e",
|
| 20 |
+
"metadata": {},
|
| 21 |
+
"outputs": [],
|
| 22 |
+
"source": [
|
| 23 |
+
"from langchain_core.documents import Document\n",
|
| 24 |
+
"from langchain_community.document_loaders import DirectoryLoader\n"
|
| 25 |
+
]
|
| 26 |
+
},
|
| 27 |
+
{
|
| 28 |
+
"cell_type": "code",
|
| 29 |
+
"execution_count": 7,
|
| 30 |
+
"id": "077c16a3",
|
| 31 |
+
"metadata": {},
|
| 32 |
+
"outputs": [
|
| 33 |
+
{
|
| 34 |
+
"name": "stderr",
|
| 35 |
+
"output_type": "stream",
|
| 36 |
+
"text": [
|
| 37 |
+
"100%|██████████| 2/2 [00:02<00:00, 1.02s/it]\n"
|
| 38 |
+
]
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"data": {
|
| 42 |
+
"text/plain": [
|
| 43 |
+
"[Document(metadata={'producer': 'PyPDF2', 'creator': '', 'creationdate': '', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_path': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'format': 'PDF 1.3', 'title': 'Attention is All you Need', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'keywords': '', 'moddate': '2018-02-12T21:22:10-08:00', 'trapped': '', 'modDate': \"D:20180212212210-08'00'\", 'creationDate': '', 'page': 0}, page_content='Attention Is All You Need\\nAshish Vaswani∗\\nGoogle Brain\\navaswani@google.com\\nNoam Shazeer∗\\nGoogle Brain\\nnoam@google.com\\nNiki Parmar∗\\nGoogle Research\\nnikip@google.com\\nJakob Uszkoreit∗\\nGoogle Research\\nusz@google.com\\nLlion Jones∗\\nGoogle Research\\nllion@google.com\\nAidan N. Gomez∗†\\nUniversity of Toronto\\naidan@cs.toronto.edu\\nŁukasz Kaiser∗\\nGoogle Brain\\nlukaszkaiser@google.com\\nIllia Polosukhin∗‡\\nillia.polosukhin@gmail.com\\nAbstract\\nThe dominant sequence transduction models are based on complex recurrent or\\nconvolutional neural networks that include an encoder and a decoder. The best\\nperforming models also connect the encoder and decoder through an attention\\nmechanism. We propose a new simple network architecture, the Transformer,\\nbased solely on attention mechanisms, dispensing with recurrence and convolutions\\nentirely. Experiments on two machine translation tasks show these models to\\nbe superior in quality while being more parallelizable and requiring significantly\\nless time to train. Our model achieves 28.4 BLEU on the WMT 2014 English-\\nto-German translation task, improving over the existing best results, including\\nensembles, by over 2 BLEU. On the WMT 2014 English-to-French translation task,\\nour model establishes a new single-model state-of-the-art BLEU score of 41.0 after\\ntraining for 3.5 days on eight GPUs, a small fraction of the training costs of the\\nbest models from the literature.\\n1\\nIntroduction\\nRecurrent neural networks, long short-term memory [12] and gated recurrent [7] neural networks\\nin particular, have been firmly established as state of the art approaches in sequence modeling and\\ntransduction problems such as language modeling and machine translation [29, 2, 5]. Numerous\\nefforts have since continued to push the boundaries of recurrent language models and encoder-decoder\\narchitectures [31, 21, 13].\\n∗Equal contribution. Listing order is random. Jakob proposed replacing RNNs with self-attention and started\\nthe effort to evaluate this idea. Ashish, with Illia, designed and implemented the first Transformer models and\\nhas been crucially involved in every aspect of this work. Noam proposed scaled dot-product attention, multi-head\\nattention and the parameter-free position representation and became the other person involved in nearly every\\ndetail. Niki designed, implemented, tuned and evaluated countless model variants in our original codebase and\\ntensor2tensor. Llion also experimented with novel model variants, was responsible for our initial codebase, and\\nefficient inference and visualizations. Lukasz and Aidan spent countless long days designing various parts of and\\nimplementing tensor2tensor, replacing our earlier codebase, greatly improving results and massively accelerating\\nour research.\\n†Work performed while at Google Brain.\\n‡Work performed while at Google Research.\\n31st Conference on Neural Information Processing Systems (NIPS 2017), Long Beach, CA, USA.'),\n",
|
| 44 |
+
" Document(metadata={'producer': 'PyPDF2', 'creator': '', 'creationdate': '', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_path': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'format': 'PDF 1.3', 'title': 'Attention is All you Need', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'keywords': '', 'moddate': '2018-02-12T21:22:10-08:00', 'trapped': '', 'modDate': \"D:20180212212210-08'00'\", 'creationDate': '', 'page': 1}, page_content='Recurrent models typically factor computation along the symbol positions of the input and output\\nsequences. Aligning the positions to steps in computation time, they generate a sequence of hidden\\nstates ht, as a function of the previous hidden state ht−1 and the input for position t. This inherently\\nsequential nature precludes parallelization within training examples, which becomes critical at longer\\nsequence lengths, as memory constraints limit batching across examples. Recent work has achieved\\nsignificant improvements in computational efficiency through factorization tricks [18] and conditional\\ncomputation [26], while also improving model performance in case of the latter. The fundamental\\nconstraint of sequential computation, however, remains.\\nAttention mechanisms have become an integral part of compelling sequence modeling and transduc-\\ntion models in various tasks, allowing modeling of dependencies without regard to their distance in\\nthe input or output sequences [2, 16]. In all but a few cases [22], however, such attention mechanisms\\nare used in conjunction with a recurrent network.\\nIn this work we propose the Transformer, a model architecture eschewing recurrence and instead\\nrelying entirely on an attention mechanism to draw global dependencies between input and output.\\nThe Transformer allows for significantly more parallelization and can reach a new state of the art in\\ntranslation quality after being trained for as little as twelve hours on eight P100 GPUs.\\n2\\nBackground\\nThe goal of reducing sequential computation also forms the foundation of the Extended Neural GPU\\n[20], ByteNet [15] and ConvS2S [8], all of which use convolutional neural networks as basic building\\nblock, computing hidden representations in parallel for all input and output positions. In these models,\\nthe number of operations required to relate signals from two arbitrary input or output positions grows\\nin the distance between positions, linearly for ConvS2S and logarithmically for ByteNet. This makes\\nit more difficult to learn dependencies between distant positions [11]. In the Transformer this is\\nreduced to a constant number of operations, albeit at the cost of reduced effective resolution due\\nto averaging attention-weighted positions, an effect we counteract with Multi-Head Attention as\\ndescribed in section 3.2.\\nSelf-attention, sometimes called intra-attention is an attention mechanism relating different positions\\nof a single sequence in order to compute a representation of the sequence. Self-attention has been\\nused successfully in a variety of tasks including reading comprehension, abstractive summarization,\\ntextual entailment and learning task-independent sentence representations [4, 22, 23, 19].\\nEnd-to-end memory networks are based on a recurrent attention mechanism instead of sequence-\\naligned recurrence and have been shown to perform well on simple-language question answering and\\nlanguage modeling tasks [28].\\nTo the best of our knowledge, however, the Transformer is the first transduction model relying\\nentirely on self-attention to compute representations of its input and output without using sequence-\\naligned RNNs or convolution. In the following sections, we will describe the Transformer, motivate\\nself-attention and discuss its advantages over models such as [14, 15] and [8].\\n3\\nModel Architecture\\nMost competitive neural sequence transduction models have an encoder-decoder structure [5, 2, 29].\\nHere, the encoder maps an input sequence of symbol representations (x1, ..., xn) to a sequence\\nof continuous representations z = (z1, ..., zn). Given z, the decoder then generates an output\\nsequence (y1, ..., ym) of symbols one element at a time. At each step the model is auto-regressive\\n[9], consuming the previously generated symbols as additional input when generating the next.\\nThe Transformer follows this overall architecture using stacked self-attention and point-wise, fully\\nconnected layers for both the encoder and decoder, shown in the left and right halves of Figure 1,\\nrespectively.\\n3.1\\nEncoder and Decoder Stacks\\nEncoder:\\nThe encoder is composed of a stack of N = 6 identical layers. Each layer has two\\nsub-layers. The first is a multi-head self-attention mechanism, and the second is a simple, position-\\n2'),\n",
|
| 45 |
+
" Document(metadata={'producer': 'PyPDF2', 'creator': '', 'creationdate': '', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_path': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'format': 'PDF 1.3', 'title': 'Attention is All you Need', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'keywords': '', 'moddate': '2018-02-12T21:22:10-08:00', 'trapped': '', 'modDate': \"D:20180212212210-08'00'\", 'creationDate': '', 'page': 2}, page_content='Figure 1: The Transformer - model architecture.\\nwise fully connected feed-forward network. We employ a residual connection [10] around each of\\nthe two sub-layers, followed by layer normalization [1]. That is, the output of each sub-layer is\\nLayerNorm(x + Sublayer(x)), where Sublayer(x) is the function implemented by the sub-layer\\nitself. To facilitate these residual connections, all sub-layers in the model, as well as the embedding\\nlayers, produce outputs of dimension dmodel = 512.\\nDecoder:\\nThe decoder is also composed of a stack of N = 6 identical layers. In addition to the two\\nsub-layers in each encoder layer, the decoder inserts a third sub-layer, which performs multi-head\\nattention over the output of the encoder stack. Similar to the encoder, we employ residual connections\\naround each of the sub-layers, followed by layer normalization. We also modify the self-attention\\nsub-layer in the decoder stack to prevent positions from attending to subsequent positions. This\\nmasking, combined with fact that the output embeddings are offset by one position, ensures that the\\npredictions for position i can depend only on the known outputs at positions less than i.\\n3.2\\nAttention\\nAn attention function can be described as mapping a query and a set of key-value pairs to an output,\\nwhere the query, keys, values, and output are all vectors. The output is computed as a weighted sum\\nof the values, where the weight assigned to each value is computed by a compatibility function of the\\nquery with the corresponding key.\\n3.2.1\\nScaled Dot-Product Attention\\nWe call our particular attention \"Scaled Dot-Product Attention\" (Figure 2). The input consists of\\nqueries and keys of dimension dk, and values of dimension dv. We compute the dot products of the\\n3'),\n",
|
| 46 |
+
" Document(metadata={'producer': 'PyPDF2', 'creator': '', 'creationdate': '', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_path': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'format': 'PDF 1.3', 'title': 'Attention is All you Need', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'keywords': '', 'moddate': '2018-02-12T21:22:10-08:00', 'trapped': '', 'modDate': \"D:20180212212210-08'00'\", 'creationDate': '', 'page': 3}, page_content='Scaled Dot-Product Attention\\nMulti-Head Attention\\nFigure 2: (left) Scaled Dot-Product Attention. (right) Multi-Head Attention consists of several\\nattention layers running in parallel.\\nquery with all keys, divide each by √dk, and apply a softmax function to obtain the weights on the\\nvalues.\\nIn practice, we compute the attention function on a set of queries simultaneously, packed together\\ninto a matrix Q. The keys and values are also packed together into matrices K and V . We compute\\nthe matrix of outputs as:\\nAttention(Q, K, V ) = softmax(QKT\\n√dk\\n)V\\n(1)\\nThe two most commonly used attention functions are additive attention [2], and dot-product (multi-\\nplicative) attention. Dot-product attention is identical to our algorithm, except for the scaling factor\\nof\\n1\\n√dk . Additive attention computes the compatibility function using a feed-forward network with\\na single hidden layer. While the two are similar in theoretical complexity, dot-product attention is\\nmuch faster and more space-efficient in practice, since it can be implemented using highly optimized\\nmatrix multiplication code.\\nWhile for small values of dk the two mechanisms perform similarly, additive attention outperforms\\ndot product attention without scaling for larger values of dk [3]. We suspect that for large values of\\ndk, the dot products grow large in magnitude, pushing the softmax function into regions where it has\\nextremely small gradients 4. To counteract this effect, we scale the dot products by\\n1\\n√dk .\\n3.2.2\\nMulti-Head Attention\\nInstead of performing a single attention function with dmodel-dimensional keys, values and queries,\\nwe found it beneficial to linearly project the queries, keys and values h times with different, learned\\nlinear projections to dk, dk and dv dimensions, respectively. On each of these projected versions of\\nqueries, keys and values we then perform the attention function in parallel, yielding dv-dimensional\\noutput values. These are concatenated and once again projected, resulting in the final values, as\\ndepicted in Figure 2.\\nMulti-head attention allows the model to jointly attend to information from different representation\\nsubspaces at different positions. With a single attention head, averaging inhibits this.\\n4To illustrate why the dot products get large, assume that the components of q and k are independent random\\nvariables with mean 0 and variance 1. Then their dot product, q · k = Pdk\\ni=1 qiki, has mean 0 and variance dk.\\n4'),\n",
|
| 47 |
+
" Document(metadata={'producer': 'PyPDF2', 'creator': '', 'creationdate': '', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_path': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'format': 'PDF 1.3', 'title': 'Attention is All you Need', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'keywords': '', 'moddate': '2018-02-12T21:22:10-08:00', 'trapped': '', 'modDate': \"D:20180212212210-08'00'\", 'creationDate': '', 'page': 4}, page_content='MultiHead(Q, K, V ) = Concat(head1, ..., headh)W O\\nwhere headi = Attention(QW Q\\ni , KW K\\ni , V W V\\ni )\\nWhere the projections are parameter matrices W Q\\ni\\n∈Rdmodel×dk, W K\\ni\\n∈Rdmodel×dk, W V\\ni\\n∈Rdmodel×dv\\nand W O ∈Rhdv×dmodel.\\nIn this work we employ h = 8 parallel attention layers, or heads. For each of these we use\\ndk = dv = dmodel/h = 64. Due to the reduced dimension of each head, the total computational cost\\nis similar to that of single-head attention with full dimensionality.\\n3.2.3\\nApplications of Attention in our Model\\nThe Transformer uses multi-head attention in three different ways:\\n• In \"encoder-decoder attention\" layers, the queries come from the previous decoder layer,\\nand the memory keys and values come from the output of the encoder. This allows every\\nposition in the decoder to attend over all positions in the input sequence. This mimics the\\ntypical encoder-decoder attention mechanisms in sequence-to-sequence models such as\\n[31, 2, 8].\\n• The encoder contains self-attention layers. In a self-attention layer all of the keys, values\\nand queries come from the same place, in this case, the output of the previous layer in the\\nencoder. Each position in the encoder can attend to all positions in the previous layer of the\\nencoder.\\n• Similarly, self-attention layers in the decoder allow each position in the decoder to attend to\\nall positions in the decoder up to and including that position. We need to prevent leftward\\ninformation flow in the decoder to preserve the auto-regressive property. We implement this\\ninside of scaled dot-product attention by masking out (setting to −∞) all values in the input\\nof the softmax which correspond to illegal connections. See Figure 2.\\n3.3\\nPosition-wise Feed-Forward Networks\\nIn addition to attention sub-layers, each of the layers in our encoder and decoder contains a fully\\nconnected feed-forward network, which is applied to each position separately and identically. This\\nconsists of two linear transformations with a ReLU activation in between.\\nFFN(x) = max(0, xW1 + b1)W2 + b2\\n(2)\\nWhile the linear transformations are the same across different positions, they use different parameters\\nfrom layer to layer. Another way of describing this is as two convolutions with kernel size 1.\\nThe dimensionality of input and output is dmodel = 512, and the inner-layer has dimensionality\\ndff = 2048.\\n3.4\\nEmbeddings and Softmax\\nSimilarly to other sequence transduction models, we use learned embeddings to convert the input\\ntokens and output tokens to vectors of dimension dmodel. We also use the usual learned linear transfor-\\nmation and softmax function to convert the decoder output to predicted next-token probabilities. In\\nour model, we share the same weight matrix between the two embedding layers and the pre-softmax\\nlinear transformation, similar to [24]. In the embedding layers, we multiply those weights by √dmodel.\\n3.5\\nPositional Encoding\\nSince our model contains no recurrence and no convolution, in order for the model to make use of the\\norder of the sequence, we must inject some information about the relative or absolute position of the\\ntokens in the sequence. To this end, we add \"positional encodings\" to the input embeddings at the\\n5'),\n",
|
| 48 |
+
" Document(metadata={'producer': 'PyPDF2', 'creator': '', 'creationdate': '', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_path': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'format': 'PDF 1.3', 'title': 'Attention is All you Need', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'keywords': '', 'moddate': '2018-02-12T21:22:10-08:00', 'trapped': '', 'modDate': \"D:20180212212210-08'00'\", 'creationDate': '', 'page': 5}, page_content='Table 1: Maximum path lengths, per-layer complexity and minimum number of sequential operations\\nfor different layer types. n is the sequence length, d is the representation dimension, k is the kernel\\nsize of convolutions and r the size of the neighborhood in restricted self-attention.\\nLayer Type\\nComplexity per Layer\\nSequential\\nMaximum Path Length\\nOperations\\nSelf-Attention\\nO(n2 · d)\\nO(1)\\nO(1)\\nRecurrent\\nO(n · d2)\\nO(n)\\nO(n)\\nConvolutional\\nO(k · n · d2)\\nO(1)\\nO(logk(n))\\nSelf-Attention (restricted)\\nO(r · n · d)\\nO(1)\\nO(n/r)\\nbottoms of the encoder and decoder stacks. The positional encodings have the same dimension dmodel\\nas the embeddings, so that the two can be summed. There are many choices of positional encodings,\\nlearned and fixed [8].\\nIn this work, we use sine and cosine functions of different frequencies:\\nPE(pos,2i) = sin(pos/100002i/dmodel)\\nPE(pos,2i+1) = cos(pos/100002i/dmodel)\\nwhere pos is the position and i is the dimension. That is, each dimension of the positional encoding\\ncorresponds to a sinusoid. The wavelengths form a geometric progression from 2π to 10000 · 2π. We\\nchose this function because we hypothesized it would allow the model to easily learn to attend by\\nrelative positions, since for any fixed offset k, PEpos+k can be represented as a linear function of\\nPEpos.\\nWe also experimented with using learned positional embeddings [8] instead, and found that the two\\nversions produced nearly identical results (see Table 3 row (E)). We chose the sinusoidal version\\nbecause it may allow the model to extrapolate to sequence lengths longer than the ones encountered\\nduring training.\\n4\\nWhy Self-Attention\\nIn this section we compare various aspects of self-attention layers to the recurrent and convolu-\\ntional layers commonly used for mapping one variable-length sequence of symbol representations\\n(x1, ..., xn) to another sequence of equal length (z1, ..., zn), with xi, zi ∈Rd, such as a hidden\\nlayer in a typical sequence transduction encoder or decoder. Motivating our use of self-attention we\\nconsider three desiderata.\\nOne is the total computational complexity per layer. Another is the amount of computation that can\\nbe parallelized, as measured by the minimum number of sequential operations required.\\nThe third is the path length between long-range dependencies in the network. Learning long-range\\ndependencies is a key challenge in many sequence transduction tasks. One key factor affecting the\\nability to learn such dependencies is the length of the paths forward and backward signals have to\\ntraverse in the network. The shorter these paths between any combination of positions in the input\\nand output sequences, the easier it is to learn long-range dependencies [11]. Hence we also compare\\nthe maximum path length between any two input and output positions in networks composed of the\\ndifferent layer types.\\nAs noted in Table 1, a self-attention layer connects all positions with a constant number of sequentially\\nexecuted operations, whereas a recurrent layer requires O(n) sequential operations. In terms of\\ncomputational complexity, self-attention layers are faster than recurrent layers when the sequence\\nlength n is smaller than the representation dimensionality d, which is most often the case with\\nsentence representations used by state-of-the-art models in machine translations, such as word-piece\\n[31] and byte-pair [25] representations. To improve computational performance for tasks involving\\nvery long sequences, self-attention could be restricted to considering only a neighborhood of size r in\\n6'),\n",
|
| 49 |
+
" Document(metadata={'producer': 'PyPDF2', 'creator': '', 'creationdate': '', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_path': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'format': 'PDF 1.3', 'title': 'Attention is All you Need', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'keywords': '', 'moddate': '2018-02-12T21:22:10-08:00', 'trapped': '', 'modDate': \"D:20180212212210-08'00'\", 'creationDate': '', 'page': 6}, page_content='the input sequence centered around the respective output position. This would increase the maximum\\npath length to O(n/r). We plan to investigate this approach further in future work.\\nA single convolutional layer with kernel width k < n does not connect all pairs of input and output\\npositions. Doing so requires a stack of O(n/k) convolutional layers in the case of contiguous kernels,\\nor O(logk(n)) in the case of dilated convolutions [15], increasing the length of the longest paths\\nbetween any two positions in the network. Convolutional layers are generally more expensive than\\nrecurrent layers, by a factor of k. Separable convolutions [6], however, decrease the complexity\\nconsiderably, to O(k · n · d + n · d2). Even with k = n, however, the complexity of a separable\\nconvolution is equal to the combination of a self-attention layer and a point-wise feed-forward layer,\\nthe approach we take in our model.\\nAs side benefit, self-attention could yield more interpretable models. We inspect attention distributions\\nfrom our models and present and discuss examples in the appendix. Not only do individual attention\\nheads clearly learn to perform different tasks, many appear to exhibit behavior related to the syntactic\\nand semantic structure of the sentences.\\n5\\nTraining\\nThis section describes the training regime for our models.\\n5.1\\nTraining Data and Batching\\nWe trained on the standard WMT 2014 English-German dataset consisting of about 4.5 million\\nsentence pairs. Sentences were encoded using byte-pair encoding [3], which has a shared source-\\ntarget vocabulary of about 37000 tokens. For English-French, we used the significantly larger WMT\\n2014 English-French dataset consisting of 36M sentences and split tokens into a 32000 word-piece\\nvocabulary [31]. Sentence pairs were batched together by approximate sequence length. Each training\\nbatch contained a set of sentence pairs containing approximately 25000 source tokens and 25000\\ntarget tokens.\\n5.2\\nHardware and Schedule\\nWe trained our models on one machine with 8 NVIDIA P100 GPUs. For our base models using\\nthe hyperparameters described throughout the paper, each training step took about 0.4 seconds. We\\ntrained the base models for a total of 100,000 steps or 12 hours. For our big models,(described on the\\nbottom line of table 3), step time was 1.0 seconds. The big models were trained for 300,000 steps\\n(3.5 days).\\n5.3\\nOptimizer\\nWe used the Adam optimizer [17] with β1 = 0.9, β2 = 0.98 and ϵ = 10−9. We varied the learning\\nrate over the course of training, according to the formula:\\nlrate = d−0.5\\nmodel · min(step_num−0.5, step_num · warmup_steps−1.5)\\n(3)\\nThis corresponds to increasing the learning rate linearly for the first warmup_steps training steps,\\nand decreasing it thereafter proportionally to the inverse square root of the step number. We used\\nwarmup_steps = 4000.\\n5.4\\nRegularization\\nWe employ three types of regularization during training:\\nResidual Dropout\\nWe apply dropout [27] to the output of each sub-layer, before it is added to the\\nsub-layer input and normalized. In addition, we apply dropout to the sums of the embeddings and the\\npositional encodings in both the encoder and decoder stacks. For the base model, we use a rate of\\nPdrop = 0.1.\\n7'),\n",
|
| 50 |
+
" Document(metadata={'producer': 'PyPDF2', 'creator': '', 'creationdate': '', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_path': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'format': 'PDF 1.3', 'title': 'Attention is All you Need', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'keywords': '', 'moddate': '2018-02-12T21:22:10-08:00', 'trapped': '', 'modDate': \"D:20180212212210-08'00'\", 'creationDate': '', 'page': 7}, page_content='Table 2: The Transformer achieves better BLEU scores than previous state-of-the-art models on the\\nEnglish-to-German and English-to-French newstest2014 tests at a fraction of the training cost.\\nModel\\nBLEU\\nTraining Cost (FLOPs)\\nEN-DE\\nEN-FR\\nEN-DE\\nEN-FR\\nByteNet [15]\\n23.75\\nDeep-Att + PosUnk [32]\\n39.2\\n1.0 · 1020\\nGNMT + RL [31]\\n24.6\\n39.92\\n2.3 · 1019\\n1.4 · 1020\\nConvS2S [8]\\n25.16\\n40.46\\n9.6 · 1018\\n1.5 · 1020\\nMoE [26]\\n26.03\\n40.56\\n2.0 · 1019\\n1.2 · 1020\\nDeep-Att + PosUnk Ensemble [32]\\n40.4\\n8.0 · 1020\\nGNMT + RL Ensemble [31]\\n26.30\\n41.16\\n1.8 · 1020\\n1.1 · 1021\\nConvS2S Ensemble [8]\\n26.36\\n41.29\\n7.7 · 1019\\n1.2 · 1021\\nTransformer (base model)\\n27.3\\n38.1\\n3.3 · 1018\\nTransformer (big)\\n28.4\\n41.0\\n2.3 · 1019\\nLabel Smoothing\\nDuring training, we employed label smoothing of value ϵls = 0.1 [30]. This\\nhurts perplexity, as the model learns to be more unsure, but improves accuracy and BLEU score.\\n6\\nResults\\n6.1\\nMachine Translation\\nOn the WMT 2014 English-to-German translation task, the big transformer model (Transformer (big)\\nin Table 2) outperforms the best previously reported models (including ensembles) by more than 2.0\\nBLEU, establishing a new state-of-the-art BLEU score of 28.4. The configuration of this model is\\nlisted in the bottom line of Table 3. Training took 3.5 days on 8 P100 GPUs. Even our base model\\nsurpasses all previously published models and ensembles, at a fraction of the training cost of any of\\nthe competitive models.\\nOn the WMT 2014 English-to-French translation task, our big model achieves a BLEU score of 41.0,\\noutperforming all of the previously published single models, at less than 1/4 the training cost of the\\nprevious state-of-the-art model. The Transformer (big) model trained for English-to-French used\\ndropout rate Pdrop = 0.1, instead of 0.3.\\nFor the base models, we used a single model obtained by averaging the last 5 checkpoints, which\\nwere written at 10-minute intervals. For the big models, we averaged the last 20 checkpoints. We\\nused beam search with a beam size of 4 and length penalty α = 0.6 [31]. These hyperparameters\\nwere chosen after experimentation on the development set. We set the maximum output length during\\ninference to input length + 50, but terminate early when possible [31].\\nTable 2 summarizes our results and compares our translation quality and training costs to other model\\narchitectures from the literature. We estimate the number of floating point operations used to train a\\nmodel by multiplying the training time, the number of GPUs used, and an estimate of the sustained\\nsingle-precision floating-point capacity of each GPU 5.\\n6.2\\nModel Variations\\nTo evaluate the importance of different components of the Transformer, we varied our base model\\nin different ways, measuring the change in performance on English-to-German translation on the\\ndevelopment set, newstest2013. We used beam search as described in the previous section, but no\\ncheckpoint averaging. We present these results in Table 3.\\nIn Table 3 rows (A), we vary the number of attention heads and the attention key and value dimensions,\\nkeeping the amount of computation constant, as described in Section 3.2.2. While single-head\\nattention is 0.9 BLEU worse than the best setting, quality also drops off with too many heads.\\n5We used values of 2.8, 3.7, 6.0 and 9.5 TFLOPS for K80, K40, M40 and P100, respectively.\\n8'),\n",
|
| 51 |
+
" Document(metadata={'producer': 'PyPDF2', 'creator': '', 'creationdate': '', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_path': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'format': 'PDF 1.3', 'title': 'Attention is All you Need', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'keywords': '', 'moddate': '2018-02-12T21:22:10-08:00', 'trapped': '', 'modDate': \"D:20180212212210-08'00'\", 'creationDate': '', 'page': 8}, page_content='Table 3: Variations on the Transformer architecture. Unlisted values are identical to those of the base\\nmodel. All metrics are on the English-to-German translation development set, newstest2013. Listed\\nperplexities are per-wordpiece, according to our byte-pair encoding, and should not be compared to\\nper-word perplexities.\\nN\\ndmodel\\ndff\\nh\\ndk\\ndv\\nPdrop\\nϵls\\ntrain\\nPPL\\nBLEU\\nparams\\nsteps\\n(dev)\\n(dev)\\n×106\\nbase\\n6\\n512\\n2048\\n8\\n64\\n64\\n0.1\\n0.1\\n100K\\n4.92\\n25.8\\n65\\n(A)\\n1\\n512\\n512\\n5.29\\n24.9\\n4\\n128\\n128\\n5.00\\n25.5\\n16\\n32\\n32\\n4.91\\n25.8\\n32\\n16\\n16\\n5.01\\n25.4\\n(B)\\n16\\n5.16\\n25.1\\n58\\n32\\n5.01\\n25.4\\n60\\n(C)\\n2\\n6.11\\n23.7\\n36\\n4\\n5.19\\n25.3\\n50\\n8\\n4.88\\n25.5\\n80\\n256\\n32\\n32\\n5.75\\n24.5\\n28\\n1024\\n128\\n128\\n4.66\\n26.0\\n168\\n1024\\n5.12\\n25.4\\n53\\n4096\\n4.75\\n26.2\\n90\\n(D)\\n0.0\\n5.77\\n24.6\\n0.2\\n4.95\\n25.5\\n0.0\\n4.67\\n25.3\\n0.2\\n5.47\\n25.7\\n(E)\\npositional embedding instead of sinusoids\\n4.92\\n25.7\\nbig\\n6\\n1024\\n4096\\n16\\n0.3\\n300K\\n4.33\\n26.4\\n213\\nIn Table 3 rows (B), we observe that reducing the attention key size dk hurts model quality. This\\nsuggests that determining compatibility is not easy and that a more sophisticated compatibility\\nfunction than dot product may be beneficial. We further observe in rows (C) and (D) that, as expected,\\nbigger models are better, and dropout is very helpful in avoiding over-fitting. In row (E) we replace our\\nsinusoidal positional encoding with learned positional embeddings [8], and observe nearly identical\\nresults to the base model.\\n7\\nConclusion\\nIn this work, we presented the Transformer, the first sequence transduction model based entirely on\\nattention, replacing the recurrent layers most commonly used in encoder-decoder architectures with\\nmulti-headed self-attention.\\nFor translation tasks, the Transformer can be trained significantly faster than architectures based\\non recurrent or convolutional layers. On both WMT 2014 English-to-German and WMT 2014\\nEnglish-to-French translation tasks, we achieve a new state of the art. In the former task our best\\nmodel outperforms even all previously reported ensembles.\\nWe are excited about the future of attention-based models and plan to apply them to other tasks. We\\nplan to extend the Transformer to problems involving input and output modalities other than text and\\nto investigate local, restricted attention mechanisms to efficiently handle large inputs and outputs\\nsuch as images, audio and video. Making generation less sequential is another research goals of ours.\\nThe code we used to train and evaluate our models is available at https://github.com/\\ntensorflow/tensor2tensor.\\nAcknowledgements\\nWe are grateful to Nal Kalchbrenner and Stephan Gouws for their fruitful\\ncomments, corrections and inspiration.\\n9'),\n",
|
| 52 |
+
" Document(metadata={'producer': 'PyPDF2', 'creator': '', 'creationdate': '', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_path': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'format': 'PDF 1.3', 'title': 'Attention is All you Need', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'keywords': '', 'moddate': '2018-02-12T21:22:10-08:00', 'trapped': '', 'modDate': \"D:20180212212210-08'00'\", 'creationDate': '', 'page': 9}, page_content='References\\n[1] Jimmy Lei Ba, Jamie Ryan Kiros, and Geoffrey E Hinton. Layer normalization. arXiv preprint\\narXiv:1607.06450, 2016.\\n[2] Dzmitry Bahdanau, Kyunghyun Cho, and Yoshua Bengio. Neural machine translation by jointly\\nlearning to align and translate. CoRR, abs/1409.0473, 2014.\\n[3] Denny Britz, Anna Goldie, Minh-Thang Luong, and Quoc V. Le. Massive exploration of neural\\nmachine translation architectures. CoRR, abs/1703.03906, 2017.\\n[4] Jianpeng Cheng, Li Dong, and Mirella Lapata. Long short-term memory-networks for machine\\nreading. arXiv preprint arXiv:1601.06733, 2016.\\n[5] Kyunghyun Cho, Bart van Merrienboer, Caglar Gulcehre, Fethi Bougares, Holger Schwenk,\\nand Yoshua Bengio. Learning phrase representations using rnn encoder-decoder for statistical\\nmachine translation. CoRR, abs/1406.1078, 2014.\\n[6] Francois Chollet. Xception: Deep learning with depthwise separable convolutions. arXiv\\npreprint arXiv:1610.02357, 2016.\\n[7] Junyoung Chung, Çaglar Gülçehre, Kyunghyun Cho, and Yoshua Bengio. Empirical evaluation\\nof gated recurrent neural networks on sequence modeling. CoRR, abs/1412.3555, 2014.\\n[8] Jonas Gehring, Michael Auli, David Grangier, Denis Yarats, and Yann N. Dauphin. Convolu-\\ntional sequence to sequence learning. arXiv preprint arXiv:1705.03122v2, 2017.\\n[9] Alex Graves.\\nGenerating sequences with recurrent neural networks.\\narXiv preprint\\narXiv:1308.0850, 2013.\\n[10] Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. Deep residual learning for im-\\nage recognition. In Proceedings of the IEEE Conference on Computer Vision and Pattern\\nRecognition, pages 770–778, 2016.\\n[11] Sepp Hochreiter, Yoshua Bengio, Paolo Frasconi, and Jürgen Schmidhuber. Gradient flow in\\nrecurrent nets: the difficulty of learning long-term dependencies, 2001.\\n[12] Sepp Hochreiter and Jürgen Schmidhuber. Long short-term memory. Neural computation,\\n9(8):1735–1780, 1997.\\n[13] Rafal Jozefowicz, Oriol Vinyals, Mike Schuster, Noam Shazeer, and Yonghui Wu. Exploring\\nthe limits of language modeling. arXiv preprint arXiv:1602.02410, 2016.\\n[14] Łukasz Kaiser and Ilya Sutskever. Neural GPUs learn algorithms. In International Conference\\non Learning Representations (ICLR), 2016.\\n[15] Nal Kalchbrenner, Lasse Espeholt, Karen Simonyan, Aaron van den Oord, Alex Graves, and Ko-\\nray Kavukcuoglu. Neural machine translation in linear time. arXiv preprint arXiv:1610.10099v2,\\n2017.\\n[16] Yoon Kim, Carl Denton, Luong Hoang, and Alexander M. Rush. Structured attention networks.\\nIn International Conference on Learning Representations, 2017.\\n[17] Diederik Kingma and Jimmy Ba. Adam: A method for stochastic optimization. In ICLR, 2015.\\n[18] Oleksii Kuchaiev and Boris Ginsburg. Factorization tricks for LSTM networks. arXiv preprint\\narXiv:1703.10722, 2017.\\n[19] Zhouhan Lin, Minwei Feng, Cicero Nogueira dos Santos, Mo Yu, Bing Xiang, Bowen\\nZhou, and Yoshua Bengio. A structured self-attentive sentence embedding. arXiv preprint\\narXiv:1703.03130, 2017.\\n[20] Samy Bengio Łukasz Kaiser. Can active memory replace attention? In Advances in Neural\\nInformation Processing Systems, (NIPS), 2016.\\n10'),\n",
|
| 53 |
+
" Document(metadata={'producer': 'PyPDF2', 'creator': '', 'creationdate': '', 'source': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'file_path': '../data/pdf/NIPS-2017-attention-is-all-you-need-Paper.pdf', 'total_pages': 11, 'format': 'PDF 1.3', 'title': 'Attention is All you Need', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'keywords': '', 'moddate': '2018-02-12T21:22:10-08:00', 'trapped': '', 'modDate': \"D:20180212212210-08'00'\", 'creationDate': '', 'page': 10}, page_content='[21] Minh-Thang Luong, Hieu Pham, and Christopher D Manning. Effective approaches to attention-\\nbased neural machine translation. arXiv preprint arXiv:1508.04025, 2015.\\n[22] Ankur Parikh, Oscar Täckström, Dipanjan Das, and Jakob Uszkoreit. A decomposable attention\\nmodel. In Empirical Methods in Natural Language Processing, 2016.\\n[23] Romain Paulus, Caiming Xiong, and Richard Socher. A deep reinforced model for abstractive\\nsummarization. arXiv preprint arXiv:1705.04304, 2017.\\n[24] Ofir Press and Lior Wolf. Using the output embedding to improve language models. arXiv\\npreprint arXiv:1608.05859, 2016.\\n[25] Rico Sennrich, Barry Haddow, and Alexandra Birch. Neural machine translation of rare words\\nwith subword units. arXiv preprint arXiv:1508.07909, 2015.\\n[26] Noam Shazeer, Azalia Mirhoseini, Krzysztof Maziarz, Andy Davis, Quoc Le, Geoffrey Hinton,\\nand Jeff Dean. Outrageously large neural networks: The sparsely-gated mixture-of-experts\\nlayer. arXiv preprint arXiv:1701.06538, 2017.\\n[27] Nitish Srivastava, Geoffrey E Hinton, Alex Krizhevsky, Ilya Sutskever, and Ruslan Salakhutdi-\\nnov. Dropout: a simple way to prevent neural networks from overfitting. Journal of Machine\\nLearning Research, 15(1):1929–1958, 2014.\\n[28] Sainbayar Sukhbaatar, arthur szlam, Jason Weston, and Rob Fergus. End-to-end memory\\nnetworks. In C. Cortes, N. D. Lawrence, D. D. Lee, M. Sugiyama, and R. Garnett, editors,\\nAdvances in Neural Information Processing Systems 28, pages 2440–2448. Curran Associates,\\nInc., 2015.\\n[29] Ilya Sutskever, Oriol Vinyals, and Quoc VV Le. Sequence to sequence learning with neural\\nnetworks. In Advances in Neural Information Processing Systems, pages 3104–3112, 2014.\\n[30] Christian Szegedy, Vincent Vanhoucke, Sergey Ioffe, Jonathon Shlens, and Zbigniew Wojna.\\nRethinking the inception architecture for computer vision. CoRR, abs/1512.00567, 2015.\\n[31] Yonghui Wu, Mike Schuster, Zhifeng Chen, Quoc V Le, Mohammad Norouzi, Wolfgang\\nMacherey, Maxim Krikun, Yuan Cao, Qin Gao, Klaus Macherey, et al. Google’s neural machine\\ntranslation system: Bridging the gap between human and machine translation. arXiv preprint\\narXiv:1609.08144, 2016.\\n[32] Jie Zhou, Ying Cao, Xuguang Wang, Peng Li, and Wei Xu. Deep recurrent models with\\nfast-forward connections for neural machine translation. CoRR, abs/1606.04199, 2016.\\n11'),\n",
|
| 54 |
+
" Document(metadata={'producer': 'Microsoft® Word 2016', 'creator': 'Microsoft® Word 2016', 'creationdate': '2023-10-09T10:46:36+05:30', 'source': '../data/pdf/2310.05421v1.pdf', 'file_path': '../data/pdf/2310.05421v1.pdf', 'total_pages': 4, 'format': 'PDF 1.7', 'title': 'Paper Title (use style: paper title)', 'author': 'Keivalya Pandya;Dr Mehfuza Holia', 'subject': '', 'keywords': '', 'moddate': '2023-10-09T10:46:36+05:30', 'trapped': '', 'modDate': \"D:20231009104636+05'30'\", 'creationDate': \"D:20231009104636+05'30'\", 'page': 0}, page_content='Submitted to the 3rd International Conference on “Women in Science & Technology: Creating Sustainable Career” \\n28 -30 December, 2023 \\nAutomating Customer Service using LangChain \\nBuilding custom open-source GPT Chatbot for organizations \\nKeivalya Pandya \\n19me439@bvmengineering.ac.in \\nBirla Vishvakarma Mahavidyalaya, Gujarat, India \\nProf. Dr. Mehfuza Holia \\nmsholia@bvmengineering.ac.in \\nBirla Vishvakarma Mahavidyalaya, Gujarat, India \\n \\nAbstract— In the digital age, the dynamics of customer \\nservice are evolving, driven by technological advancements and \\nthe integration of Large Language Models (LLMs). This research \\npaper introduces a groundbreaking approach to automating \\ncustomer service using LangChain, a custom LLM tailored for \\norganizations. The paper explores the obsolescence of traditional \\ncustomer support techniques, particularly Frequently Asked \\nQuestions (FAQs), and proposes a paradigm shift towards \\nresponsive, \\ncontext-aware, \\nand \\npersonalized \\ncustomer \\ninteractions. The heart of this innovation lies in the fusion of \\nopen-source methodologies, web scraping, fine-tuning, and the \\nseamless integration of LangChain into customer service \\nplatforms. \\nThis \\nopen-source \\nstate-of-the-art \\nframework, \\npresented as \"Sahaay,\" demonstrates the ability to scale across \\nindustries and organizations, offering real-time support and \\nquery resolution. Key elements of this research encompass data \\ncollection via web scraping, the role of embeddings, the \\nutilization of Google\\'s Flan T5 XXL, Base and Small language \\nmodels for knowledge retrieval, and the integration of the \\nchatbot into customer service platforms. The results section \\nprovides insights into their performance and use cases, here \\nparticularly within an educational institution. This research \\nheralds a new era in customer service, where technology is \\nharnessed to create efficient, personalized, and responsive \\ninteractions. Sahaay, powered by LangChain, redefines the \\ncustomer-company relationship, elevating customer retention, \\nvalue extraction, and brand image. As organizations embrace \\nLLMs, customer service becomes a dynamic and customer-\\ncentric ecosystem. \\nKeywords— Customer Service Automation, Large Language \\nModels, LangChain, Web Scraping, Context-Aware Interactions \\nI. INTRODUCTION \\n“Customer is king” is the ancient mantra reflecting the \\nsignificance of customers in every business. In the digital age, \\nwhere the rhythms of modern life are guided by the pulse of \\ntechnology, the realm of customer service stands as the \\nfrontline of engagement between businesses and their clientele. \\nIt is the place where queries are answered, problems are \\nresolved, and trust is forged. \\nThis research paper brings the future of customer service, \\nwhere \\nautomation, \\npersonalization, \\nand \\nresponsiveness \\nconverge to redefine the customer-company relationship. At \\nthe heart of this transformation lies the integration of LLMs, \\nexemplified by LangChain [1]. \\nIn the annals of customer service history, FAQs and \\ntraditional support mechanisms have long held sway. These \\nvenerable tools have dutifully served as repositories of \\ninformation, attempting to address the queries and concerns of \\ncustomers. However, as we stand at the cusp of a new era in \\ncustomer service automation, it becomes abundantly clear that \\nthe traditional methods once hailed as revolutionary, are \\ngradually becoming obsolete. \\nThis paper is an invitation to envision a future where \\ncustomer service is not a cost center but a wellspring of \\ncustomer satisfaction and loyalty. We propose an open-source \\nframework that can be scaled to any industry or organization to \\nfulfill the consumer needs for support and query resolution \\nwithin seconds. \\nFor demonstration purposes, we use the information \\npresented by Birla Vishvakarma Mahavidyalaya (BVM) \\nEngineering \\nCollege \\non \\ntheir \\nwebsite \\nhttps://bvmengineering.ac.in/ as the context for our chatbot, \\nfrom where it can retrieve all the information in real-time and \\nanswer to any queries that are raised by the users. Here, users \\ncan be anyone ranging from prospective students, current \\nstudents who intend to get information from the Notice Board, \\nresearchers who wish to search for their potential research \\nguide, and so on. The applications are endless. \\nII. LITERATURE SURVEY \\nS. Kim (2023) et al addresses the challenge of deploying \\nresource-intensive large neural models, such as Transformers, \\nfor information retrieval (IR) while maintaining efficiency. \\nExperimental results on MSMARCO benchmarks demonstrate \\nthe effectiveness of this approach, achieving successful \\ndistillation of both dual-encoder and cross-encoder teacher \\nmodels into smaller, 1/10th size asymmetric students while \\nretaining 95-97% of the teacher\\'s performance [2]. L. Bonifacio \\net al (2022) highlights the recent transformation in the \\nInformation Retrieval (IR) field, propelled by the emergence of \\nlarge pretrained transformer models. The MS MARCO dataset \\nplayed a pivotal role in this revolution, enabling zero-shot \\ntransfer learning across various tasks [3]. \\nThis paper proposed a novel open-source approach to \\nbuilding LLM Chatbots using custom knowledge from the \\ncontent in the website. It is unique in several ways: \\n1. We propose an open-source framework which is robust \\nwith the type of dataset available on the webpage or \\nthe web of links. \\n2. This implementation aims to compliment the use of \\nFAQs with a more interactive and user-friendly \\ninterface. \\n3. We then do a comparative study of various models, \\ntheir performance on the provided data relative to the \\nexpected response from the LLM.'),\n",
|
| 55 |
+
" Document(metadata={'producer': 'Microsoft® Word 2016', 'creator': 'Microsoft® Word 2016', 'creationdate': '2023-10-09T10:46:36+05:30', 'source': '../data/pdf/2310.05421v1.pdf', 'file_path': '../data/pdf/2310.05421v1.pdf', 'total_pages': 4, 'format': 'PDF 1.7', 'title': 'Paper Title (use style: paper title)', 'author': 'Keivalya Pandya;Dr Mehfuza Holia', 'subject': '', 'keywords': '', 'moddate': '2023-10-09T10:46:36+05:30', 'trapped': '', 'modDate': \"D:20231009104636+05'30'\", 'creationDate': \"D:20231009104636+05'30'\", 'page': 1}, page_content='Submitted to the 3rd International Conference on “Women in Science & Technology: Creating Sustainable Career” \\n28 -30 December, 2023 \\nIII. METHODOLOGY \\nThis section covers the data collection, details about the \\nselected model, fine-tuning, and integration with the Gradio \\nAPIs for web deployment. \\nA. Data Collection \\nTo gather the necessary data for our project, we employed \\nBeautifulSoup web scraping techniques to retrieve publicly \\naccessible information from an organization’s homepage. We \\nobserved this page is often linked with all the relevant \\ninformation required for the user/visitor. This approach \\nallowed us to collect a wide array of data, including customer \\nservice FAQs, product manuals, support forums, chat logs, \\nassociated institutions, and so on. This data further serves as \\nthe context for our LLM. \\nB. Embeddings \\nEmbeddings play a pivotal role in the development of any \\nLLM powered. They are vector representations of words or \\nphrases in a continuous mathematical space that capture \\nsemantic and contextual information, allowing the model to \\nunderstand the meaning and relationships between words, \\nwhich is essential for providing meaningful responses to user \\nqueries. \\nWe have used HuggingFace Instuct Embeddings – \\n“hkunlp/instructor-large” a text embedding model fine-tuned \\nfor specific tasks and domains, such as classification, retrieval, \\nclustering, and text evaluation [4]. What sets Instructor apart is \\nits ability to generate tailored text embeddings without \\nrequiring additional fine-tuning. These embeddings are then \\nstored using FAISS (Facebook AI Similarity Search) library \\nthat allows developers to quickly search for embeddings of \\nmultimedia documents that are similar to each other [5]. \\nC. Language Model \\nWe have chosen Google’s Flan T5 XXL as the most \\nappropriate language model after comparing with other Flan T5 \\ndistributions to retrieve knowledge from the vectorspace and \\nchat_history (or memory) [6]. The model retains the context of \\nprevious messages and uses that as a reference to predict \\nanswers for the upcoming questions. This helps users to have \\nan interactive conversation with the chatbot, instead of a \\nmonotonous and robotic one. \\nD. Integration with Customer Service Platforms \\nA simple chat window can be activated at the corner of any \\nwebsite which would enable users to interact with the chatbot \\nand ask any relevant questions or doubts regarding the \\norganization. However, for the demonstration purpose of this \\npaper, we are using Gradio API framework [7]. \\nIV. RESULTS \\nIn this section, we mention the metrics of comparison, \\nprovide comparative analysis, and use cases in association with \\nan educational institution. \\nA. Evaluating the Performance of LLMs \\nIt is relatively difficult to evaluate LangChain agents, \\nespecially when trained on large chunks of context datasets for \\ninformation retrieval. Hence, the current solution for the lack of \\nmetrics is to rely on human knowledge to get a sense of how \\nthe chain/agent is performing. \\nIt is evident from TABLE-I, II and III that the XXL model \\noutperforms other competitive LLMs such as BASE and \\nSMALL. \\n \\nFig. 1. Model Architecture – Sahaay'),\n",
|
| 56 |
+
" Document(metadata={'producer': 'Microsoft® Word 2016', 'creator': 'Microsoft® Word 2016', 'creationdate': '2023-10-09T10:46:36+05:30', 'source': '../data/pdf/2310.05421v1.pdf', 'file_path': '../data/pdf/2310.05421v1.pdf', 'total_pages': 4, 'format': 'PDF 1.7', 'title': 'Paper Title (use style: paper title)', 'author': 'Keivalya Pandya;Dr Mehfuza Holia', 'subject': '', 'keywords': '', 'moddate': '2023-10-09T10:46:36+05:30', 'trapped': '', 'modDate': \"D:20231009104636+05'30'\", 'creationDate': \"D:20231009104636+05'30'\", 'page': 2}, page_content=\"Submitted to the 3rd International Conference on “Women in Science & Technology: Creating Sustainable Career” \\n28 -30 December, 2023 \\nTABLE I. \\nGoogle’s Flan-T5-XXL Performance \\nMetrics \\nPerformance \\nSr. \\nNo. \\nQuery/Prompt \\nAnswer \\n1. \\nWhat is BVM? \\nBirla \\nVishvakarma \\nMahavidyalaya \\n✯✯✯✯ \\n2. \\nWhere is it?a \\nVallabh Vidyanagar, Gujarat \\nIndia \\n✯✯✯ \\n3. \\nWhat is IEEE \\nBVM? \\nInstitute \\nof \\nElectrical \\nand \\nElectronics Engineers Student \\nBranch of BVM \\n✯✯✯✯ \\n4. \\nWhat is TRS \\nBVM? \\nBVM \\nStudent \\nChapter \\nassociated \\nwith \\nRobotics \\nSociety India \\n✯✯✯✯ \\n5. \\nName the annual \\nnewsletter? \\nVishvakarma Magazine and \\nNewsletter \\n✯✯✯✯ \\n6. \\nTell me \\nsomething about \\nICWSTCSC \\nThe International Conference \\nfor Women in Science and \\nTechnology \\nCreating \\nSustainable Career is the 3rd \\nInternational \\nConference \\nhappening in hybrid mode. \\n✯✯✯✯✯ \\na. Follow-up question \\nTABLE II. \\nGOOGLE’S FLAN-T5-BASE PERFORMANCE \\nMetrics \\nPerformance \\nSr. \\nNo. \\nQuery/Prompt \\nAnswer \\n1. \\nWhat is BVM? \\nBVM is the first engineering \\ncollege \\nof \\nGujarat \\nState \\nestablished way back in 1948. \\n✯✯✯✯ \\n2. \\nWhere is it?b \\nVV Nagar, Gujarat, India \\n✯✯✯ \\n3. \\nWhat is IEEE \\nBVM? \\nfirst engineering college of \\nGujarat State established way \\nback in 1948 \\n✯ \\n4. \\nWhat is TRS \\nBVM? \\nCVM BVM Robotics Society \\nOf India \\n✯✯ \\n5. \\nName the annual \\nnewsletter? \\nVishvakarma Magazine \\n✯✯✯✯ \\n6. \\nTell me \\nsomething about \\nICWSTCSC \\nBVM \\n3rd \\nInternartional \\nConference \\n✯✯✯✯ \\nb. Follow-up question \\nTABLE III. \\nGOOGLE’S FLAN-T5-SMALL PERFORMANCE \\nMetrics \\nPerformance \\nSr. \\nNo. \\nQuery/Prompt \\nAnswer \\n1. \\nWhat is BVM? \\nBVM is the first Autonomous \\nEngineering institute of Gujarat \\nto obtain academic autonomy \\nfor all its UG & PG programs, \\nfrom \\nUniversity \\nGrant \\nCommission (UGC). \\n✯✯✯ \\n2. \\nWhere is it?c \\nBVM Engineering College \\n✯ \\n3. \\nWhat is IEEE \\nBVM? \\nengineering college of Gujarat \\nState \\n✯ \\n4. \\nWhat is TRS \\nBVM? \\nBVM \\n✯ \\n5. \\nName the annual \\nnewsletter? \\nCampus Publications \\n✯ \\n6. \\nTell me \\nsomething about \\nICWSTCSC \\nICWSTCSC \\n2023 \\nPMSSS \\nstudents' \\nreporting \\nafter \\nadmission (AY: 2023-24) at \\nBVM \\n3rd \\nInternartional \\nConference. \\n✯✯✯ \\nc. Follow-up question \\nB. Applications \\nCustomer service establishes a direct connection between \\nthe customer and the company. It retains customers and \\nextracts higher value from them. By harnessing the power of \\nLarge Language Models as shown in Fig. 2, customer service \\ncan be elevated to new heights, facilitating efficient, \\npersonalized, and responsive interactions. The LangChain fine-\\ntuned over custom knowledge of the product, service, or \\norganization can effectively address a wide array of customer \\ninquiries and issues. Its ability to understand context and \\nhistory empowers it to provide personalized support to \\ncustomers. Automated customer service powered by LLMs is \\navailable around the clock and is also proficient in multiple \\nlanguages. \\nV. CONCLUSION \\nIn the ever-evolving landscape of customer service, the \\nintroduction of Sahaay’s innovative approach presented in this \\npaper, using LangChain as a prime example, ushered in a new \\nera of automation. Automating customer service using \\nSahaay’s open-source Large Language architecture leveraging \\nLangChain revolutionizes the customer-company relationship \\nand CX. It enables companies to provide efficient, \\nFig. 2. User interface – Gradio framework\"),\n",
|
| 57 |
+
" Document(metadata={'producer': 'Microsoft® Word 2016', 'creator': 'Microsoft® Word 2016', 'creationdate': '2023-10-09T10:46:36+05:30', 'source': '../data/pdf/2310.05421v1.pdf', 'file_path': '../data/pdf/2310.05421v1.pdf', 'total_pages': 4, 'format': 'PDF 1.7', 'title': 'Paper Title (use style: paper title)', 'author': 'Keivalya Pandya;Dr Mehfuza Holia', 'subject': '', 'keywords': '', 'moddate': '2023-10-09T10:46:36+05:30', 'trapped': '', 'modDate': \"D:20231009104636+05'30'\", 'creationDate': \"D:20231009104636+05'30'\", 'page': 3}, page_content='Submitted to the 3rd International Conference on “Women in Science & Technology: Creating Sustainable Career” \\n28 -30 December, 2023 \\npersonalized, and responsive support, ultimately leading to \\ncustomer retention, increased customer value, and a more \\npositive brand image. As organizations continue to leverage the \\ncapabilities of LLMs, the landscape of customer service is \\nevolving into a more dynamic and customer-centric ecosystem. \\nThis paper demonstrates a comparison between various \\nmodel performances and evaluates them on the basis of the \\nquality \\nof \\nresponse \\ngenerated. \\nWe \\nhave \\ncompared \\nGOOGLE/FLAN-T5-XXL with GOOGLE/FLAN-T5-BASE, \\nand GOOGLE/FLAN-T5-SMALL and observed that the XXL \\nmodel outperforms the other LLMs in the provided task. Each \\nmodel is posed with the same questions. \\nIn the future, Sahaay can access PDFs, Videos, Audio, and \\nother files to extract relevant information about, for example, \\nstudent activities, research work and innovation carried out by \\nBVM. This multimodal capability has the potential to change \\nforever the way we interact with websites and retrieve \\ninformation in much less time. \\nACKNOWLEDGMENT \\nThe authors would like to express their deepest appreciation \\nto the research facility provided at TRS BVM Laboratory for \\nencouraging multi-disciplinary collaborative research within \\nthe campus. We’d also like to thank Birla Vishvakarma \\nMahavidyalaya (Engineering College) for allowing us to \\nexperiment with the innovation on their website. \\nREFERENCES \\n[1] Asbjørn Følstad and Marita Skjuve. 2019. Chatbots for customer \\nservice: user experience and motivation. In Proceedings of the 1st \\nInternational Conference on Conversational User Interfaces (CUI \\'19). \\nAssociation for Computing Machinery, New York, NY, USA, Article 1, \\n1–9. https://doi.org/10.1145/3342775.3342784 \\n[2] Kim, S., Rawat, A. S., Zaheer, M., Jayasumana, S., Sadhanala, V., \\nJitkrittum, W., Menon, A. K., Fergus, R., & Kumar, S. (2023). \\nEmbedDistill: A Geometric Knowledge Distillation for Information \\nRetrieval. ArXiv. /abs/2301.12005 \\n[3] Luiz Bonifacio, Hugo Abonizio, Marzieh Fadaee, and Rodrigo \\nNogueira. 2022. InPars: Unsupervised Dataset Generation for \\nInformation Retrieval. In Proceedings of the 45th International ACM \\nSIGIR Conference on Research and Development in Information \\nRetrieval (SIGIR \\'22). Association for Computing Machinery, New \\nYork, NY, USA, 2387–2392. https://doi.org/10.1145/3477495.3531863 \\n[4] Su, Hongjin, Weijia Shi, Jungo Kasai, Yizhong Wang, Yushi Hu, Mari \\nOstendorf, Wen Yih, Noah A. Smith, Luke Zettlemoyer, and Tao Yu. \\n\"One Embedder, Any Task: Instruction-Finetuned Text Embeddings.\" \\nArXiv, (2022). /abs/2212.09741. \\n[5] Johnson, Jeff, Matthijs Douze, and Hervé Jégou. \"Billion-scale \\nSimilarity Search with GPUs.\" ArXiv, (2017). Accessed September 28, \\n2023. /abs/1702.08734. \\n[6] Chung, Hyung W., Le Hou, Shayne Longpre, Barret Zoph, Yi Tay, \\nWilliam Fedus, Yunxuan Li et al. \"Scaling Instruction-Finetuned \\nLanguage Models.\" ArXiv, (2022). Accessed September 28, 2023. \\n/abs/2210.11416 \\n[7] Abid, A., Abdalla, A., Abid, A., Khan, D., Alfozan, A., & Zou, J. \\n(2019). Gradio: Hassle-Free Sharing and Testing of ML Models in the \\nWild. ArXiv. /abs/1906.02569')]"
|
| 58 |
+
]
|
| 59 |
+
},
|
| 60 |
+
"execution_count": 7,
|
| 61 |
+
"metadata": {},
|
| 62 |
+
"output_type": "execute_result"
|
| 63 |
+
}
|
| 64 |
+
],
|
| 65 |
+
"source": [
|
| 66 |
+
"from langchain_community.document_loaders import PyPDFLoader, PyMuPDFLoader\n",
|
| 67 |
+
"dir_loaders= DirectoryLoader(\n",
|
| 68 |
+
" \"../data/pdf\",\n",
|
| 69 |
+
" glob=\"**/*.pdf\",\n",
|
| 70 |
+
" loader_cls=PyMuPDFLoader,\n",
|
| 71 |
+
" show_progress=True,\n",
|
| 72 |
+
"\n",
|
| 73 |
+
")\n",
|
| 74 |
+
"\n",
|
| 75 |
+
"pdf_docs= dir_loaders.load()\n",
|
| 76 |
+
"pdf_docs"
|
| 77 |
+
]
|
| 78 |
+
},
|
| 79 |
+
{
|
| 80 |
+
"cell_type": "code",
|
| 81 |
+
"execution_count": 8,
|
| 82 |
+
"id": "52ac65f1",
|
| 83 |
+
"metadata": {},
|
| 84 |
+
"outputs": [
|
| 85 |
+
{
|
| 86 |
+
"data": {
|
| 87 |
+
"text/plain": [
|
| 88 |
+
"langchain_core.documents.base.Document"
|
| 89 |
+
]
|
| 90 |
+
},
|
| 91 |
+
"execution_count": 8,
|
| 92 |
+
"metadata": {},
|
| 93 |
+
"output_type": "execute_result"
|
| 94 |
+
}
|
| 95 |
+
],
|
| 96 |
+
"source": [
|
| 97 |
+
"type(pdf_docs[0]) # should be Document"
|
| 98 |
+
]
|
| 99 |
+
},
|
| 100 |
+
{
|
| 101 |
+
"cell_type": "code",
|
| 102 |
+
"execution_count": null,
|
| 103 |
+
"id": "dd37f704",
|
| 104 |
+
"metadata": {},
|
| 105 |
+
"outputs": [],
|
| 106 |
+
"source": []
|
| 107 |
+
}
|
| 108 |
+
],
|
| 109 |
+
"metadata": {
|
| 110 |
+
"kernelspec": {
|
| 111 |
+
"display_name": "RAG-Pipeline",
|
| 112 |
+
"language": "python",
|
| 113 |
+
"name": "python3"
|
| 114 |
+
},
|
| 115 |
+
"language_info": {
|
| 116 |
+
"codemirror_mode": {
|
| 117 |
+
"name": "ipython",
|
| 118 |
+
"version": 3
|
| 119 |
+
},
|
| 120 |
+
"file_extension": ".py",
|
| 121 |
+
"mimetype": "text/x-python",
|
| 122 |
+
"name": "python",
|
| 123 |
+
"nbconvert_exporter": "python",
|
| 124 |
+
"pygments_lexer": "ipython3",
|
| 125 |
+
"version": "3.12.7"
|
| 126 |
+
}
|
| 127 |
+
},
|
| 128 |
+
"nbformat": 4,
|
| 129 |
+
"nbformat_minor": 5
|
| 130 |
+
}
|
notebook/pdf_loader.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
notebook/pdf_loader2.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pyproject.toml
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[project]
|
| 2 |
+
name = "rag-pipeline"
|
| 3 |
+
version = "0.1.0"
|
| 4 |
+
description = "Add your description here"
|
| 5 |
+
readme = "README.md"
|
| 6 |
+
requires-python = ">=3.12"
|
| 7 |
+
dependencies = [
|
| 8 |
+
"chromadb>=1.3.4",
|
| 9 |
+
"faiss-cpu>=1.12.0",
|
| 10 |
+
"fastapi>=0.121.0",
|
| 11 |
+
"ipykernel>=7.1.0",
|
| 12 |
+
"langchain>=1.0.3",
|
| 13 |
+
"langchain-community>=0.4.1",
|
| 14 |
+
"langchain-core>=1.0.3",
|
| 15 |
+
"langchain-groq>=1.0.0",
|
| 16 |
+
"langchain-text-splitters>=1.0.0",
|
| 17 |
+
"pymupdf>=1.26.6",
|
| 18 |
+
"pypdf>=6.1.3",
|
| 19 |
+
"python-dotenv>=1.2.1",
|
| 20 |
+
"python-multipart>=0.0.20",
|
| 21 |
+
"sentence-transformers>=5.1.2",
|
| 22 |
+
"streamlit>=1.51.0",
|
| 23 |
+
"tqdm>=4.67.1",
|
| 24 |
+
"uvicorn>=0.38.0",
|
| 25 |
+
]
|
requirements.txt
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
langchain
|
| 2 |
+
langchain-core
|
| 3 |
+
langchain-community
|
| 4 |
+
pypdf
|
| 5 |
+
pymupdf
|
| 6 |
+
tqdm
|
| 7 |
+
sentence-transformers
|
| 8 |
+
faiss-cpu
|
| 9 |
+
chromadb
|
| 10 |
+
langchain-text-splitters
|
| 11 |
+
langchain-groq
|
| 12 |
+
python-dotenv
|
| 13 |
+
streamlit
|
| 14 |
+
fastapi
|
| 15 |
+
uvicorn
|
| 16 |
+
python-multipart
|
src/__pycache__/rag_pipeline.cpython-310.pyc
ADDED
|
Binary file (10.2 kB). View file
|
|
|
src/__pycache__/rag_pipeline.cpython-312.pyc
ADDED
|
Binary file (19.7 kB). View file
|
|
|
src/rag_pipeline.py
ADDED
|
@@ -0,0 +1,571 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
RAG Pipeline with Groq LLM
|
| 3 |
+
This module contains all the components for a Retrieval-Augmented Generation pipeline
|
| 4 |
+
using Groq LLM, including embedding models, vector store, retriever, and RAG functions.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import uuid
|
| 9 |
+
from typing import List, Dict, Any, Optional
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
from sentence_transformers import SentenceTransformer
|
| 13 |
+
import chromadb
|
| 14 |
+
from langchain_groq import ChatGroq
|
| 15 |
+
from langchain_community.document_loaders import PyPDFLoader, PyMuPDFLoader, DirectoryLoader
|
| 16 |
+
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 17 |
+
from dotenv import load_dotenv
|
| 18 |
+
|
| 19 |
+
# Load environment variables
|
| 20 |
+
load_dotenv()
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def process_pdfs_in_directory(directory_path: str):
|
| 24 |
+
"""
|
| 25 |
+
Load all PDF files from a directory.
|
| 26 |
+
|
| 27 |
+
Args:
|
| 28 |
+
directory_path: Path to the directory containing PDF files
|
| 29 |
+
|
| 30 |
+
Returns:
|
| 31 |
+
List of Document objects loaded from PDFs
|
| 32 |
+
"""
|
| 33 |
+
pdf_loader = DirectoryLoader(
|
| 34 |
+
directory_path,
|
| 35 |
+
glob="**/*.pdf",
|
| 36 |
+
loader_cls=PyMuPDFLoader,
|
| 37 |
+
show_progress=True,
|
| 38 |
+
)
|
| 39 |
+
documents = pdf_loader.load()
|
| 40 |
+
return documents
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def documents_chunking(
|
| 44 |
+
documents: List[Any],
|
| 45 |
+
chunk_size: int = 800,
|
| 46 |
+
chunk_overlap: int = 200
|
| 47 |
+
) -> List[Any]:
|
| 48 |
+
"""
|
| 49 |
+
Split documents into smaller chunks for better retrieval.
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
documents: List of Document objects to chunk
|
| 53 |
+
chunk_size: Size of each chunk in characters
|
| 54 |
+
chunk_overlap: Number of characters to overlap between chunks
|
| 55 |
+
|
| 56 |
+
Returns:
|
| 57 |
+
List of chunked Document objects
|
| 58 |
+
"""
|
| 59 |
+
splitter = RecursiveCharacterTextSplitter(
|
| 60 |
+
chunk_size=chunk_size,
|
| 61 |
+
chunk_overlap=chunk_overlap,
|
| 62 |
+
)
|
| 63 |
+
# Basic cleanup before splitting - normalize whitespace
|
| 64 |
+
for d in documents:
|
| 65 |
+
d.page_content = " ".join(d.page_content.split())
|
| 66 |
+
chunks = splitter.split_documents(documents)
|
| 67 |
+
print(f"Processed {len(chunks)} chunks")
|
| 68 |
+
return chunks
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class EmbeddingModel:
|
| 72 |
+
"""Manages sentence transformer models for generating embeddings."""
|
| 73 |
+
|
| 74 |
+
def __init__(self, model_name: str = "all-MiniLM-L6-v2"):
|
| 75 |
+
"""
|
| 76 |
+
Initialize the embedding model.
|
| 77 |
+
|
| 78 |
+
Args:
|
| 79 |
+
model_name: Name of the sentence transformer model to use
|
| 80 |
+
"""
|
| 81 |
+
self.model_name = model_name
|
| 82 |
+
self.model = None
|
| 83 |
+
self.load_model()
|
| 84 |
+
|
| 85 |
+
def load_model(self):
|
| 86 |
+
"""Load the sentence transformer model."""
|
| 87 |
+
self.model = SentenceTransformer(self.model_name)
|
| 88 |
+
print(f"Loaded model: {self.model_name}")
|
| 89 |
+
print(f"Embedding dimension: {self.model.get_sentence_embedding_dimension()}")
|
| 90 |
+
|
| 91 |
+
def generate_embedding(self, text: List[str]) -> np.ndarray:
|
| 92 |
+
"""
|
| 93 |
+
Generate embeddings for a list of texts.
|
| 94 |
+
|
| 95 |
+
Args:
|
| 96 |
+
text: List of text strings to embed
|
| 97 |
+
|
| 98 |
+
Returns:
|
| 99 |
+
numpy array of embeddings with shape (N, D) where N is number of texts
|
| 100 |
+
and D is embedding dimension
|
| 101 |
+
"""
|
| 102 |
+
return self.model.encode(
|
| 103 |
+
text,
|
| 104 |
+
normalize_embeddings=True, # ensures cosine distance in [0,2], similarity = dot
|
| 105 |
+
show_progress_bar=True
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class VectorStore:
|
| 110 |
+
"""Manages ChromaDB vector store for document embeddings."""
|
| 111 |
+
|
| 112 |
+
def __init__(self, collection_name: str = "pdf_documents", persist_directory: str = "./data/vector_store"):
|
| 113 |
+
"""
|
| 114 |
+
Initialize the vector store.
|
| 115 |
+
|
| 116 |
+
Args:
|
| 117 |
+
collection_name: Name of the ChromaDB collection
|
| 118 |
+
persist_directory: Directory to persist the vector store
|
| 119 |
+
"""
|
| 120 |
+
self.collection_name = collection_name
|
| 121 |
+
self.persist_directory = persist_directory
|
| 122 |
+
self.client = None # chromadb.PersistentClient
|
| 123 |
+
self.collection = None # chroma Collection
|
| 124 |
+
self.initialize_vector_store()
|
| 125 |
+
|
| 126 |
+
def initialize_vector_store(self):
|
| 127 |
+
"""Set up ChromaDB client and collection."""
|
| 128 |
+
os.makedirs(self.persist_directory, exist_ok=True)
|
| 129 |
+
self.client = chromadb.PersistentClient(path=self.persist_directory)
|
| 130 |
+
self.collection = self.client.get_or_create_collection(
|
| 131 |
+
name=self.collection_name,
|
| 132 |
+
metadata={"description": "PDF Documents Embeddings Collection"},
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
print(f"Vector store initialized with collection: {self.collection_name}")
|
| 136 |
+
print(f"Existing number of documents in collection: {self.collection.count()}")
|
| 137 |
+
|
| 138 |
+
def add_documents(self, documents: List[Any], embeddings: np.ndarray, ids: Optional[List[str]] = None):
|
| 139 |
+
"""
|
| 140 |
+
Add documents and their embeddings to the vector store.
|
| 141 |
+
|
| 142 |
+
Args:
|
| 143 |
+
documents: List of document objects (must have page_content and metadata attributes)
|
| 144 |
+
embeddings: numpy array of embeddings with shape (N, D)
|
| 145 |
+
ids: Optional list of IDs for documents. If None, UUIDs will be generated
|
| 146 |
+
"""
|
| 147 |
+
if embeddings is None or len(documents) == 0:
|
| 148 |
+
raise ValueError("documents and embeddings must be non-empty.")
|
| 149 |
+
if embeddings.ndim != 2:
|
| 150 |
+
raise ValueError(f"embeddings must be 2D (N, D); got shape {embeddings.shape}")
|
| 151 |
+
if len(documents) != embeddings.shape[0]:
|
| 152 |
+
raise ValueError("Number of documents and embeddings must be the same.")
|
| 153 |
+
|
| 154 |
+
n = len(documents)
|
| 155 |
+
ids = ids or [str(uuid.uuid4()) for _ in range(n)]
|
| 156 |
+
if len(ids) != n:
|
| 157 |
+
raise ValueError("Length of ids must match number of documents.")
|
| 158 |
+
|
| 159 |
+
texts = [doc.page_content for doc in documents]
|
| 160 |
+
metadatas = []
|
| 161 |
+
for i, doc in enumerate(documents):
|
| 162 |
+
md = dict(getattr(doc, "metadata", {}) or {})
|
| 163 |
+
md["doc_index"] = i
|
| 164 |
+
md["content_length"] = len(doc.page_content)
|
| 165 |
+
metadatas.append(md)
|
| 166 |
+
|
| 167 |
+
embeddings_list = embeddings.tolist()
|
| 168 |
+
|
| 169 |
+
self.collection.add(
|
| 170 |
+
ids=ids,
|
| 171 |
+
documents=texts,
|
| 172 |
+
metadatas=metadatas,
|
| 173 |
+
embeddings=embeddings_list,
|
| 174 |
+
)
|
| 175 |
+
print(f"Added {n} items. Collection count: {self.collection.count()}")
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class RagRetriever:
|
| 179 |
+
"""Handles query-based retrieval from the vector store."""
|
| 180 |
+
|
| 181 |
+
def __init__(self, vector_store: VectorStore, embedding_manager: EmbeddingModel):
|
| 182 |
+
"""
|
| 183 |
+
Initialize the retriever.
|
| 184 |
+
|
| 185 |
+
Args:
|
| 186 |
+
vector_store: Vector store containing document embeddings
|
| 187 |
+
embedding_manager: Manager for generating query embeddings
|
| 188 |
+
"""
|
| 189 |
+
self.vector_store = vector_store
|
| 190 |
+
self.embedding_manager = embedding_manager
|
| 191 |
+
|
| 192 |
+
def retrieve(
|
| 193 |
+
self,
|
| 194 |
+
query: str,
|
| 195 |
+
top_k: int = 5,
|
| 196 |
+
score_threshold: float = 0,
|
| 197 |
+
metadata_filters: Optional[Dict[str, Any]] = None
|
| 198 |
+
) -> List[Dict[str, Any]]:
|
| 199 |
+
"""
|
| 200 |
+
Retrieve relevant documents for a query with optional metadata filtering.
|
| 201 |
+
|
| 202 |
+
Args:
|
| 203 |
+
query: The search query
|
| 204 |
+
top_k: Number of top results to return
|
| 205 |
+
score_threshold: Minimum similarity score threshold
|
| 206 |
+
metadata_filters: Optional dictionary of metadata filters (e.g., {"source": "file.pdf", "page": 1})
|
| 207 |
+
Supports filtering by any metadata field
|
| 208 |
+
|
| 209 |
+
Returns:
|
| 210 |
+
List of dictionaries containing retrieved documents and metadata
|
| 211 |
+
"""
|
| 212 |
+
try:
|
| 213 |
+
print(f"Retrieving top {top_k} documents for query: '{query}', score threshold: {score_threshold}")
|
| 214 |
+
if metadata_filters:
|
| 215 |
+
print(f"Metadata filters: {metadata_filters}")
|
| 216 |
+
|
| 217 |
+
# Check if collection has documents
|
| 218 |
+
collection_count = self.vector_store.collection.count()
|
| 219 |
+
if collection_count == 0:
|
| 220 |
+
print("Warning: Vector store collection is empty!")
|
| 221 |
+
return []
|
| 222 |
+
|
| 223 |
+
query_embedding = self.embedding_manager.generate_embedding([query])[0]
|
| 224 |
+
|
| 225 |
+
# Build where clause for metadata filtering
|
| 226 |
+
# ChromaDB requires $and operator when combining multiple conditions
|
| 227 |
+
where_clause = None
|
| 228 |
+
if metadata_filters and len(metadata_filters) > 0:
|
| 229 |
+
conditions = []
|
| 230 |
+
for key, value in metadata_filters.items():
|
| 231 |
+
# Skip None, empty dict, empty list, or empty string
|
| 232 |
+
if value is None:
|
| 233 |
+
continue
|
| 234 |
+
if isinstance(value, dict) and len(value) == 0:
|
| 235 |
+
continue
|
| 236 |
+
if isinstance(value, list):
|
| 237 |
+
# Support "in" operator for multiple values
|
| 238 |
+
if len(value) == 0:
|
| 239 |
+
continue
|
| 240 |
+
# Filter out None values from list
|
| 241 |
+
value = [v for v in value if v is not None]
|
| 242 |
+
if len(value) == 0:
|
| 243 |
+
continue
|
| 244 |
+
elif len(value) == 1:
|
| 245 |
+
# Single value in list, use direct equality
|
| 246 |
+
conditions.append({key: value[0]})
|
| 247 |
+
else:
|
| 248 |
+
# Multiple values, use $in
|
| 249 |
+
conditions.append({key: {"$in": value}})
|
| 250 |
+
elif isinstance(value, str) and len(value.strip()) == 0:
|
| 251 |
+
# Skip empty strings
|
| 252 |
+
continue
|
| 253 |
+
else:
|
| 254 |
+
# Single value (int, str, etc.) - ensure it's not empty
|
| 255 |
+
conditions.append({key: value})
|
| 256 |
+
|
| 257 |
+
# ChromaDB requires exactly one operator at top level
|
| 258 |
+
# If multiple conditions, wrap in $and; if single, use directly
|
| 259 |
+
if len(conditions) == 0:
|
| 260 |
+
where_clause = None
|
| 261 |
+
elif len(conditions) == 1:
|
| 262 |
+
where_clause = conditions[0]
|
| 263 |
+
else:
|
| 264 |
+
# Multiple conditions - MUST use $and operator
|
| 265 |
+
where_clause = {"$and": conditions}
|
| 266 |
+
|
| 267 |
+
if where_clause:
|
| 268 |
+
print(f"Built where clause: {where_clause}")
|
| 269 |
+
|
| 270 |
+
query_params = {
|
| 271 |
+
"query_embeddings": [query_embedding.tolist()],
|
| 272 |
+
"n_results": min(top_k * 2, collection_count), # Get more results to account for filtering
|
| 273 |
+
}
|
| 274 |
+
if where_clause:
|
| 275 |
+
# Final validation: ensure where_clause has exactly one operator at top level
|
| 276 |
+
# ChromaDB requires this format
|
| 277 |
+
if isinstance(where_clause, dict):
|
| 278 |
+
# Check if it's already properly formatted (has $and, $or, or single key)
|
| 279 |
+
top_level_keys = list(where_clause.keys())
|
| 280 |
+
if len(top_level_keys) > 1 and '$and' not in top_level_keys and '$or' not in top_level_keys:
|
| 281 |
+
# Multiple keys without operator - this is the error case
|
| 282 |
+
# Rebuild it properly
|
| 283 |
+
conditions = [{k: v} for k, v in where_clause.items()]
|
| 284 |
+
where_clause = {"$and": conditions}
|
| 285 |
+
print(f"Fixed where clause format: {where_clause}")
|
| 286 |
+
|
| 287 |
+
query_params["where"] = where_clause
|
| 288 |
+
print(f"Final where clause being sent: {query_params.get('where')}")
|
| 289 |
+
|
| 290 |
+
results = self.vector_store.collection.query(**query_params)
|
| 291 |
+
retrieved_items = []
|
| 292 |
+
|
| 293 |
+
if results.get('documents') and results['documents'][0]:
|
| 294 |
+
documents = results['documents'][0]
|
| 295 |
+
metadatas = results['metadatas'][0]
|
| 296 |
+
distances = results['distances'][0]
|
| 297 |
+
ids = results['ids'][0]
|
| 298 |
+
|
| 299 |
+
for i, (doc, md, dist, id_) in enumerate(zip(documents, metadatas, distances, ids)):
|
| 300 |
+
score = 1 - dist
|
| 301 |
+
# When score_threshold is 0, include all results (even negative scores)
|
| 302 |
+
# This handles cases where cosine similarity is negative (dissimilar documents)
|
| 303 |
+
if score_threshold == 0 or score >= score_threshold:
|
| 304 |
+
retrieved_items.append({
|
| 305 |
+
"id": id_,
|
| 306 |
+
"document": doc,
|
| 307 |
+
"metadata": md,
|
| 308 |
+
"score": score,
|
| 309 |
+
"distance": dist,
|
| 310 |
+
"rank": i + 1,
|
| 311 |
+
})
|
| 312 |
+
print(f"Retrieved doc {i}: ID={id_}, Score={score:.4f}, Distance={dist:.4f}")
|
| 313 |
+
else:
|
| 314 |
+
print(f"Doc {i} below threshold: ID={id_}, Score={score:.4f}, Distance={dist:.4f}")
|
| 315 |
+
else:
|
| 316 |
+
print(f"No documents retrieved. Collection has {collection_count} documents.")
|
| 317 |
+
|
| 318 |
+
return retrieved_items
|
| 319 |
+
except Exception as e:
|
| 320 |
+
print(f"Error in retrieve: {str(e)}")
|
| 321 |
+
raise
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def create_groq_llm(
|
| 325 |
+
model_name: str = "llama-3.1-8b-instant",
|
| 326 |
+
temperature: float = 0.1,
|
| 327 |
+
max_tokens: int = 1024
|
| 328 |
+
) -> ChatGroq:
|
| 329 |
+
"""
|
| 330 |
+
Create and configure a Groq LLM instance.
|
| 331 |
+
|
| 332 |
+
Args:
|
| 333 |
+
model_name: Name of the Groq model to use
|
| 334 |
+
temperature: Sampling temperature (0.0 to 1.0)
|
| 335 |
+
max_tokens: Maximum tokens in the response
|
| 336 |
+
|
| 337 |
+
Returns:
|
| 338 |
+
Configured ChatGroq instance
|
| 339 |
+
"""
|
| 340 |
+
groq_api_key = os.getenv("GROQ_API_KEY")
|
| 341 |
+
if not groq_api_key:
|
| 342 |
+
raise ValueError("GROQ_API_KEY not found in environment variables. Please set it in .env file.")
|
| 343 |
+
|
| 344 |
+
return ChatGroq(
|
| 345 |
+
model_name=model_name,
|
| 346 |
+
api_key=groq_api_key,
|
| 347 |
+
temperature=temperature,
|
| 348 |
+
max_tokens=max_tokens,
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def rag_pipeline(query: str, retriever: RagRetriever, llm: ChatGroq, top_k: int = 5) -> str:
|
| 353 |
+
"""
|
| 354 |
+
Simple RAG pipeline that retrieves context and generates an answer.
|
| 355 |
+
|
| 356 |
+
Args:
|
| 357 |
+
query: User query
|
| 358 |
+
retriever: RagRetriever instance
|
| 359 |
+
llm: ChatGroq LLM instance
|
| 360 |
+
top_k: Number of documents to retrieve
|
| 361 |
+
|
| 362 |
+
Returns:
|
| 363 |
+
Generated answer as a string
|
| 364 |
+
"""
|
| 365 |
+
results = retriever.retrieve(query, top_k=top_k)
|
| 366 |
+
context = "\n".join([r["document"] for r in results]) if results else ""
|
| 367 |
+
if not context:
|
| 368 |
+
return "No relevant information found in the context."
|
| 369 |
+
|
| 370 |
+
prompt = f"""Use the following context to answer the question.
|
| 371 |
+
Context: {context}
|
| 372 |
+
Question: {query}
|
| 373 |
+
Answer:"""
|
| 374 |
+
response = llm.invoke(prompt)
|
| 375 |
+
return response.content
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
def summarize_answer(answer: str, llm: ChatGroq, max_length: int = 150) -> str:
|
| 379 |
+
"""
|
| 380 |
+
Extract important/key points from an answer to keep memory concise.
|
| 381 |
+
|
| 382 |
+
Args:
|
| 383 |
+
answer: Full answer text
|
| 384 |
+
llm: LLM instance for summarization
|
| 385 |
+
max_length: Maximum length of summary
|
| 386 |
+
|
| 387 |
+
Returns:
|
| 388 |
+
Concise summary of key points
|
| 389 |
+
"""
|
| 390 |
+
if len(answer) <= max_length:
|
| 391 |
+
return answer
|
| 392 |
+
|
| 393 |
+
prompt = f"""Extract the key points and important information from this answer.
|
| 394 |
+
Keep it concise (max {max_length} characters). Focus on facts, conclusions, and actionable information.
|
| 395 |
+
|
| 396 |
+
Answer:
|
| 397 |
+
{answer}
|
| 398 |
+
|
| 399 |
+
Key points:"""
|
| 400 |
+
|
| 401 |
+
try:
|
| 402 |
+
response = llm.invoke(prompt)
|
| 403 |
+
summary = response.content.strip()
|
| 404 |
+
return summary[:max_length] if len(summary) > max_length else summary
|
| 405 |
+
except:
|
| 406 |
+
# Fallback: return first part of answer
|
| 407 |
+
return answer[:max_length] + "..."
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def rag_pipeline_with_memory(
|
| 411 |
+
query: str,
|
| 412 |
+
retriever: RagRetriever,
|
| 413 |
+
llm: ChatGroq,
|
| 414 |
+
conversation_history: List[Dict[str, str]] = None,
|
| 415 |
+
top_k: int = 5,
|
| 416 |
+
metadata_filters: Optional[Dict[str, Any]] = None
|
| 417 |
+
) -> str:
|
| 418 |
+
"""
|
| 419 |
+
RAG pipeline with conversation memory that includes previous context.
|
| 420 |
+
|
| 421 |
+
Args:
|
| 422 |
+
query: Current user query
|
| 423 |
+
retriever: RagRetriever instance
|
| 424 |
+
llm: ChatGroq LLM instance
|
| 425 |
+
conversation_history: List of previous messages in format [{"role": "user", "content": "..."}, {"role": "assistant", "content": "..."}]
|
| 426 |
+
top_k: Number of documents to retrieve
|
| 427 |
+
metadata_filters: Optional dictionary of metadata filters (e.g., {"source": "file.pdf"})
|
| 428 |
+
|
| 429 |
+
Returns:
|
| 430 |
+
Generated answer as a string
|
| 431 |
+
"""
|
| 432 |
+
# Retrieve with score_threshold=0 to get all results, even with low similarity
|
| 433 |
+
results = retriever.retrieve(
|
| 434 |
+
query,
|
| 435 |
+
top_k=top_k,
|
| 436 |
+
score_threshold=0,
|
| 437 |
+
metadata_filters=metadata_filters
|
| 438 |
+
)
|
| 439 |
+
context = "\n".join([r["document"] for r in results]) if results else ""
|
| 440 |
+
|
| 441 |
+
if not context:
|
| 442 |
+
# Check if vector store has any documents
|
| 443 |
+
collection_count = retriever.vector_store.collection.count()
|
| 444 |
+
if collection_count == 0:
|
| 445 |
+
return "No documents have been processed yet. Please upload and process documents first."
|
| 446 |
+
else:
|
| 447 |
+
return f"No relevant information found in the context. The vector store has {collection_count} documents, but none matched your query. Try rephrasing your question or check if the documents contain the information you're looking for."
|
| 448 |
+
|
| 449 |
+
# Build conversation history string (use concise versions for memory efficiency)
|
| 450 |
+
history_text = ""
|
| 451 |
+
if conversation_history:
|
| 452 |
+
history_text = "\n\nPrevious conversation (key points):\n"
|
| 453 |
+
for msg in conversation_history[-6:]: # Keep last 6 messages (3 exchanges)
|
| 454 |
+
role = msg.get("role", "user")
|
| 455 |
+
if role == "user":
|
| 456 |
+
# Store full user query
|
| 457 |
+
content = msg.get("content", "")
|
| 458 |
+
history_text += f"User: {content}\n"
|
| 459 |
+
elif role == "assistant":
|
| 460 |
+
# Use concise version if available, otherwise full content
|
| 461 |
+
content = msg.get("concise", msg.get("content", ""))
|
| 462 |
+
history_text += f"Assistant: {content}\n"
|
| 463 |
+
|
| 464 |
+
# Build prompt with context and conversation history
|
| 465 |
+
prompt = f"""Use the following context from the documents to answer the question.
|
| 466 |
+
{history_text}
|
| 467 |
+
Current question: {query}
|
| 468 |
+
|
| 469 |
+
Context from documents:
|
| 470 |
+
{context}
|
| 471 |
+
|
| 472 |
+
Based on the context above and the conversation history, provide a helpful answer. If the question refers to something from the previous conversation, use that context along with the document context.
|
| 473 |
+
Answer:"""
|
| 474 |
+
|
| 475 |
+
response = llm.invoke(prompt)
|
| 476 |
+
return response.content
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
# def rag_advanced(
|
| 480 |
+
# query: str,
|
| 481 |
+
# retriever: RagRetriever,
|
| 482 |
+
# llm: ChatGroq,
|
| 483 |
+
# top_k: int = 5,
|
| 484 |
+
# min_score: float = 0.2,
|
| 485 |
+
# return_context: bool = False
|
| 486 |
+
# ) -> Dict[str, Any]:
|
| 487 |
+
# """
|
| 488 |
+
# Advanced RAG pipeline with extra features:
|
| 489 |
+
# - Returns answer, sources, confidence score, and optionally full context.
|
| 490 |
+
|
| 491 |
+
# Args:
|
| 492 |
+
# query: User query
|
| 493 |
+
# retriever: RagRetriever instance
|
| 494 |
+
# llm: ChatGroq LLM instance
|
| 495 |
+
# top_k: Number of documents to retrieve
|
| 496 |
+
# min_score: Minimum similarity score threshold
|
| 497 |
+
# return_context: Whether to include full context in the response
|
| 498 |
+
|
| 499 |
+
# Returns:
|
| 500 |
+
# Dictionary containing:
|
| 501 |
+
# - answer: Generated answer
|
| 502 |
+
# - sources: List of source documents with metadata
|
| 503 |
+
# - confidence: Maximum similarity score
|
| 504 |
+
# - context: Full context (if return_context=True)
|
| 505 |
+
# """
|
| 506 |
+
# results = retriever.retrieve(query, top_k=top_k, score_threshold=min_score)
|
| 507 |
+
# if not results:
|
| 508 |
+
# return {
|
| 509 |
+
# 'answer': 'No relevant context found.',
|
| 510 |
+
# 'sources': [],
|
| 511 |
+
# 'confidence': 0.0,
|
| 512 |
+
# 'context': ''
|
| 513 |
+
# }
|
| 514 |
+
|
| 515 |
+
# # Prepare context and sources
|
| 516 |
+
# context = "\n\n".join([doc['document'] for doc in results])
|
| 517 |
+
# sources = [{
|
| 518 |
+
# 'source': doc['metadata'].get('source_file', doc['metadata'].get('source', 'unknown')),
|
| 519 |
+
# 'page': doc['metadata'].get('page', 'unknown'),
|
| 520 |
+
# 'score': doc['score'],
|
| 521 |
+
# 'preview': doc['document'][:300] + '...'
|
| 522 |
+
# } for doc in results]
|
| 523 |
+
# confidence = max([doc['score'] for doc in results])
|
| 524 |
+
|
| 525 |
+
# # Generate answer
|
| 526 |
+
# prompt = f"""Use the following context to answer the question concisely.
|
| 527 |
+
# Context:
|
| 528 |
+
# {context}
|
| 529 |
+
|
| 530 |
+
# Question: {query}
|
| 531 |
+
|
| 532 |
+
# Answer:"""
|
| 533 |
+
# response = llm.invoke(prompt)
|
| 534 |
+
|
| 535 |
+
# output = {
|
| 536 |
+
# 'answer': response.content,
|
| 537 |
+
# 'sources': sources,
|
| 538 |
+
# 'confidence': confidence
|
| 539 |
+
# }
|
| 540 |
+
# if return_context:
|
| 541 |
+
# output['context'] = context
|
| 542 |
+
# return output
|
| 543 |
+
|
| 544 |
+
|
| 545 |
+
# Example usage (commented out)
|
| 546 |
+
"""
|
| 547 |
+
if __name__ == "__main__":
|
| 548 |
+
# Step 1: Load PDF documents
|
| 549 |
+
documents = process_pdfs_in_directory("../data/pdf")
|
| 550 |
+
|
| 551 |
+
# Step 2: Chunk documents
|
| 552 |
+
chunked_documents = documents_chunking(documents, chunk_size=800, chunk_overlap=200)
|
| 553 |
+
|
| 554 |
+
# Step 3: Initialize components
|
| 555 |
+
embedding_manager = EmbeddingModel()
|
| 556 |
+
vectorstore = VectorStore()
|
| 557 |
+
|
| 558 |
+
# Step 4: Generate embeddings and add to vector store
|
| 559 |
+
texts = [doc.page_content for doc in chunked_documents]
|
| 560 |
+
embeddings = embedding_manager.generate_embedding(texts)
|
| 561 |
+
vectorstore.add_documents(documents=chunked_documents, embeddings=embeddings)
|
| 562 |
+
|
| 563 |
+
# Step 5: Initialize retriever and LLM
|
| 564 |
+
retriever = RagRetriever(vector_store=vectorstore, embedding_manager=embedding_manager)
|
| 565 |
+
llm = create_groq_llm()
|
| 566 |
+
|
| 567 |
+
# Step 6: Use RAG pipeline
|
| 568 |
+
answer = rag_pipeline("What is attention?", retriever, llm)
|
| 569 |
+
print(answer)
|
| 570 |
+
"""
|
| 571 |
+
|
uv.lock
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|