mirror of
https://github.com/run-llama/LlamaIndexTS.git
synced 2026-07-01 22:14:03 -04:00
Compare commits
570 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 335f2df626 | |||
| ee963644bf | |||
| cb256f24ae | |||
| 1ccc04ecb5 | |||
| 034639153b | |||
| 1914b52708 | |||
| cb021e7196 | |||
| c2aa836b35 | |||
| 3b0f55f1ea | |||
| a9c6144eec | |||
| 3564244ced | |||
| d952e68ec4 | |||
| 5c026e839f | |||
| 9c1c5b4d50 | |||
| c902fcbc33 | |||
| 88d776f392 | |||
| 6fcc6bcb84 | |||
| be74207945 | |||
| 6be223dfad | |||
| 4cbfdb5f5c | |||
| 9767d1c004 | |||
| e831b28627 | |||
| cc50c9c2d4 | |||
| 954140776e | |||
| 6d37d440a6 | |||
| e724f7e9f2 | |||
| 1b029ae525 | |||
| d1db2189c9 | |||
| 2c5b4030c9 | |||
| 96eb597059 | |||
| 04098d55ff | |||
| 335a6b9e88 | |||
| c2a345ebb1 | |||
| d3fa729a30 | |||
| c7c08005ec | |||
| bb0ae5e321 | |||
| f4588bc770 | |||
| b49037612d | |||
| a87efb91a4 | |||
| 6a4a73760b | |||
| 1564831158 | |||
| 4d94f6e50d | |||
| 7bd5d9340c | |||
| d924c63162 | |||
| 83cff1277c | |||
| 1c908fd852 | |||
| 56f367f08d | |||
| cb608b5d01 | |||
| bd55bcffff | |||
| 6d4d96f8fe | |||
| b6ea2bf964 | |||
| 15563a0f70 | |||
| bd940d1d43 | |||
| 9f8ad37b79 | |||
| 7265f74c24 | |||
| e3f1b85846 | |||
| e38e474f86 | |||
| 2019a041f7 | |||
| 067a4894fe | |||
| 21769c8ad9 | |||
| 89ea1e1d31 | |||
| d9bbaf95f3 | |||
| 8744796c06 | |||
| f02621e379 | |||
| 1892e1ce1d | |||
| d90d8959a5 | |||
| 4df1fe6cca | |||
| 34faf4821a | |||
| b24ffc6174 | |||
| 82e25c924c | |||
| 1931bbca74 | |||
| 94566169fb | |||
| d6c270ec7a | |||
| e3a77044d5 | |||
| fd9c8294e1 | |||
| 0ebbfc1031 | |||
| 5dec9f912a | |||
| 1f53819b64 | |||
| d211b7ab13 | |||
| 057ee146bd | |||
| 4a831b192c | |||
| cf29ca1bf8 | |||
| 09b933f8da | |||
| 44c0734106 | |||
| a7023b4a93 | |||
| 012495b5ba | |||
| a8afb9a7a7 | |||
| dd596a0cf2 | |||
| 9e648a0b4f | |||
| bbb87f42ed | |||
| 24caf93efe | |||
| a9b5b993fa | |||
| f369d3de4f | |||
| c1850ee370 | |||
| 086a65141d | |||
| d99d598491 | |||
| a0e6f57d9b | |||
| e0f6cc3be1 | |||
| 8386510d86 | |||
| b504303c66 | |||
| cf9a9356e0 | |||
| 335020e242 | |||
| 3d1808b5d2 | |||
| a19cbc7fe0 | |||
| b8f0cbc4e0 | |||
| 7e8230b056 | |||
| 8be45899a7 | |||
| c4800bcf82 | |||
| fd38a253b7 | |||
| 510191cb5d | |||
| 7934ade092 | |||
| a6c1eab762 | |||
| 515f2c1e3d | |||
| dc85649ead | |||
| d2b2722a30 | |||
| a2bbd62399 | |||
| 969365ca0a | |||
| 819af453d6 | |||
| 9db36f7384 | |||
| efa221116f | |||
| 83c3897539 | |||
| e1cbce1f80 | |||
| 02b22da384 | |||
| 0aa61db547 | |||
| 90d265cf47 | |||
| fc2d5ea1cd | |||
| ef4f63d9f4 | |||
| d17450fdfb | |||
| 805d2b0d55 | |||
| 6d22fa2a50 | |||
| 16f0068175 | |||
| 1054c3382a | |||
| e60328b086 | |||
| 3371dfb89f | |||
| 2065a16a07 | |||
| 5dae534f8d | |||
| 3d503cb810 | |||
| daf8522bec | |||
| 223f3136b4 | |||
| c6bad7d951 | |||
| 630b425545 | |||
| 4c7b891446 | |||
| a9c5b4899b | |||
| a7b0ac3cb7 | |||
| a7540ff47b | |||
| c69605f406 | |||
| ee20c44d9b | |||
| 1d470363df | |||
| b39f40dbd8 | |||
| fadc8b8ea0 | |||
| ea92b6986d | |||
| 17f9022d22 | |||
| 14792cd8b4 | |||
| 7ae6eaa0a2 | |||
| dbb5bd9f23 | |||
| aacd606204 | |||
| f865c984d3 | |||
| 7b10882d06 | |||
| f066e50482 | |||
| fd8c882792 | |||
| d89ebe0261 | |||
| 968feb32cd | |||
| 43f6f56c5b | |||
| b2364dc5ba | |||
| 67f4db8501 | |||
| e4151a8b02 | |||
| 4d4cd8ac6b | |||
| 4fc001c8de | |||
| cf675bdc7a | |||
| 660b831b9e | |||
| ad85bd0b46 | |||
| 18ec1f2f61 | |||
| b0fbd8b5c8 | |||
| c0dfc8c641 | |||
| a8d3fa68a1 | |||
| f9470c470a | |||
| 95a5cc6ee1 | |||
| 487782cd98 | |||
| 58e65d399e | |||
| fdad3d66ac | |||
| a6db5dd29b | |||
| 7b684c4480 | |||
| c66868a98a | |||
| 14cc9ebe59 | |||
| 396b1e1474 | |||
| 69f3095424 | |||
| dc8bd5ea92 | |||
| 4af9a77d8b | |||
| 9c1d094455 | |||
| 0a8e3fdbcd | |||
| 1c0e0e1e1d | |||
| 47a7c3ea15 | |||
| 898cff0d6a | |||
| 9df37edef4 | |||
| f86a7a4fa3 | |||
| 35430d3609 | |||
| 3c162b2b4a | |||
| 5bb4531245 | |||
| 2ff0a89891 | |||
| d57917d782 | |||
| f231e0739f | |||
| 0765742ef3 | |||
| ec7fd6be5c | |||
| c7a918c3f5 | |||
| 00e681d43b | |||
| c01502fb84 | |||
| 075f88dbc3 | |||
| cc47ee0602 | |||
| 5e6ef55a5a | |||
| 9c73f0a530 | |||
| 52a4d2b83d | |||
| 0fd78d5434 | |||
| 5c4f4a8d83 | |||
| 620c63cd19 | |||
| cb51ad90ea | |||
| 359fd33041 | |||
| efb7e1b868 | |||
| 98ba1e71bd | |||
| fd4b09d375 | |||
| 7c90e1b6b4 | |||
| 21ba0a80d1 | |||
| 9df9a8fc1d | |||
| 60b185ff53 | |||
| ca75c81bc0 | |||
| 691c5bcaf1 | |||
| 9ab998c5d5 | |||
| 938b417028 | |||
| fa60fc66ae | |||
| 5607ed2fec | |||
| f57ad6150e | |||
| 2486bd8f41 | |||
| e2a0876ddd | |||
| a75d899a57 | |||
| 809a6e7eea | |||
| da6eb6474b | |||
| cd83f8ee4f | |||
| 534d5505cb | |||
| eb87b96518 | |||
| 9510d45046 | |||
| 9b5b012fdf | |||
| a5a75f618d | |||
| 051faddefd | |||
| 9f22aae57c | |||
| e9a111d9d3 | |||
| bb7622e4d4 | |||
| 06f632b2cb | |||
| 76b925e62a | |||
| 0493f679a4 | |||
| 0e0a627c9a | |||
| 4ba2cfe7ab | |||
| c1578a19d9 | |||
| ae49ff4e15 | |||
| a75af835a5 | |||
| 7c7cd34908 | |||
| f651891196 | |||
| 04714c886f | |||
| cf28574f51 | |||
| 24d065f054 | |||
| b8719586e3 | |||
| 07a40aca49 | |||
| 33b562938d | |||
| 723b41c23c | |||
| 4c38c1be0b | |||
| 0dde0ca27f | |||
| f3e0d07f48 | |||
| 1364e8eeed | |||
| 96fc69cc61 | |||
| 3b7736f763 | |||
| a7a7afe66e | |||
| c646ee2eca | |||
| 5729bd92fd | |||
| e0e52cf879 | |||
| 6f75306c17 | |||
| 94cb4ad810 | |||
| 1ea4014746 | |||
| 6a9a7b1458 | |||
| 1c168cd531 | |||
| 62cba5236d | |||
| d265e96420 | |||
| d30bbf799f | |||
| 53fd00a7c3 | |||
| 83f2848d47 | |||
| 313071e9cd | |||
| 5f6782038a | |||
| fe08d0451b | |||
| 59c5e5c3d4 | |||
| ee697fb1b3 | |||
| cf3320a4ea | |||
| f2ed69f2f8 | |||
| 3489e7de84 | |||
| 468bda594e | |||
| 6f3a31caf6 | |||
| 63e9846e97 | |||
| b7382b0d24 | |||
| 2a8241328d | |||
| 0b20ff9f17 | |||
| 1fc26046e3 | |||
| b17d439d6d | |||
| 040160c360 | |||
| 981811efd1 | |||
| d563b45a27 | |||
| 2774e80234 | |||
| 449274ca5a | |||
| 78037a664c | |||
| 1d9e3b1000 | |||
| df83e32107 | |||
| f7b4e94231 | |||
| 4c07a2655d | |||
| 5c0c8b2ec4 | |||
| e5e18688a6 | |||
| b6fb10eba8 | |||
| df441e28f4 | |||
| a4e05ec7ab | |||
| 96f72ad86e | |||
| f3556c011c | |||
| ebc510582b | |||
| f3bfdc29e3 | |||
| 6cce3b12ea | |||
| 0273e9739a | |||
| 7c8b883448 | |||
| c2bb418542 | |||
| ed6acbead0 | |||
| 976cce40d7 | |||
| e4fd4158bb | |||
| 31d5dffcef | |||
| d12edee802 | |||
| ac41ed3aae | |||
| d8c1159032 | |||
| c856c5becb | |||
| 50e6b57be0 | |||
| 8b7fdba544 | |||
| 22ae8d0166 | |||
| 23bcc379a8 | |||
| bdc4bfe7b0 | |||
| 025ffe6b50 | |||
| a6595747fa | |||
| d902cc3e7e | |||
| 726eb41359 | |||
| e9714dbfcd | |||
| a3618e761e | |||
| 24eabe7f35 | |||
| ecfa939ea6 | |||
| b48bcc3add | |||
| fa01fa2051 | |||
| fb36eff5e1 | |||
| d24d3d1e8c | |||
| 5c4badbcca | |||
| 2cd1383dc8 | |||
| 72440c101f | |||
| 423d66b07a | |||
| b42adebd51 | |||
| 749b43a3b1 | |||
| 8daaef44ee | |||
| ac07e3cbe6 | |||
| 1a6137b323 | |||
| 85c2e198a4 | |||
| 01263c4cfd | |||
| fbd5e0174d | |||
| 70ccb4ae65 | |||
| 7eb331774d | |||
| 24a3f058a3 | |||
| 84c28f95f9 | |||
| 7af57982fe | |||
| 6b70c5408f | |||
| 74fc725f37 | |||
| a0a74aed60 | |||
| 11feef8c82 | |||
| 9c5ff164ac | |||
| 7edeb1c2d7 | |||
| 8b95abdc85 | |||
| ffe0cd1ef1 | |||
| 5d2111a19f | |||
| 68ac7fd57f | |||
| 7320d96a36 | |||
| ee17fb475b | |||
| 28b877e31f | |||
| 4389b80a52 | |||
| d3bc663951 | |||
| 4810364788 | |||
| 2dcad52dd9 | |||
| 0bf8d80b12 | |||
| e4bba02aec | |||
| 1caa0da657 | |||
| 711c814bb2 | |||
| 5b832eb927 | |||
| 49988431f6 | |||
| 72d65dd51a | |||
| 553bc55b19 | |||
| fc6f69833c | |||
| c7fd06841f | |||
| 4648da6849 | |||
| 0188cf3bb6 | |||
| e0b4f9c047 | |||
| 4895bba96e | |||
| 76d1df817b | |||
| 83d7f415e2 | |||
| ae1149ffaf | |||
| 0148354dbe | |||
| 11b3856334 | |||
| e8f229cd01 | |||
| 75b70e5824 | |||
| 1711f6d8fc | |||
| 20d16abdf4 | |||
| 2411c9fbd0 | |||
| be3e280f2a | |||
| 2afcbe6587 | |||
| 22ff486fbe | |||
| eed0b0415d | |||
| d9d6c56ed5 | |||
| f99a237093 | |||
| fcbf18344c | |||
| bf8cbeb6c5 | |||
| e27e7dd054 | |||
| 8b66cf4341 | |||
| 6f4549bdea | |||
| c654398f75 | |||
| 0664a99945 | |||
| 58abc5731b | |||
| 7498b1e0f1 | |||
| 07a275fea5 | |||
| 1b6263e08d | |||
| 089f1d49c0 | |||
| 01c184c608 | |||
| 1752463ee6 | |||
| c825a2f743 | |||
| ba058dc8d4 | |||
| 04b2f8e062 | |||
| 62b874e14f | |||
| 9c9e9b4e03 | |||
| e3c307ab55 | |||
| b1b2baa969 | |||
| 0452af91cc | |||
| da5cfc42e5 | |||
| eb89223386 | |||
| 93dc3a31b3 | |||
| 345300f110 | |||
| f322c5d202 | |||
| 376d29a78f | |||
| 224d507ab5 | |||
| 1f680d731d | |||
| f0a1cc51b4 | |||
| fee3280799 | |||
| 54925bf1ae | |||
| 91d02a4fc0 | |||
| 086b94038e | |||
| 5d5716b339 | |||
| fb6db454d4 | |||
| e4d4e0d024 | |||
| 17724d961e | |||
| 6776910c93 | |||
| 15962b36f0 | |||
| 3d9a802734 | |||
| 9cd8f8b0cf | |||
| b44330cbc6 | |||
| 3d5ba0873c | |||
| d917cdc3fa | |||
| b370edf329 | |||
| ec59acd329 | |||
| c69e740c56 | |||
| 6cf6ae631c | |||
| 2562244fb6 | |||
| a2691ee163 | |||
| ab700ea546 | |||
| e775afc3f2 | |||
| 92f07824a7 | |||
| b7cfe5bce6 | |||
| 3ccfb28352 | |||
| 325aa51e51 | |||
| d1d9bd6e41 | |||
| 9a71382243 | |||
| b974eea341 | |||
| e82632f83d | |||
| 1a65ead849 | |||
| 50b7d1b7bb | |||
| 09beb72f5b | |||
| 9bbbc67c8e | |||
| b3681bf681 | |||
| b548b1443b | |||
| 0e980d962d | |||
| 3ed6acc6a6 | |||
| 56746c240f | |||
| 5c1c2c7f5b | |||
| a699086f46 | |||
| 454c204112 | |||
| 277468160d | |||
| a0f424e592 | |||
| 3ae832ca28 | |||
| 16ef5dd631 | |||
| c4bd0a5215 | |||
| f5c8ca7dfb | |||
| 36ddec44af | |||
| c147d8a271 | |||
| 1c444d58b6 | |||
| 1f910f7566 | |||
| 99826cff43 | |||
| e8f8bea969 | |||
| 304484b77a | |||
| 29fed77d58 | |||
| db070588c8 | |||
| 76deca7fea | |||
| f326ab86d2 | |||
| ca8d9709e0 | |||
| e0af059221 | |||
| 8bf5b4acfd | |||
| 93a003baa0 | |||
| 5d9b0bd3f0 | |||
| 9a5525e1b3 | |||
| 7dce3d28d3 | |||
| d4c1482c1c | |||
| 3a96a483a6 | |||
| 7467fce2d4 | |||
| 06af08cac4 | |||
| 83ebdfb1c5 | |||
| 835b1ac000 | |||
| f10b41dbc1 | |||
| 41fe871e2f | |||
| 321c39ddc7 | |||
| f7f1af0139 | |||
| a8c9c279d6 | |||
| eece129831 | |||
| 80e4f51a83 | |||
| 22ff0837c3 | |||
| 74d7e05bcb | |||
| 1feb23bb83 | |||
| 08c55ec258 | |||
| 394e797567 | |||
| 6c3e5d08b8 | |||
| 6e19482814 | |||
| 42eb73a08f | |||
| 4b59ffee45 | |||
| d4e853c8b5 | |||
| a94b8ec3d2 | |||
| ed57e6b7be | |||
| 05f006e7e1 | |||
| c3aed72c29 | |||
| 7deba94e6b | |||
| d15811f09f | |||
| 2ef62a93bb | |||
| 9015aea527 | |||
| 4bb401e6f9 | |||
| a87a4d1222 | |||
| d27ad16335 | |||
| 20498a2bce | |||
| 0730140e62 | |||
| 810711d355 | |||
| f3b34b457c | |||
| 6f4b9f3372 | |||
| 01658fdb31 | |||
| 66c26d9cce | |||
| a4060a7914 | |||
| 469e438741 | |||
| 56fabbb4f5 | |||
| dfd8cc1ba4 | |||
| cba54061a2 | |||
| ed467a9889 | |||
| 3c4791007f | |||
| 8f16a179c3 | |||
| ce3a4cac6c | |||
| be46044b98 | |||
| 154c7f8e36 | |||
| 8b6c2b45a6 | |||
| b1a4a74270 | |||
| d7fb095fbd | |||
| 58791d4bdd | |||
| d3b635b193 | |||
| 436bc41f82 | |||
| 834f49275a | |||
| a44e54f9ec | |||
| a51ed8dd70 | |||
| c8cfc6c06d |
@@ -1,79 +0,0 @@
|
||||
const { join } = require("node:path");
|
||||
|
||||
module.exports = {
|
||||
root: true,
|
||||
extends: [
|
||||
"turbo",
|
||||
"prettier",
|
||||
"plugin:@typescript-eslint/recommended-type-checked-only",
|
||||
],
|
||||
parserOptions: {
|
||||
project: join(__dirname, "tsconfig.eslint.json"),
|
||||
__tsconfigRootDir: __dirname,
|
||||
},
|
||||
settings: {
|
||||
react: {
|
||||
version: "999.999.999",
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
"max-params": ["error", 4],
|
||||
"prefer-const": "error",
|
||||
"@typescript-eslint/no-floating-promises": [
|
||||
"error",
|
||||
{
|
||||
ignoreIIFE: true,
|
||||
},
|
||||
],
|
||||
"no-debugger": "error",
|
||||
"@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/"],
|
||||
};
|
||||
@@ -0,0 +1,46 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: ""
|
||||
labels: bug
|
||||
assignees: ""
|
||||
---
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**To Reproduce**
|
||||
Code to reproduce the behavior:
|
||||
|
||||
```ts
|
||||
// paste the code here
|
||||
```
|
||||
|
||||
**Expected behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**Screenshots**
|
||||
If applicable, add screenshots to help explain your problem.
|
||||
|
||||
**Desktop (please complete the following information):**
|
||||
|
||||
- OS: [e.g. macOS, Linux]
|
||||
- JS Runtime / Framework / Bundler (select all applicable)
|
||||
- [ ] Node.js
|
||||
- [ ] Deno
|
||||
- [ ] Bun
|
||||
- [ ] Next.js
|
||||
- [ ] ESBuild
|
||||
- [ ] Rollup
|
||||
- [ ] Webpack
|
||||
- [ ] Turbopack
|
||||
- [ ] Vite
|
||||
- [ ] Waku
|
||||
- [ ] Edge Runtime
|
||||
- [ ] AWS Lambda
|
||||
- [ ] Cloudflare Worker
|
||||
- [ ] Others (please elaborate on this)
|
||||
- Version [e.g. 22]
|
||||
|
||||
**Additional context**
|
||||
Add any other context about the problem here.
|
||||
@@ -13,7 +13,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v3
|
||||
- uses: pnpm/action-setup@v4
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
name: Publish Preview
|
||||
on: [pull_request]
|
||||
|
||||
jobs:
|
||||
pre_release:
|
||||
name: Pre Release
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout Repo
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
|
||||
- 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
|
||||
|
||||
- name: Pre Release
|
||||
run: pnpx pkg-pr-new publish --pnpm ./packages/* ./packages/providers/* ./packages/providers/storage/*
|
||||
@@ -1,36 +0,0 @@
|
||||
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 }}
|
||||
@@ -12,7 +12,7 @@ jobs:
|
||||
- name: Checkout Repo
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v3
|
||||
- uses: pnpm/action-setup@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
@@ -26,12 +26,12 @@ jobs:
|
||||
- name: Build tarball
|
||||
run: |
|
||||
pnpm pack
|
||||
working-directory: packages/core
|
||||
working-directory: packages/llamaindex
|
||||
|
||||
- name: Create release
|
||||
uses: ncipollo/release-action@v1
|
||||
with:
|
||||
artifacts: "packages/core/llamaindex-*.tgz"
|
||||
artifacts: "packages/llamaindex/llamaindex-*.tgz"
|
||||
name: Release ${{ github.ref }}
|
||||
bodyFile: "packages/core/CHANGELOG.md"
|
||||
bodyFile: "packages/llamaindex/CHANGELOG.md"
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
@@ -15,7 +15,7 @@ jobs:
|
||||
- name: Checkout Repo
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v3
|
||||
- uses: pnpm/action-setup@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
@@ -55,3 +55,16 @@ jobs:
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
|
||||
# Refs: https://github.com/changesets/changesets/issues/421
|
||||
- name: Update lock file
|
||||
continue-on-error: true
|
||||
run: pnpm install --lockfile-only
|
||||
|
||||
- name: Commit lock file
|
||||
continue-on-error: true
|
||||
uses: stefanzweifel/git-auto-commit-action@v5
|
||||
with:
|
||||
commit_message: "chore: update lock file"
|
||||
branch: changeset-release/main
|
||||
file_pattern: "pnpm-lock.yaml"
|
||||
|
||||
+81
-29
@@ -12,19 +12,33 @@ concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
POSTGRES_HOST_AUTH_METHOD: trust
|
||||
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
|
||||
TURBO_TEAM: ${{ vars.TURBO_TEAM }}
|
||||
TURBO_REMOTE_ONLY: true
|
||||
|
||||
jobs:
|
||||
e2e:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
node-version: [18.x, 20.x, 22.x]
|
||||
node-version: [18.x, 20.x, 22.x, 23.x]
|
||||
name: E2E on Node.js ${{ matrix.node-version }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v3
|
||||
|
||||
- uses: ankane/setup-postgres@v1
|
||||
with:
|
||||
database: llamaindex_node_test
|
||||
dev-files: true
|
||||
- run: |
|
||||
cd /tmp
|
||||
git clone --branch v0.7.0 https://github.com/pgvector/pgvector.git
|
||||
cd pgvector
|
||||
make
|
||||
sudo make install
|
||||
- uses: pnpm/action-setup@v4
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
@@ -39,13 +53,12 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
node-version: [18.x, 20.x, 22.x]
|
||||
node-version: [18.x, 20.x, 22.x, 23.x]
|
||||
name: Test on Node.js ${{ matrix.node-version }}
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v3
|
||||
- uses: pnpm/action-setup@v4
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
@@ -60,7 +73,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v3
|
||||
- uses: pnpm/action-setup@v4
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
@@ -70,20 +83,11 @@ jobs:
|
||||
run: pnpm install
|
||||
- name: Build
|
||||
run: pnpm run build
|
||||
- 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 dlx turbo run circular-check
|
||||
- uses: actions/upload-artifact@v3
|
||||
if: failure()
|
||||
with:
|
||||
name: typecheck-build-dist
|
||||
path: ./packages/core/dist
|
||||
if-no-files-found: error
|
||||
e2e-core-examples:
|
||||
run: pnpm run circular-check
|
||||
e2e-llamaindex-examples:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -91,12 +95,15 @@ jobs:
|
||||
- cloudflare-worker-agent
|
||||
- nextjs-agent
|
||||
- nextjs-edge-runtime
|
||||
- nextjs-node-runtime
|
||||
- waku-query-engine
|
||||
- llama-parse-browser
|
||||
- vite-import-llamaindex
|
||||
runs-on: ubuntu-latest
|
||||
name: Build Core Example (${{ matrix.packages }})
|
||||
name: Build LlamaIndex Example (${{ matrix.packages }})
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v3
|
||||
- uses: pnpm/action-setup@v4
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
@@ -108,14 +115,38 @@ jobs:
|
||||
run: pnpm run build
|
||||
- name: Build ${{ matrix.packages }}
|
||||
run: pnpm run build
|
||||
working-directory: packages/core/e2e/examples/${{ matrix.packages }}
|
||||
working-directory: e2e/examples/${{ matrix.packages }}
|
||||
|
||||
size-limit:
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event_name == 'pull_request'
|
||||
name: Size Limit
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
- 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
|
||||
- uses: andresz1/size-limit-action@94bc357df29c36c8f8d50ea497c3e225c3c95d1d
|
||||
with:
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
directory: e2e/examples/vite-import-llamaindex
|
||||
skip_step: "install"
|
||||
build_script: build
|
||||
package_manager: pnpm
|
||||
|
||||
typecheck-examples:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v3
|
||||
- uses: pnpm/action-setup@v4
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
@@ -127,15 +158,36 @@ jobs:
|
||||
run: pnpm run build
|
||||
- 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: Pack packages
|
||||
run: |
|
||||
for dir in packages/*; do
|
||||
if [ -d "$dir" ] && [ -f "$dir/package.json" ] && [[ ! "$dir" =~ autotool ]]; then
|
||||
echo "Packing $dir"
|
||||
pnpm pack --pack-destination ${{ runner.temp }} -C $dir
|
||||
else
|
||||
echo "Skipping $dir, no package.json found"
|
||||
fi
|
||||
done
|
||||
- name: Pack provider packages
|
||||
run: |
|
||||
for dir in packages/providers/* packages/providers/storage/*; do
|
||||
if [ -d "$dir" ] && [ -f "$dir/package.json" ]; then
|
||||
echo "Packing $dir"
|
||||
pnpm pack --pack-destination ${{ runner.temp }} -C $dir
|
||||
else
|
||||
echo "Skipping $dir, no package.json found"
|
||||
fi
|
||||
done
|
||||
- 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
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: failure()
|
||||
with:
|
||||
name: build-dist
|
||||
path: |
|
||||
${{ runner.temp }}/*.tgz
|
||||
if-no-files-found: error
|
||||
|
||||
@@ -48,3 +48,6 @@ playwright/.cache/
|
||||
|
||||
# intellij
|
||||
**/.idea
|
||||
|
||||
# generated API
|
||||
packages/cloud/src/client
|
||||
|
||||
+1
-3
@@ -1,3 +1 @@
|
||||
pnpm format
|
||||
pnpm lint
|
||||
npx lint-staged
|
||||
pnpm run lint-staged
|
||||
|
||||
@@ -4,3 +4,6 @@ pnpm-lock.yaml
|
||||
lib/
|
||||
dist/
|
||||
.docusaurus/
|
||||
.source/
|
||||
# prttier doesn't support mdx3 we are using
|
||||
*.mdx
|
||||
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
LlamaIndexTS
|
||||
Vendored
+3
-1
@@ -13,5 +13,7 @@
|
||||
},
|
||||
"[json]": {
|
||||
"editor.defaultFormatter": "esbenp.prettier-vscode"
|
||||
}
|
||||
},
|
||||
"prettier.prettierPath": "./node_modules/prettier",
|
||||
"prettier.configPath": "prettier.config.mjs"
|
||||
}
|
||||
|
||||
+38
-59
@@ -2,86 +2,65 @@
|
||||
|
||||
## Structure
|
||||
|
||||
This is a monorepo built with Turborepo
|
||||
LlamaIndex.TS uses pnpm monorepo.
|
||||
|
||||
Right now there are two packages of importance:
|
||||
We recommend you to understand the basics of Node.js, TypeScript, pnpm, and of course, LLM before contributing.
|
||||
|
||||
packages/core which is the main NPM library llamaindex
|
||||
There are some important folders in the repository:
|
||||
|
||||
examples is where the demo code lives
|
||||
|
||||
### Turborepo docs
|
||||
|
||||
You can checkout how Turborepo works using the default [README-turborepo.md](/README-turborepo.md)
|
||||
- `packages/*`: Contains the source code of the packages. Each package is a separate npm package.
|
||||
- `llamaindex`: The starter package for LlamaIndex.TS, which contains the all sub-packages.
|
||||
- `core`: The core package of LlamaIndex.TS, which contains the abstract classes and interfaces. It is designed for
|
||||
all JS runtime environments.
|
||||
- `env`: The environment package of LlamaIndex.TS, which contains the environment-specific classes and interfaces. It
|
||||
includes compatibility layers for Node.js, Deno, Vercel Edge Runtime, Cloudflare Workers...
|
||||
- `apps/*`: The applications based on LlamaIndex.TS.
|
||||
- `next`: Our documentation website based on Next.js.
|
||||
- `examples`: The code examples of LlamaIndex.TS using Node.js.
|
||||
|
||||
## Getting Started
|
||||
|
||||
Install NodeJS. Preferably v18 using nvm or n.
|
||||
|
||||
Inside the LlamaIndexTS directory:
|
||||
Make sure you have Node.js LIS (Long-term Support) installed. You can check your Node.js version by running:
|
||||
|
||||
```shell
|
||||
node -v
|
||||
# v20.x.x
|
||||
```
|
||||
npm i -g pnpm ts-node
|
||||
|
||||
### Use pnpm
|
||||
|
||||
```shell
|
||||
corepack enable
|
||||
```
|
||||
|
||||
### Install dependencies
|
||||
|
||||
```shell
|
||||
pnpm install
|
||||
```
|
||||
|
||||
Note: we use pnpm in this repo, which has a lot of the same functionality and CLI options as npm but it does do some things better in a monorepo, like centralizing dependencies and caching.
|
||||
### Build the packages
|
||||
|
||||
PNPM's has documentation on its [workspace feature](https://pnpm.io/workspaces) and Turborepo had some [useful documentation also](https://turbo.build/repo/docs/core-concepts/monorepos/running-tasks).
|
||||
You'll need Turbo to build the packages. If you don't have it, you can run it with `pnpx`.
|
||||
|
||||
### Running Typescript
|
||||
To build all packages, run:
|
||||
|
||||
When we publish to NPM we will have a tsc compiled version of the library in JS. For now, the easiest thing to do is use ts-node.
|
||||
```shell
|
||||
# Build all packages
|
||||
pnpx turbo build --filter "./packages/*"
|
||||
|
||||
### Test cases
|
||||
|
||||
To run them, run
|
||||
|
||||
```
|
||||
pnpm run test
|
||||
```
|
||||
|
||||
To write new test cases write them in [packages/core/src/tests](/packages/core/src/tests)
|
||||
|
||||
We use Jest https://jestjs.io/ to write our test cases. Jest comes with a bunch of built in assertions using the expect function: https://jestjs.io/docs/expect
|
||||
|
||||
### Demo applications
|
||||
|
||||
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
|
||||
|
||||
### Installing packages
|
||||
|
||||
To install packages for a specific package or demo application, run
|
||||
|
||||
```
|
||||
pnpm add [NPM Package] --filter [package or application i.e. core or docs]
|
||||
```
|
||||
|
||||
To install packages for every package or application run
|
||||
|
||||
```
|
||||
pnpm add -w [NPM Package]
|
||||
# Or if you have turbo installed, you can run:
|
||||
turbo build --filter "./packages/*"
|
||||
```
|
||||
|
||||
### Docs
|
||||
|
||||
To contribute to the docs, go to the docs website folder and run the Docusaurus instance.
|
||||
|
||||
```bash
|
||||
cd apps/docs
|
||||
pnpm install
|
||||
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.
|
||||
See the [docs](./apps/next/README.md) for more information.
|
||||
|
||||
## Changeset
|
||||
|
||||
We use [changesets](https://github.com/changesets/changesets) for managing versions and changelogs. To create a new changeset, run:
|
||||
We use [changesets](https://github.com/changesets/changesets) for managing versions and changelogs. To create a new
|
||||
changeset, run in the root folder:
|
||||
|
||||
```
|
||||
pnpm changeset
|
||||
@@ -95,6 +74,6 @@ The [Release Github Action](.github/workflows/release.yml) is automatically gene
|
||||
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.
|
||||
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,13 +1,17 @@
|
||||
# LlamaIndex.TS
|
||||
<p align="center">
|
||||
<img height="100" width="100" alt="LlamaIndex logo" src="https://ts.llamaindex.ai/square.svg" />
|
||||
</p>
|
||||
<h1 align="center">LlamaIndex.TS</h1>
|
||||
<h3 align="center">
|
||||
Data framework for your LLM application.
|
||||
</h3>
|
||||
|
||||
[](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.
|
||||
Use your own data with large language models (LLMs, OpenAI ChatGPT and others) in JS runtime environments with TypeScript support.
|
||||
|
||||
Documentation: https://ts.llamaindex.ai/
|
||||
|
||||
@@ -19,173 +23,58 @@ Try examples online:
|
||||
|
||||
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.
|
||||
|
||||
## Multiple JS Environment Support
|
||||
## Compatibility
|
||||
|
||||
### Multiple JS Environment Support
|
||||
|
||||
LlamaIndex.TS supports multiple JS environments, including:
|
||||
|
||||
- Node.js (18, 20, 22) ✅
|
||||
- Node.js >= 20 ✅
|
||||
- Deno ✅
|
||||
- Bun ✅
|
||||
- React Server Components (Next.js) ✅
|
||||
- Nitro ✅
|
||||
- Vercel Edge Runtime ✅ (with some limitations)
|
||||
- Cloudflare Workers ✅ (with some limitations)
|
||||
|
||||
For now, browser support is limited due to the lack of support for [AsyncLocalStorage-like APIs](https://github.com/tc39/proposal-async-context)
|
||||
|
||||
### Supported LLMs:
|
||||
|
||||
- OpenAI LLms
|
||||
- Anthropic LLms
|
||||
- Groq LLMs
|
||||
- Llama2, Llama3, Llama3.1 LLMs
|
||||
- MistralAI LLMs
|
||||
- Fireworks LLMs
|
||||
- DeepSeek LLMs
|
||||
- ReplicateAI LLMs
|
||||
- TogetherAI LLMs
|
||||
- HuggingFace LLms
|
||||
- DeepInfra LLMs
|
||||
- Gemini LLMs
|
||||
|
||||
## Getting started
|
||||
|
||||
```shell
|
||||
npm install llamaindex
|
||||
pnpm install llamaindex
|
||||
yarn add llamaindex
|
||||
jsr install @llamaindex/core
|
||||
```
|
||||
|
||||
### Node.js
|
||||
### Setup in Node.js, Deno, Bun, TypeScript...?
|
||||
|
||||
```ts
|
||||
import fs from "fs/promises";
|
||||
import { Document, VectorStoreIndex } from "llamaindex";
|
||||
See our official document: <https://ts.llamaindex.ai/docs/llamaindex/getting_started/>
|
||||
|
||||
async function main() {
|
||||
// Load essay from abramov.txt in Node
|
||||
const essay = await fs.readFile(
|
||||
"node_modules/llamaindex/examples/abramov.txt",
|
||||
"utf-8",
|
||||
);
|
||||
### Adding provider packages
|
||||
|
||||
// Create Document object with essay
|
||||
const document = new Document({ text: essay });
|
||||
In most cases, you'll also need to install provider packages to use LlamaIndexTS. These are for adding AI models, file readers for ingestion or storing documents, e.g. in vector databases.
|
||||
|
||||
// Split text and create embeddings. Store them in a VectorStoreIndex
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
For example, to use the OpenAI LLM, you would install the following package:
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine();
|
||||
const response = await queryEngine.query({
|
||||
query: "What did the author do in college?",
|
||||
});
|
||||
|
||||
// Output response
|
||||
console.log(response.toString());
|
||||
}
|
||||
|
||||
main();
|
||||
```
|
||||
|
||||
```bash
|
||||
# `pnpm install tsx` before running the script
|
||||
node --import tsx ./main.ts
|
||||
```
|
||||
|
||||
### Next.js
|
||||
|
||||
First, you will need to add a llamaindex plugin to your Next.js project.
|
||||
|
||||
```js
|
||||
// next.config.js
|
||||
const withLlamaIndex = require("llamaindex/next");
|
||||
|
||||
module.exports = withLlamaIndex({
|
||||
// your next.js config
|
||||
});
|
||||
```
|
||||
|
||||
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);
|
||||
},
|
||||
};
|
||||
```shell
|
||||
npm install @llamaindex/openai
|
||||
pnpm install @llamaindex/openai
|
||||
yarn add @llamaindex/openai
|
||||
```
|
||||
|
||||
## Playground
|
||||
@@ -194,71 +83,25 @@ Check out our NextJS playground at https://llama-playground.vercel.app/. The sou
|
||||
|
||||
## Core concepts for getting started:
|
||||
|
||||
- [Document](/packages/core/src/Node.ts): A document represents a text file, PDF file or other contiguous piece of data.
|
||||
- [Document](/packages/llamaindex/src/Node.ts): A document represents a text file, PDF file or other contiguous piece of data.
|
||||
|
||||
- [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.
|
||||
- [Node](/packages/llamaindex/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/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)).
|
||||
- [Embedding](/packages/llamaindex/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 question. Because the default service context is OpenAI, the default embedding is `OpenAIEmbedding`. If using different models, say through Ollama, use this [Embedding](/packages/llamaindex/src/embeddings/OllamaEmbedding.ts) (see all [here](/packages/llamaindex/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.
|
||||
- [Indices](/packages/llamaindex/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/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).
|
||||
- [QueryEngine](/packages/llamaindex/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/llamaindex/src/indices/BaseIndex.ts) method on your Index. See all query engines [here](/packages/llamaindex/src/engines/query).
|
||||
|
||||
- [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).
|
||||
- [ChatEngine](/packages/llamaindex/src/engines/chat/SimpleChatEngine.ts): A ChatEngine helps you build a chatbot that will interact with your Indices. See all chat engines [here](/packages/llamaindex/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.
|
||||
|
||||
## Tips when using in non-Node.js environments
|
||||
|
||||
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.
|
||||
|
||||
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";
|
||||
```
|
||||
|
||||
As the `PDFReader` is not working with the Edge runtime, here's how to use the `SimpleDirectoryReader` with the `LlamaParseReader` to load PDFs:
|
||||
|
||||
```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 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
|
||||
- [SimplePrompt](/packages/llamaindex/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.
|
||||
|
||||
## Contributing:
|
||||
|
||||
We are in the very early days of LlamaIndex.TS. If you’re interested in hacking on it with us check out our [contributing guide](/CONTRIBUTING.md)
|
||||
Please see our [contributing guide](CONTRIBUTING.md) for more information.
|
||||
You are highly encouraged to contribute to LlamaIndex.TS!
|
||||
|
||||
## Bugs? Questions?
|
||||
## Community
|
||||
|
||||
Please join our Discord! https://discord.com/invite/eN6D2HQ4aX
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
# Dependencies
|
||||
/node_modules
|
||||
|
||||
# Production
|
||||
/build
|
||||
|
||||
# Generated files
|
||||
.docusaurus
|
||||
.cache-loader
|
||||
lib
|
||||
|
||||
# Misc
|
||||
.DS_Store
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
@@ -1,210 +0,0 @@
|
||||
# docs
|
||||
|
||||
## 0.0.25
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [6bc5bdd]
|
||||
- Updated dependencies [bf25ff6]
|
||||
- Updated dependencies [e6d6576]
|
||||
- llamaindex@0.3.17
|
||||
|
||||
## 0.0.24
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 631f000: feat: DeepInfra LLM implementation
|
||||
- 8832669: Community bedrock support added
|
||||
- a29d835: setDocumentHash should be async
|
||||
- Updated dependencies [11ae926]
|
||||
- Updated dependencies [631f000]
|
||||
- Updated dependencies [1378ec4]
|
||||
- Updated dependencies [6b1ded4]
|
||||
- Updated dependencies [4d4bd85]
|
||||
- Updated dependencies [24a9d1e]
|
||||
- Updated dependencies [45952de]
|
||||
- Updated dependencies [54230f0]
|
||||
- Updated dependencies [a29d835]
|
||||
- Updated dependencies [73819bf]
|
||||
- llamaindex@0.3.16
|
||||
|
||||
## 0.0.23
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [6e156ed]
|
||||
- Updated dependencies [265976d]
|
||||
- Updated dependencies [8e26f75]
|
||||
- llamaindex@0.3.15
|
||||
|
||||
## 0.0.22
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [6ff7576]
|
||||
- Updated dependencies [94543de]
|
||||
- llamaindex@0.3.14
|
||||
|
||||
## 0.0.21
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [1b1081b]
|
||||
- Updated dependencies [37525df]
|
||||
- Updated dependencies [660a2b3]
|
||||
- Updated dependencies [a1f2475]
|
||||
- llamaindex@0.3.13
|
||||
|
||||
## 0.0.20
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [34fb1d8]
|
||||
- llamaindex@0.3.12
|
||||
|
||||
## 0.0.19
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [e072c45]
|
||||
- Updated dependencies [9e133ac]
|
||||
- Updated dependencies [447105a]
|
||||
- Updated dependencies [320be3f]
|
||||
- llamaindex@0.3.11
|
||||
|
||||
## 0.0.18
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [4aba02e]
|
||||
- llamaindex@0.3.10
|
||||
|
||||
## 0.0.17
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [c3747d0]
|
||||
- llamaindex@0.3.9
|
||||
|
||||
## 0.0.16
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [ce94780]
|
||||
- llamaindex@0.3.8
|
||||
|
||||
## 0.0.15
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [b6a6606]
|
||||
- Updated dependencies [b6a6606]
|
||||
- llamaindex@0.3.7
|
||||
|
||||
## 0.0.14
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [efa326a]
|
||||
- llamaindex@0.3.6
|
||||
|
||||
## 0.0.13
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [bc7a11c]
|
||||
- Updated dependencies [2fe2b81]
|
||||
- Updated dependencies [5596e31]
|
||||
- Updated dependencies [e74fe88]
|
||||
- Updated dependencies [be5df5b]
|
||||
- llamaindex@0.3.5
|
||||
|
||||
## 0.0.12
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [1dce275]
|
||||
- Updated dependencies [d10533e]
|
||||
- Updated dependencies [2008efe]
|
||||
- Updated dependencies [5e61934]
|
||||
- Updated dependencies [9e74a43]
|
||||
- Updated dependencies [ee719a1]
|
||||
- llamaindex@0.3.4
|
||||
|
||||
## 0.0.11
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [e8c41c5]
|
||||
- llamaindex@0.3.3
|
||||
|
||||
## 0.0.10
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [61103b6]
|
||||
- llamaindex@0.3.2
|
||||
|
||||
## 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
|
||||
@@ -1,47 +0,0 @@
|
||||
# Website
|
||||
|
||||
This website is built using [Docusaurus 2](https://docusaurus.io/), a modern static website generator.
|
||||
|
||||
### Installation
|
||||
|
||||
```
|
||||
$ pnpm
|
||||
```
|
||||
|
||||
### Local Development
|
||||
|
||||
```
|
||||
$ pnpm start
|
||||
```
|
||||
|
||||
This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server.
|
||||
|
||||
However, the searchbar may not function with `yarn start`. Instead, run `yarn build` and launch a server:
|
||||
|
||||
```
|
||||
$ npx http-server ./build
|
||||
```
|
||||
|
||||
### Build
|
||||
|
||||
```
|
||||
$ pnpm build
|
||||
```
|
||||
|
||||
This command generates static content into the `build` directory and can be served using any static contents hosting service.
|
||||
|
||||
### Deployment
|
||||
|
||||
Using SSH:
|
||||
|
||||
```
|
||||
$ USE_SSH=true pnpm deploy
|
||||
```
|
||||
|
||||
Not using SSH:
|
||||
|
||||
```
|
||||
$ GIT_USER=<Your GitHub username> pnpm deploy
|
||||
```
|
||||
|
||||
If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch.
|
||||
@@ -1,3 +0,0 @@
|
||||
module.exports = {
|
||||
presets: [require.resolve("@docusaurus/core/lib/babel/preset")],
|
||||
};
|
||||
@@ -1,493 +0,0 @@
|
||||
---
|
||||
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, enqueueOutput) => {
|
||||
const { llm, stream } = step.context;
|
||||
// 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 */
|
||||
enqueueOutput({
|
||||
taskStep: step,
|
||||
output: response,
|
||||
isLast: !shouldContinue,
|
||||
});
|
||||
if (shouldContinue) {
|
||||
const content = await someHeavyFunctionCall();
|
||||
// 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,
|
||||
role: "user",
|
||||
},
|
||||
];
|
||||
}
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
### 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.
|
||||
|
||||
For now, you can install llamaindex and directly import it into your existing Next.js, Deno or Cloudflare Worker project
|
||||
**without any extra configuration**.
|
||||
|
||||
#### [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.
|
Before Width: | Height: | Size: 178 KiB |
@@ -1 +0,0 @@
|
||||
api/
|
||||
@@ -1,2 +0,0 @@
|
||||
label: Examples
|
||||
position: 3
|
||||
@@ -1,10 +0,0 @@
|
||||
# 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>
|
||||
@@ -1,12 +0,0 @@
|
||||
---
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
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>
|
||||
@@ -1,77 +0,0 @@
|
||||
# Local LLMs
|
||||
|
||||
LlamaIndex.TS supports OpenAI and [other remote LLM APIs](other_llms). You can also run a local LLM on your machine!
|
||||
|
||||
## Using a local model via Ollama
|
||||
|
||||
The easiest way to run a local LLM is via the great work of our friends at [Ollama](https://ollama.com/), who provide a simple to use client that will download, install and run a [growing range of models](https://ollama.com/library) for you.
|
||||
|
||||
### Install Ollama
|
||||
|
||||
They provide a one-click installer for Mac, Linux and Windows on their [home page](https://ollama.com/).
|
||||
|
||||
### Pick and run a model
|
||||
|
||||
Since we're going to be doing agentic work, we'll need a very capable model, but the largest models are hard to run on a laptop. We think `mixtral 8x7b` is a good balance between power and resources, but `llama3` is another great option. You can run Mixtral by running
|
||||
|
||||
```bash
|
||||
ollama run mixtral:8x7b
|
||||
```
|
||||
|
||||
The first time you run it will also automatically download and install the model for you.
|
||||
|
||||
### Switch the LLM in your code
|
||||
|
||||
To tell LlamaIndex to use a local LLM, use the `Settings` object:
|
||||
|
||||
```javascript
|
||||
Settings.llm = new Ollama({
|
||||
model: "mixtral:8x7b",
|
||||
});
|
||||
```
|
||||
|
||||
### Use local embeddings
|
||||
|
||||
If you're doing retrieval-augmented generation, LlamaIndex.TS will also call out to OpenAI to index and embed your data. To be entirely local, you can use a local embedding model like this:
|
||||
|
||||
```javascript
|
||||
Settings.embedModel = new HuggingFaceEmbedding({
|
||||
modelType: "BAAI/bge-small-en-v1.5",
|
||||
quantized: false,
|
||||
});
|
||||
```
|
||||
|
||||
The first time this runs it will download the embedding model to run it.
|
||||
|
||||
### Try it out
|
||||
|
||||
With a local LLM and local embeddings in place, you can perform RAG as usual and everything will happen on your machine without calling an API:
|
||||
|
||||
```typescript
|
||||
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 });
|
||||
|
||||
// Split text and create embeddings. Store them in a VectorStoreIndex
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const response = await queryEngine.query({
|
||||
query: "What did the author do in college?",
|
||||
});
|
||||
|
||||
// Output response
|
||||
console.log(response.toString());
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
```
|
||||
|
||||
You can see the [full example file](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/vectorIndexLocal.ts).
|
||||
@@ -1,41 +0,0 @@
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../examples/mistral";
|
||||
|
||||
# Using other LLM APIs
|
||||
|
||||
By default LlamaIndex.TS uses OpenAI's LLMs and embedding models, but we support [lots of other LLMs](../modules/llms) including models from Mistral (Mistral, Mixtral), Anthropic (Claude) and Google (Gemini).
|
||||
|
||||
If you don't want to use an API at all you can [run a local model](../../examples/local_llm)
|
||||
|
||||
## Using another LLM
|
||||
|
||||
You can specify what LLM LlamaIndex.TS will use on the `Settings` object, like this:
|
||||
|
||||
```typescript
|
||||
import { MistralAI, Settings } from "llamaindex";
|
||||
|
||||
Settings.llm = new MistralAI({
|
||||
model: "mistral-tiny",
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
```
|
||||
|
||||
You can see examples of other APIs we support by checking out "Available LLMs" in the sidebar of our [LLMs section](../modules/llms).
|
||||
|
||||
## Using another embedding model
|
||||
|
||||
A frequent gotcha when trying to use a different API as your LLM is that LlamaIndex will also by default index and embed your data using OpenAI's embeddings. To completely switch away from OpenAI you will need to set your embedding model as well, for example:
|
||||
|
||||
```typescript
|
||||
import { MistralAIEmbedding, Settings } from "llamaindex";
|
||||
|
||||
Settings.embedModel = new MistralAIEmbedding();
|
||||
```
|
||||
|
||||
We support [many different embeddings](../modules/embeddings).
|
||||
|
||||
## Full example
|
||||
|
||||
This example uses Mistral's `mistral-tiny` model as the LLM and Mistral for embeddings as well.
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
@@ -1,10 +0,0 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../examples/storageContext";
|
||||
|
||||
# Save/Load an Index
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
@@ -1,10 +0,0 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../examples/summaryIndex";
|
||||
|
||||
# Summary Index
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
@@ -1,10 +0,0 @@
|
||||
---
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../examples/vectorIndex";
|
||||
|
||||
# Vector Index
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
@@ -1,2 +0,0 @@
|
||||
label: Getting Started
|
||||
position: 1
|
||||
@@ -1,78 +0,0 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
# Concepts
|
||||
|
||||
LlamaIndex.TS helps you build LLM-powered applications (e.g. Q&A, chatbot) over custom data.
|
||||
|
||||
In this high-level concepts guide, you will learn:
|
||||
|
||||
- how an LLM can answer questions using your own data.
|
||||
- key concepts and modules in LlamaIndex.TS for composing your own query pipeline.
|
||||
|
||||
## Answering Questions Across Your Data
|
||||
|
||||
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).
|
||||
|
||||
LlamaIndex.TS provides the essential toolkit for making both steps super easy.
|
||||
|
||||
Let's explore each stage in detail.
|
||||
|
||||
### Indexing Stage
|
||||
|
||||
LlamaIndex.TS help you prepare the knowledge base with a suite of data connectors and indexes.
|
||||
|
||||

|
||||
|
||||
[**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/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/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.
|
||||
|
||||
### Querying Stage
|
||||
|
||||
In the querying stage, the query pipeline retrieves the most relevant context given a user query,
|
||||
and pass that to the LLM (along with the query) to synthesize a response.
|
||||
|
||||
This gives the LLM up-to-date knowledge that is not in its original training data,
|
||||
(also reducing hallucination).
|
||||
|
||||
The key challenge in the querying stage is retrieval, orchestration, and reasoning over (potentially many) knowledge bases.
|
||||
|
||||
LlamaIndex provides composable modules that help you build and integrate RAG pipelines for Q&A (query engine), chatbot (chat engine), or as part of an agent.
|
||||
|
||||
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/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/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/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/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).
|
||||
@@ -1,15 +0,0 @@
|
||||
---
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
# Environments
|
||||
|
||||
We support Node.JS versions 18, 20 and 22, with experimental support for Deno, Bun and Vercel Edge functions.
|
||||
|
||||
## 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
|
||||
```
|
||||
@@ -1,34 +0,0 @@
|
||||
---
|
||||
sidebar_position: 0
|
||||
---
|
||||
|
||||
# Installation and Setup
|
||||
|
||||
We support Node.JS versions 18, 20 and 22, with experimental support for Deno, Bun and Vercel Edge functions.
|
||||
|
||||
## Installation from NPM
|
||||
|
||||
```bash npm2yarn
|
||||
npm install llamaindex
|
||||
```
|
||||
|
||||
### Environment variables
|
||||
|
||||
Our examples use OpenAI by default. You can use [other LLMs](../examples/other_llms) via their APIs; if you would prefer to use local models check out our [local LLM example](../examples/local_llm).
|
||||
|
||||
To use OpenAI, you'll need to [get an OpenAI API key](https://platform.openai.com/account/api-keys) and then make it available as an environment variable this way:
|
||||
|
||||
```bash
|
||||
export OPENAI_API_KEY="sk-......" # Replace with your key
|
||||
```
|
||||
|
||||
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. GitHub automatically invalidates OpenAI keys checked in by accident.
|
||||
|
||||
## What next?
|
||||
|
||||
- The easiest way to started is to [build a full-stack chat app with `create-llama`](starter_tutorial/chatbot).
|
||||
- Try our other [getting started tutorials](starter_tutorial/retrieval_augmented_generation)
|
||||
- Learn more about the [high level concepts](concepts) behind how LlamaIndex works
|
||||
- Check out our [many examples](../examples/more_examples) of LlamaIndex.TS in action
|
||||
@@ -1,2 +0,0 @@
|
||||
label: Starter Tutorials
|
||||
position: 1
|
||||
@@ -1,49 +0,0 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../../examples/agent/openai";
|
||||
|
||||
# Agent tutorial
|
||||
|
||||
We have a comprehensive, step-by-step [guide to building agents in LlamaIndex.TS](../../guides/agents/setup) that we recommend to learn what agents are and how to build them for production. But building a basic agent is simple:
|
||||
|
||||
## Set up
|
||||
|
||||
In a new folder:
|
||||
|
||||
```bash npm2yarn
|
||||
npm init
|
||||
npm install -D typescript @types/node
|
||||
```
|
||||
|
||||
## Run agent
|
||||
|
||||
Create the file `example.ts`. This code will:
|
||||
|
||||
- Create two tools for use by the agent:
|
||||
- A `sumNumbers` tool that adds two numbers
|
||||
- A `divideNumbers` tool that divides numbers
|
||||
-
|
||||
- Give an example of the data structure we wish to generate
|
||||
- Prompt the LLM with instructions and the example, plus a sample transcript
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
|
||||
To run the code:
|
||||
|
||||
```bash
|
||||
npx tsx example.ts
|
||||
```
|
||||
|
||||
You should expect output something like:
|
||||
|
||||
```
|
||||
{
|
||||
content: 'The sum of 5 + 5 is 10. When you divide 10 by 2, you get 5.',
|
||||
role: 'assistant',
|
||||
options: {}
|
||||
}
|
||||
Done
|
||||
```
|
||||
@@ -1,58 +0,0 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../../examples/vectorIndex";
|
||||
import TSConfigSource from "!!raw-loader!../../../../../examples/tsconfig.json";
|
||||
|
||||
# Retrieval Augmented Generation (RAG) Tutorial
|
||||
|
||||
One of the most common use-cases for LlamaIndex is Retrieval-Augmented Generation or RAG, in which your data is indexed and selectively retrieved to be given to an LLM as source material for responding to a query. You can learn more about the [concepts behind RAG](../concepts).
|
||||
|
||||
## Set up the project
|
||||
|
||||
In a new folder, run:
|
||||
|
||||
```bash npm2yarn
|
||||
npm init
|
||||
npm install -D typescript @types/node
|
||||
```
|
||||
|
||||
Then, check out the [installation](../installation) steps to install LlamaIndex.TS and prepare an OpenAI key.
|
||||
|
||||
You can use [other LLMs](../examples/other_llms) via their APIs; if you would prefer to use local models check out our [local LLM example](../../examples/local_llm).
|
||||
|
||||
## Run queries
|
||||
|
||||
Create the file `example.ts`. This code will
|
||||
|
||||
- load an example file
|
||||
- convert it into a Document object
|
||||
- index it (which creates embeddings using OpenAI)
|
||||
- create a 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
|
||||
```
|
||||
|
||||
You should expect output something like:
|
||||
|
||||
```
|
||||
In college, the author studied subjects like linear algebra and physics, but did not find them particularly interesting. They started slacking off, skipping lectures, and eventually stopped attending classes altogether. They also had a negative experience with their English classes, where they were required to pay for catch-up training despite getting verbal approval to skip most of the classes. Ultimately, the author lost motivation for college due to their job as a software developer and stopped attending classes, only returning years later to pick up their papers.
|
||||
|
||||
0: Score: 0.8305309270895813 - I started this decade as a first-year college stud...
|
||||
|
||||
|
||||
1: Score: 0.8286388215713089 - A short digression. I’m not saying colleges are wo...
|
||||
```
|
||||
|
||||
Once you've mastered basic RAG, you may want to consider [chatting with your data](chatbot).
|
||||
@@ -1,52 +0,0 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../../examples/jsonExtract";
|
||||
|
||||
# Structured data extraction tutorial
|
||||
|
||||
Make sure you have installed LlamaIndex.TS and have an OpenAI key. If you haven't, check out the [installation](installation) guide.
|
||||
|
||||
You can use [other LLMs](../examples/other_llms) via their APIs; if you would prefer to use local models check out our [local LLM example](../../examples/local_llm).
|
||||
|
||||
## Set up
|
||||
|
||||
In a new folder:
|
||||
|
||||
```bash npm2yarn
|
||||
npm init
|
||||
npm install -D typescript @types/node
|
||||
```
|
||||
|
||||
## Extract data
|
||||
|
||||
Create the file `example.ts`. This code will:
|
||||
|
||||
- Set up an LLM connection to GPT-4
|
||||
- Give an example of the data structure we wish to generate
|
||||
- Prompt the LLM with instructions and the example, plus a sample transcript
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
|
||||
To run the code:
|
||||
|
||||
```bash
|
||||
npx tsx example.ts
|
||||
```
|
||||
|
||||
You should expect output something like:
|
||||
|
||||
```json
|
||||
{
|
||||
"summary": "Sarah from XYZ Company called John to introduce the XYZ Widget, a tool designed to automate tasks and improve productivity. John expressed interest and requested case studies and a product demo. Sarah agreed to send the information and follow up to schedule the demo.",
|
||||
"products": ["XYZ Widget"],
|
||||
"rep_name": "Sarah",
|
||||
"prospect_name": "John",
|
||||
"action_items": [
|
||||
"Send case studies and additional product information to John",
|
||||
"Follow up with John to schedule a product demo"
|
||||
]
|
||||
}
|
||||
```
|
||||
@@ -1,2 +0,0 @@
|
||||
label: Guides
|
||||
position: 2
|
||||
@@ -1,165 +0,0 @@
|
||||
# Adding Retrieval-Augmented Generation (RAG)
|
||||
|
||||
While an agent that can perform math is nifty (LLMs are usually not very good at math), LLM-based applications are always more interesting when they work with large amounts of data. In this case, we're going to use a 200-page PDF of the proposed budget of the city of San Francisco for fiscal years 2024-2024 and 2024-2025. It's a great example because it's extremely wordy and full of tables of figures, which present a challenge for humans and LLMs alike.
|
||||
|
||||
To learn more about RAG, we recommend this [introduction](https://docs.llamaindex.ai/en/stable/getting_started/concepts/) from our Python docs. We'll assume you know the basics:
|
||||
|
||||
- You need to parse your source data into chunks of text
|
||||
- You need to encode that text as numbers, called embeddings
|
||||
- You need to search your embeddings for the most relevant chunks of text
|
||||
- You feed your relevant chunks and a query to an LLM to answer a question
|
||||
|
||||
We're going to start with the same agent we [built in step 1](https://github.com/run-llama/ts-agents/blob/main/1_agent/agent.ts), but make a few changes. You can find the finished version [in the repository](https://github.com/run-llama/ts-agents/blob/main/2_agentic_rag/agent.ts).
|
||||
|
||||
### New dependencies
|
||||
|
||||
We'll be bringing in `SimpleDirectoryReader`, `HuggingFaceEmbedding`, `VectorStoreIndex`, and `QueryEngineTool` from LlamaIndex.TS, as well as the dependencies we previously used.
|
||||
|
||||
```javascript
|
||||
import {
|
||||
OpenAI,
|
||||
FunctionTool,
|
||||
OpenAIAgent,
|
||||
Settings,
|
||||
SimpleDirectoryReader,
|
||||
HuggingFaceEmbedding,
|
||||
VectorStoreIndex,
|
||||
QueryEngineTool,
|
||||
} from "llamaindex";
|
||||
```
|
||||
|
||||
### Add an embedding model
|
||||
|
||||
To encode our text into embeddings, we'll need an embedding model. We could use OpenAI for this but to save on API calls we're going to use a local embedding model from HuggingFace.
|
||||
|
||||
```javascript
|
||||
Settings.embedModel = new HuggingFaceEmbedding({
|
||||
modelType: "BAAI/bge-small-en-v1.5",
|
||||
quantized: false,
|
||||
});
|
||||
```
|
||||
|
||||
### Load data using SimpleDirectoryReader
|
||||
|
||||
SimpleDirectoryReader is a flexible tool that can read a variety of file formats. We're going to point it at our data directory, which contains just the single PDF file, and get it to return a set of documents.
|
||||
|
||||
```javascript
|
||||
const reader = new SimpleDirectoryReader();
|
||||
const documents = await reader.loadData("../data");
|
||||
```
|
||||
|
||||
### Index our data
|
||||
|
||||
Now we turn our text into embeddings. The `VectorStoreIndex` class takes care of this for us when we use the `fromDocuments` method (it uses the embedding model we defined in `Settings` earlier).
|
||||
|
||||
```javascript
|
||||
const index = await VectorStoreIndex.fromDocuments(documents);
|
||||
```
|
||||
|
||||
### Configure a retriever
|
||||
|
||||
Before LlamaIndex can send a query to the LLM, it needs to find the most relevant chunks to send. That's the purpose of a `Retriever`. We're going to get `VectorStoreIndex` to act as a retriever for us
|
||||
|
||||
```javascript
|
||||
const retriever = await index.asRetriever();
|
||||
```
|
||||
|
||||
### Configure how many documents to retrieve
|
||||
|
||||
By default LlamaIndex will retrieve just the 2 most relevant chunks of text. This document is complex though, so we'll ask for more context.
|
||||
|
||||
```javascript
|
||||
retriever.similarityTopK = 10;
|
||||
```
|
||||
|
||||
### Create a query engine
|
||||
|
||||
And our final step in creating a RAG pipeline is to create a query engine that will use the retriever to find the most relevant chunks of text, and then use the LLM to answer the question.
|
||||
|
||||
```javascript
|
||||
const queryEngine = await index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
```
|
||||
|
||||
### Define the query engine as a tool
|
||||
|
||||
Just as before we created a `FunctionTool`, we're going to create a `QueryEngineTool` that uses our `queryEngine`.
|
||||
|
||||
```javascript
|
||||
const tools = [
|
||||
new QueryEngineTool({
|
||||
queryEngine: queryEngine,
|
||||
metadata: {
|
||||
name: "san_francisco_budget_tool",
|
||||
description: `This tool can answer detailed questions about the individual components of the budget of San Francisco in 2023-2024.`,
|
||||
},
|
||||
}),
|
||||
];
|
||||
```
|
||||
|
||||
As before, we've created an array of tools with just one tool in it. The metadata is slightly different: we don't need to define our parameters, we just give the tool a name and a natural-language description.
|
||||
|
||||
### Create the agent as before
|
||||
|
||||
Creating the agent and asking a question is exactly the same as before, but we'll ask a different question.
|
||||
|
||||
```javascript
|
||||
// create the agent
|
||||
const agent = new OpenAIAgent({ tools });
|
||||
|
||||
let response = await agent.chat({
|
||||
message: "What's the budget of San Francisco in 2023-2024?",
|
||||
});
|
||||
|
||||
console.log(response);
|
||||
```
|
||||
|
||||
Once again we'll run `npx tsx agent.ts` and see what we get:
|
||||
|
||||
**_Output_**
|
||||
|
||||
```javascript
|
||||
{
|
||||
toolCall: {
|
||||
id: 'call_iNo6rTK4pOpOBbO8FanfWLI9',
|
||||
name: 'san_francisco_budget_tool',
|
||||
input: { query: 'total budget' }
|
||||
},
|
||||
toolResult: {
|
||||
tool: QueryEngineTool {
|
||||
queryEngine: [RetrieverQueryEngine],
|
||||
metadata: [Object]
|
||||
},
|
||||
input: { query: 'total budget' },
|
||||
output: 'The total budget for the City and County of San Francisco for Fiscal Year (FY) 2023-24 is $14.6 billion, which represents a $611.8 million, or 4.4 percent, increase over the FY 2022-23 budget. For FY 2024-25, the total budget is also projected to be $14.6 billion, reflecting a $40.5 million, or 0.3 percent, decrease from the FY 2023-24 proposed budget. This budget includes various expenditures across different departments and services, with significant allocations to public works, transportation, commerce, public protection, and health services.',
|
||||
isError: false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```javascript
|
||||
{
|
||||
response: {
|
||||
raw: {
|
||||
id: 'chatcmpl-9KxUkwizVCYCmxwFQcZFSHrInzNFU',
|
||||
object: 'chat.completion',
|
||||
created: 1714782286,
|
||||
model: 'gpt-4-turbo-2024-04-09',
|
||||
choices: [Array],
|
||||
usage: [Object],
|
||||
system_fingerprint: 'fp_ea6eb70039'
|
||||
},
|
||||
message: {
|
||||
content: "The total budget for the City and County of San Francisco for the fiscal year 2023-2024 is $14.6 billion. This represents a $611.8 million, or 4.4 percent, increase over the previous fiscal year's budget. The budget covers various expenditures across different departments and services, including significant allocations to public works, transportation, commerce, public protection, and health services.",
|
||||
role: 'assistant',
|
||||
options: {}
|
||||
}
|
||||
},
|
||||
sources: [Getter]
|
||||
}
|
||||
```
|
||||
|
||||
Once again we see a `toolResult`. You can see the query the LLM decided to send to the query engine ("total budget"), and the output the engine returned. In `response.message` you see that the LLM has returned the output from the tool almost verbatim, although it trimmed out the bit about 2024-2025 since we didn't ask about that year.
|
||||
|
||||
So now we have an agent that can index complicated documents and answer questions about them. Let's [combine our math agent and our RAG agent](rag_and_tools)!
|
||||
@@ -1,2 +0,0 @@
|
||||
label: Agents
|
||||
position: 1
|
||||
@@ -1,54 +0,0 @@
|
||||
---
|
||||
sidebar_position: 0
|
||||
slug: /
|
||||
---
|
||||
|
||||
# What is LlamaIndex?
|
||||
|
||||
LlamaIndex is a framework for building LLM-powered applications. LlamaIndex helps you ingest, structure, and access private or domain-specific data. It's available [as a Python package](https://docs.llamaindex.ai/en/stable/) and in TypeScript (this package). LlamaIndex.TS offers the core features of LlamaIndex for popular runtimes like Node.js (official support), Vercel Edge Functions (experimental), and Deno (experimental).
|
||||
|
||||
## 🚀 Why LlamaIndex.TS?
|
||||
|
||||
LLMs offer a natural language interface between humans and inferred data. Widely available models come pre-trained on huge amounts of publicly available data, from Wikipedia and mailing lists to textbooks and source code.
|
||||
|
||||
Applications built on top of LLMs often require augmenting these models with private or domain-specific data. That data is often distributed across siloed applications and data stores. It's behind APIs, in SQL databases, or trapped in PDFs and slide decks.
|
||||
|
||||
LlamaIndex.TS helps you unlock that data and then build powerful applications with it.
|
||||
|
||||
## 🦙 What is LlamaIndex for?
|
||||
|
||||
LlamaIndex.TS handles several major use cases:
|
||||
|
||||
- **Structured Data Extraction**: turning complex, unstructured and semi-structured data into uniform, programmatically accessible formats.
|
||||
- **Retrieval-Augmented Generation (RAG)**: answering queries across your internal data by providing LLMs with up-to-date, semantically relevant context including Question and Answer systems and chat bots.
|
||||
- **Autonomous Agents**: building software that is capable of intelligently selecting and using tools to accomplish tasks in an interative, unsupervised manner.
|
||||
|
||||
## 👨👩👧👦 Who is LlamaIndex for?
|
||||
|
||||
LlamaIndex targets the "AI Engineer": developers building software in any domain that can be enhanced by LLM-powered functionality, without needing to be an expert in machine learning or natural language processing.
|
||||
|
||||
Our high-level API allows beginner users to use LlamaIndex.TS to ingest, index, and query their data in just a few lines of code.
|
||||
|
||||
For more complex applications, our lower-level APIs allow advanced users to customize and extend any module—data connectors, indices, retrievers, and query engines, to fit their needs.
|
||||
|
||||
## Getting Started
|
||||
|
||||
`npm install llamaindex`
|
||||
|
||||
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](./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
|
||||
|
||||
To download or contribute, find LlamaIndex on:
|
||||
|
||||
- Github: https://github.com/run-llama/LlamaIndexTS
|
||||
- NPM: https://www.npmjs.com/package/llamaindex
|
||||
|
||||
## Community
|
||||
|
||||
Need help? Have a feature suggestion? Join the LlamaIndex community:
|
||||
|
||||
- Twitter: https://twitter.com/llama_index
|
||||
- Discord https://discord.gg/dGcwcsnxhU
|
||||
@@ -1,3 +0,0 @@
|
||||
label: "Modules"
|
||||
collapsed: false
|
||||
position: 5
|
||||
@@ -1,2 +0,0 @@
|
||||
label: "Agents"
|
||||
position: 3
|
||||
@@ -1,20 +0,0 @@
|
||||
# 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)
|
||||
@@ -1,29 +0,0 @@
|
||||
---
|
||||
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)
|
||||
@@ -1,23 +0,0 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
# Index
|
||||
|
||||
An index is the basic container and organization for your data. LlamaIndex.TS supports two indexes:
|
||||
|
||||
- `VectorStoreIndex` - will send the top-k `Node`s to the LLM when generating a response. The default top-k is 2.
|
||||
- `SummaryIndex` - will send every `Node` in the index to the LLM in order to generate a response
|
||||
|
||||
```typescript
|
||||
import { Document, VectorStoreIndex } from "llamaindex";
|
||||
|
||||
const document = new Document({ text: "test" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [SummaryIndex](../api/classes/SummaryIndex.md)
|
||||
- [VectorStoreIndex](../api/classes/VectorStoreIndex.md)
|
||||
@@ -1,68 +0,0 @@
|
||||
---
|
||||
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";
|
||||
import CodeSource4 from "!raw-loader!../../../../examples/readers/src/simple-directory-reader-with-llamaparse.ts";
|
||||
|
||||
# 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 `.txt`, `.pdf`, `.csv`, `.md`, `.docx`, `.htm`, `.html`, `.jpg`, `.jpeg`, `.png` and `.gif` files, but support for other file types is planned.
|
||||
|
||||
You can override the default reader for all file types, inlcuding unsupported ones, with the `overrideReader` option.
|
||||
Additionally, you can override the default reader for specific file types or add support for additional file types with the `fileExtToReader` option.
|
||||
Also, you can provide a `defaultReader` as a fallback for files with unsupported extensions. By default it is `TextFileReader`.
|
||||
|
||||
SimpleDirectoryReader supports up to 9 concurrent requests. Use the `numWorkers` option to set the number of concurrent requests. By default it runs in sequential mode, i.e. set to 1.
|
||||
|
||||
<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 as `apiKey` parameter or in the environment variable `LLAMA_CLOUD_API_KEY`.
|
||||
|
||||
Then, you can use the `LlamaParseReader` class to local files and convert them into a parsed document that can be used by LlamaIndex.
|
||||
See [LlamaParseReader.ts](https://github.com/run-llama/LlamaIndexTS/blob/main/packages/core/src/readers/LlamaParseReader.ts#L6) for a list of supported file types:
|
||||
|
||||
<CodeBlock language="ts">{CodeSource3}</CodeBlock>
|
||||
|
||||
Additional options can be set with the `LlamaParseReader` constructor:
|
||||
|
||||
- `resultType` can be set to `markdown`, `text` or `.json`. Defaults to `text`
|
||||
- `language` primarly helps with OCR recognition. Defaults to `en`. See [../readers/type.ts](https://github.com/run-llama/LlamaIndexTS/blob/main/packages/core/src/readers/type.ts#L20) for a list of supported languages.
|
||||
- `parsingInstructions` can help with complicated document structures. See this [LlamaIndex Blog Post](https://www.llamaindex.ai/blog/launching-the-first-genai-native-document-parsing-platform) for an example.
|
||||
- `skipDiagonalText` set to true to ignore diagonal text.
|
||||
- `invalidateCache` set to true to ignore the LlamaCloud cache. All document are kept in cache for 48hours after the job was completed to avoid processing the same document twice. Can be useful for testing when trying to re-parse the same document with, e.g. different `parsingInstructions`.
|
||||
- `gpt4oMode` set to true to use GPT-4o to extract content.
|
||||
- `gpt4oApiKey` set the GPT-4o API key. Optional. Lowers the cost of parsing by using your own API key. Your OpenAI account will be charged. Can also be set in the environment variable `LLAMA_CLOUD_GPT4O_API_KEY`.
|
||||
- `numWorkers` as in the python version, is set in `SimpleDirectoryReader`. Default is 1.
|
||||
|
||||
## LlamaParse with SimpleDirectoryReader
|
||||
|
||||
Below a full example of `LlamaParse` integrated in `SimpleDirectoryReader` with additional options.
|
||||
|
||||
<CodeBlock language="ts">{CodeSource4}</CodeBlock>
|
||||
|
||||
## API Reference
|
||||
|
||||
- [SimpleDirectoryReader](../api/classes/SimpleDirectoryReader.md)
|
||||
- [LlamaParseReader](../api/classes/LlamaParseReader.md)
|
||||
@@ -1,2 +0,0 @@
|
||||
label: "Document / Nodes"
|
||||
position: 0
|
||||
@@ -1,18 +0,0 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# Documents and Nodes
|
||||
|
||||
`Document`s and `Node`s are the basic building blocks of any index. While the API for these objects is similar, `Document` objects represent entire files, while `Node`s are smaller pieces of that original document, that are suitable for an LLM and Q&A.
|
||||
|
||||
```typescript
|
||||
import { Document } from "llamaindex";
|
||||
|
||||
document = new Document({ text: "text", metadata: { key: "val" } });
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [Document](../api/classes/Document.md)
|
||||
- [TextNode](../api/classes/TextNode.md)
|
||||
@@ -1,45 +0,0 @@
|
||||
# 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"));
|
||||
```
|
||||
@@ -1,2 +0,0 @@
|
||||
label: "Embeddings"
|
||||
position: 3
|
||||
@@ -1 +0,0 @@
|
||||
label: "Available Embeddings"
|
||||
@@ -1,79 +0,0 @@
|
||||
# DeepInfra
|
||||
|
||||
To use DeepInfra embeddings, you need to import `DeepInfraEmbedding` from llamaindex.
|
||||
Check out available embedding models [here](https://deepinfra.com/models/embeddings).
|
||||
|
||||
```ts
|
||||
import {
|
||||
DeepInfraEmbedding,
|
||||
Settings,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
|
||||
// Update Embed Model
|
||||
Settings.embedModel = new DeepInfraEmbedding();
|
||||
|
||||
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,
|
||||
});
|
||||
```
|
||||
|
||||
By default, DeepInfraEmbedding is using the sentence-transformers/clip-ViT-B-32 model. You can change the model by passing the model parameter to the constructor.
|
||||
For example:
|
||||
|
||||
```ts
|
||||
import { DeepInfraEmbedding } from "llamaindex";
|
||||
|
||||
const model = "intfloat/e5-large-v2";
|
||||
Settings.embedModel = new DeepInfraEmbedding({
|
||||
model,
|
||||
});
|
||||
```
|
||||
|
||||
You can also set the `maxRetries` and `timeout` parameters when initializing `DeepInfraEmbedding` for better control over the request behavior.
|
||||
|
||||
For example:
|
||||
|
||||
```ts
|
||||
import { DeepInfraEmbedding, Settings } from "llamaindex";
|
||||
|
||||
const model = "intfloat/e5-large-v2";
|
||||
const maxRetries = 5;
|
||||
const timeout = 5000; // 5 seconds
|
||||
|
||||
Settings.embedModel = new DeepInfraEmbedding({
|
||||
model,
|
||||
maxRetries,
|
||||
timeout,
|
||||
});
|
||||
```
|
||||
|
||||
Standalone usage:
|
||||
|
||||
```ts
|
||||
import { DeepInfraEmbedding } from "llamaindex";
|
||||
import { config } from "dotenv";
|
||||
// For standalone usage, you need to configure DEEPINFRA_API_TOKEN in .env file
|
||||
config();
|
||||
|
||||
const main = async () => {
|
||||
const model = "intfloat/e5-large-v2";
|
||||
const embeddings = new DeepInfraEmbedding({ model });
|
||||
const text = "What is the meaning of life?";
|
||||
const response = await embeddings.embed([text]);
|
||||
console.log(response);
|
||||
};
|
||||
|
||||
main();
|
||||
```
|
||||
|
||||
For questions or feedback, please contact us at [feedback@deepinfra.com](mailto:feedback@deepinfra.com)
|
||||
@@ -1,33 +0,0 @@
|
||||
# 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,
|
||||
});
|
||||
```
|
||||
@@ -1,34 +0,0 @@
|
||||
# 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,
|
||||
});
|
||||
```
|
||||
@@ -1,21 +0,0 @@
|
||||
# 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,
|
||||
});
|
||||
```
|
||||
@@ -1,24 +0,0 @@
|
||||
# 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,
|
||||
});
|
||||
```
|
||||
@@ -1,29 +0,0 @@
|
||||
# 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,
|
||||
});
|
||||
```
|
||||
@@ -1,21 +0,0 @@
|
||||
# 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,
|
||||
});
|
||||
```
|
||||
@@ -1,23 +0,0 @@
|
||||
# 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,
|
||||
});
|
||||
```
|
||||
@@ -1,21 +0,0 @@
|
||||
# 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)
|
||||
@@ -1,2 +0,0 @@
|
||||
label: "Evaluating"
|
||||
position: 3
|
||||
@@ -1,32 +0,0 @@
|
||||
# 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)
|
||||
@@ -1 +0,0 @@
|
||||
label: "Modules"
|
||||
@@ -1,58 +0,0 @@
|
||||
# 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, Response } 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: new Response(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
|
||||
```
|
||||
@@ -1,78 +0,0 @@
|
||||
# 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
|
||||
```
|
||||
@@ -1,72 +0,0 @@
|
||||
# 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,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
} 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,2 +0,0 @@
|
||||
label: "Ingestion Pipeline"
|
||||
position: 2
|
||||
@@ -1,99 +0,0 @@
|
||||
# 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);
|
||||
```
|
||||
@@ -1,77 +0,0 @@
|
||||
# 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);
|
||||
```
|
||||
@@ -1,2 +0,0 @@
|
||||
label: "LLMs"
|
||||
position: 3
|
||||
@@ -1 +0,0 @@
|
||||
label: "Available LLMs"
|
||||
@@ -1,65 +0,0 @@
|
||||
# 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);
|
||||
}
|
||||
```
|
||||
@@ -1,76 +0,0 @@
|
||||
# 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);
|
||||
}
|
||||
```
|
||||
@@ -1,61 +0,0 @@
|
||||
# Bedrock
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { BEDROCK_MODELS, Bedrock } from "@llamaindex/community";
|
||||
|
||||
Settings.llm = new Bedrock({
|
||||
model: BEDROCK_MODELS.ANTHROPIC_CLAUDE_3_HAIKU,
|
||||
region: "us-east-1", // can be provided via env AWS_REGION
|
||||
credentials: {
|
||||
accessKeyId: "...", // optional and can be provided via env AWS_ACCESS_KEY_ID
|
||||
secretAccessKey: "...", // optional and can be provided via env AWS_SECRET_ACCESS_KEY
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Currently only supports Anthropic models:
|
||||
|
||||
```ts
|
||||
ANTHROPIC_CLAUDE_INSTANT_1 = "anthropic.claude-instant-v1";
|
||||
ANTHROPIC_CLAUDE_2 = "anthropic.claude-v2";
|
||||
ANTHROPIC_CLAUDE_2_1 = "anthropic.claude-v2:1";
|
||||
ANTHROPIC_CLAUDE_3_SONNET = "anthropic.claude-3-sonnet-20240229-v1:0";
|
||||
ANTHROPIC_CLAUDE_3_HAIKU = "anthropic.claude-3-haiku-20240307-v1:0";
|
||||
ANTHROPIC_CLAUDE_3_OPUS = "anthropic.claude-3-opus-20240229-v1:0"; // Not currently on Bedrock
|
||||
```
|
||||
|
||||
Sonnet, Haiku and Opus are multimodal, image_url only supports base64 data url format, e.g. `data:image/jpeg;base64,SGVsbG8sIFdvcmxkIQ==`
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import { BEDROCK_MODELS, Bedrock } from "llamaindex";
|
||||
|
||||
Settings.llm = new Bedrock({
|
||||
model: BEDROCK_MODELS.ANTHROPIC_CLAUDE_3_HAIKU,
|
||||
});
|
||||
|
||||
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);
|
||||
}
|
||||
```
|
||||
@@ -1,83 +0,0 @@
|
||||
# DeepInfra
|
||||
|
||||
Check out available LLMs [here](https://deepinfra.com/models/text-generation).
|
||||
|
||||
```ts
|
||||
import { DeepInfra, Settings } from "llamaindex";
|
||||
|
||||
// Get the API key from `DEEPINFRA_API_TOKEN` environment variable
|
||||
import { config } from "dotenv";
|
||||
config();
|
||||
Settings.llm = new DeepInfra();
|
||||
|
||||
// Set the API key
|
||||
apiKey = "YOUR_API_KEY";
|
||||
Settings.llm = new DeepInfra({ apiKey });
|
||||
```
|
||||
|
||||
You can setup the apiKey on the environment variables, like:
|
||||
|
||||
```bash
|
||||
export DEEPINFRA_API_TOKEN="<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 { DeepInfra, Document, VectorStoreIndex, Settings } from "llamaindex";
|
||||
|
||||
// Use custom LLM
|
||||
const model = "meta-llama/Meta-Llama-3-8B-Instruct";
|
||||
Settings.llm = new DeepInfra({ model, 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);
|
||||
}
|
||||
```
|
||||
|
||||
## Feedback
|
||||
|
||||
If you have any feedback, please reach out to us at [feedback@deepinfra.com](mailto:feedback@deepinfra.com)
|
||||
@@ -1,61 +0,0 @@
|
||||
# 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);
|
||||
```
|
||||
@@ -1,101 +0,0 @@
|
||||
# Gemini
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { Gemini, Settings, GEMINI_MODEL } from "llamaindex";
|
||||
|
||||
Settings.llm = new Gemini({
|
||||
model: GEMINI_MODEL.GEMINI_PRO,
|
||||
});
|
||||
```
|
||||
|
||||
### Usage with Vertex AI
|
||||
|
||||
To use Gemini via Vertex AI you can use `GeminiVertexSession`.
|
||||
|
||||
GeminiVertexSession accepts the env variables: `GOOGLE_VERTEX_LOCATION` and `GOOGLE_VERTEX_PROJECT`
|
||||
|
||||
```ts
|
||||
import { Gemini, GEMINI_MODEL, GeminiVertexSession } from "llamaindex";
|
||||
|
||||
const gemini = new Gemini({
|
||||
model: GEMINI_MODEL.GEMINI_PRO,
|
||||
session: new GeminiVertexSession({
|
||||
location: "us-central1", // optional if provided by GOOGLE_VERTEX_LOCATION env variable
|
||||
project: "project1", // optional if provided by GOOGLE_VERTEX_PROJECT env variable
|
||||
googleAuthOptions: {...}, // optional, but useful for production. It accepts all values from `GoogleAuthOptions`
|
||||
}),
|
||||
});
|
||||
```
|
||||
|
||||
[GoogleAuthOptions](https://github.com/googleapis/google-auth-library-nodejs/blob/main/src/auth/googleauth.ts)
|
||||
|
||||
To authenticate for local development:
|
||||
|
||||
```bash
|
||||
npm install @google-cloud/vertexai
|
||||
gcloud auth application-default login
|
||||
```
|
||||
|
||||
To authenticate for production you'll have to use a [service account](https://cloud.google.com/docs/authentication/). `googleAuthOptions` has `credentials` which might be useful for you.
|
||||
|
||||
## 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);
|
||||
}
|
||||
```
|
||||
@@ -1,52 +0,0 @@
|
||||
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>
|
||||
@@ -1,91 +0,0 @@
|
||||
# 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);
|
||||
}
|
||||
```
|
||||
@@ -1,68 +0,0 @@
|
||||
# Mistral
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { MistralAI, 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);
|
||||
}
|
||||
```
|
||||
@@ -1,73 +0,0 @@
|
||||
# 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);
|
||||
}
|
||||
```
|
||||
@@ -1,69 +0,0 @@
|
||||
# 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);
|
||||
}
|
||||
```
|
||||
@@ -1,70 +0,0 @@
|
||||
# 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);
|
||||
}
|
||||
```
|
||||
@@ -1,68 +0,0 @@
|
||||
# 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);
|
||||
}
|
||||
```
|
||||
@@ -1,35 +0,0 @@
|
||||
---
|
||||
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)
|
||||
@@ -1,97 +0,0 @@
|
||||
---
|
||||
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)
|
||||
@@ -1,2 +0,0 @@
|
||||
label: "Node Postprocessors"
|
||||
position: 3
|
||||
@@ -1,67 +0,0 @@
|
||||
# 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?");
|
||||
```
|
||||
@@ -1,105 +0,0 @@
|
||||
# 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);
|
||||
```
|
||||
@@ -1,71 +0,0 @@
|
||||
# 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?");
|
||||
```
|
||||
@@ -1,2 +0,0 @@
|
||||
label: "Prompts"
|
||||
position: 0
|
||||
@@ -1,72 +0,0 @@
|
||||
# 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?",
|
||||
});
|
||||
```
|
||||
@@ -1,2 +0,0 @@
|
||||
label: "Query Engines"
|
||||
position: 2
|
||||
@@ -1,41 +0,0 @@
|
||||
# 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: "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
|
||||
|
||||
The basic concept of the Sub Question Query Engine is that it splits a single query into multiple queries, gets an answer for each of those queries, and then combines those different answers into a single coherent response for the user. You can think of it as the "think this through step by step" prompt technique but iterating over your data sources!
|
||||
|
||||
### Getting Started
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
### Tools
|
||||
|
||||
SubQuestionQueryEngine is implemented with Tools. The basic idea of Tools is that they are executable options for the large language model. In this case, our SubQuestionQueryEngine relies on QueryEngineTool, which as you guessed it is a tool to run queries on a QueryEngine. This allows us to give the model an option to query different documents for different questions for example. You could also imagine that the SubQuestionQueryEngine could use a Tool that searches for something on the web or gets an answer using Wolfram Alpha.
|
||||
|
||||
You can learn more about Tools by taking a look at the LlamaIndex Python documentation https://gpt-index.readthedocs.io/en/latest/core_modules/agent_modules/tools/root.html
|
||||
|
||||
## API Reference
|
||||
|
||||
- [RetrieverQueryEngine](../../api/classes/RetrieverQueryEngine.md)
|
||||
- [SubQuestionQueryEngine](../../api/classes/SubQuestionQueryEngine.md)
|
||||
- [QueryEngineTool](../../api/interfaces/QueryEngineTool.md)
|
||||
@@ -1,153 +0,0 @@
|
||||
# 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();
|
||||
```
|
||||
@@ -1,167 +0,0 @@
|
||||
# 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"));
|
||||
```
|
||||
@@ -1,64 +0,0 @@
|
||||
---
|
||||
sidebar_position: 6
|
||||
---
|
||||
|
||||
# ResponseSynthesizer
|
||||
|
||||
The ResponseSynthesizer is responsible for sending the query, nodes, and prompt templates to the LLM to generate a response. There are a few key modes for generating a response:
|
||||
|
||||
- `Refine`: "create and refine" an answer by sequentially going through each retrieved text chunk.
|
||||
This makes a separate LLM call per Node. Good for more detailed answers.
|
||||
- `CompactAndRefine` (default): "compact" the prompt during each LLM call by stuffing as
|
||||
many text chunks that can fit within the maximum prompt size. If there are
|
||||
too many chunks to stuff in one prompt, "create and refine" an answer by going through
|
||||
multiple compact prompts. The same as `refine`, but should result in less LLM calls.
|
||||
- `TreeSummarize`: Given a set of text chunks and the query, recursively construct a tree
|
||||
and return the root node as the response. Good for summarization purposes.
|
||||
- `SimpleResponseBuilder`: Given a set of text chunks and the query, apply the query to each text
|
||||
chunk while accumulating the responses into an array. Returns a concatenated string of all
|
||||
responses. Good for when you need to run the same query separately against each text
|
||||
chunk.
|
||||
|
||||
```typescript
|
||||
import { NodeWithScore, ResponseSynthesizer, TextNode } from "llamaindex";
|
||||
|
||||
const responseSynthesizer = new ResponseSynthesizer();
|
||||
|
||||
const nodesWithScore: NodeWithScore[] = [
|
||||
{
|
||||
node: new TextNode({ text: "I am 10 years old." }),
|
||||
score: 1,
|
||||
},
|
||||
{
|
||||
node: new TextNode({ text: "John is 20 years old." }),
|
||||
score: 0.5,
|
||||
},
|
||||
];
|
||||
|
||||
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)
|
||||
@@ -1,21 +0,0 @@
|
||||
---
|
||||
sidebar_position: 5
|
||||
---
|
||||
|
||||
# Retriever
|
||||
|
||||
A retriever in LlamaIndex is what is used to fetch `Node`s from an index using a query string. Aa `VectorIndexRetriever` will fetch the top-k most similar nodes. Meanwhile, a `SummaryIndexRetriever` will fetch all nodes no matter the query.
|
||||
|
||||
```typescript
|
||||
const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Fetch nodes!
|
||||
const nodesWithScore = await retriever.retrieve({ query: "query string" });
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [SummaryIndexRetriever](../api/classes/SummaryIndexRetriever.md)
|
||||
- [SummaryIndexLLMRetriever](../api/classes/SummaryIndexLLMRetriever.md)
|
||||
- [VectorIndexRetriever](../api/classes/VectorIndexRetriever.md)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user