File size: 41,078 Bytes
10bf19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "28224481-4cb0-4bc6-bf88-2d2b383094df",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ[\"TAVILY_API_KEY\"] = \"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\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "55ec4c0c-65cc-4816-86df-c40b55f9c2d5",
   "metadata": {},
   "source": [
    "### Tracing\n",
    "\n",
    "Optionally, use [LangSmith](https://docs.smith.langchain.com/) for tracing (shown at bottom)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "68fed362-871a-46df-8ba0-579797ff2e9c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# os.environ[\"LANGCHAIN_TRACING_V2\"] = \"true\"\n",
    "# os.environ[\"LANGCHAIN_ENDPOINT\"] = \"https://api.smith.langchain.com\"\n",
    "# os.environ[\"LANGCHAIN_API_KEY\"] = \"<your-api-key>\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c059c3a3-7f01-4d46-8289-fde4c1b4155f",
   "metadata": {},
   "source": [
    "## Configuration\n",
    "\n",
    "Decide to run locally and select LLM to use with Ollama."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "2f4db331-c4d0-4c7c-a9a5-0bebc8a89c6c",
   "metadata": {},
   "outputs": [],
   "source": [
    "run_local = \"Yes\"\n",
    "local_llm = \"llama2-13b\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "632ae5bb-8b63-43a8-bfb8-da05d1c1bde4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# !pip install langchain_nomic"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6e2b6eed-3b3f-44b5-a34a-4ade1e94caf0",
   "metadata": {},
   "source": [
    "## Index\n",
    "\n",
    "Let's index 3 blog posts."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "d3f4d43f-eb93-4f7d-9cab-1ab3c7de6c6a",
   "metadata": {},
   "outputs": [
    {
     "ename": "ModuleNotFoundError",
     "evalue": "No module named 'fitz'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mModuleNotFoundError\u001b[0m                       Traceback (most recent call last)",
      "\u001b[0;32m/var/folders/z2/flyw6y956lz1rzq3xqs85jmw0000gn/T/ipykernel_33228/418487326.py\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m      2\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mos\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      3\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mrequests\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0;32mimport\u001b[0m \u001b[0mfitz\u001b[0m \u001b[0;31m# (pymupdf, found this is better than pypdf for our use case, note: licence is AGPL-3.0, keep that in mind if you want to use any code commercially)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m      5\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0mtqdm\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mauto\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mtqdm\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      6\u001b[0m \u001b[0;31m# Get PDF document\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mModuleNotFoundError\u001b[0m: No module named 'fitz'"
     ]
    }
   ],
   "source": [
    "# Download PDF file\n",
    "import os\n",
    "import requests\n",
    "import fitz # (pymupdf, found this is better than pypdf for our use case, note: licence is AGPL-3.0, keep that in mind if you want to use any code commercially)\n",
    "from tqdm.auto import tqdm\n",
    "# Get PDF document\n",
    "\n",
    "# Download PDF if it doesn't already exist\n",
    "if not os.path.exists(pdf_path):\n",
    "  print(\"File doesn't exist, downloading...\")\n",
    "\n",
    "  # The URL of the PDF you want to download\n",
    "  url = \"https://pressbooks.oer.hawaii.edu/humannutrition2/open/download?type=pdf\"\n",
    "\n",
    "  # The local filename to save the downloaded file\n",
    "  filename = pdf_path\n",
    "\n",
    "  # Send a GET request to the URL\n",
    "  response = requests.get(url)\n",
    "\n",
    "  # Check if the request was successful\n",
    "  if response.status_code == 200:\n",
    "      # Open a file in binary write mode and save the content to it\n",
    "      with open(filename, \"wb\") as file:\n",
    "          file.write(response.content)\n",
    "      print(f\"The file has been downloaded and saved as {filename}\")\n",
    "  else:\n",
    "      print(f\"Failed to download the file. Status code: {response.status_code}\")\n",
    "else:\n",
    "  print(f\"File {pdf_path} exists.\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a5debec4-983b-462e-b871-81b8cf3dd33b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# # Requires !pip install PyMuPDF, see: https://github.com/pymupdf/pymupdf\n",
    "# import fitz # (pymupdf, found this is better than pypdf for our use case, note: licence is AGPL-3.0, keep that in mind if you want to use any code commercially)\n",
    "# from tqdm.auto import tqdm # for progress bars, requires !pip install tqdm \n",
    "\n",
    "# def text_formatter(text: str) -> str:\n",
    "#     \"\"\"Performs minor formatting on text.\"\"\"\n",
    "#     cleaned_text = text.replace(\"\\n\", \" \").strip() # note: this might be different for each doc (best to experiment)\n",
    "\n",
    "#     # Other potential text formatting functions can go here\n",
    "#     return cleaned_text\n",
    "\n",
    "# # Open PDF and get lines/pages\n",
    "# # Note: this only focuses on text, rather than images/figures etc\n",
    "# def open_and_read_pdf(pdf_path: str) -> list[dict]:\n",
    "#     \"\"\"\n",
    "#     Opens a PDF file, reads its text content page by page, and collects statistics.\n",
    "\n",
    "#     Parameters:\n",
    "#         pdf_path (str): The file path to the PDF document to be opened and read.\n",
    "\n",
    "#     Returns:\n",
    "#         list[dict]: A list of dictionaries, each containing the page number\n",
    "#         (adjusted), character count, word count, sentence count, token count, and the extracted text\n",
    "#         for each page.\n",
    "#     \"\"\"\n",
    "#     doc = fitz.open(pdf_path)  # open a document\n",
    "#     pages_and_texts = \"\"\n",
    "#     for page_number, page in tqdm(enumerate(doc)):  # iterate the document pages\n",
    "#         text = page.get_text()  # get plain text encoded as UTF-8\n",
    "#         text = text_formatter(text)\n",
    "#         pages_and_texts+=text\n",
    "#         # pages_and_texts.append({\"page_number\": page_number - 41,  # adjust page numbers since our PDF starts on page 42\n",
    "#         #                         \"page_char_count\": len(text),\n",
    "#         #                         \"page_word_count\": len(text.split(\" \")),\n",
    "#         #                         \"page_sentence_count_raw\": len(text.split(\". \")),\n",
    "#         #                         \"page_token_count\": len(text) / 4,  # 1 token = ~4 chars, see: https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them\n",
    "#         #                         \"text\": text})\n",
    "#     return pages_and_texts\n",
    "\n",
    "# pages_and_texts = open_and_read_pdf(pdf_path=pdf_path)\n",
    "# pages_and_texts[:100]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c19560ff-2808-406a-aa70-b8c4d303121e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# !pip install fastembed"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bb8b789b-475b-4e1b-9c66-03504c837830",
   "metadata": {},
   "outputs": [],
   "source": [
    "# from langchain.text_splitter import RecursiveCharacterTextSplitter,CharacterTextSplitter\n",
    "# from langchain_community.document_loaders import WebBaseLoader\n",
    "# from langchain_community.vectorstores import Chroma\n",
    "# from langchain_mistralai import MistralAIEmbeddings\n",
    "# # from langchain_nomic.embeddings import NomicEmbeddings\n",
    "# from langchain_community.embeddings import OllamaEmbeddings\n",
    "# # ollama_emb = \n",
    "# # Load\n",
    "# from langchain_community.embeddings.fastembed import FastEmbedEmbeddings\n",
    "\n",
    "# # # Split\n",
    "# # text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(\n",
    "# #     chunk_size=500, chunk_overlap=100\n",
    "# # )\n",
    "\n",
    "# text_splitter = CharacterTextSplitter(\n",
    "#     chunk_size=1000,\n",
    "#     chunk_overlap=200,\n",
    "#     separator=\"\\n\"\n",
    "# )\n",
    "\n",
    "\n",
    "# all_splits = text_splitter.create_documents(pages_and_texts)\n",
    "\n",
    "# # Embed and index\n",
    "# if run_local == \"Yes\":\n",
    "#     embedding = FastEmbedEmbeddings(model_name=\"BAAI/bge-base-en-v1.5\",device=\"cuda\")\n",
    "\n",
    "# else:\n",
    "#     embedding = MistralAIEmbeddings(mistral_api_key=mistral_api_key)\n",
    "\n",
    "# # Index\n",
    "# vectorstore = Chroma.from_documents(\n",
    "#     documents=all_splits,\n",
    "#     collection_name=\"rag-chroma\",\n",
    "#     embedding=embedding,\n",
    "# )\n",
    "# retriever = vectorstore.as_retriever()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bc1efd13-576f-4bae-996b-81dd8f8863df",
   "metadata": {},
   "outputs": [],
   "source": [
    "import fitz  # PyMuPDF\n",
    "def text_formatter(text: str) -> str:\n",
    "    \"\"\"Performs minor formatting on text.\"\"\"\n",
    "    cleaned_text = text.replace(\"\\n\", \" \").strip() # note: this might be different for each doc (best to experiment)\n",
    "\n",
    "    # Other potential text formatting functions can go here\n",
    "    return cleaned_text\n",
    "def extract_text_from_pdf(pdf_path):\n",
    "    document = fitz.open(pdf_path)\n",
    "    pages_and_texts = []\n",
    "    for page_num in range(len(document)):\n",
    "        page = document.load_page(page_num)\n",
    "        text = page.get_text(\"text\")\n",
    "        text = text_formatter(text)\n",
    "        pages_and_texts.append(text)\n",
    "    return pages_and_texts\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "15dcb261-2197-4207-bf1d-e9d9ddcc007a",
   "metadata": {},
   "outputs": [],
   "source": [
    "pages_and_texts = basic+surgery"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4e57c3b2-060c-4f0d-aae4-d052a202ea5e",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.text_splitter import RecursiveCharacterTextSplitter, CharacterTextSplitter\n",
    "from langchain_community.document_loaders import WebBaseLoader\n",
    "from langchain_community.vectorstores import Chroma\n",
    "from sentence_transformers import SentenceTransformer\n",
    "import torch\n",
    "\n",
    "# Define your text splitter\n",
    "text_splitter = CharacterTextSplitter(\n",
    "    chunk_size=1000,\n",
    "    chunk_overlap=200,\n",
    "    separator=\" \"\n",
    ")\n",
    "\n",
    "# Assuming 'pages_and_texts' is your list of documents' text\n",
    "all_splits = text_splitter.create_documents(pages_and_texts)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dcf9e2f5-009b-4320-ad0f-23b0fd231072",
   "metadata": {},
   "outputs": [],
   "source": [
    "len(all_splits)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0b37fc4b-ee00-4523-86d6-e9657e2b8c91",
   "metadata": {},
   "outputs": [],
   "source": [
    "# !pip install langchain_openai"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cdc20558-395f-4330-83f8-13070e377526",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_community.embeddings.sentence_transformer import (\n",
    "    SentenceTransformerEmbeddings,\n",
    ")\n",
    "\n",
    "if run_local == \"Yes\":\n",
    "    embedding = SentenceTransformerEmbeddings(model_name=\"BAAI/bge-base-en-v1.5\")\n",
    "#     from langchain_openai import OpenAIEmbeddings\n",
    "\n",
    "#     embedding = OpenAIEmbeddings(api_key=\"sk-proj-KQ4DlWOH3c1mSlTGHXbqT3BlbkFJ3TxJ8nsKKJyk98rFXx1x\")\n",
    "else:\n",
    "    # Handle the case when not running locally\n",
    "    embedding = MistralAIEmbeddings(mistral_api_key=mistral_api_key)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d43b5ba7-c2e7-45b1-bcdd-156e53ef9f68",
   "metadata": {},
   "outputs": [],
   "source": [
    "all_splits[156]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9bb98da2-e40d-46e7-be5b-0f85a801b9db",
   "metadata": {},
   "outputs": [],
   "source": [
    "from tqdm.notebook import tqdm\n",
    "\n",
    "# Embed the documents with progress tracking\n",
    "embedded_docs = []\n",
    "# for doc in tqdm(all_splits, desc=\"Embedding Documents\"):\n",
    "#     embedded_docs.append(embedding.embed_documents([doc.page_content])[0])\n",
    "\n",
    "    # # Embed and index\n",
    "# if run_local == \"Yes\":\n",
    "#     embedding = FastEmbedEmbeddings(model_name=\"BAAI/bge-base-en-v1.5\",device=\"cuda\")\n",
    "\n",
    "# else:\n",
    "#     embedding = MistralAIEmbeddings(mistral_api_key=mistral_api_key)\n",
    "\n",
    "# # Index\n",
    "# vectorstore = Chroma.from_documents(\n",
    "#     documents=all_splits,\n",
    "#     collection_name=\"rag-chroma\",\n",
    "#     embedding=embedding,\n",
    "# )\n",
    "# retriever = vectorstore.as_retriever()\n",
    "    \n",
    "    \n",
    "# Store in Chroma vector store\n",
    "vectorstore = Chroma.from_documents(\n",
    "    embedding=embedding,\n",
    "    documents=all_splits,\n",
    "    collection_name=\"rag-chroma\"\n",
    ")\n",
    "\n",
    "# Use the vector store as a retriever\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f008f94e-5f17-4596-a9e3-64cc6a153249",
   "metadata": {},
   "outputs": [],
   "source": [
    "# # Embed the documents\n",
    "# embedded_docs = embedding.embed_documents([doc.page_content for doc in all_splits])\n",
    "\n",
    "# # Store in Chroma vector store\n",
    "# vectorstore = Chroma.from_embeddings(\n",
    "#     embeddings=embedded_docs,\n",
    "#     documents=all_splits,\n",
    "#     collection_name=\"rag-chroma\"\n",
    "# )\n",
    "\n",
    "# # Use the vector store as a retriever\n",
    "# retriever = vectorstore.as_retriever()\n",
    "\n",
    "retriever = vectorstore.as_retriever(search_kwargs={\"k\": 3})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "29c4d43b-0ca2-4183-81ef-abf880c4e66d",
   "metadata": {},
   "outputs": [],
   "source": [
    "retriever"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ec422828-696d-455c-9f6a-34a6dd0e6ac8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# !pip install langchain_huggingface"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fe7fd10a-f64a-48de-a116-6d5890def1af",
   "metadata": {},
   "source": [
    "## LLMs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0e75c029-6c10-47c7-871c-1f4932b25309",
   "metadata": {},
   "outputs": [],
   "source": [
    "### Retrieval Grader\n",
    "\n",
    "from langchain.prompts import PromptTemplate\n",
    "from langchain_community.chat_models import ChatOllama\n",
    "from langchain_core.output_parsers import JsonOutputParser\n",
    "from langchain_mistralai.chat_models import ChatMistralAI\n",
    "from langchain_core.messages import (\n",
    "    HumanMessage,\n",
    "    SystemMessage,\n",
    ")\n",
    "from langchain_huggingface import ChatHuggingFace\n",
    "# LLM\n",
    "\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "\n",
    "if run_local == \"Yes\":\n",
    "\n",
    "#     from langchain_huggingface.llms import HuggingFacePipeline\n",
    "\n",
    "#     hf = HuggingFacePipeline.from_model_id(\n",
    "#         model_id=\"meta-llama/Llama-2-13b-chat-hf\",\n",
    "#         task=\"text-generation\",\n",
    "#         pipeline_kwargs={\"max_new_tokens\": 256,'temperature' :1e-10},\n",
    "#         device = 0,\n",
    "#     )\n",
    "    llm = ChatOpenAI(\n",
    "        model=\"gpt-4o\",\n",
    "        temperature=0,\n",
    "        max_tokens=None,\n",
    "        timeout=None,\n",
    "        max_retries=2,\n",
    "        api_key=\"sk-proj-HuhcUUXH7vs9SxE26VvdT3BlbkFJX8cOCyM7wDb3ZMoxmnRS\",  # if you prefer to pass api key in directly instaed of using env vars\n",
    "        # base_url=\"...\",\n",
    "        # organization=\"...\",\n",
    "        # other params...\n",
    "    )\n",
    "    # chat_model = ChatHuggingFace(llm=llm)\n",
    "    chat_model = llm\n",
    "else:\n",
    "    llm = ChatMistralAI(\n",
    "        model=\"mistral-medium\", temperature=0, mistral_api_key=mistral_api_key\n",
    "    )\n",
    "    print(\"yesmistral\")\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7c719323-f184-4747-9479-7414deeffd01",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.prompts import (\n",
    "    ChatPromptTemplate,\n",
    "    FewShotChatMessagePromptTemplate,\n",
    ")\n",
    "examples = [\n",
    "    {\"input\": \"\"\"Here is the retrieved document: \n",
    "\n",
    " are packaged into the lipid-containing chylomicrons inside small intestine mucosal cells and then transported to the liver. In the liver, carotenoids are repackaged into lipoproteins, which transport them to cells. The retinoids are aptly named as their most notable function is in the retina of the eye where they aid in vision, particularly in seeing under low-light conditions. This is why night blindness is the most definitive sign of vitamin A deficiency.Vitamin A has several important functions in the body, including maintaining vision and a healthy immune system. Many of vitamin A’s functions in the body are similar to the functions of hormones (for example, vitamin A can interact with DNA, causing a change in protein function). Vitamin A assists in maintaining healthy skin and the linings and coverings of tissues; it also regulates growth and development. As an antioxidant, vitamin A protects cellular membranes, helps in maintaining glutathione levels, and influences the amount \n",
    "\n",
    " \n",
    "     Here is the user question: What is Vitamin A? Is this retrieved document relevant to user question? Yes or no.\"\"\", \"output\": \"yes\"},\n",
    "\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cfa8ab09-61cc-413b-b9c5-754792f2d1a9",
   "metadata": {},
   "outputs": [],
   "source": [
    "example_prompt = ChatPromptTemplate.from_messages(\n",
    "    [\n",
    "        (\"human\", \"{input}\"),\n",
    "        (\"ai\", \"{output}\"),\n",
    "    ]\n",
    ")\n",
    "few_shot_prompt = FewShotChatMessagePromptTemplate(\n",
    "    example_prompt=example_prompt,\n",
    "    examples=examples,\n",
    ")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0e76ba41-f6ab-4cd8-bf35-d9ebaada3600",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "from langchain_core.output_parsers import StrOutputParser\n",
    "# prompt = PromptTemplate(\n",
    "#     template=\"\"\"You are a grader assessing relevance of a retrieved document to a user question. \\n \n",
    "#     Here is the retrieved document: \\n\\n {document} \\n\\n \n",
    "#     Here is the user question: {question} \\n \n",
    "#     Is this retrieved document relevant to user question? Yes or no. \"\"\",\n",
    "#     input_variables=[\"question\", \"document\"],\n",
    "# )\n",
    "\n",
    "# messages = [\n",
    "#     SystemMessage(content=\"You are a grader assessing relevance of a retrieved document to a user question. Your answer should only be 'yes' or 'no'\"),\n",
    "#     HumanMessage(\n",
    "#         content=\"What happens when an unstoppable force meets an immovable object?\"\n",
    "#     ),\n",
    "# ]\n",
    "prompt = ChatPromptTemplate.from_messages(\n",
    "    [\n",
    "        (\"system\", \"You are a grader assessing relevance of a retrieved document to a user question. Your answer should only be 'yes' or 'no'\"),\n",
    "        few_shot_prompt,\n",
    "        (\"human\", \"\"\"Here is the retrieved document: \\n\\n {document} \\n\\n \n",
    "     Here is the user question: {question} \\n \n",
    "     Is this retrieved document relevant to user question? Yes or no. \"\"\"),\n",
    "    ]\n",
    ")\n",
    "\n",
    "retrieval_grader = prompt | chat_model \n",
    "question = \"what is Vitamin D?\"\n",
    "docs = retriever.get_relevant_documents(question)\n",
    "doc_txt = docs[1].page_content\n",
    "print(retrieval_grader.invoke({\"question\": question, \"document\": doc_txt}))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fdf3f319-9448-4706-b042-c292d0fb3283",
   "metadata": {},
   "outputs": [],
   "source": [
    "docs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dad03302-bd93-43fc-949e-af51a3298cfa",
   "metadata": {},
   "outputs": [],
   "source": [
    "### Generate\n",
    "\n",
    "from langchain import hub\n",
    "\n",
    "# Prompt\n",
    "prompt = hub.pull(\"rlm/rag-prompt\")\n",
    "\n",
    "\n",
    "# Post-processing\n",
    "def format_docs(docs):\n",
    "    return \"\\n\\n\".join(doc.page_content for doc in docs)\n",
    "\n",
    "\n",
    "# Chain\n",
    "rag_chain = prompt | chat_model | StrOutputParser()\n",
    "\n",
    "# Run\n",
    "generation = rag_chain.invoke({\"context\": docs, \"question\": question})\n",
    "print(generation)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f4b61211-70b5-4471-a714-feb9cc91e860",
   "metadata": {},
   "outputs": [],
   "source": [
    "examples2 = [\n",
    "    {\"input\": \"\"\"Here is the initial question: \\n what is Vitamin D? \\n Write me an improved question only with no explanation: \"\"\", \"output\": \"What are the key properties and benefits of vitamin D, and how does it contribute to maintaining overall health and wellness?\"},\n",
    "\n",
    "]\n",
    "\n",
    "example_prompt2 = ChatPromptTemplate.from_messages(\n",
    "    [\n",
    "        (\"human\", \"{input}\"),\n",
    "        (\"ai\", \"{output}\"),\n",
    "    ]\n",
    ")\n",
    "few_shot_prompt2 = FewShotChatMessagePromptTemplate(\n",
    "    example_prompt=example_prompt2,\n",
    "    examples=examples2,\n",
    ")\n",
    "\n",
    "re_write_prompt = ChatPromptTemplate.from_messages(\n",
    "    [\n",
    "        (\"system\", \"You a question re-writer that converts an input question to a better version that is optimized for vectorstore retrieval. Look at the initial and formulate an improved question.\"),\n",
    "        few_shot_prompt2,\n",
    "        (\"human\", \"\"\"Here is the initial question: \\n\\n {question} \\n\\n \n",
    "     Write me an improved question only with no explanation:  \"\"\"),\n",
    "        \n",
    "    ]\n",
    ")\n",
    "\n",
    "question = \"what is love?\"\n",
    "# re_write_prompt = PromptTemplate(\n",
    "#     template=\"\"\"You a question re-writer that converts an input question to a better version that is optimized \\n \n",
    "#      for vectorstore retrieval. Look at the initial and formulate an improved question. \\n\n",
    "#      Here is the initial question: \\n\\n {question}. Improved question with no explanation: \\n \"\"\",\n",
    "#     input_variables=[\"generation\", \"question\"],\n",
    "# )\n",
    "\n",
    "question_rewriter = re_write_prompt | chat_model | StrOutputParser()\n",
    "question_rewriter.invoke({\"question\": question})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5cd97fcd-218c-431b-8447-2a88cface6f6",
   "metadata": {},
   "source": [
    "# Translator"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "63857bdd-5c99-456a-a2cf-8ffb4319e610",
   "metadata": {},
   "outputs": [],
   "source": [
    "# \n",
    "\n",
    "translate_prompt = ChatPromptTemplate.from_messages(\n",
    "    [\n",
    "        (\"system\", \"You are a multilingual medical question translator, if the input question is in english, directly return the question. If it is in Portuguese/Spanish/Filipino, directly return the question translated in English.\"),\n",
    "        (\"human\", \"\"\"Here is the initial question: \\n\\n {question} \\n\\n \n",
    "     If not in English, return the question in English ONLY:  \"\"\"),   \n",
    "    ]\n",
    ")\n",
    "\n",
    "question = \"\"\"\"\n",
    "什么是视网膜? A 眼球 B 视网膜 C 视神经 D不知道\"\"\"\n",
    "\n",
    "\n",
    "question_translator = translate_prompt | chat_model | StrOutputParser()\n",
    "question_translator.invoke({\"question\": question})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5d7fde29-e62e-4445-80f9-122eee0a3922",
   "metadata": {},
   "source": [
    "## Web Search Tool"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b36a2f36-bc5f-408d-a5e8-3fa203c233f6",
   "metadata": {},
   "outputs": [],
   "source": [
    "### Search\n",
    "\n",
    "from langchain_community.tools.tavily_search import TavilySearchResults\n",
    "\n",
    "web_search_tool = TavilySearchResults(k=3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a3421cf0-9067-43fe-8681-0d3189d15dd3",
   "metadata": {},
   "source": [
    "# Graph \n",
    "\n",
    "Capture the flow in as a graph.\n",
    "\n",
    "## Graph state"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "10028794-2fbc-43f9-aa4c-7fe3abd69c1e",
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "\n",
    "from typing_extensions import TypedDict\n",
    "\n",
    "\n",
    "class GraphState(TypedDict):\n",
    "    \"\"\"\n",
    "    Represents the state of our graph.\n",
    "\n",
    "    Attributes:\n",
    "        question: question\n",
    "        generation: LLM generation\n",
    "        web_search: whether to add search\n",
    "        documents: list of documents\n",
    "    \"\"\"\n",
    "\n",
    "    question: str\n",
    "    generation: str\n",
    "    web_search: str\n",
    "    documents: List[str]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "447d1333-082d-479a-a6fa-0ac0df78bb9d",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.schema import Document\n",
    "\n",
    "\n",
    "def translate(state):\n",
    "    \"\"\"\n",
    "    Translate to english\n",
    "    \"\"\"\n",
    "    print(\"---Translate---\")\n",
    "    question = state[\"question\"]\n",
    "\n",
    "    # Retrieval\n",
    "    question = question_translator.invoke({\"question\": question})\n",
    "    return {\"question\": question}\n",
    "\n",
    "\n",
    "def retrieve(state):\n",
    "    \"\"\"\n",
    "    Retrieve documents\n",
    "\n",
    "    Args:\n",
    "        state (dict): The current graph state\n",
    "\n",
    "    Returns:ß\n",
    "        state (dict): New key added to state, documents, that contains retrieved documents\n",
    "    \"\"\"\n",
    "    print(\"---RETRIEVE---\")\n",
    "    question = state[\"question\"]\n",
    "\n",
    "    # Retrieval\n",
    "    documents = retriever.get_relevant_documents(question)\n",
    "    return {\"documents\": documents, \"question\": question}\n",
    "\n",
    "\n",
    "def generate(state):\n",
    "    \"\"\"\n",
    "    Generate answer\n",
    "\n",
    "    Args:\n",
    "        state (dict): The current graph state\n",
    "\n",
    "    Returns:\n",
    "        state (dict): New key added to state, generation, that contains LLM generation\n",
    "    \"\"\"\n",
    "    print(\"---GENERATE---\")\n",
    "    question = state[\"question\"]\n",
    "    documents = state[\"documents\"]\n",
    "\n",
    "    # RAG generation\n",
    "    generation = rag_chain.invoke({\"context\": documents, \"question\": question})\n",
    "    return {\"documents\": documents, \"question\": question, \"generation\": generation}\n",
    "\n",
    "\n",
    "def grade_documents(state):\n",
    "    \"\"\"\n",
    "    Determines whether the retrieved documents are relevant to the question.\n",
    "\n",
    "    Args:\n",
    "        state (dict): The current graph state\n",
    "\n",
    "    Returns:\n",
    "        state (dict): Updates documents key with only filtered relevant documents\n",
    "    \"\"\"\n",
    "\n",
    "    print(\"---CHECK DOCUMENT RELEVANCE TO QUESTION---\")\n",
    "    question = state[\"question\"]\n",
    "    documents = state[\"documents\"]\n",
    "\n",
    "    # Score each doc\n",
    "    filtered_docs = []\n",
    "    web_search = \"No\"\n",
    "    for d in documents:\n",
    "        score = retrieval_grader.invoke(\n",
    "            {\"question\": question, \"document\": d.page_content}\n",
    "        )\n",
    "        print(\"SC\", score)\n",
    "        grade = score.content\n",
    "        if grade == \"yes\":\n",
    "            print(\"---GRADE: DOCUMENT RELEVANT---\")\n",
    "            filtered_docs.append(d)\n",
    "        else:\n",
    "            print(\"---GRADE: DOCUMENT NOT RELEVANT---\")\n",
    "            web_search = \"Yes\"\n",
    "            continue\n",
    "    return {\"documents\": filtered_docs, \"question\": question, \"web_search\": web_search}\n",
    "\n",
    "\n",
    "def transform_query(state):\n",
    "    \"\"\"\n",
    "    Transform the query to produce a better question.\n",
    "\n",
    "    Args:\n",
    "        state (dict): The current graph state\n",
    "\n",
    "    Returns:\n",
    "        state (dict): Updates question key with a re-phrased question\n",
    "    \"\"\"\n",
    "\n",
    "    print(\"---TRANSFORM QUERY---\")\n",
    "    question = state[\"question\"]\n",
    "    documents = state[\"documents\"]\n",
    "\n",
    "    # Re-write question\n",
    "    # better_question = question_rewriter.invoke({\"question\": question})\n",
    "    return {\"documents\": documents, \"question\": question}\n",
    "\n",
    "\n",
    "def web_search(state):\n",
    "    \"\"\"\n",
    "    Web search based on the re-phrased question.\n",
    "\n",
    "    Args:\n",
    "        state (dict): The current graph state\n",
    "\n",
    "    Returns:\n",
    "        state (dict): Updates documents key with appended web results\n",
    "    \"\"\"\n",
    "\n",
    "    print(\"---WEB SEARCH---\")\n",
    "    question = state[\"question\"]\n",
    "    documents = state[\"documents\"]\n",
    "    print(\"WEB SEARCH\", question)\n",
    "    # Web search\n",
    "    docs = web_search_tool.invoke({\"query\":  question[:100]})\n",
    "\n",
    "    web_results = \"\\n\".join([d[\"content\"] for d in docs])\n",
    "\n",
    "    web_results = Document(page_content=web_results)\n",
    "    documents.append(web_results)\n",
    "\n",
    "    return {\"documents\": documents, \"question\": question}\n",
    "\n",
    "\n",
    "### Edges\n",
    "\n",
    "\n",
    "def decide_to_generate(state):\n",
    "    \"\"\"\n",
    "    Determines whether to generate an answer, or re-generate a question.\n",
    "\n",
    "    Args:\n",
    "        state (dict): The current graph state\n",
    "\n",
    "    Returns:\n",
    "        str: Binary decision for next node to call\n",
    "    \"\"\"\n",
    "\n",
    "    print(\"---ASSESS GRADED DOCUMENTS---\")\n",
    "    state[\"question\"]\n",
    "    web_search = state[\"web_search\"]\n",
    "    state[\"documents\"]\n",
    "\n",
    "    if web_search == \"Yes\":\n",
    "        # All documents have been filtered check_relevance\n",
    "        # We will re-generate a new query\n",
    "        print(\n",
    "            \"---DECISION: ALL DOCUMENTS ARE NOT RELEVANT TO QUESTION, TRANSFORM QUERY---\"\n",
    "        )\n",
    "        return \"transform_query\"\n",
    "    else:\n",
    "        # We have relevant documents, so generate answer\n",
    "        print(\"---DECISION: GENERATE---\")\n",
    "        return \"generate\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6096626d-dfa5-48e0-8a24-3747b298bc67",
   "metadata": {},
   "source": [
    "## Build Graph\n",
    "\n",
    "This just follows the flow we outlined in the figure above."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0a63776c-f9cd-46ce-b8cf-95c066dc5b06",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langgraph.graph import END, StateGraph\n",
    "\n",
    "workflow = StateGraph(GraphState)\n",
    "\n",
    "# Define the nodes\n",
    "workflow.add_node(\"translate\", translate)\n",
    "workflow.add_node(\"retrieve\", retrieve)  # retrieve\n",
    "workflow.add_node(\"grade_documents\", grade_documents)  # grade documents\n",
    "workflow.add_node(\"generate\", generate)  # generatae\n",
    "workflow.add_node(\"transform_query\", transform_query)  # transform_query\n",
    "workflow.add_node(\"web_search_node\", web_search)  # web search\n",
    "\n",
    "# Build graph\n",
    "workflow.set_entry_point(\"translate\")\n",
    "workflow.add_edge(\"translate\",\"retrieve\")\n",
    "workflow.add_edge(\"retrieve\", \"grade_documents\")\n",
    "workflow.add_conditional_edges(\n",
    "    \"grade_documents\",\n",
    "    decide_to_generate,\n",
    "    {\n",
    "        \"transform_query\": \"transform_query\",\n",
    "        \"generate\": \"generate\",\n",
    "    },\n",
    ")\n",
    "workflow.add_edge(\"transform_query\", \"web_search_node\")\n",
    "workflow.add_edge(\"web_search_node\", \"generate\")\n",
    "workflow.add_edge(\"generate\", END)\n",
    "\n",
    "# Compile\n",
    "app = workflow.compile()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "54623177-0572-4f9a-b32c-0de3bec45b01",
   "metadata": {},
   "outputs": [],
   "source": [
    "QA"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3b32741c-dbca-4075-ba80-c45e3728059e",
   "metadata": {},
   "outputs": [],
   "source": [
    "q_phi =QA['spanish'].copy()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3ab1d8df-a74e-4b48-a30b-e39bbfd5925a",
   "metadata": {},
   "outputs": [],
   "source": [
    "from pprint import pprint\n",
    "results_phi = []\n",
    "from tqdm.notebook import tqdm\n",
    "for q_e in tqdm(q_phi): \n",
    "    inputs = {\"question\": \"Only answer in a,b,c,d.\" +q_e }\n",
    "    for output in app.stream(inputs):\n",
    "        for key, value in output.items():\n",
    "            # Node\n",
    "            pprint(f\"Node '{key}':\")\n",
    "            # Optional: print full state at each node\n",
    "            # pprint.pprint(value[\"keys\"], indent=2, width=80, depth=None)\n",
    "        pprint(\"\\n---\\n\")\n",
    "\n",
    "    # Final generation\n",
    "    pprint(value[\"generation\"])\n",
    "    results_phi.append(value[\"generation\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4837cd9d-a86b-4611-b7b8-f85d2df6edae",
   "metadata": {},
   "outputs": [],
   "source": [
    "len(results_phi)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "71777932-7710-47d8-93dc-2a1657c48909",
   "metadata": {},
   "outputs": [],
   "source": [
    "import csv\n",
    "file_name = 'output_spanish.csv'\n",
    "\n",
    "# Open the file in write mode\n",
    "with open(file_name, mode='w', newline='') as file:\n",
    "    writer = csv.writer(file)\n",
    "\n",
    "    # Write each item in the list as a new row in the CSV file\n",
    "    for item in results_phi:\n",
    "        writer.writerow([item]) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "71b2cd11-9435-4a47-9027-3c2718dd5284",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "\n",
    "# Find all indexes of strings that start with \"I don\"\n",
    "indexes = [index for index, item in enumerate(results_phi) if item.startswith(\"I don\")]\n",
    "\n",
    "print(indexes)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "44c29209-f759-445d-ba52-79b6019fd6de",
   "metadata": {},
   "outputs": [],
   "source": [
    "len(indexes)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "614970c7-02bf-4ee4-9e78-cd025b2e43bf",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "res = pd.read_csv(\"output_spanish.csv\",header=None)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ab9393e4-8b9b-4bf0-970a-8ebb54b83246",
   "metadata": {},
   "outputs": [],
   "source": [
    "res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "50a5d9c6-dd60-4033-9e20-673d2cdd50cc",
   "metadata": {},
   "outputs": [],
   "source": [
    "gt = QA.answer.str.lower().tolist()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c86b57dd-7d6f-4b1e-9566-d9ebc8b10b5d",
   "metadata": {},
   "outputs": [],
   "source": [
    "preds = res[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fa6fc4a4-cd10-44a7-926f-6bdbc68345bc",
   "metadata": {},
   "outputs": [],
   "source": [
    "first_chars = [s[0] for s in preds if s]  # the 'if s' ensures the string is not empty\n",
    "\n",
    "print(first_chars)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "935cb5e2-d9e2-4c08-9989-44d4cc6cac8e",
   "metadata": {},
   "outputs": [],
   "source": [
    "(np.array(first_chars) == np.array(gt)).sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "362733c3-b419-46b4-8b52-88f6473eb1a2",
   "metadata": {},
   "outputs": [],
   "source": [
    "(np.array(first_chars) == np.array(gt)).sum()/164"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6d927ae5-9179-400e-85f2-23a8afa01dc1",
   "metadata": {},
   "outputs": [],
   "source": [
    "from pprint import pprint\n",
    "results_phi2 = []\n",
    "from tqdm.notebook import tqdm\n",
    "for q_e in tqdm(q_phi[indexes]): \n",
    "    inputs = {\"question\": \"Only answer in a,b,c,d.\" +q_e }\n",
    "    for output in app.stream(inputs):\n",
    "        for key, value in output.items():\n",
    "            # Node\n",
    "            pprint(f\"Node '{key}':\")\n",
    "            # Optional: print full state at each node\n",
    "            # pprint.pprint(value[\"keys\"], indent=2, width=80, depth=None)\n",
    "        pprint(\"\\n---\\n\")\n",
    "\n",
    "    # Final generation\n",
    "    pprint(value[\"generation\"])\n",
    "    results_phi2.append(value[\"generation\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5fdece1a-2159-458e-b1a9-e85c518475eb",
   "metadata": {},
   "outputs": [],
   "source": [
    "gt_2 = np.array(QA.answer.str.lower().tolist())[indexes]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8cbc16c8-55ea-4aff-bade-f43d20332a6d",
   "metadata": {},
   "outputs": [],
   "source": [
    "first_chars2 = [s[0] for s in results_phi2 if s]  # the 'if s' ensures the string is not empty\n",
    "\n",
    "print(first_chars2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0666dfbb-6273-41e9-8d75-a1ccd118c7e4",
   "metadata": {},
   "outputs": [],
   "source": [
    "((gt_2==first_chars2).sum()+(np.array(first_chars) == np.array(gt)).sum() )/164"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "565853fc-73f9-47b4-ad88-bf0831335006",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b9a18a07-0965-4d33-b6f9-5b4f96144a1f",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "106e7d28-9a6f-41d4-a61c-a3aba19e7649",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.9.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}