mirror of
https://github.com/run-llama/LlamaIndexTS.git
synced 2026-07-01 22:14:03 -04:00
Compare commits
459 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b6ed679771 | |||
| 68fc6e8b50 | |||
| ea0331ef5a | |||
| 6827e245b8 | |||
| ef25d6960c | |||
| f740f44cf2 | |||
| a5e4e6d857 | |||
| cfdd6db530 | |||
| d4eda9f396 | |||
| a433b107e0 | |||
| 59f9fb6c3f | |||
| 09d532ebcc | |||
| cfd6f3ca8c | |||
| 95add73c38 | |||
| 9ee036b160 | |||
| c2b521199c | |||
| ee9f3f373a | |||
| f205358587 | |||
| 255ae7dced | |||
| b4c6d509a0 | |||
| 34cd57b639 | |||
| 50dfd7bf60 | |||
| 0b57187909 | |||
| e78e9f4832 | |||
| 383933adb5 | |||
| dd054137bf | |||
| cf3b7571eb | |||
| ae7a2c202a | |||
| 9b00d578bc | |||
| b8173e4c4e | |||
| 67b5445fb9 | |||
| 87419ef5d1 | |||
| ad218160d8 | |||
| eeb90d7991 | |||
| 7b7329bd18 | |||
| b3acbb06f4 | |||
| 7db7562841 | |||
| 0e75b124c3 | |||
| d79a0b76f3 | |||
| c3eb4933fb | |||
| e3a956aedd | |||
| e562e479dc | |||
| 1900e019e3 | |||
| 317f140822 | |||
| cd829474d6 | |||
| b6c1500570 | |||
| d06a85bd34 | |||
| 6b9a2feac5 | |||
| bd08004afe | |||
| 0ecc4b2051 | |||
| f9f351229a | |||
| 72659a237b | |||
| 6cc3a36d44 | |||
| 6fe55d6e88 | |||
| 36f2903eb3 | |||
| 09464e6da7 | |||
| 955e084cf3 | |||
| 46ee0c8765 | |||
| da5391c018 | |||
| ce732beece | |||
| 889b70093c | |||
| 7211a27f01 | |||
| ba95ca3fb6 | |||
| ffdc507625 | |||
| 8aef0dece9 | |||
| c680af63ef | |||
| 4a7ac65184 | |||
| 4016c55604 | |||
| 0f64084c20 | |||
| 7af03d9205 | |||
| d903da626f | |||
| 177b446229 | |||
| ab9d941d15 | |||
| 66fd990624 | |||
| f6dabd0d3e | |||
| 74caaa2bf7 | |||
| 552403b370 | |||
| a93d09d159 | |||
| 0fb757f6c1 | |||
| a68053ca4e | |||
| 36d4f4027b | |||
| 19d92507e3 | |||
| 664e92a3d6 | |||
| d687c110e4 | |||
| af5ae7054e | |||
| dff1e7f552 | |||
| cf446401e5 | |||
| e9b87ef09b | |||
| 7231ddb1b3 | |||
| 1ead36f1bb | |||
| 8a9b78a4ab | |||
| 569299724a | |||
| 6dd401e1c7 | |||
| c4cb37786b | |||
| b757d9a94e | |||
| 6cc083f370 | |||
| c419027db9 | |||
| 6a16b47406 | |||
| 4197ae8b9f | |||
| 88696e1407 | |||
| 24cb48f195 | |||
| 965cfd291e | |||
| 873329c052 | |||
| 3d8023b9a9 | |||
| 93d1450fc1 | |||
| 27d55fde8c | |||
| 690399b04c | |||
| 65b84f1ab3 | |||
| 835acb89d0 | |||
| d9df9ea75c | |||
| 06874ffb69 | |||
| f0898a3930 | |||
| 7d50196d2f | |||
| f90f7fee64 | |||
| 3d860df873 | |||
| 2fe3a2b6a8 | |||
| eb3d4af204 | |||
| 0652352e92 | |||
| 103949513b | |||
| 9ba4547c4d | |||
| 4fea0adf43 | |||
| de070dbfa7 | |||
| 87eb72bdb2 | |||
| fe03aaae55 | |||
| 9ce7d3d648 | |||
| 0471407761 | |||
| e4b807a018 | |||
| 0a0ec37725 | |||
| 8abca5d818 | |||
| 3a29a8036b | |||
| e2b9b66f71 | |||
| bb66cb7e36 | |||
| 2159e77c9d | |||
| 3154f521d9 | |||
| fda8024607 | |||
| 89336e4ddf | |||
| a94f747307 | |||
| 88d3b41044 | |||
| 7fd02ab8d1 | |||
| 9e5d8e143e | |||
| f0f7df29b3 | |||
| 05ba70881c | |||
| 8a729cdd0d | |||
| ffe5fbcd51 | |||
| 18cc545e16 | |||
| c818e90cfc | |||
| 570973b9d6 | |||
| 09d19b99ba | |||
| 7ad30dc660 | |||
| 5c1702c527 | |||
| f1063d58ae | |||
| eee39221c4 | |||
| 4303961948 | |||
| e2790dabc8 | |||
| ba42aa592c | |||
| e1deba1222 | |||
| f9c2dd1b3a | |||
| 8bf0a41926 | |||
| 5c89aa54c4 | |||
| 69484526e6 | |||
| bfc84384ea | |||
| cce3b792db | |||
| bff40f27c5 | |||
| c3e3b598bb | |||
| fa17f7e352 | |||
| 3aed922a3b | |||
| 7c4e37c5cd | |||
| 2d8845b084 | |||
| 47f21796e0 | |||
| eb6de99fcb | |||
| 2bfc8f3161 | |||
| bcacf88e55 | |||
| 13766a82b2 | |||
| 34d7ca66f5 | |||
| 17a803bb17 | |||
| 1bd47969b3 | |||
| 5fec0f1135 | |||
| a73942ddea | |||
| 34a26e5e4d | |||
| f74dea5fae | |||
| ee3eb7d8e2 | |||
| 75f94eea1b | |||
| b737bda40d | |||
| d99b1d61d7 | |||
| 844029d8e5 | |||
| 9492cc64b5 | |||
| 5773f97e88 | |||
| 0784dc3a0a | |||
| 7993be7d0d | |||
| f22ce6e757 | |||
| 3c4347b247 | |||
| 977f2840b9 | |||
| 5d3bb6642e | |||
| 2001eb7ffb | |||
| f18c9f69d4 | |||
| 8e124e5b63 | |||
| 4ed5e544b0 | |||
| b185bda5b1 | |||
| d79804e271 | |||
| 2b356c8613 | |||
| 2e6b36ef4b | |||
| edd0f66234 | |||
| 2da407d66c | |||
| fa574f709e | |||
| 1e6171521b | |||
| 3f3e4eca66 | |||
| 648482b0f1 | |||
| bb46afe33d | |||
| 80f5914abf | |||
| 1c4e7f9c3e | |||
| e4ae6e9076 | |||
| f93efa2ea1 | |||
| 7d79365262 | |||
| 555692207e | |||
| fcc06b227a | |||
| 08a39790e4 | |||
| a8270082a0 | |||
| 85da798538 | |||
| b68d8697df | |||
| 7704df5042 | |||
| 16f04c7e7e | |||
| 7c6b3117bf | |||
| 7def68fb37 | |||
| 03ed2b4129 | |||
| 733d62a699 | |||
| f76e1d0796 | |||
| 88d42ccd8d | |||
| a0686fb1f2 | |||
| 3d198d94a6 | |||
| 036c00db73 | |||
| 548f0687f1 | |||
| f85c042a94 | |||
| 40e892f813 | |||
| 2381025306 | |||
| a0909dc053 | |||
| 853a14b7c7 | |||
| b31e2d42eb | |||
| 5b6ad9419f | |||
| a60948a87e | |||
| 8b420da753 | |||
| 12c079b74a | |||
| c835f78dd0 | |||
| d52eb9d4ee | |||
| 0cfd9f60b5 | |||
| 5ab65eb95a | |||
| b13fb36de0 | |||
| d8fe65a273 | |||
| ba1cb996cf | |||
| 41f41d6543 | |||
| e25fc44db9 | |||
| 2ea91dc94b | |||
| b16419ad3e | |||
| 1e3c05c408 | |||
| a7eb59f472 | |||
| e99448481c | |||
| 83ab7622d9 | |||
| d4312d504b | |||
| 95742e7704 | |||
| a8845a33df | |||
| b3fd87f302 | |||
| 25ba970e09 | |||
| a67f9aaad7 | |||
| 210ce35867 | |||
| 36905f6442 | |||
| ed509db04a | |||
| 14413c0637 | |||
| 9682c95da8 | |||
| 7c6eba90e5 | |||
| c85bf225b9 | |||
| b51c2d66a5 | |||
| 935bc52239 | |||
| 57ff51823c | |||
| 06b20a1772 | |||
| 7a98255149 | |||
| 980038c711 | |||
| 09d4e36200 | |||
| 8fb523bcef | |||
| e48a621d61 | |||
| 1f87787b05 | |||
| fb6cef8a0b | |||
| 21368f6218 | |||
| 116685017d | |||
| 23082f2c5e | |||
| ff2b3ca727 | |||
| e55d41f5df | |||
| 91fb5101d6 | |||
| 9c5e22a656 | |||
| 18f23b298e | |||
| ddf39ebeaa | |||
| 320b515e7d | |||
| 04c50ee946 | |||
| 3d626d68aa | |||
| 9c0442bdb5 | |||
| 606ffa40d1 | |||
| e9f6de1238 | |||
| 8110ab98b6 | |||
| b8c4bd70ae | |||
| 2e49856621 | |||
| 2039509811 | |||
| 420f2ddeb7 | |||
| afc0516868 | |||
| 02a0f5e96c | |||
| 2f7b05006b | |||
| 314089b0a1 | |||
| 60e626d6d0 | |||
| 5c2050ebcf | |||
| 7fd2870d45 | |||
| 609e3339c0 | |||
| 0e01723aee | |||
| 25141b85f9 | |||
| 21510bd664 | |||
| 696d1de19f | |||
| 56020b4bc3 | |||
| 62e29d5a51 | |||
| 15c890a7b8 | |||
| 43b33c558f | |||
| be0661f156 | |||
| b9a5a0498a | |||
| 8c4261500c | |||
| 2254d98bcc | |||
| 21f9096846 | |||
| 9830dc2962 | |||
| c29a8cc63b | |||
| ef7872eb4f | |||
| 3282223511 | |||
| c99c5eb03f | |||
| 3b759c26c4 | |||
| 5038a1f351 | |||
| 0aa7552de6 | |||
| 7fae7d2cde | |||
| f35d8e5b64 | |||
| 63cc0a35d3 | |||
| d159bdd50c | |||
| 0f2c609621 | |||
| 4e14952b24 | |||
| b36d4b2723 | |||
| bf53cd3d3d | |||
| f2e3935c0b | |||
| 77f41f9356 | |||
| 042500dd55 | |||
| f0be93313a | |||
| bf9e26319c | |||
| 5054eb3b10 | |||
| 9bea88c7b8 | |||
| 786c25d342 | |||
| d00f18d567 | |||
| 0f363487e9 | |||
| b471da75d6 | |||
| e5937ff6f8 | |||
| 08379e61bf | |||
| 6c8a65b055 | |||
| d059db62c3 | |||
| e4dd4a9036 | |||
| c0fc9f6e55 | |||
| 72d919566c | |||
| 2aeb3415b1 | |||
| 680a12f87e | |||
| 7a83b34c16 | |||
| ecd16f9fb0 | |||
| 54ca85d482 | |||
| 65ef0be90c | |||
| 57106affdf | |||
| d613bbd358 | |||
| d0bf2104dc | |||
| e70413373f | |||
| 36f0af5a5d | |||
| 79d7076121 | |||
| 526b3e74bf | |||
| d03dc21e8a | |||
| c31dfa4957 | |||
| c7e510723d | |||
| 42093de872 | |||
| 886e58828e | |||
| c8eaf1c9ac | |||
| 2169dadccc | |||
| 4bc8a7b733 | |||
| 61eb955921 | |||
| aa48a5d764 | |||
| 1dedca45ac | |||
| 9d90335a12 | |||
| b577acb115 | |||
| 425e2bcccc | |||
| 3766251891 | |||
| 3552de1b45 | |||
| 2b94e36df6 | |||
| d1e1de4a8d | |||
| 23587e17ad | |||
| 213f452f0b | |||
| 27a488539d | |||
| 283da50d33 | |||
| a809085715 | |||
| 67321f1cba | |||
| 7683186470 | |||
| fded43b77e | |||
| 22ff7da4e0 | |||
| 844561b6cc | |||
| 1fe02a3067 | |||
| 362d8ecb31 | |||
| 5f5f6389f9 | |||
| 31cf3cde45 | |||
| 11f0c2cab1 | |||
| 52bc1d8387 | |||
| 8a3ac0c338 | |||
| bb125d7d4f | |||
| a405716847 | |||
| bad6e03095 | |||
| 2330fddfbb | |||
| 61dfd74134 | |||
| 029ff83979 | |||
| dbbc4cb2e1 | |||
| 1cce21cdc2 | |||
| 8b786a51b3 | |||
| ad7537dd84 | |||
| 3bab23172a | |||
| 18c132d494 | |||
| d072353e08 | |||
| c8bbc101cc | |||
| b93f748998 | |||
| ecb100448a | |||
| c749c856b5 | |||
| 0baf278972 | |||
| ae7780266a | |||
| 587960aebe | |||
| 4e1b6784f7 | |||
| 8b381f2640 | |||
| 0dc7fa6c34 | |||
| 2a2bf682bf | |||
| 87526129fb | |||
| 8ed1b7aa46 | |||
| 4084bd0ecc | |||
| d11eaceaf1 | |||
| 1e6986fbc5 | |||
| 11a19bdec7 | |||
| 51064f1b90 | |||
| 3385cd19e8 | |||
| 852f8517df | |||
| bb917f9818 | |||
| 10248fb29f | |||
| 446dc85bdd | |||
| 4aa2c226a9 | |||
| bf9ba8313a | |||
| 444b59c557 | |||
| b2e1df94db | |||
| b4963cabc8 | |||
| 2851024340 | |||
| 7f25a25729 | |||
| acfe23265a | |||
| 2c6fbbd7dd | |||
| 3e8c923641 | |||
| df5cbe30a6 | |||
| 9e1a536778 | |||
| a1db8833ef | |||
| 95dd0e0158 | |||
| 19f3c857d5 | |||
| 7f3da73aa4 | |||
| c384c2b610 | |||
| dcf358f27d | |||
| 40afc8c0e2 | |||
| b22bc8a799 |
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://unpkg.com/@changesets/config@2.3.1/schema.json",
|
||||
"changelog": "@changesets/cli/changelog",
|
||||
"commit": false,
|
||||
"commit": true,
|
||||
"fixed": [],
|
||||
"linked": [],
|
||||
"access": "public",
|
||||
|
||||
@@ -7,4 +7,8 @@ module.exports = {
|
||||
rootDir: ["apps/*/"],
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
"max-params": ["error", 4],
|
||||
},
|
||||
ignorePatterns: ["dist/"],
|
||||
};
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
examples/readers/data/** binary
|
||||
examples/data/** binary
|
||||
@@ -1,7 +1,6 @@
|
||||
name: Bugfix
|
||||
title: "Sweep: "
|
||||
description: Write something like "We notice ... behavior when ... happens instead of ...""
|
||||
labels: sweep
|
||||
title: ""
|
||||
description: Write something like "We notice ... behavior when ... happens instead of ..." If you would like to use sweep.dev prefix with "Sweep:"
|
||||
body:
|
||||
- type: textarea
|
||||
id: description
|
||||
@@ -1,11 +1,10 @@
|
||||
name: Feature Request
|
||||
title: "Sweep: "
|
||||
description: Write something like "Write an api endpoint that does "..." in the "..." file"
|
||||
labels: sweep
|
||||
title: ""
|
||||
description: Write something like "Write an api endpoint that does "..." in the "..." file". If you would like to use sweep.dev prefix with "Sweep:"
|
||||
body:
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: Details
|
||||
description: More details for Sweep
|
||||
description: More details
|
||||
placeholder: The new endpoint should use the ... class from ... file because it contains ... logic
|
||||
@@ -1,11 +1,10 @@
|
||||
name: Refactor
|
||||
title: "Sweep: "
|
||||
description: Write something like "Modify the ... api endpoint to use ... version and ... framework"
|
||||
labels: sweep
|
||||
title: ""
|
||||
description: Write something like "Modify the ... api endpoint to use ... version and ... framework" If you would like to use sweep.dev prefix with "Sweep:"
|
||||
body:
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: Details
|
||||
description: More details for Sweep
|
||||
description: More details
|
||||
placeholder: We are migrating this function to ... version because ...
|
||||
@@ -0,0 +1,68 @@
|
||||
name: E2E Tests
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
paths:
|
||||
- "packages/create-llama/**"
|
||||
- ".github/workflows/e2e.yml"
|
||||
branches: [main]
|
||||
|
||||
env:
|
||||
POETRY_VERSION: "1.6.1"
|
||||
|
||||
jobs:
|
||||
e2e:
|
||||
name: create-llama
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: true
|
||||
matrix:
|
||||
node-version: [18, 20]
|
||||
python-version: ["3.11"]
|
||||
os: [macos-latest, windows-latest]
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Set up python ${{ matrix.python-version }}
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
- name: Install Poetry
|
||||
uses: snok/install-poetry@v1
|
||||
with:
|
||||
version: ${{ env.POETRY_VERSION }}
|
||||
- uses: pnpm/action-setup@v2
|
||||
- name: Setup Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: "pnpm"
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
- name: Install Playwright Browsers
|
||||
run: pnpm exec playwright install --with-deps
|
||||
working-directory: ./packages/create-llama
|
||||
- name: Build create-llama
|
||||
run: pnpm run build
|
||||
working-directory: ./packages/create-llama
|
||||
- name: Pack
|
||||
run: pnpm pack --pack-destination ./output
|
||||
working-directory: ./packages/create-llama
|
||||
- name: Extract Pack
|
||||
run: tar -xvzf ./output/*.tgz -C ./output
|
||||
working-directory: ./packages/create-llama
|
||||
- name: Run Playwright tests
|
||||
run: pnpm exec playwright test
|
||||
env:
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
working-directory: ./packages/create-llama
|
||||
- uses: actions/upload-artifact@v3
|
||||
if: always()
|
||||
with:
|
||||
name: playwright-report
|
||||
path: ./packages/create-llama/playwright-report/
|
||||
retention-days: 30
|
||||
@@ -12,14 +12,18 @@ jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Install pnpm
|
||||
run: npm install -g pnpm
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v2
|
||||
with:
|
||||
version: latest
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: "pnpm"
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Run lint
|
||||
run: pnpm run lint
|
||||
- name: Run Prettier
|
||||
run: pnpm run format
|
||||
|
||||
+58
-10
@@ -7,18 +7,66 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v2
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v2
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "18"
|
||||
|
||||
node-version-file: ".nvmrc"
|
||||
cache: "pnpm"
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
npm i -g pnpm
|
||||
pnpm install
|
||||
|
||||
run: pnpm install
|
||||
- name: Run tests
|
||||
run: pnpm run test
|
||||
typecheck:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v2
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: "pnpm"
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
- name: Build
|
||||
run: pnpm run build --filter llamaindex
|
||||
- name: Run Type Check
|
||||
run: pnpm run type-check
|
||||
- name: Run Circular Dependency Check
|
||||
run: pnpm run circular-check
|
||||
working-directory: ./packages/core
|
||||
- uses: actions/upload-artifact@v3
|
||||
if: failure()
|
||||
with:
|
||||
name: typecheck-build-dist
|
||||
path: ./packages/core/dist
|
||||
if-no-files-found: error
|
||||
typecheck-examples:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v2
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: "pnpm"
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
- name: Build
|
||||
run: pnpm run build --filter llamaindex
|
||||
- name: Copy examples
|
||||
run: rsync -rv --exclude=node_modules ./examples ${{ runner.temp }}
|
||||
- name: Pack
|
||||
run: pnpm pack --pack-destination ${{ runner.temp }}
|
||||
working-directory: packages/core
|
||||
- name: Install llamaindex
|
||||
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
|
||||
|
||||
+9
-2
@@ -37,6 +37,13 @@ yarn-error.log*
|
||||
.vercel
|
||||
|
||||
dist/
|
||||
lib/
|
||||
|
||||
# vs code
|
||||
.vscode/launch.json
|
||||
.cache
|
||||
test-results/
|
||||
playwright-report/
|
||||
blob-report/
|
||||
playwright/.cache/
|
||||
|
||||
# intellij
|
||||
**/.idea
|
||||
|
||||
+1
-3
@@ -1,5 +1,3 @@
|
||||
#!/usr/bin/env sh
|
||||
. "$(dirname -- "$0")/_/husky.sh"
|
||||
|
||||
pnpm format
|
||||
pnpm lint
|
||||
npx lint-staged
|
||||
|
||||
@@ -1,4 +1 @@
|
||||
#!/usr/bin/env sh
|
||||
. "$(dirname -- "$0")/_/husky.sh"
|
||||
|
||||
pnpm test
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
apps/docs/i18n
|
||||
apps/docs/docs/api
|
||||
pnpm-lock.yaml
|
||||
lib/
|
||||
dist/
|
||||
.docusaurus/
|
||||
Vendored
+17
@@ -0,0 +1,17 @@
|
||||
{
|
||||
// Use IntelliSense to learn about possible attributes.
|
||||
// Hover to view descriptions of existing attributes.
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
"name": "Debug Example",
|
||||
"skipFiles": ["<node_internals>/**"],
|
||||
"runtimeExecutable": "pnpm",
|
||||
"cwd": "${workspaceFolder}/examples",
|
||||
"runtimeArgs": ["ts-node", "${fileBasename}"]
|
||||
}
|
||||
]
|
||||
}
|
||||
Vendored
+10
@@ -4,5 +4,15 @@
|
||||
"editor.defaultFormatter": "esbenp.prettier-vscode",
|
||||
"[xml]": {
|
||||
"editor.defaultFormatter": "redhat.vscode-xml"
|
||||
},
|
||||
"jest.rootPath": "./packages/core",
|
||||
"[python]": {
|
||||
"editor.defaultFormatter": "ms-python.black-formatter"
|
||||
},
|
||||
"[jsonc]": {
|
||||
"editor.defaultFormatter": "esbenp.prettier-vscode"
|
||||
},
|
||||
"[json]": {
|
||||
"editor.defaultFormatter": "esbenp.prettier-vscode"
|
||||
}
|
||||
}
|
||||
|
||||
+15
-3
@@ -8,7 +8,7 @@ Right now there are two packages of importance:
|
||||
|
||||
packages/core which is the main NPM library llamaindex
|
||||
|
||||
apps/simple is where the demo code lives
|
||||
examples is where the demo code lives
|
||||
|
||||
### Turborepo docs
|
||||
|
||||
@@ -47,7 +47,7 @@ We use Jest https://jestjs.io/ to write our test cases. Jest comes with a bunch
|
||||
|
||||
### Demo applications
|
||||
|
||||
There is an existing ["simple"](/apps/simple/README.md) demos folder with mainly NodeJS scripts. Feel free to add additional demos to that folder. If you would like to try out your changes in the core package with a new demo, you need to run the build command in the README.
|
||||
There is an existing ["example"](/examples/README.md) demos folder with mainly NodeJS scripts. Feel free to add additional demos to that folder. If you would like to try out your changes in the core package with a new demo, you need to run the build command in the README.
|
||||
|
||||
You can create new demo applications in the apps folder. Just run pnpm init in the folder after you create it to create its own package.json
|
||||
|
||||
@@ -56,7 +56,7 @@ You can create new demo applications in the apps folder. Just run pnpm init in t
|
||||
To install packages for a specific package or demo application, run
|
||||
|
||||
```
|
||||
pnpm add [NPM Package] --filter [package or application i.e. core or simple]
|
||||
pnpm add [NPM Package] --filter [package or application i.e. core or docs]
|
||||
```
|
||||
|
||||
To install packages for every package or application run
|
||||
@@ -78,3 +78,15 @@ pnpm start
|
||||
That should start a webserver which will serve the docs on https://localhost:3000
|
||||
|
||||
Any changes you make should be reflected in the browser. If you need to regenerate the API docs and find that your TSDoc isn't getting the updates, feel free to remove apps/docs/api. It will automatically regenerate itself when you run pnpm start again.
|
||||
|
||||
## Publishing
|
||||
|
||||
To publish a new version of the library, run
|
||||
|
||||
```shell
|
||||
pnpm new-llamaindex
|
||||
pnpm new-create-llama
|
||||
pnpm release
|
||||
git push # push to the main branch
|
||||
git push --tags
|
||||
```
|
||||
|
||||
@@ -1,18 +1,27 @@
|
||||
# LlamaIndex.TS
|
||||
|
||||
[](https://www.npmjs.com/package/llamaindex)
|
||||
[](https://www.npmjs.com/package/llamaindex)
|
||||
[](https://www.npmjs.com/package/llamaindex)
|
||||
[](https://discord.com/invite/eN6D2HQ4aX)
|
||||
|
||||
LlamaIndex is a data framework for your LLM application.
|
||||
|
||||
Use your own data with large language models (LLMs, OpenAI ChatGPT and others) in Typescript and Javascript.
|
||||
|
||||
Documentation: https://ts.llamaindex.ai/
|
||||
|
||||
Try examples online:
|
||||
|
||||
[](https://stackblitz.com/github/run-llama/LlamaIndexTS/tree/main/examples)
|
||||
|
||||
## What is LlamaIndex.TS?
|
||||
|
||||
LlamaIndex.TS aims to be a lightweight, easy to use set of libraries to help you integrate large language models into your applications with your own data.
|
||||
|
||||
## Getting started with an example:
|
||||
|
||||
LlamaIndex.TS requries Node v18 or higher. You can download it from https://nodejs.org or use https://nvm.sh (our preferred option).
|
||||
LlamaIndex.TS requires Node v18 or higher. You can download it from https://nodejs.org or use https://nvm.sh (our preferred option).
|
||||
|
||||
In a new folder:
|
||||
|
||||
@@ -47,9 +56,9 @@ async function main() {
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine();
|
||||
const response = await queryEngine.query(
|
||||
"What did the author do in college?",
|
||||
);
|
||||
const response = await queryEngine.query({
|
||||
query: "What did the author do in college?",
|
||||
});
|
||||
|
||||
// Output response
|
||||
console.log(response.toString());
|
||||
@@ -61,7 +70,7 @@ main();
|
||||
Then you can run it using
|
||||
|
||||
```bash
|
||||
pnpx ts-node example.ts
|
||||
pnpm dlx ts-node example.ts
|
||||
```
|
||||
|
||||
## Playground
|
||||
@@ -86,7 +95,7 @@ Check out our NextJS playground at https://llama-playground.vercel.app/. The sou
|
||||
|
||||
## Note: NextJS:
|
||||
|
||||
If you're using NextJS App Router, you'll need to use the NodeJS runtime (default) and add the follow config to your next.config.js to have it use imports/exports in the same way Node does.
|
||||
If you're using NextJS App Router, you'll need to use the NodeJS runtime (default) and add the following config to your next.config.js to have it use imports/exports in the same way Node does.
|
||||
|
||||
```js
|
||||
export const runtime = "nodejs"; // default
|
||||
@@ -97,7 +106,15 @@ export const runtime = "nodejs"; // default
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
experimental: {
|
||||
serverComponentsExternalPackages: ["pdf-parse"], // Puts pdf-parse in actual NodeJS mode with NextJS App Router
|
||||
serverComponentsExternalPackages: ["pdf2json"],
|
||||
},
|
||||
webpack: (config) => {
|
||||
config.resolve.alias = {
|
||||
...config.resolve.alias,
|
||||
sharp$: false,
|
||||
"onnxruntime-node$": false,
|
||||
};
|
||||
return config;
|
||||
},
|
||||
};
|
||||
|
||||
@@ -109,6 +126,8 @@ module.exports = nextConfig;
|
||||
- OpenAI GPT-3.5-turbo and GPT-4
|
||||
- Anthropic Claude Instant and Claude 2
|
||||
- Llama2 Chat LLMs (70B, 13B, and 7B parameters)
|
||||
- MistralAI Chat LLMs
|
||||
- Fireworks Chat LLMs
|
||||
|
||||
## Contributing:
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
# Generated files
|
||||
.docusaurus
|
||||
.cache-loader
|
||||
lib
|
||||
|
||||
# Misc
|
||||
.DS_Store
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# docs
|
||||
|
||||
## 0.0.2
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 0f64084: docs: update API references
|
||||
|
||||
## 0.0.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 3154f52: chore: add qdrant readme
|
||||
@@ -1,45 +0,0 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
# End to End Examples
|
||||
|
||||
We include several end-to-end examples using LlamaIndex.TS in the repository
|
||||
|
||||
Check out the examples below or try them out and complete them in minutes with interactive Github Codespace tutorials provided by Dev-Docs [here](https://codespaces.new/team-dev-docs/lits-dev-docs-playground?devcontainer_path=.devcontainer%2Fjavascript_ltsquickstart%2Fdevcontainer.json):
|
||||
|
||||
## [Chat Engine](https://github.com/run-llama/LlamaIndexTS/blob/main/apps/simple/chatEngine.ts)
|
||||
|
||||
Read a file and chat about it with the LLM.
|
||||
|
||||
## [Vector Index](https://github.com/run-llama/LlamaIndexTS/blob/main/apps/simple/vectorIndex.ts)
|
||||
|
||||
Create a vector index and query it. The vector index will use embeddings to fetch the top k most relevant nodes. By default, the top k is 2.
|
||||
|
||||
## [Summary Index](https://github.com/run-llama/LlamaIndexTS/blob/main/apps/simple/summaryIndex.ts)
|
||||
|
||||
Create a list index and query it. This example also use the `LLMRetriever`, which will use the LLM to select the best nodes to use when generating answer.
|
||||
|
||||
## [Save / Load an Index](https://github.com/run-llama/LlamaIndexTS/blob/main/apps/simple/storageContext.ts)
|
||||
|
||||
Create and load a vector index. Persistance to disk in LlamaIndex.TS happens automatically once a storage context object is created.
|
||||
|
||||
## [Customized Vector Index](https://github.com/run-llama/LlamaIndexTS/blob/main/apps/simple/vectorIndexCustomize.ts)
|
||||
|
||||
Create a vector index and query it, while also configuring the the `LLM`, the `ServiceContext`, and the `similarity_top_k`.
|
||||
|
||||
## [OpenAI LLM](https://github.com/run-llama/LlamaIndexTS/blob/main/apps/simple/openai.ts)
|
||||
|
||||
Create an OpenAI LLM and directly use it for chat.
|
||||
|
||||
## [Llama2 DeuceLLM](https://github.com/run-llama/LlamaIndexTS/blob/main/apps/simple/llamadeuce.ts)
|
||||
|
||||
Create a Llama-2 LLM and directly use it for chat.
|
||||
|
||||
## [SubQuestionQueryEngine](https://github.com/run-llama/LlamaIndexTS/blob/main/apps/simple/subquestion.ts)
|
||||
|
||||
Uses the `SubQuestionQueryEngine`, which breaks complex queries into multiple questions, and then aggreates a response across the answers to all sub-questions.
|
||||
|
||||
## [Low Level Modules](https://github.com/run-llama/LlamaIndexTS/blob/main/apps/simple/lowlevel.ts)
|
||||
|
||||
This example uses several low-level components, which removes the need for an actual query engine. These components can be used anywhere, in any application, or customized and sub-classed to meet your own needs.
|
||||
@@ -1,29 +0,0 @@
|
||||
---
|
||||
sidebar_position: 5
|
||||
---
|
||||
|
||||
# Environments
|
||||
|
||||
LlamaIndex currently officially supports NodeJS 18 and NodeJS 20.
|
||||
|
||||
## NextJS App Router
|
||||
|
||||
If you're using NextJS App Router route handlers/serverless functions, you'll need to use the NodeJS mode:
|
||||
|
||||
```js
|
||||
export const runtime = "nodejs"; // default
|
||||
```
|
||||
|
||||
and you'll need to add an exception for pdf-parse in your next.config.js
|
||||
|
||||
```js
|
||||
// next.config.js
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
experimental: {
|
||||
serverComponentsExternalPackages: ["pdf-parse"], // Puts pdf-parse in actual NodeJS mode with NextJS App Router
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = nextConfig;
|
||||
```
|
||||
@@ -0,0 +1,2 @@
|
||||
label: Examples
|
||||
position: 2
|
||||
@@ -0,0 +1,85 @@
|
||||
# Agents
|
||||
|
||||
A built-in agent that can take decisions and reasoning based on the tools provided to it.
|
||||
|
||||
## OpenAI Agent
|
||||
|
||||
```ts
|
||||
import { FunctionTool, OpenAIAgent } from "llamaindex";
|
||||
|
||||
// Define a function to sum two numbers
|
||||
function sumNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
// Define a function to divide two numbers
|
||||
function divideNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a / b;
|
||||
}
|
||||
|
||||
// Define the parameters of the sum function as a JSON schema
|
||||
const sumJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The first number",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The second number",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
// Define the parameters of the divide function as a JSON schema
|
||||
const divideJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The dividend to divide",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The divisor to divide by",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
async function main() {
|
||||
// Create a function tool from the sum function
|
||||
const sumFunctionTool = new FunctionTool(sumNumbers, {
|
||||
name: "sumNumbers",
|
||||
description: "Use this function to sum two numbers",
|
||||
parameters: sumJSON,
|
||||
});
|
||||
|
||||
// Create a function tool from the divide function
|
||||
const divideFunctionTool = new FunctionTool(divideNumbers, {
|
||||
name: "divideNumbers",
|
||||
description: "Use this function to divide two numbers"
|
||||
parameters: divideJSON,
|
||||
});
|
||||
|
||||
// Create an OpenAIAgent with the function tools
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [sumFunctionTool, divideFunctionTool],
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
// Chat with the agent
|
||||
const response = await agent.chat({
|
||||
message: "How much is 5 + 5? then divide by 2",
|
||||
});
|
||||
|
||||
// Print the response
|
||||
console.log(String(response));
|
||||
}
|
||||
|
||||
main().then(() => {
|
||||
console.log("Done");
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,12 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../examples/chatEngine";
|
||||
|
||||
# Chat Engine
|
||||
|
||||
Chat Engine is a class that allows you to create a chatbot from a retriever. It is a wrapper around a retriever that allows you to chat with it in a conversational manner.
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
sidebar_position: 5
|
||||
---
|
||||
|
||||
# More examples
|
||||
|
||||
You can check out more examples in the [examples](https://github.com/run-llama/LlamaIndexTS/tree/main/examples) folder of the repository.
|
||||
@@ -0,0 +1,10 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../examples/storageContext";
|
||||
|
||||
# Save/Load an Index
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
@@ -0,0 +1,10 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../examples/summaryIndex";
|
||||
|
||||
# Summary Index
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
@@ -0,0 +1,10 @@
|
||||
---
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../examples/vectorIndex";
|
||||
|
||||
# Vector Index
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
@@ -0,0 +1,2 @@
|
||||
label: Getting Started
|
||||
position: 1
|
||||
@@ -2,7 +2,7 @@
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
# High-Level Concepts
|
||||
# Concepts
|
||||
|
||||
LlamaIndex.TS helps you build LLM-powered applications (e.g. Q&A, chatbot) over custom data.
|
||||
|
||||
@@ -18,7 +18,7 @@ LlamaIndex uses a two stage method when using an LLM with your data:
|
||||
1. **indexing stage**: preparing a knowledge base, and
|
||||
2. **querying stage**: retrieving relevant context from the knowledge to assist the LLM in responding to a question
|
||||
|
||||

|
||||

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

|
||||

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

|
||||

|
||||
|
||||
#### Building Blocks
|
||||
|
||||
[**Retrievers**](./modules/low_level/retriever.md):
|
||||
[**Retrievers**](../modules/retriever.md):
|
||||
A retriever defines how to efficiently retrieve relevant context from a knowledge base (i.e. index) when given a query.
|
||||
The specific retrieval logic differs for difference indices, the most popular being dense retrieval against a vector index.
|
||||
|
||||
[**Response Synthesizers**](./modules/low_level/response_synthesizer.md):
|
||||
[**Response Synthesizers**](../modules/response_synthesizer.md):
|
||||
A response synthesizer generates a response from an LLM, using a user query and a given set of retrieved text chunks.
|
||||
|
||||
#### Pipelines
|
||||
|
||||
[**Query Engines**](./modules/high_level/query_engine.md):
|
||||
[**Query Engines**](../modules/query_engines):
|
||||
A query engine is an end-to-end pipeline that allow you to ask question over your data.
|
||||
It takes in a natural language query, and returns a response, along with reference context retrieved and passed to the LLM.
|
||||
|
||||
[**Chat Engines**](./modules/high_level/chat_engine.md):
|
||||
[**Chat Engines**](../modules/chat_engine.md):
|
||||
A chat engine is an end-to-end pipeline for having a conversation with your data
|
||||
(multiple back-and-forth instead of a single question & answer).
|
||||
@@ -0,0 +1,15 @@
|
||||
---
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
# Environments
|
||||
|
||||
LlamaIndex currently officially supports NodeJS 18 and NodeJS 20.
|
||||
|
||||
## NextJS App Router
|
||||
|
||||
If you're using NextJS App Router route handlers/serverless functions, you'll need to use the NodeJS mode:
|
||||
|
||||
```js
|
||||
export const runtime = "nodejs"; // default
|
||||
```
|
||||
@@ -0,0 +1,63 @@
|
||||
---
|
||||
sidebar_position: 0
|
||||
---
|
||||
|
||||
# Installation and Setup
|
||||
|
||||
Make sure you have NodeJS v18 or higher.
|
||||
|
||||
## Using create-llama
|
||||
|
||||
The easiest way to get started with LlamaIndex is by using `create-llama`. This CLI tool enables you to quickly start building a new LlamaIndex application, with everything set up for you.
|
||||
|
||||
Just run
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="1" label="npm" default>
|
||||
|
||||
```bash
|
||||
npx create-llama@latest
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="2" label="Yarn">
|
||||
|
||||
```bash
|
||||
yarn create llama
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="3" label="pnpm">
|
||||
|
||||
```bash
|
||||
pnpm create llama@latest
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
to get started. Once your app is generated, run
|
||||
|
||||
```bash npm2yarn
|
||||
npm run dev
|
||||
```
|
||||
|
||||
to start the development server. You can then visit [http://localhost:3000](http://localhost:3000) to see your app
|
||||
|
||||
## Installation from NPM
|
||||
|
||||
```bash npm2yarn
|
||||
npm install llamaindex
|
||||
```
|
||||
|
||||
### Environment variables
|
||||
|
||||
Our examples use OpenAI by default. You'll need to set up your Open AI key like so:
|
||||
|
||||
```bash
|
||||
export OPENAI_API_KEY="sk-......" # Replace with your key from https://platform.openai.com/account/api-keys
|
||||
```
|
||||
|
||||
If you want to have it automatically loaded every time, add it to your `.zshrc/.bashrc`.
|
||||
|
||||
WARNING: do not check in your OpenAI key into version control.
|
||||
@@ -1,10 +1,10 @@
|
||||
---
|
||||
sidebar_position: 2
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# Starter Tutorial
|
||||
|
||||
Once you have [installed LlamaIndex.TS using NPM](installation.md) and set up your OpenAI key, you're ready to start your first app:
|
||||
Once you have [installed LlamaIndex.TS using NPM](installation) and set up your OpenAI key, you're ready to start your first app:
|
||||
|
||||
In a new folder:
|
||||
|
||||
@@ -36,9 +36,9 @@ async function main() {
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine();
|
||||
const response = await queryEngine.query(
|
||||
"What did the author do in college?",
|
||||
);
|
||||
const response = await queryEngine.query({
|
||||
query: "What did the author do in college?",
|
||||
});
|
||||
|
||||
// Output response
|
||||
console.log(response.toString());
|
||||
@@ -1,25 +0,0 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# Installation and Setup
|
||||
|
||||
## Installation from NPM
|
||||
|
||||
Make sure you have NodeJS v18 or higher.
|
||||
|
||||
```bash npm2yarn
|
||||
npm install llamaindex
|
||||
```
|
||||
|
||||
## Environment variables
|
||||
|
||||
Our examples use OpenAI by default. You'll need to set up your Open AI key like so:
|
||||
|
||||
```bash
|
||||
export OPENAI_API_KEY="sk-......" # Replace with your key from https://platform.openai.com/account/api-keys
|
||||
```
|
||||
|
||||
If you want to have it automatically loaded every time, add it to your .zshrc/.bashrc.
|
||||
|
||||
WARNING: do not check in your OpenAI key into version control.
|
||||
@@ -5,7 +5,7 @@ slug: /
|
||||
|
||||
# What is LlamaIndex.TS?
|
||||
|
||||
LlamaIndex.TS is a data framework for LLM applications to ingest, structure, and access private or domain-specific data. While a python package is also available (see [here](https://gpt-index.readthedocs.io/en/latest/)), LlamaIndex.TS offers core features in a simple package, optimized for usage with TypeScript.
|
||||
LlamaIndex.TS is a data framework for LLM applications to ingest, structure, and access private or domain-specific data. While a python package is also available (see [here](https://docs.llamaindex.ai/en/stable/)), LlamaIndex.TS offers core features in a simple package, optimized for usage with TypeScript.
|
||||
|
||||
## 🚀 Why LlamaIndex.TS?
|
||||
|
||||
@@ -37,9 +37,9 @@ For more complex applications, our lower-level APIs allow advanced users to cust
|
||||
|
||||
`npm install llamaindex`
|
||||
|
||||
Our documentation includes [Installation Instructions](./installation.md) and a [Starter Tutorial](./starter.md) to build your first application.
|
||||
Our documentation includes [Installation Instructions](./getting_started/installation.mdx) and a [Starter Tutorial](./getting_started/starter.md) to build your first application.
|
||||
|
||||
Once you're up and running, [High-Level Concepts](./concepts.md) has an overview of LlamaIndex's modular architecture. For more hands-on practical examples, look through our [End-to-End Tutorials](./end_to_end.md).
|
||||
Once you're up and running, [High-Level Concepts](./getting_started/concepts.md) has an overview of LlamaIndex's modular architecture. For more hands-on practical examples, look through our Examples section on the sidebar.
|
||||
|
||||
## 🗺️ Ecosystem
|
||||
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "Agents"
|
||||
position: 3
|
||||
@@ -0,0 +1,14 @@
|
||||
# Agents
|
||||
|
||||
An “agent” is an automated reasoning and decision engine. It takes in a user input/query and can make internal decisions for executing that query in order to return the correct result. The key agent components can include, but are not limited to:
|
||||
|
||||
- Breaking down a complex question into smaller ones
|
||||
- Choosing an external Tool to use + coming up with parameters for calling the Tool
|
||||
- Planning out a set of tasks
|
||||
- Storing previously completed tasks in a memory module
|
||||
|
||||
## Getting Started
|
||||
|
||||
LlamaIndex.TS comes with a few built-in agents, but you can also create your own. The built-in agents include:
|
||||
|
||||
- [OpenAI Agent](./openai.mdx)
|
||||
@@ -0,0 +1,314 @@
|
||||
# Multi-Document Agent
|
||||
|
||||
In this guide, you learn towards setting up an agent that can effectively answer different types of questions over a larger set of documents.
|
||||
|
||||
These questions include the following
|
||||
|
||||
- QA over a specific doc
|
||||
- QA comparing different docs
|
||||
- Summaries over a specific doc
|
||||
- Comparing summaries between different docs
|
||||
|
||||
We do this with the following architecture:
|
||||
|
||||
- setup a “document agent” over each Document: each doc agent can do QA/summarization within its doc
|
||||
- setup a top-level agent over this set of document agents. Do tool retrieval and then do CoT over the set of tools to answer a question.
|
||||
|
||||
## Setup and Download Data
|
||||
|
||||
We first start by installing the necessary libraries and downloading the data.
|
||||
|
||||
```bash
|
||||
pnpm i llamaindex
|
||||
```
|
||||
|
||||
```ts
|
||||
import {
|
||||
Document,
|
||||
ObjectIndex,
|
||||
OpenAI,
|
||||
OpenAIAgent,
|
||||
QueryEngineTool,
|
||||
SimpleNodeParser,
|
||||
SimpleToolNodeMapping,
|
||||
SummaryIndex,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
storageContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
```
|
||||
|
||||
And then for the data we will run through a list of countries and download the wikipedia page for each country.
|
||||
|
||||
```ts
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
const dataPath = path.join(__dirname, "tmp_data");
|
||||
|
||||
const extractWikipediaTitle = async (title: string) => {
|
||||
const fileExists = fs.existsSync(path.join(dataPath, `${title}.txt`));
|
||||
|
||||
if (fileExists) {
|
||||
console.log(`File already exists for the title: ${title}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const queryParams = new URLSearchParams({
|
||||
action: "query",
|
||||
format: "json",
|
||||
titles: title,
|
||||
prop: "extracts",
|
||||
explaintext: "true",
|
||||
});
|
||||
|
||||
const url = `https://en.wikipedia.org/w/api.php?${queryParams}`;
|
||||
|
||||
const response = await fetch(url);
|
||||
const data: any = await response.json();
|
||||
|
||||
const pages = data.query.pages;
|
||||
const page = pages[Object.keys(pages)[0]];
|
||||
const wikiText = page.extract;
|
||||
|
||||
await new Promise((resolve) => {
|
||||
fs.writeFile(path.join(dataPath, `${title}.txt`), wikiText, (err: any) => {
|
||||
if (err) {
|
||||
console.error(err);
|
||||
resolve(title);
|
||||
return;
|
||||
}
|
||||
console.log(`${title} stored in file!`);
|
||||
|
||||
resolve(title);
|
||||
});
|
||||
});
|
||||
};
|
||||
```
|
||||
|
||||
```ts
|
||||
export const extractWikipedia = async (titles: string[]) => {
|
||||
if (!fs.existsSync(dataPath)) {
|
||||
fs.mkdirSync(dataPath);
|
||||
}
|
||||
|
||||
for await (const title of titles) {
|
||||
await extractWikipediaTitle(title);
|
||||
}
|
||||
|
||||
console.log("Extration finished!");
|
||||
```
|
||||
|
||||
These files will be saved in the `tmp_data` folder.
|
||||
|
||||
Now we can call the function to download the data for each country.
|
||||
|
||||
```ts
|
||||
await extractWikipedia([
|
||||
"Brazil",
|
||||
"United States",
|
||||
"Canada",
|
||||
"Mexico",
|
||||
"Argentina",
|
||||
"Chile",
|
||||
"Colombia",
|
||||
"Peru",
|
||||
"Venezuela",
|
||||
"Ecuador",
|
||||
"Bolivia",
|
||||
"Paraguay",
|
||||
"Uruguay",
|
||||
"Guyana",
|
||||
"Suriname",
|
||||
"French Guiana",
|
||||
"Falkland Islands",
|
||||
]);
|
||||
```
|
||||
|
||||
## Load the data
|
||||
|
||||
Now that we have the data, we can load it into the LlamaIndex and store as a document.
|
||||
|
||||
```ts
|
||||
import { Document } from "llamaindex";
|
||||
|
||||
const countryDocs: Record<string, Document> = {};
|
||||
|
||||
for (const title of wikiTitles) {
|
||||
const path = `./agent/helpers/tmp_data/${title}.txt`;
|
||||
const text = await fs.readFile(path, "utf-8");
|
||||
const document = new Document({ text: text, id_: path });
|
||||
countryDocs[title] = document;
|
||||
}
|
||||
```
|
||||
|
||||
## Setup LLM and StorageContext
|
||||
|
||||
We will be using gpt-4 for this example and we will use the `StorageContext` to store the documents in-memory.
|
||||
|
||||
```ts
|
||||
const llm = new OpenAI({
|
||||
model: "gpt-4",
|
||||
});
|
||||
|
||||
const ctx = serviceContextFromDefaults({ llm });
|
||||
|
||||
const storageContext = await storageContextFromDefaults({
|
||||
persistDir: "./storage",
|
||||
});
|
||||
```
|
||||
|
||||
## Building Multi-Document Agents
|
||||
|
||||
In this section we show you how to construct the multi-document agent. We first build a document agent for each document, and then define the top-level parent agent with an object index.
|
||||
|
||||
```ts
|
||||
const documentAgents: Record<string, any> = {};
|
||||
const queryEngines: Record<string, any> = {};
|
||||
```
|
||||
|
||||
Now we iterate over each country and create a document agent for each one.
|
||||
|
||||
### Build Agent for each Document
|
||||
|
||||
In this section we define “document agents” for each document.
|
||||
|
||||
We define both a vector index (for semantic search) and summary index (for summarization) for each document. The two query engines are then converted into tools that are passed to an OpenAI function calling agent.
|
||||
|
||||
This document agent can dynamically choose to perform semantic search or summarization within a given document.
|
||||
|
||||
We create a separate document agent for each coutnry.
|
||||
|
||||
```ts
|
||||
for (const title of wikiTitles) {
|
||||
// parse the document into nodes
|
||||
const nodes = new SimpleNodeParser({
|
||||
chunkSize: 200,
|
||||
chunkOverlap: 20,
|
||||
}).getNodesFromDocuments([countryDocs[title]]);
|
||||
|
||||
// create the vector index for specific search
|
||||
const vectorIndex = await VectorStoreIndex.init({
|
||||
serviceContext: serviceContext,
|
||||
storageContext: storageContext,
|
||||
nodes,
|
||||
});
|
||||
|
||||
// create the summary index for broader search
|
||||
const summaryIndex = await SummaryIndex.init({
|
||||
serviceContext: serviceContext,
|
||||
nodes,
|
||||
});
|
||||
|
||||
const vectorQueryEngine = summaryIndex.asQueryEngine();
|
||||
const summaryQueryEngine = summaryIndex.asQueryEngine();
|
||||
|
||||
// create the query engines for each task
|
||||
const queryEngineTools = [
|
||||
new QueryEngineTool({
|
||||
queryEngine: vectorQueryEngine,
|
||||
metadata: {
|
||||
name: "vector_tool",
|
||||
description: `Useful for questions related to specific aspects of ${title} (e.g. the history, arts and culture, sports, demographics, or more).`,
|
||||
},
|
||||
}),
|
||||
new QueryEngineTool({
|
||||
queryEngine: summaryQueryEngine,
|
||||
metadata: {
|
||||
name: "summary_tool",
|
||||
description: `Useful for any requests that require a holistic summary of EVERYTHING about ${title}. For questions about more specific sections, please use the vector_tool.`,
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
// create the document agent
|
||||
const agent = new OpenAIAgent({
|
||||
tools: queryEngineTools,
|
||||
llm,
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
documentAgents[title] = agent;
|
||||
queryEngines[title] = vectorIndex.asQueryEngine();
|
||||
}
|
||||
```
|
||||
|
||||
## Build Top-Level Agent
|
||||
|
||||
Now we define the top-level agent that can answer questions over the set of document agents.
|
||||
|
||||
This agent takes in all document agents as tools. This specific agent RetrieverOpenAIAgent performs tool retrieval before tool use (unlike a default agent that tries to put all tools in the prompt).
|
||||
|
||||
Here we use a top-k retriever, but we encourage you to customize the tool retriever method!
|
||||
|
||||
Firstly, we create a tool for each document agent
|
||||
|
||||
```ts
|
||||
const allTools: QueryEngineTool[] = [];
|
||||
```
|
||||
|
||||
```ts
|
||||
for (const title of wikiTitles) {
|
||||
const wikiSummary = `
|
||||
This content contains Wikipedia articles about ${title}.
|
||||
Use this tool if you want to answer any questions about ${title}
|
||||
`;
|
||||
|
||||
const docTool = new QueryEngineTool({
|
||||
queryEngine: documentAgents[title],
|
||||
metadata: {
|
||||
name: `tool_${title}`,
|
||||
description: wikiSummary,
|
||||
},
|
||||
});
|
||||
|
||||
allTools.push(docTool);
|
||||
}
|
||||
```
|
||||
|
||||
Our top level agent will use this document agents as tools and use toolRetriever to retrieve the best tool to answer a question.
|
||||
|
||||
```ts
|
||||
// map the tools to nodes
|
||||
const toolMapping = SimpleToolNodeMapping.fromObjects(allTools);
|
||||
|
||||
// create the object index
|
||||
const objectIndex = await ObjectIndex.fromObjects(
|
||||
allTools,
|
||||
toolMapping,
|
||||
VectorStoreIndex,
|
||||
{
|
||||
serviceContext,
|
||||
storageContext,
|
||||
},
|
||||
);
|
||||
|
||||
// create the top agent
|
||||
const topAgent = new OpenAIAgent({
|
||||
toolRetriever: await objectIndex.asRetriever({}),
|
||||
llm,
|
||||
verbose: true,
|
||||
prefixMessages: [
|
||||
{
|
||||
content:
|
||||
"You are an agent designed to answer queries about a set of given countries. Please always use the tools provided to answer a question. Do not rely on prior knowledge.",
|
||||
role: "system",
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Use the Agent
|
||||
|
||||
Now we can use the agent to answer questions.
|
||||
|
||||
```ts
|
||||
const response = await topAgent.chat({
|
||||
message: "Tell me the differences between Brazil and Canada economics?",
|
||||
});
|
||||
|
||||
// print output
|
||||
console.log(response);
|
||||
```
|
||||
|
||||
You can find the full code for this example [here](https://github.com/run-llama/LlamaIndexTS/tree/main/examples/agent/multi-document-agent.ts)
|
||||
@@ -0,0 +1,187 @@
|
||||
---
|
||||
sidebar_position: 0
|
||||
---
|
||||
|
||||
# OpenAI Agent
|
||||
|
||||
OpenAI API that supports function calling, it’s never been easier to build your own agent!
|
||||
|
||||
In this notebook tutorial, we showcase how to write your own OpenAI agent
|
||||
|
||||
## Setup
|
||||
|
||||
First, you need to install the `llamaindex` package. You can do this by running the following command in your terminal:
|
||||
|
||||
```bash
|
||||
pnpm i llamaindex
|
||||
```
|
||||
|
||||
Then we can define a function to sum two numbers and another function to divide two numbers.
|
||||
|
||||
```ts
|
||||
function sumNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
// Define a function to divide two numbers
|
||||
function divideNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a / b;
|
||||
}
|
||||
```
|
||||
|
||||
## Create a function tool
|
||||
|
||||
Now we can create a function tool from the sum function and another function tool from the divide function.
|
||||
|
||||
For the parameters of the sum function, we can define a JSON schema.
|
||||
|
||||
### JSON Schema
|
||||
|
||||
```ts
|
||||
const sumJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The first number",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The second number",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
const divideJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The dividend a to divide",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The divisor b to divide by",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
const sumFunctionTool = new FunctionTool(sumNumbers, {
|
||||
name: "sumNumbers",
|
||||
description: "Use this function to sum two numbers",
|
||||
parameters: sumJSON,
|
||||
});
|
||||
|
||||
const divideFunctionTool = new FunctionTool(divideNumbers, {
|
||||
name: "divideNumbers",
|
||||
description: "Use this function to divide two numbers",
|
||||
parameters: divideJSON,
|
||||
});
|
||||
```
|
||||
|
||||
## Create an OpenAIAgent
|
||||
|
||||
Now we can create an OpenAIAgent with the function tools.
|
||||
|
||||
```ts
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [sumFunctionTool, divideFunctionTool],
|
||||
verbose: true,
|
||||
});
|
||||
```
|
||||
|
||||
## Chat with the agent
|
||||
|
||||
Now we can chat with the agent.
|
||||
|
||||
```ts
|
||||
const response = await agent.chat({
|
||||
message: "How much is 5 + 5? then divide by 2",
|
||||
});
|
||||
|
||||
console.log(String(response));
|
||||
```
|
||||
|
||||
## Full code
|
||||
|
||||
```ts
|
||||
import { FunctionTool, OpenAIAgent } from "llamaindex";
|
||||
|
||||
// Define a function to sum two numbers
|
||||
function sumNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
// Define a function to divide two numbers
|
||||
function divideNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a / b;
|
||||
}
|
||||
|
||||
// Define the parameters of the sum function as a JSON schema
|
||||
const sumJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The first number",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The second number",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
// Define the parameters of the divide function as a JSON schema
|
||||
const divideJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The argument a to divide",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The argument b to divide",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
async function main() {
|
||||
// Create a function tool from the sum function
|
||||
const sumFunctionTool = new FunctionTool(sumNumbers, {
|
||||
name: "sumNumbers",
|
||||
description: "Use this function to sum two numbers",
|
||||
parameters: sumJSON,
|
||||
});
|
||||
|
||||
// Create a function tool from the divide function
|
||||
const divideFunctionTool = new FunctionTool(divideNumbers, {
|
||||
name: "divideNumbers",
|
||||
description: "Use this function to divide two numbers",
|
||||
parameters: divideJSON,
|
||||
});
|
||||
|
||||
// Create an OpenAIAgent with the function tools
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [sumFunctionTool, divideFunctionTool],
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
// Chat with the agent
|
||||
const response = await agent.chat({
|
||||
message: "How much is 5 + 5? then divide by 2",
|
||||
});
|
||||
|
||||
// Print the response
|
||||
console.log(String(response));
|
||||
}
|
||||
|
||||
main().then(() => {
|
||||
console.log("Done");
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,132 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# OpenAI Agent + QueryEngineTool
|
||||
|
||||
QueryEngineTool is a tool that allows you to query a vector index. In this example, we will create a vector index from a set of documents and then create a QueryEngineTool from the vector index. We will then create an OpenAIAgent with the QueryEngineTool and chat with the agent.
|
||||
|
||||
## Setup
|
||||
|
||||
First, you need to install the `llamaindex` package. You can do this by running the following command in your terminal:
|
||||
|
||||
```bash
|
||||
pnpm i llamaindex
|
||||
```
|
||||
|
||||
Then you can import the necessary classes and functions.
|
||||
|
||||
```ts
|
||||
import {
|
||||
OpenAIAgent,
|
||||
SimpleDirectoryReader,
|
||||
VectorStoreIndex,
|
||||
QueryEngineTool,
|
||||
} from "llamaindex";
|
||||
```
|
||||
|
||||
## Create a vector index
|
||||
|
||||
Now we can create a vector index from a set of documents.
|
||||
|
||||
```ts
|
||||
// Load the documents
|
||||
const documents = await new SimpleDirectoryReader().loadData({
|
||||
directoryPath: "node_modules/llamaindex/examples/",
|
||||
});
|
||||
|
||||
// Create a vector index from the documents
|
||||
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
|
||||
```
|
||||
|
||||
## Create a QueryEngineTool
|
||||
|
||||
Now we can create a QueryEngineTool from the vector index.
|
||||
|
||||
```ts
|
||||
// Create a query engine from the vector index
|
||||
const abramovQueryEngine = vectorIndex.asQueryEngine();
|
||||
|
||||
// Create a QueryEngineTool with the query engine
|
||||
const queryEngineTool = new QueryEngineTool({
|
||||
queryEngine: abramovQueryEngine,
|
||||
metadata: {
|
||||
name: "abramov_query_engine",
|
||||
description: "A query engine for the Abramov documents",
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
## Create an OpenAIAgent
|
||||
|
||||
```ts
|
||||
// Create an OpenAIAgent with the query engine tool tools
|
||||
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [queryEngineTool],
|
||||
verbose: true,
|
||||
});
|
||||
```
|
||||
|
||||
## Chat with the agent
|
||||
|
||||
Now we can chat with the agent.
|
||||
|
||||
```ts
|
||||
const response = await agent.chat({
|
||||
message: "What was his salary?",
|
||||
});
|
||||
|
||||
console.log(String(response));
|
||||
```
|
||||
|
||||
## Full code
|
||||
|
||||
```ts
|
||||
import {
|
||||
OpenAIAgent,
|
||||
SimpleDirectoryReader,
|
||||
VectorStoreIndex,
|
||||
QueryEngineTool,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Load the documents
|
||||
const documents = await new SimpleDirectoryReader().loadData({
|
||||
directoryPath: "node_modules/llamaindex/examples/",
|
||||
});
|
||||
|
||||
// Create a vector index from the documents
|
||||
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
|
||||
|
||||
// Create a query engine from the vector index
|
||||
const abramovQueryEngine = vectorIndex.asQueryEngine();
|
||||
|
||||
// Create a QueryEngineTool with the query engine
|
||||
const queryEngineTool = new QueryEngineTool({
|
||||
queryEngine: abramovQueryEngine,
|
||||
metadata: {
|
||||
name: "abramov_query_engine",
|
||||
description: "A query engine for the Abramov documents",
|
||||
},
|
||||
});
|
||||
|
||||
// Create an OpenAIAgent with the function tools
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [queryEngineTool],
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
// Chat with the agent
|
||||
const response = await agent.chat({
|
||||
message: "What was his salary?",
|
||||
});
|
||||
|
||||
// Print the response
|
||||
console.log(String(response));
|
||||
}
|
||||
|
||||
main().then(() => {
|
||||
console.log("Done");
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,203 @@
|
||||
# ReAct Agent
|
||||
|
||||
The ReAct agent is an AI agent that can reason over the next action, construct an action command, execute the action, and repeat these steps in an iterative loop until the task is complete.
|
||||
|
||||
In this notebook tutorial, we showcase how to write your ReAct agent using the `llamaindex` package.
|
||||
|
||||
## Setup
|
||||
|
||||
First, you need to install the `llamaindex` package. You can do this by running the following command in your terminal:
|
||||
|
||||
```bash
|
||||
pnpm i llamaindex
|
||||
```
|
||||
|
||||
And then you can import the `OpenAIAgent` and `FunctionTool` from the `llamaindex` package.
|
||||
|
||||
```ts
|
||||
import { FunctionTool, OpenAIAgent } from "llamaindex";
|
||||
```
|
||||
|
||||
Then we can define a function to sum two numbers and another function to divide two numbers.
|
||||
|
||||
```ts
|
||||
function sumNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
// Define a function to divide two numbers
|
||||
function divideNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a / b;
|
||||
}
|
||||
```
|
||||
|
||||
## Create a function tool
|
||||
|
||||
Now we can create a function tool from the sum function and another function tool from the divide function.
|
||||
|
||||
For the parameters of the sum function, we can define a JSON schema.
|
||||
|
||||
### JSON Schema
|
||||
|
||||
```ts
|
||||
const sumJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The first number",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The second number",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
const divideJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The dividend a to divide",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The divisor b to divide by",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
const sumFunctionTool = new FunctionTool(sumNumbers, {
|
||||
name: "sumNumbers",
|
||||
description: "Use this function to sum two numbers",
|
||||
parameters: sumJSON,
|
||||
});
|
||||
|
||||
const divideFunctionTool = new FunctionTool(divideNumbers, {
|
||||
name: "divideNumbers",
|
||||
description: "Use this function to divide two numbers",
|
||||
parameters: divideJSON,
|
||||
});
|
||||
```
|
||||
|
||||
## Create an ReAct
|
||||
|
||||
Now we can create an OpenAIAgent with the function tools.
|
||||
|
||||
```ts
|
||||
const agent = new ReActAgent({
|
||||
tools: [sumFunctionTool, divideFunctionTool],
|
||||
verbose: true,
|
||||
});
|
||||
```
|
||||
|
||||
## Chat with the agent
|
||||
|
||||
Now we can chat with the agent.
|
||||
|
||||
```ts
|
||||
const response = await agent.chat({
|
||||
message: "How much is 5 + 5? then divide by 2",
|
||||
});
|
||||
|
||||
console.log(String(response));
|
||||
```
|
||||
|
||||
The output will be:
|
||||
|
||||
```bash
|
||||
Thought: I need to use a tool to help me answer the question.
|
||||
Action: sumNumbers
|
||||
Action Input: {"a":5,"b":5}
|
||||
|
||||
Observation: 10
|
||||
Thought: I can answer without using any more tools.
|
||||
Answer: The sum of 5 and 5 is 10, and when divided by 2, the result is 5.
|
||||
|
||||
The sum of 5 and 5 is 10, and when divided by 2, the result is 5.
|
||||
```
|
||||
|
||||
## Full code
|
||||
|
||||
```ts
|
||||
import { FunctionTool, ReActAgent } from "llamaindex";
|
||||
|
||||
// Define a function to sum two numbers
|
||||
function sumNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
// Define a function to divide two numbers
|
||||
function divideNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a / b;
|
||||
}
|
||||
|
||||
// Define the parameters of the sum function as a JSON schema
|
||||
const sumJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The first number",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The second number",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
// Define the parameters of the divide function as a JSON schema
|
||||
const divideJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The argument a to divide",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The argument b to divide",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
async function main() {
|
||||
// Create a function tool from the sum function
|
||||
const sumFunctionTool = new FunctionTool(sumNumbers, {
|
||||
name: "sumNumbers",
|
||||
description: "Use this function to sum two numbers",
|
||||
parameters: sumJSON,
|
||||
});
|
||||
|
||||
// Create a function tool from the divide function
|
||||
const divideFunctionTool = new FunctionTool(divideNumbers, {
|
||||
name: "divideNumbers",
|
||||
description: "Use this function to divide two numbers",
|
||||
parameters: divideJSON,
|
||||
});
|
||||
|
||||
// Create an OpenAIAgent with the function tools
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [sumFunctionTool, divideFunctionTool],
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
// Chat with the agent
|
||||
const response = await agent.chat({
|
||||
message: "I want to sum 5 and 5 and then divide by 2",
|
||||
});
|
||||
|
||||
// Print the response
|
||||
console.log(String(response));
|
||||
}
|
||||
|
||||
main().then(() => {
|
||||
console.log("Done");
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,29 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
# ChatEngine
|
||||
|
||||
The chat engine is a quick and simple way to chat with the data in your index.
|
||||
|
||||
```typescript
|
||||
const retriever = index.asRetriever();
|
||||
const chatEngine = new ContextChatEngine({ retriever });
|
||||
|
||||
// start chatting
|
||||
const response = await chatEngine.chat({ message: query });
|
||||
```
|
||||
|
||||
The `chat` function also supports streaming, just add `stream: true` as an option:
|
||||
|
||||
```typescript
|
||||
const stream = await chatEngine.chat({ message: query, stream: true });
|
||||
for await (const chunk of stream) {
|
||||
process.stdout.write(chunk.response);
|
||||
}
|
||||
```
|
||||
|
||||
## Api References
|
||||
|
||||
- [ContextChatEngine](../api/classes/ContextChatEngine.md)
|
||||
- [CondenseQuestionChatEngine](../api/classes/ContextChatEngine.md)
|
||||
+3
-3
@@ -1,5 +1,5 @@
|
||||
---
|
||||
sidebar_position: 2
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
# Index
|
||||
@@ -19,5 +19,5 @@ const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
## API Reference
|
||||
|
||||
- [SummaryIndex](../../api/classes/SummaryIndex.md)
|
||||
- [VectorStoreIndex](../../api/classes/VectorStoreIndex.md)
|
||||
- [SummaryIndex](../api/classes/SummaryIndex.md)
|
||||
- [VectorStoreIndex](../api/classes/VectorStoreIndex.md)
|
||||
@@ -0,0 +1,48 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../examples/readers/src/simple-directory-reader";
|
||||
import CodeSource2 from "!raw-loader!../../../../examples/readers/src/custom-simple-directory-reader";
|
||||
import CodeSource3 from "!raw-loader!../../../../examples/readers/src/llamaparse";
|
||||
|
||||
# Loader
|
||||
|
||||
Before you can start indexing your documents, you need to load them into memory.
|
||||
|
||||
### SimpleDirectoryReader
|
||||
|
||||
[](https://stackblitz.com/github/run-llama/LlamaIndexTS/tree/main/examples/readers?file=src/simple-directory-reader.ts&title=Simple%20Directory%20Reader)
|
||||
|
||||
LlamaIndex.TS supports easy loading of files from folders using the `SimpleDirectoryReader` class.
|
||||
|
||||
It is a simple reader that reads all files from a directory and its subdirectories.
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
|
||||
Currently, it supports reading `.csv`, `.docx`, `.html`, `.md` and `.pdf` files,
|
||||
but support for other file types is planned.
|
||||
|
||||
Also, you can provide a `defaultReader` as a fallback for files with unsupported extensions.
|
||||
Or pass new readers for `fileExtToReader` to support more file types.
|
||||
|
||||
<CodeBlock language="ts" showLineNumbers metastring="{8-12,17-21}">
|
||||
{CodeSource2}
|
||||
</CodeBlock>
|
||||
|
||||
### LlamaParse
|
||||
|
||||
LlamaParse is an API created by LlamaIndex to efficiently parse files, e.g. it's great at converting PDF tables into markdown.
|
||||
|
||||
To use it, first login and get an API key from https://cloud.llamaindex.ai. Make sure to store the key in the environment variable `LLAMA_CLOUD_API_KEY`.
|
||||
|
||||
Then, you can use the `LlamaParseReader` class to read a local PDF file and convert it into a markdown document that can be used by LlamaIndex:
|
||||
|
||||
<CodeBlock language="ts">{CodeSource3}</CodeBlock>
|
||||
|
||||
Alternatively, you can set the [`resultType`](../api/classes/LlamaParseReader.md#resulttype) option to `text` to get the parsed document as a text string.
|
||||
|
||||
## API Reference
|
||||
|
||||
- [SimpleDirectoryReader](../api/classes/SimpleDirectoryReader.md)
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "Document / Nodes"
|
||||
position: 0
|
||||
+3
-3
@@ -1,5 +1,5 @@
|
||||
---
|
||||
sidebar_position: 0
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# Documents and Nodes
|
||||
@@ -14,5 +14,5 @@ document = new Document({ text: "text", metadata: { key: "val" } });
|
||||
|
||||
## API Reference
|
||||
|
||||
- [Document](../../api/classes/Document.md)
|
||||
- [TextNode](../../api/classes/TextNode.md)
|
||||
- [Document](../api/classes/Document.md)
|
||||
- [TextNode](../api/classes/TextNode.md)
|
||||
@@ -0,0 +1,45 @@
|
||||
# Metadata Extraction Usage Pattern
|
||||
|
||||
You can use LLMs to automate metadata extraction with our `Metadata Extractor` modules.
|
||||
|
||||
Our metadata extractor modules include the following "feature extractors":
|
||||
|
||||
- `SummaryExtractor` - automatically extracts a summary over a set of Nodes
|
||||
- `QuestionsAnsweredExtractor` - extracts a set of questions that each Node can answer
|
||||
- `TitleExtractor` - extracts a title over the context of each Node by document and combine them
|
||||
- `KeywordExtractor` - extracts keywords over the context of each Node
|
||||
|
||||
Then you can chain the `Metadata Extractors` with the `IngestionPipeline` to extract metadata from a set of documents.
|
||||
|
||||
```ts
|
||||
import {
|
||||
IngestionPipeline,
|
||||
TitleExtractor,
|
||||
QuestionsAnsweredExtractor,
|
||||
Document,
|
||||
OpenAI,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
const pipeline = new IngestionPipeline({
|
||||
transformations: [
|
||||
new TitleExtractor(),
|
||||
new QuestionsAnsweredExtractor({
|
||||
questions: 5,
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const nodes = await pipeline.run({
|
||||
documents: [
|
||||
new Document({ text: "I am 10 years old. John is 20 years old." }),
|
||||
],
|
||||
});
|
||||
|
||||
for (const node of nodes) {
|
||||
console.log(node.metadata);
|
||||
}
|
||||
}
|
||||
|
||||
main().then(() => console.log("done"));
|
||||
```
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "Embeddings"
|
||||
position: 3
|
||||
@@ -0,0 +1 @@
|
||||
label: "Available Embeddings"
|
||||
@@ -0,0 +1,25 @@
|
||||
# HuggingFace
|
||||
|
||||
To use HuggingFace embeddings, you need to import `HuggingFaceEmbedding` from `llamaindex`.
|
||||
|
||||
```ts
|
||||
import { HuggingFaceEmbedding, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const huggingFaceEmbeds = new HuggingFaceEmbedding();
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ embedModel: openaiEmbeds });
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,29 @@
|
||||
# MistralAI
|
||||
|
||||
To use MistralAI embeddings, you need to import `MistralAIEmbedding` from `llamaindex`.
|
||||
|
||||
```ts
|
||||
import { MistralAIEmbedding, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const mistralEmbedModel = new MistralAIEmbedding({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
embedModel: mistralEmbedModel,
|
||||
});
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,27 @@
|
||||
# Ollama
|
||||
|
||||
To use Ollama embeddings, you need to import `Ollama` from `llamaindex`.
|
||||
|
||||
```ts
|
||||
import { Ollama, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const ollamaEmbedModel = new Ollama();
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
embedModel: ollamaEmbedModel,
|
||||
});
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,27 @@
|
||||
# OpenAI
|
||||
|
||||
To use OpenAI embeddings, you need to import `OpenAIEmbedding` from `llamaindex`.
|
||||
|
||||
```ts
|
||||
import { OpenAIEmbedding, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const openaiEmbedModel = new OpenAIEmbedding();
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
embedModel: openaiEmbedModel,
|
||||
});
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,29 @@
|
||||
# Together
|
||||
|
||||
To use together embeddings, you need to import `TogetherEmbedding` from `llamaindex`.
|
||||
|
||||
```ts
|
||||
import { TogetherEmbedding, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const togetherEmbedModel = new TogetherEmbedding({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
embedModel: togetherEmbedModel,
|
||||
});
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
+5
-5
@@ -1,7 +1,3 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# Embedding
|
||||
|
||||
The embedding model in LlamaIndex is responsible for creating numerical representations of text. By default, LlamaIndex will use the `text-embedding-ada-002` model from OpenAI.
|
||||
@@ -16,7 +12,11 @@ const openaiEmbeds = new OpenAIEmbedding();
|
||||
const serviceContext = serviceContextFromDefaults({ embedModel: openaiEmbeds });
|
||||
```
|
||||
|
||||
## Local Embedding
|
||||
|
||||
For local embeddings, you can use the [HuggingFace](./available_embeddings/huggingface.md) embedding model.
|
||||
|
||||
## API Reference
|
||||
|
||||
- [OpenAIEmbedding](../../api/classes/OpenAIEmbedding.md)
|
||||
- [ServiceContext](../../api/interfaces/ServiceContext.md)
|
||||
- [ServiceContext](../../api/interfaces//ServiceContext.md)
|
||||
@@ -1,17 +0,0 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# Reader / Loader
|
||||
|
||||
LlamaIndex.TS supports easy loading of files from folders using the `SimpleDirectoryReader` class. Currently, `.txt`, `.pdf`, `.csv`, `.md` and `.docx` files are supported, with more planned in the future!
|
||||
|
||||
```typescript
|
||||
import { SimpleDirectoryReader } from "llamaindex";
|
||||
|
||||
documents = new SimpleDirectoryReader().loadData("./data");
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [SimpleDirectoryReader](../../api/classes/SimpleDirectoryReader.md)
|
||||
@@ -1,31 +0,0 @@
|
||||
# Core Modules
|
||||
|
||||
LlamaIndex.TS offers several core modules, seperated into high-level modules for quickly getting started, and low-level modules for customizing key components as you need.
|
||||
|
||||
## High-Level Modules
|
||||
|
||||
- [**Document**](./high_level/documents_and_nodes.md): A document represents a text file, PDF file or other contiguous piece of data.
|
||||
|
||||
- [**Node**](./high_level/documents_and_nodes.md): The basic data building block. Most commonly, these are parts of the document split into manageable pieces that are small enough to be fed into an embedding model and LLM.
|
||||
|
||||
- [**Reader/Loader**](./high_level/data_loader.md): A reader or loader is something that takes in a document in the real world and transforms into a Document class that can then be used in your Index and queries. We currently support plain text files and PDFs with many many more to come.
|
||||
|
||||
- [**Indexes**](./high_level/data_index.md): indexes store the Nodes and the embeddings of those nodes.
|
||||
|
||||
- [**QueryEngine**](./high_level/query_engine.md): Query engines are what generate the query you put in and give you back the result. Query engines generally combine a pre-built prompt with selected nodes from your Index to give the LLM the context it needs to answer your query.
|
||||
|
||||
- [**ChatEngine**](./high_level/chat_engine.md): A ChatEngine helps you build a chatbot that will interact with your Indexes.
|
||||
|
||||
## Low Level Module
|
||||
|
||||
- [**LLM**](./low_level/llm.md): The LLM class is a unified interface over a large language model provider such as OpenAI GPT-4, Anthropic Claude, or Meta LLaMA. You can subclass it to write a connector to your own large language model.
|
||||
|
||||
- [**Embedding**](./low_level/embedding.md): An embedding is represented as a vector of floating point numbers. OpenAI's text-embedding-ada-002 is our default embedding model and each embedding it generates consists of 1,536 floating point numbers. Another popular embedding model is BERT which uses 768 floating point numbers to represent each Node. We provide a number of utilities to work with embeddings including 3 similarity calculation options and Maximum Marginal Relevance
|
||||
|
||||
- [**TextSplitter/NodeParser**](./low_level/node_parser.md): Text splitting strategies are incredibly important to the overall efficacy of the embedding search. Currently, while we do have a default, there's no one size fits all solution. Depending on the source documents, you may want to use different splitting sizes and strategies. Currently we support spliltting by fixed size, splitting by fixed size with overlapping sections, splitting by sentence, and splitting by paragraph. The text splitter is used by the NodeParser when splitting `Document`s into `Node`s.
|
||||
|
||||
- [**Retriever**](./low_level/retriever.md): The Retriever is what actually chooses the Nodes to retrieve from the index. Here, you may wish to try retrieving more or fewer Nodes per query, changing your similarity function, or creating your own retriever for each individual use case in your application. For example, you may wish to have a separate retriever for code content vs. text content.
|
||||
|
||||
- [**ResponseSynthesizer**](./low_level/response_synthesizer.md): The ResponseSynthesizer is responsible for taking a query string, and using a list of `Node`s to generate a response. This can take many forms, like iterating over all the context and refining an answer, or building a tree of summaries and returning the root summary.
|
||||
|
||||
- [**Storage**](./low_level/storage.md): At some point you're going to want to store your indexes, data and vectors instead of re-running the embedding models every time. IndexStore, DocStore, VectorStore, and KVStore are abstractions that let you do that. Combined, they form the StorageContext. Currently, we allow you to persist your embeddings in files on the filesystem (or a virtual in memory file system), but we are also actively adding integrations to Vector Databases.
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "Ingestion Pipeline"
|
||||
position: 2
|
||||
@@ -0,0 +1,99 @@
|
||||
# Ingestion Pipeline
|
||||
|
||||
An `IngestionPipeline` uses a concept of `Transformations` that are applied to input data.
|
||||
These `Transformations` are applied to your input data, and the resulting nodes are either returned or inserted into a vector database (if given).
|
||||
|
||||
## Usage Pattern
|
||||
|
||||
The simplest usage is to instantiate an IngestionPipeline like so:
|
||||
|
||||
```ts
|
||||
import fs from "node:fs/promises";
|
||||
|
||||
import {
|
||||
Document,
|
||||
IngestionPipeline,
|
||||
MetadataMode,
|
||||
OpenAIEmbedding,
|
||||
TitleExtractor,
|
||||
SimpleNodeParser,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Load essay from abramov.txt in Node
|
||||
const path = "node_modules/llamaindex/examples/abramov.txt";
|
||||
|
||||
const essay = await fs.readFile(path, "utf-8");
|
||||
|
||||
// Create Document object with essay
|
||||
const document = new Document({ text: essay, id_: path });
|
||||
const pipeline = new IngestionPipeline({
|
||||
transformations: [
|
||||
new SimpleNodeParser({ chunkSize: 1024, chunkOverlap: 20 }),
|
||||
new TitleExtractor(),
|
||||
new OpenAIEmbedding(),
|
||||
],
|
||||
});
|
||||
|
||||
// run the pipeline
|
||||
const nodes = await pipeline.run({ documents: [document] });
|
||||
|
||||
// print out the result of the pipeline run
|
||||
for (const node of nodes) {
|
||||
console.log(node.getContent(MetadataMode.NONE));
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
```
|
||||
|
||||
## Connecting to Vector Databases
|
||||
|
||||
When running an ingestion pipeline, you can also chose to automatically insert the resulting nodes into a remote vector store.
|
||||
|
||||
Then, you can construct an index from that vector store later on.
|
||||
|
||||
```ts
|
||||
import fs from "node:fs/promises";
|
||||
|
||||
import {
|
||||
Document,
|
||||
IngestionPipeline,
|
||||
MetadataMode,
|
||||
OpenAIEmbedding,
|
||||
TitleExtractor,
|
||||
SimpleNodeParser,
|
||||
QdrantVectorStore,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Load essay from abramov.txt in Node
|
||||
const path = "node_modules/llamaindex/examples/abramov.txt";
|
||||
|
||||
const essay = await fs.readFile(path, "utf-8");
|
||||
|
||||
const vectorStore = new QdrantVectorStore({
|
||||
host: "http://localhost:6333",
|
||||
});
|
||||
|
||||
// Create Document object with essay
|
||||
const document = new Document({ text: essay, id_: path });
|
||||
const pipeline = new IngestionPipeline({
|
||||
transformations: [
|
||||
new SimpleNodeParser({ chunkSize: 1024, chunkOverlap: 20 }),
|
||||
new TitleExtractor(),
|
||||
new OpenAIEmbedding(),
|
||||
],
|
||||
vectorStore,
|
||||
});
|
||||
|
||||
// run the pipeline
|
||||
const nodes = await pipeline.run({ documents: [document] });
|
||||
|
||||
// create an index
|
||||
const index = VectorStoreIndex.fromVectorStore(vectorStore);
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
```
|
||||
@@ -0,0 +1,77 @@
|
||||
# Transformations
|
||||
|
||||
A transformation is something that takes a list of nodes as an input, and returns a list of nodes. Each component that implements the Transformatio class has both a `transform` definition responsible for transforming the nodes
|
||||
|
||||
Currently, the following components are Transformation objects:
|
||||
|
||||
- [SimpleNodeParser](../api/classes/SimpleNodeParser.md)
|
||||
- [MetadataExtractor](../documents_and_nodes/metadata_extraction.md)
|
||||
- Embeddings
|
||||
|
||||
## Usage Pattern
|
||||
|
||||
While transformations are best used with with an IngestionPipeline, they can also be used directly.
|
||||
|
||||
```ts
|
||||
import { SimpleNodeParser, TitleExtractor, Document } from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
let nodes = new SimpleNodeParser().getNodesFromDocuments([
|
||||
new Document({ text: "I am 10 years old. John is 20 years old." }),
|
||||
]);
|
||||
|
||||
const titleExtractor = new TitleExtractor();
|
||||
|
||||
nodes = await titleExtractor.transform(nodes);
|
||||
|
||||
for (const node of nodes) {
|
||||
console.log(node.getContent(MetadataMode.NONE));
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
```
|
||||
|
||||
## Custom Transformations
|
||||
|
||||
You can implement any transformation yourself by implementing the `TransformerComponent`.
|
||||
|
||||
The following custom transformation will remove any special characters or punctutaion in text.
|
||||
|
||||
```ts
|
||||
import { TransformerComponent, Node } from "llamaindex";
|
||||
|
||||
class RemoveSpecialCharacters extends TransformerComponent {
|
||||
async transform(nodes: Node[]): Promise<Node[]> {
|
||||
for (const node of nodes) {
|
||||
node.text = node.text.replace(/[^\w\s]/gi, "");
|
||||
}
|
||||
|
||||
return nodes;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
These can then be used directly or in any IngestionPipeline.
|
||||
|
||||
```ts
|
||||
import { IngestionPipeline, Document } from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
const pipeline = new IngestionPipeline({
|
||||
transformations: [new RemoveSpecialCharacters()],
|
||||
});
|
||||
|
||||
const nodes = await pipeline.run({
|
||||
documents: [
|
||||
new Document({ text: "I am 10 years old. John is 20 years old." }),
|
||||
],
|
||||
});
|
||||
|
||||
for (const node of nodes) {
|
||||
console.log(node.getContent(MetadataMode.NONE));
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
```
|
||||
@@ -0,0 +1,32 @@
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../examples/cloud/chat.ts";
|
||||
|
||||
# LlamaCloud
|
||||
|
||||
LlamaCloud is a new generation of managed parsing, ingestion, and retrieval services, designed to bring production-grade context-augmentation to your LLM and RAG applications.
|
||||
|
||||
Currently, LlamaCloud supports
|
||||
|
||||
- Managed Ingestion API, handling parsing and document management
|
||||
- Managed Retrieval API, configuring optimal retrieval for your RAG system
|
||||
|
||||
## Access
|
||||
|
||||
We are opening up a private beta to a limited set of enterprise partners for the managed ingestion and retrieval API. If you’re interested in centralizing your data pipelines and spending more time working on your actual RAG use cases, come [talk to us.](https://www.llamaindex.ai/contact)
|
||||
|
||||
If you have access to LlamaCloud, you can visit [LlamaCloud](https://cloud.llamaindex.ai) to sign in and get an API key.
|
||||
|
||||
## Create a Managed Index
|
||||
|
||||
Currently, you can't create a managed index on LlamaCloud using LlamaIndexTS, but you can use an existing managed index for retrieval that was created by the Python version of LlamaIndex. See [the LlamaCloudIndex documentation](https://docs.llamaindex.ai/en/stable/module_guides/indexing/llama_cloud_index.html#usage) for more information on how to create a managed index.
|
||||
|
||||
## Use a Managed Index
|
||||
|
||||
Here's an example of how to use a managed index together with a chat engine:
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
|
||||
## API Reference
|
||||
|
||||
- [LlamaCloudIndex](../api/classes/LlamaCloudIndex.md)
|
||||
- [LlamaCloudRetriever](../api/classes/LlamaCloudRetriever.md)
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "LLMs"
|
||||
position: 3
|
||||
@@ -0,0 +1 @@
|
||||
label: "Available LLMs"
|
||||
@@ -0,0 +1,80 @@
|
||||
# Anthropic
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { Anthropic, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const anthropicLLM = new Anthropic({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm: anthropicLLM });
|
||||
```
|
||||
|
||||
## 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], {
|
||||
serviceContext,
|
||||
});
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import {
|
||||
Anthropic,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Create an instance of the Anthropic LLM
|
||||
const anthropicLLM = new Anthropic({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
// Create a service context
|
||||
const serviceContext = serviceContextFromDefaults({ llm: anthropicLLM });
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
// Create a query engine
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
// Query
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
// Log the response
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,91 @@
|
||||
# Azure OpenAI
|
||||
|
||||
To use Azure OpenAI, you only need to set a few environment variables together with the `OpenAI` class.
|
||||
|
||||
For example:
|
||||
|
||||
## Environment Variables
|
||||
|
||||
```
|
||||
export AZURE_OPENAI_KEY="<YOUR KEY HERE>"
|
||||
export AZURE_OPENAI_ENDPOINT="<YOUR ENDPOINT, see https://learn.microsoft.com/en-us/azure/ai-services/openai/quickstart?tabs=command-line%2Cpython&pivots=rest-api>"
|
||||
export AZURE_OPENAI_DEPLOYMENT="gpt-4" # or some other deployment name
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { OpenAI, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const azureOpenaiLLM = new OpenAI({ model: "gpt-4", temperature: 0 });
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm: azureOpenaiLLM });
|
||||
```
|
||||
|
||||
## 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], {
|
||||
serviceContext,
|
||||
});
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import {
|
||||
OpenAI,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Create an instance of the LLM
|
||||
const azureOpenaiLLM = new OpenAI({ model: "gpt-4", temperature: 0 });
|
||||
|
||||
// Create a service context
|
||||
const serviceContext = serviceContextFromDefaults({ llm: azureOpenaiLLM });
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
// Create a query engine
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
// Query
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
// Log the response
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,65 @@
|
||||
# Fireworks LLM
|
||||
|
||||
Fireworks.ai focus on production use cases for open source LLMs, offering speed and quality.
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { FireworksLLM, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const fireworksLLM = new FireworksLLM({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm: fireworksLLM });
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
|
||||
For this example, we will load the Berkshire Hathaway 2022 annual report pdf
|
||||
|
||||
```ts
|
||||
const reader = new PDFReader();
|
||||
const documents = await reader.loadData("../data/brk-2022.pdf");
|
||||
|
||||
// Split text and create embeddings. Store them in a VectorStoreIndex
|
||||
const index = await VectorStoreIndex.fromDocuments(documents, {
|
||||
serviceContext,
|
||||
});
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
const response = await queryEngine.query({
|
||||
query: "What mistakes did Warren E. Buffett make?",
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import { VectorStoreIndex } from "llamaindex";
|
||||
import { PDFReader } from "llamaindex/readers/PDFReader";
|
||||
|
||||
async function main() {
|
||||
// Load PDF
|
||||
const reader = new PDFReader();
|
||||
const documents = await reader.loadData("../data/brk-2022.pdf");
|
||||
|
||||
// Split text and create embeddings. Store them in a VectorStoreIndex
|
||||
const index = await VectorStoreIndex.fromDocuments(documents);
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine();
|
||||
const response = await queryEngine.query({
|
||||
query: "What mistakes did Warren E. Buffett make?",
|
||||
});
|
||||
|
||||
// Output response
|
||||
console.log(response.toString());
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
```
|
||||
@@ -0,0 +1,100 @@
|
||||
# LLama2
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { Ollama, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const llama2LLM = new LlamaDeuce({ chatStrategy: DeuceChatStrategy.META });
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm: llama2LLM });
|
||||
```
|
||||
|
||||
## Usage with Replication
|
||||
|
||||
```ts
|
||||
import {
|
||||
Ollama,
|
||||
ReplicateSession,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
const replicateSession = new ReplicateSession({
|
||||
replicateKey,
|
||||
});
|
||||
|
||||
const llama2LLM = new LlamaDeuce({
|
||||
chatStrategy: DeuceChatStrategy.META,
|
||||
replicateSession,
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm: llama2LLM });
|
||||
```
|
||||
|
||||
## 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], {
|
||||
serviceContext,
|
||||
});
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import {
|
||||
LlamaDeuce,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Create an instance of the LLM
|
||||
const llama2LLM = new LlamaDeuce({ chatStrategy: DeuceChatStrategy.META });
|
||||
|
||||
// Create a service context
|
||||
const serviceContext = serviceContextFromDefaults({ llm: mistralLLM });
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
// Create a query engine
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
// Query
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
// Log the response
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,82 @@
|
||||
# Mistral
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { Ollama, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const mistralLLM = new MistralAI({
|
||||
model: "mistral-tiny",
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm: mistralLLM });
|
||||
```
|
||||
|
||||
## 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], {
|
||||
serviceContext,
|
||||
});
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import {
|
||||
MistralAI,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Create an instance of the LLM
|
||||
const mistralLLM = new MistralAI({ model: "mistral-tiny" });
|
||||
|
||||
// Create a service context
|
||||
const serviceContext = serviceContextFromDefaults({ llm: mistralLLM });
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
// Create a query engine
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
// Query
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
// Log the response
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,89 @@
|
||||
# Ollama
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { Ollama, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const ollamaLLM = new Ollama({ model: "llama2", temperature: 0.75 });
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
llm: ollamaLLM,
|
||||
embedModel: ollamaLLM,
|
||||
});
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
|
||||
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
|
||||
|
||||
```ts
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import {
|
||||
Ollama,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
import fs from "fs/promises";
|
||||
|
||||
async function main() {
|
||||
// Create an instance of the LLM
|
||||
const ollamaLLM = new Ollama({ model: "llama2", temperature: 0.75 });
|
||||
|
||||
const essay = await fs.readFile("./paul_graham_essay.txt", "utf-8");
|
||||
|
||||
// Create a service context
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
embedModel: ollamaLLM, // prevent 'Set OpenAI Key in OPENAI_API_KEY env variable' error
|
||||
llm: ollamaLLM,
|
||||
});
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
// Create a query engine
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
// Query
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
// Log the response
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,83 @@
|
||||
# OpenAI
|
||||
|
||||
```ts
|
||||
import { OpenAI, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const openaiLLM = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0, apiKey: <YOUR_API_KEY> });
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm: openaiLLM });
|
||||
```
|
||||
|
||||
You can setup the apiKey on the environment variables, like:
|
||||
|
||||
```bash
|
||||
export OPENAI_API_KEY="<YOUR_API_KEY>"
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
|
||||
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
|
||||
|
||||
```ts
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import {
|
||||
OpenAI,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Create an instance of the LLM
|
||||
const openaiLLM = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0 });
|
||||
|
||||
// Create a service context
|
||||
const serviceContext = serviceContextFromDefaults({ llm: openaiLLM });
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
// Create a query engine
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
// Query
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
// Log the response
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,83 @@
|
||||
# Portkey LLM
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { Portkey, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const portkeyLLM = new Portkey({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm: portkeyLLM });
|
||||
```
|
||||
|
||||
## 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], {
|
||||
serviceContext,
|
||||
});
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import {
|
||||
Portkey,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Create an instance of the LLM
|
||||
const portkeyLLM = new Portkey({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
// Create a service context
|
||||
const serviceContext = serviceContextFromDefaults({ llm: portkeyLLM });
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
// Create a query engine
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
// Query
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
// Log the response
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,83 @@
|
||||
# Together LLM
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { TogetherLLM, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const togetherLLM = new TogetherLLM({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm: togetherLLM });
|
||||
```
|
||||
|
||||
## 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], {
|
||||
serviceContext,
|
||||
});
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import {
|
||||
TogetherLLM,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Create an instance of the LLM
|
||||
const togetherLLM = new TogetherLLM({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
// Create a service context
|
||||
const serviceContext = serviceContextFromDefaults({ llm: togetherLLM });
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
// Create a query engine
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
// Query
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
// Log the response
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
# Large Language Models (LLMs)
|
||||
|
||||
The LLM is responsible for reading text and generating natural language responses to queries. By default, LlamaIndex.TS uses `gpt-3.5-turbo`.
|
||||
|
||||
The LLM can be explicitly set in the `ServiceContext` object.
|
||||
|
||||
```typescript
|
||||
import { OpenAI, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const openaiLLM = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0 });
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm: openaiLLM });
|
||||
```
|
||||
|
||||
## Azure OpenAI
|
||||
|
||||
To use Azure OpenAI, you only need to set a few environment variables.
|
||||
|
||||
For example:
|
||||
|
||||
```
|
||||
export AZURE_OPENAI_KEY="<YOUR KEY HERE>"
|
||||
export AZURE_OPENAI_ENDPOINT="<YOUR ENDPOINT, see https://learn.microsoft.com/en-us/azure/ai-services/openai/quickstart?tabs=command-line%2Cpython&pivots=rest-api>"
|
||||
export AZURE_OPENAI_DEPLOYMENT="gpt-4" # or some other deployment name
|
||||
```
|
||||
|
||||
## Local LLM
|
||||
|
||||
For local LLMs, currently we recommend the use of [Ollama](./available_llms/ollama.md) LLM.
|
||||
|
||||
## API Reference
|
||||
|
||||
- [OpenAI](../api/classes/OpenAI.md)
|
||||
- [ServiceContext](../api/interfaces//ServiceContext.md)
|
||||
@@ -0,0 +1,98 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
# NodeParser
|
||||
|
||||
The `NodeParser` in LlamaIndex is responsible for splitting `Document` objects into more manageable `Node` objects. When you call `.fromDocuments()`, the `NodeParser` from the `ServiceContext` is used to do this automatically for you. Alternatively, you can use it to split documents ahead of time.
|
||||
|
||||
```typescript
|
||||
import { Document, SimpleNodeParser } from "llamaindex";
|
||||
|
||||
const nodeParser = new SimpleNodeParser();
|
||||
const nodes = nodeParser.getNodesFromDocuments([
|
||||
new Document({ text: "I am 10 years old. John is 20 years old." }),
|
||||
]);
|
||||
```
|
||||
|
||||
## TextSplitter
|
||||
|
||||
The underlying text splitter will split text by sentences. It can also be used as a standalone module for splitting raw text.
|
||||
|
||||
```typescript
|
||||
import { SentenceSplitter } from "llamaindex";
|
||||
|
||||
const splitter = new SentenceSplitter({ chunkSize: 1 });
|
||||
|
||||
const textSplits = splitter.splitText("Hello World");
|
||||
```
|
||||
|
||||
## MarkdownNodeParser
|
||||
|
||||
The `MarkdownNodeParser` is a more advanced `NodeParser` that can handle markdown documents. It will split the markdown into nodes and then parse the nodes into a `Document` object.
|
||||
|
||||
```typescript
|
||||
import { MarkdownNodeParser } from "llamaindex";
|
||||
|
||||
const nodeParser = new MarkdownNodeParser();
|
||||
|
||||
const nodes = nodeParser.getNodesFromDocuments([
|
||||
new Document({
|
||||
text: `# Main Header
|
||||
Main content
|
||||
|
||||
# Header 2
|
||||
Header 2 content
|
||||
|
||||
## Sub-header
|
||||
Sub-header content
|
||||
|
||||
`,
|
||||
}),
|
||||
]);
|
||||
```
|
||||
|
||||
The output metadata will be something like:
|
||||
|
||||
```bash
|
||||
[
|
||||
TextNode {
|
||||
id_: '008e41a8-b097-487c-bee8-bd88b9455844',
|
||||
metadata: { 'Header 1': 'Main Header' },
|
||||
excludedEmbedMetadataKeys: [],
|
||||
excludedLlmMetadataKeys: [],
|
||||
relationships: { PARENT: [Array] },
|
||||
hash: 'KJ5e/um/RkHaNR6bonj9ormtZY7I8i4XBPVYHXv1A5M=',
|
||||
text: 'Main Header\nMain content',
|
||||
textTemplate: '',
|
||||
metadataSeparator: '\n'
|
||||
},
|
||||
TextNode {
|
||||
id_: '0f5679b3-ba63-4aff-aedc-830c4208d0b5',
|
||||
metadata: { 'Header 1': 'Header 2' },
|
||||
excludedEmbedMetadataKeys: [],
|
||||
excludedLlmMetadataKeys: [],
|
||||
relationships: { PARENT: [Array] },
|
||||
hash: 'IP/g/dIld3DcbK+uHzDpyeZ9IdOXY4brxhOIe7wc488=',
|
||||
text: 'Header 2\nHeader 2 content',
|
||||
textTemplate: '',
|
||||
metadataSeparator: '\n'
|
||||
},
|
||||
TextNode {
|
||||
id_: 'e81e9bd0-121c-4ead-8ca7-1639d65fdf90',
|
||||
metadata: { 'Header 1': 'Header 2', 'Header 2': 'Sub-header' },
|
||||
excludedEmbedMetadataKeys: [],
|
||||
excludedLlmMetadataKeys: [],
|
||||
relationships: { PARENT: [Array] },
|
||||
hash: 'B3kYNnxaYi9ghtAgwza0ZEVKF4MozobkNUlcekDL7JQ=',
|
||||
text: 'Sub-header\nSub-header content',
|
||||
textTemplate: '',
|
||||
metadataSeparator: '\n'
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [SimpleNodeParser](../api/classes/SimpleNodeParser.md)
|
||||
- [SentenceSplitter](../api/classes/SentenceSplitter.md)
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "Node Postprocessors"
|
||||
position: 3
|
||||
@@ -0,0 +1,71 @@
|
||||
# Cohere Reranker
|
||||
|
||||
The Cohere Reranker is a postprocessor that uses the Cohere API to rerank the results of a search query.
|
||||
|
||||
## Setup
|
||||
|
||||
Firstly, you will need to install the `llamaindex` package.
|
||||
|
||||
```bash
|
||||
pnpm install llamaindex
|
||||
```
|
||||
|
||||
Now, you will need to sign up for an API key at [Cohere](https://cohere.ai/). Once you have your API key you can import the necessary modules and create a new instance of the `CohereRerank` class.
|
||||
|
||||
```ts
|
||||
import {
|
||||
CohereRerank,
|
||||
Document,
|
||||
OpenAI,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
|
||||
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
|
||||
|
||||
```ts
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
llm: new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 }),
|
||||
});
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
```
|
||||
|
||||
## Increase similarity topK to retrieve more results
|
||||
|
||||
The default value for `similarityTopK` is 2. This means that only the most similar document will be returned. To retrieve more results, you can increase the value of `similarityTopK`.
|
||||
|
||||
```ts
|
||||
const retriever = index.asRetriever();
|
||||
retriever.similarityTopK = 5;
|
||||
```
|
||||
|
||||
## Create a new instance of the CohereRerank class
|
||||
|
||||
Then you can create a new instance of the `CohereRerank` class and pass in your API key and the number of results you want to return.
|
||||
|
||||
```ts
|
||||
const nodePostprocessor = new CohereRerank({
|
||||
apiKey: "<COHERE_API_KEY>",
|
||||
topN: 4,
|
||||
});
|
||||
```
|
||||
|
||||
## Create a query engine with the retriever and node postprocessor
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
nodePostprocessors: [nodePostprocessor],
|
||||
});
|
||||
|
||||
// log the response
|
||||
const response = await queryEngine.query("Where did the author grown up?");
|
||||
```
|
||||
@@ -0,0 +1,110 @@
|
||||
# Node Postprocessors
|
||||
|
||||
## Concept
|
||||
|
||||
Node postprocessors are a set of modules that take a set of nodes, and apply some kind of transformation or filtering before returning them.
|
||||
|
||||
In LlamaIndex, node postprocessors are most commonly applied within a query engine, after the node retrieval step and before the response synthesis step.
|
||||
|
||||
LlamaIndex offers several node postprocessors for immediate use, while also providing a simple API for adding your own custom postprocessors.
|
||||
|
||||
## Usage Pattern
|
||||
|
||||
An example of using a node postprocessors is below:
|
||||
|
||||
```ts
|
||||
import {
|
||||
Node,
|
||||
NodeWithScore,
|
||||
SimilarityPostprocessor,
|
||||
CohereRerank,
|
||||
} from "llamaindex";
|
||||
|
||||
const nodes: NodeWithScore[] = [
|
||||
{
|
||||
node: new TextNode({ text: "hello world" }),
|
||||
score: 0.8,
|
||||
},
|
||||
{
|
||||
node: new TextNode({ text: "LlamaIndex is the best" }),
|
||||
score: 0.6,
|
||||
},
|
||||
];
|
||||
|
||||
// similarity postprocessor: filter nodes below 0.75 similarity score
|
||||
const processor = new SimilarityPostprocessor({
|
||||
similarityCutoff: 0.7,
|
||||
});
|
||||
|
||||
const filteredNodes = processor.postprocessNodes(nodes);
|
||||
|
||||
// cohere rerank: rerank nodes given query using trained model
|
||||
const reranker = new CohereRerank({
|
||||
apiKey: "<COHERE_API_KEY>",
|
||||
topN: 2,
|
||||
});
|
||||
|
||||
const rerankedNodes = await reranker.postprocessNodes(nodes, "<user_query>");
|
||||
|
||||
console.log(filteredNodes, rerankedNodes);
|
||||
```
|
||||
|
||||
Now you can use the `filteredNodes` and `rerankedNodes` in your application.
|
||||
|
||||
## Using Node Postprocessors in LlamaIndex
|
||||
|
||||
Most commonly, node-postprocessors will be used in a query engine, where they are applied to the nodes returned from a retriever, and before the response synthesis step.
|
||||
|
||||
### Using Node Postprocessors in a Query Engine
|
||||
|
||||
```ts
|
||||
import { Node, NodeWithScore, SimilarityPostprocessor, CohereRerank } from "llamaindex";
|
||||
|
||||
const nodes: NodeWithScore[] = [
|
||||
{
|
||||
node: new TextNode({ text: "hello world" }),
|
||||
score: 0.8,
|
||||
},
|
||||
{
|
||||
node: new TextNode({ text: "LlamaIndex is the best" }),
|
||||
score: 0.6,
|
||||
}
|
||||
];
|
||||
|
||||
// cohere rerank: rerank nodes given query using trained model
|
||||
const reranker = new CohereRerank({
|
||||
apiKey: "<COHERE_API_KEY>,
|
||||
topN: 2,
|
||||
})
|
||||
|
||||
const document = new Document({ text: "essay", id_: "essay" });
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
llm: new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 }),
|
||||
});
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
const queryEngine = index.asQueryEngine({
|
||||
nodePostprocessors: [processor, reranker],
|
||||
});
|
||||
|
||||
// all node post-processors will be applied during each query
|
||||
const response = await queryEngine.query("<user_query>");
|
||||
```
|
||||
|
||||
### Using with retrieved nodes
|
||||
|
||||
```ts
|
||||
import { SimilarityPostprocessor } from "llamaindex";
|
||||
|
||||
nodes = await index.asRetriever().retrieve("test query str");
|
||||
|
||||
const processor = new SimilarityPostprocessor({
|
||||
similarityCutoff: 0.7,
|
||||
});
|
||||
|
||||
const filteredNodes = processor.postprocessNodes(nodes);
|
||||
```
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "Prompts"
|
||||
position: 0
|
||||
@@ -0,0 +1,76 @@
|
||||
# Prompts
|
||||
|
||||
Prompting is the fundamental input that gives LLMs their expressive power. LlamaIndex uses prompts to build the index, do insertion, perform traversal during querying, and to synthesize the final answer.
|
||||
|
||||
Users may also provide their own prompt templates to further customize the behavior of the framework. The best method for customizing is copying the default prompt from the link above, and using that as the base for any modifications.
|
||||
|
||||
## Usage Pattern
|
||||
|
||||
Currently, there are two ways to customize prompts in LlamaIndex:
|
||||
|
||||
For both methods, you will need to create an function that overrides the default prompt.
|
||||
|
||||
```ts
|
||||
// Define a custom prompt
|
||||
const newTextQaPrompt: TextQaPrompt = ({ context, query }) => {
|
||||
return `Context information is below.
|
||||
---------------------
|
||||
${context}
|
||||
---------------------
|
||||
Given the context information and not prior knowledge, answer the query.
|
||||
Answer the query in the style of a Sherlock Holmes detective novel.
|
||||
Query: ${query}
|
||||
Answer:`;
|
||||
};
|
||||
```
|
||||
|
||||
### 1. Customizing the default prompt on initialization
|
||||
|
||||
The first method is to create a new instance of `ResponseSynthesizer` (or the module you would like to update the prompt) and pass the custom prompt to the `responseBuilder` parameter. Then, pass the instance to the `asQueryEngine` method of the index.
|
||||
|
||||
```ts
|
||||
// Create an instance of response synthesizer
|
||||
const responseSynthesizer = new ResponseSynthesizer({
|
||||
responseBuilder: new CompactAndRefine(serviceContext, newTextQaPrompt),
|
||||
});
|
||||
|
||||
// Create index
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine({ responseSynthesizer });
|
||||
|
||||
const response = await queryEngine.query({
|
||||
query: "What did the author do in college?",
|
||||
});
|
||||
```
|
||||
|
||||
### 2. Customizing submodules prompt
|
||||
|
||||
The second method is that most of the modules in LlamaIndex have a `getPrompts` and a `updatePrompt` method that allows you to override the default prompt. This method is useful when you want to change the prompt on the fly or in submodules on a more granular level.
|
||||
|
||||
```ts
|
||||
// Create index
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
// Get a list of prompts for the query engine
|
||||
const prompts = queryEngine.getPrompts();
|
||||
|
||||
// output: { "responseSynthesizer:textQATemplate": defaultTextQaPrompt, "responseSynthesizer:refineTemplate": defaultRefineTemplatePrompt }
|
||||
|
||||
// Now, we can override the default prompt
|
||||
queryEngine.updatePrompt({
|
||||
"responseSynthesizer:textQATemplate": newTextQaPrompt,
|
||||
});
|
||||
|
||||
const response = await queryEngine.query({
|
||||
query: "What did the author do in college?",
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "Query Engines"
|
||||
position: 2
|
||||
+11
-6
@@ -1,14 +1,19 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
# QueryEngine
|
||||
|
||||
A query engine wraps a `Retriever` and a `ResponseSynthesizer` into a pipeline, that will use the query string to fetech nodes and then send them to the LLM to generate a response.
|
||||
|
||||
```typescript
|
||||
const queryEngine = index.asQueryEngine();
|
||||
const response = await queryEngine.query("query string");
|
||||
const response = await queryEngine.query({ query: "query string" });
|
||||
```
|
||||
|
||||
The `query` function also supports streaming, just add `stream: true` as an option:
|
||||
|
||||
```typescript
|
||||
const stream = await queryEngine.query({ query: "query string", stream: true });
|
||||
for await (const chunk of stream) {
|
||||
process.stdout.write(chunk.response);
|
||||
}
|
||||
```
|
||||
|
||||
## Sub Question Query Engine
|
||||
@@ -17,7 +22,7 @@ The basic concept of the Sub Question Query Engine is that it splits a single qu
|
||||
|
||||
### Getting Started
|
||||
|
||||
The easiest way to start trying the Sub Question Query Engine is running the subquestion.ts file in [apps/simple](https://github.com/run-llama/LlamaIndexTS/blob/main/apps/simple/subquestion.ts).
|
||||
The easiest way to start trying the Sub Question Query Engine is running the subquestion.ts file in [examples](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/subquestion.ts).
|
||||
|
||||
```bash
|
||||
npx ts-node subquestion.ts
|
||||
@@ -0,0 +1,152 @@
|
||||
# Metadata Filtering
|
||||
|
||||
Metadata filtering is a way to filter the documents that are returned by a query based on the metadata associated with the documents. This is useful when you want to filter the documents based on some metadata that is not part of the document text.
|
||||
|
||||
You can also check our multi-tenancy blog post to see how metadata filtering can be used in a multi-tenant environment. [https://blog.llamaindex.ai/building-multi-tenancy-rag-system-with-llamaindex-0d6ab4e0c44b] (the article uses the Python version of LlamaIndex, but the concepts are the same).
|
||||
|
||||
## Setup
|
||||
|
||||
Firstly if you haven't already, you need to install the `llamaindex` package:
|
||||
|
||||
```bash
|
||||
pnpm i llamaindex
|
||||
```
|
||||
|
||||
Then you can import the necessary modules from `llamaindex`:
|
||||
|
||||
```ts
|
||||
import {
|
||||
ChromaVectorStore,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
storageContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
const collectionName = "dog_colors";
|
||||
```
|
||||
|
||||
## Creating documents with metadata
|
||||
|
||||
You can create documents with metadata using the `Document` class:
|
||||
|
||||
```ts
|
||||
const docs = [
|
||||
new Document({
|
||||
text: "The dog is brown",
|
||||
metadata: {
|
||||
color: "brown",
|
||||
dogId: "1",
|
||||
},
|
||||
}),
|
||||
new Document({
|
||||
text: "The dog is red",
|
||||
metadata: {
|
||||
color: "red",
|
||||
dogId: "2",
|
||||
},
|
||||
}),
|
||||
];
|
||||
```
|
||||
|
||||
## Creating a ChromaDB vector store
|
||||
|
||||
You can create a `ChromaVectorStore` to store the documents:
|
||||
|
||||
```ts
|
||||
const chromaVS = new ChromaVectorStore({ collectionName });
|
||||
const serviceContext = await storageContextFromDefaults({
|
||||
vectorStore: chromaVS,
|
||||
});
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments(docs, {
|
||||
storageContext: serviceContext,
|
||||
});
|
||||
```
|
||||
|
||||
## Querying the index with metadata filtering
|
||||
|
||||
Now you can query the index with metadata filtering using the `preFilters` option:
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine({
|
||||
preFilters: {
|
||||
filters: [
|
||||
{
|
||||
key: "dogId",
|
||||
value: "2",
|
||||
filterType: "ExactMatch",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const response = await queryEngine.query({
|
||||
query: "What is the color of the dog?",
|
||||
});
|
||||
|
||||
console.log(response.toString());
|
||||
```
|
||||
|
||||
## Full Code
|
||||
|
||||
```ts
|
||||
import {
|
||||
ChromaVectorStore,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
storageContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
const collectionName = "dog_colors";
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
const docs = [
|
||||
new Document({
|
||||
text: "The dog is brown",
|
||||
metadata: {
|
||||
color: "brown",
|
||||
dogId: "1",
|
||||
},
|
||||
}),
|
||||
new Document({
|
||||
text: "The dog is red",
|
||||
metadata: {
|
||||
color: "red",
|
||||
dogId: "2",
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
console.log("Creating ChromaDB vector store");
|
||||
const chromaVS = new ChromaVectorStore({ collectionName });
|
||||
const ctx = await storageContextFromDefaults({ vectorStore: chromaVS });
|
||||
|
||||
console.log("Embedding documents and adding to index");
|
||||
const index = await VectorStoreIndex.fromDocuments(docs, {
|
||||
storageContext: ctx,
|
||||
});
|
||||
|
||||
console.log("Querying index");
|
||||
const queryEngine = index.asQueryEngine({
|
||||
preFilters: {
|
||||
filters: [
|
||||
{
|
||||
key: "dogId",
|
||||
value: "2",
|
||||
filterType: "ExactMatch",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const response = await queryEngine.query({
|
||||
query: "What is the color of the dog?",
|
||||
});
|
||||
console.log(response.toString());
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
```
|
||||
@@ -0,0 +1,189 @@
|
||||
# Router Query Engine
|
||||
|
||||
In this tutorial, we define a custom router query engine that selects one out of several candidate query engines to execute a query.
|
||||
|
||||
## Setup
|
||||
|
||||
First, we need to install import the necessary modules from `llamaindex`:
|
||||
|
||||
```bash
|
||||
pnpm i lamaindex
|
||||
```
|
||||
|
||||
```ts
|
||||
import {
|
||||
OpenAI,
|
||||
RouterQueryEngine,
|
||||
SimpleDirectoryReader,
|
||||
SimpleNodeParser,
|
||||
SummaryIndex,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
```
|
||||
|
||||
## Loading Data
|
||||
|
||||
Next, we need to load some data. We will use the `SimpleDirectoryReader` to load documents from a directory:
|
||||
|
||||
```ts
|
||||
const documents = await new SimpleDirectoryReader().loadData({
|
||||
directoryPath: "node_modules/llamaindex/examples",
|
||||
});
|
||||
```
|
||||
|
||||
## Service Context
|
||||
|
||||
Next, we need to define some basic rules and parse the documents into nodes. We will use the `SimpleNodeParser` to parse the documents into nodes and `ServiceContext` to define the rules (eg. LLM API key, chunk size, etc.):
|
||||
|
||||
```ts
|
||||
const nodeParser = new SimpleNodeParser({
|
||||
chunkSize: 1024,
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
nodeParser,
|
||||
llm: new OpenAI(),
|
||||
});
|
||||
```
|
||||
|
||||
## Creating Indices
|
||||
|
||||
Next, we need to create some indices. We will create a `VectorStoreIndex` and a `SummaryIndex`:
|
||||
|
||||
```ts
|
||||
const vectorIndex = await VectorStoreIndex.fromDocuments(documents, {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
const summaryIndex = await SummaryIndex.fromDocuments(documents, {
|
||||
serviceContext,
|
||||
});
|
||||
```
|
||||
|
||||
## Creating Query Engines
|
||||
|
||||
Next, we need to create some query engines. We will create a `VectorStoreQueryEngine` and a `SummaryQueryEngine`:
|
||||
|
||||
```ts
|
||||
const vectorQueryEngine = vectorIndex.asQueryEngine();
|
||||
const summaryQueryEngine = summaryIndex.asQueryEngine();
|
||||
```
|
||||
|
||||
## Creating a Router Query Engine
|
||||
|
||||
Next, we need to create a router query engine. We will use the `RouterQueryEngine` to create a router query engine:
|
||||
|
||||
We're defining two query engines, one for summarization and one for retrieving specific context. The router query engine will select the most appropriate query engine based on the query.
|
||||
|
||||
```ts
|
||||
const queryEngine = RouterQueryEngine.fromDefaults({
|
||||
queryEngineTools: [
|
||||
{
|
||||
queryEngine: vectorQueryEngine,
|
||||
description: "Useful for summarization questions related to Abramov",
|
||||
},
|
||||
{
|
||||
queryEngine: summaryQueryEngine,
|
||||
description: "Useful for retrieving specific context from Abramov",
|
||||
},
|
||||
],
|
||||
serviceContext,
|
||||
});
|
||||
```
|
||||
|
||||
## Querying the Router Query Engine
|
||||
|
||||
Finally, we can query the router query engine:
|
||||
|
||||
```ts
|
||||
const summaryResponse = await queryEngine.query({
|
||||
query: "Give me a summary about his past experiences?",
|
||||
});
|
||||
|
||||
console.log({
|
||||
answer: summaryResponse.response,
|
||||
metadata: summaryResponse?.metadata?.selectorResult,
|
||||
});
|
||||
```
|
||||
|
||||
## Full code
|
||||
|
||||
```ts
|
||||
import {
|
||||
OpenAI,
|
||||
RouterQueryEngine,
|
||||
SimpleDirectoryReader,
|
||||
SimpleNodeParser,
|
||||
SummaryIndex,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Load documents from a directory
|
||||
const documents = await new SimpleDirectoryReader().loadData({
|
||||
directoryPath: "node_modules/llamaindex/examples",
|
||||
});
|
||||
|
||||
// Parse the documents into nodes
|
||||
const nodeParser = new SimpleNodeParser({
|
||||
chunkSize: 1024,
|
||||
});
|
||||
|
||||
// Create a service context
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
nodeParser,
|
||||
llm: new OpenAI(),
|
||||
});
|
||||
|
||||
// Create indices
|
||||
const vectorIndex = await VectorStoreIndex.fromDocuments(documents, {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
const summaryIndex = await SummaryIndex.fromDocuments(documents, {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
// Create query engines
|
||||
const vectorQueryEngine = vectorIndex.asQueryEngine();
|
||||
const summaryQueryEngine = summaryIndex.asQueryEngine();
|
||||
|
||||
// Create a router query engine
|
||||
const queryEngine = RouterQueryEngine.fromDefaults({
|
||||
queryEngineTools: [
|
||||
{
|
||||
queryEngine: vectorQueryEngine,
|
||||
description: "Useful for summarization questions related to Abramov",
|
||||
},
|
||||
{
|
||||
queryEngine: summaryQueryEngine,
|
||||
description: "Useful for retrieving specific context from Abramov",
|
||||
},
|
||||
],
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
// Query the router query engine
|
||||
const summaryResponse = await queryEngine.query({
|
||||
query: "Give me a summary about his past experiences?",
|
||||
});
|
||||
|
||||
console.log({
|
||||
answer: summaryResponse.response,
|
||||
metadata: summaryResponse?.metadata?.selectorResult,
|
||||
});
|
||||
|
||||
const specificResponse = await queryEngine.query({
|
||||
query: "Tell me about abramov first job?",
|
||||
});
|
||||
|
||||
console.log({
|
||||
answer: specificResponse.response,
|
||||
metadata: specificResponse.metadata.selectorResult,
|
||||
});
|
||||
}
|
||||
|
||||
main().then(() => console.log("Done"));
|
||||
```
|
||||
+21
-8
@@ -35,17 +35,30 @@ const nodesWithScore: NodeWithScore[] = [
|
||||
},
|
||||
];
|
||||
|
||||
const response = await responseSynthesizer.synthesize(
|
||||
"What age am I?",
|
||||
const response = await responseSynthesizer.synthesize({
|
||||
query: "What age am I?",
|
||||
nodesWithScore,
|
||||
);
|
||||
});
|
||||
console.log(response.response);
|
||||
```
|
||||
|
||||
The `synthesize` function also supports streaming, just add `stream: true` as an option:
|
||||
|
||||
```typescript
|
||||
const stream = await responseSynthesizer.synthesize({
|
||||
query: "What age am I?",
|
||||
nodesWithScore,
|
||||
stream: true,
|
||||
});
|
||||
for await (const chunk of stream) {
|
||||
process.stdout.write(chunk.response);
|
||||
}
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [ResponseSynthesizer](../../api/classes/ResponseSynthesizer.md)
|
||||
- [Refine](../../api/classes/Refine.md)
|
||||
- [CompactAndRefine](../../api/classes/CompactAndRefine.md)
|
||||
- [TreeSummarize](../../api/classes/TreeSummarize.md)
|
||||
- [SimpleResponseBuilder](../../api/classes/SimpleResponseBuilder.md)
|
||||
- [ResponseSynthesizer](../api/classes/ResponseSynthesizer.md)
|
||||
- [Refine](../api/classes/Refine.md)
|
||||
- [CompactAndRefine](../api/classes/CompactAndRefine.md)
|
||||
- [TreeSummarize](../api/classes/TreeSummarize.md)
|
||||
- [SimpleResponseBuilder](../api/classes/SimpleResponseBuilder.md)
|
||||
@@ -16,6 +16,6 @@ const nodesWithScore = await retriever.retrieve("query string");
|
||||
|
||||
## API Reference
|
||||
|
||||
- [SummaryIndexRetriever](../../api/classes/SummaryIndexRetriever.md)
|
||||
- [SummaryIndexLLMRetriever](../../api/classes/SummaryIndexLLMRetriever.md)
|
||||
- [VectorIndexRetriever](../../api/classes/VectorIndexRetriever.md)
|
||||
- [SummaryIndexRetriever](../api/classes/SummaryIndexRetriever.md)
|
||||
- [SummaryIndexLLMRetriever](../api/classes/SummaryIndexLLMRetriever.md)
|
||||
- [VectorIndexRetriever](../api/classes/VectorIndexRetriever.md)
|
||||
@@ -23,4 +23,4 @@ const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
|
||||
## API Reference
|
||||
|
||||
- [StorageContext](../../api/interfaces/StorageContext.md)
|
||||
- [StorageContext](../api/interfaces//StorageContext.md)
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "Vector Stores"
|
||||
position: 1
|
||||
@@ -0,0 +1,86 @@
|
||||
# Qdrant Vector Store
|
||||
|
||||
To run this example, you need to have a Qdrant instance running. You can run it with Docker:
|
||||
|
||||
```bash
|
||||
docker pull qdrant/qdrant
|
||||
docker run -p 6333:6333 qdrant/qdrant
|
||||
```
|
||||
|
||||
## Importing the modules
|
||||
|
||||
```ts
|
||||
import fs from "node:fs/promises";
|
||||
import { Document, VectorStoreIndex, QdrantVectorStore } from "llamaindex";
|
||||
```
|
||||
|
||||
## Load the documents
|
||||
|
||||
```ts
|
||||
const path = "node_modules/llamaindex/examples/abramov.txt";
|
||||
const essay = await fs.readFile(path, "utf-8");
|
||||
```
|
||||
|
||||
## Setup Qdrant
|
||||
|
||||
```ts
|
||||
const vectorStore = new QdrantVectorStore({
|
||||
url: "http://localhost:6333",
|
||||
});
|
||||
```
|
||||
|
||||
## Setup the index
|
||||
|
||||
```ts
|
||||
const document = new Document({ text: essay, id_: path });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
vectorStore,
|
||||
});
|
||||
```
|
||||
|
||||
## Query the index
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const response = await queryEngine.query({
|
||||
query: "What did the author do in college?",
|
||||
});
|
||||
|
||||
// Output response
|
||||
console.log(response.toString());
|
||||
```
|
||||
|
||||
## Full code
|
||||
|
||||
```ts
|
||||
import fs from "node:fs/promises";
|
||||
import { Document, VectorStoreIndex, QdrantVectorStore } from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
const path = "node_modules/llamaindex/examples/abramov.txt";
|
||||
const essay = await fs.readFile(path, "utf-8");
|
||||
|
||||
const vectorStore = new QdrantVectorStore({
|
||||
url: "http://localhost:6333",
|
||||
});
|
||||
|
||||
const document = new Document({ text: essay, id_: path });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
vectorStore,
|
||||
});
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const response = await queryEngine.query({
|
||||
query: "What did the author do in college?",
|
||||
});
|
||||
|
||||
// Output response
|
||||
console.log(response.toString());
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
```
|
||||
@@ -0,0 +1,2 @@
|
||||
label: Observability
|
||||
position: 5
|
||||
@@ -0,0 +1,35 @@
|
||||
# Observability
|
||||
|
||||
LlamaIndex provides **one-click observability** 🔭 to allow you to build principled LLM applications in a production setting.
|
||||
|
||||
A key requirement for principled development of LLM applications over your data (RAG systems, agents) is being able to observe, debug, and evaluate
|
||||
your system - both as a whole and for each component.
|
||||
|
||||
This feature allows you to seamlessly integrate the LlamaIndex library with powerful observability/evaluation tools offered by our partners.
|
||||
Configure a variable once, and you'll be able to do things like the following:
|
||||
|
||||
- View LLM/prompt inputs/outputs
|
||||
- Ensure that the outputs of any component (LLMs, embeddings) are performing as expected
|
||||
- View call traces for both indexing and querying
|
||||
|
||||
Each provider has similarities and differences. Take a look below for the full set of guides for each one!
|
||||
|
||||
## OpenLLMetry
|
||||
|
||||
[OpenLLMetry](https://github.com/traceloop/openllmetry-js) is an open-source project based on OpenTelemetry for tracing and monitoring
|
||||
LLM applications. It connects to [all major observability platforms](https://www.traceloop.com/docs/openllmetry/integrations/introduction) and installs in minutes.
|
||||
|
||||
### Usage Pattern
|
||||
|
||||
```bash
|
||||
npm install @traceloop/node-server-sdk
|
||||
```
|
||||
|
||||
```js
|
||||
import * as traceloop from "@traceloop/node-server-sdk";
|
||||
|
||||
traceloop.initialize({
|
||||
apiKey: process.env.TRACELOOP_API_KEY,
|
||||
disableBatch: true,
|
||||
});
|
||||
```
|
||||
@@ -1,8 +1,9 @@
|
||||
// @ts-check
|
||||
// Note: type annotations allow type checking and IDEs autocompletion
|
||||
|
||||
const lightCodeTheme = require("prism-react-renderer/themes/github");
|
||||
const darkCodeTheme = require("prism-react-renderer/themes/dracula");
|
||||
const renderer = require("prism-react-renderer");
|
||||
const lightCodeTheme = renderer.themes.github;
|
||||
const darkCodeTheme = renderer.themes.dracula;
|
||||
|
||||
/** @type {import('@docusaurus/types').Config} */
|
||||
const config = {
|
||||
@@ -29,15 +30,32 @@ const config = {
|
||||
// to replace "en" with "zh-Hans".
|
||||
i18n: {
|
||||
defaultLocale: "en",
|
||||
locales: ["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: [
|
||||
[
|
||||
"classic",
|
||||
"@docusaurus/preset-classic",
|
||||
/** @type {import('@docusaurus/preset-classic').Options} */
|
||||
({
|
||||
docs: {
|
||||
path: "docs",
|
||||
routeBasePath: "/",
|
||||
sidebarPath: require.resolve("./sidebars.js"),
|
||||
// Please change this to your repo.
|
||||
@@ -49,6 +67,10 @@ const config = {
|
||||
],
|
||||
},
|
||||
blog: false,
|
||||
gtag: {
|
||||
trackingID: "G-NB9B8LW9W5",
|
||||
anonymizeIP: true,
|
||||
},
|
||||
}),
|
||||
],
|
||||
],
|
||||
@@ -71,6 +93,10 @@ const config = {
|
||||
position: "left",
|
||||
label: "Docs",
|
||||
},
|
||||
{
|
||||
type: "localeDropdown",
|
||||
position: "left",
|
||||
},
|
||||
{
|
||||
href: "https://github.com/run-llama/LlamaIndexTS",
|
||||
label: "GitHub",
|
||||
@@ -147,6 +173,9 @@ const config = {
|
||||
},
|
||||
],
|
||||
],
|
||||
markdown: {
|
||||
format: "detect",
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = config;
|
||||
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 27 KiB |
BIN
Binary file not shown.
|
After Width: | Height: | Size: 49 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 36 KiB |
@@ -0,0 +1 @@
|
||||
../../../../docs/api
|
||||
@@ -0,0 +1,86 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
# المفاهيم على المستوى العالي
|
||||
|
||||
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
|
||||
|
||||
يساعدك LlamaIndex.TS في بناء تطبيقات قائمة على LLM (مثل Q&A و chatbot) على بيانات مخصصة.
|
||||
|
||||
في هذا الدليل عن المفاهيم على المستوى العالي، ستتعلم:
|
||||
|
||||
- كيف يمكن لـ LLM الإجابة على الأسئلة باستخدام بياناتك الخاصة.
|
||||
- المفاهيم الرئيسية والوحدات في LlamaIndex.TS لبناء خط أنابيب الاستعلام الخاص بك.
|
||||
|
||||
## الإجابة على الأسئلة عبر بياناتك
|
||||
|
||||
يستخدم LlamaIndex طريقة مكونة من مرحلتين عند استخدام LLM مع بياناتك:
|
||||
|
||||
1. **مرحلة الفهرسة**: إعداد قاعدة المعرفة، و
|
||||
2. **مرحلة الاستعلام**: استرداد السياق ذي الصلة من المعرفة لمساعدة LLM في الاستجابة لسؤال
|
||||
|
||||

|
||||
|
||||
تُعرف هذه العملية أيضًا باسم "استرجاع معزز للتوليد" (RAG).
|
||||
|
||||
يوفر LlamaIndex.TS أدوات أساسية لجعل كلا المرحلتين سهلتين للغاية.
|
||||
|
||||
دعنا نستكشف كل مرحلة بالتفصيل.
|
||||
|
||||
### مرحلة الفهرسة
|
||||
|
||||
يساعدك LlamaIndex.TS في إعداد قاعدة المعرفة باستخدام مجموعة من موصلات البيانات والفهارس.
|
||||
|
||||

|
||||
|
||||
[**محمّلات البيانات**](./modules/high_level/data_loader.md):
|
||||
موصل البيانات (أي `Reader`) يقوم بتجميع البيانات من مصادر بيانات مختلفة وتنسيقات بيانات مختلفة في تمثيل بسيط للـ `Document` (نص وبيانات تعريفية بسيطة).
|
||||
|
||||
[**المستندات / العقد**](./modules/high_level/documents_and_nodes.md): المستند هو حاوية عامة حول أي مصدر بيانات - على سبيل المثال، ملف PDF، نتائج واجهة برمجة التطبيقات، أو بيانات استرداد من قاعدة بيانات. العقد هو الوحدة الذرية للبيانات في LlamaIndex ويمثل "قطعة" من المستند الأصلي. إنه تمثيل غني يتضمن بيانات تعريفية وعلاقات (مع عقد أخرى) لتمكين عمليات الاسترجاع الدقيقة والتعبيرية.
|
||||
|
||||
[**فهارس البيانات**](./modules/high_level/data_index.md):
|
||||
بمجرد أن تقوم بتجميع بياناتك، يساعدك LlamaIndex في فهرسة البيانات في تنسيق سهل الاسترداد.
|
||||
|
||||
تحت الغطاء، يقوم LlamaIndex بتحليل المستندات الخام إلى تمثيلات وسيطة، وحساب تضمينات الناقلات، وتخزين بياناتك في الذاكرة أو على القرص.
|
||||
|
||||
"
|
||||
|
||||
### مرحلة الاستعلام
|
||||
|
||||
في مرحلة الاستعلام، يقوم خط الأنابيب للاستعلام بجلب السياق الأكثر صلة بناءً على استعلام المستخدم،
|
||||
ويمرر ذلك إلى LLM (جنبًا إلى جنب مع الاستعلام) لتوليد استجابة.
|
||||
|
||||
يمنح ذلك LLM معرفة محدثة ليست موجودة في بيانات التدريب الأصلية لديه،
|
||||
(مما يقلل أيضًا من الهلوسة).
|
||||
|
||||
التحدي الرئيسي في مرحلة الاستعلام هو الاسترجاع والتنسيق والاستدلال عبر قواعد المعرفة (المحتملة).
|
||||
|
||||
يوفر LlamaIndex وحدات قابلة للتركيب تساعدك في بناء ودمج خطوط أنابيب RAG لـ Q&A (محرك الاستعلام)، chatbot (محرك الدردشة)، أو كجزء من وكيل.
|
||||
|
||||
يمكن تخصيص هذه الكتل البنائية لتعكس تفضيلات التصنيف، وكذلك تركيبها للاستدلال عبر عدة قواعد معرفة بطريقة منظمة.
|
||||
|
||||

|
||||
|
||||
#### الكتل الأساسية
|
||||
|
||||
[**مسترجعات**](./modules/low_level/retriever.md):
|
||||
يحدد المسترجع كيفية استرجاع السياق ذي الصلة بكفاءة من قاعدة المعرفة (أي الفهرس) عند إعطاء استعلام.
|
||||
تختلف منطق الاسترجاع المحددة حسب الفهارس المختلفة، والأكثر شيوعًا هو الاسترجاع الكثيف ضد فهرس الناقل.
|
||||
|
||||
[**مركبات الاستجابة**](./modules/low_level/response_synthesizer.md):
|
||||
تقوم مركبة الاستجابة بتوليد استجابة من LLM باستخدام استعلام المستخدم ومجموعة معينة من أجزاء النص المسترجعة.
|
||||
|
||||
"
|
||||
|
||||
#### خطوط الأنابيب
|
||||
|
||||
[**محركات الاستعلام**](./modules/high_level/query_engine.md):
|
||||
محرك الاستعلام هو خط أنابيب شامل يتيح لك طرح الأسئلة على بياناتك.
|
||||
يأخذ استعلامًا بلغة طبيعية ويعيد استجابة، جنبًا إلى جنب مع السياق المرجعي المسترجع والممرر إلى LLM.
|
||||
|
||||
[**محركات الدردشة**](./modules/high_level/chat_engine.md):
|
||||
محرك الدردشة هو خط أنابيب شامل لإجراء محادثة مع بياناتك
|
||||
(عدة تفاعلات بدلاً من سؤال وجواب واحد).
|
||||
|
||||
"
|
||||
@@ -0,0 +1,61 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
# أمثلة من البداية إلى النهاية
|
||||
|
||||
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
|
||||
|
||||
نقدم العديد من الأمثلة من البداية إلى النهاية باستخدام LlamaIndex.TS في المستودع
|
||||
|
||||
تحقق من الأمثلة أدناه أو جربها وأكملها في دقائق مع دروس تفاعلية على Github Codespace المقدمة من Dev-Docs [هنا](https://codespaces.new/team-dev-docs/lits-dev-docs-playground?devcontainer_path=.devcontainer%2Fjavascript_ltsquickstart%2Fdevcontainer.json):
|
||||
|
||||
## [محرك الدردشة](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/chatEngine.ts)
|
||||
|
||||
اقرأ ملفًا وتحدث عنه مع LLM.
|
||||
|
||||
## [فهرس الفيكتور](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/vectorIndex.ts)
|
||||
|
||||
إنشاء فهرس فيكتور واستعلامه. سيستخدم فهرس الفيكتور التضمينات لاسترداد أعلى k عقد ذات صلة. بشكل افتراضي ، يكون k الأعلى هو 2.
|
||||
|
||||
"
|
||||
|
||||
## [مؤشر الملخص](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/summaryIndex.ts)
|
||||
|
||||
إنشاء مؤشر قائمة واستعلامه. يستخدم هذا المثال أيضًا `LLMRetriever` ، الذي سيستخدم LLM لتحديد أفضل العقد لاستخدامها عند إنشاء الإجابة.
|
||||
|
||||
"
|
||||
|
||||
## [حفظ / تحميل فهرس](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/storageContext.ts)
|
||||
|
||||
إنشاء وتحميل فهرس ناقل. يحدث التخزين المؤقت على القرص تلقائيًا في LlamaIndex.TS بمجرد إنشاء كائن سياق التخزين.
|
||||
|
||||
"
|
||||
|
||||
## [فهرس الناقل المخصص](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/vectorIndexCustomize.ts)
|
||||
|
||||
إنشاء فهرس ناقل واستعلامه، مع تكوين `LLM` و `ServiceContext` و `similarity_top_k`.
|
||||
|
||||
"
|
||||
|
||||
## [OpenAI LLM](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/openai.ts)
|
||||
|
||||
أنشئ OpenAI LLM واستخدمه مباشرة للدردشة.
|
||||
|
||||
"
|
||||
|
||||
## [Llama2 DeuceLLM](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/llamadeuce.ts)
|
||||
|
||||
إنشاء Llama-2 LLM واستخدامه مباشرة للدردشة.
|
||||
|
||||
"
|
||||
|
||||
## [محرك استعلام الأسئلة الفرعية](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/subquestion.ts)
|
||||
|
||||
يستخدم `محرك استعلام الأسئلة الفرعية` الذي يقسم الاستعلامات المعقدة إلى أسئلة فرعية متعددة، ثم يجمع الاستجابة عبر الإجابات على جميع الأسئلة الفرعية.
|
||||
|
||||
"
|
||||
|
||||
## [وحدات منخفضة المستوى](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/lowlevel.ts)
|
||||
|
||||
يستخدم هذا المثال العديد من المكونات منخفضة المستوى، مما يزيل الحاجة إلى محرك استعلام فعلي. يمكن استخدام هذه المكونات في أي مكان، في أي تطبيق، أو تخصيصها وتصنيفها الفرعي لتلبية احتياجاتك الخاصة.
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
sidebar_position: 5
|
||||
---
|
||||
|
||||
# البيئات
|
||||
|
||||
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
|
||||
|
||||
يدعم LlamaIndex حاليًا رسميًا NodeJS 18 و NodeJS 20.
|
||||
|
||||
## NextJS App Router
|
||||
|
||||
إذا كنت تستخدم معالج الطرق / الوظائف الخادمة في NextJS App Router ، فستحتاج إلى استخدام وضع NodeJS:
|
||||
|
||||
```js
|
||||
export const runtime = "nodejs"; // الافتراضي
|
||||
```
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user