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 
 
 
 
 
 
 
 
 
 
d7d18e9
 
f063263
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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
---
title: Cortex RAG
sdk: docker
emoji: 🧠
colorFrom: blue
colorTo: purple
---

# Cortex RAG β€” Next-Gen Retrieval-Augmented Generation

<div align="center">

**Production-grade RAG system with dense retrieval, semantic chunking, knowledge graph integration, CRAG gating, and multi-provider LLM support.**

![Python](https://img.shields.io/badge/Python-3.10+-3776ab?logo=python&logoColor=white)
![FastAPI](https://img.shields.io/badge/FastAPI-0.100+-009688?logo=fastapi&logoColor=white)
![Docker](https://img.shields.io/badge/Docker-Ready-2496ED?logo=docker&logoColor=white)
![License](https://img.shields.io/badge/License-MIT-green)

</div>

---

## 🎯 Overview

**Cortex** is a production-ready Retrieval-Augmented Generation (RAG) framework that combines:

- **Dense Vector Search** β€” Fast, accurate document retrieval using BAAI embeddings (384-dim)
- **Semantic Chunking** β€” Intelligent split boundaries based on sentence-level cosine similarity
- **Parent-Child Chunks** β€” 256-token child chunks for precision, 1024-token parents for context
- **Multi-Strategy Retrieval** β€” Dense search, BM25 hybrid, knowledge graph traversal
- **CRAG Gating** β€” Automatic relevance assessment with fallback to web search
- **Multi-Provider LLM** β€” Support for Groq, OpenAI, NVIDIA NIM, and custom endpoints
- **Streaming Responses** β€” Real-time SSE-based answer generation with inline citations
- **Knowledge Graphs** β€” Automatic relation extraction and entity-based retrieval
- **Caching Layer** β€” Redis integration for query result caching
- **Evaluation Framework** β€” RAGAS-based RAG evaluation metrics

---

## πŸ—οΈ Architecture

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    Document Ingestion                            β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  PDF/HTML/TXT β†’ DocumentLoader β†’ SemanticChunker                 β”‚
β”‚                                       ↓                          β”‚
β”‚                   Child (~256 tokens) + Parent (~1024 tokens)    β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                        Embedding Layer                            β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  BAAI/bge-small-en-v1.5 (384-dim, L2-normalized)                β”‚
β”‚  β†’ Milvus Store (IVF_FLAT, COSINE metric)                        β”‚
β”‚  β†’ BM25 Index (keyword search)                                   β”‚
β”‚  β†’ Knowledge Graph (entities, relations, triples)                β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                       Query Processing                            β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  Dense Search (top-15) β†’ Reranking β†’ CRAG Gate                   β”‚
β”‚         ↓                                    ↓                    β”‚
β”‚  High Confidence?                    Low Confidence?             β”‚
β”‚         ↓                                    ↓                    β”‚
β”‚    Use KnowledgeBase               ⚠️ Web Search (Tavily)        β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                    LLM Generation (Streaming)                     β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  Groq Llama 3.3-70B / OpenAI GPT-4o / NVIDIA NIM / Custom        β”‚
β”‚  Process context β†’ Generate answer β†’ Extract citations           β”‚
β”‚  Stream via SSE β†’ Client receives real-time response             β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                  Frontend Interfaces                              β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  Streamlit UI (Ask/Ingest/System) | REST API (FastAPI)           β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

---

## ✨ Key Features

| Feature | Details |
|---------|---------|
| πŸ” **Dense Retrieval** | Sub-50ms semantic search via Milvus with 384-dim embeddings |
| πŸ“š **Smart Chunking** | Semantic splits + parent-child hierarchy for precision + context |
| 🧬 **Knowledge Graphs** | Automatic relation extraction (REBEL or LLM-based) |
| 🚨 **CRAG Gating** | Relevance assessment with web search fallback |
| πŸ”— **Multi-Strategy** | Dense + BM25 keyword + graph traversal combined |
| πŸ’Ύ **Redis Cache** | Query result caching with configurable TTL |
| 🌐 **Multi-Provider LLM** | Groq, OpenAI, NVIDIA NIM, Ollama, custom OpenAI-compatible |
| πŸ“Š **Evaluation** | RAGAS metrics for answer relevance, faithfulness, context precision |
| 🎨 **Streaming UI** | Real-time responses with inline citations and source cards |
| 🐳 **Docker Ready** | Full Docker Compose setup with Milvus, Redis, API, UI |

---

## πŸš€ Quick Start

### Prerequisites

- Python 3.10+
- Docker & Docker Compose (optional, for containerized setup)
- GROQ API key (default LLM provider)

### 1. Clone & Setup

```bash
# Clone repository
git clone <repo-url>
cd cortex

# Create virtual environment
python -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt
```

### 2. Environment Configuration

Create `.env` file in project root:

```bash
# LLM Providers
GROQ_API_KEY=your_groq_api_key
GROQ_MODEL=llama-3.3-70b-versatile
GROQ_TEMPERATURE=0.1

# Optional: Other LLM providers
OPENAI_API_KEY=your_openai_key
MISTRAL_API_KEY=your_mistral_key
NVIDIA_API_KEY=your_nvidia_key

# Embedding & Storage
EMBED_MODEL_NAME=BAAI/bge-small-en-v1.5
EMBED_DEVICE=cpu  # "cuda" if GPU available

# Milvus Vector Store
MILVUS_HOST=localhost
MILVUS_PORT=19530
MILVUS_COLLECTION=cortex_chunks
MILVUS_INDEX_TYPE=IVF_FLAT

# Redis Cache (optional)
REDIS_URL=redis://localhost:6379

# Retrieval
RETRIEVAL_TOP_K=15
FINAL_TOP_K=5

# CRAG (Consistency-based Retrieval Augmented Generation)
CRAG_ENABLED=true
CRAG_RELEVANCE_THRESHOLD=0.5

# Knowledge Graph
GRAPH_ENABLED=true
GRAPH_EXTRACTOR=llm-filtered  # "rebel", "llm", "rebel-filtered", "llm-filtered"
GRAPH_MAX_HOPS=2

# API
API_HOST=0.0.0.0
API_PORT=8000
```

### 3. Start Services

**Option A: Docker Compose (Recommended)**

```bash
docker-compose up -d
# API: http://localhost:8000
# Streamlit UI: http://localhost:8501
# Milvus: http://localhost:19530
```

**Option B: Local Setup**

Make sure Milvus is running:

```bash
# Using Milvus Docker (if not using compose)
docker run -d -p 19530:19530 -p 9091:9091 milvusdb/milvus:latest

# Start API
python -m uvicorn api.main:app --host 0.0.0.0 --port 8000 --reload

# In another terminal, start UI
streamlit run ui/app.py
```

### 4. Ingest Documents

**Via Streamlit UI:**
- Open http://localhost:8501
- Go to "πŸ“₯ Ingest" tab
- Upload PDF/HTML/TXT or provide directory path

**Via REST API:**

```bash
curl -X POST "http://localhost:8000/ingest" \
  -H "Content-Type: application/json" \
  -d '{
    "mode": "directory",
    "path": "/path/to/documents"
  }'
```

### 5. Ask Questions

**Via Streamlit UI:**
- Go to "πŸ” Ask" tab
- Type your question
- Watch streaming response with citations

**Via REST API:**

```bash
curl -X POST "http://localhost:8000/query" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "What is machine learning?",
    "provider": "groq",
    "top_k": 5
  }' | jq .
```

**Streaming Response:**

```bash
curl -X POST "http://localhost:8000/query/stream" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "Your question here",
    "provider": "groq"
  }'
```

---

## πŸ“‘ REST API Endpoints

### Health & Status

```http
GET /health
```

Returns system health, Milvus status, collection stats.

```json
{
  "status": "healthy",
  "milvus": {
    "connected": true,
    "collection_count": 2500,
    "index_type": "IVF_FLAT"
  }
}
```

### Document Ingestion

```http
POST /ingest
Content-Type: application/json

{
  "mode": "directory|file|upload",
  "path": "/path/to/documents",
  "chunk_size": 256,
  "overlap": 32
}
```

### Query (Blocking)

```http
POST /query
Content-Type: application/json

{
  "query": "Your question",
  "provider": "groq",
  "model": "llama-3.3-70b-versatile",
  "top_k": 5,
  "crag": true,
  "graph": true
}
```

**Response:**

```json
{
  "answer": "Answer text with citations [1][2]...",
  "chunks": [
    {
      "id": "chunk_001",
      "text": "...",
      "score": 0.87,
      "source": "document_name.pdf"
    }
  ],
  "citations": [1, 2],
  "latency_ms": 1245
}
```

### Query (Streaming)

```http
POST /query/stream
Content-Type: application/json

{
  "query": "Your question",
  "provider": "groq"
}
```

**Response:** Server-Sent Events (SSE) stream

```
data: {"type": "start"}
data: {"type": "chunk", "content": "Answer "}
data: {"type": "chunk", "content": "is "}
data: {"type": "chunk", "content": "streaming..."}
data: {"type": "citations", "citations": [1, 2]}
data: {"type": "end"}
```

### Model Information

```http
GET /providers
```

Lists all available LLM providers and models.

---

## πŸ› οΈ Configuration Guide

### Retrieval Configuration

```env
# Chunk sizes (tokens)
CHUNK_SIZE_TOKENS=256                    # Child chunk size
PARENT_CHUNK_SIZE_TOKENS=1024            # Parent chunk size
SEMANTIC_SIMILARITY_THRESHOLD=0.82       # Split boundary threshold
CHUNK_OVERLAP_TOKENS=32                  # Overlap padding

# Retrieval settings
RETRIEVAL_TOP_K=15                       # Candidates before reranking
FINAL_TOP_K=5                            # Chunks sent to LLM
```

### Embedding Configuration

```env
EMBED_MODEL_NAME=BAAI/bge-small-en-v1.5  # Model identifier
EMBED_DIM=384                             # Output dimension
EMBED_BATCH_SIZE=64                       # Batch size for processing
EMBED_DEVICE=cpu                          # cpu or cuda
```

### Milvus Configuration

```env
MILVUS_HOST=localhost
MILVUS_PORT=19530
MILVUS_COLLECTION=cortex_chunks
MILVUS_INDEX_TYPE=IVF_FLAT                # or HNSW for larger corpora
MILVUS_METRIC_TYPE=COSINE                 # Vector similarity metric
MILVUS_NLIST=128                          # clustering parameter for IVF
MILVUS_NPROBE=16                          # search parameter
```

### LLM Provider Configuration

**Groq (Default)**
```env
GROQ_API_KEY=your_key
GROQ_MODEL=llama-3.3-70b-versatile
GROQ_TEMPERATURE=0.1
GROQ_MAX_TOKENS=1024
GROQ_TIMEOUT=30
```

**OpenAI**
```env
OPENAI_API_KEY=your_key
```

**NVIDIA NIM**
```env
NVIDIA_API_KEY=your_key
```

**Custom/Ollama**
```env
CUSTOM_BASE_URL=http://localhost:11434/v1
CUSTOM_API_KEY=your_key
```

### CRAG (Consistency-based Retrieval Augmented Generation)

```env
CRAG_ENABLED=true
CRAG_RELEVANCE_THRESHOLD=0.5             # Grade boundary
TAVILY_API_KEY=your_tavily_key           # For web search fallback
```

The CRAG gate automatically assesses retrieval quality:
- **High confidence** (score β‰₯ threshold) β†’ Use knowledge base
- **Low confidence** (score < threshold) β†’ Augment with web search

### Knowledge Graph

```env
GRAPH_ENABLED=true
GRAPH_EXTRACTOR=llm-filtered             # rebel|llm|rebel-filtered|llm-filtered
GRAPH_MAX_HOPS=2                          # Traversal depth
GRAPH_PATH=/data/storage/knowledge_graph.json

# Density filtering (for "filtered" extractors)
DENSITY_TOP_FRACTION=0.30                 # Process top 30% entity-dense chunks
DENSITY_MIN_ENTITIES=2                    # Minimum entities per chunk
```

### Caching

```env
REDIS_URL=redis://localhost:6379
CACHE_TTL_SECONDS=3600                    # 1 hour
```

### Evaluation

```env
EVAL_DB_PATH=/data/storage/eval.db
```

---

## πŸ“ Project Structure

```
cortex/
β”œβ”€β”€ api/                          # FastAPI REST endpoints
β”‚   β”œβ”€β”€ main.py                   # App initialization, endpoints
β”‚   └── schemas.py                # Request/response Pydantic models
β”‚
β”œβ”€β”€ ingestion/                    # Document processing pipeline
β”‚   β”œβ”€β”€ pipeline.py               # Orchestration
β”‚   β”œβ”€β”€ document_loader.py        # PDF/HTML/TXT parsing
β”‚   β”œβ”€β”€ chunker.py                # Semantic chunking
β”‚   └── __init__.py
β”‚
β”œβ”€β”€ retrieval/                    # Multi-strategy retrieval
β”‚   β”œβ”€β”€ orchestrator.py           # Coordinate retrieval strategies
β”‚   β”œβ”€β”€ dense.py                  # Milvus vector search
β”‚   β”œβ”€β”€ bm25.py                   # Keyword search index
β”‚   β”œβ”€β”€ embedder.py               # HuggingFace embedding model
β”‚   β”œβ”€β”€ router.py                 # Query routing logic
β”‚   β”œβ”€β”€ fusion.py                 # Result fusion & reranking
β”‚   β”œβ”€β”€ graph_builder.py          # Build knowledge graphs
β”‚   β”œβ”€β”€ graph_retriever.py        # Entity-based retrieval
β”‚   β”œβ”€β”€ relation_extractors.py    # REBEL + LLM extractors
β”‚   β”œβ”€β”€ cache.py                  # Redis caching wrapper
β”‚   └── __init__.py
β”‚
β”œβ”€β”€ generation/                   # LLM generation & CRAG
β”‚   β”œβ”€β”€ generator.py              # Multi-provider LLM wrapper
β”‚   β”œβ”€β”€ crag.py                   # CRAG gate logic
β”‚   └── __init__.py
β”‚
β”œβ”€β”€ evaluation/                   # RAG evaluation metrics
β”‚   β”œβ”€β”€ ragas_eval.py             # RAGAS evaluator
β”‚   β”œβ”€β”€ store.py                  # Evaluation database
β”‚   └── __init__.py
β”‚
β”œβ”€β”€ ui/                           # Streamlit frontend
β”‚   β”œβ”€β”€ app.py                    # Main UI
β”‚   └── static/                   # (Optional) HTML/CSS/JS
β”‚
β”œβ”€β”€ data/                         # Data storage
β”‚   β”œβ”€β”€ documents/                # Input documents
β”‚   β”œβ”€β”€ storage/                  # Persistent storage
β”‚   β”‚   β”œβ”€β”€ knowledge_graph.json
β”‚   β”‚   β”œβ”€β”€ bm25_index.pkl
β”‚   β”‚   └── uploads/
β”‚   └── synthetic_knowledge_items.txt
β”‚
β”œβ”€β”€ config.py                     # Configuration & settings
β”œβ”€β”€ requirements.txt              # Python dependencies
β”œβ”€β”€ Dockerfile                    # Docker image build
β”œβ”€β”€ docker-compose.yml            # Multi-container orchestration
β”œβ”€β”€ test.py                       # Test suite
└── README.md                     # This file
```

---

## 🐳 Docker & Deployment

### Docker Compose Quick Deploy

```bash
# Start all services
docker-compose up -d

# View logs
docker-compose logs -f api

# Stop services
docker-compose down
```

**Services:**
- `milvus` β€” Vector database (port 19530)
- `redis` β€” Caching layer (port 6379)
- `api` β€” FastAPI backend (port 8000)
- `ui` β€” Streamlit frontend (port 8501)

### Environment Variables in Compose

Edit `docker-compose.yml` to customize:

```yaml
services:
  api:
    environment:
      - GROQ_API_KEY=${GROQ_API_KEY}
      - GROQ_MODEL=llama-3.3-70b-versatile
      - MILVUS_HOST=milvus
      - REDIS_URL=redis://redis:6379
      - GRAPH_EXTRACTOR=llm-filtered
```

### Production Deployment

For production, consider:

1. **Use HNSW index** instead of IVF_FLAT for better recall:
   ```env
   MILVUS_INDEX_TYPE=HNSW
   ```

2. **Enable caching** for frequently asked questions:
   ```env
   REDIS_URL=redis://redis-prod:6379
   ```

3. **Use stronger embedding model** for higher quality:
   ```env
   EMBED_MODEL_NAME=BAAI/bge-base-en-v1.5  # 768-dim, better quality
   ```

4. **Configure CRAG** for reliability:
   ```env
   CRAG_ENABLED=true
   CRAG_RELEVANCE_THRESHOLD=0.6
   TAVILY_API_KEY=your_key
   ```

---

## πŸ”„ Workflow Examples

### Example 1: Legal Document Q&A

```bash
# 1. Ingest legal documents
curl -X POST "http://localhost:8000/ingest" \
  -H "Content-Type: application/json" \
  -d '{
    "mode": "directory",
    "path": "/data/legal_documents"
  }'

# 2. Query with graph enabled for relation extraction
curl -X POST "http://localhost:8000/query" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "What are the penalties for breach of contract?",
    "provider": "groq",
    "graph": true,
    "crag": true
  }'
```

### Example 2: Research Paper Analysis

```bash
# Ingest PDF papers
python -c "
from ingestion.pipeline import IngestionPipeline
from retrieval.embedder import Embedder
from retrieval.dense import MilvusStore

embedder = Embedder()
store = MilvusStore(embedder=embedder)
pipeline = IngestionPipeline(embedder=embedder, store=store, bm25=None)

pipeline.ingest('/data/papers', mode='pdf')
"

# Query for specific findings
curl -X POST "http://localhost:8000/query/stream" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "What are the key findings about transformer performance?",
    "model": "gpt-4o"
  }'
```

### Example 3: Customer Support Bot

```bash
# 1. Ingest FAQ and documentation
# 2. Set up CRAG with relevant threshold
# 3. Route low-confidence queries to web search

CRAG_RELEVANCE_THRESHOLD=0.6
TAVILY_API_KEY=your_key
```

---

## πŸ“Š Advanced Features

### Knowledge Graph Extraction

Three modes available:

| Mode | Backend | Speed | Quality | Cost |
|------|---------|-------|---------|------|
| `rebel` | Local REBEL model | Fast | Good | Free |
| `llm` | LLM (Groq/OpenAI) | Slower | Excellent | $$ |
| `rebel-filtered` | REBEL + entity filtering | Fast | Good | Free |
| `llm-filtered` | LLM + entity filtering | Slower | Excellent | $$ |

Switch via config:
```env
GRAPH_EXTRACTOR=llm-filtered
```

### CRAG (Consistency-based RAG)

Automatically:
1. Evaluates retrieval confidence
2. Assigns relevance grade (Correct/Partially-Correct/Missing)
3. Supplements low-confidence with web search via Tavily

```python
from generation.crag import CRAGGate

crag = CRAGGate()
response = crag.evaluate(query, context, answer)
# Returns: grade, supplemental_docs
```

### Evaluation & Metrics

RAGAS-based evaluation:

```python
from evaluation.ragas_eval import RAGASEvaluator
from evaluation.store import EvalStore

evaluator = RAGASEvaluator(store=EvalStore())
metrics = evaluator.evaluate(query, context, answer)
# Returns: answer_relevance, faithfulness, context_precision
```

### Caching Strategy

```python
from retrieval.cache import CachedRetriever

retriever = CachedRetriever(base_retriever)
# First call: 1000ms (database query)
# Second call: 5ms (Redis cache hit, TTL: 1 hour)
results = retriever.retrieve("machine learning basics")
```

---

## βš™οΈ Performance Tuning

### For Speed

```env
# Smaller embedding model
EMBED_MODEL_NAME=BAAI/bge-small-en-v1.5

# Smaller chunks
CHUNK_SIZE_TOKENS=128
PARENT_CHUNK_SIZE_TOKENS=512

# Faster index
MILVUS_INDEX_TYPE=IVF_FLAT
MILVUS_NPROBE=8  # Lower = faster

# Enable cache
REDIS_URL=redis://localhost:6379

# Fewer LLM tokens
GROQ_MAX_TOKENS=512
```

### For Quality

```env
# Larger embedding model
EMBED_MODEL_NAME=BAAI/bge-base-en-v1.5

# Optimal chunks
CHUNK_SIZE_TOKENS=512
PARENT_CHUNK_SIZE_TOKENS=2048

# More precise index
MILVUS_INDEX_TYPE=HNSW
MILVUS_NPROBE=32

# Better LLM
GROQ_MODEL=llama-3.3-70b-versatile

# Enable CRAG
CRAG_ENABLED=true
```

---

## πŸ› Troubleshooting

### Milvus Connection Failed

```bash
# Check if Milvus is running
curl http://localhost:19530/healthz

# Restart Milvus
docker-compose restart milvus

# Verify in settings
python -c "from config import get_settings; print(get_settings().milvus_host)"
```

### Low Retrieval Quality

1. **Check chunk quality:**
   ```python
   from ingestion.chunker import SemanticChunker
   chunker = SemanticChunker()
   chunks = chunker.chunk("your document text")
   print([c.text for c in chunks[:3]])
   ```

2. **Verify embeddings:**
   ```python
   from retrieval.embedder import Embedder
   embedder = Embedder()
   emb = embedder.embed("test query")
   print(f"Embedding dim: {len(emb)}, sample: {emb[:5]}")
   ```

3. **Enable CRAG** for automatic augmentation:
   ```env
   CRAG_ENABLED=true
   ```

### Slow Response Times

1. Check cache hit rate
2. Reduce `MILVUS_NPROBE`
3. Use streaming endpoint (`/query/stream`)
4. Enable Redis caching

### Out of Memory

```env
# Reduce batch sizes
EMBED_BATCH_SIZE=16

# Reduce chunk sizes
CHUNK_SIZE_TOKENS=128

# Switch to CPU if using GPU
EMBED_DEVICE=cpu
```

---

## πŸ“ˆ Monitoring & Evaluation

### Health Check

```bash
curl http://localhost:8000/health | jq .
```

### Collection Statistics

```python
from retrieval.dense import MilvusStore
from retrieval.embedder import Embedder

store = MilvusStore(embedder=Embedder())
stats = store.get_stats()
print(f"Documents: {stats['collection_count']}")
```

### Query Evaluation

```python
from evaluation.ragas_eval import RAGASEvaluator
from evaluation.store import EvalStore

evaluator = RAGASEvaluator(store=EvalStore(db_path="/data/storage/eval.db"))
metrics = evaluator.evaluate(query, context, answer)
print(f"Answer Relevance: {metrics['answer_relevance']:.2f}")
print(f"Faithfulness: {metrics['faithfulness']:.2f}")
print(f"Context Precision: {metrics['context_precision']:.2f}")
```

---

## 🀝 Contributing

Contributions welcome! Areas for enhancement:

- [ ] Multi-language support
- [ ] Fine-tuned domain-specific embeddings
- [ ] Advanced reranking strategies
- [ ] GraphQL API
- [ ] Persistent trace logging
- [ ] A/B testing framework

---

## πŸ“ License

MIT License β€” see LICENSE file for details

---

## πŸ”— Resources

- [Milvus Documentation](https://milvus.io/docs)
- [FastAPI Guide](https://fastapi.tiangolo.com/)
- [RAGAS Evaluation Framework](https://github.com/explorerx3/ragas)
- [Groq API Reference](https://console.groq.com/docs/api-reference)
- [CRAG Paper](https://arxiv.org/abs/2401.15884)

---

**Questions?** Open an issue on GitHub or check the documentation.
source .venv/bin/activate
pip install -r requirements.txt
python -m nltk.downloader punkt
python -m spacy download en_core_web_sm
```

### 2. Configure

```bash
cp .env.example .env
# Edit .env β€” set GROQ_API_KEY at minimum
```

Get a free Groq API key at https://console.groq.com

### 3. Start Milvus

```bash
docker-compose up -d
# Wait ~30s for Milvus to be healthy
docker-compose ps   # all three services should show "healthy"
```

### 4. Ingest documents

```bash
mkdir -p data/documents
# Copy PDFs / HTML / TXT files into data/documents/

python -m ingestion.pipeline data/documents
```

Or use the CLI:
```bash
python ingestion/pipeline.py data/documents
python ingestion/pipeline.py data/documents/paper.pdf
```

### 5. Start the API

```bash
uvicorn api.main:app --reload --port 8000
```

### 6. Start the UI

```bash
streamlit run ui/app.py
```

Open http://localhost:8501 in your browser.

---

## API endpoints

| Method | Path | Description |
|--------|------|-------------|
| GET  | `/health` | Component health check |
| POST | `/ingest` | Trigger ingestion pipeline |
| POST | `/query` | Blocking query (full JSON) |
| POST | `/query/stream` | Streaming query (SSE) |

### Example β€” blocking query

```bash
curl -X POST http://localhost:8000/query \
  -H "Content-Type: application/json" \
  -d '{"query": "What is attention in transformers?", "top_k": 5}'
```

### Example β€” streaming query

```bash
curl -X POST http://localhost:8000/query/stream \
  -H "Content-Type: application/json" \
  -d '{"query": "Explain PagedAttention", "stream": true}'
```

---

## Key design decisions

### Semantic chunking
Fixed-size chunking (e.g. 1000 chars with 200 overlap) splits mid-sentence
and mid-concept. Semantic chunking detects topic boundaries using cosine
similarity between consecutive sentence embeddings, producing chunks that
align with natural concept transitions. Combined with a fallback on token
count (child_max = 256 tokens), chunks are both semantically coherent and
bounded in size.

### Parent-child hierarchy
The child chunk (β‰ˆ256 tokens) is what gets embedded and indexed β€” small,
precise, high-relevance. When a child chunk is retrieved, its parent chunk
(β‰ˆ1024 tokens, centred on the child) is what goes into the LLM context.
This separates the **retrieval granularity** from the **generation context
width**, giving you the precision of small chunks with the coherence of
large ones.

### BGE query prefix
`BAAI/bge-small-en-v1.5` is trained to expect a task-specific prefix on
query strings for retrieval tasks:
`"Represent this sentence for searching relevant passages: <query>"`
Documents are embedded as-is. Skipping this prefix typically costs 3-5
points on retrieval benchmarks.

---

## Phase roadmap

| Phase | Status | What's added |
|-------|--------|--------------|
| 1 | βœ… Done | Dense RAG, semantic chunking, parent-child, streaming UI |
| 2 | βœ… Done | BM25 sparse, query router, RRF fusion, cross-encoder reranking |
| 3 | βœ… Done | GraphRAG (spaCy NER + NetworkX), CRAG gate, web fallback |
| 4 | βœ… Done | RAGAS eval harness, Redis cache, evaluation dashboard |