File size: 51,928 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
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "83f74055-d137-466c-9555-4e2da9759ddb",
   "metadata": {},
   "source": [
    "### Search\n",
    " \n",
    "We'll use [Tavily Search](https://python.langchain.com/docs/integrations/tools/tavily_search) for web search."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "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": 37,
   "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": 38,
   "id": "2f4db331-c4d0-4c7c-a9a5-0bebc8a89c6c",
   "metadata": {},
   "outputs": [],
   "source": [
    "run_local = \"Yes\"\n",
    "local_llm = \"llama2-13b\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "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": 2,
   "id": "d3f4d43f-eb93-4f7d-9cab-1ab3c7de6c6a",
   "metadata": {},
   "outputs": [],
   "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",
    "pdf_path = \"\"\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": 41,
   "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": 42,
   "id": "c19560ff-2808-406a-aa70-b8c4d303121e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# !pip install fastembed"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "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": 44,
   "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": 46,
   "id": "15dcb261-2197-4207-bf1d-e9d9ddcc007a",
   "metadata": {},
   "outputs": [],
   "source": [
    "pages_and_texts = basic+surgery"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "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": 49,
   "id": "0b37fc4b-ee00-4523-86d6-e9657e2b8c91",
   "metadata": {},
   "outputs": [],
   "source": [
    "# !pip install langchain_openai"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "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": 51,
   "id": "d43b5ba7-c2e7-45b1-bcdd-156e53ef9f68",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Document(page_content='CHAPTER 2 Diagnostic tests and their interpretation 54 Automated perimetry: performance and interpretation (2) Interpretation of Humphrey perimetry (cont.) Table 2.4 Global indices (a summary of the results as a single number used to monitor change) Mean deviation (MD) A measure of overall fi eld loss. Pattern standard deviation (PSD) Measure of focal loss or variability within the fi eld, taking into account any generalized depression. An increased PSD is more indicative of glaucomatous fi eld loss than MD. Short-term fl uctuation (SF) An indication of the consistency of responses. It is assessed by measuring threshold twice at 10 preselected points and calculated on the difference between the fi rst and second measurements. Corrected pattern standard deviation (CPSD) A measure of variability within the fi eld after correcting for SF (intratest variability). Table 2.3 Typical graphical results from automated perimetry (Fig. 2.2) Gray scale Decreasing sensitivity is represented by the darker')"
      ]
     },
     "execution_count": 51,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "all_splits[156]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "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": 53,
   "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": 54,
   "id": "29c4d43b-0ca2-4183-81ef-abf880c4e66d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "VectorStoreRetriever(tags=['Chroma', 'HuggingFaceEmbeddings'], vectorstore=<langchain_community.vectorstores.chroma.Chroma object at 0x14c041973550>, search_kwargs={'k': 3})"
      ]
     },
     "execution_count": 54,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "retriever"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "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": 56,
   "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-3.5-turbo-0125\",\n",
    "        temperature=0,\n",
    "        max_tokens=None,\n",
    "        timeout=None,\n",
    "        max_retries=2,\n",
    "        api_key=\"\",  # 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": 57,
   "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": 58,
   "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": 59,
   "id": "0e76ba41-f6ab-4cd8-bf35-d9ebaada3600",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "content='no' response_metadata={'token_usage': {'completion_tokens': 1, 'prompt_tokens': 534, 'total_tokens': 535}, 'model_name': 'gpt-3.5-turbo-0125', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None} id='run-ed0b1a12-eb21-450d-87ef-d8c18b292d0a-0' usage_metadata={'input_tokens': 534, 'output_tokens': 1, 'total_tokens': 535}\n"
     ]
    }
   ],
   "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": 60,
   "id": "fdf3f319-9448-4706-b042-c292d0fb3283",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[Document(page_content='corticosteroid use, and diabetes mellitus. Nutritional or vitamin supplementation has not consistently been shown to be useful in preventing cataract formation. Pathogenesis The way in which these factors cause cataracts is unclear, although a com- mon pathway appears to be protein denaturation (e.g., by oxidative stress). Metabolic disturbance (hyperglycemia in diabetes mellitus or hyperuremia in dehydration or renal failure), toxins (e.g., smoking, alcohol), loss of anti-oxidant enzymes (e.g., superoxide dismutase), membrane disruption, reduced metabolism, failure of active transport, and loss of ionic–osmotic balance may all contribute to this process. Clinical presentations Common Change in vision—reduced acuity, contrast sensitivity, or color • appreciation, glare, monocular diplopia, or ghosting. Change in refraction—typically a myopic shift due to nuclear sclerosis. • Change in fundus view—clinicians may have diffi culty “looking in” • long before the patients feel they have diffi'),\n",
       " Document(page_content='corticosteroid use, and diabetes mellitus. Nutritional or vitamin supplementation has not consistently been shown to be useful in preventing cataract formation. Pathogenesis The way in which these factors cause cataracts is unclear, although a com- mon pathway appears to be protein denaturation (e.g., by oxidative stress). Metabolic disturbance (hyperglycemia in diabetes mellitus or hyperuremia in dehydration or renal failure), toxins (e.g., smoking, alcohol), loss of anti-oxidant enzymes (e.g., superoxide dismutase), membrane disruption, reduced metabolism, failure of active transport, and loss of ionic–osmotic balance may all contribute to this process. Clinical presentations Common Change in vision—reduced acuity, contrast sensitivity, or color • appreciation, glare, monocular diplopia, or ghosting. Change in refraction—typically a myopic shift due to nuclear sclerosis. • Change in fundus view—clinicians may have diffi culty “looking in” • long before the patients feel they have diffi'),\n",
       " Document(page_content='dysgenesis Peters anomaly Rieger syndrome Metabolic Carbohydrate Hypoglycemia Galactokinase defi ciency Galactosemia, Mannosidosis Lipids Abetalipoproteinemia Amino acid Lowe syndrome Homocysteinuria Sphingolipidoses Niemann–Pick disease Fabry disease Minerals Wilson disease Hypocalcemia Phytanic acid Refsum disease Endocrine Diabetes mellitus Hypoparathyroidism Infective Toxoplasma Rubella Herpes group (CMV, HSV1 & 2, VZV) Syphilis Measles Poliomyelitis Infl uenza Other Trauma Drugs (steroids) Eczema Radiation')]"
      ]
     },
     "execution_count": 60,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "docs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "id": "dad03302-bd93-43fc-949e-af51a3298cfa",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Vitamin D is a nutrient that helps the body absorb calcium and phosphorus, which are essential for bone health. It can be obtained through sunlight exposure, certain foods, and supplements. Deficiency in Vitamin D can lead to bone disorders like rickets or osteomalacia.\n"
     ]
    }
   ],
   "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": 62,
   "id": "f4b61211-70b5-4471-a714-feb9cc91e860",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'What are the fundamental aspects and significance of love in human relationships and emotional well-being?'"
      ]
     },
     "execution_count": 62,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "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": 63,
   "id": "63857bdd-5c99-456a-a2cf-8ffb4319e610",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"What is the retina? A eyeball B retina C optic nerve D don't know\""
      ]
     },
     "execution_count": 63,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "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": 64,
   "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": "8edf5e5b-8633-4cd6-8498-bf39016c7c6c",
   "metadata": {},
   "source": [
    "# generateor"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "id": "7ae7b15d-f255-4a19-93e3-25b462efff7a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'B 视网膜。视网膜是眼睛内部的一层组织,位于眼球的后部,包含了感光细胞,负责接收光线并将其转化为神经信号,然后通过视神经传送到大脑,使我们能够看到周围的世界。'"
      ]
     },
     "execution_count": 65,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\n",
    "gen_prompt =ChatPromptTemplate.from_messages([ \"human\", \"{question}\"])\n",
    "genner = gen_prompt | chat_model | StrOutputParser()\n",
    "genner.invoke({\"question\": question})"
   ]
  },
  {
   "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": 66,
   "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": 67,
   "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": 68,
   "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(\"generate\", generate)  # generatae\n",
    "\n",
    "# Build graph\n",
    "workflow.set_entry_point(\"translate\")\n",
    "workflow.add_edge(\"translate\",\"generate\")\n",
    "workflow.add_edge(\"generate\", END)\n",
    "\n",
    "# Compile\n",
    "app = workflow.compile()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "id": "39f83ebf-fd20-47f9-8811-0031132315b8",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "from tqdm.notebook import tqdm\n",
    "import csv\n",
    "\n",
    "# Load dataset\n",
    "QA = pd.read_csv('')\n",
    "q_eng = QA['english'].copy()\n",
    "\n",
    "# Function to generate answers\n",
    "def generate_answers(questions):\n",
    "    results = []\n",
    "    for q_e in tqdm(questions): \n",
    "        inputs = {\"question\": \"You are an expert medical assistant.\\\n",
    "You will be provided with medical queries, answer only in a,b,c,d:\" + q_e}\n",
    "        for output in app.stream(inputs):\n",
    "            for key, value in output.items():\n",
    "                pass\n",
    "        results.append(value[\"generation\"])\n",
    "    return results\n",
    "\n",
    "# Initial generation\n",
    "results_eng = generate_answers(q_eng)\n",
    "\n",
    "# Open the file in write mode\n",
    "file_name = 'en3.5t2.csv'\n",
    "with open(file_name, mode='w', newline='') as file:\n",
    "    writer = csv.writer(file)\n",
    "    for item in results_eng:\n",
    "        writer.writerow([item]) \n",
    "\n",
    "# Function to check if answers are valid\n",
    "def are_valid_answers(answers):\n",
    "    valid_answers = {'a', 'b', 'c', 'd'}\n",
    "    return [answer[0] in valid_answers for answer in answers]\n",
    "\n",
    "# Iteratively generate answers until all are valid or patience level is reached\n",
    "iteration = 0\n",
    "patience = 10\n",
    "valid_flags = are_valid_answers(results_eng)\n",
    "\n",
    "while not all(valid_flags) and iteration < patience:\n",
    "    iteration += 1\n",
    "    num_valid = sum(valid_flags)\n",
    "    num_invalid = len(valid_flags) - num_valid\n",
    "    print(f\"Iteration {iteration}: {num_valid} valid answers, {num_invalid} invalid answers\")\n",
    "    \n",
    "    # Find indexes of invalid answers\n",
    "    invalid_indexes = [index for index, is_valid in enumerate(valid_flags) if not is_valid]\n",
    "    \n",
    "    # Generate new answers for invalid questions\n",
    "    invalid_questions = [q_eng[index] for index in invalid_indexes]\n",
    "    new_answers = generate_answers(invalid_questions)\n",
    "    \n",
    "    # Update results with new answers\n",
    "    for i, index in enumerate(invalid_indexes):\n",
    "        results_eng[index] = new_answers[i]\n",
    "    \n",
    "    # Re-check validity of all answers\n",
    "    valid_flags = are_valid_answers(results_eng)\n",
    "\n",
    "# Final status\n",
    "if all(valid_flags):\n",
    "    print(\"All answers are now valid.\")\n",
    "else:\n",
    "    print(\"Reached patience limit. Some answers are still invalid.\")\n",
    "\n",
    "# Final comparison with ground truth\n",
    "res = pd.DataFrame(results_eng, columns=['answer'])\n",
    "gt = QA.answer.str.lower().tolist()\n",
    "preds = res['answer'].str[0].tolist()  # Take only the first character\n",
    "first_chars = [s[0] for s in preds if s]  # Ensure the string is not empty\n",
    "\n",
    "print(first_chars)\n",
    "print((np.array(first_chars) == np.array(gt)).sum())\n",
    "\n",
    "# Save final results to CSV\n",
    "file_name_final = 'en_3.5t2.csv'\n",
    "with open(file_name_final, mode='w', newline='') as file:\n",
    "    writer = csv.writer(file)\n",
    "    for item in results_eng:\n",
    "        writer.writerow([item])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "id": "0fd3b01c-eba8-49ee-9683-8052613c9f5a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "from tqdm.notebook import tqdm\n",
    "import csv\n",
    "\n",
    "# Open the file in write mode\n",
    "file_name = 'en3.5t2.csv'\n",
    "with open(file_name, mode='w', newline='') as file:\n",
    "    writer = csv.writer(file)\n",
    "    for item in results_eng:\n",
    "        writer.writerow([item]) \n",
    "\n",
    "# Function to check if answers are valid\n",
    "def are_valid_answers(answers):\n",
    "    valid_answers = {'a', 'b', 'c', 'd'}\n",
    "    return [answer[0] in valid_answers for answer in answers]\n",
    "\n",
    "# Iteratively generate answers until all are valid or patience level is reached\n",
    "iteration = 0\n",
    "patience = 10\n",
    "valid_flags = are_valid_answers(results_eng)\n",
    "\n",
    "while not all(valid_flags) and iteration < patience:\n",
    "    iteration += 1\n",
    "    num_valid = sum(valid_flags)\n",
    "    num_invalid = len(valid_flags) - num_valid\n",
    "    print(f\"Iteration {iteration}: {num_valid} valid answers, {num_invalid} invalid answers\")\n",
    "    \n",
    "    # Find indexes of invalid answers\n",
    "    invalid_indexes = [index for index, is_valid in enumerate(valid_flags) if not is_valid]\n",
    "    \n",
    "    # Generate new answers for invalid questions\n",
    "    invalid_questions = [q_eng[index] for index in invalid_indexes]\n",
    "    new_answers = generate_answers(invalid_questions)\n",
    "    \n",
    "    # Update results with new answers\n",
    "    for i, index in enumerate(invalid_indexes):\n",
    "        results_eng[index] = new_answers[i]\n",
    "    \n",
    "    # Re-check validity of all answers\n",
    "    valid_flags = are_valid_answers(results_eng)\n",
    "\n",
    "# Final status\n",
    "if all(valid_flags):\n",
    "    print(\"All answers are now valid.\")\n",
    "else:\n",
    "    print(\"Reached patience limit. Some answers are still invalid.\")\n",
    "\n",
    "# Final comparison with ground truth\n",
    "res = pd.DataFrame(results_eng, columns=['answer'])\n",
    "gt = QA.answer.str.lower().tolist()\n",
    "preds = res['answer'].str[0].tolist()  # Take only the first character\n",
    "first_chars = [s[0] for s in preds if s]  # Ensure the string is not empty\n",
    "\n",
    "print(first_chars)\n",
    "print((np.array(first_chars) == np.array(gt)).sum())\n",
    "\n",
    "# Save final results to CSV\n",
    "file_name_final = 'en_3.5t2.csv'\n",
    "with open(file_name_final, mode='w', newline='') as file:\n",
    "    writer = csv.writer(file)\n",
    "    for item in results_eng:\n",
    "        writer.writerow([item])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "id": "acb4e714-cd85-4bbd-8624-638d071de3b3",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "from langchain import hub\n",
    "from langchain.prompts import PromptTemplate\n",
    "from tqdm.notebook import tqdm\n",
    "import csv\n",
    "import json\n",
    "\n",
    "# Define the generate_prompt function\n",
    "def generate_prompt(LANGUAGES, REASONING, Responses=['A', 'B', 'C', 'D']):\n",
    "    delimiter = \"####\"\n",
    "    languages_text = \", \".join(LANGUAGES)\n",
    "    responses_text = \", \".join(Responses)\n",
    "\n",
    "    system_message = f\"\"\"You are an expert medical assistant.\\\n",
    "    You will be provided with medical queries in these languages: {languages_text}. \\\n",
    "    Answer the question as best as possible.\"\"\"\n",
    "\n",
    "    template = system_message + \"\\n{format_instructions}\\n{question}\"\n",
    "\n",
    "    response_schema = {\n",
    "        \"name\": \"response\",\n",
    "        \"description\": f\"This is the option of the correct response. Could be only any of these: {responses_text}\"\n",
    "    }\n",
    "\n",
    "    if REASONING:\n",
    "        reasoning_schema = {\n",
    "            \"name\": \"reasoning\",\n",
    "            \"description\": \"This is the reasons for the answer\"\n",
    "        }\n",
    "        response_schemas = [response_schema, reasoning_schema]\n",
    "    else:\n",
    "        response_schemas = [response_schema]\n",
    "\n",
    "    format_instructions = \"Respond with a JSON object containing the following keys:\\n\" + \\\n",
    "                          \"\\n\".join([f\"{schema['name']}: {schema['description']}\" for schema in response_schemas])\n",
    "\n",
    "    prompt = PromptTemplate(\n",
    "        template=template,\n",
    "        input_variables=[\"question\"],\n",
    "        partial_variables={\"format_instructions\": format_instructions}\n",
    "    )\n",
    "    \n",
    "    return prompt\n",
    "\n",
    "# Custom parsing function\n",
    "def parse_response(response_text):\n",
    "    try:\n",
    "        response_json = json.loads(response_text)\n",
    "        return response_json.get(\"response\", \"invalid\")\n",
    "    except json.JSONDecodeError:\n",
    "        return \"invalid\"\n",
    "\n",
    "# Load dataset\n",
    "QA = pd.read_csv('')\n",
    "q_eng = QA['english'].copy()\n",
    "\n",
    "# Generate prompt\n",
    "LANGUAGES = [\"English\"]\n",
    "REASONING = False\n",
    "prompt = generate_prompt(LANGUAGES, REASONING)\n",
    "\n",
    "# Post-processing function (from your current generation)\n",
    "def format_docs(docs):\n",
    "    return \"\\n\\n\".join(doc.page_content for doc in docs)\n",
    "\n",
    "# Define the generation function using LangChain\n",
    "def generate_answers(questions):\n",
    "    results = []\n",
    "    for q_e in tqdm(questions): \n",
    "        formatted_prompt = prompt.format(question=q_e)\n",
    "        inputs = {\"question\": formatted_prompt}\n",
    "        generation = rag_chain.invoke({\"context\": [], \"question\": inputs[\"question\"]})\n",
    "        print(generation)  # Print the generation to understand its structure\n",
    "        parsed_response = parse_response(generation)\n",
    "        results.append(parsed_response)\n",
    "    return results\n",
    "\n",
    "# Initial generation\n",
    "results_eng = generate_answers(q_eng)\n",
    "\n",
    "# Open the file in write mode\n",
    "file_name = 'output3.5.csv'\n",
    "with open(file_name, mode='w', newline='') as file:\n",
    "    writer = csv.writer(file)\n",
    "    for item in results_eng:\n",
    "        writer.writerow([item]) \n",
    "\n",
    "# Function to check if answers are valid\n",
    "def are_valid_answers(answers):\n",
    "    valid_answers = {'a', 'b', 'c', 'd','A','B','C','D'}\n",
    "    return [answer[0] in valid_answers for answer in answers]\n",
    "\n",
    "# Iteratively generate answers until all are valid or patience level is reached\n",
    "iteration = 0\n",
    "patience = 10\n",
    "valid_flags = are_valid_answers(results_eng)\n",
    "\n",
    "while not all(valid_flags) and iteration < patience:\n",
    "    iteration += 1\n",
    "    num_valid = sum(valid_flags)\n",
    "    num_invalid = len(valid_flags) - num_valid\n",
    "    print(f\"Iteration {iteration}: {num_valid} valid answers, {num_invalid} invalid answers\")\n",
    "    \n",
    "    # Find indexes of invalid answers\n",
    "    invalid_indexes = [index for index, is_valid in enumerate(valid_flags) if not is_valid]\n",
    "    \n",
    "    # Generate new answers for invalid questions\n",
    "    invalid_questions = [q_eng[index] for index in invalid_indexes]\n",
    "    new_answers = generate_answers(invalid_questions)\n",
    "    \n",
    "    # Update results with new answers\n",
    "    for i, index in enumerate(invalid_indexes):\n",
    "        results_eng[index] = new_answers[i]\n",
    "    \n",
    "    # Re-check validity of all answers\n",
    "    valid_flags = are_valid_answers(results_eng)\n",
    "\n",
    "# Final status\n",
    "if all(valid_flags):\n",
    "    print(\"All answers are now valid.\")\n",
    "else:\n",
    "    print(\"Reached patience limit. Some answers are still invalid.\")\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "9d42f00a-03fa-4bff-8032-f0ecb1021b18",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Final comparison with ground truth\n",
    "res = pd.DataFrame(results_eng, columns=['answer'])\n",
    "gt = QA.answer.str.lower().tolist()\n",
    "preds = res['answer'].str[0].tolist()  # Take only the first character\n",
    "first_chars = [s[0].lower() for s in preds if s]  # Ensure the string is not empty\n",
    "\n",
    "print(first_chars)\n",
    "print((np.array(first_chars) == np.array(gt)).sum())\n",
    "\n",
    "# Save final results to CSV\n",
    "file_name_final = 'final_output.csv'\n",
    "with open(file_name_final, mode='w', newline='') as file:\n",
    "    writer = csv.writer(file)\n",
    "    for item in results_eng:\n",
    "        writer.writerow([item])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "77de8ce3-d0b2-430a-bb06-770be235dbb0",
   "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.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}