Compare commits

..

29 Commits

Author SHA1 Message Date
github-actions[bot] 52c47cada3 Release 0.3.13 (#856)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-05-22 16:31:23 +07:00
Marcus Schiesser 9216312b11 docs: fix changsets and format 2024-05-22 11:25:09 +02:00
Philipp Serrer 660a2b3495 fix: text before heading in markdown reader (#864) 2024-05-22 16:49:52 +08:00
Henry Heng 6d21092805 Fix/Agent llm initialization (#866) 2024-05-21 15:35:18 -07:00
Laurie Voss fb2c1fa917 Docs update: (#857)
Co-authored-by: Yi Ding <yi.s.ding@gmail.com>
2024-05-20 13:53:23 -07:00
Parham Saidi 37525df529 feat: Gemini Access via Vertex AI (#838) 2024-05-20 17:09:25 +07:00
Marcus Schiesser a1f24753d9 docs: systemprompt changeset 2024-05-20 11:05:20 +02:00
Thuc Pham aa0f586330 feat: allow adding system prompt to chat engine (#855)
Co-authored-by: Marcus Schiesser <mail@marcusschiesser.de>
2024-05-20 15:57:58 +07:00
Alex Yang ff03139799 Revert "fix: cloudflare dev (#851)"
`@xenova/transformers` only ship node.js and browser output, it's not possible to load this in edge runtime and workerd

This reverts commit 34fb1d8992.
2024-05-17 12:11:31 -07:00
Marcus Schiesser 1b1081b9c9 feat: bind embedding models to vec stores and use vector store map (#821)
Co-authored-by: Alex Yang <himself65@outlook.com>
2024-05-17 22:30:33 +07:00
Thuc Pham 047ae07e74 feat: add local hugging face LLM (#854) 2024-05-17 16:01:10 +07:00
github-actions[bot] d8aa29a115 Release 0.3.12 (#852)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-05-16 17:45:09 -07:00
Alex Yang 34fb1d8992 fix: cloudflare dev (#851) 2024-05-16 17:25:32 -07:00
github-actions[bot] c517f35526 Release 0.3.11 (#835)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-05-16 16:35:57 -07:00
Alex Yang e072c45393 fix: remove non-standard API pipeline (#850) 2024-05-16 16:31:48 -07:00
Alex Yang 51241865f8 feat: improve BaseNode (#848) 2024-05-16 16:29:16 -07:00
Thuc Pham 10c83485d2 fix: allow custom task query for agents (#846) 2024-05-16 12:48:50 -07:00
Alex Yang 1e6a18ad2d build: fix jsr release 2024-05-15 18:03:22 -07:00
Alex Yang 9e133ac10d refactor: remove defaultFS from parameters (#841) 2024-05-15 17:37:51 -07:00
Alex Yang ba217eec2c chore: remove test.py (#842) 2024-05-15 16:47:39 -07:00
Alex Yang 64ef70b735 build: ignore example project 2024-05-15 16:10:08 -07:00
Alex Yang 6615aaa4ab chore: use pnpm format
Using `pnpm format:write` will cause two commits which is not expected
2024-05-15 13:11:53 -07:00
Parham Saidi 447105a6dc fix: Gemini text chat - prevent sending broken messageContent and history (#822) 2024-05-15 16:33:55 +07:00
Huu Le (Lee) 320be3fab6 chore: rollback chromadb version to 1.7.3 (#834)
Co-authored-by: Marcus Schiesser <mail@marcusschiesser.de>
2024-05-14 16:07:44 +07:00
Alex Yang bbd9f85a45 chore: bump openai (#833) 2024-05-13 12:53:12 -07:00
github-actions[bot] 5f29ba5e2c Release 0.3.10 (#832)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-05-13 10:53:59 -07:00
Alex Yang 4aba02eb82 feat: support gpt4-o (#831) 2024-05-13 10:51:10 -07:00
Alex Yang 75736ad01b build: release output files 2024-05-10 14:08:21 -07:00
Alex Yang 68a508fcd0 test: fix check host (#829) 2024-05-10 11:07:40 -07:00
146 changed files with 16372 additions and 1982 deletions
+1 -2
View File
@@ -76,8 +76,7 @@ jobs:
- name: Run Type Check
run: pnpm run type-check
- name: Run Circular Dependency Check
run: pnpm run circular-check
working-directory: ./packages/core
run: pnpm dlx turbo run circular-check
- uses: actions/upload-artifact@v3
if: failure()
with:
+1 -1
View File
@@ -1,3 +1,3 @@
pnpm format:write
pnpm format
pnpm lint
npx lint-staged
+34
View File
@@ -1,5 +1,39 @@
# docs
## 0.0.21
### Patch Changes
- Updated dependencies [1b1081b]
- Updated dependencies [37525df]
- Updated dependencies [660a2b3]
- Updated dependencies [a1f2475]
- llamaindex@0.3.13
## 0.0.20
### Patch Changes
- Updated dependencies [34fb1d8]
- llamaindex@0.3.12
## 0.0.19
### Patch Changes
- Updated dependencies [e072c45]
- Updated dependencies [9e133ac]
- Updated dependencies [447105a]
- Updated dependencies [320be3f]
- llamaindex@0.3.11
## 0.0.18
### Patch Changes
- Updated dependencies [4aba02e]
- llamaindex@0.3.10
## 0.0.17
### Patch Changes
+1 -1
View File
@@ -1,2 +1,2 @@
label: Examples
position: 2
position: 3
+1 -1
View File
@@ -1,5 +1,5 @@
---
sidebar_position: 1
sidebar_position: 2
---
import CodeBlock from "@theme/CodeBlock";
+77
View File
@@ -0,0 +1,77 @@
# Local LLMs
LlamaIndex.TS supports OpenAI and [other remote LLM APIs](other_llms). You can also run a local LLM on your machine!
## Using a local model via Ollama
The easiest way to run a local LLM is via the great work of our friends at [Ollama](https://ollama.com/), who provide a simple to use client that will download, install and run a [growing range of models](https://ollama.com/library) for you.
### Install Ollama
They provide a one-click installer for Mac, Linux and Windows on their [home page](https://ollama.com/).
### Pick and run a model
Since we're going to be doing agentic work, we'll need a very capable model, but the largest models are hard to run on a laptop. We think `mixtral 8x7b` is a good balance between power and resources, but `llama3` is another great option. You can run Mixtral by running
```bash
ollama run mixtral:8x7b
```
The first time you run it will also automatically download and install the model for you.
### Switch the LLM in your code
To tell LlamaIndex to use a local LLM, use the `Settings` object:
```javascript
Settings.llm = new Ollama({
model: "mixtral:8x7b",
});
```
### Use local embeddings
If you're doing retrieval-augmented generation, LlamaIndex.TS will also call out to OpenAI to index and embed your data. To be entirely local, you can use a local embedding model like this:
```javascript
Settings.embedModel = new HuggingFaceEmbedding({
modelType: "BAAI/bge-small-en-v1.5",
quantized: false,
});
```
The first time this runs it will download the embedding model to run it.
### Try it out
With a local LLM and local embeddings in place, you can perform RAG as usual and everything will happen on your machine without calling an API:
```typescript
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 });
// Split text and create embeddings. Store them in a VectorStoreIndex
const index = await VectorStoreIndex.fromDocuments([document]);
// Query the index
const queryEngine = index.asQueryEngine();
const response = await queryEngine.query({
query: "What did the author do in college?",
});
// Output response
console.log(response.toString());
}
main().catch(console.error);
```
You can see the [full example file](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/vectorIndexLocal.ts).
+19 -3
View File
@@ -1,7 +1,23 @@
---
sidebar_position: 5
sidebar_position: 1
---
# More examples
# See all examples
You can check out more examples in the [examples](https://github.com/run-llama/LlamaIndexTS/tree/main/examples) folder of the repository.
Our GitHub repository has a wealth of examples to explore and try out. You can check out our [examples folder](https://github.com/run-llama/LlamaIndexTS/tree/main/examples) to see them all at once, or browse the pages in this section for some selected highlights.
## Check out all examples
It may be useful to check out all the examples at once so you can try them out locally. To do this into a folder called `my-new-project`, run these commands:
```bash npm2yarn
npx degit run-llama/LlamaIndexTS/examples my-new-project
cd my-new-project
npm install
```
Then you can run any example in the folder with `tsx`, e.g.:
```bash npm2yarn
npx tsx ./vectorIndex.ts
```
+41
View File
@@ -0,0 +1,41 @@
import CodeBlock from "@theme/CodeBlock";
import CodeSource from "!raw-loader!../../../../examples/mistral";
# Using other LLM APIs
By default LlamaIndex.TS uses OpenAI's LLMs and embedding models, but we support [lots of other LLMs](../modules/llms) including models from Mistral (Mistral, Mixtral), Anthropic (Claude) and Google (Gemini).
If you don't want to use an API at all you can [run a local model](../../examples/local_llm)
## Using another LLM
You can specify what LLM LlamaIndex.TS will use on the `Settings` object, like this:
```typescript
import { MistralAI, Settings } from "llamaindex";
Settings.llm = new MistralAI({
model: "mistral-tiny",
apiKey: "<YOUR_API_KEY>",
});
```
You can see examples of other APIs we support by checking out "Available LLMs" in the sidebar of our [LLMs section](../modules/llms).
## Using another embedding model
A frequent gotcha when trying to use a different API as your LLM is that LlamaIndex will also by default index and embed your data using OpenAI's embeddings. To completely switch away from OpenAI you will need to set your embedding model as well, for example:
```typescript
import { MistralAIEmbedding, Settings } from "llamaindex";
Settings.embedModel = new MistralAIEmbedding();
```
We support [many different embeddings](../modules/embeddings).
## Full example
This example uses Mistral's `mistral-tiny` model as the LLM and Mistral for embeddings as well.
<CodeBlock language="ts">{CodeSource}</CodeBlock>
@@ -4,7 +4,7 @@ sidebar_position: 2
# Environments
LlamaIndex currently officially supports NodeJS 18 and NodeJS 20.
We support Node.JS versions 18, 20 and 22, with experimental support for Deno, Bun and Vercel Edge functions.
## NextJS App Router
+13 -42
View File
@@ -4,45 +4,7 @@ sidebar_position: 0
# Installation and Setup
Make sure you have NodeJS v18 or higher.
## Using create-llama
The easiest way to get started with LlamaIndex is by using `create-llama`. This CLI tool enables you to quickly start building a new LlamaIndex application, with everything set up for you.
Just run
<Tabs>
<TabItem value="1" label="npm" default>
```bash
npx create-llama@latest
```
</TabItem>
<TabItem value="2" label="Yarn">
```bash
yarn create llama
```
</TabItem>
<TabItem value="3" label="pnpm">
```bash
pnpm create llama@latest
```
</TabItem>
</Tabs>
to get started. Once your app is generated, run
```bash npm2yarn
npm run dev
```
to start the development server. You can then visit [http://localhost:3000](http://localhost:3000) to see your app
We support Node.JS versions 18, 20 and 22, with experimental support for Deno, Bun and Vercel Edge functions.
## Installation from NPM
@@ -52,12 +14,21 @@ npm install llamaindex
### Environment variables
Our examples use OpenAI by default. You'll need to set up your Open AI key like so:
Our examples use OpenAI by default. You can use [other LLMs](../examples/other_llms) via their APIs; if you would prefer to use local models check out our [local LLM example](../examples/local_llm).
To use OpenAI, you'll need to [get an OpenAI API key](https://platform.openai.com/account/api-keys) and then make it available as an environment variable this way:
```bash
export OPENAI_API_KEY="sk-......" # Replace with your key from https://platform.openai.com/account/api-keys
export OPENAI_API_KEY="sk-......" # Replace with your key
```
If you want to have it automatically loaded every time, add it to your `.zshrc/.bashrc`.
WARNING: do not check in your OpenAI key into version control.
**WARNING:** do not check in your OpenAI key into version control. GitHub automatically invalidates OpenAI keys checked in by accident.
## What next?
- The easiest way to started is to [build a full-stack chat app with `create-llama`](starter_tutorial/chatbot).
- Try our other [getting started tutorials](starter_tutorial/retrieval_augmented_generation)
- Learn more about the [high level concepts](concepts) behind how LlamaIndex works
- Check out our [many examples](../examples/more_examples) of LlamaIndex.TS in action
@@ -1,51 +0,0 @@
---
sidebar_position: 1
---
import CodeBlock from "@theme/CodeBlock";
import CodeSource from "!raw-loader!../../../../examples/vectorIndex";
import TSConfigSource from "!!raw-loader!../../../../examples/tsconfig.json";
# Starter Tutorial
Make sure you have installed LlamaIndex.TS and have an OpenAI key. If you haven't, check out the [installation](installation) guide.
## From scratch(node.js + TypeScript):
In a new folder:
```bash npm2yarn
npm init
npm install -D typescript @types/node
```
Create the file `example.ts`. This code will load some example data, create a document, index it (which creates embeddings using OpenAI), and then creates query engine to answer questions about the data.
<CodeBlock language="ts">{CodeSource}</CodeBlock>
Create a `tsconfig.json` file in the same folder:
<CodeBlock language="json">{TSConfigSource}</CodeBlock>
Now you can run the code with
```bash
npx tsx example.ts
```
Also, you can clone our examples and try them out:
```bash npm2yarn
npx degit run-llama/LlamaIndexTS/examples my-new-project
cd my-new-project
npm install
npx tsx ./vectorIndex.ts
```
## From scratch (Next.js + TypeScript):
You just need one command to create a new Next.js project:
```bash npm2yarn
npx create-llama@latest
```
@@ -0,0 +1,2 @@
label: Starter Tutorials
position: 1
@@ -0,0 +1,49 @@
---
sidebar_position: 4
---
import CodeBlock from "@theme/CodeBlock";
import CodeSource from "!raw-loader!../../../../../examples/agent/openai";
# Agent tutorial
We have a comprehensive, step-by-step [guide to building agents in LlamaIndex.TS](../../guides/agents/setup) that we recommend to learn what agents are and how to build them for production. But building a basic agent is simple:
## Set up
In a new folder:
```bash npm2yarn
npm init
npm install -D typescript @types/node
```
## Run agent
Create the file `example.ts`. This code will:
- Create two tools for use by the agent:
- A `sumNumbers` tool that adds two numbers
- A `divideNumbers` tool that divides numbers
-
- Give an example of the data structure we wish to generate
- Prompt the LLM with instructions and the example, plus a sample transcript
<CodeBlock language="ts">{CodeSource}</CodeBlock>
To run the code:
```bash
npx tsx example.ts
```
You should expect output something like:
```
{
content: 'The sum of 5 + 5 is 10. When you divide 10 by 2, you get 5.',
role: 'assistant',
options: {}
}
Done
```
@@ -0,0 +1,27 @@
---
sidebar_position: 2
---
# Chatbot tutorial
Once you've mastered basic [retrieval-augment generation](retrieval_augmented_generation) you may want to create an interface to chat with your data. You can do this step-by-step, but we recommend getting started quickly using `create-llama`.
## Using create-llama
`create-llama` is a powerful but easy to use command-line tool that generates a working, full-stack web application that allows you to chat with your data. You can learn more about it on [the `create-llama` README page](https://www.npmjs.com/package/create-llama).
Run it once and it will ask you a series of questions about the kind of application you want to generate. Then you can customize your application to suit your use-case. To get started, run:
```bash npm2yarn
npx create-llama@latest
```
Once your app is generated, `cd` into your app directory and run
```bash npm2yarn
npm run dev
```
to start the development server. You can then visit [http://localhost:3000](http://localhost:3000) to see your app, which should look something like this:
![create-llama interface](./images/create_llama.png)
Binary file not shown.

After

Width:  |  Height:  |  Size: 540 KiB

@@ -0,0 +1,60 @@
---
sidebar_position: 1
---
import CodeBlock from "@theme/CodeBlock";
import CodeSource from "!raw-loader!../../../../../examples/vectorIndex";
import TSConfigSource from "!!raw-loader!../../../../../examples/tsconfig.json";
# Retrieval Augmented Generation (RAG) Tutorial
One of the most common use-cases for LlamaIndex is Retrieval-Augmented Generation or RAG, in which your data is indexed and selectively retrieved to be given to an LLM as source material for responding to a query. You can learn more about the [concepts behind RAG](../concepts).
## Before you start
Make sure you have installed LlamaIndex.TS and have an OpenAI key. If you haven't, check out the [installation](../installation) steps.
You can use [other LLMs](../examples/other_llms) via their APIs; if you would prefer to use local models check out our [local LLM example](../../examples/local_llm).
## Set up
In a new folder:
```bash npm2yarn
npm init
npm install -D typescript @types/node
```
## Run queries
Create the file `example.ts`. This code will
- load an example file
- convert it into a Document object
- index it (which creates embeddings using OpenAI)
- create a query engine to answer questions about the data
<CodeBlock language="ts">{CodeSource}</CodeBlock>
Create a `tsconfig.json` file in the same folder:
<CodeBlock language="json">{TSConfigSource}</CodeBlock>
Now you can run the code with
```bash
npx tsx example.ts
```
You should expect output something like:
```
In college, the author studied subjects like linear algebra and physics, but did not find them particularly interesting. They started slacking off, skipping lectures, and eventually stopped attending classes altogether. They also had a negative experience with their English classes, where they were required to pay for catch-up training despite getting verbal approval to skip most of the classes. Ultimately, the author lost motivation for college due to their job as a software developer and stopped attending classes, only returning years later to pick up their papers.
0: Score: 0.8305309270895813 - I started this decade as a first-year college stud...
1: Score: 0.8286388215713089 - A short digression. Im not saying colleges are wo...
```
Once you've mastered basic RAG, you may want to consider [chatting with your data](chatbot).
@@ -0,0 +1,52 @@
---
sidebar_position: 3
---
import CodeBlock from "@theme/CodeBlock";
import CodeSource from "!raw-loader!../../../../../examples/jsonExtract";
# Structured data extraction tutorial
Make sure you have installed LlamaIndex.TS and have an OpenAI key. If you haven't, check out the [installation](installation) guide.
You can use [other LLMs](../examples/other_llms) via their APIs; if you would prefer to use local models check out our [local LLM example](../../examples/local_llm).
## Set up
In a new folder:
```bash npm2yarn
npm init
npm install -D typescript @types/node
```
## Extract data
Create the file `example.ts`. This code will:
- Set up an LLM connection to GPT-4
- Give an example of the data structure we wish to generate
- Prompt the LLM with instructions and the example, plus a sample transcript
<CodeBlock language="ts">{CodeSource}</CodeBlock>
To run the code:
```bash
npx tsx example.ts
```
You should expect output something like:
```json
{
"summary": "Sarah from XYZ Company called John to introduce the XYZ Widget, a tool designed to automate tasks and improve productivity. John expressed interest and requested case studies and a product demo. Sarah agreed to send the information and follow up to schedule the demo.",
"products": ["XYZ Widget"],
"rep_name": "Sarah",
"prospect_name": "John",
"action_items": [
"Send case studies and additional product information to John",
"Follow up with John to schedule a product demo"
]
}
```
+2
View File
@@ -0,0 +1,2 @@
label: Guides
position: 2
+41
View File
@@ -0,0 +1,41 @@
---
sidebar_position: 1
---
# Getting started
In this guide we'll walk you through the process of building an Agent in JavaScript using the LlamaIndex.TS library, starting from nothing and adding complexity in stages.
## What is an Agent?
In LlamaIndex, an agent is a semi-autonomous piece of software powered by an LLM that is given a task and executes a series of steps towards solving that task. It is given a set of tools, which can be anything from arbitrary functions up to full LlamaIndex query engines, and it selects the best available tool to complete each step. When each step is completed, the agent judges whether the task is now complete, in which case it returns a result to the user, or whether it needs to take another step, in which case it loops back to the start.
![agent flow](./images/agent_flow.png)
## Install LlamaIndex.TS
You'll need to have a recent version of [Node.js](https://nodejs.org/en) installed. Then you can install LlamaIndex.TS by running
```bash
npm install llamaindex
```
## Choose your model
By default we'll be using OpenAI with GPT-4, as it's a powerful model and easy to get started with. If you'd prefer to run a local model, see [using a local model](local_model).
## Get an OpenAI API key
If you don't already have one, you can sign up for an [OpenAI API key](https://platform.openai.com/api-keys). You should then put the key in a `.env` file in the root of the project; the file should look like
```
OPENAI_API_KEY=sk-XXXXXXXXXXXXXXXXXXXXXXXX
```
We'll use `dotenv` to pull the API key out of that .env file, so also run:
```bash
npm install dotenv
```
Now you're ready to [create your agent](create_agent).
@@ -0,0 +1,179 @@
# Create a basic agent
We want to use `await` so we're going to wrap all of our code in a `main` function, like this:
```typescript
// Your imports go here
async function main() {
// the rest of your code goes here
}
main().catch(console.error);
```
For the rest of this guide we'll assume your code is wrapped like this so we can use `await`. You can run the code this way:
```bash
npx tsx example.ts
```
### Load your dependencies
First we'll need to pull in our dependencies. These are:
- The OpenAI class to use the OpenAI LLM
- FunctionTool to provide tools to our agent
- OpenAIAgent to create the agent itself
- Settings to define some global settings for the library
- Dotenv to load our API key from the .env file
```javascript
import { OpenAI, FunctionTool, OpenAIAgent, Settings } from "llamaindex";
import "dotenv/config";
```
### Initialize your LLM
We need to tell our OpenAI class where its API key is, and which of OpenAI's models to use. We'll be using `gpt-4o`, which is capable while still being pretty cheap. This is a global setting, so anywhere an LLM is needed will use the same model.
```javascript
Settings.llm = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
model: "gpt-4o",
});
```
### Turn on logging
We want to see what our agent is up to, so we're going to hook into some events that the library generates and print them out. There are several events possible, but we'll specifically tune in to `llm-tool-call` (when a tool is called) and `llm-tool-result` (when it responds).
```javascript
Settings.callbackManager.on("llm-tool-call", (event) => {
console.log(event.detail.payload);
});
Settings.callbackManager.on("llm-tool-result", (event) => {
console.log(event.detail.payload);
});
```
### Create a function
We're going to create a very simple function that adds two numbers together. This will be the tool we ask our agent to use.
```javascript
const sumNumbers = ({ a, b }) => {
return `${a + b}`;
};
```
Note that we're passing in an object with two named parameters, `a` and `b`. This is a little unusual, but important for defining a tool that an LLM can use.
### Turn the function into a tool for the agent
This is the most complicated part of creating an agent. We need to define a `FunctionTool`. We have to pass in:
- The function itself (`sumNumbers`)
- A name for the function, which the LLM will use to call it
- A description of the function. The LLM will read this description to figure out what the tool does, and if it needs to call it
- A schema for function. We tell the LLM that the parameter is an `object`, and we tell it about the two named parameters we gave it, `a` and `b`. We describe each parameter as a `number`, and we say that both are required.
- You can see [more examples of function schemas](https://cookbook.openai.com/examples/how_to_call_functions_with_chat_models).
```javascript
const tool = FunctionTool.from(sumNumbers, {
name: "sumNumbers",
description: "Use this function to sum two numbers",
parameters: {
type: "object",
properties: {
a: {
type: "number",
description: "First number to sum",
},
b: {
type: "number",
description: "Second number to sum",
},
},
required: ["a", "b"],
},
});
```
We then wrap up the tools into an array. We could provide lots of tools this way, but for this example we're just using the one.
```javascript
const tools = [tool];
```
### Create the agent
With your LLM already set up and your tools defined, creating an agent is simple:
```javascript
const agent = new OpenAIAgent({ tools });
```
### Ask the agent a question
We can use the `chat` interface to ask our agent a question, and it will use the tools we've defined to find an answer.
```javascript
let response = await agent.chat({
message: "Add 101 and 303",
});
console.log(response);
```
Let's see what running this looks like using `npx tsx agent.ts`
**_Output_**
```javascript
{
toolCall: {
id: 'call_ze6A8C3mOUBG4zmXO8Z4CPB5',
name: 'sumNumbers',
input: { a: 101, b: 303 }
},
toolResult: {
tool: FunctionTool { _fn: [Function: sumNumbers], _metadata: [Object] },
input: { a: 101, b: 303 },
output: '404',
isError: false
}
}
```
```javascript
{
response: {
raw: {
id: 'chatcmpl-9KwauZku3QOvH78MNvxJs81mDvQYK',
object: 'chat.completion',
created: 1714778824,
model: 'gpt-4-turbo-2024-04-09',
choices: [Array],
usage: [Object],
system_fingerprint: 'fp_ea6eb70039'
},
message: {
content: 'The sum of 101 and 303 is 404.',
role: 'assistant',
options: {}
}
},
sources: [Getter]
}
```
We're seeing two pieces of output here. The first is our callback firing when the tool is called. You can see in `toolResult` that the LLM has correctly passed `101` and `303` to our `sumNumbers` function, which adds them up and returns `404`.
The second piece of output is the response from the LLM itself, where the `message.content` key is giving us the answer.
Great! We've built an agent with tool use! Next you can:
- [See the full code](https://github.com/run-llama/ts-agents/blob/main/1_agent/agent.ts)
- [Switch to a local LLM](local_model)
- Move on to [add Retrieval-Augmented Generation to your agent](agentic_rag)
@@ -0,0 +1,90 @@
# Using a local model via Ollama
If you're happy using OpenAI, you can skip this section, but many people are interested in using models they run themselves. The easiest way to do this is via the great work of our friends at [Ollama](https://ollama.com/), who provide a simple to use client that will download, install and run a [growing range of models](https://ollama.com/library) for you.
### Install Ollama
They provide a one-click installer for Mac, Linux and Windows on their [home page](https://ollama.com/).
### Pick and run a model
Since we're going to be doing agentic work, we'll need a very capable model, but the largest models are hard to run on a laptop. We think `mixtral 8x7b` is a good balance between power and resources, but `llama3` is another great option. You can run it simply by running
```bash
ollama run mixtral:8x7b
```
The first time you run it will also automatically download and install the model for you.
### Switch the LLM in your code
There are two changes you need to make to the code we already wrote in `1_agent` to get Mixtral 8x7b to work. First, you need to switch to that model. Replace the call to `Settings.llm` with this:
```javascript
Settings.llm = new Ollama({
model: "mixtral:8x7b",
});
```
### Swap to a ReActAgent
In our original code we used a specific OpenAIAgent, so we'll need to switch to a more generic agent pattern, the ReAct pattern. This is simple: change the `const agent` line in your code to read
```javascript
const agent = new ReActAgent({ tools });
```
(You will also need to bring in `Ollama` and `ReActAgent` in your imports)
### Run your totally local agent
Because your embeddings were already local, your agent can now run entirely locally without making any API calls.
```bash
node agent.mjs
```
Note that your model will probably run a lot slower than OpenAI, so be prepared to wait a while!
**_Output_**
```javascript
{
response: {
message: {
role: 'assistant',
content: ' Thought: I need to use a tool to add the numbers 101 and 303.\n' +
'Action: sumNumbers\n' +
'Action Input: {"a": 101, "b": 303}\n' +
'\n' +
'Observation: 404\n' +
'\n' +
'Thought: I can answer without using any more tools.\n' +
'Answer: The sum of 101 and 303 is 404.'
},
raw: {
model: 'mixtral:8x7b',
created_at: '2024-05-09T00:24:30.339473Z',
message: [Object],
done: true,
total_duration: 64678371209,
load_duration: 57394551334,
prompt_eval_count: 475,
prompt_eval_duration: 4163981000,
eval_count: 94,
eval_duration: 3116692000
}
},
sources: [Getter]
}
```
Tada! You can see all of this in the folder `1a_mixtral`.
### Extending to other examples
You can use a ReActAgent instead of an OpenAIAgent in any of the further examples below, but keep in mind that GPT-4 is a lot more capable than Mixtral 8x7b, so you may see more errors or failures in reasoning if you are using an entirely local setup.
### Next steps
Now you've got a local agent, you can [add Retrieval-Augmented Generation to your agent](agentic_rag).
@@ -0,0 +1,165 @@
# Adding Retrieval-Augmented Generation (RAG)
While an agent that can perform math is nifty (LLMs are usually not very good at math), LLM-based applications are always more interesting when they work with large amounts of data. In this case, we're going to use a 200-page PDF of the proposed budget of the city of San Francisco for fiscal years 2024-2024 and 2024-2025. It's a great example because it's extremely wordy and full of tables of figures, which present a challenge for humans and LLMs alike.
To learn more about RAG, we recommend this [introduction](https://docs.llamaindex.ai/en/stable/getting_started/concepts/) from our Python docs. We'll assume you know the basics:
- You need to parse your source data into chunks of text
- You need to encode that text as numbers, called embeddings
- You need to search your embeddings for the most relevant chunks of text
- You feed your relevant chunks and a query to an LLM to answer a question
We're going to start with the same agent we [built in step 1](https://github.com/run-llama/ts-agents/blob/main/1_agent/agent.ts), but make a few changes. You can find the finished version [in the repository](https://github.com/run-llama/ts-agents/blob/main/2_agentic_rag/agent.ts).
### New dependencies
We'll be bringing in `SimpleDirectoryReader`, `HuggingFaceEmbedding`, `VectorStoreIndex`, and `QueryEngineTool` from LlamaIndex.TS, as well as the dependencies we previously used.
```javascript
import {
OpenAI,
FunctionTool,
OpenAIAgent,
Settings,
SimpleDirectoryReader,
HuggingFaceEmbedding,
VectorStoreIndex,
QueryEngineTool,
} from "llamaindex";
```
### Add an embedding model
To encode our text into embeddings, we'll need an embedding model. We could use OpenAI for this but to save on API calls we're going to use a local embedding model from HuggingFace.
```javascript
Settings.embedModel = new HuggingFaceEmbedding({
modelType: "BAAI/bge-small-en-v1.5",
quantized: false,
});
```
### Load data using SimpleDirectoryReader
SimpleDirectoryReader is a flexible tool that can read a variety of file formats. We're going to point it at our data directory, which contains just the single PDF file, and get it to return a set of documents.
```javascript
const reader = new SimpleDirectoryReader();
const documents = await reader.loadData("../data");
```
### Index our data
Now we turn our text into embeddings. The `VectorStoreIndex` class takes care of this for us when we use the `fromDocuments` method (it uses the embedding model we defined in `Settings` earlier).
```javascript
const index = await VectorStoreIndex.fromDocuments(documents);
```
### Configure a retriever
Before LlamaIndex can send a query to the LLM, it needs to find the most relevant chunks to send. That's the purpose of a `Retriever`. We're going to get `VectorStoreIndex` to act as a retriever for us
```javascript
const retriever = await index.asRetriever();
```
### Configure how many documents to retrieve
By default LlamaIndex will retrieve just the 2 most relevant chunks of text. This document is complex though, so we'll ask for more context.
```javascript
retriever.similarityTopK = 10;
```
### Create a query engine
And our final step in creating a RAG pipeline is to create a query engine that will use the retriever to find the most relevant chunks of text, and then use the LLM to answer the question.
```javascript
const queryEngine = await index.asQueryEngine({
retriever,
});
```
### Define the query engine as a tool
Just as before we created a `FunctionTool`, we're going to create a `QueryEngineTool` that uses our `queryEngine`.
```javascript
const tools = [
new QueryEngineTool({
queryEngine: queryEngine,
metadata: {
name: "san_francisco_budget_tool",
description: `This tool can answer detailed questions about the individual components of the budget of San Francisco in 2023-2024.`,
},
}),
];
```
As before, we've created an array of tools with just one tool in it. The metadata is slightly different: we don't need to define our parameters, we just give the tool a name and a natural-language description.
### Create the agent as before
Creating the agent and asking a question is exactly the same as before, but we'll ask a different question.
```javascript
// create the agent
const agent = new OpenAIAgent({ tools });
let response = await agent.chat({
message: "What's the budget of San Francisco in 2023-2024?",
});
console.log(response);
```
Once again we'll run `npx tsx agent.ts` and see what we get:
**_Output_**
```javascript
{
toolCall: {
id: 'call_iNo6rTK4pOpOBbO8FanfWLI9',
name: 'san_francisco_budget_tool',
input: { query: 'total budget' }
},
toolResult: {
tool: QueryEngineTool {
queryEngine: [RetrieverQueryEngine],
metadata: [Object]
},
input: { query: 'total budget' },
output: 'The total budget for the City and County of San Francisco for Fiscal Year (FY) 2023-24 is $14.6 billion, which represents a $611.8 million, or 4.4 percent, increase over the FY 2022-23 budget. For FY 2024-25, the total budget is also projected to be $14.6 billion, reflecting a $40.5 million, or 0.3 percent, decrease from the FY 2023-24 proposed budget. This budget includes various expenditures across different departments and services, with significant allocations to public works, transportation, commerce, public protection, and health services.',
isError: false
}
}
```
```javascript
{
response: {
raw: {
id: 'chatcmpl-9KxUkwizVCYCmxwFQcZFSHrInzNFU',
object: 'chat.completion',
created: 1714782286,
model: 'gpt-4-turbo-2024-04-09',
choices: [Array],
usage: [Object],
system_fingerprint: 'fp_ea6eb70039'
},
message: {
content: "The total budget for the City and County of San Francisco for the fiscal year 2023-2024 is $14.6 billion. This represents a $611.8 million, or 4.4 percent, increase over the previous fiscal year's budget. The budget covers various expenditures across different departments and services, including significant allocations to public works, transportation, commerce, public protection, and health services.",
role: 'assistant',
options: {}
}
},
sources: [Getter]
}
```
Once again we see a `toolResult`. You can see the query the LLM decided to send to the query engine ("total budget"), and the output the engine returned. In `response.message` you see that the LLM has returned the output from the tool almost verbatim, although it trimmed out the bit about 2024-2025 since we didn't ask about that year.
So now we have an agent that can index complicated documents and answer questions about them. Let's [combine our math agent and our RAG agent](rag_and_tools)!
@@ -0,0 +1,128 @@
# A RAG agent that does math
In [our third iteration of the agent](https://github.com/run-llama/ts-agents/blob/main/3_rag_and_tools/agent.ts) we've combined the two previous agents, so we've defined both `sumNumbers` and a `QueryEngineTool` and created an array of two tools:
```javascript
// define the query engine as a tool
const tools = [
new QueryEngineTool({
queryEngine: queryEngine,
metadata: {
name: "san_francisco_budget_tool",
description: `This tool can answer detailed questions about the individual components of the budget of San Francisco in 2023-2024.`,
},
}),
FunctionTool.from(sumNumbers, {
name: "sumNumbers",
description: "Use this function to sum two numbers",
parameters: {
type: "object",
properties: {
a: {
type: "number",
description: "First number to sum",
},
b: {
type: "number",
description: "Second number to sum",
},
},
required: ["a", "b"],
},
}),
];
```
These tool descriptions are identical to the ones we previously defined. Now let's ask it 3 questions in a row:
```javascript
let response = await agent.chat({
message:
"What's the budget of San Francisco for community health in 2023-24?",
});
console.log(response);
let response2 = await agent.chat({
message:
"What's the budget of San Francisco for public protection in 2023-24?",
});
console.log(response2);
let response3 = await agent.chat({
message:
"What's the combined budget of San Francisco for community health and public protection in 2023-24?",
});
console.log(response3);
```
We'll abbreviate the output, but here are the important things to spot:
```javascript
{
toolCall: {
id: 'call_ZA1LPx03gO4ABre1r6XowLWq',
name: 'san_francisco_budget_tool',
input: { query: 'community health budget 2023-2024' }
},
toolResult: {
tool: QueryEngineTool {
queryEngine: [RetrieverQueryEngine],
metadata: [Object]
},
input: { query: 'community health budget 2023-2024' },
output: 'The proposed Fiscal Year (FY) 2023-24 budget for the Department of Public Health is $3.2 billion
}
}
```
This is the first tool call, where it used the query engine to get the public health budget.
```javascript
{
toolCall: {
id: 'call_oHu1KjEvA47ER6HYVfFIq9yp',
name: 'san_francisco_budget_tool',
input: { query: 'public protection budget 2023-2024' }
},
toolResult: {
tool: QueryEngineTool {
queryEngine: [RetrieverQueryEngine],
metadata: [Object]
},
input: { query: 'public protection budget 2023-2024' },
output: "The budget for Public Protection in San Francisco for Fiscal Year (FY) 2023-24 is $2,012.5 million."
}
}
```
In the second tool call, it got the police budget also from the query engine.
```javascript
{
toolCall: {
id: 'call_SzG4yGUnLbv1T7IyaLAOqg3t',
name: 'sumNumbers',
input: { a: 3200, b: 2012.5 }
},
toolResult: {
tool: FunctionTool { _fn: [Function: sumNumbers], _metadata: [Object] },
input: { a: 3200, b: 2012.5 },
output: '5212.5',
isError: false
}
}
```
In the final tool call, it used the `sumNumbers` function to add the two budgets together. Perfect! This leads to the final answer:
```javascript
{
message: {
content: 'The combined budget of San Francisco for community health and public protection in Fiscal Year (FY) 2023-24 is $5,212.5 million.',
role: 'assistant',
options: {}
}
}
```
Great! Now let's improve accuracy by improving our parsing with [LlamaParse](llamaparse).
@@ -0,0 +1,18 @@
# Adding LlamaParse
Complicated PDFs can be very tricky for LLMs to understand. To help with this, LlamaIndex provides LlamaParse, a hosted service that parses complex documents including PDFs. To use it, get a `LLAMA_CLOUD_API_KEY` by [signing up for LlamaCloud](https://cloud.llamaindex.ai/) (it's free for up to 1000 pages/day) and adding it to your `.env` file just as you did for your OpenAI key:
```bash
LLAMA_CLOUD_API_KEY=llx-XXXXXXXXXXXXXXXX
```
Then replace `SimpleDirectoryReader` with `LlamaParseReader`:
```javascript
const reader = new LlamaParseReader({ resultType: "markdown" });
const documents = await reader.loadData("../data/sf_budget_2023_2024.pdf");
```
Now you will be able to ask more complicated questions of the same PDF and get better results. You can find this code [in our repo](https://github.com/run-llama/ts-agents/blob/main/4_llamaparse/agent.ts).
Next up, let's persist our embedded data so we don't have to re-parse every time by [using a vector store](qdrant).
+75
View File
@@ -0,0 +1,75 @@
# Adding persistent vector storage
In the previous examples, we've been loading our data into memory each time we run the agent. This is fine for small datasets, but for larger datasets you'll want to store your embeddings in a database. LlamaIndex.TS provides a `VectorStore` class that can store your embeddings in a variety of databases. We're going to use [Qdrant](https://qdrant.tech/), a popular vector store, for this example.
We can get a local instance of Qdrant running very simply with Docker (make sure you [install Docker](https://www.docker.com/products/docker-desktop/) first):
```bash
docker pull qdrant/qdrant
docker run -p 6333:6333 qdrant/qdrant
```
And in our code we initialize a `VectorStore` with the Qdrant URL:
```javascript
// initialize qdrant vector store
const vectorStore = new QdrantVectorStore({
url: "http://localhost:6333",
});
```
Now once we have loaded our documents, we can instantiate an index with the vector store:
```javascript
// create a query engine from our documents
const index = await VectorStoreIndex.fromDocuments(documents, { vectorStore });
```
In [the final iteration](https://github.com/run-llama/ts-agents/blob/main/5_qdrant/agent.ts) you can see that we have also implemented a very naive caching mechanism to avoid re-parsing the PDF each time we run the agent:
```javascript
// load cache.json and parse it
let cache = {};
let cacheExists = false;
try {
await fs.access(PARSING_CACHE, fs.constants.F_OK);
cacheExists = true;
} catch (e) {
console.log("No cache found");
}
if (cacheExists) {
cache = JSON.parse(await fs.readFile(PARSING_CACHE, "utf-8"));
}
const filesToParse = ["../data/sf_budget_2023_2024.pdf"];
// load our data, reading only files we haven't seen before
let documents = [];
const reader = new LlamaParseReader({ resultType: "markdown" });
for (let file of filesToParse) {
if (!cache[file]) {
documents = documents.concat(await reader.loadData(file));
cache[file] = true;
}
}
// write the cache back to disk
await fs.writeFile(PARSING_CACHE, JSON.stringify(cache));
```
Since parsing a PDF can be slow, especially a large one, using the pre-parsed chunks in Qdrant can significantly speed up your agent.
## Next steps
In this guide you've learned how to
- [Create an agent](create_agent)
- Use remote LLMs like GPT-4
- [Use local LLMs like Mixtral](local_model)
- [Create a RAG query engine](agentic_rag)
- [Turn functions and query engines into agent tools](rag_and_tools)
- Combine those tools
- [Enhance your parsing with LlamaParse](llamaparse)
- Persist your data in a vector store
The next steps are up to you! Try creating more complex functions and query engines, and set your agent loose on the world.
@@ -0,0 +1,2 @@
label: Agents
position: 1
Binary file not shown.

After

Width:  |  Height:  |  Size: 236 KiB

+12 -14
View File
@@ -3,33 +3,31 @@ sidebar_position: 0
slug: /
---
# What is LlamaIndex.TS?
# What is LlamaIndex?
LlamaIndex.TS is a data framework for LLM applications to ingest, structure, and access private or domain-specific data. While a python package is also available (see [here](https://docs.llamaindex.ai/en/stable/)), LlamaIndex.TS offers core features in a simple package, optimized for usage with TypeScript.
LlamaIndex is a framework for building LLM-powered applications. LlamaIndex helps you ingest, structure, and access private or domain-specific data. It's available [as a Python package](https://docs.llamaindex.ai/en/stable/) and in TypeScript (this package). LlamaIndex.TS offers the core features of LlamaIndex for popular runtimes like Node.js (official support), Vercel Edge Functions (experimental), and Deno (experimental).
## 🚀 Why LlamaIndex.TS?
At their core, LLMs offer a natural language interface between humans and inferred data. Widely available models come pre-trained on huge amounts of publicly available data, from Wikipedia and mailing lists to textbooks and source code.
LLMs offer a natural language interface between humans and inferred data. Widely available models come pre-trained on huge amounts of publicly available data, from Wikipedia and mailing lists to textbooks and source code.
Applications built on top of LLMs often require augmenting these models with private or domain-specific data. Unfortunately, that data can be distributed across siloed applications and data stores. It's behind APIs, in SQL databases, or trapped in PDFs and slide decks.
Applications built on top of LLMs often require augmenting these models with private or domain-specific data. That data is often distributed across siloed applications and data stores. It's behind APIs, in SQL databases, or trapped in PDFs and slide decks.
That's where **LlamaIndex.TS** comes in.
LlamaIndex.TS helps you unlock that data and then build powerful applications with it.
## 🦙 How can LlamaIndex.TS help?
## 🦙 What is LlamaIndex for?
LlamaIndex.TS provides the following tools:
LlamaIndex.TS handles several major use cases:
- **Data loading** ingest your existing `.txt`, `.pdf`, `.csv`, `.md` and `.docx` data directly
- **Data indexes** structure your data in intermediate representations that are easy and performant for LLMs to consume.
- **Engines** provide natural language access to your data. For example:
- Query engines are powerful retrieval interfaces for knowledge-augmented output.
- Chat engines are conversational interfaces for multi-message, "back and forth" interactions with your data.
- **Structured Data Extraction**: turning complex, unstructured and semi-structured data into uniform, programmatically accessible formats.
- **Retrieval-Augmented Generation (RAG)**: answering queries across your internal data by providing LLMs with up-to-date, semantically relevant context including Question and Answer systems and chat bots.
- **Autonomous Agents**: building software that is capable of intelligently selecting and using tools to accomplish tasks in an interative, unsupervised manner.
## 👨‍👩‍👧‍👦 Who is LlamaIndex for?
LlamaIndex.TS provides a core set of tools, essential for anyone building LLM apps with JavaScript and TypeScript.
LlamaIndex targets the "AI Engineer": developers building software in any domain that can be enhanced by LLM-powered functionality, without needing to be an expert in machine learning or natural language processing.
Our high-level API allows beginner users to use LlamaIndex.TS to ingest and query their data.
Our high-level API allows beginner users to use LlamaIndex.TS to ingest, index, and query their data in just a few lines of code.
For more complex applications, our lower-level APIs allow advanced users to customize and extend any module—data connectors, indices, retrievers, and query engines, to fit their needs.
@@ -10,6 +10,36 @@ Settings.llm = new Gemini({
});
```
### Usage with Vertex AI
To use Gemini via Vertex AI you can use `GeminiVertexSession`.
GeminiVertexSession accepts the env variables: `GOOGLE_VERTEX_LOCATION` and `GOOGLE_VERTEX_PROJECT`
```ts
import { Gemini, GEMINI_MODEL, GeminiVertexSession } from "llamaindex";
const gemini = new Gemini({
model: GEMINI_MODEL.GEMINI_PRO,
session: new GeminiVertexSession({
location: "us-central1", // optional if provided by GOOGLE_VERTEX_LOCATION env variable
project: "project1", // optional if provided by GOOGLE_VERTEX_PROJECT env variable
googleAuthOptions: {...}, // optional, but useful for production. It accepts all values from `GoogleAuthOptions`
}),
});
```
[GoogleAuthOptions](https://github.com/googleapis/google-auth-library-nodejs/blob/main/src/auth/googleauth.ts)
To authenticate for local development:
```bash
npm install @google-cloud/vertexai
gcloud auth application-default login
```
To authenticate for production you'll have to use a [service account](https://cloud.google.com/docs/authentication/). `googleAuthOptions` has `credentials` which might be useful for you.
## Load and index documents
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
@@ -3,7 +3,7 @@
## Usage
```ts
import { Ollama, Settings } from "llamaindex";
import { MistralAI, Settings } from "llamaindex";
Settings.llm = new MistralAI({
model: "mistral-tiny",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "docs",
"version": "0.0.17",
"version": "0.0.21",
"private": true,
"scripts": {
"docusaurus": "docusaurus",
+19
View File
@@ -0,0 +1,19 @@
import { Gemini, GEMINI_MODEL, GeminiVertexSession } from "llamaindex";
(async () => {
const gemini = new Gemini({
model: GEMINI_MODEL.GEMINI_PRO,
session: new GeminiVertexSession(),
});
const result = await gemini.chat({
messages: [
{ content: "You want to talk in rhymes.", role: "system" },
{
content:
"How much wood would a woodchuck chuck if a woodchuck could chuck wood?",
role: "user",
},
],
});
console.log(result);
})();
+16
View File
@@ -0,0 +1,16 @@
import { HuggingFaceLLM } from "llamaindex";
(async () => {
const hf = new HuggingFaceLLM();
const result = await hf.chat({
messages: [
{ content: "You want to talk in rhymes.", role: "system" },
{
content:
"How much wood would a woodchuck chuck if a woodchuck could chuck wood?",
role: "user",
},
],
});
console.log(result);
})();
+4 -12
View File
@@ -1,11 +1,6 @@
import {
Settings,
SimpleDirectoryReader,
VectorStoreIndex,
storageContextFromDefaults,
} from "llamaindex";
import * as path from "path";
import { Settings, SimpleDirectoryReader, VectorStoreIndex } from "llamaindex";
import path from "path";
import { getStorageContext } from "./storage";
// Update chunk size and overlap
Settings.chunkSize = 512;
@@ -25,10 +20,7 @@ async function generateDatasource() {
const documents = await new SimpleDirectoryReader().loadData({
directoryPath: path.join("multimodal", "data"),
});
const storageContext = await storageContextFromDefaults({
persistDir: "storage",
storeImages: true,
});
const storageContext = await getStorageContext();
await VectorStoreIndex.fromDocuments(documents, {
storageContext,
});
+11 -20
View File
@@ -1,12 +1,12 @@
import {
CallbackManager,
ImageType,
MultiModalResponseSynthesizer,
OpenAI,
RetrievalEndEvent,
Settings,
VectorStoreIndex,
storageContextFromDefaults,
} from "llamaindex";
import { getStorageContext } from "./storage";
// Update chunk size and overlap
Settings.chunkSize = 512;
@@ -16,32 +16,23 @@ Settings.chunkOverlap = 20;
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}`);
},
Settings.callbackManager.on("retrieve-end", (event: RetrievalEndEvent) => {
const { nodes, query } = event.detail.payload;
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",
storeImages: true,
});
return await VectorStoreIndex.init({
nodes: [],
storageContext,
});
}
async function main() {
const images: ImageType[] = [];
const index = await createIndex();
const storageContext = await getStorageContext();
const index = await VectorStoreIndex.init({
nodes: [],
storageContext,
});
const queryEngine = index.asQueryEngine({
responseSynthesizer: new MultiModalResponseSynthesizer(),
retriever: index.asRetriever({ similarityTopK: 3, imageSimilarityTopK: 1 }),
retriever: index.asRetriever({ topK: { TEXT: 3, IMAGE: 1 } }),
});
const result = await queryEngine.query({
query: "Tell me more about Vincent van Gogh's famous paintings",
+8 -21
View File
@@ -1,31 +1,18 @@
import {
ImageNode,
Settings,
TextNode,
VectorStoreIndex,
storageContextFromDefaults,
} from "llamaindex";
import { ImageNode, Settings, TextNode, VectorStoreIndex } from "llamaindex";
import { getStorageContext } from "./storage";
// 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 storageContext = await storageContextFromDefaults({
persistDir: "storage",
storeImages: true,
});
return await VectorStoreIndex.init({
async function main() {
// retrieve documents using the index
const storageContext = await getStorageContext();
const index = await VectorStoreIndex.init({
nodes: [],
storageContext,
});
}
async function main() {
// retrieve documents using the index
const index = await createIndex();
const retriever = index.asRetriever({ similarityTopK: 3 });
const retriever = index.asRetriever({ topK: { TEXT: 1, IMAGE: 3 } });
const results = await retriever.retrieve({
query: "what are Vincent van Gogh's famous paintings",
});
@@ -40,7 +27,7 @@ async function main() {
console.log("Text:", (node as TextNode).text.substring(0, 128));
}
console.log(`ID: ${node.id_}`);
console.log(`Similarity: ${result.score}`);
console.log(`Similarity: ${result.score}\n`);
}
}
+17
View File
@@ -0,0 +1,17 @@
import { storageContextFromDefaults } from "llamaindex";
// set up store context with two vector stores, one for text, the other for images
export async function getStorageContext() {
return await storageContextFromDefaults({
persistDir: "storage",
storeImages: true,
// if storeImages is true, the following vector store will be added
// vectorStores: {
// IMAGE: SimpleVectorStore.fromPersistDir(
// `${persistDir}/images`,
// fs,
// new ClipEmbedding(),
// ),
// },
});
}
+1 -1
View File
@@ -8,7 +8,7 @@
"@notionhq/client": "^2.2.15",
"@pinecone-database/pinecone": "^2.2.0",
"@zilliz/milvus2-sdk-node": "^2.4.2",
"chromadb": "^1.8.1",
"chromadb": "^1.7.3",
"commander": "^12.0.0",
"dotenv": "^16.4.5",
"js-tiktoken": "^1.0.11",
View File
+2
View File
@@ -1,5 +1,6 @@
import {
OpenAI,
OpenAIEmbedding,
ResponseSynthesizer,
RetrieverQueryEngine,
Settings,
@@ -28,6 +29,7 @@ class PineconeVectorStore<T extends RecordMetadata = RecordMetadata>
{
storesText = true;
isEmbeddingQuery = false;
embedModel = new OpenAIEmbedding();
indexName!: string;
pineconeClient!: Pinecone;
+43
View File
@@ -0,0 +1,43 @@
import fs from "node:fs/promises";
import {
Document,
HuggingFaceEmbedding,
Ollama,
Settings,
VectorStoreIndex,
} from "llamaindex";
Settings.llm = new Ollama({
model: "mixtral:8x7b",
});
Settings.embedModel = new HuggingFaceEmbedding({
modelType: "BAAI/bge-small-en-v1.5",
quantized: false,
});
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 });
// Split text and create embeddings. Store them in a VectorStoreIndex
const index = await VectorStoreIndex.fromDocuments([document]);
// Query the index
const queryEngine = index.asQueryEngine();
const response = await queryEngine.query({
query: "What did the author do in college?",
});
// Output response
console.log(response.toString());
}
main().catch(console.error);
+3 -2
View File
@@ -2,8 +2,8 @@
"name": "@llamaindex/monorepo",
"private": true,
"scripts": {
"build": "turbo run build --filter=\"!docs\" --filter=\"!*-test\"",
"build:release": "turbo run build lint test --filter=\"!docs\" --filter=\"!*-test\"",
"build": "turbo run build --filter=\"!docs\" --filter=\"!*-test\" --filter=\"!*-example\"",
"build:release": "turbo run build lint test --filter=\"!docs\" --filter=\"!*-test\" --filter=\"!*-example\"",
"dev": "turbo run dev",
"format": "prettier --ignore-unknown --cache --check .",
"format:write": "prettier --ignore-unknown --write .",
@@ -28,6 +28,7 @@
"eslint-plugin-react": "7.34.1",
"husky": "^9.0.11",
"lint-staged": "^15.2.2",
"madge": "^7.0.0",
"prettier": "^3.2.5",
"prettier-plugin-organize-imports": "^3.2.4",
"turbo": "^1.13.3",
@@ -4,6 +4,44 @@
### Patch Changes
- Updated dependencies [1b1081b]
- Updated dependencies [37525df]
- Updated dependencies [660a2b3]
- Updated dependencies [a1f2475]
- llamaindex@0.3.13
- @llamaindex/autotool@0.0.1
## null
### Patch Changes
- Updated dependencies [34fb1d8]
- llamaindex@0.3.12
- @llamaindex/autotool@0.0.1
## null
### Patch Changes
- Updated dependencies [e072c45]
- Updated dependencies [9e133ac]
- Updated dependencies [447105a]
- Updated dependencies [320be3f]
- llamaindex@0.3.11
- @llamaindex/autotool@0.0.1
## null
### Patch Changes
- Updated dependencies [4aba02e]
- llamaindex@0.3.10
- @llamaindex/autotool@0.0.1
## null
### Patch Changes
- Updated dependencies [c3747d0]
- llamaindex@0.3.9
- @llamaindex/autotool@0.0.1
@@ -1,5 +1,43 @@
# @llamaindex/autotool-02-next-example
## 0.1.5
### Patch Changes
- Updated dependencies [1b1081b]
- Updated dependencies [37525df]
- Updated dependencies [660a2b3]
- Updated dependencies [a1f2475]
- llamaindex@0.3.13
- @llamaindex/autotool@0.0.1
## 0.1.4
### Patch Changes
- Updated dependencies [34fb1d8]
- llamaindex@0.3.12
- @llamaindex/autotool@0.0.1
## 0.1.3
### Patch Changes
- Updated dependencies [e072c45]
- Updated dependencies [9e133ac]
- Updated dependencies [447105a]
- Updated dependencies [320be3f]
- llamaindex@0.3.11
- @llamaindex/autotool@0.0.1
## 0.1.2
### Patch Changes
- Updated dependencies [4aba02e]
- llamaindex@0.3.10
- @llamaindex/autotool@0.0.1
## 0.1.1
### Patch Changes
@@ -1,6 +1,7 @@
import { withNext } from "@llamaindex/autotool/next";
import withLlamaIndex from "llamaindex/next";
/** @type {import('next').NextConfig} */
const nextConfig = {};
export default withNext(nextConfig);
export default withLlamaIndex(withNext(nextConfig));
@@ -1,7 +1,7 @@
{
"name": "@llamaindex/autotool-02-next-example",
"private": true,
"version": "0.1.1",
"version": "0.1.5",
"scripts": {
"dev": "next dev",
"build": "next build",
+6 -2
View File
@@ -2,7 +2,11 @@
"name": "@llamaindex/autotool",
"type": "module",
"version": "0.0.1",
"description": "",
"description": "auto transpile your JS function to LLM Agent compatible",
"files": [
"dist",
"CHANGELOG.md"
],
"exports": {
".": {
"types": "./dist/index.d.ts",
@@ -47,7 +51,7 @@
"unplugin": "^1.10.1"
},
"peerDependencies": {
"llamaindex": "^0.3.9",
"llamaindex": "^0.3.13",
"openai": "^4",
"typescript": "^4"
},
+7
View File
@@ -0,0 +1,7 @@
{
"detectiveOptions": {
"ts": {
"skipTypeImports": true
}
}
}
+38
View File
@@ -1,5 +1,43 @@
# llamaindex
## 0.3.13
### Patch Changes
- 1b1081b: Add vectorStores to storage context to define vector store per modality
- 37525df: Added support for accessing Gemini via Vertex AI
- 660a2b3: Fix text before heading in markdown reader
- a1f2475: Add system prompt to ContextChatEngine
## 0.3.12
### Patch Changes
- 34fb1d8: fix: cloudflare dev
## 0.3.11
### Patch Changes
- e072c45: fix: remove non-standard API `pipeline`
- 9e133ac: refactor: remove `defaultFS` from parameters
We don't accept passing fs in the parameter since it's unnecessary for a determined JS environment.
This was a polyfill way for the non-Node.js environment, but now we use another way to polyfill APIs.
- 447105a: Improve Gemini message and context preparation
- 320be3f: Force ChromaDB version to 1.7.3 (to prevent NextJS issues)
- Updated dependencies [e072c45]
- Updated dependencies [9e133ac]
- @llamaindex/env@0.1.3
## 0.3.10
### Patch Changes
- 4aba02e: feat: support gpt4-o
## 0.3.9
### Patch Changes
+6
View File
@@ -1,5 +1,11 @@
# @llamaindex/core-e2e
## 0.0.6
### Patch Changes
- 34fb1d8: fix: cloudflare dev
## 0.0.5
### Patch Changes
@@ -1,5 +1,40 @@
# @llamaindex/cloudflare-worker-agent-test
## 0.0.14
### Patch Changes
- Updated dependencies [1b1081b]
- Updated dependencies [37525df]
- Updated dependencies [660a2b3]
- Updated dependencies [a1f2475]
- llamaindex@0.3.13
## 0.0.13
### Patch Changes
- 34fb1d8: fix: cloudflare dev
- Updated dependencies [34fb1d8]
- llamaindex@0.3.12
## 0.0.12
### Patch Changes
- Updated dependencies [e072c45]
- Updated dependencies [9e133ac]
- Updated dependencies [447105a]
- Updated dependencies [320be3f]
- llamaindex@0.3.11
## 0.0.11
### Patch Changes
- Updated dependencies [4aba02e]
- llamaindex@0.3.10
## 0.0.10
### Patch Changes
@@ -1,6 +1,6 @@
{
"name": "@llamaindex/cloudflare-worker-agent-test",
"version": "0.0.10",
"version": "0.0.14",
"type": "module",
"private": true,
"scripts": {
@@ -1,5 +1,39 @@
# @llamaindex/next-agent-test
## 0.1.14
### Patch Changes
- Updated dependencies [1b1081b]
- Updated dependencies [37525df]
- Updated dependencies [660a2b3]
- Updated dependencies [a1f2475]
- llamaindex@0.3.13
## 0.1.13
### Patch Changes
- Updated dependencies [34fb1d8]
- llamaindex@0.3.12
## 0.1.12
### Patch Changes
- Updated dependencies [e072c45]
- Updated dependencies [9e133ac]
- Updated dependencies [447105a]
- Updated dependencies [320be3f]
- llamaindex@0.3.11
## 0.1.11
### Patch Changes
- Updated dependencies [4aba02e]
- llamaindex@0.3.10
## 0.1.10
### Patch Changes
@@ -1,6 +1,6 @@
{
"name": "@llamaindex/next-agent-test",
"version": "0.1.10",
"version": "0.1.14",
"private": true,
"scripts": {
"dev": "next dev",
@@ -1,5 +1,39 @@
# test-edge-runtime
## 0.1.13
### Patch Changes
- Updated dependencies [1b1081b]
- Updated dependencies [37525df]
- Updated dependencies [660a2b3]
- Updated dependencies [a1f2475]
- llamaindex@0.3.13
## 0.1.12
### Patch Changes
- Updated dependencies [34fb1d8]
- llamaindex@0.3.12
## 0.1.11
### Patch Changes
- Updated dependencies [e072c45]
- Updated dependencies [9e133ac]
- Updated dependencies [447105a]
- Updated dependencies [320be3f]
- llamaindex@0.3.11
## 0.1.10
### Patch Changes
- Updated dependencies [4aba02e]
- llamaindex@0.3.10
## 0.1.9
### Patch Changes
@@ -1,6 +1,6 @@
{
"name": "@llamaindex/nextjs-edge-runtime-test",
"version": "0.1.9",
"version": "0.1.13",
"private": true,
"scripts": {
"dev": "next dev",
@@ -1,5 +1,39 @@
# @llamaindex/waku-query-engine-test
## 0.0.14
### Patch Changes
- Updated dependencies [1b1081b]
- Updated dependencies [37525df]
- Updated dependencies [660a2b3]
- Updated dependencies [a1f2475]
- llamaindex@0.3.13
## 0.0.13
### Patch Changes
- Updated dependencies [34fb1d8]
- llamaindex@0.3.12
## 0.0.12
### Patch Changes
- Updated dependencies [e072c45]
- Updated dependencies [9e133ac]
- Updated dependencies [447105a]
- Updated dependencies [320be3f]
- llamaindex@0.3.11
## 0.0.11
### Patch Changes
- Updated dependencies [4aba02e]
- llamaindex@0.3.10
## 0.0.10
### Patch Changes
@@ -1,6 +1,6 @@
{
"name": "@llamaindex/waku-query-engine-test",
"version": "0.0.10",
"version": "0.0.14",
"type": "module",
"private": true,
"scripts": {
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@llamaindex/core-e2e",
"private": true,
"version": "0.0.5",
"version": "0.0.6",
"type": "module",
"scripts": {
"e2e": "node --import tsx --import ./mock-register.js --test ./node/*.e2e.ts",
+2 -2
View File
@@ -1,9 +1,9 @@
{
"name": "@llamaindex/core",
"version": "0.3.9",
"version": "0.3.13",
"exports": "./src/index.ts",
"imports": {
"@llamaindex/env": "jsr:@llamaindex/env@0.1.2"
"@llamaindex/env": "jsr:@llamaindex/env@0.1.3"
},
"publish": {
"include": ["LICENSE", "README.md", "src/**/*", "jsr.json"]
+5 -5
View File
@@ -1,6 +1,6 @@
{
"name": "llamaindex",
"version": "0.3.9",
"version": "0.3.13",
"expectedMinorVersion": "3",
"license": "MIT",
"type": "module",
@@ -24,6 +24,7 @@
"@anthropic-ai/sdk": "^0.20.9",
"@aws-crypto/sha256-js": "^5.2.0",
"@datastax/astra-db-ts": "^1.1.0",
"@google-cloud/vertexai": "^1.1.0",
"@google/generative-ai": "^0.11.0",
"@grpc/grpc-js": "^1.10.7",
"@huggingface/inference": "^2.6.7",
@@ -39,7 +40,7 @@
"@zilliz/milvus2-sdk-node": "^2.4.2",
"ajv": "^8.13.0",
"assemblyai": "^4.4.2",
"chromadb": "~1.8.1",
"chromadb": "~1.7.3",
"cohere-ai": "^7.9.5",
"js-tiktoken": "^1.0.11",
"lodash": "^4.17.21",
@@ -48,7 +49,7 @@
"md-utils-ts": "^2.0.0",
"mongodb": "^6.6.1",
"notion-md-crawler": "^1.0.0",
"openai": "^4.43.0",
"openai": "^4.46.0",
"papaparse": "^5.4.1",
"pathe": "^1.1.2",
"pdf2json": "3.0.5",
@@ -69,7 +70,6 @@
"@swc/core": "^1.5.5",
"concurrently": "^8.2.2",
"glob": "^10.3.12",
"madge": "^7.0.0",
"typescript": "^5.4.5"
},
"engines": {
@@ -151,7 +151,7 @@
"build:type": "tsc -p tsconfig.json",
"copy": "cp -r ../../README.md ../../LICENSE .",
"postbuild": "pnpm run copy && node -e \"require('fs').writeFileSync('./dist/cjs/package.json', JSON.stringify({ type: 'commonjs' }))\"",
"circular-check": "madge -c ./src/index.ts",
"circular-check": "madge -c ./src/**/*.ts",
"dev": "concurrently \"pnpm run build:esm --watch\" \"pnpm run build:cjs --watch\" \"pnpm run build:type --watch\""
}
}
+111 -65
View File
@@ -1,5 +1,5 @@
import { createSHA256, path, randomUUID } from "@llamaindex/env";
import _ from "lodash";
import { chunkSizeCheck, lazyInitHash } from "./internal/decorator/node.js";
export enum NodeRelationship {
SOURCE = "SOURCE",
@@ -37,6 +37,16 @@ export type RelatedNodeType<T extends Metadata = Metadata> =
| RelatedNodeInfo<T>
| RelatedNodeInfo<T>[];
export type BaseNodeParams<T extends Metadata = Metadata> = {
id_?: string;
metadata?: T;
excludedEmbedMetadataKeys?: string[];
excludedLlmMetadataKeys?: string[];
relationships?: Partial<Record<NodeRelationship, RelatedNodeType<T>>>;
hash?: string;
embedding?: number[];
};
/**
* Generic abstract class for retrievable nodes
*/
@@ -47,21 +57,37 @@ export abstract class BaseNode<T extends Metadata = Metadata> {
*
* Set to a UUID by default.
*/
id_: string = randomUUID();
id_: string;
embedding?: number[];
// Metadata fields
metadata: T = {} as T;
excludedEmbedMetadataKeys: string[] = [];
excludedLlmMetadataKeys: string[] = [];
relationships: Partial<Record<NodeRelationship, RelatedNodeType<T>>> = {};
hash: string = "";
metadata: T;
excludedEmbedMetadataKeys: string[];
excludedLlmMetadataKeys: string[];
relationships: Partial<Record<NodeRelationship, RelatedNodeType<T>>>;
constructor(init?: Partial<BaseNode<T>>) {
Object.assign(this, init);
@lazyInitHash
accessor hash: string = "";
protected constructor(init?: BaseNodeParams<T>) {
const {
id_,
metadata,
excludedEmbedMetadataKeys,
excludedLlmMetadataKeys,
relationships,
hash,
embedding,
} = init || {};
this.id_ = id_ ?? randomUUID();
this.metadata = metadata ?? ({} as T);
this.excludedEmbedMetadataKeys = excludedEmbedMetadataKeys ?? [];
this.excludedLlmMetadataKeys = excludedLlmMetadataKeys ?? [];
this.relationships = relationships ?? {};
this.embedding = embedding;
}
abstract getType(): ObjectType;
abstract get type(): ObjectType;
abstract getContent(metadataMode: MetadataMode): string;
abstract getMetadataStr(metadataMode: MetadataMode): string;
@@ -146,7 +172,12 @@ export abstract class BaseNode<T extends Metadata = Metadata> {
* @see toMutableJSON - use to return a mutable JSON instead
*/
toJSON(): Record<string, any> {
return { ...this, type: this.getType() };
return {
...this,
type: this.type,
// hash is an accessor property, so it's not included in the rest operator
hash: this.hash,
};
}
clone(): BaseNode {
@@ -159,32 +190,43 @@ export abstract class BaseNode<T extends Metadata = Metadata> {
* @return {Record<string, any>} - The JSON representation of the object.
*/
toMutableJSON(): Record<string, any> {
return _.cloneDeep(this.toJSON());
return structuredClone(this.toJSON());
}
}
export type TextNodeParams<T extends Metadata = Metadata> =
BaseNodeParams<T> & {
text?: string;
textTemplate?: string;
startCharIdx?: number;
endCharIdx?: number;
metadataSeparator?: string;
};
/**
* TextNode is the default node type for text. Most common node type in LlamaIndex.TS
*/
export class TextNode<T extends Metadata = Metadata> extends BaseNode<T> {
text: string = "";
textTemplate: string = "";
text: string;
textTemplate: string;
startCharIdx?: number;
endCharIdx?: number;
// textTemplate: NOTE write your own formatter if needed
// metadataTemplate: NOTE write your own formatter if needed
metadataSeparator: string = "\n";
metadataSeparator: string;
constructor(init?: Partial<TextNode<T>>) {
constructor(init: TextNodeParams<T> = {}) {
super(init);
Object.assign(this, init);
if (new.target === TextNode) {
// Don't generate the hash repeatedly so only do it if this is
// constructing the derived class
this.hash = init?.hash ?? this.generateHash();
const { text, textTemplate, startCharIdx, endCharIdx, metadataSeparator } =
init;
this.text = text ?? "";
this.textTemplate = textTemplate ?? "";
if (startCharIdx) {
this.startCharIdx = startCharIdx;
}
this.endCharIdx = endCharIdx;
this.metadataSeparator = metadataSeparator ?? "\n";
}
/**
@@ -194,7 +236,7 @@ export class TextNode<T extends Metadata = Metadata> extends BaseNode<T> {
*/
generateHash() {
const hashFunction = createSHA256();
hashFunction.update(`type=${this.getType()}`);
hashFunction.update(`type=${this.type}`);
hashFunction.update(
`startCharIdx=${this.startCharIdx} endCharIdx=${this.endCharIdx}`,
);
@@ -202,10 +244,11 @@ export class TextNode<T extends Metadata = Metadata> extends BaseNode<T> {
return hashFunction.digest();
}
getType(): ObjectType {
get type() {
return ObjectType.TEXT;
}
@chunkSizeCheck
getContent(metadataMode: MetadataMode = MetadataMode.NONE): string {
const metadataStr = this.getMetadataStr(metadataMode).trim();
return `${metadataStr}\n\n${this.text}`.trim();
@@ -246,19 +289,21 @@ export class TextNode<T extends Metadata = Metadata> extends BaseNode<T> {
}
}
export type IndexNodeParams<T extends Metadata = Metadata> =
TextNodeParams<T> & {
indexId: string;
};
export class IndexNode<T extends Metadata = Metadata> extends TextNode<T> {
indexId: string = "";
indexId: string;
constructor(init?: Partial<IndexNode<T>>) {
constructor(init?: IndexNodeParams<T>) {
super(init);
Object.assign(this, init);
if (new.target === IndexNode) {
this.hash = init?.hash ?? this.generateHash();
}
const { indexId } = init || {};
this.indexId = indexId ?? "";
}
getType(): ObjectType {
get type() {
return ObjectType.INDEX;
}
}
@@ -267,16 +312,11 @@ export class IndexNode<T extends Metadata = Metadata> extends TextNode<T> {
* A document is just a special text node with a docId.
*/
export class Document<T extends Metadata = Metadata> extends TextNode<T> {
constructor(init?: Partial<Document<T>>) {
constructor(init?: TextNodeParams<T>) {
super(init);
Object.assign(this, init);
if (new.target === Document) {
this.hash = init?.hash ?? this.generateHash();
}
}
getType() {
get type() {
return ObjectType.DOCUMENT;
}
}
@@ -303,21 +343,21 @@ export function jsonToNode(json: any, type?: ObjectType) {
export type ImageType = string | Blob | URL;
export type ImageNodeConstructorProps<T extends Metadata> = Pick<
ImageNode<T>,
"image" | "id_"
> &
Partial<ImageNode<T>>;
export type ImageNodeParams<T extends Metadata = Metadata> =
TextNodeParams<T> & {
image: ImageType;
};
export class ImageNode<T extends Metadata = Metadata> extends TextNode<T> {
image: ImageType; // image as blob
constructor(init: ImageNodeConstructorProps<T>) {
constructor(init: ImageNodeParams<T>) {
super(init);
this.image = init.image;
const { image } = init;
this.image = image;
}
getType(): ObjectType {
get type() {
return ObjectType.IMAGE;
}
@@ -360,15 +400,11 @@ export class ImageNode<T extends Metadata = Metadata> extends TextNode<T> {
}
export class ImageDocument<T extends Metadata = Metadata> extends ImageNode<T> {
constructor(init: ImageNodeConstructorProps<T>) {
constructor(init: ImageNodeParams<T>) {
super(init);
if (new.target === ImageDocument) {
this.hash = init?.hash ?? this.generateHash();
}
}
getType() {
get type() {
return ObjectType.IMAGE_DOCUMENT;
}
}
@@ -381,22 +417,32 @@ export interface NodeWithScore<T extends Metadata = Metadata> {
score?: number;
}
export function splitNodesByType(nodes: BaseNode[]): {
imageNodes: ImageNode[];
textNodes: TextNode[];
} {
const imageNodes: ImageNode[] = [];
const textNodes: TextNode[] = [];
export enum ModalityType {
TEXT = "TEXT",
IMAGE = "IMAGE",
}
type NodesByType = {
[P in ModalityType]?: BaseNode[];
};
export function splitNodesByType(nodes: BaseNode[]): NodesByType {
const result: NodesByType = {};
for (const node of nodes) {
let type: ModalityType;
if (node instanceof ImageNode) {
imageNodes.push(node);
type = ModalityType.IMAGE;
} else if (node instanceof TextNode) {
textNodes.push(node);
type = ModalityType.TEXT;
} else {
throw new Error(`Unknown node type: ${node.type}`);
}
if (type in result) {
result[type]?.push(node);
} else {
result[type] = [node];
}
}
return {
imageNodes,
textNodes,
};
return result;
}
+1
View File
@@ -371,6 +371,7 @@ export function messagesToHistoryStr(messages: ChatMessage[]) {
}
export const defaultContextSystemPrompt = ({ context = "" }) => {
if (!context) return "";
return `Context information is below.
---------------------
${context}
+18 -17
View File
@@ -1,5 +1,4 @@
import { CallbackManager } from "./callbacks/CallbackManager.js";
import { OpenAIEmbedding } from "./embeddings/OpenAIEmbedding.js";
import { OpenAI } from "./llm/openai.js";
import { PromptHelper } from "./PromptHelper.js";
@@ -13,6 +12,16 @@ import {
setCallbackManager,
withCallbackManager,
} from "./internal/settings/CallbackManager.js";
import {
getEmbeddedModel,
setEmbeddedModel,
withEmbeddedModel,
} from "./internal/settings/EmbedModel.js";
import {
getChunkSize,
setChunkSize,
withChunkSize,
} from "./internal/settings/chunk-size.js";
import type { LLM } from "./llm/types.js";
import type { NodeParser } from "./nodeParsers/types.js";
@@ -39,16 +48,12 @@ 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>();
@@ -97,26 +102,22 @@ class GlobalSettings implements Config {
}
get embedModel(): BaseEmbedding {
if (this.#embedModel === null) {
this.#embedModel = new OpenAIEmbedding();
}
return this.#embedModelAsyncLocalStorage.getStore() ?? this.#embedModel;
return getEmbeddedModel();
}
set embedModel(embedModel: BaseEmbedding) {
this.#embedModel = embedModel;
setEmbeddedModel(embedModel);
}
withEmbedModel<Result>(embedModel: BaseEmbedding, fn: () => Result): Result {
return this.#embedModelAsyncLocalStorage.run(embedModel, fn);
return withEmbeddedModel(embedModel, fn);
}
get nodeParser(): NodeParser {
if (this.#nodeParser === null) {
this.#nodeParser = new SimpleNodeParser({
chunkSize: this.#chunkSize,
chunkOverlap: this.#chunkOverlap,
chunkSize: this.chunkSize,
chunkOverlap: this.chunkOverlap,
});
}
@@ -147,15 +148,15 @@ class GlobalSettings implements Config {
}
set chunkSize(chunkSize: number | undefined) {
this.#chunkSize = chunkSize;
setChunkSize(chunkSize);
}
get chunkSize(): number | undefined {
return this.#chunkSizeAsyncLocalStorage.getStore() ?? this.#chunkSize;
return getChunkSize();
}
withChunkSize<Result>(chunkSize: number, fn: () => Result): Result {
return this.#chunkSizeAsyncLocalStorage.run(chunkSize, fn);
return withChunkSize(chunkSize, fn);
}
get chunkOverlap(): number | undefined {
+3 -2
View File
@@ -39,9 +39,10 @@ export class AnthropicAgent extends AgentRunner<Anthropic> {
constructor(params: AnthropicAgentParams) {
super({
llm:
params.llm ?? Settings.llm instanceof Anthropic
params.llm ??
(Settings.llm instanceof Anthropic
? (Settings.llm as Anthropic)
: new Anthropic(),
: new Anthropic()),
chatHistory: params.chatHistory ?? [],
systemPrompt: params.systemPrompt ?? null,
runner: new AnthropicAgentWorker(),
+32 -48
View File
@@ -1,9 +1,4 @@
import {
ReadableStream,
TransformStream,
pipeline,
randomUUID,
} from "@llamaindex/env";
import { ReadableStream, TransformStream, randomUUID } from "@llamaindex/env";
import { Settings } from "../Settings.js";
import {
type ChatEngine,
@@ -21,7 +16,6 @@ import type {
LLM,
MessageContent,
} from "../llm/index.js";
import { extractText } from "../llm/utils.js";
import type { BaseToolWithCall, ToolOutput } from "../types.js";
import type {
AgentTaskContext,
@@ -169,7 +163,7 @@ export abstract class AgentWorker<
abstract taskHandler: TaskHandler<AI, Store, AdditionalMessageOptions>;
public createTask(
query: string,
query: MessageContent,
context: AgentTaskContext<AI, Store, AdditionalMessageOptions>,
): ReadableStream<TaskStepOutput<AI, Store, AdditionalMessageOptions>> {
context.store.messages.push({
@@ -305,7 +299,7 @@ export abstract class AgentRunner<
});
}
}
return this.#runner.createTask(extractText(message), {
return this.#runner.createTask(message, {
stream,
toolCallCount: 0,
llm: this.#llm,
@@ -340,46 +334,36 @@ export abstract class AgentRunner<
| ReadableStream<AgentStreamChatResponse<AdditionalMessageOptions>>
> {
const task = this.createTask(params.message, !!params.stream);
const stepOutput = await pipeline(
task,
async (
iter: AsyncIterable<
TaskStepOutput<AI, Store, AdditionalMessageOptions>
>,
) => {
for await (const stepOutput of iter) {
// update chat history for each round
this.#chatHistory = [...stepOutput.taskStep.context.store.messages];
if (stepOutput.isLast) {
return stepOutput;
}
}
throw new Error("Task did not complete");
},
);
const { output, taskStep } = stepOutput;
if (isAsyncIterable(output)) {
return output.pipeThrough<
AgentStreamChatResponse<AdditionalMessageOptions>
>(
new TransformStream({
transform(chunk, controller) {
controller.enqueue({
response: chunk,
get sources() {
return [...taskStep.context.store.toolOutputs];
for await (const stepOutput of task) {
// update chat history for each round
this.#chatHistory = [...stepOutput.taskStep.context.store.messages];
if (stepOutput.isLast) {
const { output, taskStep } = stepOutput;
if (isAsyncIterable(output)) {
return output.pipeThrough<
AgentStreamChatResponse<AdditionalMessageOptions>
>(
new TransformStream({
transform(chunk, controller) {
controller.enqueue({
response: chunk,
get sources() {
return [...taskStep.context.store.toolOutputs];
},
});
},
});
},
}),
);
} else {
return {
response: output,
get sources() {
return [...taskStep.context.store.toolOutputs];
},
} satisfies AgentChatResponse<AdditionalMessageOptions>;
}),
);
} else {
return {
response: output,
get sources() {
return [...taskStep.context.store.toolOutputs];
},
} satisfies AgentChatResponse<AdditionalMessageOptions>;
}
}
}
throw new Error("Task ended without a last step.");
}
}
+13 -20
View File
@@ -1,4 +1,5 @@
import { pipeline, ReadableStream } from "@llamaindex/env";
import { ReadableStream } from "@llamaindex/env";
import { Settings } from "../Settings.js";
import { stringifyJSONToMessageContent } from "../internal/utils.js";
import type {
ChatResponseChunk,
@@ -8,7 +9,6 @@ import type {
} from "../llm/index.js";
import { OpenAI } from "../llm/openai.js";
import { ObjectRetriever } from "../objects/index.js";
import { Settings } from "../Settings.js";
import type { BaseToolWithCall } from "../types.js";
import { AgentRunner, AgentWorker, type AgentParamsBase } from "./base.js";
import type { TaskHandler } from "./types.js";
@@ -36,9 +36,10 @@ export class OpenAIAgent extends AgentRunner<OpenAI> {
constructor(params: OpenAIAgentParams) {
super({
llm:
params.llm ?? Settings.llm instanceof OpenAI
params.llm ??
(Settings.llm instanceof OpenAI
? (Settings.llm as OpenAI)
: new OpenAI(),
: new OpenAI()),
chatHistory: params.chatHistory ?? [],
runner: new OpenAIAgentWorker(),
systemPrompt: params.systemPrompt ?? null,
@@ -130,22 +131,14 @@ export class OpenAIAgent extends AgentRunner<OpenAI> {
if (hasToolCall) {
// you need to consume the response to get the full toolCalls
const toolCalls = await pipeline(
pipStream,
async (
iter: AsyncIterable<ChatResponseChunk<ToolCallLLMMessageOptions>>,
) => {
const toolCalls = new Map<string, ToolCall | PartialToolCall>();
for await (const chunk of iter) {
if (chunk.options && "toolCall" in chunk.options) {
const toolCall = chunk.options.toolCall;
toolCalls.set(toolCall.id, toolCall);
}
}
return [...toolCalls.values()];
},
);
for (const toolCall of toolCalls) {
const toolCalls = new Map<string, ToolCall | PartialToolCall>();
for await (const chunk of pipStream) {
if (chunk.options && "toolCall" in chunk.options) {
const toolCall = chunk.options.toolCall;
toolCalls.set(toolCall.id, toolCall);
}
}
for (const toolCall of toolCalls.values()) {
const targetTool = tools.find(
(tool) => tool.metadata.name === toolCall.name,
);
@@ -1,4 +1,5 @@
import { GeminiSessionStore, type GeminiSession } from "../llm/gemini.js";
import { GeminiSession, GeminiSessionStore } from "../llm/gemini/base.js";
import { GEMINI_BACKENDS } from "../llm/gemini/types.js";
import { BaseEmbedding } from "./types.js";
export enum GEMINI_EMBEDDING_MODEL {
@@ -8,6 +9,7 @@ export enum GEMINI_EMBEDDING_MODEL {
/**
* GeminiEmbedding is an alias for Gemini that implements the BaseEmbedding interface.
* Note: Vertex SDK currently does not support embeddings
*/
export class GeminiEmbedding extends BaseEmbedding {
model: GEMINI_EMBEDDING_MODEL;
@@ -16,11 +18,15 @@ export class GeminiEmbedding extends BaseEmbedding {
constructor(init?: Partial<GeminiEmbedding>) {
super();
this.model = init?.model ?? GEMINI_EMBEDDING_MODEL.EMBEDDING_001;
this.session = init?.session ?? GeminiSessionStore.get();
this.session =
init?.session ??
(GeminiSessionStore.get({
backend: GEMINI_BACKENDS.GOOGLE,
}) as GeminiSession);
}
private async getEmbedding(prompt: string): Promise<number[]> {
const client = this.session.gemini.getGenerativeModel({
const client = this.session.getGenerativeModel({
model: this.model,
});
const result = await client.embedContent(prompt);
@@ -1,5 +1,7 @@
import {
ImageNode,
MetadataMode,
ModalityType,
splitNodesByType,
type BaseNode,
type ImageType,
@@ -24,7 +26,9 @@ export abstract class MultiModalEmbedding extends BaseEmbedding {
}
async transform(nodes: BaseNode[], _options?: any): Promise<BaseNode[]> {
const { imageNodes, textNodes } = splitNodesByType(nodes);
const nodeMap = splitNodesByType(nodes);
const imageNodes = nodeMap[ModalityType.IMAGE] ?? [];
const textNodes = nodeMap[ModalityType.TEXT] ?? [];
const embeddings = await batchEmbeddings(
textNodes.map((node) => node.getContent(MetadataMode.EMBED)),
@@ -37,7 +41,7 @@ export abstract class MultiModalEmbedding extends BaseEmbedding {
}
const imageEmbeddings = await batchEmbeddings(
imageNodes.map((n) => n.image),
imageNodes.map((n) => (n as ImageNode).image),
this.getImageEmbeddings.bind(this),
this.embedBatchSize,
_options,
+4 -6
View File
@@ -1,9 +1,9 @@
import { defaultFS } from "@llamaindex/env";
import { fs } from "@llamaindex/env";
import _ from "lodash";
import { filetypemime } from "magic-bytes.js";
import type { ImageType } from "../Node.js";
import { DEFAULT_SIMILARITY_TOP_K } from "../constants.js";
import { VectorStoreQueryMode } from "../storage/vectorStore/types.js";
import type { VectorStoreQueryMode } from "../storage/vectorStore/types.js";
/**
* Similarity type
@@ -126,11 +126,9 @@ export function getTopKEmbeddingsLearner(
embeddings: number[][],
similarityTopK?: number,
embeddingsIds?: any[],
queryMode: VectorStoreQueryMode = VectorStoreQueryMode.SVM,
queryMode?: VectorStoreQueryMode,
): [number[], any[]] {
throw new Error("Not implemented yet");
// To support SVM properly we're probably going to have to use something like
// https://github.com/mljs/libsvm which itself hasn't been updated in a while
}
// eslint-disable-next-line max-params
@@ -243,7 +241,7 @@ export async function imageToDataUrl(input: ImageType): Promise<string> {
_.isString(input)
) {
// string or file URL
const dataBuffer = await defaultFS.readFile(
const dataBuffer = await fs.readFile(
input instanceof URL ? input.pathname : input,
);
input = new Blob([dataBuffer]);
@@ -31,6 +31,7 @@ export class ContextChatEngine extends PromptMixin implements ChatEngine {
chatModel: LLM;
chatHistory: ChatHistory;
contextGenerator: ContextGenerator;
systemPrompt?: string;
constructor(init: {
retriever: BaseRetriever;
@@ -38,9 +39,9 @@ export class ContextChatEngine extends PromptMixin implements ChatEngine {
chatHistory?: ChatMessage[];
contextSystemPrompt?: ContextSystemPrompt;
nodePostprocessors?: BaseNodePostprocessor[];
systemPrompt?: string;
}) {
super();
this.chatModel =
init.chatModel ?? new OpenAI({ model: "gpt-3.5-turbo-16k" });
this.chatHistory = getHistory(init?.chatHistory);
@@ -49,6 +50,7 @@ export class ContextChatEngine extends PromptMixin implements ChatEngine {
contextSystemPrompt: init?.contextSystemPrompt,
nodePostprocessors: init?.nodePostprocessors,
});
this.systemPrompt = init.systemPrompt;
}
protected _getPromptModules(): Record<string, ContextGenerator> {
@@ -71,7 +73,6 @@ export class ContextChatEngine extends PromptMixin implements ChatEngine {
message,
chatHistory,
);
if (stream) {
const stream = await this.chatModel.chat({
messages: requestMessages.messages,
@@ -113,9 +114,16 @@ export class ContextChatEngine extends PromptMixin implements ChatEngine {
});
const textOnly = extractText(message);
const context = await this.contextGenerator.generate(textOnly);
const messages = await chatHistory.requestMessages(
context ? [context.message] : undefined,
);
const systemMessage = this.prependSystemPrompt(context.message);
const messages = await chatHistory.requestMessages([systemMessage]);
return { nodes: context.nodes, messages };
}
private prependSystemPrompt(message: ChatMessage): ChatMessage {
if (!this.systemPrompt) return message;
return {
...message,
content: this.systemPrompt.trim() + "\n" + message.content,
};
}
}
+3
View File
@@ -10,3 +10,6 @@ export {
HuggingFaceEmbedding,
HuggingFaceEmbeddingModelType,
} from "./embeddings/HuggingFaceEmbedding.js";
export { type VertexGeminiSessionOptions } from "./llm/gemini/types.js";
export { GeminiVertexSession } from "./llm/gemini/vertex.js";
-4
View File
@@ -6,7 +6,6 @@ import { runTransformations } from "../ingestion/IngestionPipeline.js";
import type { StorageContext } from "../storage/StorageContext.js";
import type { BaseDocumentStore } from "../storage/docStore/types.js";
import type { BaseIndexStore } from "../storage/indexStore/types.js";
import type { VectorStore } from "../storage/vectorStore/types.js";
import type { BaseSynthesizer } from "../synthesizers/types.js";
import type { QueryEngine } from "../types.js";
import { IndexStruct } from "./IndexStruct.js";
@@ -47,7 +46,6 @@ export interface BaseIndexInit<T> {
serviceContext?: ServiceContext;
storageContext: StorageContext;
docStore: BaseDocumentStore;
vectorStore?: VectorStore;
indexStore?: BaseIndexStore;
indexStruct: T;
}
@@ -60,7 +58,6 @@ export abstract class BaseIndex<T> {
serviceContext?: ServiceContext;
storageContext: StorageContext;
docStore: BaseDocumentStore;
vectorStore?: VectorStore;
indexStore?: BaseIndexStore;
indexStruct: T;
@@ -68,7 +65,6 @@ export abstract class BaseIndex<T> {
this.serviceContext = init.serviceContext;
this.storageContext = init.storageContext;
this.docStore = init.docStore;
this.vectorStore = init.vectorStore;
this.indexStore = init.indexStore;
this.indexStruct = init.indexStruct;
}
+101 -108
View File
@@ -1,19 +1,22 @@
import type { BaseNode, Document, NodeWithScore } from "../../Node.js";
import { ImageNode, ObjectType, splitNodesByType } from "../../Node.js";
import {
ImageNode,
ModalityType,
ObjectType,
splitNodesByType,
type BaseNode,
type Document,
type NodeWithScore,
} from "../../Node.js";
import type { BaseRetriever, RetrieveParams } from "../../Retriever.js";
import type { ServiceContext } from "../../ServiceContext.js";
import {
embedModelFromSettingsOrContext,
nodeParserFromSettingsOrContext,
} from "../../Settings.js";
import { nodeParserFromSettingsOrContext } from "../../Settings.js";
import { DEFAULT_SIMILARITY_TOP_K } from "../../constants.js";
import { ClipEmbedding } from "../../embeddings/ClipEmbedding.js";
import type {
BaseEmbedding,
MultiModalEmbedding,
} from "../../embeddings/index.js";
import type { BaseEmbedding } from "../../embeddings/index.js";
import { RetrieverQueryEngine } from "../../engines/query/RetrieverQueryEngine.js";
import { runTransformations } from "../../ingestion/IngestionPipeline.js";
import {
addNodesToVectorStores,
runTransformations,
} from "../../ingestion/IngestionPipeline.js";
import {
DocStoreStrategy,
createDocStoreStrategy,
@@ -26,6 +29,7 @@ import { storageContextFromDefaults } from "../../storage/StorageContext.js";
import type {
MetadataFilters,
VectorStore,
VectorStoreByType,
VectorStoreQuery,
VectorStoreQueryResult,
} from "../../storage/index.js";
@@ -45,36 +49,28 @@ export interface VectorIndexOptions extends IndexStructOptions {
nodes?: BaseNode[];
serviceContext?: ServiceContext;
storageContext?: StorageContext;
imageVectorStore?: VectorStore;
vectorStore?: VectorStore;
vectorStores?: VectorStoreByType;
logProgress?: boolean;
}
export interface VectorIndexConstructorProps extends BaseIndexInit<IndexDict> {
indexStore: BaseIndexStore;
imageVectorStore?: VectorStore;
vectorStores?: VectorStoreByType;
}
/**
* The VectorStoreIndex, an index that stores the nodes only according to their vector embedings.
* The VectorStoreIndex, an index that stores the nodes only according to their vector embeddings.
*/
export class VectorStoreIndex extends BaseIndex<IndexDict> {
vectorStore: VectorStore;
indexStore: BaseIndexStore;
embedModel: BaseEmbedding;
imageVectorStore?: VectorStore;
imageEmbedModel?: MultiModalEmbedding;
embedModel?: BaseEmbedding;
vectorStores: VectorStoreByType;
private constructor(init: VectorIndexConstructorProps) {
super(init);
this.indexStore = init.indexStore;
this.vectorStore = init.vectorStore ?? init.storageContext.vectorStore;
this.embedModel = embedModelFromSettingsOrContext(init.serviceContext);
this.imageVectorStore =
init.imageVectorStore ?? init.storageContext.imageVectorStore;
if (this.imageVectorStore) {
this.imageEmbedModel = new ClipEmbedding();
}
this.vectorStores = init.vectorStores ?? init.storageContext.vectorStores;
this.embedModel = init.serviceContext?.embedModel;
}
/**
@@ -110,8 +106,7 @@ export class VectorStoreIndex extends BaseIndex<IndexDict> {
docStore,
indexStruct,
indexStore,
vectorStore: options.vectorStore,
imageVectorStore: options.imageVectorStore,
vectorStores: options.vectorStores,
});
if (options.nodes) {
@@ -169,20 +164,17 @@ export class VectorStoreIndex extends BaseIndex<IndexDict> {
nodes: BaseNode[],
options?: { logProgress?: boolean },
): Promise<BaseNode[]> {
const { imageNodes, textNodes } = splitNodesByType(nodes);
if (imageNodes.length > 0) {
if (!this.imageEmbedModel) {
throw new Error(
"Cannot calculate image nodes embedding without 'imageEmbedModel' set",
);
const nodeMap = splitNodesByType(nodes);
for (const type in nodeMap) {
const nodes = nodeMap[type as ModalityType];
const embedModel =
this.embedModel ?? this.vectorStores[type as ModalityType]?.embedModel;
if (embedModel && nodes) {
await embedModel.transform(nodes, {
logProgress: options?.logProgress,
});
}
await this.imageEmbedModel.transform(imageNodes, {
logProgress: options?.logProgress,
});
}
await this.embedModel.transform(textNodes, {
logProgress: options?.logProgress,
});
return nodes;
}
@@ -210,14 +202,15 @@ export class VectorStoreIndex extends BaseIndex<IndexDict> {
docStoreStrategy?: DocStoreStrategy;
} = {},
): Promise<VectorStoreIndex> {
args.storageContext =
args.storageContext ?? (await storageContextFromDefaults({}));
args.vectorStores = args.vectorStores ?? args.storageContext.vectorStores;
args.docStoreStrategy =
args.docStoreStrategy ??
// set doc store strategy defaults to the same as for the IngestionPipeline
(args.vectorStore
(args.vectorStores
? DocStoreStrategy.UPSERTS
: DocStoreStrategy.DUPLICATES_ONLY);
args.storageContext =
args.storageContext ?? (await storageContextFromDefaults({}));
args.serviceContext = args.serviceContext;
const docStore = args.storageContext.docStore;
@@ -226,10 +219,11 @@ export class VectorStoreIndex extends BaseIndex<IndexDict> {
}
// use doc store strategy to avoid duplicates
const vectorStores = Object.values(args.vectorStores ?? {});
const docStoreStrategy = createDocStoreStrategy(
args.docStoreStrategy,
docStore,
args.vectorStore,
vectorStores,
);
args.nodes = await runTransformations(
documents,
@@ -243,20 +237,18 @@ export class VectorStoreIndex extends BaseIndex<IndexDict> {
return await this.init(args);
}
static async fromVectorStore(
vectorStore: VectorStore,
static async fromVectorStores(
vectorStores: VectorStoreByType,
serviceContext?: ServiceContext,
imageVectorStore?: VectorStore,
) {
if (!vectorStore.storesText) {
if (!vectorStores[ModalityType.TEXT]?.storesText) {
throw new Error(
"Cannot initialize from a vector store that does not store text",
);
}
const storageContext = await storageContextFromDefaults({
vectorStore,
imageVectorStore,
vectorStores,
});
const index = await this.init({
@@ -268,6 +260,16 @@ export class VectorStoreIndex extends BaseIndex<IndexDict> {
return index;
}
static async fromVectorStore(
vectorStore: VectorStore,
serviceContext?: ServiceContext,
) {
return this.fromVectorStores(
{ [ModalityType.TEXT]: vectorStore },
serviceContext,
);
}
asRetriever(
options?: Omit<VectorIndexRetrieverOptions, "index">,
): VectorIndexRetriever {
@@ -301,17 +303,16 @@ export class VectorStoreIndex extends BaseIndex<IndexDict> {
}
protected async insertNodesToStore(
vectorStore: VectorStore,
newIds: string[],
nodes: BaseNode[],
vectorStore: VectorStore,
): Promise<void> {
const newIds = await vectorStore.add(nodes);
// NOTE: if the vector store doesn't store text,
// we need to add the nodes to the index struct and document store
// NOTE: if the vector store keeps text,
// we only need to add image and index nodes
for (let i = 0; i < nodes.length; ++i) {
const type = nodes[i].getType();
const { type } = nodes[i];
if (
!vectorStore.storesText ||
type === ObjectType.INDEX ||
@@ -333,14 +334,11 @@ export class VectorStoreIndex extends BaseIndex<IndexDict> {
return;
}
nodes = await this.getNodeEmbeddingResults(nodes, options);
const { imageNodes, textNodes } = splitNodesByType(nodes);
if (imageNodes.length > 0) {
if (!this.imageVectorStore) {
throw new Error("Cannot insert image nodes without image vector store");
}
await this.insertNodesToStore(this.imageVectorStore, imageNodes);
}
await this.insertNodesToStore(this.vectorStore, textNodes);
await addNodesToVectorStores(
nodes,
this.vectorStores,
this.insertNodesToStore.bind(this),
);
await this.indexStore.addIndexStruct(this.indexStruct);
}
@@ -348,11 +346,9 @@ export class VectorStoreIndex extends BaseIndex<IndexDict> {
refDocId: string,
deleteFromDocStore: boolean = true,
): Promise<void> {
await this.deleteRefDocFromStore(this.vectorStore, refDocId);
if (this.imageVectorStore) {
await this.deleteRefDocFromStore(this.imageVectorStore, refDocId);
for (const vectorStore of Object.values(this.vectorStores)) {
await this.deleteRefDocFromStore(vectorStore, refDocId);
}
if (deleteFromDocStore) {
await this.docStore.deleteDocument(refDocId, false);
}
@@ -382,28 +378,34 @@ export class VectorStoreIndex extends BaseIndex<IndexDict> {
* VectorIndexRetriever retrieves nodes from a VectorIndex.
*/
type TopKMap = { [P in ModalityType]: number };
export type VectorIndexRetrieverOptions = {
index: VectorStoreIndex;
similarityTopK?: number;
imageSimilarityTopK?: number;
topK?: TopKMap;
};
export class VectorIndexRetriever implements BaseRetriever {
index: VectorStoreIndex;
similarityTopK: number;
imageSimilarityTopK: number;
topK: TopKMap;
serviceContext?: ServiceContext;
constructor({
index,
similarityTopK,
imageSimilarityTopK,
}: VectorIndexRetrieverOptions) {
constructor({ index, similarityTopK, topK }: VectorIndexRetrieverOptions) {
this.index = index;
this.serviceContext = this.index.serviceContext;
this.similarityTopK = similarityTopK ?? DEFAULT_SIMILARITY_TOP_K;
this.imageSimilarityTopK = imageSimilarityTopK ?? DEFAULT_SIMILARITY_TOP_K;
this.topK = topK ?? {
[ModalityType.TEXT]: similarityTopK ?? DEFAULT_SIMILARITY_TOP_K,
[ModalityType.IMAGE]: DEFAULT_SIMILARITY_TOP_K,
};
}
/**
* @deprecated, pass topK in constructor instead
*/
set similarityTopK(similarityTopK: number) {
this.topK[ModalityType.TEXT] = similarityTopK;
}
@wrapEventCaller
@@ -416,13 +418,21 @@ export class VectorIndexRetriever implements BaseRetriever {
query,
},
});
let nodesWithScores = await this.textRetrieve(
query,
preFilters as MetadataFilters,
);
nodesWithScores = nodesWithScores.concat(
await this.textToImageRetrieve(query, preFilters as MetadataFilters),
);
const vectorStores = this.index.vectorStores;
let nodesWithScores: NodeWithScore[] = [];
for (const type in vectorStores) {
// TODO: add retrieval by using an image as query
const vectorStore: VectorStore = vectorStores[type as ModalityType]!;
nodesWithScores = nodesWithScores.concat(
await this.textRetrieve(
query,
type as ModalityType,
vectorStore,
preFilters as MetadataFilters,
),
);
}
getCallbackManager().dispatchEvent("retrieve-end", {
payload: {
query,
@@ -439,34 +449,17 @@ export class VectorIndexRetriever implements BaseRetriever {
protected async textRetrieve(
query: string,
type: ModalityType,
vectorStore: VectorStore,
preFilters?: MetadataFilters,
): Promise<NodeWithScore[]> {
const options = {};
const q = await this.buildVectorStoreQuery(
this.index.embedModel,
this.index.embedModel ?? vectorStore.embedModel,
query,
this.similarityTopK,
this.topK[type],
preFilters,
);
const result = await this.index.vectorStore.query(q, options);
return this.buildNodeListFromQueryResult(result);
}
private async textToImageRetrieve(
query: string,
preFilters?: MetadataFilters,
) {
if (!this.index.imageEmbedModel || !this.index.imageVectorStore) {
// no-op if image embedding and vector store are not set
return [];
}
const q = await this.buildVectorStoreQuery(
this.index.imageEmbedModel,
query,
this.imageSimilarityTopK,
preFilters,
);
const result = await this.index.imageVectorStore.query(q, preFilters);
const result = await vectorStore.query(q);
return this.buildNodeListFromQueryResult(result);
}
@@ -479,9 +472,9 @@ export class VectorIndexRetriever implements BaseRetriever {
const queryEmbedding = await embedModel.getQueryEmbedding(query);
return {
queryEmbedding: queryEmbedding,
queryEmbedding,
mode: VectorStoreQueryMode.DEFAULT,
similarityTopK: similarityTopK,
similarityTopK,
filters: preFilters ?? undefined,
};
}
@@ -1,5 +1,11 @@
import type { PlatformApiClient } from "@llamaindex/cloud";
import type { BaseNode, Document } from "../Node.js";
import {
ModalityType,
splitNodesByType,
type BaseNode,
type Document,
type Metadata,
} from "../Node.js";
import { getPipelineCreate } from "../cloud/config.js";
import {
DEFAULT_PIPELINE_NAME,
@@ -9,7 +15,10 @@ import {
import { getAppBaseUrl, getClient } from "../cloud/utils.js";
import type { BaseReader } from "../readers/type.js";
import type { BaseDocumentStore } from "../storage/docStore/types.js";
import type { VectorStore } from "../storage/vectorStore/types.js";
import type {
VectorStore,
VectorStoreByType,
} from "../storage/vectorStore/types.js";
import { IngestionCache, getTransformationHash } from "./IngestionCache.js";
import {
DocStoreStrategy,
@@ -63,6 +72,7 @@ export class IngestionPipeline {
documents?: Document[];
reader?: BaseReader;
vectorStore?: VectorStore;
vectorStores?: VectorStoreByType;
docStore?: BaseDocumentStore;
docStoreStrategy: DocStoreStrategy = DocStoreStrategy.UPSERTS;
cache?: IngestionCache;
@@ -80,10 +90,13 @@ export class IngestionPipeline {
if (!this.docStore) {
this.docStoreStrategy = DocStoreStrategy.NONE;
}
this.vectorStores = this.vectorStores ?? {
[ModalityType.TEXT]: this.vectorStore,
};
this._docStoreStrategy = createDocStoreStrategy(
this.docStoreStrategy,
this.docStore,
this.vectorStore,
Object.values(this.vectorStores),
);
if (!this.disableCache) {
this.cache = new IngestionCache();
@@ -123,9 +136,9 @@ export class IngestionPipeline {
transformOptions,
args,
);
if (this.vectorStore) {
if (this.vectorStores) {
const nodesToAdd = nodes.filter((node) => node.embedding);
await this.vectorStore.add(nodesToAdd);
await addNodesToVectorStores(nodesToAdd, this.vectorStores);
}
return nodes;
}
@@ -176,3 +189,30 @@ export class IngestionPipeline {
return pipeline.id;
}
}
export async function addNodesToVectorStores(
nodes: BaseNode<Metadata>[],
vectorStores: VectorStoreByType,
nodesAdded?: (
newIds: string[],
nodes: BaseNode<Metadata>[],
vectorStore: VectorStore,
) => Promise<void>,
) {
const nodeMap = splitNodesByType(nodes);
for (const type in nodeMap) {
const nodes = nodeMap[type as ModalityType];
if (nodes) {
const vectorStore = vectorStores[type as ModalityType];
if (!vectorStore) {
throw new Error(
`Cannot insert nodes of type ${type} without assigned vector store`,
);
}
const newIds = await vectorStore.add(nodes);
if (nodesAdded) {
await nodesAdded(newIds, nodes, vectorStore);
}
}
}
}
@@ -10,11 +10,11 @@ import { classify } from "./classify.js";
*/
export class UpsertsAndDeleteStrategy implements TransformComponent {
protected docStore: BaseDocumentStore;
protected vectorStore?: VectorStore;
protected vectorStores?: VectorStore[];
constructor(docStore: BaseDocumentStore, vectorStore?: VectorStore) {
constructor(docStore: BaseDocumentStore, vectorStores?: VectorStore[]) {
this.docStore = docStore;
this.vectorStore = vectorStore;
this.vectorStores = vectorStores;
}
async transform(nodes: BaseNode[]): Promise<BaseNode[]> {
@@ -26,16 +26,20 @@ export class UpsertsAndDeleteStrategy implements TransformComponent {
// remove unused docs
for (const refDocId of unusedDocs) {
await this.docStore.deleteRefDoc(refDocId, false);
if (this.vectorStore) {
await this.vectorStore.delete(refDocId);
if (this.vectorStores) {
for (const vectorStore of this.vectorStores) {
await vectorStore.delete(refDocId);
}
}
}
// remove missing docs
for (const docId of missingDocs) {
await this.docStore.deleteDocument(docId, true);
if (this.vectorStore) {
await this.vectorStore.delete(docId);
if (this.vectorStores) {
for (const vectorStore of this.vectorStores) {
await vectorStore.delete(docId);
}
}
}
@@ -9,11 +9,11 @@ import { classify } from "./classify.js";
*/
export class UpsertsStrategy implements TransformComponent {
protected docStore: BaseDocumentStore;
protected vectorStore?: VectorStore;
protected vectorStores?: VectorStore[];
constructor(docStore: BaseDocumentStore, vectorStore?: VectorStore) {
constructor(docStore: BaseDocumentStore, vectorStores?: VectorStore[]) {
this.docStore = docStore;
this.vectorStore = vectorStore;
this.vectorStores = vectorStores;
}
async transform(nodes: BaseNode[]): Promise<BaseNode[]> {
@@ -21,8 +21,10 @@ export class UpsertsStrategy implements TransformComponent {
// remove unused docs
for (const refDocId of unusedDocs) {
await this.docStore.deleteRefDoc(refDocId, false);
if (this.vectorStore) {
await this.vectorStore.delete(refDocId);
if (this.vectorStores) {
for (const vectorStore of this.vectorStores) {
await vectorStore.delete(refDocId);
}
}
}
// add non-duplicate docs
@@ -28,7 +28,7 @@ class NoOpStrategy implements TransformComponent {
export function createDocStoreStrategy(
docStoreStrategy: DocStoreStrategy,
docStore?: BaseDocumentStore,
vectorStore?: VectorStore,
vectorStores: VectorStore[] = [],
): TransformComponent {
if (docStoreStrategy === DocStoreStrategy.NONE) {
return new NoOpStrategy();
@@ -36,11 +36,11 @@ export function createDocStoreStrategy(
if (!docStore) {
throw new Error("docStore is required to create a doc store strategy.");
}
if (vectorStore) {
if (vectorStores.length > 0) {
if (docStoreStrategy === DocStoreStrategy.UPSERTS) {
return new UpsertsStrategy(docStore, vectorStore);
return new UpsertsStrategy(docStore, vectorStores);
} else if (docStoreStrategy === DocStoreStrategy.UPSERTS_AND_DELETE) {
return new UpsertsAndDeleteStrategy(docStore, vectorStore);
return new UpsertsAndDeleteStrategy(docStore, vectorStores);
} else if (docStoreStrategy === DocStoreStrategy.DUPLICATES_ONLY) {
return new DuplicatesStrategy(docStore);
} else {
@@ -0,0 +1,60 @@
import { getEnv } from "@llamaindex/env";
import type { BaseNode } from "../../Node.js";
import { getChunkSize } from "../settings/chunk-size.js";
const emitOnce = false;
export function chunkSizeCheck(
contentGetter: () => string,
_context: ClassMethodDecoratorContext | ClassGetterDecoratorContext,
) {
return function <Node extends BaseNode>(this: Node) {
const content = contentGetter.call(this);
const chunkSize = getChunkSize();
const enableChunkSizeCheck = getEnv("ENABLE_CHUNK_SIZE_CHECK") === "true";
if (
enableChunkSizeCheck &&
chunkSize !== undefined &&
content.length > chunkSize
) {
console.warn(
`Node (${this.id_}) is larger than chunk size: ${content.length}`,
);
if (!emitOnce) {
console.warn(
"Will truncate the content if it is larger than chunk size",
);
console.warn("If you want to disable this behavior:");
console.warn(" 1. Set Settings.chunkSize = undefined");
console.warn(" 2. Set Settings.chunkSize to a larger value");
console.warn(
" 3. Change the way of splitting content into smaller chunks",
);
}
return content.slice(0, chunkSize);
}
return content;
};
}
export function lazyInitHash(
value: ClassAccessorDecoratorTarget<BaseNode, string>,
_context: ClassAccessorDecoratorContext,
): ClassAccessorDecoratorResult<BaseNode, string> {
return {
get() {
const oldValue = value.get.call(this);
if (oldValue === "") {
const hash = this.generateHash();
value.set.call(this, hash);
}
return value.get.call(this);
},
set(newValue: string) {
value.set.call(this, newValue);
},
init(value: string): string {
return value;
},
};
}
@@ -0,0 +1,24 @@
import { AsyncLocalStorage } from "@llamaindex/env";
import { OpenAIEmbedding } from "../../embeddings/OpenAIEmbedding.js";
import type { BaseEmbedding } from "../../embeddings/index.js";
const embeddedModelAsyncLocalStorage = new AsyncLocalStorage<BaseEmbedding>();
let globalEmbeddedModel: BaseEmbedding | null = null;
export function getEmbeddedModel(): BaseEmbedding {
if (globalEmbeddedModel === null) {
globalEmbeddedModel = new OpenAIEmbedding();
}
return embeddedModelAsyncLocalStorage.getStore() ?? globalEmbeddedModel;
}
export function setEmbeddedModel(embeddedModel: BaseEmbedding) {
globalEmbeddedModel = embeddedModel;
}
export function withEmbeddedModel<Result>(
embeddedModel: BaseEmbedding,
fn: () => Result,
): Result {
return embeddedModelAsyncLocalStorage.run(embeddedModel, fn);
}
@@ -0,0 +1,19 @@
import { AsyncLocalStorage } from "@llamaindex/env";
const chunkSizeAsyncLocalStorage = new AsyncLocalStorage<number | undefined>();
const globalChunkSize: number | null = null;
export function getChunkSize(): number | undefined {
return globalChunkSize ?? chunkSizeAsyncLocalStorage.getStore();
}
export function setChunkSize(chunkSize: number | undefined) {
chunkSizeAsyncLocalStorage.enterWith(chunkSize);
}
export function withChunkSize<Result>(
embeddedModel: number,
fn: () => Result,
): Result {
return chunkSizeAsyncLocalStorage.run(embeddedModel, fn);
}
-355
View File
@@ -1,355 +0,0 @@
import {
ChatSession,
GoogleGenerativeAI,
type Content as GeminiMessageContent,
type Part,
} from "@google/generative-ai";
import { getEnv } from "@llamaindex/env";
import { ToolCallLLM } from "./base.js";
import type {
ChatMessage,
ChatResponse,
ChatResponseChunk,
CompletionResponse,
LLMChatParamsNonStreaming,
LLMChatParamsStreaming,
LLMCompletionParamsNonStreaming,
LLMCompletionParamsStreaming,
LLMMetadata,
MessageContent,
MessageContentImageDetail,
MessageContentTextDetail,
MessageType,
ToolCallLLMMessageOptions,
} from "./types.js";
import { streamConverter, wrapLLMEvent } from "./utils.js";
// Session and Model Type Definitions
type GeminiSessionOptions = {
apiKey?: string;
};
export enum GEMINI_MODEL {
GEMINI_PRO = "gemini-pro",
GEMINI_PRO_VISION = "gemini-pro-vision",
GEMINI_PRO_LATEST = "gemini-1.5-pro-latest",
}
export interface GeminiModelInfo {
contextWindow: number;
}
export const GEMINI_MODEL_INFO_MAP: Record<GEMINI_MODEL, GeminiModelInfo> = {
[GEMINI_MODEL.GEMINI_PRO]: { contextWindow: 30720 },
[GEMINI_MODEL.GEMINI_PRO_VISION]: { contextWindow: 12288 },
[GEMINI_MODEL.GEMINI_PRO_LATEST]: { contextWindow: 10 ** 6 },
};
const SUPPORT_TOOL_CALL_MODELS: GEMINI_MODEL[] = [
GEMINI_MODEL.GEMINI_PRO,
GEMINI_MODEL.GEMINI_PRO_VISION,
];
const DEFAULT_GEMINI_PARAMS = {
model: GEMINI_MODEL.GEMINI_PRO,
temperature: 0.1,
topP: 1,
maxTokens: undefined,
};
export type GeminiConfig = Partial<typeof DEFAULT_GEMINI_PARAMS> & {
session?: GeminiSession;
};
/// Chat Type Definitions
type GeminiMessageRole = "user" | "model";
export type GeminiAdditionalChatOptions = {};
export type GeminiChatParamsStreaming = LLMChatParamsStreaming<
GeminiAdditionalChatOptions,
ToolCallLLMMessageOptions
>;
export type GeminiChatStreamResponse = AsyncIterable<
ChatResponseChunk<ToolCallLLMMessageOptions>
>;
export type GeminiChatParamsNonStreaming = LLMChatParamsNonStreaming<
GeminiAdditionalChatOptions,
ToolCallLLMMessageOptions
>;
export type GeminiChatNonStreamResponse =
ChatResponse<ToolCallLLMMessageOptions>;
/**
* Gemini Session to manage the connection to the Gemini API
*/
export class GeminiSession {
gemini: GoogleGenerativeAI;
constructor(options: GeminiSessionOptions) {
if (!options.apiKey) {
options.apiKey = getEnv("GOOGLE_API_KEY");
}
if (!options.apiKey) {
throw new Error("Set Google API Key in GOOGLE_API_KEY env variable");
}
this.gemini = new GoogleGenerativeAI(options.apiKey);
}
}
/**
* Gemini Session Store to manage the current Gemini sessions
*/
export class GeminiSessionStore {
static sessions: Array<{
session: GeminiSession;
options: GeminiSessionOptions;
}> = [];
private static sessionMatched(
o1: GeminiSessionOptions,
o2: GeminiSessionOptions,
): boolean {
return o1.apiKey === o2.apiKey;
}
static get(options: GeminiSessionOptions = {}): GeminiSession {
let session = this.sessions.find((session) =>
this.sessionMatched(session.options, options),
)?.session;
if (!session) {
session = new GeminiSession(options);
this.sessions.push({ session, options });
}
return session;
}
}
/**
* Helper class providing utility functions for Gemini
*/
class GeminiHelper {
// Gemini only has user and model roles. Put the rest in user role.
public static readonly ROLES_TO_GEMINI: Record<
MessageType,
GeminiMessageRole
> = {
user: "user",
system: "user",
assistant: "user",
memory: "user",
};
public static readonly ROLES_FROM_GEMINI: Record<
GeminiMessageRole,
MessageType
> = {
user: "user",
model: "assistant",
};
public static mergeNeighboringSameRoleMessages(
messages: ChatMessage[],
): ChatMessage[] {
// Gemini does not support multiple messages of the same role in a row, so we merge them
const mergedMessages: ChatMessage[] = [];
let i: number = 0;
while (i < messages.length) {
const currentMessage: ChatMessage = messages[i];
// Initialize merged content with current message content
const mergedContent: MessageContent[] = [currentMessage.content];
// Check if the next message exists and has the same role
while (
i + 1 < messages.length &&
this.ROLES_TO_GEMINI[messages[i + 1].role] ===
this.ROLES_TO_GEMINI[currentMessage.role]
) {
i++;
const nextMessage: ChatMessage = messages[i];
mergedContent.push(nextMessage.content);
}
// Create a new ChatMessage object with merged content
const mergedMessage: ChatMessage = {
role: currentMessage.role,
content: mergedContent.join("\n"),
};
mergedMessages.push(mergedMessage);
i++;
}
return mergedMessages;
}
public static messageContentToGeminiParts(content: MessageContent): Part[] {
if (typeof content === "string") {
return [{ text: content }];
}
const parts: Part[] = [];
const imageContents = content.filter(
(i) => i.type === "image_url",
) as MessageContentImageDetail[];
parts.push(
...imageContents.map((i) => ({
fileData: {
mimeType: i.type,
fileUri: i.image_url.url,
},
})),
);
const textContents = content.filter(
(i) => i.type === "text",
) as MessageContentTextDetail[];
parts.push(...textContents.map((t) => ({ text: t.text })));
return parts;
}
public static chatMessageToGemini(
message: ChatMessage,
): GeminiMessageContent {
return {
role: this.ROLES_TO_GEMINI[message.role],
parts: this.messageContentToGeminiParts(message.content),
};
}
}
/**
* ToolCallLLM for Gemini
*/
export class Gemini extends ToolCallLLM<GeminiAdditionalChatOptions> {
model: GEMINI_MODEL;
temperature: number;
topP: number;
maxTokens?: number;
session: GeminiSession;
constructor(init?: GeminiConfig) {
super();
this.model = init?.model ?? GEMINI_MODEL.GEMINI_PRO;
this.temperature = init?.temperature ?? 0.1;
this.topP = init?.topP ?? 1;
this.maxTokens = init?.maxTokens ?? undefined;
this.session = init?.session ?? GeminiSessionStore.get();
}
get supportToolCall(): boolean {
return SUPPORT_TOOL_CALL_MODELS.includes(this.model);
}
get metadata(): LLMMetadata {
return {
model: this.model,
temperature: this.temperature,
topP: this.topP,
maxTokens: this.maxTokens,
contextWindow: GEMINI_MODEL_INFO_MAP[this.model].contextWindow,
tokenizer: undefined,
};
}
private prepareChat(
params: GeminiChatParamsStreaming | GeminiChatParamsNonStreaming,
): {
chat: ChatSession;
messageContent: Part[];
} {
const { messages } = params;
const mergedMessages =
GeminiHelper.mergeNeighboringSameRoleMessages(messages);
const history = mergedMessages.slice(0, -1);
const nextMessage = mergedMessages[mergedMessages.length - 1];
const messageContent = GeminiHelper.chatMessageToGemini(nextMessage).parts;
const client = this.session.gemini.getGenerativeModel(this.metadata);
const chat = client.startChat({
history: history.map(GeminiHelper.chatMessageToGemini),
});
return {
chat,
messageContent,
};
}
protected async nonStreamChat(
params: GeminiChatParamsNonStreaming,
): Promise<GeminiChatNonStreamResponse> {
const { chat, messageContent } = this.prepareChat(params);
const result = await chat.sendMessage(messageContent);
const { response } = result;
const topCandidate = response.candidates![0];
return {
raw: response,
message: {
content: response.text(),
role: GeminiHelper.ROLES_FROM_GEMINI[
topCandidate.content.role as GeminiMessageRole
],
},
};
}
protected async *streamChat(
params: GeminiChatParamsStreaming,
): GeminiChatStreamResponse {
const { chat, messageContent } = this.prepareChat(params);
const result = await chat.sendMessageStream(messageContent);
yield* streamConverter(result.stream, (response) => ({
delta: response.text(),
raw: response,
}));
}
chat(params: GeminiChatParamsStreaming): Promise<GeminiChatStreamResponse>;
chat(
params: GeminiChatParamsNonStreaming,
): Promise<GeminiChatNonStreamResponse>;
@wrapLLMEvent
async chat(
params: GeminiChatParamsStreaming | GeminiChatParamsNonStreaming,
): Promise<GeminiChatStreamResponse | GeminiChatNonStreamResponse> {
if (params.stream) return this.streamChat(params);
return this.nonStreamChat(params);
}
complete(
params: LLMCompletionParamsStreaming,
): Promise<AsyncIterable<CompletionResponse>>;
complete(
params: LLMCompletionParamsNonStreaming,
): Promise<CompletionResponse>;
async complete(
params: LLMCompletionParamsStreaming | LLMCompletionParamsNonStreaming,
): Promise<CompletionResponse | AsyncIterable<CompletionResponse>> {
const { prompt, stream } = params;
const client = this.session.gemini.getGenerativeModel(this.metadata);
if (stream) {
const result = await client.generateContentStream(
GeminiHelper.messageContentToGeminiParts(prompt),
);
return streamConverter(result.stream, (response) => {
return {
text: response.text(),
raw: response,
};
});
}
const result = await client.generateContent(
GeminiHelper.messageContentToGeminiParts(prompt),
);
return {
text: result.response.text(),
raw: result.response,
};
}
}
+248
View File
@@ -0,0 +1,248 @@
import {
GoogleGenerativeAI,
GenerativeModel as GoogleGenerativeModel,
type EnhancedGenerateContentResponse,
type ModelParams as GoogleModelParams,
type GenerateContentStreamResult as GoogleStreamGenerateContentResult,
} from "@google/generative-ai";
import { getEnv } from "@llamaindex/env";
import { ToolCallLLM } from "../base.js";
import type {
CompletionResponse,
LLMCompletionParamsNonStreaming,
LLMCompletionParamsStreaming,
LLMMetadata,
} from "../types.js";
import { streamConverter, wrapLLMEvent } from "../utils.js";
import {
GEMINI_BACKENDS,
GEMINI_MODEL,
type GeminiAdditionalChatOptions,
type GeminiChatNonStreamResponse,
type GeminiChatParamsNonStreaming,
type GeminiChatParamsStreaming,
type GeminiChatStreamResponse,
type GeminiMessageRole,
type GeminiModelInfo,
type GeminiSessionOptions,
type GoogleGeminiSessionOptions,
type IGeminiSession,
} from "./types.js";
import { GeminiHelper, getChatContext, getPartsText } from "./utils.js";
export const GEMINI_MODEL_INFO_MAP: Record<GEMINI_MODEL, GeminiModelInfo> = {
[GEMINI_MODEL.GEMINI_PRO]: { contextWindow: 30720 },
[GEMINI_MODEL.GEMINI_PRO_VISION]: { contextWindow: 12288 },
[GEMINI_MODEL.GEMINI_PRO_LATEST]: { contextWindow: 10 ** 6 },
};
const SUPPORT_TOOL_CALL_MODELS: GEMINI_MODEL[] = [
GEMINI_MODEL.GEMINI_PRO,
GEMINI_MODEL.GEMINI_PRO_VISION,
];
const DEFAULT_GEMINI_PARAMS = {
model: GEMINI_MODEL.GEMINI_PRO,
temperature: 0.1,
topP: 1,
maxTokens: undefined,
};
export type GeminiConfig = Partial<typeof DEFAULT_GEMINI_PARAMS> & {
session?: IGeminiSession;
};
/**
* Gemini Session to manage the connection to the Gemini API
*/
export class GeminiSession implements IGeminiSession {
private gemini: GoogleGenerativeAI;
constructor(options: GoogleGeminiSessionOptions) {
if (!options.apiKey) {
options.apiKey = getEnv("GOOGLE_API_KEY");
}
if (!options.apiKey) {
throw new Error("Set Google API Key in GOOGLE_API_KEY env variable");
}
this.gemini = new GoogleGenerativeAI(options.apiKey);
}
getGenerativeModel(metadata: GoogleModelParams): GoogleGenerativeModel {
return this.gemini.getGenerativeModel(metadata);
}
getResponseText(response: EnhancedGenerateContentResponse): string {
return response.text();
}
async *getChatStream(
result: GoogleStreamGenerateContentResult,
): GeminiChatStreamResponse {
yield* streamConverter(result.stream, (response) => ({
delta: this.getResponseText(response),
raw: response,
}));
}
getCompletionStream(
result: GoogleStreamGenerateContentResult,
): AsyncIterable<CompletionResponse> {
return streamConverter(result.stream, (response) => ({
text: this.getResponseText(response),
raw: response,
}));
}
}
/**
* Gemini Session Store to manage the current Gemini sessions
*/
export class GeminiSessionStore {
static sessions: Array<{
session: IGeminiSession;
options: GeminiSessionOptions;
}> = [];
private static getSessionId(options: GeminiSessionOptions): string {
if (options.backend === GEMINI_BACKENDS.GOOGLE)
return options?.apiKey ?? "";
return "";
}
private static sessionMatched(
o1: GeminiSessionOptions,
o2: GeminiSessionOptions,
): boolean {
return (
GeminiSessionStore.getSessionId(o1) ===
GeminiSessionStore.getSessionId(o2)
);
}
static get(
options: GeminiSessionOptions = { backend: GEMINI_BACKENDS.GOOGLE },
): IGeminiSession {
let session = this.sessions.find((session) =>
this.sessionMatched(session.options, options),
)?.session;
if (session) return session;
if (options.backend === GEMINI_BACKENDS.VERTEX) {
throw Error("No Session");
} else {
session = new GeminiSession(options);
}
this.sessions.push({ session, options });
return session;
}
}
/**
* ToolCallLLM for Gemini
*/
export class Gemini extends ToolCallLLM<GeminiAdditionalChatOptions> {
model: GEMINI_MODEL;
temperature: number;
topP: number;
maxTokens?: number;
session: IGeminiSession;
constructor(init?: GeminiConfig) {
super();
this.model = init?.model ?? GEMINI_MODEL.GEMINI_PRO;
this.temperature = init?.temperature ?? 0.1;
this.topP = init?.topP ?? 1;
this.maxTokens = init?.maxTokens ?? undefined;
this.session = init?.session ?? GeminiSessionStore.get();
}
get supportToolCall(): boolean {
return SUPPORT_TOOL_CALL_MODELS.includes(this.model);
}
get metadata(): LLMMetadata {
return {
model: this.model,
temperature: this.temperature,
topP: this.topP,
maxTokens: this.maxTokens,
contextWindow: GEMINI_MODEL_INFO_MAP[this.model].contextWindow,
tokenizer: undefined,
};
}
protected async nonStreamChat(
params: GeminiChatParamsNonStreaming,
): Promise<GeminiChatNonStreamResponse> {
const context = getChatContext(params);
const client = this.session.getGenerativeModel(this.metadata);
const chat = client.startChat({
history: context.history,
});
const { response } = await chat.sendMessage(context.message);
const topCandidate = response.candidates![0];
return {
raw: response,
message: {
content: this.session.getResponseText(response),
role: GeminiHelper.ROLES_FROM_GEMINI[
topCandidate.content.role as GeminiMessageRole
],
},
};
}
protected async *streamChat(
params: GeminiChatParamsStreaming,
): GeminiChatStreamResponse {
const context = getChatContext(params);
const client = this.session.getGenerativeModel(this.metadata);
const chat = client.startChat({
history: context.history,
});
const result = await chat.sendMessageStream(context.message);
yield* this.session.getChatStream(result);
}
chat(params: GeminiChatParamsStreaming): Promise<GeminiChatStreamResponse>;
chat(
params: GeminiChatParamsNonStreaming,
): Promise<GeminiChatNonStreamResponse>;
@wrapLLMEvent
async chat(
params: GeminiChatParamsStreaming | GeminiChatParamsNonStreaming,
): Promise<GeminiChatStreamResponse | GeminiChatNonStreamResponse> {
if (params.stream) return this.streamChat(params);
return this.nonStreamChat(params);
}
complete(
params: LLMCompletionParamsStreaming,
): Promise<AsyncIterable<CompletionResponse>>;
complete(
params: LLMCompletionParamsNonStreaming,
): Promise<CompletionResponse>;
async complete(
params: LLMCompletionParamsStreaming | LLMCompletionParamsNonStreaming,
): Promise<CompletionResponse | AsyncIterable<CompletionResponse>> {
const { prompt, stream } = params;
const client = this.session.getGenerativeModel(this.metadata);
if (stream) {
const result = await client.generateContentStream(
getPartsText(GeminiHelper.messageContentToGeminiParts(prompt)),
);
return this.session.getCompletionStream(result);
}
const result = await client.generateContent(
getPartsText(GeminiHelper.messageContentToGeminiParts(prompt)),
);
return {
text: this.session.getResponseText(result.response),
raw: result.response,
};
}
}
+111
View File
@@ -0,0 +1,111 @@
import {
GenerativeModel as GoogleGenerativeModel,
type EnhancedGenerateContentResponse,
type Content as GeminiMessageContent,
type FileDataPart as GoogleFileDataPart,
type InlineDataPart as GoogleInlineFileDataPart,
type ModelParams as GoogleModelParams,
type Part as GooglePart,
type GenerateContentStreamResult as GoogleStreamGenerateContentResult,
} from "@google/generative-ai";
import {
GenerativeModel as VertexGenerativeModel,
GenerativeModelPreview as VertexGenerativeModelPreview,
type GenerateContentResponse,
type FileDataPart as VertexFileDataPart,
type VertexInit,
type InlineDataPart as VertexInlineFileDataPart,
type ModelParams as VertexModelParams,
type Part as VertexPart,
type StreamGenerateContentResult as VertexStreamGenerateContentResult,
} from "@google-cloud/vertexai";
import type {
ChatResponse,
ChatResponseChunk,
CompletionResponse,
LLMChatParamsNonStreaming,
LLMChatParamsStreaming,
ToolCallLLMMessageOptions,
} from "../types.js";
export enum GEMINI_BACKENDS {
GOOGLE = "google",
VERTEX = "vertex",
}
export type GoogleGeminiSessionOptions = {
apiKey?: string;
};
export type VertexGeminiSessionOptions = {
preview?: boolean;
} & VertexInit;
export type GeminiSessionOptions =
| (GoogleGeminiSessionOptions & { backend: GEMINI_BACKENDS.GOOGLE })
| (VertexGeminiSessionOptions & { backend: GEMINI_BACKENDS.VERTEX });
export enum GEMINI_MODEL {
GEMINI_PRO = "gemini-pro",
GEMINI_PRO_VISION = "gemini-pro-vision",
GEMINI_PRO_LATEST = "gemini-1.5-pro-latest",
}
export interface GeminiModelInfo {
contextWindow: number;
}
export type Part = GooglePart | VertexPart;
export type FileDataPart = GoogleFileDataPart | VertexFileDataPart;
export type InlineDataPart =
| GoogleInlineFileDataPart
| VertexInlineFileDataPart;
export type ModelParams = GoogleModelParams | VertexModelParams;
export type GenerativeModel =
| VertexGenerativeModelPreview
| VertexGenerativeModel
| GoogleGenerativeModel;
export type ChatContext = { message: Part[]; history: GeminiMessageContent[] };
export type GeminiMessageRole = "user" | "model";
export type GeminiAdditionalChatOptions = {};
export type GeminiChatParamsStreaming = LLMChatParamsStreaming<
GeminiAdditionalChatOptions,
ToolCallLLMMessageOptions
>;
export type GeminiChatStreamResponse = AsyncIterable<
ChatResponseChunk<ToolCallLLMMessageOptions>
>;
export type GeminiChatParamsNonStreaming = LLMChatParamsNonStreaming<
GeminiAdditionalChatOptions,
ToolCallLLMMessageOptions
>;
export type GeminiChatNonStreamResponse =
ChatResponse<ToolCallLLMMessageOptions>;
export interface IGeminiSession {
getGenerativeModel(metadata: ModelParams): GenerativeModel;
getResponseText(
response: EnhancedGenerateContentResponse | GenerateContentResponse,
): string;
getCompletionStream(
result:
| GoogleStreamGenerateContentResult
| VertexStreamGenerateContentResult,
): AsyncIterable<CompletionResponse>;
getChatStream(
result:
| GoogleStreamGenerateContentResult
| VertexStreamGenerateContentResult,
): GeminiChatStreamResponse;
}
+197
View File
@@ -0,0 +1,197 @@
import { type Content as GeminiMessageContent } from "@google/generative-ai";
import { type GenerateContentResponse } from "@google-cloud/vertexai";
import type {
ChatMessage,
MessageContent,
MessageContentImageDetail,
MessageContentTextDetail,
MessageType,
} from "../types.js";
import { extractDataUrlComponents } from "../utils.js";
import type {
ChatContext,
FileDataPart,
GeminiChatParamsNonStreaming,
GeminiChatParamsStreaming,
GeminiMessageRole,
InlineDataPart,
Part,
} from "./types.js";
const FILE_EXT_MIME_TYPES: { [key: string]: string } = {
png: "image/png",
jpeg: "image/jpeg",
jpg: "image/jpeg",
webp: "image/webp",
heic: "image/heic",
heif: "image/heif",
};
const ACCEPTED_IMAGE_MIME_TYPES = Object.values(FILE_EXT_MIME_TYPES);
const getFileURLExtension = (url: string): string | null => {
const pathname = new URL(url).pathname;
const parts = pathname.split(".");
return parts.length > 1 ? parts.pop()?.toLowerCase() || null : null;
};
const getFileURLMimeType = (url: string): string | null => {
const ext = getFileURLExtension(url);
return ext ? FILE_EXT_MIME_TYPES[ext] || null : null;
};
const getImageParts = (
message: MessageContentImageDetail,
): InlineDataPart | FileDataPart => {
if (message.image_url.url.startsWith("data:")) {
const { mimeType, base64: data } = extractDataUrlComponents(
message.image_url.url,
);
if (!mimeType || !ACCEPTED_IMAGE_MIME_TYPES.includes(mimeType))
throw new Error(
`Gemini only accepts the following mimeTypes: ${ACCEPTED_IMAGE_MIME_TYPES.join("\n")}`,
);
return {
inlineData: {
mimeType,
data,
},
};
}
const mimeType = getFileURLMimeType(message.image_url.url);
if (!mimeType || !ACCEPTED_IMAGE_MIME_TYPES.includes(mimeType))
throw new Error(
`Gemini only accepts the following mimeTypes: ${ACCEPTED_IMAGE_MIME_TYPES.join("\n")}`,
);
return {
fileData: { mimeType, fileUri: message.image_url.url },
};
};
export const getPartsText = (parts: Part[]): string => {
const textStrings = [];
if (parts.length) {
for (const part of parts) {
if (part.text) {
textStrings.push(part.text);
}
}
}
if (textStrings.length > 0) {
return textStrings.join("");
} else {
return "";
}
};
/**
* Returns all text found in all parts of first candidate.
*/
export const getText = (response: GenerateContentResponse): string => {
if (response.candidates?.[0].content?.parts) {
return getPartsText(response.candidates?.[0].content?.parts);
}
return "";
};
export const cleanParts = (
message: GeminiMessageContent,
): GeminiMessageContent => {
return {
...message,
parts: message.parts.filter((part) => part.text?.trim()),
};
};
export const getChatContext = (
params: GeminiChatParamsStreaming | GeminiChatParamsNonStreaming,
): ChatContext => {
// Gemini doesn't allow:
// 1. Consecutive messages from the same role
// 2. Parts that have empty text
const messages = GeminiHelper.mergeNeighboringSameRoleMessages(
params.messages.map(GeminiHelper.chatMessageToGemini),
).map(cleanParts);
const history = messages.slice(0, -1);
const message = messages[messages.length - 1].parts;
return {
history,
message,
};
};
/**
* Helper class providing utility functions for Gemini
*/
export class GeminiHelper {
// Gemini only has user and model roles. Put the rest in user role.
public static readonly ROLES_TO_GEMINI: Record<
MessageType,
GeminiMessageRole
> = {
user: "user",
system: "user",
assistant: "model",
memory: "user",
};
public static readonly ROLES_FROM_GEMINI: Record<
GeminiMessageRole,
MessageType
> = {
user: "user",
model: "assistant",
};
public static mergeNeighboringSameRoleMessages(
messages: GeminiMessageContent[],
): GeminiMessageContent[] {
return messages.reduce(
(
result: GeminiMessageContent[],
current: GeminiMessageContent,
index: number,
) => {
if (index > 0 && messages[index - 1].role === current.role) {
result[result.length - 1].parts = [
...result[result.length - 1].parts,
...current.parts,
];
} else {
result.push(current);
}
return result;
},
[],
);
}
public static messageContentToGeminiParts(content: MessageContent): Part[] {
if (typeof content === "string") {
return [{ text: content }];
}
const parts: Part[] = [];
const imageContents = content.filter(
(i) => i.type === "image_url",
) as MessageContentImageDetail[];
parts.push(...imageContents.map(getImageParts));
const textContents = content.filter(
(i) => i.type === "text",
) as MessageContentTextDetail[];
parts.push(...textContents.map((t) => ({ text: t.text })));
return parts;
}
public static chatMessageToGemini(
message: ChatMessage,
): GeminiMessageContent {
return {
role: GeminiHelper.ROLES_TO_GEMINI[message.role],
parts: GeminiHelper.messageContentToGeminiParts(message.content),
};
}
}
+81
View File
@@ -0,0 +1,81 @@
import {
VertexAI,
GenerativeModel as VertexGenerativeModel,
GenerativeModelPreview as VertexGenerativeModelPreview,
type GenerateContentResponse,
type ModelParams as VertexModelParams,
type StreamGenerateContentResult as VertexStreamGenerateContentResult,
} from "@google-cloud/vertexai";
import type {
GeminiChatStreamResponse,
IGeminiSession,
VertexGeminiSessionOptions,
} from "./types.js";
import { getEnv } from "@llamaindex/env";
import type { CompletionResponse } from "../types.js";
import { streamConverter } from "../utils.js";
import { getText } from "./utils.js";
/* To use Google's Vertex AI backend, it doesn't use api key authentication.
*
* To authenticate for local development:
*
* ```
* npm install @google-cloud/vertexai
* gcloud auth application-default login
* ```
* For production the prefered method is via a service account, more
* details: https://cloud.google.com/docs/authentication/
*
* */
export class GeminiVertexSession implements IGeminiSession {
private vertex: VertexAI;
private preview: boolean = false;
constructor(options?: Partial<VertexGeminiSessionOptions>) {
const project = options?.project ?? getEnv("GOOGLE_VERTEX_PROJECT");
const location = options?.location ?? getEnv("GOOGLE_VERTEX_LOCATION");
if (!project || !location) {
throw new Error(
"Set Google Vertex project and location in GOOGLE_VERTEX_PROJECT and GOOGLE_VERTEX_LOCATION env variables",
);
}
this.vertex = new VertexAI({
...options,
project,
location,
});
this.preview = options?.preview ?? false;
}
getGenerativeModel(
metadata: VertexModelParams,
): VertexGenerativeModelPreview | VertexGenerativeModel {
if (this.preview) return this.vertex.preview.getGenerativeModel(metadata);
return this.vertex.getGenerativeModel(metadata);
}
getResponseText(response: GenerateContentResponse): string {
return getText(response);
}
async *getChatStream(
result: VertexStreamGenerateContentResult,
): GeminiChatStreamResponse {
yield* streamConverter(result.stream, (response) => ({
delta: this.getResponseText(response),
raw: response,
}));
}
getCompletionStream(
result: VertexStreamGenerateContentResult,
): AsyncIterable<CompletionResponse> {
return streamConverter(result.stream, (response) => ({
text: this.getResponseText(response),
raw: response,
}));
}
}
+119
View File
@@ -2,6 +2,12 @@ import {
HfInference,
type Options as HfInferenceOptions,
} from "@huggingface/inference";
import type {
PreTrainedModel,
PreTrainedTokenizer,
Tensor,
} from "@xenova/transformers";
import { lazyLoadTransformers } from "../internal/deps/transformers.js";
import { BaseLLM } from "./base.js";
import type {
ChatMessage,
@@ -139,3 +145,116 @@ export class HuggingFaceInferenceAPI extends BaseLLM {
}));
}
}
const DEFAULT_HUGGINGFACE_MODEL = "stabilityai/stablelm-tuned-alpha-3b";
export interface HFLLMConfig {
modelName?: string;
tokenizerName?: string;
temperature?: number;
topP?: number;
maxTokens?: number;
contextWindow?: number;
}
export class HuggingFaceLLM extends BaseLLM {
modelName: string;
tokenizerName: string;
temperature: number;
topP: number;
maxTokens?: number;
contextWindow: number;
private tokenizer: PreTrainedTokenizer | null = null;
private model: PreTrainedModel | null = null;
constructor(init?: HFLLMConfig) {
super();
this.modelName = init?.modelName ?? DEFAULT_HUGGINGFACE_MODEL;
this.tokenizerName = init?.tokenizerName ?? DEFAULT_HUGGINGFACE_MODEL;
this.temperature = init?.temperature ?? DEFAULT_PARAMS.temperature;
this.topP = init?.topP ?? DEFAULT_PARAMS.topP;
this.maxTokens = init?.maxTokens ?? DEFAULT_PARAMS.maxTokens;
this.contextWindow = init?.contextWindow ?? DEFAULT_PARAMS.contextWindow;
}
get metadata(): LLMMetadata {
return {
model: this.modelName,
temperature: this.temperature,
topP: this.topP,
maxTokens: this.maxTokens,
contextWindow: this.contextWindow,
tokenizer: undefined,
};
}
async getTokenizer() {
const { AutoTokenizer } = await lazyLoadTransformers();
if (!this.tokenizer) {
this.tokenizer = await AutoTokenizer.from_pretrained(this.tokenizerName);
}
return this.tokenizer;
}
async getModel() {
const { AutoModelForCausalLM } = await lazyLoadTransformers();
if (!this.model) {
this.model = await AutoModelForCausalLM.from_pretrained(this.modelName);
}
return this.model;
}
chat(
params: LLMChatParamsStreaming,
): Promise<AsyncIterable<ChatResponseChunk>>;
chat(params: LLMChatParamsNonStreaming): Promise<ChatResponse>;
@wrapLLMEvent
async chat(
params: LLMChatParamsStreaming | LLMChatParamsNonStreaming,
): Promise<AsyncIterable<ChatResponseChunk> | ChatResponse<object>> {
if (params.stream) return this.streamChat(params);
return this.nonStreamChat(params);
}
protected async nonStreamChat(
params: LLMChatParamsNonStreaming,
): Promise<ChatResponse> {
const tokenizer = await this.getTokenizer();
const model = await this.getModel();
const messageInputs = params.messages.map((msg) => ({
role: msg.role,
content: msg.content as string,
}));
const inputs = tokenizer.apply_chat_template(messageInputs, {
add_generation_prompt: true,
...this.metadata,
}) as Tensor;
// TODO: the input for model.generate should be updated when using @xenova/transformers v3
// We should add `stopping_criteria` also when it's supported in v3
// See: https://github.com/xenova/transformers.js/blob/3260640b192b3e06a10a1f4dc004b1254fdf1b80/src/models.js#L1248C9-L1248C27
const outputs = await model.generate(inputs, this.metadata);
const outputText = tokenizer.batch_decode(outputs, {
skip_special_tokens: false,
});
return {
raw: outputs,
message: {
content: outputText.join(""),
role: "assistant",
},
};
}
protected async *streamChat(
params: LLMChatParamsStreaming,
): AsyncIterable<ChatResponseChunk> {
// @xenova/transformers v2 doesn't support streaming generation yet
// they are working on it in v3
// See: https://github.com/xenova/transformers.js/blob/3260640b192b3e06a10a1f4dc004b1254fdf1b80/src/models.js#L1249
throw new Error("Method not implemented.");
}
}
+8 -2
View File
@@ -5,9 +5,15 @@ export {
Anthropic,
} from "./anthropic.js";
export { FireworksLLM } from "./fireworks.js";
export { GEMINI_MODEL, Gemini } from "./gemini.js";
export { Gemini, GeminiSession } from "./gemini/base.js";
export {
GEMINI_MODEL,
type GoogleGeminiSessionOptions,
} from "./gemini/types.js";
export { Groq } from "./groq.js";
export { HuggingFaceInferenceAPI } from "./huggingface.js";
export { HuggingFaceInferenceAPI, HuggingFaceLLM } from "./huggingface.js";
export {
ALL_AVAILABLE_MISTRAL_MODELS,
MistralAI,
+3
View File
@@ -110,6 +110,9 @@ export const GPT4_MODELS = {
"gpt-4-1106-preview": { contextWindow: 128000 },
"gpt-4-0125-preview": { contextWindow: 128000 },
"gpt-4-vision-preview": { contextWindow: 128000 },
// fixme: wait for openai documentation
"gpt-4o": { contextWindow: 128000 },
"gpt-4o-2024-05-13": { contextWindow: 128000 },
};
// NOTE we don't currently support gpt-3.5-turbo-instruct and don't plan to in the near future
+21
View File
@@ -77,6 +77,27 @@ export function extractText(message: MessageContent): string {
}
}
export const extractDataUrlComponents = (
dataUrl: string,
): {
mimeType: string;
base64: string;
} => {
const parts = dataUrl.split(";base64,");
if (parts.length !== 2 || !parts[0].startsWith("data:")) {
throw new Error("Invalid data URL");
}
const mimeType = parts[0].slice(5);
const base64 = parts[1];
return {
mimeType,
base64,
};
};
/**
* @internal
*/
+1
View File
@@ -28,6 +28,7 @@ export default function withLlamaIndex(config: any) {
...webpackConfig.resolve.alias,
sharp$: false,
"onnxruntime-node$": false,
"@google-cloud/vertexai": false,
};
return webpackConfig;
};
+3 -7
View File
@@ -1,5 +1,4 @@
import type { GenericFileSystem } from "@llamaindex/env";
import { defaultFS } from "@llamaindex/env";
import { fs } from "@llamaindex/env";
import type { ParseConfig } from "papaparse";
import Papa from "papaparse";
import { Document } from "../Node.js";
@@ -40,11 +39,8 @@ export class PapaCSVReader implements FileReader {
* @param {GenericFileSystem} [fs=DEFAULT_FS] - The file system to use for reading the file.
* @returns {Promise<Document[]>}
*/
async loadData(
file: string,
fs: GenericFileSystem = defaultFS,
): Promise<Document[]> {
const fileContent = await fs.readFile(file);
async loadData(file: string): Promise<Document[]> {
const fileContent = await fs.readFile(file, "utf-8");
const result = Papa.parse(fileContent, this.papaConfig);
const textList = result.data.map((row: any) => {
// Compatible with header row mode
+3 -7
View File
@@ -1,16 +1,12 @@
import type { GenericFileSystem } from "@llamaindex/env";
import { defaultFS } from "@llamaindex/env";
import { fs } from "@llamaindex/env";
import mammoth from "mammoth";
import { Document } from "../Node.js";
import type { FileReader } from "./type.js";
export class DocxReader implements FileReader {
/** DocxParser */
async loadData(
file: string,
fs: GenericFileSystem = defaultFS,
): Promise<Document[]> {
const dataBuffer = await fs.readRawFile(file);
async loadData(file: string): Promise<Document[]> {
const dataBuffer = await fs.readFile(file);
const { value } = await mammoth.extractRawText({ buffer: dataBuffer });
return [new Document({ text: value, id_: file })];
}
+3 -8
View File
@@ -1,5 +1,4 @@
import type { GenericFileSystem } from "@llamaindex/env";
import { defaultFS } from "@llamaindex/env";
import { fs } from "@llamaindex/env";
import { Document } from "../Node.js";
import type { FileReader } from "./type.js";
@@ -15,14 +14,10 @@ export class HTMLReader implements FileReader {
* Public method for this reader.
* Required by BaseReader interface.
* @param file Path/name of the file to be loaded.
* @param fs fs wrapper interface for getting the file content.
* @returns Promise<Document[]> A Promise object, eventually yielding zero or one Document parsed from the HTML content of the specified file.
*/
async loadData(
file: string,
fs: GenericFileSystem = defaultFS,
): Promise<Document[]> {
const dataBuffer = await fs.readFile(file);
async loadData(file: string): Promise<Document[]> {
const dataBuffer = await fs.readFile(file, "utf-8");
const htmlOptions = this.getOptions();
const content = await this.parseContent(dataBuffer, htmlOptions);
return [new Document({ text: content, id_: file })];
+3 -7
View File
@@ -1,5 +1,4 @@
import type { GenericFileSystem } from "@llamaindex/env";
import { defaultFS } from "@llamaindex/env";
import { fs } from "@llamaindex/env";
import type { Document } from "../Node.js";
import { ImageDocument } from "../Node.js";
import type { FileReader } from "./type.js";
@@ -15,11 +14,8 @@ export class ImageReader implements FileReader {
* @param fs fs wrapper interface for getting the file content.
* @returns Promise<Document[]> A Promise object, eventually yielding zero or one ImageDocument of the specified file.
*/
async loadData(
file: string,
fs: GenericFileSystem = defaultFS,
): Promise<Document[]> {
const dataBuffer = await fs.readRawFile(file);
async loadData(file: string): Promise<Document[]> {
const dataBuffer = await fs.readFile(file);
const blob = new Blob([dataBuffer]);
return [new ImageDocument({ image: blob, id_: file })];
}
@@ -1,4 +1,4 @@
import { defaultFS, getEnv, type GenericFileSystem } from "@llamaindex/env";
import { fs, getEnv } from "@llamaindex/env";
import { filetypemime } from "magic-bytes.js";
import { Document } from "../Node.js";
import type { FileReader, Language, ResultType } from "./type.js";
@@ -79,14 +79,11 @@ export class LlamaParseReader implements FileReader {
this.apiKey = params.apiKey;
}
async loadData(
file: string,
fs: GenericFileSystem = defaultFS,
): Promise<Document[]> {
async loadData(file: string): Promise<Document[]> {
const metadata = { file_path: file };
// Load data, set the mime type
const data = await fs.readRawFile(file);
const data = await fs.readFile(file);
const mimeType = await this.getMimeType(data);
const body = new FormData();
+5 -7
View File
@@ -1,5 +1,4 @@
import type { GenericFileSystem } from "@llamaindex/env";
import { defaultFS } from "@llamaindex/env";
import { fs } from "@llamaindex/env";
import { Document } from "../Node.js";
import type { FileReader } from "./type.js";
@@ -44,6 +43,8 @@ export class MarkdownReader implements FileReader {
continue;
}
markdownTups.push([currentHeader, currentText]);
} else if (currentText) {
markdownTups.push([null, currentText]);
}
currentHeader = line;
@@ -88,11 +89,8 @@ export class MarkdownReader implements FileReader {
return this.markdownToTups(modifiedContent);
}
async loadData(
file: string,
fs: GenericFileSystem = defaultFS,
): Promise<Document[]> {
const content = await fs.readFile(file);
async loadData(file: string): Promise<Document[]> {
const content = await fs.readFile(file, "utf-8");
const tups = this.parseTups(content);
const results: Document[] = [];
let counter = 0;
+3 -7
View File
@@ -1,5 +1,4 @@
import type { GenericFileSystem } from "@llamaindex/env";
import { defaultFS } from "@llamaindex/env";
import { fs } from "@llamaindex/env";
import { Document } from "../Node.js";
import type { BaseReader } from "./type.js";
@@ -7,11 +6,8 @@ import type { BaseReader } from "./type.js";
* Read the text of a PDF
*/
export class PDFReader implements BaseReader {
async loadData(
file: string,
fs: GenericFileSystem = defaultFS,
): Promise<Document[]> {
const content = await fs.readRawFile(file);
async loadData(file: string): Promise<Document[]> {
const content = await fs.readFile(file);
const pages = await readPDF(content);
return pages.map((text, page) => {
const id_ = `${file}_${page + 1}`;
@@ -1,5 +1,4 @@
import type { CompleteFileSystem } from "@llamaindex/env";
import { defaultFS, path } from "@llamaindex/env";
import { fs, path } from "@llamaindex/env";
import { Document, type Metadata } from "../Node.js";
import { walk } from "../storage/FileSystem.js";
import { TextFileReader } from "./TextFileReader.js";
@@ -19,7 +18,6 @@ enum ReaderStatus {
export type SimpleDirectoryReaderLoadDataParams = {
directoryPath: string;
fs?: CompleteFileSystem;
defaultReader?: BaseReader | null;
fileExtToReader?: Record<string, BaseReader>;
};
@@ -45,7 +43,6 @@ export class SimpleDirectoryReader implements BaseReader {
const {
directoryPath,
fs = defaultFS,
defaultReader = new TextFileReader(),
fileExtToReader,
} = params;
@@ -58,7 +55,7 @@ export class SimpleDirectoryReader implements BaseReader {
}
const docs: Document[] = [];
for await (const filePath of walk(fs, directoryPath)) {
for await (const filePath of walk(directoryPath)) {
try {
const fileExt = path.extname(filePath).slice(1).toLowerCase();
+3 -7
View File
@@ -1,5 +1,4 @@
import type { CompleteFileSystem } from "@llamaindex/env";
import { defaultFS } from "@llamaindex/env";
import { fs } from "@llamaindex/env";
import { Document } from "../Node.js";
import type { BaseReader } from "./type.js";
@@ -8,11 +7,8 @@ import type { BaseReader } from "./type.js";
*/
export class TextFileReader implements BaseReader {
async loadData(
file: string,
fs: CompleteFileSystem = defaultFS,
): Promise<Document[]> {
const dataBuffer = await fs.readFile(file);
async loadData(file: string): Promise<Document[]> {
const dataBuffer = await fs.readFile(file, "utf-8");
return [new Document({ text: dataBuffer, id_: file })];
}
}

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