mirror of
https://github.com/run-llama/LlamaIndexTS.git
synced 2026-07-01 22:14:03 -04:00
Compare commits
292 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b6fb10eba8 | |||
| df441e28f4 | |||
| a4e05ec7ab | |||
| 96f72ad86e | |||
| f3556c011c | |||
| ebc510582b | |||
| f3bfdc29e3 | |||
| 6cce3b12ea | |||
| 0273e9739a | |||
| 7c8b883448 | |||
| c2bb418542 | |||
| ed6acbead0 | |||
| 976cce40d7 | |||
| e4fd4158bb | |||
| 31d5dffcef | |||
| d12edee802 | |||
| ac41ed3aae | |||
| d8c1159032 | |||
| c856c5becb | |||
| 50e6b57be0 | |||
| 8b7fdba544 | |||
| 22ae8d0166 | |||
| 23bcc379a8 | |||
| bdc4bfe7b0 | |||
| 025ffe6b50 | |||
| a6595747fa | |||
| d902cc3e7e | |||
| 726eb41359 | |||
| e9714dbfcd | |||
| a3618e761e | |||
| 24eabe7f35 | |||
| ecfa939ea6 | |||
| b48bcc3add | |||
| fa01fa2051 | |||
| fb36eff5e1 | |||
| d24d3d1e8c | |||
| 5c4badbcca | |||
| 2cd1383dc8 | |||
| 72440c101f | |||
| 423d66b07a | |||
| b42adebd51 | |||
| 749b43a3b1 | |||
| 8daaef44ee | |||
| ac07e3cbe6 | |||
| 1a6137b323 | |||
| 85c2e198a4 | |||
| 01263c4cfd | |||
| fbd5e0174d | |||
| 70ccb4ae65 | |||
| 7eb331774d | |||
| 24a3f058a3 | |||
| 84c28f95f9 | |||
| 7af57982fe | |||
| 6b70c5408f | |||
| 74fc725f37 | |||
| a0a74aed60 | |||
| 11feef8c82 | |||
| 9c5ff164ac | |||
| 7edeb1c2d7 | |||
| 8b95abdc85 | |||
| ffe0cd1ef1 | |||
| 5d2111a19f | |||
| 68ac7fd57f | |||
| 7320d96a36 | |||
| ee17fb475b | |||
| 28b877e31f | |||
| 4389b80a52 | |||
| d3bc663951 | |||
| 4810364788 | |||
| 2dcad52dd9 | |||
| 0bf8d80b12 | |||
| e4bba02aec | |||
| 1caa0da657 | |||
| 711c814bb2 | |||
| 5b832eb927 | |||
| 49988431f6 | |||
| 72d65dd51a | |||
| 553bc55b19 | |||
| fc6f69833c | |||
| c7fd06841f | |||
| 4648da6849 | |||
| 0188cf3bb6 | |||
| e0b4f9c047 | |||
| 4895bba96e | |||
| 76d1df817b | |||
| 83d7f415e2 | |||
| ae1149ffaf | |||
| 0148354dbe | |||
| 11b3856334 | |||
| e8f229cd01 | |||
| 75b70e5824 | |||
| 1711f6d8fc | |||
| 20d16abdf4 | |||
| 2411c9fbd0 | |||
| be3e280f2a | |||
| 2afcbe6587 | |||
| 22ff486fbe | |||
| eed0b0415d | |||
| d9d6c56ed5 | |||
| f99a237093 | |||
| fcbf18344c | |||
| bf8cbeb6c5 | |||
| e27e7dd054 | |||
| 8b66cf4341 | |||
| 6f4549bdea | |||
| c654398f75 | |||
| 0664a99945 | |||
| 58abc5731b | |||
| 7498b1e0f1 | |||
| 07a275fea5 | |||
| 1b6263e08d | |||
| 089f1d49c0 | |||
| 01c184c608 | |||
| 1752463ee6 | |||
| c825a2f743 | |||
| ba058dc8d4 | |||
| 04b2f8e062 | |||
| 62b874e14f | |||
| 9c9e9b4e03 | |||
| e3c307ab55 | |||
| b1b2baa969 | |||
| 0452af91cc | |||
| da5cfc42e5 | |||
| eb89223386 | |||
| 93dc3a31b3 | |||
| 345300f110 | |||
| f322c5d202 | |||
| 376d29a78f | |||
| 224d507ab5 | |||
| 1f680d731d | |||
| f0a1cc51b4 | |||
| fee3280799 | |||
| 54925bf1ae | |||
| 91d02a4fc0 | |||
| 086b94038e | |||
| 5d5716b339 | |||
| fb6db454d4 | |||
| e4d4e0d024 | |||
| 17724d961e | |||
| 6776910c93 | |||
| 15962b36f0 | |||
| 3d9a802734 | |||
| 9cd8f8b0cf | |||
| b44330cbc6 | |||
| 3d5ba0873c | |||
| d917cdc3fa | |||
| b370edf329 | |||
| ec59acd329 | |||
| c69e740c56 | |||
| 6cf6ae631c | |||
| 2562244fb6 | |||
| a2691ee163 | |||
| ab700ea546 | |||
| e775afc3f2 | |||
| 92f07824a7 | |||
| b7cfe5bce6 | |||
| 3ccfb28352 | |||
| 325aa51e51 | |||
| d1d9bd6e41 | |||
| 9a71382243 | |||
| b974eea341 | |||
| e82632f83d | |||
| 1a65ead849 | |||
| 50b7d1b7bb | |||
| 09beb72f5b | |||
| 9bbbc67c8e | |||
| b3681bf681 | |||
| b548b1443b | |||
| 0e980d962d | |||
| 3ed6acc6a6 | |||
| 56746c240f | |||
| 5c1c2c7f5b | |||
| a699086f46 | |||
| 454c204112 | |||
| 277468160d | |||
| a0f424e592 | |||
| 3ae832ca28 | |||
| 16ef5dd631 | |||
| c4bd0a5215 | |||
| f5c8ca7dfb | |||
| 36ddec44af | |||
| c147d8a271 | |||
| 1c444d58b6 | |||
| 1f910f7566 | |||
| 99826cff43 | |||
| e8f8bea969 | |||
| 304484b77a | |||
| 29fed77d58 | |||
| db070588c8 | |||
| 76deca7fea | |||
| f326ab86d2 | |||
| ca8d9709e0 | |||
| e0af059221 | |||
| 8bf5b4acfd | |||
| 93a003baa0 | |||
| 5d9b0bd3f0 | |||
| 9a5525e1b3 | |||
| 7dce3d28d3 | |||
| d4c1482c1c | |||
| 3a96a483a6 | |||
| 7467fce2d4 | |||
| 06af08cac4 | |||
| 83ebdfb1c5 | |||
| 835b1ac000 | |||
| f10b41dbc1 | |||
| 41fe871e2f | |||
| 321c39ddc7 | |||
| f7f1af0139 | |||
| a8c9c279d6 | |||
| eece129831 | |||
| 80e4f51a83 | |||
| 22ff0837c3 | |||
| 74d7e05bcb | |||
| 1feb23bb83 | |||
| 08c55ec258 | |||
| 394e797567 | |||
| 6c3e5d08b8 | |||
| 6e19482814 | |||
| 42eb73a08f | |||
| 4b59ffee45 | |||
| d4e853c8b5 | |||
| a94b8ec3d2 | |||
| ed57e6b7be | |||
| 05f006e7e1 | |||
| c3aed72c29 | |||
| 7deba94e6b | |||
| d15811f09f | |||
| 2ef62a93bb | |||
| 9015aea527 | |||
| 4bb401e6f9 | |||
| a87a4d1222 | |||
| d27ad16335 | |||
| 20498a2bce | |||
| 0730140e62 | |||
| 810711d355 | |||
| f3b34b457c | |||
| 6f4b9f3372 | |||
| 01658fdb31 | |||
| 66c26d9cce | |||
| a4060a7914 | |||
| 469e438741 | |||
| 56fabbb4f5 | |||
| dfd8cc1ba4 | |||
| cba54061a2 | |||
| ed467a9889 | |||
| 3c4791007f | |||
| 8f16a179c3 | |||
| ce3a4cac6c | |||
| be46044b98 | |||
| 154c7f8e36 | |||
| 8b6c2b45a6 | |||
| b1a4a74270 | |||
| d7fb095fbd | |||
| 58791d4bdd | |||
| d3b635b193 | |||
| 436bc41f82 | |||
| 834f49275a | |||
| a44e54f9ec | |||
| a51ed8dd70 | |||
| c8cfc6c06d | |||
| 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 |
+10
-2
@@ -1,3 +1,5 @@
|
||||
const { join } = require("node:path");
|
||||
|
||||
module.exports = {
|
||||
root: true,
|
||||
extends: [
|
||||
@@ -6,7 +8,7 @@ module.exports = {
|
||||
"plugin:@typescript-eslint/recommended-type-checked-only",
|
||||
],
|
||||
parserOptions: {
|
||||
project: true,
|
||||
project: join(__dirname, "tsconfig.eslint.json"),
|
||||
__tsconfigRootDir: __dirname,
|
||||
},
|
||||
settings: {
|
||||
@@ -23,12 +25,18 @@ module.exports = {
|
||||
ignoreIIFE: true,
|
||||
},
|
||||
],
|
||||
"no-debugger": "error",
|
||||
"@typescript-eslint/await-thenable": "off",
|
||||
"@typescript-eslint/ban-ts-comment": "off",
|
||||
"@typescript-eslint/ban-types": "off",
|
||||
"no-array-constructor": "off",
|
||||
"@typescript-eslint/no-array-constructor": "off",
|
||||
"@typescript-eslint/no-base-to-string": "off",
|
||||
"@typescript-eslint/no-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",
|
||||
|
||||
@@ -13,7 +13,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v3
|
||||
- uses: pnpm/action-setup@v4
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
name: Publish Preview
|
||||
on: [pull_request]
|
||||
|
||||
jobs:
|
||||
pre_release:
|
||||
name: Pre Release
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout Repo
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: "pnpm"
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Build
|
||||
run: pnpm run build
|
||||
|
||||
- name: Pre Release
|
||||
run: pnpx pkg-pr-new publish ./packages/*
|
||||
@@ -1,36 +0,0 @@
|
||||
name: Publish
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v3
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: "pnpm"
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Publish @llamaindex/env
|
||||
run: npx jsr publish
|
||||
working-directory: packages/env
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Publish @llamaindex/core
|
||||
run: npx jsr publish --allow-slow-types
|
||||
working-directory: packages/core
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -12,7 +12,7 @@ jobs:
|
||||
- name: Checkout Repo
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v3
|
||||
- uses: pnpm/action-setup@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
@@ -26,12 +26,12 @@ jobs:
|
||||
- name: Build tarball
|
||||
run: |
|
||||
pnpm pack
|
||||
working-directory: packages/core
|
||||
working-directory: packages/llamaindex
|
||||
|
||||
- name: Create release
|
||||
uses: ncipollo/release-action@v1
|
||||
with:
|
||||
artifacts: "packages/core/llamaindex-*.tgz"
|
||||
artifacts: "packages/llamaindex/llamaindex-*.tgz"
|
||||
name: Release ${{ github.ref }}
|
||||
bodyFile: "packages/core/CHANGELOG.md"
|
||||
bodyFile: "packages/llamaindex/CHANGELOG.md"
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
@@ -15,7 +15,7 @@ jobs:
|
||||
- name: Checkout Repo
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v3
|
||||
- uses: pnpm/action-setup@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
@@ -55,3 +55,16 @@ jobs:
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
|
||||
# Refs: https://github.com/changesets/changesets/issues/421
|
||||
- name: Update lock file
|
||||
continue-on-error: true
|
||||
run: pnpm install --lockfile-only
|
||||
|
||||
- name: Commit lock file
|
||||
continue-on-error: true
|
||||
uses: stefanzweifel/git-auto-commit-action@v5
|
||||
with:
|
||||
commit_message: "chore: update lock file"
|
||||
branch: changeset-release/main
|
||||
file_pattern: "pnpm-lock.yaml"
|
||||
|
||||
+52
-20
@@ -12,6 +12,12 @@ concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
POSTGRES_HOST_AUTH_METHOD: trust
|
||||
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
|
||||
TURBO_TEAM: ${{ vars.TURBO_TEAM }}
|
||||
TURBO_REMOTE_ONLY: true
|
||||
|
||||
jobs:
|
||||
e2e:
|
||||
strategy:
|
||||
@@ -22,9 +28,17 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v3
|
||||
|
||||
- uses: ankane/setup-postgres@v1
|
||||
with:
|
||||
database: llamaindex_node_test
|
||||
dev-files: true
|
||||
- run: |
|
||||
cd /tmp
|
||||
git clone --branch v0.7.0 https://github.com/pgvector/pgvector.git
|
||||
cd pgvector
|
||||
make
|
||||
sudo make install
|
||||
- uses: pnpm/action-setup@v4
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
@@ -42,10 +56,9 @@ jobs:
|
||||
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@v3
|
||||
- uses: pnpm/action-setup@v4
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
@@ -60,7 +73,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v3
|
||||
- uses: pnpm/action-setup@v4
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
@@ -71,31 +84,28 @@ jobs:
|
||||
- name: Build
|
||||
run: pnpm run build
|
||||
- name: Use Build For Examples
|
||||
run: pnpm link ../packages/core/
|
||||
run: pnpm link ../packages/llamaindex/
|
||||
working-directory: ./examples
|
||||
- name: Run Type Check
|
||||
run: pnpm run type-check
|
||||
- name: Run Circular Dependency Check
|
||||
run: pnpm dlx turbo run circular-check
|
||||
- uses: actions/upload-artifact@v3
|
||||
if: failure()
|
||||
with:
|
||||
name: typecheck-build-dist
|
||||
path: ./packages/core/dist
|
||||
if-no-files-found: error
|
||||
e2e-core-examples:
|
||||
run: pnpm run circular-check
|
||||
e2e-llamaindex-examples:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
packages:
|
||||
- cloudflare-worker-agent
|
||||
- nextjs-agent
|
||||
- nextjs-edge-runtime
|
||||
- nextjs-node-runtime
|
||||
- waku-query-engine
|
||||
- llama-parse-browser
|
||||
runs-on: ubuntu-latest
|
||||
name: Build Core Example (${{ matrix.packages }})
|
||||
name: Build LlamaIndex Example (${{ matrix.packages }})
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v3
|
||||
- uses: pnpm/action-setup@v4
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
@@ -107,14 +117,14 @@ jobs:
|
||||
run: pnpm run build
|
||||
- name: Build ${{ matrix.packages }}
|
||||
run: pnpm run build
|
||||
working-directory: packages/core/e2e/examples/${{ matrix.packages }}
|
||||
working-directory: packages/llamaindex/e2e/examples/${{ matrix.packages }}
|
||||
|
||||
typecheck-examples:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v3
|
||||
- uses: pnpm/action-setup@v4
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
@@ -126,15 +136,37 @@ jobs:
|
||||
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/ollama
|
||||
run: pnpm pack --pack-destination ${{ runner.temp }}
|
||||
working-directory: packages/llm/ollama
|
||||
- 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
|
||||
- name: Run Type Check
|
||||
run: npx tsc --project ./tsconfig.json
|
||||
working-directory: ${{ runner.temp }}/examples
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: failure()
|
||||
with:
|
||||
name: build-dist
|
||||
path: |
|
||||
${{ runner.temp }}/*.tgz
|
||||
if-no-files-found: error
|
||||
|
||||
@@ -48,3 +48,6 @@ playwright/.cache/
|
||||
|
||||
# intellij
|
||||
**/.idea
|
||||
|
||||
# generated API
|
||||
packages/cloud/src/client
|
||||
|
||||
+9
-9
@@ -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
|
||||
@@ -81,7 +81,7 @@ Any changes you make should be reflected in the browser. If you need to regenera
|
||||
|
||||
## Changeset
|
||||
|
||||
We use [changesets](https://github.com/changesets/changesets) for managing versions and changelogs. To create a new changeset, run:
|
||||
We use [changesets](https://github.com/changesets/changesets) for managing versions and changelogs. To create a new changeset, run in the root folder:
|
||||
|
||||
```
|
||||
pnpm changeset
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
LlamaIndex is a data framework for your LLM application.
|
||||
|
||||
Use your own data with large language models (LLMs, OpenAI ChatGPT and others) in Typescript and Javascript.
|
||||
Use your own data with large language models (LLMs, OpenAI ChatGPT and others) in JS runtime environments with TypeScript support.
|
||||
|
||||
Documentation: https://ts.llamaindex.ai/
|
||||
|
||||
@@ -19,30 +19,84 @@ Try examples online:
|
||||
|
||||
LlamaIndex.TS aims to be a lightweight, easy to use set of libraries to help you integrate large language models into your applications with your own data.
|
||||
|
||||
## Multiple JS Environment Support
|
||||
## Compatibility
|
||||
|
||||
### Multiple JS Environment Support
|
||||
|
||||
LlamaIndex.TS supports multiple JS environments, including:
|
||||
|
||||
- Node.js (18, 20, 22) ✅
|
||||
- Deno ✅
|
||||
- Bun ✅
|
||||
- React Server Components (Next.js) ✅
|
||||
- Nitro ✅
|
||||
- Vercel Edge Runtime ✅ (with some limitations)
|
||||
- Cloudflare Workers ✅ (with some limitations)
|
||||
|
||||
For now, browser support is limited due to the lack of support for [AsyncLocalStorage-like APIs](https://github.com/tc39/proposal-async-context)
|
||||
|
||||
### Supported LLMs:
|
||||
|
||||
- OpenAI LLms
|
||||
- Anthropic LLms
|
||||
- Groq LLMs
|
||||
- Llama2, Llama3, Llama3.1 LLMs
|
||||
- MistralAI LLMs
|
||||
- Fireworks LLMs
|
||||
- DeepSeek LLMs
|
||||
- ReplicateAI LLMs
|
||||
- TogetherAI LLMs
|
||||
- HuggingFace LLms
|
||||
- DeepInfra LLMs
|
||||
- Gemini LLMs
|
||||
|
||||
## Getting started
|
||||
|
||||
```shell
|
||||
npm install llamaindex
|
||||
pnpm install llamaindex
|
||||
yarn add llamaindex
|
||||
jsr install @llamaindex/core
|
||||
```
|
||||
|
||||
### 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
|
||||
import fs from "fs/promises";
|
||||
import fs from "node:fs/promises";
|
||||
import { Document, VectorStoreIndex } from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
@@ -78,7 +132,7 @@ node --import tsx ./main.ts
|
||||
|
||||
### Next.js
|
||||
|
||||
First, you will need to add a llamaindex plugin to your Next.js project.
|
||||
You will need to add a llamaindex plugin to your Next.js project.
|
||||
|
||||
```js
|
||||
// next.config.js
|
||||
@@ -89,20 +143,18 @@ module.exports = withLlamaIndex({
|
||||
});
|
||||
```
|
||||
|
||||
You can combine `ai` with `llamaindex` in Next.js with RSC (React Server Components).
|
||||
### React Server Actions
|
||||
|
||||
You can combine `ai` with `llamaindex` in Next.js, Waku or Redwood.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";
|
||||
import { useActionState } from "react";
|
||||
|
||||
export default function Home() {
|
||||
const [ui, action] = useFormState<JSX.Element | null>(async () => {
|
||||
const [ui, action] = useActionState<JSX.Element | null>(async () => {
|
||||
return chatWithAgent("hello!", []);
|
||||
}, null);
|
||||
return (
|
||||
@@ -132,11 +184,13 @@ export async function chatWithAgent(
|
||||
// ... adding your tools here
|
||||
],
|
||||
});
|
||||
const responseStream = await agent.chat({
|
||||
stream: true,
|
||||
message: question,
|
||||
chatHistory: prevMessages,
|
||||
});
|
||||
const responseStream = await agent.chat(
|
||||
{
|
||||
message: question,
|
||||
chatHistory: prevMessages,
|
||||
},
|
||||
true,
|
||||
);
|
||||
const uiStream = createStreamableUI(<div>loading...</div>);
|
||||
responseStream
|
||||
.pipeTo(
|
||||
@@ -156,30 +210,38 @@ export async function chatWithAgent(
|
||||
|
||||
### Cloudflare Workers
|
||||
|
||||
> [!TIP]
|
||||
> Some modules are not supported in Cloudflare Workers which require Node.js APIs.
|
||||
|
||||
```ts
|
||||
// src/index.ts
|
||||
// add `OPENAI_API_KEY` to the `.dev.vars` file
|
||||
interface Env {
|
||||
OPENAI_API_KEY: string;
|
||||
}
|
||||
|
||||
export default {
|
||||
async fetch(
|
||||
request: Request,
|
||||
env: Env,
|
||||
ctx: ExecutionContext,
|
||||
): Promise<Response> {
|
||||
const { setEnvs } = await import("@llamaindex/env");
|
||||
// set environment variables so that the OpenAIAgent can use them
|
||||
setEnvs(env);
|
||||
const { OpenAIAgent } = await import("llamaindex");
|
||||
const { OpenAIAgent, OpenAI } = await import("@llamaindex/openai");
|
||||
const text = await request.text();
|
||||
const agent = new OpenAIAgent({
|
||||
llm: new OpenAI({
|
||||
apiKey: env.OPENAI_API_KEY,
|
||||
}),
|
||||
tools: [],
|
||||
});
|
||||
const responseStream = await agent.chat({
|
||||
stream: true,
|
||||
message: "Hello? What is the weather today?",
|
||||
message: text,
|
||||
});
|
||||
const textEncoder = new TextEncoder();
|
||||
const response = responseStream.pipeThrough(
|
||||
const response = responseStream.pipeThrough<Uint8Array>(
|
||||
new TransformStream({
|
||||
transform: (chunk, controller) => {
|
||||
controller.enqueue(textEncoder.encode(chunk.response.delta));
|
||||
controller.enqueue(textEncoder.encode(chunk.delta));
|
||||
},
|
||||
}),
|
||||
);
|
||||
@@ -188,29 +250,24 @@ export default {
|
||||
};
|
||||
```
|
||||
|
||||
## Playground
|
||||
### Vite
|
||||
|
||||
Check out our NextJS playground at https://llama-playground.vercel.app/. The source is available at https://github.com/run-llama/ts-playground
|
||||
We have some wasm dependencies for better performance. You can use `vite-plugin-wasm` to load them.
|
||||
|
||||
## Core concepts for getting started:
|
||||
```ts
|
||||
import wasm from "vite-plugin-wasm";
|
||||
|
||||
- [Document](/packages/core/src/Node.ts): A document represents a text file, PDF file or other contiguous piece of data.
|
||||
export default {
|
||||
plugins: [wasm()],
|
||||
ssr: {
|
||||
external: ["tiktoken"],
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
- [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.
|
||||
### Tips when using in non-Node.js environments
|
||||
|
||||
- [Embedding](/packages/core/src/embeddings/OpenAIEmbedding.ts): Embeddings are sets of floating point numbers which represent the data in a Node. By comparing the similarity of embeddings, we can derive an understanding of the similarity of two pieces of data. One use case is to compare the embedding of a question with the embeddings of our Nodes to see which Nodes may contain the data needed to answer that quesiton. Because the default service context is OpenAI, the default embedding is `OpenAIEmbedding`. If using different models, say through Ollama, use this [Embedding](/packages/core/src/embeddings/OllamaEmbedding.ts) (see all [here](/packages/core/src/embeddings)).
|
||||
|
||||
- [Indices](/packages/core/src/indices/): Indices store the Nodes and the embeddings of those nodes. QueryEngines retrieve Nodes from these Indices using embedding similarity.
|
||||
|
||||
- [QueryEngine](/packages/core/src/engines/query/RetrieverQueryEngine.ts): Query engines are what generate the query you put in and give you back the result. Query engines generally combine a pre-built prompt with selected Nodes from your Index to give the LLM the context it needs to answer your query. To build a query engine from your Index (recommended), use the [`asQueryEngine`](/packages/core/src/indices/BaseIndex.ts) method on your Index. See all query engines [here](/packages/core/src/engines/query).
|
||||
|
||||
- [ChatEngine](/packages/core/src/engines/chat/SimpleChatEngine.ts): A ChatEngine helps you build a chatbot that will interact with your Indices. See all chat engines [here](/packages/core/src/engines/chat).
|
||||
|
||||
- [SimplePrompt](/packages/core/src/Prompt.ts): A simple standardized function call definition that takes in inputs and formats them in a template literal. SimplePrompts can be specialized using currying and combined using other SimplePrompt functions.
|
||||
|
||||
## Tips when using in non-Node.js environments
|
||||
|
||||
When you are importing `llamaindex` in a non-Node.js environment(such as React Server Components, Cloudflare Workers, etc.)
|
||||
When you are importing `llamaindex` in a non-Node.js environment(such as Vercel Edge, Cloudflare Workers, etc.)
|
||||
Some classes are not exported from top-level entry file.
|
||||
|
||||
The reason is that some classes are only compatible with Node.js runtime,(e.g. `PDFReader`) which uses Node.js specific APIs(like `fs`, `child_process`, `crypto`).
|
||||
@@ -246,19 +303,31 @@ export async function getDocuments() {
|
||||
|
||||
You'll find a complete example with LlamaIndexTS here: https://github.com/run-llama/create_llama_projects/tree/main/nextjs-edge-llamaparse
|
||||
|
||||
## Supported LLMs:
|
||||
## Playground
|
||||
|
||||
- OpenAI GPT-3.5-turbo and GPT-4
|
||||
- Anthropic Claude 3 (Opus, Sonnet, and Haiku) and the legacy models (Claude 2 and Instant)
|
||||
- Groq LLMs
|
||||
- Llama2/3 Chat LLMs (70B, 13B, and 7B parameters)
|
||||
- MistralAI Chat LLMs
|
||||
- Fireworks Chat LLMs
|
||||
Check out our NextJS playground at https://llama-playground.vercel.app/. The source is available at https://github.com/run-llama/ts-playground
|
||||
|
||||
## Core concepts for getting started:
|
||||
|
||||
- [Document](/packages/llamaindex/src/Node.ts): A document represents a text file, PDF file or other contiguous piece of data.
|
||||
|
||||
- [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/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/llamaindex/src/indices/): Indices store the Nodes and the embeddings of those nodes. QueryEngines retrieve Nodes from these Indices using embedding similarity.
|
||||
|
||||
- [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/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/llamaindex/src/Prompt.ts): A simple standardized function call definition that takes in inputs and formats them in a template literal. SimplePrompts can be specialized using currying and combined using other SimplePrompt functions.
|
||||
|
||||
## Contributing:
|
||||
|
||||
We are in the very early days of LlamaIndex.TS. If you’re interested in hacking on it with us check out our [contributing guide](/CONTRIBUTING.md)
|
||||
Please see our [contributing guide](CONTRIBUTING.md) for more information.
|
||||
You are highly encouraged to contribute to LlamaIndex.TS!
|
||||
|
||||
## Bugs? Questions?
|
||||
## Community
|
||||
|
||||
Please join our Discord! https://discord.com/invite/eN6D2HQ4aX
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
"llamaindex": minor
|
||||
"docs": minor
|
||||
---
|
||||
|
||||
Add deepseek llm class
|
||||
@@ -1,5 +1,464 @@
|
||||
# docs
|
||||
|
||||
## 0.0.80
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [df441e2]
|
||||
- llamaindex@0.6.11
|
||||
|
||||
## 0.0.79
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [ebc5105]
|
||||
- Updated dependencies [6cce3b1]
|
||||
- llamaindex@0.6.10
|
||||
|
||||
## 0.0.78
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- llamaindex@0.6.9
|
||||
|
||||
## 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
|
||||
|
||||
@@ -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>
|
||||
@@ -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.
|
||||
|
||||
@@ -6,10 +6,17 @@ sidebar_position: 2
|
||||
|
||||
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.
|
||||
|
||||
@@ -21,7 +21,7 @@ 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).
|
||||
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
|
||||
|
||||
|
||||
@@ -7,9 +7,9 @@ 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.
|
||||
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).
|
||||
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
|
||||
|
||||
|
||||
@@ -50,10 +50,10 @@ We want to see what our agent is up to, so we're going to hook into some events
|
||||
|
||||
```javascript
|
||||
Settings.callbackManager.on("llm-tool-call", (event) => {
|
||||
console.log(event.detail.payload);
|
||||
console.log(event.detail);
|
||||
});
|
||||
Settings.callbackManager.on("llm-tool-result", (event) => {
|
||||
console.log(event.detail.payload);
|
||||
console.log(event.detail);
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ LlamaIndex.TS handles several major use cases:
|
||||
|
||||
- **Structured Data Extraction**: turning complex, unstructured and semi-structured data into uniform, programmatically accessible formats.
|
||||
- **Retrieval-Augmented Generation (RAG)**: answering queries across your internal data by providing LLMs with up-to-date, semantically relevant context including Question and Answer systems and chat bots.
|
||||
- **Autonomous Agents**: building software that is capable of intelligently selecting and using tools to accomplish tasks in an interative, unsupervised manner.
|
||||
- **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?
|
||||
|
||||
@@ -35,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.mdx) 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
|
||||
|
||||
@@ -12,9 +12,18 @@ 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
|
||||
- Anthropic 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,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)
|
||||
@@ -31,3 +31,7 @@ Settings.embedModel = new GeminiEmbedding({
|
||||
model: GEMINI_MODEL.GEMINI_PRO_LATEST,
|
||||
});
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [GeminiEmbedding](../../../api/classes/GeminiEmbedding.md)
|
||||
|
||||
@@ -32,3 +32,7 @@ Settings.embedModel = new HuggingFaceEmbedding({
|
||||
quantized: false,
|
||||
});
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [HuggingFaceEmbedding](../../../api/classes/HuggingFaceEmbedding.md)
|
||||
|
||||
@@ -19,3 +19,7 @@ const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [JinaAIEmbedding](../../../api/classes/JinaAIEmbedding.md)
|
||||
|
||||
@@ -22,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)
|
||||
@@ -27,3 +27,7 @@ const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [OllamaEmbedding](../../../api/classes/OllamaEmbedding.md)
|
||||
|
||||
@@ -19,3 +19,7 @@ const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [OpenAIEmbedding](../../../api/classes/OpenAIEmbedding.md)
|
||||
|
||||
@@ -21,3 +21,7 @@ const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [TogetherEmbedding](../../../api/classes/TogetherEmbedding.md)
|
||||
|
||||
@@ -16,6 +16,16 @@ Settings.embedModel = new OpenAIEmbedding({
|
||||
|
||||
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)
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
label: "Evaluating"
|
||||
position: 3
|
||||
position: 9
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
## Concept
|
||||
|
||||
Evaluation and benchmarking are crucial concepts in LLM development. To improve the perfomance of an LLM app (RAG, agents) you must have a way to measure it.
|
||||
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.
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ export OPENAI_API_KEY=your-api-key
|
||||
Import the required modules:
|
||||
|
||||
```ts
|
||||
import { CorrectnessEvaluator, OpenAI, Settings } from "llamaindex";
|
||||
import { CorrectnessEvaluator, OpenAI, Settings, Response } from "llamaindex";
|
||||
```
|
||||
|
||||
Let's setup gpt-4 for better results:
|
||||
@@ -45,7 +45,7 @@ const evaluator = new CorrectnessEvaluator();
|
||||
|
||||
const result = await evaluator.evaluateResponse({
|
||||
query,
|
||||
response,
|
||||
response: new Response(response),
|
||||
});
|
||||
|
||||
console.log(
|
||||
@@ -56,3 +56,7 @@ console.log(
|
||||
```bash
|
||||
the response is not correct with a score of 2.5
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [CorrectnessEvaluator](../../../api/classes/CorrectnessEvaluator.md)
|
||||
|
||||
@@ -76,3 +76,7 @@ console.log(`the response is ${result.passing ? "faithful" : "not faithful"}`);
|
||||
```bash
|
||||
the response is faithful
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [FaithfulnessEvaluator](../../../api/classes/FaithfulnessEvaluator.md)
|
||||
|
||||
@@ -21,7 +21,13 @@ export OPENAI_API_KEY=your-api-key
|
||||
Import the required modules:
|
||||
|
||||
```ts
|
||||
import { RelevancyEvaluator, OpenAI, Settings } from "llamaindex";
|
||||
import {
|
||||
RelevancyEvaluator,
|
||||
OpenAI,
|
||||
Settings,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
```
|
||||
|
||||
Let's setup gpt-4 for better results:
|
||||
@@ -64,3 +70,7 @@ console.log(`the response is ${result.passing ? "relevant" : "not relevant"}`);
|
||||
```bash
|
||||
the response is relevant
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [RelevancyEvaluator](../../../api/classes/RelevancyEvaluator.md)
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
label: "Ingestion Pipeline"
|
||||
position: 2
|
||||
position: 4
|
||||
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
MetadataMode,
|
||||
OpenAIEmbedding,
|
||||
TitleExtractor,
|
||||
SimpleNodeParser,
|
||||
SentenceSplitter,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
@@ -29,7 +29,7 @@ async function main() {
|
||||
const document = new Document({ text: essay, id_: path });
|
||||
const pipeline = new IngestionPipeline({
|
||||
transformations: [
|
||||
new SimpleNodeParser({ chunkSize: 1024, chunkOverlap: 20 }),
|
||||
new SentenceSplitter({ chunkSize: 1024, chunkOverlap: 20 }),
|
||||
new TitleExtractor(),
|
||||
new OpenAIEmbedding(),
|
||||
],
|
||||
@@ -62,7 +62,7 @@ import {
|
||||
MetadataMode,
|
||||
OpenAIEmbedding,
|
||||
TitleExtractor,
|
||||
SimpleNodeParser,
|
||||
SentenceSplitter,
|
||||
QdrantVectorStore,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
@@ -81,7 +81,7 @@ async function main() {
|
||||
const document = new Document({ text: essay, id_: path });
|
||||
const pipeline = new IngestionPipeline({
|
||||
transformations: [
|
||||
new SimpleNodeParser({ chunkSize: 1024, chunkOverlap: 20 }),
|
||||
new SentenceSplitter({ chunkSize: 1024, chunkOverlap: 20 }),
|
||||
new TitleExtractor(),
|
||||
new OpenAIEmbedding(),
|
||||
],
|
||||
@@ -97,3 +97,7 @@ async function main() {
|
||||
|
||||
main().catch(console.error);
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [IngestionPipeline](../../api/classes/IngestionPipeline.md)
|
||||
|
||||
@@ -4,19 +4,19 @@ A transformation is something that takes a list of nodes as an input, and return
|
||||
|
||||
Currently, the following components are Transformation objects:
|
||||
|
||||
- [SimpleNodeParser](../api/classes/SimpleNodeParser.md)
|
||||
- [SentenceSplitter](../../api/classes/SentenceSplitter.md)
|
||||
- [MetadataExtractor](../documents_and_nodes/metadata_extraction.md)
|
||||
- Embeddings
|
||||
- [Embeddings](../embeddings/index.md)
|
||||
|
||||
## Usage Pattern
|
||||
|
||||
While transformations are best used with with an IngestionPipeline, they can also be used directly.
|
||||
|
||||
```ts
|
||||
import { SimpleNodeParser, TitleExtractor, Document } from "llamaindex";
|
||||
import { SentenceSplitter, TitleExtractor, Document } from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
let nodes = new SimpleNodeParser().getNodesFromDocuments([
|
||||
let nodes = new SentenceSplitter().getNodesFromDocuments([
|
||||
new Document({ text: "I am 10 years old. John is 20 years old." }),
|
||||
]);
|
||||
|
||||
@@ -34,15 +34,15 @@ main().catch(console.error);
|
||||
|
||||
## Custom Transformations
|
||||
|
||||
You can implement any transformation yourself by implementing the `TransformerComponent`.
|
||||
You can implement any transformation yourself by implementing the `TransformComponent`.
|
||||
|
||||
The following custom transformation will remove any special characters or punctutaion in text.
|
||||
The following custom transformation will remove any special characters or punctuation in text.
|
||||
|
||||
```ts
|
||||
import { TransformerComponent, Node } from "llamaindex";
|
||||
import { TransformComponent, TextNode } from "llamaindex";
|
||||
|
||||
class RemoveSpecialCharacters extends TransformerComponent {
|
||||
async transform(nodes: Node[]): Promise<Node[]> {
|
||||
export class RemoveSpecialCharacters extends TransformComponent {
|
||||
async transform(nodes: TextNode[]): Promise<TextNode[]> {
|
||||
for (const node of nodes) {
|
||||
node.text = node.text.replace(/[^\w\s]/gi, "");
|
||||
}
|
||||
@@ -75,3 +75,7 @@ async function main() {
|
||||
|
||||
main().catch(console.error);
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [TransformComponent](../../api/classes/TransformComponent.md)
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
label: "LLMs"
|
||||
position: 3
|
||||
position: 5
|
||||
|
||||
@@ -63,3 +63,7 @@ async function main() {
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [Anthropic](../../../api/classes/Anthropic.md)
|
||||
|
||||
@@ -74,3 +74,7 @@ async function main() {
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [OpenAI](../../../api/classes/OpenAI.md)
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
# Bedrock
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { BEDROCK_MODELS, Bedrock } from "@llamaindex/community";
|
||||
|
||||
Settings.llm = new Bedrock({
|
||||
model: BEDROCK_MODELS.ANTHROPIC_CLAUDE_3_HAIKU,
|
||||
region: "us-east-1", // can be provided via env AWS_REGION
|
||||
credentials: {
|
||||
accessKeyId: "...", // optional and can be provided via env AWS_ACCESS_KEY_ID
|
||||
secretAccessKey: "...", // optional and can be provided via env AWS_SECRET_ACCESS_KEY
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Currently only supports Anthropic and Meta models:
|
||||
|
||||
```ts
|
||||
ANTHROPIC_CLAUDE_INSTANT_1 = "anthropic.claude-instant-v1";
|
||||
ANTHROPIC_CLAUDE_2 = "anthropic.claude-v2";
|
||||
ANTHROPIC_CLAUDE_2_1 = "anthropic.claude-v2:1";
|
||||
ANTHROPIC_CLAUDE_3_SONNET = "anthropic.claude-3-sonnet-20240229-v1:0";
|
||||
ANTHROPIC_CLAUDE_3_HAIKU = "anthropic.claude-3-haiku-20240307-v1:0";
|
||||
ANTHROPIC_CLAUDE_3_OPUS = "anthropic.claude-3-opus-20240229-v1:0"; // available on us-west-2
|
||||
ANTHROPIC_CLAUDE_3_5_SONNET = "anthropic.claude-3-5-sonnet-20240620-v1:0";
|
||||
META_LLAMA2_13B_CHAT = "meta.llama2-13b-chat-v1";
|
||||
META_LLAMA2_70B_CHAT = "meta.llama2-70b-chat-v1";
|
||||
META_LLAMA3_8B_INSTRUCT = "meta.llama3-8b-instruct-v1:0";
|
||||
META_LLAMA3_70B_INSTRUCT = "meta.llama3-70b-instruct-v1:0";
|
||||
META_LLAMA3_1_8B_INSTRUCT = "meta.llama3-1-8b-instruct-v1:0"; // available on us-west-2
|
||||
META_LLAMA3_1_70B_INSTRUCT = "meta.llama3-1-70b-instruct-v1:0"; // available on us-west-2
|
||||
META_LLAMA3_1_405B_INSTRUCT = "meta.llama3-1-405b-instruct-v1:0"; // preview only, available on us-west-2, tool calling supported
|
||||
```
|
||||
|
||||
Sonnet, Haiku and Opus are multimodal, image_url only supports base64 data url format, e.g. `data:image/jpeg;base64,SGVsbG8sIFdvcmxkIQ==`
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import { BEDROCK_MODELS, Bedrock } from "llamaindex";
|
||||
|
||||
Settings.llm = new Bedrock({
|
||||
model: BEDROCK_MODELS.ANTHROPIC_CLAUDE_3_HAIKU,
|
||||
});
|
||||
|
||||
async function main() {
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// Create a query engine
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
// Query
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
// Log the response
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
|
||||
## Agent Example
|
||||
|
||||
```ts
|
||||
import { BEDROCK_MODELS, Bedrock } from "@llamaindex/community";
|
||||
import { FunctionTool, LLMAgent } from "llamaindex";
|
||||
|
||||
const sumNumbers = FunctionTool.from(
|
||||
({ a, b }: { a: number; b: number }) => `${a + b}`,
|
||||
{
|
||||
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"],
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const divideNumbers = FunctionTool.from(
|
||||
({ a, b }: { a: number; b: number }) => `${a / b}`,
|
||||
{
|
||||
name: "divideNumbers",
|
||||
description: "Use this function to divide two numbers",
|
||||
parameters: {
|
||||
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 bedrock = new Bedrock({
|
||||
model: BEDROCK_MODELS.META_LLAMA3_1_405B_INSTRUCT,
|
||||
...
|
||||
});
|
||||
|
||||
async function main() {
|
||||
const agent = new LLMAgent({
|
||||
llm: bedrock,
|
||||
tools: [sumNumbers, divideNumbers],
|
||||
});
|
||||
|
||||
const response = await agent.chat({
|
||||
message: "How much is 5 + 5? then divide by 2",
|
||||
});
|
||||
|
||||
console.log(response.message);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,87 @@
|
||||
# DeepInfra
|
||||
|
||||
Check out available LLMs [here](https://deepinfra.com/models/text-generation).
|
||||
|
||||
```ts
|
||||
import { DeepInfra, Settings } from "llamaindex";
|
||||
|
||||
// Get the API key from `DEEPINFRA_API_TOKEN` environment variable
|
||||
import { config } from "dotenv";
|
||||
config();
|
||||
Settings.llm = new DeepInfra();
|
||||
|
||||
// Set the API key
|
||||
apiKey = "YOUR_API_KEY";
|
||||
Settings.llm = new DeepInfra({ apiKey });
|
||||
```
|
||||
|
||||
You can setup the apiKey on the environment variables, like:
|
||||
|
||||
```bash
|
||||
export DEEPINFRA_API_TOKEN="<YOUR_API_KEY>"
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
|
||||
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
|
||||
|
||||
```ts
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import { DeepInfra, Document, VectorStoreIndex, Settings } from "llamaindex";
|
||||
|
||||
// Use custom LLM
|
||||
const model = "meta-llama/Meta-Llama-3-8B-Instruct";
|
||||
Settings.llm = new DeepInfra({ model, temperature: 0 });
|
||||
|
||||
async function main() {
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
// Create a query engine
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
// Query
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
// Log the response
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
|
||||
## Feedback
|
||||
|
||||
If you have any feedback, please reach out to us at [feedback@deepinfra.com](mailto:feedback@deepinfra.com)
|
||||
|
||||
## API Reference
|
||||
|
||||
- [DeepInfra](../../../api/classes/DeepInfra)
|
||||
@@ -0,0 +1,52 @@
|
||||
# DeepSeek LLM
|
||||
|
||||
[DeepSeek Platform](https://platform.deepseek.com/)
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { DeepSeekLLM, Settings } from "llamaindex";
|
||||
|
||||
Settings.llm = new DeepSeekLLM({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
model: "deepseek-coder", // or "deepseek-chat"
|
||||
});
|
||||
```
|
||||
|
||||
## Example
|
||||
|
||||
```ts
|
||||
import { DeepSeekLLM, Document, VectorStoreIndex, Settings } from "llamaindex";
|
||||
|
||||
const deepseekLlm = new DeepSeekLLM({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
model: "deepseek-coder", // or "deepseek-chat"
|
||||
});
|
||||
|
||||
async function main() {
|
||||
const response = await llm.deepseekLlm.chat({
|
||||
messages: [
|
||||
{
|
||||
role: "system",
|
||||
content: "You are an AI assistant",
|
||||
},
|
||||
{
|
||||
role: "user",
|
||||
content: "Tell me about San Francisco",
|
||||
},
|
||||
],
|
||||
stream: false,
|
||||
});
|
||||
console.log(response);
|
||||
}
|
||||
```
|
||||
|
||||
# Limitations
|
||||
|
||||
Currently does not support function calling.
|
||||
|
||||
[Currently does not support json-output param while still is very good at json generating.](https://platform.deepseek.com/api-docs/faq#does-your-api-support-json-output)
|
||||
|
||||
## API Reference
|
||||
|
||||
- [DeepSeekLLM](../../../api/classes/DeepSeekLLM.md)
|
||||
@@ -1,6 +1,6 @@
|
||||
# Fireworks LLM
|
||||
|
||||
Fireworks.ai focus on production use cases for open source LLMs, offering speed and quality.
|
||||
[Fireworks.ai](https://fireworks.ai/) focus on production use cases for open source LLMs, offering speed and quality.
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -59,3 +59,7 @@ async function main() {
|
||||
|
||||
main().catch(console.error);
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [FireworksLLM](../../../api/classes/FireworksLLM.md)
|
||||
|
||||
@@ -99,3 +99,7 @@ async function main() {
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [Gemini](../../../api/classes/Gemini.md)
|
||||
|
||||
@@ -50,3 +50,7 @@ const results = await queryEngine.query({
|
||||
<CodeBlock language="ts" showLineNumbers>
|
||||
{CodeSource}
|
||||
</CodeBlock>
|
||||
|
||||
## API Reference
|
||||
|
||||
- [Groq](../../../api/classes/Groq.md)
|
||||
|
||||
@@ -89,3 +89,8 @@ async function main() {
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [LlamaDeuce](../../../api/variables/LlamaDeuce.md)
|
||||
- [DeuceChatStrategy](../../../api/variables/DeuceChatStrategy.md)
|
||||
|
||||
@@ -66,3 +66,7 @@ async function main() {
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [MistralAI](../../../api/classes/MistralAI.md)
|
||||
|
||||
@@ -71,3 +71,7 @@ async function main() {
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [Ollama](../../../api/classes/Ollama.md)
|
||||
|
||||
@@ -67,3 +67,7 @@ async function main() {
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [OpenAI](../../../api/classes/OpenAI.md)
|
||||
|
||||
@@ -68,3 +68,7 @@ async function main() {
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [Portkey](../../../api/classes/Portkey.md)
|
||||
|
||||
@@ -66,3 +66,7 @@ async function main() {
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [TogetherLLM](../../../api/classes/TogetherLLM.md)
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
# Large Language Models (LLMs)
|
||||
|
||||
The LLM is responsible for reading text and generating natural language responses to queries. By default, LlamaIndex.TS uses `gpt-3.5-turbo`.
|
||||
@@ -30,6 +26,15 @@ export AZURE_OPENAI_DEPLOYMENT="gpt-4" # or some other deployment name
|
||||
|
||||
For local LLMs, currently we recommend the use of [Ollama](./available_llms/ollama.md) LLM.
|
||||
|
||||
## Available LLMs
|
||||
|
||||
Most available LLMs are listed in the sidebar on the left. Additionally the following integrations exist without separate documentation:
|
||||
|
||||
- [HuggingFaceLLM](../../api/classes/HuggingFaceLLM.md) and [HuggingFaceInferenceAPI](../../api/classes/HuggingFaceInferenceAPI.md).
|
||||
- [ReplicateLLM](../../api/classes/ReplicateLLM.md) see [replicate.com](https://replicate.com/)
|
||||
|
||||
Check the [LlamaIndexTS Github](https://github.com/run-llama/LlamaIndexTS) for the most up to date overview of integrations.
|
||||
|
||||
## API Reference
|
||||
|
||||
- [OpenAI](../api/classes/OpenAI.md)
|
||||
- [OpenAI](../../api/classes/OpenAI.md)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
sidebar_position: 11
|
||||
---
|
||||
|
||||
# NodeParser
|
||||
@@ -7,9 +7,9 @@ sidebar_position: 4
|
||||
The `NodeParser` in LlamaIndex is responsible for splitting `Document` objects into more manageable `Node` objects. When you call `.fromDocuments()`, the `NodeParser` from the `Settings` is used to do this automatically for you. Alternatively, you can use it to split documents ahead of time.
|
||||
|
||||
```typescript
|
||||
import { Document, SimpleNodeParser } from "llamaindex";
|
||||
import { Document, SentenceSplitter } from "llamaindex";
|
||||
|
||||
const nodeParser = new SimpleNodeParser();
|
||||
const nodeParser = new SentenceSplitter();
|
||||
|
||||
Settings.nodeParser = nodeParser;
|
||||
```
|
||||
@@ -93,5 +93,5 @@ The output metadata will be something like:
|
||||
|
||||
## API Reference
|
||||
|
||||
- [SimpleNodeParser](../api/classes/SimpleNodeParser.md)
|
||||
- [SentenceSplitter](../api/classes/SentenceSplitter.md)
|
||||
- [MarkdownNodeParser](../api/classes/MarkdownNodeParser.md)
|
||||
|
||||
@@ -39,8 +39,9 @@ const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
The default value for `similarityTopK` is 2. This means that only the most similar document will be returned. To retrieve more results, you can increase the value of `similarityTopK`.
|
||||
|
||||
```ts
|
||||
const retriever = index.asRetriever();
|
||||
retriever.similarityTopK = 5;
|
||||
const retriever = index.asRetriever({
|
||||
similarityTopK: 5,
|
||||
});
|
||||
```
|
||||
|
||||
## Create a new instance of the CohereRerank class
|
||||
@@ -65,3 +66,7 @@ const queryEngine = index.asQueryEngine({
|
||||
// log the response
|
||||
const response = await queryEngine.query("Where did the author grown up?");
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [CohereRerank](../../api/classes/CohereRerank.md)
|
||||
|
||||
@@ -103,3 +103,8 @@ const processor = new SimilarityPostprocessor({
|
||||
|
||||
const filteredNodes = processor.postprocessNodes(nodes);
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [SimilarityPostprocessor](../../api/classes/SimilarityPostprocessor.md)
|
||||
- [MetadataReplacementPostProcessor](../../api/classes/MetadataReplacementPostProcessor.md)
|
||||
|
||||
@@ -39,8 +39,9 @@ const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
The default value for `similarityTopK` is 2. This means that only the most similar document will be returned. To retrieve more results, you can increase the value of `similarityTopK`.
|
||||
|
||||
```ts
|
||||
const retriever = index.asRetriever();
|
||||
retriever.similarityTopK = 5;
|
||||
const retriever = index.asRetriever({
|
||||
similarityTopK: 5,
|
||||
});
|
||||
```
|
||||
|
||||
## Create a new instance of the JinaAIReranker class
|
||||
@@ -69,3 +70,7 @@ const queryEngine = index.asQueryEngine({
|
||||
// log the response
|
||||
const response = await queryEngine.query("Where did the author grown up?");
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [JinaAIReranker](../../api/classes/JinaAIReranker.md)
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
# MixedbreadAI
|
||||
|
||||
Welcome to the mixedbread ai reranker guide! This guide will help you use mixedbread ai's API to rerank search query results, ensuring you get the most relevant information, just like picking the freshest bread from the bakery.
|
||||
|
||||
To find out more about the latest features and updates, visit the [mixedbread.ai](https://mixedbread.ai/).
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. [Setup](#setup)
|
||||
2. [Usage with LlamaIndex](#usage-with-llamaindex)
|
||||
3. [Simple Reranking Guide](#simple-reranking-guide)
|
||||
4. [Reranking with Objects](#reranking-with-objects)
|
||||
|
||||
## 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 `MixedbreadAIReranker` class.
|
||||
|
||||
```ts
|
||||
import {
|
||||
MixedbreadAIReranker,
|
||||
Document,
|
||||
OpenAI,
|
||||
VectorStoreIndex,
|
||||
Settings,
|
||||
} from "llamaindex";
|
||||
```
|
||||
|
||||
## Usage with LlamaIndex
|
||||
|
||||
This section will guide you through integrating mixedbread's reranker with LlamaIndex.
|
||||
|
||||
### 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
|
||||
const document = new Document({
|
||||
text: "This is a sample document.",
|
||||
id_: "sampleDoc",
|
||||
});
|
||||
|
||||
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
```
|
||||
|
||||
### Step 2: Increase Similarity TopK
|
||||
|
||||
The default value for `similarityTopK` is 2, which means only the most similar document will be returned. To get more results, like picking a variety of fresh breads, you can increase the value of `similarityTopK`.
|
||||
|
||||
```ts
|
||||
const retriever = index.asRetriever({
|
||||
similarityTopK: 5,
|
||||
});
|
||||
```
|
||||
|
||||
### Step 3: Create a MixedbreadAIReranker Instance
|
||||
|
||||
Create a new instance of the `MixedbreadAIReranker` class.
|
||||
|
||||
```ts
|
||||
const nodePostprocessor = new MixedbreadAIReranker({
|
||||
apiKey: "<MIXEDBREAD_API_KEY>",
|
||||
topN: 4,
|
||||
});
|
||||
```
|
||||
|
||||
### Step 4: Create a Query Engine
|
||||
|
||||
Combine the retriever and node postprocessor to create a query engine. This setup ensures that your queries are processed and reranked to provide the best results, like arranging the bread in the order of freshness and quality.
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
nodePostprocessors: [nodePostprocessor],
|
||||
});
|
||||
|
||||
// Log the response
|
||||
const response = await queryEngine.query("Where did the author grow up?");
|
||||
console.log(response);
|
||||
```
|
||||
|
||||
With mixedbread's Reranker, you're all set to serve up the most relevant and well-ordered results, just like a skilled baker arranging their best breads for eager customers. Enjoy the perfect blend of technology and culinary delight!
|
||||
|
||||
## Simple Reranking Guide
|
||||
|
||||
This section will guide you through a simple reranking process using mixedbread ai.
|
||||
|
||||
### Step 1: Create an Instance of MixedbreadAIReranker
|
||||
|
||||
Create a new instance of the `MixedbreadAIReranker` class, passing in your API key and the number of results you want to return. It's like setting up your bakery to offer a specific number of freshly baked items.
|
||||
|
||||
```ts
|
||||
const reranker = new MixedbreadAIReranker({
|
||||
apiKey: "<MIXEDBREAD_API_KEY>",
|
||||
topN: 4,
|
||||
});
|
||||
```
|
||||
|
||||
### Step 2: Define Nodes and Query
|
||||
|
||||
Define the nodes (documents) you want to rerank and the query.
|
||||
|
||||
```ts
|
||||
const nodes = [
|
||||
{ node: new BaseNode("To bake bread you need flour") },
|
||||
{ node: new BaseNode("To bake bread you need yeast") },
|
||||
];
|
||||
const query = "What do you need to bake bread?";
|
||||
```
|
||||
|
||||
### Step 3: Perform Reranking
|
||||
|
||||
Use the `postprocessNodes` method to rerank the nodes based on the query.
|
||||
|
||||
```ts
|
||||
const result = await reranker.postprocessNodes(nodes, query);
|
||||
console.log(result); // Like pulling freshly baked nodes out of the oven.
|
||||
```
|
||||
|
||||
## Reranking with Objects
|
||||
|
||||
This section will guide you through reranking when working with objects.
|
||||
|
||||
### Step 1: Create an Instance of MixedbreadAIReranker
|
||||
|
||||
Create a new instance of the `MixedbreadAIReranker` class, just like before.
|
||||
|
||||
```ts
|
||||
const reranker = new MixedbreadAIReranker({
|
||||
apiKey: "<MIXEDBREAD_API_KEY>",
|
||||
model: "mixedbread-ai/mxbai-rerank-large-v1",
|
||||
topK: 5,
|
||||
rankFields: ["title", "content"],
|
||||
returnInput: true,
|
||||
maxRetries: 5,
|
||||
});
|
||||
```
|
||||
|
||||
### Step 2: Define Documents and Query
|
||||
|
||||
Define the documents (objects) you want to rerank and the query.
|
||||
|
||||
```ts
|
||||
const documents = [
|
||||
{ title: "Bread Recipe", content: "To bake bread you need flour" },
|
||||
{ title: "Bread Recipe", content: "To bake bread you need yeast" },
|
||||
];
|
||||
const query = "What do you need to bake bread?";
|
||||
```
|
||||
|
||||
### Step 3: Perform Reranking
|
||||
|
||||
Use the `rerank` method to reorder the documents based on the query.
|
||||
|
||||
```ts
|
||||
const result = await reranker.rerank(documents, query);
|
||||
console.log(result); // Perfectly customized results, ready to serve.
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [MixedbreadAIReranker](../../api/classes/MixedbreadAIReranker.md)
|
||||
@@ -1,2 +1,2 @@
|
||||
label: "Prompts"
|
||||
position: 0
|
||||
position: 7
|
||||
|
||||
@@ -70,3 +70,8 @@ const response = await queryEngine.query({
|
||||
query: "What did the author do in college?",
|
||||
});
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [ResponseSynthesizer](../../api/classes/ResponseSynthesizer.md)
|
||||
- [CompactAndRefine](../../api/classes/CompactAndRefine.md)
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
label: "Query Engines"
|
||||
position: 2
|
||||
position: 8
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# QueryEngine
|
||||
|
||||
A query engine wraps a `Retriever` and a `ResponseSynthesizer` into a pipeline, that will use the query string to fetech nodes and then send them to the LLM to generate a response.
|
||||
A query engine wraps a `Retriever` and a `ResponseSynthesizer` into a pipeline, that will use the query string to fetch nodes and then send them to the LLM to generate a response.
|
||||
|
||||
```typescript
|
||||
const queryEngine = index.asQueryEngine();
|
||||
@@ -38,4 +38,4 @@ You can learn more about Tools by taking a look at the LlamaIndex Python documen
|
||||
|
||||
- [RetrieverQueryEngine](../../api/classes/RetrieverQueryEngine.md)
|
||||
- [SubQuestionQueryEngine](../../api/classes/SubQuestionQueryEngine.md)
|
||||
- [QueryEngineTool](../../api/interfaces/QueryEngineTool.md)
|
||||
- [QueryEngineTool](../../api/classes/QueryEngineTool.md)
|
||||
|
||||
@@ -75,7 +75,7 @@ const queryEngine = index.asQueryEngine({
|
||||
{
|
||||
key: "dogId",
|
||||
value: "2",
|
||||
filterType: "ExactMatch",
|
||||
operator: "==",
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -88,6 +88,8 @@ const response = await queryEngine.query({
|
||||
console.log(response.toString());
|
||||
```
|
||||
|
||||
Besides using the equal operator (`==`), you can also use a whole set of different [operators](../../api/interfaces/MetadataFilter.md#operator) to filter your documents.
|
||||
|
||||
## Full Code
|
||||
|
||||
```ts
|
||||
@@ -135,7 +137,7 @@ async function main() {
|
||||
{
|
||||
key: "dogId",
|
||||
value: "2",
|
||||
filterType: "ExactMatch",
|
||||
operator: "==",
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -151,3 +153,9 @@ async function main() {
|
||||
|
||||
main();
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [VectorStoreIndex](../../api/classes/VectorStoreIndex.md)
|
||||
- [ChromaVectorStore](../../api/classes/ChromaVectorStore.md)
|
||||
- [MetadataFilter](../../api/interfaces/MetadataFilter.md)
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
OpenAI,
|
||||
RouterQueryEngine,
|
||||
SimpleDirectoryReader,
|
||||
SimpleNodeParser,
|
||||
SentenceSplitter,
|
||||
SummaryIndex,
|
||||
VectorStoreIndex,
|
||||
Settings,
|
||||
@@ -34,11 +34,11 @@ const documents = await new SimpleDirectoryReader().loadData({
|
||||
|
||||
## Service Context
|
||||
|
||||
Next, we need to define some basic rules and parse the documents into nodes. We will use the `SimpleNodeParser` to parse the documents into nodes and `Settings` to define the rules (eg. LLM API key, chunk size, etc.):
|
||||
Next, we need to define some basic rules and parse the documents into nodes. We will use the `SentenceSplitter` to parse the documents into nodes and `Settings` to define the rules (eg. LLM API key, chunk size, etc.):
|
||||
|
||||
```ts
|
||||
Settings.llm = new OpenAI();
|
||||
Settings.nodeParser = new SimpleNodeParser({
|
||||
Settings.nodeParser = new SentenceSplitter({
|
||||
chunkSize: 1024,
|
||||
});
|
||||
```
|
||||
@@ -104,14 +104,14 @@ import {
|
||||
OpenAI,
|
||||
RouterQueryEngine,
|
||||
SimpleDirectoryReader,
|
||||
SimpleNodeParser,
|
||||
SentenceSplitter,
|
||||
SummaryIndex,
|
||||
VectorStoreIndex,
|
||||
Settings,
|
||||
} from "llamaindex";
|
||||
|
||||
Settings.llm = new OpenAI();
|
||||
Settings.nodeParser = new SimpleNodeParser({
|
||||
Settings.nodeParser = new SentenceSplitter({
|
||||
chunkSize: 1024,
|
||||
});
|
||||
|
||||
@@ -165,3 +165,7 @@ async function main() {
|
||||
|
||||
main().then(() => console.log("Done"));
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [RouterQueryEngine](../../api/classes/RouterQueryEngine.md)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
sidebar_position: 6
|
||||
sidebar_position: 15
|
||||
---
|
||||
|
||||
# ResponseSynthesizer
|
||||
|
||||
@@ -1,21 +1,23 @@
|
||||
---
|
||||
sidebar_position: 5
|
||||
sidebar_position: 14
|
||||
---
|
||||
|
||||
# Retriever
|
||||
|
||||
A retriever in LlamaIndex is what is used to fetch `Node`s from an index using a query string. Aa `VectorIndexRetriever` will fetch the top-k most similar nodes. Meanwhile, a `SummaryIndexRetriever` will fetch all nodes no matter the query.
|
||||
A retriever in LlamaIndex is what is used to fetch `Node`s from an index using a query string.
|
||||
|
||||
- [VectorIndexRetriever](../api/classes/VectorIndexRetriever.md) will fetch the top-k most similar nodes. Ideal for dense retrieval to find most relevant nodes.
|
||||
- [SummaryIndexRetriever](../api/classes/SummaryIndexRetriever.md) will fetch all nodes no matter the query. Ideal when complete context is necessary, e.g. analyzing large datasets.
|
||||
- [SummaryIndexLLMRetriever](../api/classes/SummaryIndexLLMRetriever.md) utilizes an LLM to score and filter nodes based on relevancy to the query.
|
||||
- [KeywordTableLLMRetriever](../api/classes/KeywordTableLLMRetriever.md) uses an LLM to extract keywords from the query and retrieve relevant nodes based on keyword matches.
|
||||
- [KeywordTableSimpleRetriever](../api/classes/KeywordTableSimpleRetriever.md) uses a basic frequency-based approach to extract keywords and retrieve nodes.
|
||||
- [KeywordTableRAKERetriever](../api/classes/KeywordTableRAKERetriever.md) uses the RAKE (Rapid Automatic Keyword Extraction) algorithm to extract keywords from the query, focusing on co-occurrence and context for keyword-based retrieval.
|
||||
|
||||
```typescript
|
||||
const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
const retriever = vectorIndex.asRetriever({
|
||||
similarityTopK: 3,
|
||||
});
|
||||
|
||||
// Fetch nodes!
|
||||
const nodesWithScore = await retriever.retrieve({ query: "query string" });
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [SummaryIndexRetriever](../api/classes/SummaryIndexRetriever.md)
|
||||
- [SummaryIndexLLMRetriever](../api/classes/SummaryIndexLLMRetriever.md)
|
||||
- [VectorIndexRetriever](../api/classes/VectorIndexRetriever.md)
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
---
|
||||
sidebar_position: 7
|
||||
---
|
||||
|
||||
# Storage
|
||||
|
||||
Storage in LlamaIndex.TS works automatically once you've configured a `StorageContext` object. Just configure the `persistDir` and attach it to an index.
|
||||
|
||||
Right now, only saving and loading from disk is supported, with future integrations planned!
|
||||
|
||||
```typescript
|
||||
import { Document, VectorStoreIndex, storageContextFromDefaults } from "./src";
|
||||
|
||||
const storageContext = await storageContextFromDefaults({
|
||||
persistDir: "./storage",
|
||||
});
|
||||
|
||||
const document = new Document({ text: "Test Text" });
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
storageContext,
|
||||
});
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [StorageContext](../api/interfaces//StorageContext.md)
|
||||
@@ -0,0 +1,168 @@
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../examples/workflow/joke.ts";
|
||||
|
||||
# Workflows
|
||||
|
||||
A `Workflow` in LlamaIndexTS is an event-driven abstraction used to chain together several events. Workflows are made up of `steps`, with each step responsible for handling certain event types and emitting new events.
|
||||
|
||||
Workflows in LlamaIndexTS work by defining step functions that handle specific event types and emit new events.
|
||||
|
||||
When a step function is added to a workflow, you need to specify the input and optionally the output event types (used for validation). The specification of the input events ensures each step only runs when an accepted event is ready.
|
||||
|
||||
You can create a `Workflow` to do anything! Build an agent, a RAG flow, an extraction flow, or anything else you want.
|
||||
|
||||
## Getting Started
|
||||
|
||||
As an illustrative example, let's consider a naive workflow where a joke is generated and then critiqued.
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
|
||||
There's a few moving pieces here, so let's go through this piece by piece.
|
||||
|
||||
### Defining Workflow Events
|
||||
|
||||
```typescript
|
||||
export class JokeEvent extends WorkflowEvent<{ joke: string }> {}
|
||||
```
|
||||
|
||||
Events are user-defined classes that extend `WorkflowEvent` and contain arbitrary data provided as template argument. In this case, our workflow relies on a single user-defined event, the `JokeEvent` with a `joke` attribute of type `string`.
|
||||
|
||||
### Setting up the Workflow Class
|
||||
|
||||
```typescript
|
||||
const llm = new OpenAI();
|
||||
...
|
||||
const jokeFlow = new Workflow({ verbose: true });
|
||||
```
|
||||
|
||||
Our workflow is implemented by initiating the `Workflow` class. For simplicity, we created a `OpenAI` llm instance.
|
||||
|
||||
### Workflow Entry Points
|
||||
|
||||
```typescript
|
||||
const generateJoke = async (_context: Context, ev: StartEvent) => {
|
||||
const prompt = `Write your best joke about ${ev.data.input}.`;
|
||||
const response = await llm.complete({ prompt });
|
||||
return new JokeEvent({ joke: response.text });
|
||||
};
|
||||
```
|
||||
|
||||
Here, we come to the entry-point of our workflow. While events are user-defined, there are two special-case events, the `StartEvent` and the `StopEvent`. Here, the `StartEvent` signifies where to send the initial workflow input.
|
||||
|
||||
The `StartEvent` is a bit of a special object since it can hold arbitrary attributes. Here, we accessed the topic with `ev.data.input`.
|
||||
|
||||
At this point, you may have noticed that we haven't explicitly told the workflow what events are handled by which steps.
|
||||
|
||||
To do so, we use the `addStep` method which adds a step to the workflow. The first argument is the event type that the step will handle, and the second argument is the previously defined step function:
|
||||
|
||||
```typescript
|
||||
jokeFlow.addStep(StartEvent, generateJoke);
|
||||
```
|
||||
|
||||
### Workflow Exit Points
|
||||
|
||||
```typescript
|
||||
const critiqueJoke = async (_context: Context, ev: JokeEvent) => {
|
||||
const prompt = `Give a thorough critique of the following joke: ${ev.data.joke}`;
|
||||
const response = await llm.complete({ prompt });
|
||||
return new StopEvent({ result: response.text });
|
||||
};
|
||||
```
|
||||
|
||||
Here, we have our second, and last step, in the workflow. We know its the last step because the special `StopEvent` is returned. When the workflow encounters a returned `StopEvent`, it immediately stops the workflow and returns whatever the result was.
|
||||
|
||||
In this case, the result is a string, but it could be a map, array, or any other object.
|
||||
|
||||
Don't forget to add the step to the workflow:
|
||||
|
||||
```typescript
|
||||
jokeFlow.addStep(JokeEvent, critiqueJoke);
|
||||
```
|
||||
|
||||
### Running the Workflow
|
||||
|
||||
```typescript
|
||||
const result = await jokeFlow.run("pirates");
|
||||
console.log(result.data.result);
|
||||
```
|
||||
|
||||
Lastly, we run the workflow. The `.run()` method is async, so we use await here to wait for the result.
|
||||
|
||||
### Validating Workflows
|
||||
|
||||
To tell the workflow what events are produced by each step, you can optionally provide a third argument to `addStep` to specify the output event type:
|
||||
|
||||
```typescript
|
||||
jokeFlow.addStep(StartEvent, generateJoke, { outputs: JokeEvent });
|
||||
jokeFlow.addStep(JokeEvent, critiqueJoke, { outputs: StopEvent });
|
||||
```
|
||||
|
||||
To validate a workflow, you need to call the `validate` method:
|
||||
|
||||
```typescript
|
||||
jokeFlow.validate();
|
||||
```
|
||||
|
||||
To automatically validate a workflow when you run it, you can set the `validate` flag to `true` at initialization:
|
||||
|
||||
```typescript
|
||||
const jokeFlow = new Workflow({ verbose: true, validate: true });
|
||||
```
|
||||
|
||||
## Working with Global Context/State
|
||||
|
||||
Optionally, you can choose to use global context between steps. For example, maybe multiple steps access the original `query` input from the user. You can store this in global context so that every step has access.
|
||||
|
||||
```typescript
|
||||
import { Context } from "@llamaindex/core/workflow";
|
||||
|
||||
const query = async (context: Context, ev: MyEvent) => {
|
||||
// get the query from the context
|
||||
const query = context.get("query");
|
||||
// do something with context and event
|
||||
const val = ...
|
||||
const result = ...
|
||||
// store in context
|
||||
context.set("key", val);
|
||||
|
||||
return new StopEvent({ result });
|
||||
};
|
||||
```
|
||||
|
||||
## Waiting for Multiple Events
|
||||
|
||||
The context does more than just hold data, it also provides utilities to buffer and wait for multiple events.
|
||||
|
||||
For example, you might have a step that waits for a query and retrieved nodes before synthesizing a response:
|
||||
|
||||
```typescript
|
||||
const synthesize = async (context: Context, ev: QueryEvent | RetrieveEvent) => {
|
||||
const events = context.collectEvents(ev, [QueryEvent | RetrieveEvent]);
|
||||
if (!events) {
|
||||
return;
|
||||
}
|
||||
const prompt = events
|
||||
.map((event) => {
|
||||
if (event instanceof QueryEvent) {
|
||||
return `Answer this query using the context provided: ${event.data.query}`;
|
||||
} else if (event instanceof RetrieveEvent) {
|
||||
return `Context: ${event.data.context}`;
|
||||
}
|
||||
return "";
|
||||
})
|
||||
.join("\n");
|
||||
|
||||
const response = await llm.complete({ prompt });
|
||||
return new StopEvent({ result: response.text });
|
||||
};
|
||||
```
|
||||
|
||||
Using `ctx.collectEvents()` we can buffer and wait for ALL expected events to arrive. This function will only return events (in the requested order) once all events have arrived.
|
||||
|
||||
## Manually Triggering Events
|
||||
|
||||
Normally, events are triggered by returning another event during a step. However, events can also be manually dispatched using the `ctx.sendEvent(event)` method within a workflow.
|
||||
|
||||
## Examples
|
||||
|
||||
You can find many useful examples of using workflows in the [examples folder](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/workflow).
|
||||
@@ -25,30 +25,6 @@ const config = {
|
||||
onBrokenLinks: "warn",
|
||||
onBrokenMarkdownLinks: "warn",
|
||||
|
||||
// Even if you don't use internalization, you can use this field to set useful
|
||||
// metadata like html lang. For example, if your site is Chinese, you may want
|
||||
// to replace "en" with "zh-Hans".
|
||||
i18n: {
|
||||
defaultLocale: "en",
|
||||
locales: [
|
||||
"en",
|
||||
"zh-Hans",
|
||||
"es",
|
||||
"fr",
|
||||
"de",
|
||||
"ja",
|
||||
"ko",
|
||||
"pt",
|
||||
"ar",
|
||||
"it",
|
||||
"tr",
|
||||
"pl",
|
||||
"nl",
|
||||
"vi",
|
||||
"th",
|
||||
], // "fa", "ru", "ro", "sv", "hu", "cs", "el", "da", "fi", "he", "no", "hi", "in", "sl", "se", "sk", "uk", "bg", "hr", "lt", "lv", "et", "cat"
|
||||
},
|
||||
|
||||
presets: [
|
||||
[
|
||||
"@docusaurus/preset-classic",
|
||||
@@ -167,7 +143,7 @@ const config = {
|
||||
[
|
||||
"docusaurus-plugin-typedoc",
|
||||
{
|
||||
entryPoints: ["../../packages/core/src/index.ts"],
|
||||
entryPoints: ["../../packages/llamaindex/src/index.ts"],
|
||||
tsconfig: "../../tsconfig.json",
|
||||
readme: "none",
|
||||
sourceLinkTemplate:
|
||||
|
||||
BIN
Binary file not shown.
|
Before Width: | Height: | Size: 27 KiB |
BIN
Binary file not shown.
|
Before Width: | Height: | Size: 49 KiB |
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user