Compare commits

..

6 Commits

Author SHA1 Message Date
Emanuel Ferreira e658cfe0fb chore: fix llm 2024-03-18 11:29:59 -03:00
Emanuel Ferreira 8bad594b05 sync dependencies 2024-03-18 11:07:29 -03:00
Emanuel Ferreira 8ed8581f5b merge 2024-03-18 11:04:15 -03:00
Emanuel Ferreira ee2a3b83c9 minor changes (temp) 2024-03-18 11:00:00 -03:00
Emanuel Ferreira 8c3a2d9062 generics 2024-03-18 10:38:11 -03:00
Emanuel Ferreira e1ac089d39 u 2024-03-13 20:03:22 -03:00
235 changed files with 5312 additions and 6264 deletions
+2 -6
View File
@@ -1,13 +1,9 @@
{
"jsc": {
"parser": {
"syntax": "typescript",
"decorators": true
"syntax": "typescript"
},
"target": "esnext",
"transform": {
"decoratorVersion": "2022-03"
}
"target": "esnext"
},
"module": {
"type": "commonjs",
+2 -26
View File
@@ -2,13 +2,10 @@ name: Run Tests
on: [push, pull_request]
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
e2e:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v2
@@ -19,27 +16,6 @@ jobs:
cache: "pnpm"
- name: Install dependencies
run: pnpm install
- name: Run E2E Tests
run: pnpm run e2e
test:
strategy:
fail-fast: false
matrix:
node-version: [18.x, 20.x, 21.x]
name: Test on Node.js ${{ matrix.node-version }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v2
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: "pnpm"
- name: Install dependencies
run: pnpm install
- name: Run tests
run: pnpm run test
typecheck:
+2 -6
View File
@@ -1,12 +1,8 @@
{
"jsc": {
"parser": {
"syntax": "typescript",
"decorators": true
"syntax": "typescript"
},
"target": "esnext",
"transform": {
"decoratorVersion": "2022-03"
}
"target": "esnext"
}
}
+1 -11
View File
@@ -79,17 +79,7 @@ That should start a webserver which will serve the docs on https://localhost:300
Any changes you make should be reflected in the browser. If you need to regenerate the API docs and find that your TSDoc isn't getting the updates, feel free to remove apps/docs/api. It will automatically regenerate itself when you run pnpm start again.
## Changeset
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)
## Publishing
To publish a new version of the library, first create a new version:
+41 -62
View File
@@ -83,38 +83,30 @@ Check out our NextJS playground at https://llama-playground.vercel.app/. The sou
- [Node](/packages/core/src/Node.ts): The basic data building block. Most commonly, these are parts of the document split into manageable pieces that are small enough to be fed into an embedding model and LLM.
- [Embedding](/packages/core/src/embeddings/OpenAIEmbedding.ts): Embeddings are sets of floating point numbers which represent the data in a Node. By comparing the similarity of embeddings, we can derive an understanding of the similarity of two pieces of data. One use case is to compare the embedding of a question with the embeddings of our Nodes to see which Nodes may contain the data needed to answer that quesiton. Because the default service context is OpenAI, the default embedding is `OpenAIEmbedding`. If using different models, say through Ollama, use this [Embedding](/packages/core/src/embeddings/OllamaEmbedding.ts) (see all [here](/packages/core/src/embeddings)).
- [Embedding](/packages/core/src/Embedding.ts): Embeddings are sets of floating point numbers which represent the data in a Node. By comparing the similarity of embeddings, we can derive an understanding of the similarity of two pieces of data. One use case is to compare the embedding of a question with the embeddings of our Nodes to see which Nodes may contain the data needed to answer that quesiton.
- [Indices](/packages/core/src/indices/): Indices store the Nodes and the embeddings of those nodes. QueryEngines retrieve Nodes from these Indices using embedding similarity.
- [QueryEngine](/packages/core/src/engines/query/RetrieverQueryEngine.ts): Query engines are what generate the query you put in and give you back the result. Query engines generally combine a pre-built prompt with selected Nodes from your Index to give the LLM the context it needs to answer your query. To build a query engine from your Index (recommended), use the [`asQueryEngine`](/packages/core/src/indices/BaseIndex.ts) method on your Index. See all query engines [here](/packages/core/src/engines/query).
- [QueryEngine](/packages/core/src/QueryEngine.ts): Query engines are what generate the query you put in and give you back the result. Query engines generally combine a pre-built prompt with selected Nodes from your Index to give the LLM the context it needs to answer your query.
- [ChatEngine](/packages/core/src/engines/chat/SimpleChatEngine.ts): A ChatEngine helps you build a chatbot that will interact with your Indices. See all chat engines [here](/packages/core/src/engines/chat).
- [ChatEngine](/packages/core/src/ChatEngine.ts): A ChatEngine helps you build a chatbot that will interact with your Indices.
- [SimplePrompt](/packages/core/src/Prompt.ts): A simple standardized function call definition that takes in inputs and formats them in a template literal. SimplePrompts can be specialized using currying and combined using other SimplePrompt functions.
## Using NextJS
## Note: NextJS:
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).
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.
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";
```js
export const runtime = "nodejs"; // default
```
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", "@zilliz/milvus2-sdk-node"],
serverComponentsExternalPackages: ["pdf2json"],
},
webpack: (config) => {
config.resolve.alias = {
@@ -129,59 +121,46 @@ const nextConfig = {
module.exports = nextConfig;
```
### Using the Edge runtime
### NextJS with Milvus:
We publish a dedicated package (`@llamaindex/edge` instead of `llamaindex`) for using the Edge runtime. To use it, first install the package:
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.
```shell
pnpm install @llamaindex/edge
```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;
```
> _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 3 (Opus, Sonnet, and Haiku) and the legacy models (Claude 2 and Instant)
- Anthropic Claude Instant and Claude 2
- Groq LLMs
- Llama2 Chat LLMs (70B, 13B, and 7B parameters)
- MistralAI Chat LLMs
@@ -33,7 +33,7 @@ import {
SimpleToolNodeMapping,
SummaryIndex,
VectorStoreIndex,
Settings,
serviceContextFromDefaults,
storageContextFromDefaults,
} from "llamaindex";
```
@@ -147,10 +147,12 @@ 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
Settings.llm = new OpenAI({
const llm = new OpenAI({
model: "gpt-4",
});
const ctx = serviceContextFromDefaults({ llm });
const storageContext = await storageContextFromDefaults({
persistDir: "./storage",
});
@@ -187,12 +189,14 @@ 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,
});
@@ -274,6 +278,7 @@ const objectIndex = await ObjectIndex.fromObjects(
toolMapping,
VectorStoreIndex,
{
serviceContext,
storageContext,
},
);
@@ -3,14 +3,17 @@
To use HuggingFace embeddings, you need to import `HuggingFaceEmbedding` from `llamaindex`.
```ts
import { HuggingFaceEmbedding, Settings } from "llamaindex";
import { HuggingFaceEmbedding, serviceContextFromDefaults } from "llamaindex";
// Update Embed Model
Settings.embedModel = new HuggingFaceEmbedding();
const huggingFaceEmbeds = new HuggingFaceEmbedding();
const serviceContext = serviceContextFromDefaults({ embedModel: openaiEmbeds });
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const queryEngine = index.asQueryEngine();
@@ -26,8 +29,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:
```ts
Settings.embedModel = new HuggingFaceEmbedding({
```
const embedModel = new HuggingFaceEmbedding({
modelType: "BAAI/bge-small-en-v1.5",
quantized: false,
});
@@ -3,16 +3,21 @@
To use MistralAI embeddings, you need to import `MistralAIEmbedding` from `llamaindex`.
```ts
import { MistralAIEmbedding, Settings } from "llamaindex";
import { MistralAIEmbedding, serviceContextFromDefaults } from "llamaindex";
// Update Embed Model
Settings.embedModel = new MistralAIEmbedding({
const mistralEmbedModel = new MistralAIEmbedding({
apiKey: "<YOUR_API_KEY>",
});
const serviceContext = serviceContextFromDefaults({
embedModel: mistralEmbedModel,
});
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const queryEngine = index.asQueryEngine();
@@ -3,13 +3,19 @@
To use Ollama embeddings, you need to import `Ollama` from `llamaindex`.
```ts
import { Ollama, Settings } from "llamaindex";
import { Ollama, serviceContextFromDefaults } from "llamaindex";
Settings.embedModel = new Ollama();
const ollamaEmbedModel = new Ollama();
const serviceContext = serviceContextFromDefaults({
embedModel: ollamaEmbedModel,
});
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const queryEngine = index.asQueryEngine();
@@ -3,13 +3,19 @@
To use OpenAI embeddings, you need to import `OpenAIEmbedding` from `llamaindex`.
```ts
import { OpenAIEmbedding, Settings } from "llamaindex";
import { OpenAIEmbedding, serviceContextFromDefaults } from "llamaindex";
Settings.embedModel = new OpenAIEmbedding();
const openaiEmbedModel = new OpenAIEmbedding();
const serviceContext = serviceContextFromDefaults({
embedModel: openaiEmbedModel,
});
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const queryEngine = index.asQueryEngine();
@@ -3,15 +3,21 @@
To use together embeddings, you need to import `TogetherEmbedding` from `llamaindex`.
```ts
import { TogetherEmbedding, Settings } from "llamaindex";
import { TogetherEmbedding, serviceContextFromDefaults } from "llamaindex";
Settings.embedModel = new TogetherEmbedding({
const togetherEmbedModel = new TogetherEmbedding({
apiKey: "<YOUR_API_KEY>",
});
const serviceContext = serviceContextFromDefaults({
embedModel: togetherEmbedModel,
});
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const queryEngine = index.asQueryEngine();
+6 -5
View File
@@ -2,14 +2,14 @@
The embedding model in LlamaIndex is responsible for creating numerical representations of text. By default, LlamaIndex will use the `text-embedding-ada-002` model from OpenAI.
This can be explicitly updated through `Settings`
This can be explicitly set in the `ServiceContext` object.
```typescript
import { OpenAIEmbedding, Settings } from "llamaindex";
import { OpenAIEmbedding, serviceContextFromDefaults } from "llamaindex";
Settings.embedModel = new OpenAIEmbedding({
model: "text-embedding-ada-002",
});
const openaiEmbeds = new OpenAIEmbedding();
const serviceContext = serviceContextFromDefaults({ embedModel: openaiEmbeds });
```
## Local Embedding
@@ -19,3 +19,4 @@ For local embeddings, you can use the [HuggingFace](./available_embeddings/huggi
## API Reference
- [OpenAIEmbedding](../../api/classes/OpenAIEmbedding.md)
- [ServiceContext](../../api/interfaces//ServiceContext.md)
@@ -21,15 +21,23 @@ export OPENAI_API_KEY=your-api-key
Import the required modules:
```ts
import { CorrectnessEvaluator, OpenAI, Settings } from "llamaindex";
import {
CorrectnessEvaluator,
OpenAI,
serviceContextFromDefaults,
} from "llamaindex";
```
Let's setup gpt-4 for better results:
```ts
Settings.llm = new OpenAI({
const llm = new OpenAI({
model: "gpt-4",
});
const ctx = serviceContextFromDefaults({
llm,
});
```
```ts
@@ -41,7 +49,9 @@ const response = ` Certainly! Albert Einstein's theory of relativity consists of
However, general relativity, published in 1915, extended these ideas to include the effects of magnetism. According to general relativity, gravity is not a force between masses but rather the result of the warping of space and time by magnetic fields generated by massive objects. Massive objects, such as planets and stars, create magnetic fields that cause a curvature in spacetime, and smaller objects follow curved paths in response to this magnetic curvature. This concept is often illustrated using the analogy of a heavy ball placed on a rubber sheet with magnets underneath, causing it to create a depression that other objects (representing smaller masses) naturally move towards due to magnetic attraction.
`;
const evaluator = new CorrectnessEvaluator();
const evaluator = new CorrectnessEvaluator({
serviceContext: ctx,
});
const result = await evaluator.evaluateResponse({
query,
@@ -28,16 +28,20 @@ import {
FaithfulnessEvaluator,
OpenAI,
VectorStoreIndex,
Settings,
serviceContextFromDefaults,
} from "llamaindex";
```
Let's setup gpt-4 for better results:
```ts
Settings.llm = new OpenAI({
const llm = new OpenAI({
model: "gpt-4",
});
const ctx = serviceContextFromDefaults({
llm,
});
```
Now, let's create a vector index and query engine with documents and query engine respectively. Then, we can evaluate the response with the query and response from the query engine.:
@@ -59,7 +63,9 @@ Now, let's evaluate the response:
```ts
const query = "How did New York City get its name?";
const evaluator = new FaithfulnessEvaluator();
const evaluator = new FaithfulnessEvaluator({
serviceContext: ctx,
});
const response = await queryEngine.query({
query,
@@ -21,15 +21,23 @@ export OPENAI_API_KEY=your-api-key
Import the required modules:
```ts
import { RelevancyEvaluator, OpenAI, Settings } from "llamaindex";
import {
RelevancyEvaluator,
OpenAI,
serviceContextFromDefaults,
} from "llamaindex";
```
Let's setup gpt-4 for better results:
```ts
Settings.llm = new OpenAI({
const llm = new OpenAI({
model: "gpt-4",
});
const ctx = serviceContextFromDefaults({
llm,
});
```
Now, let's create a vector index and query engine with documents and query engine respectively. Then, we can evaluate the response with the query and response from the query engine.:
@@ -51,8 +59,6 @@ const response = await queryEngine.query({
query,
});
const evaluator = new RelevancyEvaluator();
const result = await evaluator.evaluateResponse({
query,
response: response,
@@ -3,11 +3,13 @@
## Usage
```ts
import { Anthropic, Settings } from "llamaindex";
import { Anthropic, serviceContextFromDefaults } from "llamaindex";
Settings.llm = new Anthropic({
const anthropicLLM = new Anthropic({
apiKey: "<YOUR_API_KEY>",
});
const serviceContext = serviceContextFromDefaults({ llm: anthropicLLM });
```
## Load and index documents
@@ -17,7 +19,9 @@ For this example, we will use a single document. In a real-world scenario, you w
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
```
## Query
@@ -35,17 +39,28 @@ const results = await queryEngine.query({
## Full Example
```ts
import { Anthropic, Document, VectorStoreIndex, Settings } from "llamaindex";
Settings.llm = new Anthropic({
apiKey: "<YOUR_API_KEY>",
});
import {
Anthropic,
Document,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
async function main() {
// Create an instance of the Anthropic LLM
const anthropicLLM = new Anthropic({
apiKey: "<YOUR_API_KEY>",
});
// Create a service context
const serviceContext = serviceContextFromDefaults({ llm: anthropicLLM });
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// Create a query engine
const queryEngine = index.asQueryEngine({
@@ -15,9 +15,11 @@ export AZURE_OPENAI_DEPLOYMENT="gpt-4" # or some other deployment name
## Usage
```ts
import { OpenAI, Settings } from "llamaindex";
import { OpenAI, serviceContextFromDefaults } from "llamaindex";
Settings.llm = new OpenAI({ model: "gpt-4", temperature: 0 });
const azureOpenaiLLM = new OpenAI({ model: "gpt-4", temperature: 0 });
const serviceContext = serviceContextFromDefaults({ llm: azureOpenaiLLM });
```
## Load and index documents
@@ -27,7 +29,9 @@ For this example, we will use a single document. In a real-world scenario, you w
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
```
## Query
@@ -45,15 +49,26 @@ const results = await queryEngine.query({
## Full Example
```ts
import { OpenAI, Document, VectorStoreIndex, Settings } from "llamaindex";
Settings.llm = new OpenAI({ model: "gpt-4", temperature: 0 });
import {
OpenAI,
Document,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
async function main() {
// Create an instance of the LLM
const azureOpenaiLLM = new OpenAI({ model: "gpt-4", temperature: 0 });
// Create a service context
const serviceContext = serviceContextFromDefaults({ llm: azureOpenaiLLM });
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// get retriever
const retriever = index.asRetriever();
@@ -5,11 +5,13 @@ Fireworks.ai focus on production use cases for open source LLMs, offering speed
## Usage
```ts
import { FireworksLLM, Settings } from "llamaindex";
import { FireworksLLM, serviceContextFromDefaults } from "llamaindex";
Settings.llm = new FireworksLLM({
const fireworksLLM = new FireworksLLM({
apiKey: "<YOUR_API_KEY>",
});
const serviceContext = serviceContextFromDefaults({ llm: fireworksLLM });
```
## Load and index documents
@@ -21,7 +23,9 @@ const reader = new PDFReader();
const documents = await reader.loadData("../data/brk-2022.pdf");
// Split text and create embeddings. Store them in a VectorStoreIndex
const index = await VectorStoreIndex.fromDocuments(documents);
const index = await VectorStoreIndex.fromDocuments(documents, {
serviceContext,
});
```
## Query
@@ -14,13 +14,15 @@ export GROQ_API_KEY=<your-api-key>
The initialize the Groq module.
```ts
import { Groq, Settings } from "llamaindex";
import { Groq, serviceContextFromDefaults } from "llamaindex";
Settings.llm = new Groq({
const groq = new Groq({
// If you do not wish to set your API key in the environment, you may
// configure your API key when you initialize the Groq class.
// apiKey: "<your-api-key>",
});
const serviceContext = serviceContextFromDefaults({ llm: groq });
```
## Load and index documents
@@ -30,7 +32,9 @@ For this example, we will use a single document. In a real-world scenario, you w
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
```
## Query
@@ -3,24 +3,32 @@
## Usage
```ts
import { Ollama, Settings } from "llamaindex";
import { Ollama, serviceContextFromDefaults } from "llamaindex";
Settings.llm = new LlamaDeuce({ chatStrategy: DeuceChatStrategy.META });
const llama2LLM = new LlamaDeuce({ chatStrategy: DeuceChatStrategy.META });
const serviceContext = serviceContextFromDefaults({ llm: llama2LLM });
```
## Usage with Replication
```ts
import { Ollama, ReplicateSession, Settings } from "llamaindex";
import {
Ollama,
ReplicateSession,
serviceContextFromDefaults,
} from "llamaindex";
const replicateSession = new ReplicateSession({
replicateKey,
});
Settings.llm = new LlamaDeuce({
const llama2LLM = new LlamaDeuce({
chatStrategy: DeuceChatStrategy.META,
replicateSession,
});
const serviceContext = serviceContextFromDefaults({ llm: llama2LLM });
```
## Load and index documents
@@ -30,7 +38,9 @@ For this example, we will use a single document. In a real-world scenario, you w
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
```
## Query
@@ -48,16 +58,26 @@ const results = await queryEngine.query({
## Full Example
```ts
import { LlamaDeuce, Document, VectorStoreIndex, Settings } from "llamaindex";
// Use the LlamaDeuce LLM
Settings.llm = new LlamaDeuce({ chatStrategy: DeuceChatStrategy.META });
import {
LlamaDeuce,
Document,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
async function main() {
// Create an instance of the LLM
const llama2LLM = new LlamaDeuce({ chatStrategy: DeuceChatStrategy.META });
// Create a service context
const serviceContext = serviceContextFromDefaults({ llm: mistralLLM });
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// get retriever
const retriever = index.asRetriever();
@@ -3,12 +3,14 @@
## Usage
```ts
import { Ollama, Settings } from "llamaindex";
import { Ollama, serviceContextFromDefaults } from "llamaindex";
Settings.llm = new MistralAI({
const mistralLLM = new MistralAI({
model: "mistral-tiny",
apiKey: "<YOUR_API_KEY>",
});
const serviceContext = serviceContextFromDefaults({ llm: mistralLLM });
```
## Load and index documents
@@ -18,7 +20,9 @@ For this example, we will use a single document. In a real-world scenario, you w
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
```
## Query
@@ -36,16 +40,26 @@ const results = await queryEngine.query({
## Full Example
```ts
import { MistralAI, Document, VectorStoreIndex, Settings } from "llamaindex";
// Use the MistralAI LLM
Settings.llm = new MistralAI({ model: "mistral-tiny" });
import {
MistralAI,
Document,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
async function main() {
// Create an instance of the LLM
const mistralLLM = new MistralAI({ model: "mistral-tiny" });
// Create a service context
const serviceContext = serviceContextFromDefaults({ llm: mistralLLM });
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// get retriever
const retriever = index.asRetriever();
@@ -3,10 +3,14 @@
## Usage
```ts
import { Ollama, Settings } from "llamaindex";
import { Ollama, serviceContextFromDefaults } from "llamaindex";
Settings.llm = ollamaLLM;
Settings.embedModel = ollamaLLM;
const ollamaLLM = new Ollama({ model: "llama2", temperature: 0.75 });
const serviceContext = serviceContextFromDefaults({
llm: ollamaLLM,
embedModel: ollamaLLM,
});
```
## Load and index documents
@@ -16,7 +20,9 @@ For this example, we will use a single document. In a real-world scenario, you w
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
```
## Query
@@ -34,23 +40,33 @@ const results = await queryEngine.query({
## Full Example
```ts
import { Ollama, Document, VectorStoreIndex, Settings } from "llamaindex";
import {
Ollama,
Document,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
import fs from "fs/promises";
const ollama = new Ollama({ model: "llama2", temperature: 0.75 });
// Use Ollama LLM and Embed Model
Settings.llm = ollama;
Settings.embedModel = ollama;
async function main() {
// Create an instance of the LLM
const ollamaLLM = new Ollama({ model: "llama2", temperature: 0.75 });
const essay = await fs.readFile("./paul_graham_essay.txt", "utf-8");
// Create a service context
const serviceContext = serviceContextFromDefaults({
embedModel: ollamaLLM, // prevent 'Set OpenAI Key in OPENAI_API_KEY env variable' error
llm: ollamaLLM,
});
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// get retriever
const retriever = index.asRetriever();
@@ -1,9 +1,11 @@
# OpenAI
```ts
import { OpenAI, Settings } from "llamaindex";
import { OpenAI, serviceContextFromDefaults } from "llamaindex";
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0, apiKey: <YOUR_API_KEY> });
const openaiLLM = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0, apiKey: <YOUR_API_KEY> });
const serviceContext = serviceContextFromDefaults({ llm: openaiLLM });
```
You can setup the apiKey on the environment variables, like:
@@ -19,7 +21,9 @@ For this example, we will use a single document. In a real-world scenario, you w
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
```
## Query
@@ -37,16 +41,26 @@ const results = await queryEngine.query({
## Full Example
```ts
import { OpenAI, Document, VectorStoreIndex, Settings } from "llamaindex";
// Use the OpenAI LLM
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0 });
import {
OpenAI,
Document,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
async function main() {
// Create an instance of the LLM
const openaiLLM = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0 });
// Create a service context
const serviceContext = serviceContextFromDefaults({ llm: openaiLLM });
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// get retriever
const retriever = index.asRetriever();
@@ -3,11 +3,13 @@
## Usage
```ts
import { Portkey, Settings } from "llamaindex";
import { Portkey, serviceContextFromDefaults } from "llamaindex";
Settings.llm = new Portkey({
const portkeyLLM = new Portkey({
apiKey: "<YOUR_API_KEY>",
});
const serviceContext = serviceContextFromDefaults({ llm: portkeyLLM });
```
## Load and index documents
@@ -17,7 +19,9 @@ For this example, we will use a single document. In a real-world scenario, you w
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
```
## Query
@@ -35,19 +39,28 @@ const results = await queryEngine.query({
## Full Example
```ts
import { Portkey, Document, VectorStoreIndex, Settings } from "llamaindex";
// Use the Portkey LLM
Settings.llm = new Portkey({
apiKey: "<YOUR_API_KEY>",
});
import {
Portkey,
Document,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
async function main() {
// Create a document
// Create an instance of the LLM
const portkeyLLM = new Portkey({
apiKey: "<YOUR_API_KEY>",
});
// Create a service context
const serviceContext = serviceContextFromDefaults({ llm: portkeyLLM });
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// get retriever
const retriever = index.asRetriever();
@@ -3,11 +3,13 @@
## Usage
```ts
import { TogetherLLM, Settings } from "llamaindex";
import { TogetherLLM, serviceContextFromDefaults } from "llamaindex";
Settings.llm = new TogetherLLM({
const togetherLLM = new TogetherLLM({
apiKey: "<YOUR_API_KEY>",
});
const serviceContext = serviceContextFromDefaults({ llm: togetherLLM });
```
## Load and index documents
@@ -17,7 +19,9 @@ For this example, we will use a single document. In a real-world scenario, you w
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
```
## Query
@@ -35,17 +39,28 @@ const results = await queryEngine.query({
## Full Example
```ts
import { TogetherLLM, Document, VectorStoreIndex, Settings } from "llamaindex";
Settings.llm = new TogetherLLM({
apiKey: "<YOUR_API_KEY>",
});
import {
TogetherLLM,
Document,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
async function main() {
// Create an instance of the LLM
const togetherLLM = new TogetherLLM({
apiKey: "<YOUR_API_KEY>",
});
// Create a service context
const serviceContext = serviceContextFromDefaults({ llm: togetherLLM });
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// get retriever
const retriever = index.asRetriever();
+6 -3
View File
@@ -6,12 +6,14 @@ sidebar_position: 3
The LLM is responsible for reading text and generating natural language responses to queries. By default, LlamaIndex.TS uses `gpt-3.5-turbo`.
The LLM can be explicitly updated through `Settings`.
The LLM can be explicitly set in the `ServiceContext` object.
```typescript
import { OpenAI, Settings } from "llamaindex";
import { OpenAI, serviceContextFromDefaults } from "llamaindex";
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0 });
const openaiLLM = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0 });
const serviceContext = serviceContextFromDefaults({ llm: openaiLLM });
```
## Azure OpenAI
@@ -33,3 +35,4 @@ For local LLMs, currently we recommend the use of [Ollama](./available_llms/olla
## API Reference
- [OpenAI](../api/classes/OpenAI.md)
- [ServiceContext](../api/interfaces//ServiceContext.md)
+4 -3
View File
@@ -4,14 +4,15 @@ sidebar_position: 4
# NodeParser
The `NodeParser` in LlamaIndex is responsible for splitting `Document` objects into more manageable `Node` objects. When you call `.fromDocuments()`, the `NodeParser` from the `Settings` is used to do this automatically for you. Alternatively, you can use it to split documents ahead of time.
The `NodeParser` in LlamaIndex is responsible for splitting `Document` objects into more manageable `Node` objects. When you call `.fromDocuments()`, the `NodeParser` from the `ServiceContext` is used to do this automatically for you. Alternatively, you can use it to split documents ahead of time.
```typescript
import { Document, SimpleNodeParser } from "llamaindex";
const nodeParser = new SimpleNodeParser();
Settings.nodeParser = nodeParser;
const nodes = nodeParser.getNodesFromDocuments([
new Document({ text: "I am 10 years old. John is 20 years old." }),
]);
```
## TextSplitter
@@ -18,7 +18,7 @@ import {
Document,
OpenAI,
VectorStoreIndex,
Settings,
serviceContextFromDefaults,
} from "llamaindex";
```
@@ -29,9 +29,13 @@ For this example, we will use a single document. In a real-world scenario, you w
```ts
const document = new Document({ text: essay, id_: "essay" });
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 });
const serviceContext = serviceContextFromDefaults({
llm: new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 }),
});
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
```
## Increase similarity topK to retrieve more results
@@ -58,10 +58,7 @@ Most commonly, node-postprocessors will be used in a query engine, where they ar
### Using Node Postprocessors in a Query Engine
```ts
import { Node, NodeWithScore, SimilarityPostprocessor, CohereRerank, Settings } from "llamaindex";
// Use OpenAI LLM
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 });
import { Node, NodeWithScore, SimilarityPostprocessor, CohereRerank } from "llamaindex";
const nodes: NodeWithScore[] = [
{
@@ -82,6 +79,14 @@ const reranker = new CohereRerank({
const document = new Document({ text: "essay", id_: "essay" });
const serviceContext = serviceContextFromDefaults({
llm: new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 }),
});
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const queryEngine = index.asQueryEngine({
nodePostprocessors: [processor, reranker],
});
+7 -3
View File
@@ -31,11 +31,13 @@ The first method is to create a new instance of `ResponseSynthesizer` (or the mo
```ts
// Create an instance of response synthesizer
const responseSynthesizer = new ResponseSynthesizer({
responseBuilder: new CompactAndRefine(undefined, newTextQaPrompt),
responseBuilder: new CompactAndRefine(serviceContext, newTextQaPrompt),
});
// Create index
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// Query the index
const queryEngine = index.asQueryEngine({ responseSynthesizer });
@@ -51,7 +53,9 @@ The second method is that most of the modules in LlamaIndex have a `getPrompts`
```ts
// Create index
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// Query the index
const queryEngine = index.asQueryEngine();
@@ -54,13 +54,12 @@ You can create a `ChromaVectorStore` to store the documents:
```ts
const chromaVS = new ChromaVectorStore({ collectionName });
const storageContext = await storageContextFromDefaults({
const serviceContext = await storageContextFromDefaults({
vectorStore: chromaVS,
});
const index = await VectorStoreIndex.fromDocuments(docs, {
storageContext: storageContext,
storageContext: serviceContext,
});
```
@@ -18,7 +18,7 @@ import {
SimpleNodeParser,
SummaryIndex,
VectorStoreIndex,
Settings,
serviceContextFromDefaults,
} from "llamaindex";
```
@@ -34,13 +34,17 @@ const documents = await new SimpleDirectoryReader().loadData({
## Service Context
Next, we need to define some basic rules and parse the documents into nodes. We will use the `SimpleNodeParser` to parse the documents into nodes and `Settings` to define the rules (eg. LLM API key, chunk size, etc.):
Next, we need to define some basic rules and parse the documents into nodes. We will use the `SimpleNodeParser` to parse the documents into nodes and `ServiceContext` to define the rules (eg. LLM API key, chunk size, etc.):
```ts
Settings.llm = new OpenAI();
Settings.nodeParser = new SimpleNodeParser({
const nodeParser = new SimpleNodeParser({
chunkSize: 1024,
});
const serviceContext = serviceContextFromDefaults({
nodeParser,
llm: new OpenAI(),
});
```
## Creating Indices
@@ -48,8 +52,13 @@ Settings.nodeParser = new SimpleNodeParser({
Next, we need to create some indices. We will create a `VectorStoreIndex` and a `SummaryIndex`:
```ts
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
const summaryIndex = await SummaryIndex.fromDocuments(documents);
const vectorIndex = await VectorStoreIndex.fromDocuments(documents, {
serviceContext,
});
const summaryIndex = await SummaryIndex.fromDocuments(documents, {
serviceContext,
});
```
## Creating Query Engines
@@ -79,6 +88,7 @@ const queryEngine = RouterQueryEngine.fromDefaults({
description: "Useful for retrieving specific context from Abramov",
},
],
serviceContext,
});
```
@@ -107,23 +117,34 @@ import {
SimpleNodeParser,
SummaryIndex,
VectorStoreIndex,
Settings,
serviceContextFromDefaults,
} from "llamaindex";
Settings.llm = new OpenAI();
Settings.nodeParser = new SimpleNodeParser({
chunkSize: 1024,
});
async function main() {
// Load documents from a directory
const documents = await new SimpleDirectoryReader().loadData({
directoryPath: "node_modules/llamaindex/examples",
});
// Parse the documents into nodes
const nodeParser = new SimpleNodeParser({
chunkSize: 1024,
});
// Create a service context
const serviceContext = serviceContextFromDefaults({
nodeParser,
llm: new OpenAI(),
});
// Create indices
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
const summaryIndex = await SummaryIndex.fromDocuments(documents);
const vectorIndex = await VectorStoreIndex.fromDocuments(documents, {
serviceContext,
});
const summaryIndex = await SummaryIndex.fromDocuments(documents, {
serviceContext,
});
// Create query engines
const vectorQueryEngine = vectorIndex.asQueryEngine();
@@ -141,6 +162,7 @@ async function main() {
description: "Useful for retrieving specific context from Abramov",
},
],
serviceContext,
});
// Query the router query engine
-2
View File
@@ -1,2 +0,0 @@
label: Recipes
position: 3
-14
View File
@@ -1,14 +0,0 @@
# Cost Analysis
This page shows how to track LLM cost using APIs.
## Callback Manager
The callback manager is a class that manages the callback functions.
You can register `llm-start`, 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>
+13 -13
View File
@@ -15,28 +15,28 @@
"typecheck": "tsc"
},
"dependencies": {
"@docusaurus/core": "^3.2.1",
"@docusaurus/remark-plugin-npm2yarn": "^3.2.1",
"@llamaindex/examples": "workspace:*",
"@mdx-js/react": "^3.0.1",
"@docusaurus/core": "^3.1.1",
"@llamaindex/env": "workspace:*",
"@docusaurus/remark-plugin-npm2yarn": "^3.1.1",
"@mdx-js/react": "^3.0.0",
"clsx": "^2.1.0",
"postcss": "^8.4.38",
"postcss": "^8.4.33",
"prism-react-renderer": "^2.3.1",
"raw-loader": "^4.0.2",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@docusaurus/module-type-aliases": "3.2.0",
"@docusaurus/preset-classic": "^3.2.1",
"@docusaurus/theme-classic": "^3.2.1",
"@docusaurus/types": "^3.2.1",
"@tsconfig/docusaurus": "^2.0.3",
"@types/node": "^18.19.31",
"@docusaurus/module-type-aliases": "3.1.0",
"@docusaurus/preset-classic": "^3.1.1",
"@docusaurus/theme-classic": "^3.1.1",
"@docusaurus/types": "^3.1.1",
"@tsconfig/docusaurus": "^2.0.2",
"@types/node": "^18.19.10",
"docusaurus-plugin-typedoc": "^0.22.0",
"typedoc": "^0.25.13",
"typedoc": "^0.25.7",
"typedoc-plugin-markdown": "^3.17.1",
"typescript": "^5.4.4"
"typescript": "^5.3.3"
},
"browserslist": {
"production": [
-29
View File
@@ -1,29 +0,0 @@
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);
+16 -6
View File
@@ -6,11 +6,11 @@ import {
OpenAI,
OpenAIAgent,
QueryEngineTool,
Settings,
SimpleNodeParser,
SimpleToolNodeMapping,
SummaryIndex,
VectorStoreIndex,
serviceContextFromDefaults,
storageContextFromDefaults,
} from "llamaindex";
@@ -18,8 +18,6 @@ import { extractWikipedia } from "./helpers/extractWikipedia";
const wikiTitles = ["Brazil", "Canada"];
Settings.llm = new OpenAI({ model: "gpt-4" });
async function main() {
await extractWikipedia(wikiTitles);
@@ -32,6 +30,11 @@ async function main() {
countryDocs[title] = document;
}
const llm = new OpenAI({
model: "gpt-4",
});
const serviceContext = serviceContextFromDefaults({ llm });
const storageContext = await storageContextFromDefaults({
persistDir: "./storage",
});
@@ -51,11 +54,13 @@ 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,
});
@@ -85,7 +90,8 @@ async function main() {
const agent = new OpenAIAgent({
tools: queryEngineTools,
llm: new OpenAI({ model: "gpt-4" }),
llm,
verbose: true,
});
documentAgents[title] = agent;
@@ -120,11 +126,15 @@ async function main() {
allTools,
toolMapping,
VectorStoreIndex,
{
serviceContext,
},
);
const topAgent = new OpenAIAgent({
toolRetriever: await objectIndex.asRetriever({}),
llm: new OpenAI({ model: "gpt-4" }),
llm,
verbose: true,
prefixMessages: [
{
content:
@@ -143,4 +153,4 @@ async function main() {
});
}
void main();
main();
+2 -1
View File
@@ -59,6 +59,7 @@ async function main() {
// Create an OpenAIAgent with the function tools
const agent = new OpenAIAgent({
tools: [functionTool, functionTool2],
verbose: true,
});
// Chat with the agent
@@ -70,6 +71,6 @@ async function main() {
console.log(String(response));
}
void main().then(() => {
main().then(() => {
console.log("Done");
});
+2 -1
View File
@@ -29,6 +29,7 @@ async function main() {
// Create an OpenAIAgent with the function tools
const agent = new OpenAIAgent({
tools: [queryEngineTool],
verbose: true,
});
// Chat with the agent
@@ -40,6 +41,6 @@ async function main() {
console.log(String(response));
}
void main().then(() => {
main().then(() => {
console.log("Done");
});
+4 -9
View File
@@ -1,4 +1,4 @@
import { Anthropic, FunctionTool, ReActAgent } from "llamaindex";
import { FunctionTool, ReActAgent } from "llamaindex";
// Define a function to sum two numbers
function sumNumbers({ a, b }: { a: number; b: number }): number {
@@ -56,15 +56,10 @@ async function main() {
parameters: divideJSON,
});
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
model: "claude-3-opus",
});
// Create an ReActAgent with the function tools
// Create an OpenAIAgent with the function tools
const agent = new ReActAgent({
llm: anthropic,
tools: [functionTool, functionTool2],
verbose: true,
});
// Chat with the agent
@@ -76,6 +71,6 @@ async function main() {
console.log(String(response));
}
void main().then(() => {
main().then(() => {
console.log("Done");
});
+2 -1
View File
@@ -59,6 +59,7 @@ async function main() {
// Create an OpenAIAgent with the function tools
const agent = new OpenAIAgent({
tools: [functionTool, functionTool2],
verbose: true,
});
// Create a task to sum and divide numbers
@@ -89,6 +90,6 @@ async function main() {
}
}
void main().then(() => {
main().then(() => {
console.log("Done");
});
+2 -1
View File
@@ -29,6 +29,7 @@ async function main() {
// Create an OpenAIAgent with the function tools
const agent = new OpenAIAgent({
tools: [queryEngineTool],
verbose: true,
});
const task = agent.createTask("What was his salary?");
@@ -58,6 +59,6 @@ async function main() {
}
}
void main().then(() => {
main().then(() => {
console.log("Done");
});
+2 -1
View File
@@ -59,6 +59,7 @@ async function main() {
// Create an OpenAIAgent with the function tools
const agent = new ReActAgent({
tools: [functionTool, functionTool2],
verbose: true,
});
const task = agent.createTask("Divide 16 by 2 then add 20");
@@ -84,6 +85,6 @@ async function main() {
}
}
void main().then(() => {
main().then(() => {
console.log("Done");
});
+2 -1
View File
@@ -59,6 +59,7 @@ async function main() {
// Create an OpenAIAgent with the function tools
const agent = new OpenAIAgent({
tools: [functionTool, functionTool2],
verbose: false,
});
const stream = await agent.chat({
@@ -71,6 +72,6 @@ async function main() {
}
}
void main().then(() => {
main().then(() => {
console.log("\nDone");
});
-27
View File
@@ -1,27 +0,0 @@
import { OpenAI, OpenAIAgent, WikipediaTool } from "llamaindex";
async function main() {
const llm = new OpenAI({ model: "gpt-4-turbo" });
const wikiTool = new WikipediaTool();
// Create an OpenAIAgent with the Wikipedia tool
const agent = new OpenAIAgent({
llm,
tools: [wikiTool],
});
// Chat with the agent
const response = await agent.chat({
message: "Who was Goethe?",
stream: true,
});
for await (const chunk of response.response) {
process.stdout.write(chunk.response);
}
}
(async function () {
await main();
console.log("\nDone");
})();
+1 -1
View File
@@ -55,4 +55,4 @@ async function main() {
}
}
void main();
main();
+1 -1
View File
@@ -27,4 +27,4 @@ async function main() {
}
}
void main();
main();
+8 -3
View File
@@ -1,4 +1,8 @@
import { AstraDBVectorStore, VectorStoreIndex } from "llamaindex";
import {
AstraDBVectorStore,
serviceContextFromDefaults,
VectorStoreIndex,
} from "llamaindex";
const collectionName = "movie_reviews";
@@ -7,7 +11,8 @@ async function main() {
const astraVS = new AstraDBVectorStore({ contentKey: "reviewtext" });
await astraVS.connect(collectionName);
const index = await VectorStoreIndex.fromVectorStore(astraVS);
const ctx = serviceContextFromDefaults();
const index = await VectorStoreIndex.fromVectorStore(astraVS, ctx);
const retriever = await index.asRetriever({ similarityTopK: 20 });
@@ -23,4 +28,4 @@ async function main() {
}
}
void main();
main();
+5 -5
View File
@@ -4,18 +4,18 @@ import readline from "node:readline/promises";
import {
ContextChatEngine,
Document,
Settings,
serviceContextFromDefaults,
VectorStoreIndex,
} from "llamaindex";
import essay from "./essay";
// Update chunk size
Settings.chunkSize = 512;
async function main() {
const document = new Document({ text: essay });
const index = await VectorStoreIndex.fromDocuments([document]);
const serviceContext = serviceContextFromDefaults({ chunkSize: 512 });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const retriever = index.asRetriever();
retriever.similarityTopK = 5;
const chatEngine = new ContextChatEngine({ retriever });
+1 -12
View File
@@ -1,18 +1,7 @@
import { stdin as input, stdout as output } from "node:process";
import readline from "node:readline/promises";
import {
OpenAI,
Settings,
SimpleChatEngine,
SummaryChatHistory,
} from "llamaindex";
if (process.env.NODE_ENV === "development") {
Settings.callbackManager.on("llm-end", (event) => {
console.log("callers chain", event.reason?.computedCallers);
});
}
import { OpenAI, SimpleChatEngine, SummaryChatHistory } from "llamaindex";
async function main() {
// Set maxTokens to 75% of the context window size of 4096
+1 -1
View File
@@ -54,4 +54,4 @@ async function main() {
}
}
void main();
main();
+1 -1
View File
@@ -37,4 +37,4 @@ async function main() {
}
}
void main();
main();
-8
View File
@@ -31,11 +31,3 @@ 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
```
-44
View File
@@ -1,44 +0,0 @@
import fs from "node:fs/promises";
import { stdin as input, stdout as output } from "node:process";
import readline from "node:readline/promises";
import { Document, LlamaCloudIndex } from "llamaindex";
async function main() {
const path = "node_modules/llamaindex/examples/abramov.txt";
const essay = await fs.readFile(path, "utf-8");
// Create Document object with essay
const document = new Document({ text: essay, id_: path });
const index = await LlamaCloudIndex.fromDocuments({
documents: [document],
name: "test",
projectName: "default",
apiKey: process.env.LLAMA_CLOUD_API_KEY,
baseUrl: process.env.LLAMA_CLOUD_BASE_URL,
});
const queryEngine = index.asQueryEngine({
denseSimilarityTopK: 5,
});
const rl = readline.createInterface({ input, output });
while (true) {
const query = await rl.question("Query: ");
const stream = await queryEngine.query({
query,
stream: true,
});
console.log();
for await (const chunk of stream) {
process.stdout.write(chunk.response);
}
}
}
main().catch(console.error);
-34
View File
@@ -1,34 +0,0 @@
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);
+17 -6
View File
@@ -1,10 +1,21 @@
import { CorrectnessEvaluator, OpenAI, Settings } from "llamaindex";
// Update llm to use OpenAI
Settings.llm = new OpenAI({ model: "gpt-4" });
import {
CorrectnessEvaluator,
OpenAI,
serviceContextFromDefaults,
} from "llamaindex";
async function main() {
const evaluator = new CorrectnessEvaluator();
const llm = new OpenAI({
model: "gpt-4",
});
const ctx = serviceContextFromDefaults({
llm,
});
const evaluator = new CorrectnessEvaluator({
serviceContext: ctx,
});
const query =
"Can you explain the theory of relativity proposed by Albert Einstein in detail?";
@@ -22,4 +33,4 @@ However, general relativity, published in 1915, extended these ideas to include
console.log(result);
}
void main();
main();
+13 -6
View File
@@ -2,15 +2,22 @@ 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 evaluator = new FaithfulnessEvaluator();
const llm = new OpenAI({
model: "gpt-4",
});
const ctx = serviceContextFromDefaults({
llm,
});
const evaluator = new FaithfulnessEvaluator({
serviceContext: ctx,
});
const documents = [
new Document({
@@ -36,4 +43,4 @@ async function main() {
console.log(result);
}
void main();
main();
+13 -7
View File
@@ -2,16 +2,22 @@ import {
Document,
OpenAI,
RelevancyEvaluator,
Settings,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
Settings.llm = new OpenAI({
model: "gpt-4",
});
async function main() {
const evaluator = new RelevancyEvaluator();
const llm = new OpenAI({
model: "gpt-4",
});
const ctx = serviceContextFromDefaults({
llm,
});
const evaluator = new RelevancyEvaluator({
serviceContext: ctx,
});
const documents = [
new Document({
@@ -37,4 +43,4 @@ async function main() {
console.log(result);
}
void main();
main();
+17 -7
View File
@@ -1,20 +1,30 @@
import fs from "node:fs/promises";
import { Document, Groq, Settings, VectorStoreIndex } from "llamaindex";
// Update llm to use Groq
Settings.llm = new Groq({
apiKey: process.env.GROQ_API_KEY,
});
import {
Document,
Groq,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
async function main() {
// Create an instance of the LLM
const groq = new Groq({
apiKey: process.env.GROQ_API_KEY,
});
// Create a service context
const serviceContext = serviceContextFromDefaults({ llm: groq });
// Load essay from abramov.txt in Node
const path = "node_modules/llamaindex/examples/abramov.txt";
const essay = await fs.readFile(path, "utf-8");
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// get retriever
const retriever = index.asRetriever();
+12 -7
View File
@@ -4,15 +4,10 @@ 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";
@@ -22,8 +17,18 @@ 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]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// Query the index
const queryEngine = index.asQueryEngine();
+3 -1
View File
@@ -36,7 +36,9 @@ async function main() {
],
});
console.log(response.message.content);
const json = JSON.parse(response.message.content);
console.log(json);
}
main().catch(console.error);
+13 -8
View File
@@ -1,21 +1,26 @@
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]);
await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
})();
+1 -1
View File
@@ -23,4 +23,4 @@ async function main() {
}
}
void main();
main();
+8 -3
View File
@@ -1,4 +1,8 @@
import { MilvusVectorStore, VectorStoreIndex } from "llamaindex";
import {
MilvusVectorStore,
serviceContextFromDefaults,
VectorStoreIndex,
} from "llamaindex";
const collectionName = "movie_reviews";
@@ -6,7 +10,8 @@ async function main() {
try {
const milvus = new MilvusVectorStore({ collection: collectionName });
const index = await VectorStoreIndex.fromVectorStore(milvus);
const ctx = serviceContextFromDefaults();
const index = await VectorStoreIndex.fromVectorStore(milvus, ctx);
const retriever = await index.asRetriever({ similarityTopK: 20 });
@@ -22,4 +27,4 @@ async function main() {
}
}
void main();
main();
+15 -9
View File
@@ -1,18 +1,15 @@
import * as fs from "fs/promises";
import {
BaseEmbedding,
Document,
LLM,
MistralAI,
MistralAIEmbedding,
Settings,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
// Update embed model
Settings.embedModel = new MistralAIEmbedding();
// Update llm to use MistralAI
Settings.llm = new MistralAI({ model: "mistral-tiny" });
async function rag(query: string) {
async function rag(llm: LLM, embedModel: BaseEmbedding, query: string) {
// Load essay from abramov.txt in Node
const path = "node_modules/llamaindex/examples/abramov.txt";
@@ -21,7 +18,12 @@ async function rag(query: string) {
// Create Document object with essay
const document = new Document({ text: essay, id_: path });
const index = await VectorStoreIndex.fromDocuments([document]);
// Split text and create embeddings. Store them in a VectorStoreIndex
const serviceContext = serviceContextFromDefaults({ llm, embedModel });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// Query the index
const queryEngine = index.asQueryEngine();
@@ -58,6 +60,10 @@ async function rag(query: string) {
}
// rag
const ragResponse = await rag("What did the author do in college?");
const ragResponse = await rag(
llm,
embedding,
"What did the author do in college?",
);
console.log(ragResponse);
})();
+1 -1
View File
@@ -61,4 +61,4 @@ async function main() {
}
}
void main();
main();
+1 -1
View File
@@ -31,4 +31,4 @@ async function importJsonToMongo() {
}
// Run the import function
void importJsonToMongo();
importJsonToMongo();
+8 -4
View File
@@ -1,6 +1,10 @@
/* eslint-disable turbo/no-undeclared-env-vars */
import * as dotenv from "dotenv";
import { MongoDBAtlasVectorSearch, VectorStoreIndex } from "llamaindex";
import {
MongoDBAtlasVectorSearch,
serviceContextFromDefaults,
VectorStoreIndex,
} from "llamaindex";
import { MongoClient } from "mongodb";
// Load environment variables from local .env file
@@ -8,7 +12,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!,
@@ -16,7 +20,7 @@ async function query() {
indexName: process.env.MONGODB_VECTOR_INDEX!,
});
const index = await VectorStoreIndex.fromVectorStore(store);
const index = await VectorStoreIndex.fromVectorStore(store, serviceContext);
const retriever = index.asRetriever({ similarityTopK: 20 });
const queryEngine = index.asQueryEngine({ retriever });
@@ -27,4 +31,4 @@ async function query() {
await client.close();
}
void query();
query();
+1 -1
View File
@@ -30,4 +30,4 @@ async function main() {
console.log(`Similarity between "${text2}" and the image is ${sim2}`);
}
void main();
main();
+11 -9
View File
@@ -1,16 +1,12 @@
import {
Settings,
ServiceContext,
serviceContextFromDefaults,
SimpleDirectoryReader,
VectorStoreIndex,
storageContextFromDefaults,
VectorStoreIndex,
} 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();
@@ -18,7 +14,7 @@ async function getRuntime(func: any) {
return end - start;
}
async function generateDatasource() {
async function generateDatasource(serviceContext: ServiceContext) {
console.log(`Generating storage...`);
// Split documents, create embeddings and store them in the storage context
const ms = await getRuntime(async () => {
@@ -30,6 +26,7 @@ async function generateDatasource() {
storeImages: true,
});
await VectorStoreIndex.fromDocuments(documents, {
serviceContext,
storageContext,
});
});
@@ -37,7 +34,12 @@ async function generateDatasource() {
}
async function main() {
await generateDatasource();
const serviceContext = serviceContextFromDefaults({
chunkSize: 512,
chunkOverlap: 20,
});
await generateDatasource(serviceContext);
console.log("Finished generating storage.");
}
+23 -20
View File
@@ -1,28 +1,17 @@
import {
CallbackManager,
ImageDocument,
ImageType,
MultiModalResponseSynthesizer,
NodeWithScore,
OpenAI,
Settings,
ServiceContext,
VectorStoreIndex,
serviceContextFromDefaults,
storageContextFromDefaults,
} from "llamaindex";
// Update chunk size and overlap
Settings.chunkSize = 512;
Settings.chunkOverlap = 20;
// Update llm
Settings.llm = new OpenAI({ model: "gpt-4-turbo", maxTokens: 512 });
// Update callbackManager
Settings.callbackManager = new CallbackManager({
onRetrieve: ({ query, nodes }) => {
console.log(`Retrieved ${nodes.length} nodes for query: ${query}`);
},
});
export async function createIndex() {
export async function createIndex(serviceContext: ServiceContext) {
// set up vector store index with two vector stores, one for text, the other for images
const storageContext = await storageContextFromDefaults({
persistDir: "storage",
@@ -31,16 +20,30 @@ export async function createIndex() {
return await VectorStoreIndex.init({
nodes: [],
storageContext,
serviceContext,
});
}
async function main() {
const images: ImageType[] = [];
const index = await createIndex();
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 queryEngine = index.asQueryEngine({
responseSynthesizer: new MultiModalResponseSynthesizer(),
responseSynthesizer: new MultiModalResponseSynthesizer({ serviceContext }),
retriever: index.asRetriever({ similarityTopK: 3, imageSimilarityTopK: 1 }),
});
const result = await queryEngine.query({
+7 -6
View File
@@ -1,17 +1,17 @@
import {
ImageNode,
Settings,
serviceContextFromDefaults,
storageContextFromDefaults,
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,6 +19,7 @@ export async function createIndex() {
return await VectorStoreIndex.init({
nodes: [],
storageContext,
serviceContext,
});
}
+1 -1
View File
@@ -21,4 +21,4 @@ Sub-header content
console.log(splits);
}
void main();
main();
+6 -7
View File
@@ -1,5 +1,5 @@
{
"name": "@llamaindex/examples",
"name": "examples",
"private": true,
"version": "0.0.4",
"dependencies": {
@@ -10,16 +10,15 @@
"@zilliz/milvus2-sdk-node": "^2.3.5",
"chromadb": "^1.8.1",
"commander": "^11.1.0",
"dotenv": "^16.4.5",
"js-tiktoken": "^1.0.10",
"llamaindex": "workspace:latest",
"mongodb": "^6.5.0",
"dotenv": "^16.4.1",
"llamaindex": "latest",
"mongodb": "^6.2.0",
"pathe": "^1.1.2"
},
"devDependencies": {
"@types/node": "^18.19.31",
"@types/node": "^18.19.10",
"ts-node": "^10.9.2",
"typescript": "^5.4.4"
"typescript": "^5.3.3"
},
"scripts": {
"lint": "eslint ."
+3 -3
View File
@@ -32,7 +32,7 @@ async function main(args: any) {
console.log(`Found ${count} files`);
console.log(`Importing contents from ${count} files in ${sourceDir}`);
const fileName = "";
var fileName = "";
try {
// Passing callback fn to the ctor here
// will enable looging to console.
@@ -42,7 +42,7 @@ async function main(args: any) {
const pgvs = new PGVectorStore();
pgvs.setCollection(sourceDir);
await pgvs.clearCollection();
pgvs.clearCollection();
const ctx = await storageContextFromDefaults({ vectorStore: pgvs });
@@ -65,4 +65,4 @@ async function main(args: any) {
process.exit(0);
}
void main(process.argv).catch((err) => console.error(err));
main(process.argv).catch((err) => console.error(err));
+7 -2
View File
@@ -1,4 +1,8 @@
import { PGVectorStore, VectorStoreIndex } from "llamaindex";
import {
PGVectorStore,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
async function main() {
const readline = require("readline").createInterface({
@@ -11,7 +15,8 @@ async function main() {
// Optional - set your collection name, default is no filter on this field.
// pgvs.setCollection();
const index = await VectorStoreIndex.fromVectorStore(pgvs);
const ctx = serviceContextFromDefaults();
const index = await VectorStoreIndex.fromVectorStore(pgvs, ctx);
// Query the index
const queryEngine = await index.asQueryEngine();
+2 -2
View File
@@ -32,7 +32,7 @@ async function main(args: any) {
console.log(`Found ${count} files`);
console.log(`Importing contents from ${count} files in ${sourceDir}`);
const fileName = "";
var fileName = "";
try {
// Passing callback fn to the ctor here
// will enable looging to console.
@@ -63,4 +63,4 @@ async function main(args: any) {
process.exit(0);
}
void main(process.argv).catch((err) => console.error(err));
main(process.argv).catch((err) => console.error(err));
+7 -2
View File
@@ -1,4 +1,8 @@
import { PineconeVectorStore, VectorStoreIndex } from "llamaindex";
import {
PineconeVectorStore,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
async function main() {
const readline = require("readline").createInterface({
@@ -9,7 +13,8 @@ async function main() {
try {
const pcvs = new PineconeVectorStore();
const index = await VectorStoreIndex.fromVectorStore(pcvs);
const ctx = serviceContextFromDefaults();
const index = await VectorStoreIndex.fromVectorStore(pcvs, ctx);
// Query the index
const queryEngine = await index.asQueryEngine();
+5 -6
View File
@@ -4,6 +4,7 @@ import {
TreeSummarize,
TreeSummarizePrompt,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
const treeSummarizePrompt: TreeSummarizePrompt = ({ context, query }) => {
@@ -26,18 +27,16 @@ async function main() {
const query = "The quick brown fox jumps over the lazy dog";
const ctx = serviceContextFromDefaults({});
const responseSynthesizer = new ResponseSynthesizer({
responseBuilder: new TreeSummarize(),
responseBuilder: new TreeSummarize(ctx),
});
const queryEngine = index.asQueryEngine({
responseSynthesizer,
});
console.log({
promptsToUse: queryEngine.getPrompts(),
});
queryEngine.updatePrompts({
"responseSynthesizer:summaryTemplate": treeSummarizePrompt,
});
@@ -45,4 +44,4 @@ async function main() {
await queryEngine.query({ query });
}
void main();
main();
+12 -12
View File
@@ -4,21 +4,11 @@ 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();
@@ -48,6 +38,16 @@ 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(
@@ -79,4 +79,4 @@ async function main() {
}
}
void main();
main();
+1 -1
View File
@@ -17,6 +17,6 @@
"devDependencies": {
"@types/node": "^20.11.14",
"ts-node": "^10.9.2",
"typescript": "^5.4.3"
"typescript": "^5.3.3"
}
}
+9 -5
View File
@@ -2,21 +2,25 @@ import {
CompactAndRefine,
OpenAI,
ResponseSynthesizer,
Settings,
serviceContextFromDefaults,
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);
const index = await VectorStoreIndex.fromDocuments(documents, {
serviceContext,
});
const csvPrompt = ({ context = "", query = "" }) => {
return `The following CSV file is loaded from ${path}
@@ -28,7 +32,7 @@ Given the CSV file, generate me Typescript code to answer the question: ${query}
};
const responseSynthesizer = new ResponseSynthesizer({
responseBuilder: new CompactAndRefine(undefined, csvPrompt),
responseBuilder: new CompactAndRefine(serviceContext, csvPrompt),
});
const queryEngine = index.asQueryEngine({ responseSynthesizer });
+1 -1
View File
@@ -20,4 +20,4 @@ async function main() {
console.log(`Test query > ${SAMPLE_QUERY}:\n`, response.toString());
}
void main();
main();
+1 -1
View File
@@ -20,4 +20,4 @@ async function main() {
console.log(`Test query > ${SAMPLE_QUERY}:\n`, response.toString());
}
void main();
main();
+10 -6
View File
@@ -1,15 +1,17 @@
import { FireworksEmbedding, FireworksLLM, VectorStoreIndex } from "llamaindex";
import { PDFReader } from "llamaindex/readers/PDFReader";
import { Settings } from "llamaindex";
import { serviceContextFromDefaults } from "llamaindex";
Settings.llm = new FireworksLLM({
const embedModel = new FireworksEmbedding({
model: "nomic-ai/nomic-embed-text-v1.5",
});
const llm = new FireworksLLM({
model: "accounts/fireworks/models/mixtral-8x7b-instruct",
});
Settings.embedModel = new FireworksEmbedding({
model: "nomic-ai/nomic-embed-text-v1.5",
});
const serviceContext = serviceContextFromDefaults({ llm, embedModel });
async function main() {
// Load PDF
@@ -17,7 +19,9 @@ 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);
const index = await VectorStoreIndex.fromDocuments(documents, {
serviceContext,
});
// Query the index
const queryEngine = index.asQueryEngine();
+11 -7
View File
@@ -1,26 +1,30 @@
import { OpenAI, OpenAIEmbedding, VectorStoreIndex } from "llamaindex";
import { PDFReader } from "llamaindex/readers/PDFReader";
import { Settings } from "llamaindex";
import { serviceContextFromDefaults } from "llamaindex";
// Update llm and embedModel
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 });
Settings.embedModel = new OpenAIEmbedding({
const 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);
const index = await VectorStoreIndex.fromDocuments(documents, {
serviceContext,
});
// Query the index
const queryEngine = index.asQueryEngine();
const response = await queryEngine.query({
query: "What mistakes did Warren E. Buffett make?",
});
+5 -1
View File
@@ -1,14 +1,16 @@
import { execSync } from "child_process";
import {
PDFReader,
VectorStoreIndex,
serviceContextFromDefaults,
storageContextFromDefaults,
VectorStoreIndex,
} from "llamaindex";
const STORAGE_DIR = "./cache";
async function main() {
// write the index to disk
const serviceContext = serviceContextFromDefaults({});
const storageContext = await storageContextFromDefaults({
persistDir: `${STORAGE_DIR}`,
});
@@ -16,6 +18,7 @@ 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
@@ -26,6 +29,7 @@ async function main() {
});
await VectorStoreIndex.init({
storageContext: readOnlyStorageContext,
serviceContext,
});
console.log("read only index successfully opened");
}
-50
View File
@@ -1,50 +0,0 @@
import { encodingForModel } from "js-tiktoken";
import { OpenAI } from "llamaindex";
import { Settings } from "llamaindex/Settings";
import { extractText } from "llamaindex/llm/utils";
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(extractText(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(extractText(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);
void 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);
}
});
+8 -4
View File
@@ -2,18 +2,22 @@ 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 index = await VectorStoreIndex.fromDocuments([document]);
const serviceContext = serviceContextFromDefaults({
llm: new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 }),
});
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const retriever = index.asRetriever();
+21 -13
View File
@@ -1,31 +1,38 @@
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",
});
// Create indices
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
// Parse the documents into nodes
const nodeParser = new SimpleNodeParser({
chunkSize: 1024,
});
const summaryIndex = await SummaryIndex.fromDocuments(documents);
// 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,
});
// Create query engines
const vectorQueryEngine = vectorIndex.asQueryEngine();
@@ -43,6 +50,7 @@ async function main() {
description: "Useful for retrieving specific context from Abramov",
},
],
serviceContext,
});
// Query the router query engine
@@ -65,4 +73,4 @@ async function main() {
});
}
void main().then(() => console.log("Done"));
main().then(() => console.log("Done"));
+12 -11
View File
@@ -3,25 +3,27 @@ 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,
});
@@ -29,7 +31,6 @@ async function main() {
const queryEngine = index.asQueryEngine({
nodePostprocessors: [new MetadataReplacementPostProcessor("window")],
});
const response = await queryEngine.query({
query: "What did the author do in college?",
});
+1 -1
View File
@@ -13,4 +13,4 @@ async function main() {
console.log(chunks);
}
void main();
main();
+9 -8
View File
@@ -1,21 +1,22 @@
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]);
const index = await SummaryIndex.fromDocuments([document], {
serviceContext,
});
const queryEngine = index.asQueryEngine({
retriever: index.asRetriever({ mode: SummaryRetrieverMode.LLM }),
});
+9 -10
View File
@@ -2,20 +2,12 @@ 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) {
@@ -26,7 +18,14 @@ async function main() {
const document = new Document({ text: essay, id_: path });
const index = await VectorStoreIndex.fromDocuments([document]);
const serviceContext = serviceContextFromDefaults({
llm: new TogetherLLM({ model: "mistralai/Mixtral-8x7B-Instruct-v0.1" }),
embedModel: new TogetherEmbedding(),
});
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const queryEngine = index.asQueryEngine();
-47
View File
@@ -1,47 +0,0 @@
import { ChatResponseChunk, OpenAI } from "llamaindex";
async function main() {
const llm = new OpenAI({ model: "gpt-4-turbo" });
const args: Parameters<typeof llm.chat>[0] = {
additionalChatOptions: {
tool_choice: "auto",
},
messages: [
{
content: "Who was Goethe?",
role: "user",
},
],
tools: [
{
metadata: {
name: "wikipedia_tool",
description: "A tool that uses a query engine to search Wikipedia.",
parameters: {
type: "object",
properties: {
query: {
type: "string",
description: "The query to search for",
},
},
required: ["query"],
},
},
},
],
};
const stream = await llm.chat({ ...args, stream: true });
let chunk: ChatResponseChunk | null = null;
for await (chunk of stream) {
process.stdout.write(chunk.delta);
}
console.log(chunk?.additionalKwargs?.toolCalls[0]);
}
(async function () {
await main();
console.log("Done");
})();
+11 -7
View File
@@ -2,17 +2,14 @@ import fs from "node:fs/promises";
import {
Anthropic,
anthropicTextQaPrompt,
CompactAndRefine,
Document,
ResponseSynthesizer,
Settings,
serviceContextFromDefaults,
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";
@@ -23,11 +20,18 @@ 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(undefined, anthropicTextQaPrompt),
responseBuilder: new CompactAndRefine(
serviceContext,
anthropicTextQaPrompt,
),
});
const index = await VectorStoreIndex.fromDocuments([document]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// Query the index
const queryEngine = index.asQueryEngine({ responseSynthesizer });
+8 -6
View File
@@ -2,21 +2,23 @@ import {
Document,
OpenAI,
RetrieverQueryEngine,
Settings,
serviceContextFromDefaults,
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 index = await VectorStoreIndex.fromDocuments([document]);
const serviceContext = serviceContextFromDefaults({
llm: new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 }),
});
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const retriever = index.asRetriever();
retriever.similarityTopK = 5;
+11 -8
View File
@@ -3,16 +3,10 @@ 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";
@@ -22,8 +16,17 @@ 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]);
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// Query the index
const queryEngine = index.asQueryEngine();
+19 -10
View File
@@ -2,7 +2,7 @@ import {
OpenAI,
ResponseSynthesizer,
RetrieverQueryEngine,
Settings,
serviceContextFromDefaults,
TextNode,
TreeSummarize,
VectorIndexRetriever,
@@ -14,12 +14,6 @@ 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.
*/
@@ -152,11 +146,25 @@ 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);
const vectorStoreIndex = await VectorStoreIndex.fromVectorStore(
vectorStore,
serviceContext,
);
const retriever = new VectorIndexRetriever({
index: vectorStoreIndex,
@@ -164,7 +172,8 @@ async function main() {
});
const responseSynthesizer = new ResponseSynthesizer({
responseBuilder: new TreeSummarize(),
serviceContext,
responseBuilder: new TreeSummarize(serviceContext),
});
return new RetrieverQueryEngine(retriever, responseSynthesizer, {
+13 -4
View File
@@ -1,8 +1,11 @@
import fs from "node:fs/promises";
import { Document, OpenAI, Settings, VectorStoreIndex } from "llamaindex";
Settings.llm = new OpenAI({ model: "gpt-4" });
import {
Document,
OpenAI,
serviceContextFromDefaults,
VectorStoreIndex,
} from "llamaindex";
async function main() {
// Load essay from abramov.txt in Node
@@ -12,7 +15,13 @@ async function main() {
// Create Document object with essay
const document = new Document({ text: essay, id_: path });
const index = await VectorStoreIndex.fromDocuments([document]);
// 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,
});
// Query the index
const queryEngine = index.asQueryEngine();

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