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
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
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "b0f26b66",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "d:\\projects\\doc-intelligence-rag\\.venv\\Scripts\\python.exe\n"
     ]
    }
   ],
   "source": [
    "import sys\n",
    "print(sys.executable)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "d39fb45d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "============================================================\n",
      "PART 0: RAG Pipeline Overview\n",
      "============================================================\n",
      "\n",
      "Input: User asks \"What is machine learning?\"\n",
      "\n",
      "       ↓\n",
      "\n",
      "1. RETRIEVE: Search similar docs\n",
      "   Question embedding β†’ Find top 3 most similar chunks\n",
      "\n",
      "2. AUGMENT: Build context\n",
      "   Combine retrieved chunks into a context string\n",
      "\n",
      "3. GENERATE: LLM answers\n",
      "   Pass (context + question) β†’ LLM β†’ Answer\n",
      "\n",
      "Output: \"Machine learning is...\"\n",
      "\n",
      "\n",
      "============================================================\n",
      "PART 1: Text Chunking (Why?)\n",
      "============================================================\n",
      "\n",
      "WHY chunk text?\n",
      "  β€’ Embeddings work better on ~500 token chunks (not 50k token documents)\n",
      "  β€’ Allows granular retrieval (retrieve only relevant section)\n",
      "  β€’ Reduces embedding costs\n",
      "\n",
      "CHALLENGE: Chunking strategy matters!\n",
      "  β€’ Too small: Lose context (100 tokens)\n",
      "  β€’ Too large: Lose precision (5000 tokens)\n",
      "  β€’ SOLUTION: Use overlap (e.g., 500 token chunk with 50 token overlap)\n",
      "\n",
      "WHY overlap?\n",
      "  β€’ Important info might be at chunk boundary\n",
      "  β€’ Overlap ensures semantic continuity\n",
      "  β€’ Example: \"The study shows A. B supports A.\" might split badly without overlap\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# RAG System from First Principles\n",
    "# =====================================\n",
    "# This notebook builds a RAG system step-by-step\n",
    "# We'll understand WHY before we code\n",
    "#\n",
    "# Prerequisites with UV:\n",
    "#   uv init rag-learning\n",
    "#   uv add jupyter numpy pandas requests pydantic groq\n",
    "#   uv venv && source .venv/bin/activate\n",
    "#\n",
    "# Free APIs Used:\n",
    "#   - Groq (LLM): https://console.groq.com (free API key)\n",
    "#   - Ollama (Embeddings): https://ollama.ai (local, completely free)\n",
    "\n",
    "# ========== PART 0: THE PROBLEM ==========\n",
    "# \n",
    "# Problem: How do we make an LLM answer questions about OUR documents?\n",
    "# \n",
    "# Naive approach: Put entire document into prompt\n",
    "#   ❌ Problem: Context window is limited (4k, 8k, 128k tokens)\n",
    "#   ❌ Problem: Costs scale with document size\n",
    "#   ❌ Problem: LLM gets confused with irrelevant information\n",
    "#\n",
    "# Better approach: RAG (Retrieval-Augmented Generation)\n",
    "#   βœ“ Only pass relevant chunks to LLM\n",
    "#   βœ“ Reduces costs\n",
    "#   βœ“ Improves accuracy\n",
    "#\n",
    "# RAG Pipeline:\n",
    "#   1. Split document into chunks\n",
    "#   2. Convert chunks to embeddings (vectors)\n",
    "#   3. Store embeddings in vector database\n",
    "#   4. When user asks question:\n",
    "#      a) Convert question to embedding\n",
    "#      b) Find most similar chunks (similarity search)\n",
    "#      c) Pass those chunks + question to LLM\n",
    "#      d) LLM answers based on those chunks\n",
    "\n",
    "print(\"=\" * 60)\n",
    "print(\"PART 0: RAG Pipeline Overview\")\n",
    "print(\"=\" * 60)\n",
    "print(\"\"\"\n",
    "Input: User asks \"What is machine learning?\"\n",
    "       \n",
    "       ↓\n",
    "       \n",
    "1. RETRIEVE: Search similar docs\n",
    "   Question embedding β†’ Find top 3 most similar chunks\n",
    "   \n",
    "2. AUGMENT: Build context\n",
    "   Combine retrieved chunks into a context string\n",
    "   \n",
    "3. GENERATE: LLM answers\n",
    "   Pass (context + question) β†’ LLM β†’ Answer\n",
    "\n",
    "Output: \"Machine learning is...\"\n",
    "\"\"\")\n",
    "\n",
    "# ========== PART 1: TEXT CHUNKING ==========\n",
    "print(\"\\n\" + \"=\" * 60)\n",
    "print(\"PART 1: Text Chunking (Why?)\")\n",
    "print(\"=\" * 60)\n",
    "\n",
    "print(\"\"\"\n",
    "WHY chunk text?\n",
    "  β€’ Embeddings work better on ~500 token chunks (not 50k token documents)\n",
    "  β€’ Allows granular retrieval (retrieve only relevant section)\n",
    "  β€’ Reduces embedding costs\n",
    "\n",
    "CHALLENGE: Chunking strategy matters!\n",
    "  β€’ Too small: Lose context (100 tokens)\n",
    "  β€’ Too large: Lose precision (5000 tokens)\n",
    "  β€’ SOLUTION: Use overlap (e.g., 500 token chunk with 50 token overlap)\n",
    "\n",
    "WHY overlap?\n",
    "  β€’ Important info might be at chunk boundary\n",
    "  β€’ Overlap ensures semantic continuity\n",
    "  β€’ Example: \"The study shows A. B supports A.\" might split badly without overlap\n",
    "\"\"\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "0523d02c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "βœ“ Split into 5 chunks:\n",
      "  Chunk 0: 20 words | Machine learning is a subset of artificial intelligence. It ...\n",
      "  Chunk 1: 20 words | on algorithms that learn from data. Deep learning uses neura...\n",
      "  Chunk 2: 20 words | networks with multiple layers. Transformers are the backbone...\n",
      "  Chunk 3: 12 words | NLP systems. The attention mechanism allows models to focus ...\n",
      "  Chunk 4: 2 words | relevant parts....\n"
     ]
    }
   ],
   "source": [
    "\n",
    "# Implement chunking\n",
    "def chunk_text(text, chunk_size=500, overlap=50):\n",
    "    \"\"\"\n",
    "    Split text into overlapping chunks.\n",
    "    \n",
    "    Args:\n",
    "        text: Raw text to chunk\n",
    "        chunk_size: Tokens per chunk (roughly words * 0.75)\n",
    "        overlap: Tokens overlap between chunks\n",
    "    \n",
    "    Returns:\n",
    "        List of chunk dicts with text and metadata\n",
    "    \"\"\"\n",
    "    words = text.split()\n",
    "    chunks = []\n",
    "    \n",
    "    # Calculate stride (how many words to move forward each iteration)\n",
    "    # If overlap=50 and chunk_size=500, stride=450\n",
    "    stride = chunk_size - overlap\n",
    "    \n",
    "    for i in range(0, len(words), stride):\n",
    "        chunk_words = words[i:i + chunk_size]\n",
    "        chunk_text = \" \".join(chunk_words)\n",
    "        \n",
    "        if chunk_text.strip():  # Skip empty chunks\n",
    "            chunks.append({\n",
    "                \"text\": chunk_text,\n",
    "                \"start_idx\": i,\n",
    "                \"word_count\": len(chunk_words),\n",
    "                \"chunk_id\": len(chunks)  # Simple ID\n",
    "            })\n",
    "    \n",
    "    return chunks\n",
    "\n",
    "# Test chunking\n",
    "sample_text = \"\"\"\n",
    "Machine learning is a subset of artificial intelligence. \n",
    "It focuses on algorithms that learn from data. \n",
    "Deep learning uses neural networks with multiple layers. \n",
    "Transformers are the backbone of modern NLP systems. \n",
    "The attention mechanism allows models to focus on relevant parts.\n",
    "\"\"\"\n",
    "\n",
    "chunks = chunk_text(sample_text, chunk_size=20, overlap=10)\n",
    "print(f\"\\nβœ“ Split into {len(chunks)} chunks:\")\n",
    "for i, chunk in enumerate(chunks):\n",
    "    print(f\"  Chunk {i}: {chunk['word_count']} words | {chunk['text'][:60]}...\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "3464f9c9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "============================================================\n",
      "PART 2: Embeddings (Why?)\n",
      "============================================================\n",
      "\n",
      "PROBLEM: How do we compare text for similarity?\n",
      "  β€’ Can't just use string matching (\"cat\" β‰  \"feline\")\n",
      "  β€’ Need semantic understanding\n",
      "\n",
      "SOLUTION: Embeddings (vectors that capture meaning)\n",
      "  β€’ Convert text β†’ vector (list of numbers)\n",
      "  β€’ Similar texts have similar vectors\n",
      "  β€’ We can use math to compare them!\n",
      "\n",
      "EXAMPLE:\n",
      "  \"The cat sat on the mat\" β†’ [0.2, -0.5, 0.8, 0.1, ...] (384 dims)\n",
      "  \"A feline sat on rug\"    β†’ [0.21, -0.48, 0.79, 0.12, ...] (384 dims)\n",
      "\n",
      "  Notice: Very similar vectors = similar meaning!\n",
      "\n",
      "HOW DO WE GET EMBEDDINGS?\n",
      "  Option 1: Use OpenAI API (costs money)\n",
      "  Option 2: Use local Ollama (free, slower)\n",
      "\n",
      "  We'll use Ollama because:\n",
      "    βœ“ Free (no API costs)\n",
      "    βœ“ Privacy (stays on your machine)\n",
      "    βœ“ Fast for this use case\n",
      "    βœ“ Good enough for RAG\n",
      "\n",
      "EMBEDDING MODELS:\n",
      "  β€’ nomic-embed-text: 384 dimensions (good for RAG)\n",
      "  β€’ all-minilm-l6-v2: 384 dimensions (lighter)\n",
      "  β€’ openai embedding: 1536 dimensions (more expensive, higher quality)\n",
      "\n"
     ]
    }
   ],
   "source": [
    "\n",
    "# ========== PART 2: EMBEDDINGS ==========\n",
    "print(\"\\n\" + \"=\" * 60)\n",
    "print(\"PART 2: Embeddings (Why?)\")\n",
    "print(\"=\" * 60)\n",
    "\n",
    "print(\"\"\"\n",
    "PROBLEM: How do we compare text for similarity?\n",
    "  β€’ Can't just use string matching (\"cat\" β‰  \"feline\")\n",
    "  β€’ Need semantic understanding\n",
    "\n",
    "SOLUTION: Embeddings (vectors that capture meaning)\n",
    "  β€’ Convert text β†’ vector (list of numbers)\n",
    "  β€’ Similar texts have similar vectors\n",
    "  β€’ We can use math to compare them!\n",
    "\n",
    "EXAMPLE:\n",
    "  \"The cat sat on the mat\" β†’ [0.2, -0.5, 0.8, 0.1, ...] (384 dims)\n",
    "  \"A feline sat on rug\"    β†’ [0.21, -0.48, 0.79, 0.12, ...] (384 dims)\n",
    "  \n",
    "  Notice: Very similar vectors = similar meaning!\n",
    "\n",
    "HOW DO WE GET EMBEDDINGS?\n",
    "  Option 1: Use OpenAI API (costs money)\n",
    "  Option 2: Use local Ollama (free, slower)\n",
    "  \n",
    "  We'll use Ollama because:\n",
    "    βœ“ Free (no API costs)\n",
    "    βœ“ Privacy (stays on your machine)\n",
    "    βœ“ Fast for this use case\n",
    "    βœ“ Good enough for RAG\n",
    "\n",
    "EMBEDDING MODELS:\n",
    "  β€’ nomic-embed-text: 384 dimensions (good for RAG)\n",
    "  β€’ all-minilm-l6-v2: 384 dimensions (lighter)\n",
    "  β€’ openai embedding: 1536 dimensions (more expensive, higher quality)\n",
    "\"\"\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "5eb96a3e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "βœ“ Embedding shape: 348 dimensions\n",
      "  Sample values: [-0.019382589036581188, -0.005570373852637493, -0.05710695701024572, -0.04601154504073093, 0.08037614551187885] ...\n"
     ]
    }
   ],
   "source": [
    "\n",
    "import numpy as np\n",
    "\n",
    "def simulate_embedding(text, dims=348):\n",
    "    \"\"\"\n",
    "    Simulate what an embedding looks like.\n",
    "    \n",
    "    In reality, Ollama would use a neural network to create this.\n",
    "    For learning, we'll just use a hash-based deterministic vector.\n",
    "    \"\"\"\n",
    "    # Hash the text to get consistent numbers\n",
    "    hash_val = hash(text) % 10000\n",
    "    np.random.seed(hash_val)\n",
    "    \n",
    "    # Create random but consistent vector\n",
    "    embedding = np.random.randn(dims)\n",
    "    \n",
    "    # Normalize to unit length (important for cosine similarity)\n",
    "    embedding = embedding / np.linalg.norm(embedding)\n",
    "    \n",
    "    return embedding.tolist()\n",
    "\n",
    "# Demonstrate\n",
    "text1 = \"Machine learning is AI\"\n",
    "text2 = \"Deep learning uses neural networks\"\n",
    "text3 = \"Cooking pasta is delicious\"\n",
    "\n",
    "emb1 = simulate_embedding(text1)\n",
    "emb2 = simulate_embedding(text2)\n",
    "emb3 = simulate_embedding(text3)\n",
    "\n",
    "print(f\"\\nβœ“ Embedding shape: {len(emb1)} dimensions\")\n",
    "print(f\"  Sample values: {emb1[:5]} ...\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "e15b8066",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "============================================================\n",
      "PART 3: Similarity Search (Why?)\n",
      "============================================================\n",
      "\n",
      "GOAL: Find which chunks are most relevant to a query\n",
      "\n",
      "METHOD: Cosine Similarity\n",
      "  β€’ Measure angle between vectors\n",
      "  β€’ Values from -1 to 1 (1 = identical direction = same meaning)\n",
      "  β€’ Formula: similarity = (A Β· B) / (|A| * |B|)\n",
      "\n",
      "EXAMPLE:\n",
      "  Query: \"What is deep learning?\"\n",
      "  Chunk 1: \"Deep learning uses neural networks\" β†’ similarity = 0.92 βœ“ Relevant!\n",
      "  Chunk 2: \"Cooking pasta...\" β†’ similarity = 0.15 βœ— Not relevant\n",
      "  Chunk 3: \"Neural networks have many layers\" β†’ similarity = 0.85 βœ“ Relevant!\n",
      "\n",
      "  Return top 2: Chunks 1 and 3\n",
      "\n",
      "\n",
      "βœ“ Query: 'neural networks'\n",
      "  Results (sorted by relevance):\n",
      "     -0.077 | Deep learning uses neural networks\n",
      "     -0.021 | Cooking pasta is delicious\n",
      "     -0.005 | Machine learning is AI\n"
     ]
    }
   ],
   "source": [
    "\n",
    "# ========== PART 3: SIMILARITY SEARCH ==========\n",
    "print(\"\\n\" + \"=\" * 60)\n",
    "print(\"PART 3: Similarity Search (Why?)\")\n",
    "print(\"=\" * 60)\n",
    "\n",
    "print(\"\"\"\n",
    "GOAL: Find which chunks are most relevant to a query\n",
    "\n",
    "METHOD: Cosine Similarity\n",
    "  β€’ Measure angle between vectors\n",
    "  β€’ Values from -1 to 1 (1 = identical direction = same meaning)\n",
    "  β€’ Formula: similarity = (A Β· B) / (|A| * |B|)\n",
    "  \n",
    "EXAMPLE:\n",
    "  Query: \"What is deep learning?\"\n",
    "  Chunk 1: \"Deep learning uses neural networks\" β†’ similarity = 0.92 βœ“ Relevant!\n",
    "  Chunk 2: \"Cooking pasta...\" β†’ similarity = 0.15 βœ— Not relevant\n",
    "  Chunk 3: \"Neural networks have many layers\" β†’ similarity = 0.85 βœ“ Relevant!\n",
    "  \n",
    "  Return top 2: Chunks 1 and 3\n",
    "\"\"\")\n",
    "\n",
    "def cosine_similarity(vec_a, vec_b):\n",
    "    \"\"\"\n",
    "    Calculate cosine similarity between two vectors.\n",
    "    \n",
    "    Returns value between -1 and 1 (higher = more similar)\n",
    "    \"\"\"\n",
    "    a = np.array(vec_a)\n",
    "    b = np.array(vec_b)\n",
    "    \n",
    "    dot_product = np.dot(a, b)\n",
    "    norm_a = np.linalg.norm(a)\n",
    "    norm_b = np.linalg.norm(b)\n",
    "    \n",
    "    if norm_a == 0 or norm_b == 0:\n",
    "        return 0.0\n",
    "    \n",
    "    return float(dot_product / (norm_a * norm_b))\n",
    "\n",
    "# Test similarity\n",
    "query = \"neural networks\"\n",
    "query_emb = simulate_embedding(query)\n",
    "\n",
    "similarities = [\n",
    "    (\"Deep learning uses neural networks\", cosine_similarity(query_emb, emb2)),\n",
    "    (\"Machine learning is AI\", cosine_similarity(query_emb, emb1)),\n",
    "    (\"Cooking pasta is delicious\", cosine_similarity(query_emb, emb3)),\n",
    "]\n",
    "\n",
    "# Sort by similarity\n",
    "similarities.sort(key=lambda x: x[1], reverse=False)\n",
    "\n",
    "print(f\"\\nβœ“ Query: '{query}'\")\n",
    "print(f\"  Results (sorted by relevance):\")\n",
    "for text, score in similarities:\n",
    "    bar = \"β–ˆ\" * int(score * 20)\n",
    "    print(f\"    {bar} {score:.3f} | {text}\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "33b76510",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "============================================================\n",
      "PART 4: Vector Store (Why?)\n",
      "============================================================\n",
      "\n",
      "PROBLEM: How do we store and retrieve embeddings efficiently?\n",
      "\n",
      "SIMPLE APPROACH: In-memory dictionary\n",
      "  βœ“ Easy to understand and implement\n",
      "  βœ“ Fast for small documents (< 10k chunks)\n",
      "  βœ— Loses data when program stops\n",
      "  βœ— Doesn't scale to millions of vectors\n",
      "\n",
      "PRODUCTION APPROACH: Vector databases\n",
      "  β€’ Pinecone, Weaviate, Milvus, Chroma, Qdrant\n",
      "  β€’ Optimized for similarity search\n",
      "  β€’ Persistent storage\n",
      "  β€’ Scales to billions of vectors\n",
      "\n",
      "FOR NOW: We'll use in-memory (simple) but structure it to be replaceable\n",
      "\n",
      "\n",
      "βœ“ Query: 'transformers attention mechanism'\n",
      "  Retrieved 2 chunks:\n",
      "    [0.005] on algorithms that learn from data. Deep learning uses neural networks...\n",
      "    [-0.012] NLP systems. The attention mechanism allows models to focus on relevan...\n"
     ]
    }
   ],
   "source": [
    "\n",
    "# ========== PART 4: VECTOR STORE ==========\n",
    "print(\"\\n\" + \"=\" * 60)\n",
    "print(\"PART 4: Vector Store (Why?)\")\n",
    "print(\"=\" * 60)\n",
    "\n",
    "print(\"\"\"\n",
    "PROBLEM: How do we store and retrieve embeddings efficiently?\n",
    "\n",
    "SIMPLE APPROACH: In-memory dictionary\n",
    "  βœ“ Easy to understand and implement\n",
    "  βœ“ Fast for small documents (< 10k chunks)\n",
    "  βœ— Loses data when program stops\n",
    "  βœ— Doesn't scale to millions of vectors\n",
    "\n",
    "PRODUCTION APPROACH: Vector databases\n",
    "  β€’ Pinecone, Weaviate, Milvus, Chroma, Qdrant\n",
    "  β€’ Optimized for similarity search\n",
    "  β€’ Persistent storage\n",
    "  β€’ Scales to billions of vectors\n",
    "\n",
    "FOR NOW: We'll use in-memory (simple) but structure it to be replaceable\n",
    "\"\"\")\n",
    "\n",
    "class SimpleVectorStore:\n",
    "    \"\"\"\n",
    "    In-memory vector store.\n",
    "    Structure: Can easily swap for Pinecone/Weaviate later.\n",
    "    \"\"\"\n",
    "    \n",
    "    def __init__(self):\n",
    "        self.vectors = {}      # chunk_id -> embedding vector\n",
    "        self.metadata = {}     # chunk_id -> {text, source, etc}\n",
    "    \n",
    "    def add(self, chunk_id, text, embedding):\n",
    "        \"\"\"Store a chunk with its embedding.\"\"\"\n",
    "        self.vectors[chunk_id] = embedding\n",
    "        self.metadata[chunk_id] = {\"text\": text, \"length\": len(text)}\n",
    "    \n",
    "    def search(self, query_embedding, top_k=3):\n",
    "        \"\"\"Find most similar chunks.\"\"\"\n",
    "        if not self.vectors:\n",
    "            return []\n",
    "        \n",
    "        results = []\n",
    "        for chunk_id, vector in self.vectors.items():\n",
    "            similarity = cosine_similarity(query_embedding, vector)\n",
    "            results.append({\n",
    "                \"chunk_id\": chunk_id,\n",
    "                \"similarity\": similarity,\n",
    "                \"text\": self.metadata[chunk_id][\"text\"]\n",
    "            })\n",
    "        \n",
    "        # Sort by similarity descending\n",
    "        results.sort(key=lambda x: x[\"similarity\"], reverse=True)\n",
    "        return results[:top_k]\n",
    "\n",
    "# Test vector store\n",
    "store = SimpleVectorStore()\n",
    "\n",
    "# Add chunks with embeddings\n",
    "for chunk in chunks:\n",
    "    emb = simulate_embedding(chunk[\"text\"])\n",
    "    store.add(chunk[\"chunk_id\"], chunk[\"text\"], emb)\n",
    "\n",
    "# Search\n",
    "query = \"transformers attention mechanism\"\n",
    "query_emb = simulate_embedding(query)\n",
    "results = store.search(query_emb, top_k=2)\n",
    "\n",
    "print(f\"\\nβœ“ Query: '{query}'\")\n",
    "print(f\"  Retrieved {len(results)} chunks:\")\n",
    "for r in results:\n",
    "    print(f\"    [{r['similarity']:.3f}] {r['text'][:70]}...\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "94ca95e9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "============================================================\n",
      "PART 5: LLM Integration (Why?)\n",
      "============================================================\n",
      "\n",
      "PROBLEM: How do we actually answer the user's question?\n",
      "\n",
      "SOLUTION: Pass context + question to LLM\n",
      "  1. Retrieve relevant chunks (from vector store)\n",
      "  2. Combine into \"context\" string\n",
      "  3. Create prompt: \"Context: [chunks] Question: [query]\"\n",
      "  4. Send to LLM (Groq, OpenAI, etc)\n",
      "  5. LLM answers based on context\n",
      "\n",
      "WHY THIS WORKS:\n",
      "  β€’ LLM has knowledge from training\n",
      "  β€’ Context grounds answer in YOUR documents\n",
      "  β€’ LLM won't hallucinate (ideally) because answer must match context\n",
      "\n",
      "EXAMPLE PROMPT:\n",
      "  ---\n",
      "  Context:\n",
      "  Deep learning uses neural networks with many layers.\n",
      "  The attention mechanism focuses on relevant parts.\n",
      "\n",
      "  Question: How does deep learning work?\n",
      "\n",
      "  Answer: (LLM fills this in)\n",
      "  ---\n",
      "\n",
      "\n",
      "βœ“ Built context from 2 chunks:\n",
      "  Length: 271 characters\n",
      "  Preview:\n",
      "  [Chunk 1 - Relevance: 0.5%]\n",
      "on algorithms that learn from data. Deep learning uses neural networks with multiple layers. Transformers are the backbone of modern\n",
      "\n",
      "[Chunk 2 - Relevance: -1.2%]\n",
      "NLP syste...\n"
     ]
    }
   ],
   "source": [
    "\n",
    "# ========== PART 5: LLM INTEGRATION ==========\n",
    "print(\"\\n\" + \"=\" * 60)\n",
    "print(\"PART 5: LLM Integration (Why?)\")\n",
    "print(\"=\" * 60)\n",
    "\n",
    "print(\"\"\"\n",
    "PROBLEM: How do we actually answer the user's question?\n",
    "\n",
    "SOLUTION: Pass context + question to LLM\n",
    "  1. Retrieve relevant chunks (from vector store)\n",
    "  2. Combine into \"context\" string\n",
    "  3. Create prompt: \"Context: [chunks] Question: [query]\"\n",
    "  4. Send to LLM (Groq, OpenAI, etc)\n",
    "  5. LLM answers based on context\n",
    "\n",
    "WHY THIS WORKS:\n",
    "  β€’ LLM has knowledge from training\n",
    "  β€’ Context grounds answer in YOUR documents\n",
    "  β€’ LLM won't hallucinate (ideally) because answer must match context\n",
    "\n",
    "EXAMPLE PROMPT:\n",
    "  ---\n",
    "  Context:\n",
    "  Deep learning uses neural networks with many layers.\n",
    "  The attention mechanism focuses on relevant parts.\n",
    "  \n",
    "  Question: How does deep learning work?\n",
    "  \n",
    "  Answer: (LLM fills this in)\n",
    "  ---\n",
    "\"\"\")\n",
    "\n",
    "def build_context(retrieved_chunks):\n",
    "    \"\"\"\n",
    "    Combine retrieved chunks into a context string for the LLM.\n",
    "    \n",
    "    This is where you control what the LLM sees.\n",
    "    \"\"\"\n",
    "    context = \"\"\n",
    "    for i, chunk in enumerate(retrieved_chunks):\n",
    "        score = chunk.get(\"similarity\", 0)\n",
    "        context += f\"[Chunk {i+1} - Relevance: {score:.1%}]\\n\"\n",
    "        context += chunk[\"text\"] + \"\\n\\n\"\n",
    "    \n",
    "    return context\n",
    "\n",
    "# Demo\n",
    "context = build_context(results)\n",
    "print(f\"\\nβœ“ Built context from {len(results)} chunks:\")\n",
    "print(f\"  Length: {len(context)} characters\")\n",
    "print(f\"  Preview:\\n  {context[:200]}...\")\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "2b841f01",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "============================================================\n",
      "PART 6: Complete RAG Pipeline\n",
      "============================================================\n",
      "\n",
      "[STEP 1] Chunking document...\n",
      "  β†’ Split into 1 chunks\n",
      "\n",
      "[STEP 2] Creating embeddings...\n",
      "  β†’ Created 1 embeddings\n",
      "\n",
      "[STEP 3] Embedding query...\n",
      "  β†’ Query embedding ready\n",
      "\n",
      "[STEP 4] Searching similar chunks...\n",
      "  β†’ Retrieved 1 chunks\n",
      "\n",
      "[STEP 5] Building prompt...\n",
      "  β†’ Prompt ready (518 chars)\n",
      "\n",
      "============================================================\n",
      "RESULT SUMMARY\n",
      "============================================================\n",
      "Query: How do transformers work?\n",
      "Chunks created: 1\n",
      "Chunks retrieved: 1\n",
      "\n",
      "Top retrieved chunks:\n",
      "  [6.46%] Machine learning is a subset of AI that learns from data. De...\n",
      "\n",
      "Final prompt (to be sent to LLM):\n",
      "You are a helpful assistant. Answer the question based ONLY on the provided context.\n",
      "If the context doesn't contain the answer, say so explicitly.\n",
      "\n",
      "Context:\n",
      "[Chunk 1 - Relevance: 6.5%]\n",
      "Machine learning is a subset of AI that learns from data. Deep learning uses neural networks with many layers. Transformers use attention mechanisms for NLP tasks. The attention mechanism allows models to focus on important parts. Large language models are trained on massive datasets.\n",
      "\n",
      "\n",
      "\n",
      "Question: How do transformers work?\n",
      "\n",
      "Answer:\n",
      "\n",
      "============================================================\n",
      "βœ“ You now understand RAG!\n",
      "============================================================\n",
      "\n",
      "Next steps:\n",
      "  1. Replace simulate_embedding() with real Ollama calls\n",
      "  2. Replace our Vector Store with Pinecone/Chroma\n",
      "  3. Replace the final prompt with real Groq LLM calls\n",
      "  4. Wrap in FastAPI for production\n",
      "\n",
      "But the LOGIC stays the same!\n",
      "\n"
     ]
    }
   ],
   "source": [
    "def build_prompt(context, query):\n",
    "    \"\"\"Build final prompt for LLM.\"\"\"\n",
    "    prompt = f\"\"\"You are a helpful assistant. Answer the question based ONLY on the provided context.\n",
    "If the context doesn't contain the answer, say so explicitly.\n",
    "\n",
    "Context:\n",
    "{context}\n",
    "\n",
    "Question: {query}\n",
    "\n",
    "Answer:\"\"\"\n",
    "    return prompt\n",
    "    \n",
    "# ========== PART 6: PUTTING IT TOGETHER ==========\n",
    "print(\"\\n\" + \"=\" * 60)\n",
    "print(\"PART 6: Complete RAG Pipeline\")\n",
    "print(\"=\" * 60)\n",
    "\n",
    "def rag_pipeline(query, document_text, chunk_size=500, overlap=50, top_k=3):\n",
    "    \"\"\"\n",
    "    Complete RAG pipeline:\n",
    "    1. Chunk document\n",
    "    2. Create embeddings\n",
    "    3. Build vector store\n",
    "    4. Retrieve relevant chunks\n",
    "    5. Build prompt\n",
    "    6. Return to user (in real system, send to LLM)\n",
    "    \"\"\"\n",
    "    \n",
    "    print(f\"\\n[STEP 1] Chunking document...\")\n",
    "    chunks = chunk_text(document_text, chunk_size, overlap)\n",
    "    print(f\"  β†’ Split into {len(chunks)} chunks\")\n",
    "    \n",
    "    print(f\"\\n[STEP 2] Creating embeddings...\")\n",
    "    store = SimpleVectorStore()\n",
    "    for chunk in chunks:\n",
    "        emb = simulate_embedding(chunk[\"text\"])\n",
    "        store.add(chunk[\"chunk_id\"], chunk[\"text\"], emb)\n",
    "    print(f\"  β†’ Created {len(chunks)} embeddings\")\n",
    "    \n",
    "    print(f\"\\n[STEP 3] Embedding query...\")\n",
    "    query_emb = simulate_embedding(query)\n",
    "    print(f\"  β†’ Query embedding ready\")\n",
    "    \n",
    "    print(f\"\\n[STEP 4] Searching similar chunks...\")\n",
    "    retrieved = store.search(query_emb, top_k)\n",
    "    print(f\"  β†’ Retrieved {len(retrieved)} chunks\")\n",
    "    \n",
    "    print(f\"\\n[STEP 5] Building prompt...\")\n",
    "    context = build_context(retrieved)\n",
    "    prompt = build_prompt(context, query)\n",
    "    print(f\"  β†’ Prompt ready ({len(prompt)} chars)\")\n",
    "    \n",
    "    return {\n",
    "        \"query\": query,\n",
    "        \"chunks_created\": len(chunks),\n",
    "        \"chunks_retrieved\": len(retrieved),\n",
    "        \"context\": context,\n",
    "        \"prompt\": prompt,\n",
    "        \"retrieved_chunks\": retrieved\n",
    "    }\n",
    "\n",
    "# Test full pipeline\n",
    "doc = \"\"\"\n",
    "Machine learning is a subset of AI that learns from data.\n",
    "Deep learning uses neural networks with many layers.\n",
    "Transformers use attention mechanisms for NLP tasks.\n",
    "The attention mechanism allows models to focus on important parts.\n",
    "Large language models are trained on massive datasets.\n",
    "\"\"\"\n",
    "\n",
    "result = rag_pipeline(\"How do transformers work?\", doc, chunk_size=500, top_k=2)\n",
    "\n",
    "print(f\"\\n\" + \"=\" * 60)\n",
    "print(\"RESULT SUMMARY\")\n",
    "print(\"=\" * 60)\n",
    "print(f\"Query: {result['query']}\")\n",
    "print(f\"Chunks created: {result['chunks_created']}\")\n",
    "print(f\"Chunks retrieved: {result['chunks_retrieved']}\")\n",
    "print(f\"\\nTop retrieved chunks:\")\n",
    "for chunk in result['retrieved_chunks']:\n",
    "    print(f\"  [{chunk['similarity']:.2%}] {chunk['text'][:60]}...\")\n",
    "print(f\"\\nFinal prompt (to be sent to LLM):\")\n",
    "print(result['prompt'])\n",
    "\n",
    "print(\"\\n\" + \"=\" * 60)\n",
    "print(\"βœ“ You now understand RAG!\")\n",
    "print(\"=\" * 60)\n",
    "print(\"\"\"\n",
    "Next steps:\n",
    "  1. Replace simulate_embedding() with real Ollama calls\n",
    "  2. Replace our Vector Store with Pinecone/Chroma\n",
    "  3. Replace the final prompt with real Groq LLM calls\n",
    "  4. Wrap in FastAPI for production\n",
    "  \n",
    "But the LOGIC stays the same!\n",
    "\"\"\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "33af125c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "llama-3.1-8b-instant\n",
      "groq/compound-mini\n",
      "whisper-large-v3\n",
      "moonshotai/kimi-k2-instruct-0905\n",
      "openai/gpt-oss-20b\n",
      "playai-tts-arabic\n",
      "groq/compound\n",
      "whisper-large-v3-turbo\n",
      "openai/gpt-oss-120b\n",
      "meta-llama/llama-prompt-guard-2-86m\n",
      "meta-llama/llama-prompt-guard-2-22m\n",
      "openai/gpt-oss-safeguard-20b\n",
      "moonshotai/kimi-k2-instruct\n",
      "qwen/qwen3-32b\n",
      "meta-llama/llama-4-maverick-17b-128e-instruct\n",
      "allam-2-7b\n",
      "meta-llama/llama-guard-4-12b\n",
      "playai-tts\n",
      "meta-llama/llama-4-scout-17b-16e-instruct\n",
      "llama-3.3-70b-versatile\n"
     ]
    }
   ],
   "source": [
    "from groq import Groq\n",
    "import os\n",
    "\n",
    "client = Groq(api_key=os.getenv(\"GROQ_API_KEY\"))\n",
    "\n",
    "models = client.models.list()\n",
    "for m in models.data:\n",
    "    print(m.id)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "704478dc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "πŸ€– LLM ANSWER:\n",
      "According to the provided context, transformers use attention mechanisms for NLP tasks.\n"
     ]
    }
   ],
   "source": [
    "from dotenv import load_dotenv\n",
    "import os\n",
    "from groq import Groq\n",
    "\n",
    "# Load from .env file\n",
    "load_dotenv()\n",
    "\n",
    "# Get API key safely\n",
    "api_key = os.getenv(\"GROQ_API_KEY\")\n",
    "\n",
    "if not api_key:\n",
    "    raise ValueError(\"GROQ_API_KEY not found in environment or .env file\")\n",
    "\n",
    "def query_groq(context, query):\n",
    "    \"\"\"Get real answer from Groq LLM.\"\"\"\n",
    "    client = Groq(api_key=api_key)\n",
    "    \n",
    "    message = client.chat.completions.create(\n",
    "        model=\"llama-3.1-8b-instant\",\n",
    "        max_tokens=1024,\n",
    "        messages=[{\n",
    "            \"role\": \"user\",\n",
    "            \"content\": f\"\"\"Based on this context, answer the question.\n",
    "Only use the context provided.\n",
    "\n",
    "Context:\n",
    "{context}\n",
    "\n",
    "Question: {query}\n",
    "\n",
    "Answer:\"\"\"\n",
    "        }]\n",
    "    )\n",
    "    return message.choices[0].message.content\n",
    "\n",
    "# Test it\n",
    "answer = query_groq(result[\"context\"], result[\"query\"])\n",
    "print(f\"\\nπŸ€– LLM ANSWER:\\n{answer}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8866fa43",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}