mirror of
https://github.com/run-llama/LlamaIndexTS.git
synced 2026-07-01 22:14:03 -04:00
Compare commits
571 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 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 | |||
| 83b2f0b0af | |||
| 1a6abb38bc | |||
| 6bc5bddb59 | |||
| e6d6576b2f | |||
| bf25ff6104 | |||
| 32ad0992cf | |||
| af650343d9 | |||
| f6f4ca44bd | |||
| 9aa918f026 | |||
| 00a92cd125 | |||
| 73819bf19d | |||
| d10cca28fc | |||
| 1378ec4e50 | |||
| 24a9d1e816 | |||
| b100684bad | |||
| c375cd5c6b | |||
| 45952dee59 | |||
| 6db7f23ec7 | |||
| 0721a84900 | |||
| 4d4bd85448 | |||
| 11ae9267ae | |||
| 174cb3e6da | |||
| 5ab5e5191d | |||
| 54230f0477 | |||
| 3d484da1c5 | |||
| 631f0001ef | |||
| 060b700e09 | |||
| 83c24f4d50 | |||
| 883266939e | |||
| a29d8351c8 | |||
| da1f025229 | |||
| 6b1ded41a9 | |||
| e01cc053e3 | |||
| 6e156edb11 | |||
| 0b519958e9 | |||
| 265976df12 | |||
| 7e1b96a2db | |||
| 8e26f753b7 | |||
| 31e3251435 | |||
| 058c275a72 | |||
| 6ff7576eb9 | |||
| 94543decad | |||
| b963782137 | |||
| 52c47cada3 | |||
| 9216312b11 | |||
| 660a2b3495 | |||
| 6d21092805 | |||
| fb2c1fa917 | |||
| 37525df529 | |||
| a1f24753d9 | |||
| aa0f586330 | |||
| ff03139799 | |||
| 1b1081b9c9 | |||
| 047ae07e74 | |||
| d8aa29a115 | |||
| 34fb1d8992 | |||
| c517f35526 | |||
| e072c45393 | |||
| 51241865f8 | |||
| 10c83485d2 | |||
| 1e6a18ad2d | |||
| 9e133ac10d | |||
| ba217eec2c | |||
| 64ef70b735 | |||
| 6615aaa4ab | |||
| 447105a6dc | |||
| 320be3fab6 | |||
| bbd9f85a45 | |||
| 5f29ba5e2c | |||
| 4aba02eb82 | |||
| 75736ad01b | |||
| 68a508fcd0 | |||
| 6281fc8c91 | |||
| c3747d092a | |||
| 24a39aefb8 | |||
| 0b1299036d | |||
| 2c8d7941f0 | |||
| a1a72ab223 | |||
| b99ab056d1 | |||
| 1a45b44307 | |||
| 804c57519f | |||
| ce94780b95 | |||
| 645fcf6c24 | |||
| e37fa5d9ca | |||
| 97e4ecd5b8 | |||
| b6a660651b | |||
| 456d3fb0b3 | |||
| efa326a871 | |||
| 5765b637ce | |||
| 72687b4f69 | |||
| 0c67e1f8f3 | |||
| 4a0619758a | |||
| bc7a11cdbe | |||
| 5596e31947 | |||
| 2fe2b813ba | |||
| be5df5b01b | |||
| e74fe88342 | |||
| f1862ccab1 | |||
| 9e74a4327f | |||
| 5e61934d5a | |||
| 2008efe0ee | |||
| ee719a1fda | |||
| 1dce275a7c | |||
| d10533ef77 | |||
| 8aeb8ae690 | |||
| e8c41c5c27 | |||
| 051b4ddfa2 | |||
| 61103b677b | |||
| e69cac672a | |||
| 94246a3ca8 | |||
| b440a008e5 | |||
| 46227f2a70 | |||
| 77f0298f6f | |||
| c14e112236 | |||
| 62b035fdc1 | |||
| aa0be1469b | |||
| 5016f21d52 | |||
| 130b7992a1 | |||
| 0d50b22dbf | |||
| db1d1f57c9 | |||
| dccb8163d8 | |||
| 1ab3ba407e | |||
| b03f765733 | |||
| 7488d3c235 | |||
| 5cb270d07f | |||
| 62771058aa | |||
| ca348a6570 | |||
| 44a7fd72e8 | |||
| d8d952d937 | |||
| 216ba1f22b | |||
| 74686f5776 | |||
| 1ebf9e67a4 | |||
| aeefc77da0 | |||
| 13d8d7cbbe | |||
| 9c34e44b85 | |||
| cb2dc802d9 | |||
| 5a6cc0e32e | |||
| a63256eb84 | |||
| 0a160b97a0 | |||
| 95602c7959 | |||
| 20bc466ca1 | |||
| efb1c56ba5 | |||
| 286499388d | |||
| 460c6574cc | |||
| 8b0e0e3cc8 | |||
| 87142b29fa | |||
| 501b844f0f | |||
| 03157dc295 | |||
| ef80b684f7 | |||
| 472e70feee | |||
| cfb90f7666 | |||
| 2e3a287a27 | |||
| 635fbb8618 | |||
| d2d34acb31 | |||
| cf70edbede | |||
| 79b7d246bd | |||
| bcc3d0b4d1 | |||
| 238ca86534 | |||
| 1f3efe8947 | |||
| 89324b4067 | |||
| 8cc848aee6 | |||
| cd54a7a66b | |||
| dca02f7277 | |||
| b757fa9aa3 | |||
| bc594a0674 | |||
| 208282d62f | |||
| 060880abfe | |||
| 728b35e774 | |||
| bdaa043404 | |||
| a55cf8d870 | |||
| cf4244fd3a | |||
| 76c3fd64ad | |||
| 701e0ac2be | |||
| a285f8ba3a | |||
| 663821cdf6 | |||
| c4b95494ac | |||
| 980fb4e5a3 | |||
| 96f8f40291 | |||
| 1c698df6e0 | |||
| 298cb433be | |||
| 63af7dd99d | |||
| af5df1d083 | |||
| a3b44093c2 | |||
| c80bf3311f | |||
| 7940d249b0 | |||
| 4a07c81f71 | |||
| 7d56cdf045 | |||
| 0affe621d5 | |||
| 93932b1a9c | |||
| a87f13b9d2 | |||
| 8d2b21ee75 | |||
| 87741c9be8 | |||
| 171cb89170 | |||
| 5dad867bbe | |||
| 13f26fd84d | |||
| 3bc77f7d7f | |||
| aac1ee3af3 | |||
| e85893ac0f | |||
| 315947ee6f | |||
| 23a0d44b11 | |||
| 3b501de057 | |||
| 6cc645aa2a | |||
| 0b37207adc | |||
| f0704ec705 | |||
| 4fcbdf710e | |||
| 866149193a | |||
| 6ffb161618 | |||
| 8e4b49824b | |||
| 5263576de1 | |||
| 6d4e2ea0e9 | |||
| 3cbfa98e6b | |||
| d256cbe0e0 | |||
| a6dfa30dcf | |||
| d0365dc434 | |||
| aa41432bbb | |||
| 98a2b4a547 | |||
| 806ce9a360 | |||
| 8b28092cc8 | |||
| 5c5f4c1c84 | |||
| 949d330295 | |||
| 9a5ee4f37a | |||
| 7a23cc6c84 | |||
| 041acd11fe | |||
| 24b4033db9 | |||
| 1115f83b8f | |||
| 60a1603636 | |||
| ea467fa031 | |||
| b0e6f73b1d | |||
| 6d9e015b5e | |||
| fececd89ab | |||
| 48e287892f | |||
| f118400820 | |||
| 3f8407c7af | |||
| 83317739c7 | |||
| 0b665bd1ca | |||
| 98d4cbdf95 | |||
| 6cb75b54a0 | |||
| 53edfe93cf | |||
| b856deae43 | |||
| 259c842259 | |||
| ffb195ea7a | |||
| b4677534d1 | |||
| f967b82467 | |||
| c81946930e | |||
| 1008b775a4 | |||
| 41210dfc51 | |||
| 67b7272249 | |||
| 964e045903 | |||
| 137cf67f40 | |||
| 309a526e3c | |||
| dd95927498 | |||
| 4f72feae91 | |||
| 3cd8f9f597 | |||
| d2e8d0c62a | |||
| fafbd8c9c7 | |||
| a40c91b054 | |||
| 98894055c6 | |||
| 4589a84643 | |||
| e6b7f52d3e | |||
| b169db617a | |||
| 89a49f4f4f | |||
| 58490715fe | |||
| 4c2283c4e5 | |||
| a059070dec | |||
| 20dfeb4cfa | |||
| aefc3266c1 | |||
| fdf48dd459 | |||
| 66525346a2 | |||
| c9b2ec4a2b | |||
| bf583a7266 | |||
| de194d1c73 | |||
| ecdc289df1 | |||
| 9e198ac40d | |||
| 0a06998690 | |||
| 484a7105a9 | |||
| 8d18ea167b | |||
| a2ca89bfe0 | |||
| edeea40898 | |||
| 2a7080b094 | |||
| b354f2386b | |||
| d766bd03d2 | |||
| 6a69148356 | |||
| e1e1b0b522 | |||
| d824876653 | |||
| 2048698f77 | |||
| 9942979aa7 | |||
| 3c2655a1f9 | |||
| 552a61a66f | |||
| d13143e322 | |||
| 5116ad8d08 | |||
| 64683a55f3 | |||
| 698cd9c631 | |||
| c744a99102 | |||
| 2d2935085e | |||
| 1b31e2c8cd | |||
| 7257751993 | |||
| de6bfdb1b1 | |||
| 9e49f4411b | |||
| 026d068ddf | |||
| 7055d6fc3c | |||
| e9c2366bf1 | |||
| 6278152e49 | |||
| 76010c0cea | |||
| 889b84cfb9 | |||
| a26681c416 | |||
| 90027a7b44 | |||
| aab56faf88 | |||
| c57bd11c45 | |||
| 3fa1e29468 | |||
| cf87f84900 | |||
| 402d4ef013 | |||
| fc94906a1e | |||
| b83fcd11e4 | |||
| c28af7c7bc | |||
| dbc853bcc5 | |||
| c8396c5a3c | |||
| 65af8d3a26 | |||
| 329b6ec958 | |||
| 09bf27abd7 | |||
| 2ec6a529c7 | |||
| e8e21a0e4e | |||
| 88d243f145 | |||
| 3a6e287443 | |||
| beb3e5cd7f | |||
| 7416a87e10 | |||
| 65b85b237e | |||
| b17a80014a | |||
| ff87f99807 |
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://unpkg.com/@changesets/config@2.3.1/schema.json",
|
||||
"changelog": "@changesets/cli/changelog",
|
||||
"commit": true,
|
||||
"commit": false,
|
||||
"fixed": [],
|
||||
"linked": [],
|
||||
"access": "public",
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"llamaindex": patch
|
||||
---
|
||||
|
||||
build: use ESM as default
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"llamaindex": patch
|
||||
---
|
||||
|
||||
feat: abstract `@llamaindex/env` package
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"jsc": {
|
||||
"parser": {
|
||||
"syntax": "typescript",
|
||||
"decorators": true
|
||||
},
|
||||
"target": "esnext",
|
||||
"transform": {
|
||||
"decoratorVersion": "2022-03"
|
||||
}
|
||||
},
|
||||
"module": {
|
||||
"type": "commonjs",
|
||||
"ignoreDynamic": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
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": [
|
||||
"error",
|
||||
{
|
||||
ignoredTypeNames: ["Error", "RegExp", "URL", "URLSearchParams"],
|
||||
},
|
||||
],
|
||||
"@typescript-eslint/no-duplicate-enum-values": "off",
|
||||
"@typescript-eslint/no-duplicate-type-constituents": "off",
|
||||
"@typescript-eslint/no-explicit-any": "off",
|
||||
"@typescript-eslint/no-extra-non-null-assertion": "off",
|
||||
"@typescript-eslint/no-for-in-array": "off",
|
||||
"no-implied-eval": "off",
|
||||
"@typescript-eslint/no-implied-eval": "off",
|
||||
"no-loss-of-precision": "off",
|
||||
"@typescript-eslint/no-loss-of-precision": "off",
|
||||
"@typescript-eslint/no-misused-new": "off",
|
||||
"@typescript-eslint/no-misused-promises": "off",
|
||||
"@typescript-eslint/no-namespace": "off",
|
||||
"@typescript-eslint/no-non-null-asserted-optional-chain": "off",
|
||||
"@typescript-eslint/no-redundant-type-constituents": "off",
|
||||
"@typescript-eslint/no-this-alias": "off",
|
||||
"@typescript-eslint/no-unnecessary-type-assertion": "off",
|
||||
"@typescript-eslint/no-unnecessary-type-constraint": "off",
|
||||
"@typescript-eslint/no-unsafe-argument": "off",
|
||||
"@typescript-eslint/no-unsafe-assignment": "off",
|
||||
"@typescript-eslint/no-unsafe-call": "off",
|
||||
"@typescript-eslint/no-unsafe-declaration-merging": "off",
|
||||
"@typescript-eslint/no-unsafe-enum-comparison": "off",
|
||||
"@typescript-eslint/no-unsafe-member-access": "off",
|
||||
"@typescript-eslint/no-unsafe-return": "off",
|
||||
"no-unused-vars": "off",
|
||||
"@typescript-eslint/no-unused-vars": "off",
|
||||
"@typescript-eslint/no-var-requires": "off",
|
||||
"@typescript-eslint/prefer-as-const": "off",
|
||||
"require-await": "off",
|
||||
"@typescript-eslint/require-await": "off",
|
||||
"@typescript-eslint/restrict-plus-operands": "off",
|
||||
"@typescript-eslint/restrict-template-expressions": "off",
|
||||
"@typescript-eslint/triple-slash-reference": "off",
|
||||
"@typescript-eslint/unbound-method": "off",
|
||||
},
|
||||
overrides: [
|
||||
{
|
||||
files: ["examples/**/*.ts"],
|
||||
rules: {
|
||||
"turbo/no-undeclared-env-vars": "off",
|
||||
},
|
||||
},
|
||||
],
|
||||
ignorePatterns: ["dist/", "lib/", "deps/"],
|
||||
};
|
||||
@@ -1,15 +0,0 @@
|
||||
module.exports = {
|
||||
root: true,
|
||||
// This tells ESLint to load the config from the package `eslint-config-custom`
|
||||
extends: ["custom"],
|
||||
settings: {
|
||||
next: {
|
||||
rootDir: ["apps/*/"],
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
"max-params": ["error", 4],
|
||||
"prefer-const": "error",
|
||||
},
|
||||
ignorePatterns: ["dist/"],
|
||||
};
|
||||
@@ -1,68 +0,0 @@
|
||||
name: E2E Tests
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
paths:
|
||||
- "packages/create-llama/**"
|
||||
- ".github/workflows/e2e.yml"
|
||||
branches: [main]
|
||||
|
||||
env:
|
||||
POETRY_VERSION: "1.6.1"
|
||||
|
||||
jobs:
|
||||
e2e:
|
||||
name: create-llama
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: true
|
||||
matrix:
|
||||
node-version: [18, 20]
|
||||
python-version: ["3.11"]
|
||||
os: [macos-latest, windows-latest]
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Set up python ${{ matrix.python-version }}
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
- name: Install Poetry
|
||||
uses: snok/install-poetry@v1
|
||||
with:
|
||||
version: ${{ env.POETRY_VERSION }}
|
||||
- uses: pnpm/action-setup@v2
|
||||
- name: Setup Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: "pnpm"
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
- name: Install Playwright Browsers
|
||||
run: pnpm exec playwright install --with-deps
|
||||
working-directory: ./packages/create-llama
|
||||
- name: Build create-llama
|
||||
run: pnpm run build
|
||||
working-directory: ./packages/create-llama
|
||||
- name: Pack
|
||||
run: pnpm pack --pack-destination ./output
|
||||
working-directory: ./packages/create-llama
|
||||
- name: Extract Pack
|
||||
run: tar -xvzf ./output/*.tgz -C ./output
|
||||
working-directory: ./packages/create-llama
|
||||
- name: Run Playwright tests
|
||||
run: pnpm exec playwright test
|
||||
env:
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
working-directory: ./packages/create-llama
|
||||
- uses: actions/upload-artifact@v3
|
||||
if: always()
|
||||
with:
|
||||
name: playwright-report
|
||||
path: ./packages/create-llama/playwright-report/
|
||||
retention-days: 30
|
||||
@@ -13,9 +13,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v2
|
||||
with:
|
||||
version: latest
|
||||
- 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 ./packages/*
|
||||
@@ -0,0 +1,37 @@
|
||||
name: Publish to GitHub Releases
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "llamaindex@*"
|
||||
|
||||
jobs:
|
||||
build-and-publish:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Repo
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@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 tarball
|
||||
run: |
|
||||
pnpm pack
|
||||
working-directory: packages/llamaindex
|
||||
|
||||
- name: Create release
|
||||
uses: ncipollo/release-action@v1
|
||||
with:
|
||||
artifacts: "packages/llamaindex/llamaindex-*.tgz"
|
||||
name: Release ${{ github.ref }}
|
||||
bodyFile: "packages/llamaindex/CHANGELOG.md"
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -0,0 +1,70 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
concurrency: ${{ github.workflow }}-${{ github.ref }}
|
||||
|
||||
jobs:
|
||||
release:
|
||||
name: Release
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Repo
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: "pnpm"
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Add auth token to .npmrc file
|
||||
run: |
|
||||
cat << EOF >> ".npmrc"
|
||||
//registry.npmjs.org/:_authToken=$NPM_TOKEN
|
||||
EOF
|
||||
env:
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
|
||||
- name: Get changeset status
|
||||
id: get-changeset-status
|
||||
run: |
|
||||
pnpm changeset status --output .changeset/status.json
|
||||
new_version=$(jq -r '.releases[] | select(.name == "llamaindex") | .newVersion' < .changeset/status.json)
|
||||
rm -v .changeset/status.json
|
||||
echo "new-version=${new_version}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Create Release Pull Request or Publish to npm
|
||||
id: changesets
|
||||
uses: changesets/action@v1
|
||||
with:
|
||||
commit: Release ${{ steps.get-changeset-status.outputs.new-version }}
|
||||
title: Release ${{ steps.get-changeset-status.outputs.new-version }}
|
||||
# update version PR with the latest changesets
|
||||
version: pnpm new-version
|
||||
# build package and call changeset publish
|
||||
publish: pnpm release
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
|
||||
# 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"
|
||||
+106
-13
@@ -1,18 +1,68 @@
|
||||
name: Run Tests
|
||||
|
||||
on: [push, pull_request]
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
POSTGRES_HOST_AUTH_METHOD: trust
|
||||
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
|
||||
TURBO_TEAM: ${{ vars.TURBO_TEAM }}
|
||||
TURBO_REMOTE_ONLY: true
|
||||
|
||||
jobs:
|
||||
test:
|
||||
e2e:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
node-version: [18.x, 20.x, 22.x]
|
||||
name: E2E on Node.js ${{ matrix.node-version }}
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v2
|
||||
- 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:
|
||||
node-version-file: ".nvmrc"
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: "pnpm"
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
- name: Run E2E Tests
|
||||
run: pnpm run e2e
|
||||
|
||||
test:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
node-version: [18.x, 20.x, 22.x]
|
||||
name: Test on Node.js ${{ matrix.node-version }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: "pnpm"
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
@@ -23,7 +73,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v2
|
||||
- uses: pnpm/action-setup@v4
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
@@ -32,24 +82,55 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
- name: Build
|
||||
run: pnpm run build --filter llamaindex
|
||||
run: pnpm run build
|
||||
- name: Use Build For Examples
|
||||
run: pnpm link ../packages/llamaindex/
|
||||
working-directory: ./examples
|
||||
- name: Run Type Check
|
||||
run: pnpm run type-check
|
||||
- name: Run Circular Dependency Check
|
||||
run: pnpm run circular-check
|
||||
working-directory: ./packages/core
|
||||
run: pnpm dlx turbo run circular-check
|
||||
- uses: actions/upload-artifact@v3
|
||||
if: failure()
|
||||
with:
|
||||
name: typecheck-build-dist
|
||||
path: ./packages/core/dist
|
||||
path: ./packages/llamaindex/dist
|
||||
if-no-files-found: error
|
||||
e2e-llamaindex-examples:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
packages:
|
||||
- cloudflare-worker-agent
|
||||
- nextjs-agent
|
||||
- nextjs-edge-runtime
|
||||
- nextjs-node-runtime
|
||||
- waku-query-engine
|
||||
- llama-parse-browser
|
||||
runs-on: ubuntu-latest
|
||||
name: Build LlamaIndex Example (${{ matrix.packages }})
|
||||
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
|
||||
- name: Build ${{ matrix.packages }}
|
||||
run: pnpm run build
|
||||
working-directory: packages/llamaindex/e2e/examples/${{ matrix.packages }}
|
||||
|
||||
typecheck-examples:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v2
|
||||
- uses: pnpm/action-setup@v4
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
@@ -58,15 +139,27 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
- name: Build
|
||||
run: pnpm run build --filter llamaindex
|
||||
run: pnpm run build
|
||||
- name: Copy examples
|
||||
run: rsync -rv --exclude=node_modules ./examples ${{ runner.temp }}
|
||||
- name: Pack @llamaindex/cloud
|
||||
run: pnpm pack --pack-destination ${{ runner.temp }}
|
||||
working-directory: packages/cloud
|
||||
- name: Pack @llamaindex/openai
|
||||
run: pnpm pack --pack-destination ${{ runner.temp }}
|
||||
working-directory: packages/llm/openai
|
||||
- name: Pack @llamaindex/groq
|
||||
run: pnpm pack --pack-destination ${{ runner.temp }}
|
||||
working-directory: packages/llm/groq
|
||||
- name: Pack @llamaindex/core
|
||||
run: pnpm pack --pack-destination ${{ runner.temp }}
|
||||
working-directory: packages/core
|
||||
- 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
|
||||
working-directory: packages/llamaindex
|
||||
- name: Install
|
||||
run: npm add ${{ runner.temp }}/*.tgz
|
||||
working-directory: ${{ runner.temp }}/examples
|
||||
|
||||
@@ -44,6 +44,10 @@ test-results/
|
||||
playwright-report/
|
||||
blob-report/
|
||||
playwright/.cache/
|
||||
.tsbuildinfo
|
||||
|
||||
# intellij
|
||||
**/.idea
|
||||
|
||||
# generated API
|
||||
packages/cloud/src/client
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
pnpm test
|
||||
@@ -1,2 +1,5 @@
|
||||
auto-install-peers = true
|
||||
enable-pre-post-scripts = true
|
||||
prefer-workspace-packages = true
|
||||
save-workspace-protocol = true
|
||||
link-workspace-packages = true
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"jsc": {
|
||||
"parser": {
|
||||
"syntax": "typescript",
|
||||
"decorators": true
|
||||
},
|
||||
"target": "esnext",
|
||||
"transform": {
|
||||
"decoratorVersion": "2022-03"
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+2
-1
@@ -10,8 +10,9 @@
|
||||
"name": "Debug Example",
|
||||
"skipFiles": ["<node_internals>/**"],
|
||||
"runtimeExecutable": "pnpm",
|
||||
"console": "integratedTerminal",
|
||||
"cwd": "${workspaceFolder}/examples",
|
||||
"runtimeArgs": ["ts-node", "${fileBasename}"]
|
||||
"runtimeArgs": ["npx", "tsx", "${file}"]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
+24
-16
@@ -4,11 +4,11 @@
|
||||
|
||||
This is a monorepo built with Turborepo
|
||||
|
||||
Right now there are two packages of importance:
|
||||
Right now, for first-time contributors, these three packages are of the highest importance:
|
||||
|
||||
packages/core which is the main NPM library llamaindex
|
||||
|
||||
examples is where the demo code lives
|
||||
- `packages/llamaindex` which is the main NPM library `llamaindex`
|
||||
- `examples` is where the demo code lives
|
||||
- `apps/docs` is where the code for the documentation of https://ts.llamaindex.ai/ is located
|
||||
|
||||
### Turborepo docs
|
||||
|
||||
@@ -41,13 +41,13 @@ To run them, run
|
||||
pnpm run test
|
||||
```
|
||||
|
||||
To write new test cases write them in [packages/core/src/tests](/packages/core/src/tests)
|
||||
To write new test cases write them in [packages/llamaindex/tests](/packages/llamaindex/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
|
||||
We use Vitest https://vitest.dev to write our test cases. Vitest comes with a bunch of built-in assertions using the expect function: https://vitest.dev/api/expect.html#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.
|
||||
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 `llamaindex` package with a new demo, you need to run the build command in the README.
|
||||
|
||||
You can create new demo applications in the apps folder. Just run pnpm init in the folder after you create it to create its own package.json
|
||||
|
||||
@@ -56,7 +56,7 @@ You can create new demo applications in the apps folder. Just run pnpm init in t
|
||||
To install packages for a specific package or demo application, run
|
||||
|
||||
```
|
||||
pnpm add [NPM Package] --filter [package or application i.e. core or docs]
|
||||
pnpm add [NPM Package] --filter [package or application i.e. llamaindex or docs]
|
||||
```
|
||||
|
||||
To install packages for every package or application run
|
||||
@@ -79,14 +79,22 @@ That should start a webserver which will serve the docs on https://localhost:300
|
||||
|
||||
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.
|
||||
|
||||
## Publishing
|
||||
## Changeset
|
||||
|
||||
To publish a new version of the library, run
|
||||
We use [changesets](https://github.com/changesets/changesets) for managing versions and changelogs. To create a new changeset, run in the root folder:
|
||||
|
||||
```shell
|
||||
pnpm new-llamaindex
|
||||
pnpm new-create-llama
|
||||
pnpm release
|
||||
git push # push to the main branch
|
||||
git push --tags
|
||||
```
|
||||
pnpm changeset
|
||||
```
|
||||
|
||||
Please send a descriptive changeset for each PR.
|
||||
|
||||
## Publishing (maintainers only)
|
||||
|
||||
The [Release Github Action](.github/workflows/release.yml) is automatically generating and updating a
|
||||
PR called "Release {version}".
|
||||
|
||||
This PR will update the `package.json` and `CHANGELOG.md` files of each package according to
|
||||
the current changesets in the [.changeset](.changeset/) folder.
|
||||
|
||||
If this PR is merged it will automatically add version tags to the repository and publish the updated packages to NPM.
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
# Turborepo starter
|
||||
|
||||
This is an official starter Turborepo.
|
||||
|
||||
## Using this example
|
||||
|
||||
Run the following command:
|
||||
|
||||
```sh
|
||||
npx create-turbo@latest
|
||||
```
|
||||
|
||||
## What's inside?
|
||||
|
||||
This Turborepo includes the following packages/apps:
|
||||
|
||||
### Apps and Packages
|
||||
|
||||
- `docs`: a [Next.js](https://nextjs.org/) app
|
||||
- `web`: another [Next.js](https://nextjs.org/) app
|
||||
- `ui`: a stub React component library shared by both `web` and `docs` applications
|
||||
- `eslint-config-custom`: `eslint` configurations (includes `eslint-config-next` and `eslint-config-prettier`)
|
||||
- `tsconfig`: `tsconfig.json`s used throughout the monorepo
|
||||
|
||||
Each package/app is 100% [TypeScript](https://www.typescriptlang.org/).
|
||||
|
||||
### Utilities
|
||||
|
||||
This Turborepo has some additional tools already setup for you:
|
||||
|
||||
- [TypeScript](https://www.typescriptlang.org/) for static type checking
|
||||
- [ESLint](https://eslint.org/) for code linting
|
||||
- [Prettier](https://prettier.io) for code formatting
|
||||
|
||||
### Build
|
||||
|
||||
To build all apps and packages, run the following command:
|
||||
|
||||
```
|
||||
cd my-turborepo
|
||||
pnpm build
|
||||
```
|
||||
|
||||
### Develop
|
||||
|
||||
To develop all apps and packages, run the following command:
|
||||
|
||||
```
|
||||
cd my-turborepo
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
### Remote Caching
|
||||
|
||||
Turborepo can use a technique known as [Remote Caching](https://turbo.build/repo/docs/core-concepts/remote-caching) to share cache artifacts across machines, enabling you to share build caches with your team and CI/CD pipelines.
|
||||
|
||||
By default, Turborepo will cache locally. To enable Remote Caching you will need an account with Vercel. If you don't have an account you can [create one](https://vercel.com/signup), then enter the following commands:
|
||||
|
||||
```
|
||||
cd my-turborepo
|
||||
npx turbo login
|
||||
```
|
||||
|
||||
This will authenticate the Turborepo CLI with your [Vercel account](https://vercel.com/docs/concepts/personal-accounts/overview).
|
||||
|
||||
Next, you can link your Turborepo to your Remote Cache by running the following command from the root of your Turborepo:
|
||||
|
||||
```
|
||||
npx turbo link
|
||||
```
|
||||
|
||||
## Useful Links
|
||||
|
||||
Learn more about the power of Turborepo:
|
||||
|
||||
- [Tasks](https://turbo.build/repo/docs/core-concepts/monorepos/running-tasks)
|
||||
- [Caching](https://turbo.build/repo/docs/core-concepts/caching)
|
||||
- [Remote Caching](https://turbo.build/repo/docs/core-concepts/remote-caching)
|
||||
- [Filtering](https://turbo.build/repo/docs/core-concepts/monorepos/filtering)
|
||||
- [Configuration Options](https://turbo.build/repo/docs/reference/configuration)
|
||||
- [CLI Usage](https://turbo.build/repo/docs/reference/command-line-reference)
|
||||
@@ -19,25 +19,64 @@ 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.
|
||||
|
||||
## Getting started with an example:
|
||||
## Multiple JS Environment Support
|
||||
|
||||
LlamaIndex.TS requires Node v18 or higher. You can download it from https://nodejs.org or use https://nvm.sh (our preferred option).
|
||||
LlamaIndex.TS supports multiple JS environments, including:
|
||||
|
||||
In a new folder:
|
||||
- Node.js (18, 20, 22) ✅
|
||||
- Deno ✅
|
||||
- Bun ✅
|
||||
- React Server Components (Next.js) ✅
|
||||
|
||||
```bash
|
||||
export OPENAI_API_KEY="sk-......" # Replace with your key from https://platform.openai.com/account/api-keys
|
||||
pnpm init
|
||||
pnpm install typescript
|
||||
pnpm exec tsc --init # if needed
|
||||
For now, browser support is limited due to the lack of support for [AsyncLocalStorage-like APIs](https://github.com/tc39/proposal-async-context)
|
||||
|
||||
## Getting started
|
||||
|
||||
```shell
|
||||
npm install llamaindex
|
||||
pnpm install llamaindex
|
||||
pnpm install @types/node
|
||||
yarn add llamaindex
|
||||
```
|
||||
|
||||
Create the file example.ts
|
||||
### Setup TypeScript
|
||||
|
||||
```json5
|
||||
{
|
||||
compilerOptions: {
|
||||
// ⬇️ add this line to your tsconfig.json
|
||||
moduleResolution: "bundler", // or "node16"
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Why?</summary>
|
||||
We are shipping both ESM and CJS module, and compatible with Vercel Edge, Cloudflare Workers, and other serverless platforms.
|
||||
|
||||
So we are using [conditional exports](https://nodejs.org/api/packages.html#conditional-exports) to support all environments.
|
||||
|
||||
This is a kind of modern way of shipping packages, but might cause TypeScript type check to fail because of legacy module resolution.
|
||||
|
||||
Imaging you put output file into `/dist/openai.js` but you are importing `llamaindex/openai` in your code, and set `package.json` like this:
|
||||
|
||||
```json
|
||||
{
|
||||
"exports": {
|
||||
"./openai": "./dist/openai.js"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In old module resolution, TypeScript will not be able to find the module because it is not follow the file structure, even you run `node index.js` successfully. (on Node.js >=16)
|
||||
|
||||
See more about [moduleResolution](https://www.typescriptlang.org/docs/handbook/modules/theory.html#module-resolution) or
|
||||
[TypeScript 5.0 blog](https://devblogs.microsoft.com/typescript/announcing-typescript-5-0/#--moduleresolution-bundler7).
|
||||
|
||||
</details>
|
||||
|
||||
### Node.js
|
||||
|
||||
```ts
|
||||
// example.ts
|
||||
import fs from "fs/promises";
|
||||
import { Document, VectorStoreIndex } from "llamaindex";
|
||||
|
||||
@@ -67,10 +106,104 @@ async function main() {
|
||||
main();
|
||||
```
|
||||
|
||||
Then you can run it using
|
||||
|
||||
```bash
|
||||
pnpm dlx ts-node example.ts
|
||||
# `pnpm install tsx` before running the script
|
||||
node --import tsx ./main.ts
|
||||
```
|
||||
|
||||
### React Server Component (Next.js, Waku, Redwood.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(
|
||||
{
|
||||
message: question,
|
||||
chatHistory: prevMessages,
|
||||
},
|
||||
true,
|
||||
);
|
||||
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;
|
||||
}
|
||||
```
|
||||
|
||||
### Vite
|
||||
|
||||
We have some wasm dependencies for better performance. You can use `vite-plugin-wasm` to load them.
|
||||
|
||||
```ts
|
||||
import wasm from "vite-plugin-wasm";
|
||||
|
||||
export default {
|
||||
plugins: [wasm()],
|
||||
ssr: {
|
||||
external: ["tiktoken"],
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
## Playground
|
||||
@@ -79,53 +212,64 @@ 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/Embedding.ts): Embeddings are sets of floating point numbers which represent the data in a Node. By comparing the similarity of embeddings, we can derive an understanding of the similarity of two pieces of data. One use case is to compare the embedding of a question with the embeddings of our Nodes to see which Nodes may contain the data needed to answer that quesiton.
|
||||
- [Embedding](/packages/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/QueryEngine.ts): Query engines are what generate the query you put in and give you back the result. Query engines generally combine a pre-built prompt with selected Nodes from your Index to give the LLM the context it needs to answer your query.
|
||||
- [QueryEngine](/packages/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/ChatEngine.ts): A ChatEngine helps you build a chatbot that will interact with your Indices.
|
||||
- [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.
|
||||
- [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.
|
||||
|
||||
## Note: NextJS:
|
||||
## Tips when using in non-Node.js environments
|
||||
|
||||
If you're using NextJS App Router, you'll need to use the NodeJS runtime (default) and add the following config to your next.config.js to have it use imports/exports in the same way Node does.
|
||||
When you are importing `llamaindex` in a non-Node.js environment(such as React Server Components, Cloudflare Workers, etc.)
|
||||
Some classes are not exported from top-level entry file.
|
||||
|
||||
```js
|
||||
export const runtime = "nodejs"; // default
|
||||
The reason is that some classes are only compatible with Node.js runtime,(e.g. `PDFReader`) which uses Node.js specific APIs(like `fs`, `child_process`, `crypto`).
|
||||
|
||||
If you need any of those classes, you have to import them instead directly though their file path in the package.
|
||||
Here's an example for importing the `PineconeVectorStore` class:
|
||||
|
||||
```typescript
|
||||
import { PineconeVectorStore } from "llamaindex/storage/vectorStore/PineconeVectorStore";
|
||||
```
|
||||
|
||||
```js
|
||||
// next.config.js
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
experimental: {
|
||||
serverComponentsExternalPackages: ["pdf2json"],
|
||||
},
|
||||
webpack: (config) => {
|
||||
config.resolve.alias = {
|
||||
...config.resolve.alias,
|
||||
sharp$: false,
|
||||
"onnxruntime-node$": false,
|
||||
};
|
||||
return config;
|
||||
},
|
||||
};
|
||||
As the `PDFReader` is not working with the Edge runtime, here's how to use the `SimpleDirectoryReader` with the `LlamaParseReader` to load PDFs:
|
||||
|
||||
module.exports = nextConfig;
|
||||
```typescript
|
||||
import { SimpleDirectoryReader } from "llamaindex/readers/SimpleDirectoryReader";
|
||||
import { LlamaParseReader } from "llamaindex/readers/LlamaParseReader";
|
||||
|
||||
export const DATA_DIR = "./data";
|
||||
|
||||
export async function getDocuments() {
|
||||
const reader = new SimpleDirectoryReader();
|
||||
// Load PDFs using LlamaParseReader
|
||||
return await reader.loadData({
|
||||
directoryPath: DATA_DIR,
|
||||
fileExtToReader: {
|
||||
pdf: new LlamaParseReader({ resultType: "markdown" }),
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
> _Note_: Reader classes have to be added explictly to the `fileExtToReader` map in the Edge version of the `SimpleDirectoryReader`.
|
||||
|
||||
You'll find a complete example with LlamaIndexTS here: https://github.com/run-llama/create_llama_projects/tree/main/nextjs-edge-llamaparse
|
||||
|
||||
## Supported LLMs:
|
||||
|
||||
- OpenAI GPT-3.5-turbo and GPT-4
|
||||
- Anthropic Claude Instant and Claude 2
|
||||
- Llama2 Chat LLMs (70B, 13B, and 7B parameters)
|
||||
- Anthropic Claude 3 (Opus, Sonnet, and Haiku) and the legacy models (Claude 2 and Instant)
|
||||
- Groq LLMs
|
||||
- Llama2/3 Chat LLMs (70B, 13B, and 7B parameters)
|
||||
- MistralAI Chat LLMs
|
||||
- Fireworks Chat LLMs
|
||||
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
"llamaindex": minor
|
||||
"docs": minor
|
||||
---
|
||||
|
||||
Add deepseek llm class
|
||||
@@ -1,5 +1,612 @@
|
||||
# docs
|
||||
|
||||
## 0.0.77
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [8b7fdba]
|
||||
- llamaindex@0.6.8
|
||||
|
||||
## 0.0.76
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [23bcc37]
|
||||
- llamaindex@0.6.7
|
||||
|
||||
## 0.0.75
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [d902cc3]
|
||||
- Updated dependencies [025ffe6]
|
||||
- Updated dependencies [a659574]
|
||||
- llamaindex@0.6.6
|
||||
|
||||
## 0.0.74
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [e9714db]
|
||||
- llamaindex@0.6.5
|
||||
|
||||
## 0.0.73
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [b48bcc3]
|
||||
- llamaindex@0.6.4
|
||||
|
||||
## 0.0.72
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [2cd1383]
|
||||
- Updated dependencies [5c4badb]
|
||||
- llamaindex@0.6.3
|
||||
|
||||
## 0.0.71
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [749b43a]
|
||||
- llamaindex@0.6.2
|
||||
|
||||
## 0.0.70
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [fbd5e01]
|
||||
- Updated dependencies [6b70c54]
|
||||
- Updated dependencies [1a6137b]
|
||||
- Updated dependencies [85c2e19]
|
||||
- llamaindex@0.6.1
|
||||
|
||||
## 0.0.69
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [11feef8]
|
||||
- llamaindex@0.6.0
|
||||
- @llamaindex/examples@0.0.8
|
||||
|
||||
## 0.0.68
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [7edeb1c]
|
||||
- llamaindex@0.5.27
|
||||
|
||||
## 0.0.67
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [ffe0cd1]
|
||||
- Updated dependencies [ffe0cd1]
|
||||
- llamaindex@0.5.26
|
||||
|
||||
## 0.0.66
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [4810364]
|
||||
- Updated dependencies [d3bc663]
|
||||
- llamaindex@0.5.25
|
||||
|
||||
## 0.0.65
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- llamaindex@0.5.24
|
||||
|
||||
## 0.0.64
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- llamaindex@0.5.23
|
||||
|
||||
## 0.0.63
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [4648da6]
|
||||
- llamaindex@0.5.22
|
||||
|
||||
## 0.0.62
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [ae1149f]
|
||||
- Updated dependencies [2411c9f]
|
||||
- Updated dependencies [e8f229c]
|
||||
- Updated dependencies [11b3856]
|
||||
- Updated dependencies [83d7f41]
|
||||
- Updated dependencies [0148354]
|
||||
- Updated dependencies [1711f6d]
|
||||
- llamaindex@0.5.21
|
||||
|
||||
## 0.0.61
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [d9d6c56]
|
||||
- Updated dependencies [22ff486]
|
||||
- Updated dependencies [eed0b04]
|
||||
- llamaindex@0.5.20
|
||||
|
||||
## 0.0.60
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [fcbf183]
|
||||
- llamaindex@0.5.19
|
||||
|
||||
## 0.0.59
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [8b66cf4]
|
||||
- llamaindex@0.5.18
|
||||
|
||||
## 0.0.58
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [c654398]
|
||||
- llamaindex@0.5.17
|
||||
|
||||
## 0.0.57
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [58abc57]
|
||||
- llamaindex@0.5.16
|
||||
|
||||
## 0.0.56
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [01c184c]
|
||||
- Updated dependencies [07a275f]
|
||||
- llamaindex@0.5.15
|
||||
|
||||
## 0.0.55
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [c825a2f]
|
||||
- llamaindex@0.5.14
|
||||
|
||||
## 0.0.54
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- llamaindex@0.5.13
|
||||
|
||||
## 0.0.53
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [345300f]
|
||||
- Updated dependencies [da5cfc4]
|
||||
- Updated dependencies [da5cfc4]
|
||||
- llamaindex@0.5.12
|
||||
|
||||
## 0.0.52
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 376d29a: feat: added tool calling and agent support for llama3.1 504B
|
||||
- llamaindex@0.5.11
|
||||
|
||||
## 0.0.51
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 086b940: feat: add DeepSeek LLM
|
||||
- 5d5716b: feat: add a reader for JSON data
|
||||
- Updated dependencies [086b940]
|
||||
- Updated dependencies [5d5716b]
|
||||
- Updated dependencies [91d02a4]
|
||||
- Updated dependencies [fb6db45]
|
||||
- llamaindex@0.5.10
|
||||
|
||||
## 0.0.50
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [15962b3]
|
||||
- llamaindex@0.5.9
|
||||
|
||||
## 0.0.49
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [3d5ba08]
|
||||
- Updated dependencies [d917cdc]
|
||||
- llamaindex@0.5.8
|
||||
|
||||
## 0.0.48
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [ec59acd]
|
||||
- llamaindex@0.5.7
|
||||
|
||||
## 0.0.47
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [2562244]
|
||||
- Updated dependencies [325aa51]
|
||||
- Updated dependencies [ab700ea]
|
||||
- Updated dependencies [92f0782]
|
||||
- Updated dependencies [6cf6ae6]
|
||||
- Updated dependencies [b7cfe5b]
|
||||
- llamaindex@0.5.6
|
||||
|
||||
## 0.0.46
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [b974eea]
|
||||
- llamaindex@0.5.5
|
||||
|
||||
## 0.0.45
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [1a65ead]
|
||||
- llamaindex@0.5.4
|
||||
|
||||
## 0.0.44
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [9bbbc67]
|
||||
- Updated dependencies [b3681bf]
|
||||
- llamaindex@0.5.3
|
||||
|
||||
## 0.0.43
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- llamaindex@0.5.2
|
||||
|
||||
## 0.0.42
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 2774681: Add mixedbread's embeddings and reranking API
|
||||
- Updated dependencies [2774681]
|
||||
- Updated dependencies [a0f424e]
|
||||
- llamaindex@0.5.1
|
||||
|
||||
## 0.0.41
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 36ddec4: fix: typo in custom page separator parameter for LlamaParse
|
||||
- Updated dependencies [16ef5dd]
|
||||
- Updated dependencies [16ef5dd]
|
||||
- Updated dependencies [36ddec4]
|
||||
- llamaindex@0.5.0
|
||||
- @llamaindex/examples@0.0.7
|
||||
|
||||
## 0.0.40
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- llamaindex@0.4.14
|
||||
|
||||
## 0.0.39
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [e8f8bea]
|
||||
- Updated dependencies [304484b]
|
||||
- llamaindex@0.4.13
|
||||
|
||||
## 0.0.38
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [f326ab8]
|
||||
- llamaindex@0.4.12
|
||||
|
||||
## 0.0.37
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [8bf5b4a]
|
||||
- llamaindex@0.4.11
|
||||
|
||||
## 0.0.36
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [7dce3d2]
|
||||
- llamaindex@0.4.10
|
||||
|
||||
## 0.0.35
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [3a96a48]
|
||||
- llamaindex@0.4.9
|
||||
|
||||
## 0.0.34
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [83ebdfb]
|
||||
- llamaindex@0.4.8
|
||||
|
||||
## 0.0.33
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [41fe871]
|
||||
- Updated dependencies [321c39d]
|
||||
- Updated dependencies [f7f1af0]
|
||||
- llamaindex@0.4.7
|
||||
|
||||
## 0.0.32
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [1feb23b]
|
||||
- Updated dependencies [08c55ec]
|
||||
- llamaindex@0.4.6
|
||||
|
||||
## 0.0.31
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [6c3e5d0]
|
||||
- llamaindex@0.4.5
|
||||
|
||||
## 0.0.30
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [42eb73a]
|
||||
- llamaindex@0.4.4
|
||||
|
||||
## 0.0.29
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [2ef62a9]
|
||||
- llamaindex@0.4.3
|
||||
- @llamaindex/examples@0.0.6
|
||||
|
||||
## 0.0.28
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [a87a4d1]
|
||||
- Updated dependencies [0730140]
|
||||
- llamaindex@0.4.2
|
||||
|
||||
## 0.0.27
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [3c47910]
|
||||
- Updated dependencies [ed467a9]
|
||||
- Updated dependencies [cba5406]
|
||||
- llamaindex@0.4.1
|
||||
|
||||
## 0.0.26
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- b1a4a74: docs: updated Bedrock Opus region and added a basic README
|
||||
- Updated dependencies [436bc41]
|
||||
- Updated dependencies [a44e54f]
|
||||
- Updated dependencies [a51ed8d]
|
||||
- Updated dependencies [d3b635b]
|
||||
- llamaindex@0.4.0
|
||||
- @llamaindex/examples@0.0.5
|
||||
|
||||
## 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
|
||||
|
||||
@@ -0,0 +1,493 @@
|
||||
---
|
||||
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.
|
After Width: | Height: | Size: 178 KiB |
@@ -1,2 +1,2 @@
|
||||
label: Examples
|
||||
position: 2
|
||||
position: 3
|
||||
|
||||
@@ -4,82 +4,7 @@ A built-in agent that can take decisions and reasoning based on the tools provid
|
||||
|
||||
## OpenAI Agent
|
||||
|
||||
```ts
|
||||
import { FunctionTool, OpenAIAgent } from "llamaindex";
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../examples/agent/openai";
|
||||
|
||||
// Define a function to sum two numbers
|
||||
function sumNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
// Define a function to divide two numbers
|
||||
function divideNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a / b;
|
||||
}
|
||||
|
||||
// Define the parameters of the sum function as a JSON schema
|
||||
const sumJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The first number",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The second number",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
// Define the parameters of the divide function as a JSON schema
|
||||
const divideJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The dividend to divide",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The divisor to divide by",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
async function main() {
|
||||
// Create a function tool from the sum function
|
||||
const sumFunctionTool = new FunctionTool(sumNumbers, {
|
||||
name: "sumNumbers",
|
||||
description: "Use this function to sum two numbers",
|
||||
parameters: sumJSON,
|
||||
});
|
||||
|
||||
// Create a function tool from the divide function
|
||||
const divideFunctionTool = new FunctionTool(divideNumbers, {
|
||||
name: "divideNumbers",
|
||||
description: "Use this function to divide two numbers"
|
||||
parameters: divideJSON,
|
||||
});
|
||||
|
||||
// Create an OpenAIAgent with the function tools
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [sumFunctionTool, divideFunctionTool],
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
// Chat with the agent
|
||||
const response = await agent.chat({
|
||||
message: "How much is 5 + 5? then divide by 2",
|
||||
});
|
||||
|
||||
// Print the response
|
||||
console.log(String(response));
|
||||
}
|
||||
|
||||
main().then(() => {
|
||||
console.log("Done");
|
||||
});
|
||||
```
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
# Gemini Agent
|
||||
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSourceGemini from "!raw-loader!../../../../examples/gemini/agent.ts";
|
||||
|
||||
<CodeBlock language="ts">{CodeSourceGemini}</CodeBlock>
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
# 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,7 +1,23 @@
|
||||
---
|
||||
sidebar_position: 5
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# More examples
|
||||
# See all examples
|
||||
|
||||
You can check out more examples in the [examples](https://github.com/run-llama/LlamaIndexTS/tree/main/examples) folder of the repository.
|
||||
Our GitHub repository has a wealth of examples to explore and try out. You can check out our [examples folder](https://github.com/run-llama/LlamaIndexTS/tree/main/examples) to see them all at once, or browse the pages in this section for some selected highlights.
|
||||
|
||||
## Check out all examples
|
||||
|
||||
It may be useful to check out all the examples at once so you can try them out locally. To do this into a folder called `my-new-project`, run these commands:
|
||||
|
||||
```bash npm2yarn
|
||||
npx degit run-llama/LlamaIndexTS/examples my-new-project
|
||||
cd my-new-project
|
||||
npm install
|
||||
```
|
||||
|
||||
Then you can run any example in the folder with `tsx`, e.g.:
|
||||
|
||||
```bash npm2yarn
|
||||
npx tsx ./vectorIndex.ts
|
||||
```
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
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>
|
||||
@@ -32,7 +32,7 @@ LlamaIndex.TS help you prepare the knowledge base with a suite of data connector
|
||||
|
||||

|
||||
|
||||
[**Data Loaders**](../modules/data_loader.md):
|
||||
[**Data Loaders**](../modules/data_loaders/index.mdx):
|
||||
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.
|
||||
@@ -62,7 +62,7 @@ These building blocks can be customized to reflect ranking preferences, as well
|
||||
|
||||
[**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.
|
||||
The specific retrieval logic differs for different 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.
|
||||
|
||||
@@ -4,12 +4,19 @@ sidebar_position: 2
|
||||
|
||||
# Environments
|
||||
|
||||
LlamaIndex currently officially supports NodeJS 18 and NodeJS 20.
|
||||
We support Node.JS versions 18, 20 and 22, with experimental support for Deno, Bun and Vercel Edge functions.
|
||||
|
||||
## NextJS App Router
|
||||
## NextJS
|
||||
|
||||
If you're using NextJS App Router route handlers/serverless functions, you'll need to use the NodeJS mode:
|
||||
If you're using NextJS you'll need to add `withLlamaIndex` to your `next.config.js` file. This will add the necessary configuration for included 3rd-party libraries to your build:
|
||||
|
||||
```js
|
||||
export const runtime = "nodejs"; // default
|
||||
// next.config.js
|
||||
const withLlamaIndex = require("llamaindex/next");
|
||||
|
||||
module.exports = withLlamaIndex({
|
||||
// your next.js config
|
||||
});
|
||||
```
|
||||
|
||||
For details, check the latest [withLlamaIndex](https://github.com/run-llama/LlamaIndexTS/blob/main/packages/llamaindex/src/next.ts) implementation.
|
||||
|
||||
@@ -4,45 +4,7 @@ sidebar_position: 0
|
||||
|
||||
# Installation and Setup
|
||||
|
||||
Make sure you have NodeJS v18 or higher.
|
||||
|
||||
## Using create-llama
|
||||
|
||||
The easiest way to get started with LlamaIndex is by using `create-llama`. This CLI tool enables you to quickly start building a new LlamaIndex application, with everything set up for you.
|
||||
|
||||
Just run
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="1" label="npm" default>
|
||||
|
||||
```bash
|
||||
npx create-llama@latest
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="2" label="Yarn">
|
||||
|
||||
```bash
|
||||
yarn create llama
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="3" label="pnpm">
|
||||
|
||||
```bash
|
||||
pnpm create llama@latest
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
to get started. Once your app is generated, run
|
||||
|
||||
```bash npm2yarn
|
||||
npm run dev
|
||||
```
|
||||
|
||||
to start the development server. You can then visit [http://localhost:3000](http://localhost:3000) to see your app
|
||||
We support Node.JS versions 18, 20 and 22, with experimental support for Deno, Bun and Vercel Edge functions.
|
||||
|
||||
## Installation from NPM
|
||||
|
||||
@@ -52,12 +14,21 @@ npm install llamaindex
|
||||
|
||||
### Environment variables
|
||||
|
||||
Our examples use OpenAI by default. You'll need to set up your Open AI key like so:
|
||||
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 from https://platform.openai.com/account/api-keys
|
||||
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.
|
||||
**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,56 +0,0 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# Starter Tutorial
|
||||
|
||||
Once you have [installed LlamaIndex.TS using NPM](installation) and set up your OpenAI key, you're ready to start your first app:
|
||||
|
||||
In a new folder:
|
||||
|
||||
```bash npm2yarn
|
||||
npm install typescript
|
||||
npm install @types/node
|
||||
npx tsc --init # if needed
|
||||
```
|
||||
|
||||
Create the file `example.ts`. This code will load some example data, create a document, index it (which creates embeddings using OpenAI), and then creates query engine to answer questions about the data.
|
||||
|
||||
```ts
|
||||
// example.ts
|
||||
import fs from "fs/promises";
|
||||
import { Document, VectorStoreIndex } from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Load essay from abramov.txt in Node
|
||||
const essay = await fs.readFile(
|
||||
"node_modules/llamaindex/examples/abramov.txt",
|
||||
"utf-8",
|
||||
);
|
||||
|
||||
// Create Document object with essay
|
||||
const document = new Document({ text: essay });
|
||||
|
||||
// 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();
|
||||
```
|
||||
|
||||
Then you can run it using
|
||||
|
||||
```bash
|
||||
npx ts-node example.ts
|
||||
```
|
||||
|
||||
Ready to learn more? Check out our NextJS playground at https://llama-playground.vercel.app/. The source is available at https://github.com/run-llama/ts-playground
|
||||
@@ -0,0 +1,2 @@
|
||||
label: Starter Tutorials
|
||||
position: 1
|
||||
@@ -0,0 +1,49 @@
|
||||
---
|
||||
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
|
||||
```
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
# Chatbot tutorial
|
||||
|
||||
Once you've mastered basic [retrieval-augment generation](retrieval_augmented_generation) you may want to create an interface to chat with your data. You can do this step-by-step, but we recommend getting started quickly using `create-llama`.
|
||||
|
||||
## Using create-llama
|
||||
|
||||
`create-llama` is a powerful but easy to use command-line tool that generates a working, full-stack web application that allows you to chat with your data. You can learn more about it on [the `create-llama` README page](https://www.npmjs.com/package/create-llama).
|
||||
|
||||
Run it once and it will ask you a series of questions about the kind of application you want to generate. Then you can customize your application to suit your use-case. To get started, run:
|
||||
|
||||
```bash npm2yarn
|
||||
npx create-llama@latest
|
||||
```
|
||||
|
||||
Once your app is generated, `cd` into your app directory and run
|
||||
|
||||
```bash npm2yarn
|
||||
npm run dev
|
||||
```
|
||||
|
||||
to start the development server. You can then visit [http://localhost:3000](http://localhost:3000) to see your app, which should look something like this:
|
||||
|
||||

|
||||
Binary file not shown.
|
After Width: | Height: | Size: 540 KiB |
@@ -0,0 +1,58 @@
|
||||
---
|
||||
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).
|
||||
@@ -0,0 +1,52 @@
|
||||
---
|
||||
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"
|
||||
]
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,2 @@
|
||||
label: Guides
|
||||
position: 2
|
||||
@@ -0,0 +1,41 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# Getting started
|
||||
|
||||
In this guide we'll walk you through the process of building an Agent in JavaScript using the LlamaIndex.TS library, starting from nothing and adding complexity in stages.
|
||||
|
||||
## What is an Agent?
|
||||
|
||||
In LlamaIndex, an agent is a semi-autonomous piece of software powered by an LLM that is given a task and executes a series of steps towards solving that task. It is given a set of tools, which can be anything from arbitrary functions up to full LlamaIndex query engines, and it selects the best available tool to complete each step. When each step is completed, the agent judges whether the task is now complete, in which case it returns a result to the user, or whether it needs to take another step, in which case it loops back to the start.
|
||||
|
||||

|
||||
|
||||
## Install LlamaIndex.TS
|
||||
|
||||
You'll need to have a recent version of [Node.js](https://nodejs.org/en) installed. Then you can install LlamaIndex.TS by running
|
||||
|
||||
```bash
|
||||
npm install llamaindex
|
||||
```
|
||||
|
||||
## Choose your model
|
||||
|
||||
By default we'll be using OpenAI with GPT-4, as it's a powerful model and easy to get started with. If you'd prefer to run a local model, see [using a local model](local_model).
|
||||
|
||||
## Get an OpenAI API key
|
||||
|
||||
If you don't already have one, you can sign up for an [OpenAI API key](https://platform.openai.com/api-keys). You should then put the key in a `.env` file in the root of the project; the file should look like
|
||||
|
||||
```
|
||||
OPENAI_API_KEY=sk-XXXXXXXXXXXXXXXXXXXXXXXX
|
||||
```
|
||||
|
||||
We'll use `dotenv` to pull the API key out of that .env file, so also run:
|
||||
|
||||
```bash
|
||||
npm install dotenv
|
||||
```
|
||||
|
||||
Now you're ready to [create your agent](create_agent).
|
||||
@@ -0,0 +1,179 @@
|
||||
# Create a basic agent
|
||||
|
||||
We want to use `await` so we're going to wrap all of our code in a `main` function, like this:
|
||||
|
||||
```typescript
|
||||
// Your imports go here
|
||||
|
||||
async function main() {
|
||||
// the rest of your code goes here
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
```
|
||||
|
||||
For the rest of this guide we'll assume your code is wrapped like this so we can use `await`. You can run the code this way:
|
||||
|
||||
```bash
|
||||
npx tsx example.ts
|
||||
```
|
||||
|
||||
### Load your dependencies
|
||||
|
||||
First we'll need to pull in our dependencies. These are:
|
||||
|
||||
- The OpenAI class to use the OpenAI LLM
|
||||
- FunctionTool to provide tools to our agent
|
||||
- OpenAIAgent to create the agent itself
|
||||
- Settings to define some global settings for the library
|
||||
- Dotenv to load our API key from the .env file
|
||||
|
||||
```javascript
|
||||
import { OpenAI, FunctionTool, OpenAIAgent, Settings } from "llamaindex";
|
||||
import "dotenv/config";
|
||||
```
|
||||
|
||||
### Initialize your LLM
|
||||
|
||||
We need to tell our OpenAI class where its API key is, and which of OpenAI's models to use. We'll be using `gpt-4o`, which is capable while still being pretty cheap. This is a global setting, so anywhere an LLM is needed will use the same model.
|
||||
|
||||
```javascript
|
||||
Settings.llm = new OpenAI({
|
||||
apiKey: process.env.OPENAI_API_KEY,
|
||||
model: "gpt-4o",
|
||||
});
|
||||
```
|
||||
|
||||
### Turn on logging
|
||||
|
||||
We want to see what our agent is up to, so we're going to hook into some events that the library generates and print them out. There are several events possible, but we'll specifically tune in to `llm-tool-call` (when a tool is called) and `llm-tool-result` (when it responds).
|
||||
|
||||
```javascript
|
||||
Settings.callbackManager.on("llm-tool-call", (event) => {
|
||||
console.log(event.detail);
|
||||
});
|
||||
Settings.callbackManager.on("llm-tool-result", (event) => {
|
||||
console.log(event.detail);
|
||||
});
|
||||
```
|
||||
|
||||
### Create a function
|
||||
|
||||
We're going to create a very simple function that adds two numbers together. This will be the tool we ask our agent to use.
|
||||
|
||||
```javascript
|
||||
const sumNumbers = ({ a, b }) => {
|
||||
return `${a + b}`;
|
||||
};
|
||||
```
|
||||
|
||||
Note that we're passing in an object with two named parameters, `a` and `b`. This is a little unusual, but important for defining a tool that an LLM can use.
|
||||
|
||||
### Turn the function into a tool for the agent
|
||||
|
||||
This is the most complicated part of creating an agent. We need to define a `FunctionTool`. We have to pass in:
|
||||
|
||||
- The function itself (`sumNumbers`)
|
||||
- A name for the function, which the LLM will use to call it
|
||||
- A description of the function. The LLM will read this description to figure out what the tool does, and if it needs to call it
|
||||
- A schema for function. We tell the LLM that the parameter is an `object`, and we tell it about the two named parameters we gave it, `a` and `b`. We describe each parameter as a `number`, and we say that both are required.
|
||||
- You can see [more examples of function schemas](https://cookbook.openai.com/examples/how_to_call_functions_with_chat_models).
|
||||
|
||||
```javascript
|
||||
const tool = FunctionTool.from(sumNumbers, {
|
||||
name: "sumNumbers",
|
||||
description: "Use this function to sum two numbers",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "First number to sum",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "Second number to sum",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
We then wrap up the tools into an array. We could provide lots of tools this way, but for this example we're just using the one.
|
||||
|
||||
```javascript
|
||||
const tools = [tool];
|
||||
```
|
||||
|
||||
### Create the agent
|
||||
|
||||
With your LLM already set up and your tools defined, creating an agent is simple:
|
||||
|
||||
```javascript
|
||||
const agent = new OpenAIAgent({ tools });
|
||||
```
|
||||
|
||||
### Ask the agent a question
|
||||
|
||||
We can use the `chat` interface to ask our agent a question, and it will use the tools we've defined to find an answer.
|
||||
|
||||
```javascript
|
||||
let response = await agent.chat({
|
||||
message: "Add 101 and 303",
|
||||
});
|
||||
|
||||
console.log(response);
|
||||
```
|
||||
|
||||
Let's see what running this looks like using `npx tsx agent.ts`
|
||||
|
||||
**_Output_**
|
||||
|
||||
```javascript
|
||||
{
|
||||
toolCall: {
|
||||
id: 'call_ze6A8C3mOUBG4zmXO8Z4CPB5',
|
||||
name: 'sumNumbers',
|
||||
input: { a: 101, b: 303 }
|
||||
},
|
||||
toolResult: {
|
||||
tool: FunctionTool { _fn: [Function: sumNumbers], _metadata: [Object] },
|
||||
input: { a: 101, b: 303 },
|
||||
output: '404',
|
||||
isError: false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```javascript
|
||||
{
|
||||
response: {
|
||||
raw: {
|
||||
id: 'chatcmpl-9KwauZku3QOvH78MNvxJs81mDvQYK',
|
||||
object: 'chat.completion',
|
||||
created: 1714778824,
|
||||
model: 'gpt-4-turbo-2024-04-09',
|
||||
choices: [Array],
|
||||
usage: [Object],
|
||||
system_fingerprint: 'fp_ea6eb70039'
|
||||
},
|
||||
message: {
|
||||
content: 'The sum of 101 and 303 is 404.',
|
||||
role: 'assistant',
|
||||
options: {}
|
||||
}
|
||||
},
|
||||
sources: [Getter]
|
||||
}
|
||||
```
|
||||
|
||||
We're seeing two pieces of output here. The first is our callback firing when the tool is called. You can see in `toolResult` that the LLM has correctly passed `101` and `303` to our `sumNumbers` function, which adds them up and returns `404`.
|
||||
|
||||
The second piece of output is the response from the LLM itself, where the `message.content` key is giving us the answer.
|
||||
|
||||
Great! We've built an agent with tool use! Next you can:
|
||||
|
||||
- [See the full code](https://github.com/run-llama/ts-agents/blob/main/1_agent/agent.ts)
|
||||
- [Switch to a local LLM](local_model)
|
||||
- Move on to [add Retrieval-Augmented Generation to your agent](agentic_rag)
|
||||
@@ -0,0 +1,90 @@
|
||||
# Using a local model via Ollama
|
||||
|
||||
If you're happy using OpenAI, you can skip this section, but many people are interested in using models they run themselves. The easiest way to do this 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 it simply 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
|
||||
|
||||
There are two changes you need to make to the code we already wrote in `1_agent` to get Mixtral 8x7b to work. First, you need to switch to that model. Replace the call to `Settings.llm` with this:
|
||||
|
||||
```javascript
|
||||
Settings.llm = new Ollama({
|
||||
model: "mixtral:8x7b",
|
||||
});
|
||||
```
|
||||
|
||||
### Swap to a ReActAgent
|
||||
|
||||
In our original code we used a specific OpenAIAgent, so we'll need to switch to a more generic agent pattern, the ReAct pattern. This is simple: change the `const agent` line in your code to read
|
||||
|
||||
```javascript
|
||||
const agent = new ReActAgent({ tools });
|
||||
```
|
||||
|
||||
(You will also need to bring in `Ollama` and `ReActAgent` in your imports)
|
||||
|
||||
### Run your totally local agent
|
||||
|
||||
Because your embeddings were already local, your agent can now run entirely locally without making any API calls.
|
||||
|
||||
```bash
|
||||
node agent.mjs
|
||||
```
|
||||
|
||||
Note that your model will probably run a lot slower than OpenAI, so be prepared to wait a while!
|
||||
|
||||
**_Output_**
|
||||
|
||||
```javascript
|
||||
{
|
||||
response: {
|
||||
message: {
|
||||
role: 'assistant',
|
||||
content: ' Thought: I need to use a tool to add the numbers 101 and 303.\n' +
|
||||
'Action: sumNumbers\n' +
|
||||
'Action Input: {"a": 101, "b": 303}\n' +
|
||||
'\n' +
|
||||
'Observation: 404\n' +
|
||||
'\n' +
|
||||
'Thought: I can answer without using any more tools.\n' +
|
||||
'Answer: The sum of 101 and 303 is 404.'
|
||||
},
|
||||
raw: {
|
||||
model: 'mixtral:8x7b',
|
||||
created_at: '2024-05-09T00:24:30.339473Z',
|
||||
message: [Object],
|
||||
done: true,
|
||||
total_duration: 64678371209,
|
||||
load_duration: 57394551334,
|
||||
prompt_eval_count: 475,
|
||||
prompt_eval_duration: 4163981000,
|
||||
eval_count: 94,
|
||||
eval_duration: 3116692000
|
||||
}
|
||||
},
|
||||
sources: [Getter]
|
||||
}
|
||||
```
|
||||
|
||||
Tada! You can see all of this in the folder `1a_mixtral`.
|
||||
|
||||
### Extending to other examples
|
||||
|
||||
You can use a ReActAgent instead of an OpenAIAgent in any of the further examples below, but keep in mind that GPT-4 is a lot more capable than Mixtral 8x7b, so you may see more errors or failures in reasoning if you are using an entirely local setup.
|
||||
|
||||
### Next steps
|
||||
|
||||
Now you've got a local agent, you can [add Retrieval-Augmented Generation to your agent](agentic_rag).
|
||||
@@ -0,0 +1,165 @@
|
||||
# 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)!
|
||||
@@ -0,0 +1,128 @@
|
||||
# A RAG agent that does math
|
||||
|
||||
In [our third iteration of the agent](https://github.com/run-llama/ts-agents/blob/main/3_rag_and_tools/agent.ts) we've combined the two previous agents, so we've defined both `sumNumbers` and a `QueryEngineTool` and created an array of two tools:
|
||||
|
||||
```javascript
|
||||
// define the query engine as a tool
|
||||
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.`,
|
||||
},
|
||||
}),
|
||||
FunctionTool.from(sumNumbers, {
|
||||
name: "sumNumbers",
|
||||
description: "Use this function to sum two numbers",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "First number to sum",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "Second number to sum",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
},
|
||||
}),
|
||||
];
|
||||
```
|
||||
|
||||
These tool descriptions are identical to the ones we previously defined. Now let's ask it 3 questions in a row:
|
||||
|
||||
```javascript
|
||||
let response = await agent.chat({
|
||||
message:
|
||||
"What's the budget of San Francisco for community health in 2023-24?",
|
||||
});
|
||||
console.log(response);
|
||||
|
||||
let response2 = await agent.chat({
|
||||
message:
|
||||
"What's the budget of San Francisco for public protection in 2023-24?",
|
||||
});
|
||||
console.log(response2);
|
||||
|
||||
let response3 = await agent.chat({
|
||||
message:
|
||||
"What's the combined budget of San Francisco for community health and public protection in 2023-24?",
|
||||
});
|
||||
console.log(response3);
|
||||
```
|
||||
|
||||
We'll abbreviate the output, but here are the important things to spot:
|
||||
|
||||
```javascript
|
||||
{
|
||||
toolCall: {
|
||||
id: 'call_ZA1LPx03gO4ABre1r6XowLWq',
|
||||
name: 'san_francisco_budget_tool',
|
||||
input: { query: 'community health budget 2023-2024' }
|
||||
},
|
||||
toolResult: {
|
||||
tool: QueryEngineTool {
|
||||
queryEngine: [RetrieverQueryEngine],
|
||||
metadata: [Object]
|
||||
},
|
||||
input: { query: 'community health budget 2023-2024' },
|
||||
output: 'The proposed Fiscal Year (FY) 2023-24 budget for the Department of Public Health is $3.2 billion
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This is the first tool call, where it used the query engine to get the public health budget.
|
||||
|
||||
```javascript
|
||||
{
|
||||
toolCall: {
|
||||
id: 'call_oHu1KjEvA47ER6HYVfFIq9yp',
|
||||
name: 'san_francisco_budget_tool',
|
||||
input: { query: 'public protection budget 2023-2024' }
|
||||
},
|
||||
toolResult: {
|
||||
tool: QueryEngineTool {
|
||||
queryEngine: [RetrieverQueryEngine],
|
||||
metadata: [Object]
|
||||
},
|
||||
input: { query: 'public protection budget 2023-2024' },
|
||||
output: "The budget for Public Protection in San Francisco for Fiscal Year (FY) 2023-24 is $2,012.5 million."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In the second tool call, it got the police budget also from the query engine.
|
||||
|
||||
```javascript
|
||||
{
|
||||
toolCall: {
|
||||
id: 'call_SzG4yGUnLbv1T7IyaLAOqg3t',
|
||||
name: 'sumNumbers',
|
||||
input: { a: 3200, b: 2012.5 }
|
||||
},
|
||||
toolResult: {
|
||||
tool: FunctionTool { _fn: [Function: sumNumbers], _metadata: [Object] },
|
||||
input: { a: 3200, b: 2012.5 },
|
||||
output: '5212.5',
|
||||
isError: false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In the final tool call, it used the `sumNumbers` function to add the two budgets together. Perfect! This leads to the final answer:
|
||||
|
||||
```javascript
|
||||
{
|
||||
message: {
|
||||
content: 'The combined budget of San Francisco for community health and public protection in Fiscal Year (FY) 2023-24 is $5,212.5 million.',
|
||||
role: 'assistant',
|
||||
options: {}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Great! Now let's improve accuracy by improving our parsing with [LlamaParse](llamaparse).
|
||||
@@ -0,0 +1,18 @@
|
||||
# Adding LlamaParse
|
||||
|
||||
Complicated PDFs can be very tricky for LLMs to understand. To help with this, LlamaIndex provides LlamaParse, a hosted service that parses complex documents including PDFs. To use it, get a `LLAMA_CLOUD_API_KEY` by [signing up for LlamaCloud](https://cloud.llamaindex.ai/) (it's free for up to 1000 pages/day) and adding it to your `.env` file just as you did for your OpenAI key:
|
||||
|
||||
```bash
|
||||
LLAMA_CLOUD_API_KEY=llx-XXXXXXXXXXXXXXXX
|
||||
```
|
||||
|
||||
Then replace `SimpleDirectoryReader` with `LlamaParseReader`:
|
||||
|
||||
```javascript
|
||||
const reader = new LlamaParseReader({ resultType: "markdown" });
|
||||
const documents = await reader.loadData("../data/sf_budget_2023_2024.pdf");
|
||||
```
|
||||
|
||||
Now you will be able to ask more complicated questions of the same PDF and get better results. You can find this code [in our repo](https://github.com/run-llama/ts-agents/blob/main/4_llamaparse/agent.ts).
|
||||
|
||||
Next up, let's persist our embedded data so we don't have to re-parse every time by [using a vector store](qdrant).
|
||||
@@ -0,0 +1,75 @@
|
||||
# Adding persistent vector storage
|
||||
|
||||
In the previous examples, we've been loading our data into memory each time we run the agent. This is fine for small datasets, but for larger datasets you'll want to store your embeddings in a database. LlamaIndex.TS provides a `VectorStore` class that can store your embeddings in a variety of databases. We're going to use [Qdrant](https://qdrant.tech/), a popular vector store, for this example.
|
||||
|
||||
We can get a local instance of Qdrant running very simply with Docker (make sure you [install Docker](https://www.docker.com/products/docker-desktop/) first):
|
||||
|
||||
```bash
|
||||
docker pull qdrant/qdrant
|
||||
docker run -p 6333:6333 qdrant/qdrant
|
||||
```
|
||||
|
||||
And in our code we initialize a `VectorStore` with the Qdrant URL:
|
||||
|
||||
```javascript
|
||||
// initialize qdrant vector store
|
||||
const vectorStore = new QdrantVectorStore({
|
||||
url: "http://localhost:6333",
|
||||
});
|
||||
```
|
||||
|
||||
Now once we have loaded our documents, we can instantiate an index with the vector store:
|
||||
|
||||
```javascript
|
||||
// create a query engine from our documents
|
||||
const index = await VectorStoreIndex.fromDocuments(documents, { vectorStore });
|
||||
```
|
||||
|
||||
In [the final iteration](https://github.com/run-llama/ts-agents/blob/main/5_qdrant/agent.ts) you can see that we have also implemented a very naive caching mechanism to avoid re-parsing the PDF each time we run the agent:
|
||||
|
||||
```javascript
|
||||
// load cache.json and parse it
|
||||
let cache = {};
|
||||
let cacheExists = false;
|
||||
try {
|
||||
await fs.access(PARSING_CACHE, fs.constants.F_OK);
|
||||
cacheExists = true;
|
||||
} catch (e) {
|
||||
console.log("No cache found");
|
||||
}
|
||||
if (cacheExists) {
|
||||
cache = JSON.parse(await fs.readFile(PARSING_CACHE, "utf-8"));
|
||||
}
|
||||
|
||||
const filesToParse = ["../data/sf_budget_2023_2024.pdf"];
|
||||
|
||||
// load our data, reading only files we haven't seen before
|
||||
let documents = [];
|
||||
const reader = new LlamaParseReader({ resultType: "markdown" });
|
||||
for (let file of filesToParse) {
|
||||
if (!cache[file]) {
|
||||
documents = documents.concat(await reader.loadData(file));
|
||||
cache[file] = true;
|
||||
}
|
||||
}
|
||||
|
||||
// write the cache back to disk
|
||||
await fs.writeFile(PARSING_CACHE, JSON.stringify(cache));
|
||||
```
|
||||
|
||||
Since parsing a PDF can be slow, especially a large one, using the pre-parsed chunks in Qdrant can significantly speed up your agent.
|
||||
|
||||
## Next steps
|
||||
|
||||
In this guide you've learned how to
|
||||
|
||||
- [Create an agent](create_agent)
|
||||
- Use remote LLMs like GPT-4
|
||||
- [Use local LLMs like Mixtral](local_model)
|
||||
- [Create a RAG query engine](agentic_rag)
|
||||
- [Turn functions and query engines into agent tools](rag_and_tools)
|
||||
- Combine those tools
|
||||
- [Enhance your parsing with LlamaParse](llamaparse)
|
||||
- Persist your data in a vector store
|
||||
|
||||
The next steps are up to you! Try creating more complex functions and query engines, and set your agent loose on the world.
|
||||
@@ -0,0 +1,2 @@
|
||||
label: Agents
|
||||
position: 1
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 236 KiB |
@@ -3,33 +3,31 @@ sidebar_position: 0
|
||||
slug: /
|
||||
---
|
||||
|
||||
# What is LlamaIndex.TS?
|
||||
# What is LlamaIndex?
|
||||
|
||||
LlamaIndex.TS is a data framework for LLM applications to ingest, structure, and access private or domain-specific data. While a python package is also available (see [here](https://docs.llamaindex.ai/en/stable/)), LlamaIndex.TS offers core features in a simple package, optimized for usage with TypeScript.
|
||||
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?
|
||||
|
||||
At their core, 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.
|
||||
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. Unfortunately, that data can be distributed across siloed applications and data stores. It's behind APIs, in SQL databases, or trapped in PDFs and slide decks.
|
||||
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.
|
||||
|
||||
That's where **LlamaIndex.TS** comes in.
|
||||
LlamaIndex.TS helps you unlock that data and then build powerful applications with it.
|
||||
|
||||
## 🦙 How can LlamaIndex.TS help?
|
||||
## 🦙 What is LlamaIndex for?
|
||||
|
||||
LlamaIndex.TS provides the following tools:
|
||||
LlamaIndex.TS handles several major use cases:
|
||||
|
||||
- **Data loading** ingest your existing `.txt`, `.pdf`, `.csv`, `.md` and `.docx` data directly
|
||||
- **Data indexes** structure your data in intermediate representations that are easy and performant for LLMs to consume.
|
||||
- **Engines** provide natural language access to your data. For example:
|
||||
- Query engines are powerful retrieval interfaces for knowledge-augmented output.
|
||||
- Chat engines are conversational interfaces for multi-message, "back and forth" interactions with your data.
|
||||
- **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 interactive, unsupervised manner.
|
||||
|
||||
## 👨👩👧👦 Who is LlamaIndex for?
|
||||
|
||||
LlamaIndex.TS provides a core set of tools, essential for anyone building LLM apps with JavaScript and TypeScript.
|
||||
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 and query their data.
|
||||
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.
|
||||
|
||||
@@ -37,7 +35,7 @@ For more complex applications, our lower-level APIs allow advanced users to cust
|
||||
|
||||
`npm install llamaindex`
|
||||
|
||||
Our documentation includes [Installation Instructions](./getting_started/installation.mdx) and a [Starter Tutorial](./getting_started/starter.md) to build your first application.
|
||||
Our documentation includes [Installation Instructions](./getting_started/installation.mdx) and a [Starter Tutorial](./getting_started/starter_tutorial/retrieval_augmented_generation.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.
|
||||
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
label: "Agents"
|
||||
position: 3
|
||||
position: 10
|
||||
|
||||
@@ -11,4 +11,19 @@ An “agent” is an automated reasoning and decision engine. It takes in a user
|
||||
|
||||
LlamaIndex.TS comes with a few built-in agents, but you can also create your own. The built-in agents include:
|
||||
|
||||
- [OpenAI Agent](./openai.mdx)
|
||||
- OpenAI Agent
|
||||
- Anthropic Agent both via Anthropic and Bedrock (in `@llamaIndex/community`)
|
||||
- Gemini Agent
|
||||
- ReACT Agent
|
||||
- Meta3.1 504B via Bedrock (in `@llamaIndex/community`)
|
||||
|
||||
## Examples
|
||||
|
||||
- [OpenAI Agent](../../examples/agent.mdx)
|
||||
- [Gemini Agent](../../examples/agent_gemini.mdx)
|
||||
|
||||
## Api References
|
||||
|
||||
- [OpenAIAgent](../../api/classes/OpenAIAgent.md)
|
||||
- [AnthropicAgent](../../api/classes/AnthropicAgent.md)
|
||||
- [ReActAgent](../../api/classes/ReActAgent.md)
|
||||
|
||||
@@ -1,314 +0,0 @@
|
||||
# Multi-Document Agent
|
||||
|
||||
In this guide, you learn towards setting up an agent that can effectively answer different types of questions over a larger set of documents.
|
||||
|
||||
These questions include the following
|
||||
|
||||
- QA over a specific doc
|
||||
- QA comparing different docs
|
||||
- Summaries over a specific doc
|
||||
- Comparing summaries between different docs
|
||||
|
||||
We do this with the following architecture:
|
||||
|
||||
- setup a “document agent” over each Document: each doc agent can do QA/summarization within its doc
|
||||
- setup a top-level agent over this set of document agents. Do tool retrieval and then do CoT over the set of tools to answer a question.
|
||||
|
||||
## Setup and Download Data
|
||||
|
||||
We first start by installing the necessary libraries and downloading the data.
|
||||
|
||||
```bash
|
||||
pnpm i llamaindex
|
||||
```
|
||||
|
||||
```ts
|
||||
import {
|
||||
Document,
|
||||
ObjectIndex,
|
||||
OpenAI,
|
||||
OpenAIAgent,
|
||||
QueryEngineTool,
|
||||
SimpleNodeParser,
|
||||
SimpleToolNodeMapping,
|
||||
SummaryIndex,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
storageContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
```
|
||||
|
||||
And then for the data we will run through a list of countries and download the wikipedia page for each country.
|
||||
|
||||
```ts
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
const dataPath = path.join(__dirname, "tmp_data");
|
||||
|
||||
const extractWikipediaTitle = async (title: string) => {
|
||||
const fileExists = fs.existsSync(path.join(dataPath, `${title}.txt`));
|
||||
|
||||
if (fileExists) {
|
||||
console.log(`File already exists for the title: ${title}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const queryParams = new URLSearchParams({
|
||||
action: "query",
|
||||
format: "json",
|
||||
titles: title,
|
||||
prop: "extracts",
|
||||
explaintext: "true",
|
||||
});
|
||||
|
||||
const url = `https://en.wikipedia.org/w/api.php?${queryParams}`;
|
||||
|
||||
const response = await fetch(url);
|
||||
const data: any = await response.json();
|
||||
|
||||
const pages = data.query.pages;
|
||||
const page = pages[Object.keys(pages)[0]];
|
||||
const wikiText = page.extract;
|
||||
|
||||
await new Promise((resolve) => {
|
||||
fs.writeFile(path.join(dataPath, `${title}.txt`), wikiText, (err: any) => {
|
||||
if (err) {
|
||||
console.error(err);
|
||||
resolve(title);
|
||||
return;
|
||||
}
|
||||
console.log(`${title} stored in file!`);
|
||||
|
||||
resolve(title);
|
||||
});
|
||||
});
|
||||
};
|
||||
```
|
||||
|
||||
```ts
|
||||
export const extractWikipedia = async (titles: string[]) => {
|
||||
if (!fs.existsSync(dataPath)) {
|
||||
fs.mkdirSync(dataPath);
|
||||
}
|
||||
|
||||
for await (const title of titles) {
|
||||
await extractWikipediaTitle(title);
|
||||
}
|
||||
|
||||
console.log("Extration finished!");
|
||||
```
|
||||
|
||||
These files will be saved in the `tmp_data` folder.
|
||||
|
||||
Now we can call the function to download the data for each country.
|
||||
|
||||
```ts
|
||||
await extractWikipedia([
|
||||
"Brazil",
|
||||
"United States",
|
||||
"Canada",
|
||||
"Mexico",
|
||||
"Argentina",
|
||||
"Chile",
|
||||
"Colombia",
|
||||
"Peru",
|
||||
"Venezuela",
|
||||
"Ecuador",
|
||||
"Bolivia",
|
||||
"Paraguay",
|
||||
"Uruguay",
|
||||
"Guyana",
|
||||
"Suriname",
|
||||
"French Guiana",
|
||||
"Falkland Islands",
|
||||
]);
|
||||
```
|
||||
|
||||
## Load the data
|
||||
|
||||
Now that we have the data, we can load it into the LlamaIndex and store as a document.
|
||||
|
||||
```ts
|
||||
import { Document } from "llamaindex";
|
||||
|
||||
const countryDocs: Record<string, Document> = {};
|
||||
|
||||
for (const title of wikiTitles) {
|
||||
const path = `./agent/helpers/tmp_data/${title}.txt`;
|
||||
const text = await fs.readFile(path, "utf-8");
|
||||
const document = new Document({ text: text, id_: path });
|
||||
countryDocs[title] = document;
|
||||
}
|
||||
```
|
||||
|
||||
## Setup LLM and StorageContext
|
||||
|
||||
We will be using gpt-4 for this example and we will use the `StorageContext` to store the documents in-memory.
|
||||
|
||||
```ts
|
||||
const llm = new OpenAI({
|
||||
model: "gpt-4",
|
||||
});
|
||||
|
||||
const ctx = serviceContextFromDefaults({ llm });
|
||||
|
||||
const storageContext = await storageContextFromDefaults({
|
||||
persistDir: "./storage",
|
||||
});
|
||||
```
|
||||
|
||||
## Building Multi-Document Agents
|
||||
|
||||
In this section we show you how to construct the multi-document agent. We first build a document agent for each document, and then define the top-level parent agent with an object index.
|
||||
|
||||
```ts
|
||||
const documentAgents: Record<string, any> = {};
|
||||
const queryEngines: Record<string, any> = {};
|
||||
```
|
||||
|
||||
Now we iterate over each country and create a document agent for each one.
|
||||
|
||||
### Build Agent for each Document
|
||||
|
||||
In this section we define “document agents” for each document.
|
||||
|
||||
We define both a vector index (for semantic search) and summary index (for summarization) for each document. The two query engines are then converted into tools that are passed to an OpenAI function calling agent.
|
||||
|
||||
This document agent can dynamically choose to perform semantic search or summarization within a given document.
|
||||
|
||||
We create a separate document agent for each coutnry.
|
||||
|
||||
```ts
|
||||
for (const title of wikiTitles) {
|
||||
// parse the document into nodes
|
||||
const nodes = new SimpleNodeParser({
|
||||
chunkSize: 200,
|
||||
chunkOverlap: 20,
|
||||
}).getNodesFromDocuments([countryDocs[title]]);
|
||||
|
||||
// create the vector index for specific search
|
||||
const vectorIndex = await VectorStoreIndex.init({
|
||||
serviceContext: serviceContext,
|
||||
storageContext: storageContext,
|
||||
nodes,
|
||||
});
|
||||
|
||||
// create the summary index for broader search
|
||||
const summaryIndex = await SummaryIndex.init({
|
||||
serviceContext: serviceContext,
|
||||
nodes,
|
||||
});
|
||||
|
||||
const vectorQueryEngine = summaryIndex.asQueryEngine();
|
||||
const summaryQueryEngine = summaryIndex.asQueryEngine();
|
||||
|
||||
// create the query engines for each task
|
||||
const queryEngineTools = [
|
||||
new QueryEngineTool({
|
||||
queryEngine: vectorQueryEngine,
|
||||
metadata: {
|
||||
name: "vector_tool",
|
||||
description: `Useful for questions related to specific aspects of ${title} (e.g. the history, arts and culture, sports, demographics, or more).`,
|
||||
},
|
||||
}),
|
||||
new QueryEngineTool({
|
||||
queryEngine: summaryQueryEngine,
|
||||
metadata: {
|
||||
name: "summary_tool",
|
||||
description: `Useful for any requests that require a holistic summary of EVERYTHING about ${title}. For questions about more specific sections, please use the vector_tool.`,
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
// create the document agent
|
||||
const agent = new OpenAIAgent({
|
||||
tools: queryEngineTools,
|
||||
llm,
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
documentAgents[title] = agent;
|
||||
queryEngines[title] = vectorIndex.asQueryEngine();
|
||||
}
|
||||
```
|
||||
|
||||
## Build Top-Level Agent
|
||||
|
||||
Now we define the top-level agent that can answer questions over the set of document agents.
|
||||
|
||||
This agent takes in all document agents as tools. This specific agent RetrieverOpenAIAgent performs tool retrieval before tool use (unlike a default agent that tries to put all tools in the prompt).
|
||||
|
||||
Here we use a top-k retriever, but we encourage you to customize the tool retriever method!
|
||||
|
||||
Firstly, we create a tool for each document agent
|
||||
|
||||
```ts
|
||||
const allTools: QueryEngineTool[] = [];
|
||||
```
|
||||
|
||||
```ts
|
||||
for (const title of wikiTitles) {
|
||||
const wikiSummary = `
|
||||
This content contains Wikipedia articles about ${title}.
|
||||
Use this tool if you want to answer any questions about ${title}
|
||||
`;
|
||||
|
||||
const docTool = new QueryEngineTool({
|
||||
queryEngine: documentAgents[title],
|
||||
metadata: {
|
||||
name: `tool_${title}`,
|
||||
description: wikiSummary,
|
||||
},
|
||||
});
|
||||
|
||||
allTools.push(docTool);
|
||||
}
|
||||
```
|
||||
|
||||
Our top level agent will use this document agents as tools and use toolRetriever to retrieve the best tool to answer a question.
|
||||
|
||||
```ts
|
||||
// map the tools to nodes
|
||||
const toolMapping = SimpleToolNodeMapping.fromObjects(allTools);
|
||||
|
||||
// create the object index
|
||||
const objectIndex = await ObjectIndex.fromObjects(
|
||||
allTools,
|
||||
toolMapping,
|
||||
VectorStoreIndex,
|
||||
{
|
||||
serviceContext,
|
||||
storageContext,
|
||||
},
|
||||
);
|
||||
|
||||
// create the top agent
|
||||
const topAgent = new OpenAIAgent({
|
||||
toolRetriever: await objectIndex.asRetriever({}),
|
||||
llm,
|
||||
verbose: true,
|
||||
prefixMessages: [
|
||||
{
|
||||
content:
|
||||
"You are an agent designed to answer queries about a set of given countries. Please always use the tools provided to answer a question. Do not rely on prior knowledge.",
|
||||
role: "system",
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Use the Agent
|
||||
|
||||
Now we can use the agent to answer questions.
|
||||
|
||||
```ts
|
||||
const response = await topAgent.chat({
|
||||
message: "Tell me the differences between Brazil and Canada economics?",
|
||||
});
|
||||
|
||||
// print output
|
||||
console.log(response);
|
||||
```
|
||||
|
||||
You can find the full code for this example [here](https://github.com/run-llama/LlamaIndexTS/tree/main/examples/agent/multi-document-agent.ts)
|
||||
@@ -1,187 +0,0 @@
|
||||
---
|
||||
sidebar_position: 0
|
||||
---
|
||||
|
||||
# OpenAI Agent
|
||||
|
||||
OpenAI API that supports function calling, it’s never been easier to build your own agent!
|
||||
|
||||
In this notebook tutorial, we showcase how to write your own OpenAI agent
|
||||
|
||||
## Setup
|
||||
|
||||
First, you need to install the `llamaindex` package. You can do this by running the following command in your terminal:
|
||||
|
||||
```bash
|
||||
pnpm i llamaindex
|
||||
```
|
||||
|
||||
Then we can define a function to sum two numbers and another function to divide two numbers.
|
||||
|
||||
```ts
|
||||
function sumNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
// Define a function to divide two numbers
|
||||
function divideNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a / b;
|
||||
}
|
||||
```
|
||||
|
||||
## Create a function tool
|
||||
|
||||
Now we can create a function tool from the sum function and another function tool from the divide function.
|
||||
|
||||
For the parameters of the sum function, we can define a JSON schema.
|
||||
|
||||
### JSON Schema
|
||||
|
||||
```ts
|
||||
const sumJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The first number",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The second number",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
const divideJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The dividend a to divide",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The divisor b to divide by",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
const sumFunctionTool = new FunctionTool(sumNumbers, {
|
||||
name: "sumNumbers",
|
||||
description: "Use this function to sum two numbers",
|
||||
parameters: sumJSON,
|
||||
});
|
||||
|
||||
const divideFunctionTool = new FunctionTool(divideNumbers, {
|
||||
name: "divideNumbers",
|
||||
description: "Use this function to divide two numbers",
|
||||
parameters: divideJSON,
|
||||
});
|
||||
```
|
||||
|
||||
## Create an OpenAIAgent
|
||||
|
||||
Now we can create an OpenAIAgent with the function tools.
|
||||
|
||||
```ts
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [sumFunctionTool, divideFunctionTool],
|
||||
verbose: true,
|
||||
});
|
||||
```
|
||||
|
||||
## Chat with the agent
|
||||
|
||||
Now we can chat with the agent.
|
||||
|
||||
```ts
|
||||
const response = await agent.chat({
|
||||
message: "How much is 5 + 5? then divide by 2",
|
||||
});
|
||||
|
||||
console.log(String(response));
|
||||
```
|
||||
|
||||
## Full code
|
||||
|
||||
```ts
|
||||
import { FunctionTool, OpenAIAgent } from "llamaindex";
|
||||
|
||||
// Define a function to sum two numbers
|
||||
function sumNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
// Define a function to divide two numbers
|
||||
function divideNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a / b;
|
||||
}
|
||||
|
||||
// Define the parameters of the sum function as a JSON schema
|
||||
const sumJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The first number",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The second number",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
// Define the parameters of the divide function as a JSON schema
|
||||
const divideJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The argument a to divide",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The argument b to divide",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
async function main() {
|
||||
// Create a function tool from the sum function
|
||||
const sumFunctionTool = new FunctionTool(sumNumbers, {
|
||||
name: "sumNumbers",
|
||||
description: "Use this function to sum two numbers",
|
||||
parameters: sumJSON,
|
||||
});
|
||||
|
||||
// Create a function tool from the divide function
|
||||
const divideFunctionTool = new FunctionTool(divideNumbers, {
|
||||
name: "divideNumbers",
|
||||
description: "Use this function to divide two numbers",
|
||||
parameters: divideJSON,
|
||||
});
|
||||
|
||||
// Create an OpenAIAgent with the function tools
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [sumFunctionTool, divideFunctionTool],
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
// Chat with the agent
|
||||
const response = await agent.chat({
|
||||
message: "How much is 5 + 5? then divide by 2",
|
||||
});
|
||||
|
||||
// Print the response
|
||||
console.log(String(response));
|
||||
}
|
||||
|
||||
main().then(() => {
|
||||
console.log("Done");
|
||||
});
|
||||
```
|
||||
@@ -1,132 +0,0 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# OpenAI Agent + QueryEngineTool
|
||||
|
||||
QueryEngineTool is a tool that allows you to query a vector index. In this example, we will create a vector index from a set of documents and then create a QueryEngineTool from the vector index. We will then create an OpenAIAgent with the QueryEngineTool and chat with the agent.
|
||||
|
||||
## Setup
|
||||
|
||||
First, you need to install the `llamaindex` package. You can do this by running the following command in your terminal:
|
||||
|
||||
```bash
|
||||
pnpm i llamaindex
|
||||
```
|
||||
|
||||
Then you can import the necessary classes and functions.
|
||||
|
||||
```ts
|
||||
import {
|
||||
OpenAIAgent,
|
||||
SimpleDirectoryReader,
|
||||
VectorStoreIndex,
|
||||
QueryEngineTool,
|
||||
} from "llamaindex";
|
||||
```
|
||||
|
||||
## Create a vector index
|
||||
|
||||
Now we can create a vector index from a set of documents.
|
||||
|
||||
```ts
|
||||
// Load the documents
|
||||
const documents = await new SimpleDirectoryReader().loadData({
|
||||
directoryPath: "node_modules/llamaindex/examples/",
|
||||
});
|
||||
|
||||
// Create a vector index from the documents
|
||||
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
|
||||
```
|
||||
|
||||
## Create a QueryEngineTool
|
||||
|
||||
Now we can create a QueryEngineTool from the vector index.
|
||||
|
||||
```ts
|
||||
// Create a query engine from the vector index
|
||||
const abramovQueryEngine = vectorIndex.asQueryEngine();
|
||||
|
||||
// Create a QueryEngineTool with the query engine
|
||||
const queryEngineTool = new QueryEngineTool({
|
||||
queryEngine: abramovQueryEngine,
|
||||
metadata: {
|
||||
name: "abramov_query_engine",
|
||||
description: "A query engine for the Abramov documents",
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
## Create an OpenAIAgent
|
||||
|
||||
```ts
|
||||
// Create an OpenAIAgent with the query engine tool tools
|
||||
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [queryEngineTool],
|
||||
verbose: true,
|
||||
});
|
||||
```
|
||||
|
||||
## Chat with the agent
|
||||
|
||||
Now we can chat with the agent.
|
||||
|
||||
```ts
|
||||
const response = await agent.chat({
|
||||
message: "What was his salary?",
|
||||
});
|
||||
|
||||
console.log(String(response));
|
||||
```
|
||||
|
||||
## Full code
|
||||
|
||||
```ts
|
||||
import {
|
||||
OpenAIAgent,
|
||||
SimpleDirectoryReader,
|
||||
VectorStoreIndex,
|
||||
QueryEngineTool,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Load the documents
|
||||
const documents = await new SimpleDirectoryReader().loadData({
|
||||
directoryPath: "node_modules/llamaindex/examples/",
|
||||
});
|
||||
|
||||
// Create a vector index from the documents
|
||||
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
|
||||
|
||||
// Create a query engine from the vector index
|
||||
const abramovQueryEngine = vectorIndex.asQueryEngine();
|
||||
|
||||
// Create a QueryEngineTool with the query engine
|
||||
const queryEngineTool = new QueryEngineTool({
|
||||
queryEngine: abramovQueryEngine,
|
||||
metadata: {
|
||||
name: "abramov_query_engine",
|
||||
description: "A query engine for the Abramov documents",
|
||||
},
|
||||
});
|
||||
|
||||
// Create an OpenAIAgent with the function tools
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [queryEngineTool],
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
// Chat with the agent
|
||||
const response = await agent.chat({
|
||||
message: "What was his salary?",
|
||||
});
|
||||
|
||||
// Print the response
|
||||
console.log(String(response));
|
||||
}
|
||||
|
||||
main().then(() => {
|
||||
console.log("Done");
|
||||
});
|
||||
```
|
||||
@@ -1,203 +0,0 @@
|
||||
# ReAct Agent
|
||||
|
||||
The ReAct agent is an AI agent that can reason over the next action, construct an action command, execute the action, and repeat these steps in an iterative loop until the task is complete.
|
||||
|
||||
In this notebook tutorial, we showcase how to write your ReAct agent using the `llamaindex` package.
|
||||
|
||||
## Setup
|
||||
|
||||
First, you need to install the `llamaindex` package. You can do this by running the following command in your terminal:
|
||||
|
||||
```bash
|
||||
pnpm i llamaindex
|
||||
```
|
||||
|
||||
And then you can import the `OpenAIAgent` and `FunctionTool` from the `llamaindex` package.
|
||||
|
||||
```ts
|
||||
import { FunctionTool, OpenAIAgent } from "llamaindex";
|
||||
```
|
||||
|
||||
Then we can define a function to sum two numbers and another function to divide two numbers.
|
||||
|
||||
```ts
|
||||
function sumNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
// Define a function to divide two numbers
|
||||
function divideNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a / b;
|
||||
}
|
||||
```
|
||||
|
||||
## Create a function tool
|
||||
|
||||
Now we can create a function tool from the sum function and another function tool from the divide function.
|
||||
|
||||
For the parameters of the sum function, we can define a JSON schema.
|
||||
|
||||
### JSON Schema
|
||||
|
||||
```ts
|
||||
const sumJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The first number",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The second number",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
const divideJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The dividend a to divide",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The divisor b to divide by",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
const sumFunctionTool = new FunctionTool(sumNumbers, {
|
||||
name: "sumNumbers",
|
||||
description: "Use this function to sum two numbers",
|
||||
parameters: sumJSON,
|
||||
});
|
||||
|
||||
const divideFunctionTool = new FunctionTool(divideNumbers, {
|
||||
name: "divideNumbers",
|
||||
description: "Use this function to divide two numbers",
|
||||
parameters: divideJSON,
|
||||
});
|
||||
```
|
||||
|
||||
## Create an ReAct
|
||||
|
||||
Now we can create an OpenAIAgent with the function tools.
|
||||
|
||||
```ts
|
||||
const agent = new ReActAgent({
|
||||
tools: [sumFunctionTool, divideFunctionTool],
|
||||
verbose: true,
|
||||
});
|
||||
```
|
||||
|
||||
## Chat with the agent
|
||||
|
||||
Now we can chat with the agent.
|
||||
|
||||
```ts
|
||||
const response = await agent.chat({
|
||||
message: "How much is 5 + 5? then divide by 2",
|
||||
});
|
||||
|
||||
console.log(String(response));
|
||||
```
|
||||
|
||||
The output will be:
|
||||
|
||||
```bash
|
||||
Thought: I need to use a tool to help me answer the question.
|
||||
Action: sumNumbers
|
||||
Action Input: {"a":5,"b":5}
|
||||
|
||||
Observation: 10
|
||||
Thought: I can answer without using any more tools.
|
||||
Answer: The sum of 5 and 5 is 10, and when divided by 2, the result is 5.
|
||||
|
||||
The sum of 5 and 5 is 10, and when divided by 2, the result is 5.
|
||||
```
|
||||
|
||||
## Full code
|
||||
|
||||
```ts
|
||||
import { FunctionTool, ReActAgent } from "llamaindex";
|
||||
|
||||
// Define a function to sum two numbers
|
||||
function sumNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
// Define a function to divide two numbers
|
||||
function divideNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a / b;
|
||||
}
|
||||
|
||||
// Define the parameters of the sum function as a JSON schema
|
||||
const sumJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The first number",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The second number",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
// Define the parameters of the divide function as a JSON schema
|
||||
const divideJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The argument a to divide",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The argument b to divide",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
async function main() {
|
||||
// Create a function tool from the sum function
|
||||
const sumFunctionTool = new FunctionTool(sumNumbers, {
|
||||
name: "sumNumbers",
|
||||
description: "Use this function to sum two numbers",
|
||||
parameters: sumJSON,
|
||||
});
|
||||
|
||||
// Create a function tool from the divide function
|
||||
const divideFunctionTool = new FunctionTool(divideNumbers, {
|
||||
name: "divideNumbers",
|
||||
description: "Use this function to divide two numbers",
|
||||
parameters: divideJSON,
|
||||
});
|
||||
|
||||
// Create an OpenAIAgent with the function tools
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [sumFunctionTool, divideFunctionTool],
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
// Chat with the agent
|
||||
const response = await agent.chat({
|
||||
message: "I want to sum 5 and 5 and then divide by 2",
|
||||
});
|
||||
|
||||
// Print the response
|
||||
console.log(String(response));
|
||||
}
|
||||
|
||||
main().then(() => {
|
||||
console.log("Done");
|
||||
});
|
||||
```
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
sidebar_position: 13
|
||||
---
|
||||
|
||||
# ChatEngine
|
||||
@@ -27,3 +27,4 @@ for await (const chunk of stream) {
|
||||
|
||||
- [ContextChatEngine](../api/classes/ContextChatEngine.md)
|
||||
- [CondenseQuestionChatEngine](../api/classes/ContextChatEngine.md)
|
||||
- [SimpleChatEngine](../api/classes/SimpleChatEngine.md)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
sidebar_position: 12
|
||||
---
|
||||
|
||||
# Index
|
||||
@@ -8,6 +8,7 @@ An index is the basic container and organization for your data. LlamaIndex.TS su
|
||||
|
||||
- `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
|
||||
- `KeywordTableIndex` extracts and provides keywords from `Node`s to the LLM
|
||||
|
||||
```typescript
|
||||
import { Document, VectorStoreIndex } from "llamaindex";
|
||||
@@ -21,3 +22,4 @@ const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
- [SummaryIndex](../api/classes/SummaryIndex.md)
|
||||
- [VectorStoreIndex](../api/classes/VectorStoreIndex.md)
|
||||
- [KeywordTableIndex](../api/classes/KeywordTableIndex.md)
|
||||
|
||||
@@ -1,48 +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";
|
||||
|
||||
# Loader
|
||||
|
||||
Before you can start indexing your documents, you need to load them into memory.
|
||||
|
||||
### SimpleDirectoryReader
|
||||
|
||||
[](https://stackblitz.com/github/run-llama/LlamaIndexTS/tree/main/examples/readers?file=src/simple-directory-reader.ts&title=Simple%20Directory%20Reader)
|
||||
|
||||
LlamaIndex.TS supports easy loading of files from folders using the `SimpleDirectoryReader` class.
|
||||
|
||||
It is a simple reader that reads all files from a directory and its subdirectories.
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
|
||||
Currently, it supports reading `.csv`, `.docx`, `.html`, `.md` and `.pdf` files,
|
||||
but support for other file types is planned.
|
||||
|
||||
Also, you can provide a `defaultReader` as a fallback for files with unsupported extensions.
|
||||
Or pass new readers for `fileExtToReader` to support more file types.
|
||||
|
||||
<CodeBlock language="ts" showLineNumbers metastring="{8-12,17-21}">
|
||||
{CodeSource2}
|
||||
</CodeBlock>
|
||||
|
||||
### LlamaParse
|
||||
|
||||
LlamaParse is an API created by LlamaIndex to efficiently parse files, e.g. it's great at converting PDF tables into markdown.
|
||||
|
||||
To use it, first login and get an API key from https://cloud.llamaindex.ai. Make sure to store the key in the environment variable `LLAMA_CLOUD_API_KEY`.
|
||||
|
||||
Then, you can use the `LlamaParseReader` class to read a local PDF file and convert it into a markdown document that can be used by LlamaIndex:
|
||||
|
||||
<CodeBlock language="ts">{CodeSource3}</CodeBlock>
|
||||
|
||||
Alternatively, you can set the [`resultType`](../api/classes/LlamaParseReader.md#resulttype) option to `text` to get the parsed document as a text string.
|
||||
|
||||
## API Reference
|
||||
|
||||
- [SimpleDirectoryReader](../api/classes/SimpleDirectoryReader.md)
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "Loaders"
|
||||
position: 1
|
||||
@@ -0,0 +1,34 @@
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../../examples/readers/src/discord";
|
||||
|
||||
# DiscordReader
|
||||
|
||||
DiscordReader is a simple data loader that reads all messages in a given Discord channel and returns them as Document objects.
|
||||
It uses the [@discordjs/rest](https://github.com/discordjs/discord.js/tree/main/packages/rest) library to fetch the messages.
|
||||
|
||||
## Usage
|
||||
|
||||
First step is to create a Discord Application and generating a bot token [here](https://discord.com/developers/applications).
|
||||
In your Discord Application, go to the `OAuth2` tab and generate an invite URL by selecting `bot` and click `Read Messages/View Channels` as wells as `Read Message History`.
|
||||
This will invite the bot with the necessary permissions to read messages.
|
||||
Copy the URL in your browser and select the server you want your bot to join.
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
|
||||
### Params
|
||||
|
||||
#### DiscordReader()
|
||||
|
||||
- `discordToken?`: The Discord bot token.
|
||||
- `requestHandler?`: Optionally provide a custom request function for edge environments, e.g. `fetch`. See discord.js for more info.
|
||||
|
||||
#### DiscordReader.loadData
|
||||
|
||||
- `channelIDs`: The ID(s) of discord channels as an array of strings.
|
||||
- `limit?`: Optionally limit the number of messages to read
|
||||
- `additionalInfo?`: An optional flag to include embedded messages and attachment urls in the document.
|
||||
- `oldestFirst?`: An optional flag to return the oldest messages first.
|
||||
|
||||
## API Reference
|
||||
|
||||
- [DiscordReader](../../api/classes/DiscordReader.md)
|
||||
@@ -0,0 +1,58 @@
|
||||
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";
|
||||
|
||||
# Loader
|
||||
|
||||
Before you can start indexing your documents, you need to load them into memory.
|
||||
|
||||
All "basic" data loaders can be seen below, mapped to their respective filetypes in `SimpleDirectoryReader`. More loaders are shown in the sidebar on the left.
|
||||
Additionally the following loaders exist without separate documentation:
|
||||
|
||||
- `AssemblyAIReader` transcribes audio using [AssemblyAI](https://www.assemblyai.com/).
|
||||
- [AudioTranscriptReader](../../api/classes/AudioTranscriptReader.md): loads entire transcript as a single document.
|
||||
- [AudioTranscriptParagraphsReader](../../api/classes/AudioTranscriptParagraphsReader.md): creates a document per paragraph.
|
||||
- [AudioTranscriptSentencesReader](../../api/classes/AudioTranscriptSentencesReader.md): creates a document per sentence.
|
||||
- [AudioSubtitlesReader](../../api/classes/AudioTranscriptParagraphsReader.md): creates a document containing the subtitles of a transcript.
|
||||
- [NotionReader](../../api/classes/NotionReader.md) loads [Notion](https://www.notion.so/) pages.
|
||||
- [SimpleMongoReader](../../api/classes/SimpleMongoReader) loads data from a [MongoDB](https://www.mongodb.com/).
|
||||
|
||||
Check the [LlamaIndexTS Github](https://github.com/run-llama/LlamaIndexTS) for the most up to date overview of integrations.
|
||||
|
||||
## 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, the following readers are mapped to specific file types:
|
||||
|
||||
- [TextFileReader](../../api/classes/TextFileReader.md): `.txt`
|
||||
- [PDFReader](../../api/classes/PDFReader.md): `.pdf`
|
||||
- [PapaCSVReader](../../api/classes/PapaCSVReader.md): `.csv`
|
||||
- [MarkdownReader](../../api/classes/MarkdownReader.md): `.md`
|
||||
- [DocxReader](../../api/classes/DocxReader.md): `.docx`
|
||||
- [HTMLReader](../../api/classes/HTMLReader.md): `.htm`, `.html`
|
||||
- [ImageReader](../../api/classes/ImageReader.md): `.jpg`, `.jpeg`, `.png`, `.gif`
|
||||
|
||||
You can modify the reader three different ways:
|
||||
|
||||
- `overrideReader` overrides the reader for all file types, including unsupported ones.
|
||||
- `fileExtToReader` maps a reader to a specific file type. Can override reader for existing file types or add support for new file types.
|
||||
- `defaultReader` sets a fallback reader 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.
|
||||
|
||||
### Example
|
||||
|
||||
<CodeBlock language="ts" showLineNumbers metastring="{8-12,17-21}">
|
||||
{CodeSource2}
|
||||
</CodeBlock>
|
||||
|
||||
## API Reference
|
||||
|
||||
- [SimpleDirectoryReader](../../api/classes/SimpleDirectoryReader.md)
|
||||
@@ -0,0 +1,149 @@
|
||||
# JSONReader
|
||||
|
||||
A simple JSON data loader with various options.
|
||||
Either parses the entire string, cleaning it and treat each line as an embedding or performs a recursive depth-first traversal yielding JSON paths.
|
||||
Supports streaming of large JSON data using [@discoveryjs/json-ext](https://github.com/discoveryjs/json-ext)
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { JSONReader } from "llamaindex";
|
||||
|
||||
const file = "../../PATH/TO/FILE";
|
||||
const content = new TextEncoder().encode("JSON_CONTENT");
|
||||
|
||||
const reader = new JSONReader({ levelsBack: 0, collapseLength: 100 });
|
||||
const docsFromFile = reader.loadData(file);
|
||||
const docsFromContent = reader.loadDataAsContent(content);
|
||||
```
|
||||
|
||||
### Options
|
||||
|
||||
Basic:
|
||||
|
||||
- `streamingThreshold?`: The threshold for using streaming mode in MB of the JSON Data. CEstimates characters by calculating bytes: `(streamingThreshold * 1024 * 1024) / 2` and comparing against `.length` of the JSON string. Set `undefined` to disable streaming or `0` to always use streaming. Default is `50` MB.
|
||||
|
||||
- `ensureAscii?`: Wether to ensure only ASCII characters be present in the output by converting non-ASCII characters to their unicode escape sequence. Default is `false`.
|
||||
|
||||
- `isJsonLines?`: Wether the JSON is in JSON Lines format. If true, will split into lines, remove empty one and parse each line as JSON. Note: Uses a custom streaming parser, most likely less robust than json-ext. Default is `false`
|
||||
|
||||
- `cleanJson?`: Whether to clean the JSON by filtering out structural characters (`{}, [], and ,`). If set to false, it will just parse the JSON, not removing structural characters. Default is `true`.
|
||||
|
||||
- `logger?`: A placeholder for a custom logger function.
|
||||
|
||||
Depth-First-Traversal:
|
||||
|
||||
- `levelsBack?`: Specifies how many levels up the JSON structure to include in the output. `cleanJson` will be ignored. If set to 0, all levels are included. If undefined, parses the entire JSON, treat each line as an embedding and create a document per top-level array. Default is `undefined`
|
||||
|
||||
- `collapseLength?`: The maximum length of JSON string representation to be collapsed into a single line. Only applicable when `levelsBack` is set. Default is `undefined`
|
||||
|
||||
#### Examples
|
||||
|
||||
<!-- prettier-ignore-start -->
|
||||
Input:
|
||||
|
||||
```json
|
||||
{"a": {"1": {"key1": "value1"}, "2": {"key2": "value2"}}, "b": {"3": {"k3": "v3"}, "4": {"k4": "v4"}}}
|
||||
```
|
||||
|
||||
Default options:
|
||||
|
||||
`LevelsBack` = `undefined` & `cleanJson` = `true`
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
"a": {
|
||||
"1": {
|
||||
"key1": "value1"
|
||||
"2": {
|
||||
"key2": "value2"
|
||||
"b": {
|
||||
"3": {
|
||||
"k3": "v3"
|
||||
"4": {
|
||||
"k4": "v4"
|
||||
```
|
||||
|
||||
Depth-First Traversal all levels:
|
||||
|
||||
`levelsBack` = `0`
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
a 1 key1 value1
|
||||
a 2 key2 value2
|
||||
b 3 k3 v3
|
||||
b 4 k4 v4
|
||||
```
|
||||
|
||||
Depth-First Traversal and Collapse:
|
||||
|
||||
`levelsBack` = `0` & `collapseLength` = `35`
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
a 1 {"key1":"value1"}
|
||||
a 2 {"key2":"value2"}
|
||||
b {"3":{"k3":"v3"},"4":{"k4":"v4"}}
|
||||
```
|
||||
|
||||
Depth-First Traversal limited levels:
|
||||
|
||||
`levelsBack` = `2`
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
1 key1 value1
|
||||
2 key2 value2
|
||||
3 k3 v3
|
||||
4 k4 v4
|
||||
```
|
||||
|
||||
Uncleaned JSON:
|
||||
|
||||
`levelsBack` = `undefined` & `cleanJson` = `false`
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
{"a":{"1":{"key1":"value1"},"2":{"key2":"value2"}},"b":{"3":{"k3":"v3"},"4":{"k4":"v4"}}}
|
||||
```
|
||||
|
||||
ASCII-Conversion:
|
||||
|
||||
Input:
|
||||
|
||||
```json
|
||||
{ "message": "こんにちは世界" }
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
"message": "\u3053\u3093\u306b\u3061\u306f\u4e16\u754c"
|
||||
```
|
||||
|
||||
JSON Lines Format:
|
||||
|
||||
Input:
|
||||
|
||||
```json
|
||||
{"tweet": "Hello world"}\n{"tweet": "こんにちは世界"}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
"tweet": "Hello world"
|
||||
|
||||
"tweet": "こんにちは世界"
|
||||
```
|
||||
<!-- prettier-ignore-end -->
|
||||
|
||||
## API Reference
|
||||
|
||||
- [JSONReader](../../api/classes/JSONReader.md)
|
||||
@@ -0,0 +1 @@
|
||||
label: "LlamaParse"
|
||||
@@ -0,0 +1,117 @@
|
||||
---
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
# Image Retrieval
|
||||
|
||||
LlamaParse `json` mode supports extracting any images found in a page object by using the `getImages` function. They are downloaded to a local folder and can then be sent to a multimodal LLM for further processing.
|
||||
|
||||
## Usage
|
||||
|
||||
We use the `getImages` method to input our array of JSON objects, download the images to a specified folder and get a list of ImageNodes.
|
||||
|
||||
```ts
|
||||
const reader = new LlamaParseReader();
|
||||
const jsonObjs = await reader.loadJson("../data/uber_10q_march_2022.pdf");
|
||||
const imageDicts = await reader.getImages(jsonObjs, "images");
|
||||
```
|
||||
|
||||
### Multimodal Indexing
|
||||
|
||||
You can create an index across both text and image nodes by requesting alternative text for the image from a multimodal LLM.
|
||||
|
||||
```ts
|
||||
import {
|
||||
Document,
|
||||
ImageNode,
|
||||
LlamaParseReader,
|
||||
OpenAI,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
import { createMessageContent } from "llamaindex/synthesizers/utils";
|
||||
|
||||
const reader = new LlamaParseReader();
|
||||
async function main() {
|
||||
// Load PDF using LlamaParse JSON mode and return an array of json objects
|
||||
const jsonObjs = await reader.loadJson("../data/uber_10q_march_2022.pdf");
|
||||
// Access the first "pages" (=a single parsed file) object in the array
|
||||
const jsonList = jsonObjs[0]["pages"];
|
||||
|
||||
const textDocs = getTextDocs(jsonList);
|
||||
const imageTextDocs = await getImageTextDocs(jsonObjs);
|
||||
const documents = [...textDocs, ...imageTextDocs];
|
||||
// Split text, create embeddings and query the index
|
||||
const index = await VectorStoreIndex.fromDocuments(documents);
|
||||
const queryEngine = index.asQueryEngine();
|
||||
const response = await queryEngine.query({
|
||||
query:
|
||||
"What does the bar graph titled 'Monthly Active Platform Consumers' show?",
|
||||
});
|
||||
|
||||
console.log(response.toString());
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
```
|
||||
|
||||
We use two helper functions to create documents from the text and image nodes provided.
|
||||
|
||||
#### Text Documents
|
||||
|
||||
To create documents from the text nodes of the json object, we just map the needed values to a new `Document` object. In this case we assign the text as text and the page number as metadata.
|
||||
|
||||
```ts
|
||||
function getTextDocs(jsonList: { text: string; page: number }[]): Document[] {
|
||||
return jsonList.map(
|
||||
(page) => new Document({ text: page.text, metadata: { page: page.page } }),
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
#### Image Documents
|
||||
|
||||
To create documents from the images, we need to use a multimodal LLM to generate alt text.
|
||||
|
||||
For this we create `ImageNodes` and add them as part of our message.
|
||||
|
||||
We can use the `createMessageContent` function to simplify this.
|
||||
|
||||
```ts
|
||||
async function getImageTextDocs(
|
||||
jsonObjs: Record<string, any>[],
|
||||
): Promise<Document[]> {
|
||||
const llm = new OpenAI({
|
||||
model: "gpt-4o",
|
||||
temperature: 0.2,
|
||||
maxTokens: 1000,
|
||||
});
|
||||
const imageDicts = await reader.getImages(jsonObjs, "images");
|
||||
const imageDocs = [];
|
||||
|
||||
for (const imageDict of imageDicts) {
|
||||
const imageDoc = new ImageNode({ image: imageDict.path });
|
||||
const prompt = () => `Describe the image as alt text`;
|
||||
const message = await createMessageContent(prompt, [imageDoc]);
|
||||
|
||||
const response = await llm.complete({
|
||||
prompt: message,
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
text: response.text,
|
||||
metadata: { path: imageDict.path },
|
||||
});
|
||||
imageDocs.push(doc);
|
||||
}
|
||||
|
||||
return imageDocs;
|
||||
}
|
||||
```
|
||||
|
||||
The returned `imageDocs` have the alt text assigned as text and the image path as metadata.
|
||||
|
||||
You can see the full example file [here](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/readers/src/llamaparse-json.ts).
|
||||
|
||||
## API Reference
|
||||
|
||||
- [LlamaParseReader](../../../api/classes/LlamaParseReader.md)
|
||||
@@ -0,0 +1,66 @@
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../../../examples/readers/src/llamaparse";
|
||||
import CodeSource2 from "!raw-loader!../../../../../../examples/readers/src/simple-directory-reader-with-llamaparse.ts";
|
||||
|
||||
# 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`.
|
||||
|
||||
Official documentation for LlamaParse can be found [here](https://docs.cloud.llamaindex.ai/).
|
||||
|
||||
## Usage
|
||||
|
||||
You can then use the `LlamaParseReader` class to load 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/llamaindex/src/readers/LlamaParseReader.ts) for a list of supported file types:
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
|
||||
### Params
|
||||
|
||||
All options can be set with the `LlamaParseReader` constructor.
|
||||
|
||||
They can be divided into two groups.
|
||||
|
||||
#### General params:
|
||||
|
||||
- `apiKey` is required. Can be set as an environment variable `LLAMA_CLOUD_API_KEY`
|
||||
- `checkInterval` is the interval in seconds to check if the parsing is done. Default is `1`.
|
||||
- `maxTimeout` is the maximum timeout to wait for parsing to finish. Default is `2000`
|
||||
- `verbose` shows progress of the parsing. Default is `true`
|
||||
- `ignoreErrors` set to false to get errors while parsing. Default is `true` and returns an empty array on error.
|
||||
|
||||
#### Advanced params:
|
||||
|
||||
- `resultType` can be set to `markdown`, `text` or `json`. Defaults to `text`. More information about `json` mode on the next pages.
|
||||
- `language` primarily helps with OCR recognition. Defaults to `en`. Click [here](../../../api/type-aliases/Language.md) for a list of supported languages.
|
||||
- `parsingInstructions?` Optional. 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?` Optional. Set to true to ignore diagonal text. (Text that is not rotated 0, 90, 180 or 270 degrees)
|
||||
- `invalidateCache?` Optional. 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`.
|
||||
- `doNotCache?` Optional. Set to true to not cache the document.
|
||||
- `fastMode?` Optional. Set to true to use the fast mode. This mode will skip OCR of images, and table/heading reconstruction. Note: Non-compatible with `gpt4oMode`.
|
||||
- `doNotUnrollColumns?` Optional. Set to true to keep the text according to document layout. Reduce reconstruction accuracy, and LLMs/embeddings performances in most cases.
|
||||
- `pageSeparator?` Optional. A templated page separator to use to split the text. If the results contain `{page_number}` (e.g. JSON mode), it will be replaced by the next page number. If not set the default separator `\\n---\\n` will be used.
|
||||
- `pagePrefix?` Optional. A templated prefix to add to the beginning of each page. If the results contain `{page_number}`, it will be replaced by the page number.
|
||||
- `pageSuffix?` Optional. A templated suffix to add to the end of each page. If the results contain `{page_number}`, it will be replaced by the page number.
|
||||
- `gpt4oMode` Deprecated. Use vendorMultimodal params. Set to true to use GPT-4o to extract content. Default is `false`.
|
||||
- `gpt4oApiKey?` Deprecated. Use vendorMultimodal params. Optional. Set the GPT-4o API key. 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`.
|
||||
- `boundingBox?` Optional. Specify an area of the document to parse. Expects the bounding box margins as a string in clockwise order, e.g. `boundingBox = "0.1,0,0,0"` to not parse the top 10% of the document.
|
||||
- `targetPages?` Optional. Specify which pages to parse by specifying them as a comma-separated list. First page is `0`.
|
||||
- `splitByPage` Wether to split the results, creating one document per page. Uses the set `pageSeparator` or `\n---\n` as fallback. Default is true.
|
||||
- `useVendorMultimodalModel` set to true to use a multimodal model. Default is `false`.
|
||||
- `vendorMultimodalModel?` Optional. Specify which multimodal model to use. Default is GPT4o. See [here](https://docs.cloud.llamaindex.ai/llamaparse/features/multimodal) for a list of available models and cost.
|
||||
- `vendorMultimodalApiKey?` Optional. Set the multimodal model API key. Can also be set in the environment variable `LLAMA_CLOUD_VENDOR_MULTIMODAL_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">{CodeSource2}</CodeBlock>
|
||||
|
||||
## API Reference
|
||||
|
||||
- [SimpleDirectoryReader](../../../api/classes/SimpleDirectoryReader.md)
|
||||
- [LlamaParseReader](../../../api/classes/LlamaParseReader.md)
|
||||
@@ -0,0 +1,95 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# JSON Mode
|
||||
|
||||
In JSON mode, LlamaParse will return a data structure representing the parsed object.
|
||||
|
||||
## Usage
|
||||
|
||||
For Json mode, you need to use `loadJson`. The `resultType` is automatically set with this method.
|
||||
More information about indexing the results on the next page.
|
||||
|
||||
```ts
|
||||
const reader = new LlamaParseReader();
|
||||
async function main() {
|
||||
// Load the file and return an array of json objects
|
||||
const jsonObjs = await reader.loadJson("../data/uber_10q_march_2022.pdf");
|
||||
// Access the first "pages" (=a single parsed file) object in the array
|
||||
const jsonList = jsonObjs[0]["pages"];
|
||||
// Further process the jsonList object as needed.
|
||||
}
|
||||
```
|
||||
|
||||
### Output
|
||||
|
||||
The result format of the response, written to `jsonObjs` in the example, follows this structure:
|
||||
|
||||
```json
|
||||
{
|
||||
"pages": [
|
||||
..page objects..
|
||||
],
|
||||
"job_metadata": {
|
||||
"credits_used": int,
|
||||
"credits_max": int,
|
||||
"job_credits_usage": int,
|
||||
"job_pages": int,
|
||||
"job_is_cache_hit": boolean
|
||||
},
|
||||
"job_id": string ,
|
||||
"file_path": string,
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Page objects
|
||||
|
||||
Within page objects, the following keys may be present depending on your document.
|
||||
|
||||
- `page`: The page number of the document.
|
||||
- `text`: The text extracted from the page.
|
||||
- `md`: The markdown version of the extracted text.
|
||||
- `images`: Any images extracted from the page.
|
||||
- `items`: An array of heading, text and table objects in the order they appear on the page.
|
||||
|
||||
### JSON Mode with SimpleDirectoryReader
|
||||
|
||||
All Readers share a `loadData` method with `SimpleDirectoryReader` that promises to return a uniform Document with Metadata. This makes JSON mode incompatible with SimpleDirectoryReader.
|
||||
|
||||
However, a simple work around is to create a new reader class that extends `LlamaParseReader` and adds a new method or overrides `loadData`, wrapping around JSON mode, extracting the required values, and returning a Document object.
|
||||
|
||||
```ts
|
||||
import { LlamaParseReader, Document } from "llamaindex";
|
||||
|
||||
class LlamaParseReaderWithJson extends LlamaParseReader {
|
||||
// Override the loadData method
|
||||
override async loadData(filePath: string): Promise<Document[]> {
|
||||
// Call loadJson method that was inherited by LlamaParseReader
|
||||
const jsonObjs = await super.loadJson(filePath);
|
||||
let documents: Document[] = [];
|
||||
|
||||
jsonObjs.forEach((jsonObj) => {
|
||||
// Making sure it's an array before iterating over it
|
||||
if (Array.isArray(jsonObj.pages)) {
|
||||
}
|
||||
const docs = jsonObj.pages.map(
|
||||
(page: { text: string; page: number }) =>
|
||||
new Document({ text: page.text, metadata: { page: page.page } }),
|
||||
);
|
||||
documents = documents.concat(docs);
|
||||
});
|
||||
return documents;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Now we have documents with page number as metadata. This new reader can be used like any other and be integrated with SimpleDirectoryReader. Since it extends `LlamaParseReader`, you can use the same params.
|
||||
|
||||
You can assign any other values of the JSON response to the Document as needed.
|
||||
|
||||
## API Reference
|
||||
|
||||
- [LlamaParseReader](../../../api/classes/LlamaParseReader.md)
|
||||
- [SimpleDirectoryReader](../../../api/classes/SimpleDirectoryReader.md)
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "Data Stores"
|
||||
position: 2
|
||||
@@ -0,0 +1 @@
|
||||
label: "Chat Stores"
|
||||
@@ -0,0 +1,13 @@
|
||||
# Chat Stores
|
||||
|
||||
Chat stores manage chat history by storing sequences of messages in a structured way, ensuring the order of messages is maintained for accurate conversation flow.
|
||||
|
||||
## Available Chat Stores
|
||||
|
||||
- [SimpleChatStore](../../../api/classes/SimpleChatStore.md): A simple in-memory chat store with support for [persisting](../index.md#local-storage) data to disk.
|
||||
|
||||
Check the [LlamaIndexTS Github](https://github.com/run-llama/LlamaIndexTS) for the most up to date overview of integrations.
|
||||
|
||||
## API Reference
|
||||
|
||||
- [BaseChatStore](../../../api/interfaces/BaseChatStore.md)
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "Document Stores"
|
||||
position: 2
|
||||
@@ -0,0 +1,14 @@
|
||||
# Document Stores
|
||||
|
||||
Document stores contain ingested document chunks, i.e. [Node](../../documents_and_nodes/index.md)s.
|
||||
|
||||
## Available Document Stores
|
||||
|
||||
- [SimpleDocumentStore](../../../api/classes/SimpleDocumentStore.md): A simple in-memory document store with support for [persisting](../index.md#local-storage) data to disk.
|
||||
- [PostgresDocumentStore](../../../api/classes/PostgresDocumentStore.md): A PostgreSQL document store, see [PostgreSQL Storage](../index.md#postgresql-storage).
|
||||
|
||||
Check the [LlamaIndexTS Github](https://github.com/run-llama/LlamaIndexTS) for the most up to date overview of integrations.
|
||||
|
||||
## API Reference
|
||||
|
||||
- [BaseDocumentStore](../../../api/classes/BaseDocumentStore.md)
|
||||
@@ -0,0 +1,56 @@
|
||||
# Storage
|
||||
|
||||
Storage in LlamaIndex.TS works automatically once you've configured a
|
||||
`StorageContext` object.
|
||||
|
||||
## Local Storage
|
||||
|
||||
You can configure the `persistDir` and attach it to an index.
|
||||
|
||||
```typescript
|
||||
import {
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
storageContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
const storageContext = await storageContextFromDefaults({
|
||||
persistDir: "./storage",
|
||||
});
|
||||
|
||||
const document = new Document({ text: "Test Text" });
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
storageContext,
|
||||
});
|
||||
```
|
||||
|
||||
## PostgreSQL Storage
|
||||
|
||||
You can configure the `schemaName`, `tableName`, `namespace`, and
|
||||
`connectionString`. If a `connectionString` is not
|
||||
provided, it will use the environment variables `PGHOST`, `PGUSER`,
|
||||
`PGPASSWORD`, `PGDATABASE` and `PGPORT`.
|
||||
|
||||
```typescript
|
||||
import {
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
PostgresDocumentStore,
|
||||
PostgresIndexStore,
|
||||
storageContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
const storageContext = await storageContextFromDefaults({
|
||||
docStore: new PostgresDocumentStore(),
|
||||
indexStore: new PostgresIndexStore(),
|
||||
});
|
||||
|
||||
const document = new Document({ text: "Test Text" });
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
storageContext,
|
||||
});
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [StorageContext](../../api/interfaces/StorageContext.md)
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "Index Stores"
|
||||
position: 3
|
||||
@@ -0,0 +1,14 @@
|
||||
# Index Stores
|
||||
|
||||
Index stores are underlying storage components that contain metadata(i.e. information created when indexing) about the [index](../../data_index.md) itself.
|
||||
|
||||
## Available Index Stores
|
||||
|
||||
- [SimpleIndexStore](../../../api/classes/SimpleIndexStore.md): A simple in-memory index store with support for [persisting](../index.md#local-storage) data to disk.
|
||||
- [PostgresIndexStore](../../../api/classes/PostgresIndexStore.md): A PostgreSQL index store, , see [PostgreSQL Storage](../index.md#postgresql-storage).
|
||||
|
||||
Check the [LlamaIndexTS Github](https://github.com/run-llama/LlamaIndexTS) for the most up to date overview of integrations.
|
||||
|
||||
## API Reference
|
||||
|
||||
- [BaseIndexStore](../../../api/classes/BaseIndexStore.md)
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "Key-Value Stores"
|
||||
position: 4
|
||||
@@ -0,0 +1,14 @@
|
||||
# Key-Value Stores
|
||||
|
||||
Key-Value Stores represent underlying storage components used in [Document Stores](../doc_stores/index.md) and [Index Stores](../index_stores/index.md)
|
||||
|
||||
## Available Key-Value Stores
|
||||
|
||||
- [SimpleKVStore](../../../api/classes/SimpleKVStore.md): A simple Key-Value store with support of [persisting](../index.md#local-storage) data to disk.
|
||||
- [PostgresKVStore](../../../api/classes/PostgresKVStore.md): A PostgreSQL Key-Value store, see [PostgreSQL Storage](../index.md#postgresql-storage).
|
||||
|
||||
Check the [LlamaIndexTS Github](https://github.com/run-llama/LlamaIndexTS) for the most up to date overview of integrations.
|
||||
|
||||
## API Reference
|
||||
|
||||
- [BaseKVStore](../../../api/classes/BaseKVStore.md)
|
||||
@@ -0,0 +1,22 @@
|
||||
# Vector Stores
|
||||
|
||||
Vector stores save embedding vectors of your ingested document chunks.
|
||||
|
||||
## Available Vector Stores
|
||||
|
||||
Available Vector Stores are shown on the sidebar to the left. Additionally the following integrations exist without separate documentation:
|
||||
|
||||
- [SimpleVectorStore](../../../api/classes/SimpleVectorStore.md): A simple in-memory vector store with optional [persistance](../index.md#local-storage) to disk.
|
||||
- [AstraDBVectorStore](../../../api/classes/AstraDBVectorStore.md): A cloud-native, scalable Database-as-a-Service built on Apache Cassandra, see [datastax.com](https://www.datastax.com/products/datastax-astra)
|
||||
- [ChromaVectorStore](../../../api/classes/ChromaVectorStore.md): An open-source vector database, focused on ease of use and performance, see [trychroma.com](https://www.trychroma.com/)
|
||||
- [MilvusVectorStore](../../../api/classes/MilvusVectorStore.md): An open-source, high-performance, highly scalable vector database, see [milvus.io](https://milvus.io/)
|
||||
- [MongoDBAtlasVectorSearch](../../../api/classes/MongoDBAtlasVectorSearch.md): A cloud-based vector search solution for MongoDB, see [mongodb.com](https://www.mongodb.com/products/platform/atlas-vector-search)
|
||||
- [PGVectorStore](../../../api/classes/PGVectorStore.md): An open-source vector store built on PostgreSQL, see [pgvector Github](https://github.com/pgvector/pgvector)
|
||||
- [PineconeVectorStore](../../../api/classes/PineconeVectorStore.md): A managed, cloud-native vector database, see [pinecone.io](https://www.pinecone.io/)
|
||||
- [WeaviateVectorStore](../../../api/classes/WeaviateVectorStore.md): An open-source, ai-native vector database, see [weaviate.io](https://weaviate.io/)
|
||||
|
||||
Check the [LlamaIndexTS Github](https://github.com/run-llama/LlamaIndexTS) for the most up to date overview of integrations.
|
||||
|
||||
## API Reference
|
||||
|
||||
- [VectorStoreBase](../../../api/classes/VectorStoreBase.md)
|
||||
+6
@@ -1,5 +1,7 @@
|
||||
# Qdrant Vector Store
|
||||
|
||||
[qdrant.tech](https://qdrant.tech/)
|
||||
|
||||
To run this example, you need to have a Qdrant instance running. You can run it with Docker:
|
||||
|
||||
```bash
|
||||
@@ -84,3 +86,7 @@ async function main() {
|
||||
|
||||
main().catch(console.error);
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [QdrantVectorStore](../../../api/classes/QdrantVectorStore.md)
|
||||
@@ -1,7 +1,3 @@
|
||||
---
|
||||
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.
|
||||
@@ -14,5 +10,5 @@ document = new Document({ text: "text", metadata: { key: "val" } });
|
||||
|
||||
## API Reference
|
||||
|
||||
- [Document](../api/classes/Document.md)
|
||||
- [TextNode](../api/classes/TextNode.md)
|
||||
- [Document](../../api/classes/Document.md)
|
||||
- [TextNode](../../api/classes/TextNode.md)
|
||||
|
||||
@@ -43,3 +43,10 @@ async function main() {
|
||||
|
||||
main().then(() => console.log("done"));
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [SummaryExtractor](../../api/classes/SummaryExtractor.md)
|
||||
- [QuestionsAnsweredExtractor](../../api/classes/QuestionsAnsweredExtractor.md)
|
||||
- [TitleExtractor](../../api/classes/TitleExtractor.md)
|
||||
- [KeywordExtractor](../../api/classes/KeywordExtractor.md)
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
label: "Embeddings"
|
||||
position: 3
|
||||
position: 6
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
# 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)
|
||||
|
||||
## API Reference
|
||||
|
||||
- [DeepInfraEmbedding](../../../api/classes/DeepInfraEmbedding.md)
|
||||
@@ -0,0 +1,37 @@
|
||||
# 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,
|
||||
});
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [GeminiEmbedding](../../../api/classes/GeminiEmbedding.md)
|
||||
@@ -3,17 +3,14 @@
|
||||
To use HuggingFace embeddings, you need to import `HuggingFaceEmbedding` from `llamaindex`.
|
||||
|
||||
```ts
|
||||
import { HuggingFaceEmbedding, serviceContextFromDefaults } from "llamaindex";
|
||||
import { HuggingFaceEmbedding, Settings } from "llamaindex";
|
||||
|
||||
const huggingFaceEmbeds = new HuggingFaceEmbedding();
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ embedModel: openaiEmbeds });
|
||||
// Update Embed Model
|
||||
Settings.embedModel = new HuggingFaceEmbedding();
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
@@ -23,3 +20,19 @@ 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,
|
||||
});
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [HuggingFaceEmbedding](../../../api/classes/HuggingFaceEmbedding.md)
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
# 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,
|
||||
});
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [JinaAIEmbedding](../../../api/classes/JinaAIEmbedding.md)
|
||||
@@ -3,21 +3,16 @@
|
||||
To use MistralAI embeddings, you need to import `MistralAIEmbedding` from `llamaindex`.
|
||||
|
||||
```ts
|
||||
import { MistralAIEmbedding, serviceContextFromDefaults } from "llamaindex";
|
||||
import { MistralAIEmbedding, Settings } from "llamaindex";
|
||||
|
||||
const mistralEmbedModel = new MistralAIEmbedding({
|
||||
// Update Embed Model
|
||||
Settings.embedModel = new MistralAIEmbedding({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
embedModel: mistralEmbedModel,
|
||||
});
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
@@ -27,3 +22,7 @@ const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [MistralAIEmbedding](../../../api/classes/MistralAIEmbedding.md)
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
# MixedbreadAI
|
||||
|
||||
Welcome to the mixedbread embeddings guide! This guide will help you use the mixedbread ai's API to generate embeddings for your text documents, ensuring you get the most relevant information, just like picking the freshest bread from the bakery.
|
||||
|
||||
To find out more about the latest features, updates, and available models, visit [mixedbread.ai](https://mixedbread-ai.com/).
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. [Setup](#setup)
|
||||
2. [Usage with LlamaIndex](#usage-with-llamaindex)
|
||||
3. [Embeddings with Custom Parameters](#embeddings-with-custom-parameters)
|
||||
|
||||
## Setup
|
||||
|
||||
First, you will need to install the `llamaindex` package.
|
||||
|
||||
```bash
|
||||
pnpm install llamaindex
|
||||
```
|
||||
|
||||
Next, sign up for an API key at [mixedbread.ai](https://mixedbread.ai/). Once you have your API key, you can import the necessary modules and create a new instance of the `MixedbreadAIEmbeddings` class.
|
||||
|
||||
```ts
|
||||
import { MixedbreadAIEmbeddings, Document, Settings } from "llamaindex";
|
||||
```
|
||||
|
||||
## Usage with LlamaIndex
|
||||
|
||||
This section will guide you through integrating mixedbread embeddings with LlamaIndex for more advanced usage.
|
||||
|
||||
### Step 1: 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, like a variety of breads in a bakery.
|
||||
|
||||
```ts
|
||||
Settings.embedModel = new MixedbreadAIEmbeddings({
|
||||
apiKey: "<MIXEDBREAD_API_KEY>",
|
||||
model: "mixedbread-ai/mxbai-embed-large-v1",
|
||||
});
|
||||
|
||||
const document = new Document({
|
||||
text: "The true source of happiness.",
|
||||
id_: "bread",
|
||||
});
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
```
|
||||
|
||||
### Step 2: Create a Query Engine
|
||||
|
||||
Combine the retriever and the embed model to create a query engine. This setup ensures that your queries are processed to provide the best results, like arranging the bread in the order of freshness and quality.
|
||||
|
||||
Models can require prompts to generate embeddings for queries, in the 'mixedbread-ai/mxbai-embed-large-v1' model's case, the prompt is `Represent this sentence for searching relevant passages:`.
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query =
|
||||
"Represent this sentence for searching relevant passages: What is bread?";
|
||||
|
||||
// Log the response
|
||||
const results = await queryEngine.query(query);
|
||||
console.log(results); // Serving up the freshest, most relevant results.
|
||||
```
|
||||
|
||||
## Embeddings with Custom Parameters
|
||||
|
||||
This section will guide you through generating embeddings with custom parameters and usage with f.e. matryoshka and binary embeddings.
|
||||
|
||||
### Step 1: Create an Instance of MixedbreadAIEmbeddings
|
||||
|
||||
Create a new instance of the `MixedbreadAIEmbeddings` class with custom parameters. For example, to use the `mixedbread-ai/mxbai-embed-large-v1` model with a batch size of 64, normalized embeddings, and binary encoding format:
|
||||
|
||||
```ts
|
||||
const embeddings = new MixedbreadAIEmbeddings({
|
||||
apiKey: "<MIXEDBREAD_API_KEY>",
|
||||
model: "mixedbread-ai/mxbai-embed-large-v1",
|
||||
batchSize: 64,
|
||||
normalized: true,
|
||||
dimensions: 512,
|
||||
encodingFormat: MixedbreadAI.EncodingFormat.Binary,
|
||||
});
|
||||
```
|
||||
|
||||
### Step 2: Define Texts
|
||||
|
||||
Define the texts you want to generate embeddings for.
|
||||
|
||||
```ts
|
||||
const texts = ["Bread is life", "Bread is love"];
|
||||
```
|
||||
|
||||
### Step 3: Generate Embeddings
|
||||
|
||||
Use the `embedDocuments` method to generate embeddings for the texts.
|
||||
|
||||
```ts
|
||||
const result = await embeddings.embedDocuments(texts);
|
||||
console.log(result); // Perfectly customized embeddings, ready to serve.
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [MixedbreadAIEmbeddings](../../../api/classes/MixedbreadAIEmbeddings.md)
|
||||
@@ -1,21 +1,23 @@
|
||||
# Ollama
|
||||
|
||||
To use Ollama embeddings, you need to import `Ollama` from `llamaindex`.
|
||||
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 { Ollama, serviceContextFromDefaults } from "llamaindex";
|
||||
import { OllamaEmbedding, Settings } from "llamaindex";
|
||||
|
||||
const ollamaEmbedModel = new Ollama();
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
embedModel: ollamaEmbedModel,
|
||||
});
|
||||
Settings.embedModel = new OllamaEmbedding({ model: "nomic-embed-text" });
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
@@ -25,3 +27,7 @@ const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [OllamaEmbedding](../../../api/classes/OllamaEmbedding.md)
|
||||
|
||||
@@ -3,19 +3,13 @@
|
||||
To use OpenAI embeddings, you need to import `OpenAIEmbedding` from `llamaindex`.
|
||||
|
||||
```ts
|
||||
import { OpenAIEmbedding, serviceContextFromDefaults } from "llamaindex";
|
||||
import { OpenAIEmbedding, Settings } from "llamaindex";
|
||||
|
||||
const openaiEmbedModel = new OpenAIEmbedding();
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
embedModel: openaiEmbedModel,
|
||||
});
|
||||
Settings.embedModel = new OpenAIEmbedding();
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
@@ -25,3 +19,7 @@ const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [OpenAIEmbedding](../../../api/classes/OpenAIEmbedding.md)
|
||||
|
||||
@@ -3,21 +3,15 @@
|
||||
To use together embeddings, you need to import `TogetherEmbedding` from `llamaindex`.
|
||||
|
||||
```ts
|
||||
import { TogetherEmbedding, serviceContextFromDefaults } from "llamaindex";
|
||||
import { TogetherEmbedding, Settings } from "llamaindex";
|
||||
|
||||
const togetherEmbedModel = new TogetherEmbedding({
|
||||
Settings.embedModel = new TogetherEmbedding({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
embedModel: togetherEmbedModel,
|
||||
});
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
@@ -27,3 +21,7 @@ const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [TogetherEmbedding](../../../api/classes/TogetherEmbedding.md)
|
||||
|
||||
@@ -2,21 +2,30 @@
|
||||
|
||||
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 set in the `ServiceContext` object.
|
||||
This can be explicitly updated through `Settings`
|
||||
|
||||
```typescript
|
||||
import { OpenAIEmbedding, serviceContextFromDefaults } from "llamaindex";
|
||||
import { OpenAIEmbedding, Settings } from "llamaindex";
|
||||
|
||||
const openaiEmbeds = new OpenAIEmbedding();
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ embedModel: openaiEmbeds });
|
||||
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.
|
||||
|
||||
## Available Embeddings
|
||||
|
||||
Most available embeddings are listed in the sidebar on the left.
|
||||
Additionally the following integrations exist without separate documentation:
|
||||
|
||||
- [ClipEmbedding](../../api/classes/ClipEmbedding.md) using `@xenova/transformers`
|
||||
- [FireworksEmbedding](../../api/classes/FireworksEmbedding.md) see [fireworks.ai](https://fireworks.ai/)
|
||||
|
||||
Check the [LlamaIndexTS Github](https://github.com/run-llama/LlamaIndexTS) for the most up to date overview of integrations.
|
||||
|
||||
## API Reference
|
||||
|
||||
- [OpenAIEmbedding](../../api/classes/OpenAIEmbedding.md)
|
||||
- [ServiceContext](../../api/interfaces//ServiceContext.md)
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "Evaluating"
|
||||
position: 9
|
||||
@@ -0,0 +1,32 @@
|
||||
# Evaluating
|
||||
|
||||
## Concept
|
||||
|
||||
Evaluation and benchmarking are crucial concepts in LLM development. To improve the performance of an LLM app (RAG, agents) you must have a way to measure it.
|
||||
|
||||
LlamaIndex offers key modules to measure the quality of generated results. We also offer key modules to measure retrieval quality.
|
||||
|
||||
- **Response Evaluation**: Does the response match the retrieved context? Does it also match the query? Does it match the reference answer or guidelines?
|
||||
- **Retrieval Evaluation**: Are the retrieved sources relevant to the query?
|
||||
|
||||
## Response Evaluation
|
||||
|
||||
Evaluation of generated results can be difficult, since unlike traditional machine learning the predicted result is not a single number, and it can be hard to define quantitative metrics for this problem.
|
||||
|
||||
LlamaIndex offers LLM-based evaluation modules to measure the quality of results. This uses a “gold” LLM (e.g. GPT-4) to decide whether the predicted answer is correct in a variety of ways.
|
||||
|
||||
Note that many of these current evaluation modules do not require ground-truth labels. Evaluation can be done with some combination of the query, context, response, and combine these with LLM calls.
|
||||
|
||||
These evaluation modules are in the following forms:
|
||||
|
||||
- **Correctness**: Whether the generated answer matches that of the reference answer given the query (requires labels).
|
||||
|
||||
- **Faithfulness**: Evaluates if the answer is faithful to the retrieved contexts (in other words, whether if there’s hallucination).
|
||||
|
||||
- **Relevancy**: Evaluates if the response from a query engine matches any source nodes.
|
||||
|
||||
## Usage
|
||||
|
||||
- [Correctness Evaluator](./modules/correctness.md)
|
||||
- [Faithfulness Evaluator](./modules/faithfulness.md)
|
||||
- [Relevancy Evaluator](./modules/relevancy.md)
|
||||
@@ -0,0 +1 @@
|
||||
label: "Modules"
|
||||
@@ -0,0 +1,62 @@
|
||||
# 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
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [CorrectnessEvaluator](../../../api/classes/CorrectnessEvaluator.md)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user