mirror of
https://github.com/run-llama/LlamaIndexTS.git
synced 2026-07-07 23:07:53 -04:00
Compare commits
78 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 298cb433be | |||
| 63af7dd99d | |||
| af5df1d083 | |||
| a3b44093c2 | |||
| c80bf3311f | |||
| 7940d249b0 | |||
| 4a07c81f71 | |||
| 7d56cdf045 | |||
| 0affe621d5 | |||
| 93932b1a9c | |||
| a87f13b9d2 | |||
| 8d2b21ee75 | |||
| 87741c9be8 | |||
| 171cb89170 | |||
| 5dad867bbe | |||
| 13f26fd84d | |||
| 3bc77f7d7f | |||
| aac1ee3af3 | |||
| e85893ac0f | |||
| 315947ee6f | |||
| 23a0d44b11 | |||
| 3b501de057 | |||
| 6cc645aa2a | |||
| 0b37207adc | |||
| f0704ec705 | |||
| 4fcbdf710e | |||
| 866149193a | |||
| 6ffb161618 | |||
| 8e4b49824b | |||
| 5263576de1 | |||
| 6d4e2ea0e9 | |||
| 3cbfa98e6b | |||
| d256cbe0e0 | |||
| a6dfa30dcf | |||
| d0365dc434 | |||
| aa41432bbb | |||
| 98a2b4a547 | |||
| 806ce9a360 | |||
| 8b28092cc8 | |||
| 5c5f4c1c84 | |||
| 949d330295 | |||
| 9a5ee4f37a | |||
| 7a23cc6c84 | |||
| 041acd11fe | |||
| 24b4033db9 | |||
| 1115f83b8f | |||
| 60a1603636 | |||
| ea467fa031 | |||
| b0e6f73b1d | |||
| 6d9e015b5e | |||
| fececd89ab | |||
| 48e287892f | |||
| f118400820 | |||
| 3f8407c7af | |||
| 83317739c7 | |||
| 0b665bd1ca | |||
| 98d4cbdf95 | |||
| 6cb75b54a0 | |||
| 53edfe93cf | |||
| b856deae43 | |||
| 259c842259 | |||
| ffb195ea7a | |||
| b4677534d1 | |||
| f967b82467 | |||
| c81946930e | |||
| 1008b775a4 | |||
| 41210dfc51 | |||
| 67b7272249 | |||
| 964e045903 | |||
| 137cf67f40 | |||
| 309a526e3c | |||
| dd95927498 | |||
| 4f72feae91 | |||
| 3cd8f9f597 | |||
| d2e8d0c62a | |||
| fafbd8c9c7 | |||
| a40c91b054 | |||
| 98894055c6 |
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"llamaindex": patch
|
||||
---
|
||||
|
||||
feat: experimental package + json query engine
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://unpkg.com/@changesets/config@2.3.1/schema.json",
|
||||
"changelog": "@changesets/cli/changelog",
|
||||
"commit": true,
|
||||
"commit": false,
|
||||
"fixed": [],
|
||||
"linked": [],
|
||||
"access": "public",
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
---
|
||||
"llamaindex": patch
|
||||
"@llamaindex/core-test": patch
|
||||
---
|
||||
|
||||
- Add missing exports:
|
||||
- `IndexStructType`,
|
||||
- `IndexDict`,
|
||||
- `jsonToIndexStruct`,
|
||||
- `IndexList`,
|
||||
- `IndexStruct`
|
||||
- Fix `IndexDict.toJson()` method
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"llamaindex": patch
|
||||
---
|
||||
|
||||
Add streaming to agents
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"llamaindex": patch
|
||||
---
|
||||
|
||||
Fix agent streaming with new OpenAI models
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"llamaindex": minor
|
||||
---
|
||||
|
||||
Use parameter object for retrieve function of Retriever (to align usage with query function of QueryEngine)
|
||||
+6
-2
@@ -1,9 +1,13 @@
|
||||
{
|
||||
"jsc": {
|
||||
"parser": {
|
||||
"syntax": "typescript"
|
||||
"syntax": "typescript",
|
||||
"decorators": true
|
||||
},
|
||||
"target": "esnext"
|
||||
"target": "esnext",
|
||||
"transform": {
|
||||
"decoratorVersion": "2022-03"
|
||||
}
|
||||
},
|
||||
"module": {
|
||||
"type": "commonjs",
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
name: E2E Tests
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
paths:
|
||||
- "packages/create-llama/**"
|
||||
- ".github/workflows/e2e.yml"
|
||||
branches: [main]
|
||||
|
||||
env:
|
||||
POETRY_VERSION: "1.6.1"
|
||||
|
||||
jobs:
|
||||
e2e:
|
||||
name: create-llama
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: true
|
||||
matrix:
|
||||
node-version: [18, 20]
|
||||
python-version: ["3.11"]
|
||||
os: [macos-latest, windows-latest]
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Set up python ${{ matrix.python-version }}
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
- name: Install Poetry
|
||||
uses: snok/install-poetry@v1
|
||||
with:
|
||||
version: ${{ env.POETRY_VERSION }}
|
||||
- uses: pnpm/action-setup@v2
|
||||
- name: Setup Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: "pnpm"
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
- name: Install Playwright Browsers
|
||||
run: pnpm exec playwright install --with-deps
|
||||
working-directory: ./packages/create-llama
|
||||
- name: Build create-llama
|
||||
run: pnpm run build
|
||||
working-directory: ./packages/create-llama
|
||||
- name: Pack
|
||||
run: pnpm pack --pack-destination ./output
|
||||
working-directory: ./packages/create-llama
|
||||
- name: Extract Pack
|
||||
run: tar -xvzf ./output/*.tgz -C ./output
|
||||
working-directory: ./packages/create-llama
|
||||
- name: Run Playwright tests
|
||||
run: pnpm exec playwright test
|
||||
env:
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
working-directory: ./packages/create-llama
|
||||
- uses: actions/upload-artifact@v3
|
||||
if: always()
|
||||
with:
|
||||
name: playwright-report
|
||||
path: ./packages/create-llama/playwright-report/
|
||||
retention-days: 30
|
||||
@@ -14,6 +14,14 @@ jobs:
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v2
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: "pnpm"
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Publish @llamaindex/env
|
||||
run: npx jsr publish
|
||||
|
||||
@@ -1,9 +1,44 @@
|
||||
name: Run Tests
|
||||
|
||||
on: [push, pull_request]
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
e2e:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
node-version: [18.x, 20.x, 21.x]
|
||||
name: E2E on Node.js ${{ matrix.node-version }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v2
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: "pnpm"
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
- name: Run E2E Tests
|
||||
run: pnpm run e2e
|
||||
|
||||
test:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
node-version: [18.x, 20.x, 21.x]
|
||||
name: Test on Node.js ${{ matrix.node-version }}
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
@@ -12,7 +47,7 @@ jobs:
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: "pnpm"
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
@@ -44,6 +79,24 @@ jobs:
|
||||
name: typecheck-build-dist
|
||||
path: ./packages/core/dist
|
||||
if-no-files-found: error
|
||||
core-edge-runtime:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v2
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: "pnpm"
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
- name: Build
|
||||
run: pnpm run build --filter @llamaindex/edge
|
||||
- name: Build Edge Runtime
|
||||
run: pnpm run build
|
||||
working-directory: ./packages/edge/e2e/test-edge-runtime
|
||||
typecheck-examples:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
|
||||
@@ -45,7 +45,6 @@ playwright-report/
|
||||
blob-report/
|
||||
playwright/.cache/
|
||||
.tsbuildinfo
|
||||
packages/create-llama/e2e/cache
|
||||
|
||||
# intellij
|
||||
**/.idea
|
||||
|
||||
@@ -4,4 +4,3 @@ pnpm-lock.yaml
|
||||
lib/
|
||||
dist/
|
||||
.docusaurus/
|
||||
packages/create-llama/e2e/cache/
|
||||
@@ -1,8 +1,12 @@
|
||||
{
|
||||
"jsc": {
|
||||
"parser": {
|
||||
"syntax": "typescript"
|
||||
"syntax": "typescript",
|
||||
"decorators": true
|
||||
},
|
||||
"target": "esnext"
|
||||
"target": "esnext",
|
||||
"transform": {
|
||||
"decoratorVersion": "2022-03"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+18
-4
@@ -79,13 +79,27 @@ That should start a webserver which will serve the docs on https://localhost:300
|
||||
|
||||
Any changes you make should be reflected in the browser. If you need to regenerate the API docs and find that your TSDoc isn't getting the updates, feel free to remove apps/docs/api. It will automatically regenerate itself when you run pnpm start again.
|
||||
|
||||
## Publishing
|
||||
## Changeset
|
||||
|
||||
To publish a new version of the library, run
|
||||
We use [changesets](https://github.com/changesets/changesets) for managing versions and changelogs. To create a new changeset, run:
|
||||
|
||||
```
|
||||
pnpm changeset
|
||||
```
|
||||
|
||||
Please send a descriptive changeset for each PR.
|
||||
|
||||
## Publishing (maintainers only)
|
||||
|
||||
To publish a new version of the library, first create a new version:
|
||||
|
||||
```shell
|
||||
pnpm new-version
|
||||
```
|
||||
|
||||
If everything looks good, commit the generated files and release the new version:
|
||||
|
||||
```shell
|
||||
pnpm new-llamaindex
|
||||
pnpm new-create-llama
|
||||
pnpm release
|
||||
git push # push to the main branch
|
||||
git push --tags
|
||||
|
||||
@@ -83,30 +83,38 @@ 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/Embedding.ts): Embeddings are sets of floating point numbers which represent the data in a Node. By comparing the similarity of embeddings, we can derive an understanding of the similarity of two pieces of data. One use case is to compare the embedding of a question with the embeddings of our Nodes to see which Nodes may contain the data needed to answer that quesiton.
|
||||
- [Embedding](/packages/core/src/embeddings/OpenAIEmbedding.ts): Embeddings are sets of floating point numbers which represent the data in a Node. By comparing the similarity of embeddings, we can derive an understanding of the similarity of two pieces of data. One use case is to compare the embedding of a question with the embeddings of our Nodes to see which Nodes may contain the data needed to answer that quesiton. Because the default service context is OpenAI, the default embedding is `OpenAIEmbedding`. If using different models, say through Ollama, use this [Embedding](/packages/core/src/embeddings/OllamaEmbedding.ts) (see all [here](/packages/core/src/embeddings)).
|
||||
|
||||
- [Indices](/packages/core/src/indices/): Indices store the Nodes and the embeddings of those nodes. QueryEngines retrieve Nodes from these Indices using embedding similarity.
|
||||
|
||||
- [QueryEngine](/packages/core/src/QueryEngine.ts): Query engines are what generate the query you put in and give you back the result. Query engines generally combine a pre-built prompt with selected Nodes from your Index to give the LLM the context it needs to answer your query.
|
||||
- [QueryEngine](/packages/core/src/engines/query/RetrieverQueryEngine.ts): Query engines are what generate the query you put in and give you back the result. Query engines generally combine a pre-built prompt with selected Nodes from your Index to give the LLM the context it needs to answer your query. To build a query engine from your Index (recommended), use the [`asQueryEngine`](/packages/core/src/indices/BaseIndex.ts) method on your Index. See all query engines [here](/packages/core/src/engines/query).
|
||||
|
||||
- [ChatEngine](/packages/core/src/ChatEngine.ts): A ChatEngine helps you build a chatbot that will interact with your Indices.
|
||||
- [ChatEngine](/packages/core/src/engines/chat/SimpleChatEngine.ts): A ChatEngine helps you build a chatbot that will interact with your Indices. See all chat engines [here](/packages/core/src/engines/chat).
|
||||
|
||||
- [SimplePrompt](/packages/core/src/Prompt.ts): A simple standardized function call definition that takes in inputs and formats them in a template literal. SimplePrompts can be specialized using currying and combined using other SimplePrompt functions.
|
||||
|
||||
## Note: NextJS:
|
||||
## Using NextJS
|
||||
|
||||
If you're using NextJS App Router, you'll need to use the NodeJS runtime (default) and add the following config to your next.config.js to have it use imports/exports in the same way Node does.
|
||||
If you're using the NextJS App Router, you can choose between the Node.js and the [Edge runtime](https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes#edge-runtime).
|
||||
|
||||
```js
|
||||
export const runtime = "nodejs"; // default
|
||||
With NextJS 13 and 14, using the Node.js runtime is the default. You can explicitly set the Edge runtime in your [router handler](https://nextjs.org/docs/app/building-your-application/routing/route-handlers) by adding this line:
|
||||
|
||||
```typescript
|
||||
export const runtime = "edge";
|
||||
```
|
||||
|
||||
The following sections explain further differences in using the Node.js or Edge runtime.
|
||||
|
||||
### Using the Node.js runtime
|
||||
|
||||
Add the following config to your `next.config.js` to ignore specific packages in the server-side bundling:
|
||||
|
||||
```js
|
||||
// next.config.js
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
experimental: {
|
||||
serverComponentsExternalPackages: ["pdf2json"],
|
||||
serverComponentsExternalPackages: ["pdf2json", "@zilliz/milvus2-sdk-node"],
|
||||
},
|
||||
webpack: (config) => {
|
||||
config.resolve.alias = {
|
||||
@@ -121,10 +129,59 @@ const nextConfig = {
|
||||
module.exports = nextConfig;
|
||||
```
|
||||
|
||||
### Using the Edge runtime
|
||||
|
||||
We publish a dedicated package (`@llamaindex/edge` instead of `llamaindex`) for using the Edge runtime. To use it, first install the package:
|
||||
|
||||
```shell
|
||||
pnpm install @llamaindex/edge
|
||||
```
|
||||
|
||||
> _Note_: Ensure that your `package.json` doesn't include the `llamaindex` package if you're using `@llamaindex/edge`.
|
||||
|
||||
Then make sure to use the correct import statement in your code:
|
||||
|
||||
```typescript
|
||||
// replace 'llamaindex' with '@llamaindex/edge'
|
||||
import {} from "@llamaindex/edge";
|
||||
```
|
||||
|
||||
A further difference is that the `@llamaindex/edge` package doesn't export classes from the `readers` or `storage` folders. The reason is that most of these classes are not compatible with the Edge runtime.
|
||||
|
||||
If you need any of those classes, you have to import them instead directly. Here's an example for importing the `PineconeVectorStore` class:
|
||||
|
||||
```typescript
|
||||
import { PineconeVectorStore } from "@llamaindex/edge/storage/vectorStore/PineconeVectorStore";
|
||||
```
|
||||
|
||||
As the `PDFReader` is not with the Edge runtime, here's how to use the `SimpleDirectoryReader` with the `LlamaParseReader` to load PDFs:
|
||||
|
||||
```typescript
|
||||
import { SimpleDirectoryReader } from "@llamaindex/edge/readers/SimpleDirectoryReader";
|
||||
import { LlamaParseReader } from "@llamaindex/edge/readers/LlamaParseReader";
|
||||
|
||||
export const DATA_DIR = "./data";
|
||||
|
||||
export async function getDocuments() {
|
||||
const reader = new SimpleDirectoryReader();
|
||||
// Load PDFs using LlamaParseReader
|
||||
return await reader.loadData({
|
||||
directoryPath: DATA_DIR,
|
||||
fileExtToReader: {
|
||||
pdf: new LlamaParseReader({ resultType: "markdown" }),
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
> _Note_: Reader classes have to be added explictly to the `fileExtToReader` map in the Edge version of the `SimpleDirectoryReader`.
|
||||
|
||||
You'll find a complete example of using the Edge runtime with LlamaIndexTS here: https://github.com/run-llama/create_llama_projects/tree/main/nextjs-edge-llamaparse
|
||||
|
||||
## Supported LLMs:
|
||||
|
||||
- OpenAI GPT-3.5-turbo and GPT-4
|
||||
- Anthropic Claude Instant and Claude 2
|
||||
- Anthropic Claude 3 (Opus, Sonnet, and Haiku) and the legacy models (Claude 2 and Instant)
|
||||
- Groq LLMs
|
||||
- Llama2 Chat LLMs (70B, 13B, and 7B parameters)
|
||||
- MistralAI Chat LLMs
|
||||
|
||||
@@ -33,7 +33,7 @@ import {
|
||||
SimpleToolNodeMapping,
|
||||
SummaryIndex,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
Settings,
|
||||
storageContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
```
|
||||
@@ -147,12 +147,10 @@ for (const title of wikiTitles) {
|
||||
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({
|
||||
Settings.llm = new OpenAI({
|
||||
model: "gpt-4",
|
||||
});
|
||||
|
||||
const ctx = serviceContextFromDefaults({ llm });
|
||||
|
||||
const storageContext = await storageContextFromDefaults({
|
||||
persistDir: "./storage",
|
||||
});
|
||||
@@ -189,14 +187,12 @@ for (const title of wikiTitles) {
|
||||
|
||||
// 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,
|
||||
});
|
||||
|
||||
@@ -278,7 +274,6 @@ const objectIndex = await ObjectIndex.fromObjects(
|
||||
toolMapping,
|
||||
VectorStoreIndex,
|
||||
{
|
||||
serviceContext,
|
||||
storageContext,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -3,17 +3,14 @@
|
||||
To use HuggingFace embeddings, you need to import `HuggingFaceEmbedding` from `llamaindex`.
|
||||
|
||||
```ts
|
||||
import { HuggingFaceEmbedding, serviceContextFromDefaults } from "llamaindex";
|
||||
import { HuggingFaceEmbedding, Settings } from "llamaindex";
|
||||
|
||||
const huggingFaceEmbeds = new HuggingFaceEmbedding();
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ embedModel: openaiEmbeds });
|
||||
// Update Embed Model
|
||||
Settings.embedModel = new HuggingFaceEmbedding();
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
@@ -29,8 +26,8 @@ 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:
|
||||
|
||||
```
|
||||
const embedModel = new HuggingFaceEmbedding({
|
||||
```ts
|
||||
Settings.embedModel = new HuggingFaceEmbedding({
|
||||
modelType: "BAAI/bge-small-en-v1.5",
|
||||
quantized: false,
|
||||
});
|
||||
|
||||
@@ -3,21 +3,16 @@
|
||||
To use MistralAI embeddings, you need to import `MistralAIEmbedding` from `llamaindex`.
|
||||
|
||||
```ts
|
||||
import { MistralAIEmbedding, serviceContextFromDefaults } from "llamaindex";
|
||||
import { MistralAIEmbedding, Settings } from "llamaindex";
|
||||
|
||||
const mistralEmbedModel = new MistralAIEmbedding({
|
||||
// Update Embed Model
|
||||
Settings.embedModel = new MistralAIEmbedding({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
embedModel: mistralEmbedModel,
|
||||
});
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
|
||||
@@ -3,19 +3,13 @@
|
||||
To use Ollama embeddings, you need to import `Ollama` from `llamaindex`.
|
||||
|
||||
```ts
|
||||
import { Ollama, serviceContextFromDefaults } from "llamaindex";
|
||||
import { Ollama, Settings } from "llamaindex";
|
||||
|
||||
const ollamaEmbedModel = new Ollama();
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
embedModel: ollamaEmbedModel,
|
||||
});
|
||||
Settings.embedModel = new Ollama();
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
|
||||
@@ -3,19 +3,13 @@
|
||||
To use OpenAI embeddings, you need to import `OpenAIEmbedding` from `llamaindex`.
|
||||
|
||||
```ts
|
||||
import { OpenAIEmbedding, serviceContextFromDefaults } from "llamaindex";
|
||||
import { OpenAIEmbedding, Settings } from "llamaindex";
|
||||
|
||||
const openaiEmbedModel = new OpenAIEmbedding();
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
embedModel: openaiEmbedModel,
|
||||
});
|
||||
Settings.embedModel = new OpenAIEmbedding();
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
|
||||
@@ -3,21 +3,15 @@
|
||||
To use together embeddings, you need to import `TogetherEmbedding` from `llamaindex`.
|
||||
|
||||
```ts
|
||||
import { TogetherEmbedding, serviceContextFromDefaults } from "llamaindex";
|
||||
import { TogetherEmbedding, Settings } from "llamaindex";
|
||||
|
||||
const togetherEmbedModel = new TogetherEmbedding({
|
||||
Settings.embedModel = new TogetherEmbedding({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
embedModel: togetherEmbedModel,
|
||||
});
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
|
||||
@@ -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 set in the `ServiceContext` object.
|
||||
This can be explicitly updated through `Settings`
|
||||
|
||||
```typescript
|
||||
import { OpenAIEmbedding, serviceContextFromDefaults } from "llamaindex";
|
||||
import { OpenAIEmbedding, Settings } from "llamaindex";
|
||||
|
||||
const openaiEmbeds = new OpenAIEmbedding();
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ embedModel: openaiEmbeds });
|
||||
Settings.embedModel = new OpenAIEmbedding({
|
||||
model: "text-embedding-ada-002",
|
||||
});
|
||||
```
|
||||
|
||||
## Local Embedding
|
||||
@@ -19,4 +19,3 @@ For local embeddings, you can use the [HuggingFace](./available_embeddings/huggi
|
||||
## API Reference
|
||||
|
||||
- [OpenAIEmbedding](../../api/classes/OpenAIEmbedding.md)
|
||||
- [ServiceContext](../../api/interfaces//ServiceContext.md)
|
||||
|
||||
@@ -21,23 +21,15 @@ export OPENAI_API_KEY=your-api-key
|
||||
Import the required modules:
|
||||
|
||||
```ts
|
||||
import {
|
||||
CorrectnessEvaluator,
|
||||
OpenAI,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
import { CorrectnessEvaluator, OpenAI, Settings } from "llamaindex";
|
||||
```
|
||||
|
||||
Let's setup gpt-4 for better results:
|
||||
|
||||
```ts
|
||||
const llm = new OpenAI({
|
||||
Settings.llm = new OpenAI({
|
||||
model: "gpt-4",
|
||||
});
|
||||
|
||||
const ctx = serviceContextFromDefaults({
|
||||
llm,
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
@@ -49,9 +41,7 @@ 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({
|
||||
serviceContext: ctx,
|
||||
});
|
||||
const evaluator = new CorrectnessEvaluator();
|
||||
|
||||
const result = await evaluator.evaluateResponse({
|
||||
query,
|
||||
|
||||
@@ -28,20 +28,16 @@ import {
|
||||
FaithfulnessEvaluator,
|
||||
OpenAI,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
Settings,
|
||||
} from "llamaindex";
|
||||
```
|
||||
|
||||
Let's setup gpt-4 for better results:
|
||||
|
||||
```ts
|
||||
const llm = new OpenAI({
|
||||
Settings.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.:
|
||||
@@ -63,9 +59,7 @@ Now, let's evaluate the response:
|
||||
```ts
|
||||
const query = "How did New York City get its name?";
|
||||
|
||||
const evaluator = new FaithfulnessEvaluator({
|
||||
serviceContext: ctx,
|
||||
});
|
||||
const evaluator = new FaithfulnessEvaluator();
|
||||
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
|
||||
@@ -21,23 +21,15 @@ export OPENAI_API_KEY=your-api-key
|
||||
Import the required modules:
|
||||
|
||||
```ts
|
||||
import {
|
||||
RelevancyEvaluator,
|
||||
OpenAI,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
import { RelevancyEvaluator, OpenAI, Settings } from "llamaindex";
|
||||
```
|
||||
|
||||
Let's setup gpt-4 for better results:
|
||||
|
||||
```ts
|
||||
const llm = new OpenAI({
|
||||
Settings.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,6 +51,8 @@ const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
const evaluator = new RelevancyEvaluator();
|
||||
|
||||
const result = await evaluator.evaluateResponse({
|
||||
query,
|
||||
response: response,
|
||||
|
||||
@@ -3,13 +3,11 @@
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { Anthropic, serviceContextFromDefaults } from "llamaindex";
|
||||
import { Anthropic, Settings } from "llamaindex";
|
||||
|
||||
const anthropicLLM = new Anthropic({
|
||||
Settings.llm = new Anthropic({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm: anthropicLLM });
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
@@ -19,9 +17,7 @@ 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], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
```
|
||||
|
||||
## Query
|
||||
@@ -39,28 +35,17 @@ const results = await queryEngine.query({
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import {
|
||||
Anthropic,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
import { Anthropic, Document, VectorStoreIndex, Settings } from "llamaindex";
|
||||
|
||||
Settings.llm = new Anthropic({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
async function main() {
|
||||
// Create an instance of the Anthropic LLM
|
||||
const anthropicLLM = new Anthropic({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
// Create a service context
|
||||
const serviceContext = serviceContextFromDefaults({ llm: anthropicLLM });
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// Create a query engine
|
||||
const queryEngine = index.asQueryEngine({
|
||||
|
||||
@@ -15,11 +15,9 @@ export AZURE_OPENAI_DEPLOYMENT="gpt-4" # or some other deployment name
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { OpenAI, serviceContextFromDefaults } from "llamaindex";
|
||||
import { OpenAI, Settings } from "llamaindex";
|
||||
|
||||
const azureOpenaiLLM = new OpenAI({ model: "gpt-4", temperature: 0 });
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm: azureOpenaiLLM });
|
||||
Settings.llm = new OpenAI({ model: "gpt-4", temperature: 0 });
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
@@ -29,9 +27,7 @@ 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], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
```
|
||||
|
||||
## Query
|
||||
@@ -49,26 +45,15 @@ const results = await queryEngine.query({
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import {
|
||||
OpenAI,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
import { OpenAI, Document, VectorStoreIndex, Settings } from "llamaindex";
|
||||
|
||||
Settings.llm = new OpenAI({ model: "gpt-4", temperature: 0 });
|
||||
|
||||
async function main() {
|
||||
// Create an instance of the LLM
|
||||
const azureOpenaiLLM = new OpenAI({ model: "gpt-4", temperature: 0 });
|
||||
|
||||
// Create a service context
|
||||
const serviceContext = serviceContextFromDefaults({ llm: azureOpenaiLLM });
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
@@ -5,13 +5,11 @@ Fireworks.ai focus on production use cases for open source LLMs, offering speed
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { FireworksLLM, serviceContextFromDefaults } from "llamaindex";
|
||||
import { FireworksLLM, Settings } from "llamaindex";
|
||||
|
||||
const fireworksLLM = new FireworksLLM({
|
||||
Settings.llm = new FireworksLLM({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm: fireworksLLM });
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
@@ -23,9 +21,7 @@ const reader = new PDFReader();
|
||||
const documents = await reader.loadData("../data/brk-2022.pdf");
|
||||
|
||||
// Split text and create embeddings. Store them in a VectorStoreIndex
|
||||
const index = await VectorStoreIndex.fromDocuments(documents, {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments(documents);
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
@@ -14,15 +14,13 @@ export GROQ_API_KEY=<your-api-key>
|
||||
The initialize the Groq module.
|
||||
|
||||
```ts
|
||||
import { Groq, serviceContextFromDefaults } from "llamaindex";
|
||||
import { Groq, Settings } from "llamaindex";
|
||||
|
||||
const groq = new Groq({
|
||||
Settings.llm = 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
|
||||
@@ -32,9 +30,7 @@ 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], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
@@ -3,32 +3,24 @@
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { Ollama, serviceContextFromDefaults } from "llamaindex";
|
||||
import { Ollama, Settings } from "llamaindex";
|
||||
|
||||
const llama2LLM = new LlamaDeuce({ chatStrategy: DeuceChatStrategy.META });
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm: llama2LLM });
|
||||
Settings.llm = new LlamaDeuce({ chatStrategy: DeuceChatStrategy.META });
|
||||
```
|
||||
|
||||
## Usage with Replication
|
||||
|
||||
```ts
|
||||
import {
|
||||
Ollama,
|
||||
ReplicateSession,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
import { Ollama, ReplicateSession, Settings } from "llamaindex";
|
||||
|
||||
const replicateSession = new ReplicateSession({
|
||||
replicateKey,
|
||||
});
|
||||
|
||||
const llama2LLM = new LlamaDeuce({
|
||||
Settings.llm = new LlamaDeuce({
|
||||
chatStrategy: DeuceChatStrategy.META,
|
||||
replicateSession,
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm: llama2LLM });
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
@@ -38,9 +30,7 @@ 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], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
```
|
||||
|
||||
## Query
|
||||
@@ -58,26 +48,16 @@ const results = await queryEngine.query({
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import {
|
||||
LlamaDeuce,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
import { LlamaDeuce, Document, VectorStoreIndex, Settings } 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], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
@@ -3,14 +3,12 @@
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { Ollama, serviceContextFromDefaults } from "llamaindex";
|
||||
import { Ollama, Settings } from "llamaindex";
|
||||
|
||||
const mistralLLM = new MistralAI({
|
||||
Settings.llm = new MistralAI({
|
||||
model: "mistral-tiny",
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm: mistralLLM });
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
@@ -20,9 +18,7 @@ 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], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
```
|
||||
|
||||
## Query
|
||||
@@ -40,26 +36,16 @@ const results = await queryEngine.query({
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import {
|
||||
MistralAI,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
import { MistralAI, Document, VectorStoreIndex, Settings } from "llamaindex";
|
||||
|
||||
// Use the MistralAI LLM
|
||||
Settings.llm = new MistralAI({ model: "mistral-tiny" });
|
||||
|
||||
async function main() {
|
||||
// Create an instance of the LLM
|
||||
const mistralLLM = new MistralAI({ model: "mistral-tiny" });
|
||||
|
||||
// Create a service context
|
||||
const serviceContext = serviceContextFromDefaults({ llm: mistralLLM });
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
@@ -3,14 +3,10 @@
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { Ollama, serviceContextFromDefaults } from "llamaindex";
|
||||
import { Ollama, Settings } from "llamaindex";
|
||||
|
||||
const ollamaLLM = new Ollama({ model: "llama2", temperature: 0.75 });
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
llm: ollamaLLM,
|
||||
embedModel: ollamaLLM,
|
||||
});
|
||||
Settings.llm = ollamaLLM;
|
||||
Settings.embedModel = ollamaLLM;
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
@@ -20,9 +16,7 @@ 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], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
```
|
||||
|
||||
## Query
|
||||
@@ -40,33 +34,23 @@ const results = await queryEngine.query({
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import {
|
||||
Ollama,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
import { Ollama, Document, VectorStoreIndex, Settings } 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], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
# OpenAI
|
||||
|
||||
```ts
|
||||
import { OpenAI, serviceContextFromDefaults } from "llamaindex";
|
||||
import { OpenAI, Settings } from "llamaindex";
|
||||
|
||||
const openaiLLM = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0, apiKey: <YOUR_API_KEY> });
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm: openaiLLM });
|
||||
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0, apiKey: <YOUR_API_KEY> });
|
||||
```
|
||||
|
||||
You can setup the apiKey on the environment variables, like:
|
||||
@@ -21,9 +19,7 @@ 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], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
```
|
||||
|
||||
## Query
|
||||
@@ -41,26 +37,16 @@ const results = await queryEngine.query({
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import {
|
||||
OpenAI,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
import { OpenAI, Document, VectorStoreIndex, Settings } from "llamaindex";
|
||||
|
||||
// Use the OpenAI LLM
|
||||
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0 });
|
||||
|
||||
async function main() {
|
||||
// Create an instance of the LLM
|
||||
const openaiLLM = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0 });
|
||||
|
||||
// Create a service context
|
||||
const serviceContext = serviceContextFromDefaults({ llm: openaiLLM });
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
@@ -3,13 +3,11 @@
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { Portkey, serviceContextFromDefaults } from "llamaindex";
|
||||
import { Portkey, Settings } from "llamaindex";
|
||||
|
||||
const portkeyLLM = new Portkey({
|
||||
Settings.llm = new Portkey({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm: portkeyLLM });
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
@@ -19,9 +17,7 @@ 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], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
```
|
||||
|
||||
## Query
|
||||
@@ -39,28 +35,19 @@ const results = await queryEngine.query({
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import {
|
||||
Portkey,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
import { Portkey, Document, VectorStoreIndex, Settings } from "llamaindex";
|
||||
|
||||
// Use the Portkey LLM
|
||||
Settings.llm = new Portkey({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
async function main() {
|
||||
// Create an instance of the LLM
|
||||
const portkeyLLM = new Portkey({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
// Create a service context
|
||||
const serviceContext = serviceContextFromDefaults({ llm: portkeyLLM });
|
||||
|
||||
// Create a document
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
@@ -3,13 +3,11 @@
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { TogetherLLM, serviceContextFromDefaults } from "llamaindex";
|
||||
import { TogetherLLM, Settings } from "llamaindex";
|
||||
|
||||
const togetherLLM = new TogetherLLM({
|
||||
Settings.llm = new TogetherLLM({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm: togetherLLM });
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
@@ -19,9 +17,7 @@ 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], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
```
|
||||
|
||||
## Query
|
||||
@@ -39,28 +35,17 @@ const results = await queryEngine.query({
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import {
|
||||
TogetherLLM,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
import { TogetherLLM, Document, VectorStoreIndex, Settings } from "llamaindex";
|
||||
|
||||
Settings.llm = new TogetherLLM({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
async function main() {
|
||||
// Create an instance of the LLM
|
||||
const togetherLLM = new TogetherLLM({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
// Create a service context
|
||||
const serviceContext = serviceContextFromDefaults({ llm: togetherLLM });
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
@@ -6,14 +6,12 @@ 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 set in the `ServiceContext` object.
|
||||
The LLM can be explicitly updated through `Settings`.
|
||||
|
||||
```typescript
|
||||
import { OpenAI, serviceContextFromDefaults } from "llamaindex";
|
||||
import { OpenAI, Settings } from "llamaindex";
|
||||
|
||||
const openaiLLM = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0 });
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm: openaiLLM });
|
||||
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0 });
|
||||
```
|
||||
|
||||
## Azure OpenAI
|
||||
@@ -35,4 +33,3 @@ 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,15 +4,14 @@ sidebar_position: 4
|
||||
|
||||
# NodeParser
|
||||
|
||||
The `NodeParser` in LlamaIndex is responsible for splitting `Document` objects into more manageable `Node` objects. When you call `.fromDocuments()`, the `NodeParser` from the `ServiceContext` is used to do this automatically for you. Alternatively, you can use it to split documents ahead of time.
|
||||
The `NodeParser` in LlamaIndex is responsible for splitting `Document` objects into more manageable `Node` objects. When you call `.fromDocuments()`, the `NodeParser` from the `Settings` is used to do this automatically for you. Alternatively, you can use it to split documents ahead of time.
|
||||
|
||||
```typescript
|
||||
import { Document, SimpleNodeParser } from "llamaindex";
|
||||
|
||||
const nodeParser = new SimpleNodeParser();
|
||||
const nodes = nodeParser.getNodesFromDocuments([
|
||||
new Document({ text: "I am 10 years old. John is 20 years old." }),
|
||||
]);
|
||||
|
||||
Settings.nodeParser = nodeParser;
|
||||
```
|
||||
|
||||
## TextSplitter
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
Document,
|
||||
OpenAI,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
Settings,
|
||||
} from "llamaindex";
|
||||
```
|
||||
|
||||
@@ -29,13 +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 serviceContext = serviceContextFromDefaults({
|
||||
llm: new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 }),
|
||||
});
|
||||
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
```
|
||||
|
||||
## Increase similarity topK to retrieve more results
|
||||
|
||||
@@ -36,7 +36,7 @@ const processor = new SimilarityPostprocessor({
|
||||
similarityCutoff: 0.7,
|
||||
});
|
||||
|
||||
const filteredNodes = processor.postprocessNodes(nodes);
|
||||
const filteredNodes = await processor.postprocessNodes(nodes);
|
||||
|
||||
// cohere rerank: rerank nodes given query using trained model
|
||||
const reranker = new CohereRerank({
|
||||
@@ -58,7 +58,10 @@ 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 } from "llamaindex";
|
||||
import { Node, NodeWithScore, SimilarityPostprocessor, CohereRerank, Settings } from "llamaindex";
|
||||
|
||||
// Use OpenAI LLM
|
||||
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 });
|
||||
|
||||
const nodes: NodeWithScore[] = [
|
||||
{
|
||||
@@ -79,14 +82,6 @@ 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],
|
||||
});
|
||||
|
||||
@@ -31,13 +31,11 @@ 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(serviceContext, newTextQaPrompt),
|
||||
responseBuilder: new CompactAndRefine(undefined, newTextQaPrompt),
|
||||
});
|
||||
|
||||
// Create index
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine({ responseSynthesizer });
|
||||
@@ -53,9 +51,7 @@ The second method is that most of the modules in LlamaIndex have a `getPrompts`
|
||||
|
||||
```ts
|
||||
// Create index
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
@@ -54,12 +54,13 @@ You can create a `ChromaVectorStore` to store the documents:
|
||||
|
||||
```ts
|
||||
const chromaVS = new ChromaVectorStore({ collectionName });
|
||||
const serviceContext = await storageContextFromDefaults({
|
||||
|
||||
const storageContext = await storageContextFromDefaults({
|
||||
vectorStore: chromaVS,
|
||||
});
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments(docs, {
|
||||
storageContext: serviceContext,
|
||||
storageContext: storageContext,
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
SimpleNodeParser,
|
||||
SummaryIndex,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
Settings,
|
||||
} from "llamaindex";
|
||||
```
|
||||
|
||||
@@ -34,17 +34,13 @@ 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 `ServiceContext` 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 `Settings` to define the rules (eg. LLM API key, chunk size, etc.):
|
||||
|
||||
```ts
|
||||
const nodeParser = new SimpleNodeParser({
|
||||
Settings.llm = new OpenAI();
|
||||
Settings.nodeParser = new SimpleNodeParser({
|
||||
chunkSize: 1024,
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
nodeParser,
|
||||
llm: new OpenAI(),
|
||||
});
|
||||
```
|
||||
|
||||
## Creating Indices
|
||||
@@ -52,13 +48,8 @@ const serviceContext = serviceContextFromDefaults({
|
||||
Next, we need to create some indices. We will create a `VectorStoreIndex` and a `SummaryIndex`:
|
||||
|
||||
```ts
|
||||
const vectorIndex = await VectorStoreIndex.fromDocuments(documents, {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
const summaryIndex = await SummaryIndex.fromDocuments(documents, {
|
||||
serviceContext,
|
||||
});
|
||||
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
|
||||
const summaryIndex = await SummaryIndex.fromDocuments(documents);
|
||||
```
|
||||
|
||||
## Creating Query Engines
|
||||
@@ -88,7 +79,6 @@ const queryEngine = RouterQueryEngine.fromDefaults({
|
||||
description: "Useful for retrieving specific context from Abramov",
|
||||
},
|
||||
],
|
||||
serviceContext,
|
||||
});
|
||||
```
|
||||
|
||||
@@ -117,34 +107,23 @@ import {
|
||||
SimpleNodeParser,
|
||||
SummaryIndex,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
Settings,
|
||||
} 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, {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
const summaryIndex = await SummaryIndex.fromDocuments(documents, {
|
||||
serviceContext,
|
||||
});
|
||||
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
|
||||
const summaryIndex = await SummaryIndex.fromDocuments(documents);
|
||||
|
||||
// Create query engines
|
||||
const vectorQueryEngine = vectorIndex.asQueryEngine();
|
||||
@@ -162,7 +141,6 @@ async function main() {
|
||||
description: "Useful for retrieving specific context from Abramov",
|
||||
},
|
||||
],
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
// Query the router query engine
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
label: Recipes
|
||||
position: 3
|
||||
@@ -0,0 +1,14 @@
|
||||
# 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>
|
||||
+13
-13
@@ -15,28 +15,28 @@
|
||||
"typecheck": "tsc"
|
||||
},
|
||||
"dependencies": {
|
||||
"@docusaurus/core": "^3.1.1",
|
||||
"@llamaindex/env": "workspace:*",
|
||||
"@docusaurus/remark-plugin-npm2yarn": "^3.1.1",
|
||||
"@mdx-js/react": "^3.0.0",
|
||||
"@docusaurus/core": "^3.2.1",
|
||||
"@docusaurus/remark-plugin-npm2yarn": "^3.2.1",
|
||||
"@llamaindex/examples": "workspace:*",
|
||||
"@mdx-js/react": "^3.0.1",
|
||||
"clsx": "^2.1.0",
|
||||
"postcss": "^8.4.33",
|
||||
"postcss": "^8.4.38",
|
||||
"prism-react-renderer": "^2.3.1",
|
||||
"raw-loader": "^4.0.2",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@docusaurus/module-type-aliases": "3.1.0",
|
||||
"@docusaurus/preset-classic": "^3.1.1",
|
||||
"@docusaurus/theme-classic": "^3.1.1",
|
||||
"@docusaurus/types": "^3.1.1",
|
||||
"@tsconfig/docusaurus": "^2.0.2",
|
||||
"@types/node": "^18.19.10",
|
||||
"@docusaurus/module-type-aliases": "3.2.0",
|
||||
"@docusaurus/preset-classic": "^3.2.1",
|
||||
"@docusaurus/theme-classic": "^3.2.1",
|
||||
"@docusaurus/types": "^3.2.1",
|
||||
"@tsconfig/docusaurus": "^2.0.3",
|
||||
"@types/node": "^18.19.31",
|
||||
"docusaurus-plugin-typedoc": "^0.22.0",
|
||||
"typedoc": "^0.25.7",
|
||||
"typedoc": "^0.25.13",
|
||||
"typedoc-plugin-markdown": "^3.17.1",
|
||||
"typescript": "^5.3.3"
|
||||
"typescript": "^5.4.4"
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
# examples
|
||||
|
||||
## 0.0.4
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- d2e8d0c: add support for Milvus vector store
|
||||
- Updated dependencies [d2e8d0c]
|
||||
- Updated dependencies [aefc326]
|
||||
- Updated dependencies [484a710]
|
||||
- Updated dependencies [d766bd0]
|
||||
- Updated dependencies [dd95927]
|
||||
- Updated dependencies [bf583a7]
|
||||
- llamaindex@0.2.0
|
||||
@@ -0,0 +1,29 @@
|
||||
import fs from "node:fs/promises";
|
||||
|
||||
import { Document, OpenAI, Settings, VectorStoreIndex } from "llamaindex";
|
||||
|
||||
Settings.llm = new OpenAI({ model: "gpt-4" });
|
||||
|
||||
async function main() {
|
||||
// Load essay from abramov.txt in Node
|
||||
const path = "node_modules/llamaindex/examples/abramov.txt";
|
||||
|
||||
const essay = await fs.readFile(path, "utf-8");
|
||||
|
||||
// Create Document object with essay
|
||||
const document = new Document({ text: essay, id_: path });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const response = await queryEngine.query({
|
||||
query: "What did the author do in college?",
|
||||
});
|
||||
|
||||
// Output response
|
||||
console.log(response.toString());
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -6,11 +6,11 @@ import {
|
||||
OpenAI,
|
||||
OpenAIAgent,
|
||||
QueryEngineTool,
|
||||
Settings,
|
||||
SimpleNodeParser,
|
||||
SimpleToolNodeMapping,
|
||||
SummaryIndex,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
storageContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
@@ -18,6 +18,8 @@ import { extractWikipedia } from "./helpers/extractWikipedia";
|
||||
|
||||
const wikiTitles = ["Brazil", "Canada"];
|
||||
|
||||
Settings.llm = new OpenAI({ model: "gpt-4" });
|
||||
|
||||
async function main() {
|
||||
await extractWikipedia(wikiTitles);
|
||||
|
||||
@@ -30,11 +32,6 @@ async function main() {
|
||||
countryDocs[title] = document;
|
||||
}
|
||||
|
||||
const llm = new OpenAI({
|
||||
model: "gpt-4",
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm });
|
||||
const storageContext = await storageContextFromDefaults({
|
||||
persistDir: "./storage",
|
||||
});
|
||||
@@ -54,13 +51,11 @@ async function main() {
|
||||
console.log(`Creating index for ${title}`);
|
||||
|
||||
const vectorIndex = await VectorStoreIndex.init({
|
||||
serviceContext: serviceContext,
|
||||
storageContext: storageContext,
|
||||
nodes,
|
||||
});
|
||||
|
||||
const summaryIndex = await SummaryIndex.init({
|
||||
serviceContext: serviceContext,
|
||||
nodes,
|
||||
});
|
||||
|
||||
@@ -90,8 +85,7 @@ async function main() {
|
||||
|
||||
const agent = new OpenAIAgent({
|
||||
tools: queryEngineTools,
|
||||
llm,
|
||||
verbose: true,
|
||||
llm: new OpenAI({ model: "gpt-4" }),
|
||||
});
|
||||
|
||||
documentAgents[title] = agent;
|
||||
@@ -126,15 +120,11 @@ async function main() {
|
||||
allTools,
|
||||
toolMapping,
|
||||
VectorStoreIndex,
|
||||
{
|
||||
serviceContext,
|
||||
},
|
||||
);
|
||||
|
||||
const topAgent = new OpenAIAgent({
|
||||
toolRetriever: await objectIndex.asRetriever({}),
|
||||
llm,
|
||||
verbose: true,
|
||||
llm: new OpenAI({ model: "gpt-4" }),
|
||||
prefixMessages: [
|
||||
{
|
||||
content:
|
||||
@@ -153,4 +143,4 @@ async function main() {
|
||||
});
|
||||
}
|
||||
|
||||
main();
|
||||
void main();
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { FunctionTool, OpenAIAgent } from "llamaindex";
|
||||
|
||||
// Define a function to sum two numbers
|
||||
function sumNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a + b;
|
||||
function sumNumbers({ a, b }: { a: number; b: number }) {
|
||||
return `${a + b}`;
|
||||
}
|
||||
|
||||
// Define a function to divide two numbers
|
||||
function divideNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a / b;
|
||||
function divideNumbers({ a, b }: { a: number; b: number }) {
|
||||
return `${a / b}`;
|
||||
}
|
||||
|
||||
// Define the parameters of the sum function as a JSON schema
|
||||
@@ -24,7 +24,7 @@ const sumJSON = {
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
} as const;
|
||||
|
||||
const divideJSON = {
|
||||
type: "object",
|
||||
@@ -39,7 +39,7 @@ const divideJSON = {
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
} as const;
|
||||
|
||||
async function main() {
|
||||
// Create a function tool from the sum function
|
||||
@@ -59,7 +59,6 @@ async function main() {
|
||||
// Create an OpenAIAgent with the function tools
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [functionTool, functionTool2],
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
// Chat with the agent
|
||||
@@ -71,6 +70,6 @@ async function main() {
|
||||
console.log(String(response));
|
||||
}
|
||||
|
||||
main().then(() => {
|
||||
void main().then(() => {
|
||||
console.log("Done");
|
||||
});
|
||||
|
||||
@@ -29,7 +29,6 @@ async function main() {
|
||||
// Create an OpenAIAgent with the function tools
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [queryEngineTool],
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
// Chat with the agent
|
||||
@@ -41,6 +40,6 @@ async function main() {
|
||||
console.log(String(response));
|
||||
}
|
||||
|
||||
main().then(() => {
|
||||
void main().then(() => {
|
||||
console.log("Done");
|
||||
});
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { FunctionTool, ReActAgent } from "llamaindex";
|
||||
import { Anthropic, FunctionTool, ReActAgent } from "llamaindex";
|
||||
|
||||
// Define a function to sum two numbers
|
||||
function sumNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a + b;
|
||||
function sumNumbers({ a, b }: { a: number; b: number }) {
|
||||
return `${a + b}`;
|
||||
}
|
||||
|
||||
// Define a function to divide two numbers
|
||||
function divideNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a / b;
|
||||
function divideNumbers({ a, b }: { a: number; b: number }) {
|
||||
return `${a / b}`;
|
||||
}
|
||||
|
||||
// Define the parameters of the sum function as a JSON schema
|
||||
@@ -24,7 +24,7 @@ const sumJSON = {
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
} as const;
|
||||
|
||||
const divideJSON = {
|
||||
type: "object",
|
||||
@@ -39,7 +39,7 @@ const divideJSON = {
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
} as const;
|
||||
|
||||
async function main() {
|
||||
// Create a function tool from the sum function
|
||||
@@ -56,10 +56,15 @@ async function main() {
|
||||
parameters: divideJSON,
|
||||
});
|
||||
|
||||
// Create an OpenAIAgent with the function tools
|
||||
const anthropic = new Anthropic({
|
||||
apiKey: process.env.ANTHROPIC_API_KEY,
|
||||
model: "claude-3-opus",
|
||||
});
|
||||
|
||||
// Create an ReActAgent with the function tools
|
||||
const agent = new ReActAgent({
|
||||
llm: anthropic,
|
||||
tools: [functionTool, functionTool2],
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
// Chat with the agent
|
||||
@@ -71,6 +76,6 @@ async function main() {
|
||||
console.log(String(response));
|
||||
}
|
||||
|
||||
main().then(() => {
|
||||
void main().then(() => {
|
||||
console.log("Done");
|
||||
});
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { FunctionTool, OpenAIAgent } from "llamaindex";
|
||||
|
||||
// Define a function to sum two numbers
|
||||
function sumNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a + b;
|
||||
function sumNumbers({ a, b }: { a: number; b: number }) {
|
||||
return `${a + b}`;
|
||||
}
|
||||
|
||||
// Define a function to divide two numbers
|
||||
function divideNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a / b;
|
||||
function divideNumbers({ a, b }: { a: number; b: number }) {
|
||||
return `${a / b}`;
|
||||
}
|
||||
|
||||
// Define the parameters of the sum function as a JSON schema
|
||||
@@ -24,22 +24,22 @@ const sumJSON = {
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
} as const;
|
||||
|
||||
const divideJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The dividend a to divide",
|
||||
description: "The dividend",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The divisor b to divide by",
|
||||
description: "The divisor",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
} as const;
|
||||
|
||||
async function main() {
|
||||
// Create a function tool from the sum function
|
||||
@@ -59,7 +59,6 @@ async function main() {
|
||||
// Create an OpenAIAgent with the function tools
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [functionTool, functionTool2],
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
// Create a task to sum and divide numbers
|
||||
@@ -90,6 +89,6 @@ async function main() {
|
||||
}
|
||||
}
|
||||
|
||||
main().then(() => {
|
||||
void main().then(() => {
|
||||
console.log("Done");
|
||||
});
|
||||
|
||||
@@ -29,7 +29,6 @@ async function main() {
|
||||
// Create an OpenAIAgent with the function tools
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [queryEngineTool],
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
const task = agent.createTask("What was his salary?");
|
||||
@@ -59,6 +58,6 @@ async function main() {
|
||||
}
|
||||
}
|
||||
|
||||
main().then(() => {
|
||||
void main().then(() => {
|
||||
console.log("Done");
|
||||
});
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { FunctionTool, ReActAgent } from "llamaindex";
|
||||
|
||||
// Define a function to sum two numbers
|
||||
function sumNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a + b;
|
||||
function sumNumbers({ a, b }: { a: number; b: number }) {
|
||||
return `${a + b}`;
|
||||
}
|
||||
|
||||
// Define a function to divide two numbers
|
||||
function divideNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a / b;
|
||||
function divideNumbers({ a, b }: { a: number; b: number }) {
|
||||
return `${a / b}`;
|
||||
}
|
||||
|
||||
// Define the parameters of the sum function as a JSON schema
|
||||
@@ -24,7 +24,7 @@ const sumJSON = {
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
} as const;
|
||||
|
||||
const divideJSON = {
|
||||
type: "object",
|
||||
@@ -39,7 +39,7 @@ const divideJSON = {
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
} as const;
|
||||
|
||||
async function main() {
|
||||
// Create a function tool from the sum function
|
||||
@@ -59,7 +59,6 @@ async function main() {
|
||||
// Create an OpenAIAgent with the function tools
|
||||
const agent = new ReActAgent({
|
||||
tools: [functionTool, functionTool2],
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
const task = agent.createTask("Divide 16 by 2 then add 20");
|
||||
@@ -85,6 +84,6 @@ async function main() {
|
||||
}
|
||||
}
|
||||
|
||||
main().then(() => {
|
||||
void main().then(() => {
|
||||
console.log("Done");
|
||||
});
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { FunctionTool, OpenAIAgent } from "llamaindex";
|
||||
|
||||
// Define a function to sum two numbers
|
||||
function sumNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a + b;
|
||||
function sumNumbers({ a, b }: { a: number; b: number }) {
|
||||
return `${a + b}`;
|
||||
}
|
||||
|
||||
// Define a function to divide two numbers
|
||||
function divideNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a / b;
|
||||
function divideNumbers({ a, b }: { a: number; b: number }) {
|
||||
return `${a / b}`;
|
||||
}
|
||||
|
||||
// Define the parameters of the sum function as a JSON schema
|
||||
@@ -24,7 +24,7 @@ const sumJSON = {
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
} as const;
|
||||
|
||||
const divideJSON = {
|
||||
type: "object",
|
||||
@@ -39,18 +39,18 @@ const divideJSON = {
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
} as const;
|
||||
|
||||
async function main() {
|
||||
// Create a function tool from the sum function
|
||||
const functionTool = new FunctionTool(sumNumbers, {
|
||||
const functionTool = FunctionTool.from(sumNumbers, {
|
||||
name: "sumNumbers",
|
||||
description: "Use this function to sum two numbers",
|
||||
parameters: sumJSON,
|
||||
});
|
||||
|
||||
// Create a function tool from the divide function
|
||||
const functionTool2 = new FunctionTool(divideNumbers, {
|
||||
const functionTool2 = FunctionTool.from(divideNumbers, {
|
||||
name: "divideNumbers",
|
||||
description: "Use this function to divide two numbers",
|
||||
parameters: divideJSON,
|
||||
@@ -59,7 +59,6 @@ async function main() {
|
||||
// Create an OpenAIAgent with the function tools
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [functionTool, functionTool2],
|
||||
verbose: false,
|
||||
});
|
||||
|
||||
const stream = await agent.chat({
|
||||
@@ -72,6 +71,6 @@ async function main() {
|
||||
}
|
||||
}
|
||||
|
||||
main().then(() => {
|
||||
void main().then(() => {
|
||||
console.log("\nDone");
|
||||
});
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { OpenAI, OpenAIAgent, WikipediaTool } from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
const llm = new OpenAI({ model: "gpt-4-turbo" });
|
||||
const wikiTool = new WikipediaTool();
|
||||
|
||||
// Create an OpenAIAgent with the Wikipedia tool
|
||||
const agent = new OpenAIAgent({
|
||||
llm,
|
||||
tools: [wikiTool],
|
||||
});
|
||||
|
||||
// Chat with the agent
|
||||
const response = await agent.chat({
|
||||
message: "Who was Goethe?",
|
||||
stream: true,
|
||||
});
|
||||
|
||||
for await (const chunk of response.response) {
|
||||
process.stdout.write(chunk.response);
|
||||
}
|
||||
}
|
||||
|
||||
(async function () {
|
||||
await main();
|
||||
console.log("\nDone");
|
||||
})();
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Anthropic } from "llamaindex";
|
||||
|
||||
(async () => {
|
||||
const anthropic = new Anthropic({
|
||||
apiKey: process.env.ANTHROPIC_API_KEY,
|
||||
model: "claude-3-haiku",
|
||||
});
|
||||
const result = await anthropic.chat({
|
||||
messages: [
|
||||
{ content: "You want to talk in rhymes.", role: "system" },
|
||||
{
|
||||
content:
|
||||
"How much wood would a woodchuck chuck if a woodchuck could chuck wood?",
|
||||
role: "user",
|
||||
},
|
||||
],
|
||||
});
|
||||
console.log(result);
|
||||
})();
|
||||
@@ -32,10 +32,10 @@ run `ts-node astradb/example`
|
||||
|
||||
This sample loads the same dataset of movie reviews as the Astra Portal sample dataset. (Feel free to load the data in your the Astra Data Explorer to compare)
|
||||
|
||||
run `ts-node astradb/load`
|
||||
run `npx ts-node astradb/load`
|
||||
|
||||
### Use RAG to Query the data
|
||||
|
||||
Check out your data in the Astra Data Explorer and change the sample query as you see fit.
|
||||
|
||||
run `ts-node astradb/query`
|
||||
run `npx ts-node astradb/query`
|
||||
|
||||
@@ -55,4 +55,4 @@ async function main() {
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
void main();
|
||||
|
||||
@@ -27,4 +27,4 @@ async function main() {
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
void main();
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
import {
|
||||
AstraDBVectorStore,
|
||||
serviceContextFromDefaults,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
import { AstraDBVectorStore, VectorStoreIndex } from "llamaindex";
|
||||
|
||||
const collectionName = "movie_reviews";
|
||||
|
||||
@@ -11,8 +7,7 @@ async function main() {
|
||||
const astraVS = new AstraDBVectorStore({ contentKey: "reviewtext" });
|
||||
await astraVS.connect(collectionName);
|
||||
|
||||
const ctx = serviceContextFromDefaults();
|
||||
const index = await VectorStoreIndex.fromVectorStore(astraVS, ctx);
|
||||
const index = await VectorStoreIndex.fromVectorStore(astraVS);
|
||||
|
||||
const retriever = await index.asRetriever({ similarityTopK: 20 });
|
||||
|
||||
@@ -28,4 +23,4 @@ async function main() {
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
void main();
|
||||
|
||||
@@ -4,18 +4,18 @@ import readline from "node:readline/promises";
|
||||
import {
|
||||
ContextChatEngine,
|
||||
Document,
|
||||
serviceContextFromDefaults,
|
||||
Settings,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
|
||||
import essay from "./essay";
|
||||
|
||||
// Update chunk size
|
||||
Settings.chunkSize = 512;
|
||||
|
||||
async function main() {
|
||||
const document = new Document({ text: essay });
|
||||
const serviceContext = serviceContextFromDefaults({ chunkSize: 512 });
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
const retriever = index.asRetriever();
|
||||
retriever.similarityTopK = 5;
|
||||
const chatEngine = new ContextChatEngine({ retriever });
|
||||
|
||||
+12
-1
@@ -1,7 +1,18 @@
|
||||
import { stdin as input, stdout as output } from "node:process";
|
||||
import readline from "node:readline/promises";
|
||||
|
||||
import { OpenAI, SimpleChatEngine, SummaryChatHistory } from "llamaindex";
|
||||
import {
|
||||
OpenAI,
|
||||
Settings,
|
||||
SimpleChatEngine,
|
||||
SummaryChatHistory,
|
||||
} from "llamaindex";
|
||||
|
||||
if (process.env.NODE_ENV === "development") {
|
||||
Settings.callbackManager.on("llm-end", (event) => {
|
||||
console.log("callers chain", event.reason?.computedCallers);
|
||||
});
|
||||
}
|
||||
|
||||
async function main() {
|
||||
// Set maxTokens to 75% of the context window size of 4096
|
||||
|
||||
@@ -54,4 +54,4 @@ async function main() {
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
void main();
|
||||
|
||||
@@ -37,4 +37,4 @@ async function main() {
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
void main();
|
||||
|
||||
@@ -31,3 +31,11 @@ This example shows how to use the managed index with a query engine.
|
||||
```shell
|
||||
pnpx ts-node cloud/query.ts
|
||||
```
|
||||
|
||||
## Pipeline
|
||||
|
||||
This example shows how to create a managed index with a pipeline.
|
||||
|
||||
```shell
|
||||
pnpx ts-node cloud/pipeline.ts
|
||||
```
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import fs from "node:fs/promises";
|
||||
|
||||
import { stdin as input, stdout as output } from "node:process";
|
||||
|
||||
import readline from "node:readline/promises";
|
||||
|
||||
import { Document, LlamaCloudIndex } from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
const path = "node_modules/llamaindex/examples/abramov.txt";
|
||||
|
||||
const essay = await fs.readFile(path, "utf-8");
|
||||
|
||||
// Create Document object with essay
|
||||
const document = new Document({ text: essay, id_: path });
|
||||
|
||||
const index = await LlamaCloudIndex.fromDocuments({
|
||||
documents: [document],
|
||||
name: "test",
|
||||
projectName: "default",
|
||||
apiKey: process.env.LLAMA_CLOUD_API_KEY,
|
||||
baseUrl: process.env.LLAMA_CLOUD_BASE_URL,
|
||||
});
|
||||
|
||||
const queryEngine = index.asQueryEngine({
|
||||
denseSimilarityTopK: 5,
|
||||
});
|
||||
|
||||
const rl = readline.createInterface({ input, output });
|
||||
|
||||
while (true) {
|
||||
const query = await rl.question("Query: ");
|
||||
const stream = await queryEngine.query({
|
||||
query,
|
||||
stream: true,
|
||||
});
|
||||
console.log();
|
||||
for await (const chunk of stream) {
|
||||
process.stdout.write(chunk.response);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,34 @@
|
||||
import fs from "node:fs/promises";
|
||||
|
||||
import {
|
||||
Document,
|
||||
IngestionPipeline,
|
||||
OpenAIEmbedding,
|
||||
SimpleNodeParser,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Load essay from abramov.txt in Node
|
||||
const path = "node_modules/llamaindex/examples/abramov.txt";
|
||||
|
||||
const essay = await fs.readFile(path, "utf-8");
|
||||
|
||||
// Create Document object with essay
|
||||
const document = new Document({ text: essay, id_: path });
|
||||
const pipeline = new IngestionPipeline({
|
||||
name: "pipeline",
|
||||
transformations: [
|
||||
new SimpleNodeParser({ chunkSize: 1024, chunkOverlap: 20 }),
|
||||
new OpenAIEmbedding({ apiKey: "api-key" }),
|
||||
],
|
||||
});
|
||||
|
||||
const pipelineId = await pipeline.register({
|
||||
documents: [document],
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
console.log(`Pipeline with id ${pipelineId} successfully created.`);
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,21 +1,10 @@
|
||||
import {
|
||||
CorrectnessEvaluator,
|
||||
OpenAI,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
import { CorrectnessEvaluator, OpenAI, Settings } from "llamaindex";
|
||||
|
||||
// Update llm to use OpenAI
|
||||
Settings.llm = new OpenAI({ model: "gpt-4" });
|
||||
|
||||
async function main() {
|
||||
const llm = new OpenAI({
|
||||
model: "gpt-4",
|
||||
});
|
||||
|
||||
const ctx = serviceContextFromDefaults({
|
||||
llm,
|
||||
});
|
||||
|
||||
const evaluator = new CorrectnessEvaluator({
|
||||
serviceContext: ctx,
|
||||
});
|
||||
const evaluator = new CorrectnessEvaluator();
|
||||
|
||||
const query =
|
||||
"Can you explain the theory of relativity proposed by Albert Einstein in detail?";
|
||||
@@ -33,4 +22,4 @@ However, general relativity, published in 1915, extended these ideas to include
|
||||
console.log(result);
|
||||
}
|
||||
|
||||
main();
|
||||
void main();
|
||||
|
||||
@@ -2,22 +2,15 @@ import {
|
||||
Document,
|
||||
FaithfulnessEvaluator,
|
||||
OpenAI,
|
||||
Settings,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
// Update llm to use OpenAI
|
||||
Settings.llm = new OpenAI({ model: "gpt-4" });
|
||||
|
||||
async function main() {
|
||||
const llm = new OpenAI({
|
||||
model: "gpt-4",
|
||||
});
|
||||
|
||||
const ctx = serviceContextFromDefaults({
|
||||
llm,
|
||||
});
|
||||
|
||||
const evaluator = new FaithfulnessEvaluator({
|
||||
serviceContext: ctx,
|
||||
});
|
||||
const evaluator = new FaithfulnessEvaluator();
|
||||
|
||||
const documents = [
|
||||
new Document({
|
||||
@@ -43,4 +36,4 @@ async function main() {
|
||||
console.log(result);
|
||||
}
|
||||
|
||||
main();
|
||||
void main();
|
||||
|
||||
@@ -2,22 +2,16 @@ import {
|
||||
Document,
|
||||
OpenAI,
|
||||
RelevancyEvaluator,
|
||||
Settings,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
Settings.llm = new OpenAI({
|
||||
model: "gpt-4",
|
||||
});
|
||||
|
||||
async function main() {
|
||||
const llm = new OpenAI({
|
||||
model: "gpt-4",
|
||||
});
|
||||
|
||||
const ctx = serviceContextFromDefaults({
|
||||
llm,
|
||||
});
|
||||
|
||||
const evaluator = new RelevancyEvaluator({
|
||||
serviceContext: ctx,
|
||||
});
|
||||
const evaluator = new RelevancyEvaluator();
|
||||
|
||||
const documents = [
|
||||
new Document({
|
||||
@@ -43,4 +37,4 @@ async function main() {
|
||||
console.log(result);
|
||||
}
|
||||
|
||||
main();
|
||||
void main();
|
||||
|
||||
+7
-17
@@ -1,30 +1,20 @@
|
||||
import fs from "node:fs/promises";
|
||||
|
||||
import {
|
||||
Document,
|
||||
Groq,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
import { Document, Groq, Settings, VectorStoreIndex } from "llamaindex";
|
||||
|
||||
// Update llm to use Groq
|
||||
Settings.llm = new Groq({
|
||||
apiKey: process.env.GROQ_API_KEY,
|
||||
});
|
||||
|
||||
async function main() {
|
||||
// Create an instance of the LLM
|
||||
const groq = new Groq({
|
||||
apiKey: process.env.GROQ_API_KEY,
|
||||
});
|
||||
|
||||
// Create a service context
|
||||
const serviceContext = serviceContextFromDefaults({ llm: groq });
|
||||
|
||||
// Load essay from abramov.txt in Node
|
||||
const path = "node_modules/llamaindex/examples/abramov.txt";
|
||||
const essay = await fs.readFile(path, "utf-8");
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
+7
-12
@@ -4,10 +4,15 @@ import {
|
||||
Document,
|
||||
HuggingFaceEmbedding,
|
||||
HuggingFaceEmbeddingModelType,
|
||||
Settings,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
// Update embed model
|
||||
Settings.embedModel = new HuggingFaceEmbedding({
|
||||
modelType: HuggingFaceEmbeddingModelType.XENOVA_ALL_MPNET_BASE_V2,
|
||||
});
|
||||
|
||||
async function main() {
|
||||
// Load essay from abramov.txt in Node
|
||||
const path = "node_modules/llamaindex/examples/abramov.txt";
|
||||
@@ -17,18 +22,8 @@ async function main() {
|
||||
// Create Document object with essay
|
||||
const document = new Document({ text: essay, id_: path });
|
||||
|
||||
// Use Local embedding from HuggingFace
|
||||
const embedModel = new HuggingFaceEmbedding({
|
||||
modelType: HuggingFaceEmbeddingModelType.XENOVA_ALL_MPNET_BASE_V2,
|
||||
});
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
embedModel,
|
||||
});
|
||||
|
||||
// Split text and create embeddings. Store them in a VectorStoreIndex
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
@@ -36,9 +36,7 @@ async function main() {
|
||||
],
|
||||
});
|
||||
|
||||
const json = JSON.parse(response.message.content);
|
||||
|
||||
console.log(json);
|
||||
console.log(response.message.content);
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
|
||||
+8
-13
@@ -1,26 +1,21 @@
|
||||
import {
|
||||
Document,
|
||||
Settings,
|
||||
SimpleNodeParser,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
export const STORAGE_DIR = "./data";
|
||||
|
||||
// Update node parser
|
||||
Settings.nodeParser = new SimpleNodeParser({
|
||||
chunkSize: 512,
|
||||
chunkOverlap: 20,
|
||||
splitLongSentences: true,
|
||||
});
|
||||
(async () => {
|
||||
// create service context that is splitting sentences longer than CHUNK_SIZE
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
nodeParser: new SimpleNodeParser({
|
||||
chunkSize: 512,
|
||||
chunkOverlap: 20,
|
||||
splitLongSentences: true,
|
||||
}),
|
||||
});
|
||||
|
||||
// generate a document with a very long sentence (9000 words long)
|
||||
const longSentence = "is ".repeat(9000) + ".";
|
||||
const document = new Document({ text: longSentence, id_: "1" });
|
||||
await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
await VectorStoreIndex.fromDocuments([document]);
|
||||
})();
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
# Milvus Vector Store
|
||||
|
||||
Here are two sample scripts which work with loading and querying data from a Milvus Vector Store.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- An Milvus Vector Database
|
||||
- Hosted https://milvus.io/
|
||||
- Self Hosted https://milvus.io/docs/install_standalone-docker.md
|
||||
- An OpenAI API Key
|
||||
|
||||
## Setup
|
||||
|
||||
1. Set your env variables:
|
||||
|
||||
- `MILVUS_ADDRESS`: Address of your Milvus Vector Store (like localhost:19530)
|
||||
- `MILVUS_USERNAME`: empty or username for your Milvus Vector Store
|
||||
- `MILVUS_PASSWORD`: empty or password for your Milvus Vector Store
|
||||
- `OPENAI_API_KEY`: Your OpenAI key
|
||||
|
||||
2. `cd` Into the `examples` directory
|
||||
3. run `npm i`
|
||||
|
||||
## Load the data
|
||||
|
||||
This sample loads the same dataset of movie reviews as sample dataset. You can install https://github.com/zilliztech/attu to inspect the loaded data.
|
||||
|
||||
run `npx ts-node milvus/load`
|
||||
|
||||
## Use RAG to Query the data
|
||||
|
||||
Check out your data in Attu and change the sample query as you see fit.
|
||||
|
||||
run `npx ts-node milvus/query`
|
||||
@@ -0,0 +1,26 @@
|
||||
import {
|
||||
MilvusVectorStore,
|
||||
PapaCSVReader,
|
||||
storageContextFromDefaults,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
|
||||
const collectionName = "movie_reviews";
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
const reader = new PapaCSVReader(false);
|
||||
const docs = await reader.loadData("./data/movie_reviews.csv");
|
||||
|
||||
const vectorStore = new MilvusVectorStore({ collection: collectionName });
|
||||
|
||||
const ctx = await storageContextFromDefaults({ vectorStore });
|
||||
const index = await VectorStoreIndex.fromDocuments(docs, {
|
||||
storageContext: ctx,
|
||||
});
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
void main();
|
||||
@@ -0,0 +1,25 @@
|
||||
import { MilvusVectorStore, VectorStoreIndex } from "llamaindex";
|
||||
|
||||
const collectionName = "movie_reviews";
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
const milvus = new MilvusVectorStore({ collection: collectionName });
|
||||
|
||||
const index = await VectorStoreIndex.fromVectorStore(milvus);
|
||||
|
||||
const retriever = await index.asRetriever({ similarityTopK: 20 });
|
||||
|
||||
const queryEngine = await index.asQueryEngine({ retriever });
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query: "What is the best reviewed movie?",
|
||||
});
|
||||
|
||||
console.log(results.response);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
void main();
|
||||
+9
-15
@@ -1,15 +1,18 @@
|
||||
import * as fs from "fs/promises";
|
||||
import {
|
||||
BaseEmbedding,
|
||||
Document,
|
||||
LLM,
|
||||
MistralAI,
|
||||
MistralAIEmbedding,
|
||||
Settings,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
async function rag(llm: LLM, embedModel: BaseEmbedding, query: string) {
|
||||
// Update embed model
|
||||
Settings.embedModel = new MistralAIEmbedding();
|
||||
// Update llm to use MistralAI
|
||||
Settings.llm = new MistralAI({ model: "mistral-tiny" });
|
||||
|
||||
async function rag(query: string) {
|
||||
// Load essay from abramov.txt in Node
|
||||
const path = "node_modules/llamaindex/examples/abramov.txt";
|
||||
|
||||
@@ -18,12 +21,7 @@ async function rag(llm: LLM, embedModel: BaseEmbedding, query: string) {
|
||||
// Create Document object with essay
|
||||
const document = new Document({ text: essay, id_: path });
|
||||
|
||||
// Split text and create embeddings. Store them in a VectorStoreIndex
|
||||
const serviceContext = serviceContextFromDefaults({ llm, embedModel });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine();
|
||||
@@ -60,10 +58,6 @@ async function rag(llm: LLM, embedModel: BaseEmbedding, query: string) {
|
||||
}
|
||||
|
||||
// rag
|
||||
const ragResponse = await rag(
|
||||
llm,
|
||||
embedding,
|
||||
"What did the author do in college?",
|
||||
);
|
||||
const ragResponse = await rag("What did the author do in college?");
|
||||
console.log(ragResponse);
|
||||
})();
|
||||
|
||||
+1
-1
@@ -61,4 +61,4 @@ async function main() {
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
void main();
|
||||
|
||||
@@ -31,4 +31,4 @@ async function importJsonToMongo() {
|
||||
}
|
||||
|
||||
// Run the import function
|
||||
importJsonToMongo();
|
||||
void importJsonToMongo();
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
/* eslint-disable turbo/no-undeclared-env-vars */
|
||||
import * as dotenv from "dotenv";
|
||||
import {
|
||||
MongoDBAtlasVectorSearch,
|
||||
serviceContextFromDefaults,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
import { MongoDBAtlasVectorSearch, VectorStoreIndex } from "llamaindex";
|
||||
import { MongoClient } from "mongodb";
|
||||
|
||||
// Load environment variables from local .env file
|
||||
@@ -12,7 +8,7 @@ dotenv.config();
|
||||
|
||||
async function query() {
|
||||
const client = new MongoClient(process.env.MONGODB_URI!);
|
||||
const serviceContext = serviceContextFromDefaults();
|
||||
|
||||
const store = new MongoDBAtlasVectorSearch({
|
||||
mongodbClient: client,
|
||||
dbName: process.env.MONGODB_DATABASE!,
|
||||
@@ -20,7 +16,7 @@ async function query() {
|
||||
indexName: process.env.MONGODB_VECTOR_INDEX!,
|
||||
});
|
||||
|
||||
const index = await VectorStoreIndex.fromVectorStore(store, serviceContext);
|
||||
const index = await VectorStoreIndex.fromVectorStore(store);
|
||||
|
||||
const retriever = index.asRetriever({ similarityTopK: 20 });
|
||||
const queryEngine = index.asQueryEngine({ retriever });
|
||||
@@ -31,4 +27,4 @@ async function query() {
|
||||
await client.close();
|
||||
}
|
||||
|
||||
query();
|
||||
void query();
|
||||
|
||||
@@ -30,4 +30,4 @@ async function main() {
|
||||
console.log(`Similarity between "${text2}" and the image is ${sim2}`);
|
||||
}
|
||||
|
||||
main();
|
||||
void main();
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
import {
|
||||
ServiceContext,
|
||||
serviceContextFromDefaults,
|
||||
Settings,
|
||||
SimpleDirectoryReader,
|
||||
storageContextFromDefaults,
|
||||
VectorStoreIndex,
|
||||
storageContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
import * as path from "path";
|
||||
|
||||
// Update chunk size and overlap
|
||||
Settings.chunkSize = 512;
|
||||
Settings.chunkOverlap = 20;
|
||||
|
||||
async function getRuntime(func: any) {
|
||||
const start = Date.now();
|
||||
await func();
|
||||
@@ -14,7 +18,7 @@ async function getRuntime(func: any) {
|
||||
return end - start;
|
||||
}
|
||||
|
||||
async function generateDatasource(serviceContext: ServiceContext) {
|
||||
async function generateDatasource() {
|
||||
console.log(`Generating storage...`);
|
||||
// Split documents, create embeddings and store them in the storage context
|
||||
const ms = await getRuntime(async () => {
|
||||
@@ -26,7 +30,6 @@ async function generateDatasource(serviceContext: ServiceContext) {
|
||||
storeImages: true,
|
||||
});
|
||||
await VectorStoreIndex.fromDocuments(documents, {
|
||||
serviceContext,
|
||||
storageContext,
|
||||
});
|
||||
});
|
||||
@@ -34,12 +37,7 @@ async function generateDatasource(serviceContext: ServiceContext) {
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
chunkSize: 512,
|
||||
chunkOverlap: 20,
|
||||
});
|
||||
|
||||
await generateDatasource(serviceContext);
|
||||
await generateDatasource();
|
||||
console.log("Finished generating storage.");
|
||||
}
|
||||
|
||||
|
||||
+20
-23
@@ -1,17 +1,28 @@
|
||||
import {
|
||||
CallbackManager,
|
||||
ImageDocument,
|
||||
ImageType,
|
||||
MultiModalResponseSynthesizer,
|
||||
NodeWithScore,
|
||||
OpenAI,
|
||||
ServiceContext,
|
||||
Settings,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
storageContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
export async function createIndex(serviceContext: ServiceContext) {
|
||||
// Update chunk size and overlap
|
||||
Settings.chunkSize = 512;
|
||||
Settings.chunkOverlap = 20;
|
||||
|
||||
// Update llm
|
||||
Settings.llm = new OpenAI({ model: "gpt-4-turbo", maxTokens: 512 });
|
||||
|
||||
// Update callbackManager
|
||||
Settings.callbackManager = new CallbackManager({
|
||||
onRetrieve: ({ query, nodes }) => {
|
||||
console.log(`Retrieved ${nodes.length} nodes for query: ${query}`);
|
||||
},
|
||||
});
|
||||
|
||||
export async function createIndex() {
|
||||
// set up vector store index with two vector stores, one for text, the other for images
|
||||
const storageContext = await storageContextFromDefaults({
|
||||
persistDir: "storage",
|
||||
@@ -20,30 +31,16 @@ export async function createIndex(serviceContext: ServiceContext) {
|
||||
return await VectorStoreIndex.init({
|
||||
nodes: [],
|
||||
storageContext,
|
||||
serviceContext,
|
||||
});
|
||||
}
|
||||
|
||||
async function main() {
|
||||
let images: ImageType[] = [];
|
||||
const callbackManager = new CallbackManager({
|
||||
onRetrieve: ({ query, nodes }) => {
|
||||
images = nodes
|
||||
.filter(({ node }: NodeWithScore) => node instanceof ImageDocument)
|
||||
.map(({ node }: NodeWithScore) => (node as ImageDocument).image);
|
||||
},
|
||||
});
|
||||
const llm = new OpenAI({ model: "gpt-4-vision-preview", maxTokens: 512 });
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
llm,
|
||||
chunkSize: 512,
|
||||
chunkOverlap: 20,
|
||||
callbackManager,
|
||||
});
|
||||
const index = await createIndex(serviceContext);
|
||||
const images: ImageType[] = [];
|
||||
|
||||
const index = await createIndex();
|
||||
|
||||
const queryEngine = index.asQueryEngine({
|
||||
responseSynthesizer: new MultiModalResponseSynthesizer({ serviceContext }),
|
||||
responseSynthesizer: new MultiModalResponseSynthesizer(),
|
||||
retriever: index.asRetriever({ similarityTopK: 3, imageSimilarityTopK: 1 }),
|
||||
});
|
||||
const result = await queryEngine.query({
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
import {
|
||||
ImageNode,
|
||||
serviceContextFromDefaults,
|
||||
storageContextFromDefaults,
|
||||
Settings,
|
||||
TextNode,
|
||||
VectorStoreIndex,
|
||||
storageContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
// Update chunk size and overlap
|
||||
Settings.chunkSize = 512;
|
||||
Settings.chunkOverlap = 20;
|
||||
|
||||
export async function createIndex() {
|
||||
// set up vector store index with two vector stores, one for text, the other for images
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
chunkSize: 512,
|
||||
chunkOverlap: 20,
|
||||
});
|
||||
const storageContext = await storageContextFromDefaults({
|
||||
persistDir: "storage",
|
||||
storeImages: true,
|
||||
@@ -19,7 +19,6 @@ export async function createIndex() {
|
||||
return await VectorStoreIndex.init({
|
||||
nodes: [],
|
||||
storageContext,
|
||||
serviceContext,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -21,4 +21,4 @@ Sub-header content
|
||||
console.log(splits);
|
||||
}
|
||||
|
||||
main();
|
||||
void main();
|
||||
|
||||
+13
-8
@@ -1,21 +1,26 @@
|
||||
{
|
||||
"name": "examples",
|
||||
"name": "@llamaindex/examples",
|
||||
"private": true,
|
||||
"version": "0.0.3",
|
||||
"version": "0.0.4",
|
||||
"dependencies": {
|
||||
"@aws-crypto/sha256-js": "^5.2.0",
|
||||
"@datastax/astra-db-ts": "^0.1.4",
|
||||
"@notionhq/client": "^2.2.14",
|
||||
"@notionhq/client": "^2.2.15",
|
||||
"@pinecone-database/pinecone": "^1.1.3",
|
||||
"@zilliz/milvus2-sdk-node": "^2.3.5",
|
||||
"chromadb": "^1.8.1",
|
||||
"commander": "^11.1.0",
|
||||
"dotenv": "^16.4.1",
|
||||
"llamaindex": "latest",
|
||||
"mongodb": "^6.2.0"
|
||||
"dotenv": "^16.4.5",
|
||||
"js-tiktoken": "^1.0.10",
|
||||
"llamaindex": "workspace:latest",
|
||||
"mongodb": "^6.5.0",
|
||||
"pathe": "^1.1.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^18.19.10",
|
||||
"@types/node": "^18.19.31",
|
||||
"ts-node": "^10.9.2",
|
||||
"typescript": "^5.3.3"
|
||||
"tsx": "^4.7.2",
|
||||
"typescript": "^5.4.5"
|
||||
},
|
||||
"scripts": {
|
||||
"lint": "eslint ."
|
||||
|
||||
@@ -32,7 +32,7 @@ async function main(args: any) {
|
||||
console.log(`Found ${count} files`);
|
||||
|
||||
console.log(`Importing contents from ${count} files in ${sourceDir}`);
|
||||
var fileName = "";
|
||||
const fileName = "";
|
||||
try {
|
||||
// Passing callback fn to the ctor here
|
||||
// will enable looging to console.
|
||||
@@ -42,7 +42,7 @@ async function main(args: any) {
|
||||
|
||||
const pgvs = new PGVectorStore();
|
||||
pgvs.setCollection(sourceDir);
|
||||
pgvs.clearCollection();
|
||||
await pgvs.clearCollection();
|
||||
|
||||
const ctx = await storageContextFromDefaults({ vectorStore: pgvs });
|
||||
|
||||
@@ -65,4 +65,4 @@ async function main(args: any) {
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
main(process.argv).catch((err) => console.error(err));
|
||||
void main(process.argv).catch((err) => console.error(err));
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
import {
|
||||
PGVectorStore,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
import { PGVectorStore, VectorStoreIndex } from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
const readline = require("readline").createInterface({
|
||||
@@ -15,8 +11,7 @@ async function main() {
|
||||
// Optional - set your collection name, default is no filter on this field.
|
||||
// pgvs.setCollection();
|
||||
|
||||
const ctx = serviceContextFromDefaults();
|
||||
const index = await VectorStoreIndex.fromVectorStore(pgvs, ctx);
|
||||
const index = await VectorStoreIndex.fromVectorStore(pgvs);
|
||||
|
||||
// Query the index
|
||||
const queryEngine = await index.asQueryEngine();
|
||||
|
||||
@@ -32,7 +32,7 @@ async function main(args: any) {
|
||||
console.log(`Found ${count} files`);
|
||||
|
||||
console.log(`Importing contents from ${count} files in ${sourceDir}`);
|
||||
var fileName = "";
|
||||
const fileName = "";
|
||||
try {
|
||||
// Passing callback fn to the ctor here
|
||||
// will enable looging to console.
|
||||
@@ -63,4 +63,4 @@ async function main(args: any) {
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
main(process.argv).catch((err) => console.error(err));
|
||||
void main(process.argv).catch((err) => console.error(err));
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
import {
|
||||
PineconeVectorStore,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
import { PineconeVectorStore, VectorStoreIndex } from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
const readline = require("readline").createInterface({
|
||||
@@ -13,8 +9,7 @@ async function main() {
|
||||
try {
|
||||
const pcvs = new PineconeVectorStore();
|
||||
|
||||
const ctx = serviceContextFromDefaults();
|
||||
const index = await VectorStoreIndex.fromVectorStore(pcvs, ctx);
|
||||
const index = await VectorStoreIndex.fromVectorStore(pcvs);
|
||||
|
||||
// Query the index
|
||||
const queryEngine = await index.asQueryEngine();
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
TreeSummarize,
|
||||
TreeSummarizePrompt,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
const treeSummarizePrompt: TreeSummarizePrompt = ({ context, query }) => {
|
||||
@@ -27,10 +26,8 @@ async function main() {
|
||||
|
||||
const query = "The quick brown fox jumps over the lazy dog";
|
||||
|
||||
const ctx = serviceContextFromDefaults({});
|
||||
|
||||
const responseSynthesizer = new ResponseSynthesizer({
|
||||
responseBuilder: new TreeSummarize(ctx),
|
||||
responseBuilder: new TreeSummarize(),
|
||||
});
|
||||
|
||||
const queryEngine = index.asQueryEngine({
|
||||
@@ -48,4 +45,4 @@ async function main() {
|
||||
await queryEngine.query({ query });
|
||||
}
|
||||
|
||||
main();
|
||||
void main();
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# Qdrant Vector Store Example
|
||||
|
||||
How to run `examples/qdrantdb/preFilters.ts`:
|
||||
|
||||
Add your OpenAI API Key into a file called `.env` in the parent folder of this directory. It should look like this:
|
||||
|
||||
```
|
||||
OPEN_API_KEY=sk-you-key
|
||||
```
|
||||
|
||||
Now, open a new terminal window and inside `examples`, run `npx ts-node qdrantdb/preFilters.ts`.
|
||||
@@ -0,0 +1,82 @@
|
||||
import * as dotenv from "dotenv";
|
||||
import {
|
||||
CallbackManager,
|
||||
Document,
|
||||
MetadataMode,
|
||||
QdrantVectorStore,
|
||||
Settings,
|
||||
VectorStoreIndex,
|
||||
storageContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
// Update callback manager
|
||||
Settings.callbackManager = new CallbackManager({
|
||||
onRetrieve: (data) => {
|
||||
console.log(
|
||||
"The retrieved nodes are:",
|
||||
data.nodes.map((node) => node.node.getContent(MetadataMode.NONE)),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
// Load environment variables from local .env file
|
||||
dotenv.config();
|
||||
|
||||
const collectionName = "dog_colors";
|
||||
const qdrantUrl = "http://127.0.0.1:6333";
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
const docs = [
|
||||
new Document({
|
||||
text: "The dog is brown",
|
||||
metadata: {
|
||||
dogId: "1",
|
||||
},
|
||||
}),
|
||||
new Document({
|
||||
text: "The dog is red",
|
||||
metadata: {
|
||||
dogId: "2",
|
||||
},
|
||||
}),
|
||||
];
|
||||
console.log("Creating QdrantDB vector store");
|
||||
const qdrantVs = new QdrantVectorStore({ url: qdrantUrl, collectionName });
|
||||
const ctx = await storageContextFromDefaults({ vectorStore: qdrantVs });
|
||||
|
||||
console.log("Embedding documents and adding to index");
|
||||
const index = await VectorStoreIndex.fromDocuments(docs, {
|
||||
storageContext: ctx,
|
||||
});
|
||||
|
||||
console.log(
|
||||
"Querying index with no filters: Expected output: Brown probably",
|
||||
);
|
||||
const queryEngineNoFilters = index.asQueryEngine();
|
||||
const noFilterResponse = await queryEngineNoFilters.query({
|
||||
query: "What is the color of the dog?",
|
||||
});
|
||||
console.log("No filter response:", noFilterResponse.toString());
|
||||
console.log("Querying index with dogId 2: Expected output: Red");
|
||||
const queryEngineDogId2 = index.asQueryEngine({
|
||||
preFilters: {
|
||||
filters: [
|
||||
{
|
||||
key: "dogId",
|
||||
value: "2",
|
||||
filterType: "ExactMatch",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const response = await queryEngineDogId2.query({
|
||||
query: "What is the color of the dog?",
|
||||
});
|
||||
console.log("Filter with dogId 2 response:", response.toString());
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
void main();
|
||||
@@ -0,0 +1,11 @@
|
||||
# llamaindex-loader-example
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [d2e8d0c]
|
||||
- Updated dependencies [aefc326]
|
||||
- Updated dependencies [484a710]
|
||||
- Updated dependencies [d766bd0]
|
||||
- Updated dependencies [dd95927]
|
||||
- Updated dependencies [bf583a7]
|
||||
- llamaindex@0.2.0
|
||||
@@ -17,6 +17,6 @@
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.11.14",
|
||||
"ts-node": "^10.9.2",
|
||||
"typescript": "^5.3.3"
|
||||
"typescript": "^5.4.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,25 +2,21 @@ import {
|
||||
CompactAndRefine,
|
||||
OpenAI,
|
||||
ResponseSynthesizer,
|
||||
serviceContextFromDefaults,
|
||||
Settings,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
import { PapaCSVReader } from "llamaindex/readers/CSVReader";
|
||||
|
||||
Settings.llm = new OpenAI({ model: "gpt-4" });
|
||||
|
||||
async function main() {
|
||||
// Load CSV
|
||||
const reader = new PapaCSVReader();
|
||||
const path = "../data/titanic_train.csv";
|
||||
const documents = await reader.loadData(path);
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
llm: new OpenAI({ model: "gpt-4" }),
|
||||
});
|
||||
|
||||
// Split text and create embeddings. Store them in a VectorStoreIndex
|
||||
const index = await VectorStoreIndex.fromDocuments(documents, {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments(documents);
|
||||
|
||||
const csvPrompt = ({ context = "", query = "" }) => {
|
||||
return `The following CSV file is loaded from ${path}
|
||||
@@ -32,7 +28,7 @@ Given the CSV file, generate me Typescript code to answer the question: ${query}
|
||||
};
|
||||
|
||||
const responseSynthesizer = new ResponseSynthesizer({
|
||||
responseBuilder: new CompactAndRefine(serviceContext, csvPrompt),
|
||||
responseBuilder: new CompactAndRefine(undefined, csvPrompt),
|
||||
});
|
||||
|
||||
const queryEngine = index.asQueryEngine({ responseSynthesizer });
|
||||
|
||||
@@ -2,8 +2,8 @@ import type { BaseReader, Document, Metadata } from "llamaindex";
|
||||
import {
|
||||
FILE_EXT_TO_READER,
|
||||
SimpleDirectoryReader,
|
||||
TextFileReader,
|
||||
} from "llamaindex/readers/SimpleDirectoryReader";
|
||||
import { TextFileReader } from "llamaindex/readers/TextFileReader";
|
||||
|
||||
class ZipReader implements BaseReader {
|
||||
loadData(...args: any[]): Promise<Document<Metadata>[]> {
|
||||
|
||||
@@ -20,4 +20,4 @@ async function main() {
|
||||
console.log(`Test query > ${SAMPLE_QUERY}:\n`, response.toString());
|
||||
}
|
||||
|
||||
main();
|
||||
void main();
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user