Compare commits

..

1 Commits

Author SHA1 Message Date
Emanuel Ferreira 14d5a1458c fix: remove storageContext 2024-02-26 12:02:19 -03:00
681 changed files with 22864 additions and 35599 deletions
+1 -1
View File
@@ -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",
+5
View File
@@ -0,0 +1,5 @@
---
"llamaindex": patch
---
feat: add base evaluator and correctness evaluator
+5
View File
@@ -0,0 +1,5 @@
---
"llamaindex": patch
---
feat: add base evaluator and correctness evaluator
+6
View File
@@ -0,0 +1,6 @@
---
"llamaindex": patch
"docs": patch
---
Add Groq LLM to LlamaIndex
-16
View File
@@ -1,16 +0,0 @@
{
"jsc": {
"parser": {
"syntax": "typescript",
"decorators": true
},
"target": "esnext",
"transform": {
"decoratorVersion": "2022-03"
}
},
"module": {
"type": "commonjs",
"ignoreDynamic": true
}
}
-76
View File
@@ -1,76 +0,0 @@
module.exports = {
root: true,
extends: [
"turbo",
"prettier",
"plugin:@typescript-eslint/recommended-type-checked-only",
],
parserOptions: {
project: true,
__tsconfigRootDir: __dirname,
},
settings: {
react: {
version: "999.999.999",
},
},
rules: {
"max-params": ["error", 4],
"prefer-const": "error",
"@typescript-eslint/no-floating-promises": [
"error",
{
ignoreIIFE: true,
},
],
"@typescript-eslint/await-thenable": "off",
"@typescript-eslint/ban-ts-comment": "off",
"@typescript-eslint/ban-types": "off",
"no-array-constructor": "off",
"@typescript-eslint/no-array-constructor": "off",
"@typescript-eslint/no-base-to-string": "off",
"@typescript-eslint/no-duplicate-enum-values": "off",
"@typescript-eslint/no-duplicate-type-constituents": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-extra-non-null-assertion": "off",
"@typescript-eslint/no-for-in-array": "off",
"no-implied-eval": "off",
"@typescript-eslint/no-implied-eval": "off",
"no-loss-of-precision": "off",
"@typescript-eslint/no-loss-of-precision": "off",
"@typescript-eslint/no-misused-new": "off",
"@typescript-eslint/no-misused-promises": "off",
"@typescript-eslint/no-namespace": "off",
"@typescript-eslint/no-non-null-asserted-optional-chain": "off",
"@typescript-eslint/no-redundant-type-constituents": "off",
"@typescript-eslint/no-this-alias": "off",
"@typescript-eslint/no-unnecessary-type-assertion": "off",
"@typescript-eslint/no-unnecessary-type-constraint": "off",
"@typescript-eslint/no-unsafe-argument": "off",
"@typescript-eslint/no-unsafe-assignment": "off",
"@typescript-eslint/no-unsafe-call": "off",
"@typescript-eslint/no-unsafe-declaration-merging": "off",
"@typescript-eslint/no-unsafe-enum-comparison": "off",
"@typescript-eslint/no-unsafe-member-access": "off",
"@typescript-eslint/no-unsafe-return": "off",
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": "off",
"@typescript-eslint/no-var-requires": "off",
"@typescript-eslint/prefer-as-const": "off",
"require-await": "off",
"@typescript-eslint/require-await": "off",
"@typescript-eslint/restrict-plus-operands": "off",
"@typescript-eslint/restrict-template-expressions": "off",
"@typescript-eslint/triple-slash-reference": "off",
"@typescript-eslint/unbound-method": "off",
},
overrides: [
{
files: ["examples/**/*.ts"],
rules: {
"turbo/no-undeclared-env-vars": "off",
},
},
],
ignorePatterns: ["dist/", "lib/", "deps/"],
};
+15
View File
@@ -0,0 +1,15 @@
module.exports = {
root: true,
// This tells ESLint to load the config from the package `eslint-config-custom`
extends: ["custom"],
settings: {
next: {
rootDir: ["apps/*/"],
},
},
rules: {
"max-params": ["error", 4],
"prefer-const": "error",
},
ignorePatterns: ["dist/", "lib/"],
};
+68
View File
@@ -0,0 +1,68 @@
name: E2E Tests
on:
push:
branches: [main]
pull_request:
paths:
- "packages/create-llama/**"
- ".github/workflows/e2e.yml"
branches: [main]
env:
POETRY_VERSION: "1.6.1"
jobs:
e2e:
name: create-llama
timeout-minutes: 60
strategy:
fail-fast: true
matrix:
node-version: [18, 20]
python-version: ["3.11"]
os: [macos-latest, windows-latest]
defaults:
run:
shell: bash
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- name: Set up python ${{ matrix.python-version }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- name: Install Poetry
uses: snok/install-poetry@v1
with:
version: ${{ env.POETRY_VERSION }}
- uses: pnpm/action-setup@v2
- name: Setup Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: "pnpm"
- name: Install dependencies
run: pnpm install
- name: Install Playwright Browsers
run: pnpm exec playwright install --with-deps
working-directory: ./packages/create-llama
- name: Build create-llama
run: pnpm run build
working-directory: ./packages/create-llama
- name: Pack
run: pnpm pack --pack-destination ./output
working-directory: ./packages/create-llama
- name: Extract Pack
run: tar -xvzf ./output/*.tgz -C ./output
working-directory: ./packages/create-llama
- name: Run Playwright tests
run: pnpm exec playwright test
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
working-directory: ./packages/create-llama
- uses: actions/upload-artifact@v3
if: always()
with:
name: playwright-report
path: ./packages/create-llama/playwright-report/
retention-days: 30
+3 -1
View File
@@ -13,7 +13,9 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
- uses: pnpm/action-setup@v2
with:
version: latest
- name: Setup Node.js
uses: actions/setup-node@v4
with:
-36
View File
@@ -1,36 +0,0 @@
name: Publish
on:
push:
branches:
- main
jobs:
publish:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
cache: "pnpm"
- name: Install dependencies
run: pnpm install
- name: Publish @llamaindex/env
run: npx jsr publish
working-directory: packages/env
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Publish @llamaindex/core
run: npx jsr publish --allow-slow-types
working-directory: packages/core
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
-37
View File
@@ -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@v3
- 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/core
- name: Create release
uses: ncipollo/release-action@v1
with:
artifacts: "packages/core/llamaindex-*.tgz"
name: Release ${{ github.ref }}
bodyFile: "packages/core/CHANGELOG.md"
token: ${{ secrets.GITHUB_TOKEN }}
-57
View File
@@ -1,57 +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@v3
- 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 }}
+5 -71
View File
@@ -1,55 +1,18 @@
name: Run Tests
on:
push:
branches:
- main
pull_request:
branches:
- main
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
on: [push, pull_request]
jobs:
e2e:
strategy:
fail-fast: false
matrix:
node-version: [18.x, 20.x, 22.x]
name: E2E on Node.js ${{ matrix.node-version }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
- 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: [18.x, 20.x, 22.x]
name: Test on Node.js ${{ matrix.node-version }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
- uses: pnpm/action-setup@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
@@ -60,7 +23,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
- uses: pnpm/action-setup@v2
- name: Setup Node.js
uses: actions/setup-node@v4
with:
@@ -70,9 +33,6 @@ jobs:
run: pnpm install
- name: Build
run: pnpm run build --filter llamaindex
- name: Use Build For Examples
run: pnpm link ../packages/core/
working-directory: ./examples
- name: Run Type Check
run: pnpm run type-check
- name: Run Circular Dependency Check
@@ -84,38 +44,12 @@ jobs:
name: typecheck-build-dist
path: ./packages/core/dist
if-no-files-found: error
e2e-core-examples:
strategy:
matrix:
packages:
- cloudflare-worker-agent
- nextjs-agent
- nextjs-edge-runtime
- waku-query-engine
runs-on: ubuntu-latest
name: Build Core Example (${{ matrix.packages }})
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
cache: "pnpm"
- name: Install dependencies
run: pnpm install
- name: Build llamaindex
run: pnpm run build --filter llamaindex
- name: Build ${{ matrix.packages }}
run: pnpm run build
working-directory: packages/core/e2e/examples/${{ matrix.packages }}
typecheck-examples:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
- uses: pnpm/action-setup@v2
- name: Setup Node.js
uses: actions/setup-node@v4
with:
-1
View File
@@ -44,7 +44,6 @@ test-results/
playwright-report/
blob-report/
playwright/.cache/
.tsbuildinfo
# intellij
**/.idea
+1 -1
View File
@@ -1,3 +1,3 @@
pnpm format:write
pnpm format
pnpm lint
npx lint-staged
+1
View File
@@ -0,0 +1 @@
pnpm test
-3
View File
@@ -1,5 +1,2 @@
auto-install-peers = true
enable-pre-post-scripts = true
prefer-workspace-packages = true
save-workspace-protocol = true
link-workspace-packages = true
+1 -1
View File
@@ -1 +1 @@
20
18
-12
View File
@@ -1,12 +0,0 @@
{
"jsc": {
"parser": {
"syntax": "typescript",
"decorators": true
},
"target": "esnext",
"transform": {
"decoratorVersion": "2022-03"
}
}
}
+1 -2
View File
@@ -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}"]
}
]
}
+8 -16
View File
@@ -79,22 +79,14 @@ That should start a webserver which will serve the docs on https://localhost:300
Any changes you make should be reflected in the browser. If you need to regenerate the API docs and find that your TSDoc isn't getting the updates, feel free to remove apps/docs/api. It will automatically regenerate itself when you run pnpm start again.
## Changeset
## Publishing
We use [changesets](https://github.com/changesets/changesets) for managing versions and changelogs. To create a new changeset, run:
To publish a new version of the library, run
```shell
pnpm new-llamaindex
pnpm new-create-llama
pnpm release
git push # push to the main branch
git push --tags
```
pnpm changeset
```
Please send a descriptive changeset for each PR.
## Publishing (maintainers only)
The [Release Github Action](.github/workflows/release.yml) is automatically generating and updating a
PR called "Release {version}".
This PR will update the `package.json` and `CHANGELOG.md` files of each package according to
the current changesets in the [.changeset](.changeset/) folder.
If this PR is merged it will automatically add version tags to the repository and publish the updated packages to NPM.
+81
View File
@@ -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)
+40 -154
View File
@@ -19,29 +19,25 @@ Try examples online:
LlamaIndex.TS aims to be a lightweight, easy to use set of libraries to help you integrate large language models into your applications with your own data.
## Multiple JS Environment Support
## Getting started with an example:
LlamaIndex.TS supports multiple JS environments, including:
LlamaIndex.TS requires Node v18 or higher. You can download it from https://nodejs.org or use https://nvm.sh (our preferred option).
- Node.js (18, 20, 22) ✅
- Deno ✅
- Bun ✅
- React Server Components (Next.js) ✅
In a new folder:
For now, browser support is limited due to the lack of support for [AsyncLocalStorage-like APIs](https://github.com/tc39/proposal-async-context)
## Getting started
```shell
npm install llamaindex
```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
jsr install @llamaindex/core
pnpm install @types/node
```
### Node.js
Create the file example.ts
```ts
// example.ts
import fs from "fs/promises";
import { Document, VectorStoreIndex } from "llamaindex";
@@ -71,110 +67,10 @@ async function main() {
main();
```
Then you can run it using
```bash
# `pnpm install tsx` before running the script
node --import tsx ./main.ts
```
### Next.js
You can combine `ai` with `llamaindex` in Next.js with RSC (React Server Components).
```tsx
// src/apps/page.tsx
"use client";
import { chatWithAgent } from "@/actions";
import type { JSX } from "react";
import { useFormState } from "react-dom";
// You can use the Edge runtime in Next.js by adding this line:
// export const runtime = "edge";
export default function Home() {
const [ui, action] = useFormState<JSX.Element | null>(async () => {
return chatWithAgent("hello!", []);
}, null);
return (
<main>
{ui}
<form action={action}>
<button>Chat</button>
</form>
</main>
);
}
```
```tsx
// src/actions/index.ts
"use server";
import { createStreamableUI } from "ai/rsc";
import { OpenAIAgent } from "llamaindex";
import type { ChatMessage } from "llamaindex/llm/types";
export async function chatWithAgent(
question: string,
prevMessages: ChatMessage[] = [],
) {
const agent = new OpenAIAgent({
tools: [
// ... adding your tools here
],
});
const responseStream = await agent.chat({
stream: true,
message: question,
chatHistory: prevMessages,
});
const uiStream = createStreamableUI(<div>loading...</div>);
responseStream
.pipeTo(
new WritableStream({
start: () => {
uiStream.update("response:");
},
write: async (message) => {
uiStream.append(message.response.delta);
},
}),
)
.catch(console.error);
return uiStream.value;
}
```
### Cloudflare Workers
```ts
// src/index.ts
export default {
async fetch(
request: Request,
env: Env,
ctx: ExecutionContext,
): Promise<Response> {
const { setEnvs } = await import("@llamaindex/env");
// set environment variables so that the OpenAIAgent can use them
setEnvs(env);
const { OpenAIAgent } = await import("llamaindex");
const agent = new OpenAIAgent({
tools: [],
});
const responseStream = await agent.chat({
stream: true,
message: "Hello? What is the weather today?",
});
const textEncoder = new TextEncoder();
const response = responseStream.pipeThrough(
new TransformStream({
transform: (chunk, controller) => {
controller.enqueue(textEncoder.encode(chunk.response.delta));
},
}),
);
return new Response(response);
},
};
pnpm dlx ts-node example.ts
```
## Playground
@@ -187,60 +83,50 @@ Check out our NextJS playground at https://llama-playground.vercel.app/. The sou
- [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/embeddings/OpenAIEmbedding.ts): Embeddings are sets of floating point numbers which represent the data in a Node. By comparing the similarity of embeddings, we can derive an understanding of the similarity of two pieces of data. One use case is to compare the embedding of a question with the embeddings of our Nodes to see which Nodes may contain the data needed to answer that quesiton. Because the default service context is OpenAI, the default embedding is `OpenAIEmbedding`. If using different models, say through Ollama, use this [Embedding](/packages/core/src/embeddings/OllamaEmbedding.ts) (see all [here](/packages/core/src/embeddings)).
- [Embedding](/packages/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/engines/query/RetrieverQueryEngine.ts): Query engines are what generate the query you put in and give you back the result. Query engines generally combine a pre-built prompt with selected Nodes from your Index to give the LLM the context it needs to answer your query. To build a query engine from your Index (recommended), use the [`asQueryEngine`](/packages/core/src/indices/BaseIndex.ts) method on your Index. See all query engines [here](/packages/core/src/engines/query).
- [QueryEngine](/packages/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/engines/chat/SimpleChatEngine.ts): A ChatEngine helps you build a chatbot that will interact with your Indices. See all chat engines [here](/packages/core/src/engines/chat).
- [ChatEngine](/packages/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.
## Tips when using in non-Node.js environments
## Note: NextJS:
When you are importing `llamaindex` in a non-Node.js environment(such as React Server Components, Cloudflare Workers, etc.)
Some classes are not exported from top-level entry file.
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.
The reason is that some classes are only compatible with Node.js runtime,(e.g. `PDFReader`) which uses Node.js specific APIs(like `fs`, `child_process`, `crypto`).
If you need any of those classes, you have to import them instead directly though their file path in the package.
Here's an example for importing the `PineconeVectorStore` class:
```typescript
import { PineconeVectorStore } from "llamaindex/storage/vectorStore/PineconeVectorStore";
```js
export const runtime = "nodejs"; // default
```
As the `PDFReader` is not working with the Edge runtime, here's how to use the `SimpleDirectoryReader` with the `LlamaParseReader` to load PDFs:
```js
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
serverComponentsExternalPackages: ["pdf2json"],
},
webpack: (config) => {
config.resolve.alias = {
...config.resolve.alias,
sharp$: false,
"onnxruntime-node$": false,
};
return config;
},
};
```typescript
import { SimpleDirectoryReader } from "llamaindex/readers/SimpleDirectoryReader";
import { LlamaParseReader } from "llamaindex/readers/LlamaParseReader";
export const DATA_DIR = "./data";
export async function getDocuments() {
const reader = new SimpleDirectoryReader();
// Load PDFs using LlamaParseReader
return await reader.loadData({
directoryPath: DATA_DIR,
fileExtToReader: {
pdf: new LlamaParseReader({ resultType: "markdown" }),
},
});
}
module.exports = nextConfig;
```
> _Note_: Reader classes have to be added explictly to the `fileExtToReader` map in the Edge version of the `SimpleDirectoryReader`.
You'll find a complete example with LlamaIndexTS here: https://github.com/run-llama/create_llama_projects/tree/main/nextjs-edge-llamaparse
## Supported LLMs:
- OpenAI GPT-3.5-turbo and GPT-4
- Anthropic Claude 3 (Opus, Sonnet, and Haiku) and the legacy models (Claude 2 and Instant)
- Anthropic Claude Instant and Claude 2
- Groq LLMs
- Llama2/3 Chat LLMs (70B, 13B, and 7B parameters)
- Llama2 Chat LLMs (70B, 13B, and 7B parameters)
- MistralAI Chat LLMs
- Fireworks Chat LLMs
-104
View File
@@ -1,109 +1,5 @@
# docs
## 0.0.15
### Patch Changes
- Updated dependencies [b6a6606]
- Updated dependencies [b6a6606]
- llamaindex@0.3.7
## 0.0.14
### Patch Changes
- Updated dependencies [efa326a]
- llamaindex@0.3.6
## 0.0.13
### Patch Changes
- Updated dependencies [bc7a11c]
- Updated dependencies [2fe2b81]
- Updated dependencies [5596e31]
- Updated dependencies [e74fe88]
- Updated dependencies [be5df5b]
- llamaindex@0.3.5
## 0.0.12
### Patch Changes
- Updated dependencies [1dce275]
- Updated dependencies [d10533e]
- Updated dependencies [2008efe]
- Updated dependencies [5e61934]
- Updated dependencies [9e74a43]
- Updated dependencies [ee719a1]
- llamaindex@0.3.4
## 0.0.11
### Patch Changes
- Updated dependencies [e8c41c5]
- llamaindex@0.3.3
## 0.0.10
### Patch Changes
- Updated dependencies [61103b6]
- llamaindex@0.3.2
## 0.0.9
### Patch Changes
- Updated dependencies [46227f2]
- llamaindex@0.3.1
## 0.0.8
### Patch Changes
- Updated dependencies [5016f21]
- llamaindex@0.3.0
## 0.0.7
### Patch Changes
- Updated dependencies [6277105]
- llamaindex@0.2.13
## 0.0.6
### Patch Changes
- Updated dependencies [d8d952d]
- llamaindex@0.2.12
## 0.0.5
### Patch Changes
- Updated dependencies [87142b2]
- Updated dependencies [5a6cc0e]
- Updated dependencies [87142b2]
- llamaindex@0.2.11
## 0.0.4
### Patch Changes
- Updated dependencies [5116ad8]
- @llamaindex/env@0.0.5
## 0.0.3
### Patch Changes
- 09bf27a: Add Groq LLM to LlamaIndex
- Updated dependencies [cf87f84]
- @llamaindex/env@0.0.4
## 0.0.2
### Patch Changes
-493
View File
@@ -1,493 +0,0 @@
---
title: LlamaIndexTS v0.3.0
description: This is my first post on Docusaurus.
slug: welcome-llamaindexts-v0.3
authors:
- name: Alex Yang
title: LlamaIndexTS maintainer, Node.js Member
url: https://github.com/himself65
image_url: https://github.com/himself65.png
tags: [llamaindex, agent]
hide_table_of_contents: false
---
- [What's new in LlamaIndexTS v0.3.0](#whats-new-in-llamaindexts-v030)
- [Improvement in LlamaIndexTS v0.3.0](#improvement-in-llamaindexts-v030)
- [What's the next?](#whats-the-next)
## What's new in LlamaIndexTS v0.3.0
## Agents
In this release, we've not only ported the Agent module from the LlamaIndex Python version but have significantly
enhanced it to be more powerful and user-friendly for JavaScript/TypeScript applications.
Starting from v0.3.0, we are introducing multiple agents specifically designed for RAG applications, including:
- `OpenAIAgent`
- `AnthropicAgent`
- `ReActAgent`:
```ts
import { OpenAIAgent } from "llamaindex";
import { tools } from "./tools";
const agent = new OpenAIAgent({
tools: [...tools],
});
const { response } = await agent.chat({
message: "What is weather today?",
stream: false,
});
console.log(response.message.content);
```
We are also introducing the abstract AgentRunner class, which allows you to create your own agent by simply implementing
the task handler.
```ts
import { AgentRunner, OpenAI } from "llamaindex";
class MyLLM extends OpenAI {}
export class MyAgentWorker extends AgentWorker<MyLLM> {
taskHandler = MyAgent.taskHandler;
}
export class MyAgent extends AgentRunner<MyLLM> {
constructor(params: Params) {
super({
llm: params.llm,
chatHistory: params.chatHistory ?? [],
systemPrompt: params.systemPrompt ?? null,
runner: new MyAgentWorker(),
tools:
"tools" in params
? params.tools
: params.toolRetriever.retrieve.bind(params.toolRetriever),
});
}
// create store is a function to create a store for each task, by default it only includes `messages` and `toolOutputs`
createStore = AgentRunner.defaultCreateStore;
static taskHandler: TaskHandler<Anthropic> = async (step, enqueueOutput) => {
const { llm, stream } = step.context;
// initialize the input
const response = await llm.chat({
stream,
messages: step.context.store.messages,
});
// store the response for next task step
step.context.store.messages = [
...step.context.store.messages,
response.message,
];
// your logic here to decide whether to continue the task
const shouldContinue = Math.random(); /* <-- replace with your logic here */
enqueueOutput({
taskStep: step,
output: response,
isLast: !shouldContinue,
});
if (shouldContinue) {
const content = await someHeavyFunctionCall();
// if you want to continue the task, you can insert your new context for the next task step
step.context.store.messages = [
...step.context.store.messages,
{
content,
role: "user",
},
];
}
};
}
```
### Web Stream API for Streaming response
Web Stream is a web standard utilized in many modern web frameworks and libraries (like React 19, Deno, Node 22). We
have migrated streaming responses to Web Stream to ensure broader compatibility.
For instance, you can use the streaming response in a simple HTTP Server:
```ts
import { createServer } from "http";
import { OpenAIAgent } from "llamaindex";
import { OpenAIStream, streamToResponse } from "ai";
import { tools } from "./tools";
const agent = new OpenAIAgent({
tools: [...tools],
});
const server = createServer(async (req, res) => {
const response = await agent.chat({
message: "What is weather today?",
stream: true,
});
// Transform the response into a string readable stream
const stream: ReadableStream<string> = response.pipeThrough(
new TransformStream({
transform: (chunk, controller) => {
controller.enqueue(chunk.response.delta);
},
}),
);
// Pipe the stream to the response
streamToResponse(stream, res);
});
server.listen(3000);
```
Or it can be integrated into React Server Components (RSC) in Next.js:
```tsx
// app/actions/index.tsx
"use server";
import { createStreamableUI } from "ai/rsc";
import { OpenAIAgent } from "llamaindex";
import type { ChatMessage } from "llamaindex/llm/types";
export async function chatWithAgent(
question: string,
prevMessages: ChatMessage[] = [],
) {
const agent = new OpenAIAgent({
tools: [],
});
const responseStream = await agent.chat({
stream: true,
message: question,
chatHistory: prevMessages,
});
const uiStream = createStreamableUI(<div>loading...</div>);
responseStream
.pipeTo(
new WritableStream({
start: () => {
uiStream.update("response:");
},
write: async (message) => {
uiStream.append(message.response.delta);
},
}),
)
.catch(uiStream.error);
return uiStream.value;
}
```
```tsx
// app/src/page.tsx
"use client";
import { chatWithAgent } from "@/actions";
import type { JSX } from "react";
import { useFormState } from "react-dom";
export const runtime = "edge";
export default function Home() {
const [state, action] = useFormState<JSX.Element | null>(async () => {
return chatWithAgent("hello!", []);
}, null);
return (
<main>
{state}
<form action={action}>
<button>Chat</button>
</form>
</main>
);
}
```
## Improvement in LlamaIndexTS v0.3.0
### Better TypeScript support
We have made significant improvements to the type system to ensure that all code is thoroughly checked before it is
published. This ongoing enhancement has already resulted in better module reliability and developer experience.
For example, we have improved `FunctionTool` type with generic support:
```ts
type Input = {
a: number;
b: number;
};
const sumNumbers = FunctionTool.from<Input>(
({ a, b }) => `${a + b}`, // a and b will be checked as number
// JSON schema will be an error if you type wrong.
{
name: "sumNumbers",
description: "Use this function to sum two numbers",
parameters: {
type: "object",
properties: {
a: {
type: "number",
description: "The first number",
},
b: {
type: "number",
description: "The second number",
},
},
required: ["a", "b"],
},
},
);
```
![type checking](./img/function_tool_example.png)
### Better Next.js, Deno, Cloudflare Worker, and Waku(Vite) support
In addition to Node.js, LlamaIndexTS now offers enhanced support for Next.js, Deno, and Cloudflare Workers, making it
more versatile across different platforms.
For now, you can install llamaindex and directly import it into your existing Next.js, Deno or Cloudflare Worker project
**without any extra configuration**.
#### [Deno](https://deno.com/)
You can use LlamaIndexTS in Deno by installation through JSR:
```sh
jsr add @llamaindex/core
```
#### [Cloudflare Worker](https://developers.cloudflare.com/workers/)
For Cloudflare Workers, here is a starter template:
```typescript
export default {
async fetch(
request: Request,
env: Env,
ctx: ExecutionContext,
): Promise<Response> {
const { setEnvs } = await import("@llamaindex/env");
setEnvs(env);
const { OpenAIAgent } = await import("llamaindex");
const agent = new OpenAIAgent({
tools: [],
});
const responseStream = await agent.chat({
stream: true,
message: "Hello? What is the weather today?",
});
const textEncoder = new TextEncoder();
const response = responseStream.pipeThrough(
new TransformStream({
transform: (chunk, controller) => {
controller.enqueue(textEncoder.encode(chunk.response.delta));
},
}),
);
return new Response(response);
},
};
```
### [Waku (Vite)](https://waku.gg/)
Waku powered by Vite is a minimal React framework that supports multiple JS environments, including Deno, Cloudflare, and
Node.js.
You can use LlamaIndexTS with Node.js output to enable full Node.js support with React.
```sh
npm install llamaindex
```
```ts
// file: src/actions.ts
"use server";
import { Document, VectorStoreIndex } from "llamaindex";
import { readFile } from "node:fs/promises";
const path = "node_modules/llamaindex/examples/abramov.txt";
const essay = await readFile(path, "utf-8");
// Create Document object with essay
const document = new Document({ text: essay, id_: path });
// Split text and create embeddings. Store them in a VectorStoreIndex
const index = await VectorStoreIndex.fromDocuments([document]);
const queryEngine = index.asQueryEngine();
export async function chatWithAI(question: string): Promise<string> {
const { response } = await queryEngine.query({ query: question });
return response;
}
```
```tsx
// file: src/pages/index.tsx
import { chatWithAI } from "./actions";
export default async function HomePage() {
return (
<div>
<Chat askQuestion={chatWithAI} />
</div>
);
}
```
```tsx
// file: src/components/Chat.tsx
"use client";
export type ChatProps = {
askQuestion: (question: string) => Promise<string>;
};
export const Chat = (props: ChatProps) => {
const [response, setResponse] = useState<string | null>(null);
return (
<section className="border-blue-400 -mx-4 mt-4 rounded border border-dashed p-4">
<h2 className="text-lg font-bold">Chat with AI</h2>
{response ? (
<p className="text-sm text-gray-600 max-w-sm">{response}</p>
) : null}
<form
action={async (formData) => {
const question = formData.get("question") as string | null;
if (question) {
setResponse(await props.askQuestion(question));
}
}}
>
<input
type="text"
name="question"
className="border border-gray-400 rounded-sm px-2 py-0.5 text-sm"
/>
<button className="rounded-sm bg-black px-2 py-0.5 text-sm text-white">
Ask
</button>
</form>
</section>
);
};
```
```shell
waku dev # development mode
waku build # build for production
waku start # start the production server
```
Note that not all the modules are supported in all JS environments because of
lack of the file system, network API,
and incompatibility with the Node.js API by upstream dependencies.
But we are trying to make it more compatible with all the environments.
## What's the next?
As we continue to develop LlamaIndexTS, our focus remains on providing more comprehensive and powerful tools for
creating custom agents.
### Align with the Python `llama-index`
We aim to align LlamaIndexTS with the Python version to ensure API consistency and ease of use for developers familiar
with the Python ecosystem.
### Align with the Web Standard and JS development
Not all python APIs are compatible and easy to use in JavaScript/TypeScript.
We are trying to make the API more compatible with the Web Standard and JavaScript modern development.
### More Agents
Future releases will introduce more agents from the Python Llama-Index and explore APIs tailored to real-world use
cases.
### 🧪 `@llamaindex/tool`
We are exploring innovative ways to create tools for agents. The `@llamaindex/tool` library allows you to transform any
function into a tool for an agent, simplifying the development process and reducing runtime costs.
```ts
export function getWeather(city: string) {
return `The weather in ${city} is sunny.`;
}
// you don't need to worry about the shcema with different llm tools
export function getTemperature(city: string) {
return `The temperature in ${city} is 25°C.`;
}
export function getCurrentCity() {
return "New York";
}
```
These functions can be easily integrated into your applications, such as Next.js:
```ts
"use server";
import { OpenAI } from "openai";
import { getTools } from "@llamaindex/tool";
export async function chat(message: string) {
const openai = new OpenAI();
openai.chat.completions.create({
messages: [
{
role: "user",
content: "What is the weather in the current city?",
},
],
tools: getTools("openai"),
});
}
```
```ts
// next.config.js
const withTool = require("@llamaindex/tool/next");
const config = {
// Your original Next.js config
};
module.exports = withTool(config);
```
The functions are automatically transformed into tools for the agent at compile time, which eliminates any extra runtime
costs. This feature is particularly beneficial when you need to debug or deploy your assistant.
For deploying your local functions into OpenAI, you can use a simple command:
```sh
npm install -g @llamaindex/tool
mkai --tools ./src/index.llama.ts
# Successfully created assistant: asst_XXX
# chat with your assistant by `chatai --assistant asst_XXX`
chatai --assistant asst_XXX
# Open your browser and chat with your assistant
# Running at http://localhost:3000
```
This deployment process simplifies the testing and implementation of your custom tools in a live environment.
As this project is still in its early stages, we continue to explore the best ways to create and integrate tools for
agents. For more information and updates, visit the @llamaindex/tool repository.
This release of LlamaIndexTS v0.3.0 marks a significant step forward in our journey to provide developers with robust,
flexible tools for building advanced agents. We are excited to see how our community utilizes these new capabilities to
create innovative solutions and look forward to continuing to support and enhance LlamaIndexTS in future updates.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 178 KiB

+78 -3
View File
@@ -4,7 +4,82 @@ A built-in agent that can take decisions and reasoning based on the tools provid
## OpenAI Agent
import CodeBlock from "@theme/CodeBlock";
import CodeSource from "!raw-loader!../../../../examples/agent/openai";
```ts
import { FunctionTool, OpenAIAgent } from "llamaindex";
<CodeBlock language="ts">{CodeSource}</CodeBlock>
// Define a function to sum two numbers
function sumNumbers({ a, b }: { a: number; b: number }): number {
return a + b;
}
// Define a function to divide two numbers
function divideNumbers({ a, b }: { a: number; b: number }): number {
return a / b;
}
// Define the parameters of the sum function as a JSON schema
const sumJSON = {
type: "object",
properties: {
a: {
type: "number",
description: "The first number",
},
b: {
type: "number",
description: "The second number",
},
},
required: ["a", "b"],
};
// Define the parameters of the divide function as a JSON schema
const divideJSON = {
type: "object",
properties: {
a: {
type: "number",
description: "The dividend to divide",
},
b: {
type: "number",
description: "The divisor to divide by",
},
},
required: ["a", "b"],
};
async function main() {
// Create a function tool from the sum function
const sumFunctionTool = new FunctionTool(sumNumbers, {
name: "sumNumbers",
description: "Use this function to sum two numbers",
parameters: sumJSON,
});
// Create a function tool from the divide function
const divideFunctionTool = new FunctionTool(divideNumbers, {
name: "divideNumbers",
description: "Use this function to divide two numbers"
parameters: divideJSON,
});
// Create an OpenAIAgent with the function tools
const agent = new OpenAIAgent({
tools: [sumFunctionTool, divideFunctionTool],
verbose: true,
});
// Chat with the agent
const response = await agent.chat({
message: "How much is 5 + 5? then divide by 2",
});
// Print the response
console.log(String(response));
}
main().then(() => {
console.log("Done");
});
```
+56
View File
@@ -0,0 +1,56 @@
---
sidebar_position: 1
---
# Starter Tutorial
Once you have [installed LlamaIndex.TS using NPM](installation) and set up your OpenAI key, you're ready to start your first app:
In a new folder:
```bash npm2yarn
npm install typescript
npm install @types/node
npx tsc --init # if needed
```
Create the file `example.ts`. This code will load some example data, create a document, index it (which creates embeddings using OpenAI), and then creates query engine to answer questions about the data.
```ts
// example.ts
import fs from "fs/promises";
import { Document, VectorStoreIndex } from "llamaindex";
async function main() {
// Load essay from abramov.txt in Node
const essay = await fs.readFile(
"node_modules/llamaindex/examples/abramov.txt",
"utf-8",
);
// Create Document object with essay
const document = new Document({ text: essay });
// Split text and create embeddings. Store them in a VectorStoreIndex
const index = await VectorStoreIndex.fromDocuments([document]);
// Query the index
const queryEngine = index.asQueryEngine();
const response = await queryEngine.query({
query: "What did the author do in college?",
});
// Output response
console.log(response.toString());
}
main();
```
Then you can run it using
```bash
npx ts-node example.ts
```
Ready to learn more? Check out our NextJS playground at https://llama-playground.vercel.app/. The source is available at https://github.com/run-llama/ts-playground
@@ -1,51 +0,0 @@
---
sidebar_position: 1
---
import CodeBlock from "@theme/CodeBlock";
import CodeSource from "!raw-loader!../../../../examples/vectorIndex";
import TSConfigSource from "!!raw-loader!../../../../examples/tsconfig.json";
# Starter Tutorial
Make sure you have installed LlamaIndex.TS and have an OpenAI key. If you haven't, check out the [installation](installation) guide.
## From scratch(node.js + TypeScript):
In a new folder:
```bash npm2yarn
npm init
npm install -D typescript @types/node
```
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.
<CodeBlock language="ts">{CodeSource}</CodeBlock>
Create a `tsconfig.json` file in the same folder:
<CodeBlock language="json">{TSConfigSource}</CodeBlock>
Now you can run the code with
```bash
npx tsx example.ts
```
Also, you can clone our examples and try them out:
```bash npm2yarn
npx degit run-llama/LlamaIndexTS/examples my-new-project
cd my-new-project
npm install
npx tsx ./vectorIndex.ts
```
## From scratch (Next.js + TypeScript):
You just need one command to create a new Next.js project:
```bash npm2yarn
npx create-llama@latest
```
+1 -1
View File
@@ -37,7 +37,7 @@ For more complex applications, our lower-level APIs allow advanced users to cust
`npm install llamaindex`
Our documentation includes [Installation Instructions](./getting_started/installation.mdx) and a [Starter Tutorial](./getting_started/starter.mdx) to build your first application.
Our documentation includes [Installation Instructions](./getting_started/installation.mdx) and a [Starter Tutorial](./getting_started/starter.md) to build your first application.
Once you're up and running, [High-Level Concepts](./getting_started/concepts.md) has an overview of LlamaIndex's modular architecture. For more hands-on practical examples, look through our Examples section on the sidebar.
+1 -7
View File
@@ -11,10 +11,4 @@ An “agent” is an automated reasoning and decision engine. It takes in a user
LlamaIndex.TS comes with a few built-in agents, but you can also create your own. The built-in agents include:
- OpenAI Agent
- Anthropic Agent
- ReACT Agent
## Examples
- [OpenAI Agent](../../examples/agent.mdx)
- [OpenAI Agent](./openai.mdx)
@@ -0,0 +1,314 @@
# Multi-Document Agent
In this guide, you learn towards setting up an agent that can effectively answer different types of questions over a larger set of documents.
These questions include the following
- QA over a specific doc
- QA comparing different docs
- Summaries over a specific doc
- Comparing summaries between different docs
We do this with the following architecture:
- setup a “document agent” over each Document: each doc agent can do QA/summarization within its doc
- setup a top-level agent over this set of document agents. Do tool retrieval and then do CoT over the set of tools to answer a question.
## Setup and Download Data
We first start by installing the necessary libraries and downloading the data.
```bash
pnpm i llamaindex
```
```ts
import {
Document,
ObjectIndex,
OpenAI,
OpenAIAgent,
QueryEngineTool,
SimpleNodeParser,
SimpleToolNodeMapping,
SummaryIndex,
VectorStoreIndex,
serviceContextFromDefaults,
storageContextFromDefaults,
} from "llamaindex";
```
And then for the data we will run through a list of countries and download the wikipedia page for each country.
```ts
import fs from "fs";
import path from "path";
const dataPath = path.join(__dirname, "tmp_data");
const extractWikipediaTitle = async (title: string) => {
const fileExists = fs.existsSync(path.join(dataPath, `${title}.txt`));
if (fileExists) {
console.log(`File already exists for the title: ${title}`);
return;
}
const queryParams = new URLSearchParams({
action: "query",
format: "json",
titles: title,
prop: "extracts",
explaintext: "true",
});
const url = `https://en.wikipedia.org/w/api.php?${queryParams}`;
const response = await fetch(url);
const data: any = await response.json();
const pages = data.query.pages;
const page = pages[Object.keys(pages)[0]];
const wikiText = page.extract;
await new Promise((resolve) => {
fs.writeFile(path.join(dataPath, `${title}.txt`), wikiText, (err: any) => {
if (err) {
console.error(err);
resolve(title);
return;
}
console.log(`${title} stored in file!`);
resolve(title);
});
});
};
```
```ts
export const extractWikipedia = async (titles: string[]) => {
if (!fs.existsSync(dataPath)) {
fs.mkdirSync(dataPath);
}
for await (const title of titles) {
await extractWikipediaTitle(title);
}
console.log("Extration finished!");
```
These files will be saved in the `tmp_data` folder.
Now we can call the function to download the data for each country.
```ts
await extractWikipedia([
"Brazil",
"United States",
"Canada",
"Mexico",
"Argentina",
"Chile",
"Colombia",
"Peru",
"Venezuela",
"Ecuador",
"Bolivia",
"Paraguay",
"Uruguay",
"Guyana",
"Suriname",
"French Guiana",
"Falkland Islands",
]);
```
## Load the data
Now that we have the data, we can load it into the LlamaIndex and store as a document.
```ts
import { Document } from "llamaindex";
const countryDocs: Record<string, Document> = {};
for (const title of wikiTitles) {
const path = `./agent/helpers/tmp_data/${title}.txt`;
const text = await fs.readFile(path, "utf-8");
const document = new Document({ text: text, id_: path });
countryDocs[title] = document;
}
```
## Setup LLM and StorageContext
We will be using gpt-4 for this example and we will use the `StorageContext` to store the documents in-memory.
```ts
const llm = new OpenAI({
model: "gpt-4",
});
const ctx = serviceContextFromDefaults({ llm });
const storageContext = await storageContextFromDefaults({
persistDir: "./storage",
});
```
## Building Multi-Document Agents
In this section we show you how to construct the multi-document agent. We first build a document agent for each document, and then define the top-level parent agent with an object index.
```ts
const documentAgents: Record<string, any> = {};
const queryEngines: Record<string, any> = {};
```
Now we iterate over each country and create a document agent for each one.
### Build Agent for each Document
In this section we define “document agents” for each document.
We define both a vector index (for semantic search) and summary index (for summarization) for each document. The two query engines are then converted into tools that are passed to an OpenAI function calling agent.
This document agent can dynamically choose to perform semantic search or summarization within a given document.
We create a separate document agent for each coutnry.
```ts
for (const title of wikiTitles) {
// parse the document into nodes
const nodes = new SimpleNodeParser({
chunkSize: 200,
chunkOverlap: 20,
}).getNodesFromDocuments([countryDocs[title]]);
// create the vector index for specific search
const vectorIndex = await VectorStoreIndex.init({
serviceContext: serviceContext,
storageContext: storageContext,
nodes,
});
// create the summary index for broader search
const summaryIndex = await SummaryIndex.init({
serviceContext: serviceContext,
nodes,
});
const vectorQueryEngine = summaryIndex.asQueryEngine();
const summaryQueryEngine = summaryIndex.asQueryEngine();
// create the query engines for each task
const queryEngineTools = [
new QueryEngineTool({
queryEngine: vectorQueryEngine,
metadata: {
name: "vector_tool",
description: `Useful for questions related to specific aspects of ${title} (e.g. the history, arts and culture, sports, demographics, or more).`,
},
}),
new QueryEngineTool({
queryEngine: summaryQueryEngine,
metadata: {
name: "summary_tool",
description: `Useful for any requests that require a holistic summary of EVERYTHING about ${title}. For questions about more specific sections, please use the vector_tool.`,
},
}),
];
// create the document agent
const agent = new OpenAIAgent({
tools: queryEngineTools,
llm,
verbose: true,
});
documentAgents[title] = agent;
queryEngines[title] = vectorIndex.asQueryEngine();
}
```
## Build Top-Level Agent
Now we define the top-level agent that can answer questions over the set of document agents.
This agent takes in all document agents as tools. This specific agent RetrieverOpenAIAgent performs tool retrieval before tool use (unlike a default agent that tries to put all tools in the prompt).
Here we use a top-k retriever, but we encourage you to customize the tool retriever method!
Firstly, we create a tool for each document agent
```ts
const allTools: QueryEngineTool[] = [];
```
```ts
for (const title of wikiTitles) {
const wikiSummary = `
This content contains Wikipedia articles about ${title}.
Use this tool if you want to answer any questions about ${title}
`;
const docTool = new QueryEngineTool({
queryEngine: documentAgents[title],
metadata: {
name: `tool_${title}`,
description: wikiSummary,
},
});
allTools.push(docTool);
}
```
Our top level agent will use this document agents as tools and use toolRetriever to retrieve the best tool to answer a question.
```ts
// map the tools to nodes
const toolMapping = SimpleToolNodeMapping.fromObjects(allTools);
// create the object index
const objectIndex = await ObjectIndex.fromObjects(
allTools,
toolMapping,
VectorStoreIndex,
{
serviceContext,
storageContext,
},
);
// create the top agent
const topAgent = new OpenAIAgent({
toolRetriever: await objectIndex.asRetriever({}),
llm,
verbose: true,
prefixMessages: [
{
content:
"You are an agent designed to answer queries about a set of given countries. Please always use the tools provided to answer a question. Do not rely on prior knowledge.",
role: "system",
},
],
});
```
## Use the Agent
Now we can use the agent to answer questions.
```ts
const response = await topAgent.chat({
message: "Tell me the differences between Brazil and Canada economics?",
});
// print output
console.log(response);
```
You can find the full code for this example [here](https://github.com/run-llama/LlamaIndexTS/tree/main/examples/agent/multi-document-agent.ts)
+187
View File
@@ -0,0 +1,187 @@
---
sidebar_position: 0
---
# OpenAI Agent
OpenAI API that supports function calling, its never been easier to build your own agent!
In this notebook tutorial, we showcase how to write your own OpenAI agent
## Setup
First, you need to install the `llamaindex` package. You can do this by running the following command in your terminal:
```bash
pnpm i llamaindex
```
Then we can define a function to sum two numbers and another function to divide two numbers.
```ts
function sumNumbers({ a, b }: { a: number; b: number }): number {
return a + b;
}
// Define a function to divide two numbers
function divideNumbers({ a, b }: { a: number; b: number }): number {
return a / b;
}
```
## Create a function tool
Now we can create a function tool from the sum function and another function tool from the divide function.
For the parameters of the sum function, we can define a JSON schema.
### JSON Schema
```ts
const sumJSON = {
type: "object",
properties: {
a: {
type: "number",
description: "The first number",
},
b: {
type: "number",
description: "The second number",
},
},
required: ["a", "b"],
};
const divideJSON = {
type: "object",
properties: {
a: {
type: "number",
description: "The dividend a to divide",
},
b: {
type: "number",
description: "The divisor b to divide by",
},
},
required: ["a", "b"],
};
const sumFunctionTool = new FunctionTool(sumNumbers, {
name: "sumNumbers",
description: "Use this function to sum two numbers",
parameters: sumJSON,
});
const divideFunctionTool = new FunctionTool(divideNumbers, {
name: "divideNumbers",
description: "Use this function to divide two numbers",
parameters: divideJSON,
});
```
## Create an OpenAIAgent
Now we can create an OpenAIAgent with the function tools.
```ts
const agent = new OpenAIAgent({
tools: [sumFunctionTool, divideFunctionTool],
verbose: true,
});
```
## Chat with the agent
Now we can chat with the agent.
```ts
const response = await agent.chat({
message: "How much is 5 + 5? then divide by 2",
});
console.log(String(response));
```
## Full code
```ts
import { FunctionTool, OpenAIAgent } from "llamaindex";
// Define a function to sum two numbers
function sumNumbers({ a, b }: { a: number; b: number }): number {
return a + b;
}
// Define a function to divide two numbers
function divideNumbers({ a, b }: { a: number; b: number }): number {
return a / b;
}
// Define the parameters of the sum function as a JSON schema
const sumJSON = {
type: "object",
properties: {
a: {
type: "number",
description: "The first number",
},
b: {
type: "number",
description: "The second number",
},
},
required: ["a", "b"],
};
// Define the parameters of the divide function as a JSON schema
const divideJSON = {
type: "object",
properties: {
a: {
type: "number",
description: "The argument a to divide",
},
b: {
type: "number",
description: "The argument b to divide",
},
},
required: ["a", "b"],
};
async function main() {
// Create a function tool from the sum function
const sumFunctionTool = new FunctionTool(sumNumbers, {
name: "sumNumbers",
description: "Use this function to sum two numbers",
parameters: sumJSON,
});
// Create a function tool from the divide function
const divideFunctionTool = new FunctionTool(divideNumbers, {
name: "divideNumbers",
description: "Use this function to divide two numbers",
parameters: divideJSON,
});
// Create an OpenAIAgent with the function tools
const agent = new OpenAIAgent({
tools: [sumFunctionTool, divideFunctionTool],
verbose: true,
});
// Chat with the agent
const response = await agent.chat({
message: "How much is 5 + 5? then divide by 2",
});
// Print the response
console.log(String(response));
}
main().then(() => {
console.log("Done");
});
```
@@ -0,0 +1,132 @@
---
sidebar_position: 1
---
# OpenAI Agent + QueryEngineTool
QueryEngineTool is a tool that allows you to query a vector index. In this example, we will create a vector index from a set of documents and then create a QueryEngineTool from the vector index. We will then create an OpenAIAgent with the QueryEngineTool and chat with the agent.
## Setup
First, you need to install the `llamaindex` package. You can do this by running the following command in your terminal:
```bash
pnpm i llamaindex
```
Then you can import the necessary classes and functions.
```ts
import {
OpenAIAgent,
SimpleDirectoryReader,
VectorStoreIndex,
QueryEngineTool,
} from "llamaindex";
```
## Create a vector index
Now we can create a vector index from a set of documents.
```ts
// Load the documents
const documents = await new SimpleDirectoryReader().loadData({
directoryPath: "node_modules/llamaindex/examples/",
});
// Create a vector index from the documents
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
```
## Create a QueryEngineTool
Now we can create a QueryEngineTool from the vector index.
```ts
// Create a query engine from the vector index
const abramovQueryEngine = vectorIndex.asQueryEngine();
// Create a QueryEngineTool with the query engine
const queryEngineTool = new QueryEngineTool({
queryEngine: abramovQueryEngine,
metadata: {
name: "abramov_query_engine",
description: "A query engine for the Abramov documents",
},
});
```
## Create an OpenAIAgent
```ts
// Create an OpenAIAgent with the query engine tool tools
const agent = new OpenAIAgent({
tools: [queryEngineTool],
verbose: true,
});
```
## Chat with the agent
Now we can chat with the agent.
```ts
const response = await agent.chat({
message: "What was his salary?",
});
console.log(String(response));
```
## Full code
```ts
import {
OpenAIAgent,
SimpleDirectoryReader,
VectorStoreIndex,
QueryEngineTool,
} from "llamaindex";
async function main() {
// Load the documents
const documents = await new SimpleDirectoryReader().loadData({
directoryPath: "node_modules/llamaindex/examples/",
});
// Create a vector index from the documents
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
// Create a query engine from the vector index
const abramovQueryEngine = vectorIndex.asQueryEngine();
// Create a QueryEngineTool with the query engine
const queryEngineTool = new QueryEngineTool({
queryEngine: abramovQueryEngine,
metadata: {
name: "abramov_query_engine",
description: "A query engine for the Abramov documents",
},
});
// Create an OpenAIAgent with the function tools
const agent = new OpenAIAgent({
tools: [queryEngineTool],
verbose: true,
});
// Chat with the agent
const response = await agent.chat({
message: "What was his salary?",
});
// Print the response
console.log(String(response));
}
main().then(() => {
console.log("Done");
});
```
@@ -0,0 +1,203 @@
# ReAct Agent
The ReAct agent is an AI agent that can reason over the next action, construct an action command, execute the action, and repeat these steps in an iterative loop until the task is complete.
In this notebook tutorial, we showcase how to write your ReAct agent using the `llamaindex` package.
## Setup
First, you need to install the `llamaindex` package. You can do this by running the following command in your terminal:
```bash
pnpm i llamaindex
```
And then you can import the `OpenAIAgent` and `FunctionTool` from the `llamaindex` package.
```ts
import { FunctionTool, OpenAIAgent } from "llamaindex";
```
Then we can define a function to sum two numbers and another function to divide two numbers.
```ts
function sumNumbers({ a, b }: { a: number; b: number }): number {
return a + b;
}
// Define a function to divide two numbers
function divideNumbers({ a, b }: { a: number; b: number }): number {
return a / b;
}
```
## Create a function tool
Now we can create a function tool from the sum function and another function tool from the divide function.
For the parameters of the sum function, we can define a JSON schema.
### JSON Schema
```ts
const sumJSON = {
type: "object",
properties: {
a: {
type: "number",
description: "The first number",
},
b: {
type: "number",
description: "The second number",
},
},
required: ["a", "b"],
};
const divideJSON = {
type: "object",
properties: {
a: {
type: "number",
description: "The dividend a to divide",
},
b: {
type: "number",
description: "The divisor b to divide by",
},
},
required: ["a", "b"],
};
const sumFunctionTool = new FunctionTool(sumNumbers, {
name: "sumNumbers",
description: "Use this function to sum two numbers",
parameters: sumJSON,
});
const divideFunctionTool = new FunctionTool(divideNumbers, {
name: "divideNumbers",
description: "Use this function to divide two numbers",
parameters: divideJSON,
});
```
## Create an ReAct
Now we can create an OpenAIAgent with the function tools.
```ts
const agent = new ReActAgent({
tools: [sumFunctionTool, divideFunctionTool],
verbose: true,
});
```
## Chat with the agent
Now we can chat with the agent.
```ts
const response = await agent.chat({
message: "How much is 5 + 5? then divide by 2",
});
console.log(String(response));
```
The output will be:
```bash
Thought: I need to use a tool to help me answer the question.
Action: sumNumbers
Action Input: {"a":5,"b":5}
Observation: 10
Thought: I can answer without using any more tools.
Answer: The sum of 5 and 5 is 10, and when divided by 2, the result is 5.
The sum of 5 and 5 is 10, and when divided by 2, the result is 5.
```
## Full code
```ts
import { FunctionTool, ReActAgent } from "llamaindex";
// Define a function to sum two numbers
function sumNumbers({ a, b }: { a: number; b: number }): number {
return a + b;
}
// Define a function to divide two numbers
function divideNumbers({ a, b }: { a: number; b: number }): number {
return a / b;
}
// Define the parameters of the sum function as a JSON schema
const sumJSON = {
type: "object",
properties: {
a: {
type: "number",
description: "The first number",
},
b: {
type: "number",
description: "The second number",
},
},
required: ["a", "b"],
};
// Define the parameters of the divide function as a JSON schema
const divideJSON = {
type: "object",
properties: {
a: {
type: "number",
description: "The argument a to divide",
},
b: {
type: "number",
description: "The argument b to divide",
},
},
required: ["a", "b"],
};
async function main() {
// Create a function tool from the sum function
const sumFunctionTool = new FunctionTool(sumNumbers, {
name: "sumNumbers",
description: "Use this function to sum two numbers",
parameters: sumJSON,
});
// Create a function tool from the divide function
const divideFunctionTool = new FunctionTool(divideNumbers, {
name: "divideNumbers",
description: "Use this function to divide two numbers",
parameters: divideJSON,
});
// Create an OpenAIAgent with the function tools
const agent = new OpenAIAgent({
tools: [sumFunctionTool, divideFunctionTool],
verbose: true,
});
// Chat with the agent
const response = await agent.chat({
message: "I want to sum 5 and 5 and then divide by 2",
});
// Print the response
console.log(String(response));
}
main().then(() => {
console.log("Done");
});
```
@@ -1,33 +0,0 @@
# Gemini
To use Gemini embeddings, you need to import `GeminiEmbedding` from `llamaindex`.
```ts
import { GeminiEmbedding, Settings } from "llamaindex";
// Update Embed Model
Settings.embedModel = new GeminiEmbedding();
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const queryEngine = index.asQueryEngine();
const query = "What is the meaning of life?";
const results = await queryEngine.query({
query,
});
```
Per default, `GeminiEmbedding` is using the `gemini-pro` model. You can change the model by passing the `model` parameter to the constructor.
For example:
```ts
import { GEMINI_MODEL, GeminiEmbedding } from "llamaindex";
Settings.embedModel = new GeminiEmbedding({
model: GEMINI_MODEL.GEMINI_PRO_LATEST,
});
```
@@ -3,14 +3,17 @@
To use HuggingFace embeddings, you need to import `HuggingFaceEmbedding` from `llamaindex`.
```ts
import { HuggingFaceEmbedding, Settings } from "llamaindex";
import { HuggingFaceEmbedding, serviceContextFromDefaults } from "llamaindex";
// Update Embed Model
Settings.embedModel = new HuggingFaceEmbedding();
const huggingFaceEmbeds = new HuggingFaceEmbedding();
const serviceContext = serviceContextFromDefaults({ embedModel: openaiEmbeds });
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const queryEngine = index.asQueryEngine();
@@ -20,15 +23,3 @@ const results = await queryEngine.query({
query,
});
```
Per default, `HuggingFaceEmbedding` is using the `Xenova/all-MiniLM-L6-v2` model. You can change the model by passing the `modelType` parameter to the constructor.
If you're not using a quantized model, set the `quantized` parameter to `false`.
For example, to use the not quantized `BAAI/bge-small-en-v1.5` model, you can use the following code:
```ts
Settings.embedModel = new HuggingFaceEmbedding({
modelType: "BAAI/bge-small-en-v1.5",
quantized: false,
});
```
@@ -1,21 +0,0 @@
# Jina AI
To use Jina AI embeddings, you need to import `JinaAIEmbedding` from `llamaindex`.
```ts
import { JinaAIEmbedding, Settings } from "llamaindex";
Settings.embedModel = new JinaAIEmbedding();
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const queryEngine = index.asQueryEngine();
const query = "What is the meaning of life?";
const results = await queryEngine.query({
query,
});
```
@@ -3,16 +3,21 @@
To use MistralAI embeddings, you need to import `MistralAIEmbedding` from `llamaindex`.
```ts
import { MistralAIEmbedding, Settings } from "llamaindex";
import { MistralAIEmbedding, serviceContextFromDefaults } from "llamaindex";
// Update Embed Model
Settings.embedModel = new MistralAIEmbedding({
const mistralEmbedModel = new MistralAIEmbedding({
apiKey: "<YOUR_API_KEY>",
});
const serviceContext = serviceContextFromDefaults({
embedModel: mistralEmbedModel,
});
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const queryEngine = index.asQueryEngine();
@@ -1,23 +1,21 @@
# Ollama
To use Ollama embeddings, you need to import `OllamaEmbedding` from `llamaindex`.
Note that you need to pull the embedding model first before using it.
In the example below, we're using the [`nomic-embed-text`](https://ollama.com/library/nomic-embed-text) model, so you have to call:
```shell
ollama pull nomic-embed-text
```
To use Ollama embeddings, you need to import `Ollama` from `llamaindex`.
```ts
import { OllamaEmbedding, Settings } from "llamaindex";
import { Ollama, serviceContextFromDefaults } from "llamaindex";
Settings.embedModel = new OllamaEmbedding({ model: "nomic-embed-text" });
const ollamaEmbedModel = new Ollama();
const serviceContext = serviceContextFromDefaults({
embedModel: ollamaEmbedModel,
});
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const queryEngine = index.asQueryEngine();
@@ -3,13 +3,19 @@
To use OpenAI embeddings, you need to import `OpenAIEmbedding` from `llamaindex`.
```ts
import { OpenAIEmbedding, Settings } from "llamaindex";
import { OpenAIEmbedding, serviceContextFromDefaults } from "llamaindex";
Settings.embedModel = new OpenAIEmbedding();
const openaiEmbedModel = new OpenAIEmbedding();
const serviceContext = serviceContextFromDefaults({
embedModel: openaiEmbedModel,
});
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const queryEngine = index.asQueryEngine();
@@ -3,15 +3,21 @@
To use together embeddings, you need to import `TogetherEmbedding` from `llamaindex`.
```ts
import { TogetherEmbedding, Settings } from "llamaindex";
import { TogetherEmbedding, serviceContextFromDefaults } from "llamaindex";
Settings.embedModel = new TogetherEmbedding({
const togetherEmbedModel = new TogetherEmbedding({
apiKey: "<YOUR_API_KEY>",
});
const serviceContext = serviceContextFromDefaults({
embedModel: togetherEmbedModel,
});
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const queryEngine = index.asQueryEngine();
+6 -5
View File
@@ -2,14 +2,14 @@
The embedding model in LlamaIndex is responsible for creating numerical representations of text. By default, LlamaIndex will use the `text-embedding-ada-002` model from OpenAI.
This can be explicitly updated through `Settings`
This can be explicitly set in the `ServiceContext` object.
```typescript
import { OpenAIEmbedding, Settings } from "llamaindex";
import { OpenAIEmbedding, serviceContextFromDefaults } from "llamaindex";
Settings.embedModel = new OpenAIEmbedding({
model: "text-embedding-ada-002",
});
const openaiEmbeds = new OpenAIEmbedding();
const serviceContext = serviceContextFromDefaults({ embedModel: openaiEmbeds });
```
## Local Embedding
@@ -19,3 +19,4 @@ For local embeddings, you can use the [HuggingFace](./available_embeddings/huggi
## API Reference
- [OpenAIEmbedding](../../api/classes/OpenAIEmbedding.md)
- [ServiceContext](../../api/interfaces//ServiceContext.md)
@@ -21,15 +21,23 @@ export OPENAI_API_KEY=your-api-key
Import the required modules:
```ts
import { CorrectnessEvaluator, OpenAI, Settings } from "llamaindex";
import {
CorrectnessEvaluator,
OpenAI,
serviceContextFromDefaults,
} from "llamaindex";
```
Let's setup gpt-4 for better results:
```ts
Settings.llm = new OpenAI({
const llm = new OpenAI({
model: "gpt-4",
});
const ctx = serviceContextFromDefaults({
llm,
});
```
```ts
@@ -41,7 +49,13 @@ const response = ` Certainly! Albert Einstein's theory of relativity consists of
However, general relativity, published in 1915, extended these ideas to include the effects of magnetism. According to general relativity, gravity is not a force between masses but rather the result of the warping of space and time by magnetic fields generated by massive objects. Massive objects, such as planets and stars, create magnetic fields that cause a curvature in spacetime, and smaller objects follow curved paths in response to this magnetic curvature. This concept is often illustrated using the analogy of a heavy ball placed on a rubber sheet with magnets underneath, causing it to create a depression that other objects (representing smaller masses) naturally move towards due to magnetic attraction.
`;
const evaluator = new CorrectnessEvaluator();
const evaluator = new CorrectnessEvaluator({
serviceContext: ctx,
});
const response = await queryEngine.query({
query,
});
const result = await evaluator.evaluateResponse({
query,
@@ -28,16 +28,20 @@ import {
FaithfulnessEvaluator,
OpenAI,
VectorStoreIndex,
Settings,
serviceContextFromDefaults,
} from "llamaindex";
```
Let's setup gpt-4 for better results:
```ts
Settings.llm = new OpenAI({
const llm = new OpenAI({
model: "gpt-4",
});
const ctx = serviceContextFromDefaults({
llm,
});
```
Now, let's create a vector index and query engine with documents and query engine respectively. Then, we can evaluate the response with the query and response from the query engine.:
@@ -59,7 +63,9 @@ Now, let's evaluate the response:
```ts
const query = "How did New York City get its name?";
const evaluator = new FaithfulnessEvaluator();
const evaluator = new FaithfulnessEvaluator({
serviceContext: ctx,
});
const response = await queryEngine.query({
query,
@@ -21,15 +21,23 @@ export OPENAI_API_KEY=your-api-key
Import the required modules:
```ts
import { RelevancyEvaluator, OpenAI, Settings } from "llamaindex";
import {
RelevancyEvaluator,
OpenAI,
serviceContextFromDefaults,
} from "llamaindex";
```
Let's setup gpt-4 for better results:
```ts
Settings.llm = new OpenAI({
const llm = new OpenAI({
model: "gpt-4",
});
const ctx = serviceContextFromDefaults({
llm,
});
```
Now, let's create a vector index and query engine with documents and query engine respectively. Then, we can evaluate the response with the query and response from the query engine.:
@@ -51,8 +59,6 @@ const response = await queryEngine.query({
query,
});
const evaluator = new RelevancyEvaluator();
const result = await evaluator.evaluateResponse({
query,
response: response,
@@ -1,6 +1,6 @@
# Transformations
A transformation is something that takes a list of nodes as an input, and returns a list of nodes. Each component that implements the Transformation class has both a `transform` definition responsible for transforming the nodes.
A transformation is something that takes a list of nodes as an input, and returns a list of nodes. Each component that implements the Transformatio class has both a `transform` definition responsible for transforming the nodes
Currently, the following components are Transformation objects:
@@ -3,11 +3,13 @@
## Usage
```ts
import { Anthropic, Settings } from "llamaindex";
import { Anthropic, serviceContextFromDefaults } from "llamaindex";
Settings.llm = new Anthropic({
const anthropicLLM = new Anthropic({
apiKey: "<YOUR_API_KEY>",
});
const serviceContext = serviceContextFromDefaults({ llm: anthropicLLM });
```
## Load and index documents
@@ -17,7 +19,9 @@ For this example, we will use a single document. In a real-world scenario, you w
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
```
## Query
@@ -35,17 +39,28 @@ const results = await queryEngine.query({
## Full Example
```ts
import { Anthropic, Document, VectorStoreIndex, Settings } from "llamaindex";
Settings.llm = new Anthropic({
apiKey: "<YOUR_API_KEY>",
});
import {
Anthropic,
Document,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
async function main() {
// Create an instance of the Anthropic LLM
const anthropicLLM = new Anthropic({
apiKey: "<YOUR_API_KEY>",
});
// Create a service context
const serviceContext = serviceContextFromDefaults({ llm: anthropicLLM });
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// Create a query engine
const queryEngine = index.asQueryEngine({
@@ -15,9 +15,11 @@ export AZURE_OPENAI_DEPLOYMENT="gpt-4" # or some other deployment name
## Usage
```ts
import { OpenAI, Settings } from "llamaindex";
import { OpenAI, serviceContextFromDefaults } from "llamaindex";
Settings.llm = new OpenAI({ model: "gpt-4", temperature: 0 });
const azureOpenaiLLM = new OpenAI({ model: "gpt-4", temperature: 0 });
const serviceContext = serviceContextFromDefaults({ llm: azureOpenaiLLM });
```
## Load and index documents
@@ -27,7 +29,9 @@ For this example, we will use a single document. In a real-world scenario, you w
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
```
## Query
@@ -45,15 +49,26 @@ const results = await queryEngine.query({
## Full Example
```ts
import { OpenAI, Document, VectorStoreIndex, Settings } from "llamaindex";
Settings.llm = new OpenAI({ model: "gpt-4", temperature: 0 });
import {
OpenAI,
Document,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
async function main() {
// Create an instance of the LLM
const azureOpenaiLLM = new OpenAI({ model: "gpt-4", temperature: 0 });
// Create a service context
const serviceContext = serviceContextFromDefaults({ llm: azureOpenaiLLM });
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// get retriever
const retriever = index.asRetriever();
@@ -5,11 +5,13 @@ Fireworks.ai focus on production use cases for open source LLMs, offering speed
## Usage
```ts
import { FireworksLLM, Settings } from "llamaindex";
import { FireworksLLM, serviceContextFromDefaults } from "llamaindex";
Settings.llm = new FireworksLLM({
const fireworksLLM = new FireworksLLM({
apiKey: "<YOUR_API_KEY>",
});
const serviceContext = serviceContextFromDefaults({ llm: fireworksLLM });
```
## Load and index documents
@@ -21,7 +23,9 @@ const reader = new PDFReader();
const documents = await reader.loadData("../data/brk-2022.pdf");
// Split text and create embeddings. Store them in a VectorStoreIndex
const index = await VectorStoreIndex.fromDocuments(documents);
const index = await VectorStoreIndex.fromDocuments(documents, {
serviceContext,
});
```
## Query
@@ -1,71 +0,0 @@
# Gemini
## Usage
```ts
import { Gemini, Settings, GEMINI_MODEL } from "llamaindex";
Settings.llm = new Gemini({
model: GEMINI_MODEL.GEMINI_PRO,
});
```
## Load and index documents
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
```
## Query
```ts
const queryEngine = index.asQueryEngine();
const query = "What is the meaning of life?";
const results = await queryEngine.query({
query,
});
```
## Full Example
```ts
import {
Gemini,
Document,
VectorStoreIndex,
Settings,
GEMINI_MODEL,
} from "llamaindex";
Settings.llm = new Gemini({
model: GEMINI_MODEL.GEMINI_PRO,
});
async function main() {
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document]);
// Create a query engine
const queryEngine = index.asQueryEngine({
retriever,
});
const query = "What is the meaning of life?";
// Query
const response = await queryEngine.query({
query,
});
// Log the response
console.log(response.response);
}
```
@@ -14,13 +14,15 @@ export GROQ_API_KEY=<your-api-key>
The initialize the Groq module.
```ts
import { Groq, Settings } from "llamaindex";
import { Groq, serviceContextFromDefaults } from "llamaindex";
Settings.llm = new Groq({
const groq = new Groq({
// If you do not wish to set your API key in the environment, you may
// configure your API key when you initialize the Groq class.
// apiKey: "<your-api-key>",
});
const serviceContext = serviceContextFromDefaults({ llm: groq });
```
## Load and index documents
@@ -30,7 +32,9 @@ For this example, we will use a single document. In a real-world scenario, you w
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
```
## Query
@@ -3,9 +3,11 @@
## Usage
```ts
import { Ollama, Settings, DeuceChatStrategy } from "llamaindex";
import { Ollama, serviceContextFromDefaults } from "llamaindex";
Settings.llm = new LlamaDeuce({ chatStrategy: DeuceChatStrategy.META });
const llama2LLM = new LlamaDeuce({ chatStrategy: DeuceChatStrategy.META });
const serviceContext = serviceContextFromDefaults({ llm: llama2LLM });
```
## Usage with Replication
@@ -14,18 +16,19 @@ Settings.llm = new LlamaDeuce({ chatStrategy: DeuceChatStrategy.META });
import {
Ollama,
ReplicateSession,
Settings,
DeuceChatStrategy,
serviceContextFromDefaults,
} from "llamaindex";
const replicateSession = new ReplicateSession({
replicateKey,
});
Settings.llm = new LlamaDeuce({
const llama2LLM = new LlamaDeuce({
chatStrategy: DeuceChatStrategy.META,
replicateSession,
});
const serviceContext = serviceContextFromDefaults({ llm: llama2LLM });
```
## Load and index documents
@@ -35,7 +38,9 @@ For this example, we will use a single document. In a real-world scenario, you w
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
```
## Query
@@ -57,18 +62,22 @@ import {
LlamaDeuce,
Document,
VectorStoreIndex,
Settings,
DeuceChatStrategy,
serviceContextFromDefaults,
} from "llamaindex";
// Use the LlamaDeuce LLM
Settings.llm = new LlamaDeuce({ chatStrategy: DeuceChatStrategy.META });
async function main() {
// Create an instance of the LLM
const llama2LLM = new LlamaDeuce({ chatStrategy: DeuceChatStrategy.META });
// Create a service context
const serviceContext = serviceContextFromDefaults({ llm: mistralLLM });
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// get retriever
const retriever = index.asRetriever();
@@ -3,12 +3,14 @@
## Usage
```ts
import { Ollama, Settings } from "llamaindex";
import { Ollama, serviceContextFromDefaults } from "llamaindex";
Settings.llm = new MistralAI({
const mistralLLM = new MistralAI({
model: "mistral-tiny",
apiKey: "<YOUR_API_KEY>",
});
const serviceContext = serviceContextFromDefaults({ llm: mistralLLM });
```
## Load and index documents
@@ -18,7 +20,9 @@ For this example, we will use a single document. In a real-world scenario, you w
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
```
## Query
@@ -36,16 +40,26 @@ const results = await queryEngine.query({
## Full Example
```ts
import { MistralAI, Document, VectorStoreIndex, Settings } from "llamaindex";
// Use the MistralAI LLM
Settings.llm = new MistralAI({ model: "mistral-tiny" });
import {
MistralAI,
Document,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
async function main() {
// Create an instance of the LLM
const mistralLLM = new MistralAI({ model: "mistral-tiny" });
// Create a service context
const serviceContext = serviceContextFromDefaults({ llm: mistralLLM });
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// get retriever
const retriever = index.asRetriever();
@@ -3,10 +3,14 @@
## Usage
```ts
import { Ollama, Settings } from "llamaindex";
import { Ollama, serviceContextFromDefaults } from "llamaindex";
Settings.llm = ollamaLLM;
Settings.embedModel = ollamaLLM;
const ollamaLLM = new Ollama({ model: "llama2", temperature: 0.75 });
const serviceContext = serviceContextFromDefaults({
llm: ollamaLLM,
embedModel: ollamaLLM,
});
```
## Load and index documents
@@ -16,7 +20,9 @@ For this example, we will use a single document. In a real-world scenario, you w
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
```
## Query
@@ -34,23 +40,33 @@ const results = await queryEngine.query({
## Full Example
```ts
import { Ollama, Document, VectorStoreIndex, Settings } from "llamaindex";
import {
Ollama,
Document,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
import fs from "fs/promises";
const ollama = new Ollama({ model: "llama2", temperature: 0.75 });
// Use Ollama LLM and Embed Model
Settings.llm = ollama;
Settings.embedModel = ollama;
async function main() {
// Create an instance of the LLM
const ollamaLLM = new Ollama({ model: "llama2", temperature: 0.75 });
const essay = await fs.readFile("./paul_graham_essay.txt", "utf-8");
// Create a service context
const serviceContext = serviceContextFromDefaults({
embedModel: ollamaLLM, // prevent 'Set OpenAI Key in OPENAI_API_KEY env variable' error
llm: ollamaLLM,
});
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// get retriever
const retriever = index.asRetriever();
@@ -1,9 +1,11 @@
# OpenAI
```ts
import { OpenAI, Settings } from "llamaindex";
import { OpenAI, serviceContextFromDefaults } from "llamaindex";
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0, apiKey: <YOUR_API_KEY> });
const openaiLLM = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0, apiKey: <YOUR_API_KEY> });
const serviceContext = serviceContextFromDefaults({ llm: openaiLLM });
```
You can setup the apiKey on the environment variables, like:
@@ -19,7 +21,9 @@ For this example, we will use a single document. In a real-world scenario, you w
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
```
## Query
@@ -37,16 +41,26 @@ const results = await queryEngine.query({
## Full Example
```ts
import { OpenAI, Document, VectorStoreIndex, Settings } from "llamaindex";
// Use the OpenAI LLM
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0 });
import {
OpenAI,
Document,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
async function main() {
// Create an instance of the LLM
const openaiLLM = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0 });
// Create a service context
const serviceContext = serviceContextFromDefaults({ llm: openaiLLM });
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// get retriever
const retriever = index.asRetriever();
@@ -3,11 +3,13 @@
## Usage
```ts
import { Portkey, Settings } from "llamaindex";
import { Portkey, serviceContextFromDefaults } from "llamaindex";
Settings.llm = new Portkey({
const portkeyLLM = new Portkey({
apiKey: "<YOUR_API_KEY>",
});
const serviceContext = serviceContextFromDefaults({ llm: portkeyLLM });
```
## Load and index documents
@@ -17,7 +19,9 @@ For this example, we will use a single document. In a real-world scenario, you w
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
```
## Query
@@ -35,19 +39,28 @@ const results = await queryEngine.query({
## Full Example
```ts
import { Portkey, Document, VectorStoreIndex, Settings } from "llamaindex";
// Use the Portkey LLM
Settings.llm = new Portkey({
apiKey: "<YOUR_API_KEY>",
});
import {
Portkey,
Document,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
async function main() {
// Create a document
// Create an instance of the LLM
const portkeyLLM = new Portkey({
apiKey: "<YOUR_API_KEY>",
});
// Create a service context
const serviceContext = serviceContextFromDefaults({ llm: portkeyLLM });
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// get retriever
const retriever = index.asRetriever();
@@ -3,11 +3,13 @@
## Usage
```ts
import { TogetherLLM, Settings } from "llamaindex";
import { TogetherLLM, serviceContextFromDefaults } from "llamaindex";
Settings.llm = new TogetherLLM({
const togetherLLM = new TogetherLLM({
apiKey: "<YOUR_API_KEY>",
});
const serviceContext = serviceContextFromDefaults({ llm: togetherLLM });
```
## Load and index documents
@@ -17,7 +19,9 @@ For this example, we will use a single document. In a real-world scenario, you w
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
```
## Query
@@ -35,17 +39,28 @@ const results = await queryEngine.query({
## Full Example
```ts
import { TogetherLLM, Document, VectorStoreIndex, Settings } from "llamaindex";
Settings.llm = new TogetherLLM({
apiKey: "<YOUR_API_KEY>",
});
import {
TogetherLLM,
Document,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
async function main() {
// Create an instance of the LLM
const togetherLLM = new TogetherLLM({
apiKey: "<YOUR_API_KEY>",
});
// Create a service context
const serviceContext = serviceContextFromDefaults({ llm: togetherLLM });
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// get retriever
const retriever = index.asRetriever();
+6 -3
View File
@@ -6,12 +6,14 @@ sidebar_position: 3
The LLM is responsible for reading text and generating natural language responses to queries. By default, LlamaIndex.TS uses `gpt-3.5-turbo`.
The LLM can be explicitly updated through `Settings`.
The LLM can be explicitly set in the `ServiceContext` object.
```typescript
import { OpenAI, Settings } from "llamaindex";
import { OpenAI, serviceContextFromDefaults } from "llamaindex";
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0 });
const openaiLLM = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0 });
const serviceContext = serviceContextFromDefaults({ llm: openaiLLM });
```
## Azure OpenAI
@@ -33,3 +35,4 @@ For local LLMs, currently we recommend the use of [Ollama](./available_llms/olla
## API Reference
- [OpenAI](../api/classes/OpenAI.md)
- [ServiceContext](../api/interfaces//ServiceContext.md)
+4 -3
View File
@@ -4,14 +4,15 @@ sidebar_position: 4
# NodeParser
The `NodeParser` in LlamaIndex is responsible for splitting `Document` objects into more manageable `Node` objects. When you call `.fromDocuments()`, the `NodeParser` from the `Settings` is used to do this automatically for you. Alternatively, you can use it to split documents ahead of time.
The `NodeParser` in LlamaIndex is responsible for splitting `Document` objects into more manageable `Node` objects. When you call `.fromDocuments()`, the `NodeParser` from the `ServiceContext` is used to do this automatically for you. Alternatively, you can use it to split documents ahead of time.
```typescript
import { Document, SimpleNodeParser } from "llamaindex";
const nodeParser = new SimpleNodeParser();
Settings.nodeParser = nodeParser;
const nodes = nodeParser.getNodesFromDocuments([
new Document({ text: "I am 10 years old. John is 20 years old." }),
]);
```
## TextSplitter
@@ -18,7 +18,7 @@ import {
Document,
OpenAI,
VectorStoreIndex,
Settings,
serviceContextFromDefaults,
} from "llamaindex";
```
@@ -29,9 +29,13 @@ For this example, we will use a single document. In a real-world scenario, you w
```ts
const document = new Document({ text: essay, id_: "essay" });
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 });
const serviceContext = serviceContextFromDefaults({
llm: new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 }),
});
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
```
## Increase similarity topK to retrieve more results
@@ -36,7 +36,7 @@ const processor = new SimilarityPostprocessor({
similarityCutoff: 0.7,
});
const filteredNodes = await processor.postprocessNodes(nodes);
const filteredNodes = processor.postprocessNodes(nodes);
// cohere rerank: rerank nodes given query using trained model
const reranker = new CohereRerank({
@@ -58,10 +58,7 @@ Most commonly, node-postprocessors will be used in a query engine, where they ar
### Using Node Postprocessors in a Query Engine
```ts
import { Node, NodeWithScore, SimilarityPostprocessor, CohereRerank, Settings } from "llamaindex";
// Use OpenAI LLM
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 });
import { Node, NodeWithScore, SimilarityPostprocessor, CohereRerank } from "llamaindex";
const nodes: NodeWithScore[] = [
{
@@ -82,6 +79,14 @@ const reranker = new CohereRerank({
const document = new Document({ text: "essay", id_: "essay" });
const serviceContext = serviceContextFromDefaults({
llm: new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 }),
});
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const queryEngine = index.asQueryEngine({
nodePostprocessors: [processor, reranker],
});
@@ -95,7 +100,7 @@ const response = await queryEngine.query("<user_query>");
```ts
import { SimilarityPostprocessor } from "llamaindex";
nodes = await index.asRetriever().retrieve({ query: "test query str" });
nodes = await index.asRetriever().retrieve("test query str");
const processor = new SimilarityPostprocessor({
similarityCutoff: 0.7,
@@ -1,71 +0,0 @@
# Jina AI Reranker
The Jina AI Reranker is a postprocessor that uses the Jina AI Reranker API to rerank the results of a search query.
## Setup
Firstly, you will need to install the `llamaindex` package.
```bash
pnpm install llamaindex
```
Now, you will need to sign up for an API key at [Jina AI](https://jina.ai/reranker). Once you have your API key you can import the necessary modules and create a new instance of the `JinaAIReranker` class.
```ts
import {
JinaAIReranker,
Document,
OpenAI,
VectorStoreIndex,
Settings,
} from "llamaindex";
```
## Load and index documents
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
```ts
const document = new Document({ text: essay, id_: "essay" });
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 });
const index = await VectorStoreIndex.fromDocuments([document]);
```
## Increase similarity topK to retrieve more results
The default value for `similarityTopK` is 2. This means that only the most similar document will be returned. To retrieve more results, you can increase the value of `similarityTopK`.
```ts
const retriever = index.asRetriever();
retriever.similarityTopK = 5;
```
## Create a new instance of the JinaAIReranker class
Then you can create a new instance of the `JinaAIReranker` class and pass in the number of results you want to return.
The Jina AI Reranker API key is set in the `JINAAI_API_KEY` environment variable.
```bash
export JINAAI_API_KEY=<YOUR API KEY>
```
```ts
const nodePostprocessor = new JinaAIReranker({
topN: 5,
});
```
## Create a query engine with the retriever and node postprocessor
```ts
const queryEngine = index.asQueryEngine({
retriever,
nodePostprocessors: [nodePostprocessor],
});
// log the response
const response = await queryEngine.query("Where did the author grown up?");
```
+7 -3
View File
@@ -31,11 +31,13 @@ The first method is to create a new instance of `ResponseSynthesizer` (or the mo
```ts
// Create an instance of response synthesizer
const responseSynthesizer = new ResponseSynthesizer({
responseBuilder: new CompactAndRefine(undefined, newTextQaPrompt),
responseBuilder: new CompactAndRefine(serviceContext, newTextQaPrompt),
});
// Create index
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// Query the index
const queryEngine = index.asQueryEngine({ responseSynthesizer });
@@ -51,7 +53,9 @@ The second method is that most of the modules in LlamaIndex have a `getPrompts`
```ts
// Create index
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// Query the index
const queryEngine = index.asQueryEngine();
@@ -54,13 +54,12 @@ You can create a `ChromaVectorStore` to store the documents:
```ts
const chromaVS = new ChromaVectorStore({ collectionName });
const storageContext = await storageContextFromDefaults({
const serviceContext = await storageContextFromDefaults({
vectorStore: chromaVS,
});
const index = await VectorStoreIndex.fromDocuments(docs, {
storageContext: storageContext,
storageContext: serviceContext,
});
```
@@ -18,7 +18,7 @@ import {
SimpleNodeParser,
SummaryIndex,
VectorStoreIndex,
Settings,
serviceContextFromDefaults,
} from "llamaindex";
```
@@ -34,13 +34,17 @@ const documents = await new SimpleDirectoryReader().loadData({
## Service Context
Next, we need to define some basic rules and parse the documents into nodes. We will use the `SimpleNodeParser` to parse the documents into nodes and `Settings` to define the rules (eg. LLM API key, chunk size, etc.):
Next, we need to define some basic rules and parse the documents into nodes. We will use the `SimpleNodeParser` to parse the documents into nodes and `ServiceContext` to define the rules (eg. LLM API key, chunk size, etc.):
```ts
Settings.llm = new OpenAI();
Settings.nodeParser = new SimpleNodeParser({
const nodeParser = new SimpleNodeParser({
chunkSize: 1024,
});
const serviceContext = serviceContextFromDefaults({
nodeParser,
llm: new OpenAI(),
});
```
## Creating Indices
@@ -48,8 +52,13 @@ Settings.nodeParser = new SimpleNodeParser({
Next, we need to create some indices. We will create a `VectorStoreIndex` and a `SummaryIndex`:
```ts
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
const summaryIndex = await SummaryIndex.fromDocuments(documents);
const vectorIndex = await VectorStoreIndex.fromDocuments(documents, {
serviceContext,
});
const summaryIndex = await SummaryIndex.fromDocuments(documents, {
serviceContext,
});
```
## Creating Query Engines
@@ -79,6 +88,7 @@ const queryEngine = RouterQueryEngine.fromDefaults({
description: "Useful for retrieving specific context from Abramov",
},
],
serviceContext,
});
```
@@ -107,23 +117,34 @@ import {
SimpleNodeParser,
SummaryIndex,
VectorStoreIndex,
Settings,
serviceContextFromDefaults,
} from "llamaindex";
Settings.llm = new OpenAI();
Settings.nodeParser = new SimpleNodeParser({
chunkSize: 1024,
});
async function main() {
// Load documents from a directory
const documents = await new SimpleDirectoryReader().loadData({
directoryPath: "node_modules/llamaindex/examples",
});
// Parse the documents into nodes
const nodeParser = new SimpleNodeParser({
chunkSize: 1024,
});
// Create a service context
const serviceContext = serviceContextFromDefaults({
nodeParser,
llm: new OpenAI(),
});
// Create indices
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
const summaryIndex = await SummaryIndex.fromDocuments(documents);
const vectorIndex = await VectorStoreIndex.fromDocuments(documents, {
serviceContext,
});
const summaryIndex = await SummaryIndex.fromDocuments(documents, {
serviceContext,
});
// Create query engines
const vectorQueryEngine = vectorIndex.asQueryEngine();
@@ -141,6 +162,7 @@ async function main() {
description: "Useful for retrieving specific context from Abramov",
},
],
serviceContext,
});
// Query the router query engine
+1 -1
View File
@@ -11,7 +11,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Fetch nodes!
const nodesWithScore = await retriever.retrieve({ query: "query string" });
const nodesWithScore = await retriever.retrieve("query string");
```
## API Reference
-29
View File
@@ -14,9 +14,6 @@ Configure a variable once, and you'll be able to do things like the following:
Each provider has similarities and differences. Take a look below for the full set of guides for each one!
- [OpenLLMetry](#openllmetry)
- [Langtrace](#langtrace)
## OpenLLMetry
[OpenLLMetry](https://github.com/traceloop/openllmetry-js) is an open-source project based on OpenTelemetry for tracing and monitoring
@@ -36,29 +33,3 @@ traceloop.initialize({
disableBatch: true,
});
```
## Langtrace
Enhance your observability with Langtrace, a robust open-source tool supports OpenTelemetry and is designed to trace, evaluate, and manage LLM applications seamlessly. Langtrace integrates directly with LlamaIndex, offering detailed, real-time insights into performance metrics such as accuracy, evaluations, and latency.
#### Install
- Self-host or sign-up and generate an API key using [Langtrace](https://www.langtrace.ai) Cloud
```bash
npm install @langtrase/typescript-sdk
```
#### Initialize
```js
import * as Langtrace from "@langtrase/typescript-sdk";
Langtrace.init({ api_key: "<YOUR_API_KEY>" });
```
Features:
- OpenTelemetry compliant, ensuring broad compatibility with observability platforms.
- Provides comprehensive logs and detailed traces of all components.
- Real-time monitoring of accuracy, evaluations, usage, costs, and latency.
- For more configuration options and details, visit [Langtrace Docs](https://docs.langtrace.ai/introduction).
-2
View File
@@ -1,2 +0,0 @@
label: Recipes
position: 3
-14
View File
@@ -1,14 +0,0 @@
# Cost Analysis
This page shows how to track LLM cost using APIs.
## Callback Manager
The callback manager is a class that manages the callback functions.
You can register `llm-start`, `llm-end`, and `llm-stream` callbacks to the callback manager for tracking the cost.
import CodeBlock from "@theme/CodeBlock";
import CodeSource from "!raw-loader!../../../../examples/recipes/cost-analysis";
<CodeBlock language="ts">{CodeSource}</CodeBlock>
+2 -7
View File
@@ -66,11 +66,7 @@ const config = {
[require("@docusaurus/remark-plugin-npm2yarn"), { sync: true }],
],
},
blog: {
blogTitle: "LlamaIndexTS blog",
blogDescription: "The official blog of LlamaIndexTS",
postsPerPage: "ALL",
},
blog: false,
gtag: {
trackingID: "G-NB9B8LW9W5",
anonymizeIP: true,
@@ -101,7 +97,6 @@ const config = {
type: "localeDropdown",
position: "left",
},
{ to: "blog", label: "Blog", position: "right" },
{
href: "https://github.com/run-llama/LlamaIndexTS",
label: "GitHub",
@@ -168,7 +163,7 @@ const config = {
"docusaurus-plugin-typedoc",
{
entryPoints: ["../../packages/core/src/index.ts"],
tsconfig: "../../tsconfig.json",
tsconfig: "../../packages/core/tsconfig.json",
readme: "none",
sourceLinkTemplate:
"https://github.com/run-llama/LlamaIndexTS/blob/{gitRevision}/{path}#L{line}",
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// جلب العقد!
const nodesWithScore = await retriever.retrieve({ query: "سلسلة الاستعلام" });
const nodesWithScore = await retriever.retrieve("سلسلة الاستعلام");
```
## مرجع الواجهة البرمجية (API Reference)
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Извличане на върхове!
const nodesWithScore = await retriever.retrieve({ query: "query string" });
const nodesWithScore = await retriever.retrieve("query string");
```
## API Reference (API справка)
@@ -13,7 +13,7 @@ const recuperador = vector_index.asRetriever();
recuperador.similarityTopK = 3;
// Obteniu els nodes!
const nodesAmbPuntuació = await recuperador.retrieve({ query: "cadena de consulta" });
const nodesAmbPuntuació = await recuperador.retrieve("cadena de consulta");
```
## Referència de l'API
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Získání uzlů!
const nodesWithScore = await retriever.retrieve({ query: "dotazovací řetězec" });
const nodesWithScore = await retriever.retrieve("dotazovací řetězec");
```
## API Reference (Odkazy na rozhraní)
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Hent noder!
const nodesWithScore = await retriever.retrieve({ query: "forespørgselsstreng" });
const nodesWithScore = await retriever.retrieve("forespørgselsstreng");
```
## API Reference
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Knoten abrufen!
const nodesWithScore = await retriever.retrieve({ query: "Abfragezeichenfolge" });
const nodesWithScore = await retriever.retrieve("Abfragezeichenfolge");
```
## API-Referenz
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Ανάκτηση κόμβων!
const nodesWithScore = await retriever.retrieve({ query: "συμβολοσειρά ερωτήματος" });
const nodesWithScore = await retriever.retrieve("συμβολοσειρά ερωτήματος");
```
## Αναφορά API
@@ -13,7 +13,7 @@ const recuperador = vector_index.asRetriever();
recuperador.similarityTopK = 3;
// ¡Obtener nodos!
const nodosConPuntuación = await recuperador.retrieve({ query: "cadena de consulta" });
const nodosConPuntuación = await recuperador.retrieve("cadena de consulta");
```
## Referencia de la API
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Too sõlmed!
const nodesWithScore = await retriever.retrieve({ query: "päringu string" });
const nodesWithScore = await retriever.retrieve("päringu string");
```
## API viide
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// بازیابی گره ها!
const nodesWithScore = await retriever.retrieve({ query: "رشته پرس و جو" });
const nodesWithScore = await retriever.retrieve("رشته پرس و جو");
```
## مرجع API
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Hae solmut!
const nodesWithScore = await retriever.retrieve({ query: "kyselymerkkijono" });
const nodesWithScore = await retriever.retrieve("kyselymerkkijono");
```
## API-viite
@@ -11,7 +11,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Récupérer les nœuds !
const nodesWithScore = await retriever.retrieve({ query: "chaîne de requête" });
const nodesWithScore = await retriever.retrieve("chaîne de requête");
```
## Référence de l'API
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// אחזור צמתים!
const nodesWithScore = await retriever.retrieve({ query: "מחרוזת שאילתה" });
const nodesWithScore = await retriever.retrieve("מחרוזת שאילתה");
```
## מדריך לממשק API
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// नोड्स प्राप्त करें!
const nodesWithScore = await retriever.retrieve({ query: "क्वेरी स्ट्रिंग" });
const nodesWithScore = await retriever.retrieve("क्वेरी स्ट्रिंग");
```
## एपीआई संदर्भ (API Reference)
@@ -13,7 +13,7 @@ const dohvatnik = vector_index.asRetriever();
dohvatnik.similarityTopK = 3;
// Dohvati čvorove!
const čvoroviSaRezultatom = await dohvatnik.retrieve({ query: "upitni niz" });
const čvoroviSaRezultatom = await dohvatnik.retrieve("upitni niz");
```
## API Referenca
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Node-ok lekérése!
const nodesWithScore = await retriever.retrieve({ query: "lekérdezési karakterlánc" });
const nodesWithScore = await retriever.retrieve("lekérdezési karakterlánc");
```
## API Referencia
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Mengambil node!
const nodesWithScore = await retriever.retrieve({ query: "string query" });
const nodesWithScore = await retriever.retrieve("string query");
```
## Referensi API
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Recupera i nodi!
const nodesWithScore = await retriever.retrieve({ query: "stringa di query" });
const nodesWithScore = await retriever.retrieve("stringa di query");
```
## Riferimento API
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// ノードを取得します!
const nodesWithScore = await retriever.retrieve({ query: "クエリ文字列" });
const nodesWithScore = await retriever.retrieve("クエリ文字列");
```
## API リファレンス
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// 노드를 가져옵니다!
const nodesWithScore = await retriever.retrieve({ query: "쿼리 문자열" });
const nodesWithScore = await retriever.retrieve("쿼리 문자열");
```
## API 참조
@@ -13,7 +13,7 @@ const gavėjas = vector_index.asRetriever();
gavėjas.similarityTopK = 3;
// Išgaunami mazgai!
const mazgaiSuRezultatu = await gavėjas.retrieve({ query: "užklausos eilutė" });
const mazgaiSuRezultatu = await gavėjas.retrieve("užklausos eilutė");
```
## API nuorodos (API Reference)
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Haal knooppunten op!
const nodesWithScore = await retriever.retrieve({ query: "zoekopdracht" });
const nodesWithScore = await retriever.retrieve("zoekopdracht");
```
## API Referentie
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Hent noder!
const nodesWithScore = await retriever.retrieve({ query: "spørringsstreng" });
const nodesWithScore = await retriever.retrieve("spørringsstreng");
```
## API-referanse
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Pobierz węzły!
const nodesWithScore = await retriever.retrieve({ query: "ciąg zapytania" });
const nodesWithScore = await retriever.retrieve("ciąg zapytania");
```
## Dokumentacja interfejsu API
@@ -13,7 +13,7 @@ const recuperador = vector_index.asRetriever();
recuperador.similarityTopK = 3;
// Buscar nós!
const nósComPontuação = await recuperador.retrieve({ query: "string de consulta" });
const nósComPontuação = await recuperador.retrieve("string de consulta");
```
## Referência da API
@@ -13,7 +13,7 @@ const recuperator = vector_index.asRetriever();
recuperator.similarityTopK = 3;
// Preia nodurile!
const noduriCuScor = await recuperator.retrieve({ query: "șir de interogare" });
const noduriCuScor = await recuperator.retrieve("șir de interogare");
```
## Referință API
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Получение узлов!
const nodesWithScore = await retriever.retrieve({ query: "строка запроса" });
const nodesWithScore = await retriever.retrieve("строка запроса");
```
## Справочник по API
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
retriever.similarityTopK = 3;
// Dohvati čvorove!
const nodesWithScore = await retriever.retrieve({ query: "upitni niz" });
const nodesWithScore = await retriever.retrieve("upitni niz");
```
## API Referenca
@@ -13,7 +13,7 @@ const pridobitelj = vector_index.asRetriever();
pridobitelj.similarityTopK = 3;
// Pridobivanje vozlišč!
const vozliščaZRezultatom = await pridobitelj.retrieve({ query: "poizvedbeni niz" });
const vozliščaZRezultatom = await pridobitelj.retrieve("poizvedbeni niz");
```
## API Sklic

Some files were not shown because too many files have changed in this diff Show More