File size: 24,253 Bytes
f29cc94
 
 
 
 
 
 
 
 
 
3786a3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
---
title: Advanced RAG API
emoji: πŸš€
colorFrom: blue
colorTo: indigo
sdk: docker
app_port: 8000
pinned: false
---

# GraphRAG & Knowledge Graph AI

**Assignment #10** β€” GraphRAG-powered retrieval system with Neo4j, entity extraction, graph traversal, and hybrid graph+vector search.

**Organization:** Excellence Technologies Pvt Ltd  
**Phase:** Phase 2 β€” LangChain & Advanced RAG

---

## Table of Contents

- [Architecture Overview](#architecture-overview)
- [Tech Stack](#tech-stack)
- [Features](#features)
- [Entity Types](#entity-types)
- [Relationship Types](#relationship-types)
- [System Architecture Diagram](#system-architecture-diagram)
- [Prerequisites](#prerequisites)
- [Quick Start](#quick-start)
- [Environment Variables](#environment-variables)
- [API Endpoints](#api-endpoints)
- [Neo4j Graph Schema](#neo4j-graph-schema)
- [Usage Guide](#usage-guide)
- [Testing](#testing)
- [Evaluation](#evaluation)
- [Troubleshooting](#troubleshooting)
- [Project Structure](#project-structure)

---

## Architecture Overview

```
User β†’ Next.js Frontend (localhost:3000)
         ↓
Django REST Backend (localhost:8000)
  β”œβ”€β”€ Auth (JWT) β†’ User management
  β”œβ”€β”€ Documents β†’ Upload, ingestion, status tracking
  β”œβ”€β”€ Query β†’ Graph/Vector/Hybrid retrieval + LLM answer
  β”œβ”€β”€ Graph β†’ Cypher queries, entity details, paths, stats
  β”œβ”€β”€ Communities β†’ Louvain community detection
  └── Evaluation β†’ Accuracy, faithfulness, answer relevancy
         ↓
Neo4j (bolt://localhost:7687)          ChromaDB (local/chroma_db)
  β”œβ”€β”€ Entity nodes                        └── Vector embeddings
  β”œβ”€β”€ Relationship edges
  └── Community labels
         ↓
Groq (Llama 3.3 70B) / Google (Gemini 2.0 Flash)
```

## Tech Stack

| Layer | Technology |
|-------|------------|
| **Backend** | Django 4.2, Django REST Framework, SimpleJWT |
| **Graph DB** | Neo4j 5.12 (Docker) |
| **Vector DB** | ChromaDB (local) |
| **LLM** | Groq Llama 3.3 70B (default), Gemini 2.0 Flash, NVIDIA NIM |
| **Embeddings** | sentence-transformers (`all-MiniLM-L6-v2`) |
| **Frontend** | Next.js 14, React 18, TypeScript, Tailwind CSS |
| **Graph Viz** | react-force-graph-2d (WebGL) |
| **State** | Zustand |
| **Deployment** | Docker Compose (Neo4j + Backend + Frontend) |

---

## Features

### Core Pipeline
1. **Document Upload** β€” PDF, TXT, MD, DOCX, CSV, JSON, HTML, XML (≀10MB)
2. **Automated Entity Extraction** β€” 9 entity types via LLM structured output
3. **Automated Relationship Extraction** β€” 10 relationship types with confidence scores
4. **Entity Resolution** β€” RapidFuzz fuzzy matching + LLM disambiguation
5. **Graph Construction** β€” Neo4j nodes/edges with properties

### Retrieval Modes
6. **Graph Retrieval** β€” Cypher subgraph traversal (neighborhood, multi-hop)
7. **Vector Retrieval** β€” ChromaDB cosine similarity search
8. **Hybrid Retrieval** β€” Merged graph + vector context

### Query Capabilities
9. **Natural Language Query** β€” Question β†’ answer with citations
10. **NL-to-Cypher** β€” Schema-aware text β†’ Cypher translation
11. **Multi-Hop Reasoning** β€” Up to 4-hop relationship chains
12. **Community Detection** β€” Louvain algorithm for entity clustering

### Frontend (7 Screens)
13. **Query + Graph Split View** β€” Main workspace with real-time graph
14. **Graph Explorer** β€” Force-directed visualization with search/filter
15. **Community View** β€” Community cards with graph sub-view
16. **Multi-Hop Reasoning** β€” Step-by-step reasoning path display
17. **Retrieval Comparison** β€” Side-by-side Graph vs Vector vs Hybrid
18. **Document Management** β€” Upload with progress tracking
19. **Evaluation Dashboard** β€” Metric visualization

---

## Entity Types

| # | Type | Example |
|---|------|---------|
| 1 | PERSON | "John Smith" |
| 2 | ORGANIZATION | "Google" |
| 3 | PRODUCT | "ChatGPT" |
| 4 | TECHNOLOGY | "React" |
| 5 | LOCATION | "San Francisco" |
| 6 | EVENT | "WWDC 2024" |
| 7 | DATE | "January 2024" |
| 8 | CONCEPT | "microservices" |
| 9 | DOCUMENT | "Annual Report 2024" |

## Relationship Types

| # | Type | Example |
|---|------|---------|
| 1 | WORKS_AT | Person β†’ Organization |
| 2 | MANAGES | Person β†’ Person/Project |
| 3 | PART_OF | Component β†’ System |
| 4 | DEPENDS_ON | Service β†’ Service |
| 5 | CREATED_BY | Product β†’ Person |
| 6 | LOCATED_IN | Entity β†’ Location |
| 7 | RELATED_TO | General association |
| 8 | COMPETES_WITH | Organization ↔ Organization |
| 9 | PARTNER_OF | Organization ↔ Organization |
| 10 | SUCCEEDED_BY | Event/Version β†’ Event/Version |

---

## System Architecture Diagram

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    FRONTEND (Next.js)                       β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚  β”‚  Query    β”‚ β”‚  Graph   β”‚ β”‚Community β”‚ β”‚  Retrieval   β”‚  β”‚
β”‚  β”‚  + Graph  β”‚ β”‚ Explorer β”‚ β”‚  View    β”‚ β”‚  Comparison  β”‚  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                    β”‚
β”‚  β”‚  Multi-  β”‚ β”‚Document  β”‚ β”‚Eval      β”‚                    β”‚
β”‚  β”‚  Hop     β”‚ β”‚Upload    β”‚ β”‚Dashboard β”‚                    β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                        β”‚ REST API (JWT)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                   BACKEND (Django REST)                     β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚  β”‚  Auth    β”‚ β”‚Document  β”‚ β”‚  Query   β”‚ β”‚  Graph API   β”‚  β”‚
β”‚  β”‚  (JWT)   β”‚ β”‚  CRUD    β”‚ β”‚  Engine  β”‚ β”‚  (Cypher)    β”‚  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
│  │Community │ │  NL→     │ │ Multi-   │ │  Evaluation  │  │
β”‚  β”‚Detection β”‚ β”‚Cypher    β”‚ β”‚Hop       β”‚ β”‚  Engine      β”‚  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
            β”‚                         β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚     Neo4j 5.12       β”‚ β”‚          ChromaDB                  β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚ β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚  β”‚  :Person       β”‚   β”‚ β”‚  β”‚  Vector embeddings          β”‚  β”‚
β”‚  β”‚  :Organization β”‚   β”‚ β”‚  β”‚  (all-MiniLM-L6-v2)         β”‚  β”‚
β”‚  β”‚  :Technology   β”‚   β”‚ β”‚  β”‚  cosine similarity search   β”‚  β”‚
β”‚  β”‚  :Concept      β”‚   β”‚ β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β”‚  β”‚  ... (9 types) β”‚   β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚  :WORKS_AT     β”‚   β”‚
β”‚  β”‚  :MANAGES      β”‚   β”‚
β”‚  β”‚  :DEPENDS_ON   β”‚   β”‚
β”‚  β”‚  ... (10 types)β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚  community_id  β”‚   β”‚
β”‚  β”‚  (Louvain)     β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

---

## Prerequisites

- Docker & Docker Compose
- Node.js 18+ (for local frontend dev)
- Python 3.10+ (for local backend dev)
- LLM API key (Groq, Google, or NVIDIA)

---

## Quick Start

### 1. Clone & configure

```bash
cd 07.graphrag-knowledge-ai
cp .env.example .env
# Edit .env with your API keys (at least GROQ_API_KEY or GOOGLE_API_KEY)
```

### 2. Start with Docker Compose

```bash
docker compose up --build
```

This starts:
- **Neo4j** β€” `http://localhost:7474` (browser) / `bolt://localhost:7687` (driver)
- **Backend** β€” `http://localhost:8000/api/`
- **Frontend** β€” `http://localhost:3000`

### 3. Create a user account

```bash
curl -X POST http://localhost:8000/api/auth/register/ \
  -H "Content-Type: application/json" \
  -d '{"username": "admin", "password": "admin123", "email": "admin@example.com"}'
```

### 4. Login & get JWT token

```bash
curl -X POST http://localhost:8000/api/auth/login/ \
  -H "Content-Type: application/json" \
  -d '{"username": "admin", "password": "admin123"}'
# Response: {"access": "...", "refresh": "..."}
```

### 5. Upload a document

```bash
curl -X POST http://localhost:8000/api/documents/upload/ \
  -H "Authorization: Bearer <your_access_token>" \
  -F "file=@sample_documents/sample_tech.txt"
```

### 6. Open the frontend

Navigate to `http://localhost:3000` and log in with your credentials.

---

## Environment Variables

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `SECRET_KEY` | Yes | β€” | Django secret key (50+ chars) |
| `DEBUG` | Yes | `True` | Django debug mode |
| `ALLOWED_HOSTS` | Yes | `localhost,127.0.0.1` | Comma-separated hostnames |
| `DB_ENGINE` | Yes | `sqlite` | Database engine (`sqlite` or `postgres`) |
| `NEO4J_URI` | Yes | `bolt://localhost:7687` | Neo4j bolt URI |
| `NEO4J_USERNAME` | Yes | `neo4j` | Neo4j username |
| `NEO4J_PASSWORD` | Yes | `password` | Neo4j password |
| `CHROMADB_MODE` | Yes | `local` | `local` or `cloud` |
| `CHROMADB_DIR` | Yes | `chroma_db` | ChromaDB storage directory |
| `GROQ_API_KEY` | * | β€” | Groq API key (for Llama 3.3 70B) |
| `GROQ_MODEL` | No | `llama-3.3-70b-versatile` | Groq model name |
| `GOOGLE_API_KEY` | * | β€” | Google Gemini API key |
| `GOOGLE_MODEL` | No | `gemini-2.0-flash` | Gemini model name |
| `NVIDIA_API_KEY` | * | β€” | NVIDIA NIM API key |
| `NVIDIA_MODEL` | No | `meta/llama-3.1-70b-instruct` | NVIDIA model name |
| `LANGCHAIN_TRACING_V2` | No | `false` | Enable LangSmith tracing |

*\* At least one LLM provider API key is required.*

---

## API Endpoints

### Authentication
| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/api/auth/register/` | Register new user |
| POST | `/api/auth/login/` | Login (returns JWT) |
| POST | `/api/auth/token/refresh/` | Refresh access token |

### Documents
| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/api/documents/upload/` | Upload document (runs ingestion in background) |
| GET | `/api/documents/` | List user documents |
| GET | `/api/documents/{id}/` | Get document details |
| DELETE | `/api/documents/{id}/` | Delete document + graph/vector data |

### Query
| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/api/query/` | Main query (supports `graph`, `vector`, `hybrid` modes) |
| POST | `/api/query/graph-only/` | Graph-only retrieval |
| POST | `/api/query/vector-only/` | Vector-only retrieval |
| POST | `/api/query/compare/` | Compare all 3 retrieval modes side-by-side |

### Graph
| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/api/graph/` | Get graph data (nodes + edges) |
| GET | `/api/graph/entity/{name}/` | Entity detail (neighbors, descriptions) |
| GET | `/api/graph/path/?source=X&target=Y` | Shortest path between entities |
| POST | `/api/graph/cypher/` | Execute raw Cypher query |
| GET | `/api/graph/stats/` | Graph statistics (counts, hub entities, degree centrality) |
| GET | `/api/graph/communities/` | List all communities |
| GET | `/api/graph/communities/{id}/` | Community detail (entities, subgraph) |
| GET | `/api/graph/search/?q=X` | Search entities by name |

### Evaluation
| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/api/evaluation/` | Run evaluation against stored question-answer pairs |

### Legacy
| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/api/query/cypher/` | NL-to-Cypher translation |
| POST | `/api/query/shortest-path/` | Shortest path (legacy) |

**Total: 21 endpoints**

---

## Neo4j Graph Schema

### Node Labels (9 types)
```cypher
(:Person {name, description, source_document, community_id})
(:Organization {name, description, source_document, community_id})
(:Product {name, description, source_document, community_id})
(:Technology {name, description, source_document, community_id})
(:Location {name, description, source_document, community_id})
(:Event {name, description, source_document, community_id})
(:Date {name, description, source_document, community_id})
(:Concept {name, description, source_document, community_id})
(:Document {name, description, source_document, community_id})
```

### Relationship Types (10 types)
```cypher
(:Person)-[:WORKS_AT {description, confidence}]->(:Organization)
(:Person)-[:MANAGES {description, confidence}]->(:Person)
(:Person)-[:PART_OF {description, confidence}]->(:Organization)
(:Technology)-[:DEPENDS_ON {description, confidence}]->(:Technology)
(:Product)-[:CREATED_BY {description, confidence}]->(:Person)
(:Organization)-[:LOCATED_IN {description, confidence}]->(:Location)
(:Entity)-[:RELATED_TO {description, confidence}]->(:Entity)
(:Organization)-[:COMPETES_WITH {description, confidence}]->(:Organization)
(:Organization)-[:PARTNER_OF {description, confidence}]->(:Organization)
(:Event)-[:SUCCEEDED_BY {description, confidence}]->(:Event)
```

### Indexes
```cypher
CREATE CONSTRAINT unique_entity_name IF NOT EXISTS FOR (e:Entity) REQUIRE (e.name, e.user_id) IS UNIQUE;
CREATE INDEX entity_type_idx IF NOT EXISTS FOR (e:Entity) ON (e.type);
CREATE FULLTEXT INDEX entity_description_fulltext IF NOT EXISTS FOR (e:Entity) ON EACH [e.description, e.name];
```

### Graph Schema Diagram
```mermaid
erDiagram
    PERSON ||--o{ WORKS_AT : ""
    PERSON ||--o{ MANAGES : ""
    PERSON ||--o{ PART_OF : ""
    TECHNOLOGY ||--o{ DEPENDS_ON : ""
    PRODUCT ||--o{ CREATED_BY : ""
    ORGANIZATION ||--o{ LOCATED_IN : ""
    ENTITY ||--o{ RELATED_TO : ""
    ORGANIZATION ||--o{ COMPETES_WITH : ""
    ORGANIZATION ||--o{ PARTNER_OF : ""
    EVENT ||--o{ SUCCEEDED_BY : ""
```

---

## Usage Guide

### Upload Documents
1. Navigate to **Documents** in the sidebar
2. Click **Upload** and select a file (PDF, TXT, MD, DOCX, CSV, JSON, HTML, XML)
3. Watch real-time ingestion progress (parsing β†’ chunking β†’ extraction β†’ graph building)
4. Status changes to **Completed** when done

### Query the Knowledge Graph
1. Type a natural language question in the main query bar
2. Select retrieval mode: **Graph**, **Vector**, or **Hybrid** (default)
3. View the answer with citations
4. See the multi-hop reasoning path (if applicable)
5. The graph highlights relevant entities in real-time

### Explore the Graph
1. Click **Graph Explorer** in the sidebar
2. Use **Search** to find entities by name
3. **Zoom** with scroll wheel, **pan** with click-drag
4. Click a node to view entity details in the slide-out panel
5. Use **Filter** to show/hide entity types
6. Adjust **Depth** to control traversal level

### Compare Retrieval Modes
1. Navigate to **Retrieval Comparison**
2. Enter a query
3. View side-by-side results for Graph, Vector, and Hybrid
4. Compare answer quality, response time, and context sources

### Community Detection
1. Navigate to **Communities**
2. View auto-detected entity clusters
3. Click a community to see its entities and subgraph
4. Community summaries provide thematic overviews

---

## Testing

### Backend Unit Tests
```bash
cd backend
python manage.py test graphrag.tests_comprehensive
# 112 tests, ~57 seconds
```

### Frontend E2E Tests (Playwright)
```bash
cd frontend
npm run test:e2e:install  # Install Chromium
npm run test:e2e          # Run Playwright tests
```

### API Smoke Test
```bash
# Health check
curl http://localhost:8000/api/health/

# Full flow
curl -X POST http://localhost:8000/api/auth/login/ \
  -H "Content-Type: application/json" \
  -d '{"username": "admin", "password": "admin123"}'
```

---

## Evaluation

### Automated Metrics
The evaluation endpoint computes:
- **Answer Relevancy** β€” Does the answer address the question?
- **Faithfulness** β€” Is the answer grounded in the retrieved context?
- **Context Precision** β€” How much of the context is relevant?
- **Context Recall** β€” Did we retrieve all necessary context?

### Manual Evaluation
Upload question-answer pairs via the Evaluation dashboard or directly through the API:

```bash
curl -X POST http://localhost:8000/api/evaluation/ \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{"question": "Who manages the team working on Project X?", "expected_answer": "..."}'
```

### Evaluation Results (Sample)

| Question | Graph RAG | Vector RAG | Hybrid | Winner |
|----------|-----------|------------|--------|--------|
| Who manages the team working on Project X? | John manages Alice, Alice leads Team X | Found text about management | Combined graph chain + text | **Hybrid** |
| What dependencies does the Payment Service have? | Payment→Auth→UserDB chain | Found tech docs mentioning deps | Full dependency graph | **Graph** |
| Give an overview of the organizational structure | Entity traversal of org chart | Found relevant paragraphs | Org chart + context text | **Hybrid** |
| What companies are competitors of Google? | COMPETES_WITH edges found | Text mentions competitors | Graph edges + supporting text | **Graph** |
| What skills does the manager of Team X have? | 3-hop: Team→Alice→John→Skills | Partial text match | Full reasoning chain | **Hybrid** |

**Key Finding:** Hybrid retrieval consistently outperforms single-mode retrieval on multi-hop and relationship queries. Graph retrieval excels at entity traversal questions, while Vector retrieval provides better context for conceptual/thematic queries.

### Retrieval Comparison Mode
Use the Compare screen (`/compare`) to run any query through all 3 retrieval modes simultaneously and see side-by-side results with confidence scores and response times.

---

## Troubleshooting

### Neo4j won't start
```bash
# Check if port 7687 is in use
lsof -i :7687
# Kill existing process or change port in docker-compose.yml
```

### Backend can't connect to Neo4j
```bash
# Verify Neo4j is healthy
docker compose ps neo4j
# Check Neo4j logs
docker compose logs neo4j
```

### LLM API key errors
```bash
# Verify API key is set
echo $GROQ_API_KEY
# Test the key manually
curl https://api.groq.com/openai/v1/models \
  -H "Authorization: Bearer $GROQ_API_KEY"
```

### Graph visualization is empty
- Ensure documents have been uploaded and processed
- Check ingestion status: `GET /api/documents/`
- Verify Neo4j has data: open `http://localhost:7474` and run `MATCH (n) RETURN count(n)`

### Frontend build fails
```bash
cd frontend
rm -rf node_modules .next
npm install
npm run build
```

---

## Project Structure

```
07.graphrag-knowledge-ai/
β”œβ”€β”€ docker-compose.yml              # Neo4j + Backend + Frontend
β”œβ”€β”€ .env.example                    # Environment variable template
β”œβ”€β”€ Assignment_10_GraphRAG_Knowledge_Graph_AI.md
β”‚
β”œβ”€β”€ backend/
β”‚   β”œβ”€β”€ manage.py
β”‚   β”œβ”€β”€ requirements.txt
β”‚   β”œβ”€β”€ Dockerfile
β”‚   β”œβ”€β”€ .dockerignore
β”‚   β”œβ”€β”€ graphrag_project/
β”‚   β”‚   β”œβ”€β”€ settings.py
β”‚   β”‚   β”œβ”€β”€ urls.py
β”‚   β”‚   └── wsgi.py
β”‚   β”œβ”€β”€ graphrag/
β”‚   β”‚   β”œβ”€β”€ models.py               # User, Document, QueryLog, EvaluationPair
β”‚   β”‚   β”œβ”€β”€ views.py                # 21 API endpoints
β”‚   β”‚   β”œβ”€β”€ urls.py                 # URL routing
β”‚   β”‚   β”œβ”€β”€ serializers.py          # DRF serializers
β”‚   β”‚   β”œβ”€β”€ tests_comprehensive.py  # 112 unit tests
β”‚   β”‚   β”œβ”€β”€ admin.py
β”‚   β”‚   └── services/
β”‚   β”‚       β”œβ”€β”€ llm_client.py           # Groq/Gemini/NVIDIA provider
β”‚   β”‚       β”œβ”€β”€ entity_extractor.py     # 9 entity types
β”‚   β”‚       β”œβ”€β”€ relationship_extractor.py # 10 relationship types
β”‚   β”‚       β”œβ”€β”€ entity_resolver.py      # RapidFuzz + LLM disambiguation
β”‚   β”‚       β”œβ”€β”€ graph_builder.py        # Neo4j graph construction
β”‚   β”‚       β”œβ”€β”€ neo4j_client.py         # Neo4j driver wrapper
β”‚   β”‚       β”œβ”€β”€ graph_retriever.py      # Graph-based retrieval
β”‚   β”‚       β”œβ”€β”€ vector_retriever.py     # ChromaDB vector retrieval
β”‚   β”‚       β”œβ”€β”€ hybrid_retriever.py     # Merged graph + vector
β”‚   β”‚       β”œβ”€β”€ nl_to_cypher.py         # Schema-aware NL β†’ Cypher
β”‚   β”‚       β”œβ”€β”€ multihop_reasoner.py    # Up to 4-hop chains
β”‚   β”‚       β”œβ”€β”€ community_detector.py   # Louvain algorithm
β”‚   β”‚       └── rag_chain.py            # Answer generation
β”‚
β”œβ”€β”€ frontend/
β”‚   β”œβ”€β”€ package.json
β”‚   β”œβ”€β”€ next.config.js
β”‚   β”œβ”€β”€ tsconfig.json
β”‚   β”œβ”€β”€ tailwind.config.ts
β”‚   β”œβ”€β”€ postcss.config.js
β”‚   β”œβ”€β”€ Dockerfile
β”‚   β”œβ”€β”€ .dockerignore
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”‚   β”œβ”€β”€ page.tsx               # Root (landing/dashboard)
β”‚   β”‚   β”‚   β”œβ”€β”€ layout.tsx
β”‚   β”‚   β”‚   └── globals.css
β”‚   β”‚   β”œβ”€β”€ components/
β”‚   β”‚   β”‚   β”œβ”€β”€ layout/Sidebar.tsx
β”‚   β”‚   β”‚   β”œβ”€β”€ dashboard/MainQueryView.tsx
β”‚   β”‚   β”‚   β”œβ”€β”€ graph/GraphVisualization.tsx    # react-force-graph-2d
β”‚   β”‚   β”‚   β”œβ”€β”€ graph/EntityPanel.tsx
β”‚   β”‚   β”‚   β”œβ”€β”€ query/AnswerCard.tsx
β”‚   β”‚   β”‚   β”œβ”€β”€ query/PathView.tsx
β”‚   β”‚   β”‚   β”œβ”€β”€ query/SourceToggle.tsx
β”‚   β”‚   β”‚   β”œβ”€β”€ compare/ComparisonView.tsx
β”‚   β”‚   β”‚   β”œβ”€β”€ communities/CommunityView.tsx
β”‚   β”‚   β”‚   β”œβ”€β”€ documents/DocumentUpload.tsx
β”‚   β”‚   β”‚   β”œβ”€β”€ debug/ProcessingSteps.tsx
β”‚   β”‚   β”‚   └── eval/EvaluationDashboard.tsx
β”‚   β”‚   β”œβ”€β”€ lib/
β”‚   β”‚   β”‚   β”œβ”€β”€ api.ts                   # Axios API client
β”‚   β”‚   β”‚   β”œβ”€β”€ mockData.ts              # Mock data for development
β”‚   β”‚   β”‚   └── stores.ts                # Zustand stores
β”‚   β”‚   └── types/
β”‚   β”‚       └── index.ts                 # TypeScript interfaces
β”‚
β”œβ”€β”€ eval_dataset/                   # Evaluation question-answer pairs
└── sample_documents/               # Sample documents for testing
```

---

## License

This project is built as Assignment #10 for Excellence Technologies Phase 2 training.