Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b145db3ff3 | |||
| e8952f3753 |
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"llamaindex": patch
|
||||
---
|
||||
|
||||
feat(qdrant): Add Qdrant Vector DB
|
||||
@@ -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",
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"llamaindex": patch
|
||||
---
|
||||
|
||||
Preview: Add ingestion pipeline (incl. different strategies to handle doc store duplicates)
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"create-llama": patch
|
||||
---
|
||||
|
||||
Add an option that allows the user to run the generated app
|
||||
@@ -0,0 +1,16 @@
|
||||
---
|
||||
"llamaindex": patch
|
||||
---
|
||||
|
||||
feat: use conditional exports
|
||||
|
||||
The benefit of conditional exports is we split the llamaindex into different files. This will improve the tree shake if you are building web apps.
|
||||
|
||||
This also requires node16 (see https://nodejs.org/api/packages.html#conditional-exports).
|
||||
|
||||
If you are seeing typescript issue `TS2724`('llamaindex' has no exported member named XXX):
|
||||
|
||||
1. update `moduleResolution` to `bundler` in `tsconfig.json`, more for the web applications like Next.js, and vite, but still works for ts-node or tsx.
|
||||
2. consider the ES module in your project, add `"type": "module"` into `package.json` and update `moduleResolution` to `node16` or `nodenext` in `tsconfig.json`.
|
||||
|
||||
We still support both cjs and esm, but you should update `tsconfig.json` to make the typescript happy.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"llamaindex": patch
|
||||
---
|
||||
|
||||
feat(extractors): add keyword extractor and base extractor
|
||||
@@ -1,16 +0,0 @@
|
||||
{
|
||||
"jsc": {
|
||||
"parser": {
|
||||
"syntax": "typescript",
|
||||
"decorators": true
|
||||
},
|
||||
"target": "esnext",
|
||||
"transform": {
|
||||
"decoratorVersion": "2022-03"
|
||||
}
|
||||
},
|
||||
"module": {
|
||||
"type": "commonjs",
|
||||
"ignoreDynamic": true
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,6 @@
|
||||
"ghcr.io/devcontainers/features/node:1": {},
|
||||
"ghcr.io/devcontainers-contrib/features/turborepo-npm:1": {},
|
||||
"ghcr.io/devcontainers-contrib/features/typescript:2": {},
|
||||
"ghcr.io/devcontainers-contrib/features/pnpm:2": {}
|
||||
}
|
||||
"ghcr.io/devcontainers-contrib/features/pnpm:2": {},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
module.exports = {
|
||||
root: true,
|
||||
// This tells ESLint to load the config from the package `eslint-config-custom`
|
||||
extends: ["custom"],
|
||||
settings: {
|
||||
next: {
|
||||
rootDir: ["apps/*/"],
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
"max-params": ["error", 4],
|
||||
},
|
||||
ignorePatterns: ["dist/"],
|
||||
};
|
||||
@@ -1,2 +0,0 @@
|
||||
examples/readers/data/** binary
|
||||
examples/data/** binary
|
||||
@@ -1,46 +0,0 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: ""
|
||||
labels: bug
|
||||
assignees: ""
|
||||
---
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**To Reproduce**
|
||||
Code to reproduce the behavior:
|
||||
|
||||
```ts
|
||||
// paste the code here
|
||||
```
|
||||
|
||||
**Expected behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**Screenshots**
|
||||
If applicable, add screenshots to help explain your problem.
|
||||
|
||||
**Desktop (please complete the following information):**
|
||||
|
||||
- OS: [e.g. macOS, Linux]
|
||||
- JS Runtime / Framework / Bundler (select all applicable)
|
||||
- [ ] Node.js
|
||||
- [ ] Deno
|
||||
- [ ] Bun
|
||||
- [ ] Next.js
|
||||
- [ ] ESBuild
|
||||
- [ ] Rollup
|
||||
- [ ] Webpack
|
||||
- [ ] Turbopack
|
||||
- [ ] Vite
|
||||
- [ ] Waku
|
||||
- [ ] Edge Runtime
|
||||
- [ ] AWS Lambda
|
||||
- [ ] Cloudflare Worker
|
||||
- [ ] Others (please elaborate on this)
|
||||
- Version [e.g. 22]
|
||||
|
||||
**Additional context**
|
||||
Add any other context about the problem here.
|
||||
@@ -0,0 +1,62 @@
|
||||
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: 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
|
||||
@@ -8,17 +8,14 @@ on:
|
||||
branches:
|
||||
- main
|
||||
|
||||
env:
|
||||
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
|
||||
TURBO_TEAM: ${{ vars.TURBO_TEAM }}
|
||||
TURBO_REMOTE_ONLY: true
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
- uses: pnpm/action-setup@v2
|
||||
with:
|
||||
version: latest
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
name: Publish Preview
|
||||
on: [pull_request]
|
||||
|
||||
env:
|
||||
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
|
||||
TURBO_TEAM: ${{ vars.TURBO_TEAM }}
|
||||
TURBO_REMOTE_ONLY: true
|
||||
|
||||
jobs:
|
||||
pre_release:
|
||||
name: Pre Release
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout Repo
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: "pnpm"
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Build
|
||||
run: pnpm run build
|
||||
|
||||
- name: Pre Release
|
||||
run: pnpx pkg-pr-new publish --pnpm ./packages/* ./packages/providers/* ./packages/providers/storage/*
|
||||
@@ -1,37 +0,0 @@
|
||||
name: Publish to GitHub Releases
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "llamaindex@*"
|
||||
|
||||
jobs:
|
||||
build-and-publish:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Repo
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: "pnpm"
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Build tarball
|
||||
run: |
|
||||
pnpm pack
|
||||
working-directory: packages/llamaindex
|
||||
|
||||
- name: Create release
|
||||
uses: ncipollo/release-action@v1
|
||||
with:
|
||||
artifacts: "packages/llamaindex/llamaindex-*.tgz"
|
||||
name: Release ${{ github.ref }}
|
||||
bodyFile: "packages/llamaindex/CHANGELOG.md"
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -1,70 +0,0 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
concurrency: ${{ github.workflow }}-${{ github.ref }}
|
||||
|
||||
jobs:
|
||||
release:
|
||||
name: Release
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Repo
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: "pnpm"
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Add auth token to .npmrc file
|
||||
run: |
|
||||
cat << EOF >> ".npmrc"
|
||||
//registry.npmjs.org/:_authToken=$NPM_TOKEN
|
||||
EOF
|
||||
env:
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
|
||||
- name: Get changeset status
|
||||
id: get-changeset-status
|
||||
run: |
|
||||
pnpm changeset status --output .changeset/status.json
|
||||
new_version=$(jq -r '.releases[] | select(.name == "llamaindex") | .newVersion' < .changeset/status.json)
|
||||
rm -v .changeset/status.json
|
||||
echo "new-version=${new_version}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Create Release Pull Request or Publish to npm
|
||||
id: changesets
|
||||
uses: changesets/action@v1
|
||||
with:
|
||||
commit: Release ${{ steps.get-changeset-status.outputs.new-version }}
|
||||
title: Release ${{ steps.get-changeset-status.outputs.new-version }}
|
||||
# update version PR with the latest changesets
|
||||
version: pnpm new-version
|
||||
# build package and call changeset publish
|
||||
publish: pnpm release
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
|
||||
# Refs: https://github.com/changesets/changesets/issues/421
|
||||
- name: Update lock file
|
||||
continue-on-error: true
|
||||
run: pnpm install --lockfile-only
|
||||
|
||||
- name: Commit lock file
|
||||
continue-on-error: true
|
||||
uses: stefanzweifel/git-auto-commit-action@v5
|
||||
with:
|
||||
commit_message: "chore: update lock file"
|
||||
branch: changeset-release/main
|
||||
file_pattern: "pnpm-lock.yaml"
|
||||
@@ -1,68 +1,18 @@
|
||||
name: Run Tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
POSTGRES_HOST_AUTH_METHOD: trust
|
||||
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
|
||||
TURBO_TEAM: ${{ vars.TURBO_TEAM }}
|
||||
TURBO_REMOTE_ONLY: true
|
||||
on: [push, pull_request]
|
||||
|
||||
jobs:
|
||||
e2e:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
node-version: [20.x, 22.x, 23.x]
|
||||
name: E2E on Node.js ${{ matrix.node-version }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: ankane/setup-postgres@v1
|
||||
with:
|
||||
database: llamaindex_node_test
|
||||
dev-files: true
|
||||
- run: |
|
||||
cd /tmp
|
||||
git clone --branch v0.7.0 https://github.com/pgvector/pgvector.git
|
||||
cd pgvector
|
||||
make
|
||||
sudo make install
|
||||
- uses: pnpm/action-setup@v4
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: "pnpm"
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
- name: Run E2E Tests
|
||||
run: pnpm run e2e
|
||||
|
||||
test:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
node-version: [20.x, 22.x, 23.x]
|
||||
name: Test on Node.js ${{ matrix.node-version }}
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
- uses: pnpm/action-setup@v2
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
node-version-file: ".nvmrc"
|
||||
cache: "pnpm"
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
@@ -73,7 +23,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
- uses: pnpm/action-setup@v2
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
@@ -83,135 +33,6 @@ jobs:
|
||||
run: pnpm install
|
||||
- name: Build
|
||||
run: pnpm run build
|
||||
working-directory: ./packages/core
|
||||
- name: Run Type Check
|
||||
run: pnpm run type-check
|
||||
- name: Run Circular Dependency Check
|
||||
run: pnpm run circular-check
|
||||
e2e-npm:
|
||||
runs-on: ubuntu-latest
|
||||
name: Test using packages with npm
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
- name: Build packages
|
||||
run: pnpm run build
|
||||
- name: Pack packages
|
||||
run: |
|
||||
pnpm pack --pack-destination ${{ runner.temp }} -C packages/llamaindex
|
||||
pnpm pack --pack-destination ${{ runner.temp }} -C packages/workflow
|
||||
- name: Install packed packages
|
||||
run: npm add ${{ runner.temp }}/*.tgz
|
||||
working-directory: e2e/npm
|
||||
- name: Run tests
|
||||
run: npm test
|
||||
working-directory: e2e/npm
|
||||
e2e-llamaindex-examples:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
packages:
|
||||
- cloudflare-worker-agent
|
||||
- nextjs-agent
|
||||
- nextjs-edge-runtime
|
||||
- nextjs-node-runtime
|
||||
- waku-query-engine
|
||||
- llama-parse-browser
|
||||
- vite-import-llamaindex
|
||||
runs-on: ubuntu-latest
|
||||
name: Build LlamaIndex Example (${{ matrix.packages }})
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: "pnpm"
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
- name: Build llamaindex
|
||||
run: pnpm run build
|
||||
- name: Build ${{ matrix.packages }}
|
||||
run: pnpm run build
|
||||
working-directory: e2e/examples/${{ matrix.packages }}
|
||||
|
||||
size-limit:
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event_name == 'pull_request'
|
||||
name: Size Limit
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: "pnpm"
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
- name: Build llamaindex
|
||||
run: pnpm run build
|
||||
- uses: andresz1/size-limit-action@94bc357df29c36c8f8d50ea497c3e225c3c95d1d
|
||||
with:
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
directory: e2e/examples/vite-import-llamaindex
|
||||
skip_step: "install"
|
||||
build_script: build
|
||||
package_manager: pnpm
|
||||
|
||||
typecheck-examples:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: "pnpm"
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
- name: Build
|
||||
run: pnpm run build
|
||||
- name: Copy examples
|
||||
run: rsync -rv --exclude=node_modules ./examples ${{ runner.temp }}
|
||||
- name: Pack packages
|
||||
run: |
|
||||
for dir in packages/*; do
|
||||
if [ -d "$dir" ] && [ -f "$dir/package.json" ] && [[ ! "$dir" =~ autotool ]]; then
|
||||
echo "Packing $dir"
|
||||
pnpm pack --pack-destination ${{ runner.temp }} -C $dir
|
||||
else
|
||||
echo "Skipping $dir, no package.json found"
|
||||
fi
|
||||
done
|
||||
- name: Pack provider packages
|
||||
run: |
|
||||
for dir in packages/providers/* packages/providers/storage/*; do
|
||||
if [ -d "$dir" ] && [ -f "$dir/package.json" ]; then
|
||||
echo "Packing $dir"
|
||||
pnpm pack --pack-destination ${{ runner.temp }} -C $dir
|
||||
else
|
||||
echo "Skipping $dir, no package.json found"
|
||||
fi
|
||||
done
|
||||
- name: Install
|
||||
run: npm add ${{ runner.temp }}/*.tgz
|
||||
working-directory: ${{ runner.temp }}/examples
|
||||
- name: Run Type Check
|
||||
run: npx tsc --project ./tsconfig.json
|
||||
working-directory: ${{ runner.temp }}/examples
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: failure()
|
||||
with:
|
||||
name: build-dist
|
||||
path: |
|
||||
${{ runner.temp }}/*.tgz
|
||||
if-no-files-found: error
|
||||
|
||||
@@ -44,10 +44,6 @@ test-results/
|
||||
playwright-report/
|
||||
blob-report/
|
||||
playwright/.cache/
|
||||
.tsbuildinfo
|
||||
|
||||
# intellij
|
||||
**/.idea
|
||||
|
||||
# generated API
|
||||
packages/cloud/src/client
|
||||
|
||||
@@ -1 +1,6 @@
|
||||
pnpm run lint-staged
|
||||
#!/usr/bin/env sh
|
||||
. "$(dirname -- "$0")/_/husky.sh"
|
||||
|
||||
pnpm format
|
||||
pnpm lint
|
||||
npx lint-staged
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env sh
|
||||
. "$(dirname -- "$0")/_/husky.sh"
|
||||
|
||||
pnpm test
|
||||
@@ -1,5 +1 @@
|
||||
auto-install-peers = true
|
||||
enable-pre-post-scripts = true
|
||||
prefer-workspace-packages = true
|
||||
save-workspace-protocol = true
|
||||
link-workspace-packages = true
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
apps/docs/i18n
|
||||
apps/docs/docs/api
|
||||
pnpm-lock.yaml
|
||||
lib/
|
||||
dist/
|
||||
.docusaurus/
|
||||
.source/
|
||||
# prttier doesn't support mdx3 we are using
|
||||
*.mdx
|
||||
packages/server/server/
|
||||
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"jsc": {
|
||||
"parser": {
|
||||
"syntax": "typescript",
|
||||
"decorators": true
|
||||
},
|
||||
"target": "esnext",
|
||||
"transform": {
|
||||
"decoratorVersion": "2022-03"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,9 +10,8 @@
|
||||
"name": "Debug Example",
|
||||
"skipFiles": ["<node_internals>/**"],
|
||||
"runtimeExecutable": "pnpm",
|
||||
"console": "integratedTerminal",
|
||||
"cwd": "${workspaceFolder}/examples",
|
||||
"runtimeArgs": ["npx", "tsx", "${file}"]
|
||||
"runtimeArgs": ["ts-node", "${fileBasename}"]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
LlamaIndexTS
|
||||
@@ -5,15 +5,8 @@
|
||||
"[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"
|
||||
},
|
||||
"prettier.prettierPath": "./node_modules/prettier",
|
||||
"prettier.configPath": "prettier.config.mjs"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## Development Commands
|
||||
|
||||
This project uses pnpm as the package manager and Turbo for build orchestration:
|
||||
|
||||
- `pnpm install` - Install all dependencies
|
||||
- `pnpm build` - Build all packages using Turbo
|
||||
- `pnpm dev` - Start development mode for all packages
|
||||
- `pnpm test` - Run all unit tests
|
||||
- `pnpm e2e` - Run end-to-end tests
|
||||
- `pnpm lint` - Run ESLint across all packages
|
||||
- `pnpm type-check` - Run TypeScript type checking across workspace
|
||||
- `pnpm format` - Check code formatting with Prettier
|
||||
- `pnpm format:write` - Auto-fix formatting issues
|
||||
- `pnpm circular-check` - Check for circular dependencies using madge
|
||||
|
||||
For individual package development:
|
||||
|
||||
- `turbo run build --filter="@llamaindex/core"` - Build specific package
|
||||
- `turbo run test --filter="@llamaindex/core"` - Test specific package
|
||||
- Navigate to specific package directory and run `pnpm test` for focused testing
|
||||
- `pnpm clean` - Remove all build artifacts and node_modules across workspace
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
LlamaIndex.TS is a TypeScript data framework for LLM applications organized as a pnpm monorepo with multiple runtime environment support (Node.js, Deno, Bun, Vercel Edge, Cloudflare Workers).
|
||||
|
||||
### Package Structure
|
||||
|
||||
**Core Packages:**
|
||||
|
||||
- `packages/core/` - Abstract base classes and interfaces for all runtime environments
|
||||
- `packages/llamaindex/` - Main package that aggregates core functionality
|
||||
- `packages/env/` - Environment-specific compatibility layers for different JS runtimes
|
||||
|
||||
**Provider Packages (`packages/providers/`):**
|
||||
|
||||
- LLM providers: `openai/`, `anthropic/`, `ollama/`, `google/`, `groq/`, etc.
|
||||
- Vector stores: `storage/pinecone/`, `storage/chroma/`, `storage/qdrant/`, etc.
|
||||
- Embeddings: Various embedding providers integrated within LLM packages
|
||||
- Readers: `assemblyai/`, `discord/`, `notion/` for data ingestion
|
||||
|
||||
**Specialized Packages:**
|
||||
|
||||
- `packages/cloud/` - LlamaCloud integration for managed services
|
||||
- `packages/tools/` - Function calling tools and utilities
|
||||
- `packages/workflow/` - Agent workflow orchestration
|
||||
- `packages/readers/` - File format readers (PDF, DOCX, etc.)
|
||||
|
||||
### Key Architectural Patterns
|
||||
|
||||
**Runtime Abstraction:** Core functionality is runtime-agnostic, with environment-specific implementations in separate entry points (`index.ts`, `index.edge.ts`, `index.workerd.ts`).
|
||||
|
||||
**Provider Pattern:** LLMs, embeddings, and vector stores implement common interfaces from `@llamaindex/core`, allowing easy swapping between providers.
|
||||
|
||||
**Modular Design:** Each provider is a separate package to minimize bundle size - users install only what they need.
|
||||
|
||||
**Data Flow:** Document → NodeParser → Embedding → VectorStore → Retriever → QueryEngine → Response
|
||||
|
||||
### Core Components
|
||||
|
||||
- **Agents and Workflows:** Abstractions for building agentic workflows and agents in `packages/workflow`
|
||||
- **Chat Engines:** Conversational interfaces in `core/chat-engine/`
|
||||
- **Query Engines:** Document querying with retrieval in `core/query-engine/`
|
||||
- **Indices:** VectorStoreIndex, SummaryIndex, KeywordTable in `llamaindex/indices/`
|
||||
- **Node Parsers:** Text splitting and chunking in `core/node-parser/`
|
||||
- **Ingestion Pipeline:** Document processing workflows in `llamaindex/ingestion/`
|
||||
- **Storage:** Chat stores, document stores, index stores, and KV stores in `core/storage/`
|
||||
|
||||
### Deprecated Components
|
||||
|
||||
- **Agents:** ReAct and function calling agents in `core/agent/` and `llamaindex/agent/`
|
||||
|
||||
### Testing Structure
|
||||
|
||||
- Unit tests in each package's `tests/` directory
|
||||
- E2E tests in `e2e/` directory with runtime-specific examples
|
||||
- Tests depend on build artifacts, so always run `pnpm build` before testing
|
||||
|
||||
### Multi-Runtime Support
|
||||
|
||||
The codebase supports multiple JavaScript runtimes through conditional exports and separate entry points. When making changes, consider compatibility across Node.js, Deno, Bun, and edge runtimes.
|
||||
|
||||
### Development Notes
|
||||
|
||||
- The project uses Husky for git hooks with lint-staged for pre-commit formatting and linting
|
||||
- All packages use bunchee for building with dual CJS/ESM support
|
||||
- Core package exports are organized as sub-modules (e.g., `@llamaindex/core/llms`, `@llamaindex/core/embeddings`)
|
||||
- Always run `pnpm build` before running tests, as tests depend on build artifacts
|
||||
@@ -2,164 +2,79 @@
|
||||
|
||||
## Structure
|
||||
|
||||
LlamaIndex.TS uses pnpm monorepo.
|
||||
This is a monorepo built with Turborepo
|
||||
|
||||
We recommend you to understand the basics of Node.js, TypeScript, pnpm, and of course, LLM before contributing.
|
||||
Right now there are two packages of importance:
|
||||
|
||||
There are some important folders in the repository:
|
||||
packages/core which is the main NPM library llamaindex
|
||||
|
||||
- `packages/*`: Contains the source code of the packages. Each package is a separate npm package.
|
||||
- `llamaindex`: The starter package for LlamaIndex.TS, which contains the all sub-packages.
|
||||
- `core`: The core package of LlamaIndex.TS, which contains the abstract classes and interfaces. It is designed for
|
||||
all JS runtime environments.
|
||||
- `env`: The environment package of LlamaIndex.TS, which contains the environment-specific classes and interfaces. It
|
||||
includes compatibility layers for Node.js, Deno, Vercel Edge Runtime, Cloudflare Workers...
|
||||
- `providers/*`: The providers package of LlamaIndex.TS, which contains the providers for LLM and other services.
|
||||
- `apps/*`: The applications based on LlamaIndex.TS.
|
||||
- `next`: Our documentation website based on Next.js.
|
||||
- `examples`: The code examples of LlamaIndex.TS using Node.js.
|
||||
examples is where the demo code lives
|
||||
|
||||
### Turborepo docs
|
||||
|
||||
You can checkout how Turborepo works using the default [README-turborepo.md](/README-turborepo.md)
|
||||
|
||||
## Getting Started
|
||||
|
||||
Make sure you have Node.js LTS (Long-term Support) installed. You can check your Node.js version by running:
|
||||
Install NodeJS. Preferably v18 using nvm or n.
|
||||
|
||||
Inside the LlamaIndexTS directory:
|
||||
|
||||
```shell
|
||||
node -v
|
||||
# v22.x.x
|
||||
```
|
||||
|
||||
### Use pnpm
|
||||
|
||||
```shell
|
||||
npm install -g pnpm
|
||||
```
|
||||
|
||||
### Install dependencies
|
||||
|
||||
```shell
|
||||
npm i -g pnpm ts-node
|
||||
pnpm install
|
||||
pnpm install -g tsx
|
||||
```
|
||||
|
||||
### Build the packages
|
||||
Note: we use pnpm in this repo, which has a lot of the same functionality and CLI options as npm but it does do some things better in a monorepo, like centralizing dependencies and caching.
|
||||
|
||||
To build all packages, run:
|
||||
PNPM's has documentation on its [workspace feature](https://pnpm.io/workspaces) and Turborepo had some [useful documentation also](https://turbo.build/repo/docs/core-concepts/monorepos/running-tasks).
|
||||
|
||||
```shell
|
||||
pnpm build
|
||||
### Running Typescript
|
||||
|
||||
When we publish to NPM we will have a tsc compiled version of the library in JS. For now, the easiest thing to do is use ts-node.
|
||||
|
||||
### Test cases
|
||||
|
||||
To run them, run
|
||||
|
||||
```
|
||||
pnpm run test
|
||||
```
|
||||
|
||||
### Start Developing
|
||||
To write new test cases write them in [packages/core/src/tests](/packages/core/src/tests)
|
||||
|
||||
You can launch the package in dev-mode by running:
|
||||
We use Jest https://jestjs.io/ to write our test cases. Jest comes with a bunch of built in assertions using the expect function: https://jestjs.io/docs/expect
|
||||
|
||||
```shell
|
||||
pnpm dev
|
||||
### Demo applications
|
||||
|
||||
There is an existing ["example"](/examples/README.md) demos folder with mainly NodeJS scripts. Feel free to add additional demos to that folder. If you would like to try out your changes in the core package with a new demo, you need to run the build command in the README.
|
||||
|
||||
You can create new demo applications in the apps folder. Just run pnpm init in the folder after you create it to create its own package.json
|
||||
|
||||
### Installing packages
|
||||
|
||||
To install packages for a specific package or demo application, run
|
||||
|
||||
```
|
||||
pnpm add [NPM Package] --filter [package or application i.e. core or docs]
|
||||
```
|
||||
|
||||
This will use turbo to run all packages in watch-mode. This means you can make changes and have them automatically built.
|
||||
To install packages for every package or application run
|
||||
|
||||
If you want to customize what packages are built/watched, you can run turbo directly and adjust the filter:
|
||||
|
||||
```shell
|
||||
pnpm turbo run dev --filter="./packages/core" --concurrency=100
|
||||
```
|
||||
|
||||
In another terminal, you can write and run any script needed to quickly test your changes. For example:
|
||||
|
||||
```typescript
|
||||
import { createMemory, staticBlock } from "@llamaindex/core/memory";
|
||||
|
||||
// Create memory with predefined context
|
||||
const memory = createMemory({
|
||||
memoryBlocks: [
|
||||
staticBlock({
|
||||
content:
|
||||
"The user is a software engineer who loves TypeScript and LlamaIndex.",
|
||||
messageRole: "system",
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
async function main() {
|
||||
const result = await memory.getLLM();
|
||||
console.log(result);
|
||||
}
|
||||
|
||||
void main().catch(console.error);
|
||||
pnpm add -w [NPM Package]
|
||||
```
|
||||
|
||||
And run it with:
|
||||
|
||||
```shell
|
||||
pnpm exec tsx my_script.ts
|
||||
```
|
||||
|
||||
This flow allows you to easily test your changes without having to build the entire project.
|
||||
|
||||
Once you are happy with your changes, be sure to add tests (and confirm existing tests are passing!).
|
||||
|
||||
### Run tests
|
||||
|
||||
#### Unit tests
|
||||
|
||||
After build, to run all unit tests, call:
|
||||
|
||||
```shell
|
||||
pnpm test
|
||||
```
|
||||
|
||||
Unit tests are located in the `tests` folder of each package. They are using their own package (e.g. `@llamaindex/core-tests` for `@llamaindex/core`). The tests are importing the package under test and the test package is not published.
|
||||
|
||||
#### E2E tests
|
||||
|
||||
To run all E2E tests, call:
|
||||
|
||||
```shell
|
||||
pnpm e2e
|
||||
```
|
||||
|
||||
All E2E tests are in the `e2e` folder.
|
||||
|
||||
### Docs
|
||||
|
||||
See the [docs](./apps/next/README.md) for more information.
|
||||
To contribute to the docs, go to the docs website folder and run the Docusaurus instance.
|
||||
|
||||
## Adding a new package
|
||||
|
||||
Please follow these steps to add a new package:
|
||||
|
||||
1. Only add new packages to the `packages/providers` folder.
|
||||
2. Use the `package.json` and `tsconfig.json` of an existing packages as template.
|
||||
3. Reference your new package in the root `tsconfig.json` file
|
||||
4. Add your package to the `examples/package.json` file if you add a new example.
|
||||
|
||||
## Before sending a PR
|
||||
|
||||
Before sending a PR, make sure of the following:
|
||||
|
||||
1. Tests are all running and you added meaningful tests for your change.
|
||||
2. If you have a new feature, document it in the `apps/next` docs folder.
|
||||
3. If you have a new feature, add a new example in the `examples` folder.
|
||||
4. You have a descriptive changeset for each PR:
|
||||
|
||||
### Bumping the versions of packages you've modified
|
||||
|
||||
We use [changesets](https://github.com/changesets/changesets) for managing versions and changelogs. To create a new
|
||||
changeset, run in the root folder:
|
||||
|
||||
```shell
|
||||
pnpm changeset
|
||||
```bash
|
||||
cd apps/docs
|
||||
pnpm install
|
||||
pnpm start
|
||||
```
|
||||
|
||||
You will be prompted to choose what packages need their versions bumped, and what kind of bump (major, minor or patch) is needed. Once you carry out this operation, the bumping will be automatic after the PR is merged.
|
||||
That should start a webserver which will serve the docs on https://localhost:3000
|
||||
|
||||
## Publishing (maintainers only)
|
||||
|
||||
The [Release Github Action](.github/workflows/release.yml) is automatically generating and updating a
|
||||
PR called "Release {version}".
|
||||
|
||||
This PR will update the `package.json` and `CHANGELOG.md` files of each package according to
|
||||
the current changesets in the [.changeset](.changeset) folder.
|
||||
|
||||
If this PR is merged it will automatically add version tags to the repository and publish the updated packages to NPM.
|
||||
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.
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
# Turborepo starter
|
||||
|
||||
This is an official starter Turborepo.
|
||||
|
||||
## Using this example
|
||||
|
||||
Run the following command:
|
||||
|
||||
```sh
|
||||
npx create-turbo@latest
|
||||
```
|
||||
|
||||
## What's inside?
|
||||
|
||||
This Turborepo includes the following packages/apps:
|
||||
|
||||
### Apps and Packages
|
||||
|
||||
- `docs`: a [Next.js](https://nextjs.org/) app
|
||||
- `web`: another [Next.js](https://nextjs.org/) app
|
||||
- `ui`: a stub React component library shared by both `web` and `docs` applications
|
||||
- `eslint-config-custom`: `eslint` configurations (includes `eslint-config-next` and `eslint-config-prettier`)
|
||||
- `tsconfig`: `tsconfig.json`s used throughout the monorepo
|
||||
|
||||
Each package/app is 100% [TypeScript](https://www.typescriptlang.org/).
|
||||
|
||||
### Utilities
|
||||
|
||||
This Turborepo has some additional tools already setup for you:
|
||||
|
||||
- [TypeScript](https://www.typescriptlang.org/) for static type checking
|
||||
- [ESLint](https://eslint.org/) for code linting
|
||||
- [Prettier](https://prettier.io) for code formatting
|
||||
|
||||
### Build
|
||||
|
||||
To build all apps and packages, run the following command:
|
||||
|
||||
```
|
||||
cd my-turborepo
|
||||
pnpm build
|
||||
```
|
||||
|
||||
### Develop
|
||||
|
||||
To develop all apps and packages, run the following command:
|
||||
|
||||
```
|
||||
cd my-turborepo
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
### Remote Caching
|
||||
|
||||
Turborepo can use a technique known as [Remote Caching](https://turbo.build/repo/docs/core-concepts/remote-caching) to share cache artifacts across machines, enabling you to share build caches with your team and CI/CD pipelines.
|
||||
|
||||
By default, Turborepo will cache locally. To enable Remote Caching you will need an account with Vercel. If you don't have an account you can [create one](https://vercel.com/signup), then enter the following commands:
|
||||
|
||||
```
|
||||
cd my-turborepo
|
||||
npx turbo login
|
||||
```
|
||||
|
||||
This will authenticate the Turborepo CLI with your [Vercel account](https://vercel.com/docs/concepts/personal-accounts/overview).
|
||||
|
||||
Next, you can link your Turborepo to your Remote Cache by running the following command from the root of your Turborepo:
|
||||
|
||||
```
|
||||
npx turbo link
|
||||
```
|
||||
|
||||
## Useful Links
|
||||
|
||||
Learn more about the power of Turborepo:
|
||||
|
||||
- [Tasks](https://turbo.build/repo/docs/core-concepts/monorepos/running-tasks)
|
||||
- [Caching](https://turbo.build/repo/docs/core-concepts/caching)
|
||||
- [Remote Caching](https://turbo.build/repo/docs/core-concepts/remote-caching)
|
||||
- [Filtering](https://turbo.build/repo/docs/core-concepts/monorepos/filtering)
|
||||
- [Configuration Options](https://turbo.build/repo/docs/reference/configuration)
|
||||
- [CLI Usage](https://turbo.build/repo/docs/reference/command-line-reference)
|
||||
@@ -1,18 +1,13 @@
|
||||
<p align="center">
|
||||
<img height="100" width="100" alt="LlamaIndex logo" src="https://ts.llamaindex.ai/square.svg" />
|
||||
</p>
|
||||
<h1 align="center">LlamaIndex.TS</h1>
|
||||
<h3 align="center">
|
||||
Data framework for your LLM application.
|
||||
</h3>
|
||||
# LlamaIndex.TS
|
||||
|
||||
[](https://www.npmjs.com/package/llamaindex)
|
||||
[](https://github.com/run-llama/LlamaIndexTS/blob/main/LICENSE)
|
||||
[](https://www.npmjs.com/package/llamaindex)
|
||||
[](https://www.npmjs.com/package/llamaindex)
|
||||
[](https://discord.com/invite/eN6D2HQ4aX)
|
||||
[](https://x.com/llama_index)
|
||||
|
||||
Use your own data with large language models (LLMs, OpenAI ChatGPT and others) in JS runtime environments with TypeScript support.
|
||||
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/
|
||||
|
||||
@@ -24,58 +19,58 @@ Try examples online:
|
||||
|
||||
LlamaIndex.TS aims to be a lightweight, easy to use set of libraries to help you integrate large language models into your applications with your own data.
|
||||
|
||||
## Compatibility
|
||||
## Getting started with an example:
|
||||
|
||||
### Multiple JS Environment Support
|
||||
LlamaIndex.TS requires Node v18 or higher. You can download it from https://nodejs.org or use https://nvm.sh (our preferred option).
|
||||
|
||||
LlamaIndex.TS supports multiple JS environments, including:
|
||||
In a new folder:
|
||||
|
||||
- Node.js >= 20 ✅
|
||||
- Deno ✅
|
||||
- Bun ✅
|
||||
- Nitro ✅
|
||||
- Vercel Edge Runtime ✅ (with some limitations)
|
||||
- Cloudflare Workers ✅ (with some limitations)
|
||||
|
||||
For now, browser support is limited due to the lack of support for [AsyncLocalStorage-like APIs](https://github.com/tc39/proposal-async-context)
|
||||
|
||||
### Supported LLMs:
|
||||
|
||||
- OpenAI LLms
|
||||
- Anthropic LLms
|
||||
- Groq LLMs
|
||||
- Llama2, Llama3, Llama3.1 LLMs
|
||||
- MistralAI LLMs
|
||||
- Fireworks LLMs
|
||||
- DeepSeek LLMs
|
||||
- ReplicateAI LLMs
|
||||
- TogetherAI LLMs
|
||||
- HuggingFace LLms
|
||||
- DeepInfra LLMs
|
||||
- Gemini LLMs
|
||||
|
||||
## Getting started
|
||||
|
||||
```shell
|
||||
npm install llamaindex
|
||||
```bash
|
||||
export OPENAI_API_KEY="sk-......" # Replace with your key from https://platform.openai.com/account/api-keys
|
||||
pnpm init
|
||||
pnpm install typescript
|
||||
pnpm exec tsc --init # if needed
|
||||
pnpm install llamaindex
|
||||
yarn add llamaindex
|
||||
pnpm install @types/node
|
||||
```
|
||||
|
||||
### Setup in Node.js, Deno, Bun, TypeScript...?
|
||||
Create the file example.ts
|
||||
|
||||
See our official document: https://ts.llamaindex.ai/docs/llamaindex/getting_started
|
||||
```ts
|
||||
// example.ts
|
||||
import fs from "fs/promises";
|
||||
import { Document, VectorStoreIndex } from "llamaindex";
|
||||
|
||||
### Adding provider packages
|
||||
async function main() {
|
||||
// Load essay from abramov.txt in Node
|
||||
const essay = await fs.readFile(
|
||||
"node_modules/llamaindex/examples/abramov.txt",
|
||||
"utf-8",
|
||||
);
|
||||
|
||||
In most cases, you'll also need to install provider packages to use LlamaIndexTS. These are for adding AI models, file readers for ingestion or storing documents, e.g. in vector databases.
|
||||
// Create Document object with essay
|
||||
const document = new Document({ text: essay });
|
||||
|
||||
For example, to use the OpenAI LLM, you would install the following package:
|
||||
// Split text and create embeddings. Store them in a VectorStoreIndex
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
```shell
|
||||
npm install @llamaindex/openai
|
||||
pnpm install @llamaindex/openai
|
||||
yarn add @llamaindex/openai
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine();
|
||||
const response = await queryEngine.query({
|
||||
query: "What did the author do in college?",
|
||||
});
|
||||
|
||||
// Output response
|
||||
console.log(response.toString());
|
||||
}
|
||||
|
||||
main();
|
||||
```
|
||||
|
||||
Then you can run it using
|
||||
|
||||
```bash
|
||||
pnpx ts-node example.ts
|
||||
```
|
||||
|
||||
## Playground
|
||||
@@ -84,13 +79,56 @@ Check out our NextJS playground at https://llama-playground.vercel.app/. The sou
|
||||
|
||||
## Core concepts for getting started:
|
||||
|
||||
See our documentation: https://ts.llamaindex.ai/docs/llamaindex/getting_started/concepts
|
||||
- [Document](/packages/core/src/Node.ts): A document represents a text file, PDF file or other contiguous piece of data.
|
||||
|
||||
- [Node](/packages/core/src/Node.ts): The basic data building block. Most commonly, these are parts of the document split into manageable pieces that are small enough to be fed into an embedding model and LLM.
|
||||
|
||||
- [Embedding](/packages/core/src/Embedding.ts): Embeddings are sets of floating point numbers which represent the data in a Node. By comparing the similarity of embeddings, we can derive an understanding of the similarity of two pieces of data. One use case is to compare the embedding of a question with the embeddings of our Nodes to see which Nodes may contain the data needed to answer that quesiton.
|
||||
|
||||
- [Indices](/packages/core/src/indices/): Indices store the Nodes and the embeddings of those nodes. QueryEngines retrieve Nodes from these Indices using embedding similarity.
|
||||
|
||||
- [QueryEngine](/packages/core/src/QueryEngine.ts): Query engines are what generate the query you put in and give you back the result. Query engines generally combine a pre-built prompt with selected Nodes from your Index to give the LLM the context it needs to answer your query.
|
||||
|
||||
- [ChatEngine](/packages/core/src/ChatEngine.ts): A ChatEngine helps you build a chatbot that will interact with your Indices.
|
||||
|
||||
- [SimplePrompt](/packages/core/src/Prompt.ts): A simple standardized function call definition that takes in inputs and formats them in a template literal. SimplePrompts can be specialized using currying and combined using other SimplePrompt functions.
|
||||
|
||||
## Note: NextJS:
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
```js
|
||||
// next.config.js
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
webpack: (config) => {
|
||||
config.resolve.alias = {
|
||||
...config.resolve.alias,
|
||||
sharp$: false,
|
||||
"onnxruntime-node$": false,
|
||||
};
|
||||
return config;
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = nextConfig;
|
||||
```
|
||||
|
||||
## Supported LLMs:
|
||||
|
||||
- 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
|
||||
|
||||
## Contributing:
|
||||
|
||||
Please see our [contributing guide](CONTRIBUTING.md) for more information.
|
||||
You are highly encouraged to contribute to LlamaIndex.TS!
|
||||
We are in the very early days of LlamaIndex.TS. If you’re interested in hacking on it with us check out our [contributing guide](/CONTRIBUTING.md)
|
||||
|
||||
## Community
|
||||
## Bugs? Questions?
|
||||
|
||||
Please join our Discord! https://discord.com/invite/eN6D2HQ4aX
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
# Dependencies
|
||||
/node_modules
|
||||
|
||||
# Production
|
||||
/build
|
||||
|
||||
# Generated files
|
||||
.docusaurus
|
||||
.cache-loader
|
||||
lib
|
||||
|
||||
# Misc
|
||||
.DS_Store
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
@@ -0,0 +1,47 @@
|
||||
# Website
|
||||
|
||||
This website is built using [Docusaurus 2](https://docusaurus.io/), a modern static website generator.
|
||||
|
||||
### Installation
|
||||
|
||||
```
|
||||
$ pnpm
|
||||
```
|
||||
|
||||
### Local Development
|
||||
|
||||
```
|
||||
$ pnpm start
|
||||
```
|
||||
|
||||
This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server.
|
||||
|
||||
However, the searchbar may not function with `yarn start`. Instead, run `yarn build` and launch a server:
|
||||
|
||||
```
|
||||
$ npx http-server ./build
|
||||
```
|
||||
|
||||
### Build
|
||||
|
||||
```
|
||||
$ pnpm build
|
||||
```
|
||||
|
||||
This command generates static content into the `build` directory and can be served using any static contents hosting service.
|
||||
|
||||
### Deployment
|
||||
|
||||
Using SSH:
|
||||
|
||||
```
|
||||
$ USE_SSH=true pnpm deploy
|
||||
```
|
||||
|
||||
Not using SSH:
|
||||
|
||||
```
|
||||
$ GIT_USER=<Your GitHub username> pnpm deploy
|
||||
```
|
||||
|
||||
If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch.
|
||||
@@ -0,0 +1,3 @@
|
||||
module.exports = {
|
||||
presets: [require.resolve("@docusaurus/core/lib/babel/preset")],
|
||||
};
|
||||
@@ -0,0 +1 @@
|
||||
api/
|
||||
|
Before Width: | Height: | Size: 27 KiB After Width: | Height: | Size: 27 KiB |
|
Before Width: | Height: | Size: 49 KiB After Width: | Height: | Size: 49 KiB |
|
Before Width: | Height: | Size: 36 KiB After Width: | Height: | Size: 36 KiB |
@@ -0,0 +1,78 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
# High-Level Concepts
|
||||
|
||||
LlamaIndex.TS helps you build LLM-powered applications (e.g. Q&A, chatbot) over custom data.
|
||||
|
||||
In this high-level concepts guide, you will learn:
|
||||
|
||||
- how an LLM can answer questions using your own data.
|
||||
- key concepts and modules in LlamaIndex.TS for composing your own query pipeline.
|
||||
|
||||
## Answering Questions Across Your Data
|
||||
|
||||
LlamaIndex uses a two stage method when using an LLM with your data:
|
||||
|
||||
1. **indexing stage**: preparing a knowledge base, and
|
||||
2. **querying stage**: retrieving relevant context from the knowledge to assist the LLM in responding to a question
|
||||
|
||||

|
||||
|
||||
This process is also known as Retrieval Augmented Generation (RAG).
|
||||
|
||||
LlamaIndex.TS provides the essential toolkit for making both steps super easy.
|
||||
|
||||
Let's explore each stage in detail.
|
||||
|
||||
### Indexing Stage
|
||||
|
||||
LlamaIndex.TS help you prepare the knowledge base with a suite of data connectors and indexes.
|
||||
|
||||

|
||||
|
||||
[**Data Loaders**](./modules/high_level/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.
|
||||
|
||||
[**Data Indexes**](./modules/high_level/data_index.md):
|
||||
Once you've ingested your data, LlamaIndex helps you index data into a format that's easy to retrieve.
|
||||
|
||||
Under the hood, LlamaIndex parses the raw documents into intermediate representations, calculates vector embeddings, and stores your data in-memory or to disk.
|
||||
|
||||
### Querying Stage
|
||||
|
||||
In the querying stage, the query pipeline retrieves the most relevant context given a user query,
|
||||
and pass that to the LLM (along with the query) to synthesize a response.
|
||||
|
||||
This gives the LLM up-to-date knowledge that is not in its original training data,
|
||||
(also reducing hallucination).
|
||||
|
||||
The key challenge in the querying stage is retrieval, orchestration, and reasoning over (potentially many) knowledge bases.
|
||||
|
||||
LlamaIndex provides composable modules that help you build and integrate RAG pipelines for Q&A (query engine), chatbot (chat engine), or as part of an agent.
|
||||
|
||||
These building blocks can be customized to reflect ranking preferences, as well as composed to reason over multiple knowledge bases in a structured way.
|
||||
|
||||

|
||||
|
||||
#### Building Blocks
|
||||
|
||||
[**Retrievers**](./modules/low_level/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):
|
||||
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):
|
||||
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):
|
||||
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,49 @@
|
||||
---
|
||||
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/examples/chatEngine.ts)
|
||||
|
||||
Read a file and chat about it with the LLM.
|
||||
|
||||
## [Vector Index](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/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/examples/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/examples/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/examples/vectorIndexCustomize.ts)
|
||||
|
||||
Create a vector index and query it, while also configuring the `LLM`, the `ServiceContext`, and the `similarity_top_k`.
|
||||
|
||||
## [OpenAI LLM](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/openai.ts)
|
||||
|
||||
Create an OpenAI LLM and directly use it for chat.
|
||||
|
||||
## [Llama2 DeuceLLM](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/llamadeuce.ts)
|
||||
|
||||
Create a Llama-2 LLM and directly use it for chat.
|
||||
|
||||
## [SubQuestionQueryEngine](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/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/examples/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.
|
||||
|
||||
## [JSON Entity Extraction](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/jsonExtract.ts)
|
||||
|
||||
Features OpenAI's chat API (using [`json_mode`](https://platform.openai.com/docs/guides/text-generation/json-mode)) to extract a JSON object from a sales call transcript.
|
||||
@@ -0,0 +1,15 @@
|
||||
---
|
||||
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
|
||||
```
|
||||
@@ -0,0 +1,63 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# Installation and Setup
|
||||
|
||||
Make sure you have NodeJS v18 or higher.
|
||||
|
||||
## Using create-llama
|
||||
|
||||
The easiest way to get started with LlamaIndex is by using `create-llama`. This CLI tool enables you to quickly start building a new LlamaIndex application, with everything set up for you.
|
||||
|
||||
Just run
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="1" label="npm" default>
|
||||
|
||||
```bash
|
||||
npx create-llama@latest
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="2" label="Yarn">
|
||||
|
||||
```bash
|
||||
yarn create llama
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="3" label="pnpm">
|
||||
|
||||
```bash
|
||||
pnpm create llama@latest
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
to get started. Once your app is generated, run
|
||||
|
||||
```bash npm2yarn
|
||||
npm run dev
|
||||
```
|
||||
|
||||
to start the development server. You can then visit [http://localhost:3000](http://localhost:3000) to see your app
|
||||
|
||||
## Installation from NPM
|
||||
|
||||
```bash npm2yarn
|
||||
npm install llamaindex
|
||||
```
|
||||
|
||||
### Environment variables
|
||||
|
||||
Our examples use OpenAI by default. You'll need to set up your Open AI key like so:
|
||||
|
||||
```bash
|
||||
export OPENAI_API_KEY="sk-......" # Replace with your key from https://platform.openai.com/account/api-keys
|
||||
```
|
||||
|
||||
If you want to have it automatically loaded every time, add it to your .zshrc/.bashrc.
|
||||
|
||||
WARNING: do not check in your OpenAI key into version control.
|
||||
@@ -0,0 +1,56 @@
|
||||
---
|
||||
sidebar_position: 0
|
||||
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://docs.llamaindex.ai/en/stable/)), LlamaIndex.TS offers core features in a simple package, optimized for usage with TypeScript.
|
||||
|
||||
## 🚀 Why LlamaIndex.TS?
|
||||
|
||||
At their core, LLMs offer a natural language interface between humans and inferred data. Widely available models come pre-trained on huge amounts of publicly available data, from Wikipedia and mailing lists to textbooks and source code.
|
||||
|
||||
Applications built on top of LLMs often require augmenting these models with private or domain-specific data. Unfortunately, that data can be distributed across siloed applications and data stores. It's behind APIs, in SQL databases, or trapped in PDFs and slide decks.
|
||||
|
||||
That's where **LlamaIndex.TS** comes in.
|
||||
|
||||
## 🦙 How can LlamaIndex.TS help?
|
||||
|
||||
LlamaIndex.TS provides the following tools:
|
||||
|
||||
- **Data loading** ingest your existing `.txt`, `.pdf`, `.csv`, `.md` and `.docx` data directly
|
||||
- **Data indexes** structure your data in intermediate representations that are easy and performant for LLMs to consume.
|
||||
- **Engines** provide natural language access to your data. For example:
|
||||
- Query engines are powerful retrieval interfaces for knowledge-augmented output.
|
||||
- Chat engines are conversational interfaces for multi-message, "back and forth" interactions with your data.
|
||||
|
||||
## 👨👩👧👦 Who is LlamaIndex for?
|
||||
|
||||
LlamaIndex.TS provides a core set of tools, essential for anyone building LLM apps with JavaScript and TypeScript.
|
||||
|
||||
Our high-level API allows beginner users to use LlamaIndex.TS to ingest and query their data.
|
||||
|
||||
For more complex applications, our lower-level APIs allow advanced users to customize and extend any module—data connectors, indices, retrievers, and query engines, to fit their needs.
|
||||
|
||||
## Getting Started
|
||||
|
||||
`npm install llamaindex`
|
||||
|
||||
Our documentation includes [Installation Instructions](./installation.mdx) and a [Starter Tutorial](./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).
|
||||
|
||||
## 🗺️ Ecosystem
|
||||
|
||||
To download or contribute, find LlamaIndex on:
|
||||
|
||||
- Github: https://github.com/run-llama/LlamaIndexTS
|
||||
- NPM: https://www.npmjs.com/package/llamaindex
|
||||
|
||||
## Community
|
||||
|
||||
Need help? Have a feature suggestion? Join the LlamaIndex community:
|
||||
|
||||
- Twitter: https://twitter.com/llama_index
|
||||
- Discord https://discord.gg/dGcwcsnxhU
|
||||
@@ -0,0 +1,3 @@
|
||||
label: "Modules"
|
||||
collapsed: false
|
||||
position: 5
|
||||
@@ -0,0 +1 @@
|
||||
label: High-Level Modules
|
||||
@@ -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)
|
||||
@@ -0,0 +1,23 @@
|
||||
---
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
# Index
|
||||
|
||||
An index is the basic container and organization for your data. LlamaIndex.TS supports two indexes:
|
||||
|
||||
- `VectorStoreIndex` - will send the top-k `Node`s to the LLM when generating a response. The default top-k is 2.
|
||||
- `SummaryIndex` - will send every `Node` in the index to the LLM in order to generate a response
|
||||
|
||||
```typescript
|
||||
import { Document, VectorStoreIndex } from "llamaindex";
|
||||
|
||||
const document = new Document({ text: "test" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [SummaryIndex](../../api/classes/SummaryIndex.md)
|
||||
- [VectorStoreIndex](../../api/classes/VectorStoreIndex.md)
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
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)
|
||||
@@ -0,0 +1,18 @@
|
||||
---
|
||||
sidebar_position: 0
|
||||
---
|
||||
|
||||
# Documents and Nodes
|
||||
|
||||
`Document`s and `Node`s are the basic building blocks of any index. While the API for these objects is similar, `Document` objects represent entire files, while `Node`s are smaller pieces of that original document, that are suitable for an LLM and Q&A.
|
||||
|
||||
```typescript
|
||||
import { Document } from "llamaindex";
|
||||
|
||||
document = new Document({ text: "text", metadata: { key: "val" } });
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [Document](../../api/classes/Document.md)
|
||||
- [TextNode](../../api/classes/TextNode.md)
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
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: "query string" });
|
||||
```
|
||||
|
||||
The `query` function also supports streaming, just add `stream: true` as an option:
|
||||
|
||||
```typescript
|
||||
const stream = await queryEngine.query({ query: "query string", stream: true });
|
||||
for await (const chunk of stream) {
|
||||
process.stdout.write(chunk.response);
|
||||
}
|
||||
```
|
||||
|
||||
## Sub Question Query Engine
|
||||
|
||||
The basic concept of the Sub Question Query Engine is that it splits a single query into multiple queries, gets an answer for each of those queries, and then combines those different answers into a single coherent response for the user. You can think of it as the "think this through step by step" prompt technique but iterating over your data sources!
|
||||
|
||||
### Getting Started
|
||||
|
||||
The easiest way to start trying the Sub Question Query Engine is running the subquestion.ts file in [examples](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/subquestion.ts).
|
||||
|
||||
```bash
|
||||
npx ts-node subquestion.ts
|
||||
```
|
||||
|
||||
### Tools
|
||||
|
||||
SubQuestionQueryEngine is implemented with Tools. The basic idea of Tools is that they are executable options for the large language model. In this case, our SubQuestionQueryEngine relies on QueryEngineTool, which as you guessed it is a tool to run queries on a QueryEngine. This allows us to give the model an option to query different documents for different questions for example. You could also imagine that the SubQuestionQueryEngine could use a Tool that searches for something on the web or gets an answer using Wolfram Alpha.
|
||||
|
||||
You can learn more about Tools by taking a look at the LlamaIndex Python documentation https://gpt-index.readthedocs.io/en/latest/core_modules/agent_modules/tools/root.html
|
||||
|
||||
## API Reference
|
||||
|
||||
- [RetrieverQueryEngine](../../api/classes/RetrieverQueryEngine.md)
|
||||
- [SubQuestionQueryEngine](../../api/classes/SubQuestionQueryEngine.md)
|
||||
- [QueryEngineTool](../../api/interfaces/QueryEngineTool.md)
|
||||
@@ -0,0 +1,31 @@
|
||||
# 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 @@
|
||||
label: Low-Level Modules
|
||||
@@ -0,0 +1,22 @@
|
||||
---
|
||||
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.
|
||||
|
||||
This can be explicitly set in the `ServiceContext` object.
|
||||
|
||||
```typescript
|
||||
import { OpenAIEmbedding, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const openaiEmbeds = new OpenAIEmbedding();
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ embedModel: openaiEmbeds });
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [OpenAIEmbedding](../../api/classes/OpenAIEmbedding.md)
|
||||
- [ServiceContext](../../api/interfaces/ServiceContext.md)
|
||||
@@ -0,0 +1,22 @@
|
||||
---
|
||||
sidebar_position: 0
|
||||
---
|
||||
|
||||
# LLM
|
||||
|
||||
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 });
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [OpenAI](../../api/classes/OpenAI.md)
|
||||
- [ServiceContext](../../api/interfaces/ServiceContext.md)
|
||||
@@ -0,0 +1,33 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
# NodeParser
|
||||
|
||||
The `NodeParser` in LlamaIndex is responbile 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");
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [SimpleNodeParser](../../api/classes/SimpleNodeParser.md)
|
||||
- [SentenceSplitter](../../api/classes/SentenceSplitter.md)
|
||||
@@ -0,0 +1,64 @@
|
||||
---
|
||||
sidebar_position: 6
|
||||
---
|
||||
|
||||
# ResponseSynthesizer
|
||||
|
||||
The ResponseSynthesizer is responsible for sending the query, nodes, and prompt templates to the LLM to generate a response. There are a few key modes for generating a response:
|
||||
|
||||
- `Refine`: "create and refine" an answer by sequentially going through each retrieved text chunk.
|
||||
This makes a separate LLM call per Node. Good for more detailed answers.
|
||||
- `CompactAndRefine` (default): "compact" the prompt during each LLM call by stuffing as
|
||||
many text chunks that can fit within the maximum prompt size. If there are
|
||||
too many chunks to stuff in one prompt, "create and refine" an answer by going through
|
||||
multiple compact prompts. The same as `refine`, but should result in less LLM calls.
|
||||
- `TreeSummarize`: Given a set of text chunks and the query, recursively construct a tree
|
||||
and return the root node as the response. Good for summarization purposes.
|
||||
- `SimpleResponseBuilder`: Given a set of text chunks and the query, apply the query to each text
|
||||
chunk while accumulating the responses into an array. Returns a concatenated string of all
|
||||
responses. Good for when you need to run the same query separately against each text
|
||||
chunk.
|
||||
|
||||
```typescript
|
||||
import { NodeWithScore, ResponseSynthesizer, TextNode } from "llamaindex";
|
||||
|
||||
const responseSynthesizer = new ResponseSynthesizer();
|
||||
|
||||
const nodesWithScore: NodeWithScore[] = [
|
||||
{
|
||||
node: new TextNode({ text: "I am 10 years old." }),
|
||||
score: 1,
|
||||
},
|
||||
{
|
||||
node: new TextNode({ text: "John is 20 years old." }),
|
||||
score: 0.5,
|
||||
},
|
||||
];
|
||||
|
||||
const response = await responseSynthesizer.synthesize({
|
||||
query: "What age am I?",
|
||||
nodesWithScore,
|
||||
});
|
||||
console.log(response.response);
|
||||
```
|
||||
|
||||
The `synthesize` function also supports streaming, just add `stream: true` as an option:
|
||||
|
||||
```typescript
|
||||
const stream = await responseSynthesizer.synthesize({
|
||||
query: "What age am I?",
|
||||
nodesWithScore,
|
||||
stream: true,
|
||||
});
|
||||
for await (const chunk of stream) {
|
||||
process.stdout.write(chunk.response);
|
||||
}
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [ResponseSynthesizer](../../api/classes/ResponseSynthesizer.md)
|
||||
- [Refine](../../api/classes/Refine.md)
|
||||
- [CompactAndRefine](../../api/classes/CompactAndRefine.md)
|
||||
- [TreeSummarize](../../api/classes/TreeSummarize.md)
|
||||
- [SimpleResponseBuilder](../../api/classes/SimpleResponseBuilder.md)
|
||||
@@ -0,0 +1,21 @@
|
||||
---
|
||||
sidebar_position: 5
|
||||
---
|
||||
|
||||
# Retriever
|
||||
|
||||
A retriever in LlamaIndex is what is used to fetch `Node`s from an index using a query string. Aa `VectorIndexRetriever` will fetch the top-k most similar nodes. Meanwhile, a `SummaryIndexRetriever` will fetch all nodes no matter the query.
|
||||
|
||||
```typescript
|
||||
const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Fetch nodes!
|
||||
const nodesWithScore = await retriever.retrieve("query string");
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [SummaryIndexRetriever](../../api/classes/SummaryIndexRetriever.md)
|
||||
- [SummaryIndexLLMRetriever](../../api/classes/SummaryIndexLLMRetriever.md)
|
||||
- [VectorIndexRetriever](../../api/classes/VectorIndexRetriever.md)
|
||||
@@ -0,0 +1,26 @@
|
||||
---
|
||||
sidebar_position: 7
|
||||
---
|
||||
|
||||
# Storage
|
||||
|
||||
Storage in LlamaIndex.TS works automatically once you've configured a `StorageContext` object. Just configure the `persistDir` and attach it to an index.
|
||||
|
||||
Right now, only saving and loading from disk is supported, with future integrations planned!
|
||||
|
||||
```typescript
|
||||
import { Document, VectorStoreIndex, storageContextFromDefaults } from "./src";
|
||||
|
||||
const storageContext = await storageContextFromDefaults({
|
||||
persistDir: "./storage",
|
||||
});
|
||||
|
||||
const document = new Document({ text: "Test Text" });
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
storageContext,
|
||||
});
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [StorageContext](../../api/interfaces/StorageContext.md)
|
||||
@@ -0,0 +1 @@
|
||||
label: Observability
|
||||
@@ -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,
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,56 @@
|
||||
---
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
# Starter Tutorial
|
||||
|
||||
Once you have [installed LlamaIndex.TS using NPM](installation) and set up your OpenAI key, you're ready to start your first app:
|
||||
|
||||
In a new folder:
|
||||
|
||||
```bash npm2yarn
|
||||
npm install typescript
|
||||
npm install @types/node
|
||||
npx tsc --init # if needed
|
||||
```
|
||||
|
||||
Create the file `example.ts`. This code will load some example data, create a document, index it (which creates embeddings using OpenAI), and then creates query engine to answer questions about the data.
|
||||
|
||||
```ts
|
||||
// example.ts
|
||||
import fs from "fs/promises";
|
||||
import { Document, VectorStoreIndex } from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Load essay from abramov.txt in Node
|
||||
const essay = await fs.readFile(
|
||||
"node_modules/llamaindex/examples/abramov.txt",
|
||||
"utf-8",
|
||||
);
|
||||
|
||||
// Create Document object with essay
|
||||
const document = new Document({ text: essay });
|
||||
|
||||
// Split text and create embeddings. Store them in a VectorStoreIndex
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine();
|
||||
const response = await queryEngine.query(
|
||||
"What did the author do in college?",
|
||||
);
|
||||
|
||||
// Output response
|
||||
console.log(response.toString());
|
||||
}
|
||||
|
||||
main();
|
||||
```
|
||||
|
||||
Then you can run it using
|
||||
|
||||
```bash
|
||||
npx ts-node example.ts
|
||||
```
|
||||
|
||||
Ready to learn more? Check out our NextJS playground at https://llama-playground.vercel.app/. The source is available at https://github.com/run-llama/ts-playground
|
||||
@@ -0,0 +1,181 @@
|
||||
// @ts-check
|
||||
// Note: type annotations allow type checking and IDEs autocompletion
|
||||
|
||||
const renderer = require("prism-react-renderer");
|
||||
const lightCodeTheme = renderer.themes.github;
|
||||
const darkCodeTheme = renderer.themes.dracula;
|
||||
|
||||
/** @type {import('@docusaurus/types').Config} */
|
||||
const config = {
|
||||
title: "LlamaIndex.TS",
|
||||
tagline: "Unleash the power of LLMs over your data in TypeScript",
|
||||
favicon: "img/favicon.png",
|
||||
|
||||
// Set the production url of your site here
|
||||
url: "https://ts.llamaindex.ai",
|
||||
// Set the /<baseUrl>/ pathname under which your site is served
|
||||
// For GitHub pages deployment, it is often '/<projectName>/'
|
||||
baseUrl: "/",
|
||||
|
||||
// GitHub pages deployment config.
|
||||
// If you aren't using GitHub pages, you don't need these.
|
||||
organizationName: "run-llama", // Usually your GitHub org/user name.
|
||||
projectName: "LlamaIndex.TS", // Usually your repo name.
|
||||
|
||||
onBrokenLinks: "warn",
|
||||
onBrokenMarkdownLinks: "warn",
|
||||
|
||||
// Even if you don't use internalization, you can use this field to set useful
|
||||
// metadata like html lang. For example, if your site is Chinese, you may want
|
||||
// to replace "en" with "zh-Hans".
|
||||
i18n: {
|
||||
defaultLocale: "en",
|
||||
locales: [
|
||||
"en",
|
||||
"zh-Hans",
|
||||
"es",
|
||||
"fr",
|
||||
"de",
|
||||
"ja",
|
||||
"ko",
|
||||
"pt",
|
||||
"ar",
|
||||
"it",
|
||||
"tr",
|
||||
"pl",
|
||||
"nl",
|
||||
"vi",
|
||||
"th",
|
||||
], // "fa", "ru", "ro", "sv", "hu", "cs", "el", "da", "fi", "he", "no", "hi", "in", "sl", "se", "sk", "uk", "bg", "hr", "lt", "lv", "et", "cat"
|
||||
},
|
||||
|
||||
presets: [
|
||||
[
|
||||
"@docusaurus/preset-classic",
|
||||
/** @type {import('@docusaurus/preset-classic').Options} */
|
||||
({
|
||||
docs: {
|
||||
path: "docs",
|
||||
routeBasePath: "/",
|
||||
sidebarPath: require.resolve("./sidebars.js"),
|
||||
// Please change this to your repo.
|
||||
// Remove this to remove the "edit this page" links.
|
||||
// editUrl:
|
||||
// "https://github.com/facebook/docusaurus/tree/main/packages/create-docusaurus/templates/shared/",
|
||||
remarkPlugins: [
|
||||
[require("@docusaurus/remark-plugin-npm2yarn"), { sync: true }],
|
||||
],
|
||||
},
|
||||
blog: false,
|
||||
gtag: {
|
||||
trackingID: "G-NB9B8LW9W5",
|
||||
anonymizeIP: true,
|
||||
},
|
||||
}),
|
||||
],
|
||||
],
|
||||
|
||||
themeConfig:
|
||||
/** @type {import('@docusaurus/preset-classic').ThemeConfig} */
|
||||
({
|
||||
// Replace with your project's social card
|
||||
image: "img/favicon.png", // TODO change this
|
||||
navbar: {
|
||||
title: "LlamaIndex.TS",
|
||||
logo: {
|
||||
alt: "LlamaIndex.TS",
|
||||
src: "img/favicon.png",
|
||||
},
|
||||
items: [
|
||||
{
|
||||
type: "docSidebar",
|
||||
sidebarId: "mySidebar",
|
||||
position: "left",
|
||||
label: "Docs",
|
||||
},
|
||||
{
|
||||
type: "localeDropdown",
|
||||
position: "left",
|
||||
},
|
||||
{
|
||||
href: "https://github.com/run-llama/LlamaIndexTS",
|
||||
label: "GitHub",
|
||||
position: "right",
|
||||
},
|
||||
],
|
||||
},
|
||||
footer: {
|
||||
style: "dark",
|
||||
links: [
|
||||
{
|
||||
title: "Docs",
|
||||
items: [
|
||||
{
|
||||
label: "API",
|
||||
to: "/api",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Community",
|
||||
items: [
|
||||
{
|
||||
label: "Discord",
|
||||
href: "https://discord.com/invite/eN6D2HQ4aX",
|
||||
},
|
||||
{
|
||||
label: "Twitter",
|
||||
href: "https://twitter.com/LlamaIndex",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "More",
|
||||
items: [
|
||||
{
|
||||
label: "GitHub",
|
||||
href: "https://github.com/run-llama/LlamaIndexTS",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
copyright: `Copyright © ${new Date().getFullYear()} LlamaIndex. Built with Docusaurus.`,
|
||||
},
|
||||
prism: {
|
||||
theme: lightCodeTheme,
|
||||
darkTheme: darkCodeTheme,
|
||||
},
|
||||
algolia: {
|
||||
// The application ID provided by Algolia
|
||||
appId: "DYKPM6G4CX",
|
||||
|
||||
// Public API key: it is safe to commit it
|
||||
apiKey: "c4ff3789f20bb72a5d735082aef17719",
|
||||
|
||||
indexName: "ts-llamaindex",
|
||||
|
||||
// Optional: see doc section below
|
||||
contextualSearch: true,
|
||||
},
|
||||
}),
|
||||
plugins: [
|
||||
[
|
||||
"docusaurus-plugin-typedoc",
|
||||
{
|
||||
entryPoints: ["../../packages/core/src/index.ts"],
|
||||
tsconfig: "../../packages/core/tsconfig.json",
|
||||
readme: "none",
|
||||
sourceLinkTemplate:
|
||||
"https://github.com/run-llama/LlamaIndexTS/blob/{gitRevision}/{path}#L{line}",
|
||||
sidebar: {
|
||||
position: 6,
|
||||
},
|
||||
},
|
||||
],
|
||||
],
|
||||
markdown: {
|
||||
format: "detect",
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = config;
|
||||
|
After Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 49 KiB |
|
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"; // الافتراضي
|
||||
```
|
||||
@@ -0,0 +1,67 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# التثبيت والإعداد
|
||||
|
||||
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
|
||||
|
||||
تأكد من أن لديك NodeJS v18 أو أحدث.
|
||||
|
||||
## باستخدام create-llama
|
||||
|
||||
أسهل طريقة للبدء مع LlamaIndex هي باستخدام `create-llama`. هذه الأداة سطر الأوامر تمكنك من بدء بناء تطبيق LlamaIndex جديد بسرعة، مع كل شيء معد لك.
|
||||
|
||||
ما عليك سوى تشغيل
|
||||
|
||||
<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>
|
||||
|
||||
للبدء. بمجرد إنشاء التطبيق الخاص بك، قم بتشغيل
|
||||
|
||||
```bash npm2yarn
|
||||
npm run dev
|
||||
```
|
||||
|
||||
لبدء خادم التطوير. يمكنك ثم زيارة [http://localhost:3000](http://localhost:3000) لرؤية تطبيقك.
|
||||
|
||||
## التثبيت من NPM
|
||||
|
||||
```bash npm2yarn
|
||||
npm install llamaindex
|
||||
```
|
||||
|
||||
### المتغيرات البيئية
|
||||
|
||||
تستخدم أمثلتنا OpenAI افتراضيًا. ستحتاج إلى إعداد مفتاح Open AI الخاص بك على النحو التالي:
|
||||
|
||||
```bash
|
||||
export OPENAI_API_KEY="sk-......" # استبدله بالمفتاح الخاص بك من https://platform.openai.com/account/api-keys
|
||||
```
|
||||
|
||||
إذا كنت ترغب في تحميله تلقائيًا في كل مرة، قم بإضافته إلى ملف .zshrc/.bashrc الخاص بك.
|
||||
|
||||
تحذير: لا تقم بإضافة مفتاح OpenAI الخاص بك إلى نظام التحكم في الإصدارات.
|
||||
|
||||
"
|
||||
@@ -0,0 +1,60 @@
|
||||
---
|
||||
sidebar_position: 0
|
||||
slug: /
|
||||
---
|
||||
|
||||
# ما هو LlamaIndex.TS؟
|
||||
|
||||
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
|
||||
|
||||
LlamaIndex.TS هو إطار بيانات لتطبيقات LLM لاستيعاب وتنظيم والوصول إلى البيانات الخاصة أو الخاصة بالمجال. في حين أن حزمة Python متاحة أيضًا (انظر [هنا](https://docs.llamaindex.ai/en/stable/)), يوفر LlamaIndex.TS ميزات أساسية في حزمة بسيطة ، محسنة للاستخدام مع TypeScript.
|
||||
|
||||
## 🚀 لماذا LlamaIndex.TS؟
|
||||
|
||||
في جوهرها ، توفر LLMs واجهة لغة طبيعية بين البشر والبيانات المستنتجة. تأتي النماذج المتاحة على نطاق واسع محملة مسبقًا بكميات هائلة من البيانات المتاحة للجمهور ، من ويكيبيديا وقوائم البريد الإلكتروني إلى الكتب المدرسية وشفرة المصدر.
|
||||
|
||||
غالبًا ما تتطلب التطبيقات المبنية على LLMs تعزيز هذه النماذج بالبيانات الخاصة أو الخاصة بالمجال. للأسف ، يمكن توزيع هذه البيانات عبر تطبيقات ومخازن بيانات معزولة. إنها خلف واجهات برمجة التطبيقات ، في قواعد البيانات SQL ، أو محبوسة في ملفات PDF وعروض تقديمية.
|
||||
|
||||
هنا يأتي دور **LlamaIndex.TS**.
|
||||
|
||||
## 🦙 كيف يمكن أن يساعد LlamaIndex.TS؟
|
||||
|
||||
يوفر LlamaIndex.TS الأدوات التالية:
|
||||
|
||||
- **تحميل البيانات**: استيعاب البيانات الحالية الخاصة بك بتنسيقات `.txt`, `.pdf`, `.csv`, `.md` و `.docx` مباشرة.
|
||||
- **فهارس البيانات**: تنظيم البيانات الخاصة بك في تمثيلات وسيطة سهلة وفعالة للاستخدام من قبل LLMs.
|
||||
- **المحركات**: توفر واجهات الوصول إلى اللغة الطبيعية لبياناتك. على سبيل المثال:
|
||||
- محركات الاستعلام هي واجهات استرجاع قوية للإخراج المعزز بالمعرفة.
|
||||
- محركات الدردشة هي واجهات محادثة للتفاعلات "ذهابًا وإيابًا" متعددة الرسائل مع بياناتك.
|
||||
|
||||
## 👨👩👧👦 من أجل من هو LlamaIndex؟
|
||||
|
||||
يوفر LlamaIndex.TS مجموعة أدوات أساسية ، ضرورية لأي شخص يقوم ببناء تطبيقات LLM باستخدام JavaScript و TypeScript.
|
||||
|
||||
يتيح لنا واجهة برمجة التطبيقات على مستوى عالي استخدام LlamaIndex.TS لاستيعاب واستعلام البيانات الخاصة بهم.
|
||||
|
||||
بالنسبة للتطبيقات المعقدة أكثر ، تتيح لنا واجهات برمجة التطبيقات على مستوى أدنى للمستخدمين المتقدمين تخصيص وتوسيع أي وحدة - موصلات البيانات والفهارس وأجهزة الاسترجاع ومحركات الاستعلام - لتناسب احتياجاتهم.
|
||||
|
||||
## البدء
|
||||
|
||||
`npm install llamaindex`
|
||||
|
||||
تتضمن وثائقنا [تعليمات التثبيت](./installation.mdx) و[دليل البداية](./starter.md) لبناء تطبيقك الأول.
|
||||
|
||||
بمجرد أن تكون جاهزًا وتعمل ، يحتوي [مفاهيم عالية المستوى](./concepts.md) على نظرة عامة على الهندسة المعمارية المتعددة المستويات لـ LlamaIndex. لمزيد من الأمثلة العملية التفصيلية ، يمكنك الاطلاع على [دروس النهاية إلى النهاية](./end_to_end.md).
|
||||
|
||||
## 🗺️ النظام البيئي
|
||||
|
||||
لتنزيل أو المساهمة ، ابحث عن LlamaIndex على:
|
||||
|
||||
- Github: https://github.com/run-llama/LlamaIndexTS
|
||||
- NPM: https://www.npmjs.com/package/llamaindex
|
||||
|
||||
"
|
||||
|
||||
## المجتمع
|
||||
|
||||
هل تحتاج إلى مساعدة؟ هل لديك اقتراح لميزة؟ انضم إلى مجتمع LlamaIndex:
|
||||
|
||||
- تويتر: https://twitter.com/llama_index
|
||||
- ديسكورد: https://discord.gg/dGcwcsnxhU
|
||||
@@ -0,0 +1,22 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
# محرك الدردشة (ChatEngine)
|
||||
|
||||
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
|
||||
|
||||
محرك الدردشة هو طريقة سريعة وبسيطة للدردشة مع البيانات في الفهرس الخاص بك.
|
||||
|
||||
```typescript
|
||||
const retriever = index.asRetriever();
|
||||
const chatEngine = new ContextChatEngine({ retriever });
|
||||
|
||||
// بدء الدردشة
|
||||
const response = await chatEngine.chat(query);
|
||||
```
|
||||
|
||||
## مراجع الواجهة البرمجية
|
||||
|
||||
- [محرك الدردشة السياقي (ContextChatEngine)](../../api/classes/ContextChatEngine.md)
|
||||
- [محرك الدردشة المكثف للأسئلة (CondenseQuestionChatEngine)](../../api/classes/ContextChatEngine.md)
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
# الفهرس
|
||||
|
||||
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
|
||||
|
||||
الفهرس هو الحاوية الأساسية والتنظيم لبياناتك. يدعم LlamaIndex.TS نوعين من الفهارس:
|
||||
|
||||
- `VectorStoreIndex` - سيقوم بإرسال أعلى `Node` الموجودة إلى LLM عند إنشاء استجابة. القيمة الافتراضية لأعلى `k` هي 2.
|
||||
- `SummaryIndex` - سيقوم بإرسال كل `Node` في الفهرس إلى LLM لإنشاء استجابة.
|
||||
|
||||
```typescript
|
||||
import { Document, VectorStoreIndex } from "llamaindex";
|
||||
|
||||
const document = new Document({ text: "اختبار" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
```
|
||||
|
||||
## مرجع الواجهة البرمجية
|
||||
|
||||
- [SummaryIndex](../../api/classes/SummaryIndex.md)
|
||||
- [VectorStoreIndex](../../api/classes/VectorStoreIndex.md)
|
||||
|
||||
"
|
||||
@@ -0,0 +1,19 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# قارئ / محمل
|
||||
|
||||
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
|
||||
|
||||
يدعم LlamaIndex.TS تحميل الملفات بسهولة من المجلدات باستخدام فئة `SimpleDirectoryReader`. حاليًا ، يتم دعم الملفات `.txt` ، `.pdf` ، `.csv` ، `.md` و `.docx` ، مع المزيد المخطط له في المستقبل!
|
||||
|
||||
```typescript
|
||||
import { SimpleDirectoryReader } from "llamaindex";
|
||||
|
||||
documents = new SimpleDirectoryReader().loadData("./data");
|
||||
```
|
||||
|
||||
## مرجع الواجهة البرمجية
|
||||
|
||||
- [SimpleDirectoryReader](../../api/classes/SimpleDirectoryReader.md)
|
||||
@@ -0,0 +1,22 @@
|
||||
---
|
||||
sidebar_position: 0
|
||||
---
|
||||
|
||||
# المستندات والعقد
|
||||
|
||||
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
|
||||
|
||||
`المستندات` و `العقد` هما العناصر الأساسية لأي فهرس. بينما يكون واجهة برمجة التطبيق (API) لهذه الكائنات مشابهة، يُمثل كائن `المستند` ملفات كاملة، بينما تكون `العقد` قطعًا أصغر من ذلك المستند الأصلي، والتي تكون مناسبة لـ LLM و Q&A.
|
||||
|
||||
```typescript
|
||||
import { Document } from "llamaindex";
|
||||
|
||||
document = new Document({ text: "نص", metadata: { key: "val" } });
|
||||
```
|
||||
|
||||
## مرجع الواجهة البرمجية
|
||||
|
||||
- [المستند (Document)](../../api/classes/Document.md)
|
||||
- [نص العقد (TextNode)](../../api/classes/TextNode.md)
|
||||
|
||||
"
|
||||
@@ -0,0 +1,42 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
# محرك الاستعلامات (QueryEngine)
|
||||
|
||||
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
|
||||
|
||||
يقوم محرك الاستعلامات بتجميع "Retriever" و "ResponseSynthesizer" في أنبوبة، والتي ستستخدم سلسلة الاستعلام لاسترداد العقد ومن ثم إرسالها إلى LLM لتوليد استجابة.
|
||||
|
||||
```typescript
|
||||
const queryEngine = index.asQueryEngine();
|
||||
const response = await queryEngine.query("سلسلة الاستعلام");
|
||||
```
|
||||
|
||||
## محرك الاستعلام للأسئلة الفرعية
|
||||
|
||||
الفكرة الأساسية لمحرك الاستعلام للأسئلة الفرعية هي تقسيم استعلام واحد إلى استعلامات متعددة، والحصول على إجابة لكل من تلك الاستعلامات، ثم دمج تلك الإجابات المختلفة في استجابة واحدة متسقة للمستخدم. يمكنك أن تفكر فيها كتقنية "فكر في ذلك خطوة بخطوة" ولكن بتكرار مصادر البيانات الخاصة بك!
|
||||
|
||||
### البدء
|
||||
|
||||
أسهل طريقة لبدء تجربة محرك الاستعلام للأسئلة الفرعية هي تشغيل ملف subquestion.ts في [examples](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/subquestion.ts).
|
||||
|
||||
```bash
|
||||
npx ts-node subquestion.ts
|
||||
```
|
||||
|
||||
"
|
||||
|
||||
### الأدوات
|
||||
|
||||
يتم تنفيذ محرك الاستعلام للأسئلة الفرعية باستخدام الأدوات. الفكرة الأساسية للأدوات هي أنها خيارات قابلة للتنفيذ لنموذج اللغة الكبيرة. في هذه الحالة، يعتمد محرك الاستعلام للأسئلة الفرعية على أداة QueryEngineTool، والتي كما تخمن هي أداة لتشغيل استعلامات على محرك الاستعلام. يتيح لنا ذلك إعطاء النموذج خيارًا للاستعلام عن وثائق مختلفة لأسئلة مختلفة على سبيل المثال. يمكنك أيضًا أن تتخيل أن محرك الاستعلام للأسئلة الفرعية يمكنه استخدام أداة تبحث عن شيء ما على الويب أو تحصل على إجابة باستخدام Wolfram Alpha.
|
||||
|
||||
يمكنك معرفة المزيد عن الأدوات من خلال الاطلاع على وثائق LlamaIndex Python https://gpt-index.readthedocs.io/en/latest/core_modules/agent_modules/tools/root.html
|
||||
|
||||
"
|
||||
|
||||
## مرجع واجهة برمجة التطبيق (API)
|
||||
|
||||
- [محرك استعلام الاسترجاع (RetrieverQueryEngine)](../../api/classes/RetrieverQueryEngine.md)
|
||||
- [محرك استعلام السؤال الفرعي (SubQuestionQueryEngine)](../../api/classes/SubQuestionQueryEngine.md)
|
||||
- [أداة محرك الاستعلام (QueryEngineTool)](../../api/interfaces/QueryEngineTool.md)
|
||||
@@ -0,0 +1,33 @@
|
||||
# الوحدات الأساسية
|
||||
|
||||
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
|
||||
|
||||
يوفر LlamaIndex.TS عدة وحدات أساسية، مقسمة إلى وحدات عالية المستوى للبدء السريع ووحدات منخفضة المستوى لتخصيص المكونات الرئيسية حسب الحاجة.
|
||||
|
||||
## وحدات عالية المستوى
|
||||
|
||||
- [**المستند**](./high_level/documents_and_nodes.md): يمثل المستند ملف نصي أو ملف PDF أو قطعة بيانات متتابعة أخرى.
|
||||
|
||||
- [**العقدة**](./high_level/documents_and_nodes.md): هو البناء الأساسي للبيانات. في أغلب الأحيان، تكون هذه أجزاء من المستند المقسمة إلى قطع قابلة للإدارة وصغيرة بما يكفي ليتم تغذيتها إلى نموذج التضمين و LLM.
|
||||
|
||||
- [**القارئ/المحمل**](./high_level/data_loader.md): القارئ أو المحمل هو شيء يأخذ المستند في العالم الحقيقي ويحوله إلى فئة المستند التي يمكن استخدامها في الفهرس الخاص بك والاستعلامات. ندعم حاليًا ملفات النص العادي وملفات PDF والمزيد الكثير.
|
||||
|
||||
- [**الفهارس**](./high_level/data_index.md): تخزن الفهارس العقد وتضمينات تلك العقد.
|
||||
|
||||
- [**محرك الاستعلامات**](./high_level/query_engine.md): محركات الاستعلامات هي التي تولد الاستعلام الذي تدخله وتعيد لك النتيجة. عمومًا، تجمع محركات الاستعلامات بين تعليمة مسبقة مبنية مع العقد المحددة من الفهرس الخاص بك لتعطي LLM السياق الذي يحتاجه للإجابة على استعلامك.
|
||||
|
||||
- [**محرك الدردشة**](./high_level/chat_engine.md): يساعدك محرك الدردشة على بناء روبوت دردشة سيتفاعل مع فهرسك.
|
||||
|
||||
## وحدة منخفضة المستوى
|
||||
|
||||
- [**LLM**](./low_level/llm.md): فئة LLM هي واجهة موحدة فوق مزود نموذج لغة كبير مثل OpenAI GPT-4 أو Anthropic Claude أو Meta LLaMA. يمكنك توريثها لكتابة موصل إلى نموذج اللغة الخاص بك.
|
||||
|
||||
- [**Embedding**](./low_level/embedding.md): يتم تمثيل التضمين كمتجه من الأرقام العائمة. نموذج التضمين الافتراضي لدينا هو text-embedding-ada-002 من OpenAI ويتكون كل تضمين يولده من 1,536 رقمًا عائمًا. نموذج التضمين الشائع الآخر هو BERT الذي يستخدم 768 رقمًا عائمًا لتمثيل كل عقدة. نوفر عددًا من الأدوات للعمل مع التضمين بما في ذلك 3 خيارات لحساب التشابه و Maximum Marginal Relevance.
|
||||
|
||||
- [**TextSplitter/NodeParser**](./low_level/node_parser.md): تعتبر استراتيجيات تقسيم النصوص مهمة للغاية لفعالية البحث في التضمين. حاليًا، على الرغم من أن لدينا قيمة افتراضية، إلا أنه لا يوجد حلاً مناسبًا للجميع. اعتمادًا على وثائق المصدر، قد ترغب في استخدام أحجام واستراتيجيات تقسيم مختلفة. حاليًا، ندعم التقسيم حسب الحجم الثابت، التقسيم حسب الحجم الثابت مع أجزاء تتداخل، التقسيم حسب الجملة، والتقسيم حسب الفقرة. يتم استخدام مقسم النصوص بواسطة NodeParser عند تقسيم `Document` إلى `Node`.
|
||||
|
||||
- [**Retriever**](./low_level/retriever.md): يقوم Retriever بتحديد العقد التي يتم استردادها من الفهرس. هنا، قد ترغب في محاولة استرداد عدد أكبر أو أقل من العقد لكل استعلام، تغيير وظيفة التشابه الخاصة بك، أو إنشاء استرداد خاص بك لكل حالة استخدام فردية في تطبيقك. على سبيل المثال، قد ترغب في وجود استرداد منفصل لمحتوى الشفرة مقابل محتوى النص.
|
||||
|
||||
- [**ResponseSynthesizer**](./low_level/response_synthesizer.md): يتحمل ResponseSynthesizer مسؤولية أخذ سلسلة استعلام واستخدام قائمة من العقد لإنشاء استجابة. يمكن أن يأخذ هذا الشكل العديد من الأشكال، مثل التكرار عبر جميع السياق وتحسين الإجابة، أو بناء شجرة من الملخصات وإرجاع الملخص الجذري.
|
||||
|
||||
- [**Storage**](./low_level/storage.md): في نقطة ما، سترغب في تخزين الفهارس والبيانات والمتجهات بدلاً من إعادة تشغيل نماذج التضمين في كل مرة. IndexStore و DocStore و VectorStore و KVStore هي تجريدات تتيح لك ذلك. مجتمعة، تشكل هذه التجريدات سياق التخزين. حاليًا، نسمح لك بالاحتفاظ بالتضمينات الخاصة بك في ملفات على نظام الملفات (أو نظام ملفات افتراضي في الذاكرة)، ولكننا نضيف أيضًا تكاملات مع قواعد بيانات المتجهات.
|
||||
@@ -0,0 +1,26 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# تضمين
|
||||
|
||||
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
|
||||
|
||||
يتولى النموذج المضمن في LlamaIndex إنشاء تمثيلات رقمية للنص. بشكل افتراضي ، ستستخدم LlamaIndex نموذج `text-embedding-ada-002` من OpenAI.
|
||||
|
||||
يمكن تعيين ذلك بشكل صريح في كائن `ServiceContext`.
|
||||
|
||||
```typescript
|
||||
import { OpenAIEmbedding, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const openaiEmbeds = new OpenAIEmbedding();
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ embedModel: openaiEmbeds });
|
||||
```
|
||||
|
||||
## مرجع الواجهة البرمجية
|
||||
|
||||
- [OpenAIEmbedding](../../api/classes/OpenAIEmbedding.md)
|
||||
- [ServiceContext](../../api/interfaces/ServiceContext.md)
|
||||
|
||||
"
|
||||
@@ -0,0 +1,26 @@
|
||||
---
|
||||
sidebar_position: 0
|
||||
---
|
||||
|
||||
# LLM
|
||||
|
||||
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
|
||||
|
||||
يتولى LLM قراءة النص وتوليد استجابات لغوية طبيعية للاستفسارات. بشكل افتراضي ، يستخدم LlamaIndex.TS `gpt-3.5-turbo`.
|
||||
|
||||
يمكن تعيين LLM بشكل صريح في كائن `ServiceContext`.
|
||||
|
||||
```typescript
|
||||
import { OpenAI, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const openaiLLM = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0 });
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm: openaiLLM });
|
||||
```
|
||||
|
||||
## مرجع الواجهة البرمجية
|
||||
|
||||
- [OpenAI](../../api/classes/OpenAI.md)
|
||||
- [ServiceContext](../../api/interfaces/ServiceContext.md)
|
||||
|
||||
"
|
||||
@@ -0,0 +1,37 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
# NodeParser (محلل العقدة)
|
||||
|
||||
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
|
||||
|
||||
`NodeParser` في LlamaIndex مسؤول عن تقسيم كائنات `Document` إلى كائنات `Node` أكثر إدارة. عند استدعاء `.fromDocuments()`, يتم استخدام `NodeParser` من `ServiceContext` للقيام بذلك تلقائيًا بالنسبة لك. بدلاً من ذلك ، يمكنك استخدامه لتقسيم المستندات مسبقًا.
|
||||
|
||||
```typescript
|
||||
import { Document, SimpleNodeParser } from "llamaindex";
|
||||
|
||||
const nodeParser = new SimpleNodeParser();
|
||||
const nodes = nodeParser.getNodesFromDocuments([
|
||||
new Document({ text: "أنا عمري 10 سنوات. جون عمره 20 سنة." }),
|
||||
]);
|
||||
```
|
||||
|
||||
## TextSplitter (مقسم النص)
|
||||
|
||||
سيقوم مقسم النص الأساسي بتقسيم النص إلى جمل. يمكن أيضًا استخدامه كوحدة مستقلة لتقسيم النص الخام.
|
||||
|
||||
```typescript
|
||||
import { SentenceSplitter } from "llamaindex";
|
||||
|
||||
const splitter = new SentenceSplitter({ chunkSize: 1 });
|
||||
|
||||
const textSplits = splitter.splitText("مرحبًا بالعالم");
|
||||
```
|
||||
|
||||
## مرجع الواجهة البرمجية
|
||||
|
||||
- [SimpleNodeParser (محلل العقدة البسيط)](../../api/classes/SimpleNodeParser.md)
|
||||
- [SentenceSplitter (مقسم الجمل)](../../api/classes/SentenceSplitter.md)
|
||||
|
||||
"
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
sidebar_position: 6
|
||||
---
|
||||
|
||||
# مركب الاستجابة (ResponseSynthesizer)
|
||||
|
||||
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
|
||||
|
||||
مركب الاستجابة (ResponseSynthesizer) مسؤول عن إرسال الاستعلام والعقد وقوالب الاستفسار إلى LLM لتوليد استجابة. هناك بعض وسائط رئيسية لتوليد استجابة:
|
||||
|
||||
- `تحسين`: "إنشاء وتحسين" إجابة عن طريق المرور تتاليًا عبر كل قطعة نص مُسترجعة. يتم إجراء استدعاء LLM منفصل لكل عقدة. جيد للإجابات المفصلة.
|
||||
- `مضغوط وتحسين` (الافتراضي): "ضغط" الاستفسار أثناء كل استدعاء LLM عن طريق حشو أكبر عدد ممكن من قطع النص التي يمكن أن تتناسب مع حجم الاستفسار الأقصى. إذا كان هناك الكثير من القطع لتعبئتها في استفسار واحد، "إنشاء وتحسين" إجابة عن طريق المرور بعدة استفسارات مضغوطة. نفس العملية كـ `تحسين`، ولكن يجب أن تؤدي إلى مزيد من استدعاءات LLM أقل.
|
||||
- `ملخص الشجرة`: بناء شجرة بشكل متكرر بناءً على مجموعة من قطع النص والاستعلام، وإرجاع العقدة الجذرية كاستجابة. جيد لأغراض التلخيص.
|
||||
- `منشئ الاستجابة البسيط`: تطبيق الاستعلام على كل قطعة نص وتجميع الاستجابات في مصفوفة. يعيد سلسلة متصلة من جميع الاستجابات. جيد عندما تحتاج إلى تشغيل نفس الاستعلام بشكل منفصل على كل قطعة نص.
|
||||
|
||||
```typescript
|
||||
import { NodeWithScore, ResponseSynthesizer, TextNode } from "llamaindex";
|
||||
|
||||
const responseSynthesizer = new ResponseSynthesizer();
|
||||
|
||||
const nodesWithScore: NodeWithScore[] = [
|
||||
{
|
||||
node: new TextNode({ text: "أنا عمري 10 سنوات." }),
|
||||
score: 1,
|
||||
},
|
||||
{
|
||||
node: new TextNode({ text: "جون عمره 20 سنة." }),
|
||||
score: 0.5,
|
||||
},
|
||||
];
|
||||
|
||||
const response = await responseSynthesizer.synthesize(
|
||||
"ما هو عمري؟",
|
||||
nodesWithScore,
|
||||
);
|
||||
console.log(response.response);
|
||||
```
|
||||
|
||||
## مرجع الواجهة البرمجية
|
||||
|
||||
- [مركب الاستجابة (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)
|
||||
@@ -0,0 +1,23 @@
|
||||
---
|
||||
sidebar_position: 5
|
||||
---
|
||||
|
||||
# الباحث (Retriever)
|
||||
|
||||
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
|
||||
|
||||
الباحث في LlamaIndex هو ما يُستخدم لاسترداد العقد (`Node`) من فهرس باستخدام سلسلة الاستعلام. سيقوم الباحث `VectorIndexRetriever` بجلب أعلى k عقد مشابهة. بينما سيقوم الباحث `SummaryIndexRetriever` بجلب جميع العقد بغض النظر عن الاستعلام.
|
||||
|
||||
```typescript
|
||||
const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// جلب العقد!
|
||||
const nodesWithScore = await retriever.retrieve("سلسلة الاستعلام");
|
||||
```
|
||||
|
||||
## مرجع الواجهة البرمجية (API Reference)
|
||||
|
||||
- [SummaryIndexRetriever](../../api/classes/SummaryIndexRetriever.md)
|
||||
- [SummaryIndexLLMRetriever](../../api/classes/SummaryIndexLLMRetriever.md)
|
||||
- [VectorIndexRetriever](../../api/classes/VectorIndexRetriever.md)
|
||||
@@ -0,0 +1,30 @@
|
||||
---
|
||||
sidebar_position: 7
|
||||
---
|
||||
|
||||
# التخزين
|
||||
|
||||
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
|
||||
|
||||
يعمل التخزين في LlamaIndex.TS تلقائيًا بمجرد تكوين كائن `StorageContext`. قم بتكوين `persistDir` وربطه بفهرس.
|
||||
|
||||
في الوقت الحالي ، يتم دعم حفظ وتحميل البيانات من القرص فقط ، مع وجود تكاملات مستقبلية مخططة!
|
||||
|
||||
```typescript
|
||||
import { Document, VectorStoreIndex, storageContextFromDefaults } from "./src";
|
||||
|
||||
const storageContext = await storageContextFromDefaults({
|
||||
persistDir: "./storage",
|
||||
});
|
||||
|
||||
const document = new Document({ text: "نص اختبار" });
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
storageContext,
|
||||
});
|
||||
```
|
||||
|
||||
## مرجع الواجهة البرمجية
|
||||
|
||||
- [StorageContext](../../api/interfaces/StorageContext.md)
|
||||
|
||||
"
|
||||
@@ -0,0 +1,58 @@
|
||||
---
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
# دليل البداية
|
||||
|
||||
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
|
||||
|
||||
بمجرد [تثبيت LlamaIndex.TS باستخدام NPM](installation) وإعداد مفتاح OpenAI الخاص بك، أنت الآن جاهز لبدء تطبيقك الأول:
|
||||
|
||||
في مجلد جديد:
|
||||
|
||||
```bash npm2yarn
|
||||
npm install typescript
|
||||
npm install @types/node
|
||||
npx tsc --init # إذا لزم الأمر
|
||||
```
|
||||
|
||||
أنشئ ملف `example.ts`. سيقوم هذا الكود بتحميل بعض البيانات المثالية، وإنشاء وثيقة، وفهرسة الوثيقة (مما ينشئ تضمينات باستخدام OpenAI)، ثم إنشاء محرك الاستعلام للإجابة على الأسئلة حول البيانات.
|
||||
|
||||
```ts
|
||||
// example.ts
|
||||
import fs from "fs/promises";
|
||||
import { Document, VectorStoreIndex } from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// تحميل المقالة من abramov.txt في Node
|
||||
const essay = await fs.readFile(
|
||||
"node_modules/llamaindex/examples/abramov.txt",
|
||||
"utf-8",
|
||||
);
|
||||
|
||||
// إنشاء كائن Document بواسطة المقالة
|
||||
const document = new Document({ text: essay });
|
||||
|
||||
// تقسيم النص وإنشاء التضمينات. تخزينها في VectorStoreIndex
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// استعلام الفهرس
|
||||
const queryEngine = index.asQueryEngine();
|
||||
const response = await queryEngine.query("ماذا فعل الكاتب في الكلية؟");
|
||||
|
||||
// إخراج الاستجابة
|
||||
console.log(response.toString());
|
||||
}
|
||||
|
||||
main();
|
||||
```
|
||||
|
||||
ثم يمكنك تشغيله باستخدام
|
||||
|
||||
```bash
|
||||
npx ts-node example.ts
|
||||
```
|
||||
|
||||
هل أنت مستعد للمزيد من التعلم؟ تفضل بزيارة منصة NextJS الخاصة بنا على https://llama-playground.vercel.app/. يمكنك العثور على المصدر على https://github.com/run-llama/ts-playground
|
||||
|
||||
"
|
||||
|
After Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 49 KiB |
|
After Width: | Height: | Size: 36 KiB |
@@ -0,0 +1 @@
|
||||
../../../../docs/api
|
||||
@@ -0,0 +1,86 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
# Високо ниво на концепции
|
||||
|
||||
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите Pull Request, за да предложите промени.`
|
||||
|
||||
LlamaIndex.TS ви помага да създавате приложения, базирани на LLM (например Q&A, чатбот) върху персонализирани данни.
|
||||
|
||||
В това ръководство за високо ниво на концепции ще научите:
|
||||
|
||||
- как LLM може да отговори на въпроси, използвайки вашите собствени данни.
|
||||
- ключови концепции и модули в LlamaIndex.TS за създаване на ваша собствена заявка.
|
||||
|
||||
## Отговаряне на въпроси върху вашите данни
|
||||
|
||||
LlamaIndex използва двустепенен метод при използване на LLM с вашите данни:
|
||||
|
||||
1. **стъпка за индексиране**: подготовка на база от знания и
|
||||
2. **стъпка за заявка**: извличане на съответния контекст от знанията, за да помогне на LLM да отговори на въпрос
|
||||
|
||||

|
||||
|
||||
Този процес е известен също като Retrieval Augmented Generation (RAG).
|
||||
|
||||
LlamaIndex.TS предоставя основния инструментариум, който прави и двете стъпки изключително лесни.
|
||||
|
||||
Нека изследваме всяка стъпка подробно.
|
||||
|
||||
### Стъпка на индексиране
|
||||
|
||||
LlamaIndex.TS ви помага да подготвите базата от знания с помощта на набор от конектори за данни и индекси.
|
||||
|
||||

|
||||
|
||||
[**Data Loaders**](./modules/high_level/data_loader.md):
|
||||
Конектор за данни (т.е. `Reader`) поема данни от различни източници на данни и формати на данни и ги превръща в просто представяне на `Document` (текст и прости метаданни).
|
||||
|
||||
[**Documents / Nodes**](./modules/high_level/documents_and_nodes.md): `Document` е общ контейнер за всякакъв вид данни - например PDF, изход от API или извлечени данни от база данни. `Node` е атомарната единица от данни в LlamaIndex и представлява "част" от източниковия `Document`. Това е богато представяне, което включва метаданни и връзки (към други възли), за да позволи точни и изразителни операции за извличане.
|
||||
|
||||
[**Data Indexes**](./modules/high_level/data_index.md):
|
||||
След като сте поели данните си, LlamaIndex ви помага да индексирате данните във формат, който е лесен за извличане.
|
||||
|
||||
Под капака, LlamaIndex анализира суровите документи в промеждинни представяния, изчислява векторни вложения и съхранява данните в паметта или на диска.
|
||||
|
||||
"
|
||||
|
||||
### Стъпка за заявка
|
||||
|
||||
В стъпката за заявка, конвейерът за заявки извлича най-съответния контекст, даден на потребителска заявка,
|
||||
и го предава на LLM (заедно със заявката), за да синтезира отговор.
|
||||
|
||||
Това дава на LLM актуални познания, които не са в неговите оригинални обучаващи данни,
|
||||
(също така намалява халюцинацията).
|
||||
|
||||
Основното предизвикателство в стъпката за заявка е извличането, организирането и резонирането върху (потенциално много) бази от знания.
|
||||
|
||||
LlamaIndex предоставя модули, които могат да се комбинират и помагат за създаването и интегрирането на RAG конвейери за Q&A (заявки), чатбот (чат двигател) или като част от агент.
|
||||
|
||||
Тези строителни блокове могат да бъдат персонализирани, за да отразяват предпочитанията за ранжиране, както и да бъдат комбинирани, за да резонират върху множество бази от знания по структуриран начин.
|
||||
|
||||

|
||||
|
||||
#### Строителни блокове
|
||||
|
||||
[**Извличатели**](./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,57 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
# Примери от начало до край
|
||||
|
||||
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите Pull Request, за да предложите промени.`
|
||||
|
||||
Включени са няколко примера от начало до край, използвайки LlamaIndex.TS в хранилището
|
||||
|
||||
Разгледайте примерите по-долу или ги опитайте и завършете за минути с интерактивни уроци на Github Codespace, предоставени от Dev-Docs [тук](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/examples/chatEngine.ts)
|
||||
|
||||
Прочетете файл и обсъждайте го с LLM.
|
||||
|
||||
## [Векторен индекс](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/vectorIndex.ts)
|
||||
|
||||
Създайте векторен индекс и го запитайте. Векторният индекс ще използва вграждания, за да извлече най-релевантните k върха. По подразбиране, k е 2.
|
||||
|
||||
"
|
||||
|
||||
## [Summary Index](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 и го използвайте директно за чат.
|
||||
|
||||
## [SubQuestionQueryEngine](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/subquestion.ts)
|
||||
|
||||
Използва `SubQuestionQueryEngine`, който разбива сложни заявки на множество въпроси и след това агрегира отговорите на всички под-въпроси.
|
||||
|
||||
"
|
||||
|
||||
## [Модули с ниско ниво](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/lowlevel.ts)
|
||||
|
||||
Този пример използва няколко компонента с ниско ниво, които премахват нуждата от реален двигател за заявки. Тези компоненти могат да се използват навсякъде, във всяко приложение или да бъдат персонализирани и подкласирани, за да отговарят на вашите нужди.
|
||||
|
||||
"
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
sidebar_position: 5
|
||||
---
|
||||
|
||||
# Среди
|
||||
|
||||
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите Pull Request, за да предложите промени.`
|
||||
|
||||
LlamaIndex в момента официално поддържа NodeJS 18 и NodeJS 20.
|
||||
|
||||
## NextJS App Router
|
||||
|
||||
Ако използвате обработчици на маршрути/сървърни функции на NextJS App Router, ще трябва да използвате режима на NodeJS:
|
||||
|
||||
```js
|
||||
export const runtime = "nodejs"; // по подразбиране
|
||||
```
|
||||
@@ -0,0 +1,65 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# Инсталация и настройка
|
||||
|
||||
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите Pull Request, за да предложите промени.`
|
||||
|
||||
Уверете се, че имате NodeJS v18 или по-нова версия.
|
||||
|
||||
## Използване на create-llama
|
||||
|
||||
Най-лесният начин да започнете с LlamaIndex е чрез използването на `create-llama`. Този инструмент с команден ред ви позволява бързо да започнете да създавате ново приложение LlamaIndex, като всичко е настроено за вас.
|
||||
|
||||
Просто изпълнете
|
||||
|
||||
<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>
|
||||
|
||||
за да започнете. След като приложението ви е генерирано, изпълнете
|
||||
|
||||
```bash npm2yarn
|
||||
npm run dev
|
||||
```
|
||||
|
||||
за да стартирате сървъра за разработка. След това можете да посетите [http://localhost:3000](http://localhost:3000), за да видите вашето приложение.
|
||||
|
||||
## Инсталация от NPM
|
||||
|
||||
```bash npm2yarn
|
||||
npm install llamaindex
|
||||
```
|
||||
|
||||
### Променливи на средата
|
||||
|
||||
Нашият пример използва OpenAI по подразбиране. Ще трябва да настроите вашия Open AI ключ по следния начин:
|
||||
|
||||
```bash
|
||||
export OPENAI_API_KEY="sk-......" # Заменете с вашия ключ от https://platform.openai.com/account/api-keys
|
||||
```
|
||||
|
||||
Ако искате да го зареждате автоматично всеки път, добавете го към вашия .zshrc/.bashrc.
|
||||
|
||||
ВНИМАНИЕ: не добавяйте вашия OpenAI ключ в системата за контрол на версиите.
|
||||
@@ -0,0 +1,62 @@
|
||||
---
|
||||
sidebar_position: 0
|
||||
slug: /
|
||||
---
|
||||
|
||||
# Какво е LlamaIndex.TS?
|
||||
|
||||
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите Pull Request, за да предложите промени.`
|
||||
|
||||
LlamaIndex.TS е рамка за данни за приложения на LLM, която позволява внасяне, структуриране и достъп до частни или специфични за домейна данни. Въпреки че има наличен и пакет на Python (вижте [тук](https://docs.llamaindex.ai/en/stable/)), LlamaIndex.TS предлага основни функции в едно просто пакетиране, оптимизирано за използване с TypeScript.
|
||||
|
||||
## 🚀 Защо LlamaIndex.TS?
|
||||
|
||||
В основата си, LLM-ите предлагат естествен езиков интерфейс между хората и изводените данни. Широко разпространените модели са предварително обучени на голямо количество публично достъпни данни, от Уикипедия и списания до учебници и изходен код.
|
||||
|
||||
Приложенията, построени върху LLM-и, често изискват допълване на тези модели с частни или специфични за домейна данни. За съжаление, тези данни могат да бъдат разпределени в различни приложения и хранилища на данни. Те се намират зад API-и, в SQL бази данни или са затворени в PDF файлове и презентации.
|
||||
|
||||
Тук идва **LlamaIndex.TS**.
|
||||
|
||||
## 🦙 Как може да помогне LlamaIndex.TS?
|
||||
|
||||
LlamaIndex.TS предоставя следните инструменти:
|
||||
|
||||
- **Зареждане на данни** - внасяйте вашите съществуващи данни във формат `.txt`, `.pdf`, `.csv`, `.md` и `.docx` директно
|
||||
- **Индекси на данни** - структурирайте данните си в промежуточни представяния, които са лесни и ефективни за консумация от LLM.
|
||||
- **Двигатели** - предоставят достъп до вашите данни чрез естествен език. Например:
|
||||
- Заявителни двигатели са мощни интерфейси за извличане на знания.
|
||||
- Чат двигатели са разговорни интерфейси за многократни, "напред и назад" взаимодействия с вашите данни.
|
||||
|
||||
"
|
||||
|
||||
## 👨👩👧👦 За кого е LlamaIndex?
|
||||
|
||||
LlamaIndex.TS предоставя основен набор от инструменти, необходими за всеки, който създава LLM приложения с JavaScript и TypeScript.
|
||||
|
||||
Нашето API на високо ниво позволява на начинаещите потребители да използват LlamaIndex.TS за внасяне и заявка на техните данни.
|
||||
|
||||
За по-сложни приложения нашите API на по-ниско ниво позволяват на напредналите потребители да персонализират и разширят всяко модул - връзки с данни, индекси, извличатели и заявки, за да отговарят на техните нужди.
|
||||
|
||||
## Започване
|
||||
|
||||
`npm install llamaindex`
|
||||
|
||||
Документацията ни включва [Инструкции за инсталиране](./installation.mdx) и [Урок за начинаещи](./starter.md), за да построите първото си приложение.
|
||||
|
||||
След като сте готови, [Високо ниво концепции](./concepts.md) представя общ преглед на модулната архитектура на LlamaIndex. За повече практически примери, разгледайте нашите [Уроци от начало до край](./end_to_end.md).
|
||||
|
||||
## 🗺️ Екосистема
|
||||
|
||||
За да изтеглите или допринесете, намерете LlamaIndex на:
|
||||
|
||||
- Github: https://github.com/run-llama/LlamaIndexTS
|
||||
- NPM: https://www.npmjs.com/package/llamaindex
|
||||
|
||||
"
|
||||
|
||||
## Общност
|
||||
|
||||
Нуждаете се от помощ? Имате предложение за функционалност? Присъединете се към общността на LlamaIndex:
|
||||
|
||||
- Twitter: https://twitter.com/llama_index
|
||||
- Discord: https://discord.gg/dGcwcsnxhU
|
||||
@@ -0,0 +1,24 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
# Чат двигател (ChatEngine)
|
||||
|
||||
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите Pull Request, за да предложите промени.`
|
||||
|
||||
Чат двигателят е бърз и прост начин да чатите с данните във вашата индекс.
|
||||
|
||||
```typescript
|
||||
const retriever = index.asRetriever();
|
||||
const chatEngine = new ContextChatEngine({ retriever });
|
||||
|
||||
// започнете да чатите
|
||||
const response = await chatEngine.chat(query);
|
||||
```
|
||||
|
||||
## Api Референции
|
||||
|
||||
- [Чат двигател за контекст (ContextChatEngine)](../../api/classes/ContextChatEngine.md)
|
||||
- [Чат двигател за кондензиране на въпроси (CondenseQuestionChatEngine)](../../api/classes/ContextChatEngine.md)
|
||||
|
||||
"
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
# Индекс
|
||||
|
||||
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите Pull Request, за да предложите промени.`
|
||||
|
||||
Индексът е основният контейнер и организация за вашите данни. LlamaIndex.TS поддържа два вида индекси:
|
||||
|
||||
- `VectorStoreIndex` - ще изпраща най-добрите `Node` до LLM при генериране на отговор. По подразбиране, най-добрите два.
|
||||
- `SummaryIndex` - ще изпраща всеки `Node` в индекса до LLM, за да генерира отговор.
|
||||
|
||||
```typescript
|
||||
import { Document, VectorStoreIndex } from "llamaindex";
|
||||
|
||||
const document = new Document({ text: "тест" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
```
|
||||
|
||||
## API Референция
|
||||
|
||||
- [SummaryIndex](../../api/classes/SummaryIndex.md)
|
||||
- [VectorStoreIndex](../../api/classes/VectorStoreIndex.md)
|
||||
|
||||
"
|
||||
@@ -0,0 +1,21 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# Четец / Зареждач
|
||||
|
||||
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите Pull Request, за да предложите промени.`
|
||||
|
||||
LlamaIndex.TS поддържа лесно зареждане на файлове от папки с помощта на класа `SimpleDirectoryReader`. В момента се поддържат файлове с разширения `.txt`, `.pdf`, `.csv`, `.md` и `.docx`, с планове за добавяне на още в бъдеще!
|
||||
|
||||
```typescript
|
||||
import { SimpleDirectoryReader } from "llamaindex";
|
||||
|
||||
documents = new SimpleDirectoryReader().loadData("./data");
|
||||
```
|
||||
|
||||
## API Референция
|
||||
|
||||
- [SimpleDirectoryReader](../../api/classes/SimpleDirectoryReader.md)
|
||||
|
||||
"
|
||||
@@ -0,0 +1,22 @@
|
||||
---
|
||||
sidebar_position: 0
|
||||
---
|
||||
|
||||
# Документи и Възли
|
||||
|
||||
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите Pull Request, за да предложите промени.`
|
||||
|
||||
`Документи` и `Възли` са основните строителни блокове на всяко индексиране. Въпреки че API-то за тези обекти е подобно, обектите `Документ` представляват цели файлове, докато `Възли` са по-малки части от оригиналния документ, които са подходящи за LLM и Q&A.
|
||||
|
||||
```typescript
|
||||
import { Document } from "llamaindex";
|
||||
|
||||
document = new Document({ text: "текст", metadata: { key: "val" } });
|
||||
```
|
||||
|
||||
## API Референция
|
||||
|
||||
- [Документ](../../api/classes/Document.md)
|
||||
- [ТекстовВъзел](../../api/classes/TextNode.md)
|
||||
|
||||
"
|
||||
@@ -0,0 +1,40 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
# QueryEngine (Заявка на двигател)
|
||||
|
||||
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите Pull Request, за да предложите промени.`
|
||||
|
||||
Заявка на двигател обвива `Retriever` и `ResponseSynthesizer` в тръбопровод, който използва низа от заявки, за да извлече възли и след това ги изпраща към LLM, за да генерира отговор.
|
||||
|
||||
```typescript
|
||||
const queryEngine = index.asQueryEngine();
|
||||
const response = await queryEngine.query("query string");
|
||||
```
|
||||
|
||||
## Заявка на подзапитване на двигател
|
||||
|
||||
Основната концепция на Заявка на подзапитване на двигател е, че тя разделя една заявка на множество заявки, получава отговор за всяка от тези заявки и след това комбинира тези различни отговори в един цялостен отговор за потребителя. Можете да си представите това като техника за "мислене стъпка по стъпка", но като итерира върху източниците на данни!
|
||||
|
||||
### Започване
|
||||
|
||||
Най-лесният начин да започнете да използвате Заявка на подзапитване на двигател е да стартирате файла subquestion.ts в [примерите](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/subquestion.ts).
|
||||
|
||||
```bash
|
||||
npx ts-node subquestion.ts
|
||||
```
|
||||
|
||||
### Инструменти
|
||||
|
||||
Заявка на подзапитване на двигател е реализирана с инструменти. Основната идея на инструментите е, че те са изпълними опции за големия езиков модел. В този случай нашият Заявка на подзапитване на двигател разчита на QueryEngineTool, който, както се предполага, е инструмент за изпълнение на заявки върху QueryEngine. Това ни позволява да дадем на модела възможност да заявява различни документи за различни въпроси, например. Също така можем да си представим, че Заявка на подзапитване на двигател може да използва инструмент, който търси нещо в Интернет или получава отговор, използвайки Wolfram Alpha.
|
||||
|
||||
Можете да научите повече за инструментите, като разгледате документацията на LlamaIndex Python https://gpt-index.readthedocs.io/en/latest/core_modules/agent_modules/tools/root.html
|
||||
|
||||
## API Reference (API справка)
|
||||
|
||||
- [RetrieverQueryEngine (Заявка на двигател за извличане)](../../api/classes/RetrieverQueryEngine.md)
|
||||
- [SubQuestionQueryEngine (Заявка на двигател за подзапитване)](../../api/classes/SubQuestionQueryEngine.md)
|
||||
- [QueryEngineTool (Инструмент за заявка на двигател)](../../api/interfaces/QueryEngineTool.md)
|
||||
|
||||
"
|
||||
@@ -0,0 +1,33 @@
|
||||
# Основни модули
|
||||
|
||||
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите Pull Request, за да предложите промени.`
|
||||
|
||||
LlamaIndex.TS предлага няколко основни модула, разделени на модули на високо ниво, за бързо стартиране, и модули на ниско ниво, за персонализиране на ключовите компоненти според вашите нужди.
|
||||
|
||||
## Модули на високо ниво
|
||||
|
||||
- [**Документ**](./high_level/documents_and_nodes.md): Документ представлява текстов файл, PDF файл или друг непрекъснат парче данни.
|
||||
|
||||
- [**Възел**](./high_level/documents_and_nodes.md): Основният строителен блок от данни. Най-често това са части от документа, разделени на управляеми парчета, достатъчно малки, за да бъдат подадени на модел за вграждане и LLM.
|
||||
|
||||
- [**Четец/Зареждач**](./high_level/data_loader.md): Четецът или зареждачът е нещо, което приема документ от реалния свят и го преобразува в клас Документ, който после може да се използва в индекса и заявките ви. В момента поддържаме обикновени текстови файлове и PDF файлове, с много други, които ще бъдат добавени.
|
||||
|
||||
- [**Индекси**](./high_level/data_index.md): Индексите съхраняват Възлите и вгражданията на тези възли.
|
||||
|
||||
- [**QueryEngine**](./high_level/query_engine.md): Заявките са това, което генерира заявката, която въвеждате и ви връща резултата. Заявките обикновено комбинират предварително изграден prompt със избрани възли от вашия индекс, за да предоставят на LLM контекста, от който се нуждае, за да отговори на вашата заявка.
|
||||
|
||||
- [**ChatEngine**](./high_level/chat_engine.md): ChatEngine ви помага да построите чатбот, който ще взаимодейства с вашите индекси.
|
||||
|
||||
## Модули на ниско ниво
|
||||
|
||||
- [**LLM**](./low_level/llm.md): Класът LLM е обединен интерфейс над голям доставчик на модели на езика като OpenAI GPT-4, Anthropic Claude или Meta LLaMA. Можете да го наследите, за да напишете конектор към собствен модел на голям език.
|
||||
|
||||
- [**Embedding**](./low_level/embedding.md): Вграждането се представя като вектор от числа с плаваща запетая. Нашето вграждане по подразбиране е OpenAI's text-embedding-ada-002 и всяко вграждане, което генерира, се състои от 1,536 числа с плаваща запетая. Друго популярно вграждане е BERT, което използва 768 числа с плаваща запетая, за да представи всеки възел. Предоставяме няколко помощни функции за работа с вграждания, включително 3 опции за изчисляване на подобие и Maximum Marginal Relevance.
|
||||
|
||||
- [**TextSplitter/NodeParser**](./low_level/node_parser.md): Стратегиите за разделяне на текст са изключително важни за общата ефективност на търсенето на вграждания. В момента, въпреки че имаме стойност по подразбиране, няма универсално решение. В зависимост от източниците на документите, може да искате да използвате различни размери и стратегии за разделяне. В момента поддържаме разделяне по фиксиран размер, разделяне по фиксиран размер с препокриващи се секции, разделяне по изречение и разделяне по параграф. TextSplitter се използва от NodeParser при разделянето на `Document` на `Node`.
|
||||
|
||||
- [**Retriever**](./low_level/retriever.md): Retriever е този, който наистина избира възлите за връщане от индекса. Тук може да желаете да опитате да вземете повече или по-малко възли за всяка заявка, да промените функцията за подобие или да създадете собствен retriever за всеки отделен случай в приложението си. Например може да желаете да имате отделен retriever за съдържание на код срещу текстово съдържание.
|
||||
|
||||
- [**ResponseSynthesizer**](./low_level/response_synthesizer.md): ResponseSynthesizer е отговорен за вземането на низ от заявка и използването на списък от `Node`-и за генериране на отговор. Това може да бъде в различни форми, като обхождане на всички контексти и уточняване на отговор, или изграждане на дърво от резюмета и връщане на кореновото резюме.
|
||||
|
||||
- [**Storage**](./low_level/storage.md): На някакъв етап ще искате да съхранявате индексите, данните и векторите си, вместо да изпълнявате моделите за вграждане всеки път. IndexStore, DocStore, VectorStore и KVStore са абстракции, които ви позволяват да го направите. Заедно те формират StorageContext. В момента ви позволяваме да запазвате вгражданията си във файлове на файловата система (или виртуална файлова система в паметта), но също така активно добавяме интеграции към Vector Databases.
|
||||
@@ -0,0 +1,26 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# Вграждане (Embedding)
|
||||
|
||||
`Тази документация е преведена автоматично и може да съдържа грешки. Не се колебайте да отворите Pull Request, за да предложите промени.`
|
||||
|
||||
Моделът за вграждане в LlamaIndex е отговорен за създаването на числови представяния на текст. По подразбиране, LlamaIndex използва модела `text-embedding-ada-002` от OpenAI.
|
||||
|
||||
Това може да бъде явно зададено в обекта `ServiceContext`.
|
||||
|
||||
```typescript
|
||||
import { OpenAIEmbedding, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const openaiEmbeds = new OpenAIEmbedding();
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ embedModel: openaiEmbeds });
|
||||
```
|
||||
|
||||
## API Референция
|
||||
|
||||
- [OpenAIEmbedding](../../api/classes/OpenAIEmbedding.md)
|
||||
- [ServiceContext](../../api/interfaces/ServiceContext.md)
|
||||
|
||||
"
|
||||