mirror of
https://github.com/run-llama/LlamaIndexTS.git
synced 2026-07-09 03:23:09 -04:00
Compare commits
38 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 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 |
@@ -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",
|
||||
|
||||
+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",
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
{
|
||||
"jsc": {
|
||||
"parser": {
|
||||
"syntax": "typescript"
|
||||
"syntax": "typescript",
|
||||
"decorators": true
|
||||
},
|
||||
"target": "esnext"
|
||||
"target": "esnext",
|
||||
"transform": {
|
||||
"decoratorVersion": "2022-03"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+17
-2
@@ -79,12 +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 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,46 +129,59 @@ const nextConfig = {
|
||||
module.exports = nextConfig;
|
||||
```
|
||||
|
||||
### NextJS with Milvus:
|
||||
### Using the Edge runtime
|
||||
|
||||
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.
|
||||
We publish a dedicated package (`@llamaindex/edge` instead of `llamaindex`) for using the Edge runtime. To use it, first install the package:
|
||||
|
||||
```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;
|
||||
```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`, and `llm-end` 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>
|
||||
+10
-10
@@ -15,9 +15,9 @@
|
||||
"typecheck": "tsc"
|
||||
},
|
||||
"dependencies": {
|
||||
"@docusaurus/core": "^3.1.1",
|
||||
"@llamaindex/env": "workspace:*",
|
||||
"@docusaurus/remark-plugin-npm2yarn": "^3.1.1",
|
||||
"@docusaurus/core": "^3.2.0",
|
||||
"@docusaurus/remark-plugin-npm2yarn": "^3.2.0",
|
||||
"@llamaindex/examples": "workspace:*",
|
||||
"@mdx-js/react": "^3.0.0",
|
||||
"clsx": "^2.1.0",
|
||||
"postcss": "^8.4.33",
|
||||
@@ -27,16 +27,16 @@
|
||||
"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",
|
||||
"@docusaurus/module-type-aliases": "3.2.0",
|
||||
"@docusaurus/preset-classic": "^3.2.0",
|
||||
"@docusaurus/theme-classic": "^3.2.0",
|
||||
"@docusaurus/types": "^3.2.0",
|
||||
"@tsconfig/docusaurus": "^2.0.3",
|
||||
"@types/node": "^18.19.10",
|
||||
"docusaurus-plugin-typedoc": "^0.22.0",
|
||||
"typedoc": "^0.25.7",
|
||||
"typedoc": "^0.25.12",
|
||||
"typedoc-plugin-markdown": "^3.17.1",
|
||||
"typescript": "^5.3.3"
|
||||
"typescript": "^5.4.3"
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
|
||||
@@ -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,7 +85,7 @@ async function main() {
|
||||
|
||||
const agent = new OpenAIAgent({
|
||||
tools: queryEngineTools,
|
||||
llm,
|
||||
llm: new OpenAI({ model: "gpt-4" }),
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
@@ -126,14 +121,11 @@ async function main() {
|
||||
allTools,
|
||||
toolMapping,
|
||||
VectorStoreIndex,
|
||||
{
|
||||
serviceContext,
|
||||
},
|
||||
);
|
||||
|
||||
const topAgent = new OpenAIAgent({
|
||||
toolRetriever: await objectIndex.asRetriever({}),
|
||||
llm,
|
||||
llm: new OpenAI({ model: "gpt-4" }),
|
||||
verbose: true,
|
||||
prefixMessages: [
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
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 {
|
||||
@@ -56,8 +56,14 @@ 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,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { OpenAIAgent, WikipediaTool } from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
const wikipediaTool = new WikipediaTool();
|
||||
|
||||
// Create an OpenAIAgent with the function tools
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [wikipediaTool],
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
// Chat with the agent
|
||||
const response = await agent.chat({
|
||||
message: "Where is Ho Chi Minh City?",
|
||||
});
|
||||
|
||||
// Print the response
|
||||
console.log(response);
|
||||
}
|
||||
|
||||
main().then(() => {
|
||||
console.log("Done");
|
||||
});
|
||||
@@ -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 });
|
||||
|
||||
|
||||
@@ -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 });
|
||||
|
||||
@@ -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,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?";
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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({
|
||||
|
||||
+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();
|
||||
|
||||
+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]);
|
||||
})();
|
||||
|
||||
@@ -1,101 +0,0 @@
|
||||
title,reviewid,creationdate,criticname,originalscore,reviewstate,reviewtext
|
||||
Beavers,1145982,2003-05-23,Ivan M. Lincoln,3.5/4,fresh,"Timed to be just long enough for most youngsters' brief attention spans -- and it's packed with plenty of interesting activity, both on land and under the water."
|
||||
Blood Mask,1636744,2007-06-02,The Foywonder,1/5,rotten,"It doesn't matter if a movie costs 300 million or only 300 dollars; good is good and bad is bad, and Bloodmask: The Possession of Nicole Lameroux is just plain bad."
|
||||
City Hunter: Shinjuku Private Eyes,2590987,2019-05-28,Reuben Baron,,fresh,"The choreography is so precise and lifelike at points one might wonder whether the movie was rotoscoped, but no live-action reference footage was used. The quality is due to the skill of the animators and Kodama's love for professional wrestling."
|
||||
City Hunter: Shinjuku Private Eyes,2558908,2019-02-14,Matt Schley,2.5/5,rotten,The film's out-of-touch attempts at humor may find them hunting for the reason the franchise was so popular in the first place.
|
||||
Dangerous Men,2504681,2018-08-29,Pat Padua,,fresh,Its clumsy determination is endearing and sometimes wildly entertaining
|
||||
Dangerous Men,2299284,2015-12-13,Eric Melin,4/5,fresh,"With every new minute, there's another head-scratching choice that's bound to elicit some amazing out-loud responses, so this feels like a true party flick."
|
||||
Dangerous Men,2295858,2015-11-22,Matt Donato,7/10,fresh,"Emotionless reaction shots, zero characterization, guns that have absolutely no special effects when blasted - Dangerous Men is rare winning dish from a one star restaurant."
|
||||
Dangerous Men,2295338,2015-11-19,Peter Keough,0.5/4,rotten,"Conceivably, it could serve as a primer for students on how not to make a movie, and perhaps as a deconstruction of filmic conventions for the more theoretical minded."
|
||||
Dangerous Men,2294641,2015-11-16,Jason Wilson,3/10,rotten,"If you're not a fan of garbage cinema, even for the fun of it, Dangerous Men is best to be avoided."
|
||||
Dangerous Men,2294129,2015-11-12,Soren Andersen,0/4,rotten,"""Dangerous Men,"" the picture's production notes inform, took 26 years to reach the big screen. After having seen it, I wonder: What was the rush?"
|
||||
Dangerous Men,2293902,2015-11-12,Maitland McDonagh,,rotten,Will entertain some viewers and infuriate others with its clunky mix of feminist fury and awkward action sequences.
|
||||
Dangerous Men,2293900,2015-11-12,Marjorie Baumgarten,1.5/5,rotten,"This is a bad movie, but one that awakens your senses every so often with flashes of originality and abundant self-belief."
|
||||
Dangerous Men,2293815,2015-11-12,Katie Rife,B+,fresh,"Ridiculous, artless, and wildly entertaining, Dangerous Men is more than the sum of its fascinatingly misguided parts, although it will take a special sort of moviegoer to truly appreciate (or endure, depending on your perspective) its charms."
|
||||
Dangerous Men,2293605,2015-11-11,Amy Nicholson,C,fresh,To sit through it feels like honoring the dreamers of the world who at least get shit done. Is it terrible? Of course. Is there belly-dancing? Duh.
|
||||
Small Town Wisconsin,102711819,2022-07-22,Peter Gray,,fresh,Small Town Wisconsin could hit some home truths for viewers, and though being faced with the truth isn’t always pleasant, it feels necessary in growing towards a happier fruition.
|
||||
Small Town Wisconsin,102711545,2022-07-22,Tim Grierson,,fresh,"This low-key drama has lovely interludes and some nicely understated performances, although director Niels Mueller doesn’t glean too many new insights from Jason Naczek’s familiar story..."
|
||||
Small Town Wisconsin,102700937,2022-06-16,Sumner Forbes,8.5/10,fresh,"Small Town Wisconsin is a success in almost every regard, and if you can see over the legions of cheeseheads in the rows ahead of you, it shouldn’t be missed."
|
||||
Small Town Wisconsin,102699897,2022-06-14,Tara McNamara,3/5,fresh,Just like Wayne, Small Town Wisconsin has flaws, but the poignancy of the story will stick with you for a long time.
|
||||
Small Town Wisconsin,102698744,2022-06-10,Rob Thomas,3/4,fresh,It’s a movie with its heart in the right place, and does both small town and big city Wisconsin proud.
|
||||
Small Town Wisconsin,102698639,2022-06-10,Todd Jorgenson,,rotten,Despite some intriguing character dynamics and performances that generate sympathy for this fractured family, the film stumbles when it veers into melodrama without the narrative dexterity to tackle its weightier ambitions.
|
||||
Small Town Wisconsin,102698482,2022-06-10,Jackie K. Cooper,7/10,fresh,This is the kind of movie that draws you so deeply into its story you are reluctant to let it end.
|
||||
Small Town Wisconsin,102698164,2022-06-09,Glenn Kenny,,fresh,"Mueller’s direction is patient and sensitive, the cast is accomplished and committed, and the picture’s comedic aspects sometimes earn a chuckle."
|
||||
Small Town Wisconsin,102697854,2022-06-08,Brian Orndorf,B+,fresh,Naczek isn't interested in making a soap opera with this examination of fallibility, going somewhere much more authentic when exploring character aches and pains.
|
||||
Small Town Wisconsin,102695788,2022-06-02,Eddie Harrison,4/5,fresh,…a warm-hearted story of everyday life that’s easy to recommend for those who like films about people rather than portals and vortexes…
|
||||
Small Town Wisconsin,102695250,2022-05-31,Laura Clifford,C,rotten,Debuting screenwriter Jason Naczek has concocted a manchild redemption story using metaphors as heavy as a hammer and a fairy godmother who makes everything alright with a seeming flip of the switch.
|
||||
Small Town Wisconsin,2733251,2020-10-12,Jared Mobarak,B,fresh,Small Town Wisconsin is always proving itself to be more than its familiar premise thanks to Naczek's ability to infuse a lot more drama into the mix than one custody battle.
|
||||
Tejano,2564925,2019-03-07,Joe Friar,3/4,fresh,The story of a South Texas ranch hand who gets mixed up with a Mexican cartel moves with pulse-pounding velocity and features top performances from a talented cast of actors with Texas roots.
|
||||
Tejano,2557738,2019-02-12,Cary Darling,4/5,fresh,"An entertaining blast of Texas noir that nods toward the work of the Coen brothers, Quentin Tarantino and fellow Austinite Greg Kwedar's 2016 low-budget thriller ""Transpecos"" as well as ""Breaking Bad."""
|
||||
Tejano,2547231,2019-01-10,Danielle White,3/5,fresh,The story itself slithers with twists and turns and unexpected betrayals. It's almost ridiculous how many characters die in this film.
|
||||
Tejano,2530119,2018-11-08,Chris Salce,9/10,fresh,"Tejano is one of those films that can be described as a hidden gem as it sneaks under the radar and will have you talking, telling your friends about it, and wanting to watch it again."
|
||||
Death of a Salesman,2770637,2021-02-23,Michael Dougan,,fresh,"Miller has taken a small, intimate tale and expanded it into a treatise on larger themes, primarily the abuse of the American Dream."
|
||||
Death of a Salesman,1950734,2011-01-02,Randy White,5/5,fresh,A classic American tragedy.
|
||||
Death of a Salesman,1422415,2005-08-04,Jules Brenner,4/5,fresh,
|
||||
Death of a Salesman,1409415,2005-07-05,Emanuel Levy,3/5,fresh,
|
||||
Death of a Salesman,839546,2003-02-06,Frederic and Mary Ann Brussat,,fresh,"Death of a Salesman, directed by Volker Schlondorff, draws out the multiple meanings of this Pulitzer Prize-winning play by Arthur Miller about change, family and fatherhood, work and love."
|
||||
Death of a Salesman,788410,2002-09-29,Dan Lybarger,4/5,fresh,"Schlndorff's artificial settings and some amazing performances help keep this from looking like a typical ""filmed play."""
|
||||
Death of a Salesman,751951,2002-08-08,Cory Cheney,4/5,fresh,
|
||||
Death of a Salesman,743794,2002-07-26,Bob Grimm,5/5,fresh,
|
||||
Death of a Salesman,743291,2002-07-26,Scott Weinberg,5/5,fresh,They MAKE you watch it in English class for a good reason!
|
||||
Sahara,1137710,2003-05-13,Dragan Antulov,5/10,fresh,
|
||||
The Debt,2628192,2019-09-20,Diego Batlle,,fresh,A Bresson-esque movie that is always enigmatic. [Full Review in Spanish]
|
||||
The Debt,2627988,2019-09-20,Gaspar Zimerman,,fresh,The story [Director Gustavo Fontán] tells is an excuse to give way to the exploration of feelings and sensations that avoid verbality. [Full review in Spanish]
|
||||
Peppermint Candy,2725008,2020-09-16,A.S. Hamrah,,fresh,"South Korean political history of the previous twenty years, Peppermint Candy is not tempered by its hysterical edge, which adds unpredictable violence to its vignettes of romantic, domestic, and business failure."
|
||||
Peppermint Candy,2541271,2018-12-16,Panos Kotzathanasis,,fresh,"Lee Chang-dong presents a melodrama that stands apart from the plethora of similar productions due to its intense political element, because it doesn't lose its seriousness at any point and because it doesn't become hyperbolic in his effort to draw tears"
|
||||
Peppermint Candy,1883708,2010-05-11,Anton Bitel,,fresh,"This is Korea's millennial elegy, filtering its search for times past through a confection no less bittersweet than Proust's madeleine."
|
||||
Peppermint Candy,1706014,2008-01-29,Beth Accomando,9/10,fresh,The film offers a heartbreaking drama told in reverse chronology and spanning twenty years in both the life of the main character and the political history of Korea.
|
||||
Peppermint Candy,1231988,2003-12-22,Greg Muskewitz,2/5,rotten,
|
||||
Peppermint Candy,1187104,2003-08-14,Joshua Tanzer,4/4,fresh,"It's a story about the original sin of a nation as well as one character. There has rarely been a better film made, ever"
|
||||
Prison Girls,2475348,2018-05-03,Roger Ebert,,rotten,Prison Girls didn't have a lot of prison sets because it was a big-budget exploitation movie. Maybe.
|
||||
Gimme the Power,2575688,2019-04-09,Afroxander,,fresh,"Rubio's film shows ambition where none is required, making Gimme the Power a lot like Molotov's music: politically engaged without having to take itself too seriously."
|
||||
Paa,2673089,2020-02-27,Nikhat Kazmi,3.5/5,fresh,"The film, which peters off into vague sub-plots about slum redevelopment and unwarranted media-bashing in the first half, suddenly picks up and scales new heights in the second half."
|
||||
Paa,2578129,2019-04-17,Shubhra Gupta,2/5,rotten,"Disappointingly, Paa is not as out-of-the-box as it could have been."
|
||||
Paa,2429810,2017-10-24,Anil Sinanan,3/5,rotten,Will Auro survive to know his Pa and reunite his parents? Forget about the disease: this is a vanity vehicle designed to showcase the Big B's versatility.
|
||||
Paa,1860476,2009-12-14,Frank Lovece,,rotten,This would-be tearjerker without the musical numbers of typical Bollywood fare is for die-hard Amitabh Bachchan fans only.
|
||||
Paa,1860473,2009-12-14,David Chute,,fresh,"The film owes much of its interest to the alertness and sincerity of the younger Bachchan and the luminous Vidya Balan as the anguished parents, and to the soft wash of the tasteful playback songs supplied by Ilaiyaraaja."
|
||||
Paa,1858964,2009-12-05,Avi Offer,5.85/10,rotten,"Well-acted, funny and occasionally witty with terrific make-up design. However, it's often convoluted, awkwardly paced and too uneven as a whole."
|
||||
Paa,1858853,2009-12-04,Frank Lovece,,fresh,"A would-be tearjerker without the singing-dancing musical numbers of typical Bollywood fare seen in the U.S., the lackluster Paa is for die-hard Amitabh Bachchan fans only%u2014of which there is no small number."
|
||||
Paa,1858816,2009-12-04,Rachel Saltz,3/5,fresh,Odd and sometimes oddly affecting.
|
||||
Alraune (A Daughter of Destiny) (Mandrake) (Unholy Love),2835964,2021-10-30,Erich Hellmund-Waldow,,fresh,"The acting is not only artistic, it is also as realistic as can be possible in such a film."
|
||||
Alraune (A Daughter of Destiny) (Mandrake) (Unholy Love),2357086,2016-10-17,C. Hooper Trask,,fresh,"Aimed straight for the gooseflesh, it strikes directly into the centre of the target."
|
||||
Toorbos,2760593,2021-01-29,Neil Young,,fresh,Built around a luminous and intriguing central performance by dancer-actor Elani Dekker.
|
||||
Toorbos,2752827,2020-12-21,Guy Lodge,,fresh,"A satisfying marriage of folky period romance and environmental parable from the misty, mossy depths of South Africa's Knysna forest region..."
|
||||
Connors' War,1555113,2006-11-09,David Nusair,1.5/4,rotten,"...although Criss does show some potential as a performer, his efforts to step into the shoes of a blind character are laughable."
|
||||
Connors' War,1539106,2006-09-19,Scott Weinberg,2/5,rotten,"Standard cable fodder all the way, with only a few solid action scenes and maybe one colorful performance in the whole thing."
|
||||
Born to Kill,2710947,2020-08-05,Mike Massie,10/10,fresh,"One of the most acerbic of all films noir, boasting essentially no redeemable characters (or a wealth of deliciously evil villains) while also being utterly enthralling."
|
||||
Born to Kill,2340106,2016-07-15,David Nusair,3/4,fresh,...a fairly typical film-noir premise that's employed to watchable yet entirely unmemorable effect by Robert Wise...
|
||||
Born to Kill,1507021,2006-05-16,Nick Schager,B,fresh,Competent if slightly too tame for a supposedly sleazy story.
|
||||
Born to Kill,1501617,2006-05-01,Fernando F. Croce,,fresh,"The usually meek Robert Wise trades his chameleonic tastefulness for full-on, jazzy misanthropy in this nasty melodrama."
|
||||
Born to Kill,1433953,2005-09-09,Jeffrey M. Anderson,3/4,fresh,"Hard to watch, but effective and alluring nonetheless."
|
||||
Born to Kill,1123980,2003-04-02,Dennis Schwartz,C,rotten,A revolting B film noir...
|
||||
The Soong Sisters,1402087,2005-06-15,Emanuel Levy,3/5,fresh,
|
||||
La Sapienza,102772380,2023-01-24,Vadim Rizov,,fresh,"Sapienza is a pretty lovely film. Symmetricities are everywhere, starting with that opening architectural showreel, which deliberately avoids perfect symmetricity..."
|
||||
La Sapienza,2767839,2021-02-14,Dustin Chang,,fresh,Their sincere expression of these thoughts rings true and melts away its artificiality in its presentation soon enough. This is the beauty of La Sapienza and Green films in general.
|
||||
La Sapienza,2598336,2019-06-18,C.J. Prince,,fresh,"It's a nice entry point into a peculiar cinematic universe, and those willing to open themselves to it will find a lot to enjoy."
|
||||
La Sapienza,2503963,2018-08-28,Charles Mudede,,fresh,"If architecture aspires to the condition of music, the acting in La Sapienza aspires to the condition of architecture. You will love the ending of this very original and elegant and arty work."
|
||||
La Sapienza,2314368,2016-03-12,Forrest Cardamenis,B,fresh,This startling architectural juxtaposition feels like a wake-up call.
|
||||
La Sapienza,2275677,2015-08-03,Nicole Armour,,fresh,"While Green's film is dense with historical fact and theory, it's not averse to plumbing life's mysteries. Suffused with warmth, it expresses a potent admiration for human striving and accomplishment."
|
||||
La Sapienza,2273804,2015-07-23,Norman Wilner,2/5,rotten,"The uncomplicated narrative resists stylization; Green's presentation turns everyone into mannequins, rendering their emotions theoretical. That may well be his point, but it didn't work for me."
|
||||
La Sapienza,2269287,2015-06-26,Sam Lubell,,fresh,"On the surface, writer-director Eugne Green's film ""La Sapienza"" is slow, strange and awkward - but stick with it and it may win you over."
|
||||
La Sapienza,2265997,2015-06-05,Rob Garratt,4/5,fresh,"Layered with reels of swirling shots of Rome's most beautiful buildings -- all crucially shot from the ground upwards, staring at the heavens-- La Sapienza is visually stunning."
|
||||
La Sapienza,2265990,2015-06-05,Boyd van Hoeij,,fresh,"The Sapience juxtaposes insights on how people are emotionally connected with ruminations on the buildings and spaces through which they move, in which they live and, in Alexandre's case, which they also create."
|
||||
La Sapienza,2265989,2015-06-05,Robert Horton,3/4,fresh,"If you can groove into this non-realistic mode, the film casts a spell."
|
||||
La Sapienza,2265790,2015-06-04,Tom Keogh,3.5/4,fresh,A beautiful space for people and light.
|
||||
La Sapienza,2255621,2015-04-09,Wesley Morris,,rotten,This kind of formalism needs to do more than walk through classical wonders. It should want to create cinema that can stand near or beside them. This movie defensively consecrates what's already there. You don't need a film to do that.
|
||||
La Sapienza,2255195,2015-04-08,Scott Foundas,,fresh,"An exquisite rumination on life, love and art that tickles the heart and mind in equal measure."
|
||||
La Sapienza,2252858,2015-03-23,Richard Brody,,fresh,"Green's richly textured, painterly images fuse with the story to evoke the essence of humane urbanity and the relationships that it fosters, whether educational, familial, or erotic."
|
||||
La Sapienza,2252553,2015-03-20,Ignatiy Vishnevetsky,B+,fresh,"Green doesn't so much use his characters as mouthpieces as emotionally invest them in art, turning opinions into feelings."
|
||||
La Sapienza,2252541,2015-03-20,Godfrey Cheshire,4/4,fresh,"""La Sapienza"" strikes this reviewer as easily the most astonishing and important movie to emerge from France in quite some time."
|
||||
La Sapienza,2252452,2015-03-19,A.O. Scott,,fresh,The movie is an unapologetically rarefied undertaking and at the same time a gracious and inviting film.
|
||||
La Sapienza,2252301,2015-03-19,David Noh,,rotten,"Pretentious, stuffy and slow. There's some beautiful scenery here but oh, what you must put up with to earn it!"
|
||||
La Sapienza,2252028,2015-03-18,Noel Murray,3/5,fresh,"While La Sapienza is unsatisfying as drama, it's frequently beautiful just as a tour through architecturally significant Italian buildings."
|
||||
La Sapienza,2251985,2015-03-17,David Ehrlich,3/5,fresh,La Sapienza alternately feels like a self-reflexive love story or a haunted history lesson -- its best scenes play like both.
|
||||
La Sapienza,2251926,2015-03-17,Zachary Wigon,,fresh,A picture that balances heart and mind with nuance.
|
||||
La Sapienza,2251650,2015-03-14,Harvey S. Karten,B+,fresh,"As in ""Who's Afraid of Virginia Woolf,"" both the younger couple and their older mentors are changed from a relationship."
|
||||
La Sapienza,2250991,2015-03-12,Ben Sachs,,fresh,"This recalls Manoel de Oliveira and Eric Rohmer in its poker-faced style, deliberately archaic storytelling, and magisterial epiphanies."
|
||||
La Sapienza,2225361,2014-09-28,Donald J. Levit,,fresh,"Although a love-fiction crossed with documentary lecture and superb Raphael O'Byrne cinematography, 'La Sapienza' is as close as celluloid can approach to architecture."
|
||||
La Sapienza,2222032,2014-09-10,Carson Lund,3/4,fresh,"Eugne Green's mannered direction doesn't work for every situation it's homogenously applied to, but at its most effective it inspires an enhanced sensitivity to the import of every gesture, visual or verbal."
|
||||
Uncle Tom,2713732,2020-08-14,Megan Basham,,fresh,Uncle Tom suffers from an overreliance on pundits. Its most compelling insights come from people who've never been quoted in a Twitter or Facebook battle.
|
||||
Uncle Tom,2706229,2020-07-19,Matthew Pejkovic,4/5,fresh,"An incredibly relevant and insightful documentary that delves into the past, present, and future of the black American conservative movement."
|
||||
Uncle Tom,2698525,2020-06-24,Dante James,7/10,fresh,"It's a little misleading in some areas, especially if you know the players involved in this doc, but there are a lot of interesting historical facts about the breakdown of the Black family and how the whole welfare system targeted the Black community."
|
||||
|
+1
-40
@@ -1,4 +1,3 @@
|
||||
import { DataType } from "@zilliz/milvus2-sdk-node";
|
||||
import {
|
||||
MilvusVectorStore,
|
||||
PapaCSVReader,
|
||||
@@ -13,45 +12,7 @@ async function main() {
|
||||
const reader = new PapaCSVReader(false);
|
||||
const docs = await reader.loadData("./data/movie_reviews.csv");
|
||||
|
||||
const vectorStore = new MilvusVectorStore({
|
||||
contentKey: "content",
|
||||
});
|
||||
|
||||
const milvus = vectorStore.client();
|
||||
|
||||
await milvus.createCollection({
|
||||
collection_name: collectionName,
|
||||
fields: [
|
||||
{
|
||||
name: "id",
|
||||
data_type: DataType.VarChar,
|
||||
is_primary_key: true,
|
||||
max_length: 200,
|
||||
},
|
||||
{
|
||||
name: "embedding",
|
||||
data_type: DataType.FloatVector,
|
||||
dim: 1536,
|
||||
},
|
||||
{
|
||||
name: "content",
|
||||
data_type: DataType.VarChar,
|
||||
max_length: 9000,
|
||||
},
|
||||
{
|
||||
name: "metadata",
|
||||
data_type: DataType.JSON,
|
||||
},
|
||||
],
|
||||
});
|
||||
await milvus.createIndex({
|
||||
collection_name: collectionName,
|
||||
field_name: "embedding",
|
||||
index_type: "HNSW",
|
||||
params: { efConstruction: 10, M: 4 },
|
||||
metric_type: "L2",
|
||||
});
|
||||
await vectorStore.connect(collectionName);
|
||||
const vectorStore = new MilvusVectorStore({ collection: collectionName });
|
||||
|
||||
const ctx = await storageContextFromDefaults({ vectorStore });
|
||||
const index = await VectorStoreIndex.fromDocuments(docs, {
|
||||
|
||||
@@ -1,20 +1,12 @@
|
||||
import {
|
||||
MilvusVectorStore,
|
||||
serviceContextFromDefaults,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
import { MilvusVectorStore, VectorStoreIndex } from "llamaindex";
|
||||
|
||||
const collectionName = "movie_reviews";
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
const milvus = new MilvusVectorStore({
|
||||
contentKey: "content",
|
||||
});
|
||||
await milvus.connect(collectionName);
|
||||
const milvus = new MilvusVectorStore({ collection: collectionName });
|
||||
|
||||
const ctx = serviceContextFromDefaults();
|
||||
const index = await VectorStoreIndex.fromVectorStore(milvus, ctx);
|
||||
const index = await VectorStoreIndex.fromVectorStore(milvus);
|
||||
|
||||
const retriever = await index.asRetriever({ similarityTopK: 20 });
|
||||
|
||||
|
||||
+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,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 });
|
||||
|
||||
@@ -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-vision-preview", 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,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"name": "examples",
|
||||
"name": "@llamaindex/examples",
|
||||
"private": true,
|
||||
"version": "0.0.4",
|
||||
"dependencies": {
|
||||
@@ -11,14 +11,15 @@
|
||||
"chromadb": "^1.8.1",
|
||||
"commander": "^11.1.0",
|
||||
"dotenv": "^16.4.1",
|
||||
"llamaindex": "workspace:*",
|
||||
"js-tiktoken": "^1.0.10",
|
||||
"llamaindex": "latest",
|
||||
"mongodb": "^6.2.0",
|
||||
"pathe": "^1.1.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^18.19.10",
|
||||
"ts-node": "^10.9.2",
|
||||
"typescript": "^5.3.3"
|
||||
"typescript": "^5.4.3"
|
||||
},
|
||||
"scripts": {
|
||||
"lint": "eslint ."
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -1,7 +1,5 @@
|
||||
# llamaindex-loader-example
|
||||
|
||||
## null
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [d2e8d0c]
|
||||
|
||||
@@ -12,12 +12,11 @@
|
||||
"start:llamaparse": "node --loader ts-node/esm ./src/llamaparse.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"llamaindex": "workspace:*"
|
||||
"llamaindex": "latest"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.11.14",
|
||||
"ts-node": "^10.9.2",
|
||||
"typescript": "^5.3.3"
|
||||
},
|
||||
"version": null
|
||||
"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>[]> {
|
||||
|
||||
@@ -1,17 +1,15 @@
|
||||
import { FireworksEmbedding, FireworksLLM, VectorStoreIndex } from "llamaindex";
|
||||
import { PDFReader } from "llamaindex/readers/PDFReader";
|
||||
|
||||
import { serviceContextFromDefaults } from "llamaindex";
|
||||
import { Settings } from "llamaindex";
|
||||
|
||||
const embedModel = new FireworksEmbedding({
|
||||
model: "nomic-ai/nomic-embed-text-v1.5",
|
||||
});
|
||||
|
||||
const llm = new FireworksLLM({
|
||||
Settings.llm = new FireworksLLM({
|
||||
model: "accounts/fireworks/models/mixtral-8x7b-instruct",
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm, embedModel });
|
||||
Settings.embedModel = new FireworksEmbedding({
|
||||
model: "nomic-ai/nomic-embed-text-v1.5",
|
||||
});
|
||||
|
||||
async function main() {
|
||||
// Load PDF
|
||||
@@ -19,9 +17,7 @@ async function main() {
|
||||
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 the index
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
@@ -1,30 +1,26 @@
|
||||
import { OpenAI, OpenAIEmbedding, VectorStoreIndex } from "llamaindex";
|
||||
import { PDFReader } from "llamaindex/readers/PDFReader";
|
||||
|
||||
import { serviceContextFromDefaults } from "llamaindex";
|
||||
import { Settings } from "llamaindex";
|
||||
|
||||
const embedModel = new OpenAIEmbedding({
|
||||
// Update llm and embedModel
|
||||
|
||||
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 });
|
||||
Settings.embedModel = new OpenAIEmbedding({
|
||||
model: "nomic-ai/nomic-embed-text-v1.5",
|
||||
});
|
||||
|
||||
const llm = new OpenAI({
|
||||
model: "accounts/fireworks/models/mixtral-8x7b-instruct",
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm, embedModel });
|
||||
|
||||
async function main() {
|
||||
// Load PDF
|
||||
const reader = new PDFReader();
|
||||
const documents = await reader.loadData("../data/brk-2022.pdf");
|
||||
|
||||
// Split text and create embeddings. Store them in a VectorStoreIndex
|
||||
const index = await VectorStoreIndex.fromDocuments(documents, {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments(documents);
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const response = await queryEngine.query({
|
||||
query: "What mistakes did Warren E. Buffett make?",
|
||||
});
|
||||
|
||||
@@ -1,16 +1,14 @@
|
||||
import { execSync } from "child_process";
|
||||
import {
|
||||
PDFReader,
|
||||
serviceContextFromDefaults,
|
||||
storageContextFromDefaults,
|
||||
VectorStoreIndex,
|
||||
storageContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
const STORAGE_DIR = "./cache";
|
||||
|
||||
async function main() {
|
||||
// write the index to disk
|
||||
const serviceContext = serviceContextFromDefaults({});
|
||||
const storageContext = await storageContextFromDefaults({
|
||||
persistDir: `${STORAGE_DIR}`,
|
||||
});
|
||||
@@ -18,7 +16,6 @@ async function main() {
|
||||
const documents = await reader.loadData("data/brk-2022.pdf");
|
||||
await VectorStoreIndex.fromDocuments(documents, {
|
||||
storageContext,
|
||||
serviceContext,
|
||||
});
|
||||
console.log("wrote index to disk - now trying to read it");
|
||||
// make index dir read only
|
||||
@@ -29,7 +26,6 @@ async function main() {
|
||||
});
|
||||
await VectorStoreIndex.init({
|
||||
storageContext: readOnlyStorageContext,
|
||||
serviceContext,
|
||||
});
|
||||
console.log("read only index successfully opened");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { encodingForModel } from "js-tiktoken";
|
||||
import { OpenAI } from "llamaindex";
|
||||
import { Settings } from "llamaindex/Settings";
|
||||
|
||||
const encoding = encodingForModel("gpt-4-0125-preview");
|
||||
|
||||
const llm = new OpenAI({
|
||||
model: "gpt-4-0125-preview",
|
||||
});
|
||||
|
||||
let tokenCount = 0;
|
||||
|
||||
Settings.callbackManager.on("llm-start", (event) => {
|
||||
const { messages } = event.detail.payload;
|
||||
tokenCount += messages.reduce((count, message) => {
|
||||
return count + encoding.encode(message.content).length;
|
||||
}, 0);
|
||||
console.log("Token count:", tokenCount);
|
||||
// https://openai.com/pricing
|
||||
// $10.00 / 1M tokens
|
||||
console.log(`Price: $${(tokenCount / 1_000_000) * 10}`);
|
||||
});
|
||||
Settings.callbackManager.on("llm-end", (event) => {
|
||||
const { response } = event.detail.payload;
|
||||
tokenCount += encoding.encode(response.message.content).length;
|
||||
console.log("Token count:", tokenCount);
|
||||
// https://openai.com/pricing
|
||||
// $30.00 / 1M tokens
|
||||
console.log(`Price: $${(tokenCount / 1_000_000) * 30}`);
|
||||
});
|
||||
|
||||
const question = "Hello, how are you?";
|
||||
console.log("Question:", question);
|
||||
llm
|
||||
.chat({
|
||||
stream: true,
|
||||
messages: [
|
||||
{
|
||||
content: question,
|
||||
role: "user",
|
||||
},
|
||||
],
|
||||
})
|
||||
.then(async (iter) => {
|
||||
console.log("Response:");
|
||||
for await (const chunk of iter) {
|
||||
process.stdout.write(chunk.delta);
|
||||
}
|
||||
});
|
||||
@@ -2,22 +2,18 @@ import {
|
||||
CohereRerank,
|
||||
Document,
|
||||
OpenAI,
|
||||
Settings,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
import essay from "../essay";
|
||||
|
||||
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 });
|
||||
|
||||
async function main() {
|
||||
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 index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
|
||||
@@ -1,38 +1,31 @@
|
||||
import {
|
||||
OpenAI,
|
||||
RouterQueryEngine,
|
||||
Settings,
|
||||
SimpleDirectoryReader,
|
||||
SimpleNodeParser,
|
||||
SummaryIndex,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
// Update llm
|
||||
Settings.llm = new OpenAI();
|
||||
|
||||
// Update node parser
|
||||
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 vectorIndex = await VectorStoreIndex.fromDocuments(documents);
|
||||
|
||||
const summaryIndex = await SummaryIndex.fromDocuments(documents, {
|
||||
serviceContext,
|
||||
});
|
||||
const summaryIndex = await SummaryIndex.fromDocuments(documents);
|
||||
|
||||
// Create query engines
|
||||
const vectorQueryEngine = vectorIndex.asQueryEngine();
|
||||
@@ -50,7 +43,6 @@ async function main() {
|
||||
description: "Useful for retrieving specific context from Abramov",
|
||||
},
|
||||
],
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
// Query the router query engine
|
||||
|
||||
+11
-12
@@ -3,27 +3,25 @@ import {
|
||||
HuggingFaceEmbedding,
|
||||
MetadataReplacementPostProcessor,
|
||||
SentenceWindowNodeParser,
|
||||
Settings,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
import essay from "./essay";
|
||||
|
||||
// Update node parser and embed model
|
||||
Settings.nodeParser = new SentenceWindowNodeParser({
|
||||
windowSize: 3,
|
||||
windowMetadataKey: "window",
|
||||
originalTextMetadataKey: "original_text",
|
||||
});
|
||||
Settings.embedModel = new HuggingFaceEmbedding();
|
||||
|
||||
async function main() {
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// create service context with sentence window parser
|
||||
// and local embedding from HuggingFace
|
||||
const nodeParser = new SentenceWindowNodeParser({
|
||||
windowSize: 3,
|
||||
windowMetadataKey: "window",
|
||||
originalTextMetadataKey: "original_text",
|
||||
});
|
||||
const embedModel = new HuggingFaceEmbedding();
|
||||
const serviceContext = serviceContextFromDefaults({ nodeParser, embedModel });
|
||||
|
||||
// Split text and create embeddings. Store them in a VectorStoreIndex
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
logProgress: true,
|
||||
});
|
||||
|
||||
@@ -31,6 +29,7 @@ async function main() {
|
||||
const queryEngine = index.asQueryEngine({
|
||||
nodePostprocessors: [new MetadataReplacementPostProcessor("window")],
|
||||
});
|
||||
|
||||
const response = await queryEngine.query({
|
||||
query: "What did the author do in college?",
|
||||
});
|
||||
|
||||
@@ -1,22 +1,21 @@
|
||||
import {
|
||||
Document,
|
||||
Settings,
|
||||
SimpleNodeParser,
|
||||
SummaryIndex,
|
||||
SummaryRetrieverMode,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
import essay from "./essay";
|
||||
|
||||
// Update node parser
|
||||
Settings.nodeParser = new SimpleNodeParser({
|
||||
chunkSize: 40,
|
||||
});
|
||||
|
||||
async function main() {
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
nodeParser: new SimpleNodeParser({
|
||||
chunkSize: 40,
|
||||
}),
|
||||
});
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
const index = await SummaryIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await SummaryIndex.fromDocuments([document]);
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever: index.asRetriever({ mode: SummaryRetrieverMode.LLM }),
|
||||
});
|
||||
|
||||
@@ -2,12 +2,20 @@ import fs from "node:fs/promises";
|
||||
|
||||
import {
|
||||
Document,
|
||||
Settings,
|
||||
TogetherEmbedding,
|
||||
TogetherLLM,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
// Update llm to use TogetherAI
|
||||
Settings.llm = new TogetherLLM({
|
||||
model: "mistralai/Mixtral-8x7B-Instruct-v0.1",
|
||||
});
|
||||
|
||||
// Update embedModel
|
||||
Settings.embedModel = new TogetherEmbedding();
|
||||
|
||||
async function main() {
|
||||
const apiKey = process.env.TOGETHER_API_KEY;
|
||||
if (!apiKey) {
|
||||
@@ -18,14 +26,7 @@ async function main() {
|
||||
|
||||
const document = new Document({ text: essay, id_: path });
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
llm: new TogetherLLM({ model: "mistralai/Mixtral-8x7B-Instruct-v0.1" }),
|
||||
embedModel: new TogetherEmbedding(),
|
||||
});
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
|
||||
@@ -2,14 +2,17 @@ import fs from "node:fs/promises";
|
||||
|
||||
import {
|
||||
Anthropic,
|
||||
anthropicTextQaPrompt,
|
||||
CompactAndRefine,
|
||||
Document,
|
||||
ResponseSynthesizer,
|
||||
serviceContextFromDefaults,
|
||||
Settings,
|
||||
VectorStoreIndex,
|
||||
anthropicTextQaPrompt,
|
||||
} from "llamaindex";
|
||||
|
||||
// Update llm to use Anthropic
|
||||
Settings.llm = new Anthropic();
|
||||
|
||||
async function main() {
|
||||
// Load essay from abramov.txt in Node
|
||||
const path = "node_modules/llamaindex/examples/abramov.txt";
|
||||
@@ -20,18 +23,11 @@ async function main() {
|
||||
const document = new Document({ text: essay, id_: path });
|
||||
|
||||
// Split text and create embeddings. Store them in a VectorStoreIndex
|
||||
const serviceContext = serviceContextFromDefaults({ llm: new Anthropic() });
|
||||
|
||||
const responseSynthesizer = new ResponseSynthesizer({
|
||||
responseBuilder: new CompactAndRefine(
|
||||
serviceContext,
|
||||
anthropicTextQaPrompt,
|
||||
),
|
||||
responseBuilder: new CompactAndRefine(undefined, anthropicTextQaPrompt),
|
||||
});
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine({ responseSynthesizer });
|
||||
|
||||
@@ -2,23 +2,21 @@ import {
|
||||
Document,
|
||||
OpenAI,
|
||||
RetrieverQueryEngine,
|
||||
serviceContextFromDefaults,
|
||||
Settings,
|
||||
SimilarityPostprocessor,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
|
||||
import essay from "./essay";
|
||||
|
||||
// Update llm to use OpenAI
|
||||
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 });
|
||||
|
||||
// Customize retrieval and query args
|
||||
async function main() {
|
||||
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 index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
const retriever = index.asRetriever();
|
||||
retriever.similarityTopK = 5;
|
||||
|
||||
@@ -3,10 +3,16 @@ import fs from "node:fs/promises";
|
||||
import {
|
||||
Document,
|
||||
OpenAIEmbedding,
|
||||
Settings,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
// Update embed model
|
||||
Settings.embedModel = new OpenAIEmbedding({
|
||||
model: "text-embedding-3-large",
|
||||
dimensions: 1024,
|
||||
});
|
||||
|
||||
async function main() {
|
||||
// Load essay from abramov.txt in Node
|
||||
const path = "node_modules/llamaindex/examples/abramov.txt";
|
||||
@@ -16,17 +22,8 @@ async function main() {
|
||||
// Create Document object with essay
|
||||
const document = new Document({ text: essay, id_: path });
|
||||
|
||||
// Create service context and specify text-embedding-3-large
|
||||
const embedModel = new OpenAIEmbedding({
|
||||
model: "text-embedding-3-large",
|
||||
dimensions: 1024,
|
||||
});
|
||||
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();
|
||||
|
||||
@@ -2,7 +2,7 @@ import {
|
||||
OpenAI,
|
||||
ResponseSynthesizer,
|
||||
RetrieverQueryEngine,
|
||||
serviceContextFromDefaults,
|
||||
Settings,
|
||||
TextNode,
|
||||
TreeSummarize,
|
||||
VectorIndexRetriever,
|
||||
@@ -14,6 +14,12 @@ import {
|
||||
|
||||
import { Index, Pinecone, RecordMetadata } from "@pinecone-database/pinecone";
|
||||
|
||||
// Update llm
|
||||
Settings.llm = new OpenAI({
|
||||
model: "gpt-4",
|
||||
apiKey: process.env.OPENAI_API_KEY,
|
||||
});
|
||||
|
||||
/**
|
||||
* Please do not use this class in production; it's only for demonstration purposes.
|
||||
*/
|
||||
@@ -146,25 +152,11 @@ async function main() {
|
||||
});
|
||||
};
|
||||
|
||||
const getServiceContext = () => {
|
||||
const openAI = new OpenAI({
|
||||
model: "gpt-4",
|
||||
apiKey: process.env.OPENAI_API_KEY,
|
||||
});
|
||||
|
||||
return serviceContextFromDefaults({
|
||||
llm: openAI,
|
||||
});
|
||||
};
|
||||
|
||||
const getQueryEngine = async (filter: unknown) => {
|
||||
const vectorStore = await getPineconeVectorStore();
|
||||
const serviceContext = getServiceContext();
|
||||
|
||||
const vectorStoreIndex = await VectorStoreIndex.fromVectorStore(
|
||||
vectorStore,
|
||||
serviceContext,
|
||||
);
|
||||
const vectorStoreIndex =
|
||||
await VectorStoreIndex.fromVectorStore(vectorStore);
|
||||
|
||||
const retriever = new VectorIndexRetriever({
|
||||
index: vectorStoreIndex,
|
||||
@@ -172,8 +164,7 @@ async function main() {
|
||||
});
|
||||
|
||||
const responseSynthesizer = new ResponseSynthesizer({
|
||||
serviceContext,
|
||||
responseBuilder: new TreeSummarize(serviceContext),
|
||||
responseBuilder: new TreeSummarize(),
|
||||
});
|
||||
|
||||
return new RetrieverQueryEngine(retriever, responseSynthesizer, {
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
import fs from "node:fs/promises";
|
||||
|
||||
import {
|
||||
Document,
|
||||
OpenAI,
|
||||
serviceContextFromDefaults,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
import { Document, OpenAI, Settings, VectorStoreIndex } from "llamaindex";
|
||||
|
||||
Settings.llm = new OpenAI({ model: "gpt-4" });
|
||||
|
||||
async function main() {
|
||||
// Load essay from abramov.txt in Node
|
||||
@@ -15,13 +12,7 @@ async function main() {
|
||||
// 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: new OpenAI({ model: "gpt-4" }),
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
+7
-3
@@ -11,8 +11,12 @@
|
||||
"prepare": "husky",
|
||||
"test": "turbo run test",
|
||||
"type-check": "tsc -b --diagnostics",
|
||||
"release": "pnpm run build:release && changeset publish",
|
||||
"new-version": "pnpm run build:release && changeset version"
|
||||
"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",
|
||||
@@ -23,7 +27,7 @@
|
||||
"prettier": "^3.2.5",
|
||||
"prettier-plugin-organize-imports": "^3.2.4",
|
||||
"turbo": "^1.12.3",
|
||||
"typescript": "^5.3.3"
|
||||
"typescript": "^5.4.3"
|
||||
},
|
||||
"packageManager": "pnpm@8.15.1",
|
||||
"pnpm": {
|
||||
|
||||
@@ -1,5 +1,30 @@
|
||||
# llamaindex
|
||||
|
||||
## 0.2.2
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 3f8407c: Add pipeline.register to create a managed index in LlamaCloud
|
||||
- 60a1603: fix: make edge run build after core
|
||||
- fececd8: feat: add tool factory
|
||||
- 1115f83: fix: throw error when no pipelines exist for the retriever
|
||||
- 7a23cc6: feat: improve CallbackManager
|
||||
- ea467fa: Update the list of supported Azure OpenAI API versions as of 2024-04-02.
|
||||
- 6d9e015: feat: use claude3 with react agent
|
||||
- 0b665bd: feat: add wikipedia tool
|
||||
- 24b4033: feat: add result type json
|
||||
- 8b28092: Add support for doc store strategies to VectorStoreIndex.fromDocuments
|
||||
- Updated dependencies [7a23cc6]
|
||||
- @llamaindex/env@0.0.6
|
||||
|
||||
## 0.2.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 41210df: Add auto create milvus collection and add milvus node metadata
|
||||
- 137cf67: Use Pinecone namespaces for all operations
|
||||
- 259c842: Add support for edge runtime by using @llamaindex/edge
|
||||
|
||||
## 0.2.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"name": "llamaindex",
|
||||
"version": "0.2.0",
|
||||
"version": "0.2.2",
|
||||
"expectedMinorVersion": "2",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
@@ -23,9 +24,9 @@
|
||||
"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",
|
||||
@@ -40,7 +41,8 @@
|
||||
"rake-modified": "^1.0.8",
|
||||
"replicate": "^0.25.2",
|
||||
"string-strip-html": "^13.4.6",
|
||||
"wink-nlp": "^1.14.3"
|
||||
"wink-nlp": "^1.14.3",
|
||||
"wikipedia": "^2.1.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@swc/cli": "^0.3.9",
|
||||
@@ -61,15 +63,15 @@
|
||||
"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"
|
||||
}
|
||||
},
|
||||
"./internal/*": {
|
||||
"import": "./dist/not-allow.js",
|
||||
"require": "./dist/cjs/not-allow.js"
|
||||
},
|
||||
"./*": {
|
||||
"import": {
|
||||
"types": "./dist/type/*.d.ts",
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { OpenAI } from "./llm/LLM.js";
|
||||
import type { ChatMessage, LLM, MessageType } from "./llm/types.js";
|
||||
import { globalsHelper } from "./GlobalsHelper.js";
|
||||
import type { SummaryPrompt } from "./Prompt.js";
|
||||
import { defaultSummaryPrompt, messagesToHistoryStr } from "./Prompt.js";
|
||||
import { OpenAI } from "./llm/LLM.js";
|
||||
import type { ChatMessage, LLM, MessageType } from "./llm/types.js";
|
||||
|
||||
/**
|
||||
* A ChatHistory is used to keep the state of back and forth chat messages
|
||||
@@ -62,6 +63,12 @@ export class SimpleChatHistory extends ChatHistory {
|
||||
}
|
||||
|
||||
export class SummaryChatHistory extends ChatHistory {
|
||||
/**
|
||||
* Tokenizer function that converts text to tokens,
|
||||
* this is used to calculate the number of tokens in a message.
|
||||
*/
|
||||
tokenizer: (text: string) => Uint32Array =
|
||||
globalsHelper.defaultTokenizer.encode;
|
||||
tokensToSummarize: number;
|
||||
messages: ChatMessage[];
|
||||
summaryPrompt: SummaryPrompt;
|
||||
@@ -104,7 +111,9 @@ export class SummaryChatHistory extends ChatHistory {
|
||||
];
|
||||
// remove oldest message until the chat history is short enough for the context window
|
||||
messagesToSummarize.shift();
|
||||
} while (this.llm.tokens(promptMessages) > this.tokensToSummarize);
|
||||
} while (
|
||||
this.tokenizer(promptMessages[0].content).length > this.tokensToSummarize
|
||||
);
|
||||
|
||||
const response = await this.llm.chat({ messages: promptMessages });
|
||||
return { content: response.message.content, role: "memory" };
|
||||
@@ -178,7 +187,10 @@ export class SummaryChatHistory extends ChatHistory {
|
||||
const requestMessages = this.calcCurrentRequestMessages(transientMessages);
|
||||
|
||||
// get tokens of current request messages and the transient messages
|
||||
const tokens = this.llm.tokens(requestMessages);
|
||||
const tokens = requestMessages.reduce(
|
||||
(count, message) => count + this.tokenizer(message.content).length,
|
||||
0,
|
||||
);
|
||||
if (tokens > this.tokensToSummarize) {
|
||||
// if there are too many tokens for the next request, call summarize
|
||||
const memoryMessage = await this.summarize();
|
||||
|
||||
@@ -12,15 +12,15 @@ export enum Tokenizers {
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper class singleton
|
||||
* @internal Helper class singleton
|
||||
*/
|
||||
class GlobalsHelper {
|
||||
defaultTokenizer: {
|
||||
encode: (text: string) => Uint32Array;
|
||||
decode: (tokens: Uint32Array) => string;
|
||||
} | null = null;
|
||||
};
|
||||
|
||||
private initDefaultTokenizer() {
|
||||
constructor() {
|
||||
const encoding = encodingForModel("text-embedding-ada-002"); // cl100k_base
|
||||
|
||||
this.defaultTokenizer = {
|
||||
@@ -40,9 +40,6 @@ class GlobalsHelper {
|
||||
if (encoding && encoding !== Tokenizers.CL100K_BASE) {
|
||||
throw new Error(`Tokenizer encoding ${encoding} not yet supported`);
|
||||
}
|
||||
if (!this.defaultTokenizer) {
|
||||
this.initDefaultTokenizer();
|
||||
}
|
||||
|
||||
return this.defaultTokenizer!.encode.bind(this.defaultTokenizer);
|
||||
}
|
||||
@@ -51,13 +48,25 @@ class GlobalsHelper {
|
||||
if (encoding && encoding !== Tokenizers.CL100K_BASE) {
|
||||
throw new Error(`Tokenizer encoding ${encoding} not yet supported`);
|
||||
}
|
||||
if (!this.defaultTokenizer) {
|
||||
this.initDefaultTokenizer();
|
||||
}
|
||||
|
||||
return this.defaultTokenizer!.decode.bind(this.defaultTokenizer);
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated createEvent will be removed in the future,
|
||||
* please use `new CustomEvent(eventType, { detail: payload })` instead.
|
||||
*
|
||||
* Also, `parentEvent` will not be used in the future,
|
||||
* use `AsyncLocalStorage` to track parent events instead.
|
||||
* @example - Usage of `AsyncLocalStorage`:
|
||||
* let id = 0;
|
||||
* const asyncLocalStorage = new AsyncLocalStorage<number>();
|
||||
* asyncLocalStorage.run(++id, async () => {
|
||||
* setTimeout(() => {
|
||||
* console.log('parent event id:', asyncLocalStorage.getStore()); // 1
|
||||
* }, 1000)
|
||||
* });
|
||||
*/
|
||||
createEvent({
|
||||
parentEvent,
|
||||
type,
|
||||
|
||||
@@ -4,6 +4,9 @@ import type { ServiceContext } from "./ServiceContext.js";
|
||||
|
||||
export type RetrieveParams = {
|
||||
query: string;
|
||||
/**
|
||||
* @deprecated will be removed in the next major version
|
||||
*/
|
||||
parentEvent?: Event;
|
||||
preFilters?: unknown;
|
||||
};
|
||||
@@ -13,5 +16,7 @@ export type RetrieveParams = {
|
||||
*/
|
||||
export interface BaseRetriever {
|
||||
retrieve(params: RetrieveParams): Promise<NodeWithScore[]>;
|
||||
getServiceContext(): ServiceContext;
|
||||
|
||||
// to be deprecated soon
|
||||
serviceContext?: ServiceContext;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { PromptHelper } from "./PromptHelper.js";
|
||||
import { CallbackManager } from "./callbacks/CallbackManager.js";
|
||||
import { OpenAIEmbedding } from "./embeddings/OpenAIEmbedding.js";
|
||||
import type { BaseEmbedding } from "./embeddings/types.js";
|
||||
import type { LLM } from "./llm/index.js";
|
||||
import { OpenAI } from "./llm/index.js";
|
||||
import { OpenAI } from "./llm/LLM.js";
|
||||
import type { LLM } from "./llm/types.js";
|
||||
import { SimpleNodeParser } from "./nodeParsers/SimpleNodeParser.js";
|
||||
import type { NodeParser } from "./nodeParsers/types.js";
|
||||
|
||||
@@ -15,7 +14,6 @@ export interface ServiceContext {
|
||||
promptHelper: PromptHelper;
|
||||
embedModel: BaseEmbedding;
|
||||
nodeParser: NodeParser;
|
||||
callbackManager: CallbackManager;
|
||||
// llamaLogger: any;
|
||||
}
|
||||
|
||||
@@ -24,14 +22,12 @@ export interface ServiceContextOptions {
|
||||
promptHelper?: PromptHelper;
|
||||
embedModel?: BaseEmbedding;
|
||||
nodeParser?: NodeParser;
|
||||
callbackManager?: CallbackManager;
|
||||
// NodeParser arguments
|
||||
chunkSize?: number;
|
||||
chunkOverlap?: number;
|
||||
}
|
||||
|
||||
export function serviceContextFromDefaults(options?: ServiceContextOptions) {
|
||||
const callbackManager = options?.callbackManager ?? new CallbackManager();
|
||||
const serviceContext: ServiceContext = {
|
||||
llm: options?.llm ?? new OpenAI(),
|
||||
embedModel: options?.embedModel ?? new OpenAIEmbedding(),
|
||||
@@ -42,7 +38,6 @@ export function serviceContextFromDefaults(options?: ServiceContextOptions) {
|
||||
chunkOverlap: options?.chunkOverlap,
|
||||
}),
|
||||
promptHelper: options?.promptHelper ?? new PromptHelper(),
|
||||
callbackManager,
|
||||
};
|
||||
|
||||
return serviceContext;
|
||||
@@ -65,8 +60,5 @@ export function serviceContextFromServiceContext(
|
||||
if (options.nodeParser) {
|
||||
newServiceContext.nodeParser = options.nodeParser;
|
||||
}
|
||||
if (options.callbackManager) {
|
||||
newServiceContext.callbackManager = options.callbackManager;
|
||||
}
|
||||
return newServiceContext;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
import { CallbackManager } from "./callbacks/CallbackManager.js";
|
||||
import { OpenAIEmbedding } from "./embeddings/OpenAIEmbedding.js";
|
||||
import { OpenAI } from "./llm/LLM.js";
|
||||
|
||||
import { PromptHelper } from "./PromptHelper.js";
|
||||
import { SimpleNodeParser } from "./nodeParsers/SimpleNodeParser.js";
|
||||
|
||||
import { AsyncLocalStorage } from "@llamaindex/env";
|
||||
import type { ServiceContext } from "./ServiceContext.js";
|
||||
import type { BaseEmbedding } from "./embeddings/types.js";
|
||||
import {
|
||||
getCallbackManager,
|
||||
setCallbackManager,
|
||||
withCallbackManager,
|
||||
} from "./internal/settings/CallbackManager.js";
|
||||
import type { LLM } from "./llm/types.js";
|
||||
import type { NodeParser } from "./nodeParsers/types.js";
|
||||
|
||||
export type PromptConfig = {
|
||||
llm?: string;
|
||||
lang?: string;
|
||||
};
|
||||
|
||||
export interface Config {
|
||||
prompt: PromptConfig;
|
||||
llm: LLM | null;
|
||||
promptHelper: PromptHelper | null;
|
||||
embedModel: BaseEmbedding | null;
|
||||
nodeParser: NodeParser | null;
|
||||
callbackManager: CallbackManager | null;
|
||||
chunkSize?: number;
|
||||
chunkOverlap?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
class GlobalSettings implements Config {
|
||||
#prompt: PromptConfig = {};
|
||||
#llm: LLM | null = null;
|
||||
#promptHelper: PromptHelper | null = null;
|
||||
#embedModel: BaseEmbedding | null = null;
|
||||
#nodeParser: NodeParser | null = null;
|
||||
#chunkSize?: number;
|
||||
#chunkOverlap?: number;
|
||||
|
||||
#llmAsyncLocalStorage = new AsyncLocalStorage<LLM>();
|
||||
#promptHelperAsyncLocalStorage = new AsyncLocalStorage<PromptHelper>();
|
||||
#embedModelAsyncLocalStorage = new AsyncLocalStorage<BaseEmbedding>();
|
||||
#nodeParserAsyncLocalStorage = new AsyncLocalStorage<NodeParser>();
|
||||
#chunkSizeAsyncLocalStorage = new AsyncLocalStorage<number>();
|
||||
#chunkOverlapAsyncLocalStorage = new AsyncLocalStorage<number>();
|
||||
#promptAsyncLocalStorage = new AsyncLocalStorage<PromptConfig>();
|
||||
|
||||
get llm(): LLM {
|
||||
if (this.#llm === null) {
|
||||
this.#llm = new OpenAI();
|
||||
}
|
||||
|
||||
return this.#llmAsyncLocalStorage.getStore() ?? this.#llm;
|
||||
}
|
||||
|
||||
set llm(llm: LLM) {
|
||||
this.#llm = llm;
|
||||
}
|
||||
|
||||
withLLM<Result>(llm: LLM, fn: () => Result): Result {
|
||||
return this.#llmAsyncLocalStorage.run(llm, fn);
|
||||
}
|
||||
|
||||
get promptHelper(): PromptHelper {
|
||||
if (this.#promptHelper === null) {
|
||||
this.#promptHelper = new PromptHelper();
|
||||
}
|
||||
|
||||
return this.#promptHelperAsyncLocalStorage.getStore() ?? this.#promptHelper;
|
||||
}
|
||||
|
||||
set promptHelper(promptHelper: PromptHelper) {
|
||||
this.#promptHelper = promptHelper;
|
||||
}
|
||||
|
||||
withPromptHelper<Result>(
|
||||
promptHelper: PromptHelper,
|
||||
fn: () => Result,
|
||||
): Result {
|
||||
return this.#promptHelperAsyncLocalStorage.run(promptHelper, fn);
|
||||
}
|
||||
|
||||
get embedModel(): BaseEmbedding {
|
||||
if (this.#embedModel === null) {
|
||||
this.#embedModel = new OpenAIEmbedding();
|
||||
}
|
||||
|
||||
return this.#embedModelAsyncLocalStorage.getStore() ?? this.#embedModel;
|
||||
}
|
||||
|
||||
set embedModel(embedModel: BaseEmbedding) {
|
||||
this.#embedModel = embedModel;
|
||||
}
|
||||
|
||||
withEmbedModel<Result>(embedModel: BaseEmbedding, fn: () => Result): Result {
|
||||
return this.#embedModelAsyncLocalStorage.run(embedModel, fn);
|
||||
}
|
||||
|
||||
get nodeParser(): NodeParser {
|
||||
if (this.#nodeParser === null) {
|
||||
this.#nodeParser = new SimpleNodeParser({
|
||||
chunkSize: this.#chunkSize,
|
||||
chunkOverlap: this.#chunkOverlap,
|
||||
});
|
||||
}
|
||||
|
||||
return this.#nodeParserAsyncLocalStorage.getStore() ?? this.#nodeParser;
|
||||
}
|
||||
|
||||
set nodeParser(nodeParser: NodeParser) {
|
||||
this.#nodeParser = nodeParser;
|
||||
}
|
||||
|
||||
withNodeParser<Result>(nodeParser: NodeParser, fn: () => Result): Result {
|
||||
return this.#nodeParserAsyncLocalStorage.run(nodeParser, fn);
|
||||
}
|
||||
|
||||
get callbackManager(): CallbackManager {
|
||||
return getCallbackManager();
|
||||
}
|
||||
|
||||
set callbackManager(callbackManager: CallbackManager) {
|
||||
setCallbackManager(callbackManager);
|
||||
}
|
||||
|
||||
withCallbackManager<Result>(
|
||||
callbackManager: CallbackManager,
|
||||
fn: () => Result,
|
||||
): Result {
|
||||
return withCallbackManager(callbackManager, fn);
|
||||
}
|
||||
|
||||
set chunkSize(chunkSize: number | undefined) {
|
||||
this.#chunkSize = chunkSize;
|
||||
}
|
||||
|
||||
get chunkSize(): number | undefined {
|
||||
return this.#chunkSizeAsyncLocalStorage.getStore() ?? this.#chunkSize;
|
||||
}
|
||||
|
||||
withChunkSize<Result>(chunkSize: number, fn: () => Result): Result {
|
||||
return this.#chunkSizeAsyncLocalStorage.run(chunkSize, fn);
|
||||
}
|
||||
|
||||
get chunkOverlap(): number | undefined {
|
||||
return this.#chunkOverlapAsyncLocalStorage.getStore() ?? this.#chunkOverlap;
|
||||
}
|
||||
|
||||
set chunkOverlap(chunkOverlap: number | undefined) {
|
||||
this.#chunkOverlap = chunkOverlap;
|
||||
}
|
||||
|
||||
withChunkOverlap<Result>(chunkOverlap: number, fn: () => Result): Result {
|
||||
return this.#chunkOverlapAsyncLocalStorage.run(chunkOverlap, fn);
|
||||
}
|
||||
|
||||
get prompt(): PromptConfig {
|
||||
return this.#promptAsyncLocalStorage.getStore() ?? this.#prompt;
|
||||
}
|
||||
|
||||
set prompt(prompt: PromptConfig) {
|
||||
this.#prompt = prompt;
|
||||
}
|
||||
|
||||
withPrompt<Result>(prompt: PromptConfig, fn: () => Result): Result {
|
||||
return this.#promptAsyncLocalStorage.run(prompt, fn);
|
||||
}
|
||||
}
|
||||
|
||||
export const llmFromSettingsOrContext = (serviceContext?: ServiceContext) => {
|
||||
if (serviceContext?.llm) {
|
||||
return serviceContext.llm;
|
||||
}
|
||||
|
||||
return Settings.llm;
|
||||
};
|
||||
|
||||
export const nodeParserFromSettingsOrContext = (
|
||||
serviceContext?: ServiceContext,
|
||||
) => {
|
||||
if (serviceContext?.nodeParser) {
|
||||
return serviceContext.nodeParser;
|
||||
}
|
||||
|
||||
return Settings.nodeParser;
|
||||
};
|
||||
|
||||
export const embedModelFromSettingsOrContext = (
|
||||
serviceContext?: ServiceContext,
|
||||
) => {
|
||||
if (serviceContext?.embedModel) {
|
||||
return serviceContext.embedModel;
|
||||
}
|
||||
|
||||
return Settings.embedModel;
|
||||
};
|
||||
|
||||
export const promptHelperFromSettingsOrContext = (
|
||||
serviceContext?: ServiceContext,
|
||||
) => {
|
||||
if (serviceContext?.promptHelper) {
|
||||
return serviceContext.promptHelper;
|
||||
}
|
||||
|
||||
return Settings.promptHelper;
|
||||
};
|
||||
|
||||
export const Settings = new GlobalSettings();
|
||||
@@ -100,7 +100,6 @@ export class SentenceSplitter {
|
||||
}
|
||||
this.chunkSize = chunkSize;
|
||||
this.chunkOverlap = chunkOverlap;
|
||||
// this._callback_manager = callback_manager || new CallbackManager([]);
|
||||
|
||||
this.tokenizer = tokenizer ?? globalsHelper.tokenizer();
|
||||
this.tokenizerDecoder =
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { CallbackManager } from "../../callbacks/CallbackManager.js";
|
||||
import type { ChatMessage } from "../../llm/index.js";
|
||||
import { OpenAI } from "../../llm/index.js";
|
||||
import type { ObjectRetriever } from "../../objects/base.js";
|
||||
@@ -14,7 +13,6 @@ type OpenAIAgentParams = {
|
||||
verbose?: boolean;
|
||||
maxFunctionCalls?: number;
|
||||
defaultToolChoice?: string;
|
||||
callbackManager?: CallbackManager;
|
||||
toolRetriever?: ObjectRetriever;
|
||||
systemPrompt?: string;
|
||||
};
|
||||
@@ -33,7 +31,6 @@ export class OpenAIAgent extends AgentRunner {
|
||||
verbose,
|
||||
maxFunctionCalls = 5,
|
||||
defaultToolChoice = "auto",
|
||||
callbackManager,
|
||||
toolRetriever,
|
||||
systemPrompt,
|
||||
}: OpenAIAgentParams) {
|
||||
@@ -58,7 +55,6 @@ export class OpenAIAgent extends AgentRunner {
|
||||
|
||||
const stepEngine = new OpenAIAgentWorker({
|
||||
tools,
|
||||
callbackManager,
|
||||
llm,
|
||||
prefixMessages,
|
||||
maxFunctionCalls,
|
||||
@@ -69,7 +65,6 @@ export class OpenAIAgent extends AgentRunner {
|
||||
super({
|
||||
agentWorker: stepEngine,
|
||||
memory,
|
||||
callbackManager,
|
||||
defaultToolChoice,
|
||||
chatHistory: prefixMessages,
|
||||
});
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { randomUUID } from "@llamaindex/env";
|
||||
import { Response } from "../../Response.js";
|
||||
import type { CallbackManager } from "../../callbacks/CallbackManager.js";
|
||||
import {
|
||||
AgentChatResponse,
|
||||
ChatResponseMode,
|
||||
@@ -79,7 +78,6 @@ type OpenAIAgentWorkerParams = {
|
||||
prefixMessages?: ChatMessage[];
|
||||
verbose?: boolean;
|
||||
maxFunctionCalls?: number;
|
||||
callbackManager?: CallbackManager | undefined;
|
||||
toolRetriever?: ObjectRetriever;
|
||||
};
|
||||
|
||||
@@ -98,7 +96,6 @@ export class OpenAIAgentWorker implements AgentWorker {
|
||||
private maxFunctionCalls: number;
|
||||
|
||||
public prefixMessages: ChatMessage[];
|
||||
public callbackManager: CallbackManager | undefined;
|
||||
|
||||
private _getTools: (input: string) => Promise<BaseTool[]>;
|
||||
|
||||
@@ -111,14 +108,12 @@ export class OpenAIAgentWorker implements AgentWorker {
|
||||
prefixMessages,
|
||||
verbose,
|
||||
maxFunctionCalls = DEFAULT_MAX_FUNCTION_CALLS,
|
||||
callbackManager,
|
||||
toolRetriever,
|
||||
}: OpenAIAgentWorkerParams) {
|
||||
this.llm = llm ?? new OpenAI({ model: "gpt-3.5-turbo-0613" });
|
||||
this.verbose = verbose || false;
|
||||
this.maxFunctionCalls = maxFunctionCalls;
|
||||
this.prefixMessages = prefixMessages || [];
|
||||
this.callbackManager = callbackManager || this.llm.callbackManager;
|
||||
|
||||
if (tools.length > 0 && toolRetriever) {
|
||||
throw new Error("Cannot specify both tools and tool_retriever");
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { CallbackManager } from "../../callbacks/CallbackManager.js";
|
||||
import type { ChatMessage, LLM } from "../../llm/index.js";
|
||||
import type { ObjectRetriever } from "../../objects/base.js";
|
||||
import type { BaseTool } from "../../types.js";
|
||||
@@ -13,7 +12,6 @@ type ReActAgentParams = {
|
||||
verbose?: boolean;
|
||||
maxInteractions?: number;
|
||||
defaultToolChoice?: string;
|
||||
callbackManager?: CallbackManager;
|
||||
toolRetriever?: ObjectRetriever;
|
||||
};
|
||||
|
||||
@@ -31,12 +29,10 @@ export class ReActAgent extends AgentRunner {
|
||||
verbose,
|
||||
maxInteractions = 10,
|
||||
defaultToolChoice = "auto",
|
||||
callbackManager,
|
||||
toolRetriever,
|
||||
}: Partial<ReActAgentParams>) {
|
||||
const stepEngine = new ReActAgentWorker({
|
||||
tools: tools ?? [],
|
||||
callbackManager,
|
||||
llm,
|
||||
maxInteractions,
|
||||
toolRetriever,
|
||||
@@ -46,7 +42,6 @@ export class ReActAgent extends AgentRunner {
|
||||
super({
|
||||
agentWorker: stepEngine,
|
||||
memory,
|
||||
callbackManager,
|
||||
defaultToolChoice,
|
||||
chatHistory: prefixMessages,
|
||||
});
|
||||
|
||||
@@ -60,7 +60,7 @@ export class ReActChatFormatter implements BaseAgentChatFormatter {
|
||||
} else {
|
||||
message = {
|
||||
content: reasoningStep.getContent(),
|
||||
role: "system",
|
||||
role: "assistant",
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { randomUUID } from "crypto";
|
||||
import { CallbackManager } from "../../callbacks/CallbackManager.js";
|
||||
import { randomUUID } from "@llamaindex/env";
|
||||
import { AgentChatResponse } from "../../engines/chat/index.js";
|
||||
import type { ChatResponse, LLM } from "../../llm/index.js";
|
||||
import { OpenAI } from "../../llm/index.js";
|
||||
@@ -17,14 +16,12 @@ import {
|
||||
ObservationReasoningStep,
|
||||
ResponseReasoningStep,
|
||||
} from "./types.js";
|
||||
|
||||
type ReActAgentWorkerParams = {
|
||||
tools: BaseTool[];
|
||||
llm?: LLM;
|
||||
maxInteractions?: number;
|
||||
reactChatFormatter?: ReActChatFormatter | undefined;
|
||||
outputParser?: ReActOutputParser | undefined;
|
||||
callbackManager?: CallbackManager | undefined;
|
||||
verbose?: boolean | undefined;
|
||||
toolRetriever?: ObjectRetriever | undefined;
|
||||
};
|
||||
@@ -70,8 +67,6 @@ export class ReActAgentWorker implements AgentWorker {
|
||||
reactChatFormatter: ReActChatFormatter;
|
||||
outputParser: ReActOutputParser;
|
||||
|
||||
callbackManager: CallbackManager;
|
||||
|
||||
_getTools: (message: string) => Promise<BaseTool[]>;
|
||||
|
||||
constructor({
|
||||
@@ -80,12 +75,10 @@ export class ReActAgentWorker implements AgentWorker {
|
||||
maxInteractions,
|
||||
reactChatFormatter,
|
||||
outputParser,
|
||||
callbackManager,
|
||||
verbose,
|
||||
toolRetriever,
|
||||
}: ReActAgentWorkerParams) {
|
||||
this.llm = llm ?? new OpenAI({ model: "gpt-3.5-turbo-0613" });
|
||||
this.callbackManager = callbackManager || new CallbackManager();
|
||||
|
||||
this.maxInteractions = maxInteractions ?? 10;
|
||||
this.reactChatFormatter = reactChatFormatter ?? new ReActChatFormatter();
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { randomUUID } from "crypto";
|
||||
import { CallbackManager } from "../../callbacks/CallbackManager.js";
|
||||
import { randomUUID } from "@llamaindex/env";
|
||||
import type { ChatEngineAgentParams } from "../../engines/chat/index.js";
|
||||
import {
|
||||
AgentChatResponse,
|
||||
@@ -12,7 +11,6 @@ import type { BaseMemory } from "../../memory/types.js";
|
||||
import type { AgentWorker, TaskStepOutput } from "../types.js";
|
||||
import { Task, TaskStep } from "../types.js";
|
||||
import { AgentState, BaseAgentRunner, TaskState } from "./types.js";
|
||||
|
||||
const validateStepFromArgs = (
|
||||
taskId: string,
|
||||
input?: string | null,
|
||||
@@ -36,7 +34,6 @@ type AgentRunnerParams = {
|
||||
state?: AgentState;
|
||||
memory?: BaseMemory;
|
||||
llm?: LLM;
|
||||
callbackManager?: CallbackManager;
|
||||
initTaskStateKwargs?: Record<string, any>;
|
||||
deleteTaskOnFinish?: boolean;
|
||||
defaultToolChoice?: string;
|
||||
@@ -46,7 +43,6 @@ export class AgentRunner extends BaseAgentRunner {
|
||||
agentWorker: AgentWorker;
|
||||
state: AgentState;
|
||||
memory: BaseMemory;
|
||||
callbackManager: CallbackManager;
|
||||
initTaskStateKwargs: Record<string, any>;
|
||||
deleteTaskOnFinish: boolean;
|
||||
defaultToolChoice: string;
|
||||
@@ -64,7 +60,6 @@ export class AgentRunner extends BaseAgentRunner {
|
||||
new ChatMemoryBuffer({
|
||||
chatHistory: params.chatHistory,
|
||||
});
|
||||
this.callbackManager = params.callbackManager ?? new CallbackManager();
|
||||
this.initTaskStateKwargs = params.initTaskStateKwargs ?? {};
|
||||
this.deleteTaskOnFinish = params.deleteTaskOnFinish ?? false;
|
||||
this.defaultToolChoice = params.defaultToolChoice ?? "auto";
|
||||
|
||||
@@ -1,6 +1,26 @@
|
||||
import type { Anthropic } from "@anthropic-ai/sdk";
|
||||
import { CustomEvent } from "@llamaindex/env";
|
||||
import type { NodeWithScore } from "../Node.js";
|
||||
|
||||
/**
|
||||
* This type is used to define the event maps for the Llamaindex package.
|
||||
*/
|
||||
export interface LlamaIndexEventMaps {}
|
||||
|
||||
declare module "llamaindex" {
|
||||
interface LlamaIndexEventMaps {
|
||||
/**
|
||||
* @deprecated
|
||||
*/
|
||||
retrieve: CustomEvent<RetrievalCallbackResponse>;
|
||||
/**
|
||||
* @deprecated
|
||||
*/
|
||||
stream: CustomEvent<StreamCallbackResponse>;
|
||||
}
|
||||
}
|
||||
|
||||
//#region @deprecated remove in the next major version
|
||||
/*
|
||||
An event is a wrapper that groups related operations.
|
||||
For example, during retrieve and synthesize,
|
||||
@@ -60,25 +80,114 @@ export interface RetrievalCallbackResponse extends BaseCallbackResponse {
|
||||
}
|
||||
|
||||
interface CallbackManagerMethods {
|
||||
/*
|
||||
onLLMStream is called when a token is streamed from the LLM. Defining this
|
||||
callback auto sets the stream = True flag on the openAI createChatCompletion request.
|
||||
*/
|
||||
onLLMStream?: (params: StreamCallbackResponse) => Promise<void> | void;
|
||||
/*
|
||||
onRetrieve is called as soon as the retriever finishes fetching relevant nodes.
|
||||
This callback allows you to handle the retrieved nodes even if the synthesizer
|
||||
is still running.
|
||||
*/
|
||||
onRetrieve?: (params: RetrievalCallbackResponse) => Promise<void> | void;
|
||||
/**
|
||||
* onLLMStream is called when a token is streamed from the LLM. Defining this
|
||||
* callback auto sets the stream = True flag on the openAI createChatCompletion request.
|
||||
* @deprecated will be removed in the next major version
|
||||
*/
|
||||
onLLMStream: (params: StreamCallbackResponse) => Promise<void> | void;
|
||||
/**
|
||||
* onRetrieve is called as soon as the retriever finishes fetching relevant nodes.
|
||||
* This callback allows you to handle the retrieved nodes even if the synthesizer
|
||||
* is still running.
|
||||
* @deprecated will be removed in the next major version
|
||||
*/
|
||||
onRetrieve: (params: RetrievalCallbackResponse) => Promise<void> | void;
|
||||
}
|
||||
//#endregion
|
||||
|
||||
const noop: (...args: any[]) => any = () => void 0;
|
||||
|
||||
type EventHandler<Event extends CustomEvent> = (event: Event) => void;
|
||||
|
||||
export class CallbackManager implements CallbackManagerMethods {
|
||||
onLLMStream?: (params: StreamCallbackResponse) => Promise<void> | void;
|
||||
onRetrieve?: (params: RetrievalCallbackResponse) => Promise<void> | void;
|
||||
/**
|
||||
* @deprecated will be removed in the next major version
|
||||
*/
|
||||
get onLLMStream(): CallbackManagerMethods["onLLMStream"] {
|
||||
return async (response) => {
|
||||
await Promise.all(
|
||||
this.#handlers
|
||||
.get("stream")!
|
||||
.map((handler) =>
|
||||
handler(new CustomEvent("stream", { detail: response })),
|
||||
),
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
constructor(handlers?: CallbackManagerMethods) {
|
||||
this.onLLMStream = handlers?.onLLMStream;
|
||||
this.onRetrieve = handlers?.onRetrieve;
|
||||
/**
|
||||
* @deprecated will be removed in the next major version
|
||||
*/
|
||||
get onRetrieve(): CallbackManagerMethods["onRetrieve"] {
|
||||
return async (response) => {
|
||||
await Promise.all(
|
||||
this.#handlers
|
||||
.get("retrieve")!
|
||||
.map((handler) =>
|
||||
handler(new CustomEvent("retrieve", { detail: response })),
|
||||
),
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated will be removed in the next major version
|
||||
*/
|
||||
set onLLMStream(_: never) {
|
||||
throw new Error("onLLMStream is deprecated. Use on('stream') instead");
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated will be removed in the next major version
|
||||
*/
|
||||
set onRetrieve(_: never) {
|
||||
throw new Error("onRetrieve is deprecated. Use `on('retrieve')` instead");
|
||||
}
|
||||
|
||||
#handlers = new Map<keyof LlamaIndexEventMaps, EventHandler<CustomEvent>[]>();
|
||||
|
||||
constructor(handlers?: Partial<CallbackManagerMethods>) {
|
||||
const onLLMStream = handlers?.onLLMStream ?? noop;
|
||||
this.on("stream", (event) => onLLMStream(event.detail));
|
||||
const onRetrieve = handlers?.onRetrieve ?? noop;
|
||||
this.on("retrieve", (event) => onRetrieve(event.detail));
|
||||
}
|
||||
|
||||
on<
|
||||
K extends keyof LlamaIndexEventMaps,
|
||||
H extends EventHandler<LlamaIndexEventMaps[K]>,
|
||||
>(event: K, handler: H) {
|
||||
if (!this.#handlers.has(event)) {
|
||||
this.#handlers.set(event, []);
|
||||
}
|
||||
this.#handlers.get(event)!.push(handler);
|
||||
return this;
|
||||
}
|
||||
|
||||
off<
|
||||
K extends keyof LlamaIndexEventMaps,
|
||||
H extends EventHandler<LlamaIndexEventMaps[K]>,
|
||||
>(event: K, handler: H) {
|
||||
if (!this.#handlers.has(event)) {
|
||||
return;
|
||||
}
|
||||
const handlers = this.#handlers.get(event)!;
|
||||
const index = handlers.indexOf(handler);
|
||||
if (index > -1) {
|
||||
handlers.splice(index, 1);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
dispatchEvent<K extends keyof LlamaIndexEventMaps>(
|
||||
event: K,
|
||||
detail: LlamaIndexEventMaps[K]["detail"],
|
||||
) {
|
||||
const handlers = this.#handlers.get(event);
|
||||
if (!handlers) {
|
||||
return;
|
||||
}
|
||||
handlers.forEach((handler) => handler(new CustomEvent(event, { detail })));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,8 +3,7 @@ import { globalsHelper } from "../GlobalsHelper.js";
|
||||
import type { NodeWithScore } from "../Node.js";
|
||||
import { ObjectType, jsonToNode } from "../Node.js";
|
||||
import type { BaseRetriever, RetrieveParams } from "../Retriever.js";
|
||||
import type { ServiceContext } from "../ServiceContext.js";
|
||||
import { serviceContextFromDefaults } from "../ServiceContext.js";
|
||||
import { Settings } from "../Settings.js";
|
||||
import type { ClientParams, CloudConstructorParams } from "./types.js";
|
||||
import { DEFAULT_PROJECT_NAME } from "./types.js";
|
||||
import { getClient } from "./utils.js";
|
||||
@@ -20,7 +19,6 @@ export class LlamaCloudRetriever implements BaseRetriever {
|
||||
retrieveParams: CloudRetrieveParams;
|
||||
projectName: string = DEFAULT_PROJECT_NAME;
|
||||
pipelineName: string;
|
||||
serviceContext: ServiceContext;
|
||||
|
||||
private resultNodesToNodeWithScore(
|
||||
nodes: PlatformApi.TextNodeWithScore[],
|
||||
@@ -44,7 +42,6 @@ export class LlamaCloudRetriever implements BaseRetriever {
|
||||
if (params.projectName) {
|
||||
this.projectName = params.projectName;
|
||||
}
|
||||
this.serviceContext = params.serviceContext ?? serviceContextFromDefaults();
|
||||
}
|
||||
|
||||
private async getClient(): Promise<PlatformApiClient> {
|
||||
@@ -65,7 +62,7 @@ export class LlamaCloudRetriever implements BaseRetriever {
|
||||
projectName: this.projectName,
|
||||
pipelineName: this.pipelineName,
|
||||
});
|
||||
if (pipelines.length !== 1 && !pipelines[0].id) {
|
||||
if (pipelines.length !== 1 && !pipelines[0]?.id) {
|
||||
throw new Error(
|
||||
`No pipeline found with name ${this.pipelineName} in project ${this.projectName}`,
|
||||
);
|
||||
@@ -80,20 +77,15 @@ export class LlamaCloudRetriever implements BaseRetriever {
|
||||
|
||||
const nodes = this.resultNodesToNodeWithScore(results.retrievalNodes);
|
||||
|
||||
if (this.serviceContext.callbackManager.onRetrieve) {
|
||||
this.serviceContext.callbackManager.onRetrieve({
|
||||
query,
|
||||
nodes,
|
||||
event: globalsHelper.createEvent({
|
||||
parentEvent,
|
||||
type: "retrieve",
|
||||
}),
|
||||
});
|
||||
}
|
||||
Settings.callbackManager.onRetrieve({
|
||||
query,
|
||||
nodes,
|
||||
event: globalsHelper.createEvent({
|
||||
parentEvent,
|
||||
type: "retrieve",
|
||||
}),
|
||||
});
|
||||
|
||||
return nodes;
|
||||
}
|
||||
|
||||
getServiceContext(): ServiceContext {
|
||||
return this.serviceContext;
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user