File size: 198,666 Bytes
d1ce356 | 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 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 | import json
import os
import pickle
import time
from typing import Any
import requests
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.Seq import Seq
from langchain_core.messages import HumanMessage, SystemMessage
from biomni.llm import get_llm
from biomni.utils import parse_hpo_obo
# Function to map HPO terms to names
def get_hpo_names(hpo_terms: list[str], data_lake_path: str) -> list[str]:
"""Retrieve the names of given HPO terms.
Args:
hpo_terms (List[str]): A list of HPO terms (e.g., ['HP:0001250']).
Returns:
List[str]: A list of corresponding HPO term names.
"""
hp_dict = parse_hpo_obo(data_lake_path + "/hp.obo")
hpo_names = []
for term in hpo_terms:
name = hp_dict.get(term, f"Unknown term: {term}")
hpo_names.append(name)
return hpo_names
def _query_llm_for_api(prompt, schema, system_template):
"""Helper function to query LLMs for generating API calls based on natural language prompts.
Supports multiple model providers including Claude, Gemini, GPT, and others via the unified get_llm interface.
Parameters
----------
prompt (str): Natural language query to process
schema (dict): API schema to include in the system prompt
system_template (str): Template string for the system prompt (should have {schema} placeholder)
Returns
-------
dict: Dictionary with 'success', 'data' (if successful), 'error' (if failed), and optional 'raw_response'
"""
# Use global config for model and api_key
try:
from biomni.config import default_config
model = default_config.llm
api_key = default_config.api_key
except ImportError:
model = "claude-3-5-haiku-20241022"
api_key = None
try:
# Format the system prompt with schema if provided
if schema is not None:
schema_json = json.dumps(schema, indent=2)
system_prompt = system_template.format(schema=schema_json)
else:
system_prompt = system_template
# Get LLM instance using the unified interface with config
try:
from biomni.config import default_config
llm = get_llm(model=model, temperature=0.0, api_key=api_key, config=default_config)
except ImportError:
llm = get_llm(model=model, temperature=0.0, api_key=api_key or "EMPTY")
# Compose messages
messages = [
SystemMessage(content=system_prompt),
HumanMessage(content=prompt),
]
# Query the LLM
response = llm.invoke(messages)
llm_text = response.content.strip()
# Find JSON boundaries (in case LLM adds explanations)
json_start = llm_text.find("{")
json_end = llm_text.rfind("}") + 1
if json_start >= 0 and json_end > json_start:
json_text = llm_text[json_start:json_end]
result = json.loads(json_text)
else:
# If no JSON found, try the whole response
result = json.loads(llm_text)
return {"success": True, "data": result, "raw_response": llm_text}
except (json.JSONDecodeError, KeyError, IndexError) as e:
return {
"success": False,
"error": f"Failed to parse LLM response: {str(e)}",
"raw_response": llm_text if "llm_text" in locals() else "No content found",
}
except Exception as e:
return {"success": False, "error": f"Error querying LLM: {str(e)}"}
def _query_rest_api(endpoint, method="GET", params=None, headers=None, json_data=None, description=None):
"""General helper function to query REST APIs with consistent error handling.
Parameters
----------
endpoint (str): Full URL endpoint to query
method (str): HTTP method ("GET" or "POST")
params (dict, optional): Query parameters to include in the URL
headers (dict, optional): HTTP headers for the request
json_data (dict, optional): JSON data for POST requests
description (str, optional): Description of this query for error messages
Returns
-------
dict: Dictionary containing the result or error information
"""
# Set default headers if not provided
if headers is None:
headers = {"Accept": "application/json"}
# Set default description if not provided
if description is None:
description = f"{method} request to {endpoint}"
url_error = None
try:
# Make the API request
if method.upper() == "GET":
response = requests.get(endpoint, params=params, headers=headers)
elif method.upper() == "POST":
response = requests.post(endpoint, params=params, headers=headers, json=json_data)
else:
return {"error": f"Unsupported HTTP method: {method}"}
url_error = str(response.text)
response.raise_for_status()
# Try to parse JSON response
try:
result = response.json()
except ValueError:
# Return raw text if not JSON
result = {"raw_text": response.text}
return {
"success": True,
"query_info": {
"endpoint": endpoint,
"method": method,
"description": description,
},
"result": result,
}
except Exception as e:
error_msg = str(e)
response_text = ""
# Try to get more detailed error info from response
if hasattr(e, "response") and e.response:
try:
error_json = e.response.json()
if "messages" in error_json:
error_msg = "; ".join(error_json["messages"])
elif "message" in error_json:
error_msg = error_json["message"]
elif "error" in error_json:
error_msg = error_json["error"]
elif "detail" in error_json:
error_msg = error_json["detail"]
except Exception:
response_text = e.response.text
return {
"success": False,
"error": f"API error: {error_msg}",
"query_info": {
"endpoint": endpoint,
"method": method,
"description": description,
},
"response_url_error": url_error,
"response_text": response_text,
}
def _query_ncbi_database(
database: str,
search_term: str,
result_formatter=None,
max_results: int = 3,
) -> dict[str, Any]:
"""Core function to query NCBI databases using Claude for query interpretation and NCBI eutils.
Parameters
----------
database (str): NCBI database to query (e.g., "clinvar", "gds", "geoprofiles")
result_formatter (callable): Function to format results from the database
api_key (str): Anthropic API key. If None, will look for ANTHROPIC_API_KEY environment variable
model (str): Anthropic model to use
max_results (int): Maximum number of results to return
verbose (bool): Whether to return verbose results
Returns
-------
dict: Dictionary containing both the structured query and the results
"""
# Query NCBI API using the structured search term
esearch_url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi"
esearch_params = {
"db": database,
"term": search_term,
"retmode": "json",
"retmax": 100,
"usehistory": "y", # Use history server to store results
}
# Get IDs of matching entries
search_response = _query_rest_api(
endpoint=esearch_url,
method="GET",
params=esearch_params,
description="NCBI ESearch API query",
)
if not search_response["success"]:
return search_response
search_data = search_response["result"]
# If we have results, fetch the details
if "esearchresult" in search_data and int(search_data["esearchresult"]["count"]) > 0:
# Extract WebEnv and query_key from the search results
webenv = search_data["esearchresult"].get("webenv", "")
query_key = search_data["esearchresult"].get("querykey", "")
# Use WebEnv and query_key if available
if webenv and query_key:
# Get details using eSummary
esummary_url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi"
esummary_params = {
"db": database,
"query_key": query_key,
"WebEnv": webenv,
"retmode": "json",
"retmax": max_results,
}
details_response = _query_rest_api(
endpoint=esummary_url,
method="GET",
params=esummary_params,
description="NCBI ESummary API query",
)
if not details_response["success"]:
return details_response
results = details_response["result"]
else:
# Fall back to direct ID fetch
id_list = search_data["esearchresult"]["idlist"][:max_results]
# Get details for each ID
esummary_url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi"
esummary_params = {
"db": database,
"id": ",".join(id_list),
"retmode": "json",
}
details_response = _query_rest_api(
endpoint=esummary_url,
method="GET",
params=esummary_params,
description="NCBI ESummary API query",
)
if not details_response["success"]:
return details_response
results = details_response["result"]
# Format results using the provided formatter
formatted_results = result_formatter(results) if result_formatter else results
# Return the combined information
return {
"database": database,
"query_interpretation": search_term,
"total_results": int(search_data["esearchresult"]["count"]),
"formatted_results": formatted_results,
}
else:
return {
"database": database,
"query_interpretation": search_term,
"total_results": 0,
"formatted_results": [],
}
def _format_query_results(result, options=None):
"""A general-purpose formatter for query function results to reduce output size.
Parameters
----------
result (dict): The original API response dictionary
options (dict, optional): Formatting options including:
- max_items (int): Maximum number of items to include in lists (default: 5)
- max_depth (int): Maximum depth to traverse in nested dictionaries (default: 2)
- include_keys (list): Only include these top-level keys (overrides exclude_keys)
- exclude_keys (list): Exclude these keys from the output
- summarize_lists (bool): Whether to summarize long lists (default: True)
- truncate_strings (int): Maximum length for string values (default: 100)
Returns
-------
dict: A condensed version of the input results
"""
def _format_value(value, depth, options):
"""Recursively format a value based on its type and formatting options.
Parameters
----------
value: The value to format
depth (int): Current recursion depth
options (dict): Formatting options
Returns
-------
Formatted value
"""
# Base case: reached max depth
if depth >= options["max_depth"] and (isinstance(value, dict | list)):
if isinstance(value, dict):
return {
"_summary": f"Nested dictionary with {len(value)} keys",
"_keys": list(value.keys())[: options["max_items"]],
}
else: # list
return _summarize_list(value, options)
# Process based on type
if isinstance(value, dict):
return _format_dict(value, depth, options)
elif isinstance(value, list):
return _format_list(value, depth, options)
elif isinstance(value, str) and len(value) > options["truncate_strings"]:
return value[: options["truncate_strings"]] + "... (truncated)"
else:
return value
def _format_dict(d, depth, options):
"""Format a dictionary according to options."""
result = {}
# Filter keys based on include/exclude options
keys_to_process = d.keys()
if depth == 0 and options["include_keys"]: # Only apply at top level
keys_to_process = [k for k in keys_to_process if k in options["include_keys"]]
elif depth == 0 and options["exclude_keys"]: # Only apply at top level
keys_to_process = [k for k in keys_to_process if k not in options["exclude_keys"]]
# Process each key
for key in keys_to_process:
result[key] = _format_value(d[key], depth + 1, options)
return result
def _format_list(lst, depth, options):
"""Format a list according to options."""
if options["summarize_lists"] and len(lst) > options["max_items"]:
return _summarize_list(lst, options)
result = []
for i, item in enumerate(lst):
if i >= options["max_items"]:
remaining = len(lst) - options["max_items"]
result.append(f"... {remaining} more items (omitted)")
break
result.append(_format_value(item, depth + 1, options))
return result
def _summarize_list(lst, options):
"""Create a summary for a list."""
if not lst:
return []
# Sample a few items
sample = lst[: min(3, len(lst))]
sample_formatted = [_format_value(item, options["max_depth"], options) for item in sample]
# For homogeneous lists, provide type info
if len(lst) > 0:
item_type = type(lst[0]).__name__
homogeneous = all(isinstance(item, type(lst[0])) for item in lst)
type_info = f"all {item_type}" if homogeneous else "mixed types"
else:
type_info = "empty"
return {
"_summary": f"List with {len(lst)} items ({type_info})",
"_sample": sample_formatted,
}
if options is None:
options = {}
# Default options
default_options = {
"max_items": 5,
"max_depth": 20,
"include_keys": None,
"exclude_keys": ["raw_response", "debug_info", "request_details"],
"summarize_lists": True,
"truncate_strings": 100,
}
# Merge provided options with defaults
for key, value in default_options.items():
if key not in options:
options[key] = value
# Filter and format the result
formatted = _format_value(result, 0, options)
return formatted
def query_uniprot(
prompt=None,
endpoint=None,
max_results=5,
):
"""Query the UniProt REST API using either natural language or a direct endpoint.
Parameters
----------
prompt (str, required): Natural language query about proteins (e.g., "Find information about human insulin")
endpoint (str, optional): Full or partial UniProt API endpoint URL to query directly
(e.g., "https://rest.uniprot.org/uniprotkb/P01308")
max_results (int): Maximum number of results to return
Returns
-------
dict: Dictionary containing the query information and the UniProt API results
Examples
--------
- Natural language: query_uniprot(prompt="Find information about human insulin protein")
- Direct endpoint: query_uniprot(endpoint="https://rest.uniprot.org/uniprotkb/P01308")
"""
# Base URL for UniProt API
base_url = "https://rest.uniprot.org"
# Ensure we have either a prompt or an endpoint
if prompt is None and endpoint is None:
return {"error": "Either a prompt or an endpoint must be provided"}
# If using prompt, parse with Claude
if prompt:
# Load UniProt schema
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "uniprot.pkl")
with open(schema_path, "rb") as f:
uniprot_schema = pickle.load(f)
# Create system prompt template
system_template = """
You are a protein biology expert specialized in using the UniProt REST API.
Based on the user's natural language request, determine the appropriate UniProt REST API endpoint and parameters.
UNIPROT REST API SCHEMA:
{schema}
Your response should be a JSON object with the following fields:
1. "full_url": The complete URL to query (including base URL, dataset, endpoint type, and parameters)
2. "description": A brief description of what the query is doing
SPECIAL NOTES:
- Base URL is "https://rest.uniprot.org"
- Search in reviewed (Swiss-Prot) entries first before using non-reviewed (TrEMBL) entries
- Assume organism is human unless otherwise specified. Human taxonomy ID is 9606
- Use gene_exact: for exact gene name searches
- Use specific query fields like accession:, gene:, organism_id: in search queries
- Use quotes for terms with spaces: organism_name:"Homo sapiens"
Return ONLY the JSON object with no additional text.
"""
# Query Claude to generate the API call
llm_result = _query_llm_for_api(
prompt=prompt,
schema=uniprot_schema,
system_template=system_template,
)
if not llm_result["success"]:
return llm_result
# Get the full URL from Claude's response
query_info = llm_result["data"]
endpoint = query_info.get("full_url", "")
description = query_info.get("description", "")
if not endpoint:
return {
"error": "Failed to generate a valid endpoint from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
else:
# Use provided endpoint directly
if endpoint.startswith("/"):
endpoint = f"{base_url}{endpoint}"
elif not endpoint.startswith("http"):
endpoint = f"{base_url}/{endpoint.lstrip('/')}"
description = "Direct query to provided endpoint"
# Use the common REST API helper function
api_result = _query_rest_api(endpoint=endpoint, method="GET", description=description)
return api_result
def query_alphafold(
uniprot_id,
endpoint="prediction",
residue_range=None,
download=False,
output_dir=None,
file_format="pdb",
model_version="v4",
model_number=1,
):
"""Query the AlphaFold Database API for protein structure predictions.
Parameters
----------
uniprot_id (str): UniProt accession ID (e.g., "P12345")
endpoint (str, optional): Specific AlphaFold API endpoint to query:
"prediction", "summary", or "annotations"
residue_range (str, optional): Specific residue range in format "start-end" (e.g., "1-100")
download (bool): Whether to download structure files
output_dir (str, optional): Directory to save downloaded files (default: current directory)
file_format (str): Format of the structure file to download - "pdb" or "cif"
model_version (str): AlphaFold model version - "v4" (latest) or "v3", "v2", "v1"
model_number (int): Model number (1-5, with 1 being the highest confidence model)
Returns
-------
dict: Dictionary containing both the query information and the AlphaFold results
Examples
--------
- Basic query: query_alphafold(uniprot_id="P53_HUMAN")
- Download structure: query_alphafold(uniprot_id="P53_HUMAN", download=True, output_dir="./structures")
- Get annotations: query_alphafold(uniprot_id="P53_HUMAN", endpoint="annotations")
"""
# Base URL for AlphaFold API
base_url = "https://alphafold.ebi.ac.uk/api"
# Ensure we have a UniProt ID
if not uniprot_id:
return {"error": "UniProt ID is required"}
# Validate endpoint
valid_endpoints = ["prediction", "summary", "annotations"]
if endpoint not in valid_endpoints:
return {"error": f"Invalid endpoint. Must be one of: {', '.join(valid_endpoints)}"}
# Construct the API URL based on endpoint
if endpoint == "prediction":
url = f"{base_url}/prediction/{uniprot_id}"
elif endpoint == "summary":
url = f"{base_url}/uniprot/summary/{uniprot_id}.json"
elif endpoint == "annotations":
if residue_range:
url = f"{base_url}/annotations/{uniprot_id}/{residue_range}"
else:
url = f"{base_url}/annotations/{uniprot_id}"
try:
# Make the API request
response = requests.get(url)
response.raise_for_status()
# Parse the response as JSON
result = response.json()
# Handle download request if specified
download_info = None
if download:
# Ensure output directory exists
if not output_dir:
output_dir = "."
os.makedirs(output_dir, exist_ok=True)
# Generate standard AlphaFold filename
file_ext = file_format.lower()
filename = f"AF-{uniprot_id}-F{model_number}-model_{model_version}.{file_ext}"
file_path = os.path.join(output_dir, filename)
# Construct download URL
download_url = f"https://alphafold.ebi.ac.uk/files/{filename}"
# Download the file
download_response = requests.get(download_url)
if download_response.status_code == 200:
with open(file_path, "wb") as f:
f.write(download_response.content)
download_info = {
"success": True,
"file_path": file_path,
"url": download_url,
}
else:
download_info = {
"success": False,
"error": f"Failed to download file (status code: {download_response.status_code})",
"url": download_url,
}
# Return the query information and results
response_data = {
"query_info": {
"uniprot_id": uniprot_id,
"endpoint": endpoint,
"residue_range": residue_range,
"url": url,
},
"result": result,
}
if download_info:
response_data["download"] = download_info
return response_data
except requests.exceptions.RequestException as e:
error_msg = str(e)
response_text = ""
# Try to get more detailed error info from response
if hasattr(e, "response") and e.response:
try:
error_json = e.response.json()
if "message" in error_json:
error_msg = error_json["message"]
except Exception:
response_text = e.response.text
return {
"error": f"AlphaFold API error: {error_msg}",
"query_info": {
"uniprot_id": uniprot_id,
"endpoint": endpoint,
"residue_range": residue_range,
"url": url,
},
"response_text": response_text,
}
except Exception as e:
return {
"error": f"Error: {str(e)}",
"query_info": {
"uniprot_id": uniprot_id,
"endpoint": endpoint,
"residue_range": residue_range,
},
}
def query_interpro(
prompt=None,
endpoint=None,
max_results=3,
):
"""Query the InterPro REST API using natural language or a direct endpoint.
Parameters
----------
prompt (str, required): Natural language query about protein domains or families
endpoint (str, optional): Direct endpoint path or full URL (e.g., "/entry/interpro/IPR023411"
or "https://www.ebi.ac.uk/interpro/api/entry/interpro/IPR023411")
max_results (int): Maximum number of results to return per page
Returns
-------
dict: Dictionary containing both the query information and the InterPro API results
Examples
--------
- Natural language: query_interpro("Find information about kinase domains in InterPro")
- Direct endpoint: query_interpro(endpoint="/entry/interpro/IPR023411")
"""
# Base URL for InterPro API
base_url = "https://www.ebi.ac.uk/interpro/api"
# Default parameters
format = "json"
# Ensure we have either a prompt or an endpoint
if prompt is None and endpoint is None:
return {"error": "Either a prompt or an endpoint must be provided"}
# If using prompt, parse with Claude
if prompt:
# Load InterPro schema
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "interpro.pkl")
with open(schema_path, "rb") as f:
interpro_schema = pickle.load(f)
# Create system prompt template
system_template = """
You are a protein domain expert specialized in using the InterPro REST API.
Based on the user's natural language request, determine the appropriate InterPro REST API endpoint.
INTERPRO REST API SCHEMA:
{schema}
Your response should be a JSON object with the following fields:
1. "full_url": The complete URL to query (including the base URL "https://www.ebi.ac.uk/interpro/api")
2. "description": A brief description of what the query is doing
SPECIAL NOTES:
- Path components for data types: entry, protein, structure, set, taxonomy, proteome
- Common sources: interpro, pfam, cdd, uniprot, pdb
- Protein subtypes can be "reviewed" or "unreviewed"
- For specific entries, use lowercase accessions (e.g., "ipr000001" instead of "IPR000001")
- Endpoints can be hierarchical like "/entry/interpro/protein/uniprot/P04637"
Return ONLY the JSON object with no additional text.
"""
# Query Claude to generate the API call
llm_result = _query_llm_for_api(
prompt=prompt,
schema=interpro_schema,
system_template=system_template,
)
if not llm_result["success"]:
return llm_result
# Extract the full URL from Claude's response
query_info = llm_result["data"]
endpoint = query_info.get("full_url", "")
description = query_info.get("description", "")
if not endpoint:
return {
"error": "Failed to generate a valid endpoint from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
else:
# Process provided endpoint
# If it's just a path, add the base URL
if endpoint.startswith("/"):
endpoint = f"{base_url}{endpoint}"
elif not endpoint.startswith("http"):
endpoint = f"{base_url}/{endpoint.lstrip('/')}"
description = "Direct query to provided endpoint"
# Add pagination parameters
params = {"page": 1, "page_size": max_results}
# Add format parameter if not json
if format and format != "json":
params["format"] = format
# Make the API request
api_result = _query_rest_api(endpoint=endpoint, method="GET", params=params, description=description)
return api_result
def query_pdb(
prompt=None,
query=None,
max_results=3,
):
"""Query the RCSB PDB database using natural language or a direct structured query.
Parameters
----------
prompt (str, required): Natural language query about protein structures
query (dict, optional): Direct structured query in RCSB Search API format (overrides prompt)
max_results (int): Maximum number of results to return
Returns
-------
dict: Dictionary containing the structured query, search results, and identifiers
Examples
--------
- Natural language: query_pdb("Find structures of human insulin")
- Direct query: query_pdb(query={"query": {"type": "terminal", "service": "full_text",
"parameters": {"value": "insulin"}}, "return_type": "entry"})
"""
# Default parameters
return_type = "entry"
search_service = "full_text"
# Generate search query from natural language if prompt is provided and query is not
if prompt and not query:
# Load schema from pickle file
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "pdb.pkl")
with open(schema_path, "rb") as f:
schema = pickle.load(f)
# Create system prompt template
system_template = """
You are a structural biology expert that creates precise RCSB PDB Search API queries based on natural language requests.
SEARCH API SCHEMA:
{schema}
IMPORTANT GUIDELINES:
1. Choose the appropriate search_service based on the query:
- Use "text" for attribute-specific searches (REQUIRES attribute, operator, and value)
- Use "full_text" for general keyword searches across multiple fields
- Use appropriate specialized services for sequence, structure, motif searches
2. For "text" searches, you MUST specify:
- attribute: The specific field to search (use common_attributes from schema)
- operator: The comparison method (exact_match, contains_words, less_or_equal, etc.)
- value: The search term or value
3. For "full_text" searches, only specify:
- value: The search term(s)
4. For combined searches, use "group" nodes with logical_operator ("and" or "or")
5. Always specify the appropriate return_type based on what the user is looking for
Generate a well-formed Search API query JSON object. Return ONLY the JSON with no additional explanation.
"""
# Query Claude to generate the search query
llm_result = _query_llm_for_api(
prompt=prompt,
schema=schema,
system_template=system_template,
)
if not llm_result["success"]:
return {
"error": llm_result["error"],
"llm_response": llm_result.get("raw_response", "No response"),
}
# Get the query from Claude's response
query_json = llm_result["data"]
else:
# Use provided query directly
query_json = (
query
if query
else {
"query": {
"type": "terminal",
"service": search_service,
"parameters": {"value": prompt},
},
"return_type": return_type,
}
)
# Ensure return_type is set
if "return_type" not in query_json:
query_json["return_type"] = return_type
# Add request options for pagination
if "request_options" not in query_json:
query_json["request_options"] = {}
if "paginate" not in query_json["request_options"]:
query_json["request_options"]["paginate"] = {"start": 0, "rows": max_results}
# Use query_rest_api to execute the search
search_url = "https://search.rcsb.org/rcsbsearch/v2/query"
api_result = _query_rest_api(
endpoint=search_url,
method="POST",
json_data=query_json,
description="PDB Search API query",
)
return api_result
def query_pdb_identifiers(identifiers, return_type="entry", download=False, attributes=None):
"""Retrieve detailed data and/or download files for PDB identifiers.
Parameters
----------
identifiers (list): List of PDB identifiers (from query_pdb)
return_type (str): Type of results: "entry", "assembly", "polymer_entity", etc.
download (bool): Whether to download PDB structure files
attributes (list, optional): List of specific attributes to retrieve
Returns
-------
dict: Dictionary containing the detailed data and file paths if downloaded
Example:
- Search and then get details:
results = query_pdb("Find structures of human insulin")
details = get_pdb_details(results["identifiers"], download=True)
"""
if not identifiers:
return {"error": "No identifiers provided"}
try:
# Fetch detailed data using Data API
detailed_results = []
for identifier in identifiers:
try:
# Determine the appropriate endpoint based on return_type and identifier format
if return_type == "entry":
data_url = f"https://data.rcsb.org/rest/v1/core/entry/{identifier}"
elif return_type == "polymer_entity":
entry_id, entity_id = identifier.split("_")
data_url = f"https://data.rcsb.org/rest/v1/core/polymer_entity/{entry_id}/{entity_id}"
elif return_type == "nonpolymer_entity":
entry_id, entity_id = identifier.split("_")
data_url = f"https://data.rcsb.org/rest/v1/core/nonpolymer_entity/{entry_id}/{entity_id}"
elif return_type == "polymer_instance":
entry_id, asym_id = identifier.split(".")
data_url = f"https://data.rcsb.org/rest/v1/core/polymer_entity_instance/{entry_id}/{asym_id}"
elif return_type == "assembly":
entry_id, assembly_id = identifier.split("-")
data_url = f"https://data.rcsb.org/rest/v1/core/assembly/{entry_id}/{assembly_id}"
elif return_type == "mol_definition":
data_url = f"https://data.rcsb.org/rest/v1/core/chem_comp/{identifier}"
# Fetch data
data_response = requests.get(data_url)
data_response.raise_for_status()
entity_data = data_response.json()
# Filter attributes if specified
if attributes:
filtered_data = {}
for attr in attributes:
parts = attr.split(".")
current = entity_data
try:
for part in parts[:-1]:
current = current[part]
filtered_data[attr] = current[parts[-1]]
except (KeyError, TypeError):
filtered_data[attr] = None
entity_data = filtered_data
detailed_results.append({"identifier": identifier, "data": entity_data})
except Exception as e:
detailed_results.append({"identifier": identifier, "error": str(e)})
# Download structure files if requested
if download:
for identifier in identifiers:
if "_" in identifier or "." in identifier or "-" in identifier:
# For non-entry identifiers, extract the PDB ID
if "_" in identifier:
pdb_id = identifier.split("_")[0]
elif "." in identifier:
pdb_id = identifier.split(".")[0]
elif "-" in identifier:
pdb_id = identifier.split("-")[0]
else:
pdb_id = identifier
try:
# Download PDB file
pdb_url = f"https://files.rcsb.org/download/{pdb_id}.pdb"
pdb_response = requests.get(pdb_url)
if pdb_response.status_code == 200:
# Create data directory if it doesn't exist
data_dir = os.path.join(os.path.dirname(__file__), "data", "pdb")
os.makedirs(data_dir, exist_ok=True)
# Save PDB file
pdb_file_path = os.path.join(data_dir, f"{pdb_id}.pdb")
with open(pdb_file_path, "wb") as pdb_file:
pdb_file.write(pdb_response.content)
# Add download information to results
for result in detailed_results:
if result["identifier"] == identifier or result["identifier"].startswith(pdb_id):
result["pdb_file_path"] = pdb_file_path
except Exception as e:
for result in detailed_results:
if result["identifier"] == identifier or result["identifier"].startswith(pdb_id):
result["download_error"] = str(e)
return {"detailed_results": detailed_results}
except Exception as e:
return {"error": f"Error retrieving PDB details: {str(e)}"}
def query_kegg(prompt, endpoint=None, verbose=True):
"""Take a natural language prompt and convert it to a structured KEGG API query.
Parameters
----------
prompt (str): Natural language query about KEGG data (e.g., "Find human pathways related to glycolysis")
endpoint (str, optional): Direct KEGG API endpoint to query
verbose (bool): Whether to print verbose output
Returns
-------
dict: Dictionary containing both the structured query and the KEGG results
"""
base_url = "https://rest.kegg.jp"
if not prompt and not endpoint:
return {"error": "Either a prompt or an endpoint must be provided"}
if prompt:
# Load schema from pickle file
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "kegg.pkl")
with open(schema_path, "rb") as f:
kegg_schema = pickle.load(f)
# Create system prompt template
system_template = """
You are a bioinformatics expert that helps convert natural language queries into KEGG API requests.
Based on the user's natural language request, you will generate a structured query for the KEGG API.
The KEGG API has the following general form:
https://rest.kegg.jp/<operation>/<argument>[/<argument2>[/<argument3> ...]]
Where <operation> can be one of: info, list, find, get, conv, link, ddi
Here is the schema of available operations, databases, and other details:
{schema}
Output only a JSON object with the following fields:
1. "full_url": The complete URL to query (including the base URL "https://rest.kegg.jp")
2. "description": A brief description of what the query is doing
IMPORTANT: Your response must ONLY contain a JSON object with the required fields.
EXAMPLES OF CORRECT OUTPUTS:
- For "Find information about glycolysis pathway": {{"full_url": "https://rest.kegg.jp/info/pathway/hsa00010", "description": "Finding information about the glycolysis pathway"}}
- For "Get information about the human BRCA1 gene": {{"full_url": "https://rest.kegg.jp/get/hsa:672", "description": "Retrieving information about BRCA1 gene in human"}}
- For "List all human pathways": {{"full_url": "https://rest.kegg.jp/list/pathway/hsa", "description": "Listing all human-specific pathways"}}
- For "Convert NCBI gene ID 672 to KEGG ID": {{"full_url": "https://rest.kegg.jp/conv/genes/ncbi-geneid:672", "description": "Converting NCBI Gene ID 672 to KEGG gene identifier"}}
"""
# Query LLM to generate the API call
llm_result = _query_llm_for_api(
prompt=prompt,
schema=kegg_schema,
system_template=system_template,
)
if not llm_result["success"]:
return llm_result
# Extract the query info from Claude's response
query_info = llm_result["data"]
endpoint = query_info["full_url"]
description = query_info["description"]
if not endpoint:
return {
"error": "Failed to generate a valid endpoint from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
if endpoint:
if endpoint.startswith("/"):
endpoint = f"{base_url}{endpoint}"
elif not endpoint.startswith("http"):
endpoint = f"{base_url}/{endpoint.lstrip('/')}"
description = "Direct query to KEGG API"
# Execute the KEGG API request using the helper function
api_result = _query_rest_api(endpoint=endpoint, method="GET", description=description)
if not verbose and "success" in api_result and api_result["success"] and "result" in api_result:
return _format_query_results(api_result["result"])
return api_result
def query_stringdb(
prompt=None,
endpoint=None,
download_image=False,
output_dir=None,
verbose=True,
):
"""Query the STRING protein interaction database using natural language or direct endpoint.
Parameters
----------
prompt (str, required): Natural language query about protein interactions
endpoint (str, optional): Full URL to query directly (overrides prompt)
download_image (bool): Whether to download image results (for image endpoints)
output_dir (str, optional): Directory to save downloaded files (default: current directory)
Returns
-------
dict: Dictionary containing the query results or error information
Examples
--------
- Natural language: query_stringdb("Show protein interactions for BRCA1 and BRCA2 in humans")
- Direct endpoint: query_stringdb(endpoint="https://string-db.org/api/json/network?identifiers=BRCA1,BRCA2&species=9606")
"""
# Base URL for STRING API
base_url = "https://version-12-0.string-db.org/api"
# Ensure we have either a prompt or an endpoint
if prompt is None and endpoint is None:
return {"error": "Either a prompt or an endpoint must be provided"}
# If using prompt, parse with Claude
if prompt:
# Load STRING schema
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "stringdb.pkl")
with open(schema_path, "rb") as f:
stringdb_schema = pickle.load(f)
# Create system prompt template
system_template = """
You are a protein interaction expert specialized in using the STRING database API.
Based on the user's natural language request, determine the appropriate STRING API endpoint and parameters.
STRING API SCHEMA:
{schema}
Your response should be a JSON object with the following fields:
1. "full_url": The complete URL to query (including all parameters)
2. "description": A brief description of what the query is doing
3. "output_format": The format of the output (json, tsv, image, svg)
SPECIAL NOTES:
- Common species IDs: 9606 (human), 10090 (mouse), 7227 (fruit fly), 4932 (yeast)
- For protein identifiers, use either gene names (e.g., "BRCA1") or UniProt IDs (e.g., "P38398")
- The "required_score" parameter accepts values from 0 to 1000 (higher means more stringent)
- Add "caller_identity=bioagentos_api" as a parameter
Return ONLY the JSON object with no additional text.
"""
# Query Claude to generate the API call
llm_result = _query_llm_for_api(
prompt=prompt,
schema=stringdb_schema,
system_template=system_template,
)
if not llm_result["success"]:
return llm_result
# Get the full URL from Claude's response
query_info = llm_result["data"]
endpoint = query_info.get("full_url", "")
description = query_info.get("description", "")
output_format = query_info.get("output_format", "json")
if not endpoint:
return {
"error": "Failed to generate a valid endpoint from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
else:
# Use direct endpoint
if endpoint.startswith("/"):
endpoint = f"{base_url}{endpoint}"
elif not endpoint.startswith("http"):
endpoint = f"{base_url}/{endpoint.lstrip('/')}"
description = "Direct query to STRING API"
output_format = "json"
# Try to determine output format from URL
if "image" in endpoint or "svg" in endpoint:
output_format = "image"
# Check if we're dealing with an image request
is_image = output_format in ["image", "highres_image", "svg"]
if is_image:
if download_image:
# For images, we need to handle the download manually
try:
response = requests.get(endpoint, stream=True)
response.raise_for_status()
# Create output directory if needed
if not output_dir:
output_dir = "."
os.makedirs(output_dir, exist_ok=True)
# Generate filename based on endpoint
endpoint_parts = endpoint.split("/")
filename = f"string_{endpoint_parts[-2]}_{int(time.time())}.{output_format}"
file_path = os.path.join(output_dir, filename)
# Save the image
with open(file_path, "wb") as f:
for chunk in response.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
return {
"success": True,
"query_info": {
"endpoint": endpoint,
"description": description,
"output_format": output_format,
},
"result": {
"image_saved": True,
"file_path": file_path,
"content_type": response.headers.get("Content-Type"),
},
}
except Exception as e:
return {
"success": False,
"error": f"Error downloading image: {str(e)}",
"query_info": {"endpoint": endpoint, "description": description},
}
else:
# Just report that an image is available but not downloaded
return {
"success": True,
"query_info": {
"endpoint": endpoint,
"description": description,
"output_format": output_format,
},
"result": {
"image_available": True,
"download_url": endpoint,
"note": "Set download_image=True to save the image",
},
}
# For non-image requests, use the REST API helper
api_result = _query_rest_api(endpoint=endpoint, method="GET", description=description)
if not verbose and "success" in api_result and api_result["success"] and "result" in api_result:
return _format_query_results(api_result["result"])
return api_result
def query_iucn(
prompt=None,
endpoint=None,
token="",
verbose=True,
):
"""Query the IUCN Red List API using natural language or a direct endpoint.
Parameters
----------
prompt (str, required): Natural language query about species conservation status
endpoint (str, optional): API endpoint name (e.g., "species/id/12392") or full URL
token (str): IUCN API token - required for all queries
verbose (bool): Whether to print verbose output
Returns
-------
dict: Dictionary containing the query results or error information
Examples
--------
- Natural language: query_iucn("Get conservation status of white rhinoceros", token="your-token")
- Direct endpoint: query_iucn(endpoint="species/id/12392", token="your-token")
"""
# Base URL for IUCN API
base_url = "https://apiv3.iucnredlist.org/api/v3"
# Ensure we have either a prompt or an endpoint
if prompt is None and endpoint is None:
return {"error": "Either a prompt or an endpoint must be provided"}
# Ensure we have a token
if not token:
return {"error": "IUCN API token is required. Get one at https://apiv3.iucnredlist.org/api/v3/token"}
# If using prompt, parse with Claude
if prompt:
# Load IUCN schema
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "iucn.pkl")
with open(schema_path, "rb") as f:
iucn_schema = pickle.load(f)
# Create system prompt template
system_template = """
You are a conservation biology expert specialized in using the IUCN Red List API.
Based on the user's natural language request, determine the appropriate IUCN API endpoint.
IUCN API SCHEMA:
{schema}
Your response should be a JSON object with the following fields:
1. "full_url": The complete URL to query (including the base URL "https://apiv3.iucnredlist.org/api/v3" and any path parameters)
2. "description": A brief description of what the query is doing
SPECIAL NOTES:
- The token parameter will be added automatically, do not include it in your URL
- For taxonomic queries, prefer using scientific names over common names
- For region-specific queries, use region identifiers from the schema
- For species queries, try to use the species ID if known, otherwise use scientific name
Return ONLY the JSON object with no additional text.
"""
# Query Claude to generate the API call
llm_result = _query_llm_for_api(
prompt=prompt,
schema=iucn_schema,
system_template=system_template,
)
if not llm_result["success"]:
return llm_result
# Get the full URL from Claude's response
query_info = llm_result["data"]
endpoint = query_info.get("full_url", "")
description = query_info.get("description", "")
if not endpoint:
return {
"error": "Failed to generate a valid endpoint from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
else:
# Process provided endpoint
if not endpoint.startswith("http"):
endpoint = f"{base_url}{endpoint}" if endpoint.startswith("/") else f"{base_url}/{endpoint}"
description = "Direct query to IUCN API"
# Add token as query parameter
params = {"token": token}
# Execute the IUCN API request using the helper function
api_result = _query_rest_api(endpoint=endpoint, method="GET", params=params, description=description)
# For security, remove token from the results
if "query_info" in api_result and "endpoint" in api_result["query_info"]:
api_result["query_info"]["endpoint"] = api_result["query_info"]["endpoint"].replace(token, "TOKEN_HIDDEN")
if not verbose and "success" in api_result and api_result["success"] and "result" in api_result:
return _format_query_results(api_result["result"])
return api_result
def query_paleobiology(
prompt=None,
endpoint=None,
verbose=True,
):
"""Query the Paleobiology Database (PBDB) API using natural language or a direct endpoint.
Parameters
----------
prompt (str, required): Natural language query about fossil records
endpoint (str, optional): API endpoint name or full URL
verbose (bool): Whether to print verbose output
Returns
-------
dict: Dictionary containing the query results or error information
Examples
--------
- Natural language: query_paleobiology("Find fossil records of Tyrannosaurus rex")
- Direct endpoint: query_paleobiology(endpoint="data1.2/taxa/list.json?name=Tyrannosaurus")
"""
# Base URL for PBDB API
base_url = "https://paleobiodb.org/data1.2"
# Ensure we have either a prompt or an endpoint
if prompt is None and endpoint is None:
return {"error": "Either a prompt or an endpoint must be provided"}
# If using prompt, parse with Claude
if prompt:
# Load PBDB schema
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "pbdb.pkl")
with open(schema_path, "rb") as f:
pbdb_schema = pickle.load(f)
# Create system prompt template
system_template = """
You are a paleobiology expert specialized in using the Paleobiology Database (PBDB) API.
Based on the user's natural language request, determine the appropriate PBDB API endpoint and parameters.
PBDB API SCHEMA:
{schema}
Your response should be a JSON object with the following fields:
1. "full_url": The complete URL to query (including the base URL "https://paleobiodb.org/data1.2" and format extension)
2. "description": A brief description of what the query is doing
SPECIAL NOTES:
- For taxonomic queries, be specific about taxonomic ranks and names
- For geographic queries, use standard country/continent names or coordinate bounding boxes
- For time interval queries, use standard geological time names (e.g., "Cretaceous", "Maastrichtian")
- Use appropriate format extension (.json, .txt, .csv, .tsv) based on the query
- If appropriate, use "vocab=pbdb" (default) or "vocab=com" (compact) parameter in the URL
- For detailed occurrence data, include "show=paleoloc,phylo" in the parameters
Return ONLY the JSON object with no additional text.
"""
# Query Claude to generate the API call
llm_result = _query_llm_for_api(
prompt=prompt,
schema=pbdb_schema,
system_template=system_template,
)
if not llm_result["success"]:
return llm_result
# Get the full URL from Claude's response
query_info = llm_result["data"]
endpoint = query_info.get("full_url", "")
description = query_info.get("description", "")
if not endpoint:
return {
"error": "Failed to generate a valid endpoint from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
else:
# Process provided endpoint
if not endpoint.startswith("http"):
# Add base URL if it's just a path
endpoint = f"{base_url}/{endpoint}" if not endpoint.startswith("/") else f"{base_url}{endpoint}"
description = "Direct query to PBDB API"
# Check if we're dealing with an image request
is_image = endpoint.endswith(".png")
if is_image:
# For image queries, we need special handling
try:
response = requests.get(endpoint)
response.raise_for_status()
# Return image metadata without the binary data
return {
"success": True,
"query_info": {
"endpoint": endpoint,
"description": description,
"format": "png",
},
"result": {
"content_type": response.headers.get("Content-Type"),
"size_bytes": len(response.content),
"note": "Binary image data not included in response",
},
}
except Exception as e:
return {
"success": False,
"error": f"Error retrieving image: {str(e)}",
"query_info": {"endpoint": endpoint, "description": description},
}
# For non-image requests, use the REST API helper
api_result = _query_rest_api(endpoint=endpoint, method="GET", description=description)
if not verbose and "success" in api_result and api_result["success"] and "result" in api_result:
return _format_query_results(api_result["result"])
return api_result
def query_jaspar(
prompt=None,
endpoint=None,
verbose=True,
):
"""Query the JASPAR REST API using natural language or a direct endpoint.
Parameters
----------
prompt (str, required): Natural language query about transcription factor binding profiles
endpoint (str, optional): API endpoint path (e.g., "/matrix/MA0002.2/") or full URL
verbose (bool): Whether to print verbose output
Returns
-------
dict: Dictionary containing the query results or error information
Examples
--------
- Natural language: query_jaspar("Find all transcription factor matrices for human")
- Direct endpoint: query_jaspar(endpoint="/matrix/MA0002.2/")
"""
# Base URL for JASPAR API
base_url = "https://jaspar.elixir.no/api/v1"
# Ensure we have either a prompt or an endpoint
if prompt is None and endpoint is None:
return {"error": "Either a prompt or an endpoint must be provided"}
# If using prompt, parse with Claude
if prompt:
# Load JASPAR schema
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "jaspar.pkl")
with open(schema_path, "rb") as f:
jaspar_schema = pickle.load(f)
# Create system prompt template
system_template = """
You are a transcription factor binding site expert specialized in using the JASPAR REST API.
Based on the user's natural language request, determine the appropriate JASPAR REST API endpoint and parameters.
JASPAR REST API SCHEMA:
{schema}
Your response should be a JSON object with the following fields:
1. "full_url": The complete URL to query (including the base URL "https://jaspar.elixir.no/api/v1" and any parameters)
2. "description": A brief description of what the query is doing
SPECIAL NOTES:
- Common taxonomic groups include: vertebrates, plants, fungi, insects, nematodes, urochordates
- Common collections include: CORE, UNVALIDATED, PENDING, etc.
- Matrix IDs follow the format MA####.# (e.g., MA0002.2)
- For inferring matrices from sequences, provide the protein sequence directly in the path
Return ONLY the JSON object with no additional text.
"""
# Query Claude to generate the API call
llm_result = _query_llm_for_api(
prompt=prompt,
schema=jaspar_schema,
system_template=system_template,
)
if not llm_result["success"]:
return llm_result
# Get the full URL from Claude's response
query_info = llm_result["data"]
endpoint = query_info.get("full_url", "")
description = query_info.get("description", "")
if not endpoint:
return {
"error": "Failed to generate a valid endpoint from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
else:
# Process provided endpoint
if not endpoint.startswith("http"):
# Clean up endpoint format
if not endpoint.startswith("/"):
endpoint = "/" + endpoint
# Ensure endpoint ends with /
if not endpoint.endswith("/"):
endpoint = endpoint + "/"
# Add base URL
endpoint = f"{base_url}{endpoint}"
description = "Direct query to JASPAR API"
# Execute the JASPAR API request using the helper function
api_result = _query_rest_api(endpoint=endpoint, method="GET", description=description)
if not verbose and "success" in api_result and api_result["success"] and "result" in api_result:
return _format_query_results(api_result["result"])
return api_result
def query_worms(
prompt=None,
endpoint=None,
verbose=True,
):
"""Query the World Register of Marine Species (WoRMS) REST API using natural language or a direct endpoint.
Parameters
----------
prompt (str, required): Natural language query about marine species
endpoint (str, optional): Full URL or endpoint specification
verbose (bool): Whether to print verbose output
Returns
-------
dict: Dictionary containing the query results or error information
Examples
--------
- Natural language: query_worms("Find information about the blue whale")
- Direct endpoint: query_worms(endpoint="https://www.marinespecies.org/rest/AphiaRecordByName/Balaenoptera%20musculus")
"""
# Base URL for WoRMS API
base_url = "https://www.marinespecies.org/rest"
# Ensure we have either a prompt or an endpoint
if prompt is None and endpoint is None:
return {"error": "Either a prompt or an endpoint must be provided"}
# If using prompt, parse with Claude
if prompt:
# Load WoRMS schema
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "worms.pkl")
with open(schema_path, "rb") as f:
worms_schema = pickle.load(f)
# Create system prompt template
system_template = """
You are a marine biology expert specialized in using the World Register of Marine Species (WoRMS) API.
Based on the user's natural language request, determine the appropriate WoRMS API endpoint and parameters.
WORMS API SCHEMA:
{schema}
Your response should be a JSON object with the following fields:
1. "full_url": The complete URL to query (including the base URL "https://www.marinespecies.org/rest" and any path/query parameters)
2. "description": A brief description of what the query is doing
SPECIAL NOTES:
- For taxonomic searches, be precise with scientific names and use proper capitalization
- For fuzzy matching, include "fuzzy=true" in the URL query parameters
- When searching by name, prefer "AphiaRecordByName" for exact matches and "AphiaRecordsByName" for broader results
- AphiaID is the main identifier in WoRMS (e.g., Blue Whale is 137087)
- For multiple IDs or names, use the appropriate POST endpoint
Return ONLY the JSON object with no additional text.
"""
# Query Claude to generate the API call
llm_result = _query_llm_for_api(
prompt=prompt,
schema=worms_schema,
system_template=system_template,
)
if not llm_result["success"]:
return llm_result
# Get the full URL and details from Claude's response
query_info = llm_result["data"]
endpoint = query_info.get("full_url", "")
description = query_info.get("description", "")
if not endpoint:
return {
"error": "Failed to generate a valid endpoint from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
else:
# Process provided endpoint
if not endpoint.startswith("http"):
# Add base URL if it's just a path
endpoint = f"{base_url}/{endpoint}" if not endpoint.startswith("/") else f"{base_url}{endpoint}"
description = "Direct query to WoRMS API"
# Execute the WoRMS API request using the helper function
api_result = _query_rest_api(endpoint=endpoint, method="GET", description=description)
if not verbose and "success" in api_result and api_result["success"] and "result" in api_result:
return _format_query_results(api_result["result"])
return api_result
def query_cbioportal(
prompt=None,
endpoint=None,
verbose=True,
):
"""Query the cBioPortal REST API using natural language or a direct endpoint.
Parameters
----------
prompt (str, required): Natural language query about cancer genomics data
endpoint (str, optional): API endpoint path (e.g., "/studies/brca_tcga/patients") or full URL
verbose (bool): Whether to print verbose output
Returns
-------
dict: Dictionary containing the query results or error information
Examples
--------
- Natural language: query_cbioportal("Find mutations in BRCA1 for breast cancer")
- Direct endpoint: query_cbioportal(endpoint="/studies/brca_tcga/molecular-profiles")
"""
# Base URL for cBioPortal API
base_url = "https://www.cbioportal.org/api"
# Ensure we have either a prompt or an endpoint
if prompt is None and endpoint is None:
return {"error": "Either a prompt or an endpoint must be provided"}
# If using prompt, parse with Claude
if prompt:
# Load cBioPortal schema
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "cbioportal.pkl")
with open(schema_path, "rb") as f:
cbioportal_schema = pickle.load(f)
# Create system prompt template
system_template = """
You are a cancer genomics expert specialized in using the cBioPortal REST API.
Based on the user's natural language request, determine the appropriate cBioPortal REST API endpoint and parameters.
CBIOPORTAL REST API SCHEMA:
{schema}
Your response should be a JSON object with the following fields:
1. "full_url": The complete URL to query (including the base URL "https://www.cbioportal.org/api" and any parameters)
2. "description": A brief description of what the query is doing
SPECIAL NOTES:
- For gene queries, use either Hugo symbol (e.g., "BRCA1") or Entrez ID (e.g., 672)
- For pagination, include parameters "pageNumber" and "pageSize" if needed
- For mutation data queries, always include appropriate sample identifiers
- Common studies include: "brca_tcga" (breast cancer), "gbm_tcga" (glioblastoma), "luad_tcga" (lung adenocarcinoma)
- For molecular profiles, common IDs follow pattern: "[study]_[data_type]" (e.g., "brca_tcga_mutations")
- Consider including "projection=DETAILED" for more comprehensive results when appropriate
Return ONLY the JSON object with no additional text.
"""
# Query Claude to generate the API call
llm_result = _query_llm_for_api(
prompt=prompt,
schema=cbioportal_schema,
system_template=system_template,
)
if not llm_result["success"]:
return llm_result
# Get the full URL from Claude's response
query_info = llm_result["data"]
endpoint = query_info.get("full_url", "")
description = query_info.get("description", "")
if not endpoint:
return {
"error": "Failed to generate a valid endpoint from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
else:
# Process provided endpoint
if not endpoint.startswith("http"):
# Clean up endpoint format
if not endpoint.startswith("/"):
endpoint = "/" + endpoint
# Add base URL
endpoint = f"{base_url}{endpoint}"
description = "Direct query to cBioPortal API"
# Execute the cBioPortal API request using the helper function
api_result = _query_rest_api(endpoint=endpoint, method="GET", description=description)
if not verbose and "success" in api_result and api_result["success"] and "result" in api_result:
return _format_query_results(api_result["result"])
return api_result
def query_clinvar(
prompt=None,
search_term=None,
max_results=3,
):
"""Take a natural language prompt and convert it to a structured ClinVar query.
Parameters
----------
prompt (str): Natural language query about genetic variants (e.g., "Find pathogenic BRCA1 variants")
search_term (str): Direct search term in ClinVar syntax
max_results (int): Maximum number of results to return
Returns
-------
dict: Dictionary containing both the structured query and the ClinVar results
"""
if not prompt and not search_term:
return {"error": "Either a prompt or an endpoint must be provided"}
if prompt:
# Load ClinVar schema
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "clinvar.pkl")
with open(schema_path, "rb") as f:
clinvar_schema = pickle.load(f)
# ClinVar system prompt template
system_prompt_template = """
You are a genetics research assistant that helps convert natural language queries into structured ClinVar search queries.
Based on the user's natural language request, you will generate a structured search for the ClinVar database.
Output only a JSON object with the following fields:
1. "search_term": The exact search query to use with the ClinVar API
IMPORTANT: Your response must ONLY contain a JSON object with the search term field.
Your "search_term" MUST strictly follow these ClinVar search syntax rules/tags:
{schema}
For combining terms: Use AND, OR, NOT (must be capitalized)
For complex logic: Use parentheses
For terms with multiple words: use double quotes escaped with a backslash or underscore (e.g. breast_cancer[dis] or \"breast cancer\"[dis])
Example: "BRCA1[gene] AND (pathogenic[clinsig] OR likely_pathogenic[clinsig])"
EXAMPLES OF CORRECT QUERIES:
- For "pathogenic BRCA1 variants": "BRCA1[gene] AND clinsig_pathogenic[prop]"
- For "Specific RS": "rs6025[rsid]"
- For "Combined search with multiple criteria": "BRCA1[gene] AND origin_germline[prop]"
- For "Find variants in a specific genomic region": "17[chr] AND 43000000:44000000[chrpos37]"
- If query asks for pathogenicity of a variant, it's asking for all possible germline classifications of the variant, so just [gene] AND [variant] is needed
"""
# Query Claude to generate the API call
llm_result = _query_llm_for_api(
prompt=prompt,
schema=clinvar_schema,
system_template=system_prompt_template,
)
if not llm_result["success"]:
return llm_result
# Get the full URL from Claude's response
query_info = llm_result["data"]
search_term = query_info.get("search_term", "")
if not search_term:
return {
"error": "Failed to generate a valid search term from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
return _query_ncbi_database(
database="clinvar",
search_term=search_term,
max_results=max_results,
)
def query_geo(
prompt=None,
search_term=None,
max_results=3,
):
"""Query the NCBI Gene Expression Omnibus (GEO) using natural language or a direct search term.
Parameters
----------
prompt (str, required): Natural language query about RNA-seq, microarray, or other expression data
search_term (str, optional): Direct search term in GEO syntax
max_results (int): Maximum number of results to return
Returns
-------
dict: Dictionary containing the query results or error information
Examples
--------
- Natural language: query_geo("Find RNA-seq datasets for breast cancer")
- Direct search: query_geo(search_term="RNA-seq AND breast cancer AND gse[ETYP]")
"""
if not prompt and not search_term:
return {"error": "Either a prompt or a search term must be provided"}
database = "gds" # Default database
if prompt:
# Load GEO schema
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "geo.pkl")
with open(schema_path, "rb") as f:
geo_schema = pickle.load(f)
# Create system prompt template
system_template = """
You are a bioinformatics research assistant that helps convert natural language queries into structured GEO (Gene Expression Omnibus) search queries.
Based on the user's natural language request, you will generate a structured search for the GEO database.
Output only a JSON object with the following fields:
1. "search_term": The exact search query to use with the GEO API
2. "database": The specific GEO database to search (either "gds" for GEO DataSets or "geoprofiles" for GEO Profiles)
IMPORTANT: Your response must ONLY contain a JSON object with the required fields.
Your "search_term" MUST strictly follow these GEO search syntax rules/tags:
{schema}
For combining terms: Use AND, OR, NOT (must be capitalized)
For complex logic: Use parentheses
For terms with multiple words: use double quotes or underscore (e.g. "breast cancer"[Title])
Date ranges use colon format: 2015/01:2020/12[PDAT]
Choose the appropriate database based on the user's query:
- gds: GEO DataSets (contains Series, Datasets, Platforms, Samples metadata)
- geoprofiles: GEO Profiles (contains gene expression data)
If database isn't clearly specified, default to "gds" as it contains most common experiment metadata.
EXAMPLES OF CORRECT OUTPUTS:
- For "RNA-seq data in breast cancer": {"search_term": "RNA-seq AND breast cancer AND gse[ETYP]", "database": "gds"}
- For "Mouse microarray data from 2020": {"search_term": "Mus musculus[ORGN] AND 2020[PDAT] AND microarray AND gse[ETYP]", "database": "gds"}
- For "Expression profiles of TP53 in lung cancer": {"search_term": "TP53[Gene Symbol] AND lung cancer", "database": "geoprofiles"}
"""
# Query Claude to generate the API call
llm_result = _query_llm_for_api(
prompt=prompt,
schema=geo_schema,
system_template=system_template,
)
if not llm_result["success"]:
return llm_result
# Get the search term and database from Claude's response
query_info = llm_result["data"]
search_term = query_info.get("search_term", "")
database = query_info.get("database", "gds")
if not search_term:
return {
"error": "Failed to generate a valid search term from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
# Execute the GEO query using the helper function
result = _query_ncbi_database(
database=database,
search_term=search_term,
max_results=max_results,
)
return result
def query_dbsnp(
prompt=None,
search_term=None,
max_results=3,
):
"""Query the NCBI dbSNP database using natural language or a direct search term.
Parameters
----------
prompt (str, required): Natural language query about genetic variants/SNPs
search_term (str, optional): Direct search term in dbSNP syntax
max_results (int): Maximum number of results to return
Returns
-------
dict: Dictionary containing the query results or error information
Examples
--------
- Natural language: query_dbsnp("Find pathogenic variants in BRCA1")
- Direct search: query_dbsnp(search_term="BRCA1[Gene Name] AND pathogenic[Clinical Significance]")
"""
if not prompt and not search_term:
return {"error": "Either a prompt or a search term must be provided"}
if prompt:
# Load dbSNP schema
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "dbsnp.pkl")
with open(schema_path, "rb") as f:
dbsnp_schema = pickle.load(f)
# Create system prompt template
system_template = """
You are a genetics research assistant that helps convert natural language queries into structured dbSNP search queries.
Based on the user's natural language request, you will generate a structured search for the dbSNP database.
Output only a JSON object with the following fields:
1. "search_term": The exact search query to use with the dbSNP API
IMPORTANT: Your response must ONLY contain a JSON object with the search term field.
Your "search_term" MUST strictly follow these dbSNP search syntax rules/tags:
{schema}
For combining terms: Use AND, OR, NOT (must be capitalized)
For complex logic: Use parentheses
For terms with multiple words: use double quotes (e.g. "breast cancer"[Disease Name])
EXAMPLES OF CORRECT QUERIES:
- For "pathogenic variants in BRCA1": "BRCA1[Gene Name] AND pathogenic[Clinical Significance]"
- For "specific SNP rs6025": "rs6025[rs]"
- For "SNPs in a genomic region": "17[Chromosome] AND 41196312:41277500[Base Position]"
- For "common SNPs in EGFR": "EGFR[Gene Name] AND common[COMMON]"
"""
# Query Claude to generate the API call
llm_result = _query_llm_for_api(
prompt=prompt,
schema=dbsnp_schema,
system_template=system_template,
)
if not llm_result["success"]:
return llm_result
# Get the search term from Claude's response
query_info = llm_result["data"]
search_term = query_info.get("search_term", "")
if not search_term:
return {
"error": "Failed to generate a valid search term from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
# Execute the dbSNP query using the helper function
result = _query_ncbi_database(
database="snp",
search_term=search_term,
max_results=max_results,
)
return result
def query_ucsc(
prompt=None,
endpoint=None,
verbose=True,
):
"""Query the UCSC Genome Browser API using natural language or a direct endpoint.
Parameters
----------
prompt (str, required): Natural language query about genomic data
endpoint (str, optional): Full URL or endpoint specification with parameters
verbose (bool): Whether to return detailed results
Returns
-------
dict: Dictionary containing the query results or error information
Examples
--------
- Natural language: query_ucsc("Get DNA sequence of chromosome M positions 1-100 in human genome")
- Direct endpoint: query_ucsc(endpoint="https://api.genome.ucsc.edu/getData/sequence?genome=hg38&chrom=chrM&start=1&end=100")
"""
# Base URL for UCSC API
base_url = "https://api.genome.ucsc.edu"
# Ensure we have either a prompt or an endpoint
if prompt is None and endpoint is None:
return {"error": "Either a prompt or an endpoint must be provided"}
# If using prompt, parse with Claude
if prompt:
# Load UCSC schema
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "ucsc.pkl")
with open(schema_path, "rb") as f:
ucsc_schema = pickle.load(f)
# Create system prompt template
system_template = """
You are a genomics expert specialized in using the UCSC Genome Browser API.
Based on the user's natural language request, determine the appropriate UCSC Genome Browser API endpoint and parameters.
UCSC GENOME BROWSER API SCHEMA:
{schema}
Your response should be a JSON object with the following fields:
1. "full_url": The complete URL to query (including the base URL "https://api.genome.ucsc.edu" and all parameters)
2. "description": A brief description of what the query is doing
SPECIAL NOTES:
- For chromosome names, always include the "chr" prefix (e.g., "chr1", "chrX", "chrM")
- Genomic positions are 0-based (first base is position 0)
- For "start" and "end" parameters, both must be provided together
- The "maxItemsOutput" parameter can be used to limit the amount of data returned
- Common genomes include: "hg38" (human), "mm39" (mouse), "danRer11" (zebrafish)
- For sequence data, use "getData/sequence" endpoint
- For chromosome listings, use "list/chromosomes" endpoint
- For available genomes, use "list/ucscGenomes" endpoint
Return ONLY the JSON object with no additional text.
"""
# Query Claude to generate the API call
llm_result = _query_llm_for_api(
prompt=prompt,
schema=ucsc_schema,
system_template=system_template,
)
if not llm_result["success"]:
return llm_result
# Get the full URL from Claude's response
query_info = llm_result["data"]
endpoint = query_info.get("full_url", "")
description = query_info.get("description", "")
if not endpoint:
return {
"error": "Failed to generate a valid endpoint from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
else:
# Process provided endpoint
if not endpoint.startswith("http"):
# Add base URL if it's just a path
endpoint = f"{base_url}/{endpoint}"
description = "Direct query to UCSC Genome Browser API"
# Execute the UCSC API request using the helper function
api_result = _query_rest_api(endpoint=endpoint, method="GET", description=description)
# Format the results if successful
if not verbose and "success" in api_result and api_result["success"] and "result" in api_result:
return _format_query_results(api_result["result"])
return api_result
def query_ensembl(
prompt=None,
endpoint=None,
verbose=True,
):
"""Query the Ensembl REST API using natural language or a direct endpoint.
Parameters
----------
prompt (str, required): Natural language query about genomic data
endpoint (str, optional): Direct API endpoint to query (e.g., "lookup/symbol/human/BRCA2") or full URL
verbose (bool): Whether to return detailed results
Returns
-------
dict: Dictionary containing the query results or error information
Examples
--------
- Natural language: query_ensembl("Get information about the human BRCA2 gene")
- Direct endpoint: query_ensembl(endpoint="lookup/symbol/homo_sapiens/BRCA2")
"""
# Base URL for Ensembl API
base_url = "https://rest.ensembl.org"
# Ensure we have either a prompt or an endpoint
if not prompt and not endpoint:
return {"error": "Either a prompt or an endpoint must be provided"}
# If using prompt, parse with Claude
if prompt:
# Load Ensembl schema
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "ensembl.pkl")
with open(schema_path, "rb") as f:
ensembl_schema = pickle.load(f)
# Create system prompt template
system_template = """
You are a genomics and bioinformatics expert specialized in using the Ensembl REST API.
Based on the user's natural language request, determine the appropriate Ensembl REST API endpoint and parameters.
ENSEMBL REST API SCHEMA:
{schema}
Your response should be a JSON object with the following fields:
1. "endpoint": The API endpoint to query (e.g., "lookup/symbol/homo_sapiens/BRCA2")
2. "params": An object containing query parameters specific to the endpoint
3. "description": A brief description of what the query is doing
SPECIAL NOTES:
- Chromosome region queries have a maximum length of 4900000 bp inclusive, so bp of start and end should be 4900000 bp apart. If the user's query exceeds this limit, Ensembl will return an error.
- For symbol lookups, the format is "lookup/symbol/[species]/[symbol]"
- To find the coordinates of a band on a chromosome, use /info/assembly/homo_sapiens/[chromosome] with parameters "band":1
- To find the overlapping genes of a genomic region, use /overlap/region/homo_sapiens/[chromosome]:[start]-[end]
- For sequence queries, specify the sequence type in parameters (genomic, cdna, cds, protein)
- For converting rsID to hg38 genomic coordinates, use the "GET id/variation/[species]/[rsid]" endpoint
- Many endpoints support "content-type" parameter for format specification (application/json, text/xml)
Return ONLY the JSON object with no additional text.
"""
# Query Claude to generate the API call
llm_result = _query_llm_for_api(
prompt=prompt,
schema=ensembl_schema,
system_template=system_template,
)
if not llm_result["success"]:
return llm_result
# Get the endpoint and parameters from Claude's response
query_info = llm_result["data"]
endpoint = query_info.get("endpoint", "")
params = query_info.get("params", {})
description = query_info.get("description", "")
if not endpoint:
return {
"error": "Failed to generate a valid endpoint from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
else:
# Process provided endpoint
if endpoint.startswith("http"):
# If a full URL is provided, extract the endpoint part
if endpoint.startswith(base_url):
endpoint = endpoint[len(base_url) :].lstrip("/")
params = {}
description = "Direct query to Ensembl API"
# Remove leading slash if present
if endpoint.startswith("/"):
endpoint = endpoint[1:]
# Prepare headers for JSON response
headers = {"Content-Type": "application/json", "Accept": "application/json"}
# Construct the URL
url = f"{base_url}/{endpoint}"
# Execute the Ensembl API request using the helper function
api_result = _query_rest_api(
endpoint=url,
method="GET",
params=params,
headers=headers,
description=description,
)
# Format the results if successful
if not verbose and "success" in api_result and api_result["success"] and "result" in api_result:
return _format_query_results(api_result["result"])
return api_result
def query_opentarget(
prompt=None,
query=None,
variables=None,
verbose=False,
):
"""Query the OpenTargets Platform API using natural language or a direct GraphQL query.
Parameters
----------
prompt (str, required): Natural language query about drug targets, diseases, and mechanisms
query (str, optional): Direct GraphQL query string
variables (dict, optional): Variables for the GraphQL query
verbose (bool): Whether to return detailed results
Returns
-------
dict: Dictionary containing the query results or error information
Examples
--------
- Natural language: query_opentarget("Find drug targets for Alzheimer's disease")
- Direct query: query_opentarget(query="query diseaseAssociations($diseaseId: String!) {...}",
variables={"diseaseId": "EFO_0000249"})
"""
# Constants and initialization
OPENTARGETS_URL = "https://api.platform.opentargets.org/api/v4/graphql"
# Ensure we have either a prompt or a query
if prompt is None and query is None:
return {"error": "Either a prompt or a GraphQL query must be provided"}
# If using prompt, parse with Claude
if prompt:
# Load OpenTargets schema
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "opentarget.pkl")
with open(schema_path, "rb") as f:
opentarget_schema = pickle.load(f)
# Create system prompt template
system_template = """
You are an expert in translating natural language requests into GraphQL queries for the OpenTargets Platform API.
Here is a schema of the main types and queries available in the OpenTargets Platform API:
{schema}
Translate the user's natural language request into a valid GraphQL query for this API.
Return only a JSON object with two fields:
1. "query": The complete GraphQL query string
2. "variables": A JSON object containing the variables needed for the query
SPECIAL NOTES:
- Disease IDs typically use EFO ontology (e.g., "EFO_0000249" for Alzheimer's disease)
- Target IDs typically use Ensembl IDs (e.g., "ENSG00000197386" for ENSG00000197386)
- The API can provide information about drug-target associations, disease-target associations, etc.
- Always limit results to a reasonable number using "first" parameter (e.g., first: 10)
- Always escape special characters, including quotes, in the query string (eg. \\" instead of ")
Return ONLY the JSON object with no additional text or explanations.
"""
# Query Claude to generate the API call
llm_result = _query_llm_for_api(
prompt=prompt,
schema=opentarget_schema,
system_template=system_template,
)
if not llm_result["success"]:
return llm_result
# Get the query and variables from Claude's response
query_info = llm_result["data"]
query = query_info.get("query", "")
if variables is None: # Only use Claude's variables if none provided
variables = query_info.get("variables", {})
if not query:
return {
"error": "Failed to generate a valid GraphQL query from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
# Execute the GraphQL query
api_result = _query_rest_api(
endpoint=OPENTARGETS_URL,
method="POST",
json_data={"query": query, "variables": variables or {}},
headers={"Content-Type": "application/json"},
description="OpenTargets Platform GraphQL query",
)
# Format the results if not verbose and successful
if not verbose and "success" in api_result and api_result["success"] and "result" in api_result:
api_result["result"] = _format_query_results(api_result["result"])
return api_result
# Monarch Initiative integration
def query_monarch(
prompt=None,
endpoint=None,
max_results=2,
verbose=False,
):
"""Query the Monarch Initiative API using natural language or a direct endpoint.
Parameters
----------
prompt (str, optional): Natural language query about genes, diseases, phenotypes, etc.
endpoint (str, optional): Direct Monarch API endpoint or full URL
max_results (int): Maximum number of results to return (if supported by endpoint)
verbose (bool): Whether to return detailed results
Returns
-------
dict: Dictionary containing the query results or error information
Examples
--------
- Natural language: query_monarch("Find phenotypes associated with BRCA1")
- Direct endpoint: query_monarch(endpoint="https://api.monarchinitiative.org/v3/api/search?q=marfan&category=biolink:Disease&limit=10")
- Direct endpoint: query_monarch(endpoint="https://api.monarchinitiative.org/v3/api/entity/MONDO:0007947")
"""
base_url = "https://api.monarchinitiative.org/v3/api"
if prompt is None and endpoint is None:
return {"error": "Either a prompt or an endpoint must be provided"}
# If using prompt, use Claude to generate the endpoint
if prompt:
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "monarch.pkl")
if os.path.exists(schema_path):
with open(schema_path, "rb") as f:
monarch_schema = pickle.load(f)
else:
monarch_schema = None
system_template = """
You are an expert in translating natural language requests into REST API calls for the Monarch Initiative Platform API.
Here is the API schema with available endpoints and parameters:
{schema}
Translate the user's natural language request into a valid REST API call for this API.
Return only a JSON object with three fields:
1. "endpoint": The specific endpoint name from the schema
2. "url": The complete URL with path parameters filled in
3. "params": A JSON object containing query parameters needed for the request
SPECIAL NOTES:
- Disease IDs typically use MONDO ontology (e.g., "MONDO:0007947" for Marfan syndrome)
- Gene IDs typically use HGNC (e.g., "HGNC:3603" for FBN1) or other standard identifiers
- Phenotype IDs use Human Phenotype Ontology (e.g., "HP:0002616" for aortic root dilatation)
- Association categories use biolink model terms (e.g., "biolink:DiseaseToPhenotypicFeatureAssociation")
- For example: to find phenotypes associated with BRCA1, use the following endpoint: /entity/HGNC:1100/biolink:GeneToPhenotypicFeatureAssociation
- For search queries, use the 'q' parameter with relevant keywords
- When looking for associations, use the association_table endpoint with entity ID and category
- For similarity searches, use semsim endpoints with comma-separated term lists
- Entity categories include: biolink:Disease, biolink:Gene, biolink:PhenotypicFeature, etc.
- Format parameter defaults to 'json' but can be 'tsv' for tabular data
- Use autocomplete endpoint for entity name suggestions before exact searches
COMMON PATTERNS:
- Search for entities: Use 'search' endpoint with 'q' and 'category' parameters
- Get entity details: Use 'get_entity' endpoint with specific ID
- Find associations: Use 'association_table' endpoint with ID and association category
- Compare phenotypes: Use 'semsim_compare' with lists of phenotype IDs
- Find similar diseases: Use 'semsim_search' with phenotype profile
Return ONLY the JSON object with no additional text or explanations.
"""
llm_result = _query_llm_for_api(
prompt=prompt,
schema=monarch_schema,
system_template=system_template,
)
if not llm_result["success"]:
return llm_result
query_info = llm_result["data"]
endpoint = query_info.get("url", "") # Changed from "full_url" to "url"
description = f"Monarch API query: {query_info.get('endpoint', 'unknown endpoint')}"
if not endpoint:
return {
"error": "Failed to generate a valid endpoint from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
else:
# Use provided endpoint directly
if endpoint is not None:
if endpoint.startswith("/"):
endpoint = f"{base_url}{endpoint}"
elif not endpoint.startswith("http"):
endpoint = f"{base_url}/{endpoint.lstrip('/')}"
description = "Direct query to Monarch API"
# Add max_results as a query parameter if not already present
if "?" in endpoint:
if "rows=" not in endpoint and "limit=" not in endpoint:
endpoint += f"&limit={max_results}"
else:
endpoint += f"?limit={max_results}"
api_result = _query_rest_api(endpoint=endpoint, method="GET", description=description)
if not verbose and "success" in api_result and api_result["success"] and "result" in api_result:
return _format_query_results(api_result["result"])
return api_result
# OpenFDA integration
def query_openfda(
prompt=None,
endpoint=None,
max_results=100,
verbose=True,
search_params=None,
sort_params=None,
count_params=None,
skip_results=0,
):
"""Query the OpenFDA API using natural language or direct parameters.
Parameters
----------
prompt (str, optional): Natural language query about drugs, adverse events, recalls, etc.
endpoint (str, optional): Direct OpenFDA API endpoint or full URL
max_results (int): Maximum number of results to return (if supported by endpoint)
verbose (bool): Whether to return detailed results
search_params (dict, optional): Search parameters in format {"field": "term"} or {"field": ["term1", "term2"]}
sort_params (dict, optional): Sort parameters in format {"field": "asc|desc"}
count_params (str, optional): Field to count unique values for
skip_results (int): Number of results to skip for pagination (max 25000)
Returns
-------
dict: Dictionary containing the query results or error information
Examples
--------
- Natural language: query_openfda("Find adverse events for Lipitor")
- Direct endpoint: query_openfda(endpoint="https://api.fda.gov/drug/event.json?search=patient.drug.medicinalproduct:lipitor")
- Search params: query_openfda(search_params={"patient.drug.medicinalproduct": "lipitor"}, endpoint="/drug/event.json")
- Count reactions: query_openfda(count_params="patient.reaction.reactionmeddrapt.exact", endpoint="/drug/event.json")
"""
base_url = "https://api.fda.gov"
if prompt is None and endpoint is None and search_params is None and count_params is None:
return {"error": "Either a prompt, endpoint, search_params, or count_params must be provided"}
# If using prompt, use LLM to generate the endpoint
if prompt:
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "openfda.pkl")
if os.path.exists(schema_path):
with open(schema_path, "rb") as f:
openfda_schema = pickle.load(f)
else:
openfda_schema = None
system_template = """
You are a biomedical informatics expert specialized in using the OpenFDA API.
Based on the user's natural language request, determine the appropriate OpenFDA API endpoint and parameters.
OPENFDA API SCHEMA:
{schema}
Your response should be a JSON object with the following fields:
1. "full_url": The complete URL to query (including the base URL "https://api.fda.gov" and any parameters)
2. "description": A brief description of what the query is doing
QUERY PARAMETERS:
- search: Use field:term syntax (e.g., "patient.drug.medicinalproduct:lipitor")
- sort: Use field:asc or field:desc (e.g., "receivedate:desc")
- count: Use field.exact for exact phrase counting (e.g., "patient.reaction.reactionmeddrapt.exact")
- limit: Maximum results (max 1000)
- skip: Skip results for pagination (max 25000)
SEARCH SYNTAX:
- Basic: search=field:term
- AND: search=field1:term1+AND+field2:term2
- OR: search=field1:term1+field2:term2
- Exact: search=field:"exact phrase"
Return ONLY the JSON object with no additional text.
"""
llm_result = _query_llm_for_api(
prompt=prompt,
schema=openfda_schema,
system_template=system_template,
)
if not llm_result["success"]:
return llm_result
query_info = llm_result["data"]
endpoint = query_info.get("full_url", "")
if not endpoint:
return {
"error": "Failed to generate a valid endpoint from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
else:
# Build endpoint from parameters
if endpoint is None:
return {"error": "Endpoint must be provided when not using prompt"}
# Ensure endpoint has proper format
if endpoint.startswith("/"):
endpoint = f"{base_url}{endpoint}"
elif not endpoint.startswith("http"):
endpoint = f"{base_url}/{endpoint.lstrip('/')}"
# Add max_results as a query parameter if not already present
if "?" in endpoint:
if "limit=" not in endpoint:
endpoint += f"&limit={max_results}"
else:
endpoint += f"?limit={max_results}"
# Make the API request using the REST API helper
description = "OpenFDA API query"
if prompt:
description = f"OpenFDA API query for: {prompt}"
api_result = _query_rest_api(endpoint=endpoint, method="GET", description=description)
# Format results based on verbose setting
if not verbose and "success" in api_result and api_result["success"] and "result" in api_result:
return _format_query_results(api_result["result"])
return api_result
def query_gwas_catalog(
prompt=None,
endpoint=None,
max_results=3,
):
"""Query the GWAS Catalog API using natural language or a direct endpoint.
Parameters
----------
prompt (str, required): Natural language query about GWAS data
endpoint (str, optional): Full API endpoint to query (e.g., "https://www.ebi.ac.uk/gwas/rest/api/studies?diseaseTraitId=EFO_0001360")
max_results (int): Maximum number of results to return
Returns
-------
dict: Dictionary containing the query results or error information
Examples
--------
- Natural language: query_gwas_catalog("Find GWAS studies related to Type 2 diabetes")
- Direct endpoint: query_gwas_catalog(endpoint="studies", params={"diseaseTraitId": "EFO_0001360"})
"""
# Base URL for GWAS Catalog API
base_url = "https://www.ebi.ac.uk/gwas/rest/api"
# Ensure we have either a prompt or an endpoint
if prompt is None and endpoint is None:
return {"error": "Either a prompt or an endpoint must be provided"}
# If using prompt, parse with Claude
if prompt:
# Load GWAS Catalog schema
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "gwas_catalog.pkl")
with open(schema_path, "rb") as f:
gwas_schema = pickle.load(f)
# Create system prompt template
system_template = """
You are a genomics expert specialized in using the GWAS Catalog API.
Based on the user's natural language request, determine the appropriate GWAS Catalog API endpoint and parameters.
GWAS CATALOG API SCHEMA:
{schema}
Your response should be a JSON object with the following fields:
1. "endpoint": The API endpoint to query (e.g., "studies", "associations")
2. "params": An object containing query parameters specific to the endpoint
3. "description": A brief description of what the query is doing
SPECIAL NOTES:
- For disease/trait searches, consider using the "EFO" identifiers when possible
- Common endpoints include: "studies", "associations", "singleNucleotidePolymorphisms", "efoTraits"
- For pagination, use "size" and "page" parameters
- For filtering by p-value, use "pvalueMax" parameter
- GWAS Catalog uses a HAL-based REST API
Return ONLY the JSON object with no additional text.
"""
# Query Claude to generate the API call
llm_result = _query_llm_for_api(
prompt=prompt,
schema=gwas_schema,
system_template=system_template,
)
if not llm_result["success"]:
return llm_result
# Get the endpoint and parameters from Claude's response
query_info = llm_result["data"]
endpoint = query_info.get("endpoint", "")
params = query_info.get("params", {})
description = query_info.get("description", "")
if not endpoint:
return {
"error": "Failed to generate a valid endpoint from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
else:
if endpoint is None:
endpoint = "" # Use root endpoint
params = {"size": max_results}
description = f"Direct query to {endpoint}"
# Remove leading slash if present
if endpoint.startswith("/"):
endpoint = endpoint[1:]
# Construct the URL
url = f"{base_url}/{endpoint}"
# Execute the GWAS Catalog API request using the helper function
api_result = _query_rest_api(endpoint=url, method="GET", params=params, description=description)
return api_result
def query_gnomad(
prompt=None,
gene_symbol=None,
verbose=True,
):
"""Query gnomAD for variants in a gene using natural language or direct gene symbol.
Parameters
----------
prompt (str, required): Natural language query about genetic variants
gene_symbol (str, optional): Gene symbol (e.g., "BRCA1")
verbose (bool): Whether to print verbose output
Returns
-------
dict: Dictionary containing the query results or error information
Examples
--------
- Direct gene: query_gnomad(gene_symbol="BRCA1")
- Natural language: query_gnomad(prompt="Find variants in the TP53 gene")
"""
# Base URL for gnomAD API
base_url = "https://gnomad.broadinstitute.org/api"
# Ensure we have either a prompt or a gene_symbol
if prompt is None and gene_symbol is None:
return {"error": "Either a prompt or a gene_symbol must be provided"}
# If using prompt, parse with Claude
if prompt and not gene_symbol:
# Load gnomAD schema
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "gnomad.pkl")
with open(schema_path, "rb") as f:
gnomad_schema = pickle.load(f)
# Create system prompt template
system_template = """
You are a genomics expert specialized in using the gnomAD GraphQL API.
Based on the user's natural language request, extract the gene symbol and relevant parameters and create the gnomAD GraphQL query.
GnomAD GraphQL API SCHEMA:
{schema}
Your response should be a JSON object with the following fields:
1. "query": The complete GraphQL query string
SPECIAL NOTES:
- The gene_symbol should be the official gene symbol (e.g., "BRCA1" not "breast cancer gene 1")
- If no reference genome is specified, default to GRCh38
- If no dataset is specified, default to gnomad_r4
- Return only a single gene symbol, even if multiple are mentioned
- Always escape special characters, including quotes, in the query string (eg. \" instead of ")
Return ONLY the JSON object with no additional text.
"""
# Query Claude to generate the API call
llm_result = _query_llm_for_api(
prompt=prompt,
schema=gnomad_schema,
system_template=system_template,
)
if not llm_result["success"]:
return llm_result
# Get the gene symbol from Claude's response
query_info = llm_result["data"]
query_str = query_info.get("query", "")
if not query_str:
return {
"error": "Failed to extract a valid query from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
else:
description = f"Query gnomAD for variants in {gene_symbol}"
# replace BRCA1 with gene_symbol
query_str = gnomad_schema.replace("BRCA1", gene_symbol)
api_result = _query_rest_api(
endpoint=base_url,
method="POST",
json_data={"query": query_str},
headers={"Content-Type": "application/json"},
description=description,
)
if not verbose and "success" in api_result and api_result["success"] and "result" in api_result:
return _format_query_results(api_result["result"])
return api_result
def blast_sequence(sequence: str, database: str, program: str) -> dict[str, str | float] | str:
"""Identifies a DNA sequence using NCBI BLAST with improved error handling, timeout management, and debugging.
Args:
sequence (str): The sequence to identify. If DNA, use database: core_nt, program: blastn;
if protein, use database: nr, program: blastp
database (str): The BLAST database to search against
program (str): The BLAST program to use
Returns:
dict: A dictionary containing the title, e-value, identity percentage, and coverage percentage of the best alignment
"""
max_attempts = 1 # One initial attempt plus one retry
attempts = 0
max_runtime = 600 # 10 minutes in seconds
while attempts < max_attempts:
try:
attempts += 1
query_sequence = Seq(sequence)
# Start timer
start_time = time.time()
# Submit BLAST job
print(f"Submitting BLAST job (attempt {attempts}/{max_attempts})...")
result_handle = NCBIWWW.qblast(
program,
database,
query_sequence,
expect=100,
word_size=7,
megablast=True,
)
# Parse results with timeout check
blast_records = NCBIXML.parse(result_handle)
blast_record = None
# Try to get the first record with timeout check
while time.time() - start_time < max_runtime:
try:
# Set a short timeout for next operation
blast_record = next(blast_records) # Get first record
break # Successfully got the record
except StopIteration:
# No more records
return "No BLAST results found"
except Exception:
# Check if we've exceeded the time limit
if time.time() - start_time >= max_runtime:
if attempts < max_attempts:
print("BLAST job timeout exceeded. Resubmitting...")
break # Break to retry
else:
return "BLAST search failed after maximum attempts due to timeout"
# Brief pause before trying again
time.sleep(1)
# Check if we timed out during record retrieval
if blast_record is None:
if attempts < max_attempts:
continue # Retry
else:
return "BLAST search failed after maximum attempts due to timeout"
# Debug information
print(f"Number of alignments found: {len(blast_record.alignments)}")
if blast_record.alignments:
for alignment in blast_record.alignments:
print("\nAlignment:")
print(f"hit_id: {alignment.hit_id}")
print(f"hit_def: {alignment.hit_def}")
print(f"accession: {alignment.accession}")
for hsp in alignment.hsps:
print(f"E-value: {hsp.expect}")
print(f"Score: {hsp.score}")
print(f"Identities: {hsp.identities}/{hsp.align_length}")
return {
"hit_id": alignment.hit_id,
"hit_def": alignment.hit_def,
"accession": alignment.accession,
"e_value": hsp.expect,
"identity": (hsp.identities / float(hsp.align_length)) * 100,
"coverage": len(hsp.query) / len(sequence) * 100,
}
else:
return "No alignments found - sequence might be too short or low complexity"
except Exception as e:
if attempts < max_attempts:
print(f"Error during BLAST search: {str(e)}. Retrying...")
time.sleep(2) # Wait briefly before retrying
else:
return f"Error during BLAST search after maximum attempts: {str(e)}"
return "BLAST search failed after maximum attempts"
def query_reactome(
prompt=None,
endpoint=None,
download=False,
output_dir=None,
verbose=True,
):
"""Query the Reactome database using natural language or a direct endpoint.
Parameters
----------
prompt (str, required): Natural language query about biological pathways
endpoint (str, optional): Direct API endpoint or full URL
download (bool): Whether to download pathway diagrams
output_dir (str, optional): Directory to save downloaded files
verbose (bool): Whether to return detailed results
Returns
-------
dict: Dictionary containing the query results or error information
Examples
--------
- Natural language: query_reactome("Find pathways related to DNA repair")
- Direct endpoint: query_reactome(endpoint="data/pathways/R-HSA-73894")
"""
# Base URLs for Reactome APIs
content_base_url = "https://reactome.org/ContentService"
analysis_base_url = "https://reactome.org/AnalysisService"
# Ensure we have either a prompt or an endpoint
if prompt is None and endpoint is None:
return {"error": "Either a prompt or an endpoint must be provided"}
# Create output directory if downloading and directory doesn't exist
if download and output_dir:
os.makedirs(output_dir, exist_ok=True)
# If using prompt, parse with Claude
if prompt:
# Load Reactome schema
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "reactome.pkl")
with open(schema_path, "rb") as f:
reactome_schema = pickle.load(f)
# Create system prompt template
system_template = """
You are a bioinformatics expert specialized in using the Reactome API.
Based on the user's natural language request, determine the appropriate Reactome API endpoint and parameters.
REACTOME API SCHEMA:
{schema}
Your response should be a JSON object with the following fields:
1. "endpoint": The API endpoint to query (e.g., "data/pathways/PATHWAY_ID", "data/query/GENE_SYMBOL")
2. "base": Which base URL to use ("content" for ContentService or "analysis" for AnalysisService)
3. "params": An object containing query parameters specific to the endpoint
4. "description": A brief description of what the query is doing
SPECIAL NOTES:
- Reactome has two primary APIs: ContentService (for retrieving specific pathway data) and AnalysisService (for analyzing gene lists)
- For pathway queries, use "data/pathways/PATHWAY_ID" with the pathway stable identifier (e.g., R-HSA-73894)
- For gene queries, use "data/query/GENE" with official gene symbol (e.g., "BRCA1")
- For pathway diagrams, include "download: true" in your response if the query is for pathway visualization
- Common human pathway IDs start with "R-HSA-"
Return ONLY the JSON object with no additional text.
"""
# Query Claude to generate the API call
llm_result = _query_llm_for_api(
prompt=prompt,
schema=reactome_schema,
system_template=system_template,
)
if not llm_result["success"]:
return llm_result
# Get the endpoint and parameters from Claude's response
query_info = llm_result["data"]
endpoint = query_info.get("endpoint", "")
base = query_info.get("base", "content") # Default to ContentService
params = query_info.get("params", {})
description = query_info.get("description", "")
should_download = query_info.get("download", download) # Override download if specified
if not endpoint:
return {
"error": "Failed to generate a valid endpoint from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
else:
# Process provided endpoint
if endpoint.startswith("http"):
# Full URL already provided
if "ContentService" in endpoint:
base = "content"
elif "AnalysisService" in endpoint:
base = "analysis"
else:
base = "content" # Default
else:
# Just endpoint provided, assume ContentService by default
base = "content"
params = {}
description = f"Direct query to Reactome {base} API: {endpoint}"
should_download = download
# Select base URL based on API type
base_url = content_base_url if base == "content" else analysis_base_url
# Remove leading slash if present
if endpoint.startswith("/"):
endpoint = endpoint[1:]
# --- ✅ FIX: Handle old 'data/query/GENE' endpoints to avoid 404 ---
if endpoint.startswith("http"):
url = endpoint
else:
if endpoint.startswith("data/query/"):
query_text = endpoint.replace("data/query/", "").strip()
url = f"{content_base_url}/search/query"
params = {"query": query_text, "species": "Homo sapiens"}
description = f"Redirected Reactome search for '{query_text}'"
else:
url = f"{base_url}/{endpoint}"
# --- ✅ END FIX ---
# Execute the Reactome API request using the helper function
api_result = _query_rest_api(endpoint=url, method="GET", params=params, description=description)
# Handle downloading pathway diagrams if requested
if should_download and api_result.get("success") and "result" in api_result:
result = api_result["result"]
pathway_id = None
# Try to extract pathway ID from result
if isinstance(result, dict):
pathway_id = result.get("stId") or result.get("dbId")
# If we have a pathway ID and output directory, download diagram
if pathway_id and output_dir:
diagram_url = f"{content_base_url}/data/pathway/{pathway_id}/diagram"
try:
diagram_response = requests.get(diagram_url)
diagram_response.raise_for_status()
# Save diagram file
diagram_path = os.path.join(output_dir, f"{pathway_id}_diagram.png")
with open(diagram_path, "wb") as f:
f.write(diagram_response.content)
api_result["diagram_path"] = diagram_path
except Exception as e:
api_result["diagram_error"] = f"Failed to download diagram: {str(e)}"
if not verbose and "success" in api_result and api_result["success"] and "result" in api_result:
return _format_query_results(api_result["result"])
return api_result
def query_regulomedb(
prompt=None,
endpoint=None,
verbose=False,
):
"""Query the RegulomeDB database using natural language or direct variant/coordinate specification.
Parameters
----------
prompt (str, required): Natural language query about regulatory elements
endpoint (str, optional): The full endpoint to query (e.g., "https://regulomedb.org/regulome-search/?regions=chr11:5246919-5246919&genome=GRCh38")
verbose (bool): Whether to return detailed results
Returns
-------
dict: Dictionary containing the query results or error information
Examples
--------
- Natural language: query_regulomedb("Find regulatory elements for rs35675666")
- Direct variant: query_regulomedb(variant="rs35675666")
- Coordinates: query_regulomedb(coordinates="chr11:5246919-5246919")
"""
# Base URL for RegulomeDB API
# Ensure we have either a prompt, variant, or coordinates
if prompt is None and endpoint is None:
return {"error": "Either a prompt, variant ID, or genomic coordinates must be provided"}
# If using prompt, parse with Claude
if prompt and not endpoint:
# Create system prompt template
system_template = """
You are a genomics expert specialized in using the RegulomeDB API.
Based on the user's natural language request, extract the variant ID or genomic coordinates they want to query.
Your response should be a JSON object with ONLY ONE of the following fields:
1. "endpoint": The API endpoint to query (e.g., "https://regulomedb.org/regulome-search/?regions=chr11:5246919-5246919&genome=GRCh38")
SPECIAL NOTES:
- RegulomeDB only works with human genome data
- Variant IDs should be rsIDs from dbSNP when possible. The endpoint should be in the format https://regulomedb.org/regulome-search/?regions=rsID&genome=GRCh38
- Thumbnails for chip and chromatin should be in the format https://regulomedb.org/regulome-search?regions=chr11:5246919-5246919&genome=GRCh38/thumbnail=chip
- Coordinates should be in GRCh37/hg19 format
- For single base queries, use the same position for start and end (e.g., "chr11:5246919-5246919")
- Chromosome should be specified with "chr" prefix (e.g., "chr11" not just "11")
Return ONLY the JSON object with no additional text.
"""
# Query Claude to generate the API call
llm_result = _query_llm_for_api(
prompt=prompt,
schema=None,
system_template=system_template,
)
if not llm_result["success"]:
return llm_result
# Get the variant or coordinates from Claude's response
query_info = llm_result["data"]
endpoint = query_info.get("endpoint", "")
if not endpoint:
return {
"error": "Failed to extract a valid variant ID or coordinates from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
else:
pass
# Construct the request URL
endpoint = endpoint
# Execute the RegulomeDB API request using the helper function
api_result = _query_rest_api(endpoint=endpoint, method="GET", headers={"Accept": "application/json"})
# Format the results if not verbose and successful
if not verbose and "success" in api_result and api_result["success"] and "result" in api_result:
api_result["result"] = _format_query_results(api_result["result"])
return api_result
def query_pride(
prompt=None,
endpoint=None,
max_results=3,
):
"""Query the PRIDE (PRoteomics IDEntifications) database using natural language or a direct endpoint.
Parameters
----------
prompt (str, required): Natural language query about proteomics data
endpoint (str, optional): The full endpoint to query (e.g., "https://www.ebi.ac.uk/pride/ws/archive/v2/projects?keyword=breast%20cancer")
max_results (int): Maximum number of results to return
Returns
-------
dict: Dictionary containing the query results or error information
Examples
--------
- Natural language: query_pride("Find proteomics data related to breast cancer")
- Direct endpoint: query_pride(endpoint="projects", params={"keyword": "breast cancer"})
"""
# Base URL for PRIDE API
base_url = "https://www.ebi.ac.uk/pride/ws/archive/v2"
# Ensure we have either a prompt or an endpoint
if prompt is None and endpoint is None:
return {"error": "Either a prompt or an endpoint must be provided"}
# If using prompt, parse with Claude
if prompt:
# Load PRIDE schema
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "pride.pkl")
with open(schema_path, "rb") as f:
pride_schema = pickle.load(f)
# Create system prompt template
system_template = """
You are a proteomics expert specialized in using the PRIDE API.
Based on the user's natural language request, determine the appropriate PRIDE API endpoint and parameters.
PRIDE API SCHEMA:
{schema}
Your response should be a JSON object with the following fields:
1. "endpoint": The full url endpoint to query
2. "description": A brief description of what the query is doing
SPECIAL NOTES:
- PRIDE is a repository for proteomics data stored at EBI
- Common endpoints include: "projects", "assays", "files", "proteins", "peptideevidences"
- For searching projects, you can use parameters like "keyword", "species", "tissue", "disease"
- For pagination, use "page" and "pageSize" parameters
- Most results include PagingObject and FieldsObject structures
Return ONLY the JSON object with no additional text.
"""
# Query Claude to generate the API call
llm_result = _query_llm_for_api(
prompt=prompt,
schema=pride_schema,
system_template=system_template,
)
if not llm_result["success"]:
return llm_result
# Get the endpoint and parameters from Claude's response
query_info = llm_result["data"]
endpoint = query_info.get("endpoint", "")
params = query_info.get("params", {})
description = query_info.get("description", "")
if not endpoint:
return {
"error": "Failed to generate a valid endpoint from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
else:
# Process provided endpoint
params = {"pageSize": max_results, "page": 0}
description = f"Direct query to PRIDE {endpoint}"
# Remove leading slash if present
if endpoint.startswith("/"):
endpoint = f"{base_url}{endpoint}"
elif not endpoint.startswith("http"):
endpoint = f"{base_url}/{endpoint.lstrip('/')}"
description = "Direct query to provided endpoint"
# Execute the PRIDE API request using the helper function
api_result = _query_rest_api(endpoint=endpoint, method="GET", params=params, description=description)
return api_result
def query_gtopdb(
prompt=None,
endpoint=None,
verbose=True,
):
"""Query the Guide to PHARMACOLOGY database (GtoPdb) using natural language or a direct endpoint.
Parameters
----------
prompt (str, required): Natural language query about drug targets, ligands, and interactions
endpoint (str, optional): Full API endpoint to query (e.g., "https://www.guidetopharmacology.org/services/targets?type=GPCR&name=beta-2")
verbose (bool): Whether to return detailed results
Returns
-------
dict: Dictionary containing the query results or error information
Examples
--------
- Natural language: query_gtopdb("Find ligands that target the beta-2 adrenergic receptor")
- Direct endpoint: query_gtopdb(endpoint="targets", params={"type": "GPCR", "name": "beta-2"})
"""
# Base URL for GtoPdb API
base_url = "https://www.guidetopharmacology.org/services"
# Ensure we have either a prompt or an endpoint
if prompt is None and endpoint is None:
return {"error": "Either a prompt or an endpoint must be provided"}
# If using prompt, parse with Claude
if prompt:
# Load GtoPdb schema
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "gtopdb.pkl")
with open(schema_path, "rb") as f:
gtopdb_schema = pickle.load(f)
# Create system prompt template
system_template = r"""
You are a pharmacology expert specialized in using the Guide to PHARMACOLOGY API.
Based on the user's natural language request, determine the appropriate GtoPdb API endpoint and parameters.
GTOPDB API SCHEMA:
{schema}
Your response should be a JSON object with the following fields:
1. "endpoint": The full API endpoint to query
2. "description": A brief description of what the query is doing
SPECIAL NOTES:
- Main endpoints include: "targets", "ligands", "interactions", "diseases", "refs"
- Target types include: "GPCR", "NHR", "LGIC", "VGIC", "OtherIC", "Enzyme", "CatalyticReceptor", "Transporter", "OtherProtein"
- Ligand types include: "Synthetic organic", "Metabolite", "Natural product", "Endogenous peptide", "Peptide", "Antibody", "Inorganic", "Approved", "Withdrawn", "Labelled", "INN"
- Interaction types include: "Activator", "Agonist", "Allosteric modulator", "Antagonist", "Antibody", "Channel blocker", "Gating inhibitor", "Inhibitor", "Subunit-specific"
- For specific target/ligand details, use formats like "targets/\{targetId\}" or "ligands/\{ligandId\}"
- For subresources, use formats like "targets/\{targetId\}/interactions" or "ligands/\{ligandId\}/structure"
Return ONLY the JSON object with no additional text.
"""
# Query Claude to generate the API call
llm_result = _query_llm_for_api(
prompt=prompt,
schema=gtopdb_schema,
system_template=system_template,
)
if not llm_result["success"]:
return llm_result
# Get the endpoint and parameters from Claude's response
query_info = llm_result["data"]
endpoint = query_info.get("endpoint", "")
description = query_info.get("description", "")
if not endpoint:
return {
"error": "Failed to generate a valid endpoint from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
else:
# Process provided endpoint
description = f"Direct query to GtoPdb {endpoint}"
# Remove leading slash if present
if endpoint.startswith("/"):
endpoint = f"{base_url}{endpoint}"
elif not endpoint.startswith("http"):
endpoint = f"{base_url}/{endpoint.lstrip('/')}"
description = "Direct query to provided endpoint"
# Execute the GtoPdb API request using the helper function
api_result = _query_rest_api(endpoint=endpoint, method="GET", description=description)
# Format the results if not verbose and successful
if not verbose and "success" in api_result and api_result["success"] and "result" in api_result:
api_result["result"] = _format_query_results(api_result["result"])
return api_result
def region_to_ccre_screen(coord_chrom: str, coord_start: int, coord_end: int, assembly: str = "GRCh38") -> str:
"""Given starting and ending coordinates, this function retrieves information of intersecting cCREs.
Args:
assembly (str): Assembly of the genome, formatted like 'GRCh38'. Default is 'GRCh38'.
coord_chrom (str): Chromosome of the gene, formatted like 'chr12'.
coord_start (int): Starting chromosome coordinate.
coord_end (int): Ending chromosome coordinate.
Returns:
str: A detailed string explaining the steps and the intersecting cCRE data or any error encountered.
"""
steps = []
try:
steps.append(
f"Starting cCRE data retrieval for coordinates: {coord_chrom}:{coord_start}-{coord_end} (Assembly: {assembly})."
)
# Build the URL and request payload
url = "https://screen-beta-api.wenglab.org/dataws/cre_table"
data = {
"assembly": assembly,
"coord_chrom": coord_chrom,
"coord_start": coord_start,
"coord_end": coord_end,
}
steps.append("Sending POST request to API with the following data:")
steps.append(str(data))
# Make the request
response = requests.post(url, json=data)
# Check if the response is successful
if not response.ok:
raise Exception(f"Request failed with status code {response.status_code}. Response: {response.text}")
steps.append("Request executed successfully. Parsing the response...")
# Parse the JSON response
response_json = response.json()
if "errors" in response_json:
raise Exception(f"API error: {response_json['errors']}")
# Function to reduce and filter response data
def reduce_tokens(res_json):
# Remove unnecessary fields and round floats
res = sorted(res_json["cres"], key=lambda x: x["dnase_zscore"], reverse=True)
filtered_res = []
for item in res:
new_item = {
"chrom": item["chrom"],
"start": item["start"],
"len": item["len"],
"pct": item["pct"],
"ctcf_zscore": round(item["ctcf_zscore"], 2),
"dnase_zscore": round(item["dnase_zscore"], 2),
"enhancer_zscore": round(item["enhancer_zscore"], 2),
"promoter_zscore": round(item["promoter_zscore"], 2),
"accession": item["info"]["accession"],
"isproximal": item["info"]["isproximal"],
"concordance": item["info"]["concordant"],
"ctcfmax": round(item["info"]["ctcfmax"], 2),
"k4me3max": round(item["info"]["k4me3max"], 2),
"k27acmax": round(item["info"]["k27acmax"], 2),
}
filtered_res.append(new_item)
return filtered_res
# Process the response data
filtered_data = reduce_tokens(response_json)
if not filtered_data:
steps.append(f"No intersecting cCREs found for coordinates: {coord_chrom}:{coord_start}-{coord_end}.")
return "\n".join(steps + ["No cCRE data available for this genomic region."])
# Format the result into a readable string
ccre_data_string = f"Intersecting cCREs for {coord_chrom}:{coord_start}-{coord_end} (Assembly: {assembly}):\n"
for i, ccre in enumerate(filtered_data, 1):
ccre_data_string += (
f"cCRE {i}:\n"
f" Chromosome: {ccre['chrom']}\n"
f" Start: {ccre['start']}\n"
f" Length: {ccre['len']}\n"
f" PCT: {ccre['pct']}\n"
f" CTCF Z-score: {ccre['ctcf_zscore']}\n"
f" DNase Z-score: {ccre['dnase_zscore']}\n"
f" Enhancer Z-score: {ccre['enhancer_zscore']}\n"
f" Promoter Z-score: {ccre['promoter_zscore']}\n"
f" Accession: {ccre['accession']}\n"
f" Is Proximal: {ccre['isproximal']}\n"
f" Concordance: {ccre['concordance']}\n"
f" CTCFmax: {ccre['ctcfmax']}\n"
f" K4me3max: {ccre['k4me3max']}\n"
f" K27acmax: {ccre['k27acmax']}\n\n"
)
steps.append(f"cCRE data successfully retrieved and formatted for {coord_chrom}:{coord_start}-{coord_end}.")
return "\n".join(steps + [ccre_data_string])
except Exception as e:
steps.append(f"Exception encountered: {str(e)}")
return "\n".join(steps + [f"Error: {str(e)}"])
def get_genes_near_ccre(accession: str, assembly: str, chromosome: str, k: int = 10) -> str:
"""Given a cCRE (Candidate cis-Regulatory Element), this function returns a string containing the
steps it performs and the k nearest genes sorted by distance.
Parameters
----------
- accession (str): ENCODE Accession ID of query cCRE, e.g., EH38E1516980.
- assembly (str): Assembly of the gene, e.g., 'GRCh38'.
- chromosome (str): Chromosome of the gene, e.g., 'chr12'.
- k (int): Number of nearby genes to return, sorted by distance. Default is 10.
Returns
-------
- str: Steps performed and the result.
"""
steps_log = (
f"Starting process with accession: {accession}, assembly: {assembly}, chromosome: {chromosome}, k: {k}\n"
)
url = "https://screen-beta-api.wenglab.org/dataws/re_detail/nearbyGenomic"
data = {"accession": accession, "assembly": assembly, "coord_chrom": chromosome}
steps_log += "Sending POST request to API with given data.\n"
response = requests.post(url, json=data)
if not response.ok:
steps_log += f"API request failed with response: {response.text}\n"
return steps_log
response_json = response.json()
if "errors" in response_json:
steps_log += f"API returned errors: {response_json['errors']}\n"
return steps_log
nearby_genes = response_json.get(accession, {}).get("nearby_genes", [])
if not nearby_genes:
steps_log += "No nearby genes found for the given accession.\n"
return steps_log
steps_log += "Successfully retrieved nearby genes. Sorting them by distance.\n"
sorted_genes = sorted(nearby_genes, key=lambda x: x["distance"])[:k]
steps_log += f"Returning the top {k} nearest genes.\n"
steps_log += "Result:\n"
for gene in sorted_genes:
gene_name = gene.get("name", "Unknown")
distance = gene.get("distance", "N/A")
ensembl_id = gene.get("ensemblid_ver", "N/A")
start = gene.get("start", "N/A")
stop = gene.get("stop", "N/A")
chrom = gene.get("chrom", "N/A")
steps_log += f"Gene: {gene_name}, Distance: {distance}, Ensembl ID: {ensembl_id}, Chromosome: {chrom}, Start: {start}, Stop: {stop}\n"
return steps_log
def query_remap(
prompt=None,
endpoint=None,
verbose=True,
):
"""Query the ReMap database for regulatory elements and transcription factor binding sites.
Parameters
----------
prompt (str, required): Natural language query about transcription factors and binding sites
endpoint (str, optional): Full API endpoint to query (e.g., "https://remap.univ-amu.fr/api/v1/catalogue/tf?tf=CTCF")
verbose (bool): Whether to return detailed results
Returns
-------
dict: Dictionary containing the query results or error information
Examples
--------
- Natural language: query_remap("Find CTCF binding sites in chromosome 1")
- Direct endpoint: query_remap(endpoint="catalogue/tf", params={"tf": "CTCF"})
"""
# Base URL for ReMap API
base_url = "https://remap.univ-amu.fr/api/v1"
# Ensure we have either a prompt or an endpoint
if prompt is None and endpoint is None:
return {"error": "Either a prompt or an endpoint must be provided"}
# If using prompt, parse with Claude
if prompt:
# Load ReMap schema
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "remap.pkl")
with open(schema_path, "rb") as f:
remap_schema = pickle.load(f)
# Create system prompt template
system_template = """
You are a genomics expert specialized in using the ReMap database API.
Based on the user's natural language request, determine the appropriate ReMap API endpoint and parameters.
REMAP API SCHEMA:
{schema}
Your response should be a JSON object with the following fields:
1. "endpoint": The full url endpoint to query
2. "description": A brief description of what the query is doing
SPECIAL NOTES:
- ReMap is a database of regulatory regions and transcription factor binding sites based on ChIP-seq experiments
- Common endpoints include: "catalogue/tf" (transcription factors), "catalogue/biotype" (biotypes), "browse/peaks" (binding sites)
- For searching binding sites, you can filter by transcription factor (tf), cell line, biotype, chromosome, etc.
- Genomic coordinates should be specified with "chr", "start", and "end" parameters
- For limiting results, use "limit" parameter (default is 100)
Return ONLY the JSON object with no additional text.
"""
# Query Claude to generate the API call
llm_result = _query_llm_for_api(
prompt=prompt,
schema=remap_schema,
system_template=system_template,
)
if not llm_result["success"]:
return llm_result
# Get the endpoint and parameters from Claude's response
query_info = llm_result["data"]
endpoint = query_info.get("endpoint", "")
description = query_info.get("description", "")
if not endpoint:
return {
"error": "Failed to generate a valid endpoint from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
else:
# Process provided endpoint
description = f"Direct query to ReMap {endpoint}"
# Remove leading slash if present
if endpoint.startswith("/"):
endpoint = f"{base_url}{endpoint}"
elif not endpoint.startswith("http"):
endpoint = f"{base_url}/{endpoint.lstrip('/')}"
description = "Direct query to provided endpoint"
# Execute the ReMap API request using the helper function
api_result = _query_rest_api(endpoint=endpoint, method="GET", description=description)
# Format the results if not verbose and successful
if not verbose and "success" in api_result and api_result["success"] and "result" in api_result:
api_result["result"] = _format_query_results(api_result["result"])
return api_result
def query_mpd(
prompt=None,
endpoint=None,
verbose=True,
):
"""Query the Mouse Phenome Database (MPD) for mouse strain phenotype data.
Parameters
----------
prompt (str, required): Natural language query about mouse phenotypes, strains, or measurements
endpoint (str, optional): Full API endpoint to query (e.g., "https://phenomedoc.jax.org/MPD_API/strains")
verbose (bool): Whether to return detailed results
Returns
-------
dict: Dictionary containing the query results or error information
Examples
--------
- Natural language: query_mpd("Find phenotype data for C57BL/6J mice related to blood glucose")
- Direct endpoint: query_mpd(endpoint="strains/C57BL/6J/measures")
"""
# Base URL for MPD API
base_url = "https://phenome.jax.org"
# Ensure we have either a prompt or an endpoint
if prompt is None and endpoint is None:
return {"error": "Either a prompt or an endpoint must be provided"}
# If using prompt, parse with Claude
if prompt:
# Load MPD schema
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "mpd.pkl")
with open(schema_path, "rb") as f:
mpd_schema = pickle.load(f)
# Create system prompt template
system_template = """
You are a mouse genetics expert specialized in using the Mouse Phenome Database (MPD) API.
Based on the user's natural language request, determine the appropriate MPD API endpoint and parameters.
MPD API SCHEMA:
{schema}
Your response should be a JSON object with the following fields:
1. "endpoint": The full url endpoint to query (e.g. https://phenome.jax.org/api/strains)
2. "description": A brief description of what the query is doing
SPECIAL NOTES:
- The MPD contains phenotype data for diverse strains of laboratory mice
- Common endpoints include: "strains" (mouse strains), "measures" (phenotypic measurements), "genes" (gene info)
- Use the url to construct the endpoint, not the endpoint name
- Common mouse strains include: "C57BL/6J", "DBA/2J", "BALB/cJ", "A/J", "129S1/SvImJ"
- Common phenotypic domains include: "behavior", "blood_chemistry", "body_weight", "cardiovascular", "growth", "metabolism"
Return ONLY the JSON object with no additional text.
"""
# Query Claude to generate the API call
llm_result = _query_llm_for_api(
prompt=prompt,
schema=mpd_schema,
system_template=system_template,
)
if not llm_result["success"]:
return llm_result
# Get the endpoint and parameters from Claude's response
query_info = llm_result["data"]
endpoint = query_info.get("endpoint", "")
description = query_info.get("description", "")
if not endpoint:
return {
"error": "Failed to generate a valid endpoint from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
else:
# Process provided endpoint
description = f"Direct query to MPD {endpoint}"
# Remove leading slash if present
if endpoint.startswith("/"):
endpoint = f"{base_url}{endpoint}"
elif not endpoint.startswith("http"):
endpoint = f"{base_url}/{endpoint.lstrip('/')}"
description = "Direct query to provided endpoint"
# Execute the MPD API request using the helper function
api_result = _query_rest_api(endpoint=endpoint, method="GET", description=description)
# Format the results if not verbose and successful
if not verbose and "success" in api_result and api_result["success"] and "result" in api_result:
api_result["result"] = _format_query_results(api_result["result"])
return api_result
def query_emdb(
prompt=None,
endpoint=None,
verbose=True,
):
"""Query the Electron Microscopy Data Bank (EMDB) for 3D macromolecular structures.
Parameters
----------
prompt (str, required): Natural language query about EM structures and associated data
endpoint (str, optional): Full API endpoint to query (e.g., "https://www.ebi.ac.uk/emdb/api/search")
verbose (bool): Whether to return detailed results
Returns
-------
dict: Dictionary containing the query results or error information
Examples
--------
- Natural language: query_emdb("Find cryo-EM structures of ribosomes at resolution better than 3Å")
- Direct endpoint: query_emdb(endpoint="entry/EMD-10000")
"""
# Base URL for EMDB API
base_url = "https://www.ebi.ac.uk/emdb/api"
# Ensure we have either a prompt or an endpoint
if prompt is None and endpoint is None:
return {"error": "Either a prompt or an endpoint must be provided"}
# If using prompt, parse with Claude
if prompt:
# Load EMDB schema
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "emdb.pkl")
with open(schema_path, "rb") as f:
emdb_schema = pickle.load(f)
# Create system prompt template
system_template = """
You are a structural biology expert specialized in using the Electron Microscopy Data Bank (EMDB) API.
Based on the user's natural language request, determine the appropriate EMDB API endpoint and parameters.
EMDB API SCHEMA:
{schema}
Your response should be a JSON object with the following fields:
1. "endpoint": The API endpoint to query (e.g., "search", "entry/EMD-XXXXX")
2. "params": An object containing query parameters specific to the endpoint
3. "description": A brief description of what the query is doing
SPECIAL NOTES:
- EMDB contains 3D macromolecular structures determined by electron microscopy
- Common endpoints include: "search" (search for entries), "entry/EMD-XXXXX" (specific entry details)
- For searching, you can filter by resolution, specimen, authors, release date, etc.
- Resolution filters should be specified with "resolution_low" and "resolution_high" parameters
- For specific entry retrieval, use the format "entry/EMD-XXXXX" where XXXXX is the EMDB ID
- Common specimen types include: "ribosome", "virus", "membrane protein", "filament"
Return ONLY the JSON object with no additional text.
"""
# Query Claude to generate the API call
llm_result = _query_llm_for_api(
prompt=prompt,
schema=emdb_schema,
system_template=system_template,
)
if not llm_result["success"]:
return llm_result
# Get the endpoint and parameters from Claude's response
query_info = llm_result["data"]
endpoint = query_info.get("endpoint", "")
params = query_info.get("params", {})
description = query_info.get("description", "")
if not endpoint:
return {
"error": "Failed to generate a valid endpoint from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
else:
# Process provided endpoint
params = {}
description = f"Direct query to EMDB {endpoint}"
# Remove leading slash if present
if endpoint.startswith("/"):
endpoint = f"{base_url}{endpoint}"
elif not endpoint.startswith("http"):
endpoint = f"{base_url}/{endpoint.lstrip('/')}"
description = "Direct query to provided endpoint"
# Execute the EMDB API request using the helper function
api_result = _query_rest_api(endpoint=endpoint, method="GET", params=params, description=description)
# Format the results if not verbose and successful
if not verbose and "success" in api_result and api_result["success"] and "result" in api_result:
api_result["result"] = _format_query_results(api_result["result"])
return api_result
def query_synapse(
prompt: str | None = None,
query_term: str | list[str] | None = None,
return_fields: list[str] | None = None,
max_results: int = 20,
query_type: str = "dataset",
verbose: bool = True,
):
"""Query Synapse REST API for biomedical datasets and files.
Synapse is a platform for sharing and analyzing biomedical data, particularly
genomics and clinical research datasets. Supports optional authentication via
SYNAPSE_AUTH_TOKEN environment variable for access to private datasets.
Parameters
----------
prompt : str, optional
Natural language query about biomedical data (e.g., "Find drug screening datasets")
query_term : str or list of str, optional
Specific search terms for Synapse search. When multiple terms are provided
as a list, they are combined with AND logic (more terms = more restrictive). Start with 1-2 most relevant search terms.
return_fields : list of str, optional
Fields to return in results. Default: ["name", "node_type", "description"]
max_results : int, default 20
Maximum number of results to return. Default 20 is optimal for most searches.
Use up to 50 if extensive results are desired for comprehensive analysis.
query_type : str, default "dataset"
Type of entity to search for ("dataset", "file", "folder")
verbose : bool, default True
Whether to return full API response or formatted results
Returns
-------
dict
Dictionary containing query information and Synapse API results
Notes
-----
Authentication is optional but recommended for access to private datasets.
Set SYNAPSE_AUTH_TOKEN environment variable with your Synapse personal access token
to enable authenticated requests.
Examples
--------
# Natural language
query_synapse(prompt="Find drug screening datasets")
# Direct search (AND logic - finds datasets with both "cancer" AND "genomics")
query_synapse(query_term=["cancer", "genomics"], max_results=10)
# Extensive search
query_synapse(query_term="alzheimer", max_results=50)
"""
base_url = "https://repo-prod.prod.sagebase.org"
# Default return fields
if return_fields is None:
return_fields = ["name", "node_type", "description"]
# Check for optional authentication
headers = {"Content-Type": "application/json"}
synapse_token = os.environ.get("SYNAPSE_AUTH_TOKEN")
if synapse_token:
headers["Authorization"] = f"Bearer {synapse_token}"
# If natural language prompt provided, convert to search terms
if prompt and not query_term:
system_template = (
"You extract search terms from natural language queries for biomedical data search.\n"
"Return ONLY a JSON object with this structure, where query_term combines search terms using AND for each entry:\n"
'{"query_term": ["term1", "term2"], "query_type": "dataset", "max_results": 20}.\n'
"query_type should be 'dataset' for datasets, 'file' for data files, or 'folder' for collections.\n"
"max_results should be 20 for typical searches, or up to 50 if extensive/comprehensive results are desired.\n"
"Use 1-2 most relevant search terms (these are combined with AND; more terms = more restrictive). Only include main term (disease, gene, etc.) of the search query and do not include any other terms/adjectives/modifiers. Do not include explanations.\n"
"Try to remove hyphens and other special characters from the search terms. For example, use RNAseq instead of RNA-seq."
)
llm_result = _query_llm_for_api(
prompt=prompt,
schema=None,
system_template=system_template,
)
if llm_result.get("success"):
mapping = llm_result["data"] or {}
query_term = mapping.get("query_term", [])
query_type = mapping.get("query_type", query_type)
max_results = mapping.get("max_results", max_results)
# Build search request
search_url = f"{base_url}/repo/v1/search"
# Ensure query_term is a list
if isinstance(query_term, str):
query_term = [query_term]
elif query_term is None:
query_term = [""]
# Build search payload
search_payload = {
"queryTerm": query_term,
"returnFields": return_fields,
"start": 0,
"size": max_results,
"booleanQuery": [{"key": "node_type", "value": query_type}],
}
description = f"Synapse search for terms: {query_term} (query type: {query_type})"
# Execute search
api_result = _query_rest_api(
endpoint=search_url,
method="POST",
json_data=search_payload,
headers=headers,
description=description,
)
# Augment results with access control information
if api_result.get("success") and "result" in api_result:
result_data = api_result["result"]
if isinstance(result_data, dict) and "hits" in result_data:
for hit in result_data["hits"]:
if "id" in hit:
# Check access requirements for this entity
access_url = f"{base_url}/repo/v1/entity/{hit['id']}/accessRequirement"
access_result = _query_rest_api(
endpoint=access_url,
method="GET",
headers=headers,
description=f"Check access requirements for {hit['id']}",
)
# Add access_restricted property based on access requirements
if access_result.get("success") and "result" in access_result:
access_data = access_result["result"]
total_requirements = access_data.get("totalNumberOfResults", 0)
hit["access_restricted"] = total_requirements > 0
else:
# If we can't check access, assume it might be restricted
hit["access_restricted"] = True
# Format results if not verbose and successful
if not verbose and api_result.get("success") and "result" in api_result:
api_result["result"] = _format_query_results(api_result["result"])
return api_result
def query_pubchem(
prompt=None,
endpoint=None,
max_results=5,
verbose=True,
):
"""Query the PubChem PUG-REST API using natural language or a direct endpoint.
Parameters
----------
prompt (str, required): Natural language query about chemical compounds
endpoint (str, optional): Direct PubChem API endpoint to query
max_results (int): Maximum number of results to return
verbose (bool): Whether to return detailed results
Returns
-------
dict: Dictionary containing the query results or error information
Examples
--------
- Natural language: query_pubchem("Find molecular weight of aspirin")
- Direct endpoint: query_pubchem(endpoint="compound/cid/2244/property/MolecularWeight/txt")
"""
# Base URL for PubChem API
base_url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug"
# Ensure we have either a prompt or an endpoint
if prompt is None and endpoint is None:
return {"error": "Either a prompt or an endpoint must be provided"}
# If using prompt, parse with Claude
if prompt:
# Load PubChem schema
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "pubchem.pkl")
with open(schema_path, "rb") as f:
pubchem_schema = pickle.load(f)
# Create system prompt template
system_template = """
You are a chemistry expert specialized in using the PubChem PUG-REST API.
Based on the user's natural language request, determine the appropriate PubChem API endpoint and parameters.
PUBCHEM API SCHEMA:
{schema}
Your response should be a JSON object with the following fields:
1. "full_url": The complete URL to query (including base URL and parameters)
2. "description": A brief description of what the query is doing
SPECIAL NOTES:
- Base URL is "https://pubchem.ncbi.nlm.nih.gov/rest/pug"
- Common operations: property, synonyms, record, xrefs
- For properties, use CSV format for multiple properties, TXT for single property
- For images, use PNG format with optional image_size parameter
- Rate limit: maximum 5 requests per second
- Use compound/name/ for chemical names, compound/cid/ for PubChem IDs
Return ONLY the JSON object with no additional text.
"""
# Query Claude to generate the API call
llm_result = _query_llm_for_api(
prompt=prompt,
schema=pubchem_schema,
system_template=system_template,
)
if not llm_result["success"]:
return llm_result
# Get the full URL from Claude's response
query_info = llm_result["data"]
endpoint = query_info.get("full_url", "")
description = query_info.get("description", "")
if not endpoint:
return {
"error": "Failed to generate a valid endpoint from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
else:
# Use provided endpoint directly
if endpoint is not None:
if endpoint.startswith("/"):
endpoint = f"{base_url}{endpoint}"
elif not endpoint.startswith("http"):
endpoint = f"{base_url}/{endpoint.lstrip('/')}"
description = "Direct query to provided endpoint"
# Rate limiting: allow user to configure or disable; only sleep if last request was too recent
if not hasattr(query_pubchem, "_last_request_time"):
query_pubchem._last_request_time = 0
min_interval = 1.0 / 5 # 5 requests per second by default
now = time.time()
elapsed = now - query_pubchem._last_request_time
if elapsed < min_interval:
time.sleep(min_interval - elapsed)
query_pubchem._last_request_time = time.time()
# Use the common REST API helper function
api_result = _query_rest_api(endpoint=endpoint, method="GET", description=description)
if not verbose and "success" in api_result and api_result["success"] and "result" in api_result:
api_result["result"] = _format_query_results(api_result["result"])
return api_result
def query_chembl(
prompt=None,
endpoint=None,
chembl_id=None,
smiles=None,
molecule_name=None,
max_results=20,
verbose=True,
):
"""Query the ChEMBL REST API using natural language, direct endpoint, or specific identifiers.
Parameters
----------
prompt (str, optional): Natural language query about bioactivity data
endpoint (str, optional): Direct ChEMBL API endpoint to query
chembl_id (str, optional): Specific ChEMBL ID to query (e.g., 'CHEMBL25')
smiles (str, optional): SMILES string for similarity/substructure search
molecule_name (str, optional): Molecule name for lookup
max_results (int): Maximum number of results to return
verbose (bool): Whether to return detailed results
Returns
-------
dict: Dictionary containing the query results or error information
Examples
--------
- Natural language: query_chembl("Find approved drugs with kinase activity")
- Direct endpoint: query_chembl(endpoint="molecule?max_phase=4")
- ChEMBL ID: query_chembl(chembl_id="CHEMBL25")
- SMILES similarity: query_chembl(smiles="CC(=O)OC1=CC=CC=C1C(=O)O", similarity_cutoff=80)
- Molecule name: query_chembl(molecule_name="aspirin")
"""
# Base URL for ChEMBL API
base_url = "https://www.ebi.ac.uk/chembl/api/data"
# Handle specific identifier parameters first (most reliable)
if chembl_id:
endpoint = f"{base_url}/molecule/{chembl_id}.json"
description = f"Direct lookup for ChEMBL ID: {chembl_id} (most reliable method)"
elif smiles:
endpoint = f"{base_url}/similarity/{smiles}/80.json" # Default similarity cutoff
description = f"Similarity search for SMILES: {smiles} with 80% cutoff"
elif molecule_name:
endpoint = f"{base_url}/molecule/search.json?q={molecule_name}&limit={max_results}"
description = f"Search for molecule with name containing: {molecule_name}"
elif prompt:
# Try LLM-based parsing with fallback
try:
# Load ChEMBL schema
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "chembl.pkl")
with open(schema_path, "rb") as f:
chembl_schema = pickle.load(f)
# Create system prompt template
system_template = """
You are a bioactivity data expert specialized in using the ChEMBL REST API.
Based on the user's natural language request, determine the appropriate ChEMBL API endpoint and parameters.
CHEMBL API SCHEMA:
{schema}
Your response should be a JSON object with the following fields:
1. "full_url": The complete URL to query (including base URL and parameters)
2. "description": A brief description of what the query is doing
SPECIAL NOTES:
- Base URL is "https://www.ebi.ac.uk/chembl/api/data"
# IMPORTANT ENDPOINTS:
- Molecule search: /molecule/search.json?q={search_term} (full-text search)
- Molecule by ID: /molecule/{chembl_id}.json (direct lookup)
- Image: /image/{chembl_id}.svg or /molecule/{chembl_id}.svg
- Substructure: /substructure/{smiles}.json (valid SMILES required)
- Similarity: /similarity/{smiles}/{cutoff}.json (cutoff 70-90 typical)
# BIOACTIVITY DATA:
- Activities: /activity.json?molecule_chembl_id={chembl_id}&limit=20
- Assays: /assay.json?molecule_chembl_id={chembl_id}&limit=20
- Use only= parameter to reduce fields: &only=target_chembl_id,standard_type,standard_value
# DRUG METADATA:
- Drug info: /drug.json?molecule_chembl_id={chembl_id} (use parent ID)
- Indications: /drug_indication.json?molecule_chembl_id={chembl_id}
- Mechanisms: /mechanism.json?molecule_chembl_id={chembl_id}
- ATC: /atc_class.json?molecule_chembl_id={chembl_id}
# COMMON FILTERS:
- max_phase=4 (approved drugs)
- assay_type=B (binding), F (functional), A (ADMET)
- standard_type=IC50, Ki, EC50
- pchembl_value__gte=5 (activity threshold)
# FORMAT NOTES:
- Add .json for JSON output (default is XML)
- Use /search.json for full-text search (not ?search=)
- Use parent ChEMBL IDs for drug endpoints
- Use raw SMILES (don't double-encode)
Return ONLY the JSON object with no additional text.
"""
# Query LLM to generate the API call
llm_result = _query_llm_for_api(
prompt=prompt,
schema=chembl_schema,
system_template=system_template,
)
if llm_result["success"]:
# Get the full URL from LLM's response
query_info = llm_result["data"]
endpoint = query_info.get("full_url", "")
description = query_info.get("description", "")
if endpoint:
# Successfully got endpoint from LLM
pass
else:
raise Exception("No endpoint generated from LLM")
else:
raise Exception(f"LLM failed: {llm_result.get('error', 'Unknown error')}")
except Exception:
# Fall back to generic endpoint mapping for common query types
prompt_lower = prompt.lower()
# Extract potential molecule names or keywords from the prompt
words = prompt.split()
potential_molecule = None
# Look for common molecule indicators - skip common words and look for longer, more specific terms
common_words = {
"find",
"search",
"get",
"show",
"list",
"target",
"targets",
"binding",
"for",
"the",
"a",
"an",
"and",
"or",
"with",
"using",
"via",
"through",
"from",
"in",
"on",
"at",
"to",
"of",
"by",
}
for word in words:
word_lower = word.lower()
# Skip common words and look for longer, more specific terms that could be molecule names
if (
len(word) > 4
and word.isalpha()
and word_lower not in common_words
and not word_lower.startswith("che") # Skip words starting with common prefixes
and not word_lower.endswith("ing")
): # Skip gerunds
potential_molecule = word
break
if "binding" in prompt_lower and "target" in prompt_lower:
# Try to find binding targets - use molecule if found, otherwise generic
if potential_molecule:
endpoint = f"{base_url}/molecule/search.json?q={potential_molecule}&limit={max_results}"
description = f"Search for {potential_molecule} binding targets in ChEMBL database"
else:
endpoint = f"{base_url}/activity.json?standard_type=IC50&limit={max_results}"
description = "Search for binding activities with IC50 values"
elif "molecule" in prompt_lower or "compound" in prompt_lower or "drug" in prompt_lower:
# Molecule search
if potential_molecule:
endpoint = f"{base_url}/molecule/search.json?q={potential_molecule}&limit={max_results}"
description = f"Search for molecule {potential_molecule} in ChEMBL database"
else:
endpoint = f"{base_url}/molecule/search.json?q=molecule&limit={max_results}"
description = "Search for molecules in ChEMBL database"
elif "activity" in prompt_lower or "bioactivity" in prompt_lower:
# Bioactivity search
endpoint = f"{base_url}/activity.json?limit={max_results}"
description = "Search for bioactivity data in ChEMBL database"
elif "assay" in prompt_lower:
# Assay search
endpoint = f"{base_url}/assay.json?limit={max_results}"
description = "Search for assay data in ChEMBL database"
elif "target" in prompt_lower:
# Target search
endpoint = f"{base_url}/target.json?limit={max_results}"
description = "Search for target data in ChEMBL database"
elif "image" in prompt_lower:
# Image search
if potential_molecule:
endpoint = f"{base_url}/molecule/search.json?q={potential_molecule}&limit={max_results}"
description = f"Search for {potential_molecule} images in ChEMBL database"
else:
endpoint = f"{base_url}/molecule/search.json?q=molecule&limit={max_results}"
description = "Search for molecule images in ChEMBL database"
else:
# Generic search - use first meaningful word or fallback
if potential_molecule:
endpoint = f"{base_url}/molecule/search.json?q={potential_molecule}&limit={max_results}"
description = f"Generic search for {potential_molecule} in ChEMBL database"
else:
endpoint = f"{base_url}/molecule/search.json?q=molecule&limit={max_results}"
description = f"Generic search in ChEMBL database for: {prompt[:50]}..."
elif endpoint:
# Use provided endpoint directly
if endpoint.startswith("/"):
endpoint = f"{base_url}{endpoint}"
elif not endpoint.startswith("http"):
endpoint = f"{base_url}/{endpoint.lstrip('/')}"
description = "Direct query to provided endpoint"
else:
# No valid parameters provided
return {
"success": False,
"error": "No query parameters provided. Use prompt, endpoint, chembl_id, smiles, or molecule_name.",
}
# Add pagination if not already specified
if "?" in endpoint:
if "limit=" not in endpoint:
endpoint += f"&limit={max_results}"
else:
endpoint += f"?limit={max_results}"
# Use the common REST API helper function
api_result = _query_rest_api(endpoint=endpoint, method="GET", description=description)
if not verbose and "success" in api_result and api_result["success"] and "result" in api_result:
api_result["result"] = _format_query_results(api_result["result"])
return api_result
def query_unichem(
prompt=None,
endpoint=None,
verbose=True,
):
"""Query the UniChem 2.0 REST API using natural language or a direct endpoint.
Parameters
----------
prompt (str, optional): Natural language query about chemical cross-references
endpoint (str, optional): Direct UniChem API endpoint to query
verbose (bool): Whether to return detailed results
Returns
-------
dict: Dictionary containing the query results or error information
Examples
--------
- Natural language: query_unichem("Find cross-references for aspirin")
- Direct endpoint: query_unichem(endpoint="/compounds")
- Compound search: query_unichem(endpoint="/compounds", data={"type": "inchikey", "compound": "LMXNVOREDXZICN-WDSOQIARSA-N"})
- Connectivity search: query_unichem(endpoint="/connectivity", data={"type": "inchi", "compound": "InChI=1S/C7H8N4O2/c1-10-5-4(8-3-9-5)6(12)11(2)7(10)13/h3H,1-2H3,(H,8,9)", "searchComponents": True})
- Get sources: query_unichem(endpoint="/sources")
"""
# Base URL for UniChem API (corrected from beta to production)
base_url = "https://www.ebi.ac.uk/unichem/api/v1"
# Ensure we have either a prompt or an endpoint
if prompt is None and endpoint is None:
return {"error": "Either a prompt or an endpoint must be provided"}
# If using prompt, parse with Claude
if prompt:
# Load UniChem schema
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "unichem.pkl")
with open(schema_path, "rb") as f:
unichem_schema = pickle.load(f)
# Create system prompt template
system_template = """
You are a chemical cross-reference expert specialized in using the UniChem 2.0 REST API.
Based on the user's natural language request, determine the appropriate UniChem API endpoint and parameters.
UNICHEM API SCHEMA:
{schema}
Your response should be a JSON object with the following fields:
1. "endpoint": The API endpoint to use (e.g., "/compounds", "/sources", "/connectivity")
2. "method": HTTP method ("GET" or "POST")
3. "data": POST data if method is POST (null for GET requests)
4. "description": A brief description of what the query is doing
SPECIAL NOTES:
- Base URL is "https://www.ebi.ac.uk/unichem/api/v1"
- Compound searches use POST method to /compounds endpoint
- Connectivity searches use POST method to /connectivity endpoint
- Source information uses GET method to /sources endpoint
- Valid identifier types: uci, inchi, inchikey, sourceID
- For compound/connectivity searches, include type and compound (or sourceID if type is sourceID)
- For connectivity searches, can include searchComponents boolean parameter
- Common source IDs: 1=ChEMBL, 2=DrugBank, 5=PubChem, 7=ChEBI
Return ONLY the JSON object with no additional text.
"""
# Query Claude to generate the API call
llm_result = _query_llm_for_api(
prompt=prompt,
schema=unichem_schema,
system_template=system_template,
)
if not llm_result["success"]:
return llm_result
# Get the API call details from Claude's response
query_info = llm_result["data"]
endpoint = query_info.get("endpoint", "")
method = query_info.get("method", "GET")
data = query_info.get("data", None)
description = query_info.get("description", "")
if not endpoint:
return {
"error": "Failed to generate a valid endpoint from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
# Construct full URL
if endpoint.startswith("/"):
full_url = f"{base_url}{endpoint}"
else:
full_url = f"{base_url}/{endpoint.lstrip('/')}"
else:
# Use provided endpoint directly
if endpoint is None:
return {"error": "Endpoint cannot be None when prompt is not provided"}
if endpoint.startswith("/"):
full_url = f"{base_url}{endpoint}"
elif not endpoint.startswith("http"):
full_url = f"{base_url}/{endpoint.lstrip('/')}"
else:
full_url = endpoint
method = "GET" # Default method for direct endpoints
data = None
description = "Direct query to provided endpoint"
# Use the common REST API helper function
api_result = _query_rest_api(endpoint=full_url, method=method, json_data=data, description=description)
if not verbose and "success" in api_result and api_result["success"] and "result" in api_result:
api_result["result"] = _format_query_results(api_result["result"])
return api_result
def query_clinicaltrials(
prompt=None,
endpoint=None,
max_results=10,
verbose=True,
):
"""Query the ClinicalTrials.gov API v2 using natural language or a direct endpoint.
Parameters
----------
prompt (str, required): Natural language query about clinical trials
endpoint (str, optional): Direct ClinicalTrials.gov API endpoint to query
max_results (int): Maximum number of results to return
verbose (bool): Whether to return detailed results
Returns
-------
dict: Dictionary containing the query results or error information
Examples
--------
- Natural language: query_clinicaltrials("Find recruiting cancer trials")
- Direct endpoint: query_clinicaltrials(endpoint="/studies?query.cond=cancer&filter.overallStatus=RECRUITING")
"""
# Base URL for ClinicalTrials.gov API
base_url = "https://clinicaltrials.gov/api/v2"
# Ensure we have either a prompt or an endpoint
if prompt is None and endpoint is None:
return {"error": "Either a prompt or an endpoint must be provided"}
# If using prompt, parse with Claude
if prompt:
# Load ClinicalTrials.gov schema
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "clinicaltrials.pkl")
with open(schema_path, "rb") as f:
clinicaltrials_schema = pickle.load(f)
# Create system prompt template
system_template = """
You are a clinical research expert specialized in using the ClinicalTrials.gov API v2.
Based on the user's natural language request, determine the appropriate ClinicalTrials.gov API endpoint and parameters.
CLINICALTRIALS.GOV API SCHEMA:
{schema}
Your response should be a JSON object with the following fields:
1. "full_url": The complete URL to query (including base URL and parameters)
2. "description": A brief description of what the query is doing
SPECIAL NOTES:
- Base URL is "https://clinicaltrials.gov/api/v2"
- Main endpoint is /studies for searching clinical trials
- Use query.cond for conditions/diseases, query.intr for interventions
- Use filter.overallStatus for study status (RECRUITING, COMPLETED, etc.)
- Use filter.phase for study phases (PHASE1, PHASE2, PHASE3, PHASE4)
- Use filter.studyType for study types (INTERVENTIONAL, OBSERVATIONAL)
- Use pageSize parameter to limit results (max 1000)
- For specific studies, use /studies/{{nctId}}
CORRECT PHASE FILTERING:
- Use filter.phase=PHASE1, PHASE2, PHASE3, PHASE4 (comma-separated for multiple phases)
- Do NOT use filter.phase=PHASE3 (single value with equals)
- Example: filter.phase=PHASE1,PHASE2 for early phase trials
Return ONLY the JSON object with no additional text.
"""
# Query Claude to generate the API call
llm_result = _query_llm_for_api(
prompt=prompt,
schema=clinicaltrials_schema,
system_template=system_template,
)
if not llm_result["success"]:
return llm_result
# Get the full URL from Claude's response
query_info = llm_result["data"]
endpoint = query_info.get("full_url", "")
description = query_info.get("description", "")
if not endpoint:
return {
"error": "Failed to generate a valid endpoint from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
else:
# Use provided endpoint directly
if endpoint is not None:
if endpoint.startswith("/"):
endpoint = f"{base_url}{endpoint}"
elif not endpoint.startswith("http"):
endpoint = f"{base_url}/{endpoint.lstrip('/')}"
description = "Direct query to provided endpoint"
# Add pageSize if not already specified and not a specific study lookup
if "/studies/" not in endpoint and "pageSize=" not in endpoint:
separator = "&" if "?" in endpoint else "?"
endpoint += f"{separator}pageSize={max_results}"
# Use the common REST API helper function
api_result = _query_rest_api(endpoint=endpoint, method="GET", description=description)
# Handle API parameter errors with fallback for ClinicalTrials.gov
if not api_result.get("success", False) and "400" in str(api_result.get("error", "")):
# Try simplified query without problematic filters
if "filter.phase" in endpoint:
simplified_endpoint = endpoint.replace("&filter.phase=PHASE3", "").replace("filter.phase=PHASE3&", "")
if simplified_endpoint != endpoint:
api_result = _query_rest_api(
endpoint=simplified_endpoint, method="GET", description=f"{description} (simplified)"
)
if api_result.get("success", False):
api_result["note"] = "Query simplified due to API parameter restrictions"
if not verbose and "success" in api_result and api_result["success"] and "result" in api_result:
api_result["result"] = _format_query_results(api_result["result"])
return api_result
def query_dailymed(
prompt=None,
endpoint=None,
format="json",
verbose=True,
):
"""Query the DailyMed RESTful API using natural language or a direct endpoint.
Parameters
----------
prompt (str, optional): Natural language query about drug labeling information
endpoint (str, optional): Direct DailyMed API endpoint to query
format (str): Response format ('json' or 'xml')
verbose (bool): Whether to return detailed results
Returns
-------
dict: Dictionary containing the query results or error information
Examples
--------
- Natural language: query_dailymed("Find all drug names")
- Direct endpoint: query_dailymed(endpoint="/drugnames.json")
- Get specific SPL: query_dailymed(endpoint="/spls/12345678-1234-1234-1234-123456789012.json")
- Get SPL history: query_dailymed(endpoint="/spls/12345678-1234-1234-1234-123456789012/history.json")
"""
# Base URL for DailyMed API
base_url = "https://dailymed.nlm.nih.gov/dailymed/services/v2"
# Ensure we have either a prompt or an endpoint
if prompt is None and endpoint is None:
return {"error": "Either a prompt or an endpoint must be provided"}
# Validate format
if format not in ["json", "xml"]:
format = "json"
# If using prompt, parse with Claude
if prompt:
# Load DailyMed schema
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "dailymed.pkl")
with open(schema_path, "rb") as f:
dailymed_schema = pickle.load(f)
# Create system prompt template
system_template = """
You are a pharmaceutical labeling expert specialized in using the DailyMed RESTful API.
Based on the user's natural language request, determine the appropriate DailyMed API endpoint and parameters.
DAILYMED API SCHEMA:
{schema}
Your response should be a JSON object with the following fields:
1. "full_url": The complete URL to query (including base URL and format extension)
2. "description": A brief description of what the query is doing
SPECIAL NOTES:
- Base URL is "https://dailymed.nlm.nih.gov/dailymed/services/v2"
- Available resources: applicationnumbers, drugclasses, drugnames, ndcs, rxcuis, spls, uniis
- For specific SPL documents, use /spls/{{SETID}} format
- For SPL-related data, use /spls/{{SETID}}/history, /spls/{{SETID}}/media, /spls/{{SETID}}/ndcs, /spls/{{SETID}}/packaging
- Always append format extension (.json or .xml)
- API only supports GET method
- HTTPS is required (HTTP disabled since 2016)
- Each resource may have optional query parameters to filter or control output
Return ONLY the JSON object with no additional text.
"""
# Query Claude to generate the API call
llm_result = _query_llm_for_api(
prompt=prompt,
schema=dailymed_schema,
system_template=system_template,
)
if not llm_result["success"]:
return llm_result
# Get the full URL from Claude's response
query_info = llm_result["data"]
endpoint = query_info.get("full_url", "")
description = query_info.get("description", "")
if not endpoint:
return {
"error": "Failed to generate a valid endpoint from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
else:
# Use provided endpoint directly
if endpoint is not None:
if endpoint.startswith("/"):
endpoint = f"{base_url}{endpoint}"
elif not endpoint.startswith("http"):
endpoint = f"{base_url}/{endpoint.lstrip('/')}"
description = "Direct query to provided endpoint"
# Add format extension if not present
if not endpoint.endswith(f".{format}") and not endpoint.endswith(".json") and not endpoint.endswith(".xml"):
endpoint += f".{format}"
# Use the common REST API helper function
api_result = _query_rest_api(endpoint=endpoint, method="GET", description=description)
if not verbose and "success" in api_result and api_result["success"] and "result" in api_result:
api_result["result"] = _format_query_results(api_result["result"])
return api_result
def query_quickgo(
prompt=None,
endpoint=None,
max_results=25,
verbose=True,
):
"""Query the QuickGO API using natural language or a direct endpoint.
Parameters
----------
prompt (str, optional): Natural language query about Gene Ontology terms, annotations, or gene products
endpoint (str, optional): Direct QuickGO API endpoint to query
max_results (int): Maximum number of results to return (max 100)
verbose (bool): Whether to return detailed results
Returns
-------
dict: Dictionary containing the query results or error information
Examples
--------
- Natural language: query_quickgo("Find GO terms related to apoptosis")
- Direct endpoint: query_quickgo(endpoint="/ontology/go/search?query=apoptosis&limit=10")
- Get specific term: query_quickgo(endpoint="/ontology/go/terms/GO:0006915")
"""
# Base URL for QuickGO API (corrected from documentation)
base_url = "https://www.ebi.ac.uk/QuickGO/services"
# Ensure we have either a prompt or an endpoint
if prompt is None and endpoint is None:
return {"error": "Either a prompt or an endpoint must be provided"}
# Validate max_results
if max_results > 100:
import warnings
warnings.warn(
f"max_results ({max_results}) exceeds QuickGO API limit (100). Setting max_results to 100.", stacklevel=2
)
max_results = 100
# If using prompt, parse with Claude
if prompt:
# Load QuickGO schema
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "quickgo.pkl")
with open(schema_path, "rb") as f:
quickgo_schema = pickle.load(f)
# Create system prompt template
system_template = """
You are a Gene Ontology expert specialized in using the QuickGO REST API.
Based on the user's natural language request, determine the appropriate QuickGO API endpoint and parameters.
QUICKGO API SCHEMA:
{schema}
Your response should be a JSON object with the following fields:
1. "full_url": The complete URL to query (including base URL and parameters)
2. "description": A brief description of what the query is doing
SPECIAL NOTES:
- Base URL is "https://www.ebi.ac.uk/QuickGO/services"
- Main services: /ontology (GO/ECO terms), /annotation (GO annotations), /geneproduct (gene products)
- For GO term search, use /ontology/go/search with query parameter
- For specific GO terms, use /ontology/go/terms/{{go_id}}
- For GO term relationships, use /ontology/go/terms/{{go_id}}/children, /descendants, /ancestors
- For annotations, use /annotation/search with various filters
- For gene products, use /geneproduct/search
- Use limit parameter to control results (max 100)
- Common organisms: 9606 (human), 10090 (mouse), 7227 (fly)
- GO aspects: biological_process, molecular_function, cellular_component
- Evidence codes: IEA, IDA, IPI, IMP, IGI, etc.
- Qualifiers: enables, involved_in, is_active_in, part_of, etc.
Return ONLY the JSON object with no additional text.
"""
# Query Claude to generate the API call
llm_result = _query_llm_for_api(
prompt=prompt,
schema=quickgo_schema,
system_template=system_template,
)
if not llm_result["success"]:
return llm_result
# Get the full URL from Claude's response
query_info = llm_result["data"]
endpoint = query_info.get("full_url", "")
description = query_info.get("description", "")
if not endpoint:
return {
"error": "Failed to generate a valid endpoint from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
else:
# Use provided endpoint directly
if endpoint is not None:
if endpoint.startswith("/"):
endpoint = f"{base_url}{endpoint}"
elif not endpoint.startswith("http"):
endpoint = f"{base_url}/{endpoint.lstrip('/')}"
description = "Direct query to provided endpoint"
# Add limit parameter if not already specified
if "limit=" not in endpoint and "/terms/" not in endpoint:
separator = "&" if "?" in endpoint else "?"
endpoint += f"{separator}limit={max_results}"
# Use the common REST API helper function
api_result = _query_rest_api(endpoint=endpoint, method="GET", description=description)
if not verbose and "success" in api_result and api_result["success"] and "result" in api_result:
api_result["result"] = _format_query_results(api_result["result"])
return api_result
def query_encode(
prompt=None,
endpoint=None,
max_results=25,
verbose=True,
):
"""Query the ENCODE Portal API to help users locate functional genomics data.
This function is designed to help users find and explore ENCODE data including:
- Experiments (ChIP-seq, RNA-seq, ATAC-seq, DNase-seq, WGBS, etc.)
- Files (BAM, BED, bigWig, fastq, etc.)
- Biosamples (cell lines, tissues, primary cells)
- Datasets and replicates
Parameters
----------
prompt (str, required): Natural language query about functional genomics data you want to find
endpoint (str, optional): Direct ENCODE Portal API endpoint to query
max_results (int): Maximum number of results to return (use "all" for all results)
verbose (bool): Whether to return detailed results
Returns
-------
dict: Dictionary containing the query results with data location information
Examples
--------
- Find experiments: query_encode("Find ChIP-seq experiments for CTCF in human K562 cells")
- Find files: query_encode("Find BAM files from ATAC-seq experiments in mouse brain")
- Find biosamples: query_encode("Find human primary T cells from blood")
- Find datasets: query_encode("Find RNA-seq datasets from human liver tissue")
- Direct endpoint: query_encode(endpoint="/search/?type=Experiment&assay_title=ChIP-seq&format=json")
"""
# Base URL for ENCODE Portal API
base_url = "https://www.encodeproject.org"
# Ensure we have either a prompt or an endpoint
if prompt is None and endpoint is None:
return {"error": "Either a prompt or an endpoint must be provided"}
# If using prompt, parse with Claude
if prompt:
# Load ENCODE schema
schema_path = os.path.join(os.path.dirname(__file__), "schema_db", "encode.pkl")
with open(schema_path, "rb") as f:
encode_schema = pickle.load(f)
# Create system prompt template
system_template = """
You are a functional genomics expert specialized in helping users locate data in the ENCODE Portal.
Your goal is to help users find the specific functional genomics data they need. Based on the user's request,
determine the most appropriate ENCODE Portal API endpoint and parameters to locate their data.
ENCODE PORTAL API SCHEMA:
{schema}
Your response should be a JSON object with the following fields:
1. "full_url": The complete URL to query (including base URL and parameters)
2. "description": A clear description of what data the query will help locate
3. "data_type": The type of data being searched (Experiment, File, Biosample, etc.)
4. "search_strategy": Brief explanation of the search approach used
CRITICAL RULES FOR SIMPLE, EFFECTIVE QUERIES:
1. KEEP QUERIES SIMPLE - use only 1-3 parameters maximum for better results
2. Start with basic searches and let users refine based on results
3. Use searchTerm for text-based searches (most reliable for complex terms)
4. Avoid complex nested property paths when possible
5. For organism filtering, use simple organism names: "Homo sapiens", "Mus musculus"
SIMPLE QUERY PATTERNS (PREFERRED):
- Basic experiment search: /search/?type=Experiment&assay_title=ChIP-seq&format=json
- Text-based search: /search/?searchTerm=CTCF&format=json
- File type search: /search/?type=File&file_format=bam&format=json
- Biosample search: /search/?type=Biosample&format=json
- Dataset search: /search/?type=Dataset&format=json
COMMON ASSAY TYPES (choose ONE per query):
- ChIP-seq, RNA-seq, ATAC-seq, DNase-seq, WGBS, Hi-C, CAGE, ChIA-PET
COMMON FILE FORMATS:
- bam, fastq, bigWig, bigBed, bed, narrowPeak, broadPeak
SIMPLE EXAMPLES:
- Find ChIP-seq experiments: /search/?type=Experiment&assay_title=ChIP-seq&format=json
- Find CTCF data: /search/?searchTerm=CTCF&format=json
- Find BAM files: /search/?type=File&file_format=bam&format=json
- Find human experiments: /search/?type=Experiment&searchTerm=human&format=json
- Find mouse brain data: /search/?type=Experiment&searchTerm=mouse%20brain&format=json
IMPORTANT: Return ONLY a valid JSON object with no additional text, code comments, or explanations.
The response must be parseable JSON starting with {{ and ending with }}.
"""
# Query Claude to generate the API call
llm_result = _query_llm_for_api(
prompt=prompt,
schema=encode_schema,
system_template=system_template,
)
if not llm_result["success"]:
return llm_result
# Get the full URL from Claude's response
query_info = llm_result["data"]
endpoint = query_info.get("full_url", "")
description = query_info.get("description", "")
if not endpoint:
return {
"error": "Failed to generate a valid endpoint from the prompt",
"llm_response": llm_result.get("raw_response", "No response"),
}
else:
# Use provided endpoint directly
if endpoint is not None:
if endpoint.startswith("/"):
endpoint = f"{base_url}{endpoint}"
elif not endpoint.startswith("http"):
endpoint = f"{base_url}/{endpoint.lstrip('/')}"
description = "Direct query to provided endpoint"
# Ensure format=json is included for API access
if "format=json" not in endpoint and "/search/" in endpoint:
separator = "&" if "?" in endpoint else "?"
endpoint += f"{separator}format=json"
# Add limit parameter if not already specified and it's a search endpoint
if "/search/" in endpoint and "limit=" not in endpoint:
separator = "&" if "?" in endpoint else "?"
limit_value = "all" if max_results == "all" or max_results > 100 else max_results
endpoint += f"{separator}limit={limit_value}"
# Use the common REST API helper function
api_result = _query_rest_api(endpoint=endpoint, method="GET", description=description)
# Add data location information to the result
if api_result.get("success", False):
# Extract data_type and search_strategy from the query_info if available
data_type = query_info.get("data_type", "Unknown") if "query_info" in locals() else "Unknown"
search_strategy = (
query_info.get("search_strategy", "Direct query") if "query_info" in locals() else "Direct query"
)
api_result["data_type"] = data_type
api_result["search_strategy"] = search_strategy
api_result["data_location_info"] = {
"description": description,
"data_type": data_type,
"search_strategy": search_strategy,
"endpoint_used": endpoint,
}
# Handle API parameter errors with fallback for ENCODE
if not api_result.get("success", False) and "404" in str(api_result.get("error", "")):
# Try simplified query with basic search
if prompt and "transcription factor" in prompt.lower():
simplified_endpoint = f"{base_url}/search/?type=Experiment&assay_title=ChIP-seq&searchTerm=transcription%20factor&format=json&limit={max_results}"
api_result = _query_rest_api(
endpoint=simplified_endpoint, method="GET", description=f"{description} (simplified)"
)
if api_result.get("success", False):
api_result["note"] = "Query simplified due to API endpoint restrictions"
if not verbose and "success" in api_result and api_result["success"] and "result" in api_result:
api_result["result"] = _format_query_results(api_result["result"])
return api_result
|