mirror of
https://github.com/run-llama/LlamaIndexTS.git
synced 2026-07-07 00:31:11 -04:00
Compare commits
85 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b856deae43 | |||
| 259c842259 | |||
| ffb195ea7a | |||
| b4677534d1 | |||
| f967b82467 | |||
| c81946930e | |||
| 1008b775a4 | |||
| 41210dfc51 | |||
| 67b7272249 | |||
| 964e045903 | |||
| 137cf67f40 | |||
| 309a526e3c | |||
| dd95927498 | |||
| 4f72feae91 | |||
| 3cd8f9f597 | |||
| d2e8d0c62a | |||
| fafbd8c9c7 | |||
| a40c91b054 | |||
| 98894055c6 | |||
| 4589a84643 | |||
| e6b7f52d3e | |||
| b169db617a | |||
| 89a49f4f4f | |||
| 58490715fe | |||
| 4c2283c4e5 | |||
| a059070dec | |||
| 20dfeb4cfa | |||
| aefc3266c1 | |||
| fdf48dd459 | |||
| 66525346a2 | |||
| c9b2ec4a2b | |||
| bf583a7266 | |||
| de194d1c73 | |||
| ecdc289df1 | |||
| 9e198ac40d | |||
| 0a06998690 | |||
| 484a7105a9 | |||
| 8d18ea167b | |||
| a2ca89bfe0 | |||
| edeea40898 | |||
| 2a7080b094 | |||
| b354f2386b | |||
| d766bd03d2 | |||
| 6a69148356 | |||
| e1e1b0b522 | |||
| d824876653 | |||
| 2048698f77 | |||
| 9942979aa7 | |||
| 3c2655a1f9 | |||
| 552a61a66f | |||
| d13143e322 | |||
| 5116ad8d08 | |||
| 64683a55f3 | |||
| 698cd9c631 | |||
| c744a99102 | |||
| 2d2935085e | |||
| 1b31e2c8cd | |||
| 7257751993 | |||
| de6bfdb1b1 | |||
| 9e49f4411b | |||
| 026d068ddf | |||
| 7055d6fc3c | |||
| e9c2366bf1 | |||
| 6278152e49 | |||
| 76010c0cea | |||
| 889b84cfb9 | |||
| a26681c416 | |||
| 90027a7b44 | |||
| aab56faf88 | |||
| c57bd11c45 | |||
| 3fa1e29468 | |||
| cf87f84900 | |||
| 402d4ef013 | |||
| fc94906a1e | |||
| b83fcd11e4 | |||
| c28af7c7bc | |||
| dbc853bcc5 | |||
| c8396c5a3c | |||
| 65af8d3a26 | |||
| 329b6ec958 | |||
| 09bf27abd7 | |||
| 2ec6a529c7 | |||
| e8e21a0e4e | |||
| 88d243f145 | |||
| 3a6e287443 |
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"llamaindex": patch
|
||||
---
|
||||
|
||||
Add auto create milvus collection and add milvus node metadata
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"llamaindex": patch
|
||||
---
|
||||
|
||||
Use Pinecone namespaces for all operations
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"llamaindex": patch
|
||||
---
|
||||
|
||||
Add support for edge runtime by using @llamaindex/edge
|
||||
@@ -6,6 +6,7 @@
|
||||
"target": "esnext"
|
||||
},
|
||||
"module": {
|
||||
"type": "commonjs"
|
||||
"type": "commonjs",
|
||||
"ignoreDynamic": true
|
||||
}
|
||||
}
|
||||
+9
-1
@@ -11,5 +11,13 @@ module.exports = {
|
||||
"max-params": ["error", 4],
|
||||
"prefer-const": "error",
|
||||
},
|
||||
ignorePatterns: ["dist/"],
|
||||
overrides: [
|
||||
{
|
||||
files: ["examples/**/*.ts"],
|
||||
rules: {
|
||||
"turbo/no-undeclared-env-vars": "off",
|
||||
},
|
||||
},
|
||||
],
|
||||
ignorePatterns: ["dist/", "lib/"],
|
||||
};
|
||||
|
||||
@@ -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
|
||||
@@ -0,0 +1,36 @@
|
||||
name: Publish
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@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
|
||||
working-directory: packages/env
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Publish @llamaindex/core
|
||||
run: npx jsr publish --allow-slow-types
|
||||
working-directory: packages/core
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -44,6 +44,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
|
||||
|
||||
|
||||
@@ -44,6 +44,7 @@ test-results/
|
||||
playwright-report/
|
||||
blob-report/
|
||||
playwright/.cache/
|
||||
.tsbuildinfo
|
||||
|
||||
# intellij
|
||||
**/.idea
|
||||
|
||||
+1
-2
@@ -84,8 +84,7 @@ Any changes you make should be reflected in the browser. If you need to regenera
|
||||
To publish a new version of the library, run
|
||||
|
||||
```shell
|
||||
pnpm new-llamaindex
|
||||
pnpm new-create-llama
|
||||
pnpm new-version
|
||||
pnpm release
|
||||
git push # push to the main branch
|
||||
git push --tags
|
||||
|
||||
@@ -121,10 +121,47 @@ const nextConfig = {
|
||||
module.exports = nextConfig;
|
||||
```
|
||||
|
||||
### NextJS with Milvus:
|
||||
|
||||
As proto files are not loaded per default in NextJS, you'll need to add the following to your next.config.js to have it load the proto files.
|
||||
|
||||
```js
|
||||
const path = require("path");
|
||||
const CopyWebpackPlugin = require("copy-webpack-plugin");
|
||||
|
||||
// next.config.js
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
webpack: (config, { isServer }) => {
|
||||
if (isServer) {
|
||||
// Copy the proto files to the server build directory
|
||||
config.plugins.push(
|
||||
new CopyWebpackPlugin({
|
||||
patterns: [
|
||||
{
|
||||
from: path.join(
|
||||
__dirname,
|
||||
"node_modules/@zilliz/milvus2-sdk-node/dist",
|
||||
),
|
||||
to: path.join(__dirname, ".next"),
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
}
|
||||
// Important: return the modified config
|
||||
return config;
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = nextConfig;
|
||||
```
|
||||
|
||||
## Supported LLMs:
|
||||
|
||||
- OpenAI GPT-3.5-turbo and GPT-4
|
||||
- Anthropic Claude Instant and Claude 2
|
||||
- Groq LLMs
|
||||
- Llama2 Chat LLMs (70B, 13B, and 7B parameters)
|
||||
- MistralAI Chat LLMs
|
||||
- Fireworks Chat LLMs
|
||||
|
||||
@@ -1,5 +1,20 @@
|
||||
# docs
|
||||
|
||||
## 0.0.4
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [5116ad8]
|
||||
- @llamaindex/env@0.0.5
|
||||
|
||||
## 0.0.3
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 09bf27a: Add Groq LLM to LlamaIndex
|
||||
- Updated dependencies [cf87f84]
|
||||
- @llamaindex/env@0.0.4
|
||||
|
||||
## 0.0.2
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# Starter Tutorial
|
||||
|
||||
Once you have [installed LlamaIndex.TS using NPM](installation) and set up your OpenAI key, you're ready to start your first app:
|
||||
|
||||
In a new folder:
|
||||
|
||||
```bash npm2yarn
|
||||
npm install typescript
|
||||
npm install @types/node
|
||||
npx tsc --init # if needed
|
||||
```
|
||||
|
||||
Create the file `example.ts`. This code will load some example data, create a document, index it (which creates embeddings using OpenAI), and then creates query engine to answer questions about the data.
|
||||
|
||||
```ts
|
||||
// example.ts
|
||||
import fs from "fs/promises";
|
||||
import { Document, VectorStoreIndex } from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Load essay from abramov.txt in Node
|
||||
const essay = await fs.readFile(
|
||||
"node_modules/llamaindex/examples/abramov.txt",
|
||||
"utf-8",
|
||||
);
|
||||
|
||||
// Create Document object with essay
|
||||
const document = new Document({ text: essay });
|
||||
|
||||
// Split text and create embeddings. Store them in a VectorStoreIndex
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine();
|
||||
const response = await queryEngine.query({
|
||||
query: "What did the author do in college?",
|
||||
});
|
||||
|
||||
// Output response
|
||||
console.log(response.toString());
|
||||
}
|
||||
|
||||
main();
|
||||
```
|
||||
|
||||
Then you can run it using
|
||||
|
||||
```bash
|
||||
npx ts-node example.ts
|
||||
```
|
||||
|
||||
Ready to learn more? Check out our NextJS playground at https://llama-playground.vercel.app/. The source is available at https://github.com/run-llama/ts-playground
|
||||
@@ -0,0 +1,51 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../examples/vectorIndex";
|
||||
import TSConfigSource from "!!raw-loader!../../../../examples/tsconfig.json";
|
||||
|
||||
# Starter Tutorial
|
||||
|
||||
Make sure you have installed LlamaIndex.TS and have an OpenAI key. If you haven't, check out the [installation](installation) guide.
|
||||
|
||||
## From scratch(node.js + TypeScript):
|
||||
|
||||
In a new folder:
|
||||
|
||||
```bash npm2yarn
|
||||
npm init
|
||||
npm install -D typescript @types/node
|
||||
```
|
||||
|
||||
Create the file `example.ts`. This code will load some example data, create a document, index it (which creates embeddings using OpenAI), and then creates query engine to answer questions about the data.
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
|
||||
Create a `tsconfig.json` file in the same folder:
|
||||
|
||||
<CodeBlock language="json">{TSConfigSource}</CodeBlock>
|
||||
|
||||
Now you can run the code with
|
||||
|
||||
```bash
|
||||
npx tsx example.ts
|
||||
```
|
||||
|
||||
Also, you can clone our examples and try them out:
|
||||
|
||||
```bash npm2yarn
|
||||
npx degit run-llama/LlamaIndexTS/examples my-new-project
|
||||
cd my-new-project
|
||||
npm install
|
||||
npx tsx ./vectorIndex.ts
|
||||
```
|
||||
|
||||
## From scratch (Next.js + TypeScript):
|
||||
|
||||
You just need one command to create a new Next.js project:
|
||||
|
||||
```bash npm2yarn
|
||||
npx create-llama@latest
|
||||
```
|
||||
@@ -37,7 +37,7 @@ For more complex applications, our lower-level APIs allow advanced users to cust
|
||||
|
||||
`npm install llamaindex`
|
||||
|
||||
Our documentation includes [Installation Instructions](./getting_started/installation.mdx) and a [Starter Tutorial](./getting_started/starter.md) to build your first application.
|
||||
Our documentation includes [Installation Instructions](./getting_started/installation.mdx) and a [Starter Tutorial](./getting_started/starter.mdx) to build your first application.
|
||||
|
||||
Once you're up and running, [High-Level Concepts](./getting_started/concepts.md) has an overview of LlamaIndex's modular architecture. For more hands-on practical examples, look through our Examples section on the sidebar.
|
||||
|
||||
|
||||
@@ -23,3 +23,15 @@ const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
Per default, `HuggingFaceEmbedding` is using the `Xenova/all-MiniLM-L6-v2` model. You can change the model by passing the `modelType` parameter to the constructor.
|
||||
If you're not using a quantized model, set the `quantized` parameter to `false`.
|
||||
|
||||
For example, to use the not quantized `BAAI/bge-small-en-v1.5` model, you can use the following code:
|
||||
|
||||
```
|
||||
const embedModel = new HuggingFaceEmbedding({
|
||||
modelType: "BAAI/bge-small-en-v1.5",
|
||||
quantized: false,
|
||||
});
|
||||
```
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "Evaluating"
|
||||
position: 3
|
||||
@@ -0,0 +1,32 @@
|
||||
# Evaluating
|
||||
|
||||
## Concept
|
||||
|
||||
Evaluation and benchmarking are crucial concepts in LLM development. To improve the perfomance of an LLM app (RAG, agents) you must have a way to measure it.
|
||||
|
||||
LlamaIndex offers key modules to measure the quality of generated results. We also offer key modules to measure retrieval quality.
|
||||
|
||||
- **Response Evaluation**: Does the response match the retrieved context? Does it also match the query? Does it match the reference answer or guidelines?
|
||||
- **Retrieval Evaluation**: Are the retrieved sources relevant to the query?
|
||||
|
||||
## Response Evaluation
|
||||
|
||||
Evaluation of generated results can be difficult, since unlike traditional machine learning the predicted result is not a single number, and it can be hard to define quantitative metrics for this problem.
|
||||
|
||||
LlamaIndex offers LLM-based evaluation modules to measure the quality of results. This uses a “gold” LLM (e.g. GPT-4) to decide whether the predicted answer is correct in a variety of ways.
|
||||
|
||||
Note that many of these current evaluation modules do not require ground-truth labels. Evaluation can be done with some combination of the query, context, response, and combine these with LLM calls.
|
||||
|
||||
These evaluation modules are in the following forms:
|
||||
|
||||
- **Correctness**: Whether the generated answer matches that of the reference answer given the query (requires labels).
|
||||
|
||||
- **Faithfulness**: Evaluates if the answer is faithful to the retrieved contexts (in other words, whether if there’s hallucination).
|
||||
|
||||
- **Relevancy**: Evaluates if the response from a query engine matches any source nodes.
|
||||
|
||||
## Usage
|
||||
|
||||
- [Correctness Evaluator](./modules/correctness.md)
|
||||
- [Faithfulness Evaluator](./modules/faithfulness.md)
|
||||
- [Relevancy Evaluator](./modules/relevancy.md)
|
||||
@@ -0,0 +1 @@
|
||||
label: "Modules"
|
||||
@@ -0,0 +1,68 @@
|
||||
# Correctness Evaluator
|
||||
|
||||
Correctness evaluates the relevance and correctness of a generated answer against a reference answer.
|
||||
|
||||
This is useful for measuring if the response was correct. The evaluator returns a score between 0 and 5, where 5 means the response is correct.
|
||||
|
||||
## Usage
|
||||
|
||||
Firstly, you need to install the package:
|
||||
|
||||
```bash
|
||||
pnpm i llamaindex
|
||||
```
|
||||
|
||||
Set the OpenAI API key:
|
||||
|
||||
```bash
|
||||
export OPENAI_API_KEY=your-api-key
|
||||
```
|
||||
|
||||
Import the required modules:
|
||||
|
||||
```ts
|
||||
import {
|
||||
CorrectnessEvaluator,
|
||||
OpenAI,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
```
|
||||
|
||||
Let's setup gpt-4 for better results:
|
||||
|
||||
```ts
|
||||
const llm = new OpenAI({
|
||||
model: "gpt-4",
|
||||
});
|
||||
|
||||
const ctx = serviceContextFromDefaults({
|
||||
llm,
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
const query =
|
||||
"Can you explain the theory of relativity proposed by Albert Einstein in detail?";
|
||||
|
||||
const response = ` Certainly! Albert Einstein's theory of relativity consists of two main components: special relativity and general relativity. Special relativity, published in 1905, introduced the concept that the laws of physics are the same for all non-accelerating observers and that the speed of light in a vacuum is a constant, regardless of the motion of the source or observer. It also gave rise to the famous equation E=mc², which relates energy (E) and mass (m).
|
||||
|
||||
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 result = await evaluator.evaluateResponse({
|
||||
query,
|
||||
response,
|
||||
});
|
||||
|
||||
console.log(
|
||||
`the response is ${result.passing ? "correct" : "not correct"} with a score of ${result.score}`,
|
||||
);
|
||||
```
|
||||
|
||||
```bash
|
||||
the response is not correct with a score of 2.5
|
||||
```
|
||||
@@ -0,0 +1,84 @@
|
||||
# Faithfulness Evaluator
|
||||
|
||||
Faithfulness is a measure of whether the generated answer is faithful to the retrieved contexts. In other words, it measures whether there is any hallucination in the generated answer.
|
||||
|
||||
This uses the FaithfulnessEvaluator module to measure if the response from a query engine matches any source nodes.
|
||||
|
||||
This is useful for measuring if the response was hallucinated. The evaluator returns a score between 0 and 1, where 1 means the response is faithful to the retrieved contexts.
|
||||
|
||||
## Usage
|
||||
|
||||
Firstly, you need to install the package:
|
||||
|
||||
```bash
|
||||
pnpm i llamaindex
|
||||
```
|
||||
|
||||
Set the OpenAI API key:
|
||||
|
||||
```bash
|
||||
export OPENAI_API_KEY=your-api-key
|
||||
```
|
||||
|
||||
Import the required modules:
|
||||
|
||||
```ts
|
||||
import {
|
||||
Document,
|
||||
FaithfulnessEvaluator,
|
||||
OpenAI,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
```
|
||||
|
||||
Let's setup gpt-4 for better results:
|
||||
|
||||
```ts
|
||||
const llm = new OpenAI({
|
||||
model: "gpt-4",
|
||||
});
|
||||
|
||||
const ctx = serviceContextFromDefaults({
|
||||
llm,
|
||||
});
|
||||
```
|
||||
|
||||
Now, let's create a vector index and query engine with documents and query engine respectively. Then, we can evaluate the response with the query and response from the query engine.:
|
||||
|
||||
```ts
|
||||
const documents = [
|
||||
new Document({
|
||||
text: `The city came under British control in 1664 and was renamed New York after King Charles II of England granted the lands to his brother, the Duke of York. The city was regained by the Dutch in July 1673 and was renamed New Orange for one year and three months; the city has been continuously named New York since November 1674. New York City was the capital of the United States from 1785 until 1790, and has been the largest U.S. city since 1790. The Statue of Liberty greeted millions of immigrants as they came to the U.S. by ship in the late 19th and early 20th centuries, and is a symbol of the U.S. and its ideals of liberty and peace. In the 21st century, New York City has emerged as a global node of creativity, entrepreneurship, and as a symbol of freedom and cultural diversity. The New York Times has won the most Pulitzer Prizes for journalism and remains the U.S. media's "newspaper of record". In 2019, New York City was voted the greatest city in the world in a survey of over 30,000 p... Pass`,
|
||||
}),
|
||||
];
|
||||
|
||||
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
|
||||
|
||||
const queryEngine = vectorIndex.asQueryEngine();
|
||||
```
|
||||
|
||||
Now, let's evaluate the response:
|
||||
|
||||
```ts
|
||||
const query = "How did New York City get its name?";
|
||||
|
||||
const evaluator = new FaithfulnessEvaluator({
|
||||
serviceContext: ctx,
|
||||
});
|
||||
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
const result = await evaluator.evaluateResponse({
|
||||
query,
|
||||
response,
|
||||
});
|
||||
|
||||
console.log(`the response is ${result.passing ? "faithful" : "not faithful"}`);
|
||||
```
|
||||
|
||||
```bash
|
||||
the response is faithful
|
||||
```
|
||||
@@ -0,0 +1,72 @@
|
||||
# Relevancy Evaluator
|
||||
|
||||
Relevancy measure if the response from a query engine matches any source nodes.
|
||||
|
||||
It is useful for measuring if the response was relevant to the query. The evaluator returns a score between 0 and 1, where 1 means the response is relevant to the query.
|
||||
|
||||
## Usage
|
||||
|
||||
Firstly, you need to install the package:
|
||||
|
||||
```bash
|
||||
pnpm i llamaindex
|
||||
```
|
||||
|
||||
Set the OpenAI API key:
|
||||
|
||||
```bash
|
||||
export OPENAI_API_KEY=your-api-key
|
||||
```
|
||||
|
||||
Import the required modules:
|
||||
|
||||
```ts
|
||||
import {
|
||||
RelevancyEvaluator,
|
||||
OpenAI,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
```
|
||||
|
||||
Let's setup gpt-4 for better results:
|
||||
|
||||
```ts
|
||||
const llm = new OpenAI({
|
||||
model: "gpt-4",
|
||||
});
|
||||
|
||||
const ctx = serviceContextFromDefaults({
|
||||
llm,
|
||||
});
|
||||
```
|
||||
|
||||
Now, let's create a vector index and query engine with documents and query engine respectively. Then, we can evaluate the response with the query and response from the query engine.:
|
||||
|
||||
```ts
|
||||
const documents = [
|
||||
new Document({
|
||||
text: `The city came under British control in 1664 and was renamed New York after King Charles II of England granted the lands to his brother, the Duke of York. The city was regained by the Dutch in July 1673 and was renamed New Orange for one year and three months; the city has been continuously named New York since November 1674. New York City was the capital of the United States from 1785 until 1790, and has been the largest U.S. city since 1790. The Statue of Liberty greeted millions of immigrants as they came to the U.S. by ship in the late 19th and early 20th centuries, and is a symbol of the U.S. and its ideals of liberty and peace. In the 21st century, New York City has emerged as a global node of creativity, entrepreneurship, and as a symbol of freedom and cultural diversity. The New York Times has won the most Pulitzer Prizes for journalism and remains the U.S. media's "newspaper of record". In 2019, New York City was voted the greatest city in the world in a survey of over 30,000 p... Pass`,
|
||||
}),
|
||||
];
|
||||
|
||||
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
|
||||
|
||||
const queryEngine = vectorIndex.asQueryEngine();
|
||||
|
||||
const query = "How did New York City get its name?";
|
||||
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
const result = await evaluator.evaluateResponse({
|
||||
query,
|
||||
response: response,
|
||||
});
|
||||
|
||||
console.log(`the response is ${result.passing ? "relevant" : "not relevant"}`);
|
||||
```
|
||||
|
||||
```bash
|
||||
the response is relevant
|
||||
```
|
||||
@@ -1,6 +1,6 @@
|
||||
# Transformations
|
||||
|
||||
A transformation is something that takes a list of nodes as an input, and returns a list of nodes. Each component that implements the Transformatio class has both a `transform` definition responsible for transforming the nodes
|
||||
A transformation is something that takes a list of nodes as an input, and returns a list of nodes. Each component that implements the Transformation class has both a `transform` definition responsible for transforming the nodes.
|
||||
|
||||
Currently, the following components are Transformation objects:
|
||||
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../../../examples/groq.ts";
|
||||
|
||||
# Groq
|
||||
|
||||
## Usage
|
||||
|
||||
First, create an API key at the [Groq Console](https://console.groq.com/keys). Then save it in your environment:
|
||||
|
||||
```bash
|
||||
export GROQ_API_KEY=<your-api-key>
|
||||
```
|
||||
|
||||
The initialize the Groq module.
|
||||
|
||||
```ts
|
||||
import { Groq, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const groq = new Groq({
|
||||
// If you do not wish to set your API key in the environment, you may
|
||||
// configure your API key when you initialize the Groq class.
|
||||
// apiKey: "<your-api-key>",
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm: groq });
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
|
||||
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
|
||||
|
||||
```ts
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
<CodeBlock language="ts" showLineNumbers>
|
||||
{CodeSource}
|
||||
</CodeBlock>
|
||||
@@ -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({
|
||||
@@ -100,7 +100,7 @@ const response = await queryEngine.query("<user_query>");
|
||||
```ts
|
||||
import { SimilarityPostprocessor } from "llamaindex";
|
||||
|
||||
nodes = await index.asRetriever().retrieve("test query str");
|
||||
nodes = await index.asRetriever().retrieve({ query: "test query str" });
|
||||
|
||||
const processor = new SimilarityPostprocessor({
|
||||
similarityCutoff: 0.7,
|
||||
|
||||
@@ -11,7 +11,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Fetch nodes!
|
||||
const nodesWithScore = await retriever.retrieve("query string");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "query string" });
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// جلب العقد!
|
||||
const nodesWithScore = await retriever.retrieve("سلسلة الاستعلام");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "سلسلة الاستعلام" });
|
||||
```
|
||||
|
||||
## مرجع الواجهة البرمجية (API Reference)
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Извличане на върхове!
|
||||
const nodesWithScore = await retriever.retrieve("query string");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "query string" });
|
||||
```
|
||||
|
||||
## API Reference (API справка)
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const recuperador = vector_index.asRetriever();
|
||||
recuperador.similarityTopK = 3;
|
||||
|
||||
// Obteniu els nodes!
|
||||
const nodesAmbPuntuació = await recuperador.retrieve("cadena de consulta");
|
||||
const nodesAmbPuntuació = await recuperador.retrieve({ query: "cadena de consulta" });
|
||||
```
|
||||
|
||||
## Referència de l'API
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Získání uzlů!
|
||||
const nodesWithScore = await retriever.retrieve("dotazovací řetězec");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "dotazovací řetězec" });
|
||||
```
|
||||
|
||||
## API Reference (Odkazy na rozhraní)
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Hent noder!
|
||||
const nodesWithScore = await retriever.retrieve("forespørgselsstreng");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "forespørgselsstreng" });
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Knoten abrufen!
|
||||
const nodesWithScore = await retriever.retrieve("Abfragezeichenfolge");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "Abfragezeichenfolge" });
|
||||
```
|
||||
|
||||
## API-Referenz
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Ανάκτηση κόμβων!
|
||||
const nodesWithScore = await retriever.retrieve("συμβολοσειρά ερωτήματος");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "συμβολοσειρά ερωτήματος" });
|
||||
```
|
||||
|
||||
## Αναφορά API
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const recuperador = vector_index.asRetriever();
|
||||
recuperador.similarityTopK = 3;
|
||||
|
||||
// ¡Obtener nodos!
|
||||
const nodosConPuntuación = await recuperador.retrieve("cadena de consulta");
|
||||
const nodosConPuntuación = await recuperador.retrieve({ query: "cadena de consulta" });
|
||||
```
|
||||
|
||||
## Referencia de la API
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Too sõlmed!
|
||||
const nodesWithScore = await retriever.retrieve("päringu string");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "päringu string" });
|
||||
```
|
||||
|
||||
## API viide
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// بازیابی گره ها!
|
||||
const nodesWithScore = await retriever.retrieve("رشته پرس و جو");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "رشته پرس و جو" });
|
||||
```
|
||||
|
||||
## مرجع API
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Hae solmut!
|
||||
const nodesWithScore = await retriever.retrieve("kyselymerkkijono");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "kyselymerkkijono" });
|
||||
```
|
||||
|
||||
## API-viite
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Récupérer les nœuds !
|
||||
const nodesWithScore = await retriever.retrieve("chaîne de requête");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "chaîne de requête" });
|
||||
```
|
||||
|
||||
## Référence de l'API
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// אחזור צמתים!
|
||||
const nodesWithScore = await retriever.retrieve("מחרוזת שאילתה");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "מחרוזת שאילתה" });
|
||||
```
|
||||
|
||||
## מדריך לממשק API
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// नोड्स प्राप्त करें!
|
||||
const nodesWithScore = await retriever.retrieve("क्वेरी स्ट्रिंग");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "क्वेरी स्ट्रिंग" });
|
||||
```
|
||||
|
||||
## एपीआई संदर्भ (API Reference)
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const dohvatnik = vector_index.asRetriever();
|
||||
dohvatnik.similarityTopK = 3;
|
||||
|
||||
// Dohvati čvorove!
|
||||
const čvoroviSaRezultatom = await dohvatnik.retrieve("upitni niz");
|
||||
const čvoroviSaRezultatom = await dohvatnik.retrieve({ query: "upitni niz" });
|
||||
```
|
||||
|
||||
## API Referenca
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Node-ok lekérése!
|
||||
const nodesWithScore = await retriever.retrieve("lekérdezési karakterlánc");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "lekérdezési karakterlánc" });
|
||||
```
|
||||
|
||||
## API Referencia
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Mengambil node!
|
||||
const nodesWithScore = await retriever.retrieve("string query");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "string query" });
|
||||
```
|
||||
|
||||
## Referensi API
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Recupera i nodi!
|
||||
const nodesWithScore = await retriever.retrieve("stringa di query");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "stringa di query" });
|
||||
```
|
||||
|
||||
## Riferimento API
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// ノードを取得します!
|
||||
const nodesWithScore = await retriever.retrieve("クエリ文字列");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "クエリ文字列" });
|
||||
```
|
||||
|
||||
## API リファレンス
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// 노드를 가져옵니다!
|
||||
const nodesWithScore = await retriever.retrieve("쿼리 문자열");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "쿼리 문자열" });
|
||||
```
|
||||
|
||||
## API 참조
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const gavėjas = vector_index.asRetriever();
|
||||
gavėjas.similarityTopK = 3;
|
||||
|
||||
// Išgaunami mazgai!
|
||||
const mazgaiSuRezultatu = await gavėjas.retrieve("užklausos eilutė");
|
||||
const mazgaiSuRezultatu = await gavėjas.retrieve({ query: "užklausos eilutė" });
|
||||
```
|
||||
|
||||
## API nuorodos (API Reference)
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Haal knooppunten op!
|
||||
const nodesWithScore = await retriever.retrieve("zoekopdracht");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "zoekopdracht" });
|
||||
```
|
||||
|
||||
## API Referentie
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Hent noder!
|
||||
const nodesWithScore = await retriever.retrieve("spørringsstreng");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "spørringsstreng" });
|
||||
```
|
||||
|
||||
## API-referanse
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Pobierz węzły!
|
||||
const nodesWithScore = await retriever.retrieve("ciąg zapytania");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "ciąg zapytania" });
|
||||
```
|
||||
|
||||
## Dokumentacja interfejsu API
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const recuperador = vector_index.asRetriever();
|
||||
recuperador.similarityTopK = 3;
|
||||
|
||||
// Buscar nós!
|
||||
const nósComPontuação = await recuperador.retrieve("string de consulta");
|
||||
const nósComPontuação = await recuperador.retrieve({ query: "string de consulta" });
|
||||
```
|
||||
|
||||
## Referência da API
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const recuperator = vector_index.asRetriever();
|
||||
recuperator.similarityTopK = 3;
|
||||
|
||||
// Preia nodurile!
|
||||
const noduriCuScor = await recuperator.retrieve("șir de interogare");
|
||||
const noduriCuScor = await recuperator.retrieve({ query: "șir de interogare" });
|
||||
```
|
||||
|
||||
## Referință API
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Получение узлов!
|
||||
const nodesWithScore = await retriever.retrieve("строка запроса");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "строка запроса" });
|
||||
```
|
||||
|
||||
## Справочник по API
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Dohvati čvorove!
|
||||
const nodesWithScore = await retriever.retrieve("upitni niz");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "upitni niz" });
|
||||
```
|
||||
|
||||
## API Referenca
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const pridobitelj = vector_index.asRetriever();
|
||||
pridobitelj.similarityTopK = 3;
|
||||
|
||||
// Pridobivanje vozlišč!
|
||||
const vozliščaZRezultatom = await pridobitelj.retrieve("poizvedbeni niz");
|
||||
const vozliščaZRezultatom = await pridobitelj.retrieve({ query: "poizvedbeni niz" });
|
||||
```
|
||||
|
||||
## API Sklic
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Získajte uzly!
|
||||
const nodesWithScore = await retriever.retrieve("reťazec dotazu");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "reťazec dotazu" });
|
||||
```
|
||||
|
||||
## API Referencia
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Hämta noder!
|
||||
const nodesWithScore = await retriever.retrieve("frågesträng");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "frågesträng" });
|
||||
```
|
||||
|
||||
## API-referens
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// เรียกคืนโหนด!
|
||||
const nodesWithScore = await retriever.retrieve("query string");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "query string" });
|
||||
```
|
||||
|
||||
## API Reference (การอ้างอิง API)
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Düğümleri getir!
|
||||
const nodesWithScore = await retriever.retrieve("sorgu dizesi");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "sorgu dizesi" });
|
||||
```
|
||||
|
||||
## API Referansı
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Отримати вузли!
|
||||
const nodesWithScore = await retriever.retrieve("рядок запиту");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "рядок запиту" });
|
||||
```
|
||||
|
||||
## Довідник API
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// Lấy các node!
|
||||
const nodesWithScore = await retriever.retrieve("chuỗi truy vấn");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "chuỗi truy vấn" });
|
||||
```
|
||||
|
||||
## Tài liệu tham khảo API
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// 获取节点!
|
||||
const nodesWithScore = await retriever.retrieve("查询字符串");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "查询字符串" });
|
||||
```
|
||||
|
||||
## API 参考
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ const retriever = vector_index.asRetriever();
|
||||
retriever.similarityTopK = 3;
|
||||
|
||||
// 提取節點!
|
||||
const nodesWithScore = await retriever.retrieve("查詢字串");
|
||||
const nodesWithScore = await retriever.retrieve({ query: "查詢字串" });
|
||||
```
|
||||
|
||||
## API 參考
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "docs",
|
||||
"version": "0.0.2",
|
||||
"version": "0.0.4",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"docusaurus": "docusaurus",
|
||||
@@ -16,6 +16,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@docusaurus/core": "^3.1.1",
|
||||
"@llamaindex/env": "workspace:*",
|
||||
"@docusaurus/remark-plugin-npm2yarn": "^3.1.1",
|
||||
"@mdx-js/react": "^3.0.0",
|
||||
"clsx": "^2.1.0",
|
||||
|
||||
@@ -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
|
||||
@@ -128,7 +128,6 @@ async function main() {
|
||||
VectorStoreIndex,
|
||||
{
|
||||
serviceContext,
|
||||
storageContext,
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
async function main() {
|
||||
// Load the documents
|
||||
const documents = await new SimpleDirectoryReader().loadData({
|
||||
directoryPath: "node_modules/llamaindex/examples/",
|
||||
directoryPath: "node_modules/llamaindex/examples",
|
||||
});
|
||||
|
||||
// Create a vector index from the documents
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { FunctionTool, OpenAIAgent } from "llamaindex";
|
||||
|
||||
// Define a function to sum two numbers
|
||||
function sumNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
// Define a function to divide two numbers
|
||||
function divideNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a / b;
|
||||
}
|
||||
|
||||
// Define the parameters of the sum function as a JSON schema
|
||||
const sumJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The first number",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The second number",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
const divideJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The dividend a to divide",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The divisor b to divide by",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
async function main() {
|
||||
// Create a function tool from the sum function
|
||||
const functionTool = new FunctionTool(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, {
|
||||
name: "divideNumbers",
|
||||
description: "Use this function to divide two numbers",
|
||||
parameters: divideJSON,
|
||||
});
|
||||
|
||||
// Create an OpenAIAgent with the function tools
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [functionTool, functionTool2],
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
// Create a task to sum and divide numbers
|
||||
const task = agent.createTask("How much is 5 + 5? then divide by 2");
|
||||
|
||||
let count = 0;
|
||||
|
||||
while (true) {
|
||||
const stepOutput = await agent.runStep(task.taskId);
|
||||
|
||||
console.log(`Runnning step ${count++}`);
|
||||
console.log(`======== OUTPUT ==========`);
|
||||
if (stepOutput.output.response) {
|
||||
console.log(stepOutput.output.response);
|
||||
} else {
|
||||
console.log(stepOutput.output.sources);
|
||||
}
|
||||
console.log(`==========================`);
|
||||
|
||||
if (stepOutput.isLast) {
|
||||
const finalResponse = await agent.finalizeResponse(
|
||||
task.taskId,
|
||||
stepOutput,
|
||||
);
|
||||
console.log({ finalResponse });
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main().then(() => {
|
||||
console.log("Done");
|
||||
});
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
async function main() {
|
||||
// Load the documents
|
||||
const documents = await new SimpleDirectoryReader().loadData({
|
||||
directoryPath: "node_modules/llamaindex/examples/",
|
||||
directoryPath: "node_modules/llamaindex/examples",
|
||||
});
|
||||
|
||||
// Create a vector index from the documents
|
||||
@@ -32,13 +32,31 @@ async function main() {
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
// Chat with the agent
|
||||
const response = await agent.chat({
|
||||
message: "What was his salary?",
|
||||
});
|
||||
const task = agent.createTask("What was his salary?");
|
||||
|
||||
// Print the response
|
||||
console.log(String(response));
|
||||
let count = 0;
|
||||
|
||||
while (true) {
|
||||
const stepOutput = await agent.runStep(task.taskId);
|
||||
|
||||
console.log(`Runnning step ${count++}`);
|
||||
console.log(`======== OUTPUT ==========`);
|
||||
if (stepOutput.output.response) {
|
||||
console.log(stepOutput.output.response);
|
||||
} else {
|
||||
console.log(stepOutput.output.sources);
|
||||
}
|
||||
console.log(`==========================`);
|
||||
|
||||
if (stepOutput.isLast) {
|
||||
const finalResponse = await agent.finalizeResponse(
|
||||
task.taskId,
|
||||
stepOutput,
|
||||
);
|
||||
console.log({ finalResponse });
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main().then(() => {
|
||||
@@ -0,0 +1,90 @@
|
||||
import { FunctionTool, ReActAgent } from "llamaindex";
|
||||
|
||||
// Define a function to sum two numbers
|
||||
function sumNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
// Define a function to divide two numbers
|
||||
function divideNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a / b;
|
||||
}
|
||||
|
||||
// Define the parameters of the sum function as a JSON schema
|
||||
const sumJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The first number",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The second number",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
const divideJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The dividend",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The divisor",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
async function main() {
|
||||
// Create a function tool from the sum function
|
||||
const functionTool = new FunctionTool(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, {
|
||||
name: "divideNumbers",
|
||||
description: "Use this function to divide two numbers",
|
||||
parameters: divideJSON,
|
||||
});
|
||||
|
||||
// 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");
|
||||
|
||||
let count = 0;
|
||||
|
||||
while (true) {
|
||||
const stepOutput = await agent.runStep(task.taskId);
|
||||
|
||||
console.log(`Runnning step ${count++}`);
|
||||
console.log(`======== OUTPUT ==========`);
|
||||
console.log(stepOutput.output);
|
||||
console.log(`==========================`);
|
||||
|
||||
if (stepOutput.isLast) {
|
||||
const finalResponse = await agent.finalizeResponse(
|
||||
task.taskId,
|
||||
stepOutput,
|
||||
);
|
||||
console.log({ finalResponse });
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main().then(() => {
|
||||
console.log("Done");
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
import { FunctionTool, OpenAIAgent } from "llamaindex";
|
||||
|
||||
// Define a function to sum two numbers
|
||||
function sumNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
// Define a function to divide two numbers
|
||||
function divideNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a / b;
|
||||
}
|
||||
|
||||
// Define the parameters of the sum function as a JSON schema
|
||||
const sumJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The first number",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The second number",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
const divideJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The dividend",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The divisor",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
async function main() {
|
||||
// Create a function tool from the sum function
|
||||
const functionTool = new FunctionTool(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, {
|
||||
name: "divideNumbers",
|
||||
description: "Use this function to divide two numbers",
|
||||
parameters: divideJSON,
|
||||
});
|
||||
|
||||
// Create an OpenAIAgent with the function tools
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [functionTool, functionTool2],
|
||||
verbose: false,
|
||||
});
|
||||
|
||||
const stream = await agent.chat({
|
||||
message: "Divide 16 by 2 then add 20",
|
||||
stream: true,
|
||||
});
|
||||
|
||||
for await (const chunk of stream.response) {
|
||||
process.stdout.write(chunk.response);
|
||||
}
|
||||
}
|
||||
|
||||
main().then(() => {
|
||||
console.log("\nDone");
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import { Anthropic } from "llamaindex";
|
||||
(async () => {
|
||||
const anthropic = new Anthropic({
|
||||
apiKey: process.env.ANTHROPIC_API_KEY,
|
||||
model: "claude-3-opus",
|
||||
});
|
||||
const result = await anthropic.chat({
|
||||
messages: [
|
||||
@@ -0,0 +1,34 @@
|
||||
import { Anthropic, SimpleChatEngine, SimpleChatHistory } from "llamaindex";
|
||||
import { stdin as input, stdout as output } from "node:process";
|
||||
import readline from "node:readline/promises";
|
||||
|
||||
(async () => {
|
||||
const llm = new Anthropic({
|
||||
apiKey: process.env.ANTHROPIC_API_KEY,
|
||||
model: "claude-3-opus",
|
||||
});
|
||||
// chatHistory will store all the messages in the conversation
|
||||
const chatHistory = new SimpleChatHistory({
|
||||
messages: [
|
||||
{
|
||||
content: "You want to talk in rhymes.",
|
||||
role: "system",
|
||||
},
|
||||
],
|
||||
});
|
||||
const chatEngine = new SimpleChatEngine({
|
||||
llm,
|
||||
chatHistory,
|
||||
});
|
||||
const rl = readline.createInterface({ input, output });
|
||||
|
||||
while (true) {
|
||||
const query = await rl.question("User: ");
|
||||
process.stdout.write("Assistant: ");
|
||||
const stream = await chatEngine.chat({ message: query, stream: true });
|
||||
for await (const chunk of stream) {
|
||||
process.stdout.write(chunk.response);
|
||||
}
|
||||
process.stdout.write("\n");
|
||||
}
|
||||
})();
|
||||
@@ -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);
|
||||
})();
|
||||
@@ -0,0 +1,23 @@
|
||||
import { Anthropic } from "llamaindex";
|
||||
|
||||
(async () => {
|
||||
const anthropic = new Anthropic({
|
||||
apiKey: process.env.ANTHROPIC_API_KEY,
|
||||
model: "claude-instant-1.2",
|
||||
});
|
||||
const stream = 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",
|
||||
},
|
||||
],
|
||||
stream: true,
|
||||
});
|
||||
|
||||
for await (const chunk of stream) {
|
||||
process.stdout.write(chunk.delta);
|
||||
}
|
||||
})();
|
||||
@@ -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`
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import {
|
||||
CorrectnessEvaluator,
|
||||
OpenAI,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
const llm = new OpenAI({
|
||||
model: "gpt-4",
|
||||
});
|
||||
|
||||
const ctx = serviceContextFromDefaults({
|
||||
llm,
|
||||
});
|
||||
|
||||
const evaluator = new CorrectnessEvaluator({
|
||||
serviceContext: ctx,
|
||||
});
|
||||
|
||||
const query =
|
||||
"Can you explain the theory of relativity proposed by Albert Einstein in detail?";
|
||||
|
||||
const response = `
|
||||
Certainly! Albert Einstein's theory of relativity consists of two main components: special relativity and general relativity. Special relativity, published in 1905, introduced the concept that the laws of physics are the same for all non-accelerating observers and that the speed of light in a vacuum is a constant, regardless of the motion of the source or observer. It also gave rise to the famous equation E=mc², which relates energy (E) and mass (m).
|
||||
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 result = await evaluator.evaluate({
|
||||
query: query,
|
||||
response: response,
|
||||
});
|
||||
|
||||
console.log(result);
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,46 @@
|
||||
import {
|
||||
Document,
|
||||
FaithfulnessEvaluator,
|
||||
OpenAI,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
const llm = new OpenAI({
|
||||
model: "gpt-4",
|
||||
});
|
||||
|
||||
const ctx = serviceContextFromDefaults({
|
||||
llm,
|
||||
});
|
||||
|
||||
const evaluator = new FaithfulnessEvaluator({
|
||||
serviceContext: ctx,
|
||||
});
|
||||
|
||||
const documents = [
|
||||
new Document({
|
||||
text: `The city came under British control in 1664 and was renamed New York after King Charles II of England granted the lands to his brother, the Duke of York. The city was regained by the Dutch in July 1673 and was renamed New Orange for one year and three months; the city has been continuously named New York since November 1674. New York City was the capital of the United States from 1785 until 1790, and has been the largest U.S. city since 1790. The Statue of Liberty greeted millions of immigrants as they came to the U.S. by ship in the late 19th and early 20th centuries, and is a symbol of the U.S. and its ideals of liberty and peace. In the 21st century, New York City has emerged as a global node of creativity, entrepreneurship, and as a symbol of freedom and cultural diversity. The New York Times has won the most Pulitzer Prizes for journalism and remains the U.S. media's "newspaper of record". In 2019, New York City was voted the greatest city in the world in a survey of over 30,000 p... Pass`,
|
||||
}),
|
||||
];
|
||||
|
||||
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
|
||||
|
||||
const queryEngine = vectorIndex.asQueryEngine();
|
||||
|
||||
const query = "How did New York City get its name?";
|
||||
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
const result = await evaluator.evaluateResponse({
|
||||
query,
|
||||
response,
|
||||
});
|
||||
|
||||
console.log(result);
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,46 @@
|
||||
import {
|
||||
Document,
|
||||
OpenAI,
|
||||
RelevancyEvaluator,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
const llm = new OpenAI({
|
||||
model: "gpt-4",
|
||||
});
|
||||
|
||||
const ctx = serviceContextFromDefaults({
|
||||
llm,
|
||||
});
|
||||
|
||||
const evaluator = new RelevancyEvaluator({
|
||||
serviceContext: ctx,
|
||||
});
|
||||
|
||||
const documents = [
|
||||
new Document({
|
||||
text: `The city came under British control in 1664 and was renamed New York after King Charles II of England granted the lands to his brother, the Duke of York. The city was regained by the Dutch in July 1673 and was renamed New Orange for one year and three months; the city has been continuously named New York since November 1674. New York City was the capital of the United States from 1785 until 1790, and has been the largest U.S. city since 1790. The Statue of Liberty greeted millions of immigrants as they came to the U.S. by ship in the late 19th and early 20th centuries, and is a symbol of the U.S. and its ideals of liberty and peace. In the 21st century, New York City has emerged as a global node of creativity, entrepreneurship, and as a symbol of freedom and cultural diversity. The New York Times has won the most Pulitzer Prizes for journalism and remains the U.S. media's "newspaper of record". In 2019, New York City was voted the greatest city in the world in a survey of over 30,000 p... Pass`,
|
||||
}),
|
||||
];
|
||||
|
||||
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
|
||||
|
||||
const queryEngine = vectorIndex.asQueryEngine();
|
||||
|
||||
const query = "How did New York City get its name?";
|
||||
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
const result = await evaluator.evaluateResponse({
|
||||
query,
|
||||
response: response,
|
||||
});
|
||||
|
||||
console.log(result);
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -1,13 +1,19 @@
|
||||
import { Document, OpenAI, SimpleNodeParser, TitleExtractor } from "llamaindex";
|
||||
|
||||
(async () => {
|
||||
const openaiLLM = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0 });
|
||||
import essay from "../essay";
|
||||
|
||||
const nodeParser = new SimpleNodeParser();
|
||||
(async () => {
|
||||
const openaiLLM = new OpenAI({ model: "gpt-3.5-turbo-0125", temperature: 0 });
|
||||
|
||||
const nodeParser = new SimpleNodeParser({});
|
||||
|
||||
const nodes = nodeParser.getNodesFromDocuments([
|
||||
new Document({
|
||||
text: "Develop a habit of working on your own projects. Don't let work mean something other people tell you to do. If you do manage to do great work one day, it will probably be on a project of your own. It may be within some bigger project, but you'll be driving your part of it.",
|
||||
text: essay,
|
||||
}),
|
||||
new Document({
|
||||
text: `Certainly! Albert Einstein's theory of relativity consists of two main components: special relativity and general relativity.
|
||||
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.`,
|
||||
}),
|
||||
]);
|
||||
|
||||
@@ -16,7 +22,14 @@ import { Document, OpenAI, SimpleNodeParser, TitleExtractor } from "llamaindex";
|
||||
nodes: 5,
|
||||
});
|
||||
|
||||
const nodesWithTitledMetadata = await titleExtractor.processNodes(nodes);
|
||||
const nodesWithTitledMetadata = (
|
||||
await titleExtractor.processNodes(nodes)
|
||||
).map((node) => {
|
||||
return {
|
||||
title: node.metadata.documentTitle,
|
||||
id: node.id_,
|
||||
};
|
||||
});
|
||||
|
||||
process.stdout.write(JSON.stringify(nodesWithTitledMetadata, null, 2));
|
||||
})();
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import fs from "node:fs/promises";
|
||||
|
||||
import {
|
||||
Document,
|
||||
Groq,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
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,
|
||||
});
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
// Create a query engine
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
// Query
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
// Log the response
|
||||
console.log(response.response);
|
||||
}
|
||||
|
||||
await main();
|
||||
@@ -0,0 +1,26 @@
|
||||
import {
|
||||
Document,
|
||||
SimpleNodeParser,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
export const STORAGE_DIR = "./data";
|
||||
|
||||
(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,
|
||||
});
|
||||
})();
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,30 @@
|
||||
import {
|
||||
MilvusVectorStore,
|
||||
serviceContextFromDefaults,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
|
||||
const collectionName = "movie_reviews";
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
const milvus = new MilvusVectorStore({ collection: collectionName });
|
||||
|
||||
const ctx = serviceContextFromDefaults();
|
||||
const index = await VectorStoreIndex.fromVectorStore(milvus, ctx);
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -27,9 +27,9 @@ async function main() {
|
||||
// retrieve documents using the index
|
||||
const index = await createIndex();
|
||||
const retriever = index.asRetriever({ similarityTopK: 3 });
|
||||
const results = await retriever.retrieve(
|
||||
"what are Vincent van Gogh's famous paintings",
|
||||
);
|
||||
const results = await retriever.retrieve({
|
||||
query: "what are Vincent van Gogh's famous paintings",
|
||||
});
|
||||
for (const result of results) {
|
||||
const node = result.node;
|
||||
if (!node) {
|
||||
|
||||
+7
-1
@@ -1,4 +1,4 @@
|
||||
import { OpenAI } from "llamaindex";
|
||||
import { OpenAI, OpenAIEmbedding } from "llamaindex";
|
||||
|
||||
(async () => {
|
||||
const llm = new OpenAI({ model: "gpt-4-1106-preview", temperature: 0.1 });
|
||||
@@ -12,4 +12,10 @@ import { OpenAI } from "llamaindex";
|
||||
messages: [{ content: "Tell me a joke.", role: "user" }],
|
||||
});
|
||||
console.log(response2.message.content);
|
||||
|
||||
// embeddings
|
||||
const embedModel = new OpenAIEmbedding();
|
||||
const texts = ["hello", "world"];
|
||||
const embeddings = await embedModel.getTextEmbeddingsBatch(texts);
|
||||
console.log(`\nWe have ${embeddings.length} embeddings`);
|
||||
})();
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
{
|
||||
"name": "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",
|
||||
"@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"
|
||||
"mongodb": "^6.2.0",
|
||||
"pathe": "^1.1.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^18.19.10",
|
||||
|
||||
@@ -7,8 +7,9 @@ There are two scripts available here: load-docs.ts and query.ts
|
||||
You'll need a Pinecone account, project, and index. Pinecone does not allow automatic creation of indexes on the free plan,
|
||||
so this vector store does not check and create the index (unlike, e.g., the PGVectorStore)
|
||||
|
||||
Set the **PINECONE_API_KEY** and **PINECONE_ENVIRONMENT** environment variables to match your specific values. You will likely also need to set **PINECONE_INDEX_NAME**, unless your
|
||||
index is the default value "llama".
|
||||
Set the **PINECONE_API_KEY** and **PINECONE_ENVIRONMENT** environment variables to match your specific values.
|
||||
You will likely also need to set **PINECONE_INDEX_NAME**, unless your index is the default value "llama".
|
||||
By default, all operations take place inside the default namespace '', but you can set **PINECONE_NAMESPACE** to a different value if you need to.
|
||||
|
||||
You'll also need a value for OPENAI_API_KEY in your environment.
|
||||
|
||||
|
||||
@@ -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,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
storageContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
// 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,
|
||||
serviceContext: serviceContextFromDefaults({
|
||||
callbackManager: new CallbackManager({
|
||||
onRetrieve: (data) => {
|
||||
console.log(
|
||||
"The retrieved nodes are:",
|
||||
data.nodes.map((node) => node.node.getContent(MetadataMode.NONE)),
|
||||
);
|
||||
},
|
||||
}),
|
||||
}),
|
||||
});
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
@@ -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>[]> {
|
||||
|
||||
+6
-4
@@ -11,10 +11,12 @@
|
||||
"prepare": "husky",
|
||||
"test": "turbo run test",
|
||||
"type-check": "tsc -b --diagnostics",
|
||||
"release": "pnpm run build:release && changeset publish",
|
||||
"new-llamaindex": "pnpm run build:release && changeset version --ignore create-llama",
|
||||
"new-create-llama": "pnpm run build:release && changeset version --ignore llamaindex",
|
||||
"new-snapshots": "pnpm run build:release && changeset version --snapshot"
|
||||
"release": "pnpm run check-minor-version && pnpm run build:release && changeset publish",
|
||||
"release-snapshot": "pnpm run check-minor-version && pnpm run build:release && changeset publish --tag snapshot",
|
||||
"check-minor-version": "node ./scripts/check-minor-version",
|
||||
"update-version": "node ./scripts/update-version",
|
||||
"new-version": "pnpm run build:release && changeset version && pnpm run check-minor-version && pnpm run update-version",
|
||||
"new-snapshot": "pnpm run build:release && changeset version --snapshot && pnpm run update-version"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@changesets/cli": "^2.27.1",
|
||||
|
||||
@@ -1 +1,3 @@
|
||||
.turbo
|
||||
README.md
|
||||
LICENSE
|
||||
@@ -1,5 +1,81 @@
|
||||
# llamaindex
|
||||
|
||||
## 0.2.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- bf583a7: Use parameter object for retrieve function of Retriever (to align usage with query function of QueryEngine)
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- d2e8d0c: add support for Milvus vector store
|
||||
- aefc326: feat: experimental package + json query engine
|
||||
- 484a710: - Add missing exports:
|
||||
- `IndexStructType`,
|
||||
- `IndexDict`,
|
||||
- `jsonToIndexStruct`,
|
||||
- `IndexList`,
|
||||
- `IndexStruct`
|
||||
- Fix `IndexDict.toJson()` method
|
||||
- d766bd0: Add streaming to agents
|
||||
- dd95927: add Claude Haiku support and update anthropic SDK
|
||||
|
||||
## 0.1.21
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 552a61a: Add quantized parameter to HuggingFaceEmbedding
|
||||
- d824876: Add support for Claude 3
|
||||
|
||||
## 0.1.20
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 64683a5: fix: prefix messages always true
|
||||
- 698cd9c: fix: step wise agent + examples
|
||||
- 7257751: fixed removeRefDocNode and persist store on delete
|
||||
- 5116ad8: fix: compatibility issue with Deno
|
||||
- Updated dependencies [5116ad8]
|
||||
- @llamaindex/env@0.0.5
|
||||
|
||||
## 0.1.19
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 026d068: feat: enhance pinecone usage
|
||||
|
||||
## 0.1.18
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 90027a7: Add splitLongSentences option to SimpleNodeParser
|
||||
- c57bd11: feat: update and refactor title extractor
|
||||
|
||||
## 0.1.17
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- c8396c5: feat: add base evaluator and correctness evaluator
|
||||
- c8396c5: feat: add base evaluator and correctness evaluator
|
||||
- cf87f84: fix: type backward compatibility
|
||||
- 09bf27a: Add Groq LLM to LlamaIndex
|
||||
- Updated dependencies [cf87f84]
|
||||
- @llamaindex/env@0.0.4
|
||||
|
||||
## 0.1.16
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- e8e21a0: build: set files in package.json
|
||||
- Updated dependencies [e8e21a0]
|
||||
- @llamaindex/env@0.0.3
|
||||
|
||||
## 0.1.15
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 3a6e287: build: improve tree-shake & reduce unused package import
|
||||
|
||||
## 0.1.14
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"name": "@llamaindex/core",
|
||||
"version": "0.1.21",
|
||||
"exports": "./src/index.ts",
|
||||
"imports": {
|
||||
"@llamaindex/env": "jsr:@llamaindex/env@0.0.5"
|
||||
}
|
||||
}
|
||||
+18
-16
@@ -1,25 +1,32 @@
|
||||
{
|
||||
"name": "llamaindex",
|
||||
"version": "0.1.14",
|
||||
"version": "0.2.0",
|
||||
"expectedMinorVersion": "2",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "^0.13.0",
|
||||
"@anthropic-ai/sdk": "^0.18.0",
|
||||
"@aws-crypto/sha256-js": "^5.2.0",
|
||||
"@datastax/astra-db-ts": "^0.1.4",
|
||||
"@llamaindex/cloud": "^0.0.1",
|
||||
"@grpc/grpc-js": "^1.10.2",
|
||||
"@llamaindex/cloud": "0.0.4",
|
||||
"@llamaindex/env": "workspace:*",
|
||||
"@mistralai/mistralai": "^0.0.10",
|
||||
"@notionhq/client": "^2.2.14",
|
||||
"@pinecone-database/pinecone": "^2.0.1",
|
||||
"@qdrant/js-client-rest": "^1.7.0",
|
||||
"@types/lodash": "^4.14.202",
|
||||
"@types/node": "^18.19.14",
|
||||
"@types/papaparse": "^5.3.14",
|
||||
"@types/pg": "^8.11.0",
|
||||
"@xenova/transformers": "^2.15.0",
|
||||
"@zilliz/milvus2-sdk-node": "^2.3.5",
|
||||
"assemblyai": "^4.2.2",
|
||||
"chromadb": "~1.7.3",
|
||||
"cohere-ai": "^7.7.5",
|
||||
"file-type": "^18.7.0",
|
||||
"js-tiktoken": "^1.0.10",
|
||||
"lodash": "^4.17.21",
|
||||
"magic-bytes.js": "^1.10.0",
|
||||
"mammoth": "^1.6.0",
|
||||
"md-utils-ts": "^2.0.0",
|
||||
"mongodb": "^6.3.0",
|
||||
@@ -39,10 +46,6 @@
|
||||
"devDependencies": {
|
||||
"@swc/cli": "^0.3.9",
|
||||
"@swc/core": "^1.4.2",
|
||||
"@types/lodash": "^4.14.202",
|
||||
"@types/node": "^18.19.14",
|
||||
"@types/papaparse": "^5.3.14",
|
||||
"@types/pg": "^8.11.0",
|
||||
"concurrently": "^8.2.2",
|
||||
"glob": "^10.3.10",
|
||||
"madge": "^6.1.0",
|
||||
@@ -59,10 +62,6 @@
|
||||
"types": "./dist/type/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"edge-light": {
|
||||
"types": "./dist/type/index.d.ts",
|
||||
"default": "./dist/index.edge-light.js"
|
||||
},
|
||||
"require": {
|
||||
"types": "./dist/type/index.d.ts",
|
||||
"default": "./dist/cjs/index.js"
|
||||
@@ -80,7 +79,9 @@
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"**"
|
||||
"dist",
|
||||
"CHANGELOG.md",
|
||||
"examples"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -90,10 +91,11 @@
|
||||
"scripts": {
|
||||
"lint": "eslint .",
|
||||
"build": "rm -rf ./dist && pnpm run build:esm && pnpm run build:cjs && pnpm run build:type",
|
||||
"build:esm": "swc src -d dist --strip-leading-paths --config-file .swcrc",
|
||||
"build:cjs": "swc src -d dist/cjs --strip-leading-paths --config-file .cjs.swcrc",
|
||||
"build:esm": "swc src -d dist --strip-leading-paths --config-file ../../.swcrc",
|
||||
"build:cjs": "swc src -d dist/cjs --strip-leading-paths --config-file ../../.cjs.swcrc",
|
||||
"build:type": "tsc -p tsconfig.json",
|
||||
"postbuild": "node -e \"require('fs').writeFileSync('./dist/cjs/package.json', JSON.stringify({ type: 'commonjs' }))\"",
|
||||
"copy": "cp -r ../../README.md ../../LICENSE .",
|
||||
"postbuild": "pnpm run copy && node -e \"require('fs').writeFileSync('./dist/cjs/package.json', JSON.stringify({ type: 'commonjs' }))\"",
|
||||
"circular-check": "madge -c ./src/index.ts",
|
||||
"dev": "concurrently \"pnpm run build:esm --watch\" \"pnpm run build:cjs --watch\" \"pnpm run build:type --watch\""
|
||||
}
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
import { OpenAI } from "./llm/LLM.js";
|
||||
import { ChatMessage, LLM, MessageType } from "./llm/types.js";
|
||||
import {
|
||||
defaultSummaryPrompt,
|
||||
messagesToHistoryStr,
|
||||
SummaryPrompt,
|
||||
} from "./Prompt.js";
|
||||
import type { ChatMessage, LLM, MessageType } from "./llm/types.js";
|
||||
import type { SummaryPrompt } from "./Prompt.js";
|
||||
import { defaultSummaryPrompt, messagesToHistoryStr } from "./Prompt.js";
|
||||
|
||||
/**
|
||||
* A ChatHistory is used to keep the state of back and forth chat messages
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user