mirror of
https://github.com/run-llama/LlamaIndexTS.git
synced 2026-07-01 22:14:03 -04:00
Compare commits
685 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b440a008e5 | |||
| 46227f2a70 | |||
| 77f0298f6f | |||
| c14e112236 | |||
| 62b035fdc1 | |||
| aa0be1469b | |||
| 5016f21d52 | |||
| 130b7992a1 | |||
| 0d50b22dbf | |||
| db1d1f57c9 | |||
| dccb8163d8 | |||
| 1ab3ba407e | |||
| b03f765733 | |||
| 7488d3c235 | |||
| 5cb270d07f | |||
| 62771058aa | |||
| ca348a6570 | |||
| 44a7fd72e8 | |||
| d8d952d937 | |||
| 216ba1f22b | |||
| 74686f5776 | |||
| 1ebf9e67a4 | |||
| aeefc77da0 | |||
| 13d8d7cbbe | |||
| 9c34e44b85 | |||
| cb2dc802d9 | |||
| 5a6cc0e32e | |||
| a63256eb84 | |||
| 0a160b97a0 | |||
| 95602c7959 | |||
| 20bc466ca1 | |||
| efb1c56ba5 | |||
| 286499388d | |||
| 460c6574cc | |||
| 8b0e0e3cc8 | |||
| 87142b29fa | |||
| 501b844f0f | |||
| 03157dc295 | |||
| ef80b684f7 | |||
| 472e70feee | |||
| cfb90f7666 | |||
| 2e3a287a27 | |||
| 635fbb8618 | |||
| d2d34acb31 | |||
| cf70edbede | |||
| 79b7d246bd | |||
| bcc3d0b4d1 | |||
| 238ca86534 | |||
| 1f3efe8947 | |||
| 89324b4067 | |||
| 8cc848aee6 | |||
| cd54a7a66b | |||
| dca02f7277 | |||
| b757fa9aa3 | |||
| bc594a0674 | |||
| 208282d62f | |||
| 060880abfe | |||
| 728b35e774 | |||
| bdaa043404 | |||
| a55cf8d870 | |||
| cf4244fd3a | |||
| 76c3fd64ad | |||
| 701e0ac2be | |||
| a285f8ba3a | |||
| 663821cdf6 | |||
| c4b95494ac | |||
| 980fb4e5a3 | |||
| 96f8f40291 | |||
| 1c698df6e0 | |||
| 298cb433be | |||
| 63af7dd99d | |||
| af5df1d083 | |||
| a3b44093c2 | |||
| c80bf3311f | |||
| 7940d249b0 | |||
| 4a07c81f71 | |||
| 7d56cdf045 | |||
| 0affe621d5 | |||
| 93932b1a9c | |||
| a87f13b9d2 | |||
| 8d2b21ee75 | |||
| 87741c9be8 | |||
| 171cb89170 | |||
| 5dad867bbe | |||
| 13f26fd84d | |||
| 3bc77f7d7f | |||
| aac1ee3af3 | |||
| e85893ac0f | |||
| 315947ee6f | |||
| 23a0d44b11 | |||
| 3b501de057 | |||
| 6cc645aa2a | |||
| 0b37207adc | |||
| f0704ec705 | |||
| 4fcbdf710e | |||
| 866149193a | |||
| 6ffb161618 | |||
| 8e4b49824b | |||
| 5263576de1 | |||
| 6d4e2ea0e9 | |||
| 3cbfa98e6b | |||
| d256cbe0e0 | |||
| a6dfa30dcf | |||
| d0365dc434 | |||
| aa41432bbb | |||
| 98a2b4a547 | |||
| 806ce9a360 | |||
| 8b28092cc8 | |||
| 5c5f4c1c84 | |||
| 949d330295 | |||
| 9a5ee4f37a | |||
| 7a23cc6c84 | |||
| 041acd11fe | |||
| 24b4033db9 | |||
| 1115f83b8f | |||
| 60a1603636 | |||
| ea467fa031 | |||
| b0e6f73b1d | |||
| 6d9e015b5e | |||
| fececd89ab | |||
| 48e287892f | |||
| f118400820 | |||
| 3f8407c7af | |||
| 83317739c7 | |||
| 0b665bd1ca | |||
| 98d4cbdf95 | |||
| 6cb75b54a0 | |||
| 53edfe93cf | |||
| b856deae43 | |||
| 259c842259 | |||
| ffb195ea7a | |||
| b4677534d1 | |||
| f967b82467 | |||
| c81946930e | |||
| 1008b775a4 | |||
| 41210dfc51 | |||
| 67b7272249 | |||
| 964e045903 | |||
| 137cf67f40 | |||
| 309a526e3c | |||
| dd95927498 | |||
| 4f72feae91 | |||
| 3cd8f9f597 | |||
| d2e8d0c62a | |||
| fafbd8c9c7 | |||
| a40c91b054 | |||
| 98894055c6 | |||
| 4589a84643 | |||
| e6b7f52d3e | |||
| b169db617a | |||
| 89a49f4f4f | |||
| 58490715fe | |||
| 4c2283c4e5 | |||
| a059070dec | |||
| 20dfeb4cfa | |||
| aefc3266c1 | |||
| fdf48dd459 | |||
| 66525346a2 | |||
| c9b2ec4a2b | |||
| bf583a7266 | |||
| de194d1c73 | |||
| ecdc289df1 | |||
| 9e198ac40d | |||
| 0a06998690 | |||
| 484a7105a9 | |||
| 8d18ea167b | |||
| a2ca89bfe0 | |||
| edeea40898 | |||
| 2a7080b094 | |||
| b354f2386b | |||
| d766bd03d2 | |||
| 6a69148356 | |||
| e1e1b0b522 | |||
| d824876653 | |||
| 2048698f77 | |||
| 9942979aa7 | |||
| 3c2655a1f9 | |||
| 552a61a66f | |||
| d13143e322 | |||
| 5116ad8d08 | |||
| 64683a55f3 | |||
| 698cd9c631 | |||
| c744a99102 | |||
| 2d2935085e | |||
| 1b31e2c8cd | |||
| 7257751993 | |||
| de6bfdb1b1 | |||
| 9e49f4411b | |||
| 026d068ddf | |||
| 7055d6fc3c | |||
| e9c2366bf1 | |||
| 6278152e49 | |||
| 76010c0cea | |||
| 889b84cfb9 | |||
| a26681c416 | |||
| 90027a7b44 | |||
| aab56faf88 | |||
| c57bd11c45 | |||
| 3fa1e29468 | |||
| cf87f84900 | |||
| 402d4ef013 | |||
| fc94906a1e | |||
| b83fcd11e4 | |||
| c28af7c7bc | |||
| dbc853bcc5 | |||
| c8396c5a3c | |||
| 65af8d3a26 | |||
| 329b6ec958 | |||
| 09bf27abd7 | |||
| 2ec6a529c7 | |||
| e8e21a0e4e | |||
| 88d243f145 | |||
| 3a6e287443 | |||
| beb3e5cd7f | |||
| 7416a87e10 | |||
| 65b85b237e | |||
| b17a80014a | |||
| ff87f99807 | |||
| 65d834615d | |||
| b8be4c09e2 | |||
| e5fb332538 | |||
| 491033d534 | |||
| 885fa316a5 | |||
| b6ed679771 | |||
| 68fc6e8b50 | |||
| ea0331ef5a | |||
| 6827e245b8 | |||
| ef25d6960c | |||
| f740f44cf2 | |||
| a5e4e6d857 | |||
| cfdd6db530 | |||
| d4eda9f396 | |||
| a433b107e0 | |||
| 59f9fb6c3f | |||
| 09d532ebcc | |||
| cfd6f3ca8c | |||
| 95add73c38 | |||
| 9ee036b160 | |||
| c2b521199c | |||
| ee9f3f373a | |||
| f205358587 | |||
| 255ae7dced | |||
| b4c6d509a0 | |||
| 34cd57b639 | |||
| 50dfd7bf60 | |||
| 0b57187909 | |||
| e78e9f4832 | |||
| 383933adb5 | |||
| dd054137bf | |||
| cf3b7571eb | |||
| ae7a2c202a | |||
| 9b00d578bc | |||
| b8173e4c4e | |||
| 67b5445fb9 | |||
| 87419ef5d1 | |||
| ad218160d8 | |||
| eeb90d7991 | |||
| 7b7329bd18 | |||
| b3acbb06f4 | |||
| 7db7562841 | |||
| 0e75b124c3 | |||
| d79a0b76f3 | |||
| c3eb4933fb | |||
| e3a956aedd | |||
| e562e479dc | |||
| 1900e019e3 | |||
| 317f140822 | |||
| cd829474d6 | |||
| b6c1500570 | |||
| d06a85bd34 | |||
| 6b9a2feac5 | |||
| bd08004afe | |||
| 0ecc4b2051 | |||
| f9f351229a | |||
| 72659a237b | |||
| 6cc3a36d44 | |||
| 6fe55d6e88 | |||
| 36f2903eb3 | |||
| 09464e6da7 | |||
| 955e084cf3 | |||
| 46ee0c8765 | |||
| da5391c018 | |||
| ce732beece | |||
| 889b70093c | |||
| 7211a27f01 | |||
| ba95ca3fb6 | |||
| ffdc507625 | |||
| 8aef0dece9 | |||
| c680af63ef | |||
| 4a7ac65184 | |||
| 4016c55604 | |||
| 0f64084c20 | |||
| 7af03d9205 | |||
| d903da626f | |||
| 177b446229 | |||
| ab9d941d15 | |||
| 66fd990624 | |||
| f6dabd0d3e | |||
| 74caaa2bf7 | |||
| 552403b370 | |||
| a93d09d159 | |||
| 0fb757f6c1 | |||
| a68053ca4e | |||
| 36d4f4027b | |||
| 19d92507e3 | |||
| 664e92a3d6 | |||
| d687c110e4 | |||
| af5ae7054e | |||
| dff1e7f552 | |||
| cf446401e5 | |||
| e9b87ef09b | |||
| 7231ddb1b3 | |||
| 1ead36f1bb | |||
| 8a9b78a4ab | |||
| 569299724a | |||
| 6dd401e1c7 | |||
| c4cb37786b | |||
| b757d9a94e | |||
| 6cc083f370 | |||
| c419027db9 | |||
| 6a16b47406 | |||
| 4197ae8b9f | |||
| 88696e1407 | |||
| 24cb48f195 | |||
| 965cfd291e | |||
| 873329c052 | |||
| 3d8023b9a9 | |||
| 93d1450fc1 | |||
| 27d55fde8c | |||
| 690399b04c | |||
| 65b84f1ab3 | |||
| 835acb89d0 | |||
| d9df9ea75c | |||
| 06874ffb69 | |||
| f0898a3930 | |||
| 7d50196d2f | |||
| f90f7fee64 | |||
| 3d860df873 | |||
| 2fe3a2b6a8 | |||
| eb3d4af204 | |||
| 0652352e92 | |||
| 103949513b | |||
| 9ba4547c4d | |||
| 4fea0adf43 | |||
| de070dbfa7 | |||
| 87eb72bdb2 | |||
| fe03aaae55 | |||
| 9ce7d3d648 | |||
| 0471407761 | |||
| e4b807a018 | |||
| 0a0ec37725 | |||
| 8abca5d818 | |||
| 3a29a8036b | |||
| e2b9b66f71 | |||
| bb66cb7e36 | |||
| 2159e77c9d | |||
| 3154f521d9 | |||
| fda8024607 | |||
| 89336e4ddf | |||
| a94f747307 | |||
| 88d3b41044 | |||
| 7fd02ab8d1 | |||
| 9e5d8e143e | |||
| f0f7df29b3 | |||
| 05ba70881c | |||
| 8a729cdd0d | |||
| ffe5fbcd51 | |||
| 18cc545e16 | |||
| c818e90cfc | |||
| 570973b9d6 | |||
| 09d19b99ba | |||
| 7ad30dc660 | |||
| 5c1702c527 | |||
| f1063d58ae | |||
| eee39221c4 | |||
| 4303961948 | |||
| e2790dabc8 | |||
| ba42aa592c | |||
| e1deba1222 | |||
| f9c2dd1b3a | |||
| 8bf0a41926 | |||
| 5c89aa54c4 | |||
| 69484526e6 | |||
| bfc84384ea | |||
| cce3b792db | |||
| bff40f27c5 | |||
| c3e3b598bb | |||
| fa17f7e352 | |||
| 3aed922a3b | |||
| 7c4e37c5cd | |||
| 2d8845b084 | |||
| 47f21796e0 | |||
| eb6de99fcb | |||
| 2bfc8f3161 | |||
| bcacf88e55 | |||
| 13766a82b2 | |||
| 34d7ca66f5 | |||
| 17a803bb17 | |||
| 1bd47969b3 | |||
| 5fec0f1135 | |||
| a73942ddea | |||
| 34a26e5e4d | |||
| f74dea5fae | |||
| ee3eb7d8e2 | |||
| 75f94eea1b | |||
| b737bda40d | |||
| d99b1d61d7 | |||
| 844029d8e5 | |||
| 9492cc64b5 | |||
| 5773f97e88 | |||
| 0784dc3a0a | |||
| 7993be7d0d | |||
| f22ce6e757 | |||
| 3c4347b247 | |||
| 977f2840b9 | |||
| 5d3bb6642e | |||
| 2001eb7ffb | |||
| f18c9f69d4 | |||
| 8e124e5b63 | |||
| 4ed5e544b0 | |||
| b185bda5b1 | |||
| d79804e271 | |||
| 2b356c8613 | |||
| 2e6b36ef4b | |||
| edd0f66234 | |||
| 2da407d66c | |||
| fa574f709e | |||
| 1e6171521b | |||
| 3f3e4eca66 | |||
| 648482b0f1 | |||
| bb46afe33d | |||
| 80f5914abf | |||
| 1c4e7f9c3e | |||
| e4ae6e9076 | |||
| f93efa2ea1 | |||
| 7d79365262 | |||
| 555692207e | |||
| fcc06b227a | |||
| 08a39790e4 | |||
| a8270082a0 | |||
| 85da798538 | |||
| b68d8697df | |||
| 7704df5042 | |||
| 16f04c7e7e | |||
| 7c6b3117bf | |||
| 7def68fb37 | |||
| 03ed2b4129 | |||
| 733d62a699 | |||
| f76e1d0796 | |||
| 88d42ccd8d | |||
| a0686fb1f2 | |||
| 3d198d94a6 | |||
| 036c00db73 | |||
| 548f0687f1 | |||
| f85c042a94 | |||
| 40e892f813 | |||
| 2381025306 | |||
| a0909dc053 | |||
| 853a14b7c7 | |||
| b31e2d42eb | |||
| 5b6ad9419f | |||
| a60948a87e | |||
| 8b420da753 | |||
| 12c079b74a | |||
| c835f78dd0 | |||
| d52eb9d4ee | |||
| 0cfd9f60b5 | |||
| 5ab65eb95a | |||
| b13fb36de0 | |||
| d8fe65a273 | |||
| ba1cb996cf | |||
| 41f41d6543 | |||
| e25fc44db9 | |||
| 2ea91dc94b | |||
| b16419ad3e | |||
| 1e3c05c408 | |||
| a7eb59f472 | |||
| e99448481c | |||
| 83ab7622d9 | |||
| d4312d504b | |||
| 95742e7704 | |||
| a8845a33df | |||
| b3fd87f302 | |||
| 25ba970e09 | |||
| a67f9aaad7 | |||
| 210ce35867 | |||
| 36905f6442 | |||
| ed509db04a | |||
| 14413c0637 | |||
| 9682c95da8 | |||
| 7c6eba90e5 | |||
| c85bf225b9 | |||
| b51c2d66a5 | |||
| 935bc52239 | |||
| 57ff51823c | |||
| 06b20a1772 | |||
| 7a98255149 | |||
| 980038c711 | |||
| 09d4e36200 | |||
| 8fb523bcef | |||
| e48a621d61 | |||
| 1f87787b05 | |||
| fb6cef8a0b | |||
| 21368f6218 | |||
| 116685017d | |||
| 23082f2c5e | |||
| ff2b3ca727 | |||
| e55d41f5df | |||
| 91fb5101d6 | |||
| 9c5e22a656 | |||
| 18f23b298e | |||
| ddf39ebeaa | |||
| 320b515e7d | |||
| 04c50ee946 | |||
| 3d626d68aa | |||
| 9c0442bdb5 | |||
| 606ffa40d1 | |||
| e9f6de1238 | |||
| 8110ab98b6 | |||
| b8c4bd70ae | |||
| 2e49856621 | |||
| 2039509811 | |||
| 420f2ddeb7 | |||
| afc0516868 | |||
| 02a0f5e96c | |||
| 2f7b05006b | |||
| 314089b0a1 | |||
| 60e626d6d0 | |||
| 5c2050ebcf | |||
| 7fd2870d45 | |||
| 609e3339c0 | |||
| 0e01723aee | |||
| 25141b85f9 | |||
| 21510bd664 | |||
| 696d1de19f | |||
| 56020b4bc3 | |||
| 62e29d5a51 | |||
| 15c890a7b8 | |||
| 43b33c558f | |||
| be0661f156 | |||
| b9a5a0498a | |||
| 8c4261500c | |||
| 2254d98bcc | |||
| 21f9096846 | |||
| 9830dc2962 | |||
| c29a8cc63b | |||
| ef7872eb4f | |||
| 3282223511 | |||
| c99c5eb03f | |||
| 3b759c26c4 | |||
| 5038a1f351 | |||
| 0aa7552de6 | |||
| 7fae7d2cde | |||
| f35d8e5b64 | |||
| 63cc0a35d3 | |||
| d159bdd50c | |||
| 0f2c609621 | |||
| 4e14952b24 | |||
| b36d4b2723 | |||
| bf53cd3d3d | |||
| f2e3935c0b | |||
| 77f41f9356 | |||
| 042500dd55 | |||
| f0be93313a | |||
| bf9e26319c | |||
| 5054eb3b10 | |||
| 9bea88c7b8 | |||
| 786c25d342 | |||
| d00f18d567 | |||
| 0f363487e9 | |||
| b471da75d6 | |||
| e5937ff6f8 | |||
| 08379e61bf | |||
| 6c8a65b055 | |||
| d059db62c3 | |||
| e4dd4a9036 | |||
| c0fc9f6e55 | |||
| 72d919566c | |||
| 2aeb3415b1 | |||
| 680a12f87e | |||
| 7a83b34c16 | |||
| ecd16f9fb0 | |||
| 54ca85d482 | |||
| 65ef0be90c | |||
| 57106affdf | |||
| d613bbd358 | |||
| d0bf2104dc | |||
| e70413373f | |||
| 36f0af5a5d | |||
| 79d7076121 | |||
| 526b3e74bf | |||
| d03dc21e8a | |||
| c31dfa4957 | |||
| c7e510723d | |||
| 42093de872 | |||
| 886e58828e | |||
| c8eaf1c9ac | |||
| 2169dadccc | |||
| 4bc8a7b733 | |||
| 61eb955921 | |||
| aa48a5d764 | |||
| 1dedca45ac | |||
| 9d90335a12 | |||
| b577acb115 | |||
| 425e2bcccc | |||
| 3766251891 | |||
| 3552de1b45 | |||
| 2b94e36df6 | |||
| d1e1de4a8d | |||
| 23587e17ad | |||
| 213f452f0b | |||
| 27a488539d | |||
| 283da50d33 | |||
| a809085715 | |||
| 67321f1cba | |||
| 7683186470 | |||
| fded43b77e | |||
| 22ff7da4e0 | |||
| 844561b6cc | |||
| 1fe02a3067 | |||
| 362d8ecb31 | |||
| 5f5f6389f9 | |||
| 31cf3cde45 | |||
| 11f0c2cab1 | |||
| 52bc1d8387 | |||
| 8a3ac0c338 | |||
| bb125d7d4f | |||
| a405716847 | |||
| bad6e03095 | |||
| 2330fddfbb | |||
| 61dfd74134 | |||
| 029ff83979 | |||
| dbbc4cb2e1 | |||
| 1cce21cdc2 | |||
| 8b786a51b3 | |||
| ad7537dd84 | |||
| 3bab23172a | |||
| 18c132d494 | |||
| d072353e08 | |||
| c8bbc101cc | |||
| b93f748998 | |||
| ecb100448a | |||
| c749c856b5 | |||
| 0baf278972 | |||
| ae7780266a | |||
| 587960aebe | |||
| 4e1b6784f7 | |||
| 8b381f2640 | |||
| 0dc7fa6c34 | |||
| 2a2bf682bf | |||
| 87526129fb | |||
| 8ed1b7aa46 | |||
| 4084bd0ecc | |||
| d11eaceaf1 | |||
| 1e6986fbc5 | |||
| 11a19bdec7 | |||
| 51064f1b90 | |||
| 3385cd19e8 | |||
| 852f8517df | |||
| bb917f9818 | |||
| 10248fb29f | |||
| 446dc85bdd | |||
| 4aa2c226a9 | |||
| bf9ba8313a | |||
| 444b59c557 | |||
| b2e1df94db | |||
| b4963cabc8 | |||
| 2851024340 | |||
| 7f25a25729 | |||
| acfe23265a | |||
| 2c6fbbd7dd | |||
| f84507f513 | |||
| be6a9e4a48 | |||
| 69e7634619 | |||
| 3e8c923641 | |||
| df5cbe30a6 | |||
| 9e1a536778 | |||
| a1db8833ef | |||
| 95dd0e0158 | |||
| 19f3c857d5 | |||
| 7f3da73aa4 | |||
| c384c2b610 | |||
| dcf358f27d | |||
| 40afc8c0e2 | |||
| b22bc8a799 |
+16
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"jsc": {
|
||||
"parser": {
|
||||
"syntax": "typescript",
|
||||
"decorators": true
|
||||
},
|
||||
"target": "esnext",
|
||||
"transform": {
|
||||
"decoratorVersion": "2022-03"
|
||||
}
|
||||
},
|
||||
"module": {
|
||||
"type": "commonjs",
|
||||
"ignoreDynamic": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
module.exports = {
|
||||
root: true,
|
||||
extends: [
|
||||
"turbo",
|
||||
"prettier",
|
||||
"plugin:@typescript-eslint/recommended-type-checked-only",
|
||||
],
|
||||
parserOptions: {
|
||||
project: true,
|
||||
__tsconfigRootDir: __dirname,
|
||||
},
|
||||
settings: {
|
||||
react: {
|
||||
version: "999.999.999",
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
"max-params": ["error", 4],
|
||||
"prefer-const": "error",
|
||||
"@typescript-eslint/no-floating-promises": [
|
||||
"error",
|
||||
{
|
||||
ignoreIIFE: true,
|
||||
},
|
||||
],
|
||||
"@typescript-eslint/await-thenable": "off",
|
||||
"@typescript-eslint/ban-ts-comment": "off",
|
||||
"@typescript-eslint/ban-types": "off",
|
||||
"no-array-constructor": "off",
|
||||
"@typescript-eslint/no-array-constructor": "off",
|
||||
"@typescript-eslint/no-base-to-string": "off",
|
||||
"@typescript-eslint/no-duplicate-enum-values": "off",
|
||||
"@typescript-eslint/no-duplicate-type-constituents": "off",
|
||||
"@typescript-eslint/no-explicit-any": "off",
|
||||
"@typescript-eslint/no-extra-non-null-assertion": "off",
|
||||
"@typescript-eslint/no-for-in-array": "off",
|
||||
"no-implied-eval": "off",
|
||||
"@typescript-eslint/no-implied-eval": "off",
|
||||
"no-loss-of-precision": "off",
|
||||
"@typescript-eslint/no-loss-of-precision": "off",
|
||||
"@typescript-eslint/no-misused-new": "off",
|
||||
"@typescript-eslint/no-misused-promises": "off",
|
||||
"@typescript-eslint/no-namespace": "off",
|
||||
"@typescript-eslint/no-non-null-asserted-optional-chain": "off",
|
||||
"@typescript-eslint/no-redundant-type-constituents": "off",
|
||||
"@typescript-eslint/no-this-alias": "off",
|
||||
"@typescript-eslint/no-unnecessary-type-assertion": "off",
|
||||
"@typescript-eslint/no-unnecessary-type-constraint": "off",
|
||||
"@typescript-eslint/no-unsafe-argument": "off",
|
||||
"@typescript-eslint/no-unsafe-assignment": "off",
|
||||
"@typescript-eslint/no-unsafe-call": "off",
|
||||
"@typescript-eslint/no-unsafe-declaration-merging": "off",
|
||||
"@typescript-eslint/no-unsafe-enum-comparison": "off",
|
||||
"@typescript-eslint/no-unsafe-member-access": "off",
|
||||
"@typescript-eslint/no-unsafe-return": "off",
|
||||
"no-unused-vars": "off",
|
||||
"@typescript-eslint/no-unused-vars": "off",
|
||||
"@typescript-eslint/no-var-requires": "off",
|
||||
"@typescript-eslint/prefer-as-const": "off",
|
||||
"require-await": "off",
|
||||
"@typescript-eslint/require-await": "off",
|
||||
"@typescript-eslint/restrict-plus-operands": "off",
|
||||
"@typescript-eslint/restrict-template-expressions": "off",
|
||||
"@typescript-eslint/triple-slash-reference": "off",
|
||||
"@typescript-eslint/unbound-method": "off",
|
||||
},
|
||||
overrides: [
|
||||
{
|
||||
files: ["examples/**/*.ts"],
|
||||
rules: {
|
||||
"turbo/no-undeclared-env-vars": "off",
|
||||
},
|
||||
},
|
||||
],
|
||||
ignorePatterns: ["dist/", "lib/", "deps/"],
|
||||
};
|
||||
@@ -1,10 +0,0 @@
|
||||
module.exports = {
|
||||
root: true,
|
||||
// This tells ESLint to load the config from the package `eslint-config-custom`
|
||||
extends: ["custom"],
|
||||
settings: {
|
||||
next: {
|
||||
rootDir: ["apps/*/"],
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,2 @@
|
||||
examples/readers/data/** binary
|
||||
examples/data/** binary
|
||||
@@ -1,7 +1,6 @@
|
||||
name: Bugfix
|
||||
title: "Sweep: "
|
||||
description: Write something like "We notice ... behavior when ... happens instead of ...""
|
||||
labels: sweep
|
||||
title: ""
|
||||
description: Write something like "We notice ... behavior when ... happens instead of ..." If you would like to use sweep.dev prefix with "Sweep:"
|
||||
body:
|
||||
- type: textarea
|
||||
id: description
|
||||
@@ -1,11 +1,10 @@
|
||||
name: Feature Request
|
||||
title: "Sweep: "
|
||||
description: Write something like "Write an api endpoint that does "..." in the "..." file"
|
||||
labels: sweep
|
||||
title: ""
|
||||
description: Write something like "Write an api endpoint that does "..." in the "..." file". If you would like to use sweep.dev prefix with "Sweep:"
|
||||
body:
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: Details
|
||||
description: More details for Sweep
|
||||
description: More details
|
||||
placeholder: The new endpoint should use the ... class from ... file because it contains ... logic
|
||||
@@ -1,11 +1,10 @@
|
||||
name: Refactor
|
||||
title: "Sweep: "
|
||||
description: Write something like "Modify the ... api endpoint to use ... version and ... framework"
|
||||
labels: sweep
|
||||
title: ""
|
||||
description: Write something like "Modify the ... api endpoint to use ... version and ... framework" If you would like to use sweep.dev prefix with "Sweep:"
|
||||
body:
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: Details
|
||||
description: More details for Sweep
|
||||
description: More details
|
||||
placeholder: We are migrating this function to ... version because ...
|
||||
@@ -12,14 +12,16 @@ jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Install pnpm
|
||||
run: npm install -g pnpm
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v3
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: "pnpm"
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Run lint
|
||||
run: pnpm run lint
|
||||
- name: Run Prettier
|
||||
run: pnpm run format
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
name: Publish
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v3
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: "pnpm"
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Publish @llamaindex/env
|
||||
run: npx jsr publish
|
||||
working-directory: packages/env
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Publish @llamaindex/core
|
||||
run: npx jsr publish --allow-slow-types
|
||||
working-directory: packages/core
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -0,0 +1,37 @@
|
||||
name: Publish to GitHub Releases
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "llamaindex@*"
|
||||
|
||||
jobs:
|
||||
build-and-publish:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Repo
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v3
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: "pnpm"
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Build tarball
|
||||
run: |
|
||||
pnpm pack
|
||||
working-directory: packages/core
|
||||
|
||||
- name: Create release
|
||||
uses: ncipollo/release-action@v1
|
||||
with:
|
||||
artifacts: "packages/core/llamaindex-*.tgz"
|
||||
name: Release ${{ github.ref }}
|
||||
bodyFile: "packages/core/CHANGELOG.md"
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -0,0 +1,57 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
concurrency: ${{ github.workflow }}-${{ github.ref }}
|
||||
|
||||
jobs:
|
||||
release:
|
||||
name: Release
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Repo
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v3
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: "pnpm"
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Add auth token to .npmrc file
|
||||
run: |
|
||||
cat << EOF >> ".npmrc"
|
||||
//registry.npmjs.org/:_authToken=$NPM_TOKEN
|
||||
EOF
|
||||
env:
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
|
||||
- name: Get changeset status
|
||||
id: get-changeset-status
|
||||
run: |
|
||||
pnpm changeset status --output .changeset/status.json
|
||||
new_version=$(jq -r '.releases[] | select(.name == "llamaindex") | .newVersion' < .changeset/status.json)
|
||||
rm -v .changeset/status.json
|
||||
echo "new-version=${new_version}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Create Release Pull Request or Publish to npm
|
||||
id: changesets
|
||||
uses: changesets/action@v1
|
||||
with:
|
||||
commit: Release ${{ steps.get-changeset-status.outputs.new-version }}
|
||||
title: Release ${{ steps.get-changeset-status.outputs.new-version }}
|
||||
# update version PR with the latest changesets
|
||||
version: pnpm new-version
|
||||
# build package and call changeset publish
|
||||
publish: pnpm release
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
+128
-11
@@ -1,24 +1,141 @@
|
||||
name: Run Tests
|
||||
|
||||
on: [push, pull_request]
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
e2e:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
node-version: [18.x, 20.x, 22.x]
|
||||
name: E2E on Node.js ${{ matrix.node-version }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v3
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: "pnpm"
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
- name: Run E2E Tests
|
||||
run: pnpm run e2e
|
||||
|
||||
test:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
node-version: [18.x, 20.x, 22.x]
|
||||
name: Test on Node.js ${{ matrix.node-version }}
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v3
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v2
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "18"
|
||||
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: "pnpm"
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
npm i -g pnpm
|
||||
pnpm install
|
||||
|
||||
run: pnpm install
|
||||
- name: Run tests
|
||||
run: pnpm run test
|
||||
typecheck:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v3
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: "pnpm"
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
- name: Build
|
||||
run: pnpm run build --filter llamaindex
|
||||
- name: Use Build For Examples
|
||||
run: pnpm link ../packages/core/
|
||||
working-directory: ./examples
|
||||
- name: Run Type Check
|
||||
run: pnpm run type-check
|
||||
- name: Run Circular Dependency Check
|
||||
run: pnpm run circular-check
|
||||
working-directory: ./packages/core
|
||||
- uses: actions/upload-artifact@v3
|
||||
if: failure()
|
||||
with:
|
||||
name: typecheck-build-dist
|
||||
path: ./packages/core/dist
|
||||
if-no-files-found: error
|
||||
e2e-core-examples:
|
||||
strategy:
|
||||
matrix:
|
||||
packages:
|
||||
- cloudflare-worker-agent
|
||||
- nextjs-agent
|
||||
- nextjs-edge-runtime
|
||||
- waku-query-engine
|
||||
runs-on: ubuntu-latest
|
||||
name: Build Core Example (${{ matrix.packages }})
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v3
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: "pnpm"
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
- name: Build llamaindex
|
||||
run: pnpm run build --filter llamaindex
|
||||
- name: Build ${{ matrix.packages }}
|
||||
run: pnpm run build
|
||||
working-directory: packages/core/e2e/examples/${{ matrix.packages }}
|
||||
|
||||
typecheck-examples:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v3
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: "pnpm"
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
- name: Build
|
||||
run: pnpm run build --filter llamaindex
|
||||
- name: Copy examples
|
||||
run: rsync -rv --exclude=node_modules ./examples ${{ runner.temp }}
|
||||
- name: Pack @llamaindex/env
|
||||
run: pnpm pack --pack-destination ${{ runner.temp }}
|
||||
working-directory: packages/env
|
||||
- name: Pack llamaindex
|
||||
run: pnpm pack --pack-destination ${{ runner.temp }}
|
||||
working-directory: packages/core
|
||||
- name: Install
|
||||
run: npm add ${{ runner.temp }}/*.tgz
|
||||
working-directory: ${{ runner.temp }}/examples
|
||||
- name: Run Type Check
|
||||
run: npx tsc --project ./tsconfig.json
|
||||
working-directory: ${{ runner.temp }}/examples
|
||||
|
||||
+10
-2
@@ -37,6 +37,14 @@ yarn-error.log*
|
||||
.vercel
|
||||
|
||||
dist/
|
||||
lib/
|
||||
|
||||
# vs code
|
||||
.vscode/launch.json
|
||||
.cache
|
||||
test-results/
|
||||
playwright-report/
|
||||
blob-report/
|
||||
playwright/.cache/
|
||||
.tsbuildinfo
|
||||
|
||||
# intellij
|
||||
**/.idea
|
||||
|
||||
+1
-3
@@ -1,5 +1,3 @@
|
||||
#!/usr/bin/env sh
|
||||
. "$(dirname -- "$0")/_/husky.sh"
|
||||
|
||||
pnpm format:write
|
||||
pnpm lint
|
||||
npx lint-staged
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
#!/usr/bin/env sh
|
||||
. "$(dirname -- "$0")/_/husky.sh"
|
||||
|
||||
pnpm test
|
||||
@@ -1 +1,5 @@
|
||||
auto-install-peers = true
|
||||
enable-pre-post-scripts = true
|
||||
prefer-workspace-packages = true
|
||||
save-workspace-protocol = true
|
||||
link-workspace-packages = true
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
apps/docs/i18n
|
||||
apps/docs/docs/api
|
||||
pnpm-lock.yaml
|
||||
lib/
|
||||
dist/
|
||||
.docusaurus/
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"jsc": {
|
||||
"parser": {
|
||||
"syntax": "typescript",
|
||||
"decorators": true
|
||||
},
|
||||
"target": "esnext",
|
||||
"transform": {
|
||||
"decoratorVersion": "2022-03"
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+18
@@ -0,0 +1,18 @@
|
||||
{
|
||||
// Use IntelliSense to learn about possible attributes.
|
||||
// Hover to view descriptions of existing attributes.
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
"name": "Debug Example",
|
||||
"skipFiles": ["<node_internals>/**"],
|
||||
"runtimeExecutable": "pnpm",
|
||||
"console": "integratedTerminal",
|
||||
"cwd": "${workspaceFolder}/examples",
|
||||
"runtimeArgs": ["npx", "tsx", "${file}"]
|
||||
}
|
||||
]
|
||||
}
|
||||
Vendored
+9
@@ -4,5 +4,14 @@
|
||||
"editor.defaultFormatter": "esbenp.prettier-vscode",
|
||||
"[xml]": {
|
||||
"editor.defaultFormatter": "redhat.vscode-xml"
|
||||
},
|
||||
"[python]": {
|
||||
"editor.defaultFormatter": "ms-python.black-formatter"
|
||||
},
|
||||
"[jsonc]": {
|
||||
"editor.defaultFormatter": "esbenp.prettier-vscode"
|
||||
},
|
||||
"[json]": {
|
||||
"editor.defaultFormatter": "esbenp.prettier-vscode"
|
||||
}
|
||||
}
|
||||
|
||||
+23
-3
@@ -8,7 +8,7 @@ Right now there are two packages of importance:
|
||||
|
||||
packages/core which is the main NPM library llamaindex
|
||||
|
||||
apps/simple is where the demo code lives
|
||||
examples is where the demo code lives
|
||||
|
||||
### Turborepo docs
|
||||
|
||||
@@ -47,7 +47,7 @@ We use Jest https://jestjs.io/ to write our test cases. Jest comes with a bunch
|
||||
|
||||
### Demo applications
|
||||
|
||||
There is an existing ["simple"](/apps/simple/README.md) demos folder with mainly NodeJS scripts. Feel free to add additional demos to that folder. If you would like to try out your changes in the core package with a new demo, you need to run the build command in the README.
|
||||
There is an existing ["example"](/examples/README.md) demos folder with mainly NodeJS scripts. Feel free to add additional demos to that folder. If you would like to try out your changes in the core package with a new demo, you need to run the build command in the README.
|
||||
|
||||
You can create new demo applications in the apps folder. Just run pnpm init in the folder after you create it to create its own package.json
|
||||
|
||||
@@ -56,7 +56,7 @@ You can create new demo applications in the apps folder. Just run pnpm init in t
|
||||
To install packages for a specific package or demo application, run
|
||||
|
||||
```
|
||||
pnpm add [NPM Package] --filter [package or application i.e. core or simple]
|
||||
pnpm add [NPM Package] --filter [package or application i.e. core or docs]
|
||||
```
|
||||
|
||||
To install packages for every package or application run
|
||||
@@ -78,3 +78,23 @@ pnpm start
|
||||
That should start a webserver which will serve the docs on https://localhost:3000
|
||||
|
||||
Any changes you make should be reflected in the browser. If you need to regenerate the API docs and find that your TSDoc isn't getting the updates, feel free to remove apps/docs/api. It will automatically regenerate itself when you run pnpm start again.
|
||||
|
||||
## Changeset
|
||||
|
||||
We use [changesets](https://github.com/changesets/changesets) for managing versions and changelogs. To create a new changeset, run:
|
||||
|
||||
```
|
||||
pnpm changeset
|
||||
```
|
||||
|
||||
Please send a descriptive changeset for each PR.
|
||||
|
||||
## Publishing (maintainers only)
|
||||
|
||||
The [Release Github Action](.github/workflows/release.yml) is automatically generating and updating a
|
||||
PR called "Release {version}".
|
||||
|
||||
This PR will update the `package.json` and `CHANGELOG.md` files of each package according to
|
||||
the current changesets in the [.changeset](.changeset/) folder.
|
||||
|
||||
If this PR is merged it will automatically add version tags to the repository and publish the updated packages to NPM.
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
# Turborepo starter
|
||||
|
||||
This is an official starter Turborepo.
|
||||
|
||||
## Using this example
|
||||
|
||||
Run the following command:
|
||||
|
||||
```sh
|
||||
npx create-turbo@latest
|
||||
```
|
||||
|
||||
## What's inside?
|
||||
|
||||
This Turborepo includes the following packages/apps:
|
||||
|
||||
### Apps and Packages
|
||||
|
||||
- `docs`: a [Next.js](https://nextjs.org/) app
|
||||
- `web`: another [Next.js](https://nextjs.org/) app
|
||||
- `ui`: a stub React component library shared by both `web` and `docs` applications
|
||||
- `eslint-config-custom`: `eslint` configurations (includes `eslint-config-next` and `eslint-config-prettier`)
|
||||
- `tsconfig`: `tsconfig.json`s used throughout the monorepo
|
||||
|
||||
Each package/app is 100% [TypeScript](https://www.typescriptlang.org/).
|
||||
|
||||
### Utilities
|
||||
|
||||
This Turborepo has some additional tools already setup for you:
|
||||
|
||||
- [TypeScript](https://www.typescriptlang.org/) for static type checking
|
||||
- [ESLint](https://eslint.org/) for code linting
|
||||
- [Prettier](https://prettier.io) for code formatting
|
||||
|
||||
### Build
|
||||
|
||||
To build all apps and packages, run the following command:
|
||||
|
||||
```
|
||||
cd my-turborepo
|
||||
pnpm build
|
||||
```
|
||||
|
||||
### Develop
|
||||
|
||||
To develop all apps and packages, run the following command:
|
||||
|
||||
```
|
||||
cd my-turborepo
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
### Remote Caching
|
||||
|
||||
Turborepo can use a technique known as [Remote Caching](https://turbo.build/repo/docs/core-concepts/remote-caching) to share cache artifacts across machines, enabling you to share build caches with your team and CI/CD pipelines.
|
||||
|
||||
By default, Turborepo will cache locally. To enable Remote Caching you will need an account with Vercel. If you don't have an account you can [create one](https://vercel.com/signup), then enter the following commands:
|
||||
|
||||
```
|
||||
cd my-turborepo
|
||||
npx turbo login
|
||||
```
|
||||
|
||||
This will authenticate the Turborepo CLI with your [Vercel account](https://vercel.com/docs/concepts/personal-accounts/overview).
|
||||
|
||||
Next, you can link your Turborepo to your Remote Cache by running the following command from the root of your Turborepo:
|
||||
|
||||
```
|
||||
npx turbo link
|
||||
```
|
||||
|
||||
## Useful Links
|
||||
|
||||
Learn more about the power of Turborepo:
|
||||
|
||||
- [Tasks](https://turbo.build/repo/docs/core-concepts/monorepos/running-tasks)
|
||||
- [Caching](https://turbo.build/repo/docs/core-concepts/caching)
|
||||
- [Remote Caching](https://turbo.build/repo/docs/core-concepts/remote-caching)
|
||||
- [Filtering](https://turbo.build/repo/docs/core-concepts/monorepos/filtering)
|
||||
- [Configuration Options](https://turbo.build/repo/docs/reference/configuration)
|
||||
- [CLI Usage](https://turbo.build/repo/docs/reference/command-line-reference)
|
||||
@@ -1,34 +1,47 @@
|
||||
# LlamaIndex.TS
|
||||
|
||||
[](https://www.npmjs.com/package/llamaindex)
|
||||
[](https://www.npmjs.com/package/llamaindex)
|
||||
[](https://www.npmjs.com/package/llamaindex)
|
||||
[](https://discord.com/invite/eN6D2HQ4aX)
|
||||
|
||||
LlamaIndex is a data framework for your LLM application.
|
||||
|
||||
Use your own data with large language models (LLMs, OpenAI ChatGPT and others) in Typescript and Javascript.
|
||||
|
||||
Documentation: https://ts.llamaindex.ai/
|
||||
|
||||
Try examples online:
|
||||
|
||||
[](https://stackblitz.com/github/run-llama/LlamaIndexTS/tree/main/examples)
|
||||
|
||||
## What is LlamaIndex.TS?
|
||||
|
||||
LlamaIndex.TS aims to be a lightweight, easy to use set of libraries to help you integrate large language models into your applications with your own data.
|
||||
|
||||
## Getting started with an example:
|
||||
## Multiple JS Environment Support
|
||||
|
||||
LlamaIndex.TS requries Node v18 or higher. You can download it from https://nodejs.org or use https://nvm.sh (our preferred option).
|
||||
LlamaIndex.TS supports multiple JS environments, including:
|
||||
|
||||
In a new folder:
|
||||
- Node.js (18, 20, 22) ✅
|
||||
- Deno ✅
|
||||
- Bun ✅
|
||||
- React Server Components (Next.js) ✅
|
||||
|
||||
```bash
|
||||
export OPENAI_API_KEY="sk-......" # Replace with your key from https://platform.openai.com/account/api-keys
|
||||
pnpm init
|
||||
pnpm install typescript
|
||||
pnpm exec tsc --init # if needed
|
||||
For now, browser support is limited due to the lack of support for [AsyncLocalStorage-like APIs](https://github.com/tc39/proposal-async-context)
|
||||
|
||||
## Getting started
|
||||
|
||||
```shell
|
||||
npm install llamaindex
|
||||
pnpm install llamaindex
|
||||
pnpm install @types/node
|
||||
yarn add llamaindex
|
||||
jsr install @llamaindex/core
|
||||
```
|
||||
|
||||
Create the file example.ts
|
||||
### Node.js
|
||||
|
||||
```ts
|
||||
// example.ts
|
||||
import fs from "fs/promises";
|
||||
import { Document, VectorStoreIndex } from "llamaindex";
|
||||
|
||||
@@ -47,9 +60,9 @@ async function main() {
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine();
|
||||
const response = await queryEngine.query(
|
||||
"What did the author do in college?",
|
||||
);
|
||||
const response = await queryEngine.query({
|
||||
query: "What did the author do in college?",
|
||||
});
|
||||
|
||||
// Output response
|
||||
console.log(response.toString());
|
||||
@@ -58,10 +71,110 @@ async function main() {
|
||||
main();
|
||||
```
|
||||
|
||||
Then you can run it using
|
||||
|
||||
```bash
|
||||
pnpx ts-node example.ts
|
||||
# `pnpm install tsx` before running the script
|
||||
node --import tsx ./main.ts
|
||||
```
|
||||
|
||||
### Next.js
|
||||
|
||||
You can combine `ai` with `llamaindex` in Next.js with RSC (React Server Components).
|
||||
|
||||
```tsx
|
||||
// src/apps/page.tsx
|
||||
"use client";
|
||||
import { chatWithAgent } from "@/actions";
|
||||
import type { JSX } from "react";
|
||||
import { useFormState } from "react-dom";
|
||||
|
||||
// You can use the Edge runtime in Next.js by adding this line:
|
||||
// export const runtime = "edge";
|
||||
|
||||
export default function Home() {
|
||||
const [ui, action] = useFormState<JSX.Element | null>(async () => {
|
||||
return chatWithAgent("hello!", []);
|
||||
}, null);
|
||||
return (
|
||||
<main>
|
||||
{ui}
|
||||
<form action={action}>
|
||||
<button>Chat</button>
|
||||
</form>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
```tsx
|
||||
// src/actions/index.ts
|
||||
"use server";
|
||||
import { createStreamableUI } from "ai/rsc";
|
||||
import { OpenAIAgent } from "llamaindex";
|
||||
import type { ChatMessage } from "llamaindex/llm/types";
|
||||
|
||||
export async function chatWithAgent(
|
||||
question: string,
|
||||
prevMessages: ChatMessage[] = [],
|
||||
) {
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [
|
||||
// ... adding your tools here
|
||||
],
|
||||
});
|
||||
const responseStream = await agent.chat({
|
||||
stream: true,
|
||||
message: question,
|
||||
chatHistory: prevMessages,
|
||||
});
|
||||
const uiStream = createStreamableUI(<div>loading...</div>);
|
||||
responseStream
|
||||
.pipeTo(
|
||||
new WritableStream({
|
||||
start: () => {
|
||||
uiStream.update("response:");
|
||||
},
|
||||
write: async (message) => {
|
||||
uiStream.append(message.response.delta);
|
||||
},
|
||||
}),
|
||||
)
|
||||
.catch(console.error);
|
||||
return uiStream.value;
|
||||
}
|
||||
```
|
||||
|
||||
### Cloudflare Workers
|
||||
|
||||
```ts
|
||||
// src/index.ts
|
||||
export default {
|
||||
async fetch(
|
||||
request: Request,
|
||||
env: Env,
|
||||
ctx: ExecutionContext,
|
||||
): Promise<Response> {
|
||||
const { setEnvs } = await import("@llamaindex/env");
|
||||
// set environment variables so that the OpenAIAgent can use them
|
||||
setEnvs(env);
|
||||
const { OpenAIAgent } = await import("llamaindex");
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [],
|
||||
});
|
||||
const responseStream = await agent.chat({
|
||||
stream: true,
|
||||
message: "Hello? What is the weather today?",
|
||||
});
|
||||
const textEncoder = new TextEncoder();
|
||||
const response = responseStream.pipeThrough(
|
||||
new TransformStream({
|
||||
transform: (chunk, controller) => {
|
||||
controller.enqueue(textEncoder.encode(chunk.response.delta));
|
||||
},
|
||||
}),
|
||||
);
|
||||
return new Response(response);
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
## Playground
|
||||
@@ -74,41 +187,62 @@ Check out our NextJS playground at https://llama-playground.vercel.app/. The sou
|
||||
|
||||
- [Node](/packages/core/src/Node.ts): The basic data building block. Most commonly, these are parts of the document split into manageable pieces that are small enough to be fed into an embedding model and LLM.
|
||||
|
||||
- [Embedding](/packages/core/src/Embedding.ts): Embeddings are sets of floating point numbers which represent the data in a Node. By comparing the similarity of embeddings, we can derive an understanding of the similarity of two pieces of data. One use case is to compare the embedding of a question with the embeddings of our Nodes to see which Nodes may contain the data needed to answer that quesiton.
|
||||
- [Embedding](/packages/core/src/embeddings/OpenAIEmbedding.ts): Embeddings are sets of floating point numbers which represent the data in a Node. By comparing the similarity of embeddings, we can derive an understanding of the similarity of two pieces of data. One use case is to compare the embedding of a question with the embeddings of our Nodes to see which Nodes may contain the data needed to answer that quesiton. Because the default service context is OpenAI, the default embedding is `OpenAIEmbedding`. If using different models, say through Ollama, use this [Embedding](/packages/core/src/embeddings/OllamaEmbedding.ts) (see all [here](/packages/core/src/embeddings)).
|
||||
|
||||
- [Indices](/packages/core/src/indices/): Indices store the Nodes and the embeddings of those nodes. QueryEngines retrieve Nodes from these Indices using embedding similarity.
|
||||
|
||||
- [QueryEngine](/packages/core/src/QueryEngine.ts): Query engines are what generate the query you put in and give you back the result. Query engines generally combine a pre-built prompt with selected Nodes from your Index to give the LLM the context it needs to answer your query.
|
||||
- [QueryEngine](/packages/core/src/engines/query/RetrieverQueryEngine.ts): Query engines are what generate the query you put in and give you back the result. Query engines generally combine a pre-built prompt with selected Nodes from your Index to give the LLM the context it needs to answer your query. To build a query engine from your Index (recommended), use the [`asQueryEngine`](/packages/core/src/indices/BaseIndex.ts) method on your Index. See all query engines [here](/packages/core/src/engines/query).
|
||||
|
||||
- [ChatEngine](/packages/core/src/ChatEngine.ts): A ChatEngine helps you build a chatbot that will interact with your Indices.
|
||||
- [ChatEngine](/packages/core/src/engines/chat/SimpleChatEngine.ts): A ChatEngine helps you build a chatbot that will interact with your Indices. See all chat engines [here](/packages/core/src/engines/chat).
|
||||
|
||||
- [SimplePrompt](/packages/core/src/Prompt.ts): A simple standardized function call definition that takes in inputs and formats them in a template literal. SimplePrompts can be specialized using currying and combined using other SimplePrompt functions.
|
||||
|
||||
## Note: NextJS:
|
||||
## Tips when using in non-Node.js environments
|
||||
|
||||
If you're using NextJS App Router, you'll need to use the NodeJS runtime (default) and add the follow config to your next.config.js to have it use imports/exports in the same way Node does.
|
||||
When you are importing `llamaindex` in a non-Node.js environment(such as React Server Components, Cloudflare Workers, etc.)
|
||||
Some classes are not exported from top-level entry file.
|
||||
|
||||
```js
|
||||
export const runtime = "nodejs"; // default
|
||||
The reason is that some classes are only compatible with Node.js runtime,(e.g. `PDFReader`) which uses Node.js specific APIs(like `fs`, `child_process`, `crypto`).
|
||||
|
||||
If you need any of those classes, you have to import them instead directly though their file path in the package.
|
||||
Here's an example for importing the `PineconeVectorStore` class:
|
||||
|
||||
```typescript
|
||||
import { PineconeVectorStore } from "llamaindex/storage/vectorStore/PineconeVectorStore";
|
||||
```
|
||||
|
||||
```js
|
||||
// next.config.js
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
experimental: {
|
||||
serverComponentsExternalPackages: ["pdf-parse"], // Puts pdf-parse in actual NodeJS mode with NextJS App Router
|
||||
},
|
||||
};
|
||||
As the `PDFReader` is not working with the Edge runtime, here's how to use the `SimpleDirectoryReader` with the `LlamaParseReader` to load PDFs:
|
||||
|
||||
module.exports = nextConfig;
|
||||
```typescript
|
||||
import { SimpleDirectoryReader } from "llamaindex/readers/SimpleDirectoryReader";
|
||||
import { LlamaParseReader } from "llamaindex/readers/LlamaParseReader";
|
||||
|
||||
export const DATA_DIR = "./data";
|
||||
|
||||
export async function getDocuments() {
|
||||
const reader = new SimpleDirectoryReader();
|
||||
// Load PDFs using LlamaParseReader
|
||||
return await reader.loadData({
|
||||
directoryPath: DATA_DIR,
|
||||
fileExtToReader: {
|
||||
pdf: new LlamaParseReader({ resultType: "markdown" }),
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
> _Note_: Reader classes have to be added explictly to the `fileExtToReader` map in the Edge version of the `SimpleDirectoryReader`.
|
||||
|
||||
You'll find a complete example with LlamaIndexTS here: https://github.com/run-llama/create_llama_projects/tree/main/nextjs-edge-llamaparse
|
||||
|
||||
## Supported LLMs:
|
||||
|
||||
- OpenAI GPT-3.5-turbo and GPT-4
|
||||
- Anthropic Claude Instant and Claude 2
|
||||
- Llama2 Chat LLMs (70B, 13B, and 7B parameters)
|
||||
- Anthropic Claude 3 (Opus, Sonnet, and Haiku) and the legacy models (Claude 2 and Instant)
|
||||
- Groq LLMs
|
||||
- Llama2/3 Chat LLMs (70B, 13B, and 7B parameters)
|
||||
- MistralAI Chat LLMs
|
||||
- Fireworks Chat LLMs
|
||||
|
||||
## Contributing:
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
# Generated files
|
||||
.docusaurus
|
||||
.cache-loader
|
||||
lib
|
||||
|
||||
# Misc
|
||||
.DS_Store
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
# docs
|
||||
|
||||
## 0.0.9
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [46227f2]
|
||||
- llamaindex@0.3.1
|
||||
|
||||
## 0.0.8
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [5016f21]
|
||||
- llamaindex@0.3.0
|
||||
|
||||
## 0.0.7
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [6277105]
|
||||
- llamaindex@0.2.13
|
||||
|
||||
## 0.0.6
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [d8d952d]
|
||||
- llamaindex@0.2.12
|
||||
|
||||
## 0.0.5
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [87142b2]
|
||||
- Updated dependencies [5a6cc0e]
|
||||
- Updated dependencies [87142b2]
|
||||
- llamaindex@0.2.11
|
||||
|
||||
## 0.0.4
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [5116ad8]
|
||||
- @llamaindex/env@0.0.5
|
||||
|
||||
## 0.0.3
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 09bf27a: Add Groq LLM to LlamaIndex
|
||||
- Updated dependencies [cf87f84]
|
||||
- @llamaindex/env@0.0.4
|
||||
|
||||
## 0.0.2
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 0f64084: docs: update API references
|
||||
|
||||
## 0.0.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 3154f52: chore: add qdrant readme
|
||||
@@ -0,0 +1,500 @@
|
||||
---
|
||||
title: LlamaIndexTS v0.3.0
|
||||
description: This is my first post on Docusaurus.
|
||||
slug: welcome-llamaindexts-v0.3
|
||||
authors:
|
||||
- name: Alex Yang
|
||||
title: LlamaIndexTS maintainer, Node.js Member
|
||||
url: https://github.com/himself65
|
||||
image_url: https://github.com/himself65.png
|
||||
tags: [llamaindex, agent]
|
||||
hide_table_of_contents: false
|
||||
---
|
||||
|
||||
- [What's new in LlamaIndexTS v0.3.0](#whats-new-in-llamaindexts-v030)
|
||||
- [Improvement in LlamaIndexTS v0.3.0](#improvement-in-llamaindexts-v030)
|
||||
- [What's the next?](#whats-the-next)
|
||||
|
||||
## What's new in LlamaIndexTS v0.3.0
|
||||
|
||||
## Agents
|
||||
|
||||
In this release, we've not only ported the Agent module from the LlamaIndex Python version but have significantly
|
||||
enhanced it to be more powerful and user-friendly for JavaScript/TypeScript applications.
|
||||
|
||||
Starting from v0.3.0, we are introducing multiple agents specifically designed for RAG applications, including:
|
||||
|
||||
- `OpenAIAgent`
|
||||
- `AnthropicAgent`
|
||||
- `ReActAgent`:
|
||||
|
||||
```ts
|
||||
import { OpenAIAgent } from "llamaindex";
|
||||
import { tools } from "./tools";
|
||||
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [...tools],
|
||||
});
|
||||
const { response } = await agent.chat({
|
||||
message: "What is weather today?",
|
||||
stream: false,
|
||||
});
|
||||
|
||||
console.log(response.message.content);
|
||||
```
|
||||
|
||||
We are also introducing the abstract AgentRunner class, which allows you to create your own agent by simply implementing
|
||||
the task handler.
|
||||
|
||||
```ts
|
||||
import { AgentRunner, OpenAI } from "llamaindex";
|
||||
|
||||
class MyLLM extends OpenAI {}
|
||||
|
||||
export class MyAgentWorker extends AgentWorker<MyLLM> {
|
||||
taskHandler = MyAgent.taskHandler;
|
||||
}
|
||||
|
||||
export class MyAgent extends AgentRunner<MyLLM> {
|
||||
constructor(params: Params) {
|
||||
super({
|
||||
llm: params.llm,
|
||||
chatHistory: params.chatHistory ?? [],
|
||||
systemPrompt: params.systemPrompt ?? null,
|
||||
runner: new MyAgentWorker(),
|
||||
tools:
|
||||
"tools" in params
|
||||
? params.tools
|
||||
: params.toolRetriever.retrieve.bind(params.toolRetriever),
|
||||
});
|
||||
}
|
||||
|
||||
// create store is a function to create a store for each task, by default it only includes `messages` and `toolOutputs`
|
||||
createStore = AgentRunner.defaultCreateStore;
|
||||
|
||||
static taskHandler: TaskHandler<Anthropic> = async (step) => {
|
||||
const { input } = step;
|
||||
const { llm, stream } = step.context;
|
||||
if (input) {
|
||||
step.context.store.messages = [...step.context.store.messages, input];
|
||||
}
|
||||
// initialize the input
|
||||
const response = await llm.chat({
|
||||
stream,
|
||||
messages: step.context.store.messages,
|
||||
});
|
||||
// store the response for next task step
|
||||
step.context.store.messages = [
|
||||
...step.context.store.messages,
|
||||
response.message,
|
||||
];
|
||||
// your logic here to decide whether to continue the task
|
||||
const shouldContinue = Math.random(); /* <-- replace with your logic here */
|
||||
if (shouldContinue) {
|
||||
// if you want to continue the task, you can insert your new context for the next task step
|
||||
step.context.store.messages = [
|
||||
...step.context.store.messages,
|
||||
{
|
||||
content: "INSERT MY NEW DATA",
|
||||
role: "user",
|
||||
},
|
||||
];
|
||||
return {
|
||||
taskStep: step,
|
||||
output: response,
|
||||
isLast: false,
|
||||
};
|
||||
} else {
|
||||
// if you want to end the task, you can return the response with `isLast: true`
|
||||
return {
|
||||
taskStep: step,
|
||||
output: response,
|
||||
isLast: true,
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
### Web Stream API for Streaming response
|
||||
|
||||
Web Stream is a web standard utilized in many modern web frameworks and libraries (like React 19, Deno, Node 22). We
|
||||
have migrated streaming responses to Web Stream to ensure broader compatibility.
|
||||
|
||||
For instance, you can use the streaming response in a simple HTTP Server:
|
||||
|
||||
```ts
|
||||
import { createServer } from "http";
|
||||
import { OpenAIAgent } from "llamaindex";
|
||||
import { OpenAIStream, streamToResponse } from "ai";
|
||||
import { tools } from "./tools";
|
||||
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [...tools],
|
||||
});
|
||||
|
||||
const server = createServer(async (req, res) => {
|
||||
const response = await agent.chat({
|
||||
message: "What is weather today?",
|
||||
stream: true,
|
||||
});
|
||||
|
||||
// Transform the response into a string readable stream
|
||||
const stream: ReadableStream<string> = response.pipeThrough(
|
||||
new TransformStream({
|
||||
transform: (chunk, controller) => {
|
||||
controller.enqueue(chunk.response.delta);
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
// Pipe the stream to the response
|
||||
streamToResponse(stream, res);
|
||||
});
|
||||
|
||||
server.listen(3000);
|
||||
```
|
||||
|
||||
Or it can be integrated into React Server Components (RSC) in Next.js:
|
||||
|
||||
```tsx
|
||||
// app/actions/index.tsx
|
||||
"use server";
|
||||
import { createStreamableUI } from "ai/rsc";
|
||||
import { OpenAIAgent } from "llamaindex";
|
||||
import type { ChatMessage } from "llamaindex/llm/types";
|
||||
|
||||
export async function chatWithAgent(
|
||||
question: string,
|
||||
prevMessages: ChatMessage[] = [],
|
||||
) {
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [],
|
||||
});
|
||||
const responseStream = await agent.chat({
|
||||
stream: true,
|
||||
message: question,
|
||||
chatHistory: prevMessages,
|
||||
});
|
||||
const uiStream = createStreamableUI(<div>loading...</div>);
|
||||
responseStream
|
||||
.pipeTo(
|
||||
new WritableStream({
|
||||
start: () => {
|
||||
uiStream.update("response:");
|
||||
},
|
||||
write: async (message) => {
|
||||
uiStream.append(message.response.delta);
|
||||
},
|
||||
}),
|
||||
)
|
||||
.catch(uiStream.error);
|
||||
return uiStream.value;
|
||||
}
|
||||
```
|
||||
|
||||
```tsx
|
||||
// app/src/page.tsx
|
||||
"use client";
|
||||
import { chatWithAgent } from "@/actions";
|
||||
import type { JSX } from "react";
|
||||
import { useFormState } from "react-dom";
|
||||
|
||||
export const runtime = "edge";
|
||||
|
||||
export default function Home() {
|
||||
const [state, action] = useFormState<JSX.Element | null>(async () => {
|
||||
return chatWithAgent("hello!", []);
|
||||
}, null);
|
||||
return (
|
||||
<main>
|
||||
{state}
|
||||
<form action={action}>
|
||||
<button>Chat</button>
|
||||
</form>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Improvement in LlamaIndexTS v0.3.0
|
||||
|
||||
### Better TypeScript support
|
||||
|
||||
We have made significant improvements to the type system to ensure that all code is thoroughly checked before it is
|
||||
published. This ongoing enhancement has already resulted in better module reliability and developer experience.
|
||||
|
||||
For example, we have improved `FunctionTool` type with generic support:
|
||||
|
||||
```ts
|
||||
type Input = {
|
||||
a: number;
|
||||
b: number;
|
||||
};
|
||||
|
||||
const sumNumbers = FunctionTool.from<Input>(
|
||||
({ a, b }) => `${a + b}`, // a and b will be checked as number
|
||||
// JSON schema will be an error if you type wrong.
|
||||
{
|
||||
name: "sumNumbers",
|
||||
description: "Use this function to sum two numbers",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The first number",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The second number",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
},
|
||||
},
|
||||
);
|
||||
```
|
||||
|
||||

|
||||
|
||||
### Better Next.js, Deno, Cloudflare Worker, and Waku(Vite) support
|
||||
|
||||
In addition to Node.js, LlamaIndexTS now offers enhanced support for Next.js, Deno, and Cloudflare Workers, making it
|
||||
more versatile across different platforms.
|
||||
|
||||
#### [Deno](https://deno.com/)
|
||||
|
||||
You can use LlamaIndexTS in Deno by installation through JSR:
|
||||
|
||||
```sh
|
||||
jsr add @llamaindex/core
|
||||
```
|
||||
|
||||
#### [Cloudflare Worker](https://developers.cloudflare.com/workers/)
|
||||
|
||||
For Cloudflare Workers, here is a starter template:
|
||||
|
||||
```typescript
|
||||
export default {
|
||||
async fetch(
|
||||
request: Request,
|
||||
env: Env,
|
||||
ctx: ExecutionContext,
|
||||
): Promise<Response> {
|
||||
const { setEnvs } = await import("@llamaindex/env");
|
||||
setEnvs(env);
|
||||
const { OpenAIAgent } = await import("llamaindex");
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [],
|
||||
});
|
||||
const responseStream = await agent.chat({
|
||||
stream: true,
|
||||
message: "Hello? What is the weather today?",
|
||||
});
|
||||
const textEncoder = new TextEncoder();
|
||||
const response = responseStream.pipeThrough(
|
||||
new TransformStream({
|
||||
transform: (chunk, controller) => {
|
||||
controller.enqueue(textEncoder.encode(chunk.response.delta));
|
||||
},
|
||||
}),
|
||||
);
|
||||
return new Response(response);
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
### [Waku (Vite)](https://waku.gg/)
|
||||
|
||||
Waku powered by Vite is a minimal React framework that supports multiple JS environments, including Deno, Cloudflare, and
|
||||
Node.js.
|
||||
|
||||
You can use LlamaIndexTS with Node.js output to enable full Node.js support with React.
|
||||
|
||||
```sh
|
||||
npm install llamaindex
|
||||
```
|
||||
|
||||
```ts
|
||||
// file: src/actions.ts
|
||||
"use server";
|
||||
import { Document, VectorStoreIndex } from "llamaindex";
|
||||
import { readFile } from "node:fs/promises";
|
||||
|
||||
const path = "node_modules/llamaindex/examples/abramov.txt";
|
||||
|
||||
const essay = await readFile(path, "utf-8");
|
||||
|
||||
// Create Document object with essay
|
||||
const document = new Document({ text: essay, id_: path });
|
||||
|
||||
// Split text and create embeddings. Store them in a VectorStoreIndex
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
export async function chatWithAI(question: string): Promise<string> {
|
||||
const { response } = await queryEngine.query({ query: question });
|
||||
return response;
|
||||
}
|
||||
```
|
||||
|
||||
```tsx
|
||||
// file: src/pages/index.tsx
|
||||
import { chatWithAI } from "./actions";
|
||||
|
||||
export default async function HomePage() {
|
||||
return (
|
||||
<div>
|
||||
<Chat askQuestion={chatWithAI} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
```tsx
|
||||
// file: src/components/Chat.tsx
|
||||
"use client";
|
||||
|
||||
export type ChatProps = {
|
||||
askQuestion: (question: string) => Promise<string>;
|
||||
};
|
||||
|
||||
export const Chat = (props: ChatProps) => {
|
||||
const [response, setResponse] = useState<string | null>(null);
|
||||
|
||||
return (
|
||||
<section className="border-blue-400 -mx-4 mt-4 rounded border border-dashed p-4">
|
||||
<h2 className="text-lg font-bold">Chat with AI</h2>
|
||||
{response ? (
|
||||
<p className="text-sm text-gray-600 max-w-sm">{response}</p>
|
||||
) : null}
|
||||
<form
|
||||
action={async (formData) => {
|
||||
const question = formData.get("question") as string | null;
|
||||
if (question) {
|
||||
setResponse(await props.askQuestion(question));
|
||||
}
|
||||
}}
|
||||
>
|
||||
<input
|
||||
type="text"
|
||||
name="question"
|
||||
className="border border-gray-400 rounded-sm px-2 py-0.5 text-sm"
|
||||
/>
|
||||
<button className="rounded-sm bg-black px-2 py-0.5 text-sm text-white">
|
||||
Ask
|
||||
</button>
|
||||
</form>
|
||||
</section>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
```shell
|
||||
waku dev # development mode
|
||||
waku build # build for production
|
||||
waku start # start the production server
|
||||
```
|
||||
|
||||
Note that not all the modules are supported in all JS environments because of
|
||||
lack of the file system, network API,
|
||||
and incompatibility with the Node.js API by upstream dependencies.
|
||||
|
||||
But we are trying to make it more compatible with all the environments.
|
||||
|
||||
## What's the next?
|
||||
|
||||
As we continue to develop LlamaIndexTS, our focus remains on providing more comprehensive and powerful tools for
|
||||
creating custom agents.
|
||||
|
||||
### Align with the Python `llama-index`
|
||||
|
||||
We aim to align LlamaIndexTS with the Python version to ensure API consistency and ease of use for developers familiar
|
||||
with the Python ecosystem.
|
||||
|
||||
### Align with the Web Standard and JS development
|
||||
|
||||
Not all python APIs are compatible and easy to use in JavaScript/TypeScript.
|
||||
We are trying to make the API more compatible with the Web Standard and JavaScript modern development.
|
||||
|
||||
### More Agents
|
||||
|
||||
Future releases will introduce more agents from the Python Llama-Index and explore APIs tailored to real-world use
|
||||
cases.
|
||||
|
||||
### 🧪 `@llamaindex/tool`
|
||||
|
||||
We are exploring innovative ways to create tools for agents. The `@llamaindex/tool` library allows you to transform any
|
||||
function into a tool for an agent, simplifying the development process and reducing runtime costs.
|
||||
|
||||
```ts
|
||||
export function getWeather(city: string) {
|
||||
return `The weather in ${city} is sunny.`;
|
||||
}
|
||||
|
||||
// you don't need to worry about the shcema with different llm tools
|
||||
export function getTemperature(city: string) {
|
||||
return `The temperature in ${city} is 25°C.`;
|
||||
}
|
||||
|
||||
export function getCurrentCity() {
|
||||
return "New York";
|
||||
}
|
||||
```
|
||||
|
||||
These functions can be easily integrated into your applications, such as Next.js:
|
||||
|
||||
```ts
|
||||
"use server";
|
||||
import { OpenAI } from "openai";
|
||||
import { getTools } from "@llamaindex/tool";
|
||||
|
||||
export async function chat(message: string) {
|
||||
const openai = new OpenAI();
|
||||
openai.chat.completions.create({
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: "What is the weather in the current city?",
|
||||
},
|
||||
],
|
||||
tools: getTools("openai"),
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
```ts
|
||||
// next.config.js
|
||||
const withTool = require("@llamaindex/tool/next");
|
||||
|
||||
const config = {
|
||||
// Your original Next.js config
|
||||
};
|
||||
module.exports = withTool(config);
|
||||
```
|
||||
|
||||
The functions are automatically transformed into tools for the agent at compile time, which eliminates any extra runtime
|
||||
costs. This feature is particularly beneficial when you need to debug or deploy your assistant.
|
||||
|
||||
For deploying your local functions into OpenAI, you can use a simple command:
|
||||
|
||||
```sh
|
||||
npm install -g @llamaindex/tool
|
||||
mkai --tools ./src/index.llama.ts
|
||||
# Successfully created assistant: asst_XXX
|
||||
# chat with your assistant by `chatai --assistant asst_XXX`
|
||||
chatai --assistant asst_XXX
|
||||
# Open your browser and chat with your assistant
|
||||
# Running at http://localhost:3000
|
||||
```
|
||||
|
||||
This deployment process simplifies the testing and implementation of your custom tools in a live environment.
|
||||
|
||||
As this project is still in its early stages, we continue to explore the best ways to create and integrate tools for
|
||||
agents. For more information and updates, visit the @llamaindex/tool repository.
|
||||
|
||||
This release of LlamaIndexTS v0.3.0 marks a significant step forward in our journey to provide developers with robust,
|
||||
flexible tools for building advanced agents. We are excited to see how our community utilizes these new capabilities to
|
||||
create innovative solutions and look forward to continuing to support and enhance LlamaIndexTS in future updates.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 178 KiB |
@@ -1,45 +0,0 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
# End to End Examples
|
||||
|
||||
We include several end-to-end examples using LlamaIndex.TS in the repository
|
||||
|
||||
Check out the examples below or try them out and complete them in minutes with interactive Github Codespace tutorials provided by Dev-Docs [here](https://codespaces.new/team-dev-docs/lits-dev-docs-playground?devcontainer_path=.devcontainer%2Fjavascript_ltsquickstart%2Fdevcontainer.json):
|
||||
|
||||
## [Chat Engine](https://github.com/run-llama/LlamaIndexTS/blob/main/apps/simple/chatEngine.ts)
|
||||
|
||||
Read a file and chat about it with the LLM.
|
||||
|
||||
## [Vector Index](https://github.com/run-llama/LlamaIndexTS/blob/main/apps/simple/vectorIndex.ts)
|
||||
|
||||
Create a vector index and query it. The vector index will use embeddings to fetch the top k most relevant nodes. By default, the top k is 2.
|
||||
|
||||
## [Summary Index](https://github.com/run-llama/LlamaIndexTS/blob/main/apps/simple/summaryIndex.ts)
|
||||
|
||||
Create a list index and query it. This example also use the `LLMRetriever`, which will use the LLM to select the best nodes to use when generating answer.
|
||||
|
||||
## [Save / Load an Index](https://github.com/run-llama/LlamaIndexTS/blob/main/apps/simple/storageContext.ts)
|
||||
|
||||
Create and load a vector index. Persistance to disk in LlamaIndex.TS happens automatically once a storage context object is created.
|
||||
|
||||
## [Customized Vector Index](https://github.com/run-llama/LlamaIndexTS/blob/main/apps/simple/vectorIndexCustomize.ts)
|
||||
|
||||
Create a vector index and query it, while also configuring the the `LLM`, the `ServiceContext`, and the `similarity_top_k`.
|
||||
|
||||
## [OpenAI LLM](https://github.com/run-llama/LlamaIndexTS/blob/main/apps/simple/openai.ts)
|
||||
|
||||
Create an OpenAI LLM and directly use it for chat.
|
||||
|
||||
## [Llama2 DeuceLLM](https://github.com/run-llama/LlamaIndexTS/blob/main/apps/simple/llamadeuce.ts)
|
||||
|
||||
Create a Llama-2 LLM and directly use it for chat.
|
||||
|
||||
## [SubQuestionQueryEngine](https://github.com/run-llama/LlamaIndexTS/blob/main/apps/simple/subquestion.ts)
|
||||
|
||||
Uses the `SubQuestionQueryEngine`, which breaks complex queries into multiple questions, and then aggreates a response across the answers to all sub-questions.
|
||||
|
||||
## [Low Level Modules](https://github.com/run-llama/LlamaIndexTS/blob/main/apps/simple/lowlevel.ts)
|
||||
|
||||
This example uses several low-level components, which removes the need for an actual query engine. These components can be used anywhere, in any application, or customized and sub-classed to meet your own needs.
|
||||
@@ -1,29 +0,0 @@
|
||||
---
|
||||
sidebar_position: 5
|
||||
---
|
||||
|
||||
# Environments
|
||||
|
||||
LlamaIndex currently officially supports NodeJS 18 and NodeJS 20.
|
||||
|
||||
## NextJS App Router
|
||||
|
||||
If you're using NextJS App Router route handlers/serverless functions, you'll need to use the NodeJS mode:
|
||||
|
||||
```js
|
||||
export const runtime = "nodejs"; // default
|
||||
```
|
||||
|
||||
and you'll need to add an exception for pdf-parse in your next.config.js
|
||||
|
||||
```js
|
||||
// next.config.js
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
experimental: {
|
||||
serverComponentsExternalPackages: ["pdf-parse"], // Puts pdf-parse in actual NodeJS mode with NextJS App Router
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = nextConfig;
|
||||
```
|
||||
@@ -0,0 +1,2 @@
|
||||
label: Examples
|
||||
position: 2
|
||||
@@ -0,0 +1,10 @@
|
||||
# Agents
|
||||
|
||||
A built-in agent that can take decisions and reasoning based on the tools provided to it.
|
||||
|
||||
## OpenAI Agent
|
||||
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../examples/agent/openai";
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
@@ -0,0 +1,12 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../examples/chatEngine";
|
||||
|
||||
# Chat Engine
|
||||
|
||||
Chat Engine is a class that allows you to create a chatbot from a retriever. It is a wrapper around a retriever that allows you to chat with it in a conversational manner.
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
sidebar_position: 5
|
||||
---
|
||||
|
||||
# More examples
|
||||
|
||||
You can check out more examples in the [examples](https://github.com/run-llama/LlamaIndexTS/tree/main/examples) folder of the repository.
|
||||
@@ -0,0 +1,10 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../examples/storageContext";
|
||||
|
||||
# Save/Load an Index
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
@@ -0,0 +1,10 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../examples/summaryIndex";
|
||||
|
||||
# Summary Index
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
@@ -0,0 +1,10 @@
|
||||
---
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../examples/vectorIndex";
|
||||
|
||||
# Vector Index
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
@@ -0,0 +1,2 @@
|
||||
label: Getting Started
|
||||
position: 1
|
||||
@@ -2,7 +2,7 @@
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
# High-Level Concepts
|
||||
# Concepts
|
||||
|
||||
LlamaIndex.TS helps you build LLM-powered applications (e.g. Q&A, chatbot) over custom data.
|
||||
|
||||
@@ -18,7 +18,7 @@ LlamaIndex uses a two stage method when using an LLM with your data:
|
||||
1. **indexing stage**: preparing a knowledge base, and
|
||||
2. **querying stage**: retrieving relevant context from the knowledge to assist the LLM in responding to a question
|
||||
|
||||

|
||||

|
||||
|
||||
This process is also known as Retrieval Augmented Generation (RAG).
|
||||
|
||||
@@ -30,14 +30,14 @@ Let's explore each stage in detail.
|
||||
|
||||
LlamaIndex.TS help you prepare the knowledge base with a suite of data connectors and indexes.
|
||||
|
||||

|
||||

|
||||
|
||||
[**Data Loaders**](./modules/high_level/data_loader.md):
|
||||
[**Data Loaders**](../modules/data_loader.md):
|
||||
A data connector (i.e. `Reader`) ingest data from different data sources and data formats into a simple `Document` representation (text and simple metadata).
|
||||
|
||||
[**Documents / Nodes**](./modules/high_level/documents_and_nodes.md): A `Document` is a generic container around any data source - for instance, a PDF, an API output, or retrieved data from a database. A `Node` is the atomic unit of data in LlamaIndex and represents a "chunk" of a source `Document`. It's a rich representation that includes metadata and relationships (to other nodes) to enable accurate and expressive retrieval operations.
|
||||
[**Documents / Nodes**](../modules/documents_and_nodes/index.md): A `Document` is a generic container around any data source - for instance, a PDF, an API output, or retrieved data from a database. A `Node` is the atomic unit of data in LlamaIndex and represents a "chunk" of a source `Document`. It's a rich representation that includes metadata and relationships (to other nodes) to enable accurate and expressive retrieval operations.
|
||||
|
||||
[**Data Indexes**](./modules/high_level/data_index.md):
|
||||
[**Data Indexes**](../modules/data_index.md):
|
||||
Once you've ingested your data, LlamaIndex helps you index data into a format that's easy to retrieve.
|
||||
|
||||
Under the hood, LlamaIndex parses the raw documents into intermediate representations, calculates vector embeddings, and stores your data in-memory or to disk.
|
||||
@@ -56,23 +56,23 @@ LlamaIndex provides composable modules that help you build and integrate RAG pip
|
||||
|
||||
These building blocks can be customized to reflect ranking preferences, as well as composed to reason over multiple knowledge bases in a structured way.
|
||||
|
||||

|
||||

|
||||
|
||||
#### Building Blocks
|
||||
|
||||
[**Retrievers**](./modules/low_level/retriever.md):
|
||||
[**Retrievers**](../modules/retriever.md):
|
||||
A retriever defines how to efficiently retrieve relevant context from a knowledge base (i.e. index) when given a query.
|
||||
The specific retrieval logic differs for difference indices, the most popular being dense retrieval against a vector index.
|
||||
|
||||
[**Response Synthesizers**](./modules/low_level/response_synthesizer.md):
|
||||
[**Response Synthesizers**](../modules/response_synthesizer.md):
|
||||
A response synthesizer generates a response from an LLM, using a user query and a given set of retrieved text chunks.
|
||||
|
||||
#### Pipelines
|
||||
|
||||
[**Query Engines**](./modules/high_level/query_engine.md):
|
||||
[**Query Engines**](../modules/query_engines):
|
||||
A query engine is an end-to-end pipeline that allow you to ask question over your data.
|
||||
It takes in a natural language query, and returns a response, along with reference context retrieved and passed to the LLM.
|
||||
|
||||
[**Chat Engines**](./modules/high_level/chat_engine.md):
|
||||
[**Chat Engines**](../modules/chat_engine.md):
|
||||
A chat engine is an end-to-end pipeline for having a conversation with your data
|
||||
(multiple back-and-forth instead of a single question & answer).
|
||||
@@ -0,0 +1,15 @@
|
||||
---
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
# Environments
|
||||
|
||||
LlamaIndex currently officially supports NodeJS 18 and NodeJS 20.
|
||||
|
||||
## NextJS App Router
|
||||
|
||||
If you're using NextJS App Router route handlers/serverless functions, you'll need to use the NodeJS mode:
|
||||
|
||||
```js
|
||||
export const runtime = "nodejs"; // default
|
||||
```
|
||||
@@ -0,0 +1,63 @@
|
||||
---
|
||||
sidebar_position: 0
|
||||
---
|
||||
|
||||
# Installation and Setup
|
||||
|
||||
Make sure you have NodeJS v18 or higher.
|
||||
|
||||
## Using create-llama
|
||||
|
||||
The easiest way to get started with LlamaIndex is by using `create-llama`. This CLI tool enables you to quickly start building a new LlamaIndex application, with everything set up for you.
|
||||
|
||||
Just run
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="1" label="npm" default>
|
||||
|
||||
```bash
|
||||
npx create-llama@latest
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="2" label="Yarn">
|
||||
|
||||
```bash
|
||||
yarn create llama
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="3" label="pnpm">
|
||||
|
||||
```bash
|
||||
pnpm create llama@latest
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
to get started. Once your app is generated, run
|
||||
|
||||
```bash npm2yarn
|
||||
npm run dev
|
||||
```
|
||||
|
||||
to start the development server. You can then visit [http://localhost:3000](http://localhost:3000) to see your app
|
||||
|
||||
## Installation from NPM
|
||||
|
||||
```bash npm2yarn
|
||||
npm install llamaindex
|
||||
```
|
||||
|
||||
### Environment variables
|
||||
|
||||
Our examples use OpenAI by default. You'll need to set up your Open AI key like so:
|
||||
|
||||
```bash
|
||||
export OPENAI_API_KEY="sk-......" # Replace with your key from https://platform.openai.com/account/api-keys
|
||||
```
|
||||
|
||||
If you want to have it automatically loaded every time, add it to your `.zshrc/.bashrc`.
|
||||
|
||||
WARNING: do not check in your OpenAI key into version control.
|
||||
@@ -0,0 +1,51 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../examples/vectorIndex";
|
||||
import TSConfigSource from "!!raw-loader!../../../../examples/tsconfig.json";
|
||||
|
||||
# Starter Tutorial
|
||||
|
||||
Make sure you have installed LlamaIndex.TS and have an OpenAI key. If you haven't, check out the [installation](installation) guide.
|
||||
|
||||
## From scratch(node.js + TypeScript):
|
||||
|
||||
In a new folder:
|
||||
|
||||
```bash npm2yarn
|
||||
npm init
|
||||
npm install -D typescript @types/node
|
||||
```
|
||||
|
||||
Create the file `example.ts`. This code will load some example data, create a document, index it (which creates embeddings using OpenAI), and then creates query engine to answer questions about the data.
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
|
||||
Create a `tsconfig.json` file in the same folder:
|
||||
|
||||
<CodeBlock language="json">{TSConfigSource}</CodeBlock>
|
||||
|
||||
Now you can run the code with
|
||||
|
||||
```bash
|
||||
npx tsx example.ts
|
||||
```
|
||||
|
||||
Also, you can clone our examples and try them out:
|
||||
|
||||
```bash npm2yarn
|
||||
npx degit run-llama/LlamaIndexTS/examples my-new-project
|
||||
cd my-new-project
|
||||
npm install
|
||||
npx tsx ./vectorIndex.ts
|
||||
```
|
||||
|
||||
## From scratch (Next.js + TypeScript):
|
||||
|
||||
You just need one command to create a new Next.js project:
|
||||
|
||||
```bash npm2yarn
|
||||
npx create-llama@latest
|
||||
```
|
||||
@@ -1,25 +0,0 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# Installation and Setup
|
||||
|
||||
## Installation from NPM
|
||||
|
||||
Make sure you have NodeJS v18 or higher.
|
||||
|
||||
```bash npm2yarn
|
||||
npm install llamaindex
|
||||
```
|
||||
|
||||
## Environment variables
|
||||
|
||||
Our examples use OpenAI by default. You'll need to set up your Open AI key like so:
|
||||
|
||||
```bash
|
||||
export OPENAI_API_KEY="sk-......" # Replace with your key from https://platform.openai.com/account/api-keys
|
||||
```
|
||||
|
||||
If you want to have it automatically loaded every time, add it to your .zshrc/.bashrc.
|
||||
|
||||
WARNING: do not check in your OpenAI key into version control.
|
||||
@@ -5,7 +5,7 @@ slug: /
|
||||
|
||||
# What is LlamaIndex.TS?
|
||||
|
||||
LlamaIndex.TS is a data framework for LLM applications to ingest, structure, and access private or domain-specific data. While a python package is also available (see [here](https://gpt-index.readthedocs.io/en/latest/)), LlamaIndex.TS offers core features in a simple package, optimized for usage with TypeScript.
|
||||
LlamaIndex.TS is a data framework for LLM applications to ingest, structure, and access private or domain-specific data. While a python package is also available (see [here](https://docs.llamaindex.ai/en/stable/)), LlamaIndex.TS offers core features in a simple package, optimized for usage with TypeScript.
|
||||
|
||||
## 🚀 Why LlamaIndex.TS?
|
||||
|
||||
@@ -37,9 +37,9 @@ For more complex applications, our lower-level APIs allow advanced users to cust
|
||||
|
||||
`npm install llamaindex`
|
||||
|
||||
Our documentation includes [Installation Instructions](./installation.md) and a [Starter Tutorial](./starter.md) to build your first application.
|
||||
Our documentation includes [Installation Instructions](./getting_started/installation.mdx) and a [Starter Tutorial](./getting_started/starter.mdx) to build your first application.
|
||||
|
||||
Once you're up and running, [High-Level Concepts](./concepts.md) has an overview of LlamaIndex's modular architecture. For more hands-on practical examples, look through our [End-to-End Tutorials](./end_to_end.md).
|
||||
Once you're up and running, [High-Level Concepts](./getting_started/concepts.md) has an overview of LlamaIndex's modular architecture. For more hands-on practical examples, look through our Examples section on the sidebar.
|
||||
|
||||
## 🗺️ Ecosystem
|
||||
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "Agents"
|
||||
position: 3
|
||||
@@ -0,0 +1,20 @@
|
||||
# Agents
|
||||
|
||||
An “agent” is an automated reasoning and decision engine. It takes in a user input/query and can make internal decisions for executing that query in order to return the correct result. The key agent components can include, but are not limited to:
|
||||
|
||||
- Breaking down a complex question into smaller ones
|
||||
- Choosing an external Tool to use + coming up with parameters for calling the Tool
|
||||
- Planning out a set of tasks
|
||||
- Storing previously completed tasks in a memory module
|
||||
|
||||
## Getting Started
|
||||
|
||||
LlamaIndex.TS comes with a few built-in agents, but you can also create your own. The built-in agents include:
|
||||
|
||||
- OpenAI Agent
|
||||
- Anthropic Agent
|
||||
- ReACT Agent
|
||||
|
||||
## Examples
|
||||
|
||||
- [OpenAI Agent](../../examples/agent.mdx)
|
||||
@@ -0,0 +1,29 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
# ChatEngine
|
||||
|
||||
The chat engine is a quick and simple way to chat with the data in your index.
|
||||
|
||||
```typescript
|
||||
const retriever = index.asRetriever();
|
||||
const chatEngine = new ContextChatEngine({ retriever });
|
||||
|
||||
// start chatting
|
||||
const response = await chatEngine.chat({ message: query });
|
||||
```
|
||||
|
||||
The `chat` function also supports streaming, just add `stream: true` as an option:
|
||||
|
||||
```typescript
|
||||
const stream = await chatEngine.chat({ message: query, stream: true });
|
||||
for await (const chunk of stream) {
|
||||
process.stdout.write(chunk.response);
|
||||
}
|
||||
```
|
||||
|
||||
## Api References
|
||||
|
||||
- [ContextChatEngine](../api/classes/ContextChatEngine.md)
|
||||
- [CondenseQuestionChatEngine](../api/classes/ContextChatEngine.md)
|
||||
+3
-3
@@ -1,5 +1,5 @@
|
||||
---
|
||||
sidebar_position: 2
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
# Index
|
||||
@@ -19,5 +19,5 @@ const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
## API Reference
|
||||
|
||||
- [SummaryIndex](../../api/classes/SummaryIndex.md)
|
||||
- [VectorStoreIndex](../../api/classes/VectorStoreIndex.md)
|
||||
- [SummaryIndex](../api/classes/SummaryIndex.md)
|
||||
- [VectorStoreIndex](../api/classes/VectorStoreIndex.md)
|
||||
@@ -0,0 +1,48 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../examples/readers/src/simple-directory-reader";
|
||||
import CodeSource2 from "!raw-loader!../../../../examples/readers/src/custom-simple-directory-reader";
|
||||
import CodeSource3 from "!raw-loader!../../../../examples/readers/src/llamaparse";
|
||||
|
||||
# Loader
|
||||
|
||||
Before you can start indexing your documents, you need to load them into memory.
|
||||
|
||||
### SimpleDirectoryReader
|
||||
|
||||
[](https://stackblitz.com/github/run-llama/LlamaIndexTS/tree/main/examples/readers?file=src/simple-directory-reader.ts&title=Simple%20Directory%20Reader)
|
||||
|
||||
LlamaIndex.TS supports easy loading of files from folders using the `SimpleDirectoryReader` class.
|
||||
|
||||
It is a simple reader that reads all files from a directory and its subdirectories.
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
|
||||
Currently, it supports reading `.csv`, `.docx`, `.html`, `.md` and `.pdf` files,
|
||||
but support for other file types is planned.
|
||||
|
||||
Also, you can provide a `defaultReader` as a fallback for files with unsupported extensions.
|
||||
Or pass new readers for `fileExtToReader` to support more file types.
|
||||
|
||||
<CodeBlock language="ts" showLineNumbers metastring="{8-12,17-21}">
|
||||
{CodeSource2}
|
||||
</CodeBlock>
|
||||
|
||||
### LlamaParse
|
||||
|
||||
LlamaParse is an API created by LlamaIndex to efficiently parse files, e.g. it's great at converting PDF tables into markdown.
|
||||
|
||||
To use it, first login and get an API key from https://cloud.llamaindex.ai. Make sure to store the key in the environment variable `LLAMA_CLOUD_API_KEY`.
|
||||
|
||||
Then, you can use the `LlamaParseReader` class to read a local PDF file and convert it into a markdown document that can be used by LlamaIndex:
|
||||
|
||||
<CodeBlock language="ts">{CodeSource3}</CodeBlock>
|
||||
|
||||
Alternatively, you can set the [`resultType`](../api/classes/LlamaParseReader.md#resulttype) option to `text` to get the parsed document as a text string.
|
||||
|
||||
## API Reference
|
||||
|
||||
- [SimpleDirectoryReader](../api/classes/SimpleDirectoryReader.md)
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "Document / Nodes"
|
||||
position: 0
|
||||
+3
-3
@@ -1,5 +1,5 @@
|
||||
---
|
||||
sidebar_position: 0
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# Documents and Nodes
|
||||
@@ -14,5 +14,5 @@ document = new Document({ text: "text", metadata: { key: "val" } });
|
||||
|
||||
## API Reference
|
||||
|
||||
- [Document](../../api/classes/Document.md)
|
||||
- [TextNode](../../api/classes/TextNode.md)
|
||||
- [Document](../api/classes/Document.md)
|
||||
- [TextNode](../api/classes/TextNode.md)
|
||||
@@ -0,0 +1,45 @@
|
||||
# Metadata Extraction Usage Pattern
|
||||
|
||||
You can use LLMs to automate metadata extraction with our `Metadata Extractor` modules.
|
||||
|
||||
Our metadata extractor modules include the following "feature extractors":
|
||||
|
||||
- `SummaryExtractor` - automatically extracts a summary over a set of Nodes
|
||||
- `QuestionsAnsweredExtractor` - extracts a set of questions that each Node can answer
|
||||
- `TitleExtractor` - extracts a title over the context of each Node by document and combine them
|
||||
- `KeywordExtractor` - extracts keywords over the context of each Node
|
||||
|
||||
Then you can chain the `Metadata Extractors` with the `IngestionPipeline` to extract metadata from a set of documents.
|
||||
|
||||
```ts
|
||||
import {
|
||||
IngestionPipeline,
|
||||
TitleExtractor,
|
||||
QuestionsAnsweredExtractor,
|
||||
Document,
|
||||
OpenAI,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
const pipeline = new IngestionPipeline({
|
||||
transformations: [
|
||||
new TitleExtractor(),
|
||||
new QuestionsAnsweredExtractor({
|
||||
questions: 5,
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const nodes = await pipeline.run({
|
||||
documents: [
|
||||
new Document({ text: "I am 10 years old. John is 20 years old." }),
|
||||
],
|
||||
});
|
||||
|
||||
for (const node of nodes) {
|
||||
console.log(node.metadata);
|
||||
}
|
||||
}
|
||||
|
||||
main().then(() => console.log("done"));
|
||||
```
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "Embeddings"
|
||||
position: 3
|
||||
@@ -0,0 +1 @@
|
||||
label: "Available Embeddings"
|
||||
@@ -0,0 +1,33 @@
|
||||
# Gemini
|
||||
|
||||
To use Gemini embeddings, you need to import `GeminiEmbedding` from `llamaindex`.
|
||||
|
||||
```ts
|
||||
import { GeminiEmbedding, Settings } from "llamaindex";
|
||||
|
||||
// Update Embed Model
|
||||
Settings.embedModel = new GeminiEmbedding();
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
Per default, `GeminiEmbedding` is using the `gemini-pro` model. You can change the model by passing the `model` parameter to the constructor.
|
||||
For example:
|
||||
|
||||
```ts
|
||||
import { GEMINI_MODEL, GeminiEmbedding } from "llamaindex";
|
||||
|
||||
Settings.embedModel = new GeminiEmbedding({
|
||||
model: GEMINI_MODEL.GEMINI_PRO_LATEST,
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,34 @@
|
||||
# HuggingFace
|
||||
|
||||
To use HuggingFace embeddings, you need to import `HuggingFaceEmbedding` from `llamaindex`.
|
||||
|
||||
```ts
|
||||
import { HuggingFaceEmbedding, Settings } from "llamaindex";
|
||||
|
||||
// Update Embed Model
|
||||
Settings.embedModel = new HuggingFaceEmbedding();
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
Per default, `HuggingFaceEmbedding` is using the `Xenova/all-MiniLM-L6-v2` model. You can change the model by passing the `modelType` parameter to the constructor.
|
||||
If you're not using a quantized model, set the `quantized` parameter to `false`.
|
||||
|
||||
For example, to use the not quantized `BAAI/bge-small-en-v1.5` model, you can use the following code:
|
||||
|
||||
```ts
|
||||
Settings.embedModel = new HuggingFaceEmbedding({
|
||||
modelType: "BAAI/bge-small-en-v1.5",
|
||||
quantized: false,
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,21 @@
|
||||
# Jina AI
|
||||
|
||||
To use Jina AI embeddings, you need to import `JinaAIEmbedding` from `llamaindex`.
|
||||
|
||||
```ts
|
||||
import { JinaAIEmbedding, Settings } from "llamaindex";
|
||||
|
||||
Settings.embedModel = new JinaAIEmbedding();
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,24 @@
|
||||
# MistralAI
|
||||
|
||||
To use MistralAI embeddings, you need to import `MistralAIEmbedding` from `llamaindex`.
|
||||
|
||||
```ts
|
||||
import { MistralAIEmbedding, Settings } from "llamaindex";
|
||||
|
||||
// Update Embed Model
|
||||
Settings.embedModel = new MistralAIEmbedding({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,29 @@
|
||||
# Ollama
|
||||
|
||||
To use Ollama embeddings, you need to import `OllamaEmbedding` from `llamaindex`.
|
||||
|
||||
Note that you need to pull the embedding model first before using it.
|
||||
|
||||
In the example below, we're using the [`nomic-embed-text`](https://ollama.com/library/nomic-embed-text) model, so you have to call:
|
||||
|
||||
```shell
|
||||
ollama pull nomic-embed-text
|
||||
```
|
||||
|
||||
```ts
|
||||
import { OllamaEmbedding, Settings } from "llamaindex";
|
||||
|
||||
Settings.embedModel = new OllamaEmbedding({ model: "nomic-embed-text" });
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,21 @@
|
||||
# OpenAI
|
||||
|
||||
To use OpenAI embeddings, you need to import `OpenAIEmbedding` from `llamaindex`.
|
||||
|
||||
```ts
|
||||
import { OpenAIEmbedding, Settings } from "llamaindex";
|
||||
|
||||
Settings.embedModel = new OpenAIEmbedding();
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,23 @@
|
||||
# Together
|
||||
|
||||
To use together embeddings, you need to import `TogetherEmbedding` from `llamaindex`.
|
||||
|
||||
```ts
|
||||
import { TogetherEmbedding, Settings } from "llamaindex";
|
||||
|
||||
Settings.embedModel = new TogetherEmbedding({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,21 @@
|
||||
# Embedding
|
||||
|
||||
The embedding model in LlamaIndex is responsible for creating numerical representations of text. By default, LlamaIndex will use the `text-embedding-ada-002` model from OpenAI.
|
||||
|
||||
This can be explicitly updated through `Settings`
|
||||
|
||||
```typescript
|
||||
import { OpenAIEmbedding, Settings } from "llamaindex";
|
||||
|
||||
Settings.embedModel = new OpenAIEmbedding({
|
||||
model: "text-embedding-ada-002",
|
||||
});
|
||||
```
|
||||
|
||||
## Local Embedding
|
||||
|
||||
For local embeddings, you can use the [HuggingFace](./available_embeddings/huggingface.md) embedding model.
|
||||
|
||||
## API Reference
|
||||
|
||||
- [OpenAIEmbedding](../../api/classes/OpenAIEmbedding.md)
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "Evaluating"
|
||||
position: 3
|
||||
@@ -0,0 +1,32 @@
|
||||
# Evaluating
|
||||
|
||||
## Concept
|
||||
|
||||
Evaluation and benchmarking are crucial concepts in LLM development. To improve the perfomance of an LLM app (RAG, agents) you must have a way to measure it.
|
||||
|
||||
LlamaIndex offers key modules to measure the quality of generated results. We also offer key modules to measure retrieval quality.
|
||||
|
||||
- **Response Evaluation**: Does the response match the retrieved context? Does it also match the query? Does it match the reference answer or guidelines?
|
||||
- **Retrieval Evaluation**: Are the retrieved sources relevant to the query?
|
||||
|
||||
## Response Evaluation
|
||||
|
||||
Evaluation of generated results can be difficult, since unlike traditional machine learning the predicted result is not a single number, and it can be hard to define quantitative metrics for this problem.
|
||||
|
||||
LlamaIndex offers LLM-based evaluation modules to measure the quality of results. This uses a “gold” LLM (e.g. GPT-4) to decide whether the predicted answer is correct in a variety of ways.
|
||||
|
||||
Note that many of these current evaluation modules do not require ground-truth labels. Evaluation can be done with some combination of the query, context, response, and combine these with LLM calls.
|
||||
|
||||
These evaluation modules are in the following forms:
|
||||
|
||||
- **Correctness**: Whether the generated answer matches that of the reference answer given the query (requires labels).
|
||||
|
||||
- **Faithfulness**: Evaluates if the answer is faithful to the retrieved contexts (in other words, whether if there’s hallucination).
|
||||
|
||||
- **Relevancy**: Evaluates if the response from a query engine matches any source nodes.
|
||||
|
||||
## Usage
|
||||
|
||||
- [Correctness Evaluator](./modules/correctness.md)
|
||||
- [Faithfulness Evaluator](./modules/faithfulness.md)
|
||||
- [Relevancy Evaluator](./modules/relevancy.md)
|
||||
@@ -0,0 +1 @@
|
||||
label: "Modules"
|
||||
@@ -0,0 +1,58 @@
|
||||
# Correctness Evaluator
|
||||
|
||||
Correctness evaluates the relevance and correctness of a generated answer against a reference answer.
|
||||
|
||||
This is useful for measuring if the response was correct. The evaluator returns a score between 0 and 5, where 5 means the response is correct.
|
||||
|
||||
## Usage
|
||||
|
||||
Firstly, you need to install the package:
|
||||
|
||||
```bash
|
||||
pnpm i llamaindex
|
||||
```
|
||||
|
||||
Set the OpenAI API key:
|
||||
|
||||
```bash
|
||||
export OPENAI_API_KEY=your-api-key
|
||||
```
|
||||
|
||||
Import the required modules:
|
||||
|
||||
```ts
|
||||
import { CorrectnessEvaluator, OpenAI, Settings } from "llamaindex";
|
||||
```
|
||||
|
||||
Let's setup gpt-4 for better results:
|
||||
|
||||
```ts
|
||||
Settings.llm = new OpenAI({
|
||||
model: "gpt-4",
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
const query =
|
||||
"Can you explain the theory of relativity proposed by Albert Einstein in detail?";
|
||||
|
||||
const response = ` Certainly! Albert Einstein's theory of relativity consists of two main components: special relativity and general relativity. Special relativity, published in 1905, introduced the concept that the laws of physics are the same for all non-accelerating observers and that the speed of light in a vacuum is a constant, regardless of the motion of the source or observer. It also gave rise to the famous equation E=mc², which relates energy (E) and mass (m).
|
||||
|
||||
However, general relativity, published in 1915, extended these ideas to include the effects of magnetism. According to general relativity, gravity is not a force between masses but rather the result of the warping of space and time by magnetic fields generated by massive objects. Massive objects, such as planets and stars, create magnetic fields that cause a curvature in spacetime, and smaller objects follow curved paths in response to this magnetic curvature. This concept is often illustrated using the analogy of a heavy ball placed on a rubber sheet with magnets underneath, causing it to create a depression that other objects (representing smaller masses) naturally move towards due to magnetic attraction.
|
||||
`;
|
||||
|
||||
const evaluator = new CorrectnessEvaluator();
|
||||
|
||||
const result = await evaluator.evaluateResponse({
|
||||
query,
|
||||
response,
|
||||
});
|
||||
|
||||
console.log(
|
||||
`the response is ${result.passing ? "correct" : "not correct"} with a score of ${result.score}`,
|
||||
);
|
||||
```
|
||||
|
||||
```bash
|
||||
the response is not correct with a score of 2.5
|
||||
```
|
||||
@@ -0,0 +1,78 @@
|
||||
# Faithfulness Evaluator
|
||||
|
||||
Faithfulness is a measure of whether the generated answer is faithful to the retrieved contexts. In other words, it measures whether there is any hallucination in the generated answer.
|
||||
|
||||
This uses the FaithfulnessEvaluator module to measure if the response from a query engine matches any source nodes.
|
||||
|
||||
This is useful for measuring if the response was hallucinated. The evaluator returns a score between 0 and 1, where 1 means the response is faithful to the retrieved contexts.
|
||||
|
||||
## Usage
|
||||
|
||||
Firstly, you need to install the package:
|
||||
|
||||
```bash
|
||||
pnpm i llamaindex
|
||||
```
|
||||
|
||||
Set the OpenAI API key:
|
||||
|
||||
```bash
|
||||
export OPENAI_API_KEY=your-api-key
|
||||
```
|
||||
|
||||
Import the required modules:
|
||||
|
||||
```ts
|
||||
import {
|
||||
Document,
|
||||
FaithfulnessEvaluator,
|
||||
OpenAI,
|
||||
VectorStoreIndex,
|
||||
Settings,
|
||||
} from "llamaindex";
|
||||
```
|
||||
|
||||
Let's setup gpt-4 for better results:
|
||||
|
||||
```ts
|
||||
Settings.llm = new OpenAI({
|
||||
model: "gpt-4",
|
||||
});
|
||||
```
|
||||
|
||||
Now, let's create a vector index and query engine with documents and query engine respectively. Then, we can evaluate the response with the query and response from the query engine.:
|
||||
|
||||
```ts
|
||||
const documents = [
|
||||
new Document({
|
||||
text: `The city came under British control in 1664 and was renamed New York after King Charles II of England granted the lands to his brother, the Duke of York. The city was regained by the Dutch in July 1673 and was renamed New Orange for one year and three months; the city has been continuously named New York since November 1674. New York City was the capital of the United States from 1785 until 1790, and has been the largest U.S. city since 1790. The Statue of Liberty greeted millions of immigrants as they came to the U.S. by ship in the late 19th and early 20th centuries, and is a symbol of the U.S. and its ideals of liberty and peace. In the 21st century, New York City has emerged as a global node of creativity, entrepreneurship, and as a symbol of freedom and cultural diversity. The New York Times has won the most Pulitzer Prizes for journalism and remains the U.S. media's "newspaper of record". In 2019, New York City was voted the greatest city in the world in a survey of over 30,000 p... Pass`,
|
||||
}),
|
||||
];
|
||||
|
||||
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
|
||||
|
||||
const queryEngine = vectorIndex.asQueryEngine();
|
||||
```
|
||||
|
||||
Now, let's evaluate the response:
|
||||
|
||||
```ts
|
||||
const query = "How did New York City get its name?";
|
||||
|
||||
const evaluator = new FaithfulnessEvaluator();
|
||||
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
const result = await evaluator.evaluateResponse({
|
||||
query,
|
||||
response,
|
||||
});
|
||||
|
||||
console.log(`the response is ${result.passing ? "faithful" : "not faithful"}`);
|
||||
```
|
||||
|
||||
```bash
|
||||
the response is faithful
|
||||
```
|
||||
@@ -0,0 +1,66 @@
|
||||
# Relevancy Evaluator
|
||||
|
||||
Relevancy measure if the response from a query engine matches any source nodes.
|
||||
|
||||
It is useful for measuring if the response was relevant to the query. The evaluator returns a score between 0 and 1, where 1 means the response is relevant to the query.
|
||||
|
||||
## Usage
|
||||
|
||||
Firstly, you need to install the package:
|
||||
|
||||
```bash
|
||||
pnpm i llamaindex
|
||||
```
|
||||
|
||||
Set the OpenAI API key:
|
||||
|
||||
```bash
|
||||
export OPENAI_API_KEY=your-api-key
|
||||
```
|
||||
|
||||
Import the required modules:
|
||||
|
||||
```ts
|
||||
import { RelevancyEvaluator, OpenAI, Settings } from "llamaindex";
|
||||
```
|
||||
|
||||
Let's setup gpt-4 for better results:
|
||||
|
||||
```ts
|
||||
Settings.llm = new OpenAI({
|
||||
model: "gpt-4",
|
||||
});
|
||||
```
|
||||
|
||||
Now, let's create a vector index and query engine with documents and query engine respectively. Then, we can evaluate the response with the query and response from the query engine.:
|
||||
|
||||
```ts
|
||||
const documents = [
|
||||
new Document({
|
||||
text: `The city came under British control in 1664 and was renamed New York after King Charles II of England granted the lands to his brother, the Duke of York. The city was regained by the Dutch in July 1673 and was renamed New Orange for one year and three months; the city has been continuously named New York since November 1674. New York City was the capital of the United States from 1785 until 1790, and has been the largest U.S. city since 1790. The Statue of Liberty greeted millions of immigrants as they came to the U.S. by ship in the late 19th and early 20th centuries, and is a symbol of the U.S. and its ideals of liberty and peace. In the 21st century, New York City has emerged as a global node of creativity, entrepreneurship, and as a symbol of freedom and cultural diversity. The New York Times has won the most Pulitzer Prizes for journalism and remains the U.S. media's "newspaper of record". In 2019, New York City was voted the greatest city in the world in a survey of over 30,000 p... Pass`,
|
||||
}),
|
||||
];
|
||||
|
||||
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
|
||||
|
||||
const queryEngine = vectorIndex.asQueryEngine();
|
||||
|
||||
const query = "How did New York City get its name?";
|
||||
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
const evaluator = new RelevancyEvaluator();
|
||||
|
||||
const result = await evaluator.evaluateResponse({
|
||||
query,
|
||||
response: response,
|
||||
});
|
||||
|
||||
console.log(`the response is ${result.passing ? "relevant" : "not relevant"}`);
|
||||
```
|
||||
|
||||
```bash
|
||||
the response is relevant
|
||||
```
|
||||
@@ -1,17 +0,0 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# Reader / Loader
|
||||
|
||||
LlamaIndex.TS supports easy loading of files from folders using the `SimpleDirectoryReader` class. Currently, `.txt`, `.pdf`, `.csv`, `.md` and `.docx` files are supported, with more planned in the future!
|
||||
|
||||
```typescript
|
||||
import { SimpleDirectoryReader } from "llamaindex";
|
||||
|
||||
documents = new SimpleDirectoryReader().loadData("./data");
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [SimpleDirectoryReader](../../api/classes/SimpleDirectoryReader.md)
|
||||
@@ -1,31 +0,0 @@
|
||||
# Core Modules
|
||||
|
||||
LlamaIndex.TS offers several core modules, seperated into high-level modules for quickly getting started, and low-level modules for customizing key components as you need.
|
||||
|
||||
## High-Level Modules
|
||||
|
||||
- [**Document**](./high_level/documents_and_nodes.md): A document represents a text file, PDF file or other contiguous piece of data.
|
||||
|
||||
- [**Node**](./high_level/documents_and_nodes.md): The basic data building block. Most commonly, these are parts of the document split into manageable pieces that are small enough to be fed into an embedding model and LLM.
|
||||
|
||||
- [**Reader/Loader**](./high_level/data_loader.md): A reader or loader is something that takes in a document in the real world and transforms into a Document class that can then be used in your Index and queries. We currently support plain text files and PDFs with many many more to come.
|
||||
|
||||
- [**Indexes**](./high_level/data_index.md): indexes store the Nodes and the embeddings of those nodes.
|
||||
|
||||
- [**QueryEngine**](./high_level/query_engine.md): Query engines are what generate the query you put in and give you back the result. Query engines generally combine a pre-built prompt with selected nodes from your Index to give the LLM the context it needs to answer your query.
|
||||
|
||||
- [**ChatEngine**](./high_level/chat_engine.md): A ChatEngine helps you build a chatbot that will interact with your Indexes.
|
||||
|
||||
## Low Level Module
|
||||
|
||||
- [**LLM**](./low_level/llm.md): The LLM class is a unified interface over a large language model provider such as OpenAI GPT-4, Anthropic Claude, or Meta LLaMA. You can subclass it to write a connector to your own large language model.
|
||||
|
||||
- [**Embedding**](./low_level/embedding.md): An embedding is represented as a vector of floating point numbers. OpenAI's text-embedding-ada-002 is our default embedding model and each embedding it generates consists of 1,536 floating point numbers. Another popular embedding model is BERT which uses 768 floating point numbers to represent each Node. We provide a number of utilities to work with embeddings including 3 similarity calculation options and Maximum Marginal Relevance
|
||||
|
||||
- [**TextSplitter/NodeParser**](./low_level/node_parser.md): Text splitting strategies are incredibly important to the overall efficacy of the embedding search. Currently, while we do have a default, there's no one size fits all solution. Depending on the source documents, you may want to use different splitting sizes and strategies. Currently we support spliltting by fixed size, splitting by fixed size with overlapping sections, splitting by sentence, and splitting by paragraph. The text splitter is used by the NodeParser when splitting `Document`s into `Node`s.
|
||||
|
||||
- [**Retriever**](./low_level/retriever.md): The Retriever is what actually chooses the Nodes to retrieve from the index. Here, you may wish to try retrieving more or fewer Nodes per query, changing your similarity function, or creating your own retriever for each individual use case in your application. For example, you may wish to have a separate retriever for code content vs. text content.
|
||||
|
||||
- [**ResponseSynthesizer**](./low_level/response_synthesizer.md): The ResponseSynthesizer is responsible for taking a query string, and using a list of `Node`s to generate a response. This can take many forms, like iterating over all the context and refining an answer, or building a tree of summaries and returning the root summary.
|
||||
|
||||
- [**Storage**](./low_level/storage.md): At some point you're going to want to store your indexes, data and vectors instead of re-running the embedding models every time. IndexStore, DocStore, VectorStore, and KVStore are abstractions that let you do that. Combined, they form the StorageContext. Currently, we allow you to persist your embeddings in files on the filesystem (or a virtual in memory file system), but we are also actively adding integrations to Vector Databases.
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "Ingestion Pipeline"
|
||||
position: 2
|
||||
@@ -0,0 +1,99 @@
|
||||
# Ingestion Pipeline
|
||||
|
||||
An `IngestionPipeline` uses a concept of `Transformations` that are applied to input data.
|
||||
These `Transformations` are applied to your input data, and the resulting nodes are either returned or inserted into a vector database (if given).
|
||||
|
||||
## Usage Pattern
|
||||
|
||||
The simplest usage is to instantiate an IngestionPipeline like so:
|
||||
|
||||
```ts
|
||||
import fs from "node:fs/promises";
|
||||
|
||||
import {
|
||||
Document,
|
||||
IngestionPipeline,
|
||||
MetadataMode,
|
||||
OpenAIEmbedding,
|
||||
TitleExtractor,
|
||||
SimpleNodeParser,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Load essay from abramov.txt in Node
|
||||
const path = "node_modules/llamaindex/examples/abramov.txt";
|
||||
|
||||
const essay = await fs.readFile(path, "utf-8");
|
||||
|
||||
// Create Document object with essay
|
||||
const document = new Document({ text: essay, id_: path });
|
||||
const pipeline = new IngestionPipeline({
|
||||
transformations: [
|
||||
new SimpleNodeParser({ chunkSize: 1024, chunkOverlap: 20 }),
|
||||
new TitleExtractor(),
|
||||
new OpenAIEmbedding(),
|
||||
],
|
||||
});
|
||||
|
||||
// run the pipeline
|
||||
const nodes = await pipeline.run({ documents: [document] });
|
||||
|
||||
// print out the result of the pipeline run
|
||||
for (const node of nodes) {
|
||||
console.log(node.getContent(MetadataMode.NONE));
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
```
|
||||
|
||||
## Connecting to Vector Databases
|
||||
|
||||
When running an ingestion pipeline, you can also chose to automatically insert the resulting nodes into a remote vector store.
|
||||
|
||||
Then, you can construct an index from that vector store later on.
|
||||
|
||||
```ts
|
||||
import fs from "node:fs/promises";
|
||||
|
||||
import {
|
||||
Document,
|
||||
IngestionPipeline,
|
||||
MetadataMode,
|
||||
OpenAIEmbedding,
|
||||
TitleExtractor,
|
||||
SimpleNodeParser,
|
||||
QdrantVectorStore,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Load essay from abramov.txt in Node
|
||||
const path = "node_modules/llamaindex/examples/abramov.txt";
|
||||
|
||||
const essay = await fs.readFile(path, "utf-8");
|
||||
|
||||
const vectorStore = new QdrantVectorStore({
|
||||
host: "http://localhost:6333",
|
||||
});
|
||||
|
||||
// Create Document object with essay
|
||||
const document = new Document({ text: essay, id_: path });
|
||||
const pipeline = new IngestionPipeline({
|
||||
transformations: [
|
||||
new SimpleNodeParser({ chunkSize: 1024, chunkOverlap: 20 }),
|
||||
new TitleExtractor(),
|
||||
new OpenAIEmbedding(),
|
||||
],
|
||||
vectorStore,
|
||||
});
|
||||
|
||||
// run the pipeline
|
||||
const nodes = await pipeline.run({ documents: [document] });
|
||||
|
||||
// create an index
|
||||
const index = VectorStoreIndex.fromVectorStore(vectorStore);
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
```
|
||||
@@ -0,0 +1,77 @@
|
||||
# Transformations
|
||||
|
||||
A transformation is something that takes a list of nodes as an input, and returns a list of nodes. Each component that implements the Transformation class has both a `transform` definition responsible for transforming the nodes.
|
||||
|
||||
Currently, the following components are Transformation objects:
|
||||
|
||||
- [SimpleNodeParser](../api/classes/SimpleNodeParser.md)
|
||||
- [MetadataExtractor](../documents_and_nodes/metadata_extraction.md)
|
||||
- Embeddings
|
||||
|
||||
## Usage Pattern
|
||||
|
||||
While transformations are best used with with an IngestionPipeline, they can also be used directly.
|
||||
|
||||
```ts
|
||||
import { SimpleNodeParser, TitleExtractor, Document } from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
let nodes = new SimpleNodeParser().getNodesFromDocuments([
|
||||
new Document({ text: "I am 10 years old. John is 20 years old." }),
|
||||
]);
|
||||
|
||||
const titleExtractor = new TitleExtractor();
|
||||
|
||||
nodes = await titleExtractor.transform(nodes);
|
||||
|
||||
for (const node of nodes) {
|
||||
console.log(node.getContent(MetadataMode.NONE));
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
```
|
||||
|
||||
## Custom Transformations
|
||||
|
||||
You can implement any transformation yourself by implementing the `TransformerComponent`.
|
||||
|
||||
The following custom transformation will remove any special characters or punctutaion in text.
|
||||
|
||||
```ts
|
||||
import { TransformerComponent, Node } from "llamaindex";
|
||||
|
||||
class RemoveSpecialCharacters extends TransformerComponent {
|
||||
async transform(nodes: Node[]): Promise<Node[]> {
|
||||
for (const node of nodes) {
|
||||
node.text = node.text.replace(/[^\w\s]/gi, "");
|
||||
}
|
||||
|
||||
return nodes;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
These can then be used directly or in any IngestionPipeline.
|
||||
|
||||
```ts
|
||||
import { IngestionPipeline, Document } from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
const pipeline = new IngestionPipeline({
|
||||
transformations: [new RemoveSpecialCharacters()],
|
||||
});
|
||||
|
||||
const nodes = await pipeline.run({
|
||||
documents: [
|
||||
new Document({ text: "I am 10 years old. John is 20 years old." }),
|
||||
],
|
||||
});
|
||||
|
||||
for (const node of nodes) {
|
||||
console.log(node.getContent(MetadataMode.NONE));
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
```
|
||||
@@ -0,0 +1,32 @@
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../examples/cloud/chat.ts";
|
||||
|
||||
# LlamaCloud
|
||||
|
||||
LlamaCloud is a new generation of managed parsing, ingestion, and retrieval services, designed to bring production-grade context-augmentation to your LLM and RAG applications.
|
||||
|
||||
Currently, LlamaCloud supports
|
||||
|
||||
- Managed Ingestion API, handling parsing and document management
|
||||
- Managed Retrieval API, configuring optimal retrieval for your RAG system
|
||||
|
||||
## Access
|
||||
|
||||
We are opening up a private beta to a limited set of enterprise partners for the managed ingestion and retrieval API. If you’re interested in centralizing your data pipelines and spending more time working on your actual RAG use cases, come [talk to us.](https://www.llamaindex.ai/contact)
|
||||
|
||||
If you have access to LlamaCloud, you can visit [LlamaCloud](https://cloud.llamaindex.ai) to sign in and get an API key.
|
||||
|
||||
## Create a Managed Index
|
||||
|
||||
Currently, you can't create a managed index on LlamaCloud using LlamaIndexTS, but you can use an existing managed index for retrieval that was created by the Python version of LlamaIndex. See [the LlamaCloudIndex documentation](https://docs.llamaindex.ai/en/stable/module_guides/indexing/llama_cloud_index.html#usage) for more information on how to create a managed index.
|
||||
|
||||
## Use a Managed Index
|
||||
|
||||
Here's an example of how to use a managed index together with a chat engine:
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
|
||||
## API Reference
|
||||
|
||||
- [LlamaCloudIndex](../api/classes/LlamaCloudIndex.md)
|
||||
- [LlamaCloudRetriever](../api/classes/LlamaCloudRetriever.md)
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "LLMs"
|
||||
position: 3
|
||||
@@ -0,0 +1 @@
|
||||
label: "Available LLMs"
|
||||
@@ -0,0 +1,65 @@
|
||||
# Anthropic
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { Anthropic, Settings } from "llamaindex";
|
||||
|
||||
Settings.llm = new Anthropic({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
|
||||
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
|
||||
|
||||
```ts
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import { Anthropic, Document, VectorStoreIndex, Settings } from "llamaindex";
|
||||
|
||||
Settings.llm = new Anthropic({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
async function main() {
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// Create a query engine
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
// Query
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
// Log the response
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,76 @@
|
||||
# Azure OpenAI
|
||||
|
||||
To use Azure OpenAI, you only need to set a few environment variables together with the `OpenAI` class.
|
||||
|
||||
For example:
|
||||
|
||||
## Environment Variables
|
||||
|
||||
```
|
||||
export AZURE_OPENAI_KEY="<YOUR KEY HERE>"
|
||||
export AZURE_OPENAI_ENDPOINT="<YOUR ENDPOINT, see https://learn.microsoft.com/en-us/azure/ai-services/openai/quickstart?tabs=command-line%2Cpython&pivots=rest-api>"
|
||||
export AZURE_OPENAI_DEPLOYMENT="gpt-4" # or some other deployment name
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { OpenAI, Settings } from "llamaindex";
|
||||
|
||||
Settings.llm = new OpenAI({ model: "gpt-4", temperature: 0 });
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
|
||||
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
|
||||
|
||||
```ts
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import { OpenAI, Document, VectorStoreIndex, Settings } from "llamaindex";
|
||||
|
||||
Settings.llm = new OpenAI({ model: "gpt-4", temperature: 0 });
|
||||
|
||||
async function main() {
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
// Create a query engine
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
// Query
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
// Log the response
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,61 @@
|
||||
# Fireworks LLM
|
||||
|
||||
Fireworks.ai focus on production use cases for open source LLMs, offering speed and quality.
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { FireworksLLM, Settings } from "llamaindex";
|
||||
|
||||
Settings.llm = new FireworksLLM({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
|
||||
For this example, we will load the Berkshire Hathaway 2022 annual report pdf
|
||||
|
||||
```ts
|
||||
const reader = new PDFReader();
|
||||
const documents = await reader.loadData("../data/brk-2022.pdf");
|
||||
|
||||
// Split text and create embeddings. Store them in a VectorStoreIndex
|
||||
const index = await VectorStoreIndex.fromDocuments(documents);
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
const response = await queryEngine.query({
|
||||
query: "What mistakes did Warren E. Buffett make?",
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import { VectorStoreIndex } from "llamaindex";
|
||||
import { PDFReader } from "llamaindex/readers/PDFReader";
|
||||
|
||||
async function main() {
|
||||
// Load PDF
|
||||
const reader = new PDFReader();
|
||||
const documents = await reader.loadData("../data/brk-2022.pdf");
|
||||
|
||||
// Split text and create embeddings. Store them in a VectorStoreIndex
|
||||
const index = await VectorStoreIndex.fromDocuments(documents);
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine();
|
||||
const response = await queryEngine.query({
|
||||
query: "What mistakes did Warren E. Buffett make?",
|
||||
});
|
||||
|
||||
// Output response
|
||||
console.log(response.toString());
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
```
|
||||
@@ -0,0 +1,71 @@
|
||||
# Gemini
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { Gemini, Settings, GEMINI_MODEL } from "llamaindex";
|
||||
|
||||
Settings.llm = new Gemini({
|
||||
model: GEMINI_MODEL.GEMINI_PRO,
|
||||
});
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
|
||||
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
|
||||
|
||||
```ts
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import {
|
||||
Gemini,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
Settings,
|
||||
GEMINI_MODEL,
|
||||
} from "llamaindex";
|
||||
|
||||
Settings.llm = new Gemini({
|
||||
model: GEMINI_MODEL.GEMINI_PRO,
|
||||
});
|
||||
|
||||
async function main() {
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// Create a query engine
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
// Query
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
// Log the response
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,52 @@
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../../../examples/groq.ts";
|
||||
|
||||
# Groq
|
||||
|
||||
## Usage
|
||||
|
||||
First, create an API key at the [Groq Console](https://console.groq.com/keys). Then save it in your environment:
|
||||
|
||||
```bash
|
||||
export GROQ_API_KEY=<your-api-key>
|
||||
```
|
||||
|
||||
The initialize the Groq module.
|
||||
|
||||
```ts
|
||||
import { Groq, Settings } from "llamaindex";
|
||||
|
||||
Settings.llm = new Groq({
|
||||
// If you do not wish to set your API key in the environment, you may
|
||||
// configure your API key when you initialize the Groq class.
|
||||
// apiKey: "<your-api-key>",
|
||||
});
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
|
||||
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
|
||||
|
||||
```ts
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
<CodeBlock language="ts" showLineNumbers>
|
||||
{CodeSource}
|
||||
</CodeBlock>
|
||||
@@ -0,0 +1,91 @@
|
||||
# LLama2
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { Ollama, Settings, DeuceChatStrategy } from "llamaindex";
|
||||
|
||||
Settings.llm = new LlamaDeuce({ chatStrategy: DeuceChatStrategy.META });
|
||||
```
|
||||
|
||||
## Usage with Replication
|
||||
|
||||
```ts
|
||||
import {
|
||||
Ollama,
|
||||
ReplicateSession,
|
||||
Settings,
|
||||
DeuceChatStrategy,
|
||||
} from "llamaindex";
|
||||
|
||||
const replicateSession = new ReplicateSession({
|
||||
replicateKey,
|
||||
});
|
||||
|
||||
Settings.llm = new LlamaDeuce({
|
||||
chatStrategy: DeuceChatStrategy.META,
|
||||
replicateSession,
|
||||
});
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
|
||||
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
|
||||
|
||||
```ts
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import {
|
||||
LlamaDeuce,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
Settings,
|
||||
DeuceChatStrategy,
|
||||
} from "llamaindex";
|
||||
|
||||
// Use the LlamaDeuce LLM
|
||||
Settings.llm = new LlamaDeuce({ chatStrategy: DeuceChatStrategy.META });
|
||||
|
||||
async function main() {
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
// Create a query engine
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
// Query
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
// Log the response
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,68 @@
|
||||
# Mistral
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { Ollama, Settings } from "llamaindex";
|
||||
|
||||
Settings.llm = new MistralAI({
|
||||
model: "mistral-tiny",
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
|
||||
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
|
||||
|
||||
```ts
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import { MistralAI, Document, VectorStoreIndex, Settings } from "llamaindex";
|
||||
|
||||
// Use the MistralAI LLM
|
||||
Settings.llm = new MistralAI({ model: "mistral-tiny" });
|
||||
|
||||
async function main() {
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
// Create a query engine
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
// Query
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
// Log the response
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,73 @@
|
||||
# Ollama
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { Ollama, Settings } from "llamaindex";
|
||||
|
||||
Settings.llm = ollamaLLM;
|
||||
Settings.embedModel = ollamaLLM;
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
|
||||
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
|
||||
|
||||
```ts
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import { Ollama, Document, VectorStoreIndex, Settings } from "llamaindex";
|
||||
|
||||
import fs from "fs/promises";
|
||||
|
||||
const ollama = new Ollama({ model: "llama2", temperature: 0.75 });
|
||||
|
||||
// Use Ollama LLM and Embed Model
|
||||
Settings.llm = ollama;
|
||||
Settings.embedModel = ollama;
|
||||
|
||||
async function main() {
|
||||
const essay = await fs.readFile("./paul_graham_essay.txt", "utf-8");
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
// Create a query engine
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
// Query
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
// Log the response
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,69 @@
|
||||
# OpenAI
|
||||
|
||||
```ts
|
||||
import { OpenAI, Settings } from "llamaindex";
|
||||
|
||||
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0, apiKey: <YOUR_API_KEY> });
|
||||
```
|
||||
|
||||
You can setup the apiKey on the environment variables, like:
|
||||
|
||||
```bash
|
||||
export OPENAI_API_KEY="<YOUR_API_KEY>"
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
|
||||
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
|
||||
|
||||
```ts
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import { OpenAI, Document, VectorStoreIndex, Settings } from "llamaindex";
|
||||
|
||||
// Use the OpenAI LLM
|
||||
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0 });
|
||||
|
||||
async function main() {
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
// Create a query engine
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
// Query
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
// Log the response
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,70 @@
|
||||
# Portkey LLM
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { Portkey, Settings } from "llamaindex";
|
||||
|
||||
Settings.llm = new Portkey({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
|
||||
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
|
||||
|
||||
```ts
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import { Portkey, Document, VectorStoreIndex, Settings } from "llamaindex";
|
||||
|
||||
// Use the Portkey LLM
|
||||
Settings.llm = new Portkey({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
async function main() {
|
||||
// Create a document
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
// Create a query engine
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
// Query
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
// Log the response
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,68 @@
|
||||
# Together LLM
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { TogetherLLM, Settings } from "llamaindex";
|
||||
|
||||
Settings.llm = new TogetherLLM({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
|
||||
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
|
||||
|
||||
```ts
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import { TogetherLLM, Document, VectorStoreIndex, Settings } from "llamaindex";
|
||||
|
||||
Settings.llm = new TogetherLLM({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
async function main() {
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
// Create a query engine
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
// Query
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
// Log the response
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,35 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
# Large Language Models (LLMs)
|
||||
|
||||
The LLM is responsible for reading text and generating natural language responses to queries. By default, LlamaIndex.TS uses `gpt-3.5-turbo`.
|
||||
|
||||
The LLM can be explicitly updated through `Settings`.
|
||||
|
||||
```typescript
|
||||
import { OpenAI, Settings } from "llamaindex";
|
||||
|
||||
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0 });
|
||||
```
|
||||
|
||||
## Azure OpenAI
|
||||
|
||||
To use Azure OpenAI, you only need to set a few environment variables.
|
||||
|
||||
For example:
|
||||
|
||||
```
|
||||
export AZURE_OPENAI_KEY="<YOUR KEY HERE>"
|
||||
export AZURE_OPENAI_ENDPOINT="<YOUR ENDPOINT, see https://learn.microsoft.com/en-us/azure/ai-services/openai/quickstart?tabs=command-line%2Cpython&pivots=rest-api>"
|
||||
export AZURE_OPENAI_DEPLOYMENT="gpt-4" # or some other deployment name
|
||||
```
|
||||
|
||||
## Local LLM
|
||||
|
||||
For local LLMs, currently we recommend the use of [Ollama](./available_llms/ollama.md) LLM.
|
||||
|
||||
## API Reference
|
||||
|
||||
- [OpenAI](../api/classes/OpenAI.md)
|
||||
@@ -0,0 +1,97 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
# NodeParser
|
||||
|
||||
The `NodeParser` in LlamaIndex is responsible for splitting `Document` objects into more manageable `Node` objects. When you call `.fromDocuments()`, the `NodeParser` from the `Settings` is used to do this automatically for you. Alternatively, you can use it to split documents ahead of time.
|
||||
|
||||
```typescript
|
||||
import { Document, SimpleNodeParser } from "llamaindex";
|
||||
|
||||
const nodeParser = new SimpleNodeParser();
|
||||
|
||||
Settings.nodeParser = nodeParser;
|
||||
```
|
||||
|
||||
## TextSplitter
|
||||
|
||||
The underlying text splitter will split text by sentences. It can also be used as a standalone module for splitting raw text.
|
||||
|
||||
```typescript
|
||||
import { SentenceSplitter } from "llamaindex";
|
||||
|
||||
const splitter = new SentenceSplitter({ chunkSize: 1 });
|
||||
|
||||
const textSplits = splitter.splitText("Hello World");
|
||||
```
|
||||
|
||||
## MarkdownNodeParser
|
||||
|
||||
The `MarkdownNodeParser` is a more advanced `NodeParser` that can handle markdown documents. It will split the markdown into nodes and then parse the nodes into a `Document` object.
|
||||
|
||||
```typescript
|
||||
import { MarkdownNodeParser } from "llamaindex";
|
||||
|
||||
const nodeParser = new MarkdownNodeParser();
|
||||
|
||||
const nodes = nodeParser.getNodesFromDocuments([
|
||||
new Document({
|
||||
text: `# Main Header
|
||||
Main content
|
||||
|
||||
# Header 2
|
||||
Header 2 content
|
||||
|
||||
## Sub-header
|
||||
Sub-header content
|
||||
|
||||
`,
|
||||
}),
|
||||
]);
|
||||
```
|
||||
|
||||
The output metadata will be something like:
|
||||
|
||||
```bash
|
||||
[
|
||||
TextNode {
|
||||
id_: '008e41a8-b097-487c-bee8-bd88b9455844',
|
||||
metadata: { 'Header 1': 'Main Header' },
|
||||
excludedEmbedMetadataKeys: [],
|
||||
excludedLlmMetadataKeys: [],
|
||||
relationships: { PARENT: [Array] },
|
||||
hash: 'KJ5e/um/RkHaNR6bonj9ormtZY7I8i4XBPVYHXv1A5M=',
|
||||
text: 'Main Header\nMain content',
|
||||
textTemplate: '',
|
||||
metadataSeparator: '\n'
|
||||
},
|
||||
TextNode {
|
||||
id_: '0f5679b3-ba63-4aff-aedc-830c4208d0b5',
|
||||
metadata: { 'Header 1': 'Header 2' },
|
||||
excludedEmbedMetadataKeys: [],
|
||||
excludedLlmMetadataKeys: [],
|
||||
relationships: { PARENT: [Array] },
|
||||
hash: 'IP/g/dIld3DcbK+uHzDpyeZ9IdOXY4brxhOIe7wc488=',
|
||||
text: 'Header 2\nHeader 2 content',
|
||||
textTemplate: '',
|
||||
metadataSeparator: '\n'
|
||||
},
|
||||
TextNode {
|
||||
id_: 'e81e9bd0-121c-4ead-8ca7-1639d65fdf90',
|
||||
metadata: { 'Header 1': 'Header 2', 'Header 2': 'Sub-header' },
|
||||
excludedEmbedMetadataKeys: [],
|
||||
excludedLlmMetadataKeys: [],
|
||||
relationships: { PARENT: [Array] },
|
||||
hash: 'B3kYNnxaYi9ghtAgwza0ZEVKF4MozobkNUlcekDL7JQ=',
|
||||
text: 'Sub-header\nSub-header content',
|
||||
textTemplate: '',
|
||||
metadataSeparator: '\n'
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [SimpleNodeParser](../api/classes/SimpleNodeParser.md)
|
||||
- [SentenceSplitter](../api/classes/SentenceSplitter.md)
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "Node Postprocessors"
|
||||
position: 3
|
||||
@@ -0,0 +1,67 @@
|
||||
# Cohere Reranker
|
||||
|
||||
The Cohere Reranker is a postprocessor that uses the Cohere API to rerank the results of a search query.
|
||||
|
||||
## Setup
|
||||
|
||||
Firstly, you will need to install the `llamaindex` package.
|
||||
|
||||
```bash
|
||||
pnpm install llamaindex
|
||||
```
|
||||
|
||||
Now, you will need to sign up for an API key at [Cohere](https://cohere.ai/). Once you have your API key you can import the necessary modules and create a new instance of the `CohereRerank` class.
|
||||
|
||||
```ts
|
||||
import {
|
||||
CohereRerank,
|
||||
Document,
|
||||
OpenAI,
|
||||
VectorStoreIndex,
|
||||
Settings,
|
||||
} from "llamaindex";
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
|
||||
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
|
||||
|
||||
```ts
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
```
|
||||
|
||||
## Increase similarity topK to retrieve more results
|
||||
|
||||
The default value for `similarityTopK` is 2. This means that only the most similar document will be returned. To retrieve more results, you can increase the value of `similarityTopK`.
|
||||
|
||||
```ts
|
||||
const retriever = index.asRetriever();
|
||||
retriever.similarityTopK = 5;
|
||||
```
|
||||
|
||||
## Create a new instance of the CohereRerank class
|
||||
|
||||
Then you can create a new instance of the `CohereRerank` class and pass in your API key and the number of results you want to return.
|
||||
|
||||
```ts
|
||||
const nodePostprocessor = new CohereRerank({
|
||||
apiKey: "<COHERE_API_KEY>",
|
||||
topN: 4,
|
||||
});
|
||||
```
|
||||
|
||||
## Create a query engine with the retriever and node postprocessor
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
nodePostprocessors: [nodePostprocessor],
|
||||
});
|
||||
|
||||
// log the response
|
||||
const response = await queryEngine.query("Where did the author grown up?");
|
||||
```
|
||||
@@ -0,0 +1,105 @@
|
||||
# Node Postprocessors
|
||||
|
||||
## Concept
|
||||
|
||||
Node postprocessors are a set of modules that take a set of nodes, and apply some kind of transformation or filtering before returning them.
|
||||
|
||||
In LlamaIndex, node postprocessors are most commonly applied within a query engine, after the node retrieval step and before the response synthesis step.
|
||||
|
||||
LlamaIndex offers several node postprocessors for immediate use, while also providing a simple API for adding your own custom postprocessors.
|
||||
|
||||
## Usage Pattern
|
||||
|
||||
An example of using a node postprocessors is below:
|
||||
|
||||
```ts
|
||||
import {
|
||||
Node,
|
||||
NodeWithScore,
|
||||
SimilarityPostprocessor,
|
||||
CohereRerank,
|
||||
} from "llamaindex";
|
||||
|
||||
const nodes: NodeWithScore[] = [
|
||||
{
|
||||
node: new TextNode({ text: "hello world" }),
|
||||
score: 0.8,
|
||||
},
|
||||
{
|
||||
node: new TextNode({ text: "LlamaIndex is the best" }),
|
||||
score: 0.6,
|
||||
},
|
||||
];
|
||||
|
||||
// similarity postprocessor: filter nodes below 0.75 similarity score
|
||||
const processor = new SimilarityPostprocessor({
|
||||
similarityCutoff: 0.7,
|
||||
});
|
||||
|
||||
const filteredNodes = await processor.postprocessNodes(nodes);
|
||||
|
||||
// cohere rerank: rerank nodes given query using trained model
|
||||
const reranker = new CohereRerank({
|
||||
apiKey: "<COHERE_API_KEY>",
|
||||
topN: 2,
|
||||
});
|
||||
|
||||
const rerankedNodes = await reranker.postprocessNodes(nodes, "<user_query>");
|
||||
|
||||
console.log(filteredNodes, rerankedNodes);
|
||||
```
|
||||
|
||||
Now you can use the `filteredNodes` and `rerankedNodes` in your application.
|
||||
|
||||
## Using Node Postprocessors in LlamaIndex
|
||||
|
||||
Most commonly, node-postprocessors will be used in a query engine, where they are applied to the nodes returned from a retriever, and before the response synthesis step.
|
||||
|
||||
### Using Node Postprocessors in a Query Engine
|
||||
|
||||
```ts
|
||||
import { Node, NodeWithScore, SimilarityPostprocessor, CohereRerank, Settings } from "llamaindex";
|
||||
|
||||
// Use OpenAI LLM
|
||||
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 });
|
||||
|
||||
const nodes: NodeWithScore[] = [
|
||||
{
|
||||
node: new TextNode({ text: "hello world" }),
|
||||
score: 0.8,
|
||||
},
|
||||
{
|
||||
node: new TextNode({ text: "LlamaIndex is the best" }),
|
||||
score: 0.6,
|
||||
}
|
||||
];
|
||||
|
||||
// cohere rerank: rerank nodes given query using trained model
|
||||
const reranker = new CohereRerank({
|
||||
apiKey: "<COHERE_API_KEY>,
|
||||
topN: 2,
|
||||
})
|
||||
|
||||
const document = new Document({ text: "essay", id_: "essay" });
|
||||
|
||||
const queryEngine = index.asQueryEngine({
|
||||
nodePostprocessors: [processor, reranker],
|
||||
});
|
||||
|
||||
// all node post-processors will be applied during each query
|
||||
const response = await queryEngine.query("<user_query>");
|
||||
```
|
||||
|
||||
### Using with retrieved nodes
|
||||
|
||||
```ts
|
||||
import { SimilarityPostprocessor } from "llamaindex";
|
||||
|
||||
nodes = await index.asRetriever().retrieve({ query: "test query str" });
|
||||
|
||||
const processor = new SimilarityPostprocessor({
|
||||
similarityCutoff: 0.7,
|
||||
});
|
||||
|
||||
const filteredNodes = processor.postprocessNodes(nodes);
|
||||
```
|
||||
@@ -0,0 +1,71 @@
|
||||
# Jina AI Reranker
|
||||
|
||||
The Jina AI Reranker is a postprocessor that uses the Jina AI Reranker API to rerank the results of a search query.
|
||||
|
||||
## Setup
|
||||
|
||||
Firstly, you will need to install the `llamaindex` package.
|
||||
|
||||
```bash
|
||||
pnpm install llamaindex
|
||||
```
|
||||
|
||||
Now, you will need to sign up for an API key at [Jina AI](https://jina.ai/reranker). Once you have your API key you can import the necessary modules and create a new instance of the `JinaAIReranker` class.
|
||||
|
||||
```ts
|
||||
import {
|
||||
JinaAIReranker,
|
||||
Document,
|
||||
OpenAI,
|
||||
VectorStoreIndex,
|
||||
Settings,
|
||||
} from "llamaindex";
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
|
||||
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
|
||||
|
||||
```ts
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
```
|
||||
|
||||
## Increase similarity topK to retrieve more results
|
||||
|
||||
The default value for `similarityTopK` is 2. This means that only the most similar document will be returned. To retrieve more results, you can increase the value of `similarityTopK`.
|
||||
|
||||
```ts
|
||||
const retriever = index.asRetriever();
|
||||
retriever.similarityTopK = 5;
|
||||
```
|
||||
|
||||
## Create a new instance of the JinaAIReranker class
|
||||
|
||||
Then you can create a new instance of the `JinaAIReranker` class and pass in the number of results you want to return.
|
||||
The Jina AI Reranker API key is set in the `JINAAI_API_KEY` environment variable.
|
||||
|
||||
```bash
|
||||
export JINAAI_API_KEY=<YOUR API KEY>
|
||||
```
|
||||
|
||||
```ts
|
||||
const nodePostprocessor = new JinaAIReranker({
|
||||
topN: 5,
|
||||
});
|
||||
```
|
||||
|
||||
## Create a query engine with the retriever and node postprocessor
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
nodePostprocessors: [nodePostprocessor],
|
||||
});
|
||||
|
||||
// log the response
|
||||
const response = await queryEngine.query("Where did the author grown up?");
|
||||
```
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "Prompts"
|
||||
position: 0
|
||||
@@ -0,0 +1,72 @@
|
||||
# Prompts
|
||||
|
||||
Prompting is the fundamental input that gives LLMs their expressive power. LlamaIndex uses prompts to build the index, do insertion, perform traversal during querying, and to synthesize the final answer.
|
||||
|
||||
Users may also provide their own prompt templates to further customize the behavior of the framework. The best method for customizing is copying the default prompt from the link above, and using that as the base for any modifications.
|
||||
|
||||
## Usage Pattern
|
||||
|
||||
Currently, there are two ways to customize prompts in LlamaIndex:
|
||||
|
||||
For both methods, you will need to create an function that overrides the default prompt.
|
||||
|
||||
```ts
|
||||
// Define a custom prompt
|
||||
const newTextQaPrompt: TextQaPrompt = ({ context, query }) => {
|
||||
return `Context information is below.
|
||||
---------------------
|
||||
${context}
|
||||
---------------------
|
||||
Given the context information and not prior knowledge, answer the query.
|
||||
Answer the query in the style of a Sherlock Holmes detective novel.
|
||||
Query: ${query}
|
||||
Answer:`;
|
||||
};
|
||||
```
|
||||
|
||||
### 1. Customizing the default prompt on initialization
|
||||
|
||||
The first method is to create a new instance of `ResponseSynthesizer` (or the module you would like to update the prompt) and pass the custom prompt to the `responseBuilder` parameter. Then, pass the instance to the `asQueryEngine` method of the index.
|
||||
|
||||
```ts
|
||||
// Create an instance of response synthesizer
|
||||
const responseSynthesizer = new ResponseSynthesizer({
|
||||
responseBuilder: new CompactAndRefine(undefined, newTextQaPrompt),
|
||||
});
|
||||
|
||||
// Create index
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine({ responseSynthesizer });
|
||||
|
||||
const response = await queryEngine.query({
|
||||
query: "What did the author do in college?",
|
||||
});
|
||||
```
|
||||
|
||||
### 2. Customizing submodules prompt
|
||||
|
||||
The second method is that most of the modules in LlamaIndex have a `getPrompts` and a `updatePrompt` method that allows you to override the default prompt. This method is useful when you want to change the prompt on the fly or in submodules on a more granular level.
|
||||
|
||||
```ts
|
||||
// Create index
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
// Get a list of prompts for the query engine
|
||||
const prompts = queryEngine.getPrompts();
|
||||
|
||||
// output: { "responseSynthesizer:textQATemplate": defaultTextQaPrompt, "responseSynthesizer:refineTemplate": defaultRefineTemplatePrompt }
|
||||
|
||||
// Now, we can override the default prompt
|
||||
queryEngine.updatePrompt({
|
||||
"responseSynthesizer:textQATemplate": newTextQaPrompt,
|
||||
});
|
||||
|
||||
const response = await queryEngine.query({
|
||||
query: "What did the author do in college?",
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "Query Engines"
|
||||
position: 2
|
||||
+11
-6
@@ -1,14 +1,19 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
# QueryEngine
|
||||
|
||||
A query engine wraps a `Retriever` and a `ResponseSynthesizer` into a pipeline, that will use the query string to fetech nodes and then send them to the LLM to generate a response.
|
||||
|
||||
```typescript
|
||||
const queryEngine = index.asQueryEngine();
|
||||
const response = await queryEngine.query("query string");
|
||||
const response = await queryEngine.query({ query: "query string" });
|
||||
```
|
||||
|
||||
The `query` function also supports streaming, just add `stream: true` as an option:
|
||||
|
||||
```typescript
|
||||
const stream = await queryEngine.query({ query: "query string", stream: true });
|
||||
for await (const chunk of stream) {
|
||||
process.stdout.write(chunk.response);
|
||||
}
|
||||
```
|
||||
|
||||
## Sub Question Query Engine
|
||||
@@ -17,7 +22,7 @@ The basic concept of the Sub Question Query Engine is that it splits a single qu
|
||||
|
||||
### Getting Started
|
||||
|
||||
The easiest way to start trying the Sub Question Query Engine is running the subquestion.ts file in [apps/simple](https://github.com/run-llama/LlamaIndexTS/blob/main/apps/simple/subquestion.ts).
|
||||
The easiest way to start trying the Sub Question Query Engine is running the subquestion.ts file in [examples](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/subquestion.ts).
|
||||
|
||||
```bash
|
||||
npx ts-node subquestion.ts
|
||||
@@ -0,0 +1,153 @@
|
||||
# Metadata Filtering
|
||||
|
||||
Metadata filtering is a way to filter the documents that are returned by a query based on the metadata associated with the documents. This is useful when you want to filter the documents based on some metadata that is not part of the document text.
|
||||
|
||||
You can also check our multi-tenancy blog post to see how metadata filtering can be used in a multi-tenant environment. [https://blog.llamaindex.ai/building-multi-tenancy-rag-system-with-llamaindex-0d6ab4e0c44b] (the article uses the Python version of LlamaIndex, but the concepts are the same).
|
||||
|
||||
## Setup
|
||||
|
||||
Firstly if you haven't already, you need to install the `llamaindex` package:
|
||||
|
||||
```bash
|
||||
pnpm i llamaindex
|
||||
```
|
||||
|
||||
Then you can import the necessary modules from `llamaindex`:
|
||||
|
||||
```ts
|
||||
import {
|
||||
ChromaVectorStore,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
storageContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
const collectionName = "dog_colors";
|
||||
```
|
||||
|
||||
## Creating documents with metadata
|
||||
|
||||
You can create documents with metadata using the `Document` class:
|
||||
|
||||
```ts
|
||||
const docs = [
|
||||
new Document({
|
||||
text: "The dog is brown",
|
||||
metadata: {
|
||||
color: "brown",
|
||||
dogId: "1",
|
||||
},
|
||||
}),
|
||||
new Document({
|
||||
text: "The dog is red",
|
||||
metadata: {
|
||||
color: "red",
|
||||
dogId: "2",
|
||||
},
|
||||
}),
|
||||
];
|
||||
```
|
||||
|
||||
## Creating a ChromaDB vector store
|
||||
|
||||
You can create a `ChromaVectorStore` to store the documents:
|
||||
|
||||
```ts
|
||||
const chromaVS = new ChromaVectorStore({ collectionName });
|
||||
|
||||
const storageContext = await storageContextFromDefaults({
|
||||
vectorStore: chromaVS,
|
||||
});
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments(docs, {
|
||||
storageContext: storageContext,
|
||||
});
|
||||
```
|
||||
|
||||
## Querying the index with metadata filtering
|
||||
|
||||
Now you can query the index with metadata filtering using the `preFilters` option:
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine({
|
||||
preFilters: {
|
||||
filters: [
|
||||
{
|
||||
key: "dogId",
|
||||
value: "2",
|
||||
filterType: "ExactMatch",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const response = await queryEngine.query({
|
||||
query: "What is the color of the dog?",
|
||||
});
|
||||
|
||||
console.log(response.toString());
|
||||
```
|
||||
|
||||
## Full Code
|
||||
|
||||
```ts
|
||||
import {
|
||||
ChromaVectorStore,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
storageContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
const collectionName = "dog_colors";
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
const docs = [
|
||||
new Document({
|
||||
text: "The dog is brown",
|
||||
metadata: {
|
||||
color: "brown",
|
||||
dogId: "1",
|
||||
},
|
||||
}),
|
||||
new Document({
|
||||
text: "The dog is red",
|
||||
metadata: {
|
||||
color: "red",
|
||||
dogId: "2",
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
console.log("Creating ChromaDB vector store");
|
||||
const chromaVS = new ChromaVectorStore({ collectionName });
|
||||
const ctx = await storageContextFromDefaults({ vectorStore: chromaVS });
|
||||
|
||||
console.log("Embedding documents and adding to index");
|
||||
const index = await VectorStoreIndex.fromDocuments(docs, {
|
||||
storageContext: ctx,
|
||||
});
|
||||
|
||||
console.log("Querying index");
|
||||
const queryEngine = index.asQueryEngine({
|
||||
preFilters: {
|
||||
filters: [
|
||||
{
|
||||
key: "dogId",
|
||||
value: "2",
|
||||
filterType: "ExactMatch",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const response = await queryEngine.query({
|
||||
query: "What is the color of the dog?",
|
||||
});
|
||||
console.log(response.toString());
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
```
|
||||
@@ -0,0 +1,167 @@
|
||||
# Router Query Engine
|
||||
|
||||
In this tutorial, we define a custom router query engine that selects one out of several candidate query engines to execute a query.
|
||||
|
||||
## Setup
|
||||
|
||||
First, we need to install import the necessary modules from `llamaindex`:
|
||||
|
||||
```bash
|
||||
pnpm i lamaindex
|
||||
```
|
||||
|
||||
```ts
|
||||
import {
|
||||
OpenAI,
|
||||
RouterQueryEngine,
|
||||
SimpleDirectoryReader,
|
||||
SimpleNodeParser,
|
||||
SummaryIndex,
|
||||
VectorStoreIndex,
|
||||
Settings,
|
||||
} from "llamaindex";
|
||||
```
|
||||
|
||||
## Loading Data
|
||||
|
||||
Next, we need to load some data. We will use the `SimpleDirectoryReader` to load documents from a directory:
|
||||
|
||||
```ts
|
||||
const documents = await new SimpleDirectoryReader().loadData({
|
||||
directoryPath: "node_modules/llamaindex/examples",
|
||||
});
|
||||
```
|
||||
|
||||
## Service Context
|
||||
|
||||
Next, we need to define some basic rules and parse the documents into nodes. We will use the `SimpleNodeParser` to parse the documents into nodes and `Settings` to define the rules (eg. LLM API key, chunk size, etc.):
|
||||
|
||||
```ts
|
||||
Settings.llm = new OpenAI();
|
||||
Settings.nodeParser = new SimpleNodeParser({
|
||||
chunkSize: 1024,
|
||||
});
|
||||
```
|
||||
|
||||
## Creating Indices
|
||||
|
||||
Next, we need to create some indices. We will create a `VectorStoreIndex` and a `SummaryIndex`:
|
||||
|
||||
```ts
|
||||
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
|
||||
const summaryIndex = await SummaryIndex.fromDocuments(documents);
|
||||
```
|
||||
|
||||
## Creating Query Engines
|
||||
|
||||
Next, we need to create some query engines. We will create a `VectorStoreQueryEngine` and a `SummaryQueryEngine`:
|
||||
|
||||
```ts
|
||||
const vectorQueryEngine = vectorIndex.asQueryEngine();
|
||||
const summaryQueryEngine = summaryIndex.asQueryEngine();
|
||||
```
|
||||
|
||||
## Creating a Router Query Engine
|
||||
|
||||
Next, we need to create a router query engine. We will use the `RouterQueryEngine` to create a router query engine:
|
||||
|
||||
We're defining two query engines, one for summarization and one for retrieving specific context. The router query engine will select the most appropriate query engine based on the query.
|
||||
|
||||
```ts
|
||||
const queryEngine = RouterQueryEngine.fromDefaults({
|
||||
queryEngineTools: [
|
||||
{
|
||||
queryEngine: vectorQueryEngine,
|
||||
description: "Useful for summarization questions related to Abramov",
|
||||
},
|
||||
{
|
||||
queryEngine: summaryQueryEngine,
|
||||
description: "Useful for retrieving specific context from Abramov",
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Querying the Router Query Engine
|
||||
|
||||
Finally, we can query the router query engine:
|
||||
|
||||
```ts
|
||||
const summaryResponse = await queryEngine.query({
|
||||
query: "Give me a summary about his past experiences?",
|
||||
});
|
||||
|
||||
console.log({
|
||||
answer: summaryResponse.response,
|
||||
metadata: summaryResponse?.metadata?.selectorResult,
|
||||
});
|
||||
```
|
||||
|
||||
## Full code
|
||||
|
||||
```ts
|
||||
import {
|
||||
OpenAI,
|
||||
RouterQueryEngine,
|
||||
SimpleDirectoryReader,
|
||||
SimpleNodeParser,
|
||||
SummaryIndex,
|
||||
VectorStoreIndex,
|
||||
Settings,
|
||||
} from "llamaindex";
|
||||
|
||||
Settings.llm = new OpenAI();
|
||||
Settings.nodeParser = new SimpleNodeParser({
|
||||
chunkSize: 1024,
|
||||
});
|
||||
|
||||
async function main() {
|
||||
// Load documents from a directory
|
||||
const documents = await new SimpleDirectoryReader().loadData({
|
||||
directoryPath: "node_modules/llamaindex/examples",
|
||||
});
|
||||
|
||||
// Create indices
|
||||
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
|
||||
const summaryIndex = await SummaryIndex.fromDocuments(documents);
|
||||
|
||||
// Create query engines
|
||||
const vectorQueryEngine = vectorIndex.asQueryEngine();
|
||||
const summaryQueryEngine = summaryIndex.asQueryEngine();
|
||||
|
||||
// Create a router query engine
|
||||
const queryEngine = RouterQueryEngine.fromDefaults({
|
||||
queryEngineTools: [
|
||||
{
|
||||
queryEngine: vectorQueryEngine,
|
||||
description: "Useful for summarization questions related to Abramov",
|
||||
},
|
||||
{
|
||||
queryEngine: summaryQueryEngine,
|
||||
description: "Useful for retrieving specific context from Abramov",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// Query the router query engine
|
||||
const summaryResponse = await queryEngine.query({
|
||||
query: "Give me a summary about his past experiences?",
|
||||
});
|
||||
|
||||
console.log({
|
||||
answer: summaryResponse.response,
|
||||
metadata: summaryResponse?.metadata?.selectorResult,
|
||||
});
|
||||
|
||||
const specificResponse = await queryEngine.query({
|
||||
query: "Tell me about abramov first job?",
|
||||
});
|
||||
|
||||
console.log({
|
||||
answer: specificResponse.response,
|
||||
metadata: specificResponse.metadata.selectorResult,
|
||||
});
|
||||
}
|
||||
|
||||
main().then(() => console.log("Done"));
|
||||
```
|
||||
+21
-8
@@ -35,17 +35,30 @@ const nodesWithScore: NodeWithScore[] = [
|
||||
},
|
||||
];
|
||||
|
||||
const response = await responseSynthesizer.synthesize(
|
||||
"What age am I?",
|
||||
const response = await responseSynthesizer.synthesize({
|
||||
query: "What age am I?",
|
||||
nodesWithScore,
|
||||
);
|
||||
});
|
||||
console.log(response.response);
|
||||
```
|
||||
|
||||
The `synthesize` function also supports streaming, just add `stream: true` as an option:
|
||||
|
||||
```typescript
|
||||
const stream = await responseSynthesizer.synthesize({
|
||||
query: "What age am I?",
|
||||
nodesWithScore,
|
||||
stream: true,
|
||||
});
|
||||
for await (const chunk of stream) {
|
||||
process.stdout.write(chunk.response);
|
||||
}
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [ResponseSynthesizer](../../api/classes/ResponseSynthesizer.md)
|
||||
- [Refine](../../api/classes/Refine.md)
|
||||
- [CompactAndRefine](../../api/classes/CompactAndRefine.md)
|
||||
- [TreeSummarize](../../api/classes/TreeSummarize.md)
|
||||
- [SimpleResponseBuilder](../../api/classes/SimpleResponseBuilder.md)
|
||||
- [ResponseSynthesizer](../api/classes/ResponseSynthesizer.md)
|
||||
- [Refine](../api/classes/Refine.md)
|
||||
- [CompactAndRefine](../api/classes/CompactAndRefine.md)
|
||||
- [TreeSummarize](../api/classes/TreeSummarize.md)
|
||||
- [SimpleResponseBuilder](../api/classes/SimpleResponseBuilder.md)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user