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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
# Dhigrowth RAG Chatbot

A Retrieval-Augmented Generation (RAG) chatbot system built for Dhigrowth, providing accurate answers based on company knowledge base using vector similarity search and fine-tuned language models.

## πŸš€ Features

- **RAG Architecture**: Combines vector similarity search with LLM generation for accurate, context-aware responses
- **Vector Database**: ChromaDB for efficient document retrieval
- **Fine-tuned Model**: Qwen2.5-0.5B model fine-tuned on Dhigrowth data
- **RESTful API**: FastAPI-based backend with comprehensive error handling
- **Input Validation**: Pydantic-based validation for robust API requests
- **Comprehensive Logging**: File and console logging for debugging and monitoring
- **Health Monitoring**: Health check endpoints for system status
- **Error Handling**: Graceful error handling with informative responses

## πŸ“‹ Table of Contents

- [Installation](#installation)
- [Project Structure](#project-structure)
- [Configuration](#configuration)
- [Usage](#usage)
- [API Documentation](#api-documentation)
- [Testing](#testing)
- [Deployment](#deployment)
- [Troubleshooting](#troubleshooting)

## πŸ› οΈ Installation

### Prerequisites

- Python 3.8 or higher
- 4GB+ RAM recommended
- 2GB+ disk space for models and embeddings

### Step 1: Clone the Repository

```bash

git clone <repository-url>

cd DHIGROWTH_RAG

```

### Step 2: Create Virtual Environment

**Windows:**

```bash

python -m venv venv

source venv/Scripts/activate

```

**Linux/Mac:**

```bash

python3 -m venv venv

source venv/bin/activate

```

### Step 3: Install Dependencies

```bash

pip install -r requirements.txt

```

### Step 4: Set Up Vector Database

Create the vector database from your data:

```bash

python src/embed_loader.py

```

This will:

- Load data from `data/dhigrowth_final_rag_ft.jsonl`
- Create embeddings using SentenceTransformer
- Store documents in ChromaDB at `./embeddings`

## πŸ“ Project Structure

```

DHIGROWTH_RAG/

β”‚

β”œβ”€β”€ app.py                      # FastAPI application

β”œβ”€β”€ config.py                   # Configuration module

β”œβ”€β”€ requirements.txt            # Python dependencies

β”œβ”€β”€ README.md                   # This file

β”‚

β”œβ”€β”€ models/                     # LLM model files

β”‚   └── Dhi_Qwen2P5_0_5B_Q4_K_M.gguf

β”‚

β”œβ”€β”€ data/                       # Training/knowledge base data

β”‚   └── dhigrowth_final_rag_ft.jsonl

β”‚

β”œβ”€β”€ embeddings/                 # ChromaDB persistent storage

β”‚   └── (auto-generated)

β”‚

└── src/                        # Source code

    β”œβ”€β”€ embed_loader.py        # Vector database creation

    β”œβ”€β”€ retriever.py            # Document retrieval module

    β”œβ”€β”€ llm_wrapper.py          # LLM model wrapper

    β”œβ”€β”€ rag_pipeline.py         # Main RAG pipeline

    └── logger_config.py        # Logging configuration

```

## βš™οΈ Configuration

Configuration is managed through environment variables or `config.py`. Create a `.env` file in the project root:

```env

# Model paths

MODEL_PATH=./models/Dhi_Qwen2P5_0_5B_Q4_K_M.gguf

EMBEDDINGS_PATH=./embeddings

DATA_PATH=./data/dhigrowth_final_rag_ft.jsonl



# Embedding model

EMBEDDING_MODEL=all-MiniLM-L6-v2



# Generation settings

MAX_TOKENS=400

TOP_K=3



# LLM settings

N_CTX=4096

TEMPERATURE=0.0

TOP_P=1.0



# Server settings

PORT=8001

```

### Configuration Options

- `MODEL_PATH`: Path to the GGUF model file
- `EMBEDDINGS_PATH`: ChromaDB storage directory
- `DATA_PATH`: Path to JSONL knowledge base file
- `EMBEDDING_MODEL`: SentenceTransformer model name
- `MAX_TOKENS`: Maximum tokens for LLM generation
- `TOP_K`: Number of documents to retrieve
- `N_CTX`: Context window size
- `TEMPERATURE`: Sampling temperature (0.0 = deterministic)
- `TOP_P`: Nucleus sampling parameter
- `PORT`: Server port (default: 8001)

## πŸš€ Usage

### Starting the API Server

```bash

# Activate virtual environment

source venv/Scripts/activate  # Windows: venv\Scripts\activate



# Start the server

uvicorn app:app --reload --port 8001

```

The API will be available at `http://localhost:8001`

### Interactive API Documentation

Once the server is running, visit:

- **Swagger UI**: http://localhost:8001/docs
- **ReDoc**: http://localhost:8001/redoc

### Using the RAG Pipeline Directly

```python

from src.rag_pipeline import rag_chat



# Ask a question

answer = rag_chat("What services does Dhigrowth offer?")

print(answer)

```

## πŸ“‘ API Documentation

### Endpoints

#### `GET /`

Root endpoint with API information.

**Response:**

```json

{

  "message": "Dhigrowth RAG Chatbot API",

  "version": "1.0.0",

  "endpoints": {

    "health": "/health",

    "ask": "/ask (POST)"

  }

}

```

#### `GET /health`

Health check endpoint.

**Response:**

```json

{

  "status": "healthy",

  "service": "Dhigrowth RAG Chatbot",

  "version": "1.0.0"

}

```

#### `POST /ask`

Ask a question to the chatbot.

**Request Body:**

```json

{

  "question": "What services does Dhigrowth offer?"

}

```

**Response:**

```json

{

  "question": "What services does Dhigrowth offer?",

  "answer": "Dhigrowth provides website development, application development, digital marketing, SEO improvement, business automation, and custom business growth strategies."

}

```

**Error Responses:**

- `400 Bad Request`: Invalid input
- `422 Unprocessable Entity`: Validation error
- `500 Internal Server Error`: Server error

### Example API Calls

**Using cURL:**

```bash

curl -X POST http://localhost:8001/ask \

  -H "Content-Type: application/json" \

  -d '{"question": "How do I book a consultation?"}'

```

**Using Python:**

```python

import requests



response = requests.post(

    "http://localhost:8001/ask",

    json={"question": "What services does Dhigrowth offer?"}

)

print(response.json())

```

**Using JavaScript:**

```javascript

fetch("http://localhost:8001/ask", {

  method: "POST",

  headers: {

    "Content-Type": "application/json",

  },

  body: JSON.stringify({

    question: "What services does Dhigrowth offer?",

  }),

})

  .then((response) => response.json())

  .then((data) => console.log(data));

```

## πŸ§ͺ Testing

### Running Tests

Test the RAG pipeline directly:

```bash

python -c "from src.rag_pipeline import rag_chat; print(rag_chat('What services does Dhigrowth offer?'))"

```

Test the API using FastAPI TestClient:

```bash

python -c "from app import app; from fastapi.testclient import TestClient; client = TestClient(app); print(client.get('/health').json())"

```

### Test Cases

The system has been tested with:

- βœ… Valid questions about Dhigrowth
- βœ… Out-of-scope questions (returns "I don't have that information")
- βœ… Input validation (empty/whitespace questions)
- βœ… Error handling

See `TEST_RESULTS.md` for detailed test results.

## 🚒 Deployment

### Option 1: Local Development

```bash

uvicorn app:app --reload --port 8001

```

### Option 2: Production with Uvicorn

```bash

uvicorn app:app --host 0.0.0.0 --port 8001 --workers 4

```

### Option 3: Docker (Recommended for Production)

Create a `Dockerfile`:

```dockerfile

FROM python:3.11-slim



WORKDIR /app



COPY requirements.txt .

RUN pip install --no-cache-dir -r requirements.txt



COPY . .



EXPOSE 8001



CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8001"]

```

Build and run:

```bash

docker build -t dhigrowth-rag .

docker run -p 8001:8001 dhigrowth-rag

```

### Option 4: Cloud Deployment

**VPS Deployment:**

1. Upload project files
2. Install dependencies
3. Run with process manager (systemd, supervisor, or PM2)
4. Configure reverse proxy (nginx)

**Platform-as-a-Service:**

- Deploy to Heroku, Railway, or Render
- Configure environment variables
- Set up persistent storage for embeddings

## πŸ”§ Troubleshooting

### Common Issues

**Issue: Model file not found**

- **Solution**: Ensure `Dhi_Qwen2P5_0_5B_Q4_K_M.gguf` is in the `models/` directory

**Issue: ChromaDB collection empty**

- **Solution**: Run `python src/embed_loader.py` to create the vector database

**Issue: Import errors**

- **Solution**: Ensure virtual environment is activated and dependencies are installed

**Issue: Port already in use**

- **Solution**: Change port: `uvicorn app:app --port 8001`

**Issue: Slow response times**

- **Solution**:
  - First request is slower (model loading)
  - Subsequent requests are faster
  - Consider using GPU for faster inference

### Logs

Check logs in `dhigrowth_rag.log` for detailed error information.

## πŸ“Š Performance

- **Model Loading**: ~2-3 seconds (first request only)
- **Embedding Model**: ~5 seconds (first request only)
- **Query Processing**: ~2-3 seconds per query
- **Vector Database**: 1,601 documents indexed

## πŸ”’ Security Considerations

- Input validation prevents injection attacks
- CORS can be configured for specific origins in production
- Consider adding authentication for production deployment
- Rate limiting recommended for public APIs

## πŸ“ License

[Add your license information here]

## πŸ‘₯ Contributing

[Add contribution guidelines if applicable]

## πŸ“§ Contact

For questions or support, contact [your contact information]

## πŸ™ Acknowledgments

- Qwen2.5 model by Alibaba Cloud
- ChromaDB for vector database
- SentenceTransformers for embeddings
- FastAPI for the web framework

---

**Version**: 1.0.0  
**Last Updated**: November 2024