Blame

721650 Rushikesh Jagdale 2025-10-15 05:32:29 1
# LLD
2
edbf23 Prashant Kumar 2025-10-15 08:51:06 3
## 1. Project Layout
4
5
The project follows a **modular and layered architecture** designed for scalability, maintainability, and separation of concerns.
6
The **backend** is implemented using **FastAPI**, with distinct folders for models, schemas, services, routes, utilities, and background workers.
7
8
Each layer has a clear responsibility:
9
10
- **Models Layer:** Contains ORM classes mapping database tables.
11
- **Schemas Layer:** Defines Pydantic models for request validation and API responses.
12
- **Service Layer:** Implements business logic (NLP, chat assistant).
13
- **Routes Layer:** Defines API endpoints exposed via FastAPI.
14
- **Utility Layer:** Includes reusable components like embedding generation, configuration, logging, and security helpers.
15
- **Worker Layer:** Handles background jobs such as scheduled chat message fetching and NLP processing.
16
17
This modular layout ensures that each component can evolve independently — for example, NLP services or integrations can scale separately from the main API.
18
19
The **frontend** is built using **React** and consumes REST APIs exposed by the FastAPI backend. It serves as the user interface for screens, chatbot interactions, and employee views.
20
16e081 Rushikesh Jagdale 2025-10-15 09:53:06 21
### Repository Structure
edbf23 Prashant Kumar 2025-10-15 08:51:06 22
23
```bash
24
/repo
25
├─ /api # FastAPI app
26
├─ main.py
27
├─ routers/
28
├─ auth.py
29
├─ chat.py
30
├─ employees.py
31
├─ models/ # ORM classes
32
└─ services/ # Business logic (NLP invocations, DB helpers)
33
├─ /workers
34
├─ telegram_worker.py
35
├─ googlechat_worker.py
36
├─ scheduler.py
37
└─ nlp_worker.py
38
├─ /nlp
39
└─ embeddings.py
40
├─ /ragsvc
41
└─ rag.py # Retrieval + prompt assembly + LLM call
42
├─ /frontend # React app
43
├── src/
44
├── components/ # Reusable UI components (cards, modals, charts)
45
├── pages/ # Dashboard and chatbot screens
46
├── services/ # API service calls
47
├── hooks/ # Custom React hooks
48
├── contexts/ # Auth and user management
49
├── assets/ # Icons, images, and theme files
50
└── utils/ # Helper functions
51
├── public/ # Static assets
52
├── package.json
53
├── vite.config.js or next.config.js
54
└── README.md
55
├─ /db
56
└─ migrations.sql
57
├─ docker-compose.yml
58
├─ Dockerfile.api
59
└─ README.md
60
```
61
62
## 2. Database Schema — SQL DDL
63
64
The database schema defines all core entities and their relationships for the MVP.
65
It is implemented in **PostgreSQL** and **pgvector** for storing text embeddings used in semantic search.
66
67
The schema captures four main domains:
68
69
### **Employee Domain**
70
- **Tables:** `employees`, `employee_tag`
71
- Manages employee profiles, departmental details, and tag associations.
72
- Defines users of the system (employees and admins) and establishes relationships between employees and tags for access control and contextual filtering.
73
74
### **Message Domain**
75
- **Tables:** `messages`
76
- Stores sanitized chat messages fetched from configured data sources.
77
- Each message is tied to an employee (sender) and a data source (Telegram or Google Chat), and includes an embedding vector for semantic search.
78
79
### **Tag Domain**
80
- **Tables:** `tags`
81
- Defines organizational tags or categories such as projects, teams, or topics.
82
- Tags serve as contextual identifiers used to categorize employees, data sources, and messages.
83
84
### **Data Source Domain**
85
- **Tables:** `data_sources`
86
- Represents external chat integrations (Google Chat or Telegram groups).
87
- Each data source is linked to a specific tag and acts as an entry point for message ingestion.
88
- Foreign key relationships use `ON DELETE CASCADE` for integrity.
89
90
> Example: Deleting a project automatically removes related skills or employees linked via `projects_employee`.
91
92
---
93
16e081 Rushikesh Jagdale 2025-10-15 09:53:06 94
### **employees**
edbf23 Prashant Kumar 2025-10-15 08:51:06 95
96
```sql
97
CREATE TABLE employees (
98
id SERIAL PRIMARY KEY,
99
external_id JSONB,
100
name VARCHAR(150) NOT NULL,
101
role VARCHAR(50) NOT NULL, -- e.g., 'Java Developer'
102
dept VARCHAR(100),
103
tenure VARCHAR(50),
104
is_active BOOLEAN DEFAULT TRUE,
105
is_admin BOOLEAN DEFAULT FALSE
106
);
107
```
108
109
**Notes:**
110
- `is_admin` defines access privileges (Employee/Admin).
111
- `is_active` allows temporary deactivation without deletion.
112
113
---
114
f1abeb Rushikesh Jagdale 2025-10-15 10:05:50 115
### messages
edbf23 Prashant Kumar 2025-10-15 08:51:06 116
117
```sql
118
CREATE EXTENSION IF NOT EXISTS vector;
119
120
CREATE TABLE messages (
121
id SERIAL PRIMARY KEY,
122
employee_id INT REFERENCES employees(id) ON DELETE SET NULL,
123
data_source_id INT REFERENCES data_sources(id) ON DELETE CASCADE,
124
text TEXT NOT NULL,
125
embedding VECTOR(768), -- semantic vector for AI search
126
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
127
);
128
```
129
130
**Notes:**
131
- `embedding` uses the **pgvector** extension for similarity-based AI search.
132
- `employee_id` may be nullable if sender info is anonymized or unavailable.
133
134
---
135
f1abeb Rushikesh Jagdale 2025-10-15 10:05:50 136
### tags
edbf23 Prashant Kumar 2025-10-15 08:51:06 137
138
```sql
139
CREATE TABLE tags (
140
id SERIAL PRIMARY KEY,
141
tag_name VARCHAR(100) UNIQUE NOT NULL,
142
is_active BOOLEAN DEFAULT TRUE
143
);
144
145
```
146
147
**Notes:**
148
- Tags are assigned to employees and data sources to define context (e.g., “Project Alpha”).
149
- Uniqueness ensures no duplicate project or topic names.
150
151
---
152
f1abeb Rushikesh Jagdale 2025-10-15 10:05:50 153
### employee–tag Relationship
edbf23 Prashant Kumar 2025-10-15 08:51:06 154
155
```sql
156
CREATE TABLE employee_tag (
157
id SERIAL PRIMARY KEY,
158
employee_id INT REFERENCES employees(id) ON DELETE CASCADE,
159
tag_id INT REFERENCES tags(id) ON DELETE CASCADE,
160
is_active BOOLEAN DEFAULT TRUE
161
);
162
163
```
164
165
**Notes:**
166
- Defines a many-to-many relationship between employees and tags.
167
- `is_active` allows toggling tag assignment without deleting the record.
168
169
---
170
16e081 Rushikesh Jagdale 2025-10-15 09:53:06 171
### Data Sources
edbf23 Prashant Kumar 2025-10-15 08:51:06 172
173
```sql
174
CREATE TABLE data_sources (
175
id SERIAL PRIMARY KEY,
176
platform VARCHAR(50) NOT NULL, -- e.g., 'telegram', 'google_chat'
177
external_id VARCHAR(200) NOT NULL, -- ID from external platform
178
name VARCHAR(150) NOT NULL,
179
tag_id INT REFERENCES tags(id) ON DELETE SET NULL,
180
description TEXT,
181
is_active BOOLEAN DEFAULT TRUE
182
);
183
184
```
185
186
**Notes:**
187
- Links chat groups/spaces to organizational tags.
188
- When a tag is deleted, `tag_id` becomes `NULL` but the data source remains for reference.
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 189
2bf0b4 Rushikesh Jagdale 2025-10-15 10:28:11 190
![](./ERD.png)
3b0202 Rushikesh Jagdale 2025-10-15 10:23:55 191
192
---
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 193
## API Contracts
194
16e081 Rushikesh Jagdale 2025-10-15 09:53:06 195
### 1 GET /employee/{id}
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 196
197
**Purpose:** Retrieve a specific employee’s profile (for dashboard view).
198
199
**Request Path Parameter:**
200
201
- `id` (integer) — Employee ID.
202
203
**Response (200 OK):**
204
205
```json
206
{
207
"id": 12,
208
"external_id": {
209
"telegram": "tg_987654321",
210
"google_chat": "gc_234567890"
211
},
212
"name": "Prashant Kumar",
213
"role": "Java Developer",
214
"dept": "Engineering",
215
"tenure": "2 years",
216
"is_active": true,
217
"tags": [
218
{ "id": 3, "tag_name": "Project Alpha" },
219
{ "id": 5, "tag_name": "DevOps" }
220
]
221
}
222
```
223
### Errors
224
- `404 Not Found` — Employee ID not found.
225
- `400 Bad Request` — Invalid message structure.
226
227
---
228
16e081 Rushikesh Jagdale 2025-10-15 09:53:06 229
### 2 GET /employee
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 230
231
**Purpose:** List all employees (Admin only).
232
233
**Query Parameters:**
234
235
- `is_active` (boolean, optional)
236
- `dept` (string, optional)
237
238
**Response (200 OK):**
239
240
```json
241
[
242
{
243
"id": 12,
244
"name": "Prashant Kumar",
245
"dept": "Engineering",
246
"role": "Backend Developer",
247
"is_active": true
248
},
249
{
250
"id": 13,
251
"name": "Ritu Sharma",
252
"dept": "Engineering",
253
"role": "Full Stack Developer",
254
"is_active": false
255
}
256
]
257
```
258
16e081 Rushikesh Jagdale 2025-10-15 09:53:06 259
### 3 POST /message/bulk_ingest
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 260
261
**Purpose:** Store messages fetched from integrations (used by ingestion worker).
262
263
**Request Body:**
264
265
```json
266
{
267
"data_source_id": 2,
268
"messages": [
269
{
270
"employee_id": 12,
271
"text": "Deployment completed for Project Alpha.",
7c3355 Rushikesh Jagdale 2025-10-15 09:40:03 272
"embedding": [0.123, -0.421, 0.567]
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 273
},
274
{
275
"employee_id": 14,
276
"text": "We need to update the CI pipeline.",
7c3355 Rushikesh Jagdale 2025-10-15 09:40:03 277
"embedding": [0.998, -0.201, 0.322]
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 278
}
279
]
280
}
281
```
282
**Response (201 Created):**
283
284
```json
285
{
286
"message": "Messages successfully ingested",
287
"count": 2
288
}
289
```
290
**Errors:**
291
292
- `400 Bad Request` — Invalid message structure.
293
16e081 Rushikesh Jagdale 2025-10-15 09:53:06 294
### 4 POST /tag
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 295
296
**Purpose:** Create or update a tag (Admin only).
297
298
**Request Body:**
299
300
```json
301
{
302
"id": 3,
303
"tag_name": "Project Alpha",
304
"is_active": true
305
}
306
```
307
**Response (200 OK):**
308
309
```json
310
{
311
"message": "Tag upserted successfully",
312
"tag": { "id": 3, "tag_name": "Project Alpha", "is_active": true }
313
}
314
```
16e081 Rushikesh Jagdale 2025-10-15 09:53:06 315
### 5 GET /tag
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 316
317
**Purpose:** Retrieve all active tags.
318
319
**Response (200 OK):**
320
321
```json
322
[
323
{ "id": 3, "tag_name": "Project Alpha" },
324
{ "id": 5, "tag_name": "Knowledge Transfer" }
325
]
326
```
16e081 Rushikesh Jagdale 2025-10-15 09:53:06 327
### 6 GET /tag/{id}
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 328
329
**Purpose:** Get tag details with linked employees and data sources.
330
331
**Response (200 OK):**
332
333
```json
334
{
335
"id": 3,
336
"tag_name": "Project Alpha",
337
"employees": [
338
{ "id": 12, "name": "Prashant Kumar", "dept": "Engineering" }
339
],
340
"data_sources": [
341
{ "id": 5, "name": "Alpha Telegram Group", "platform": "telegram" }
342
]
343
}
344
```
345
16e081 Rushikesh Jagdale 2025-10-15 09:53:06 346
### 7 POST /employee_tag
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 347
348
**Purpose:** Assign or unassign a tag to an employee (Admin only).
349
350
**Request Body:**
351
352
```json
353
{
354
"employee_id": 12,
355
"tag_id": 3,
356
"is_active": true
357
}
358
```
359
**Response (200 OK):**
360
361
```json
362
{
363
"message": "Tag assignment updated successfully"
364
}
365
```
366
16e081 Rushikesh Jagdale 2025-10-15 09:53:06 367
### 8 GET /employee_tag/{employee_id}
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 368
369
**Purpose:** Fetch all tags assigned to a specific employee.
370
371
**Response (200 OK):**
372
373
```json
374
{
375
"employee_id": 12,
376
"tags": [
377
{ "id": 3, "tag_name": "Project Alpha" },
378
{ "id": 5, "tag_name": "DevOps" }
379
]
380
}
381
```
382
16e081 Rushikesh Jagdale 2025-10-15 09:53:06 383
### 9 POST /data_source
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 384
385
**Purpose:** Add or update a chat data source.
386
387
**Request Body:**
388
389
```json
390
{
391
"id": 5,
392
"platform": "telegram",
393
"external_id": "tg_123456",
394
"name": "Alpha Project Chat",
395
"tag_id": 3,
396
"description": "Telegram group for Project Alpha",
397
"is_active": true
398
}
399
```
400
**Response (200 OK):**
401
402
```json
403
{
404
"message": "Data source upserted successfully",
405
"data_source": {
406
"id": 5,
407
"platform": "telegram",
408
"name": "Alpha Project Chat",
409
"tag_id": 3,
410
"is_active": true
411
}
412
}
413
```
414
16e081 Rushikesh Jagdale 2025-10-15 09:53:06 415
### 10 GET /data_source
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 416
417
**Purpose:** List all configured data sources with their associated tags.
418
419
**Response (200 OK):**
420
421
```json
422
[
423
{
424
"id": 5,
425
"platform": "telegram",
426
"name": "Alpha Project Chat",
427
"tag": { "id": 3, "tag_name": "Project Alpha" },
428
"is_active": true
429
},
430
{
431
"id": 7,
432
"platform": "google_chat",
433
"name": "DevOps Discussion",
434
"tag": { "id": 4, "tag_name": "DevOps" },
435
"is_active": true
436
}
437
]
438
```
439
16e081 Rushikesh Jagdale 2025-10-15 09:53:06 440
### 11 GET /data_source/{id}
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 441
442
**Purpose:** Get details of a specific data source.
443
444
**Response (200 OK):**
445
446
```json
447
{
448
"id": 5,
449
"platform": "telegram",
450
"external_id": "tg_123456",
451
"name": "Alpha Project Chat",
452
"tag": { "id": 3, "tag_name": "Project Alpha" },
453
"description": "Telegram group for Project Alpha",
454
"is_active": true
455
}
456
```
457
16e081 Rushikesh Jagdale 2025-10-15 09:53:06 458
### 12 POST /chatbot/query
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 459
460
**Purpose:** Submit a natural language query to the AI assistant.
461
462
**Request Body:**
463
464
```json
465
{
466
"query": "What are the latest updates on Project Alpha?",
467
"employee_id": 12
468
}
469
```
470
**Response (200 OK):**
471
472
```json
473
{
474
"answer": "Recent messages mention deployment completion and testing for Project Alpha.",
475
"related_messages": [
476
{
477
"id": 234,
478
"text": "Deployment completed for Project Alpha.",
479
"employee": "Prashant Kumar",
480
"timestamp": "2025-10-08T09:32:15Z"
481
}
482
]
483
}
484
```
485
16e081 Rushikesh Jagdale 2025-10-15 09:53:06 486
### 13 GET /admin/overview
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 487
488
**Purpose:** Retrieve system overview for Admin dashboard.
489
490
**Response (200 OK):**
491
492
```json
493
{
494
"active_employees": 25,
495
"active_tags": 8,
496
"data_sources": [
497
{ "tag_name": "Project Alpha", "sources": 2 },
498
{ "tag_name": "DevOps", "sources": 1 }
499
],
500
"message_count_per_tag": [
501
{ "tag_name": "Project Alpha", "count": 120 },
502
{ "tag_name": "DevOps", "count": 85 }
503
]
504
}
505
```
506
507
# 4. Core Class Layers Overview
508
509
1. **Models Layer** → ORM classes (DB mapping)
510
2. **Schemas Layer** → Pydantic models for request/response validation
511
3. **Service Layer** → Business logic (NLP, Chatbot, Handover)
512
4. **Routes Layer** → FastAPI endpoints
513
5. **Utility Layer** → Common helpers (security, embeddings, config)
514
6. **Scheduler Layer** → Cron jobs
515
516
---
517
16e081 Rushikesh Jagdale 2025-10-15 09:53:06 518
## 1 Models Layer (ORM – Database Mapping)
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 519
520
Defines ORM entities using SQLAlchemy, each mapped to a database table.
521
522
### Employee
523
- **Purpose:** Represents system users and their platform identifiers.
524
- **Key Fields:** `id`, `external_ids` (JSONB), `name`, `role`, `dept`, `tenure`, `is_admin`, `is_active`.
525
526
### Message
527
- **Purpose:** Stores cleaned messages fetched from data sources.
528
- **Key Fields:** `id`, `employee_id`, `data_source_id`, `text`, `embedding`, `created_at`.
529
530
### Tag
531
- **Purpose:** Defines project or topic categories (e.g., “Project Alpha”).
532
- **Key Fields:** `id`, `tag_name`, `is_active`.
533
534
### EmployeeTag
535
- **Purpose:** Junction table linking Employee and Tag.
536
- **Key Fields:** `id`, `employee_id`, `tag_id`, `is_active`.
537
538
### DataSource
539
- **Purpose:** Represents chat integrations like Telegram or Google Chat.
540
- **Key Fields:** `id`, `platform`, `external_id`, `name`, `tag_id`, `description`, `is_active`.
541
542
---
543
16e081 Rushikesh Jagdale 2025-10-15 09:53:06 544
## 2 Schemas Layer (Pydantic Models)
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 545
546
Defines data validation and serialization classes for API input/output.
547
548
- **EmployeeBase / EmployeeResponse**
549
Purpose: Serialize employee info for API responses.
550
Fields: `id`, `name`, `role`, `dept`, `tenure`, `is_admin`, `is_active`, `external_ids`, `tags`.
551
552
- **MessageIngestRequest**
553
Purpose: Request body for bulk message ingestion.
554
Fields: `data_source_id`, `messages` (list of `{employee_id, text, embedding}`).
555
556
- **TagCreate / TagResponse**
557
Purpose: Used for tag creation and retrieval.
558
Fields: `id`, `tag_name`, `is_active`.
559
560
- **EmployeeTagRequest**
561
Purpose: Assign or unassign tag to employee.
562
Fields: `employee_id`, `tag_id`, `is_active`.
563
564
- **DataSourceRequest / DataSourceResponse**
565
Purpose: Manage chat data sources.
566
Fields: `id`, `platform`, `external_id`, `name`, `tag_id`, `description`, `is_active`.
567
568
- **ChatbotQueryRequest / ChatbotResponse**
569
Purpose: Handles chatbot input/output payloads.
570
Fields (Request): `query`, `employee_id`
571
Fields (Response): `answer`, `related_messages`
572
573
---
574
16e081 Rushikesh Jagdale 2025-10-15 09:53:06 575
## 3 Service Layer (Business Logic)
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 576
577
Implements all application logic — CRUD operations, AI processing, and integrations.
578
579
### EmployeeService
580
- **Purpose:** Manage employee CRUD and tag relationships.
581
- **Key Methods:**
582
- `get_employee(id)` – Fetch employee with tags.
583
- `list_employees(is_active)` – List all employees.
584
- `create_or_update(data)` – Upsert employee.
585
586
### TagService
587
- **Purpose:** Handle tag creation, lookup, and linking to employees or sources.
588
- **Key Methods:**
589
- `create_or_update(tag_data)`
590
- `get_tag(id)`
591
- `get_all_tags()`
592
593
### EmployeeTagService
594
- **Purpose:** Manage mappings between employees and tags.
595
- **Key Methods:**
596
- `assign_tag(employee_id, tag_id)`
597
- `get_tags_for_employee(employee_id)`
598
599
### MessageService
600
- **Purpose:** Ingest, store, and fetch messages.
601
- **Key Methods:**
602
- `bulk_ingest(messages)` – Save messages after processing.
603
- `get_by_tag(tag_id)` – Retrieve all messages under a tag.
604
605
### DataSourceService
606
- **Purpose:** Manage chat integration sources.
607
- **Key Methods:**
608
- `create_or_update(source_data)`
609
- `get_active_sources()`
610
- `get_source_details(id)`
611
612
### ChatbotService
613
- **Purpose:** Provide AI-based Q&A by semantic search.
614
- **Key Methods:**
615
- `query(text, employee_id)` – Generate embeddings, find similar messages.
616
617
---
618
16e081 Rushikesh Jagdale 2025-10-15 09:53:06 619
## 4 Routes Layer (FastAPI Endpoints)
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 620
621
Defines REST API endpoints; connects incoming requests to service methods.
622
623
- **EmployeeRouter**
624
- `GET /employee/{id}` – Fetch employee details
625
- `GET /employee` – List employees
626
627
- **MessageRouter**
628
- `POST /message/bulk_ingest` – Store processed chat messages
629
630
- **TagRouter**
631
- `POST /tag` – Create or update a tag
632
- `GET /tag` – Retrieve all tags
633
- `GET /tag/{id}` – Tag details with employees and data sources
634
635
- **EmployeeTagRouter**
636
- `POST /employee_tag` – Assign/unassign tag to employee
637
- `GET /employee_tag/{employee_id}` – Get employee’s tags
638
639
- **DataSourceRouter**
640
- `POST /data_source` – Add or update chat source
641
- `GET /data_source` – List all data sources
642
- `GET /data_source/{id}` – Fetch specific data source
643
644
- **ChatbotRouter**
645
- `POST /chatbot/query` – Handle AI question-answer queries
646
647
- **AdminRouter**
648
- `GET /admin/overview` – Returns admin dashboard summary
649
650
---
651
16e081 Rushikesh Jagdale 2025-10-15 09:53:06 652
## 5 Utility Layer (Helper Modules)
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 653
654
Provides shared functionality for embeddings, sanitization, security, and configuration.
655
656
### EmbeddingService
657
- **Purpose:** Convert text to embeddings using SentenceTransformer
658
- **Key Methods:** `generate(text)` – Returns 768-dim vector embedding
659
660
### SanitizationUtils
661
- **Purpose:** Clean raw chat messages
662
- **Key Methods:** `sanitize(text)` – Remove PII, URLs, emojis, and normalize case
663
664
### AuthUtils
665
- **Purpose:** Handle authentication and access control
666
- **Key Methods:**
667
- `validate_token(token)`
668
- `is_admin(user)`
669
670
### Config
671
- **Purpose:** Centralized configuration management
672
- **Sources:** `.env file`, environment variables
673
674
### Logger
675
- **Purpose:** Unified logging across services
676
- **Key Methods:** `info()`, `error()`, `debug()`
677
678
---
679
16e081 Rushikesh Jagdale 2025-10-15 09:53:06 680
## 6 Scheduler Layer (Cron & Background Jobs)
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 681
682
Handles periodic and background operations such as message ingestion and cleanup.
683
684
### ChatIngestionJob
685
- **Purpose:** Periodically fetch new messages from Telegram/Google Chat sources
686
- **Key Methods:** `run()` – Fetch active data sources and ingest new messages
687
688
### EmbeddingRefreshJob (Enhancement)
689
- **Purpose:** Recompute embeddings for all stored messages (if model changes)
690
- **Key Methods:** `run()` – Iterate through messages, regenerate embeddings
691
692
### CleanupJob (Enhancement)
693
- **Purpose:** Archive or delete inactive data sources and outdated messages
694
- **Key Methods:** `run()` – Perform cleanup based on retention policies
695
696
# 5. Sequence Diagrams
697
698
## Ingestion → NLP → Store
699
700
1. **Scheduler (ChatIngestionJob)** runs periodically.
701
2. **DataSourceService** fetches all active sources from the `data_sources` table.
702
3. For each source:
703
- The system fetches messages using **Telegram/Google Chat APIs**.
704
- **SanitizationUtils** cleans the text.
705
- **EmbeddingService** converts it into a semantic vector.
706
- **MessageService** stores the text + embedding in the `messages` table.
707
4. The job logs completion status.
2bf0b4 Rushikesh Jagdale 2025-10-15 10:28:11 708
709
![](./BE_Data_Ingestion_Sequence_diagram.png)
710
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 711
---
712
713
## User query → RAG
714
715
1. The **Frontend Chat UI** sends the query to `/chatbot/query` along with `employee_id`.
716
2. **ChatbotService** generates a vector embedding for the query.
717
3. **EmployeeTagService** fetches which tags this employee has access to.
718
4. **MessageService** performs a vector similarity search within messages linked to those tags.
719
5. The **LLM** (e.g., OpenAI GPT / local model) generates a summarized, context-aware response.
720
6. The system returns both:
721
- `answer` → generated explanation or summary.
722
- `related_messages` → list of original message snippets.
723
7. The Frontend displays both to the user.
724
58d3f7 Prashant Kumar 2025-10-15 10:48:03 725
726
![](./FE_AI_Assistant_Sequence_diagram.png)
727
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 728
---
729
f1abeb Rushikesh Jagdale 2025-10-15 10:05:50 730
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 731
# 6. Docker Compose (MVP)
732
733
**docker-compose.yml (trimmed)**
734
735
```yaml
736
version: "3.9"
737
738
services:
739
# -------------------------------
740
# PostgreSQL Database
741
# -------------------------------
742
db:
743
image: postgres:15
744
container_name: knowledge_db
745
restart: always
746
environment:
747
POSTGRES_USER: postgres
748
POSTGRES_PASSWORD: postgres
749
POSTGRES_DB: knowledge_assistant
750
ports:
751
- "5432:5432"
752
volumes:
753
- db_data:/var/lib/postgresql/data
754
- ./db/init.sql:/docker-entrypoint-initdb.d/init.sql
755
healthcheck:
756
test: ["CMD-SHELL", "pg_isready -U postgres"]
757
interval: 10s
758
timeout: 5s
759
retries: 5
760
761
# -------------------------------
762
# FastAPI Backend (Main API)
763
# -------------------------------
764
api:
765
build: ./backend
766
container_name: knowledge_api
767
restart: always
768
depends_on:
769
db:
770
condition: service_healthy
771
environment:
772
DATABASE_URL: postgresql+psycopg2://postgres:postgres@db:5432/knowledge_assistant
773
APP_ENV: dev
774
EMBEDDING_MODEL: all-MiniLM-L6-v2
775
ports:
776
- "8000:8000"
777
volumes:
778
- ./backend:/app
779
command: uvicorn main:app --host 0.0.0.0 --port 8000 --reload
780
781
# -------------------------------
782
# NLP Worker (Embedding + Sanitization)
783
# -------------------------------
784
nlp_worker:
785
build: ./workers
786
container_name: knowledge_nlp_worker
787
restart: always
788
depends_on:
789
db:
790
condition: service_healthy
791
environment:
792
DATABASE_URL: postgresql+psycopg2://postgres:postgres@db:5432/knowledge_assistant
793
EMBEDDING_MODEL: all-MiniLM-L6-v2
794
command: python nlp_worker.py
795
volumes:
796
- ./workers:/app
797
798
# -------------------------------
799
# Frontend (React / Next.js)
800
# -------------------------------
801
frontend:
802
build: ./frontend
803
container_name: knowledge_frontend
804
restart: always
805
depends_on:
806
- api
807
ports:
808
- "3000:3000"
809
environment:
810
NEXT_PUBLIC_API_URL: http://localhost:8000
811
volumes:
812
- ./frontend:/app
813
command: npm run dev
814
815
volumes:
816
db_data:
817
```
818
**Environment Variables (.env)**
819
820
Store secrets in a `.env` file:
821
822
```env
823
OPENAI_API_KEY=your_openai_api_key
824
DB_URL=postgresql+psycopg2://postgres:postgres@db:5432/knowledge_assistant
825
TELEGRAM_TOKEN=your_telegram_token
826
GOOGLE_CHAT_CRED=path_to_google_chat_credentials
827
```
828
# 7. Security, Privacy & RBAC
829
830
## Authentication
831
- Uses JWT-based authentication with token expiry (1 hour).
832
- Each request validated via `Authorization: Bearer <token>`.
833
- Secure credentials managed via environment variables (`.env`).
834
835
## Role-Based Access Control (RBAC)
836
837
| Role | Access |
838
|------------|--------|
839
| Admin (`is_admin=true`) | Full control — manage employees, tags, data sources, and view all data. |
840
| Employee (`is_admin=false`) | Limited access — can view only their profile, assigned tags, and chatbot results. |
841
7c3355 Rushikesh Jagdale 2025-10-15 09:40:03 842
### Data Security
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 843
- HTTPS for all communication.
844
- Database encryption at rest.
845
- Sanitization removes PII, links, and emojis before storing messages.
846
- Minimal data stored — only required employee metadata.
847
7c3355 Rushikesh Jagdale 2025-10-15 09:40:03 848
### Privacy & Logging
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 849
- Employees can only access data within their assigned tags.
850
- Admin actions (tag assignments, data source edits) are logged.
851
- No raw chat data exposed to unauthorized users.
852
7c3355 Rushikesh Jagdale 2025-10-15 09:40:03 853
### Testing & Compliance
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 854
- JWT expiry and access control verified via Pytest.
855
- Sanitization tested for PII removal.
856
- Follows privacy-by-design and principle of least privilege.
857
858
---
859
860
# 8. Testing Plan
861
862
| Type | Purpose | Tools |
863
|-------------------|--------------------------------------------------|-------------------|
864
| Unit Tests | Validate individual functions and classes (services, utils) | pytest |
865
| Integration Tests | Ensure API ↔ DB ↔ service flow works end-to-end | pytest, Docker |
866
| API Tests | Validate REST endpoints, inputs, and responses | Postman |
867
| Functional Tests | Simulate user actions (profile, tag, chatbot) | Cypress |
868
| Performance Tests | Measure API latency & embedding search speed | Locust / k6 |
869
| Security Tests | Check authentication, authorization, and data access | OWASP ZAP |
870
871
---
872
873
# 9. Monitoring
874
875
- **Application Logs:** Centralized logging using Python’s logging module for API requests, background jobs, and errors.
876
- **Health Checks:** `/health` endpoint to monitor API and DB connectivity.
877
- **Container Monitoring:** Docker health checks for `api`, `db`, and `nlp_worker` services.
878
- **Metrics (Future):** Integration with Prometheus + Grafana for API latency, ingestion rate, and message count tracking.
879
- **Alerts:** Basic email or Slack alerts for service failures or ingestion errors.
880
881
---
882
883
# 10. Implementation Priorities (1-month)
884
7c3355 Rushikesh Jagdale 2025-10-15 09:40:03 885
### Week 1 — Core Backend Setup
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 886
**Objectives:**
16e081 Rushikesh Jagdale 2025-10-15 09:53:06 887
- Define and create DB schema: `employees`, `messages`, `tags`, `employee_tag`, `data_sources`.
888
- Set up FastAPI project structure (models, schemas, routes, services).
889
- Implement JWT authentication and role-based access (`is_admin`).
890
- Build core CRUD APIs: `/employee`, `/tag`, `/employee_tag`, `/data_source`.
891
- Setup PostgreSQL + pgvector in Docker Compose.
892
- Test all endpoints via Postman.
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 893
7c3355 Rushikesh Jagdale 2025-10-15 09:40:03 894
### Week 2 — Ingestion & AI Layer
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 895
**Objectives:**
16e081 Rushikesh Jagdale 2025-10-15 09:53:06 896
Implement message ingestion pipeline:
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 897
- `/message/bulk_ingest` endpoint
898
- `nlp_worker` for sanitization (remove PII, links, emojis)
899
- Generate embeddings (SentenceTransformer)
16e081 Rushikesh Jagdale 2025-10-15 09:53:06 900
Store cleaned messages and embeddings in DB.
901
Build ChatbotService:
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 902
- Vector search for similar messages
903
- Summarize top matches (basic LLM/OpenAI API)
16e081 Rushikesh Jagdale 2025-10-15 09:53:06 904
Unit tests for message ingestion and chatbot logic
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 905
7c3355 Rushikesh Jagdale 2025-10-15 09:40:03 906
### Week 3 — Frontend & Integration
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 907
**Objectives:**
16e081 Rushikesh Jagdale 2025-10-15 09:53:06 908
Create minimal React/Next.js frontend:
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 909
- Employee Dashboard: Profile + AI Chatbot
910
- Admin Dashboard: Manage Employees, Tags, Data Sources
16e081 Rushikesh Jagdale 2025-10-15 09:53:06 911
- Integrate frontend with backend APIs.
912
- Implement `/chatbot/query` UI → Backend connection.
913
- Add health checks, structured logging, and final testing.
914
- Prepare MVP demo.
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 915
7c3355 Rushikesh Jagdale 2025-10-15 09:40:03 916
### Week 4 — Testing, Fixes & Demo
3803c9 Rushikesh Jagdale 2025-10-15 09:26:27 917
**Objectives:**
16e081 Rushikesh Jagdale 2025-10-15 09:53:06 918
- Conduct end-to-end system testing (API + UI + AI flow).
919
- Fix API bugs, UI alignment, and edge cases.
920
- Add basic logging, health checks, and monitoring scripts.
921
- Conduct user acceptance testing (UAT) internally.
922
- Prepare final demo build via Docker Compose.
923
- MVP presentation and walkthrough.