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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
import requests
from markdownify import markdownify
import re
from pathlib import Path
import subprocess
from requests.exceptions import RequestException
from smolagents import tool
import pandas as pd
import os
import sys
from typing import Dict, List, Any, Optional, Tuple
import math
from rapidfuzz import fuzz, process
import numpy as np

# Add the parent directory to sys.path to import gene_tools from main directory
main_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(main_dir)
# Change working directory to main directory
os.chdir(main_dir)
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, current_dir)
from llm import json_llm_call


def validate_genes(genes: List[str], species: str = "human") -> Tuple[List[str], List[str]]:
    """
    Validate a list of gene symbols against local HGNC database.
    
    Args:
        genes: List of gene symbols to validate
        species: Species to validate against ("human" or "mouse")
            
    Returns:
        Tuple of (valid_genes, invalid_genes)
    """
    # Only support human genes for now since we're using HGNC data
    if species != "human":
        raise ValueError("Only human gene validation is supported with HGNC data")
    
    try:
        with open("resource/hgnc_name.txt", "r") as f:
            # Skip header line and get second column (index 1)
            next(f)  # Skip header
            valid_symbols = {line.strip().split("\t")[1] for line in f}
            
        valid_genes = [gene for gene in genes if gene in valid_symbols]
        invalid_genes = [gene for gene in genes if gene not in valid_symbols]
        
    except FileNotFoundError:
        print("HGNC gene list file not found at resource/hgnc_name.txt")
        raise
        
    return valid_genes, invalid_genes

def normalize_scores(scores: List[float], temperature: float = 1.0) -> List[float]:
    """
    Normalize scores using softmax transformation with temperature control.
    
    Args:
        scores: List of numerical scores to normalize
        temperature: Controls distribution sharpness (lower = sharper contrasts)
            Lower values (e.g., 0.5) create sharper contrasts between high/low scores
            Higher values (e.g., 2.0) make the distribution more uniform
        
    Returns:
        List of normalized scores that sum to 1.0, ensuring no zero values
    """
    if not scores:
        return []
        
    # If all scores are the same, return equal probabilities
    if len(set(scores)) == 1:
        return [1.0 / len(scores)] * len(scores)
    
    # Apply softmax with temperature: exp(x/T) / sum(exp(x/T))
    # First subtract max score for numerical stability
    max_score = max(scores)
    exp_scores = [math.exp((score - max_score) / temperature) for score in scores]
    sum_exp_scores = sum(exp_scores)
    
    return [exp_score / sum_exp_scores for exp_score in exp_scores]


@tool
def kegg_pathway_search(query_list: List[str], model_name: str = "gemini-2.5-pro") -> Dict[str, Any]:
    """
    Search and extract biological pathway information from the KEGG database. The KEGG (Kyoto Encyclopedia of Genes and Genomes) database is a comprehensive resource for understanding biological systems and their functions.
    
    Args:
        query_list: List of pathway names related to biological processes or diseases
        model_name: Model name for LLM analysis, defaults to "gemini-2.5-pro"
    
    Returns:
        Dictionary containing gene lists associated with each pathway and normalized relevance scores
    """
    
    # Prompt templates
    PROMPT_MATCH = """
    You are an assistant to biologists. Given the user query, your task is to think step by step to identify the most relevant KEGG pathway ID from the provided pathway table. Please format your response following response format and make sure it is parsable by JSON.

    User query:
    {query}

    Pathway table:
    {existing}

    Response format:
    {{
    "thoughts": <thoughts>, # your step-by-step thinking process
    "pathway_id": <pathway_id>, # Most relevant KEGG pathway ID (e.g., "hsa04630"). If no pathway is relevant, return "NA".
    }}
    """

    PROMPT_EXTRACT = """
    You are an assistant to biologists. Your task is to think step by step to extract valid gene names in the pathway information. Please format your response following response format and make sure it is parsable by JSON.

    Pathway information:
    {existing}

    Response format:
    {{
    "thoughts": <thoughts>, # your step-by-step thinking process.
    "genes": <genes>, # list of valid gene names extracted from pathway information.
    }}
    """
    
    def extract_genes(pathway_info: str) -> Dict[str, Any]:
        """Extract gene names from pathway information"""
        try:
            prompt = PROMPT_EXTRACT.format(existing=pathway_info)
            return json_llm_call(prompt, model_name=model_name)
        except Exception as e:
            print(f"Error extracting genes: {str(e)}")
            return {"thoughts": "Error in extraction", "genes": []}
    
    try:
        # Step 1: Load KEGG pathway table
        pathway_df = pd.read_csv("resource/Kegg_pathways.csv")
        
        # Step 2: Process each query
        final_results = {}
        raw_results = {}
        
        for query in query_list:
            # Use LLM to identify relevant pathway IDs
            prompt = PROMPT_MATCH.format(
                query=query,
                existing=pathway_df.to_string()
            )
            pathway_selection = json_llm_call(prompt, model_name=model_name)
            relevant_pathway_id = pathway_selection.get('pathway_id', "NA")
            
            # Store both pathway IDs and their names
            pathway_details = []
            if relevant_pathway_id != "NA":
                pathway_name = pathway_df[pathway_df['ID'] == relevant_pathway_id]['Pathways'].iloc[0]
                pathway_details.append({
                    "pathway_id": relevant_pathway_id,
                    "pathway_name": pathway_name
                })
            raw_results[query] = pathway_details
            
            # Collect gene information for each pathway
            pathway_genes = []
            for pathway_info in pathway_details:
                pathway_id = pathway_info['pathway_id']
                try:
                    url = f"https://rest.kegg.jp/get/{pathway_id}"
                    response = requests.get(url)
                    response.raise_for_status()
                    
                    # Extract GENE section
                    gene_section = ""
                    in_gene_section = False
                    for line in response.text.split('\n'):
                        if line.startswith('GENE'):
                            in_gene_section = True
                            gene_section += line + '\n'
                        elif in_gene_section and line.startswith(' '):
                            gene_section += line + '\n'
                        elif in_gene_section and not line.startswith(' '):
                            break
                    
                    # Extract genes using existing extract_genes method
                    if gene_section:
                        gene_info = extract_genes(gene_section)
                        extracted_genes = gene_info.get('genes', [])
                        
                        # Validate genes using gene_tools
                        valid_genes, invalid_genes = validate_genes(extracted_genes)
                        pathway_genes.extend(valid_genes)  # Only add valid genes
                
                except requests.exceptions.RequestException as e:
                    print(f"Error fetching pathway {pathway_id}: {str(e)}")
                    continue
            
            # Use set to remove duplicates
            unique_genes = list(set(pathway_genes))
            
            # Assign initial raw scores of 1.0 to each gene
            raw_scores = [1.0] * len(unique_genes)
            
            # Normalize scores using gene_tools function
            normalized_scores = normalize_scores(raw_scores, temperature=1.0)
            
            # Create final results with normalized scores
            final_results[query] = [
                {"gene": gene, "score": score} 
                for gene, score in zip(unique_genes, normalized_scores)
            ]

        return {
            "status": "success",
            "raw_results": raw_results,
            "final_results": final_results
        }
        
    except Exception as e:
        return {
            "status": "error",
            "error_message": str(e),
            "raw_results": {},
            "final_results": {}
        }


@tool
def disease_gene_search(
    disease_list: List[str],
    confidence_cutoff: float = 2.0,
    top_n: Optional[int] = None,
    similarity_threshold: int = 80,
    file_path: str = "resource/diseases/human_disease_integrated_full.tsv"
) -> Dict[str, Any]:
    """
    Search for genes associated with specific diseases using the DISEASES database. DISEASES is a comprehensive resource that integrates evidence on disease-gene associations from automatic text mining, manually curated literature, cancer mutation data, and genome-wide association studies.
    
    Args:
        disease_list: List of disease names to search for associated genes
        confidence_cutoff: Minimum confidence score threshold (default: 2.0)
        top_n: Maximum number of top genes to return by confidence score (None means return all)
        similarity_threshold: Minimum similarity score (0-100) for fuzzy matching (default: 80)
        file_path: Path to the disease mapping TSV file
    
    Returns:
        Dictionary containing gene lists associated with each disease and normalized confidence scores
    """
    
    def search_disease_genes(disease_list: List[str]) -> Dict[str, Dict[str, Any]]:
        """Search for genes associated with given diseases in the mapping file"""
        results = {}
        
        try:
            # Validate file existence
            if not os.path.exists(file_path):
                raise FileNotFoundError(f"Disease mapping file not found at: {file_path}")
            
            # Read the TSV file
            df = pd.read_csv(file_path, 
                           sep='\t', 
                           header=None,
                           names=['col1', 'gene_name', 'col3', 'disease', 'confidence'])
            
            # Process each disease query
            for query in disease_list:
                normalized_query = query.lower().replace('cancer', 'carcinoma')
                
                # Calculate similarity scores
                df['similarity'] = df['disease'].apply(
                    lambda x: max(
                        fuzz.token_sort_ratio(str(x).lower(), normalized_query),
                        fuzz.token_sort_ratio(str(x).lower().replace('carcinoma', 'cancer'), query.lower())
                    ) if pd.notnull(x) else 0
                )
                
                # Get the best matching disease
                best_match = df.loc[df['similarity'].idxmax()]
                best_score = best_match['similarity']
                
                # Initialize result structure with the match info, even if below threshold
                results[query] = {
                    "genes": [],
                    "scores": [],
                    "count": 0,
                    "matched_disease": best_match['disease'],  # Always include the best match
                    "similarity_score": best_score,  # Always include the score
                    "note": ""
                }
                
                # Only proceed with gene collection if above threshold
                if best_score >= similarity_threshold:
                    # Filter for the exact matched disease name
                    disease_df = df[df['disease'] == best_match['disease']]
                    # First filter by confidence score
                    score_mask = disease_df['confidence'] >= confidence_cutoff
                    filtered_df = disease_df[score_mask]
                    if len(filtered_df) > 0:
                        # Sort by confidence score
                        top_genes_df = (filtered_df.sort_values('confidence', ascending=False)
                                      .drop_duplicates('gene_name'))
                        
                        total_available = len(top_genes_df)
                        
                        # Apply top_n filter only if specified
                        if top_n is not None and total_available > top_n:
                            top_genes = top_genes_df.head(top_n)
                            matching_genes = top_genes['gene_name'].tolist()
                            raw_scores = top_genes['confidence'].tolist()
                            results[query]["note"] = f"Selected top {top_n} genes from {total_available} available genes"
                        else:
                            matching_genes = top_genes_df['gene_name'].tolist()
                            raw_scores = top_genes_df['confidence'].tolist()
                            results[query]["note"] = f"Found {total_available} genes"
                        
                        results[query].update({
                            "genes": matching_genes,
                            "scores": raw_scores,
                            "count": len(matching_genes)
                        })
                    else:
                        results[query]["note"] = f"No genes found with confidence >= {confidence_cutoff}"
                else:
                    results[query]["note"] = f"Match found but similarity ({best_score}%) below threshold ({similarity_threshold}%)"
                
        except pd.errors.EmptyDataError:
            print(f"Error: Empty file at {file_path}")
            return {disease: {"genes": [], "count": 0, "note": "Error: Empty file"} 
                   for disease in disease_list}
            
        except Exception as e:
            print(f"Error processing file: {str(e)}")
            return {disease: {"genes": [], "count": 0, "note": f"Error: {str(e)}"} 
                   for disease in disease_list}
            
        return results
    
    try:
        # Validate inputs
        if not disease_list:
            raise ValueError("Disease list cannot be empty")
        
        if confidence_cutoff < 0:
            raise ValueError("Confidence cutoff must be non-negative")
        
        if top_n is not None and top_n < 1:
            raise ValueError("top_n must be positive when specified")
        
        # Search for disease-gene associations
        detailed_results = search_disease_genes(disease_list)
        
        # Validate all genes found
        all_genes = []
        for result in detailed_results.values():
            all_genes.extend(result["genes"])
        valid_genes, invalid_genes = validate_genes(all_genes)
        valid_genes_set = set(valid_genes)
        
        # Filter results to only include valid genes
        final_results = {}
        for disease, result in detailed_results.items():
            # Filter to only valid genes first
            valid_gene_indices = [i for i, gene in enumerate(result["genes"]) if gene in valid_genes_set]
            valid_genes_list = [result["genes"][i] for i in valid_gene_indices]
            valid_scores_list = [result["scores"][i] for i in valid_gene_indices]
            
            # Normalize the scores if any valid genes exist
            if valid_scores_list:
                normalized_scores = normalize_scores(valid_scores_list)
            else:
                normalized_scores = []
            
            # Create entries with normalized scores
            valid_entries = [
                {"gene": gene, "score": score}
                for gene, score in zip(valid_genes_list, normalized_scores)
            ]
            final_results[disease] = valid_entries
        
        # Prepare output with all results
        return {
            "status": "success",
            "metadata": {
                "diseases_searched": len(disease_list),
                "confidence_cutoff": confidence_cutoff,
                "top_n": top_n,
                "genes_found": {
                    disease: len(final_results[disease])
                    for disease in disease_list
                },
                "invalid_genes": invalid_genes
            },
            "results": detailed_results,
            "final_results": final_results
        }
        
    except Exception as e:
        return {
            "status": "error",
            "error_message": str(e),
            "metadata": {},
            "results": {
                disease: {"genes": [], "count": 0, "note": f"Error: {str(e)}"} 
                for disease in disease_list
            },
            "final_results": {disease: [] for disease in disease_list}
        }


@tool
def string_database_search(
    gene_list: List[str],
    score_cutoff: float = 0.9,
    species_id: int = 9606,
    limit: int = 1000,
    model_name: str = "gemini-2.5-pro"
) -> Dict[str, Any]:
    """
    Search for protein-protein interactions using the STRING database. The STRING (Search Tool for the Retrieval of Interacting Genes/Proteins) database is a biological database of known and predicted protein-protein interactions.
    
    Args:
        gene_list: List of gene names to find interaction partners for
        score_cutoff: Minimum combined score threshold (default: 0.9)
        species_id: NCBI species identifier (default: 9606 for human)
        limit: Maximum number of interaction partners per gene (default: 1000)
        model_name: Model name for LLM analysis, defaults to "gemini-2.5-pro"
    
    Returns:
        Dictionary containing interaction partners and normalized confidence scores
    """
    from collections import defaultdict
    
    base_url = "https://version-11-5.string-db.org/api"
    output_format = "tsv-no-header"
    method = "interaction_partners"
    
    try:
        # Validate genes first
        valid_genes, invalid_genes = validate_genes(gene_list)
        if not valid_genes:
            return {
                "status": "error",
                "error_message": f"No valid genes found. Invalid genes: {invalid_genes}",
                "raw_interactions": {},
                "final_results": {}
            }

        request_url = "/".join([base_url, output_format, method])

        params = {
            "identifiers": "%0d".join(valid_genes),
            "species": species_id,
            "limit": limit,
            "caller_identity": "www.awesome_app.org"
        }

        # Make API request
        response = requests.get(request_url, params=params)
        response.raise_for_status()

        # Process results
        interactions = defaultdict(list)
        for line in response.text.strip().split("\n"):
            if not line.strip():
                continue
                
            fields = line.strip().split("\t")
            
            if len(fields) >= 6:
                query_id = fields[0]
                query_name = fields[2]
                partner_name = fields[3]
                combined_score = float(fields[5])

                if combined_score >= score_cutoff:
                    interactions[query_name].append({
                        "partner": partner_name,
                        "score": combined_score
                    })

        # Create final results with normalized scores
        final_results = {}
        raw_interactions = dict(interactions)
        
        for gene, partners in interactions.items():
            if not partners:
                continue
                
            # Get scores above cutoff
            scores = [p["score"] for p in partners]
            if not scores:
                continue
            
            # Get normalized scores
            normalized_scores = normalize_scores(scores)
            
            final_results[gene] = [
                {
                    "gene": partners[i]["partner"],
                    "score": normalized_scores[i]
                }
                for i in range(len(partners))
            ]

        return {
            "status": "success",
            "metadata": {
                "genes_searched": len(valid_genes),
                "invalid_genes": invalid_genes,
                "score_cutoff": score_cutoff,
                "interactions_found": {
                    gene: len(final_results.get(gene, []))
                    for gene in valid_genes
                }
            },
            "raw_interactions": raw_interactions,
            "final_results": final_results
        }

    except requests.exceptions.RequestException as e:
        return {
            "status": "error",
            "error_message": f"Error in STRING database request: {str(e)}",
            "raw_interactions": {},
            "final_results": {}
        }
    except Exception as e:
        return {
            "status": "error",
            "error_message": f"Unexpected error: {str(e)}",
            "raw_interactions": {},
            "final_results": {}
        }


@tool
def go_terms_search(
    query_list: List[str],
    max_candidates: int = 100,
    similarity_threshold: int = 10,
    model_name: str = "gemini-2.5-pro"
) -> Dict[str, Any]:
    """
    Search for genes associated with Gene Ontology (GO) terms. Gene Ontology provides a controlled vocabulary of terms describing gene product characteristics and gene product annotation data across various databases.
    
    Args:
        query_list: List of biological processes, molecular functions, or cellular components to search for
        max_candidates: Maximum number of GO term candidates to consider (default: 100)
        similarity_threshold: Minimum similarity score (0-100) for fuzzy matching (default: 10)
        model_name: Model name for LLM analysis, defaults to "gemini-2.5-pro"
    
    Returns:
        Dictionary containing genes associated with each GO term query and normalized relevance scores
    """
    import json
    from rapidfuzz import process, fuzz
    from rapidfuzz.utils import default_process
    
    json_directory = "resource/GO"
    
    def load_json_files() -> List[Dict[str, Any]]:
        """Load all JSON files from the GO directory"""
        data_list = []
        try:
            for file_name in os.listdir(json_directory):
                if file_name.lower().endswith(".json"):
                    file_path = os.path.join(json_directory, file_name)
                    try:
                        with open(file_path, 'r', encoding='utf-8') as f:
                            data_list.append(json.load(f))
                    except Exception as e:
                        print(f"Could not parse {file_path} as JSON: {e}")
        except FileNotFoundError:
            print(f"GO directory not found: {json_directory}")
        return data_list

    def extract_all_term_names(data_files: List[Dict[str, Any]]) -> List[str]:
        """Extract all GO term names from the loaded JSON files"""
        term_names = []
        for data_file in data_files:
            if isinstance(data_file, dict):
                term_names.extend(list(data_file.keys()))
        return term_names

    def similarity_search(query: str, all_terms: List[str]) -> List[str]:
        """Find most similar GO term names using fuzzy matching"""
        matches = process.extract(
            query, 
            all_terms, 
            scorer=fuzz.token_sort_ratio, 
            processor=default_process,
            limit=max_candidates,
            score_cutoff=similarity_threshold
        )
        return [match[0] for match in matches]

    def match_terms_with_llm(queries: List[str], all_terms: List[str]) -> Dict[str, str]:
        """Use LLM to find the most relevant GO terms"""
        matched_terms = {}
        
        for query in queries:
            candidates = similarity_search(query, all_terms)
            
            if not candidates:
                matched_terms[query] = ""
                continue
            
            prompt = f"""
You are an assistant to biologists. Given a user query, your task is to identify the SINGLE most relevant Gene Ontology (GO) term from the provided list.

IMPORTANT: You must return the EXACT GO term name from the list as it appears, including any IDs, numbers, or special characters. Do not modify, simplify, or clean up the term names.

Think step by step and select only the most relevant GO term name. Please format your response following the response format and make sure it is parsable by JSON.

User query: {query}

Available GO terms:
{chr(10).join(candidates)}

Response format:
{{
    "thoughts": "your step-by-step thinking process",
    "matched_term_name": "matched GO term name EXACTLY as it appears in the list, or NA if no relevant term found"
}}
"""
            
            try:
                result = json_llm_call(prompt, model_name=model_name)
                matched_term = result.get('matched_term_name', "")
                matched_terms[query] = matched_term if matched_term != "NA" else ""
            except Exception as e:
                print(f"Error matching GO term '{query}' with LLM: {str(e)}")
                matched_terms[query] = ""
                
        return matched_terms

    def find_genes_for_terms(matched_terms: Dict[str, str], data_files: List[Dict[str, Any]]) -> Dict[str, List[str]]:
        """Find genes for matched GO terms"""
        results = {}
        
        for query, term_name in matched_terms.items():
            found_genes = set()
            
            if term_name:  # Only search if we have a matched term
                for data_file in data_files:
                    if isinstance(data_file, dict) and term_name in data_file:
                        entry = data_file[term_name]
                        if isinstance(entry, dict):
                            genes = entry.get("geneSymbols", [])
                            if isinstance(genes, list):
                                found_genes.update(genes)
            
            results[query] = sorted(found_genes)
        
        return results

    try:
        # Load GO data files
        data_files = load_json_files()
        if not data_files:
            return {
                "status": "error",
                "error_message": f"No GO JSON files found in {json_directory}",
                "raw_results": {},
                "final_results": {}
            }

        # Extract all GO terms
        all_terms = extract_all_term_names(data_files)
        if not all_terms:
            return {
                "status": "error",
                "error_message": "No GO terms found in JSON files",
                "raw_results": {},
                "final_results": {}
            }

        final_results = {}
        raw_results = {}
        
        # Match terms with LLM
        matched_terms = match_terms_with_llm(query_list, all_terms)
        
        # Find genes for matched terms
        genes_by_query = find_genes_for_terms(matched_terms, data_files)
        
        for query in query_list:
            # Get genes for the current query
            found_genes = genes_by_query.get(query, [])
            
            # Validate genes 
            valid_genes, invalid_genes = validate_genes(found_genes)
            
            # Store raw results
            raw_results[query] = {
                "matched_go_term": matched_terms.get(query, ""),
                "total_genes_found": len(found_genes),
                "valid_genes": len(valid_genes),
                "invalid_genes": len(invalid_genes)
            }
            
            # Assign initial raw scores of 1.0 to each gene
            raw_scores = [1.0] * len(valid_genes)
            
            # Normalize scores
            normalized_scores = normalize_scores(raw_scores, temperature=1.0)
            
            # Create final results with normalized scores
            final_results[query] = [
                {"gene": gene, "score": score} 
                for gene, score in zip(valid_genes, normalized_scores)
            ]
        
        return {
            "status": "success",
            "metadata": {
                "queries_processed": len(query_list),
                "go_terms_matched": {
                    query: matched_terms.get(query, "")
                    for query in query_list
                },
                "genes_found": {
                    query: len(final_results.get(query, []))
                    for query in query_list
                }
            },
            "raw_results": raw_results,
            "final_results": final_results
        }
        
    except Exception as e:
        return {
            "status": "error",
            "error_message": str(e),
            "raw_results": {},
            "final_results": {}
        }


@tool
def screen_data_analysis(
    input_file: str,
    p_value_threshold: float = 0.05,
    effect_size_threshold: Optional[float] = None,
    top_n: Optional[int] = None,
    score_column: Optional[str] = None,
    model_name: str = "gemini-2.5-pro"
) -> Dict[str, Any]:
    """
    Process and filter genetic screen data to identify significant genes based on statistical measures. Handles various formats of screen results, supporting filtering by p-values, effect sizes, or custom scoring.
    
    Args:
        input_file: Path to the input CSV file containing screen results
        p_value_threshold: Threshold for p-values (default: 0.05)
        effect_size_threshold: Threshold for effect sizes (optional)
        top_n: Number of top genes to return (optional)
        score_column: Optional specific column to use for scoring
        model_name: Model name for LLM analysis, defaults to "gemini-2.5-pro"
    
    Returns:
        Dictionary containing filtered genes with normalized relevance scores and processing metadata
    """
    try:
        # Load screen data - try different approaches
        try:
            # Try loading with 'id' as index
            screen_data = pd.read_csv(input_file, index_col='id')
        except (KeyError, ValueError):
            # If that fails, load normally then handle index in filter method
            screen_data = pd.read_csv(input_file)
        
        # Create a copy of the data
        data = screen_data.copy()
        
        # Determine which column to use for gene identifiers
        id_col = 'Gene' if 'Gene' in data.columns else 'id'
        if id_col in data.columns and id_col != data.index.name:
            data = data.set_index(id_col)
        
        # Filter logic based on available data
        p_value_keywords = ['p-value', 'p_value', 'pvalue', 'pval']
        effect_keywords = ['effect', 'fold', 'log2fc', 'lfc']
        
        has_p_value = any(col for col in data.columns if any(keyword in col.lower() for keyword in p_value_keywords))
        has_effect = any(col for col in data.columns if any(keyword in col.lower() for keyword in effect_keywords))
        
        if p_value_threshold is not None and has_p_value:
            # Get minimum p-value between positive and negative (if both exist)
            if all(col in data.columns for col in ['pos|p-value', 'neg|p-value']):
                data['min_p_value'] = data[['pos|p-value', 'neg|p-value']].min(axis=1)
            else:
                # Find any column with p-value in the name
                p_value_col = next((col for col in data.columns if any(keyword in col.lower() for keyword in p_value_keywords)), None)
                if p_value_col:
                    # Convert to numeric, handling any string values
                    data['min_p_value'] = pd.to_numeric(data[p_value_col], errors='coerce')
            
            # Filter by p-value threshold
            significant_genes = data[data['min_p_value'] < p_value_threshold]
            # Sort by minimum p-value
            sorted_genes = significant_genes.sort_values('min_p_value')
            # Calculate -log10(p-value) for scoring
            sorted_genes['score'] = -np.log10(sorted_genes['min_p_value'])
            
        elif effect_size_threshold is not None and has_effect:
            # Find effect size column
            effect_col = next((col for col in data.columns if any(keyword in col.lower() for keyword in effect_keywords)), None)
            
            # Use absolute values for filtering
            # Convert to numeric first
            data[effect_col] = pd.to_numeric(data[effect_col], errors='coerce')
            data['abs_effect'] = data[effect_col].abs()
            
            # Filter by effect size threshold
            significant_genes = data[data['abs_effect'] > effect_size_threshold]
            # Sort by absolute effect size (descending)
            sorted_genes = significant_genes.sort_values('abs_effect', ascending=False)
            # Use absolute effect size for scoring
            sorted_genes['score'] = sorted_genes['abs_effect']
            
        else:
            # Auto-detect best scoring method
            if has_p_value:
                # Use p-value with default threshold
                p_value_col = next((col for col in data.columns if any(keyword in col.lower() for keyword in p_value_keywords)), None)
                if p_value_col:
                    # Convert to numeric, handling any string values
                    data['min_p_value'] = pd.to_numeric(data[p_value_col], errors='coerce')
                    # Use default threshold if not provided
                    threshold = p_value_threshold if p_value_threshold is not None else 0.05
                    significant_genes = data[data['min_p_value'] < threshold]
                    sorted_genes = significant_genes.sort_values('min_p_value')
                    sorted_genes['score'] = -np.log10(sorted_genes['min_p_value'])
                else:
                    raise ValueError("P-value column detected but could not be processed")
            elif has_effect:
                # Use effect size without threshold
                effect_col = next((col for col in data.columns if any(keyword in col.lower() for keyword in effect_keywords)), None)
                if effect_col:
                    # Convert to numeric first
                    data[effect_col] = pd.to_numeric(data[effect_col], errors='coerce')
                    data['abs_effect'] = data[effect_col].abs()
                    significant_genes = data
                    sorted_genes = significant_genes.sort_values('abs_effect', ascending=False)
                    sorted_genes['score'] = sorted_genes['abs_effect']
                else:
                    raise ValueError("Effect size column detected but could not be processed")
            elif score_column is not None and score_column in data.columns:
                # Use the specified column directly
                data['score'] = data[score_column].abs()
                significant_genes = data
                sorted_genes = significant_genes.sort_values('score', ascending=False)
            else:
                raise ValueError("Could not determine scoring method from data. Available columns: " + str(list(data.columns)))
        
        # Limit to top N if specified
        if top_n is not None:
            sorted_genes = sorted_genes.head(top_n)
        
        # Validate gene names
        valid_genes, invalid_genes = validate_genes(sorted_genes.index.tolist())
        sorted_genes = sorted_genes.loc[valid_genes]
        
        # Reset index to make id a column
        sorted_genes = sorted_genes.reset_index()
        col_name = id_col if id_col == 'Gene' else 'id'
        sorted_genes = sorted_genes.rename(columns={'index': col_name})
        
        # Get input file name from path
        file_name = input_file.split('/')[-1]
        
        # Normalize scores
        scores = sorted_genes['score'].tolist()
        normalized_scores = normalize_scores(scores)
        
        # Create final results
        final_results = {
            file_name: [
                {"gene": gene_name, "score": score}
                for gene_name, score in zip(valid_genes, normalized_scores)
            ]
        }
        
        return {
            "status": "success",
            "metadata": {
                "file_processed": file_name,
                "significant_genes": len(valid_genes),
                "threshold_used": p_value_threshold if p_value_threshold is not None else effect_size_threshold,
                "invalid_genes": invalid_genes
            },
            "final_results": final_results
        }
        
    except FileNotFoundError:
        return {
            "status": "error",
            "error_message": f"Input file not found: {input_file}",
            "final_results": {}
        }
    except Exception as e:
        return {
            "status": "error",
            "error_message": str(e),
            "final_results": {}
        }


@tool
def tcga_survival_analysis(
    cancer_types: List[str],
    threshold: float = 1.96,
    model_name: str = "gemini-2.5-pro"
) -> Dict[str, Any]:
    """
    Identify genes associated with cancer survival from The Cancer Genome Atlas (TCGA) data. This tool analyzes multiple data types (CNA, methylation, gene expression, miRNA, and mutations) to find genes with significant associations to patient survival across different cancer types.
    
    Args:
        cancer_types: List of cancer types (common names like "Breast Cancer" or "Chronic Myeloid Leukemia")
        threshold: Z-score threshold for statistical significance (default: 1.96)
        model_name: Model name for LLM analysis, defaults to "gemini-2.5-pro"
    
    Returns:
        Dictionary containing genes associated with survival for each cancer type with normalized relevance scores
    """
    from math import sqrt
    
    # TCGA codes mapping
    TCGA_CODES = {
        'LAML', 'ACC', 'BLCA', 'LGG', 'BRCA', 'CESC', 'CHOL', 'LCML', 'COAD',
        'CNTL', 'ESCA', 'FPPP', 'GBM', 'HNSC', 'KICH', 'KIRC', 'KIRP', 'LIHC',
        'LUAD', 'LUSC', 'DLBC', 'MESO', 'MISC', 'OV', 'PAAD', 'PCPG', 'PRAD',
        'READ', 'SARC', 'SKCM', 'STAD', 'TGCT', 'THYM', 'THCA', 'UCS', 'UCEC', 'UVM'
    }
    
    data_files = {
        "CNA": "resource/TCGA/Table S1 - univariate Cox models_S1A - CNA.csv",
        "Methylation": "resource/TCGA/Table S1 - univariate Cox models_S1B - DNA methylation.csv",
        "Gene Expression": "resource/TCGA/Table S1 - univariate Cox models_S1C - Gene expression.csv",
        "miRNA": "resource/TCGA/Table S1 - univariate Cox models_S1D - miRNA expression.csv",
        "Mutations": "resource/TCGA/Table S1 - univariate Cox models_S1E - Mutations.csv"
    }
    
    TCGA_PROMPT = """
You are an assistant to biologists. Given the user query, your task is to think step by step to identify the most relevant TCGA study abbreviation(s) from the provided mapping table. For some cancers like lung cancer, return all relevant subtypes. 

IMPORTANT: If the query is too general (e.g., "cancer", "tumor", "solid tumor", "carcinoma", "neoplasm"), return "TOO_GENERAL" as the tcga_code. Overly general terms should not match with all possible cancer types.

If the query is specific to a cancer type but could match multiple types (e.g. "lung cancer" matching both LUAD and LUSC), that's acceptable and you should return all relevant matches.

Please format your response following response format and make sure it is parsable by JSON.

User query:
{query}

TCGA mapping table:
LAML    Acute Myeloid Leukemia
ACC     Adrenocortical carcinoma
BLCA    Bladder Urothelial Carcinoma
LGG     Brain Lower Grade Glioma
BRCA    Breast invasive carcinoma
CESC    Cervical squamous cell carcinoma and endocervical adenocarcinoma
CHOL    Cholangiocarcinoma
LCML    Chronic Myelogenous Leukemia or Chronic Myeloid Leukemia
COAD    Colon adenocarcinoma
CNTL    Controls
ESCA    Esophageal carcinoma
FPPP    FFPE Pilot Phase II
GBM     Glioblastoma multiforme
HNSC    Head and Neck squamous cell carcinoma
KICH    Kidney Chromophobe
KIRC    Kidney renal clear cell carcinoma
KIRP    Kidney renal papillary cell carcinoma
LIHC    Liver hepatocellular carcinoma
LUAD    Lung adenocarcinoma
LUSC    Lung squamous cell carcinoma
DLBC    Lymphoid Neoplasm Diffuse Large B-cell Lymphoma
MESO    Mesothelioma
MISC    Miscellaneous
OV      Ovarian serous cystadenocarcinoma
PAAD    Pancreatic adenocarcinoma
PCPG    Pheochromocytoma and Paraganglioma
PRAD    Prostate adenocarcinoma
READ    Rectum adenocarcinoma
SARC    Sarcoma
SKCM    Skin Cutaneous Melanoma
STAD    Stomach adenocarcinoma
TGCT    Testicular Germ Cell Tumors
THYM    Thymoma
THCA    Thyroid carcinoma
UCS     Uterine Carcinosarcoma
UCEC    Uterine Corpus Endometrial Carcinoma
UVM     Uveal Melanoma

Response format:
{{
"thoughts": "your step-by-step thinking process",
"tcga_code": "Most relevant TCGA study abbreviation(s). Can be a single code (e.g., 'PAAD') or an array of codes (e.g., ['LUAD', 'LUSC']). If the query is too general, return 'TOO_GENERAL'. If no match is found, return 'NA'."
}}
"""

    def get_tcga_code(cancer_name: str) -> List[str]:
        """Convert common cancer name to TCGA study abbreviation(s) using LLM."""
        prompt = TCGA_PROMPT.format(query=cancer_name)
        response = json_llm_call(prompt, model_name=model_name)
        tcga_code = response.get('tcga_code', 'NA')
        
        # Handle too general case
        if tcga_code == "TOO_GENERAL":
            print(f"Warning: '{cancer_name}' is too general. Please specify a particular cancer type.")
            return []
            
        # Handle both single string and list responses
        if isinstance(tcga_code, list):
            valid_codes = [code for code in tcga_code if code in TCGA_CODES]
            return valid_codes if valid_codes else []
        return [tcga_code] if tcga_code in TCGA_CODES else []

    def get_survival_genes(cancer_type: str, threshold: float = 1.96):
        results = {}
        
        for category, file_path in data_files.items():
            try:
                df = pd.read_csv(file_path)
                df.columns = df.columns.str.strip().str.lower() 
                
                if cancer_type.lower() not in df.columns:
                    print(f"Skipping {category}: {cancer_type} not found in columns.")
                    continue
                
                gene_col = next((col for col in df.columns if "gene" in col.lower()), None)
                if gene_col is None:
                    print(f"Skipping {category}: No column with 'Gene' found.")
                    continue
                
                z_col = df.columns[-1]  # Get the last column as the Stouffer's Z-score column
                
                # Clean gene names by removing extra quotes
                df[gene_col] = df[gene_col].str.replace("'", "")
                
                df_filtered = df[abs(df[cancer_type.lower()]) > threshold][[gene_col, cancer_type.lower(), z_col]]
                results[category] = df_filtered.to_dict(orient='records')
            except FileNotFoundError:
                print(f"TCGA data file not found: {file_path}")
                continue
        
        return results

    try:
        final_results = {}
        raw_results = {}
        
        # Process all queries and collect genes first
        all_genes = set()
        for query in cancer_types:
            tcga_codes = get_tcga_code(query)
            
            if not tcga_codes:
                raw_results[query] = []
                final_results[query] = []
                continue
            
            for tcga_code in tcga_codes:
                genes_by_category = get_survival_genes(tcga_code, threshold)
                if genes_by_category:
                    # Collect all unique genes
                    for category, gene_list in genes_by_category.items():
                        all_genes.update(gene_data["gene"] for gene_data in gene_list if "gene" in gene_data)
                        
                    # Store raw results
                    if query not in raw_results:
                        raw_results[query] = []
                    raw_results[query].append({
                        "tcga_code": tcga_code,
                        "category_data": genes_by_category
                    })
        
        # Validate all unique genes at once
        valid_genes, invalid_genes = validate_genes(list(all_genes))
        valid_genes = set(valid_genes)
        
        # Process results using the pre-validated gene set
        for query in cancer_types:
            if query in raw_results:
                for result in raw_results[query]:
                    tcga_code = result["tcga_code"]
                    genes_by_category = result["category_data"]
                    
                    # Create a dictionary to store combined Z-scores for each gene
                    gene_scores = {}
                    gene_counts = {}
                    
                    # Only process valid genes
                    for category, gene_list in genes_by_category.items():
                        if gene_list:  # Check if gene_list is not empty
                            z_col = list(gene_list[0].keys())[-1]
                            for gene_data in gene_list:
                                gene = gene_data.get("gene", "")
                                if gene in valid_genes:  # Only process validated genes
                                    z_score = float(gene_data.get(z_col, 0))
                                    
                                    if gene not in gene_scores:
                                        gene_scores[gene] = 0
                                        gene_counts[gene] = 0
                                    
                                    gene_scores[gene] += z_score
                                    gene_counts[gene] += 1
                    
                    # Calculate combined Z-scores
                    combined_results = []
                    for gene in gene_scores:
                        combined_score = abs(gene_scores[gene] / sqrt(gene_counts[gene]))
                        combined_results.append({
                            "gene": gene,
                            "score": combined_score
                        })
                    
                    # Sort by combined Z-score
                    combined_results.sort(key=lambda x: x["score"], reverse=True)
                    
                    # Normalize scores
                    all_scores = [item["score"] for item in combined_results]
                    normalized_scores = normalize_scores(all_scores)
                    
                    # Update scores with normalized values
                    for i, item in enumerate(combined_results):
                        item["score"] = normalized_scores[i]
                        
                    final_results[tcga_code] = combined_results

        return {
            "status": "success",
            "metadata": {
                "cancer_types_processed": len(cancer_types),
                "tcga_codes_found": list(final_results.keys()),
                "total_genes_analyzed": len(all_genes),
                "valid_genes": len(valid_genes),
                "invalid_genes": invalid_genes
            },
            "raw_results": raw_results,
            "final_results": final_results
        }
        
    except Exception as e:
        return {
            "status": "error",
            "error_message": str(e),
            "raw_results": {},
            "final_results": {}
        }


@tool
def drug_gene_network_search(
    drug_queries: List[str],
    graph_path: str = "resource/RxGrid/G_full.p",
    model_name: str = "gemini-2.5-pro"
) -> Dict[str, Any]:
    """
    Identify relationships between drugs and genes using a graph-based database. This tool can match potentially misspelled drug names to their correct counterparts and extract gene relationships from the RxGrid network.
    
    Args:
        drug_queries: List of drug names (which may contain misspellings or variations)
        graph_path: Path to the pickled graph file (default: "resource/RxGrid/G_full.p")
        model_name: Model name for LLM analysis, defaults to "gemini-2.5-pro"
    
    Returns:
        Dictionary containing matched drugs and their associated genes with relationship details
    """
    import pickle
    import difflib
    import networkx as nx
    
    try:
        # Load the graph
        with open(graph_path, 'rb') as f:
            G = pickle.load(f)

        drug_list = [
            node for node, attrs in G.nodes(data=True)
            if attrs.get('type', '').lower() == 'compound'
        ]
        
        def find_best_drug_match(drug_query: str) -> str:
            """Find the best matching drug name, handling misspellings"""
            # Check for an exact match first
            if drug_query in drug_list:
                return drug_query
            
            # Use difflib to find the closest match
            matches = difflib.get_close_matches(drug_query, drug_list, n=1, cutoff=0.6)
            if matches:
                return matches[0]
            else:
                return None
        
        # Initialize results structure
        results = {
            "status": "success",
            "intermediate_results": {},
            "final_results": {}
        }
        
        # Process each drug query
        for drug_query in drug_queries:
            best_match = find_best_drug_match(drug_query)
            if not best_match:
                results["intermediate_results"][drug_query] = {
                    "status": "error",
                    "message": f"No drug found matching '{drug_query}'."
                }
                continue
            
            # Get neighbors and their edge data
            gene_relationships = []
            for neighbor in G.neighbors(best_match):
                if G.nodes[neighbor].get('type', '').lower() != 'compound':
                    edge_data = G.get_edge_data(best_match, neighbor)
                    gene_relationships.append({
                        'gene': neighbor,
                        'relationship': edge_data
                    })
            
            # Store in intermediate_results using the original query for reference
            results["intermediate_results"][drug_query] = {
                "status": "success",
                "best_match": best_match,
                "gene_relationships": gene_relationships
            }
            
            # First create gene relationships with initial score of 1.0
            gene_scores = [
                {
                    "gene": rel["gene"],
                    "score": 1.0
                }
                for rel in gene_relationships
            ]
            
            # Extract just the scores
            scores = [item["score"] for item in gene_scores]
            
            # Normalize the scores
            normalized_scores = normalize_scores(scores)
            
            # Update the gene_scores with normalized values
            for i, item in enumerate(gene_scores):
                item["score"] = normalized_scores[i]
            
            # Add to final results using the best_match name
            results["final_results"][best_match] = gene_scores
        
        return results
        
    except FileNotFoundError:
        return {
            "status": "error",
            "error_message": f"Graph file not found: {graph_path}",
            "intermediate_results": {},
            "final_results": {}
        }
    except Exception as e:
        return {
            "status": "error",
            "error_message": str(e),
            "intermediate_results": {},
            "final_results": {}
        }


@tool
def pubchem_drug_gene_search(
    drug_names: List[str],
    model_name: str = "gemini-2.5-pro"
) -> Dict[str, Any]:
    """
    Search and extract gene associations for drugs from the PubChem database. PubChem is a comprehensive database of chemical substances and their biological activities. This tool retrieves drug information and uses LLM analysis to extract gene targets and associations.
    
    Args:
        drug_names: List of drug names to search for gene associations
        model_name: Model name for LLM analysis, defaults to "gemini-2.5-pro"
    
    Returns:
        Dictionary containing gene associations for each drug with normalized relevance scores
    """
    import time
    
    pugrest_base = "https://pubchem.ncbi.nlm.nih.gov/rest/pug"
    pugview_base = "https://pubchem.ncbi.nlm.nih.gov/rest/pug_view/data"
    
    def get_cid_from_drug_name(drug_name: str) -> str:
        """Given a drug name, query PubChem to retrieve its CID."""
        url = f"{pugrest_base}/compound/name/{drug_name}/cids/TXT"
        try:
            response = requests.get(url, timeout=10)
            if response.status_code != 200:
                print(f"Error retrieving CID for {drug_name}: {response.text}")
                return None
            cids = response.text.strip().split()
            if not cids:
                return None
            return cids[0]
        except requests.exceptions.Timeout:
            print(f"Timeout retrieving CID for {drug_name}")
            return None
        except Exception as e:
            print(f"Error retrieving CID for {drug_name}: {str(e)}")
            return None
    
    def get_compound_record_json(cid: str) -> dict:
        """Retrieve the compound record (in JSON) for the given CID using PubChem PUG-View."""
        url = f"{pugview_base}/compound/{cid}/JSON"
        try:
            response = requests.get(url, timeout=15)
            if response.status_code != 200:
                print(f"Error retrieving compound record for CID {cid}: {response.text}")
                return None
            return response.json()
        except requests.exceptions.Timeout:
            print(f"Timeout retrieving compound record for CID {cid}")
            return None
        except Exception as e:
            print(f"Error retrieving compound record for CID {cid}: {str(e)}")
            return None
    
    def extract_relevant_text_for_gene_association(record_json: dict) -> str:
        """Extract text from 'Mechanism of Action' section focusing on the actual content in the 'String' fields."""
        text_chunks = []
        max_text_length = 10000  # Maximum text length to limit LLM input size
        
        def traverse_sections(sections):
            for section in sections:
                # Check if this is the "Mechanism of Action" section
                heading = section.get('TOCHeading', '').lower()
                
                if "mechanism of action" in heading:
                    # Extract the description if present
                    if 'Description' in section:
                        text_chunks.append(section['Description'])
                    
                    # Extract text from each Information item
                    if 'Information' in section:
                        for info_item in section['Information']:
                            if 'Value' in info_item and 'StringWithMarkup' in info_item['Value']:
                                for string_item in info_item['Value']['StringWithMarkup']:
                                    if 'String' in string_item:
                                        text_chunks.append(string_item['String'])
                    
                    return  # Once we've found the Mechanism of Action section, we're done
                
                # Recurse into nested sections, if any
                if 'Section' in section:
                    traverse_sections(section['Section'])
        
        try:
            record = record_json.get('Record', {})
            sections = record.get('Section', [])
            traverse_sections(sections)
        except Exception as e:
            print(f"Error traversing record JSON: {e}")
        
        # Truncate to maximum length if needed
        result = "\n\n".join(text_chunks)
        if len(result) > max_text_length:
            return result[:max_text_length] + "... (text truncated)"
        
        if not result:
            return "No Mechanism of Action information found in the record."
            
        return result
    
    def query_llm_for_gene_extraction(drug_name: str, record_text: str) -> dict:
        """Build a prompt for the LLM to extract gene associations from the provided record text."""
        prompt = f"""
You are an assistant to pharmacologists and geneticists. Given the drug name, your task is to think step by step to identify all gene symbols or names that are mentioned as targets or associated with the drug in the provided PubChem compound record text. Please format your response following response format and make sure it is parsable by JSON.

Drug query:
{drug_name}

PubChem compound record text:
{record_text}

Response format:
{{
"thoughts": "your step-by-step analysis of the gene associations in the text",
"drug": "{drug_name}",
"gene_count": "the number of unique genes found",
"genes": "a list of gene names/symbols associated with the drug, please make sure the gene names are in the format of HGNC symbols."
}}

If no gene associations are found, return an empty list for "genes" and set "gene_count" to 0.
"""
        # Query the LLM and return its response
        response = json_llm_call(prompt, model_name=model_name)
        return response
    
    try:
        # Convert to list if input is a single drug name
        if not isinstance(drug_names, list):
            drug_names = [drug_names]
        
        results = []
        all_genes = set()
        preliminary_results = {}
        
        # Process each drug
        for drug_name in drug_names:
            # Get CID from drug name
            cid = get_cid_from_drug_name(drug_name)
            if not cid:
                results.append({
                    "status": "error",
                    "message": f"Could not find a CID for drug '{drug_name}'."
                })
                continue
            
            # Get compound record
            record_json = get_compound_record_json(cid)
            if not record_json:
                results.append({
                    "status": "error",
                    "message": f"Could not retrieve compound record for CID {cid}."
                })
                continue
            
            # Extract text from sections that might include gene/target info
            record_text = extract_relevant_text_for_gene_association(record_json)
            if not record_text:
                record_text = "No detailed gene or target information found in the record."
            
            # Query the LLM to parse the text and extract gene associations
            llm_result = query_llm_for_gene_extraction(drug_name, record_text)

            # Store gene entries temporarily
            if isinstance(llm_result, dict) and "genes" in llm_result:
                genes_list = []
                for gene in llm_result["genes"]:
                    genes_list.append({
                        "gene": gene,
                        "score": 1.0  # Initial score of 1
                    })
                    all_genes.add(gene)
                preliminary_results[drug_name] = genes_list
            
            results.append({
                "status": "success",
                "drug": drug_name,
                "cid": cid,
                "results": llm_result
            })
        
        # Validate all the genes we've collected
        valid_genes, invalid_genes = validate_genes(list(all_genes))
        valid_genes_set = set(valid_genes)
        
        # Filter final_results to only include validated genes
        final_results = {}
        for drug_name, genes_list in preliminary_results.items():
            validated_genes_list = [gene_entry for gene_entry in genes_list 
                                   if gene_entry["gene"] in valid_genes_set]
            
            # Only normalize if we have genes
            if validated_genes_list:
                # Extract the scores for normalization
                scores = [gene_entry["score"] for gene_entry in validated_genes_list]
                # Normalize the scores
                normalized_scores = normalize_scores(scores, temperature=1.0)
                
                # Update the gene entries with normalized scores
                for i, gene_entry in enumerate(validated_genes_list):
                    gene_entry["score"] = normalized_scores[i]
                
                final_results[drug_name] = validated_genes_list
        
        # Return comprehensive results
        return {
            "status": "success",
            "metadata": {
                "drugs_processed": len(drug_names),
                "successful_queries": len(preliminary_results),
                "total_genes_found": len(all_genes),
                "valid_genes": len(valid_genes),
                "invalid_genes": invalid_genes
            },
            "results": results,
            "final_results": final_results
        }
        
    except Exception as e:
        return {
            "status": "error",
            "error_message": str(e),
            "results": [],
            "final_results": {}
        }


@tool
def hpo_phenotype_search(phenotype_terms: List[str], model_name: str = "gemini-2.5-pro") -> Dict[str, Any]:
    """
    Search and process Human Phenotype Ontology (HPO) database information. HPO provides a standardized vocabulary of phenotypic abnormalities encountered in human disease, allowing for the mapping of phenotypes to associated genes.
    
    Args:
        phenotype_terms: List of phenotype/disease terms to search in the HPO database
        model_name: Model name for LLM analysis, defaults to "gemini-2.5-pro"
    
    Returns:
        Dictionary containing status, raw results, and final results
    """
    try:
        base_url = "https://ontology.jax.org/api/hp"
        final_results = {}
        raw_results = {}
        
        for query in phenotype_terms:
            print(f"\nProcessing query: '{query}'")
            
            # Get HPO terms for the query
            try:
                response = requests.get(f"{base_url}/search", params={"q": query})
                if response.status_code == 200:
                    data = response.json()
                    if "terms" in data and len(data["terms"]) > 0:
                        hpo_terms = data["terms"][:10]  # Top 10 terms
                    else:
                        print("No HPO term found for the given input.")
                        hpo_terms = []
                else:
                    print("Failed to connect to the HPO API.")
                    hpo_terms = []
            except Exception as e:
                print(f"Error fetching HPO terms: {str(e)}")
                hpo_terms = []
            
            term_details = []
            if hpo_terms:
                # Use LLM to select the most relevant term
                terms_str = "\n".join([f"{i+1}. {term['id']} - {term['name']}" 
                                     for i, term in enumerate(hpo_terms)])
                
                prompt = f"""
You are an assistant to biologists. Given a user's phenotype or disease query and a list of HPO (Human Phenotype Ontology) terms from the database, your task is to select the most relevant HPO term that matches the query. Please format your response following response format and make sure it is parsable by JSON.

User query:
{query}

Available HPO terms:
{terms_str}

Response format:
{{
"thoughts": "your step-by-step reasoning for selection",
"selected_term": "selected HPO ID (not the full term)"
}}
"""
                try:
                    llm_response = json_llm_call(prompt, model_name=model_name)
                    selected_hpo_id = llm_response.get("selected_term", "")
                    
                    # Find the term name from the original search results
                    term_name = next((term["name"] for term in hpo_terms if term["id"] == selected_hpo_id), "Unknown term")
                    print(f"Selected HPO term for '{query}': {selected_hpo_id} - {term_name}")
                    
                    term_details.append({
                        "hpo_id": selected_hpo_id,
                        "name": term_name
                    })
                except Exception as e:
                    print(f"LLM selection unavailable (using first term): {str(e)}")
                    # Fallback to first term
                    if hpo_terms:
                        term_details.append({
                            "hpo_id": hpo_terms[0]["id"],
                            "name": hpo_terms[0]["name"]
                        })
                        print(f"Using fallback HPO term: {hpo_terms[0]['id']} - {hpo_terms[0]['name']}")
            
            raw_results[query] = term_details
            
            # Collect gene information for each HPO ID
            all_genes = []
            for term_info in term_details:
                hpo_id = term_info['hpo_id']
                try:
                    annotation_url = f"https://ontology.jax.org/api/network/annotation/{hpo_id}"
                    response = requests.get(annotation_url)
                    if response.status_code == 200:
                        data = response.json()
                        if "genes" in data:
                            genes = [gene["name"] for gene in data["genes"]]
                            all_genes.extend(genes)
                except Exception as e:
                    print(f"Error fetching genes for HPO ID {hpo_id}: {str(e)}")
                    continue
            
            # Validate genes and create final results
            valid_genes, invalid_genes = validate_genes(all_genes)
            unique_valid_genes = list(set(valid_genes))
            
            if unique_valid_genes:
                initial_scores = [1.0] * len(unique_valid_genes)
                normalized_scores = normalize_scores(initial_scores)
                final_results[query] = [
                    {"gene": gene, "score": score} 
                    for gene, score in zip(unique_valid_genes, normalized_scores)
                ]
            else:
                final_results[query] = []

        return {
            "status": "success",
            "raw_results": raw_results,
            "final_results": final_results
        }
        
    except Exception as e:
        return {
            "status": "error",
            "error_message": str(e),
            "raw_results": {},
            "final_results": {}
        }


@tool
def omim_disease_search(disease_terms: List[str], model_name: str = "gemini-2.5-pro") -> Dict[str, Any]:
    """
    Search and extract gene-disease relationship information from the OMIM database. The OMIM (Online Mendelian Inheritance in Man) database is a comprehensive catalog of human genes and genetic disorders, focusing on the relationship between phenotype and genotype.
    
    Args:
        disease_terms: List of disease or phenotype names to search in OMIM
        model_name: Model name for LLM analysis, defaults to "gemini-2.5-pro"
    
    Returns:
        Dictionary containing status, raw results, and final results
    """
    try:
        base_url = "https://api.omim.org/api"
        api_key = '7TcdVyyhRWOtu58HFHJeOw'
        final_results = {}
        raw_results = {}
        
        for query in disease_terms:
            print(f"\nProcessing query: '{query}'")
            
            # Search for OMIM terms
            search_url = f"{base_url}/entry/search"
            params = {
                'search': query,
                'start': 0,
                'limit': 10,
                'format': 'json',
                'apiKey': api_key
            }
            
            try:
                response = requests.get(search_url, params=params)
                if response.status_code == 200:
                    data = response.json()
                    if 'omim' in data and 'searchResponse' in data['omim'] and 'entryList' in data['omim']['searchResponse']:
                        omim_entries = data['omim']['searchResponse']['entryList'][:5]  # Top 5 entries
                    else:
                        print(f"No OMIM entries found for query: {query}")
                        omim_entries = []
                else:
                    print(f"Failed to search OMIM for query: {query}")
                    omim_entries = []
            except Exception as e:
                print(f"Error searching OMIM: {str(e)}")
                omim_entries = []
            
            raw_results[query] = omim_entries
            
            # Extract genes from OMIM entries
            all_genes = []
            for entry in omim_entries:
                omim_number = entry.get('entry', {}).get('mimNumber')
                if omim_number:
                    try:
                        # Get detailed entry information
                        detail_url = f"{base_url}/entry"
                        detail_params = {
                            'mimNumber': omim_number,
                            'include': 'geneMap',
                            'format': 'json',
                            'apiKey': api_key
                        }
                        
                        detail_response = requests.get(detail_url, params=detail_params)
                        if detail_response.status_code == 200:
                            detail_data = detail_response.json()
                            if 'omim' in detail_data and 'entryList' in detail_data['omim']:
                                for detail_entry in detail_data['omim']['entryList']:
                                    if 'entry' in detail_entry and 'geneMap' in detail_entry['entry']:
                                        gene_map = detail_entry['entry']['geneMap']
                                        if 'geneSymbols' in gene_map:
                                            all_genes.extend(gene_map['geneSymbols'].split(', '))
                    except Exception as e:
                        print(f"Error fetching details for OMIM {omim_number}: {str(e)}")
                        continue
            
            # Validate genes and create final results
            valid_genes, invalid_genes = validate_genes(all_genes)
            unique_valid_genes = list(set(valid_genes))
            
            if unique_valid_genes:
                initial_scores = [1.0] * len(unique_valid_genes)
                normalized_scores = normalize_scores(initial_scores)
                final_results[query] = [
                    {"gene": gene, "score": score} 
                    for gene, score in zip(unique_valid_genes, normalized_scores)
                ]
            else:
                final_results[query] = []

        return {
            "status": "success",
            "raw_results": raw_results,
            "final_results": final_results
        }
        
    except Exception as e:
        return {
            "status": "error",
            "error_message": str(e),
            "raw_results": {},
            "final_results": {}
        }


@tool
def orphanet_rare_disease_search(disease_terms: List[str], model_name: str = "gemini-2.5-pro") -> Dict[str, Any]:
    """
    Search and process Orphanet rare disease database information. Orphanet is a comprehensive resource for information on rare diseases and orphan drugs, providing data on disease-gene associations.
    
    Args:
        disease_terms: List of rare disease names or terms to search in the Orphanet database
        model_name: Model name for LLM analysis, defaults to "gemini-2.5-pro"
    
    Returns:
        Dictionary containing status, raw results, and final results
    """
    try:
        base_url = "https://api.orphadata.com"
        final_results = {}
        raw_results = {}
        
        for query in disease_terms:
            print(f"\nProcessing query: '{query}'")
            
            # Get Orphanet terms for the query
            try:
                from urllib.parse import quote
                encoded_term = quote(query)
                response = requests.get(
                    f"{base_url}/rd-cross-referencing/orphacodes/names/{encoded_term}?lang=en",
                    headers={"accept": "application/json"},
                    timeout=30
                )
                
                orphanet_terms = []
                if response.status_code == 200:
                    data = response.json()
                    results = data.get("data", {}).get("results", {})
                    if results and "ORPHAcode" in results:
                        # Convert to list format for consistency
                        orphanet_terms = [results]
                    else:
                        print("No ORPHAcode found for the given term.")
                        orphanet_terms = []
                else:
                    print("Failed to connect to the Orphadata API.")
                    orphanet_terms = []
            except Exception as e:
                print(f"Error retrieving data for '{query}': {e}")
                orphanet_terms = []
            
            term_details = []
            if orphanet_terms:
                # Use LLM to select the most relevant term if needed
                if len(orphanet_terms) > 1:
                    try:
                        # Format the terms for the prompt
                        terms_str = "\n".join([f"{i+1}. ORPHAcode: {term['ORPHAcode']} - {term['PreferredTerm']}" 
                                            for i, term in enumerate(orphanet_terms)])
                        
                        prompt = f"""
You are an assistant to biologists. Given a user's rare disease query and a list of Orphanet disease terms from the database, your task is to select the most relevant Orphanet disease that matches the query. Please format your response following response format and make sure it is parsable by JSON.

User query:
{query}

Available Orphanet terms:
{terms_str}

Response format:
{{
"thoughts": "your step-by-step reasoning for selection",
"selected_term": "orphacode" 
}}
"""
                        llm_response = json_llm_call(prompt, model_name=model_name)
                        selected_code = llm_response.get("selected_term", "")
                        
                        # Find the selected term from the list
                        selected_term = None
                        for term in orphanet_terms:
                            if str(term['ORPHAcode']) == str(selected_code):
                                selected_term = term
                                break
                        
                        if not selected_term:
                            selected_term = orphanet_terms[0]  # Fallback to first term
                            
                    except Exception as e:
                        print(f"LLM selection failed: {str(e)}")
                        selected_term = orphanet_terms[0]  # Fallback to first term
                else:
                    selected_term = orphanet_terms[0]
                
                # Print selected Orphanet term for verification
                orphacode = selected_term.get("ORPHAcode")
                term_name = selected_term.get("PreferredTerm", "Unknown")
                print(f"Selected Orphanet term for '{query}':")
                print(f"  - ORPHAcode {orphacode}: {term_name}")
                
                # Store the Orphanet information
                term_details.append({
                    "orphacode": orphacode,
                    "name": term_name
                })
            
            raw_results[query] = term_details
            
            # Collect gene information for each Orphanet disease
            all_genes = []
            for term_info in term_details:
                orphacode = term_info['orphacode']
                try:
                    response = requests.get(
                        f"{base_url}/rd-associated-genes/orphacodes/{orphacode}",
                        headers={"accept": "application/json"},
                        timeout=30
                    )
                    if response.status_code == 200:
                        data = response.json()
                        # The gene associations are located in:
                        # data → results → DisorderGeneAssociation (a list of associations)
                        associations = data.get("data", {}).get("results", {}).get("DisorderGeneAssociation", [])
                        # Extract just the gene symbols from each association
                        genes = [assoc["Gene"]["Symbol"] for assoc in associations 
                               if "Gene" in assoc and "Symbol" in assoc["Gene"]]
                        all_genes.extend(genes)
                    else:
                        print("Failed to connect to the Orphadata API for gene retrieval.")
                except Exception as e:
                    print(f"Error retrieving genes for ORPHAcode '{orphacode}': {e}")
                    continue
            
            # Validate genes and create final results
            valid_genes, invalid_genes = validate_genes(all_genes)
            unique_valid_genes = list(set(valid_genes))
            
            if unique_valid_genes:
                initial_scores = [1.0] * len(unique_valid_genes)
                normalized_scores = normalize_scores(initial_scores)
                final_results[query] = [
                    {"gene": gene, "score": score} 
                    for gene, score in zip(unique_valid_genes, normalized_scores)
                ]
            else:
                final_results[query] = []

        return {
            "status": "success",
            "metadata": {
                "diseases_searched": len(disease_terms),
                "invalid_genes": sum(len(invalid_genes) for _, invalid_genes in [validate_genes(all_genes) for all_genes in []])
            },
            "raw_results": raw_results,
            "final_results": final_results
        }
        
    except Exception as e:
        return {
            "status": "error",
            "error_message": str(e),
            "raw_results": {},
            "final_results": {}
        }


@tool
def coxpres_coexpression_search(gene_list: List[str]) -> Dict[str, Any]:
    """
    Search and process COXPRESdb coexpression database information. COXPRESdb provides gene function predictions based on gene coexpression relationships.
    
    Args:
        gene_list: List of gene symbols to search for coexpression partners
    
    Returns:
        Dictionary containing status, raw results, and final results
    """
    try:
        import urllib.parse
        import time
        
        final_results = {}
        raw_results = {}
        
        # Validate input genes
        valid_genes, invalid_genes = validate_genes(gene_list)
        
        if not valid_genes:
            return {
                "status": "error",
                "error_message": "No valid genes found",
                "raw_results": {},
                "final_results": {}
            }
        
        for gene in valid_genes:
            print(f"\nProcessing gene: {gene}")
            
            try:
                # Build COXPRESdb query URL
                base_url = "https://coxpresdb.jp/cgi-bin/search.cgi"
                
                # Query parameters
                params = {
                    'mode': 'human',
                    'genename': gene,
                    'format': 'text'
                }
                
                # Encode parameters
                query_string = urllib.parse.urlencode(params)
                url = f"{base_url}?{query_string}"
                
                # Send request
                response = requests.get(url, timeout=30)
                response.raise_for_status()
                
                # Parse response
                coexpressed_genes = []
                correlation_scores = []
                
                lines = response.text.strip().split('\n')
                for line in lines[1:]:  # Skip header line
                    if line.strip():
                        parts = line.strip().split('\t')
                        if len(parts) >= 2:
                            coexp_gene = parts[0].strip()
                            try:
                                correlation = float(parts[1].strip())
                                if correlation > 0.5:  # Only keep genes with correlation > 0.5
                                    coexpressed_genes.append(coexp_gene)
                                    correlation_scores.append(correlation)
                            except ValueError:
                                continue
                
                # Validate coexpressed genes
                if coexpressed_genes:
                    valid_coexp_genes, invalid_coexp_genes = validate_genes(coexpressed_genes)
                    
                    # Filter scores for valid genes
                    valid_scores = []
                    final_valid_genes = []
                    valid_coexp_set = set(valid_coexp_genes)
                    
                    for i, coexp_gene in enumerate(coexpressed_genes):
                        if coexp_gene in valid_coexp_set:
                            final_valid_genes.append(coexp_gene)
                            valid_scores.append(correlation_scores[i])
                    
                    # Store raw results
                    raw_results[gene] = {
                        "total_coexpressed": len(coexpressed_genes),
                        "valid_coexpressed": len(final_valid_genes),
                        "invalid_coexpressed": len(invalid_coexp_genes)
                    }
                    
                    # Normalize scores
                    if valid_scores:
                        normalized_scores = normalize_scores(valid_scores)
                        final_results[gene] = [
                            {"gene": coexp_gene, "score": norm_score}
                            for coexp_gene, norm_score in zip(final_valid_genes, normalized_scores)
                        ]
                    else:
                        final_results[gene] = []
                else:
                    raw_results[gene] = {
                        "total_coexpressed": 0,
                        "valid_coexpressed": 0,
                        "invalid_coexpressed": 0
                    }
                    final_results[gene] = []
                
                # Add delay to avoid too frequent requests
                time.sleep(1)
                
            except requests.exceptions.RequestException as e:
                print(f"COXPRESdb API unavailable for gene {gene} (this is expected): {str(e)}")
                raw_results[gene] = {
                    "note": "COXPRESdb API temporarily unavailable",
                    "total_coexpressed": 0,
                    "valid_coexpressed": 0
                }
                final_results[gene] = []
                continue
            except Exception as e:
                print(f"Unexpected error for gene {gene}: {str(e)}")
                raw_results[gene] = {
                    "error": str(e),
                    "total_coexpressed": 0,
                    "valid_coexpressed": 0
                }
                final_results[gene] = []
                continue
        
        return {
            "status": "success",
            "metadata": {
                "genes_processed": len(valid_genes),
                "invalid_input_genes": invalid_genes
            },
            "raw_results": raw_results,
            "final_results": final_results
        }
        
    except Exception as e:
        return {
            "status": "error",
            "error_message": str(e),
            "raw_results": {},
            "final_results": {}
        }


@tool
def ensembl_paralog_search(gene_list: List[str], species: str = "human") -> Dict[str, Any]:
    """
    Identify paralog genes using the Ensembl API. Paralogs are genes within the same species that evolved from a common ancestral gene through duplication events. This tool helps discover evolutionary relationships between genes.
    
    Args:
        gene_list: List of gene symbols to search for paralogs
        species: The species to search paralogs for (default: "human")
    
    Returns:
        Dictionary containing paralog genes for each input gene with normalized relevance scores
    """
    
    base_url = "https://rest.ensembl.org"
    species_map = {
        "human": "homo_sapiens",
        "mouse": "mus_musculus", 
        "rat": "rattus_norvegicus",
        "zebrafish": "danio_rerio"
    }
    
    def get_gene_id(gene_symbol: str) -> Optional[str]:
        """Fetch the Ensembl gene ID for a given gene symbol"""
        species_name = species_map.get(species.lower(), "homo_sapiens")
        try:
            response = requests.get(
                f"{base_url}/lookup/symbol/{species_name}/{gene_symbol}",
                headers={"Content-Type": "application/json"},
                timeout=10
            )
            
            if response.status_code == 200:
                data = response.json()
                return data.get("id")
            else:
                print(f"Failed to retrieve gene ID for {gene_symbol}. Status code: {response.status_code}")
                return None
        except Exception as e:
            print(f"Error retrieving gene ID for '{gene_symbol}': {e}")
            return None
    
    def get_gene_symbol_from_id(gene_id: str) -> Optional[str]:
        """Fetch the gene symbol for a given Ensembl gene ID"""
        try:
            response = requests.get(
                f"{base_url}/lookup/id/{gene_id}",
                headers={"Content-Type": "application/json"},
                timeout=10
            )
            
            if response.status_code == 200:
                data = response.json()
                return data.get("display_name")
            else:
                print(f"Failed to retrieve gene symbol for ID {gene_id}. Status code: {response.status_code}")
                return None
        except Exception as e:
            print(f"Error retrieving gene symbol for ID '{gene_id}': {e}")
            return None
    
    def get_paralogs(gene_id: str) -> List[Dict[str, Any]]:
        """Fetch paralogs for a given Ensembl gene ID"""
        species_name = species_map.get(species.lower(), "homo_sapiens")
        try:
            url = f"{base_url}/homology/id/{species_name}/{gene_id}"
            
            params = {
                "type": "paralogues",
                "format": "condensed", 
                "sequence": "none"
            }
            
            response = requests.get(
                url,
                params=params,
                headers={"Accept": "application/json"},
                timeout=15
            )
            
            if response.status_code == 200:
                data = response.json()
                homologies = data.get("data", [{}])[0].get("homologies", [])
                
                paralogs = []
                for homology in homologies:
                    paralog_id = homology.get("id")
                    if paralog_id:
                        gene_symbol = get_gene_symbol_from_id(paralog_id)
                        
                        paralog_info = {
                            "gene_symbol": gene_symbol or "",
                            "gene_id": paralog_id,
                            "similarity": homology.get("dn_ds", 0)
                        }
                        paralogs.append(paralog_info)
                
                return paralogs
            else:
                print(f"Failed to retrieve paralogs for gene ID {gene_id}. Status code: {response.status_code}")
                return []
        except Exception as e:
            print(f"Error retrieving paralogs for gene ID '{gene_id}': {e}")
            return []
    
    def get_paralogs_by_symbol(gene_symbol: str) -> List[Dict[str, Any]]:
        """Fetch paralogs for a given gene symbol"""
        gene_id = get_gene_id(gene_symbol)
        if not gene_id:
            print(f"Could not find Ensembl gene ID for {gene_symbol}")
            return []
        
        return get_paralogs(gene_id)
    
    try:
        final_results = {}
        raw_results = {}
        
        for gene_symbol in gene_list:
            # Get paralogs for the gene
            paralogs = get_paralogs_by_symbol(gene_symbol)
            
            # Store raw results
            raw_results[gene_symbol] = paralogs
            
            # Extract paralog gene symbols for validation
            paralog_genes = [p["gene_symbol"] for p in paralogs if p["gene_symbol"]]
            
            # Validate output paralog genes
            valid_paralogs, invalid_paralogs = validate_genes(paralog_genes)
            
            # Collect paralog data with fixed initial score of 1
            valid_paralogs_data = [
                {
                    "gene": paralog["gene_symbol"],
                    "score": 1
                }
                for paralog in paralogs 
                if paralog["gene_symbol"] and paralog["gene_symbol"] in valid_paralogs
            ]
            
            # Extract scores for normalization
            initial_scores = [p["score"] for p in valid_paralogs_data]
            
            # Normalize scores
            normalized_scores = normalize_scores(initial_scores)
            
            # Apply normalized scores to results
            for i, paralog in enumerate(valid_paralogs_data):
                paralog["score"] = normalized_scores[i]
                
            # Store final results with normalized scores
            final_results[gene_symbol] = valid_paralogs_data
        
        return {
            "status": "success",
            "metadata": {
                "genes_processed": len(gene_list),
                "species": species
            },
            "raw_results": raw_results,
            "final_results": final_results
        }
    
    except Exception as e:
        return {
            "status": "error",
            "error_message": str(e),
            "raw_results": {},
            "final_results": {}
        }


@tool
def gsea_hallmark_search(
    query_list: List[str], 
    json_directory: str = "resource/GSEA",
    model_name: str = "gemini-2.5-pro"
) -> Dict[str, Any]:
    """
    Search and extract gene set information from MSigDB JSON files. The MSigDB (Molecular Signatures Database) contains collections of annotated gene sets for use with gene set enrichment analysis including hallmark pathways, curated gene sets, and regulatory motifs.
    
    Args:
        query_list: List of pathway names, hallmarks, chromosome regions, or other gene set identifiers
        json_directory: Path to directory containing MSigDB JSON files (default: "resource/GSEA")
        model_name: Model name for LLM analysis, defaults to "gemini-2.5-pro"
    
    Returns:
        Dictionary containing genes associated with each gene set query and normalized relevance scores
    """
    import json
    
    def load_json_files() -> List[Dict[str, Any]]:
        """Load all JSON files from the specified directory"""
        data_list = []
        try:
            for file_name in os.listdir(json_directory):
                if file_name.lower().endswith(".json"):
                    file_path = os.path.join(json_directory, file_name)
                    try:
                        with open(file_path, 'r', encoding='utf-8') as f:
                            data_list.append(json.load(f))
                    except Exception as e:
                        print(f"Could not parse {file_path} as JSON: {e}")
        except FileNotFoundError:
            print(f"GSEA directory not found: {json_directory}")
        return data_list

    def extract_all_pathway_names(data_files: List[Dict[str, Any]]) -> List[str]:
        """Extract all pathway names from the loaded JSON files"""
        pathway_names = []
        for data_file in data_files:
            if isinstance(data_file, dict):
                pathway_names.extend(list(data_file.keys()))
        return pathway_names

    def match_pathways_with_llm(queries: List[str], all_pathways: List[str]) -> Dict[str, str]:
        """Use LLM to find the most relevant pathway names for multiple queries"""
        prompt = f"""
You are an assistant to biologists. Given multiple user queries, your task is to identify the SINGLE most relevant MSigDB pathway name from the provided list for EACH query.

Think step by step for each query and select only the most relevant pathway name. Please format your response following the response format and make sure it is parsable by JSON.

User queries:
{chr(10).join([f"{i+1}. {query}" for i, query in enumerate(queries)])}

Available pathway names:
{chr(10).join(all_pathways)}

Response format:
{{
"thoughts": "your step-by-step thinking process for each query",
"pathway_matches": [
    {{
        "query": "user query",
        "matched_pathway_name": "matched pathway name or NA if no relevant pathway found"
    }}
]
}}
"""
        
        try:
            result = json_llm_call(prompt, model_name=model_name)
            matched_pathways_list = result.get('pathway_matches', [])
            matched_pathways = {}
            for item in matched_pathways_list:
                if isinstance(item, dict) and 'query' in item and 'matched_pathway_name' in item:
                    matched_pathways[item['query']] = item['matched_pathway_name']
            return matched_pathways
        except Exception as e:
            print(f"Error matching pathways with LLM: {str(e)}")
            return {}

    def find_genes_for_pathways(matched_pathways: Dict[str, str], data_files: List[Dict[str, Any]]) -> Dict[str, List[str]]:
        """Find genes for multiple matched pathways"""
        results = {}
        
        for query, pathway_name in matched_pathways.items():
            found_genes = set()
            
            if pathway_name and pathway_name != "NA":
                # Look up genes for the matched pathway
                for data_file in data_files:
                    if isinstance(data_file, dict) and pathway_name in data_file:
                        entry = data_file[pathway_name]
                        if isinstance(entry, dict):
                            genes = entry.get("geneSymbols", [])
                            if isinstance(genes, list):
                                found_genes.update(genes)
            
            results[query] = sorted(found_genes)
        
        return results

    try:
        # Load GSEA data files
        data_files = load_json_files()
        if not data_files:
            return {
                "status": "error",
                "error_message": f"No GSEA JSON files found in {json_directory}",
                "raw_results": {},
                "final_results": {}
            }

        # Extract all pathway names
        all_pathways = extract_all_pathway_names(data_files)
        if not all_pathways:
            return {
                "status": "error",
                "error_message": "No pathway names found in JSON files",
                "raw_results": {},
                "final_results": {}
            }

        final_results = {}
        raw_results = {}
        
        # Match all pathways with LLM
        matched_pathways = match_pathways_with_llm(query_list, all_pathways)
        
        # Find genes for all matched pathways
        genes_by_query = find_genes_for_pathways(matched_pathways, data_files)
        
        for query in query_list:
            # Get genes for the current query
            found_genes = genes_by_query.get(query, [])
            
            # Validate genes 
            valid_genes, invalid_genes = validate_genes(found_genes)
            
            # Store raw results
            raw_results[query] = {
                "matched_pathway": matched_pathways.get(query, ""),
                "total_genes_found": len(found_genes),
                "valid_genes": len(valid_genes),
                "invalid_genes": len(invalid_genes)
            }
            
            # Assign initial raw scores of 1.0 to each gene
            raw_scores = [1.0] * len(valid_genes)
            
            # Normalize scores
            normalized_scores = normalize_scores(raw_scores, temperature=1.0)
            
            # Create final results with normalized scores
            final_results[query] = [
                {"gene": gene, "score": score} 
                for gene, score in zip(valid_genes, normalized_scores)
            ]
        
        return {
            "status": "success",
            "metadata": {
                "queries_processed": len(query_list),
                "pathways_matched": {
                    query: matched_pathways.get(query, "")
                    for query in query_list
                },
                "genes_found": {
                    query: len(final_results.get(query, []))
                    for query in query_list
                }
            },
            "raw_results": raw_results,
            "final_results": final_results
        }
        
    except Exception as e:
        return {
            "status": "error",
            "error_message": str(e),
            "raw_results": {},
            "final_results": {}
        }


@tool
def wikipathways_search(
    query_list: List[str], 
    json_directory: str = "resource/WikiPathways",
    model_name: str = "gemini-2.5-pro"
) -> Dict[str, Any]:
    """
    Search and extract gene set information from WikiPathways JSON files. WikiPathways is a database of biological pathways maintained by the community, containing diverse pathway information across multiple organisms including metabolic pathways, signaling cascades, and disease pathways.
    
    Args:
        query_list: List of pathway names, biological processes, or other pathway identifiers
        json_directory: Path to directory containing WikiPathways JSON files (default: "resource/WikiPathways")
        model_name: Model name for LLM analysis, defaults to "gemini-2.5-pro"
    
    Returns:
        Dictionary containing genes associated with each pathway query and normalized relevance scores
    """
    import json
    
    def load_json_files() -> List[Dict[str, Any]]:
        """Load all JSON files from the specified directory"""
        data_list = []
        try:
            for file_name in os.listdir(json_directory):
                if file_name.lower().endswith(".json"):
                    file_path = os.path.join(json_directory, file_name)
                    try:
                        with open(file_path, 'r', encoding='utf-8') as f:
                            data_list.append(json.load(f))
                    except Exception as e:
                        print(f"Could not parse {file_path} as JSON: {e}")
        except FileNotFoundError:
            print(f"WikiPathways directory not found: {json_directory}")
        return data_list

    def extract_all_pathway_names(data_files: List[Dict[str, Any]]) -> List[str]:
        """Extract all pathway names from the loaded JSON files"""
        pathway_names = []
        for data_file in data_files:
            if isinstance(data_file, dict):
                pathway_names.extend(list(data_file.keys()))
        return pathway_names

    def match_pathways_with_llm(queries: List[str], all_pathways: List[str]) -> Dict[str, str]:
        """Use LLM to find the most relevant pathway names for multiple queries"""
        prompt = f"""
You are an assistant to biologists. Given multiple user queries, your task is to identify the SINGLE most relevant WikiPathways pathway name from the provided list for EACH query.

Think step by step for each query and select only the most relevant pathway name. Please format your response following the response format and make sure it is parsable by JSON.

User queries:
{chr(10).join([f"{i+1}. {query}" for i, query in enumerate(queries)])}

Available pathway names:
{chr(10).join(all_pathways)}

Response format:
{{
"thoughts": "your step-by-step thinking process for each query",
"pathway_matches": [
    {{
        "query": "user query",
        "matched_pathway_name": "matched pathway name or NA if no relevant pathway found"
    }}
]
}}
"""
        
        try:
            result = json_llm_call(prompt, model_name=model_name)
            matched_pathways_list = result.get('pathway_matches', [])
            matched_pathways = {}
            for item in matched_pathways_list:
                if isinstance(item, dict) and 'query' in item and 'matched_pathway_name' in item:
                    matched_pathways[item['query']] = item['matched_pathway_name']
            return matched_pathways
        except Exception as e:
            print(f"Error matching pathways with LLM: {str(e)}")
            return {}

    def find_genes_for_pathways(matched_pathways: Dict[str, str], data_files: List[Dict[str, Any]]) -> Dict[str, List[str]]:
        """Find genes for multiple matched pathways"""
        results = {}
        
        for query, pathway_name in matched_pathways.items():
            found_genes = set()
            
            if pathway_name and pathway_name != "NA":
                # Look up genes for the matched pathway
                for data_file in data_files:
                    if isinstance(data_file, dict) and pathway_name in data_file:
                        entry = data_file[pathway_name]
                        if isinstance(entry, dict):
                            genes = entry.get("geneSymbols", [])
                            if isinstance(genes, list):
                                found_genes.update(genes)
            
            results[query] = sorted(found_genes)
        
        return results

    try:
        # Load WikiPathways data files
        data_files = load_json_files()
        if not data_files:
            return {
                "status": "error",
                "error_message": f"No WikiPathways JSON files found in {json_directory}",
                "raw_results": {},
                "final_results": {}
            }

        # Extract all pathway names
        all_pathways = extract_all_pathway_names(data_files)
        if not all_pathways:
            return {
                "status": "error",
                "error_message": "No pathway names found in JSON files",
                "raw_results": {},
                "final_results": {}
            }

        final_results = {}
        raw_results = {}
        
        # Match all pathways with LLM
        matched_pathways = match_pathways_with_llm(query_list, all_pathways)
        
        # Find genes for all matched pathways
        genes_by_query = find_genes_for_pathways(matched_pathways, data_files)
        
        for query in query_list:
            # Get genes for the current query
            found_genes = genes_by_query.get(query, [])
            
            # Validate genes 
            valid_genes, invalid_genes = validate_genes(found_genes)
            
            # Store raw results
            raw_results[query] = {
                "matched_pathway": matched_pathways.get(query, ""),
                "total_genes_found": len(found_genes),
                "valid_genes": len(valid_genes),
                "invalid_genes": len(invalid_genes)
            }
            
            # Assign initial raw scores of 1.0 to each gene
            raw_scores = [1.0] * len(valid_genes)
            
            # Normalize scores
            normalized_scores = normalize_scores(raw_scores, temperature=1.0)
            
            # Create final results with normalized scores
            final_results[query] = [
                {"gene": gene, "score": score} 
                for gene, score in zip(valid_genes, normalized_scores)
            ]
        
        return {
            "status": "success",
            "metadata": {
                "queries_processed": len(query_list),
                "pathways_matched": {
                    query: matched_pathways.get(query, "")
                    for query in query_list
                },
                "genes_found": {
                    query: len(final_results.get(query, []))
                    for query in query_list
                }
            },
            "raw_results": raw_results,
            "final_results": final_results
        }
        
    except Exception as e:
        return {
            "status": "error",
            "error_message": str(e),
            "raw_results": {},
            "final_results": {}
        }


@tool
def reactome_pathway_search(
    query_list: List[str], 
    json_directory: str = "resource/Reactome",
    model_name: str = "gemini-2.5-pro"
) -> Dict[str, Any]:
    """
    Search and extract gene set information from Reactome JSON files. Reactome is an open-source, curated and peer-reviewed pathway database that provides detailed information about biological pathways, reactions, and cellular processes across different species.
    
    Args:
        query_list: List of pathway names, reactions, or cellular process identifiers
        json_directory: Path to directory containing Reactome JSON files (default: "resource/Reactome")
        model_name: Model name for LLM analysis, defaults to "gemini-2.5-pro"
    
    Returns:
        Dictionary containing genes associated with each pathway/reaction query and normalized relevance scores
    """
    import json
    
    def load_json_files() -> List[Dict[str, Any]]:
        """Load all JSON files from the specified directory"""
        data_list = []
        try:
            for file_name in os.listdir(json_directory):
                if file_name.lower().endswith(".json"):
                    file_path = os.path.join(json_directory, file_name)
                    try:
                        with open(file_path, 'r', encoding='utf-8') as f:
                            data_list.append(json.load(f))
                    except Exception as e:
                        print(f"Could not parse {file_path} as JSON: {e}")
        except FileNotFoundError:
            print(f"Reactome directory not found: {json_directory}")
        return data_list

    def extract_all_pathway_names(data_files: List[Dict[str, Any]]) -> List[str]:
        """Extract all pathway names from the loaded JSON files"""
        pathway_names = []
        for data_file in data_files:
            if isinstance(data_file, dict):
                pathway_names.extend(list(data_file.keys()))
        return pathway_names

    def match_pathways_with_llm(queries: List[str], all_pathways: List[str]) -> Dict[str, str]:
        """Use LLM to find the most relevant pathway names for multiple queries"""
        prompt = f"""
You are an assistant to biologists. Given multiple user queries, your task is to identify the SINGLE most relevant Reactome pathway name from the provided list for EACH query.

Think step by step for each query and select only the most relevant pathway name. Please format your response following the response format and make sure it is parsable by JSON.

User queries:
{chr(10).join([f"{i+1}. {query}" for i, query in enumerate(queries)])}

Available pathway names:
{chr(10).join(all_pathways)}

Response format:
{{
"thoughts": "your step-by-step thinking process for each query",
"pathway_matches": [
    {{
        "query": "user query",
        "matched_pathway_name": "matched pathway name or NA if no relevant pathway found"
    }}
]
}}
"""
        
        try:
            result = json_llm_call(prompt, model_name=model_name)
            matched_pathways_list = result.get('pathway_matches', [])
            matched_pathways = {}
            for item in matched_pathways_list:
                if isinstance(item, dict) and 'query' in item and 'matched_pathway_name' in item:
                    matched_pathways[item['query']] = item['matched_pathway_name']
            return matched_pathways
        except Exception as e:
            print(f"Error matching pathways with LLM: {str(e)}")
            return {}

    def find_genes_for_pathways(matched_pathways: Dict[str, str], data_files: List[Dict[str, Any]]) -> Dict[str, List[str]]:
        """Find genes for multiple matched pathways"""
        results = {}
        
        for query, pathway_name in matched_pathways.items():
            found_genes = set()
            
            if pathway_name and pathway_name != "NA":
                # Look up genes for the matched pathway
                for data_file in data_files:
                    if isinstance(data_file, dict) and pathway_name in data_file:
                        entry = data_file[pathway_name]
                        if isinstance(entry, dict):
                            genes = entry.get("geneSymbols", [])
                            if isinstance(genes, list):
                                found_genes.update(genes)
            
            results[query] = sorted(found_genes)
        
        return results

    try:
        # Load Reactome data files
        data_files = load_json_files()
        if not data_files:
            return {
                "status": "error",
                "error_message": f"No Reactome JSON files found in {json_directory}",
                "raw_results": {},
                "final_results": {}
            }

        # Extract all pathway names
        all_pathways = extract_all_pathway_names(data_files)
        if not all_pathways:
            return {
                "status": "error",
                "error_message": "No pathway names found in JSON files",
                "raw_results": {},
                "final_results": {}
            }

        final_results = {}
        raw_results = {}
        
        # Match all pathways with LLM
        matched_pathways = match_pathways_with_llm(query_list, all_pathways)
        
        # Find genes for all matched pathways
        genes_by_query = find_genes_for_pathways(matched_pathways, data_files)
        
        for query in query_list:
            # Get genes for the current query
            found_genes = genes_by_query.get(query, [])
            
            # Validate genes 
            valid_genes, invalid_genes = validate_genes(found_genes)
            
            # Store raw results
            raw_results[query] = {
                "matched_pathway": matched_pathways.get(query, ""),
                "total_genes_found": len(found_genes),
                "valid_genes": len(valid_genes),
                "invalid_genes": len(invalid_genes)
            }
            
            # Assign initial raw scores of 1.0 to each gene
            raw_scores = [1.0] * len(valid_genes)
            
            # Normalize scores
            normalized_scores = normalize_scores(raw_scores, temperature=1.0)
            
            # Create final results with normalized scores
            final_results[query] = [
                {"gene": gene, "score": score} 
                for gene, score in zip(valid_genes, normalized_scores)
            ]
        
        return {
            "status": "success",
            "metadata": {
                "queries_processed": len(query_list),
                "pathways_matched": {
                    query: matched_pathways.get(query, "")
                    for query in query_list
                },
                "genes_found": {
                    query: len(final_results.get(query, []))
                    for query in query_list
                }
            },
            "raw_results": raw_results,
            "final_results": final_results
        }
        
    except Exception as e:
        return {
            "status": "error",
            "error_message": str(e),
            "raw_results": {},
            "final_results": {}
        }


@tool
def cancer_biomarkers_search(
    query_list: List[str], 
    json_path: str = "resource/Open_target/cancerbiomarkers.json",
    model_name: str = "gemini-2.5-pro"
) -> Dict[str, Any]:
    """
    Search and extract gene information from Cancer Biomarkers database. The Cancer Biomarkers database features biomarkers of drug sensitivity, resistance, and toxicity for drugs targeting specific targets in cancer, curated by clinical and scientific experts in precision oncology, and classified by cancer type.
    
    Args:
        query_list: List of cancer types or disease names to search for associated biomarker genes
        json_path: Path to Cancer Biomarkers JSON file (default: "resource/Open_target/cancerbiomarkers.json")
        model_name: Model name for LLM analysis, defaults to "gemini-2.5-pro"
    
    Returns:
        Dictionary containing genes associated with each cancer type query and normalized relevance scores
    """
    import json
    
    def load_json_data() -> List[Dict[str, Any]]:
        """Load the Cancer Biomarkers JSON data (line-delimited JSON format)"""
        data_list = []
        try:
            with open(json_path, 'r', encoding='utf-8') as f:
                # Each line is a separate JSON object
                for line in f:
                    line = line.strip()
                    if line:  # Skip empty lines
                        try:
                            data_list.append(json.loads(line))
                        except json.JSONDecodeError:
                            continue
        except FileNotFoundError:
            print(f"Cancer biomarkers file not found: {json_path}")
        except Exception as e:
            print(f"Could not parse {json_path} as JSON: {e}")
        return data_list

    def extract_all_disease_names(data: List[Dict[str, Any]]) -> List[str]:
        """Extract all unique disease names from the loaded JSON data"""
        disease_names = set()
        for entry in data:
            if isinstance(entry, dict) and "diseaseFromSource" in entry:
                disease_names.add(entry["diseaseFromSource"])
        return sorted(list(disease_names))

    def match_diseases_with_llm(queries: List[str], all_diseases: List[str]) -> Dict[str, str]:
        """Use LLM to find the most relevant disease names for multiple queries"""
        prompt = f"""
You are an assistant to oncologists. Given multiple user queries, your task is to identify the SINGLE most relevant cancer or disease name from the provided list for EACH query.

Think step by step for each query and select only the most relevant disease name. Please format your response following the response format and make sure it is parsable by JSON.

User queries:
{chr(10).join([f"{i+1}. {query}" for i, query in enumerate(queries)])}

Available disease names:
{chr(10).join(all_diseases)}

Response format:
{{
"thoughts": "your step-by-step thinking process for each query",
"disease_matches": [
    {{
        "query": "user query",
        "matched_disease_name": "matched disease name or NA if no relevant disease found"
    }}
]
}}
"""
        
        try:
            result = json_llm_call(prompt, model_name=model_name)
            matched_diseases_list = result.get('disease_matches', [])
            matched_diseases = {}
            for item in matched_diseases_list:
                if isinstance(item, dict) and 'query' in item and 'matched_disease_name' in item:
                    matched_diseases[item['query']] = item['matched_disease_name']
            return matched_diseases
        except Exception as e:
            print(f"Error matching diseases with LLM: {str(e)}")
            return {}

    def find_genes_for_diseases(matched_diseases: Dict[str, str], data: List[Dict[str, Any]]) -> Dict[str, List[str]]:
        """Find genes for multiple matched diseases"""
        results = {}
        
        for query, disease_name in matched_diseases.items():
            found_genes = set()
            
            if disease_name and disease_name != "NA":
                # Look up genes for the matched disease
                for entry in data:
                    if isinstance(entry, dict) and entry.get("diseaseFromSource") == disease_name:
                        target_gene = entry.get("targetFromSourceId")
                        if target_gene:
                            found_genes.add(target_gene)
            
            results[query] = sorted(found_genes)
        
        return results

    try:
        # Load Cancer Biomarkers data
        data = load_json_data()
        if not data:
            return {
                "status": "error",
                "error_message": f"No cancer biomarkers data found in {json_path}",
                "raw_results": {},
                "final_results": {}
            }

        # Extract all disease names
        all_diseases = extract_all_disease_names(data)
        if not all_diseases:
            return {
                "status": "error",
                "error_message": "No disease names found in data",
                "raw_results": {},
                "final_results": {}
            }

        final_results = {}
        raw_results = {}
        
        # Match all diseases with LLM
        matched_diseases = match_diseases_with_llm(query_list, all_diseases)
        
        # Find genes for all matched diseases
        genes_by_query = find_genes_for_diseases(matched_diseases, data)
        
        for query in query_list:
            # Get genes for the current query
            found_genes = genes_by_query.get(query, [])
            
            # Validate genes 
            valid_genes, invalid_genes = validate_genes(found_genes)
            
            # Store raw results
            raw_results[query] = {
                "matched_disease": matched_diseases.get(query, ""),
                "total_genes_found": len(found_genes),
                "valid_genes": len(valid_genes),
                "invalid_genes": len(invalid_genes)
            }
            
            # Assign initial raw scores of 1.0 to each gene
            raw_scores = [1.0] * len(valid_genes)
            
            # Normalize scores
            normalized_scores = normalize_scores(raw_scores, temperature=1.0)
            
            # Create final results with normalized scores
            final_results[query] = [
                {"gene": gene, "score": score} 
                for gene, score in zip(valid_genes, normalized_scores)
            ]
        
        return {
            "status": "success",
            "metadata": {
                "queries_processed": len(query_list),
                "diseases_matched": {
                    query: matched_diseases.get(query, "")
                    for query in query_list
                },
                "genes_found": {
                    query: len(final_results.get(query, []))
                    for query in query_list
                }
            },
            "raw_results": raw_results,
            "final_results": final_results
        }
        
    except Exception as e:
        return {
            "status": "error",
            "error_message": str(e),
            "raw_results": {},
            "final_results": {}
        }


@tool
def clingen_search(
    query_list: List[str], 
    json_path: str = "resource/Open_target/clingen.json",
    model_name: str = "gemini-2.5-pro"
) -> Dict[str, Any]:
    """
    Search and extract gene information from ClinGen database. The Clinical Genome Resource (ClinGen) Gene-Disease Validity Curation evaluates the strength of evidence supporting or refuting claims that variation in a particular gene causes a particular disease, providing a framework to assess clinical validity in a semi-quantitative manner.
    
    Args:
        query_list: List of diseases or conditions to search for associated genes with clinical evidence
        json_path: Path to ClinGen JSON file (default: "resource/Open_target/clingen.json")
        model_name: Model name for LLM analysis, defaults to "gemini-2.5-pro"
    
    Returns:
        Dictionary containing genes associated with each disease query and normalized relevance scores based on clinical evidence strength
    """
    import json
    
    # Confidence to score mapping based on ClinGen classification
    confidence_scores = {
        "No reported evidence": 0.01,
        "Refuted": 0.01,
        "Disputed": 0.01,
        "Limited": 0.01,
        "Moderate": 0.5,
        "Strong": 1.0,
        "Definitive": 1.0
    }
    
    def load_json_data() -> List[Dict[str, Any]]:
        """Load the ClinGen JSON data (line-delimited JSON format)"""
        data_list = []
        try:
            with open(json_path, 'r', encoding='utf-8') as f:
                # Each line is a separate JSON object
                for line in f:
                    line = line.strip()
                    if line:  # Skip empty lines
                        try:
                            data_list.append(json.loads(line))
                        except json.JSONDecodeError:
                            continue
        except FileNotFoundError:
            print(f"ClinGen file not found: {json_path}")
        except Exception as e:
            print(f"Could not parse {json_path} as JSON: {e}")
        return data_list

    def extract_all_disease_names(data: List[Dict[str, Any]]) -> List[str]:
        """Extract all unique disease names from the loaded JSON data"""
        disease_names = set()
        for entry in data:
            if isinstance(entry, dict) and "diseaseFromSource" in entry:
                disease_names.add(entry["diseaseFromSource"])
        return sorted(list(disease_names))

    def match_diseases_with_llm(queries: List[str], all_diseases: List[str]) -> Dict[str, str]:
        """Use LLM to find the most relevant disease names for multiple queries"""
        prompt = f"""
You are an assistant to medical genetics experts. Given multiple user queries, your task is to identify the SINGLE most relevant disease name from the provided list for EACH query.

Think step by step for each query and select only the most relevant disease name. Please format your response following the response format and make sure it is parsable by JSON.

User queries:
{chr(10).join([f"{i+1}. {query}" for i, query in enumerate(queries)])}

Available disease names:
{chr(10).join(all_diseases)}

Response format:
{{
"thoughts": "your step-by-step thinking process for each query",
"disease_matches": [
    {{
        "query": "user query",
        "matched_disease_name": "matched disease name or NA if no relevant disease found"
    }}
]
}}
"""
        
        try:
            result = json_llm_call(prompt, model_name=model_name)
            matched_diseases_list = result.get('disease_matches', [])
            matched_diseases = {}
            for item in matched_diseases_list:
                if isinstance(item, dict) and 'query' in item and 'matched_disease_name' in item:
                    matched_diseases[item['query']] = item['matched_disease_name']
            return matched_diseases
        except Exception as e:
            print(f"Error matching diseases with LLM: {str(e)}")
            return {}

    def find_genes_for_diseases(matched_diseases: Dict[str, str], data: List[Dict[str, Any]]) -> Dict[str, List[Dict[str, Any]]]:
        """Find genes for multiple matched diseases with confidence levels"""
        results = {}
        
        for query, disease_name in matched_diseases.items():
            found_genes = []
            
            if disease_name and disease_name != "NA":
                # Look up genes for the matched disease
                for entry in data:
                    if isinstance(entry, dict) and entry.get("diseaseFromSource") == disease_name:
                        target_gene = entry.get("targetFromSourceId")
                        confidence = entry.get("confidence", "No reported evidence")
                        if target_gene:
                            found_genes.append({
                                "gene": target_gene,
                                "confidence": confidence
                            })
            
            results[query] = found_genes
        
        return results

    try:
        # Load ClinGen data
        data = load_json_data()
        if not data:
            return {
                "status": "error",
                "error_message": f"No ClinGen data found in {json_path}",
                "raw_results": {},
                "final_results": {}
            }

        # Extract all disease names
        all_diseases = extract_all_disease_names(data)
        if not all_diseases:
            return {
                "status": "error",
                "error_message": "No disease names found in data",
                "raw_results": {},
                "final_results": {}
            }

        final_results = {}
        raw_results = {}
        
        # Match all diseases with LLM
        matched_diseases = match_diseases_with_llm(query_list, all_diseases)
        
        # Find genes for all matched diseases
        genes_by_query = find_genes_for_diseases(matched_diseases, data)
        
        for query in query_list:
            # Get genes for the current query
            gene_results = genes_by_query.get(query, [])
            
            # Extract gene symbols and confidence
            found_genes = [g["gene"] for g in gene_results]
            confidence_levels = [g["confidence"] for g in gene_results]
            
            # Validate genes 
            valid_genes, invalid_genes = validate_genes(found_genes)
            
            # Store raw results
            raw_results[query] = {
                "matched_disease": matched_diseases.get(query, ""),
                "total_genes_found": len(found_genes),
                "valid_genes": len(valid_genes),
                "invalid_genes": len(invalid_genes)
            }
            
            # Create a mapping of valid genes to their confidence
            # Use a dictionary to handle duplicates - keep the highest confidence version
            valid_gene_confidence = {}
            for i, gene in enumerate(found_genes):
                if gene in valid_genes:
                    current_confidence = confidence_levels[i]
                    current_score = confidence_scores.get(current_confidence, 0.01)
                    
                    # If gene already exists, only replace if current confidence score is higher
                    if gene not in valid_gene_confidence or current_score > confidence_scores.get(valid_gene_confidence[gene], 0.01):
                        valid_gene_confidence[gene] = current_confidence
            
            # Assign raw scores based on confidence levels using deduplicated genes
            raw_scores = []
            valid_genes_list = list(valid_gene_confidence.keys())  # Using deduplicated genes
            
            for gene in valid_genes_list:
                confidence = valid_gene_confidence.get(gene, "No reported evidence")
                score = confidence_scores.get(confidence, 0.01)
                raw_scores.append(score)
            
            # Normalize scores
            normalized_scores = normalize_scores(raw_scores, temperature=1.0)
            
            # Create final results with normalized scores
            final_results[query] = [
                {"gene": gene, "score": score} 
                for gene, score in zip(valid_genes_list, normalized_scores)
            ]
        
        return {
            "status": "success",
            "metadata": {
                "queries_processed": len(query_list),
                "diseases_matched": {
                    query: matched_diseases.get(query, "")
                    for query in query_list
                },
                "genes_found": {
                    query: len(final_results.get(query, []))
                    for query in query_list
                },
                "confidence_levels": ["Definitive", "Strong", "Moderate", "Limited", "Disputed", "Refuted", "No reported evidence"]
            },
            "raw_results": raw_results,
            "final_results": final_results
        }
        
    except Exception as e:
        return {
            "status": "error",
            "error_message": str(e),
            "raw_results": {},
            "final_results": {}
        }


@tool
def gene2phenotype_search(
    query_list: List[str], 
    json_path: str = "resource/Open_target/gene2phenotype.json",
    model_name: str = "gemini-2.5-pro"
) -> Dict[str, Any]:
    """
    Search and extract gene information from Gene2Phenotype database. The data in Gene2Phenotype (G2P) is produced and curated from the literature by different sets of panels formed by consultant clinical geneticists. The G2P data is designed to facilitate the development, validation, curation, and distribution of large-scale, evidence-based datasets for use in diagnostic variant filtering.
    
    Args:
        query_list: List of diseases or conditions to search for associated genes
        json_path: Path to Gene2Phenotype JSON file (default: "resource/Open_target/gene2phenotype.json")
        model_name: Model name for LLM analysis, defaults to "gemini-2.5-pro"
    
    Returns:
        Dictionary containing genes associated with each disease query and normalized relevance scores based on confidence levels
    """
    import json
    
    # Confidence to score mapping based on Gene2Phenotype classification
    confidence_scores = {
        "limited": 0.01,
        "moderate": 0.5,
        "strong": 1.0,
        "both rd and if": 1.0,
        "definitive": 1.0
    }
    
    def load_json_data() -> List[Dict[str, Any]]:
        """Load the Gene2Phenotype JSON data (line-delimited JSON format)"""
        data_list = []
        try:
            with open(json_path, 'r', encoding='utf-8') as f:
                # Each line is a separate JSON object
                for line in f:
                    line = line.strip()
                    if line:  # Skip empty lines
                        try:
                            data_list.append(json.loads(line))
                        except json.JSONDecodeError:
                            continue
        except FileNotFoundError:
            print(f"Gene2Phenotype file not found: {json_path}")
        except Exception as e:
            print(f"Could not parse {json_path} as JSON: {e}")
        return data_list

    def extract_all_disease_names(data: List[Dict[str, Any]]) -> List[str]:
        """Extract all unique disease names from the loaded JSON data"""
        disease_names = set()
        for entry in data:
            if isinstance(entry, dict) and "diseaseFromSource" in entry:
                disease_names.add(entry["diseaseFromSource"])
        return sorted(list(disease_names))

    def match_diseases_with_llm(queries: List[str], all_diseases: List[str]) -> Dict[str, str]:
        """Use LLM to find the most relevant disease names for multiple queries"""
        prompt = f"""
You are an assistant to medical genetics experts. Given multiple user queries, your task is to identify the SINGLE most relevant disease name from the provided list for EACH query.

Think step by step for each query and select only the most relevant disease name. Please format your response following the response format and make sure it is parsable by JSON.

User queries:
{chr(10).join([f"{i+1}. {query}" for i, query in enumerate(queries)])}

Available disease names:
{chr(10).join(all_diseases)}

Response format:
{{
"thoughts": "your step-by-step thinking process for each query",
"disease_matches": [
    {{
        "query": "user query",
        "matched_disease_name": "matched disease name or NA if no relevant disease found"
    }}
]
}}
"""
        
        try:
            result = json_llm_call(prompt, model_name=model_name)
            matched_diseases_list = result.get('disease_matches', [])
            matched_diseases = {}
            for item in matched_diseases_list:
                if isinstance(item, dict) and 'query' in item and 'matched_disease_name' in item:
                    matched_diseases[item['query']] = item['matched_disease_name']
            return matched_diseases
        except Exception as e:
            print(f"Error matching diseases with LLM: {str(e)}")
            return {}

    def find_genes_for_diseases(matched_diseases: Dict[str, str], data: List[Dict[str, Any]]) -> Dict[str, List[Dict[str, Any]]]:
        """Find genes for multiple matched diseases with confidence levels"""
        results = {}
        
        for query, disease_name in matched_diseases.items():
            found_genes = []
            
            if disease_name and disease_name != "NA":
                # Look up genes for the matched disease
                for entry in data:
                    if isinstance(entry, dict) and entry.get("diseaseFromSource") == disease_name:
                        target_gene = entry.get("targetFromSourceId")
                        confidence = entry.get("confidence", "limited")
                        if target_gene:
                            found_genes.append({
                                "gene": target_gene,
                                "confidence": confidence.lower()
                            })
            
            results[query] = found_genes
        
        return results

    try:
        # Load Gene2Phenotype data
        data = load_json_data()
        if not data:
            return {
                "status": "error",
                "error_message": f"No Gene2Phenotype data found in {json_path}",
                "raw_results": {},
                "final_results": {}
            }

        # Extract all disease names
        all_diseases = extract_all_disease_names(data)
        if not all_diseases:
            return {
                "status": "error",
                "error_message": "No disease names found in data",
                "raw_results": {},
                "final_results": {}
            }

        final_results = {}
        raw_results = {}
        
        # Match all diseases with LLM
        matched_diseases = match_diseases_with_llm(query_list, all_diseases)
        
        # Print matched diseases for quality check
        print("\n=== Disease Matching Results (Quality Check) ===")
        for query, disease in matched_diseases.items():
            print(f"Query: '{query}' → Matched: '{disease}'")
        print("===================================================\n")
        
        # Find genes for all matched diseases
        genes_by_query = find_genes_for_diseases(matched_diseases, data)
        
        for query in query_list:
            # Get genes for the current query
            gene_results = genes_by_query.get(query, [])
            
            # Extract gene symbols and confidence
            found_genes = [g["gene"] for g in gene_results]
            confidence_levels = [g["confidence"] for g in gene_results]
            
            # Validate genes 
            valid_genes, invalid_genes = validate_genes(found_genes)
            
            # Store raw results
            raw_results[query] = {
                "matched_disease": matched_diseases.get(query, ""),
                "total_genes_found": len(found_genes),
                "valid_genes": len(valid_genes),
                "invalid_genes": len(invalid_genes)
            }
            
            # Create a mapping of valid genes to their confidence
            # Use a dictionary to handle duplicates - keep the highest confidence version
            valid_gene_confidence = {}
            for i, gene in enumerate(found_genes):
                if gene in valid_genes:
                    current_confidence = confidence_levels[i]
                    current_score = confidence_scores.get(current_confidence, 0.01)
                    
                    # If gene already exists, only replace if current confidence score is higher
                    if gene not in valid_gene_confidence or current_score > confidence_scores.get(valid_gene_confidence[gene], 0.01):
                        valid_gene_confidence[gene] = current_confidence
            
            # Assign raw scores based on confidence levels using deduplicated genes
            raw_scores = []
            valid_genes_list = list(valid_gene_confidence.keys())  # Using deduplicated genes
            
            for gene in valid_genes_list:
                confidence = valid_gene_confidence.get(gene, "limited")
                score = confidence_scores.get(confidence, 0.01)
                raw_scores.append(score)
            
            # Normalize scores
            normalized_scores = normalize_scores(raw_scores, temperature=1.0)
            
            # Create final results with normalized scores
            final_results[query] = [
                {"gene": gene, "score": score} 
                for gene, score in zip(valid_genes_list, normalized_scores)
            ]
        
        return {
            "status": "success",
            "metadata": {
                "queries_processed": len(query_list),
                "diseases_matched": {
                    query: matched_diseases.get(query, "")
                    for query in query_list
                },
                "genes_found": {
                    query: len(final_results.get(query, []))
                    for query in query_list
                },
                "confidence_levels": ["definitive", "strong", "moderate", "limited", "both rd and if"]
            },
            "raw_results": raw_results,
            "final_results": final_results
        }
        
    except Exception as e:
        return {
            "status": "error",
            "error_message": str(e),
            "raw_results": {},
            "final_results": {}
        }


@tool
def gene_burden_search(
    query_list: List[str], 
    json_path: str = "resource/Open_target/gene_burden.json",
    model_name: str = "gemini-2.5-pro"
) -> Dict[str, Any]:
    """
    Search and extract gene information from Gene Burden database. Gene burden data comprises gene–phenotype relationships observed in gene-level association tests using rare variant collapsing analyses. These associations result from collapsing rare variants in a gene into a single burden statistic and regressing the phenotype on the burden statistic to test for the combined effects of all rare variants in that gene.
    
    Args:
        query_list: List of phenotypes or conditions to search for associated genes
        json_path: Path to Gene Burden JSON file (default: "resource/Open_target/gene_burden.json")
        model_name: Model name for LLM analysis, defaults to "gemini-2.5-pro"
    
    Returns:
        Dictionary containing genes associated with each phenotype query and normalized relevance scores based on p-values
    """
    import json
    
    def load_json_data() -> List[Dict[str, Any]]:
        """Load the Gene Burden JSON data (line-delimited JSON format)"""
        data_list = []
        try:
            with open(json_path, 'r', encoding='utf-8') as f:
                # Each line is a separate JSON object
                for line in f:
                    line = line.strip()
                    if line:  # Skip empty lines
                        try:
                            data_list.append(json.loads(line))
                        except json.JSONDecodeError:
                            continue
        except FileNotFoundError:
            print(f"Gene Burden file not found: {json_path}")
        except Exception as e:
            print(f"Could not parse {json_path} as JSON: {e}")
        return data_list

    def extract_all_phenotype_names(data: List[Dict[str, Any]]) -> List[str]:
        """Extract all unique phenotype names from the loaded JSON data"""
        phenotype_names = set()
        for entry in data:
            if isinstance(entry, dict) and "diseaseFromSource" in entry:
                phenotype_names.add(entry["diseaseFromSource"])
        return sorted(list(phenotype_names))

    def match_phenotypes_with_llm(queries: List[str], all_phenotypes: List[str]) -> Dict[str, str]:
        """Use LLM to find the most relevant phenotype names for multiple queries"""
        prompt = f"""
You are an assistant to medical genetics experts. Given multiple user queries, your task is to identify the SINGLE most relevant phenotype name from the provided list for EACH query.

IMPORTANT: You must return the EXACT phenotype name from the list as it appears, including any IDs, numbers, or special characters (like "20002#1473#high cholesterol"). Do not modify, simplify, or clean up the phenotype names.

Think step by step for each query and select only the most relevant phenotype name. Please format your response following the response format and make sure it is parsable by JSON.

User queries:
{chr(10).join([f"{i+1}. {query}" for i, query in enumerate(queries)])}

Available phenotype names:
{chr(10).join(all_phenotypes)}

Response format:
{{
"thoughts": "your step-by-step thinking process for each query",
"phenotype_matches": [
    {{
        "query": "user query",
        "matched_phenotype_name": "matched phenotype name EXACTLY as it appears in the list, or NA if no relevant phenotype found"
    }}
]
}}
"""
        
        try:
            result = json_llm_call(prompt, model_name=model_name)
            matched_phenotypes_list = result.get('phenotype_matches', [])
            matched_phenotypes = {}
            for item in matched_phenotypes_list:
                if isinstance(item, dict) and 'query' in item and 'matched_phenotype_name' in item:
                    matched_phenotypes[item['query']] = item['matched_phenotype_name']
            return matched_phenotypes
        except Exception as e:
            print(f"Error matching phenotypes with LLM: {str(e)}")
            return {}

    def find_genes_for_phenotypes(matched_phenotypes: Dict[str, str], data: List[Dict[str, Any]]) -> Dict[str, List[Dict[str, Any]]]:
        """Find genes for multiple matched phenotypes with p-values"""
        results = {}
        
        for query, phenotype_name in matched_phenotypes.items():
            found_genes = []
            
            if phenotype_name and phenotype_name != "NA":
                # Look up genes for the matched phenotype
                for entry in data:
                    if isinstance(entry, dict) and entry.get("diseaseFromSource") == phenotype_name:
                        target_gene = entry.get("targetFromSourceId")
                        p_value_mantissa = entry.get("pValueMantissa")
                        p_value_exponent = entry.get("pValueExponent")
                        
                        if target_gene and p_value_mantissa is not None:
                            found_genes.append({
                                "gene": target_gene,
                                "pValueMantissa": p_value_mantissa,
                                "pValueExponent": p_value_exponent if p_value_exponent is not None else 0
                            })
            
            results[query] = found_genes
        
        return results

    try:
        # Load Gene Burden data
        data = load_json_data()
        if not data:
            return {
                "status": "error",
                "error_message": f"No Gene Burden data found in {json_path}",
                "raw_results": {},
                "final_results": {}
            }

        # Extract all phenotype names
        all_phenotypes = extract_all_phenotype_names(data)
        if not all_phenotypes:
            return {
                "status": "error",
                "error_message": "No phenotype names found in data",
                "raw_results": {},
                "final_results": {}
            }

        final_results = {}
        raw_results = {}
        
        # Match all phenotypes with LLM
        matched_phenotypes = match_phenotypes_with_llm(query_list, all_phenotypes)
        
        # Print matched phenotypes for quality check
        print("\n=== Phenotype Matching Results (Quality Check) ===")
        for query, phenotype in matched_phenotypes.items():
            print(f"Query: '{query}' → Matched: '{phenotype}'")
        print("===================================================\n")
        
        # Find genes for all matched phenotypes
        genes_by_query = find_genes_for_phenotypes(matched_phenotypes, data)
        
        for query in query_list:
            # Get genes for the current query
            gene_results = genes_by_query.get(query, [])
            
            # Extract gene symbols
            found_genes = [g["gene"] for g in gene_results]
            
            # Validate genes 
            valid_genes, invalid_genes = validate_genes(found_genes)
            
            # Store raw results
            raw_results[query] = {
                "matched_phenotype": matched_phenotypes.get(query, ""),
                "total_genes_found": len(found_genes),
                "valid_genes": len(valid_genes),
                "invalid_genes": len(invalid_genes)
            }
            
            # Create a mapping of valid genes to their p-values
            # Use a dictionary to handle duplicates - keep the most significant (smallest p-value) version
            valid_gene_pvalues = {}
            for i, gene in enumerate(found_genes):
                if gene in valid_genes:
                    mantissa = gene_results[i].get("pValueMantissa", 0)
                    exponent = gene_results[i].get("pValueExponent", 0)
                    
                    # Calculate full p-value (for comparison only)
                    full_pvalue = mantissa * (10 ** exponent) if exponent else mantissa
                    
                    # Keep the most significant (smallest) p-value for each gene
                    if gene not in valid_gene_pvalues or full_pvalue < valid_gene_pvalues[gene]["full_pvalue"]:
                        valid_gene_pvalues[gene] = {
                            "mantissa": mantissa,
                            "full_pvalue": full_pvalue
                        }
            
            # Assign raw scores based on pValueMantissa (higher mantissa means higher significance)
            raw_scores = []
            valid_genes_list = list(valid_gene_pvalues.keys())
            
            for gene in valid_genes_list:
                # Use mantissa directly as the raw score
                score = valid_gene_pvalues[gene]["mantissa"]
                raw_scores.append(score)
            
            # Normalize scores
            normalized_scores = normalize_scores(raw_scores, temperature=1.0)
            
            # Create final results with normalized scores
            final_results[query] = [
                {"gene": gene, "score": score} 
                for gene, score in zip(valid_genes_list, normalized_scores)
            ]
        
        return {
            "status": "success",
            "metadata": {
                "queries_processed": len(query_list),
                "phenotypes_matched": {
                    query: matched_phenotypes.get(query, "")
                    for query in query_list
                },
                "genes_found": {
                    query: len(final_results.get(query, []))
                    for query in query_list
                }
            },
            "raw_results": raw_results,
            "final_results": final_results
        }
        
    except Exception as e:
        return {
            "status": "error",
            "error_message": str(e),
            "raw_results": {},
            "final_results": {}
        }


@tool
def intogen_search(
    query_list: List[str], 
    json_path: str = "resource/Open_target/intogen.json",
    model_name: str = "gemini-2.5-pro"
) -> Dict[str, Any]:
    """
    Search and extract gene information from IntOGen database. IntOGen provides a framework to identify potential cancer driver genes using large-scale mutational data from sequenced tumor samples. By harmonising tumor sequencing data from the ICGC/TCGA Pan-Cancer Analysis of Whole Genomes (PCAWG) and other comprehensive efforts, IntOGen aims to provide a consensus assessment of cancer driver genes.
    
    Args:
        query_list: List of cancer types or related conditions to search for associated driver genes
        json_path: Path to IntOGen JSON file (default: "resource/Open_target/intogen.json")
        model_name: Model name for LLM analysis, defaults to "gemini-2.5-pro"
    
    Returns:
        Dictionary containing cancer driver genes associated with each cancer type query and normalized relevance scores
    """
    import json
    import math
    
    def load_json_data() -> List[Dict[str, Any]]:
        """Load the IntOGen JSON data (line-delimited JSON format)"""
        data_list = []
        try:
            with open(json_path, 'r', encoding='utf-8') as f:
                # Each line is a separate JSON object
                for line in f:
                    line = line.strip()
                    if line:  # Skip empty lines
                        try:
                            data_list.append(json.loads(line))
                        except json.JSONDecodeError:
                            continue
        except FileNotFoundError:
            print(f"IntOGen file not found: {json_path}")
        except Exception as e:
            print(f"Could not parse {json_path} as JSON: {e}")
        return data_list

    def extract_all_disease_names(data: List[Dict[str, Any]]) -> List[str]:
        """Extract all unique disease names from the loaded JSON data"""
        disease_names = set()
        for entry in data:
            if isinstance(entry, dict) and "diseaseFromSource" in entry:
                disease_names.add(entry["diseaseFromSource"])
        return sorted(list(disease_names))

    def match_diseases_with_llm(queries: List[str], all_diseases: List[str]) -> Dict[str, str]:
        """Use LLM to find the most relevant disease names for multiple queries"""
        prompt = f"""
You are an assistant to cancer genomics experts. Given multiple user queries, your task is to identify the SINGLE most relevant cancer or disease name from the provided list for EACH query.

IMPORTANT: You must return the EXACT disease name from the list as it appears, including any IDs, numbers, or special characters. Do not modify, simplify, or clean up the disease names.

Think step by step for each query and select only the most relevant disease name. Please format your response following the response format and make sure it is parsable by JSON.

User queries:
{chr(10).join([f"{i+1}. {query}" for i, query in enumerate(queries)])}

Available disease names:
{chr(10).join(all_diseases)}

Response format:
{{
"thoughts": "your step-by-step thinking process for each query",
"disease_matches": [
    {{
        "query": "user query",
        "matched_disease_name": "matched disease name EXACTLY as it appears in the list, or NA if no relevant disease found"
    }}
]
}}
"""
        
        try:
            result = json_llm_call(prompt, model_name=model_name)
            matched_diseases_list = result.get('disease_matches', [])
            matched_diseases = {}
            for item in matched_diseases_list:
                if isinstance(item, dict) and 'query' in item and 'matched_disease_name' in item:
                    matched_diseases[item['query']] = item['matched_disease_name']
            return matched_diseases
        except Exception as e:
            print(f"Error matching diseases with LLM: {str(e)}")
            return {}

    def find_genes_for_diseases(matched_diseases: Dict[str, str], data: List[Dict[str, Any]]) -> Dict[str, List[Dict[str, Any]]]:
        """Find genes for multiple matched diseases with resource scores"""
        results = {}
        
        for query, disease_name in matched_diseases.items():
            found_genes = []
            
            if disease_name and disease_name != "NA":
                # Look up genes for the matched disease
                for entry in data:
                    if isinstance(entry, dict) and entry.get("diseaseFromSource") == disease_name:
                        target_gene = entry.get("targetFromSourceId")
                        resource_score = entry.get("resourceScore")
                        
                        if target_gene and resource_score is not None:
                            found_genes.append({
                                "gene": target_gene,
                                "resourceScore": resource_score
                            })
            
            results[query] = found_genes
        
        return results

    try:
        # Load IntOGen data
        data = load_json_data()
        if not data:
            return {
                "status": "error",
                "error_message": f"No IntOGen data found in {json_path}",
                "raw_results": {},
                "final_results": {}
            }

        # Extract all disease names
        all_diseases = extract_all_disease_names(data)
        if not all_diseases:
            return {
                "status": "error",
                "error_message": "No disease names found in data",
                "raw_results": {},
                "final_results": {}
            }

        final_results = {}
        raw_results = {}
        
        # Match all diseases with LLM
        matched_diseases = match_diseases_with_llm(query_list, all_diseases)
        
        # Print matched diseases for quality check
        print("\n=== Disease Matching Results (Quality Check) ===")
        for query, disease in matched_diseases.items():
            print(f"Query: '{query}' → Matched: '{disease}'")
        print("===================================================\n")
        
        # Find genes for all matched diseases
        genes_by_query = find_genes_for_diseases(matched_diseases, data)
        
        for query in query_list:
            # Get genes for the current query
            gene_results = genes_by_query.get(query, [])
            
            # Extract gene symbols
            found_genes = [g["gene"] for g in gene_results]
            
            # Validate genes 
            valid_genes, invalid_genes = validate_genes(found_genes)
            
            # Store raw results
            raw_results[query] = {
                "matched_disease": matched_diseases.get(query, ""),
                "total_genes_found": len(found_genes),
                "valid_genes": len(valid_genes),
                "invalid_genes": len(invalid_genes)
            }
            
            # Create a mapping of valid genes to their resource scores
            # Use a dictionary to handle duplicates - keep the highest resource score version
            valid_gene_scores = {}
            for i, gene in enumerate(found_genes):
                if gene in valid_genes:
                    resource_score = gene_results[i].get("resourceScore", 0)
                    
                    # For ties or duplicates, keep the highest resource score
                    if gene not in valid_gene_scores or resource_score > valid_gene_scores[gene]:
                        valid_gene_scores[gene] = resource_score
            
            # Assign raw scores based on -log(resourceScore)
            raw_scores = []
            valid_genes_list = list(valid_gene_scores.keys())
            
            for gene in valid_genes_list:
                # Apply -log transformation to resource score
                # Add a small epsilon to avoid log(0)
                epsilon = 1e-10
                score = -math.log(valid_gene_scores[gene] + epsilon) if valid_gene_scores[gene] > 0 else 0
                raw_scores.append(score)
            
            # Normalize scores
            normalized_scores = normalize_scores(raw_scores, temperature=1.0)
            
            # Create final results with normalized scores
            final_results[query] = [
                {"gene": gene, "score": score} 
                for gene, score in zip(valid_genes_list, normalized_scores)
            ]
        
        return {
            "status": "success",
            "metadata": {
                "queries_processed": len(query_list),
                "diseases_matched": {
                    query: matched_diseases.get(query, "")
                    for query in query_list
                },
                "genes_found": {
                    query: len(final_results.get(query, []))
                    for query in query_list
                }
            },
            "raw_results": raw_results,
            "final_results": final_results
        }
        
    except Exception as e:
        return {
            "status": "error",
            "error_message": str(e),
            "raw_results": {},
            "final_results": {}
        }


@tool
def gocc_cellular_component_search(
    query_list: List[str], 
    json_directory: str = "resource/GOCC",
    model_name: str = "gemini-2.5-pro"
) -> Dict[str, Any]:
    """
    Search and extract gene information from Gene Ontology Cellular Component (GOCC) database. The Gene Ontology (GO) Cellular Component ontology describes locations at the levels of subcellular structures and macromolecular complexes. This tool identifies genes associated with specific cellular components, organelles, and subcellular locations.
    
    Args:
        query_list: List of cellular component names, structures, or location identifiers to search for
        json_directory: Path to directory containing GOCC JSON files (default: "resource/GOCC")
        model_name: Model name for LLM analysis, defaults to "gemini-2.5-pro"
    
    Returns:
        Dictionary containing genes associated with each cellular component query and normalized relevance scores
    """
    import json
    
    def load_json_files() -> List[Dict[str, Any]]:
        """Load all JSON files from the specified directory"""
        data_list = []
        try:
            for file_name in os.listdir(json_directory):
                if file_name.lower().endswith(".json"):
                    file_path = os.path.join(json_directory, file_name)
                    try:
                        with open(file_path, 'r', encoding='utf-8') as f:
                            data_list.append(json.load(f))
                    except Exception as e:
                        print(f"Could not parse {file_path} as JSON: {e}")
        except FileNotFoundError:
            print(f"GOCC directory not found: {json_directory}")
        return data_list

    def extract_all_component_names(data_files: List[Dict[str, Any]]) -> List[str]:
        """Extract all cellular component names from the loaded JSON files"""
        component_names = []
        for data_file in data_files:
            if isinstance(data_file, dict):
                component_names.extend(list(data_file.keys()))
        return component_names

    def match_components_with_llm(queries: List[str], all_components: List[str]) -> Dict[str, str]:
        """Use LLM to find the most relevant cellular component names for multiple queries"""
        prompt = f"""
You are an assistant to biologists. Given multiple user queries, your task is to identify the SINGLE most relevant Gene Ontology Cellular Component (GOCC) name from the provided list for EACH query.

Think step by step for each query and select only the most relevant cellular component name. Please format your response following the response format and make sure it is parsable by JSON.

User queries:
{chr(10).join([f"{i+1}. {query}" for i, query in enumerate(queries)])}

Available cellular component names:
{chr(10).join(all_components)}

Response format:
{{
"thoughts": "your step-by-step thinking process for each query",
"component_matches": [
    {{
        "query": "user query",
        "matched_component_name": "matched cellular component name or NA if no relevant component found"
    }}
]
}}
"""
        
        try:
            result = json_llm_call(prompt, model_name=model_name)
            matched_components_list = result.get('component_matches', [])
            matched_components = {}
            for item in matched_components_list:
                if isinstance(item, dict) and 'query' in item and 'matched_component_name' in item:
                    matched_components[item['query']] = item['matched_component_name']
            return matched_components
        except Exception as e:
            print(f"Error matching components with LLM: {str(e)}")
            return {}

    def find_genes_for_components(matched_components: Dict[str, str], data_files: List[Dict[str, Any]]) -> Dict[str, List[str]]:
        """Find genes for multiple matched cellular components"""
        results = {}
        
        for query, component_name in matched_components.items():
            found_genes = set()
            
            if component_name and component_name != "NA":
                # Look up genes for the matched component
                for data_file in data_files:
                    if isinstance(data_file, dict) and component_name in data_file:
                        entry = data_file[component_name]
                        if isinstance(entry, dict):
                            genes = entry.get("geneSymbols", [])
                            if isinstance(genes, list):
                                found_genes.update(genes)
            
            results[query] = sorted(found_genes)
        
        return results

    try:
        # Load GOCC data files
        data_files = load_json_files()
        if not data_files:
            return {
                "status": "error",
                "error_message": f"No GOCC JSON files found in {json_directory}",
                "raw_results": {},
                "final_results": {}
            }

        # Extract all component names
        all_components = extract_all_component_names(data_files)
        if not all_components:
            return {
                "status": "error",
                "error_message": "No cellular component names found in JSON files",
                "raw_results": {},
                "final_results": {}
            }

        final_results = {}
        raw_results = {}
        
        # Match all components with LLM
        matched_components = match_components_with_llm(query_list, all_components)
        
        # Print matched components for quality check
        print("\n=== Component Matching Results (Quality Check) ===")
        for query, component in matched_components.items():
            print(f"Query: '{query}' → Matched: '{component}'")
        print("===================================================\n")
        
        # Find genes for all matched components
        genes_by_query = find_genes_for_components(matched_components, data_files)
        
        for query in query_list:
            # Get genes for the current query
            found_genes = genes_by_query.get(query, [])
            
            # Validate genes 
            valid_genes, invalid_genes = validate_genes(found_genes)
            
            # Store raw results
            raw_results[query] = {
                "matched_component": matched_components.get(query, ""),
                "total_genes_found": len(found_genes),
                "valid_genes": len(valid_genes),
                "invalid_genes": len(invalid_genes)
            }
            
            # Assign initial raw scores of 1.0 to each gene
            raw_scores = [1.0] * len(valid_genes)
            
            # Normalize scores
            normalized_scores = normalize_scores(raw_scores, temperature=1.0)
            
            # Create final results with normalized scores
            final_results[query] = [
                {"gene": gene, "score": score} 
                for gene, score in zip(valid_genes, normalized_scores)
            ]
        
        return {
            "status": "success",
            "metadata": {
                "queries_processed": len(query_list),
                "components_matched": {
                    query: matched_components.get(query, "")
                    for query in query_list
                },
                "genes_found": {
                    query: len(final_results.get(query, []))
                    for query in query_list
                }
            },
            "raw_results": raw_results,
            "final_results": final_results
        }
        
    except Exception as e:
        return {
            "status": "error",
            "error_message": str(e),
            "raw_results": {},
            "final_results": {}
        }


@tool
def clinvar_search(
    query_list: List[str], 
    json_path: str = "resource/Open_target/eva.json",
    max_candidates: int = 100,
    similarity_threshold: int = 50,
    model_name: str = "gemini-2.5-pro"
) -> Dict[str, Any]:
    """
    Search and extract gene information from ClinVar database. ClinVar is a NIH public archive of reports of the relationships among human variations and phenotypes, with supporting evidence. This tool extracts gene information based on disease associations from the ClinVar database, using clinical significance and confidence levels to calculate evidence scores.
    
    Args:
        query_list: List of disease names or related conditions to search for associated genes
        json_path: Path to ClinVar JSON file (default: "resource/Open_target/eva.json")
        max_candidates: Maximum number of disease candidates to send to LLM (default: 100)
        similarity_threshold: Minimum similarity score (0-100) for fuzzy matching (default: 50)
        model_name: Model name for LLM analysis, defaults to "gemini-2.5-pro"
    
    Returns:
        Dictionary containing genes associated with each disease query and normalized relevance scores based on clinical evidence
    """
    import json
    import time
    from rapidfuzz import process, fuzz
    
    # Cache for Ensembl ID to gene name mapping
    ensembl_id_cache = {}
    
    # Clinical significance score mapping
    clinical_significance_scores = {
        "association not found": 0.0,
        "benign": 0.0,
        "not provided": 0.0,
        "likely benign": 0.0,
        "conflicting data from submitters": 0.3,
        "conflicting interpretations of pathogenicity": 0.3,
        "low penetrance": 0.3,
        "other": 0.3,
        "uncertain risk allele": 0.3,
        "uncertain significance": 0.3,
        "established risk allele": 0.5,
        "risk factor": 0.5,
        "affects": 0.5,
        "likely pathogenic": 0.7,
        "association": 0.9,
        "confers sensitivity": 0.9,
        "drug response": 0.9,
        "protective": 0.9,
        "pathogenic": 0.9
    }
    
    # Confidence score modifiers
    confidence_score_modifiers = {
        "no assertion provided": 0.0,
        "no assertion criteria provided": 0.0,
        "no assertion for the individual variant": 0.0,
        "criteria provided, single submitter": 0.02,
        "criteria provided, conflicting interpretations": 0.02,
        "criteria provided, conflicting classifications": 0.02,
        "criteria provided, multiple submitters, no conflicts": 0.05,
        "reviewed by expert panel": 0.07,
        "practice guideline": 0.1
    }
    
    def load_json_data() -> List[Dict[str, Any]]:
        """Load the ClinVar JSON data (line-delimited JSON format)"""
        data_list = []
        try:
            with open(json_path, 'r', encoding='utf-8') as f:
                # Each line is a separate JSON object
                for line in f:
                    line = line.strip()
                    if line:  # Skip empty lines
                        try:
                            data_list.append(json.loads(line))
                        except json.JSONDecodeError:
                            continue
        except FileNotFoundError:
            print(f"ClinVar file not found: {json_path}")
        except Exception as e:
            print(f"Could not parse {json_path} as JSON: {e}")
        return data_list

    def extract_all_disease_names(data: List[Dict[str, Any]]) -> List[str]:
        """Extract all unique disease names from the loaded JSON data"""
        disease_names = set()
        for entry in data:
            if isinstance(entry, dict) and "diseaseFromSource" in entry:
                disease_names.add(entry["diseaseFromSource"])
        return sorted(list(disease_names))

    def similarity_search(query: str, all_diseases: List[str]) -> List[str]:
        """Find most similar disease names using fuzzy matching"""
        matches = process.extract(
            query, 
            all_diseases, 
            scorer=fuzz.token_sort_ratio, 
            limit=max_candidates,
            score_cutoff=similarity_threshold,
            processor=lambda s: s.lower()
        )
        return [match[0] for match in matches]

    def match_diseases_with_llm(queries: List[str], all_diseases: List[str]) -> Dict[str, str]:
        """Use LLM to find the most relevant disease names for multiple queries"""
        matched_diseases = {}
        
        for query in queries:
            # First use similarity search to get candidate matches
            candidates = similarity_search(query, all_diseases)
            print(f"Found {len(candidates)} candidate matches for '{query}'")
            
            if not candidates:
                matched_diseases[query] = ""
                continue
                
            prompt = f"""
You are an assistant to genomics experts. Given a user query, your task is to identify the SINGLE most relevant disease name from the provided list.

IMPORTANT: You must return the EXACT disease name from the list as it appears, including any IDs, numbers, or special characters. Do not modify, simplify, or clean up the disease names.

Think step by step and select only the most relevant disease name. Please format your response following the response format and make sure it is parsable by JSON.

User query:
{query}

Available disease names:
{chr(10).join(candidates)}

Response format:
{{
"thoughts": "your step-by-step thinking process",
"disease_matches": [
    {{
        "query": "{query}",
        "matched_disease_name": "matched disease name EXACTLY as it appears in the list, or NA if no relevant disease found"
    }}
]
}}
"""
            
            try:
                result = json_llm_call(prompt, model_name=model_name)
                matched_disease_list = result.get('disease_matches', [])
                if matched_disease_list and isinstance(matched_disease_list, list) and len(matched_disease_list) > 0:
                    matched_disease = matched_disease_list[0].get('matched_disease_name', "")
                    matched_diseases[query] = matched_disease if matched_disease != "NA" else ""
                else:
                    matched_diseases[query] = ""
            except Exception as e:
                print(f"Error matching disease '{query}' with LLM: {str(e)}")
                matched_diseases[query] = ""
                
        return matched_diseases

    def ensembl_id_to_gene_symbol(ensembl_id: str) -> str:
        """Convert Ensembl ID to gene symbol using Ensembl API"""
        # Check cache first
        if ensembl_id in ensembl_id_cache:
            return ensembl_id_cache[ensembl_id]
        
        try:
            # Use Ensembl REST API to fetch gene name
            url = f"https://rest.ensembl.org/lookup/id/{ensembl_id}?content-type=application/json"
            response = requests.get(url, headers={"Content-Type": "application/json"}, timeout=10)
            
            if response.status_code == 200:
                data = response.json()
                gene_symbol = data.get("display_name", ensembl_id)
                ensembl_id_cache[ensembl_id] = gene_symbol
                return gene_symbol
            
            # If we can't find the gene name, return the original ID
            ensembl_id_cache[ensembl_id] = ensembl_id
            return ensembl_id
            
        except Exception as e:
            print(f"Error converting Ensembl ID {ensembl_id} to gene symbol: {str(e)}")
            ensembl_id_cache[ensembl_id] = ensembl_id
            return ensembl_id

    def calculate_evidence_score(entry: Dict[str, Any]) -> float:
        """Calculate evidence score based on clinical significance and confidence"""
        # Get clinical significance score
        clinical_significance = "not provided"  # Default
        if "clinicalSignificances" in entry and entry["clinicalSignificances"]:
            clinical_significance = entry["clinicalSignificances"][0]
        
        base_score = clinical_significance_scores.get(clinical_significance, 0.0)
        
        # Get confidence modifier
        confidence = entry.get("confidence", "no assertion provided")
        modifier = confidence_score_modifiers.get(confidence, 0.0)
        
        # Combine base score and modifier
        return min(1.0, base_score + modifier)  # Cap at 1.0

    def find_genes_for_diseases(matched_diseases: Dict[str, str], data: List[Dict[str, Any]]) -> Dict[str, List[Dict[str, Any]]]:
        """Find genes for multiple matched diseases with evidence scores"""
        results = {}
        
        for query, disease_name in matched_diseases.items():
            found_genes = []
            
            if disease_name and disease_name != "NA":
                # Look up genes for the matched disease
                for entry in data:
                    if isinstance(entry, dict) and entry.get("diseaseFromSource") == disease_name:
                        ensembl_id = entry.get("targetFromSourceId")
                        
                        if ensembl_id:
                            # Calculate evidence score based on clinical significance and confidence
                            evidence_score = calculate_evidence_score(entry)
                            
                            found_genes.append({
                                "ensembl_id": ensembl_id,
                                "resourceScore": evidence_score
                            })
            
            results[query] = found_genes
        
        return results

    try:
        # Load ClinVar data
        data = load_json_data()
        if not data:
            return {
                "status": "error",
                "error_message": f"No ClinVar data found in {json_path}",
                "raw_results": {},
                "final_results": {}
            }

        # Extract all disease names
        all_diseases = extract_all_disease_names(data)
        if not all_diseases:
            return {
                "status": "error",
                "error_message": "No disease names found in data",
                "raw_results": {},
                "final_results": {}
            }

        final_results = {}
        raw_results = {}
        
        # Match all diseases with LLM
        matched_diseases = match_diseases_with_llm(query_list, all_diseases)
        
        # Print matched diseases for quality check
        print("\n=== Disease Matching Results (Quality Check) ===")
        for query, disease in matched_diseases.items():
            print(f"Query: '{query}' → Matched: '{disease}'")
        print("===================================================\n")
        
        # Find genes for all matched diseases
        genes_by_query = find_genes_for_diseases(matched_diseases, data)
        
        for query in query_list:
            # Get genes for the current query
            gene_results = genes_by_query.get(query, [])
            
            # Extract Ensembl IDs and scores
            ensembl_ids = [g["ensembl_id"] for g in gene_results]
            raw_scores = [g["resourceScore"] for g in gene_results]
            
            # Map of Ensembl IDs to their scores (keeping the highest score if duplicates)
            gene_score_map = {}
            for ensembl_id, score in zip(ensembl_ids, raw_scores):
                if ensembl_id in gene_score_map:
                    gene_score_map[ensembl_id] = max(gene_score_map[ensembl_id], score)
                else:
                    gene_score_map[ensembl_id] = score
            
            # Convert Ensembl IDs to gene symbols with rate limiting
            gene_symbols = []
            gene_scores = []
            for ensembl_id, score in gene_score_map.items():
                gene_symbol = ensembl_id_to_gene_symbol(ensembl_id)
                gene_symbols.append(gene_symbol)
                gene_scores.append(score)
                time.sleep(0.1)  # Add a small delay to avoid rate limiting
            
            # Validate genes 
            valid_genes, invalid_genes = validate_genes(gene_symbols)
            
            # Store raw results
            raw_results[query] = {
                "matched_disease": matched_diseases.get(query, ""),
                "total_ensembl_ids_found": len(ensembl_ids),
                "total_gene_symbols_converted": len(gene_symbols),
                "valid_genes": len(valid_genes),
                "invalid_genes": len(invalid_genes)
            }
            
            # Create a map of valid genes to their scores (keeping the highest score if duplicates)
            valid_gene_score_map = {}
            for gene, score in zip(gene_symbols, gene_scores):
                if gene in valid_genes:
                    if gene in valid_gene_score_map:
                        valid_gene_score_map[gene] = max(valid_gene_score_map[gene], score)
                    else:
                        valid_gene_score_map[gene] = score
            
            # Extract unique valid genes and their scores
            unique_valid_genes = list(valid_gene_score_map.keys())
            unique_raw_scores = [valid_gene_score_map[gene] for gene in unique_valid_genes]
            
            # Normalize scores
            normalized_scores = normalize_scores(unique_raw_scores, temperature=1.0)
            
            # Create final results with normalized scores
            final_results[query] = [
                {"gene": gene, "score": score} 
                for gene, score in zip(unique_valid_genes, normalized_scores)
            ]
        
        return {
            "status": "success",
            "metadata": {
                "queries_processed": len(query_list),
                "diseases_matched": {
                    query: matched_diseases.get(query, "")
                    for query in query_list
                },
                "genes_found": {
                    query: len(final_results.get(query, []))
                    for query in query_list
                },
                "api_cache_size": len(ensembl_id_cache),
                "max_candidates": max_candidates,
                "similarity_threshold": similarity_threshold
            },
            "raw_results": raw_results,
            "final_results": final_results
        }
        
    except Exception as e:
        return {
            "status": "error",
            "error_message": str(e),
            "raw_results": {},
            "final_results": {}
        }


@tool
def uniprot_variants_search(
    query_list: List[str], 
    json_path: str = "resource/Open_target/uniprot_variants.json",
    model_name: str = "gemini-2.5-pro"
) -> Dict[str, Any]:
    """
    Search and extract gene information from UniProt Variants database. UniProt provides comprehensive information about proteins and their variants associated with diseases. This tool extracts gene information based on disease associations from the UniProt database, converting UniProt IDs to gene symbols.
    
    Args:
        query_list: List of disease names or related conditions to search for associated genes
        json_path: Path to UniProt variants JSON file (default: "resource/Open_target/uniprot_variants.json")
        model_name: Model name for LLM analysis, defaults to "gemini-2.5-pro"
    
    Returns:
        Dictionary containing genes associated with each disease query and normalized relevance scores
    """
    import json
    import time
    
    # Cache for UniProt ID to gene name mapping
    uniprot_id_cache = {}
    
    def load_json_data() -> List[Dict[str, Any]]:
        """Load the UniProt variants JSON data (line-delimited JSON format)"""
        data_list = []
        try:
            with open(json_path, 'r', encoding='utf-8') as f:
                # Each line is a separate JSON object
                for line in f:
                    line = line.strip()
                    if line:  # Skip empty lines
                        try:
                            data_list.append(json.loads(line))
                        except json.JSONDecodeError:
                            continue
        except FileNotFoundError:
            print(f"UniProt variants file not found: {json_path}")
        except Exception as e:
            print(f"Could not parse {json_path} as JSON: {e}")
        return data_list

    def extract_all_disease_names(data: List[Dict[str, Any]]) -> List[str]:
        """Extract all unique disease names from the loaded JSON data"""
        disease_names = set()
        for entry in data:
            if isinstance(entry, dict) and "diseaseFromSource" in entry:
                disease_names.add(entry["diseaseFromSource"])
        return sorted(list(disease_names))

    def match_diseases_with_llm(queries: List[str], all_diseases: List[str]) -> Dict[str, str]:
        """Use LLM to find the most relevant disease names for multiple queries"""
        prompt = f"""
You are an assistant to genomics experts. Given multiple user queries, your task is to identify the SINGLE most relevant disease name from the provided list for EACH query.

IMPORTANT: You must return the EXACT disease name from the list as it appears, including any IDs, numbers, or special characters. Do not modify, simplify, or clean up the disease names.

Think step by step for each query and select only the most relevant disease name. Please format your response following the response format and make sure it is parsable by JSON.

User queries:
{chr(10).join([f"{i+1}. {query}" for i, query in enumerate(queries)])}

Available disease names:
{chr(10).join(all_diseases)}

Response format:
{{
"thoughts": "your step-by-step thinking process for each query",
"disease_matches": [
    {{
        "query": "user query",
        "matched_disease_name": "matched disease name EXACTLY as it appears in the list, or NA if no relevant disease found"
    }}
]
}}
"""
        
        try:
            result = json_llm_call(prompt, model_name=model_name)
            matched_diseases_list = result.get('disease_matches', [])
            matched_diseases = {}
            for item in matched_diseases_list:
                if isinstance(item, dict) and 'query' in item and 'matched_disease_name' in item:
                    matched_diseases[item['query']] = item['matched_disease_name']
            return matched_diseases
        except Exception as e:
            print(f"Error matching diseases with LLM: {str(e)}")
            return {}

    def uniprot_id_to_gene_symbol(uniprot_id: str) -> str:
        """Convert UniProt ID to gene symbol using UniProt API"""
        # Check cache first
        if uniprot_id in uniprot_id_cache:
            return uniprot_id_cache[uniprot_id]
        
        try:
            # Use UniProt REST API to fetch gene name
            url = f"https://rest.uniprot.org/uniprotkb/{uniprot_id}.json"
            response = requests.get(url, timeout=10)
            
            if response.status_code == 200:
                data = response.json()
                # Extract gene name from the response
                gene_names = data.get("genes", [])
                if gene_names and "geneName" in gene_names[0]:
                    gene_symbol = gene_names[0]["geneName"].get("value", uniprot_id)
                    uniprot_id_cache[uniprot_id] = gene_symbol
                    return gene_symbol
            
            # If we can't find the gene name, return the original ID
            uniprot_id_cache[uniprot_id] = uniprot_id
            return uniprot_id
            
        except Exception as e:
            print(f"Error converting UniProt ID {uniprot_id} to gene symbol: {str(e)}")
            uniprot_id_cache[uniprot_id] = uniprot_id
            return uniprot_id

    def find_genes_for_diseases(matched_diseases: Dict[str, str], data: List[Dict[str, Any]]) -> Dict[str, List[str]]:
        """Find UniProt IDs for multiple matched diseases"""
        results = {}
        
        for query, disease_name in matched_diseases.items():
            found_uniprot_ids = []
            
            if disease_name and disease_name != "NA":
                # Look up UniProt IDs for the matched disease
                for entry in data:
                    if isinstance(entry, dict) and entry.get("diseaseFromSource") == disease_name:
                        uniprot_id = entry.get("targetFromSourceId")
                        if uniprot_id:
                            found_uniprot_ids.append(uniprot_id)
            
            results[query] = found_uniprot_ids
        
        return results

    try:
        # Load UniProt variants data
        data = load_json_data()
        if not data:
            return {
                "status": "error",
                "error_message": f"No UniProt variants data found in {json_path}",
                "raw_results": {},
                "final_results": {}
            }

        # Extract all disease names
        all_diseases = extract_all_disease_names(data)
        if not all_diseases:
            return {
                "status": "error",
                "error_message": "No disease names found in data",
                "raw_results": {},
                "final_results": {}
            }

        final_results = {}
        raw_results = {}
        
        # Match all diseases with LLM
        matched_diseases = match_diseases_with_llm(query_list, all_diseases)
        
        # Print matched diseases for quality check
        print("\n=== Disease Matching Results (Quality Check) ===")
        for query, disease in matched_diseases.items():
            print(f"Query: '{query}' → Matched: '{disease}'")
        print("===================================================\n")
        
        # Find UniProt IDs for all matched diseases
        uniprot_ids_by_query = find_genes_for_diseases(matched_diseases, data)
        
        for query in query_list:
            # Get UniProt IDs for the current query
            uniprot_ids = uniprot_ids_by_query.get(query, [])
            
            # Convert UniProt IDs to gene symbols with rate limiting
            gene_symbols = []
            for uniprot_id in uniprot_ids:
                gene_symbol = uniprot_id_to_gene_symbol(uniprot_id)
                gene_symbols.append(gene_symbol)
                time.sleep(0.1)  # Add a small delay to avoid rate limiting
            
            # Validate genes 
            valid_genes, invalid_genes = validate_genes(gene_symbols)
            
            # Store raw results
            raw_results[query] = {
                "matched_disease": matched_diseases.get(query, ""),
                "total_uniprot_ids_found": len(uniprot_ids),
                "total_gene_symbols_converted": len(gene_symbols),
                "valid_genes": len(valid_genes),
                "invalid_genes": len(invalid_genes)
            }
            
            # Create a set of unique valid genes (to remove duplicates)
            unique_valid_genes = list(set(valid_genes))
            
            # Since all scores are conceptually equal (all are from UniProt variants), assign equal raw scores
            raw_scores = [1.0] * len(unique_valid_genes)
            
            # Normalize scores 
            normalized_scores = normalize_scores(raw_scores, temperature=1.0)
            
            # Create final results with normalized scores
            final_results[query] = [
                {"gene": gene, "score": score} 
                for gene, score in zip(unique_valid_genes, normalized_scores)
            ]
        
        return {
            "status": "success",
            "metadata": {
                "queries_processed": len(query_list),
                "diseases_matched": {
                    query: matched_diseases.get(query, "")
                    for query in query_list
                },
                "genes_found": {
                    query: len(final_results.get(query, []))
                    for query in query_list
                },
                "api_cache_size": len(uniprot_id_cache)
            },
            "raw_results": raw_results,
            "final_results": final_results
        }
        
    except Exception as e:
        return {
            "status": "error",
            "error_message": str(e),
            "raw_results": {},
            "final_results": {}
        }


if __name__ == "__main__":
    # Example usage for all tools
    
    # Test gene validation
    test_genes = ['TP53', 'BRCA1', 'NOTAREALGENE', 'BRAF']
    valid, invalid = validate_genes(test_genes)
    print("Valid genes:", valid)
    print("Invalid genes:", invalid)
    
    # Test original tools
    print("\n--- Testing KEGG pathway search ---")
    kegg_result = kegg_pathway_search(['apoptosis'])
    print(f"KEGG result status: {kegg_result['status']}")
    
    print("\n--- Testing disease gene search ---")
    disease_result = disease_gene_search(['breast cancer'])
    print(f"Disease result status: {disease_result['status']}")
    
    print("\n--- Testing STRING database search ---")
    string_result = string_database_search(['TP53', 'BRCA1'])
    print(f"STRING result status: {string_result['status']}")
    
    print("\n--- Testing GO terms search ---") 
    go_result = go_terms_search(['DNA repair', 'cell cycle'])
    print(f"GO result status: {go_result['status']}")
    
    print("\n--- Testing screen data analysis ---")
    # Note: This would need an actual CSV file to work properly
    print("Screen data analysis requires a CSV file - skipping actual test")
    
    print("\n--- Testing TCGA survival analysis ---")
    tcga_result = tcga_survival_analysis(['breast cancer'])
    print(f"TCGA result status: {tcga_result['status']}")
    
    print("\n--- Testing drug gene network search ---")
    drug_network_result = drug_gene_network_search(['aspirin', 'metformin'])
    print(f"Drug network result status: {drug_network_result['status']}")
    
    print("\n--- Testing PubChem drug gene search ---")
    pubchem_result = pubchem_drug_gene_search(['aspirin'])
    print(f"PubChem result status: {pubchem_result['status']}")
    
    # Test newly added tools
    print("\n--- Testing HPO phenotype search ---")
    hpo_result = hpo_phenotype_search(['ataxia', 'seizures'])
    print(f"HPO result status: {hpo_result['status']}")
    
    print("\n--- Testing OMIM disease search ---")
    omim_result = omim_disease_search(['cystic fibrosis'])
    print(f"OMIM result status: {omim_result['status']}")
    
    print("\n--- Testing Orphanet rare disease search ---")
    orphanet_result = orphanet_rare_disease_search(['huntington disease'])
    print(f"Orphanet result status: {orphanet_result['status']}")
    
    print("\n--- Testing COXPres coexpression search ---")
    coxpres_result = coxpres_coexpression_search(['TP53', 'BRCA1'])
    print(f"COXPres result status: {coxpres_result['status']}")
    
    print("\n--- Testing Ensembl paralog search ---")
    ensembl_result = ensembl_paralog_search(['TP53', 'BRCA1'])
    print(f"Ensembl result status: {ensembl_result['status']}")
    
    print("\n--- Testing GSEA hallmark search ---")
    gsea_result = gsea_hallmark_search(['inflammatory response', 'glycolysis'])
    print(f"GSEA result status: {gsea_result['status']}")
    
    print("\n--- Testing WikiPathways search ---")
    wiki_result = wikipathways_search(['insulin signaling', 'apoptosis'])
    print(f"WikiPathways result status: {wiki_result['status']}")
    
    print("\n--- Testing Reactome pathway search ---")
    reactome_result = reactome_pathway_search(['insulin signaling', 'apoptosis'])
    print(f"Reactome result status: {reactome_result['status']}")
    
    print("\n--- Testing Cancer Biomarkers search ---")
    cancer_biomarkers_result = cancer_biomarkers_search(['breast cancer'])
    print(f"Cancer Biomarkers result status: {cancer_biomarkers_result['status']}")
    
    print("\n--- Testing ClinGen search ---")
    clingen_result = clingen_search(['cystic fibrosis'])
    print(f"ClinGen result status: {clingen_result['status']}")
    
    print("\n--- Testing Gene2Phenotype search ---")
    gene2phenotype_result = gene2phenotype_search(['Joubert syndrome', 'Kniest dysplasia'])
    print(f"Gene2Phenotype result status: {gene2phenotype_result['status']}")
    
    print("\n--- Testing Gene Burden search ---")
    gene_burden_result = gene_burden_search(['Cholesterol', 'Endometrial cancer'])
    print(f"Gene Burden result status: {gene_burden_result['status']}")
    
    print("\n--- Testing IntOGen search ---")
    intogen_result = intogen_search(['Breast cancer', 'Glioblastoma'])
    print(f"IntOGen result status: {intogen_result['status']}")
    
    print("\n--- Testing GOCC Cellular Component search ---")
    gocc_result = gocc_cellular_component_search(['nuclear membrane', 'ribosome'])
    print(f"GOCC Cellular Component result status: {gocc_result['status']}")
    
    print("\n--- Testing ClinVar search ---")
    clinvar_result = clinvar_search(['BRCA1 mutation', 'Cystic fibrosis'])
    print(f"ClinVar result status: {clinvar_result['status']}")
    
    print("\n--- Testing UniProt Variants search ---")
    uniprot_variants_result = uniprot_variants_search(['Methylglutaryl-CoA lyase deficiency', '3-ketothiolase deficiency'])
    print(f"UniProt Variants result status: {uniprot_variants_result['status']}")
    
    print("\n=== All tool tests completed ===")
    print("Note: Some tests may show 'error' status due to missing resources or API limitations, which is expected.")