Compare commits

...

24 Commits

Author SHA1 Message Date
Alex Yang a6dfa30dcf RELEASING: Releasing 3 package(s) 2024-04-01 14:34:40 -05:00
Alex Yang d0365dc434 fix: docs dependencies (#680) 2024-04-01 14:19:37 -05:00
Alex Yang aa41432bbb refactor: remove llm.tokens api (#679) 2024-04-01 14:12:17 -05:00
Emanuel Ferreira 98a2b4a547 feat: add global settings (#668)
Co-authored-by: Alex Yang <himself65@outlook.com>
2024-04-01 13:43:35 -05:00
Benny 806ce9a360 fix: README links and examples (#678) 2024-04-01 13:16:10 -05:00
Marcus Schiesser 8b28092cc8 feat: Add doc store strategies to VectorStoreIndex.fromDocuments (#646) 2024-04-01 10:12:08 -07:00
Marcus Schiesser 5c5f4c1c84 Revert "feat: support calculate llama 2 tokens (#676)"
This reverts commit 041acd11fe.
2024-04-01 13:52:07 +08:00
Marcus Schiesser 949d330295 fix: typecheck 2024-04-01 12:26:22 +08:00
Marcus Schiesser 9a5ee4f37a Revert "fix: support import subdirectory (#655)"
This reverts commit 98d4cbdf95.
2024-04-01 11:52:41 +08:00
Alex Yang 7a23cc6c84 feat: improve callback manager (#675) 2024-03-31 15:34:48 -05:00
Alex Yang 041acd11fe feat: support calculate llama 2 tokens (#676) 2024-03-29 20:12:26 -05:00
Emanuel Ferreira 24b4033db9 feat: add result type json (#673) 2024-03-28 16:24:33 -03:00
Emanuel Ferreira 1115f83b8f fix: pipeline not found (#672) 2024-03-28 15:31:18 -03:00
Thuc Pham 60a1603636 fix: make edge run build after core (#670) 2024-03-28 18:26:35 +08:00
Peter Goldstein ea467fa031 Update to latest supported version list as of 2024-04-02. (#669) 2024-03-28 10:53:33 +07:00
Marcus Schiesser b0e6f73b1d docs: update readme for Edge runtime 2024-03-26 15:18:19 +08:00
Marcus Schiesser 6d9e015b5e feat: use claude3 with react agent (#661)
Co-authored-by: Emanuel Ferreira <contatoferreirads@gmail.com>
2024-03-22 09:25:31 -03:00
Thuc Pham fececd89ab feat: add tool factory (#663) 2024-03-22 14:40:41 +07:00
Marcus Schiesser 48e287892f test: use unique tmp dir for storage tests and wait to clean VectorStoreIndex files 2024-03-21 13:04:25 +07:00
Marcus Schiesser f118400820 docs: Add changeset instructions for PRs 2024-03-20 11:45:33 +07:00
Marcus Schiesser 3f8407c7af docs: changeset for pipeline.register added 2024-03-20 10:20:30 +07:00
Marcus Schiesser 83317739c7 feat: add pipeline.register (#589) 2024-03-19 13:32:32 -07:00
Thuc Pham 0b665bd1ca feat: add wikipedia tool (#648)
Co-authored-by: Marcus Schiesser <mail@marcusschiesser.de>
2024-03-19 11:31:08 +07:00
Alex Yang 98d4cbdf95 fix: support import subdirectory (#655) 2024-03-18 21:00:46 -05:00
154 changed files with 2288 additions and 2011 deletions
+6 -2
View File
@@ -1,9 +1,13 @@
{
"jsc": {
"parser": {
"syntax": "typescript"
"syntax": "typescript",
"decorators": true
},
"target": "esnext"
"target": "esnext",
"transform": {
"decoratorVersion": "2022-03"
}
},
"module": {
"type": "commonjs",
+6 -2
View File
@@ -1,8 +1,12 @@
{
"jsc": {
"parser": {
"syntax": "typescript"
"syntax": "typescript",
"decorators": true
},
"target": "esnext"
"target": "esnext",
"transform": {
"decoratorVersion": "2022-03"
}
}
}
+11 -1
View File
@@ -79,7 +79,17 @@ 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
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:
+62 -41
View File
@@ -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();
+5 -6
View File
@@ -2,14 +2,14 @@
The embedding model in LlamaIndex is responsible for creating numerical representations of text. By default, LlamaIndex will use the `text-embedding-ada-002` model from OpenAI.
This can be explicitly 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();
+3 -6
View File
@@ -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)
+3 -4
View File
@@ -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
@@ -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],
});
+3 -7
View File
@@ -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
+2
View File
@@ -0,0 +1,2 @@
label: Recipes
position: 3
+14
View File
@@ -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
View File
@@ -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": [
+29
View File
@@ -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);
+5 -13
View File
@@ -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: [
{
+8 -2
View File
@@ -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,
});
+23
View File
@@ -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");
});
+2 -7
View File
@@ -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 });
+5 -5
View File
@@ -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 });
+8
View File
@@ -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
```
+34
View File
@@ -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);
+5 -16
View File
@@ -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?";
+5 -12
View File
@@ -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({
+6 -12
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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]);
})();
+2 -7
View File
@@ -1,8 +1,4 @@
import {
MilvusVectorStore,
serviceContextFromDefaults,
VectorStoreIndex,
} from "llamaindex";
import { MilvusVectorStore, VectorStoreIndex } from "llamaindex";
const collectionName = "movie_reviews";
@@ -10,8 +6,7 @@ async function main() {
try {
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
View File
@@ -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);
})();
+3 -7
View File
@@ -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 });
+9 -11
View File
@@ -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
View File
@@ -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({
+6 -7
View File
@@ -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,
});
}
+3 -2
View File
@@ -1,5 +1,5 @@
{
"name": "examples",
"name": "@llamaindex/examples",
"private": true,
"version": "0.0.4",
"dependencies": {
@@ -11,6 +11,7 @@
"chromadb": "^1.8.1",
"commander": "^11.1.0",
"dotenv": "^16.4.1",
"js-tiktoken": "^1.0.10",
"llamaindex": "latest",
"mongodb": "^6.2.0",
"pathe": "^1.1.2"
@@ -18,7 +19,7 @@
"devDependencies": {
"@types/node": "^18.19.10",
"ts-node": "^10.9.2",
"typescript": "^5.3.3"
"typescript": "^5.4.3"
},
"scripts": {
"lint": "eslint ."
+2 -7
View File
@@ -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();
+2 -7
View File
@@ -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();
+1 -4
View File
@@ -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({
+11 -11
View File
@@ -4,11 +4,21 @@ import {
Document,
MetadataMode,
QdrantVectorStore,
Settings,
VectorStoreIndex,
serviceContextFromDefaults,
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();
@@ -38,16 +48,6 @@ async function main() {
console.log("Embedding documents and adding to index");
const index = await VectorStoreIndex.fromDocuments(docs, {
storageContext: ctx,
serviceContext: serviceContextFromDefaults({
callbackManager: new CallbackManager({
onRetrieve: (data) => {
console.log(
"The retrieved nodes are:",
data.nodes.map((node) => node.node.getContent(MetadataMode.NONE)),
);
},
}),
}),
});
console.log(
+1 -1
View File
@@ -17,6 +17,6 @@
"devDependencies": {
"@types/node": "^20.11.14",
"ts-node": "^10.9.2",
"typescript": "^5.3.3"
"typescript": "^5.4.3"
}
}
+5 -9
View File
@@ -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 });
+6 -10
View File
@@ -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();
+7 -11
View File
@@ -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 -5
View File
@@ -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");
}
+49
View File
@@ -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);
}
});
+4 -8
View File
@@ -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();
+11 -19
View File
@@ -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
View File
@@ -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?",
});
+8 -9
View File
@@ -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 }),
});
+10 -9
View File
@@ -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();
+7 -11
View File
@@ -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 });
+6 -8
View File
@@ -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;
+8 -11
View File
@@ -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();
+10 -19
View File
@@ -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, {
+4 -13
View File
@@ -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();
+1 -1
View File
@@ -27,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": {
+17
View File
@@ -1,5 +1,22 @@
# 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
+7 -2
View File
@@ -1,6 +1,6 @@
{
"name": "llamaindex",
"version": "0.2.1",
"version": "0.2.2",
"expectedMinorVersion": "2",
"license": "MIT",
"type": "module",
@@ -41,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",
@@ -67,6 +68,10 @@
"default": "./dist/cjs/index.js"
}
},
"./internal/*": {
"import": "./dist/not-allow.js",
"require": "./dist/cjs/not-allow.js"
},
"./*": {
"import": {
"types": "./dist/type/*.d.ts",
+16 -4
View File
@@ -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();
+18 -9
View File
@@ -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,
+6 -1
View File
@@ -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;
}
+2 -10
View File
@@ -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;
}
+215
View File
@@ -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();
-1
View File
@@ -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 =
-5
View File
@@ -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,
});
-5
View File
@@ -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");
-5
View File
@@ -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,
});
+1 -1
View File
@@ -60,7 +60,7 @@ export class ReActChatFormatter implements BaseAgentChatFormatter {
} else {
message = {
content: reasoningStep.getContent(),
role: "system",
role: "assistant",
};
}
-6
View File
@@ -1,5 +1,4 @@
import { randomUUID } from "@llamaindex/env";
import { CallbackManager } from "../../callbacks/CallbackManager.js";
import { AgentChatResponse } from "../../engines/chat/index.js";
import type { ChatResponse, LLM } from "../../llm/index.js";
import { OpenAI } from "../../llm/index.js";
@@ -23,7 +22,6 @@ type ReActAgentWorkerParams = {
maxInteractions?: number;
reactChatFormatter?: ReActChatFormatter | undefined;
outputParser?: ReActOutputParser | undefined;
callbackManager?: CallbackManager | undefined;
verbose?: boolean | undefined;
toolRetriever?: ObjectRetriever | undefined;
};
@@ -69,8 +67,6 @@ export class ReActAgentWorker implements AgentWorker {
reactChatFormatter: ReActChatFormatter;
outputParser: ReActOutputParser;
callbackManager: CallbackManager;
_getTools: (message: string) => Promise<BaseTool[]>;
constructor({
@@ -79,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();
-4
View File
@@ -1,5 +1,4 @@
import { randomUUID } from "@llamaindex/env";
import { CallbackManager } from "../../callbacks/CallbackManager.js";
import type { ChatEngineAgentParams } from "../../engines/chat/index.js";
import {
AgentChatResponse,
@@ -35,7 +34,6 @@ type AgentRunnerParams = {
state?: AgentState;
memory?: BaseMemory;
llm?: LLM;
callbackManager?: CallbackManager;
initTaskStateKwargs?: Record<string, any>;
deleteTaskOnFinish?: boolean;
defaultToolChoice?: string;
@@ -45,7 +43,6 @@ export class AgentRunner extends BaseAgentRunner {
agentWorker: AgentWorker;
state: AgentState;
memory: BaseMemory;
callbackManager: CallbackManager;
initTaskStateKwargs: Record<string, any>;
deleteTaskOnFinish: boolean;
defaultToolChoice: string;
@@ -63,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";
+125 -16
View File
@@ -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 })));
}
}
+11 -19
View File
@@ -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;
}
}
+81
View File
@@ -0,0 +1,81 @@
import type { PlatformApi } from "@llamaindex/cloud";
import { BaseNode, Document } from "../Node.js";
import { OpenAIEmbedding } from "../embeddings/OpenAIEmbedding.js";
import type { TransformComponent } from "../ingestion/types.js";
import { SimpleNodeParser } from "../nodeParsers/SimpleNodeParser.js";
export type GetPipelineCreateParams = {
pipelineName: string;
pipelineType: any; // TODO: PlatformApi.PipelineType is not exported
transformations?: TransformComponent[];
inputNodes?: BaseNode[];
};
function getTransformationConfig(
transformation: TransformComponent,
): PlatformApi.ConfiguredTransformationItem {
if (transformation instanceof SimpleNodeParser) {
return {
configurableTransformationType: "SENTENCE_AWARE_NODE_PARSER",
component: {
// TODO: API returns 422 if these parameters are included
// chunkSize: transformation.textSplitter.chunkSize, // TODO: set to public in SentenceSplitter
// chunkOverlap: transformation.textSplitter.chunkOverlap, // TODO: set to public in SentenceSplitter
// includeMetadata: transformation.includeMetadata,
// includePrevNextRel: transformation.includePrevNextRel,
},
};
}
if (transformation instanceof OpenAIEmbedding) {
return {
configurableTransformationType: "OPENAI_EMBEDDING",
component: {
modelName: transformation.model,
apiKey: transformation.apiKey,
embedBatchSize: transformation.embedBatchSize,
dimensions: transformation.dimensions,
},
};
}
throw new Error(`Unsupported transformation: ${typeof transformation}`);
}
function getDataSourceConfig(node: BaseNode): PlatformApi.DataSourceCreate {
if (node instanceof Document) {
return {
name: node.id_,
sourceType: "DOCUMENT",
component: {
id: node.id_,
text: node.text,
textTemplate: node.textTemplate,
startCharIdx: node.startCharIdx,
endCharIdx: node.endCharIdx,
metadataSeparator: node.metadataSeparator,
excludedEmbedMetadataKeys: node.excludedEmbedMetadataKeys,
excludedLlmMetadataKeys: node.excludedLlmMetadataKeys,
extraInfo: node.metadata,
},
};
}
throw new Error(`Unsupported node: ${typeof node}`);
}
export async function getPipelineCreate(
params: GetPipelineCreateParams,
): Promise<PlatformApi.PipelineCreate> {
const {
pipelineName,
pipelineType,
transformations = [],
inputNodes = [],
} = params;
return {
name: pipelineName,
configuredTransformations: transformations.map(getTransformationConfig),
dataSources: inputNodes.map(getDataSourceConfig),
dataSinks: [],
pipelineType,
};
}
+1
View File
@@ -1,5 +1,6 @@
import type { ServiceContext } from "../ServiceContext.js";
export const DEFAULT_PIPELINE_NAME = "default";
export const DEFAULT_PROJECT_NAME = "default";
export const DEFAULT_BASE_URL = "https://api.cloud.llamaindex.ai";
+9 -1
View File
@@ -3,12 +3,20 @@ import { getEnv } from "@llamaindex/env";
import type { ClientParams } from "./types.js";
import { DEFAULT_BASE_URL } from "./types.js";
function getBaseUrl(baseUrl?: string): string {
return baseUrl ?? getEnv("LLAMA_CLOUD_BASE_URL") ?? DEFAULT_BASE_URL;
}
export function getAppBaseUrl(baseUrl?: string): string {
return getBaseUrl(baseUrl).replace(/api\./, "");
}
export async function getClient({
apiKey,
baseUrl,
}: ClientParams = {}): Promise<PlatformApiClient> {
// Get the environment variables or use defaults
baseUrl = baseUrl ?? getEnv("LLAMA_CLOUD_BASE_URL") ?? DEFAULT_BASE_URL;
baseUrl = getBaseUrl(baseUrl);
apiKey = apiKey ?? getEnv("LLAMA_CLOUD_API_KEY");
const { PlatformApiClient } = await import("@llamaindex/cloud");
@@ -7,7 +7,7 @@ import {
} from "../../Prompt.js";
import type { Response } from "../../Response.js";
import type { ServiceContext } from "../../ServiceContext.js";
import { serviceContextFromDefaults } from "../../ServiceContext.js";
import { llmFromSettingsOrContext } from "../../Settings.js";
import type { ChatMessage, LLM } from "../../llm/index.js";
import { extractText, streamReducer } from "../../llm/utils.js";
import { PromptMixin } from "../../prompts/index.js";
@@ -48,7 +48,7 @@ export class CondenseQuestionChatEngine
this.queryEngine = init.queryEngine;
this.chatHistory = getHistory(init?.chatHistory);
this.llm = init?.serviceContext?.llm ?? serviceContextFromDefaults().llm;
this.llm = llmFromSettingsOrContext(init?.serviceContext);
this.condenseMessagePrompt =
init?.condenseMessagePrompt ?? defaultCondenseQuestionPrompt;
}
@@ -2,7 +2,6 @@ import { randomUUID } from "@llamaindex/env";
import type { NodeWithScore } from "../../Node.js";
import type { Response } from "../../Response.js";
import type { BaseRetriever } from "../../Retriever.js";
import type { ServiceContext } from "../../ServiceContext.js";
import type { Event } from "../../callbacks/CallbackManager.js";
import type { BaseNodePostprocessor } from "../../postprocessors/index.js";
import { PromptMixin } from "../../prompts/Mixin.js";
@@ -35,10 +34,11 @@ export class RetrieverQueryEngine
super();
this.retriever = retriever;
const serviceContext: ServiceContext | undefined =
this.retriever.getServiceContext();
this.responseSynthesizer =
responseSynthesizer || new ResponseSynthesizer({ serviceContext });
responseSynthesizer ||
new ResponseSynthesizer({
serviceContext: retriever.serviceContext,
});
this.preFilters = preFilters;
this.nodePostprocessors = nodePostprocessors || [];
}
@@ -1,7 +1,7 @@
import type { BaseNode } from "../../Node.js";
import { Response } from "../../Response.js";
import type { ServiceContext } from "../../ServiceContext.js";
import { serviceContextFromDefaults } from "../../ServiceContext.js";
import { llmFromSettingsOrContext } from "../../Settings.js";
import { PromptMixin } from "../../prompts/index.js";
import type { BaseSelector } from "../../selectors/index.js";
import { LLMSingleSelector } from "../../selectors/index.js";
@@ -55,8 +55,6 @@ async function combineResponses(
* A query engine that uses multiple query engines and selects the best one.
*/
export class RouterQueryEngine extends PromptMixin implements BaseQueryEngine {
serviceContext: ServiceContext;
private selector: BaseSelector;
private queryEngines: BaseQueryEngine[];
private metadatas: RouterQueryEngineMetadata[];
@@ -72,13 +70,12 @@ export class RouterQueryEngine extends PromptMixin implements BaseQueryEngine {
}) {
super();
this.serviceContext = init.serviceContext || serviceContextFromDefaults({});
this.selector = init.selector;
this.queryEngines = init.queryEngineTools.map((tool) => tool.queryEngine);
this.metadatas = init.queryEngineTools.map((tool) => ({
description: tool.description,
}));
this.summarizer = init.summarizer || new TreeSummarize(this.serviceContext);
this.summarizer = init.summarizer || new TreeSummarize(init.serviceContext);
this.verbose = init.verbose ?? false;
}
@@ -96,12 +93,14 @@ export class RouterQueryEngine extends PromptMixin implements BaseQueryEngine {
summarizer?: TreeSummarize;
verbose?: boolean;
}) {
const serviceContext =
init.serviceContext ?? serviceContextFromDefaults({});
const serviceContext = init.serviceContext;
return new RouterQueryEngine({
selector:
init.selector ?? new LLMSingleSelector({ llm: serviceContext.llm }),
init.selector ??
new LLMSingleSelector({
llm: llmFromSettingsOrContext(serviceContext),
}),
queryEngineTools: init.queryEngineTools,
serviceContext,
summarizer: init.summarizer,
@@ -4,7 +4,6 @@ import { TextNode } from "../../Node.js";
import { LLMQuestionGenerator } from "../../QuestionGenerator.js";
import type { Response } from "../../Response.js";
import type { ServiceContext } from "../../ServiceContext.js";
import { serviceContextFromDefaults } from "../../ServiceContext.js";
import type { Event } from "../../callbacks/CallbackManager.js";
import { PromptMixin } from "../../prompts/Mixin.js";
import type { BaseSynthesizer } from "../../synthesizers/index.js";
@@ -62,8 +61,7 @@ export class SubQuestionQueryEngine
responseSynthesizer?: BaseSynthesizer;
serviceContext?: ServiceContext;
}) {
const serviceContext =
init.serviceContext ?? serviceContextFromDefaults({});
const serviceContext = init.serviceContext;
const questionGen = init.questionGen ?? new LLMQuestionGenerator();
const responseSynthesizer =
+8 -8
View File
@@ -1,7 +1,7 @@
import { MetadataMode } from "../Node.js";
import type { ServiceContext } from "../ServiceContext.js";
import { serviceContextFromDefaults } from "../ServiceContext.js";
import type { ChatMessage } from "../llm/types.js";
import { llmFromSettingsOrContext } from "../Settings.js";
import type { ChatMessage, LLM } from "../llm/types.js";
import { PromptMixin } from "../prompts/Mixin.js";
import type { CorrectnessSystemPrompt } from "./prompts.js";
import {
@@ -24,20 +24,20 @@ type CorrectnessParams = {
/** Correctness Evaluator */
export class CorrectnessEvaluator extends PromptMixin implements BaseEvaluator {
private serviceContext: ServiceContext;
private scoreThreshold: number;
private parserFunction: (str: string) => [number, string];
private llm: LLM;
private correctnessPrompt: CorrectnessSystemPrompt =
defaultCorrectnessSystemPrompt;
constructor(params: CorrectnessParams) {
constructor(params?: CorrectnessParams) {
super();
this.serviceContext = params.serviceContext || serviceContextFromDefaults();
this.llm = llmFromSettingsOrContext(params?.serviceContext);
this.correctnessPrompt = defaultCorrectnessSystemPrompt;
this.scoreThreshold = params.scoreThreshold || 4.0;
this.parserFunction = params.parserFunction || defaultEvaluationParser;
this.scoreThreshold = params?.scoreThreshold ?? 4.0;
this.parserFunction = params?.parserFunction ?? defaultEvaluationParser;
}
_updatePrompts(prompts: {
@@ -80,7 +80,7 @@ export class CorrectnessEvaluator extends PromptMixin implements BaseEvaluator {
},
];
const evalResponse = await this.serviceContext.llm.chat({
const evalResponse = await this.llm.chat({
messages,
});

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