File size: 177,844 Bytes
7a8a241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install -qU langchain_openai langchain_huggingface langchain_core==0.2.38 langchain langchain_community langchain-text-splitters langgraph arxiv duckduckgo_search==5.3.1b1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install -qU qdrant-client pymupdf pandas faiss-cpu unstructured==0.15.7 python-pptx==1.0.2 nltk==3.9.1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install -qU sentence_transformers datasets pyarrow==14.0.1 biopytho"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.messages import SystemMessage, HumanMessage\n",
    "from langchain.tools import StructuredTool\n",
    "from langchain.agents import initialize_agent, Tool, AgentType\n",
    "from langchain_openai import ChatOpenAI\n",
    "from langgraph.graph.message import add_messages\n",
    "from langgraph.graph import StateGraph, END\n",
    "from pydantic import BaseModel\n",
    "from typing import List, TypedDict, Annotated\n",
    "import xml.etree.ElementTree as ET\n",
    "import uuid\n",
    "import re\n",
    "from langgraph.prebuilt import ToolNode\n",
    "from Bio import Entrez\n",
    "from langchain_qdrant import QdrantVectorStore\n",
    "from qdrant_client import QdrantClient\n",
    "from qdrant_client.http.models import Distance, VectorParams\n",
    "from qdrant_client.http.models import Filter, FieldCondition, MatchValue\n",
    "from langchain_huggingface import HuggingFaceEmbeddings\n",
    "from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
    "from langchain.chains import (\n",
    "    ConversationalRetrievalChain,\n",
    ")\n",
    "from langchain.docstore.document import Document\n",
    "from langchain.memory import ChatMessageHistory, ConversationBufferMemory\n",
    "from transformers import GPT2Tokenizer\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import getpass\n",
    "\n",
    "os.environ[\"OPENAI_API_KEY\"] = getpass.getpass(\"OpenAI API Key:\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "from Bio import Entrez\n",
    "import xml.etree.ElementTree as ET\n",
    "# Set your Entrez email\n",
    "Entrez.email = \"[email protected]\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "from IPython.display import display, Markdown\n",
    "\n",
    "def pretty_print(message: str) -> None:\n",
    "    display(Markdown(f\"```markdown\\n{message}\\n```\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "c:\\Users\\YLiang\\.conda\\envs\\llmops-course\\Lib\\site-packages\\sentence_transformers\\cross_encoder\\CrossEncoder.py:13: TqdmExperimentalWarning: Using `tqdm.autonotebook.tqdm` in notebook mode. Use `tqdm.tqdm` instead to force console mode (e.g. in jupyter console)\n",
      "  from tqdm.autonotebook import tqdm, trange\n",
      "c:\\Users\\YLiang\\.conda\\envs\\llmops-course\\Lib\\site-packages\\transformers\\tokenization_utils_base.py:1617: FutureWarning: `clean_up_tokenization_spaces` was not set. It will be set to `True` by default. This behavior will be deprecated in transformers v4.45, and will be then set to `False` by default. For more details check this issue: https://github.com/huggingface/transformers/issues/31884\n",
      "  warnings.warn(\n"
     ]
    }
   ],
   "source": [
    "from sentence_transformers import SentenceTransformer, util\n",
    "\n",
    "# Load the pre-trained model for embeddings (you can choose a different model if preferred)\n",
    "semantic_model = SentenceTransformer('sentence-transformers/all-mpnet-base-v2')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### MVP2: More function added (pull full-text and do simple RAG)\n",
    "- Note right now it can only pull free articles which contains something like \"StringElement('PMC11276461', attributes={'IdType': 'pmc'})\" - see below example.\n",
    "- Then it will use '11276461' from 'PMC11276461' to pull full artile."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[StringElement('39063396', attributes={'IdType': 'pubmed'}), StringElement('PMC11276461', attributes={'IdType': 'pmc'}), StringElement('10.3390/ijerph21070819', attributes={'IdType': 'doi'}), StringElement('ijerph21070819', attributes={'IdType': 'pii'})]\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Fetch full text from PubMed Central for given PMIDs.\"\"\"\n",
    "handle = Entrez.efetch(db=\"pubmed\", id=\"39063396\", retmode=\"xml\")\n",
    "records = Entrez.read(handle)\n",
    "handle.close()\n",
    "for record in records['PubmedArticle']:\n",
    "    pmc_id_temp = record['PubmedData']['ArticleIdList']\n",
    "    print(pmc_id_temp)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### MVP2: Whole Flow\n",
    "- Agent with 3 tools\n",
    "    - pubmed_tool,\n",
    "    - semantic_screening_tool,\n",
    "    - rag_tool"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "c:\\Users\\YLiang\\.conda\\envs\\llmops-course\\Lib\\site-packages\\transformers\\tokenization_utils_base.py:1617: FutureWarning: `clean_up_tokenization_spaces` was not set. It will be set to `True` by default. This behavior will be deprecated in transformers v4.45, and will be then set to `False` by default. For more details check this issue: https://github.com/huggingface/transformers/issues/31884\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Receiving update from node: 'agent'\n"
     ]
    },
    {
     "data": {
      "text/markdown": [
       "```markdown\n",
       "[AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_t7Rybf2ucTJRAnwgqU37wgwQ', 'function': {'arguments': '{\"query\":\"(Impact[Title/Abstract]) AND ((COVID[Title/Abstract] OR pandemic[Title/Abstract]) AND (healthcare resource utilization[Title/Abstract] OR health resource utilization[Title/Abstract]))\"}', 'name': 'PubMed_Search_Tool'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 59, 'prompt_tokens': 496, 'total_tokens': 555, 'prompt_tokens_details': {'cached_tokens': 0}, 'completion_tokens_details': {'reasoning_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_fd18a09f1e', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-157fed54-d117-486f-af4a-b4310c0b6854-0', tool_calls=[{'name': 'PubMed_Search_Tool', 'args': {'query': '(Impact[Title/Abstract]) AND ((COVID[Title/Abstract] OR pandemic[Title/Abstract]) AND (healthcare resource utilization[Title/Abstract] OR health resource utilization[Title/Abstract]))'}, 'id': 'call_t7Rybf2ucTJRAnwgqU37wgwQ', 'type': 'tool_call'}], usage_metadata={'input_tokens': 496, 'output_tokens': 59, 'total_tokens': 555})]\n",
       "```"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\n",
      "Receiving update from node: 'action'\n"
     ]
    },
    {
     "data": {
      "text/markdown": [
       "```markdown\n",
       "[ToolMessage(content='[{\"PMID\": \"39291999\", \"Title\": \"Clinical manifestations, healthcare resource utilization, and costs among patients with long-chain fatty acid oxidation disorders: a retrospective claims database analysis.\", \"Abstract\": \"Long-chain fatty acid oxidation disorders (LC-FAOD) are a group of rare genetic inborn errors of metabolism. Clinical manifestations may result in frequent healthcare visits, hospitalizations, and early death. This retrospective cohort study assessed manifestations, healthcare resource use (HRU), direct medical costs, and the impact of COVID-19 on HRU among patients with LC-FAOD.\"}, {\"PMID\": \"39063396\", \"Title\": \"Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.\", \"Abstract\": \"During the COVID-19 pandemic, tele-mental health (TMH) was a viable approach for providing accessible mental and behavioral health (MBH) services. This study examines the sociodemographic disparities in TMH utilization and its effects on healthcare resource utilization (HCRU) and medical expenditures in Mississippi. Utilizing a cohort of 6787 insured adult patients at the University of Mississippi Medical Center and its affiliated sites between January 2020 and June 2023, including 3065 who accessed TMH services, we observed sociodemographic disparities between TMH and non-TMH cohorts. The TMH cohort was more likely to be younger, female, White/Caucasian, using payment methods other than Medicare, Medicaid, or commercial insurers, residing in rural areas, and with higher household income compared to the non-TMH cohort. Adjusting for sociodemographic factors, TMH utilization was associated with a 190% increase in MBH-related outpatient visits, a 17% increase in MBH-related medical expenditures, and a 12% decrease in all-cause medical expenditures (all <i>p</i> < 0.001). Among rural residents, TMH utilization was associated with a 205% increase in MBH-related outpatient visits and a 19% decrease in all-cause medical expenditures (both <i>p</i> < 0.001). This study underscores the importance of addressing sociodemographic disparities in TMH services to promote equitable healthcare access while reducing overall medical expenditures.\"}, {\"PMID\": \"39051414\", \"Title\": \"Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.\", \"Abstract\": \"<b>Background:</b> This study investigated the impact of COVID-19 on patients with sickle cell crisis (SCC) using National Inpatient Sample (NIS) data for the year 2020. <b>Methods:</b> A retrospective cohort analysis was conducted utilizing International Classification of Diseases (ICD-10) codes to identify adults who were admitted with a principal diagnosis of sickle cell crisis. The primary outcomes examined were inpatient mortality, while the secondary outcomes assessed included morbidity, hospital length of stay, and resource utilization. Analyses were conducted with STATA. Multivariate logistic and linear regression analyses were used to adjust for confounding variables. <b>Results:</b> Of 66,415 adult patients with a primary SCC diagnosis, 875 were identified with a secondary diagnosis of COVID-19 infection. Unadjusted mortality rate was higher for SCC patients with COVID-19 (2.28%) compared to those without (0.33%), with an adjusted odds ratio (aOR) of 8.49 (<i>p</i> = 0.001). They also showed increased odds of developing acute respiratory failure (aOR = 2.37, <i>p</i> = 0.003) and acute kidney injury requiring dialysis (aOR = 8.66, <i>p</i> = 0.034). Additionally, these patients had longer hospital stays by an adjusted mean of 3.30 days (<i>p</i> < 0.001) and incurred higher hospitalization charges by an adjusted mean of USD 35,578 (<i>p</i> = 0.005). <b>Conclusions:</b> The SCC patients with COVID-19 presented higher mortality rates, increased morbidity indicators, longer hospital stays, and substantial economic burdens.\"}]', name='PubMed_Search_Tool', tool_call_id='call_t7Rybf2ucTJRAnwgqU37wgwQ')]\n",
       "```"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\n",
      "Receiving update from node: 'agent'\n"
     ]
    },
    {
     "data": {
      "text/markdown": [
       "```markdown\n",
       "[AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_hTrHb9Av7Uxriu6Z7woR2bMi', 'function': {'arguments': '{\"criteria\":\"comparison of healthcare resource utilization before and after the COVID pandemic\"}', 'name': 'Semantic_Abstract_Screening_Tool'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 30, 'prompt_tokens': 1469, 'total_tokens': 1499, 'prompt_tokens_details': {'cached_tokens': 0}, 'completion_tokens_details': {'reasoning_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_e5e4913e83', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-8715af33-7c99-47b8-858d-950654c6f8e2-0', tool_calls=[{'name': 'Semantic_Abstract_Screening_Tool', 'args': {'criteria': 'comparison of healthcare resource utilization before and after the COVID pandemic'}, 'id': 'call_hTrHb9Av7Uxriu6Z7woR2bMi', 'type': 'tool_call'}], usage_metadata={'input_tokens': 1469, 'output_tokens': 30, 'total_tokens': 1499})]\n",
       "```"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\n",
      "Receiving update from node: 'action'\n"
     ]
    },
    {
     "data": {
      "text/markdown": [
       "```markdown\n",
       "[ToolMessage(content=\"Error: 1 validation error for AbstractScreeningInput\\nabstracts\\n  Field required [type=missing, input_value={'criteria': 'comparison ...ter the COVID pandemic'}, input_type=dict]\\n    For further information visit https://errors.pydantic.dev/2.9/v/missing\\n Please fix your mistakes.\", name='Semantic_Abstract_Screening_Tool', tool_call_id='call_hTrHb9Av7Uxriu6Z7woR2bMi')]\n",
       "```"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\n",
      "Receiving update from node: 'agent'\n"
     ]
    },
    {
     "data": {
      "text/markdown": [
       "```markdown\n",
       "[AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_wXc1b5bfjTfc94c8GcyrlELu', 'function': {'arguments': '{\"criteria\":\"comparison of healthcare resource utilization before and after the COVID pandemic\",\"abstracts\":[{\"PMID\":\"39291999\",\"Title\":\"Clinical manifestations, healthcare resource utilization, and costs among patients with long-chain fatty acid oxidation disorders: a retrospective claims database analysis.\",\"Abstract\":\"Long-chain fatty acid oxidation disorders (LC-FAOD) are a group of rare genetic inborn errors of metabolism. Clinical manifestations may result in frequent healthcare visits, hospitalizations, and early death. This retrospective cohort study assessed manifestations, healthcare resource use (HRU), direct medical costs, and the impact of COVID-19 on HRU among patients with LC-FAOD.\"},{\"PMID\":\"39063396\",\"Title\":\"Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.\",\"Abstract\":\"During the COVID-19 pandemic, tele-mental health (TMH) was a viable approach for providing accessible mental and behavioral health (MBH) services. This study examines the sociodemographic disparities in TMH utilization and its effects on healthcare resource utilization (HCRU) and medical expenditures in Mississippi. Utilizing a cohort of 6787 insured adult patients at the University of Mississippi Medical Center and its affiliated sites between January 2020 and June 2023, including 3065 who accessed TMH services, we observed sociodemographic disparities between TMH and non-TMH cohorts. The TMH cohort was more likely to be younger, female, White/Caucasian, using payment methods other than Medicare, Medicaid, or commercial insurers, residing in rural areas, and with higher household income compared to the non-TMH cohort. Adjusting for sociodemographic factors, TMH utilization was associated with a 190% increase in MBH-related outpatient visits, a 17% increase in MBH-related medical expenditures, and a 12% decrease in all-cause medical expenditures (all <i>p</i> < 0.001). Among rural residents, TMH utilization was associated with a 205% increase in MBH-related outpatient visits and a 19% decrease in all-cause medical expenditures (both <i>p</i> < 0.001). This study underscores the importance of addressing sociodemographic disparities in TMH services to promote equitable healthcare access while reducing overall medical expenditures.\"},{\"PMID\":\"39051414\",\"Title\":\"Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.\",\"Abstract\":\"<b>Background:</b> This study investigated the impact of COVID-19 on patients with sickle cell crisis (SCC) using National Inpatient Sample (NIS) data for the year 2020. <b>Methods:</b> A retrospective cohort analysis was conducted utilizing International Classification of Diseases (ICD-10) codes to identify adults who were admitted with a principal diagnosis of sickle cell crisis. The primary outcomes examined were inpatient mortality, while the secondary outcomes assessed included morbidity, hospital length of stay, and resource utilization. Analyses were conducted with STATA. Multivariate logistic and linear regression analyses were used to adjust for confounding variables. <b>Results:</b> Of 66,415 adult patients with a primary SCC diagnosis, 875 were identified with a secondary diagnosis of COVID-19 infection. Unadjusted mortality rate was higher for SCC patients with COVID-19 (2.28%) compared to those without (0.33%), with an adjusted odds ratio (aOR) of 8.49 (<i>p</i> = 0.001). They also showed increased odds of developing acute respiratory failure (aOR = 2.37, <i>p</i> = 0.003) and acute kidney injury requiring dialysis (aOR = 8.66, <i>p</i> = 0.034). Additionally, these patients had longer hospital stays by an adjusted mean of 3.30 days (<i>p</i> < 0.001) and incurred higher hospitalization charges by an adjusted mean of USD 35,578 (<i>p</i> = 0.005). <b>Conclusions:</b> The SCC patients with COVID-19 presented higher mortality rates, increased morbidity indicators, longer hospital stays, and substantial economic burdens.\"}]}', 'name': 'Semantic_Abstract_Screening_Tool'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 920, 'prompt_tokens': 1577, 'total_tokens': 2497, 'prompt_tokens_details': {'cached_tokens': 0}, 'completion_tokens_details': {'reasoning_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_fd18a09f1e', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-a03c1cc7-0fb3-4299-8bae-89409e0713b9-0', tool_calls=[{'name': 'Semantic_Abstract_Screening_Tool', 'args': {'criteria': 'comparison of healthcare resource utilization before and after the COVID pandemic', 'abstracts': [{'PMID': '39291999', 'Title': 'Clinical manifestations, healthcare resource utilization, and costs among patients with long-chain fatty acid oxidation disorders: a retrospective claims database analysis.', 'Abstract': 'Long-chain fatty acid oxidation disorders (LC-FAOD) are a group of rare genetic inborn errors of metabolism. Clinical manifestations may result in frequent healthcare visits, hospitalizations, and early death. This retrospective cohort study assessed manifestations, healthcare resource use (HRU), direct medical costs, and the impact of COVID-19 on HRU among patients with LC-FAOD.'}, {'PMID': '39063396', 'Title': 'Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.', 'Abstract': 'During the COVID-19 pandemic, tele-mental health (TMH) was a viable approach for providing accessible mental and behavioral health (MBH) services. This study examines the sociodemographic disparities in TMH utilization and its effects on healthcare resource utilization (HCRU) and medical expenditures in Mississippi. Utilizing a cohort of 6787 insured adult patients at the University of Mississippi Medical Center and its affiliated sites between January 2020 and June 2023, including 3065 who accessed TMH services, we observed sociodemographic disparities between TMH and non-TMH cohorts. The TMH cohort was more likely to be younger, female, White/Caucasian, using payment methods other than Medicare, Medicaid, or commercial insurers, residing in rural areas, and with higher household income compared to the non-TMH cohort. Adjusting for sociodemographic factors, TMH utilization was associated with a 190% increase in MBH-related outpatient visits, a 17% increase in MBH-related medical expenditures, and a 12% decrease in all-cause medical expenditures (all <i>p</i> < 0.001). Among rural residents, TMH utilization was associated with a 205% increase in MBH-related outpatient visits and a 19% decrease in all-cause medical expenditures (both <i>p</i> < 0.001). This study underscores the importance of addressing sociodemographic disparities in TMH services to promote equitable healthcare access while reducing overall medical expenditures.'}, {'PMID': '39051414', 'Title': 'Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.', 'Abstract': '<b>Background:</b> This study investigated the impact of COVID-19 on patients with sickle cell crisis (SCC) using National Inpatient Sample (NIS) data for the year 2020. <b>Methods:</b> A retrospective cohort analysis was conducted utilizing International Classification of Diseases (ICD-10) codes to identify adults who were admitted with a principal diagnosis of sickle cell crisis. The primary outcomes examined were inpatient mortality, while the secondary outcomes assessed included morbidity, hospital length of stay, and resource utilization. Analyses were conducted with STATA. Multivariate logistic and linear regression analyses were used to adjust for confounding variables. <b>Results:</b> Of 66,415 adult patients with a primary SCC diagnosis, 875 were identified with a secondary diagnosis of COVID-19 infection. Unadjusted mortality rate was higher for SCC patients with COVID-19 (2.28%) compared to those without (0.33%), with an adjusted odds ratio (aOR) of 8.49 (<i>p</i> = 0.001). They also showed increased odds of developing acute respiratory failure (aOR = 2.37, <i>p</i> = 0.003) and acute kidney injury requiring dialysis (aOR = 8.66, <i>p</i> = 0.034). Additionally, these patients had longer hospital stays by an adjusted mean of 3.30 days (<i>p</i> < 0.001) and incurred higher hospitalization charges by an adjusted mean of USD 35,578 (<i>p</i> = 0.005). <b>Conclusions:</b> The SCC patients with COVID-19 presented higher mortality rates, increased morbidity indicators, longer hospital stays, and substantial economic burdens.'}]}, 'id': 'call_wXc1b5bfjTfc94c8GcyrlELu', 'type': 'tool_call'}], usage_metadata={'input_tokens': 1577, 'output_tokens': 920, 'total_tokens': 2497})]\n",
       "```"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\n",
      "Receiving update from node: 'action'\n"
     ]
    },
    {
     "data": {
      "text/markdown": [
       "```markdown\n",
       "[ToolMessage(content='[{\"PMID\": \"39291999\", \"Decision\": \"Exclude\", \"Reason\": \"Similarity score 0.31 < threshold 0.4\"}, {\"PMID\": \"39063396\", \"Decision\": \"Include\", \"Reason\": \"Similarity score 0.53 >= threshold 0.4\"}, {\"PMID\": \"39051414\", \"Decision\": \"Include\", \"Reason\": \"Similarity score 0.45 >= threshold 0.4\"}]', name='Semantic_Abstract_Screening_Tool', tool_call_id='call_wXc1b5bfjTfc94c8GcyrlELu')]\n",
       "```"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\n",
      "Receiving update from node: 'agent'\n"
     ]
    },
    {
     "data": {
      "text/markdown": [
       "```markdown\n",
       "[AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_KMTLEk1pHVymBlm4S9Geeig1', 'function': {'arguments': '{\"pmids\":[\"39063396\",\"39051414\"],\"query\":\"data source information used in each paper (especially medical records)\"}', 'name': 'Fetch_Extract_Tool'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 40, 'prompt_tokens': 2608, 'total_tokens': 2648, 'prompt_tokens_details': {'cached_tokens': 0}, 'completion_tokens_details': {'reasoning_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_2f406b9113', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-ea57b535-c3c0-437a-969e-7b1b69c3a8be-0', tool_calls=[{'name': 'Fetch_Extract_Tool', 'args': {'pmids': ['39063396', '39051414'], 'query': 'data source information used in each paper (especially medical records)'}, 'id': 'call_KMTLEk1pHVymBlm4S9Geeig1', 'type': 'tool_call'}], usage_metadata={'input_tokens': 2608, 'output_tokens': 40, 'total_tokens': 2648})]\n",
       "```"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "c:\\Users\\YLiang\\.conda\\envs\\llmops-course\\Lib\\site-packages\\transformers\\tokenization_utils_base.py:1617: FutureWarning: `clean_up_tokenization_spaces` was not set. It will be set to `True` by default. This behavior will be deprecated in transformers v4.45, and will be then set to `False` by default. For more details check this issue: https://github.com/huggingface/transformers/issues/31884\n",
      "  warnings.warn(\n",
      "C:\\Users\\YLiang\\AppData\\Local\\Temp\\ipykernel_35360\\1582393269.py:272: LangChainDeprecationWarning: The method `Chain.__call__` was deprecated in langchain 0.1.0 and will be removed in 1.0. Use invoke instead.\n",
      "  result = qa_chain({\"question\": query})\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Receiving update from node: 'action'\n"
     ]
    },
    {
     "data": {
      "text/markdown": [
       "```markdown\n",
       "[ToolMessage(content='{\\'39063396\\': {\\'PMID\\': \\'39063396\\', \\'Title\\': \\'Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.\\', \\'Generated Answer\\': \"The data source used in the study was the UMMC enterprise data warehouse, which contained medical records. The medical records were extracted from this data warehouse to examine sociodemographic characteristics, healthcare resource utilization (HCRU), and medical expenditures between telemedicine (TMH) and non-telemedicine cohorts. The sociodemographic characteristics considered in the study included age, sex, race, primary insurance, rurality, and household income. It\\'s important to note that due to the presence of protected health information (PHI) and in accordance with IRB regulations, the dataset cannot be made publicly available.\", \\'Sources\\': [Document(metadata={\\'PMID\\': \\'39063396\\', \\'Title\\': \\'Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.\\', \\'uuid\\': \\'54fd6497-fa85-47af-9cb6-2bf2ff99457d\\', \\'_id\\': \\'4bfc2c9803084a908b9224c458e30dfa\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'Institutional Review Board Statement\\\\n\\\\nThis study was approved by the Institutional Review Board (IRB) of the University of Mississippi Medical Center (ID: UMMC-IRB-2022-458; date of approval: 12 April 2023).\\\\n\\\\nInformed Consent Statement\\\\n\\\\nPatient consent was waived following Federal Regulations set forth by 45 CFR 46.116(f).\\\\n\\\\nData Availability Statement\\\\n\\\\nDue to the presence of protected health information (PHI) and in accordance with IRB regulations, the dataset cannot be made publicly available.\\\\n\\\\nConflicts of Interest\\\\n\\\\nLSL was an employee of ConcertAI during the conduct of this study. Other authors have no conflicts of interest to declare.\\\\n\\\\nReferences\\\\n\\\\nAverage mental and behavioral health-related and all-cause HCRU and medical expenditure PPPM.\\\\n\\\\nAverage mental and behavioral health-related and all-cause HCRU and medical expenditure PPPM of subjects residing in rural areas.\\\\n\\\\nSociodemographic characteristics of all study subjects and using TMH.\\'), Document(metadata={\\'PMID\\': \\'39063396\\', \\'Title\\': \\'Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.\\', \\'uuid\\': \\'794d626e-8bd7-4426-abdf-ae96f1079c9d\\', \\'_id\\': \\'d9173cc20922455eabcc06e47bed7d7a\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'Medical records were extracted from the UMMC enterprise data warehouse to examine sociodemographic characteristics, HCRU, and medical expenditures between TMH and non-TMH cohorts. Sociodemographic characteristics considered in this study include age, sex, race, primary insurance, rurality, and household income. Age was categorized into four groups: 18 to 34 years, 35 to 49 years, 50 to 64 years, and 65 years or older. Race was categorized into three groups: White/Caucasian, Black/African American, and other. The other race group included subjects identifying as American Indian, Alaska Native, Native Hawaiian, other Pacific Islander, Mississippi Band Choctaw Indian, Asian, Hispanic, Multiracial, and others. Subjects of unknown race or those who refused to provide this information were considered missing. Primary insurance was defined as the insurance most frequently used for mental and behavioral health visits during the study period and was categorized into four groups: commercial\\'), Document(metadata={\\'PMID\\': \\'39063396\\', \\'Title\\': \\'Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.\\', \\'uuid\\': \\'c34872ae-f47d-418b-a4a8-d69f86e50aca\\', \\'_id\\': \\'dfbd789180d74bce8c6a1e711db54c1e\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'were included, future studies should consider multiple academic centers or healthcare entities to validate the robustness of findings across different geographic regions and patient populations. Additionally, there is potential for missing data since patients may seek care at multiple institutions. This limitation was mitigated by limiting the study sample to patients who had evidence of regular care visits at UMMC and had evidence of insurance coverage for at least one visit. However, as the study sample consisted of insured patients who regularly seek healthcare from UMMC, it may not represent the entire population of Mississippi, such as those without any healthcare access, thereby limiting generalizability to uninsured populations. Future research should identify and address barriers faced by uninsured populations to provide a more comprehensive understanding of TMH utilization and its impact on HCRU and medical expenditures.\\')]}, \\'39051414\\': {\\'PMID\\': \\'39051414\\', \\'Title\\': \\'Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.\\', \\'Generated Answer\\': \\'The data source used in the study described is the 2020 National Inpatient Sample (NIS) dataset. This dataset covers hospitalizations in the United States from 1 January 2020 to 31 December 2020 and is derived from the State Inpatient Databases (SIDs). The NIS dataset is part of the Healthcare Cost and Utilization Project sponsored by the Agency for Healthcare Research and Quality (AHRQ). It is a de-identified, publicly available inpatient database that represents an estimated 98% of the U.S. population. The dataset employs a 20% stratified discharge sample, which is then weighted to ensure national representativeness.\\', \\'Sources\\': [Document(metadata={\\'PMID\\': \\'39051414\\', \\'Title\\': \\'Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.\\', \\'uuid\\': \\'731882ce-e143-49ba-8a9f-06eaa42adb10\\', \\'_id\\': \\'41646d28fb6b43bb89ab12bc8e54a654\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'3. Materials and Methods\\\\n\\\\n\\\\n\\\\n3.1. Study Design and Database Description\\\\n\\\\nUtilizing the 2020 National Inpatient Sample (NIS) dataset, we conducted a retrospective cohort analysis of adult patients admitted with a primary diagnosis of sickle cell crisis in the United States. The NIS 2020 dataset specifically covers hospitalizations within the period from 1 January 2020 to 31 December 2020. It derives from the State Inpatient Databases (SIDs) that cover an estimated 98% of the U.S. population. As part of the Healthcare Cost and Utilization Project sponsored by Agency for Healthcare Research and Quality (AHRQ), the NIS is the most extensive, de-identified, publicly available inpatient database in the U.S. This database employs a 20% stratified discharge sample, which is then weighted relative to the total discharges to ensure national representativeness.\\\\n\\\\n\\\\n\\\\n3.2. Study Patients\\'), Document(metadata={\\'PMID\\': \\'39051414\\', \\'Title\\': \\'Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.\\', \\'uuid\\': \\'de21c6f4-c463-4566-afcb-2ba1bfbf407d\\', \\'_id\\': \\'fd742ac79e9348dd8736601f0b7de762\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'Our study has some limitations. Because it was retrospective, we could not fully randomize exposure. However, by employing multivariate regression models that took into account various patient and hospital traits, as well as co-morbidities, we made an effort to reduce confounding. Still, even with these measures, there is a slight chance that residual confounding occurred. To identify patients with sickle cell crisis and COVID-19, we opted for ICD-10 codes rather than clinical measures. This might have resulted in diagnosis misclassification. Yet, the legitimacy of using ICD-10 codes for this purpose is backed by earlier studies that utilized HCUP data [\\'), Document(metadata={\\'PMID\\': \\'39051414\\', \\'Title\\': \\'Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.\\', \\'uuid\\': \\'f37a502c-2cce-40d1-a44f-c932d4b85d31\\', \\'_id\\': \\'a365b4cd3a8c418bb17b5d324bea35ab\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'Supplementary Materials\\\\n\\\\nThe following supporting information can be downloaded at:\\\\n\\\\nAuthor Contributions\\\\n\\\\nConceptualization, Z.H.B. and M.H.; methodology, Z.H.B.; formal analysis, Z.H.B.; investigation and analysis, Z.H.B.; writing—original draft preparation, Z.H.B., M.H., F.N., A.B.A., A.O., M.J.K., M.S.F., F.K. and A.-R.Z.; writing—review and editing, Z.H.B., M.H., F.N., A.B.A., A.O., M.J.K., M.S.F., F.K. and A.-R.Z.; visualization, Y.B. and C.L.B.; supervision, Y.B. and C.L.B. All authors have read and agreed to the published version of the manuscript.\\\\n\\\\nInstitutional Review Board Statement\\\\n\\\\nEthical review and approval were waived for this study as it does not involve research with human subjects and the dataset used is de-identified.\\\\n\\\\nInformed Consent Statement\\\\n\\\\nIt is a retrospective study using publicly available de-identified data and consent is not required.\\\\n\\\\nData Availability Statement\\')]}}', name='Fetch_Extract_Tool', tool_call_id='call_KMTLEk1pHVymBlm4S9Geeig1')]\n",
       "```"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\n",
      "Receiving update from node: 'agent'\n"
     ]
    },
    {
     "data": {
      "text/markdown": [
       "```markdown\n",
       "[AIMessage(content='### Summary of the Process and Findings:\\n\\n1. **Search Query Execution:**\\n   - I used the PubMed search tool with the query focused on the impact of COVID-19 on healthcare resource utilization. The search returned three relevant papers.\\n\\n2. **Abstract Screening:**\\n   - The abstracts were screened based on the criteria of comparing healthcare resource utilization before and after the COVID pandemic.\\n   - **Paper 1 (PMID: 39291999):** Excluded due to a low similarity score (0.31), indicating it did not meet the criteria.\\n   - **Paper 2 (PMID: 39063396):** Included with a similarity score of 0.53, indicating it met the criteria.\\n   - **Paper 3 (PMID: 39051414):** Included with a similarity score of 0.45, indicating it met the criteria.\\n\\n3. **Full-Text Retrieval and Information Extraction:**\\n   - For the included papers, I fetched the full-text articles and extracted information regarding the data sources used, especially focusing on medical records.\\n\\n   - **Paper 2 (PMID: 39063396):**\\n     - **Title:** Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.\\n     - **Data Source:** The study used medical records extracted from the UMMC enterprise data warehouse. This data was used to analyze sociodemographic characteristics, healthcare resource utilization, and medical expenditures between telemedicine and non-telemedicine cohorts. The dataset was not publicly available due to protected health information (PHI) regulations.\\n\\n   - **Paper 3 (PMID: 39051414):**\\n     - **Title:** Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.\\n     - **Data Source:** The study utilized the 2020 National Inpatient Sample (NIS) dataset, which is a de-identified, publicly available inpatient database representing hospitalizations in the U.S. The dataset is part of the Healthcare Cost and Utilization Project sponsored by the Agency for Healthcare Research and Quality (AHRQ).\\n\\n### Conclusion:\\nThe process involved searching for relevant literature, screening abstracts based on specific criteria, and extracting detailed data source information from the full-text articles. The included studies provided insights into the impact of COVID-19 on healthcare resource utilization, using robust data sources like institutional data warehouses and national inpatient samples.', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 519, 'prompt_tokens': 4823, 'total_tokens': 5342, 'prompt_tokens_details': {'cached_tokens': 1408}, 'completion_tokens_details': {'reasoning_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_e5e4913e83', 'finish_reason': 'stop', 'logprobs': None}, id='run-b2a9db6e-f642-44ac-8c7d-dba2345c8ee7-0', usage_metadata={'input_tokens': 4823, 'output_tokens': 519, 'total_tokens': 5342})]\n",
       "```"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\n",
      "Final message content from the last chunk:\n"
     ]
    },
    {
     "data": {
      "text/markdown": [
       "```markdown\n",
       "### Summary of the Process and Findings:\n",
       "\n",
       "1. **Search Query Execution:**\n",
       "   - I used the PubMed search tool with the query focused on the impact of COVID-19 on healthcare resource utilization. The search returned three relevant papers.\n",
       "\n",
       "2. **Abstract Screening:**\n",
       "   - The abstracts were screened based on the criteria of comparing healthcare resource utilization before and after the COVID pandemic.\n",
       "   - **Paper 1 (PMID: 39291999):** Excluded due to a low similarity score (0.31), indicating it did not meet the criteria.\n",
       "   - **Paper 2 (PMID: 39063396):** Included with a similarity score of 0.53, indicating it met the criteria.\n",
       "   - **Paper 3 (PMID: 39051414):** Included with a similarity score of 0.45, indicating it met the criteria.\n",
       "\n",
       "3. **Full-Text Retrieval and Information Extraction:**\n",
       "   - For the included papers, I fetched the full-text articles and extracted information regarding the data sources used, especially focusing on medical records.\n",
       "\n",
       "   - **Paper 2 (PMID: 39063396):**\n",
       "     - **Title:** Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.\n",
       "     - **Data Source:** The study used medical records extracted from the UMMC enterprise data warehouse. This data was used to analyze sociodemographic characteristics, healthcare resource utilization, and medical expenditures between telemedicine and non-telemedicine cohorts. The dataset was not publicly available due to protected health information (PHI) regulations.\n",
       "\n",
       "   - **Paper 3 (PMID: 39051414):**\n",
       "     - **Title:** Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.\n",
       "     - **Data Source:** The study utilized the 2020 National Inpatient Sample (NIS) dataset, which is a de-identified, publicly available inpatient database representing hospitalizations in the U.S. The dataset is part of the Healthcare Cost and Utilization Project sponsored by the Agency for Healthcare Research and Quality (AHRQ).\n",
       "\n",
       "### Conclusion:\n",
       "The process involved searching for relevant literature, screening abstracts based on specific criteria, and extracting detailed data source information from the full-text articles. The included studies provided insights into the impact of COVID-19 on healthcare resource utilization, using robust data sources like institutional data warehouses and national inpatient samples.\n",
       "```"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from langchain_core.messages import SystemMessage, HumanMessage\n",
    "from langchain.tools import StructuredTool\n",
    "from langchain.agents import initialize_agent, Tool, AgentType\n",
    "from langchain_openai import ChatOpenAI\n",
    "from langgraph.graph.message import add_messages\n",
    "from langgraph.graph import StateGraph, END\n",
    "from pydantic import BaseModel\n",
    "from typing import List, TypedDict, Annotated\n",
    "import xml.etree.ElementTree as ET\n",
    "import uuid\n",
    "import re\n",
    "from langgraph.prebuilt import ToolNode\n",
    "from Bio import Entrez\n",
    "from langchain_qdrant import QdrantVectorStore\n",
    "from qdrant_client import QdrantClient\n",
    "from qdrant_client.http.models import Distance, VectorParams\n",
    "from qdrant_client.http.models import Filter, FieldCondition, MatchValue\n",
    "from langchain_huggingface import HuggingFaceEmbeddings\n",
    "from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
    "from langchain.chains import (\n",
    "    ConversationalRetrievalChain,\n",
    ")\n",
    "from langchain.docstore.document import Document\n",
    "from langchain.memory import ChatMessageHistory, ConversationBufferMemory\n",
    "\n",
    "# 1. Define PubMed Search Tool\n",
    "class PubMedSearchInput(BaseModel):\n",
    "    query: str\n",
    "    #max_results: int = 5\n",
    "\n",
    "# PubMed search tool using Entrez (now with structured inputs)\n",
    "def pubmed_search(query: str, max_results: int = 3):\n",
    "    \"\"\"Search PubMed using Entrez API and return abstracts.\"\"\"\n",
    "    handle = Entrez.esearch(db=\"pubmed\", term=query, retmax=max_results)\n",
    "    record = Entrez.read(handle)\n",
    "    handle.close()\n",
    "    pmids = record[\"IdList\"]\n",
    "    \n",
    "    # Fetch abstracts\n",
    "    handle = Entrez.efetch(db=\"pubmed\", id=\",\".join(pmids), retmode=\"xml\")\n",
    "    records = Entrez.read(handle)\n",
    "    handle.close()\n",
    "\n",
    "    abstracts = []\n",
    "    for record in records['PubmedArticle']:\n",
    "        try:\n",
    "            title = record['MedlineCitation']['Article']['ArticleTitle']\n",
    "            abstract = record['MedlineCitation']['Article']['Abstract']['AbstractText'][0]\n",
    "            pmid = record['MedlineCitation']['PMID']\n",
    "            abstracts.append({\"PMID\": pmid, \"Title\": title, \"Abstract\": abstract})\n",
    "        except KeyError:\n",
    "            pass\n",
    "    return abstracts\n",
    "\n",
    "# Define the AbstractScreeningInput using Pydantic BaseModel\n",
    "class AbstractScreeningInput(BaseModel):\n",
    "    abstracts: List[dict]\n",
    "    criteria: str\n",
    "\n",
    "def screen_abstracts_semantic(abstracts: List[dict], criteria: str, similarity_threshold: float = 0.4):\n",
    "    \"\"\"Screen abstracts based on semantic similarity to the criteria.\"\"\"\n",
    "    \n",
    "    # Compute the embedding of the criteria\n",
    "    criteria_embedding = semantic_model.encode(criteria, convert_to_tensor=True)\n",
    "    \n",
    "    screened = []\n",
    "    for paper in abstracts:\n",
    "        abstract_text = paper['Abstract']\n",
    "        \n",
    "        # Compute the embedding of the abstract\n",
    "        abstract_embedding = semantic_model.encode(abstract_text, convert_to_tensor=True)\n",
    "        \n",
    "        # Compute cosine similarity between the abstract and the criteria\n",
    "        similarity_score = util.cos_sim(abstract_embedding, criteria_embedding).item()\n",
    "        \n",
    "        if similarity_score >= similarity_threshold:\n",
    "            screened.append({\n",
    "                \"PMID\": paper['PMID'], \n",
    "                \"Decision\": \"Include\", \n",
    "                \"Reason\": f\"Similarity score {similarity_score:.2f} >= threshold {similarity_threshold}\"\n",
    "            })\n",
    "        else:\n",
    "            screened.append({\n",
    "                \"PMID\": paper['PMID'], \n",
    "                \"Decision\": \"Exclude\", \n",
    "                \"Reason\": f\"Similarity score {similarity_score:.2f} < threshold {similarity_threshold}\"\n",
    "            })\n",
    "    \n",
    "    return screened\n",
    "\n",
    "# Define the PubMed Search Tool as a StructuredTool with proper input schema\n",
    "pubmed_tool = StructuredTool(\n",
    "    name=\"PubMed_Search_Tool\",\n",
    "    func=pubmed_search,\n",
    "    description=\"Search PubMed for research papers and retrieve abstracts. Pass the abstracts (returned results) to another tool.\",\n",
    "    args_schema=PubMedSearchInput  # Use Pydantic BaseModel for schema\n",
    ")\n",
    "\n",
    "# Define the Abstract Screening Tool with semantic screening\n",
    "semantic_screening_tool = StructuredTool(\n",
    "    name=\"Semantic_Abstract_Screening_Tool\",\n",
    "    func=screen_abstracts_semantic,\n",
    "    description=\"\"\"Screen PubMed abstracts based on semantic similarity to inclusion/exclusion criteria. Uses cosine similarity between abstracts and criteria. Requires 'abstracts' and 'screening criteria' as input.\n",
    "    The 'abstracts' is a list of dictionary with keys as PMID, Title, Abstract.\n",
    "    Output a similarity scores for each abstract and send the list of pmids that passed the screening to Fetch_Extract_Tool.\"\"\",\n",
    "    args_schema=AbstractScreeningInput  # Pydantic schema remains the same\n",
    ")\n",
    "\n",
    "# 3. Define Full-Text Retrieval Tool\n",
    "class FetchExtractInput(BaseModel):\n",
    "    pmids: List[str]  # List of PubMed IDs to fetch full text for\n",
    "    query: str\n",
    "\n",
    "def extract_text_from_pmc_xml(xml_content: str) -> str:\n",
    "    \"\"\"a function to format and clean text from PMC full-text XML.\"\"\"\n",
    "    try:\n",
    "        root = ET.fromstring(xml_content)\n",
    "        \n",
    "        # Find all relevant text sections (e.g., <body>, <sec>, <p>)\n",
    "        body_text = []\n",
    "        for elem in root.iter():\n",
    "            if elem.tag in ['p', 'sec', 'title', 'abstract', 'body']:  # Add more tags as needed\n",
    "                if elem.text:\n",
    "                    body_text.append(elem.text.strip())\n",
    "        \n",
    "        # Join all the text elements to form the complete full text\n",
    "        full_text = \"\\n\\n\".join(body_text)\n",
    "        \n",
    "        return full_text\n",
    "    except ET.ParseError:\n",
    "        print(\"Error parsing XML content.\")\n",
    "        return \"\"\n",
    "\n",
    "def fetch_and_extract(pmids: List[str], query: str):\n",
    "    \"\"\"Fetch full text from PubMed Central for given PMIDs, split into chunks, \n",
    "    store in a Qdrant vector database, and perform RAG for each paper.\n",
    "    Retrieves exactly 3 chunks per paper (if available) and generates a consolidated answer for each paper.\n",
    "    \"\"\"\n",
    "    embedding_model = HuggingFaceEmbeddings(model_name=\"sentence-transformers/all-MiniLM-L6-v2\")\n",
    "    corpus = {}\n",
    "    consolidated_results={}\n",
    "\n",
    "    # Fetch records from PubMed Central (PMC)\n",
    "    handle = Entrez.efetch(db=\"pubmed\", id=\",\".join(pmids), retmode=\"xml\")\n",
    "    records = Entrez.read(handle)\n",
    "    handle.close()\n",
    "\n",
    "    full_articles = []\n",
    "    for record in records['PubmedArticle']:\n",
    "        try:\n",
    "            title = record['MedlineCitation']['Article']['ArticleTitle']\n",
    "            pmid = record['MedlineCitation']['PMID']\n",
    "            pmc_id = 'nan'\n",
    "            pmc_id_temp = record['PubmedData']['ArticleIdList']\n",
    "            \n",
    "            # Extract PMC ID if available\n",
    "            for ele in pmc_id_temp:\n",
    "                if ele.attributes['IdType'] == 'pmc':\n",
    "                    pmc_id = ele.replace('PMC', '')\n",
    "                    break\n",
    "\n",
    "            # Fetch full article from PMC\n",
    "            if pmc_id != 'nan':\n",
    "                handle = Entrez.efetch(db=\"pmc\", id=pmc_id, rettype=\"full\", retmode=\"xml\")\n",
    "                full_article = handle.read()\n",
    "                handle.close()\n",
    "\n",
    "                # Split the full article into chunks\n",
    "                cleaned_full_article = extract_text_from_pmc_xml(full_article)\n",
    "                full_articles.append({\n",
    "                    \"PMID\": pmid,\n",
    "                    \"Title\": title,\n",
    "                    \"FullText\": cleaned_full_article   # Add chunked text\n",
    "                })\n",
    "            else:\n",
    "                full_articles.append({\"PMID\": pmid, \"Title\": title, \"FullText\": \"cannot fetch\"})\n",
    "        except KeyError:\n",
    "            pass\n",
    "\n",
    "    # Create corpus for each chunk\n",
    "    for article in full_articles:\n",
    "        article_id = str(uuid.uuid4())\n",
    "        corpus[article_id] = {\n",
    "            \"page_content\": article[\"FullText\"],\n",
    "            \"metadata\": {\n",
    "                \"PMID\": article[\"PMID\"],\n",
    "                \"Title\": article[\"Title\"]\n",
    "            }\n",
    "        }\n",
    "\n",
    "    documents = [\n",
    "        Document(page_content=content[\"page_content\"], metadata=content[\"metadata\"]) \n",
    "        for content in corpus.values()\n",
    "    ]\n",
    "    CHUNK_SIZE = 1000\n",
    "    CHUNK_OVERLAP = 200\n",
    "\n",
    "    text_splitter = RecursiveCharacterTextSplitter(\n",
    "        chunk_size=CHUNK_SIZE,\n",
    "        chunk_overlap=CHUNK_OVERLAP,\n",
    "        length_function=len,\n",
    "    )\n",
    "    \n",
    "    split_chunks = text_splitter.split_documents(documents)\n",
    "    \n",
    "    id_set = set()\n",
    "    for document in split_chunks:\n",
    "        id = str(uuid.uuid4())\n",
    "        while id in id_set:\n",
    "            id = uuid.uuid4()\n",
    "        id_set.add(id)\n",
    "        document.metadata[\"uuid\"] = id\n",
    "\n",
    "    LOCATION = \":memory:\"\n",
    "    COLLECTION_NAME = \"pmd_data\"\n",
    "    VECTOR_SIZE = 384\n",
    "\n",
    "    # Initialize Qdrant client\n",
    "    qdrant_client = QdrantClient(location=LOCATION)\n",
    "\n",
    "    # Create a collection in Qdrant\n",
    "    qdrant_client.create_collection(\n",
    "        collection_name=COLLECTION_NAME,\n",
    "        vectors_config=VectorParams(size=VECTOR_SIZE, distance=Distance.COSINE),\n",
    "    )\n",
    "\n",
    "    # Initialize the Qdrant vector store without the embedding argument\n",
    "    vdb = QdrantVectorStore(\n",
    "        client=qdrant_client,\n",
    "        collection_name=COLLECTION_NAME,\n",
    "        embedding=embedding_model,\n",
    "    )\n",
    "\n",
    "    # Add embedded documents to Qdrant\n",
    "    vdb.add_documents(split_chunks)\n",
    "\n",
    "    # Query for each paper and consolidate answers\n",
    "    for pmid in pmids:\n",
    "        # Correctly structure the filter using Qdrant Filter model\n",
    "        qdrant_filter = Filter(\n",
    "            must=[\n",
    "                FieldCondition(key=\"metadata.PMID\", match=MatchValue(value=pmid))\n",
    "            ]\n",
    "        )\n",
    "\n",
    "        # Custom filtering for the retriever to only fetch chunks related to the current PMID\n",
    "        retriever_with_filter = vdb.as_retriever(\n",
    "            search_kwargs={\n",
    "                \"filter\": qdrant_filter,  # Correctly passing the Qdrant filter\n",
    "                \"k\": 3  # Retrieve 3 chunks per PMID\n",
    "            }\n",
    "        )\n",
    "\n",
    "        # Reset message history and memory for each query to avoid interference\n",
    "        message_history = ChatMessageHistory()\n",
    "        memory = ConversationBufferMemory(memory_key=\"chat_history\", output_key=\"answer\", chat_memory=message_history, return_messages=True)\n",
    "\n",
    "        # Create the ConversationalRetrievalChain with the filtered retriever\n",
    "        qa_chain = ConversationalRetrievalChain.from_llm(\n",
    "            ChatOpenAI(model_name=\"gpt-3.5-turbo\", temperature=0),\n",
    "            retriever=retriever_with_filter,\n",
    "            memory=memory,\n",
    "            return_source_documents=True\n",
    "        )\n",
    "\n",
    "        # Query the vector store for relevant documents and extract information\n",
    "        result = qa_chain({\"question\": query})\n",
    "\n",
    "        # Generate the final answer based on the retrieved chunks\n",
    "        generated_answer = result[\"answer\"]  # This contains the LLM's generated answer based on the retrieved chunks\n",
    "        generated_source = result[\"source_documents\"]\n",
    "\n",
    "        # Consolidate the results for each paper\n",
    "        paper_info = {\n",
    "            \"PMID\": pmid,\n",
    "            \"Title\": result[\"source_documents\"][0].metadata[\"Title\"] if result[\"source_documents\"] else \"Unknown Title\",\n",
    "            \"Generated Answer\": generated_answer,  # Store the generated answer,\n",
    "            \"Sources\": generated_source \n",
    "        }\n",
    "\n",
    "        consolidated_results[pmid] = paper_info\n",
    "\n",
    "    # Return consolidated results for all papers\n",
    "    return consolidated_results\n",
    "\n",
    "rag_tool = StructuredTool(\n",
    "    name=\"Fetch_Extract_Tool\",\n",
    "    func=fetch_and_extract,\n",
    "    description=\"\"\"Fetch full-text articles based on PMIDs and store them in a Qdrant vector database.\n",
    "    Then extract information based on user's query via Qdrant retriever using a RAG pipeline.\n",
    "    Requires list of PMIDs and user query as input.\"\"\",\n",
    "    args_schema=FetchExtractInput\n",
    ")\n",
    "\n",
    "\n",
    "tool_belt = [\n",
    "    pubmed_tool,\n",
    "    semantic_screening_tool,\n",
    "    rag_tool\n",
    "]\n",
    "\n",
    "# Model setup with tools bound\n",
    "model = ChatOpenAI(model=\"gpt-4o\", temperature=0)\n",
    "model = model.bind_tools(tool_belt)\n",
    "\n",
    "# Agent state to handle the messages\n",
    "class AgentState(TypedDict):\n",
    "    messages: Annotated[list, add_messages]\n",
    "    cycle_count: int  # Add a counter to track the number of cycles\n",
    "\n",
    "# Function to call the model and handle the flow automatically\n",
    "def call_model(state):\n",
    "    messages = state[\"messages\"]\n",
    "    response = model.invoke(messages)\n",
    "    return {\"messages\": [response], \"cycle_count\": state[\"cycle_count\"] + 1}  # Increment cycle count\n",
    "\n",
    "tool_node = ToolNode(tool_belt)\n",
    "\n",
    "# Create the state graph for managing the flow between the agent and tools\n",
    "uncompiled_graph = StateGraph(AgentState)\n",
    "uncompiled_graph.add_node(\"agent\", call_model)\n",
    "uncompiled_graph.add_node(\"action\", tool_node)\n",
    "\n",
    "# Set the entry point for the graph\n",
    "uncompiled_graph.set_entry_point(\"agent\")\n",
    "\n",
    "# Define a function to check if the process should continue\n",
    "def should_continue(state):\n",
    "    # Check if the cycle count exceeds the limit (e.g., 10)\n",
    "    if state[\"cycle_count\"] > 20:\n",
    "        print(f\"Reached the cycle limit of {state['cycle_count']} cycles. Ending the process.\")\n",
    "        return END\n",
    "    \n",
    "    # If there are tool calls, continue to the action node\n",
    "    last_message = state[\"messages\"][-1]\n",
    "    if last_message.tool_calls:\n",
    "        return \"action\"\n",
    "    \n",
    "    return END\n",
    "\n",
    "# Add conditional edges for the agent to action\n",
    "uncompiled_graph.add_conditional_edges(\"agent\", should_continue)\n",
    "uncompiled_graph.add_edge(\"action\", \"agent\")\n",
    "\n",
    "# Compile the state graph\n",
    "compiled_graph = uncompiled_graph.compile()\n",
    "\n",
    "# SystemMessage that defines the execution flow\n",
    "system_instructions = SystemMessage(content=\"\"\"Please execute the following steps in sequence:\n",
    "1. Use the PubMed search tool to search for papers.\n",
    "2. Retrieve the abstracts from the search results.\n",
    "3. Screen the abstracts based on the criteria provided by the user.\n",
    "4. Fetch full-text articles for all the papers that pass step 3. Store the full-text articles in the Qdrant vector database, \n",
    "    and extract the requested information for each article that passed step 3 from the full-text using the query provided by the user.\n",
    "5. Please provide a full summary at the end of the entire flow executed, detailing the whole process/reasoning for each paper. \n",
    "The user will provide the search query, screening criteria, and the query for information extraction.\n",
    "Make sure you finish everything in one step before moving on to next step.\n",
    "Do not call more than one tool in one action.\"\"\")\n",
    "\n",
    "# HumanMessage only includes the necessary inputs\n",
    "human_inputs = HumanMessage(content=\"\"\"{\n",
    "    \"query\": \"(\\\"Impact\\\"[Title/Abstract]) AND ((\\\"COVID\\\"[Title/Abstract] OR \\\"pandemic\\\"[Title/Abstract]) AND (\\\"healthcare resource utilization\\\"[Title/Abstract] OR \\\"health resource utilization\\\"[Title/Abstract]))\",\n",
    "    \"screening_criteria\": \"comparison of healthcare resource utilization before and after the COVID pandemic\",\n",
    "    \"extraction_query\": \"data source information used in each paper (especially medical records)\"\n",
    "}\"\"\")\n",
    "\n",
    "# Combined input for the agent\n",
    "inputs = {\n",
    "    \"messages\": [system_instructions, human_inputs],\n",
    "    \"cycle_count\": 0,  # Initialize cycle count to 0\n",
    "}\n",
    "\n",
    "# # Function to run the graph asynchronously\n",
    "async def run_graph():\n",
    "    final_message_content = None  # Variable to store the final message content\n",
    "\n",
    "    async for chunk in compiled_graph.astream(inputs, stream_mode=\"updates\"):\n",
    "        for node, values in chunk.items():\n",
    "            print(f\"Receiving update from node: '{node}'\")\n",
    "            pretty_print(values[\"messages\"])  # Print all messages as before\n",
    "            \n",
    "            # Check if the message contains content\n",
    "            if \"messages\" in values and values[\"messages\"]:\n",
    "                final_message = values[\"messages\"][-1]  # Access the last message in this chunk\n",
    "                if hasattr(final_message, 'content'):  # Check if content exists\n",
    "                    final_message_content = final_message.content  # Store the last message's content\n",
    "                \n",
    "        print(\"\\n\\n\")\n",
    "\n",
    "    # After the loop finishes, print the final message content\n",
    "    if final_message_content:\n",
    "        print(\"Final message content from the last chunk:\")\n",
    "        pretty_print(final_message_content)\n",
    "    else:\n",
    "        print(\"No final message content found.\")\n",
    "\n",
    "# Run the compiled graph\n",
    "await run_graph()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "c:\\Users\\YLiang\\.conda\\envs\\llmops-course\\Lib\\site-packages\\transformers\\tokenization_utils_base.py:1617: FutureWarning: `clean_up_tokenization_spaces` was not set. It will be set to `True` by default. This behavior will be deprecated in transformers v4.45, and will be then set to `False` by default. For more details check this issue: https://github.com/huggingface/transformers/issues/31884\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'39063396': {'PMID': '39063396',\n",
       "  'Title': 'Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.',\n",
       "  'Generated Answer': \"I don't have that information based on the context provided.\",\n",
       "  'Sources': [Document(metadata={'PMID': '39063396', 'Title': 'Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.', 'uuid': 'fd8348fd-b855-45f7-992a-9b916629c09b', '_id': 'a8fbe8e1262f4ec694bff70b1dea2370', '_collection_name': 'pmd_data'}, page_content='Supplementary Materials\\n\\nThe following supporting information can be downloaded at:\\n\\nAuthor Contributions\\n\\nConceptualization: Y.Z. (Yunxi Zhang), L.S.L., J.M.S. and S.C.; Methodology: Y.Z. (Yunxi Zhang), L.S.L. and J.M.S.; Software: Y.Z. (Yunxi Zhang) and Y.Z. (Ying Zhang); Validation: Y.Z. (Yunxi Zhang), Y.Z. (Ying Zhang), and B.F.J.; Formal Analysis: Y.Z. (Yunxi Zhang); Investigation: Y.Z. (Yunxi Zhang), L.S.L., Y.-Y.L., J.M.S., B.F.J., S.C. and M.E.L.; Resources: Y.Z. (Yunxi Zhang), Y.Z. (Ying Zhang), R.L.S., B.F.J., S.C. and M.E.L.; Data Curation: Y.Z. (Ying Zhang); Visualization: Y.-Y.L.; Writing—Original Draft Preparation: Y.Z. (Yunxi Zhang); Writing—Review and Editing: Y.Z. (Yunxi Zhang), L.S.L., Y.-Y.L., J.M.S., Y.Z. (Ying Zhang), R.L.S., B.F.J., S.C. and M.E.L.; Supervision: J.M.S., S.C. and M.E.L.; Project Administration: Y.Z. (Yunxi Zhang) and S.C.; Funding Acquisition: R.L.S. and S.C. All authors have read and agreed to the published version of the manuscript.'),\n",
       "   Document(metadata={'PMID': '39063396', 'Title': 'Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.', 'uuid': 'a3961e7c-cbb3-44ba-b857-0770544e2fd6', '_id': '35ebfd3607be42fe9779f5d73d12669f', '_collection_name': 'pmd_data'}, page_content='5. Conclusions'),\n",
       "   Document(metadata={'PMID': '39063396', 'Title': 'Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.', 'uuid': '168c2b95-c340-4ca3-8291-10523de8add9', '_id': '0835f877eb11476a9ee77361ea66f593', '_collection_name': 'pmd_data'}, page_content='2.4. Statistical Analysis\\n\\nDescriptive statistics, including mean with standard deviation (SD) and frequency with percentage (%), were used to summarize continuous and categorical variables. The Shapiro–Wilk test was used to examine the normality of continuous variables for HCRU and medical expenditures. We examined the association between sociodemographic factors and the utilization of TMH services using Pearson’s\\n\\nThe Wilcoxon rank sum test was employed to compare the non-normally distributed variables of HCRU and medical expenditures. To adjust for the sociodemographic factors, generalized linear regression models (GLMs) with log links were constructed to assess the impact of TMH usage on HCRU and medical expenditures. Specifically, we fitted Poisson regression models, negative binomial regression models, or zero-inflated Poisson regression models for HCRU outcomes, depending on their distributions, and Gamma regression models for medical expenditures.')]},\n",
       " '39051414': {'PMID': '39051414',\n",
       "  'Title': 'Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.',\n",
       "  'Generated Answer': 'The data source used in the paper provided is the 2020 National Inpatient Sample (NIS) dataset, which covers hospitalizations in the United States from January 1, 2020, to December 31, 2020. The NIS dataset is derived from the State Inpatient Databases (SIDs) and is part of the Healthcare Cost and Utilization Project sponsored by the Agency for Healthcare Research and Quality (AHRQ). The dataset is de-identified and publicly available, representing an estimated 98% of the U.S. population.',\n",
       "  'Sources': [Document(metadata={'PMID': '39051414', 'Title': 'Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.', 'uuid': '36ab4b73-59f8-4539-94dd-c5d32b0b4380', '_id': 'e7a86941d7fc48c18fb7cb38e58896a4', '_collection_name': 'pmd_data'}, page_content='Supplementary Materials\\n\\nThe following supporting information can be downloaded at:\\n\\nAuthor Contributions\\n\\nConceptualization, Z.H.B. and M.H.; methodology, Z.H.B.; formal analysis, Z.H.B.; investigation and analysis, Z.H.B.; writing—original draft preparation, Z.H.B., M.H., F.N., A.B.A., A.O., M.J.K., M.S.F., F.K. and A.-R.Z.; writing—review and editing, Z.H.B., M.H., F.N., A.B.A., A.O., M.J.K., M.S.F., F.K. and A.-R.Z.; visualization, Y.B. and C.L.B.; supervision, Y.B. and C.L.B. All authors have read and agreed to the published version of the manuscript.\\n\\nInstitutional Review Board Statement\\n\\nEthical review and approval were waived for this study as it does not involve research with human subjects and the dataset used is de-identified.\\n\\nInformed Consent Statement\\n\\nIt is a retrospective study using publicly available de-identified data and consent is not required.\\n\\nData Availability Statement'),\n",
       "   Document(metadata={'PMID': '39051414', 'Title': 'Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.', 'uuid': '38957a2b-0cec-4957-95d1-6f1a6eb56df9', '_id': '55e4fa42c60848918e1d2d60c01417ea', '_collection_name': 'pmd_data'}, page_content='3. Materials and Methods\\n\\n\\n\\n3.1. Study Design and Database Description\\n\\nUtilizing the 2020 National Inpatient Sample (NIS) dataset, we conducted a retrospective cohort analysis of adult patients admitted with a primary diagnosis of sickle cell crisis in the United States. The NIS 2020 dataset specifically covers hospitalizations within the period from 1 January 2020 to 31 December 2020. It derives from the State Inpatient Databases (SIDs) that cover an estimated 98% of the U.S. population. As part of the Healthcare Cost and Utilization Project sponsored by Agency for Healthcare Research and Quality (AHRQ), the NIS is the most extensive, de-identified, publicly available inpatient database in the U.S. This database employs a 20% stratified discharge sample, which is then weighted relative to the total discharges to ensure national representativeness.\\n\\n\\n\\n3.2. Study Patients'),\n",
       "   Document(metadata={'PMID': '39051414', 'Title': 'Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.', 'uuid': '16393d9e-b309-4681-9a96-de3e12262940', '_id': '64c8170f62524d498ec71156452f5bd0', '_collection_name': 'pmd_data'}, page_content='3.4. Statistical Analyses\\n\\nAnalyses were performed using STATA, version MP 14.2 (StataCorp, College Station, TX, USA). The study used univariate and multivariate regression analyses to compute unadjusted and adjusted outcomes, respectively. The univariate analysis was conducted to identify potential confounding factors. All confounders that displayed a significant relationship with the outcome, using a\\n\\n\\n\\n4. Results\\n\\n\\n\\nPatient Characteristics')]}}"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result = rag_tool.func(pmids=[\"39063396\",\"39051414\"],query = \"what are the data sources used in each paper?\")  # Example PMIDs\n",
    "result"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### also tested to retrieve 10 papers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2024-10-03 14:29:34 - HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n",
      "Receiving update from node: 'agent'\n"
     ]
    },
    {
     "data": {
      "text/markdown": [
       "```markdown\n",
       "[AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_SEES104ri8aPSNMcFPXGZI2B', 'function': {'arguments': '{\"query\":\"(Impact[Title/Abstract]) AND ((COVID[Title/Abstract] OR pandemic[Title/Abstract]) AND (healthcare resource utilization[Title/Abstract] OR health resource utilization[Title/Abstract]))\"}', 'name': 'PubMed_Search_Tool'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 59, 'prompt_tokens': 496, 'total_tokens': 555, 'prompt_tokens_details': {'cached_tokens': 0}, 'completion_tokens_details': {'reasoning_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_e5e4913e83', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-47551650-3541-4800-a25f-847ceb4d21ab-0', tool_calls=[{'name': 'PubMed_Search_Tool', 'args': {'query': '(Impact[Title/Abstract]) AND ((COVID[Title/Abstract] OR pandemic[Title/Abstract]) AND (healthcare resource utilization[Title/Abstract] OR health resource utilization[Title/Abstract]))'}, 'id': 'call_SEES104ri8aPSNMcFPXGZI2B', 'type': 'tool_call'}], usage_metadata={'input_tokens': 496, 'output_tokens': 59, 'total_tokens': 555})]\n",
       "```"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\n",
      "Receiving update from node: 'action'\n"
     ]
    },
    {
     "data": {
      "text/markdown": [
       "```markdown\n",
       "[ToolMessage(content='[{\"PMID\": \"39291999\", \"Title\": \"Clinical manifestations, healthcare resource utilization, and costs among patients with long-chain fatty acid oxidation disorders: a retrospective claims database analysis.\", \"Abstract\": \"Long-chain fatty acid oxidation disorders (LC-FAOD) are a group of rare genetic inborn errors of metabolism. Clinical manifestations may result in frequent healthcare visits, hospitalizations, and early death. This retrospective cohort study assessed manifestations, healthcare resource use (HRU), direct medical costs, and the impact of COVID-19 on HRU among patients with LC-FAOD.\"}, {\"PMID\": \"39063396\", \"Title\": \"Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.\", \"Abstract\": \"During the COVID-19 pandemic, tele-mental health (TMH) was a viable approach for providing accessible mental and behavioral health (MBH) services. This study examines the sociodemographic disparities in TMH utilization and its effects on healthcare resource utilization (HCRU) and medical expenditures in Mississippi. Utilizing a cohort of 6787 insured adult patients at the University of Mississippi Medical Center and its affiliated sites between January 2020 and June 2023, including 3065 who accessed TMH services, we observed sociodemographic disparities between TMH and non-TMH cohorts. The TMH cohort was more likely to be younger, female, White/Caucasian, using payment methods other than Medicare, Medicaid, or commercial insurers, residing in rural areas, and with higher household income compared to the non-TMH cohort. Adjusting for sociodemographic factors, TMH utilization was associated with a 190% increase in MBH-related outpatient visits, a 17% increase in MBH-related medical expenditures, and a 12% decrease in all-cause medical expenditures (all <i>p</i> < 0.001). Among rural residents, TMH utilization was associated with a 205% increase in MBH-related outpatient visits and a 19% decrease in all-cause medical expenditures (both <i>p</i> < 0.001). This study underscores the importance of addressing sociodemographic disparities in TMH services to promote equitable healthcare access while reducing overall medical expenditures.\"}, {\"PMID\": \"39051414\", \"Title\": \"Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.\", \"Abstract\": \"<b>Background:</b> This study investigated the impact of COVID-19 on patients with sickle cell crisis (SCC) using National Inpatient Sample (NIS) data for the year 2020. <b>Methods:</b> A retrospective cohort analysis was conducted utilizing International Classification of Diseases (ICD-10) codes to identify adults who were admitted with a principal diagnosis of sickle cell crisis. The primary outcomes examined were inpatient mortality, while the secondary outcomes assessed included morbidity, hospital length of stay, and resource utilization. Analyses were conducted with STATA. Multivariate logistic and linear regression analyses were used to adjust for confounding variables. <b>Results:</b> Of 66,415 adult patients with a primary SCC diagnosis, 875 were identified with a secondary diagnosis of COVID-19 infection. Unadjusted mortality rate was higher for SCC patients with COVID-19 (2.28%) compared to those without (0.33%), with an adjusted odds ratio (aOR) of 8.49 (<i>p</i> = 0.001). They also showed increased odds of developing acute respiratory failure (aOR = 2.37, <i>p</i> = 0.003) and acute kidney injury requiring dialysis (aOR = 8.66, <i>p</i> = 0.034). Additionally, these patients had longer hospital stays by an adjusted mean of 3.30 days (<i>p</i> < 0.001) and incurred higher hospitalization charges by an adjusted mean of USD 35,578 (<i>p</i> = 0.005). <b>Conclusions:</b> The SCC patients with COVID-19 presented higher mortality rates, increased morbidity indicators, longer hospital stays, and substantial economic burdens.\"}, {\"PMID\": \"38966443\", \"Title\": \"Epidemiology of Pediatric Respiratory Tract Infections During the COVID-19 Era: A Retrospective Multicentric Study of Hospitalized Children in Lebanon Between October 2018 and March 2021.\", \"Abstract\": \"Background The identification of SARS-CoV-2 in December 2019 and its subsequent designation as the causative agent of COVID-19 marked the beginning of an unprecedented global health crisis. As the virus spread rapidly across continents, its impact on various demographic groups, including children, became a subject of intense research. While children were initially thought to be less susceptible to severe COVID-19 illness compared to adults, concerns emerged regarding their vulnerability to other respiratory infections amidst the pandemic. Understanding the epidemiological trends of pediatric respiratory tract infections (RTIs) during the COVID-19 era is crucial for informing public health strategies and clinical management protocols. This study aimed to compare the prevalence and characteristics of pediatric RTIs before and during the COVID-19 pandemic in Lebanon. Methodology A retrospective, observational study was conducted by reviewing medical records of children admitted to three tertiary care hospitals in Lebanon: Sheikh Ragheb Harb University Hospital, Al Sahel General University Hospital, and Rafik Al-Hariri University Hospital. Data were collected from October 2018 to March 2021, encompassing both the pre-COVID-19 and COVID-19 eras. A standardized data collection sheet was utilized to gather information on demographic characteristics, clinical presentations, duration of hospitalization, and antibiotic usage. Results Our analysis revealed significant shifts in the epidemiology of pediatric RTIs between the pre-COVID-19 and COVID-19 eras. There was a marked decline in the proportion of school-age children hospitalized with RTIs during the pandemic period. However, the overall percentage of Lebanese hospitalized children across different age groups increased significantly during the COVID-19 era. Furthermore, the prevalence of specific RTIs, such as pharyngitis, increased from 1.1% in the pre-COVID-19\\\\u00a0to 5.5% during the COVID-19 period (p = 0.016), and the prevalence of bronchiolitis increased from 26.7% to 50.9% (p < 0.001) during the pre-COVID-19 and COVID-19 periods, respectively. This notable rise during the pandemic suggested potential changes in circulating pathogens or diagnostic practices. Importantly, the median length of hospital stays for pediatric RTIs decreased during the COVID-19 era compared to the pre-pandemic period, indicating possible improvements in clinical management or healthcare resource utilization. Analysis of antibiotic usage revealed ceftriaxone as the most frequently prescribed antibiotic in both periods, highlighting its continued relevance in the management of pediatric RTIs. Conclusions This study highlights significant epidemiological shifts in pediatric RTIs during the COVID-19 era in Lebanon. These findings underscore the importance of ongoing surveillance and research to adapt public health interventions and clinical practices to evolving infectious disease dynamics. Further investigation is warranted to elucidate the underlying factors driving these changes and optimize strategies for the prevention and management of pediatric RTIs in the context of the ongoing pandemic.\"}, {\"PMID\": \"38885115\", \"Title\": \"Initiating immunoglobulin replacement therapy helps reduce severe infections and shifts healthcare resource utilization to outpatient services among US patients with inborn errors of immunity.\", \"Abstract\": \"Patients with inborn errors of immunity (IEI) are predisposed to severe recurrent/chronic infections, and often require hospitalization, resulting in substantial burden to patients/healthcare systems. While immunoglobulin replacement therapies (IgRTs) are the standard first-line treatment for most forms of IEI, limited real-world data exist regarding clinical characteristics and treatment costs for patients with IEI initiating such treatment. This retrospective analysis examined infection and treatment characteristics in US patients with IEI initiating IgRT with immune globulin infusion (human), 10% (IG10%). Healthcare resource utilization (HCRU) and associated costs before and after treatment initiation were compared. Additionally, the impact of COVID-19 on infection diagnoses was evaluated.\"}, {\"PMID\": \"38779335\", \"Title\": \"Impact of Pre-existing Type 2 Diabetes Mellitus and Cardiovascular Disease on Healthcare Resource Utilization and Costs in Patients With COVID-19.\", \"Abstract\": \"<b>Background:</b> The economic burden associated with type 2 diabetes mellitus (T2DM) and concurrent cardiovascular disease (CVD) among patients with COVID-19 is unclear. <b>Objective:</b> We compared healthcare resource utilization (HCRU) and costs in patients with COVID-19 and T2DM and CVD (T2DM\\\\u2009+\\\\u2009CVD), T2DM only, or neither T2DM nor CVD (T2DM/CVD). <b>Methods:</b> A retrospective observational study in COVID-19 patients using data from the Healthcare Integrated Research Database (HIRD\\\\u00ae) was conducted. Patients with COVID-19 were identified between March 1, 2020, and May 31, 2021, and followed from first diagnosis or positive lab test to the end of health plan enrollment, end of study period, or death. Patients were assigned one of 3 cohorts: pre-existing T2DM+CVD, T2DM only, or neither T2DM/CVD. Propensity score matching and multivariable analyses were performed to control for differences in baseline characteristics. Study outcomes included all-cause and COVID-19-related HCRU and costs. <b>Results:</b> In all, 321\\\\u202f232 COVID-19 patients were identified (21\\\\u202f651 with T2DM\\\\u2009+\\\\u2009CVD, 28\\\\u202f184 with T2DM only, and 271\\\\u202f397 with neither T2DM/CVD). After matching, 6967 patients were in each group. Before matching, 46.0% of patients in the T2DM\\\\u2009+\\\\u2009CVD cohort were hospitalized for any cause, compared with 18.0% in the T2DM-only cohort and 6.3% in the neither T2DM/CVD cohort; the corresponding values after matching were 34.2%, 26.0%, and 21.2%. The proportion of patients with emergency department visits, telehealth visits, or use of skilled nursing facilities was higher in patients with COVID-19 and T2DM\\\\u2009+\\\\u2009CVD compared with the other cohorts. Average all-cause costs during follow-up were <math xmlns=\\\\\"http://www.w3.org/1998/Math/MathML\\\\\"><mn>12</mn><mrow><mo>\\\\u202f</mo></mrow><mn>324</mn><mo>,</mo></math>7882, and $7277 per-patient-per-month after matching for patients with T2DM\\\\u2009+\\\\u2009CVD, T2DM-only, and neither T2DM/CVD, respectively. COVID-19-related costs contributed to 78%, 75%, and 64% of the overall costs, respectively. The multivariable model showed that per-patient-per-month all-cause costs for T2DM\\\\u2009+\\\\u2009CVD and T2DM-only were 54% and 21% higher, respectively, than those with neither T2DM/CVD after adjusting for residual confounding. <b>Conclusion:</b> HCRU and costs in patients were incrementally higher with COVID-19 and pre-existing T2DM\\\\u2009+\\\\u2009CVD compared with those with T2DM-only and neither T2DM/CVD, even after accounting for baseline differences between groups, confirming that pre-existing T2DM\\\\u2009+\\\\u2009CVD is associated with increased HCRU and costs in COVID-19 patients, highlighting the importance of proactive management.\"}, {\"PMID\": \"38686393\", \"Title\": \"Real-world total cost of care by line of therapy in relapsed/refractory diffuse large B-cell lymphoma.\", \"Abstract\": \"There are multiple recently approved treatments and a lack of clear standard-of-care therapies for relapsed/refractory (R/R) diffuse large B-cell lymphoma (DLBCL). While total cost of care (TCC) by the number of lines of therapy (LoTs) has been evaluated, more recent cost estimates using real-world data are needed. This analysis assessed real-world TCC of R/R DLBCL therapies by LoT using the IQVIA PharMetrics Plus database (1 January 2015-31 December 2021), in US patients aged \\\\u226518\\\\u2009years treated with rituximab plus cyclophosphamide, doxorubicin, vincristine, and prednisone (R-CHOP) or an R-CHOP-like regimen as first-line therapy.\"}, {\"PMID\": \"38644506\", \"Title\": \"Impact of COVID-19 pandemic on depression incidence and healthcare service use among patients with depression: an interrupted time-series analysis from a 9-year population-based study.\", \"Abstract\": \"Most studies on the impact of the COVID-19 pandemic on depression burden focused on the earlier pandemic phase specific to lockdowns, but the longer-term impact of the pandemic is less well-studied. In this population-based cohort study, we examined the short-term and long-term impacts of COVID-19 on depression incidence and healthcare service use among patients with depression.\"}, {\"PMID\": \"38534198\", \"Title\": \"Burden of disease and treatment patterns in patients with vitiligo: findings from a national longitudinal retrospective study in the UK.\", \"Abstract\": \"UK studies examining vitiligo burden and vitiligo-related healthcare resource utilization (HCRU) are lacking.\"}, {\"PMID\": \"38435542\", \"Title\": \"Impact Of body Mass Index on Cardiopulmonary Outcomes of COVID-19 Hospitalizations Complicated by Severe Sepsis.\", \"Abstract\": \"Body Mass Index (BMI) has a significant impact on Coronavirus disease (COVID-19) patient outcomes; however, major adverse cardiac and cerebrovascular outcomes in patients with severe sepsis have been poorly understood. Our study aims to explore and provide insight into its association.\"}]', name='PubMed_Search_Tool', tool_call_id='call_SEES104ri8aPSNMcFPXGZI2B')]\n",
       "```"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\n",
      "2024-10-03 14:29:40 - HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n",
      "Receiving update from node: 'agent'\n"
     ]
    },
    {
     "data": {
      "text/markdown": [
       "```markdown\n",
       "[AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_COqnk3EZgSEcOw5kP0XQFX3E', 'function': {'arguments': '{\"criteria\":\"comparison of healthcare resource utilization before and after the COVID pandemic\"}', 'name': 'Semantic_Abstract_Screening_Tool'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 30, 'prompt_tokens': 3595, 'total_tokens': 3625, 'prompt_tokens_details': {'cached_tokens': 0}, 'completion_tokens_details': {'reasoning_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_e5e4913e83', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-e00108fb-5250-4ed3-952f-10130f5ddd12-0', tool_calls=[{'name': 'Semantic_Abstract_Screening_Tool', 'args': {'criteria': 'comparison of healthcare resource utilization before and after the COVID pandemic'}, 'id': 'call_COqnk3EZgSEcOw5kP0XQFX3E', 'type': 'tool_call'}], usage_metadata={'input_tokens': 3595, 'output_tokens': 30, 'total_tokens': 3625})]\n",
       "```"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\n",
      "Receiving update from node: 'action'\n"
     ]
    },
    {
     "data": {
      "text/markdown": [
       "```markdown\n",
       "[ToolMessage(content=\"Error: 1 validation error for AbstractScreeningInput\\nabstracts\\n  Field required [type=missing, input_value={'criteria': 'comparison ...ter the COVID pandemic'}, input_type=dict]\\n    For further information visit https://errors.pydantic.dev/2.9/v/missing\\n Please fix your mistakes.\", name='Semantic_Abstract_Screening_Tool', tool_call_id='call_COqnk3EZgSEcOw5kP0XQFX3E')]\n",
       "```"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\n",
      "2024-10-03 14:30:09 - HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n",
      "Receiving update from node: 'agent'\n"
     ]
    },
    {
     "data": {
      "text/markdown": [
       "```markdown\n",
       "[AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_JQqUPfw2NKpTgmP4Eaj8xDRt', 'function': {'arguments': '{\"criteria\":\"comparison of healthcare resource utilization before and after the COVID pandemic\",\"abstracts\":[{\"PMID\":\"39291999\",\"Title\":\"Clinical manifestations, healthcare resource utilization, and costs among patients with long-chain fatty acid oxidation disorders: a retrospective claims database analysis.\",\"Abstract\":\"Long-chain fatty acid oxidation disorders (LC-FAOD) are a group of rare genetic inborn errors of metabolism. Clinical manifestations may result in frequent healthcare visits, hospitalizations, and early death. This retrospective cohort study assessed manifestations, healthcare resource use (HRU), direct medical costs, and the impact of COVID-19 on HRU among patients with LC-FAOD.\"},{\"PMID\":\"39063396\",\"Title\":\"Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.\",\"Abstract\":\"During the COVID-19 pandemic, tele-mental health (TMH) was a viable approach for providing accessible mental and behavioral health (MBH) services. This study examines the sociodemographic disparities in TMH utilization and its effects on healthcare resource utilization (HCRU) and medical expenditures in Mississippi. Utilizing a cohort of 6787 insured adult patients at the University of Mississippi Medical Center and its affiliated sites between January 2020 and June 2023, including 3065 who accessed TMH services, we observed sociodemographic disparities between TMH and non-TMH cohorts. The TMH cohort was more likely to be younger, female, White/Caucasian, using payment methods other than Medicare, Medicaid, or commercial insurers, residing in rural areas, and with higher household income compared to the non-TMH cohort. Adjusting for sociodemographic factors, TMH utilization was associated with a 190% increase in MBH-related outpatient visits, a 17% increase in MBH-related medical expenditures, and a 12% decrease in all-cause medical expenditures (all <i>p</i> < 0.001). Among rural residents, TMH utilization was associated with a 205% increase in MBH-related outpatient visits and a 19% decrease in all-cause medical expenditures (both <i>p</i> < 0.001). This study underscores the importance of addressing sociodemographic disparities in TMH services to promote equitable healthcare access while reducing overall medical expenditures.\"},{\"PMID\":\"39051414\",\"Title\":\"Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.\",\"Abstract\":\"<b>Background:</b> This study investigated the impact of COVID-19 on patients with sickle cell crisis (SCC) using National Inpatient Sample (NIS) data for the year 2020. <b>Methods:</b> A retrospective cohort analysis was conducted utilizing International Classification of Diseases (ICD-10) codes to identify adults who were admitted with a principal diagnosis of sickle cell crisis. The primary outcomes examined were inpatient mortality, while the secondary outcomes assessed included morbidity, hospital length of stay, and resource utilization. Analyses were conducted with STATA. Multivariate logistic and linear regression analyses were used to adjust for confounding variables. <b>Results:</b> Of 66,415 adult patients with a primary SCC diagnosis, 875 were identified with a secondary diagnosis of COVID-19 infection. Unadjusted mortality rate was higher for SCC patients with COVID-19 (2.28%) compared to those without (0.33%), with an adjusted odds ratio (aOR) of 8.49 (<i>p</i> = 0.001). They also showed increased odds of developing acute respiratory failure (aOR = 2.37, <i>p</i> = 0.003) and acute kidney injury requiring dialysis (aOR = 8.66, <i>p</i> = 0.034). Additionally, these patients had longer hospital stays by an adjusted mean of 3.30 days (<i>p</i> < 0.001) and incurred higher hospitalization charges by an adjusted mean of USD 35,578 (<i>p</i> = 0.005). <b>Conclusions:</b> The SCC patients with COVID-19 presented higher mortality rates, increased morbidity indicators, longer hospital stays, and substantial economic burdens.\"},{\"PMID\":\"38966443\",\"Title\":\"Epidemiology of Pediatric Respiratory Tract Infections During the COVID-19 Era: A Retrospective Multicentric Study of Hospitalized Children in Lebanon Between October 2018 and March 2021.\",\"Abstract\":\"Background The identification of SARS-CoV-2 in December 2019 and its subsequent designation as the causative agent of COVID-19 marked the beginning of an unprecedented global health crisis. As the virus spread rapidly across continents, its impact on various demographic groups, including children, became a subject of intense research. While children were initially thought to be less susceptible to severe COVID-19 illness compared to adults, concerns emerged regarding their vulnerability to other respiratory infections amidst the pandemic. Understanding the epidemiological trends of pediatric respiratory tract infections (RTIs) during the COVID-19 era is crucial for informing public health strategies and clinical management protocols. This study aimed to compare the prevalence and characteristics of pediatric RTIs before and during the COVID-19 pandemic in Lebanon. Methodology A retrospective, observational study was conducted by reviewing medical records of children admitted to three tertiary care hospitals in Lebanon: Sheikh Ragheb Harb University Hospital, Al Sahel General University Hospital, and Rafik Al-Hariri University Hospital. Data were collected from October 2018 to March 2021, encompassing both the pre-COVID-19 and COVID-19 eras. A standardized data collection sheet was utilized to gather information on demographic characteristics, clinical presentations, duration of hospitalization, and antibiotic usage. Results Our analysis revealed significant shifts in the epidemiology of pediatric RTIs between the pre-COVID-19 and COVID-19 eras. There was a marked decline in the proportion of school-age children hospitalized with RTIs during the pandemic period. However, the overall percentage of Lebanese hospitalized children across different age groups increased significantly during the COVID-19 era. Furthermore, the prevalence of specific RTIs, such as pharyngitis, increased from 1.1% in the pre-COVID-19 to 5.5% during the COVID-19 period (p = 0.016), and the prevalence of bronchiolitis increased from 26.7% to 50.9% (p < 0.001) during the pre-COVID-19 and COVID-19 periods, respectively. This notable rise during the pandemic suggested potential changes in circulating pathogens or diagnostic practices. Importantly, the median length of hospital stays for pediatric RTIs decreased during the COVID-19 era compared to the pre-pandemic period, indicating possible improvements in clinical management or healthcare resource utilization. Analysis of antibiotic usage revealed ceftriaxone as the most frequently prescribed antibiotic in both periods, highlighting its continued relevance in the management of pediatric RTIs. Conclusions This study highlights significant epidemiological shifts in pediatric RTIs during the COVID-19 era in Lebanon. These findings underscore the importance of ongoing surveillance and research to adapt public health interventions and clinical practices to evolving infectious disease dynamics. Further investigation is warranted to elucidate the underlying factors driving these changes and optimize strategies for the prevention and management of pediatric RTIs in the context of the ongoing pandemic.\"},{\"PMID\":\"38885115\",\"Title\":\"Initiating immunoglobulin replacement therapy helps reduce severe infections and shifts healthcare resource utilization to outpatient services among US patients with inborn errors of immunity.\",\"Abstract\":\"Patients with inborn errors of immunity (IEI) are predisposed to severe recurrent/chronic infections, and often require hospitalization, resulting in substantial burden to patients/healthcare systems. While immunoglobulin replacement therapies (IgRTs) are the standard first-line treatment for most forms of IEI, limited real-world data exist regarding clinical characteristics and treatment costs for patients with IEI initiating such treatment. This retrospective analysis examined infection and treatment characteristics in US patients with IEI initiating IgRT with immune globulin infusion (human), 10% (IG10%). Healthcare resource utilization (HCRU) and associated costs before and after treatment initiation were compared. Additionally, the impact of COVID-19 on infection diagnoses was evaluated.\"},{\"PMID\":\"38779335\",\"Title\":\"Impact of Pre-existing Type 2 Diabetes Mellitus and Cardiovascular Disease on Healthcare Resource Utilization and Costs in Patients With COVID-19.\",\"Abstract\":\"<b>Background:</b> The economic burden associated with type 2 diabetes mellitus (T2DM) and concurrent cardiovascular disease (CVD) among patients with COVID-19 is unclear. <b>Objective:</b> We compared healthcare resource utilization (HCRU) and costs in patients with COVID-19 and T2DM and CVD (T2DM+CVD), T2DM only, or neither T2DM nor CVD (T2DM/CVD). <b>Methods:</b> A retrospective observational study in COVID-19 patients using data from the Healthcare Integrated Research Database (HIRD®) was conducted. Patients with COVID-19 were identified between March 1, 2020, and May 31, 2021, and followed from first diagnosis or positive lab test to the end of health plan enrollment, end of study period, or death. Patients were assigned one of 3 cohorts: pre-existing T2DM+CVD, T2DM only, or neither T2DM/CVD. Propensity score matching and multivariable analyses were performed to control for differences in baseline characteristics. Study outcomes included all-cause and COVID-19-related HCRU and costs. <b>Results:</b> In all, 321\\u202f232 COVID-19 patients were identified (21\\u202f651 with T2DM+CVD, 28\\u202f184 with T2DM only, and 271\\u202f397 with neither T2DM/CVD). After matching, 6967 patients were in each group. Before matching, 46.0% of patients in the T2DM+CVD cohort were hospitalized for any cause, compared with 18.0% in the T2DM-only cohort and 6.3% in the neither T2DM/CVD cohort; the corresponding values after matching were 34.2%, 26.0%, and 21.2%. The proportion of patients with emergency department visits, telehealth visits, or use of skilled nursing facilities was higher in patients with COVID-19 and T2DM+CVD compared with the other cohorts. Average all-cause costs during follow-up were <math xmlns=\\\\\"http://www.w3.org/1998/Math/MathML\\\\\"><mn>12</mn><mrow><mo>\\u202f</mo></mrow><mn>324</mn><mo>,</mo></math>7882, and $7277 per-patient-per-month after matching for patients with T2DM+CVD, T2DM-only, and neither T2DM/CVD, respectively. COVID-19-related costs contributed to 78%, 75%, and 64% of the overall costs, respectively. The multivariable model showed that per-patient-per-month all-cause costs for T2DM+CVD and T2DM-only were 54% and 21% higher, respectively, than those with neither T2DM/CVD after adjusting for residual confounding. <b>Conclusion:</b> HCRU and costs in patients were incrementally higher with COVID-19 and pre-existing T2DM+CVD compared with those with T2DM-only and neither T2DM/CVD, even after accounting for baseline differences between groups, confirming that pre-existing T2DM+CVD is associated with increased HCRU and costs in COVID-19 patients, highlighting the importance of proactive management.\"},{\"PMID\":\"38686393\",\"Title\":\"Real-world total cost of care by line of therapy in relapsed/refractory diffuse large B-cell lymphoma.\",\"Abstract\":\"There are multiple recently approved treatments and a lack of clear standard-of-care therapies for relapsed/refractory (R/R) diffuse large B-cell lymphoma (DLBCL). While total cost of care (TCC) by the number of lines of therapy (LoTs) has been evaluated, more recent cost estimates using real-world data are needed. This analysis assessed real-world TCC of R/R DLBCL therapies by LoT using the IQVIA PharMetrics Plus database (1 January 2015-31 December 2021), in US patients aged ≥18\\u202fyears treated with rituximab plus cyclophosphamide, doxorubicin, vincristine, and prednisone (R-CHOP) or an R-CHOP-like regimen as first-line therapy.\"},{\"PMID\":\"38644506\",\"Title\":\"Impact of COVID-19 pandemic on depression incidence and healthcare service use among patients with depression: an interrupted time-series analysis from a 9-year population-based study.\",\"Abstract\":\"Most studies on the impact of the COVID-19 pandemic on depression burden focused on the earlier pandemic phase specific to lockdowns, but the longer-term impact of the pandemic is less well-studied. In this population-based cohort study, we examined the short-term and long-term impacts of COVID-19 on depression incidence and healthcare service use among patients with depression.\"},{\"PMID\":\"38534198\",\"Title\":\"Burden of disease and treatment patterns in patients with vitiligo: findings from a national longitudinal retrospective study in the UK.\",\"Abstract\":\"UK studies examining vitiligo burden and vitiligo-related healthcare resource utilization (HCRU) are lacking.\"},{\"PMID\":\"38435542\",\"Title\":\"Impact Of body Mass Index on Cardiopulmonary Outcomes of COVID-19 Hospitalizations Complicated by Severe Sepsis.\",\"Abstract\":\"Body Mass Index (BMI) has a significant impact on Coronavirus disease (COVID-19) patient outcomes; however, major adverse cardiac and cerebrovascular outcomes in patients with severe sepsis have been poorly understood. Our study aims to explore and provide insight into its association.\"}]}', 'name': 'Semantic_Abstract_Screening_Tool'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 2929, 'prompt_tokens': 3703, 'total_tokens': 6632, 'prompt_tokens_details': {'cached_tokens': 0}, 'completion_tokens_details': {'reasoning_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_e5e4913e83', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-729796e3-6e83-432e-a748-7eb29289b3d2-0', tool_calls=[{'name': 'Semantic_Abstract_Screening_Tool', 'args': {'criteria': 'comparison of healthcare resource utilization before and after the COVID pandemic', 'abstracts': [{'PMID': '39291999', 'Title': 'Clinical manifestations, healthcare resource utilization, and costs among patients with long-chain fatty acid oxidation disorders: a retrospective claims database analysis.', 'Abstract': 'Long-chain fatty acid oxidation disorders (LC-FAOD) are a group of rare genetic inborn errors of metabolism. Clinical manifestations may result in frequent healthcare visits, hospitalizations, and early death. This retrospective cohort study assessed manifestations, healthcare resource use (HRU), direct medical costs, and the impact of COVID-19 on HRU among patients with LC-FAOD.'}, {'PMID': '39063396', 'Title': 'Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.', 'Abstract': 'During the COVID-19 pandemic, tele-mental health (TMH) was a viable approach for providing accessible mental and behavioral health (MBH) services. This study examines the sociodemographic disparities in TMH utilization and its effects on healthcare resource utilization (HCRU) and medical expenditures in Mississippi. Utilizing a cohort of 6787 insured adult patients at the University of Mississippi Medical Center and its affiliated sites between January 2020 and June 2023, including 3065 who accessed TMH services, we observed sociodemographic disparities between TMH and non-TMH cohorts. The TMH cohort was more likely to be younger, female, White/Caucasian, using payment methods other than Medicare, Medicaid, or commercial insurers, residing in rural areas, and with higher household income compared to the non-TMH cohort. Adjusting for sociodemographic factors, TMH utilization was associated with a 190% increase in MBH-related outpatient visits, a 17% increase in MBH-related medical expenditures, and a 12% decrease in all-cause medical expenditures (all <i>p</i> < 0.001). Among rural residents, TMH utilization was associated with a 205% increase in MBH-related outpatient visits and a 19% decrease in all-cause medical expenditures (both <i>p</i> < 0.001). This study underscores the importance of addressing sociodemographic disparities in TMH services to promote equitable healthcare access while reducing overall medical expenditures.'}, {'PMID': '39051414', 'Title': 'Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.', 'Abstract': '<b>Background:</b> This study investigated the impact of COVID-19 on patients with sickle cell crisis (SCC) using National Inpatient Sample (NIS) data for the year 2020. <b>Methods:</b> A retrospective cohort analysis was conducted utilizing International Classification of Diseases (ICD-10) codes to identify adults who were admitted with a principal diagnosis of sickle cell crisis. The primary outcomes examined were inpatient mortality, while the secondary outcomes assessed included morbidity, hospital length of stay, and resource utilization. Analyses were conducted with STATA. Multivariate logistic and linear regression analyses were used to adjust for confounding variables. <b>Results:</b> Of 66,415 adult patients with a primary SCC diagnosis, 875 were identified with a secondary diagnosis of COVID-19 infection. Unadjusted mortality rate was higher for SCC patients with COVID-19 (2.28%) compared to those without (0.33%), with an adjusted odds ratio (aOR) of 8.49 (<i>p</i> = 0.001). They also showed increased odds of developing acute respiratory failure (aOR = 2.37, <i>p</i> = 0.003) and acute kidney injury requiring dialysis (aOR = 8.66, <i>p</i> = 0.034). Additionally, these patients had longer hospital stays by an adjusted mean of 3.30 days (<i>p</i> < 0.001) and incurred higher hospitalization charges by an adjusted mean of USD 35,578 (<i>p</i> = 0.005). <b>Conclusions:</b> The SCC patients with COVID-19 presented higher mortality rates, increased morbidity indicators, longer hospital stays, and substantial economic burdens.'}, {'PMID': '38966443', 'Title': 'Epidemiology of Pediatric Respiratory Tract Infections During the COVID-19 Era: A Retrospective Multicentric Study of Hospitalized Children in Lebanon Between October 2018 and March 2021.', 'Abstract': 'Background The identification of SARS-CoV-2 in December 2019 and its subsequent designation as the causative agent of COVID-19 marked the beginning of an unprecedented global health crisis. As the virus spread rapidly across continents, its impact on various demographic groups, including children, became a subject of intense research. While children were initially thought to be less susceptible to severe COVID-19 illness compared to adults, concerns emerged regarding their vulnerability to other respiratory infections amidst the pandemic. Understanding the epidemiological trends of pediatric respiratory tract infections (RTIs) during the COVID-19 era is crucial for informing public health strategies and clinical management protocols. This study aimed to compare the prevalence and characteristics of pediatric RTIs before and during the COVID-19 pandemic in Lebanon. Methodology A retrospective, observational study was conducted by reviewing medical records of children admitted to three tertiary care hospitals in Lebanon: Sheikh Ragheb Harb University Hospital, Al Sahel General University Hospital, and Rafik Al-Hariri University Hospital. Data were collected from October 2018 to March 2021, encompassing both the pre-COVID-19 and COVID-19 eras. A standardized data collection sheet was utilized to gather information on demographic characteristics, clinical presentations, duration of hospitalization, and antibiotic usage. Results Our analysis revealed significant shifts in the epidemiology of pediatric RTIs between the pre-COVID-19 and COVID-19 eras. There was a marked decline in the proportion of school-age children hospitalized with RTIs during the pandemic period. However, the overall percentage of Lebanese hospitalized children across different age groups increased significantly during the COVID-19 era. Furthermore, the prevalence of specific RTIs, such as pharyngitis, increased from 1.1% in the pre-COVID-19 to 5.5% during the COVID-19 period (p = 0.016), and the prevalence of bronchiolitis increased from 26.7% to 50.9% (p < 0.001) during the pre-COVID-19 and COVID-19 periods, respectively. This notable rise during the pandemic suggested potential changes in circulating pathogens or diagnostic practices. Importantly, the median length of hospital stays for pediatric RTIs decreased during the COVID-19 era compared to the pre-pandemic period, indicating possible improvements in clinical management or healthcare resource utilization. Analysis of antibiotic usage revealed ceftriaxone as the most frequently prescribed antibiotic in both periods, highlighting its continued relevance in the management of pediatric RTIs. Conclusions This study highlights significant epidemiological shifts in pediatric RTIs during the COVID-19 era in Lebanon. These findings underscore the importance of ongoing surveillance and research to adapt public health interventions and clinical practices to evolving infectious disease dynamics. Further investigation is warranted to elucidate the underlying factors driving these changes and optimize strategies for the prevention and management of pediatric RTIs in the context of the ongoing pandemic.'}, {'PMID': '38885115', 'Title': 'Initiating immunoglobulin replacement therapy helps reduce severe infections and shifts healthcare resource utilization to outpatient services among US patients with inborn errors of immunity.', 'Abstract': 'Patients with inborn errors of immunity (IEI) are predisposed to severe recurrent/chronic infections, and often require hospitalization, resulting in substantial burden to patients/healthcare systems. While immunoglobulin replacement therapies (IgRTs) are the standard first-line treatment for most forms of IEI, limited real-world data exist regarding clinical characteristics and treatment costs for patients with IEI initiating such treatment. This retrospective analysis examined infection and treatment characteristics in US patients with IEI initiating IgRT with immune globulin infusion (human), 10% (IG10%). Healthcare resource utilization (HCRU) and associated costs before and after treatment initiation were compared. Additionally, the impact of COVID-19 on infection diagnoses was evaluated.'}, {'PMID': '38779335', 'Title': 'Impact of Pre-existing Type 2 Diabetes Mellitus and Cardiovascular Disease on Healthcare Resource Utilization and Costs in Patients With COVID-19.', 'Abstract': '<b>Background:</b> The economic burden associated with type 2 diabetes mellitus (T2DM) and concurrent cardiovascular disease (CVD) among patients with COVID-19 is unclear. <b>Objective:</b> We compared healthcare resource utilization (HCRU) and costs in patients with COVID-19 and T2DM and CVD (T2DM+CVD), T2DM only, or neither T2DM nor CVD (T2DM/CVD). <b>Methods:</b> A retrospective observational study in COVID-19 patients using data from the Healthcare Integrated Research Database (HIRD®) was conducted. Patients with COVID-19 were identified between March 1, 2020, and May 31, 2021, and followed from first diagnosis or positive lab test to the end of health plan enrollment, end of study period, or death. Patients were assigned one of 3 cohorts: pre-existing T2DM+CVD, T2DM only, or neither T2DM/CVD. Propensity score matching and multivariable analyses were performed to control for differences in baseline characteristics. Study outcomes included all-cause and COVID-19-related HCRU and costs. <b>Results:</b> In all, 321\\u202f232 COVID-19 patients were identified (21\\u202f651 with T2DM+CVD, 28\\u202f184 with T2DM only, and 271\\u202f397 with neither T2DM/CVD). After matching, 6967 patients were in each group. Before matching, 46.0% of patients in the T2DM+CVD cohort were hospitalized for any cause, compared with 18.0% in the T2DM-only cohort and 6.3% in the neither T2DM/CVD cohort; the corresponding values after matching were 34.2%, 26.0%, and 21.2%. The proportion of patients with emergency department visits, telehealth visits, or use of skilled nursing facilities was higher in patients with COVID-19 and T2DM+CVD compared with the other cohorts. Average all-cause costs during follow-up were <math xmlns=\"http://www.w3.org/1998/Math/MathML\"><mn>12</mn><mrow><mo>\\u202f</mo></mrow><mn>324</mn><mo>,</mo></math>7882, and $7277 per-patient-per-month after matching for patients with T2DM+CVD, T2DM-only, and neither T2DM/CVD, respectively. COVID-19-related costs contributed to 78%, 75%, and 64% of the overall costs, respectively. The multivariable model showed that per-patient-per-month all-cause costs for T2DM+CVD and T2DM-only were 54% and 21% higher, respectively, than those with neither T2DM/CVD after adjusting for residual confounding. <b>Conclusion:</b> HCRU and costs in patients were incrementally higher with COVID-19 and pre-existing T2DM+CVD compared with those with T2DM-only and neither T2DM/CVD, even after accounting for baseline differences between groups, confirming that pre-existing T2DM+CVD is associated with increased HCRU and costs in COVID-19 patients, highlighting the importance of proactive management.'}, {'PMID': '38686393', 'Title': 'Real-world total cost of care by line of therapy in relapsed/refractory diffuse large B-cell lymphoma.', 'Abstract': 'There are multiple recently approved treatments and a lack of clear standard-of-care therapies for relapsed/refractory (R/R) diffuse large B-cell lymphoma (DLBCL). While total cost of care (TCC) by the number of lines of therapy (LoTs) has been evaluated, more recent cost estimates using real-world data are needed. This analysis assessed real-world TCC of R/R DLBCL therapies by LoT using the IQVIA PharMetrics Plus database (1 January 2015-31 December 2021), in US patients aged ≥18\\u202fyears treated with rituximab plus cyclophosphamide, doxorubicin, vincristine, and prednisone (R-CHOP) or an R-CHOP-like regimen as first-line therapy.'}, {'PMID': '38644506', 'Title': 'Impact of COVID-19 pandemic on depression incidence and healthcare service use among patients with depression: an interrupted time-series analysis from a 9-year population-based study.', 'Abstract': 'Most studies on the impact of the COVID-19 pandemic on depression burden focused on the earlier pandemic phase specific to lockdowns, but the longer-term impact of the pandemic is less well-studied. In this population-based cohort study, we examined the short-term and long-term impacts of COVID-19 on depression incidence and healthcare service use among patients with depression.'}, {'PMID': '38534198', 'Title': 'Burden of disease and treatment patterns in patients with vitiligo: findings from a national longitudinal retrospective study in the UK.', 'Abstract': 'UK studies examining vitiligo burden and vitiligo-related healthcare resource utilization (HCRU) are lacking.'}, {'PMID': '38435542', 'Title': 'Impact Of body Mass Index on Cardiopulmonary Outcomes of COVID-19 Hospitalizations Complicated by Severe Sepsis.', 'Abstract': 'Body Mass Index (BMI) has a significant impact on Coronavirus disease (COVID-19) patient outcomes; however, major adverse cardiac and cerebrovascular outcomes in patients with severe sepsis have been poorly understood. Our study aims to explore and provide insight into its association.'}]}, 'id': 'call_JQqUPfw2NKpTgmP4Eaj8xDRt', 'type': 'tool_call'}], usage_metadata={'input_tokens': 3703, 'output_tokens': 2929, 'total_tokens': 6632})]\n",
       "```"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "20f005db12534a04b951801c098e1c8b",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Batches:   0%|          | 0/1 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "1d7003157ab64a4bb296a7ed700919d5",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Batches:   0%|          | 0/1 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "c0c4a39be3fd41399edb01970120e11d",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Batches:   0%|          | 0/1 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "b2268c2818274237846582d1dd558683",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Batches:   0%|          | 0/1 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "2300759112d74195827488d3db0bab3d",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Batches:   0%|          | 0/1 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "50d163b046b842ba9268d48956129ae8",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Batches:   0%|          | 0/1 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "9752dfe417cf478b853c4cf07efbdd66",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Batches:   0%|          | 0/1 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "f2c27750871a43729fe2f0826e6907a1",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Batches:   0%|          | 0/1 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "f944474715414bfeb7d33cdf1cd53296",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Batches:   0%|          | 0/1 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "e712b9a071ce4a17a66e722c33c335cf",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Batches:   0%|          | 0/1 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "7ffa85b68586468592287ea15c57eebb",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Batches:   0%|          | 0/1 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Receiving update from node: 'action'\n"
     ]
    },
    {
     "data": {
      "text/markdown": [
       "```markdown\n",
       "[ToolMessage(content='[{\"PMID\": \"39291999\", \"Decision\": \"Exclude\", \"Reason\": \"Similarity score 0.31 < threshold 0.4\"}, {\"PMID\": \"39063396\", \"Decision\": \"Include\", \"Reason\": \"Similarity score 0.53 >= threshold 0.4\"}, {\"PMID\": \"39051414\", \"Decision\": \"Include\", \"Reason\": \"Similarity score 0.45 >= threshold 0.4\"}, {\"PMID\": \"38966443\", \"Decision\": \"Include\", \"Reason\": \"Similarity score 0.50 >= threshold 0.4\"}, {\"PMID\": \"38885115\", \"Decision\": \"Include\", \"Reason\": \"Similarity score 0.46 >= threshold 0.4\"}, {\"PMID\": \"38779335\", \"Decision\": \"Include\", \"Reason\": \"Similarity score 0.60 >= threshold 0.4\"}, {\"PMID\": \"38686393\", \"Decision\": \"Exclude\", \"Reason\": \"Similarity score 0.24 < threshold 0.4\"}, {\"PMID\": \"38644506\", \"Decision\": \"Include\", \"Reason\": \"Similarity score 0.57 >= threshold 0.4\"}, {\"PMID\": \"38534198\", \"Decision\": \"Exclude\", \"Reason\": \"Similarity score 0.25 < threshold 0.4\"}, {\"PMID\": \"38435542\", \"Decision\": \"Exclude\", \"Reason\": \"Similarity score 0.38 < threshold 0.4\"}]', name='Semantic_Abstract_Screening_Tool', tool_call_id='call_JQqUPfw2NKpTgmP4Eaj8xDRt')]\n",
       "```"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\n",
      "2024-10-03 14:30:12 - HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n",
      "Receiving update from node: 'agent'\n"
     ]
    },
    {
     "data": {
      "text/markdown": [
       "```markdown\n",
       "[AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_fR7rclKNBZduynKOpO5AkIBH', 'function': {'arguments': '{\"pmids\":[\"39063396\",\"39051414\",\"38966443\",\"38885115\",\"38779335\",\"38644506\"],\"query\":\"data source information used in each paper (especially medical records)\"}', 'name': 'Fetch_Extract_Tool'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 56, 'prompt_tokens': 6967, 'total_tokens': 7023, 'prompt_tokens_details': {'cached_tokens': 0}, 'completion_tokens_details': {'reasoning_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_fd18a09f1e', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-3936e9ef-bc6d-4f1c-acdb-5915b670941a-0', tool_calls=[{'name': 'Fetch_Extract_Tool', 'args': {'pmids': ['39063396', '39051414', '38966443', '38885115', '38779335', '38644506'], 'query': 'data source information used in each paper (especially medical records)'}, 'id': 'call_fR7rclKNBZduynKOpO5AkIBH', 'type': 'tool_call'}], usage_metadata={'input_tokens': 6967, 'output_tokens': 56, 'total_tokens': 7023})]\n",
       "```"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\n",
      "2024-10-03 14:30:12 - Use pytorch device_name: cpu\n",
      "2024-10-03 14:30:12 - Load pretrained SentenceTransformer: sentence-transformers/all-MiniLM-L6-v2\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "c:\\Users\\YLiang\\.conda\\envs\\llmops-course\\Lib\\site-packages\\transformers\\tokenization_utils_base.py:1617: FutureWarning: `clean_up_tokenization_spaces` was not set. It will be set to `True` by default. This behavior will be deprecated in transformers v4.45, and will be then set to `False` by default. For more details check this issue: https://github.com/huggingface/transformers/issues/31884\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2024-10-03 14:30:23 - HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n",
      "2024-10-03 14:30:27 - HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n",
      "2024-10-03 14:30:29 - HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n",
      "2024-10-03 14:30:30 - HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n",
      "2024-10-03 14:30:33 - HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n",
      "2024-10-03 14:30:37 - HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n",
      "Receiving update from node: 'action'\n"
     ]
    },
    {
     "data": {
      "text/markdown": [
       "```markdown\n",
       "[ToolMessage(content='{\\'39063396\\': {\\'PMID\\': \\'39063396\\', \\'Title\\': \\'Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.\\', \\'Generated Answer\\': \"The data for the study was extracted from the UMMC enterprise data warehouse. The medical records used in the research were obtained from this source to examine sociodemographic characteristics, healthcare resource utilization (HCRU), and medical expenditures between telemedicine (TMH) and non-TMH cohorts. The sociodemographic characteristics considered in the study included age, sex, race, primary insurance, rurality, and household income. It\\'s important to note that due to the presence of protected health information (PHI) and in accordance with Institutional Review Board (IRB) regulations, the dataset cannot be made publicly available.\", \\'Sources\\': [Document(metadata={\\'PMID\\': \\'39063396\\', \\'Title\\': \\'Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.\\', \\'uuid\\': \\'7174e027-b200-4d9d-9072-45a54d94fd2b\\', \\'_id\\': \\'7d6837bca7324f288effac83838b9ea0\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'Institutional Review Board Statement\\\\n\\\\nThis study was approved by the Institutional Review Board (IRB) of the University of Mississippi Medical Center (ID: UMMC-IRB-2022-458; date of approval: 12 April 2023).\\\\n\\\\nInformed Consent Statement\\\\n\\\\nPatient consent was waived following Federal Regulations set forth by 45 CFR 46.116(f).\\\\n\\\\nData Availability Statement\\\\n\\\\nDue to the presence of protected health information (PHI) and in accordance with IRB regulations, the dataset cannot be made publicly available.\\\\n\\\\nConflicts of Interest\\\\n\\\\nLSL was an employee of ConcertAI during the conduct of this study. Other authors have no conflicts of interest to declare.\\\\n\\\\nReferences\\\\n\\\\nAverage mental and behavioral health-related and all-cause HCRU and medical expenditure PPPM.\\\\n\\\\nAverage mental and behavioral health-related and all-cause HCRU and medical expenditure PPPM of subjects residing in rural areas.\\\\n\\\\nSociodemographic characteristics of all study subjects and using TMH.\\'), Document(metadata={\\'PMID\\': \\'39063396\\', \\'Title\\': \\'Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.\\', \\'uuid\\': \\'8a196627-3ff3-4936-bca0-230f89d8aacb\\', \\'_id\\': \\'cd1936164b7743eebf6afef0fe19ce39\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'Medical records were extracted from the UMMC enterprise data warehouse to examine sociodemographic characteristics, HCRU, and medical expenditures between TMH and non-TMH cohorts. Sociodemographic characteristics considered in this study include age, sex, race, primary insurance, rurality, and household income. Age was categorized into four groups: 18 to 34 years, 35 to 49 years, 50 to 64 years, and 65 years or older. Race was categorized into three groups: White/Caucasian, Black/African American, and other. The other race group included subjects identifying as American Indian, Alaska Native, Native Hawaiian, other Pacific Islander, Mississippi Band Choctaw Indian, Asian, Hispanic, Multiracial, and others. Subjects of unknown race or those who refused to provide this information were considered missing. Primary insurance was defined as the insurance most frequently used for mental and behavioral health visits during the study period and was categorized into four groups: commercial\\'), Document(metadata={\\'PMID\\': \\'39063396\\', \\'Title\\': \\'Tele-Mental Health Service: Unveiling the Disparity and Impact on Healthcare Access and Expenditures during the COVID-19 Pandemic in Mississippi.\\', \\'uuid\\': \\'69265147-6605-4899-813a-cefb9538b690\\', \\'_id\\': \\'27d8a5a5377b410f9a243598172a248a\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'were included, future studies should consider multiple academic centers or healthcare entities to validate the robustness of findings across different geographic regions and patient populations. Additionally, there is potential for missing data since patients may seek care at multiple institutions. This limitation was mitigated by limiting the study sample to patients who had evidence of regular care visits at UMMC and had evidence of insurance coverage for at least one visit. However, as the study sample consisted of insured patients who regularly seek healthcare from UMMC, it may not represent the entire population of Mississippi, such as those without any healthcare access, thereby limiting generalizability to uninsured populations. Future research should identify and address barriers faced by uninsured populations to provide a more comprehensive understanding of TMH utilization and its impact on HCRU and medical expenditures.\\')]}, \\'39051414\\': {\\'PMID\\': \\'39051414\\', \\'Title\\': \\'Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.\\', \\'Generated Answer\\': \\'The data source used in the study described is the 2020 National Inpatient Sample (NIS) dataset. This dataset covers hospitalizations in the United States from 1 January 2020 to 31 December 2020 and is derived from the State Inpatient Databases (SIDs). The NIS dataset is part of the Healthcare Cost and Utilization Project sponsored by the Agency for Healthcare Research and Quality (AHRQ). It is a de-identified, publicly available inpatient database that represents an estimated 98% of the U.S. population. The dataset employs a 20% stratified discharge sample that is weighted to ensure national representativeness. \\\\n\\\\nThe study did not involve direct access to individual medical records. Instead, it utilized aggregated and de-identified data from the NIS dataset, which does not require informed consent as it is publicly available and does not involve research with identifiable human subjects.\\', \\'Sources\\': [Document(metadata={\\'PMID\\': \\'39051414\\', \\'Title\\': \\'Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.\\', \\'uuid\\': \\'82940dc9-90af-4a8b-afb4-fec2795f43e1\\', \\'_id\\': \\'24d2b583f5e44d579a7ee6569d917be5\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'3. Materials and Methods\\\\n\\\\n\\\\n\\\\n3.1. Study Design and Database Description\\\\n\\\\nUtilizing the 2020 National Inpatient Sample (NIS) dataset, we conducted a retrospective cohort analysis of adult patients admitted with a primary diagnosis of sickle cell crisis in the United States. The NIS 2020 dataset specifically covers hospitalizations within the period from 1 January 2020 to 31 December 2020. It derives from the State Inpatient Databases (SIDs) that cover an estimated 98% of the U.S. population. As part of the Healthcare Cost and Utilization Project sponsored by Agency for Healthcare Research and Quality (AHRQ), the NIS is the most extensive, de-identified, publicly available inpatient database in the U.S. This database employs a 20% stratified discharge sample, which is then weighted relative to the total discharges to ensure national representativeness.\\\\n\\\\n\\\\n\\\\n3.2. Study Patients\\'), Document(metadata={\\'PMID\\': \\'39051414\\', \\'Title\\': \\'Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.\\', \\'uuid\\': \\'781f8646-7ab5-4ae3-8655-7d2755588e9f\\', \\'_id\\': \\'7d103fa49a5d426fa959c6caf7568078\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'Our study has some limitations. Because it was retrospective, we could not fully randomize exposure. However, by employing multivariate regression models that took into account various patient and hospital traits, as well as co-morbidities, we made an effort to reduce confounding. Still, even with these measures, there is a slight chance that residual confounding occurred. To identify patients with sickle cell crisis and COVID-19, we opted for ICD-10 codes rather than clinical measures. This might have resulted in diagnosis misclassification. Yet, the legitimacy of using ICD-10 codes for this purpose is backed by earlier studies that utilized HCUP data [\\'), Document(metadata={\\'PMID\\': \\'39051414\\', \\'Title\\': \\'Double Trouble: COVID-19 Infection Exacerbates Sickle Cell Crisis Outcomes in Hospitalized Patients-Insights from National Inpatient Sample 2020.\\', \\'uuid\\': \\'9807f9d5-936c-4dc5-b997-c1f185eede4a\\', \\'_id\\': \\'2f953983923c4fffbcf1f3f2c1bfbd83\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'Supplementary Materials\\\\n\\\\nThe following supporting information can be downloaded at:\\\\n\\\\nAuthor Contributions\\\\n\\\\nConceptualization, Z.H.B. and M.H.; methodology, Z.H.B.; formal analysis, Z.H.B.; investigation and analysis, Z.H.B.; writing—original draft preparation, Z.H.B., M.H., F.N., A.B.A., A.O., M.J.K., M.S.F., F.K. and A.-R.Z.; writing—review and editing, Z.H.B., M.H., F.N., A.B.A., A.O., M.J.K., M.S.F., F.K. and A.-R.Z.; visualization, Y.B. and C.L.B.; supervision, Y.B. and C.L.B. All authors have read and agreed to the published version of the manuscript.\\\\n\\\\nInstitutional Review Board Statement\\\\n\\\\nEthical review and approval were waived for this study as it does not involve research with human subjects and the dataset used is de-identified.\\\\n\\\\nInformed Consent Statement\\\\n\\\\nIt is a retrospective study using publicly available de-identified data and consent is not required.\\\\n\\\\nData Availability Statement\\')]}, \\'38966443\\': {\\'PMID\\': \\'38966443\\', \\'Title\\': \\'Epidemiology of Pediatric Respiratory Tract Infections During the COVID-19 Era: A Retrospective Multicentric Study of Hospitalized Children in Lebanon Between October 2018 and March 2021.\\', \\'Generated Answer\\': \\'The study mentioned in the provided context utilized medical records as the primary data source. The data collection process involved reviewing the medical records of children admitted to three major hospitals in Lebanon. The information extracted from these records was gathered according to a standardized questionnaire to collect data on demographic characteristics, clinical presentations, duration of hospitalization, and antibiotic usage among hospitalized children with respiratory tract infections.\\', \\'Sources\\': [Document(metadata={\\'PMID\\': \\'38966443\\', \\'Title\\': \\'Epidemiology of Pediatric Respiratory Tract Infections During the COVID-19 Era: A Retrospective Multicentric Study of Hospitalized Children in Lebanon Between October 2018 and March 2021.\\', \\'uuid\\': \\'fd8709b4-a96a-4736-9996-7877086006a5\\', \\'_id\\': \\'5f75387f879646e49fd39d9f69da92bb\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'Despite providing valuable insights, our study has several limitations. Data collection constraints, including missing variables such as bacterial cultures and viral panels, may have impacted the accuracy of our analyses. Additionally, the absence of information on co-infections limits our understanding of the full spectrum of respiratory pathogens circulating during the study periods.\\\\n\\\\n\\\\n\\\\nConclusions\\'), Document(metadata={\\'PMID\\': \\'38966443\\', \\'Title\\': \\'Epidemiology of Pediatric Respiratory Tract Infections During the COVID-19 Era: A Retrospective Multicentric Study of Hospitalized Children in Lebanon Between October 2018 and March 2021.\\', \\'uuid\\': \\'ab77edb9-c670-47df-b1f4-cf75ceffbc54\\', \\'_id\\': \\'853f756a0c6c486d8ab3e4906027d396\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'Materials and methods\\\\n\\\\nEthical considerations\\\\n\\\\nOur study was conducted with adherence to ethical standards, and all necessary approvals were obtained before data collection. Institutional Review Board approval was obtained from the Sheikh Ragheb Harb University Hospital (authorization number: 3279/1/22).\\\\n\\\\nStudy design\\\\n\\\\nThis study employed a retrospective observational design to investigate the epidemiology of pediatric RTIs in hospitalized children. Data collection was conducted through the review of medical records of children aged between one month and 13 years admitted to three major hospitals in Lebanon. The participating hospitals included Sheikh Ragheb Harb University Hospital located in Toul, Nabatieh Governorate, Al Sahel Hospital in Beirut, and Rafik Hariri University Hospital in Beirut.\\'), Document(metadata={\\'PMID\\': \\'38966443\\', \\'Title\\': \\'Epidemiology of Pediatric Respiratory Tract Infections During the COVID-19 Era: A Retrospective Multicentric Study of Hospitalized Children in Lebanon Between October 2018 and March 2021.\\', \\'uuid\\': \\'3da29fc9-4ab5-4965-a1ff-380fa33de2e3\\', \\'_id\\': \\'0b55a36f2330462db6992886670a189f\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'The study period spanned from October 2018 to March 2021, allowing for a comparison between the pre-COVID-19 era (October 2018 to February 2020) and the COVID-19 era (February 2020 to March 2021).\\\\n\\\\nData collection involved a systematic review of medical files and the extraction of relevant information according to a standardized questionnaire. This approach facilitated the collection of comprehensive data on demographic characteristics, clinical presentations, duration of hospitalization, and antibiotic usage among hospitalized children with RTIs.\\\\n\\\\nStudy population\\\\n\\\\nWe\\\\xa0recruited 500 cases of children with RTI between the period of 2018 and 2021.\\\\n\\\\nInclusion Criteria\\\\n\\\\nWe included children between one month and 13 years old admitted with upper or lower RTI with symptoms such as fever, cough, and dyspnea.\\\\n\\\\nExclusion Criteria\\')]}, \\'38885115\\': {\\'PMID\\': \\'38885115\\', \\'Title\\': \\'Initiating immunoglobulin replacement therapy helps reduce severe infections and shifts healthcare resource utilization to outpatient services among US patients with inborn errors of immunity.\\', \\'Generated Answer\\': \"I don\\'t know.\", \\'Sources\\': [Document(metadata={\\'PMID\\': \\'38885115\\', \\'Title\\': \\'Initiating immunoglobulin replacement therapy helps reduce severe infections and shifts healthcare resource utilization to outpatient services among US patients with inborn errors of immunity.\\', \\'uuid\\': \\'0c1f8c0c-3d99-4db3-b4b2-7afed82ec04a\\', \\'_id\\': \\'5b3f7d953eff4ab5a3875ff1564eeef3\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'cannot fetch\\')]}, \\'38779335\\': {\\'PMID\\': \\'38779335\\', \\'Title\\': \\'Impact of Pre-existing Type 2 Diabetes Mellitus and Cardiovascular Disease on Healthcare Resource Utilization and Costs in Patients With COVID-19.\\', \\'Generated Answer\\': \\'The data used in the study were patient medical claims related to COVID-19. The study was conducted in compliance with the Health Insurance Portability and Accountability Act (HIPAA) and Privacy Rule 45 CFR 164.514(e). The data were used in accordance with these regulations, and the study was exempt from Institutional Review Board review. The study mentioned limitations related to potential underestimation or overestimation of costs due to selection bias, as patients who did not seek medical care or were not tested for COVID-19 may not have been included in the data.\\', \\'Sources\\': [Document(metadata={\\'PMID\\': \\'38779335\\', \\'Title\\': \\'Impact of Pre-existing Type 2 Diabetes Mellitus and Cardiovascular Disease on Healthcare Resource Utilization and Costs in Patients With COVID-19.\\', \\'uuid\\': \\'0b12d97c-19d6-42be-b09c-9335d3de025b\\', \\'_id\\': \\'0115abbac6614701bc002b7012e138d9\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'The data were used in full compliance with the relevant provisions of the Health Insurance Portability and Accountability Act. The study was conducted under the research provisions of Privacy Rule 45 CFR 164.514(e) and was exempt from Institutional Review Board review.\\\\n\\\\n\\\\n\\\\nPatient Identification\\\\n\\\\nPatients with COVID-19, as defined by at least 1 COVID-19 medical claim (\\'), Document(metadata={\\'PMID\\': \\'38779335\\', \\'Title\\': \\'Impact of Pre-existing Type 2 Diabetes Mellitus and Cardiovascular Disease on Healthcare Resource Utilization and Costs in Patients With COVID-19.\\', \\'uuid\\': \\'a42b6e59-5f9e-4c94-9e4c-3ca915fe2e46\\', \\'_id\\': \\'1ea5fc2e7a694d25a191cd2ad179b198\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'Supplementary Material\\\\n\\\\nOnline Supplementary Material\\\\n\\\\n\\\\n\\\\nAcknowledgments\\\\n\\\\nLeena Patel, PhD, Chrysi Petraki, PhD, and Daria Renshaw from IQVIA provided medical writing and editorial support, which was funded by Carelon Research.\\'), Document(metadata={\\'PMID\\': \\'38779335\\', \\'Title\\': \\'Impact of Pre-existing Type 2 Diabetes Mellitus and Cardiovascular Disease on Healthcare Resource Utilization and Costs in Patients With COVID-19.\\', \\'uuid\\': \\'ee1f65dc-ba23-4d15-a78d-dc1489be0897\\', \\'_id\\': \\'826dec8407ff49bab845948970d8197a\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'Limitations\\\\n\\\\nThis study has a few limitations that require consideration. There is a possibility of underestimation or overestimation of costs, depending on how they were being reported, due to selection bias, as patients who did not seek medical care (including those who were not tested or did not report COVID-19 infection, or those with asymptomatic infections) would not have available data and therefore would not have been included.\\')]}, \\'38644506\\': {\\'PMID\\': \\'38644506\\', \\'Title\\': \\'Impact of COVID-19 pandemic on depression incidence and healthcare service use among patients with depression: an interrupted time-series analysis from a 9-year population-based study.\\', \\'Generated Answer\\': \\'The data source used in the study mentioned is the Clinical Data Analysis and Reporting System (CDARS), which is a territory-wide routine electronic medical record (EMR) developed by the Hospital Authority in Hong Kong. CDARS contains anonymized patient-level data, including demographics, deaths, attendances, and diagnoses coded based on the International Classification of Diseases, 9th Revision, Clinical Modification (ICD-9-CM). This system has been used since 1993 across outpatient, inpatient, and emergency settings for research and auditing purposes in the public sector. The quality and accuracy of CDARS have been demonstrated in population-based studies on COVID-19.\\', \\'Sources\\': [Document(metadata={\\'PMID\\': \\'38644506\\', \\'Title\\': \\'Impact of COVID-19 pandemic on depression incidence and healthcare service use among patients with depression: an interrupted time-series analysis from a 9-year population-based study.\\', \\'uuid\\': \\'3c2e17a7-2d1b-4743-bb63-dc384edbcd53\\', \\'_id\\': \\'739fb264248f4163aa0ec5cce1944110\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'Availability of data and materials\\\\n\\\\nWe are unable to directly share the data used in this study since the data custodian, the Hong Kong Hospital Authority who manages the Clinical Data Analysis and Reporting System (CDARS), has not given permission. However, CDARS data can be accessed via the Hospital Authority Data Sharing Portal for research purpose. The relevant information can be found online (\\\\n\\\\nDeclarations\\\\n\\\\nEthics approval and consent to participate\\\\n\\\\nThis study received ethics approval from the Institutional Review Board of The University of Hong Kong/Hospital Authority Hong Kong Western Cluster (UW 20-218). Informed consent has been waived as the study utilized de-identified data.\\\\n\\\\nConsent for publication\\\\n\\\\nNot applicable.\\\\n\\\\nCompeting interests\\'), Document(metadata={\\'PMID\\': \\'38644506\\', \\'Title\\': \\'Impact of COVID-19 pandemic on depression incidence and healthcare service use among patients with depression: an interrupted time-series analysis from a 9-year population-based study.\\', \\'uuid\\': \\'6e69cd61-ae72-47d0-b96e-faf5509c6428\\', \\'_id\\': \\'a23228f9e72f4326bf782f8b37970e57\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'Methods\\\\n\\\\n\\\\n\\\\nData source\\\\n\\\\nWe analyzed the Clinical Data Analysis and Reporting System (CDARS), the territory-wide routine electronic medical record (EMR) developed by the Hospital Authority, which manages all public healthcare services in Hong Kong and provides publicly funded healthcare services to all eligible residents (>\\\\u20097.6 million). CDARS covers real-time anonymized patient-level data, including demographics, deaths, attendances, and all-cause diagnoses coded based on the International Classification of Diseases, 9th Revision, Clinical Modification (ICD-9-CM), since 1993 across outpatient, inpatient, and emergency settings for research and auditing purposes in the public sector. The quality and accuracy of CDARS have been demonstrated in population-based studies on COVID-19 [\\\\n\\\\n\\\\n\\\\nStudy design and participants\\'), Document(metadata={\\'PMID\\': \\'38644506\\', \\'Title\\': \\'Impact of COVID-19 pandemic on depression incidence and healthcare service use among patients with depression: an interrupted time-series analysis from a 9-year population-based study.\\', \\'uuid\\': \\'e9c2bafd-9ab8-4afc-893c-c3e3f8450988\\', \\'_id\\': \\'a960c7d3c7d1403eb4ee947ea2a36081\\', \\'_collection_name\\': \\'pmd_data\\'}, page_content=\\'Authors’ Twitter handles\\\\n\\\\nVivien Kin Yi Chan: @vivienkinyichan\\\\n\\\\nMartin Knapp: @knappem\\\\n\\\\nHao Luo: @HaoLuo429\\\\n\\\\nIan Chi Kei Wong: @Ian_HKU\\\\n\\\\nXue Li: @snowly12191\\\\n\\\\nHKU Pharmacy: @HkuPharm\\\\n\\\\nFunding\\\\n\\\\nThe study was jointly supported by the Collaborative Research Fund (ACESO, C7154-20GF), the Research Impact Fund (SCAN-2030, R7007-22) granted by the Research Grant Council, University Grants Committee, and\\\\xa0the Health and Medical Research Fund (COVID19F04; COVID19F11) granted by the Health Bureau, The Government of the Hong Kong Special Administrative Region, and the Laboratory of Data Discovery for Health (D\\\\n\\\\nAvailability of data and materials\\')]}}', name='Fetch_Extract_Tool', tool_call_id='call_fR7rclKNBZduynKOpO5AkIBH')]\n",
       "```"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\n",
      "2024-10-03 14:30:44 - HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n",
      "Receiving update from node: 'agent'\n"
     ]
    },
    {
     "data": {
      "text/markdown": [
       "```markdown\n",
       "[AIMessage(content=\"Here's a summary of the entire process and findings for each paper:\\n\\n1. **Search and Retrieval**: I used the PubMed search tool to find papers related to the impact of COVID-19 on healthcare resource utilization. The search returned several papers, and I retrieved their abstracts.\\n\\n2. **Screening**: I screened the abstracts based on the criteria of comparing healthcare resource utilization before and after the COVID pandemic. The screening tool evaluated the abstracts for semantic similarity to the criteria, resulting in the inclusion of six papers for further analysis.\\n\\n3. **Full-Text Retrieval and Information Extraction**: I fetched the full-text articles for the included papers and extracted information about the data sources used in each study, focusing on medical records.\\n\\n   - **PMID 39063396**: The study used medical records from the University of Mississippi Medical Center's enterprise data warehouse to examine healthcare resource utilization and expenditures during the COVID-19 pandemic.\\n   \\n   - **PMID 39051414**: This study utilized the 2020 National Inpatient Sample (NIS) dataset, a de-identified, publicly available inpatient database in the U.S., to analyze the impact of COVID-19 on sickle cell crisis outcomes.\\n   \\n   - **PMID 38966443**: The study reviewed medical records from three hospitals in Lebanon to compare pediatric respiratory tract infections before and during the COVID-19 pandemic.\\n   \\n   - **PMID 38885115**: The data source information was not available for this study.\\n   \\n   - **PMID 38779335**: The study used patient medical claims data related to COVID-19, compliant with HIPAA regulations, to assess healthcare resource utilization and costs.\\n   \\n   - **PMID 38644506**: The study analyzed data from the Clinical Data Analysis and Reporting System (CDARS) in Hong Kong, which contains anonymized patient-level data from public healthcare services.\\n\\n4. **Summary**: The process involved searching for relevant papers, screening them based on specific criteria, and extracting detailed data source information from the full-text articles. The studies utilized various data sources, including medical records, national inpatient samples, and electronic medical records, to analyze the impact of COVID-19 on healthcare resource utilization.\", additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 455, 'prompt_tokens': 12075, 'total_tokens': 12530, 'prompt_tokens_details': {'cached_tokens': 6912}, 'completion_tokens_details': {'reasoning_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_fd18a09f1e', 'finish_reason': 'stop', 'logprobs': None}, id='run-716ed46c-b9ee-40a1-83a4-00c10b76c534-0', usage_metadata={'input_tokens': 12075, 'output_tokens': 455, 'total_tokens': 12530})]\n",
       "```"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\n",
      "Final message content from the last chunk:\n"
     ]
    },
    {
     "data": {
      "text/markdown": [
       "```markdown\n",
       "Here's a summary of the entire process and findings for each paper:\n",
       "\n",
       "1. **Search and Retrieval**: I used the PubMed search tool to find papers related to the impact of COVID-19 on healthcare resource utilization. The search returned several papers, and I retrieved their abstracts.\n",
       "\n",
       "2. **Screening**: I screened the abstracts based on the criteria of comparing healthcare resource utilization before and after the COVID pandemic. The screening tool evaluated the abstracts for semantic similarity to the criteria, resulting in the inclusion of six papers for further analysis.\n",
       "\n",
       "3. **Full-Text Retrieval and Information Extraction**: I fetched the full-text articles for the included papers and extracted information about the data sources used in each study, focusing on medical records.\n",
       "\n",
       "   - **PMID 39063396**: The study used medical records from the University of Mississippi Medical Center's enterprise data warehouse to examine healthcare resource utilization and expenditures during the COVID-19 pandemic.\n",
       "   \n",
       "   - **PMID 39051414**: This study utilized the 2020 National Inpatient Sample (NIS) dataset, a de-identified, publicly available inpatient database in the U.S., to analyze the impact of COVID-19 on sickle cell crisis outcomes.\n",
       "   \n",
       "   - **PMID 38966443**: The study reviewed medical records from three hospitals in Lebanon to compare pediatric respiratory tract infections before and during the COVID-19 pandemic.\n",
       "   \n",
       "   - **PMID 38885115**: The data source information was not available for this study.\n",
       "   \n",
       "   - **PMID 38779335**: The study used patient medical claims data related to COVID-19, compliant with HIPAA regulations, to assess healthcare resource utilization and costs.\n",
       "   \n",
       "   - **PMID 38644506**: The study analyzed data from the Clinical Data Analysis and Reporting System (CDARS) in Hong Kong, which contains anonymized patient-level data from public healthcare services.\n",
       "\n",
       "4. **Summary**: The process involved searching for relevant papers, screening them based on specific criteria, and extracting detailed data source information from the full-text articles. The studies utilized various data sources, including medical records, national inpatient samples, and electronic medical records, to analyze the impact of COVID-19 on healthcare resource utilization.\n",
       "```"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from langchain_core.messages import SystemMessage, HumanMessage\n",
    "from langchain.tools import StructuredTool\n",
    "from langchain.agents import initialize_agent, Tool, AgentType\n",
    "from langchain_openai import ChatOpenAI\n",
    "from langgraph.graph.message import add_messages\n",
    "from langgraph.graph import StateGraph, END\n",
    "from pydantic import BaseModel\n",
    "from typing import List, TypedDict, Annotated\n",
    "import xml.etree.ElementTree as ET\n",
    "import uuid\n",
    "import re\n",
    "from langgraph.prebuilt import ToolNode\n",
    "from Bio import Entrez\n",
    "from langchain_qdrant import QdrantVectorStore\n",
    "from qdrant_client import QdrantClient\n",
    "from qdrant_client.http.models import Distance, VectorParams\n",
    "from qdrant_client.http.models import Filter, FieldCondition, MatchValue\n",
    "from langchain_huggingface import HuggingFaceEmbeddings\n",
    "from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
    "from langchain.chains import (\n",
    "    ConversationalRetrievalChain,\n",
    ")\n",
    "from langchain.docstore.document import Document\n",
    "from langchain.memory import ChatMessageHistory, ConversationBufferMemory\n",
    "\n",
    "# 1. Define PubMed Search Tool\n",
    "class PubMedSearchInput(BaseModel):\n",
    "    query: str\n",
    "\n",
    "# PubMed search tool using Entrez (now with structured inputs)\n",
    "def pubmed_search(query: str, max_results: int = 10):\n",
    "    \"\"\"Search PubMed using Entrez API and return abstracts.\"\"\"\n",
    "    handle = Entrez.esearch(db=\"pubmed\", term=query, retmax=max_results)\n",
    "    record = Entrez.read(handle)\n",
    "    handle.close()\n",
    "    pmids = record[\"IdList\"]\n",
    "    \n",
    "    # Fetch abstracts\n",
    "    handle = Entrez.efetch(db=\"pubmed\", id=\",\".join(pmids), retmode=\"xml\")\n",
    "    records = Entrez.read(handle)\n",
    "    handle.close()\n",
    "\n",
    "    abstracts = []\n",
    "    for record in records['PubmedArticle']:\n",
    "        try:\n",
    "            title = record['MedlineCitation']['Article']['ArticleTitle']\n",
    "            abstract = record['MedlineCitation']['Article']['Abstract']['AbstractText'][0]\n",
    "            pmid = record['MedlineCitation']['PMID']\n",
    "            abstracts.append({\"PMID\": pmid, \"Title\": title, \"Abstract\": abstract})\n",
    "        except KeyError:\n",
    "            pass\n",
    "    return abstracts\n",
    "\n",
    "# Define the AbstractScreeningInput using Pydantic BaseModel\n",
    "class AbstractScreeningInput(BaseModel):\n",
    "    abstracts: List[dict]\n",
    "    criteria: str\n",
    "\n",
    "def screen_abstracts_semantic(abstracts: List[dict], criteria: str, similarity_threshold: float = 0.4):\n",
    "    \"\"\"Screen abstracts based on semantic similarity to the criteria.\"\"\"\n",
    "    \n",
    "    # Compute the embedding of the criteria\n",
    "    criteria_embedding = semantic_model.encode(criteria, convert_to_tensor=True)\n",
    "    \n",
    "    screened = []\n",
    "    for paper in abstracts:\n",
    "        abstract_text = paper['Abstract']\n",
    "        \n",
    "        # Compute the embedding of the abstract\n",
    "        abstract_embedding = semantic_model.encode(abstract_text, convert_to_tensor=True)\n",
    "        \n",
    "        # Compute cosine similarity between the abstract and the criteria\n",
    "        similarity_score = util.cos_sim(abstract_embedding, criteria_embedding).item()\n",
    "        \n",
    "        if similarity_score >= similarity_threshold:\n",
    "            screened.append({\n",
    "                \"PMID\": paper['PMID'], \n",
    "                \"Decision\": \"Include\", \n",
    "                \"Reason\": f\"Similarity score {similarity_score:.2f} >= threshold {similarity_threshold}\"\n",
    "            })\n",
    "        else:\n",
    "            screened.append({\n",
    "                \"PMID\": paper['PMID'], \n",
    "                \"Decision\": \"Exclude\", \n",
    "                \"Reason\": f\"Similarity score {similarity_score:.2f} < threshold {similarity_threshold}\"\n",
    "            })\n",
    "    \n",
    "    return screened\n",
    "\n",
    "# Define the PubMed Search Tool as a StructuredTool with proper input schema\n",
    "pubmed_tool = StructuredTool(\n",
    "    name=\"PubMed_Search_Tool\",\n",
    "    func=pubmed_search,\n",
    "    description=\"Search PubMed for research papers and retrieve abstracts. Pass the abstracts (returned results) to another tool.\",\n",
    "    args_schema=PubMedSearchInput  # Use Pydantic BaseModel for schema\n",
    ")\n",
    "\n",
    "# Define the Abstract Screening Tool with semantic screening\n",
    "semantic_screening_tool = StructuredTool(\n",
    "    name=\"Semantic_Abstract_Screening_Tool\",\n",
    "    func=screen_abstracts_semantic,\n",
    "    description=\"\"\"Screen PubMed abstracts based on semantic similarity to inclusion/exclusion criteria. Uses cosine similarity between abstracts and criteria. Requires 'abstracts' and 'screening criteria' as input.\n",
    "    The 'abstracts' is a list of dictionary with keys as PMID, Title, Abstract.\n",
    "    Output a similarity scores for each abstract and send the list of pmids that passed the screening to Fetch_Extract_Tool.\"\"\",\n",
    "    args_schema=AbstractScreeningInput  # Pydantic schema remains the same\n",
    ")\n",
    "\n",
    "# 3. Define Full-Text Retrieval Tool\n",
    "class FetchExtractInput(BaseModel):\n",
    "    pmids: List[str]  # List of PubMed IDs to fetch full text for\n",
    "    query: str\n",
    "\n",
    "def extract_text_from_pmc_xml(xml_content: str) -> str:\n",
    "    \"\"\"a function to format and clean text from PMC full-text XML.\"\"\"\n",
    "    try:\n",
    "        root = ET.fromstring(xml_content)\n",
    "        \n",
    "        # Find all relevant text sections (e.g., <body>, <sec>, <p>)\n",
    "        body_text = []\n",
    "        for elem in root.iter():\n",
    "            if elem.tag in ['p', 'sec', 'title', 'abstract', 'body']:  # Add more tags as needed\n",
    "                if elem.text:\n",
    "                    body_text.append(elem.text.strip())\n",
    "        \n",
    "        # Join all the text elements to form the complete full text\n",
    "        full_text = \"\\n\\n\".join(body_text)\n",
    "        \n",
    "        return full_text\n",
    "    except ET.ParseError:\n",
    "        print(\"Error parsing XML content.\")\n",
    "        return \"\"\n",
    "\n",
    "def fetch_and_extract(pmids: List[str], query: str):\n",
    "    \"\"\"Fetch full text from PubMed Central for given PMIDs, split into chunks, \n",
    "    store in a Qdrant vector database, and perform RAG for each paper.\n",
    "    Retrieves exactly 3 chunks per paper (if available) and generates a consolidated answer for each paper.\n",
    "    \"\"\"\n",
    "    embedding_model = HuggingFaceEmbeddings(model_name=\"sentence-transformers/all-MiniLM-L6-v2\")\n",
    "    corpus = {}\n",
    "    consolidated_results={}\n",
    "\n",
    "    # Fetch records from PubMed Central (PMC)\n",
    "    handle = Entrez.efetch(db=\"pubmed\", id=\",\".join(pmids), retmode=\"xml\")\n",
    "    records = Entrez.read(handle)\n",
    "    handle.close()\n",
    "\n",
    "    full_articles = []\n",
    "    for record in records['PubmedArticle']:\n",
    "        try:\n",
    "            title = record['MedlineCitation']['Article']['ArticleTitle']\n",
    "            pmid = record['MedlineCitation']['PMID']\n",
    "            pmc_id = 'nan'\n",
    "            pmc_id_temp = record['PubmedData']['ArticleIdList']\n",
    "            \n",
    "            # Extract PMC ID if available\n",
    "            for ele in pmc_id_temp:\n",
    "                if ele.attributes['IdType'] == 'pmc':\n",
    "                    pmc_id = ele.replace('PMC', '')\n",
    "                    break\n",
    "\n",
    "            # Fetch full article from PMC\n",
    "            if pmc_id != 'nan':\n",
    "                handle = Entrez.efetch(db=\"pmc\", id=pmc_id, rettype=\"full\", retmode=\"xml\")\n",
    "                full_article = handle.read()\n",
    "                handle.close()\n",
    "\n",
    "                # Split the full article into chunks\n",
    "                cleaned_full_article = extract_text_from_pmc_xml(full_article)\n",
    "                full_articles.append({\n",
    "                    \"PMID\": pmid,\n",
    "                    \"Title\": title,\n",
    "                    \"FullText\": cleaned_full_article   # Add chunked text\n",
    "                })\n",
    "            else:\n",
    "                full_articles.append({\"PMID\": pmid, \"Title\": title, \"FullText\": \"cannot fetch\"})\n",
    "        except KeyError:\n",
    "            pass\n",
    "\n",
    "    # Create corpus for each chunk\n",
    "    for article in full_articles:\n",
    "        article_id = str(uuid.uuid4())\n",
    "        corpus[article_id] = {\n",
    "            \"page_content\": article[\"FullText\"],\n",
    "            \"metadata\": {\n",
    "                \"PMID\": article[\"PMID\"],\n",
    "                \"Title\": article[\"Title\"]\n",
    "            }\n",
    "        }\n",
    "\n",
    "    documents = [\n",
    "        Document(page_content=content[\"page_content\"], metadata=content[\"metadata\"]) \n",
    "        for content in corpus.values()\n",
    "    ]\n",
    "    CHUNK_SIZE = 1000\n",
    "    CHUNK_OVERLAP = 200\n",
    "\n",
    "    text_splitter = RecursiveCharacterTextSplitter(\n",
    "        chunk_size=CHUNK_SIZE,\n",
    "        chunk_overlap=CHUNK_OVERLAP,\n",
    "        length_function=len,\n",
    "    )\n",
    "    \n",
    "    split_chunks = text_splitter.split_documents(documents)\n",
    "    \n",
    "    id_set = set()\n",
    "    for document in split_chunks:\n",
    "        id = str(uuid.uuid4())\n",
    "        while id in id_set:\n",
    "            id = uuid.uuid4()\n",
    "        id_set.add(id)\n",
    "        document.metadata[\"uuid\"] = id\n",
    "\n",
    "    LOCATION = \":memory:\"\n",
    "    COLLECTION_NAME = \"pmd_data\"\n",
    "    VECTOR_SIZE = 384\n",
    "\n",
    "    # Initialize Qdrant client\n",
    "    qdrant_client = QdrantClient(location=LOCATION)\n",
    "\n",
    "    # Create a collection in Qdrant\n",
    "    qdrant_client.create_collection(\n",
    "        collection_name=COLLECTION_NAME,\n",
    "        vectors_config=VectorParams(size=VECTOR_SIZE, distance=Distance.COSINE),\n",
    "    )\n",
    "\n",
    "    # Initialize the Qdrant vector store without the embedding argument\n",
    "    vdb = QdrantVectorStore(\n",
    "        client=qdrant_client,\n",
    "        collection_name=COLLECTION_NAME,\n",
    "        embedding=embedding_model,\n",
    "    )\n",
    "\n",
    "    # Add embedded documents to Qdrant\n",
    "    vdb.add_documents(split_chunks)\n",
    "\n",
    "    # Query for each paper and consolidate answers\n",
    "    for pmid in pmids:\n",
    "        # Correctly structure the filter using Qdrant Filter model\n",
    "        qdrant_filter = Filter(\n",
    "            must=[\n",
    "                FieldCondition(key=\"metadata.PMID\", match=MatchValue(value=pmid))\n",
    "            ]\n",
    "        )\n",
    "\n",
    "        # Custom filtering for the retriever to only fetch chunks related to the current PMID\n",
    "        retriever_with_filter = vdb.as_retriever(\n",
    "            search_kwargs={\n",
    "                \"filter\": qdrant_filter,  # Correctly passing the Qdrant filter\n",
    "                \"k\": 3  # Retrieve 3 chunks per PMID\n",
    "            }\n",
    "        )\n",
    "\n",
    "        # Reset message history and memory for each query to avoid interference\n",
    "        message_history = ChatMessageHistory()\n",
    "        memory = ConversationBufferMemory(memory_key=\"chat_history\", output_key=\"answer\", chat_memory=message_history, return_messages=True)\n",
    "\n",
    "        # Create the ConversationalRetrievalChain with the filtered retriever\n",
    "        qa_chain = ConversationalRetrievalChain.from_llm(\n",
    "            ChatOpenAI(model_name=\"gpt-3.5-turbo\", temperature=0),\n",
    "            retriever=retriever_with_filter,\n",
    "            memory=memory,\n",
    "            return_source_documents=True\n",
    "        )\n",
    "\n",
    "        # Query the vector store for relevant documents and extract information\n",
    "        result = qa_chain({\"question\": query})\n",
    "\n",
    "        # Generate the final answer based on the retrieved chunks\n",
    "        generated_answer = result[\"answer\"]  # This contains the LLM's generated answer based on the retrieved chunks\n",
    "        generated_source = result[\"source_documents\"]\n",
    "\n",
    "        # Consolidate the results for each paper\n",
    "        paper_info = {\n",
    "            \"PMID\": pmid,\n",
    "            \"Title\": result[\"source_documents\"][0].metadata[\"Title\"] if result[\"source_documents\"] else \"Unknown Title\",\n",
    "            \"Generated Answer\": generated_answer,  # Store the generated answer,\n",
    "            \"Sources\": generated_source \n",
    "        }\n",
    "\n",
    "        consolidated_results[pmid] = paper_info\n",
    "\n",
    "    # Return consolidated results for all papers\n",
    "    return consolidated_results\n",
    "\n",
    "rag_tool = StructuredTool(\n",
    "    name=\"Fetch_Extract_Tool\",\n",
    "    func=fetch_and_extract,\n",
    "    description=\"\"\"Fetch full-text articles based on PMIDs and store them in a Qdrant vector database.\n",
    "    Then extract information based on user's query via Qdrant retriever using a RAG pipeline.\n",
    "    Requires list of PMIDs and user query as input.\"\"\",\n",
    "    args_schema=FetchExtractInput\n",
    ")\n",
    "\n",
    "\n",
    "tool_belt = [\n",
    "    pubmed_tool,\n",
    "    semantic_screening_tool,\n",
    "    rag_tool\n",
    "]\n",
    "\n",
    "# Model setup with tools bound\n",
    "model = ChatOpenAI(model=\"gpt-4o\", temperature=0)\n",
    "model = model.bind_tools(tool_belt)\n",
    "\n",
    "# Agent state to handle the messages\n",
    "class AgentState(TypedDict):\n",
    "    messages: Annotated[list, add_messages]\n",
    "    cycle_count: int  # Add a counter to track the number of cycles\n",
    "\n",
    "# Function to call the model and handle the flow automatically\n",
    "def call_model(state):\n",
    "    messages = state[\"messages\"]\n",
    "    response = model.invoke(messages)\n",
    "    return {\"messages\": [response], \"cycle_count\": state[\"cycle_count\"] + 1}  # Increment cycle count\n",
    "\n",
    "tool_node = ToolNode(tool_belt)\n",
    "\n",
    "# Create the state graph for managing the flow between the agent and tools\n",
    "uncompiled_graph = StateGraph(AgentState)\n",
    "uncompiled_graph.add_node(\"agent\", call_model)\n",
    "uncompiled_graph.add_node(\"action\", tool_node)\n",
    "\n",
    "# Set the entry point for the graph\n",
    "uncompiled_graph.set_entry_point(\"agent\")\n",
    "\n",
    "# Define a function to check if the process should continue\n",
    "def should_continue(state):\n",
    "    # Check if the cycle count exceeds the limit (e.g., 10)\n",
    "    if state[\"cycle_count\"] > 20:\n",
    "        print(f\"Reached the cycle limit of {state['cycle_count']} cycles. Ending the process.\")\n",
    "        return END\n",
    "    \n",
    "    # If there are tool calls, continue to the action node\n",
    "    last_message = state[\"messages\"][-1]\n",
    "    if last_message.tool_calls:\n",
    "        return \"action\"\n",
    "    \n",
    "    return END\n",
    "\n",
    "# Add conditional edges for the agent to action\n",
    "uncompiled_graph.add_conditional_edges(\"agent\", should_continue)\n",
    "uncompiled_graph.add_edge(\"action\", \"agent\")\n",
    "\n",
    "# Compile the state graph\n",
    "compiled_graph = uncompiled_graph.compile()\n",
    "\n",
    "# SystemMessage that defines the execution flow\n",
    "system_instructions = SystemMessage(content=\"\"\"Please execute the following steps in sequence:\n",
    "1. Use the PubMed search tool to search for papers.\n",
    "2. Retrieve the abstracts from the search results.\n",
    "3. Screen the abstracts based on the criteria provided by the user.\n",
    "4. Fetch full-text articles for all the papers that pass step 3. Store the full-text articles in the Qdrant vector database, \n",
    "    and extract the requested information for each article that passed step 3 from the full-text using the query provided by the user.\n",
    "5. Please provide a full summary at the end of the entire flow executed, detailing the whole process/reasoning for each paper. \n",
    "The user will provide the search query, screening criteria, and the query for information extraction.\n",
    "Make sure you finish everything in one step before moving on to next step.\n",
    "Do not call more than one tool in one action.\"\"\")\n",
    "\n",
    "# HumanMessage only includes the necessary inputs\n",
    "human_inputs = HumanMessage(content=\"\"\"{\n",
    "    \"query\": \"(\\\"Impact\\\"[Title/Abstract]) AND ((\\\"COVID\\\"[Title/Abstract] OR \\\"pandemic\\\"[Title/Abstract]) AND (\\\"healthcare resource utilization\\\"[Title/Abstract] OR \\\"health resource utilization\\\"[Title/Abstract]))\",\n",
    "    \"screening_criteria\": \"comparison of healthcare resource utilization before and after the COVID pandemic\",\n",
    "    \"extraction_query\": \"data source information used in each paper (especially medical records)\"\n",
    "}\"\"\")\n",
    "\n",
    "# Combined input for the agent\n",
    "inputs = {\n",
    "    \"messages\": [system_instructions, human_inputs],\n",
    "    \"cycle_count\": 0,  # Initialize cycle count to 0\n",
    "}\n",
    "\n",
    "# # Function to run the graph asynchronously\n",
    "async def run_graph():\n",
    "    final_message_content = None  # Variable to store the final message content\n",
    "\n",
    "    async for chunk in compiled_graph.astream(inputs, stream_mode=\"updates\"):\n",
    "        for node, values in chunk.items():\n",
    "            print(f\"Receiving update from node: '{node}'\")\n",
    "            pretty_print(values[\"messages\"])  # Print all messages as before\n",
    "            \n",
    "            # Check if the message contains content\n",
    "            if \"messages\" in values and values[\"messages\"]:\n",
    "                final_message = values[\"messages\"][-1]  # Access the last message in this chunk\n",
    "                if hasattr(final_message, 'content'):  # Check if content exists\n",
    "                    final_message_content = final_message.content  # Store the last message's content\n",
    "                \n",
    "        print(\"\\n\\n\")\n",
    "\n",
    "    # After the loop finishes, print the final message content\n",
    "    if final_message_content:\n",
    "        print(\"Final message content from the last chunk:\")\n",
    "        pretty_print(final_message_content)\n",
    "    else:\n",
    "        print(\"No final message content found.\")\n",
    "\n",
    "# Run the compiled graph\n",
    "await run_graph()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "llmops-course",
   "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.11.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}