Compare commits

...

43 Commits

Author SHA1 Message Date
Alex Yang 2ec6a529c7 RELEASING: Releasing 2 package(s)
Releases:
  llamaindex@0.1.16
  @llamaindex/env@0.0.3

[skip ci]
2024-02-23 19:03:04 -06:00
Alex Yang e8e21a0e4e docs(changeset): build: set files in package.json 2024-02-23 19:02:42 -06:00
Alex Yang 88d243f145 RELEASING: Releasing 1 package(s)
Releases:
  llamaindex@0.1.15

[skip ci]
2024-02-23 18:57:10 -06:00
Alex Yang 3a6e287443 feat: enable verbatimModuleSyntax (#562) 2024-02-23 18:56:44 -06:00
Alex Yang beb3e5cd7f RELEASING: Releasing 2 package(s)
Releases:
  llamaindex@0.1.14
  @llamaindex/env@0.0.2

[skip ci]
2024-02-23 18:09:31 -06:00
Alex Yang 7416a87e10 build: cjs file not found 2024-02-23 18:09:15 -06:00
Alex Yang 65b85b237e RELEASING: Releasing 1 package(s)
Releases:
  llamaindex@0.1.13

[skip ci]
2024-02-23 17:59:06 -06:00
Alex Yang b17a80014a fix: unset private package 2024-02-23 17:58:46 -06:00
Alex Yang ff87f99807 fix: avoid publishing test package 2024-02-23 17:56:38 -06:00
Alex Yang 65d834615d docs(changeset): feat: abstract @llamaindex/env package 2024-02-23 17:45:43 -06:00
Alex Yang b8be4c09e2 docs(changeset): build: use ESM as default 2024-02-23 17:45:01 -06:00
Alex Yang e5fb332538 build: leave code as-is (#560)
Co-authored-by: Marcus Schiesser <mail@marcusschiesser.de>
2024-02-23 17:39:25 -06:00
Marcus Schiesser 491033d534 fix: lint errors 2024-02-23 14:55:45 +07:00
Marcus Schiesser 885fa316a5 chore: add prefer const lint 2024-02-23 14:45:17 +07:00
Marcus Schiesser b6ed679771 RELEASING: Releasing 1 package(s)
Releases:
  create-llama@0.0.26

[skip ci]
2024-02-23 12:00:37 +07:00
Marcus Schiesser 68fc6e8b50 fix: don't need similarityTopK parameter for LlamaCloud 2024-02-23 11:43:22 +07:00
Marcus Schiesser ea0331ef5a refactor: simplify generated python code (#558)
Co-authored-by: leehuwuj <leehuwuj@gmail.com>
2024-02-23 11:14:02 +07:00
Marcus Schiesser 6827e245b8 fix: don't allow runApp for LlamaPacks 2024-02-22 16:20:57 +07:00
Huu Le (Lee) ef25d6960c Upgrade llama-index version to v0.10+ for create-llama (#556) 2024-02-22 13:50:53 +07:00
Marcus Schiesser f740f44cf2 RELEASING: Releasing 1 package(s)
Releases:
  llamaindex@0.1.12

[skip ci]
2024-02-22 12:02:35 +07:00
Marcus Schiesser a5e4e6d857 Add support for LlamaCloud (#554) 2024-02-22 11:59:32 +07:00
Thuc Pham cfdd6db530 feat: add pinecone support to create llama (#555) 2024-02-22 09:55:50 +07:00
Marcus Schiesser d4eda9f396 docs: add llamaparse docs (#553) 2024-02-21 14:37:13 +07:00
Alex Yang a433b107e0 RELEASING: Releasing 1 package(s)
Releases:
  llamaindex@0.1.11

[skip ci]
2024-02-20 12:58:54 -06:00
Yufei (Benny) Chen 59f9fb6c3f Add Fireworks to LlamaIndex (#539)
Co-authored-by: Emanuel Ferreira <contatoferreirads@gmail.com>
2024-02-20 10:53:09 -03:00
Thuc Pham 09d532ebcc feat(create-llama-pack): generate llama pack project from llama index (#549) 2024-02-20 08:22:54 +07:00
Emanuel Ferreira cfd6f3ca8c feat: prompt mixin (#543) 2024-02-18 18:44:08 -03:00
Emanuel Ferreira 95add73c38 feat: multi-document agents (#531) 2024-02-18 18:43:52 -03:00
Emanuel Ferreira 9ee036b160 docs: remove duplicate embedding (#545) 2024-02-13 23:21:13 -03:00
Erick Sosa Garcia c2b521199c fix: some errors in available llms examples (#544) 2024-02-13 21:16:47 -03:00
Emanuel Ferreira ee9f3f373a refactor: openai agent and utils (#542) 2024-02-11 20:24:36 -03:00
Emanuel Ferreira f205358587 feat: add markdown node parser (#541) 2024-02-11 20:23:49 -03:00
Emanuel Ferreira 255ae7dced fix: react agent history (#540) 2024-02-11 18:46:55 -03:00
Emanuel Ferreira b4c6d509a0 docs: available embeddings (#538) 2024-02-10 22:10:20 -03:00
Emanuel Ferreira 34cd57b639 feat(react): add react agent (#511) 2024-02-10 20:52:11 -03:00
yisding 50dfd7bf60 dep security vulns (#537) 2024-02-11 04:37:42 +08:00
Emanuel Ferreira 0b57187909 docs: add available LLMs (#536) 2024-02-10 13:54:13 -03:00
Emanuel Ferreira e78e9f4832 feat(reranker): cohere reranker (#535) 2024-02-10 12:07:14 -03:00
Marcus Schiesser 383933adb5 feat: Add reader for LlamaParse (#530) 2024-02-09 11:27:50 +07:00
Marcus Schiesser dd054137bf feat: use batching in vector store index (#524)
Co-authored-by: Alex Yang <himself65@outlook.com>
Co-authored-by: Emanuel Ferreira <contatoferreirads@gmail.com>
2024-02-08 08:59:56 -03:00
byteninja cf3b7571eb feat: add filtering of metadata to PGVectorStore (#525) 2024-02-08 10:54:52 +07:00
Alex Yang ae7a2c202a fix: add alias class OllamaEmbedding (#527) 2024-02-07 14:26:39 -06:00
Alex Yang 9b00d578bc feat: improve reader interfaces (#498) 2024-02-07 11:44:01 -06:00
334 changed files with 10351 additions and 6449 deletions
+2 -1
View File
@@ -9,6 +9,7 @@ module.exports = {
},
rules: {
"max-params": ["error", 4],
"prefer-const": "error",
},
ignorePatterns: ["dist/"],
ignorePatterns: ["dist/", "lib/"],
};
+2
View File
@@ -0,0 +1,2 @@
examples/readers/data/** binary
examples/data/** binary
+5 -2
View File
@@ -61,10 +61,13 @@ jobs:
run: pnpm run build --filter llamaindex
- name: Copy examples
run: rsync -rv --exclude=node_modules ./examples ${{ runner.temp }}
- name: Pack
- name: Pack @llamaindex/env
run: pnpm pack --pack-destination ${{ runner.temp }}
working-directory: packages/env
- name: Pack llamaindex
run: pnpm pack --pack-destination ${{ runner.temp }}
working-directory: packages/core
- name: Install llamaindex
- name: Install
run: npm add ${{ runner.temp }}/*.tgz
working-directory: ${{ runner.temp }}/examples
- name: Run Type Check
-1
View File
@@ -5,7 +5,6 @@
"[xml]": {
"editor.defaultFormatter": "redhat.vscode-xml"
},
"jest.rootPath": "./packages/core",
"[python]": {
"editor.defaultFormatter": "ms-python.black-formatter"
},
+1
View File
@@ -127,6 +127,7 @@ module.exports = nextConfig;
- Anthropic Claude Instant and Claude 2
- Llama2 Chat LLMs (70B, 13B, and 7B parameters)
- MistralAI Chat LLMs
- Fireworks Chat LLMs
## Contributing:
@@ -1 +1,2 @@
label: "Agents"
position: 3
@@ -0,0 +1,314 @@
# Multi-Document Agent
In this guide, you learn towards setting up an agent that can effectively answer different types of questions over a larger set of documents.
These questions include the following
- QA over a specific doc
- QA comparing different docs
- Summaries over a specific doc
- Comparing summaries between different docs
We do this with the following architecture:
- setup a “document agent” over each Document: each doc agent can do QA/summarization within its doc
- setup a top-level agent over this set of document agents. Do tool retrieval and then do CoT over the set of tools to answer a question.
## Setup and Download Data
We first start by installing the necessary libraries and downloading the data.
```bash
pnpm i llamaindex
```
```ts
import {
Document,
ObjectIndex,
OpenAI,
OpenAIAgent,
QueryEngineTool,
SimpleNodeParser,
SimpleToolNodeMapping,
SummaryIndex,
VectorStoreIndex,
serviceContextFromDefaults,
storageContextFromDefaults,
} from "llamaindex";
```
And then for the data we will run through a list of countries and download the wikipedia page for each country.
```ts
import fs from "fs";
import path from "path";
const dataPath = path.join(__dirname, "tmp_data");
const extractWikipediaTitle = async (title: string) => {
const fileExists = fs.existsSync(path.join(dataPath, `${title}.txt`));
if (fileExists) {
console.log(`File already exists for the title: ${title}`);
return;
}
const queryParams = new URLSearchParams({
action: "query",
format: "json",
titles: title,
prop: "extracts",
explaintext: "true",
});
const url = `https://en.wikipedia.org/w/api.php?${queryParams}`;
const response = await fetch(url);
const data: any = await response.json();
const pages = data.query.pages;
const page = pages[Object.keys(pages)[0]];
const wikiText = page.extract;
await new Promise((resolve) => {
fs.writeFile(path.join(dataPath, `${title}.txt`), wikiText, (err: any) => {
if (err) {
console.error(err);
resolve(title);
return;
}
console.log(`${title} stored in file!`);
resolve(title);
});
});
};
```
```ts
export const extractWikipedia = async (titles: string[]) => {
if (!fs.existsSync(dataPath)) {
fs.mkdirSync(dataPath);
}
for await (const title of titles) {
await extractWikipediaTitle(title);
}
console.log("Extration finished!");
```
These files will be saved in the `tmp_data` folder.
Now we can call the function to download the data for each country.
```ts
await extractWikipedia([
"Brazil",
"United States",
"Canada",
"Mexico",
"Argentina",
"Chile",
"Colombia",
"Peru",
"Venezuela",
"Ecuador",
"Bolivia",
"Paraguay",
"Uruguay",
"Guyana",
"Suriname",
"French Guiana",
"Falkland Islands",
]);
```
## Load the data
Now that we have the data, we can load it into the LlamaIndex and store as a document.
```ts
import { Document } from "llamaindex";
const countryDocs: Record<string, Document> = {};
for (const title of wikiTitles) {
const path = `./agent/helpers/tmp_data/${title}.txt`;
const text = await fs.readFile(path, "utf-8");
const document = new Document({ text: text, id_: path });
countryDocs[title] = document;
}
```
## Setup LLM and StorageContext
We will be using gpt-4 for this example and we will use the `StorageContext` to store the documents in-memory.
```ts
const llm = new OpenAI({
model: "gpt-4",
});
const ctx = serviceContextFromDefaults({ llm });
const storageContext = await storageContextFromDefaults({
persistDir: "./storage",
});
```
## Building Multi-Document Agents
In this section we show you how to construct the multi-document agent. We first build a document agent for each document, and then define the top-level parent agent with an object index.
```ts
const documentAgents: Record<string, any> = {};
const queryEngines: Record<string, any> = {};
```
Now we iterate over each country and create a document agent for each one.
### Build Agent for each Document
In this section we define “document agents” for each document.
We define both a vector index (for semantic search) and summary index (for summarization) for each document. The two query engines are then converted into tools that are passed to an OpenAI function calling agent.
This document agent can dynamically choose to perform semantic search or summarization within a given document.
We create a separate document agent for each coutnry.
```ts
for (const title of wikiTitles) {
// parse the document into nodes
const nodes = new SimpleNodeParser({
chunkSize: 200,
chunkOverlap: 20,
}).getNodesFromDocuments([countryDocs[title]]);
// create the vector index for specific search
const vectorIndex = await VectorStoreIndex.init({
serviceContext: serviceContext,
storageContext: storageContext,
nodes,
});
// create the summary index for broader search
const summaryIndex = await SummaryIndex.init({
serviceContext: serviceContext,
nodes,
});
const vectorQueryEngine = summaryIndex.asQueryEngine();
const summaryQueryEngine = summaryIndex.asQueryEngine();
// create the query engines for each task
const queryEngineTools = [
new QueryEngineTool({
queryEngine: vectorQueryEngine,
metadata: {
name: "vector_tool",
description: `Useful for questions related to specific aspects of ${title} (e.g. the history, arts and culture, sports, demographics, or more).`,
},
}),
new QueryEngineTool({
queryEngine: summaryQueryEngine,
metadata: {
name: "summary_tool",
description: `Useful for any requests that require a holistic summary of EVERYTHING about ${title}. For questions about more specific sections, please use the vector_tool.`,
},
}),
];
// create the document agent
const agent = new OpenAIAgent({
tools: queryEngineTools,
llm,
verbose: true,
});
documentAgents[title] = agent;
queryEngines[title] = vectorIndex.asQueryEngine();
}
```
## Build Top-Level Agent
Now we define the top-level agent that can answer questions over the set of document agents.
This agent takes in all document agents as tools. This specific agent RetrieverOpenAIAgent performs tool retrieval before tool use (unlike a default agent that tries to put all tools in the prompt).
Here we use a top-k retriever, but we encourage you to customize the tool retriever method!
Firstly, we create a tool for each document agent
```ts
const allTools: QueryEngineTool[] = [];
```
```ts
for (const title of wikiTitles) {
const wikiSummary = `
This content contains Wikipedia articles about ${title}.
Use this tool if you want to answer any questions about ${title}
`;
const docTool = new QueryEngineTool({
queryEngine: documentAgents[title],
metadata: {
name: `tool_${title}`,
description: wikiSummary,
},
});
allTools.push(docTool);
}
```
Our top level agent will use this document agents as tools and use toolRetriever to retrieve the best tool to answer a question.
```ts
// map the tools to nodes
const toolMapping = SimpleToolNodeMapping.fromObjects(allTools);
// create the object index
const objectIndex = await ObjectIndex.fromObjects(
allTools,
toolMapping,
VectorStoreIndex,
{
serviceContext,
storageContext,
},
);
// create the top agent
const topAgent = new OpenAIAgent({
toolRetriever: await objectIndex.asRetriever({}),
llm,
verbose: true,
prefixMessages: [
{
content:
"You are an agent designed to answer queries about a set of given countries. Please always use the tools provided to answer a question. Do not rely on prior knowledge.",
role: "system",
},
],
});
```
## Use the Agent
Now we can use the agent to answer questions.
```ts
const response = await topAgent.chat({
message: "Tell me the differences between Brazil and Canada economics?",
});
// print output
console.log(response);
```
You can find the full code for this example [here](https://github.com/run-llama/LlamaIndexTS/tree/main/examples/agent/multi-document-agent.ts)
+6 -2
View File
@@ -1,3 +1,7 @@
---
sidebar_position: 0
---
# OpenAI Agent
OpenAI API that supports function calling, its never been easier to build your own agent!
@@ -82,7 +86,7 @@ const divideFunctionTool = new FunctionTool(divideNumbers, {
Now we can create an OpenAIAgent with the function tools.
```ts
const worker = new OpenAIAgent({
const agent = new OpenAIAgent({
tools: [sumFunctionTool, divideFunctionTool],
verbose: true,
});
@@ -93,7 +97,7 @@ const worker = new OpenAIAgent({
Now we can chat with the agent.
```ts
const response = await worker.chat({
const response = await agent.chat({
message: "How much is 5 + 5? then divide by 2",
});
@@ -1,3 +1,7 @@
---
sidebar_position: 1
---
# OpenAI Agent + QueryEngineTool
QueryEngineTool is a tool that allows you to query a vector index. In this example, we will create a vector index from a set of documents and then create a QueryEngineTool from the vector index. We will then create an OpenAIAgent with the QueryEngineTool and chat with the agent.
@@ -0,0 +1,203 @@
# ReAct Agent
The ReAct agent is an AI agent that can reason over the next action, construct an action command, execute the action, and repeat these steps in an iterative loop until the task is complete.
In this notebook tutorial, we showcase how to write your ReAct agent using the `llamaindex` package.
## Setup
First, you need to install the `llamaindex` package. You can do this by running the following command in your terminal:
```bash
pnpm i llamaindex
```
And then you can import the `OpenAIAgent` and `FunctionTool` from the `llamaindex` package.
```ts
import { FunctionTool, OpenAIAgent } from "llamaindex";
```
Then we can define a function to sum two numbers and another function to divide two numbers.
```ts
function sumNumbers({ a, b }: { a: number; b: number }): number {
return a + b;
}
// Define a function to divide two numbers
function divideNumbers({ a, b }: { a: number; b: number }): number {
return a / b;
}
```
## Create a function tool
Now we can create a function tool from the sum function and another function tool from the divide function.
For the parameters of the sum function, we can define a JSON schema.
### JSON Schema
```ts
const sumJSON = {
type: "object",
properties: {
a: {
type: "number",
description: "The first number",
},
b: {
type: "number",
description: "The second number",
},
},
required: ["a", "b"],
};
const divideJSON = {
type: "object",
properties: {
a: {
type: "number",
description: "The dividend a to divide",
},
b: {
type: "number",
description: "The divisor b to divide by",
},
},
required: ["a", "b"],
};
const sumFunctionTool = new FunctionTool(sumNumbers, {
name: "sumNumbers",
description: "Use this function to sum two numbers",
parameters: sumJSON,
});
const divideFunctionTool = new FunctionTool(divideNumbers, {
name: "divideNumbers",
description: "Use this function to divide two numbers",
parameters: divideJSON,
});
```
## Create an ReAct
Now we can create an OpenAIAgent with the function tools.
```ts
const agent = new ReActAgent({
tools: [sumFunctionTool, divideFunctionTool],
verbose: true,
});
```
## Chat with the agent
Now we can chat with the agent.
```ts
const response = await agent.chat({
message: "How much is 5 + 5? then divide by 2",
});
console.log(String(response));
```
The output will be:
```bash
Thought: I need to use a tool to help me answer the question.
Action: sumNumbers
Action Input: {"a":5,"b":5}
Observation: 10
Thought: I can answer without using any more tools.
Answer: The sum of 5 and 5 is 10, and when divided by 2, the result is 5.
The sum of 5 and 5 is 10, and when divided by 2, the result is 5.
```
## Full code
```ts
import { FunctionTool, ReActAgent } from "llamaindex";
// Define a function to sum two numbers
function sumNumbers({ a, b }: { a: number; b: number }): number {
return a + b;
}
// Define a function to divide two numbers
function divideNumbers({ a, b }: { a: number; b: number }): number {
return a / b;
}
// Define the parameters of the sum function as a JSON schema
const sumJSON = {
type: "object",
properties: {
a: {
type: "number",
description: "The first number",
},
b: {
type: "number",
description: "The second number",
},
},
required: ["a", "b"],
};
// Define the parameters of the divide function as a JSON schema
const divideJSON = {
type: "object",
properties: {
a: {
type: "number",
description: "The argument a to divide",
},
b: {
type: "number",
description: "The argument b to divide",
},
},
required: ["a", "b"],
};
async function main() {
// Create a function tool from the sum function
const sumFunctionTool = new FunctionTool(sumNumbers, {
name: "sumNumbers",
description: "Use this function to sum two numbers",
parameters: sumJSON,
});
// Create a function tool from the divide function
const divideFunctionTool = new FunctionTool(divideNumbers, {
name: "divideNumbers",
description: "Use this function to divide two numbers",
parameters: divideJSON,
});
// Create an OpenAIAgent with the function tools
const agent = new OpenAIAgent({
tools: [sumFunctionTool, divideFunctionTool],
verbose: true,
});
// Chat with the agent
const response = await agent.chat({
message: "I want to sum 5 and 5 and then divide by 2",
});
// Print the response
console.log(String(response));
}
main().then(() => {
console.log("Done");
});
```
-17
View File
@@ -1,17 +0,0 @@
---
sidebar_position: 3
---
# Reader / Loader
LlamaIndex.TS supports easy loading of files from folders using the `SimpleDirectoryReader` class. Currently, `.txt`, `.pdf`, `.csv`, `.md` and `.docx` files are supported, with more planned in the future!
```typescript
import { SimpleDirectoryReader } from "llamaindex";
documents = new SimpleDirectoryReader().loadData("./data");
```
## API Reference
- [SimpleDirectoryReader](../api/classes/SimpleDirectoryReader.md)
+48
View File
@@ -0,0 +1,48 @@
---
sidebar_position: 4
---
import CodeBlock from "@theme/CodeBlock";
import CodeSource from "!raw-loader!../../../../examples/readers/src/simple-directory-reader";
import CodeSource2 from "!raw-loader!../../../../examples/readers/src/custom-simple-directory-reader";
import CodeSource3 from "!raw-loader!../../../../examples/readers/src/llamaparse";
# Loader
Before you can start indexing your documents, you need to load them into memory.
### SimpleDirectoryReader
[![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/github/run-llama/LlamaIndexTS/tree/main/examples/readers?file=src/simple-directory-reader.ts&title=Simple%20Directory%20Reader)
LlamaIndex.TS supports easy loading of files from folders using the `SimpleDirectoryReader` class.
It is a simple reader that reads all files from a directory and its subdirectories.
<CodeBlock language="ts">{CodeSource}</CodeBlock>
Currently, it supports reading `.csv`, `.docx`, `.html`, `.md` and `.pdf` files,
but support for other file types is planned.
Also, you can provide a `defaultReader` as a fallback for files with unsupported extensions.
Or pass new readers for `fileExtToReader` to support more file types.
<CodeBlock language="ts" showLineNumbers metastring="{8-12,17-21}">
{CodeSource2}
</CodeBlock>
### LlamaParse
LlamaParse is an API created by LlamaIndex to efficiently parse files, e.g. it's great at converting PDF tables into markdown.
To use it, first login and get an API key from https://cloud.llamaindex.ai. Make sure to store the key in the environment variable `LLAMA_CLOUD_API_KEY`.
Then, you can use the `LlamaParseReader` class to read a local PDF file and convert it into a markdown document that can be used by LlamaIndex:
<CodeBlock language="ts">{CodeSource3}</CodeBlock>
Alternatively, you can set the [`resultType`](../api/classes/LlamaParseReader.md#resulttype) option to `text` to get the parsed document as a text string.
## API Reference
- [SimpleDirectoryReader](../api/classes/SimpleDirectoryReader.md)
@@ -0,0 +1,2 @@
label: "Embeddings"
position: 3
@@ -0,0 +1 @@
label: "Available Embeddings"
@@ -0,0 +1,25 @@
# HuggingFace
To use HuggingFace embeddings, you need to import `HuggingFaceEmbedding` from `llamaindex`.
```ts
import { HuggingFaceEmbedding, serviceContextFromDefaults } from "llamaindex";
const huggingFaceEmbeds = new HuggingFaceEmbedding();
const serviceContext = serviceContextFromDefaults({ embedModel: openaiEmbeds });
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const queryEngine = index.asQueryEngine();
const query = "What is the meaning of life?";
const results = await queryEngine.query({
query,
});
```
@@ -0,0 +1,29 @@
# MistralAI
To use MistralAI embeddings, you need to import `MistralAIEmbedding` from `llamaindex`.
```ts
import { MistralAIEmbedding, serviceContextFromDefaults } from "llamaindex";
const mistralEmbedModel = new MistralAIEmbedding({
apiKey: "<YOUR_API_KEY>",
});
const serviceContext = serviceContextFromDefaults({
embedModel: mistralEmbedModel,
});
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const queryEngine = index.asQueryEngine();
const query = "What is the meaning of life?";
const results = await queryEngine.query({
query,
});
```
@@ -0,0 +1,27 @@
# Ollama
To use Ollama embeddings, you need to import `Ollama` from `llamaindex`.
```ts
import { Ollama, serviceContextFromDefaults } from "llamaindex";
const ollamaEmbedModel = new Ollama();
const serviceContext = serviceContextFromDefaults({
embedModel: ollamaEmbedModel,
});
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const queryEngine = index.asQueryEngine();
const query = "What is the meaning of life?";
const results = await queryEngine.query({
query,
});
```
@@ -0,0 +1,27 @@
# OpenAI
To use OpenAI embeddings, you need to import `OpenAIEmbedding` from `llamaindex`.
```ts
import { OpenAIEmbedding, serviceContextFromDefaults } from "llamaindex";
const openaiEmbedModel = new OpenAIEmbedding();
const serviceContext = serviceContextFromDefaults({
embedModel: openaiEmbedModel,
});
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const queryEngine = index.asQueryEngine();
const query = "What is the meaning of life?";
const results = await queryEngine.query({
query,
});
```
@@ -0,0 +1,29 @@
# Together
To use together embeddings, you need to import `TogetherEmbedding` from `llamaindex`.
```ts
import { TogetherEmbedding, serviceContextFromDefaults } from "llamaindex";
const togetherEmbedModel = new TogetherEmbedding({
apiKey: "<YOUR_API_KEY>",
});
const serviceContext = serviceContextFromDefaults({
embedModel: togetherEmbedModel,
});
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const queryEngine = index.asQueryEngine();
const query = "What is the meaning of life?";
const results = await queryEngine.query({
query,
});
```
@@ -1,7 +1,3 @@
---
sidebar_position: 3
---
# Embedding
The embedding model in LlamaIndex is responsible for creating numerical representations of text. By default, LlamaIndex will use the `text-embedding-ada-002` model from OpenAI.
@@ -16,7 +12,11 @@ const openaiEmbeds = new OpenAIEmbedding();
const serviceContext = serviceContextFromDefaults({ embedModel: openaiEmbeds });
```
## Local Embedding
For local embeddings, you can use the [HuggingFace](./available_embeddings/huggingface.md) embedding model.
## API Reference
- [OpenAIEmbedding](../api/classes/OpenAIEmbedding.md)
- [ServiceContext](../api/interfaces//ServiceContext.md)
- [OpenAIEmbedding](../../api/classes/OpenAIEmbedding.md)
- [ServiceContext](../../api/interfaces//ServiceContext.md)
+32
View File
@@ -0,0 +1,32 @@
import CodeBlock from "@theme/CodeBlock";
import CodeSource from "!raw-loader!../../../../examples/cloud/chat.ts";
# LlamaCloud
LlamaCloud is a new generation of managed parsing, ingestion, and retrieval services, designed to bring production-grade context-augmentation to your LLM and RAG applications.
Currently, LlamaCloud supports
- Managed Ingestion API, handling parsing and document management
- Managed Retrieval API, configuring optimal retrieval for your RAG system
## Access
We are opening up a private beta to a limited set of enterprise partners for the managed ingestion and retrieval API. If youre interested in centralizing your data pipelines and spending more time working on your actual RAG use cases, come [talk to us.](https://www.llamaindex.ai/contact)
If you have access to LlamaCloud, you can visit [LlamaCloud](https://cloud.llamaindex.ai) to sign in and get an API key.
## Create a Managed Index
Currently, you can't create a managed index on LlamaCloud using LlamaIndexTS, but you can use an existing managed index for retrieval that was created by the Python version of LlamaIndex. See [the LlamaCloudIndex documentation](https://docs.llamaindex.ai/en/stable/module_guides/indexing/llama_cloud_index.html#usage) for more information on how to create a managed index.
## Use a Managed Index
Here's an example of how to use a managed index together with a chat engine:
<CodeBlock language="ts">{CodeSource}</CodeBlock>
## API Reference
- [LlamaCloudIndex](../api/classes/LlamaCloudIndex.md)
- [LlamaCloudRetriever](../api/classes/LlamaCloudRetriever.md)
@@ -0,0 +1,2 @@
label: "LLMs"
position: 3
@@ -0,0 +1 @@
label: "Available LLMs"
@@ -0,0 +1,80 @@
# Anthropic
## Usage
```ts
import { Anthropic, serviceContextFromDefaults } from "llamaindex";
const anthropicLLM = new Anthropic({
apiKey: "<YOUR_API_KEY>",
});
const serviceContext = serviceContextFromDefaults({ llm: anthropicLLM });
```
## Load and index documents
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
```
## Query
```ts
const queryEngine = index.asQueryEngine();
const query = "What is the meaning of life?";
const results = await queryEngine.query({
query,
});
```
## Full Example
```ts
import {
Anthropic,
Document,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
async function main() {
// Create an instance of the Anthropic LLM
const anthropicLLM = new Anthropic({
apiKey: "<YOUR_API_KEY>",
});
// Create a service context
const serviceContext = serviceContextFromDefaults({ llm: anthropicLLM });
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// Create a query engine
const queryEngine = index.asQueryEngine({
retriever,
});
const query = "What is the meaning of life?";
// Query
const response = await queryEngine.query({
query,
});
// Log the response
console.log(response.response);
}
```
@@ -0,0 +1,91 @@
# Azure OpenAI
To use Azure OpenAI, you only need to set a few environment variables together with the `OpenAI` class.
For example:
## Environment Variables
```
export AZURE_OPENAI_KEY="<YOUR KEY HERE>"
export AZURE_OPENAI_ENDPOINT="<YOUR ENDPOINT, see https://learn.microsoft.com/en-us/azure/ai-services/openai/quickstart?tabs=command-line%2Cpython&pivots=rest-api>"
export AZURE_OPENAI_DEPLOYMENT="gpt-4" # or some other deployment name
```
## Usage
```ts
import { OpenAI, serviceContextFromDefaults } from "llamaindex";
const azureOpenaiLLM = new OpenAI({ model: "gpt-4", temperature: 0 });
const serviceContext = serviceContextFromDefaults({ llm: azureOpenaiLLM });
```
## Load and index documents
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
```
## Query
```ts
const queryEngine = index.asQueryEngine();
const query = "What is the meaning of life?";
const results = await queryEngine.query({
query,
});
```
## Full Example
```ts
import {
OpenAI,
Document,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
async function main() {
// Create an instance of the LLM
const azureOpenaiLLM = new OpenAI({ model: "gpt-4", temperature: 0 });
// Create a service context
const serviceContext = serviceContextFromDefaults({ llm: azureOpenaiLLM });
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// get retriever
const retriever = index.asRetriever();
// Create a query engine
const queryEngine = index.asQueryEngine({
retriever,
});
const query = "What is the meaning of life?";
// Query
const response = await queryEngine.query({
query,
});
// Log the response
console.log(response.response);
}
```
@@ -0,0 +1,65 @@
# Fireworks LLM
Fireworks.ai focus on production use cases for open source LLMs, offering speed and quality.
## Usage
```ts
import { FireworksLLM, serviceContextFromDefaults } from "llamaindex";
const fireworksLLM = new FireworksLLM({
apiKey: "<YOUR_API_KEY>",
});
const serviceContext = serviceContextFromDefaults({ llm: fireworksLLM });
```
## Load and index documents
For this example, we will load the Berkshire Hathaway 2022 annual report pdf
```ts
const reader = new PDFReader();
const documents = await reader.loadData("../data/brk-2022.pdf");
// Split text and create embeddings. Store them in a VectorStoreIndex
const index = await VectorStoreIndex.fromDocuments(documents, {
serviceContext,
});
```
## Query
```ts
const queryEngine = index.asQueryEngine();
const response = await queryEngine.query({
query: "What mistakes did Warren E. Buffett make?",
});
```
## Full Example
```ts
import { VectorStoreIndex } from "llamaindex";
import { PDFReader } from "llamaindex/readers/PDFReader";
async function main() {
// Load PDF
const reader = new PDFReader();
const documents = await reader.loadData("../data/brk-2022.pdf");
// Split text and create embeddings. Store them in a VectorStoreIndex
const index = await VectorStoreIndex.fromDocuments(documents);
// Query the index
const queryEngine = index.asQueryEngine();
const response = await queryEngine.query({
query: "What mistakes did Warren E. Buffett make?",
});
// Output response
console.log(response.toString());
}
main().catch(console.error);
```
@@ -0,0 +1,100 @@
# LLama2
## Usage
```ts
import { Ollama, serviceContextFromDefaults } from "llamaindex";
const llama2LLM = new LlamaDeuce({ chatStrategy: DeuceChatStrategy.META });
const serviceContext = serviceContextFromDefaults({ llm: llama2LLM });
```
## Usage with Replication
```ts
import {
Ollama,
ReplicateSession,
serviceContextFromDefaults,
} from "llamaindex";
const replicateSession = new ReplicateSession({
replicateKey,
});
const llama2LLM = new LlamaDeuce({
chatStrategy: DeuceChatStrategy.META,
replicateSession,
});
const serviceContext = serviceContextFromDefaults({ llm: llama2LLM });
```
## Load and index documents
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
```
## Query
```ts
const queryEngine = index.asQueryEngine();
const query = "What is the meaning of life?";
const results = await queryEngine.query({
query,
});
```
## Full Example
```ts
import {
LlamaDeuce,
Document,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
async function main() {
// Create an instance of the LLM
const llama2LLM = new LlamaDeuce({ chatStrategy: DeuceChatStrategy.META });
// Create a service context
const serviceContext = serviceContextFromDefaults({ llm: mistralLLM });
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// get retriever
const retriever = index.asRetriever();
// Create a query engine
const queryEngine = index.asQueryEngine({
retriever,
});
const query = "What is the meaning of life?";
// Query
const response = await queryEngine.query({
query,
});
// Log the response
console.log(response.response);
}
```
@@ -0,0 +1,82 @@
# Mistral
## Usage
```ts
import { Ollama, serviceContextFromDefaults } from "llamaindex";
const mistralLLM = new MistralAI({
model: "mistral-tiny",
apiKey: "<YOUR_API_KEY>",
});
const serviceContext = serviceContextFromDefaults({ llm: mistralLLM });
```
## Load and index documents
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
```
## Query
```ts
const queryEngine = index.asQueryEngine();
const query = "What is the meaning of life?";
const results = await queryEngine.query({
query,
});
```
## Full Example
```ts
import {
MistralAI,
Document,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
async function main() {
// Create an instance of the LLM
const mistralLLM = new MistralAI({ model: "mistral-tiny" });
// Create a service context
const serviceContext = serviceContextFromDefaults({ llm: mistralLLM });
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// get retriever
const retriever = index.asRetriever();
// Create a query engine
const queryEngine = index.asQueryEngine({
retriever,
});
const query = "What is the meaning of life?";
// Query
const response = await queryEngine.query({
query,
});
// Log the response
console.log(response.response);
}
```
@@ -0,0 +1,89 @@
# Ollama
## Usage
```ts
import { Ollama, serviceContextFromDefaults } from "llamaindex";
const ollamaLLM = new Ollama({ model: "llama2", temperature: 0.75 });
const serviceContext = serviceContextFromDefaults({
llm: ollamaLLM,
embedModel: ollamaLLM,
});
```
## Load and index documents
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
```
## Query
```ts
const queryEngine = index.asQueryEngine();
const query = "What is the meaning of life?";
const results = await queryEngine.query({
query,
});
```
## Full Example
```ts
import {
Ollama,
Document,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
import fs from "fs/promises";
async function main() {
// Create an instance of the LLM
const ollamaLLM = new Ollama({ model: "llama2", temperature: 0.75 });
const essay = await fs.readFile("./paul_graham_essay.txt", "utf-8");
// Create a service context
const serviceContext = serviceContextFromDefaults({
embedModel: ollamaLLM, // prevent 'Set OpenAI Key in OPENAI_API_KEY env variable' error
llm: ollamaLLM,
});
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// get retriever
const retriever = index.asRetriever();
// Create a query engine
const queryEngine = index.asQueryEngine({
retriever,
});
const query = "What is the meaning of life?";
// Query
const response = await queryEngine.query({
query,
});
// Log the response
console.log(response.response);
}
```
@@ -0,0 +1,83 @@
# OpenAI
```ts
import { OpenAI, serviceContextFromDefaults } from "llamaindex";
const openaiLLM = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0, apiKey: <YOUR_API_KEY> });
const serviceContext = serviceContextFromDefaults({ llm: openaiLLM });
```
You can setup the apiKey on the environment variables, like:
```bash
export OPENAI_API_KEY="<YOUR_API_KEY>"
```
## Load and index documents
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
```
## Query
```ts
const queryEngine = index.asQueryEngine();
const query = "What is the meaning of life?";
const results = await queryEngine.query({
query,
});
```
## Full Example
```ts
import {
OpenAI,
Document,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
async function main() {
// Create an instance of the LLM
const openaiLLM = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0 });
// Create a service context
const serviceContext = serviceContextFromDefaults({ llm: openaiLLM });
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// get retriever
const retriever = index.asRetriever();
// Create a query engine
const queryEngine = index.asQueryEngine({
retriever,
});
const query = "What is the meaning of life?";
// Query
const response = await queryEngine.query({
query,
});
// Log the response
console.log(response.response);
}
```
@@ -0,0 +1,83 @@
# Portkey LLM
## Usage
```ts
import { Portkey, serviceContextFromDefaults } from "llamaindex";
const portkeyLLM = new Portkey({
apiKey: "<YOUR_API_KEY>",
});
const serviceContext = serviceContextFromDefaults({ llm: portkeyLLM });
```
## Load and index documents
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
```
## Query
```ts
const queryEngine = index.asQueryEngine();
const query = "What is the meaning of life?";
const results = await queryEngine.query({
query,
});
```
## Full Example
```ts
import {
Portkey,
Document,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
async function main() {
// Create an instance of the LLM
const portkeyLLM = new Portkey({
apiKey: "<YOUR_API_KEY>",
});
// Create a service context
const serviceContext = serviceContextFromDefaults({ llm: portkeyLLM });
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// get retriever
const retriever = index.asRetriever();
// Create a query engine
const queryEngine = index.asQueryEngine({
retriever,
});
const query = "What is the meaning of life?";
// Query
const response = await queryEngine.query({
query,
});
// Log the response
console.log(response.response);
}
```
@@ -0,0 +1,83 @@
# Together LLM
## Usage
```ts
import { TogetherLLM, serviceContextFromDefaults } from "llamaindex";
const togetherLLM = new TogetherLLM({
apiKey: "<YOUR_API_KEY>",
});
const serviceContext = serviceContextFromDefaults({ llm: togetherLLM });
```
## Load and index documents
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
```ts
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
```
## Query
```ts
const queryEngine = index.asQueryEngine();
const query = "What is the meaning of life?";
const results = await queryEngine.query({
query,
});
```
## Full Example
```ts
import {
TogetherLLM,
Document,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
async function main() {
// Create an instance of the LLM
const togetherLLM = new TogetherLLM({
apiKey: "<YOUR_API_KEY>",
});
// Create a service context
const serviceContext = serviceContextFromDefaults({ llm: togetherLLM });
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// get retriever
const retriever = index.asRetriever();
// Create a query engine
const queryEngine = index.asQueryEngine({
retriever,
});
const query = "What is the meaning of life?";
// Query
const response = await queryEngine.query({
query,
});
// Log the response
console.log(response.response);
}
```
@@ -2,7 +2,7 @@
sidebar_position: 3
---
# LLM
# Large Language Models (LLMs)
The LLM is responsible for reading text and generating natural language responses to queries. By default, LlamaIndex.TS uses `gpt-3.5-turbo`.
@@ -28,6 +28,10 @@ export AZURE_OPENAI_ENDPOINT="<YOUR ENDPOINT, see https://learn.microsoft.com/en
export AZURE_OPENAI_DEPLOYMENT="gpt-4" # or some other deployment name
```
## Local LLM
For local LLMs, currently we recommend the use of [Ollama](./available_llms/ollama.md) LLM.
## API Reference
- [OpenAI](../api/classes/OpenAI.md)
+66 -1
View File
@@ -1,5 +1,5 @@
---
sidebar_position: 3
sidebar_position: 4
---
# NodeParser
@@ -27,6 +27,71 @@ const splitter = new SentenceSplitter({ chunkSize: 1 });
const textSplits = splitter.splitText("Hello World");
```
## MarkdownNodeParser
The `MarkdownNodeParser` is a more advanced `NodeParser` that can handle markdown documents. It will split the markdown into nodes and then parse the nodes into a `Document` object.
```typescript
import { MarkdownNodeParser } from "llamaindex";
const nodeParser = new MarkdownNodeParser();
const nodes = nodeParser.getNodesFromDocuments([
new Document({
text: `# Main Header
Main content
# Header 2
Header 2 content
## Sub-header
Sub-header content
`,
}),
]);
```
The output metadata will be something like:
```bash
[
TextNode {
id_: '008e41a8-b097-487c-bee8-bd88b9455844',
metadata: { 'Header 1': 'Main Header' },
excludedEmbedMetadataKeys: [],
excludedLlmMetadataKeys: [],
relationships: { PARENT: [Array] },
hash: 'KJ5e/um/RkHaNR6bonj9ormtZY7I8i4XBPVYHXv1A5M=',
text: 'Main Header\nMain content',
textTemplate: '',
metadataSeparator: '\n'
},
TextNode {
id_: '0f5679b3-ba63-4aff-aedc-830c4208d0b5',
metadata: { 'Header 1': 'Header 2' },
excludedEmbedMetadataKeys: [],
excludedLlmMetadataKeys: [],
relationships: { PARENT: [Array] },
hash: 'IP/g/dIld3DcbK+uHzDpyeZ9IdOXY4brxhOIe7wc488=',
text: 'Header 2\nHeader 2 content',
textTemplate: '',
metadataSeparator: '\n'
},
TextNode {
id_: 'e81e9bd0-121c-4ead-8ca7-1639d65fdf90',
metadata: { 'Header 1': 'Header 2', 'Header 2': 'Sub-header' },
excludedEmbedMetadataKeys: [],
excludedLlmMetadataKeys: [],
relationships: { PARENT: [Array] },
hash: 'B3kYNnxaYi9ghtAgwza0ZEVKF4MozobkNUlcekDL7JQ=',
text: 'Sub-header\nSub-header content',
textTemplate: '',
metadataSeparator: '\n'
}
]
```
## API Reference
- [SimpleNodeParser](../api/classes/SimpleNodeParser.md)
@@ -0,0 +1,2 @@
label: "Node Postprocessors"
position: 3
@@ -0,0 +1,71 @@
# Cohere Reranker
The Cohere Reranker is a postprocessor that uses the Cohere API to rerank the results of a search query.
## Setup
Firstly, you will need to install the `llamaindex` package.
```bash
pnpm install llamaindex
```
Now, you will need to sign up for an API key at [Cohere](https://cohere.ai/). Once you have your API key you can import the necessary modules and create a new instance of the `CohereRerank` class.
```ts
import {
CohereRerank,
Document,
OpenAI,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
```
## Load and index documents
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
```ts
const document = new Document({ text: essay, id_: "essay" });
const serviceContext = serviceContextFromDefaults({
llm: new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 }),
});
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
```
## Increase similarity topK to retrieve more results
The default value for `similarityTopK` is 2. This means that only the most similar document will be returned. To retrieve more results, you can increase the value of `similarityTopK`.
```ts
const retriever = index.asRetriever();
retriever.similarityTopK = 5;
```
## Create a new instance of the CohereRerank class
Then you can create a new instance of the `CohereRerank` class and pass in your API key and the number of results you want to return.
```ts
const nodePostprocessor = new CohereRerank({
apiKey: "<COHERE_API_KEY>",
topN: 4,
});
```
## Create a query engine with the retriever and node postprocessor
```ts
const queryEngine = index.asQueryEngine({
retriever,
nodePostprocessors: [nodePostprocessor],
});
// log the response
const response = await queryEngine.query("Where did the author grown up?");
```
@@ -0,0 +1,110 @@
# Node Postprocessors
## Concept
Node postprocessors are a set of modules that take a set of nodes, and apply some kind of transformation or filtering before returning them.
In LlamaIndex, node postprocessors are most commonly applied within a query engine, after the node retrieval step and before the response synthesis step.
LlamaIndex offers several node postprocessors for immediate use, while also providing a simple API for adding your own custom postprocessors.
## Usage Pattern
An example of using a node postprocessors is below:
```ts
import {
Node,
NodeWithScore,
SimilarityPostprocessor,
CohereRerank,
} from "llamaindex";
const nodes: NodeWithScore[] = [
{
node: new TextNode({ text: "hello world" }),
score: 0.8,
},
{
node: new TextNode({ text: "LlamaIndex is the best" }),
score: 0.6,
},
];
// similarity postprocessor: filter nodes below 0.75 similarity score
const processor = new SimilarityPostprocessor({
similarityCutoff: 0.7,
});
const filteredNodes = processor.postprocessNodes(nodes);
// cohere rerank: rerank nodes given query using trained model
const reranker = new CohereRerank({
apiKey: "<COHERE_API_KEY>",
topN: 2,
});
const rerankedNodes = await reranker.postprocessNodes(nodes, "<user_query>");
console.log(filteredNodes, rerankedNodes);
```
Now you can use the `filteredNodes` and `rerankedNodes` in your application.
## Using Node Postprocessors in LlamaIndex
Most commonly, node-postprocessors will be used in a query engine, where they are applied to the nodes returned from a retriever, and before the response synthesis step.
### Using Node Postprocessors in a Query Engine
```ts
import { Node, NodeWithScore, SimilarityPostprocessor, CohereRerank } from "llamaindex";
const nodes: NodeWithScore[] = [
{
node: new TextNode({ text: "hello world" }),
score: 0.8,
},
{
node: new TextNode({ text: "LlamaIndex is the best" }),
score: 0.6,
}
];
// cohere rerank: rerank nodes given query using trained model
const reranker = new CohereRerank({
apiKey: "<COHERE_API_KEY>,
topN: 2,
})
const document = new Document({ text: "essay", id_: "essay" });
const serviceContext = serviceContextFromDefaults({
llm: new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 }),
});
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const queryEngine = index.asQueryEngine({
nodePostprocessors: [processor, reranker],
});
// all node post-processors will be applied during each query
const response = await queryEngine.query("<user_query>");
```
### Using with retrieved nodes
```ts
import { SimilarityPostprocessor } from "llamaindex";
nodes = await index.asRetriever().retrieve("test query str");
const processor = new SimilarityPostprocessor({
similarityCutoff: 0.7,
});
const filteredNodes = processor.postprocessNodes(nodes);
```
@@ -0,0 +1,2 @@
label: "Prompts"
position: 0
+76
View File
@@ -0,0 +1,76 @@
# Prompts
Prompting is the fundamental input that gives LLMs their expressive power. LlamaIndex uses prompts to build the index, do insertion, perform traversal during querying, and to synthesize the final answer.
Users may also provide their own prompt templates to further customize the behavior of the framework. The best method for customizing is copying the default prompt from the link above, and using that as the base for any modifications.
## Usage Pattern
Currently, there are two ways to customize prompts in LlamaIndex:
For both methods, you will need to create an function that overrides the default prompt.
```ts
// Define a custom prompt
const newTextQaPrompt: TextQaPrompt = ({ context, query }) => {
return `Context information is below.
---------------------
${context}
---------------------
Given the context information and not prior knowledge, answer the query.
Answer the query in the style of a Sherlock Holmes detective novel.
Query: ${query}
Answer:`;
};
```
### 1. Customizing the default prompt on initialization
The first method is to create a new instance of `ResponseSynthesizer` (or the module you would like to update the prompt) and pass the custom prompt to the `responseBuilder` parameter. Then, pass the instance to the `asQueryEngine` method of the index.
```ts
// Create an instance of response synthesizer
const responseSynthesizer = new ResponseSynthesizer({
responseBuilder: new CompactAndRefine(serviceContext, newTextQaPrompt),
});
// Create index
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// Query the index
const queryEngine = index.asQueryEngine({ responseSynthesizer });
const response = await queryEngine.query({
query: "What did the author do in college?",
});
```
### 2. Customizing submodules prompt
The second method is that most of the modules in LlamaIndex have a `getPrompts` and a `updatePrompt` method that allows you to override the default prompt. This method is useful when you want to change the prompt on the fly or in submodules on a more granular level.
```ts
// Create index
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
// Query the index
const queryEngine = index.asQueryEngine();
// Get a list of prompts for the query engine
const prompts = queryEngine.getPrompts();
// output: { "responseSynthesizer:textQATemplate": defaultTextQaPrompt, "responseSynthesizer:refineTemplate": defaultRefineTemplatePrompt }
// Now, we can override the default prompt
queryEngine.updatePrompt({
"responseSynthesizer:textQATemplate": newTextQaPrompt,
});
const response = await queryEngine.query({
query: "What did the author do in college?",
});
```
+1
View File
@@ -1,2 +1,3 @@
package-lock.json
storage
tmp_data
@@ -0,0 +1,55 @@
import fs from "fs";
import path from "path";
const dataPath = path.join(__dirname, "tmp_data");
const extractWikipediaTitle = async (title: string) => {
const fileExists = fs.existsSync(path.join(dataPath, `${title}.txt`));
if (fileExists) {
console.log(`Arquivo já existe para o título: ${title}`);
return;
}
const queryParams = new URLSearchParams({
action: "query",
format: "json",
titles: title,
prop: "extracts",
explaintext: "true",
});
const url = `https://en.wikipedia.org/w/api.php?${queryParams}`;
const response = await fetch(url);
const data: any = await response.json();
const pages = data.query.pages;
const page = pages[Object.keys(pages)[0]];
const wikiText = page.extract;
await new Promise((resolve) => {
fs.writeFile(path.join(dataPath, `${title}.txt`), wikiText, (err: any) => {
if (err) {
console.error(err);
resolve(title);
return;
}
console.log(`${title} stored!`);
resolve(title);
});
});
};
export const extractWikipedia = async (titles: string[]) => {
if (!fs.existsSync(dataPath)) {
fs.mkdirSync(dataPath);
}
for await (const title of titles) {
await extractWikipediaTitle(title);
}
console.log("Extration finished!");
};
+157
View File
@@ -0,0 +1,157 @@
import fs from "node:fs/promises";
import {
Document,
ObjectIndex,
OpenAI,
OpenAIAgent,
QueryEngineTool,
SimpleNodeParser,
SimpleToolNodeMapping,
SummaryIndex,
VectorStoreIndex,
serviceContextFromDefaults,
storageContextFromDefaults,
} from "llamaindex";
import { extractWikipedia } from "./helpers/extractWikipedia";
const wikiTitles = ["Brazil", "Canada"];
async function main() {
await extractWikipedia(wikiTitles);
const countryDocs: Record<string, Document> = {};
for (const title of wikiTitles) {
const path = `./agent/helpers/tmp_data/${title}.txt`;
const text = await fs.readFile(path, "utf-8");
const document = new Document({ text: text, id_: path });
countryDocs[title] = document;
}
const llm = new OpenAI({
model: "gpt-4",
});
const serviceContext = serviceContextFromDefaults({ llm });
const storageContext = await storageContextFromDefaults({
persistDir: "./storage",
});
// TODO: fix any
const documentAgents: any = {};
const queryEngines: any = {};
for (const title of wikiTitles) {
console.log(`Processing ${title}`);
const nodes = new SimpleNodeParser({
chunkSize: 200,
chunkOverlap: 20,
}).getNodesFromDocuments([countryDocs[title]]);
console.log(`Creating index for ${title}`);
const vectorIndex = await VectorStoreIndex.init({
serviceContext: serviceContext,
storageContext: storageContext,
nodes,
});
const summaryIndex = await SummaryIndex.init({
serviceContext: serviceContext,
nodes,
});
console.log(`Creating query engines for ${title}`);
const vectorQueryEngine = summaryIndex.asQueryEngine();
const summaryQueryEngine = summaryIndex.asQueryEngine();
const queryEngineTools = [
new QueryEngineTool({
queryEngine: vectorQueryEngine,
metadata: {
name: "vector_tool",
description: `Useful for questions related to specific aspects of ${title} (e.g. the history, arts and culture, sports, demographics, or more).`,
},
}),
new QueryEngineTool({
queryEngine: summaryQueryEngine,
metadata: {
name: "summary_tool",
description: `Useful for any requests that require a holistic summary of EVERYTHING about ${title}. For questions about more specific sections, please use the vector_tool.`,
},
}),
];
console.log(`Creating agents for ${title}`);
const agent = new OpenAIAgent({
tools: queryEngineTools,
llm,
verbose: true,
});
documentAgents[title] = agent;
queryEngines[title] = vectorIndex.asQueryEngine();
}
const allTools: QueryEngineTool[] = [];
console.log(`Creating tools for all countries`);
for (const title of wikiTitles) {
const wikiSummary = `This content contains Wikipedia articles about ${title}. Use this tool if you want to answer any questions about ${title}`;
console.log(`Creating tool for ${title}`);
const docTool = new QueryEngineTool({
queryEngine: documentAgents[title],
metadata: {
name: `tool_${title}`,
description: wikiSummary,
},
});
allTools.push(docTool);
}
console.log("creating tool mapping");
const toolMapping = SimpleToolNodeMapping.fromObjects(allTools);
const objectIndex = await ObjectIndex.fromObjects(
allTools,
toolMapping,
VectorStoreIndex,
{
serviceContext,
storageContext,
},
);
const topAgent = new OpenAIAgent({
toolRetriever: await objectIndex.asRetriever({}),
llm,
verbose: true,
prefixMessages: [
{
content:
"You are an agent designed to answer queries about a set of given countries. Please always use the tools provided to answer a question. Do not rely on prior knowledge.",
role: "system",
},
],
});
const response = await topAgent.chat({
message: "Tell me the differences between Brazil and Canada economics?",
});
console.log({
capitalOfBrazil: response,
});
}
main();
+46
View File
@@ -0,0 +1,46 @@
import {
OpenAIAgent,
QueryEngineTool,
SimpleDirectoryReader,
VectorStoreIndex,
} from "llamaindex";
async function main() {
// Load the documents
const documents = await new SimpleDirectoryReader().loadData({
directoryPath: "node_modules/llamaindex/examples/",
});
// Create a vector index from the documents
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
// Create a query engine from the vector index
const abramovQueryEngine = vectorIndex.asQueryEngine();
// Create a QueryEngineTool with the query engine
const queryEngineTool = new QueryEngineTool({
queryEngine: abramovQueryEngine,
metadata: {
name: "abramov_query_engine",
description: "A query engine for the Abramov documents",
},
});
// Create an OpenAIAgent with the function tools
const agent = new OpenAIAgent({
tools: [queryEngineTool],
verbose: true,
});
// Chat with the agent
const response = await agent.chat({
message: "What was his salary?",
});
// Print the response
console.log(String(response));
}
main().then(() => {
console.log("Done");
});
+76
View File
@@ -0,0 +1,76 @@
import { FunctionTool, ReActAgent } from "llamaindex";
// Define a function to sum two numbers
function sumNumbers({ a, b }: { a: number; b: number }): number {
return a + b;
}
// Define a function to divide two numbers
function divideNumbers({ a, b }: { a: number; b: number }): number {
return a / b;
}
// Define the parameters of the sum function as a JSON schema
const sumJSON = {
type: "object",
properties: {
a: {
type: "number",
description: "The first number",
},
b: {
type: "number",
description: "The second number",
},
},
required: ["a", "b"],
};
const divideJSON = {
type: "object",
properties: {
a: {
type: "number",
description: "The dividend",
},
b: {
type: "number",
description: "The divisor",
},
},
required: ["a", "b"],
};
async function main() {
// Create a function tool from the sum function
const functionTool = new FunctionTool(sumNumbers, {
name: "sumNumbers",
description: "Use this function to sum two numbers",
parameters: sumJSON,
});
// Create a function tool from the divide function
const functionTool2 = new FunctionTool(divideNumbers, {
name: "divideNumbers",
description: "Use this function to divide two numbers",
parameters: divideJSON,
});
// Create an OpenAIAgent with the function tools
const agent = new ReActAgent({
tools: [functionTool, functionTool2],
verbose: true,
});
// Chat with the agent
const response = await agent.chat({
message: "Divide 16 by 2 then add 20",
});
// Print the response
console.log(String(response));
}
main().then(() => {
console.log("Done");
});
+3 -1
View File
@@ -1,7 +1,9 @@
import { Anthropic } from "llamaindex";
(async () => {
const anthropic = new Anthropic();
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
});
const result = await anthropic.chat({
messages: [
{ content: "You want to talk in rhymes.", role: "system" },
+33
View File
@@ -0,0 +1,33 @@
# LlamaCloud Integration
## Getting started
To start the examples call them from the `examples` folder:
And make sure, you're setting your `LLAMA_CLOUD_API_KEY` in your environment variable:
```shell
export LLAMA_CLOUD_API_KEY=your-api-key
```
For using another environment, also set the `LLAMA_CLOUD_BASE_URL` environment variable:
```shell
export LLAMA_CLOUD_BASE_URL="https://api.staging.llamaindex.ai"
```
## Chat Engine
This example is using the managed index named `test` from the project `default` to create a chat engine.
```shell
pnpx ts-node cloud/chat.ts
```
## Query Engine
This example shows how to use the managed index with a query engine.
```shell
pnpx ts-node cloud/query.ts
```
+29
View File
@@ -0,0 +1,29 @@
import { stdin as input, stdout as output } from "node:process";
import readline from "node:readline/promises";
import { ContextChatEngine, LlamaCloudIndex } from "llamaindex";
async function main() {
const index = new LlamaCloudIndex({
name: "test",
projectName: "default",
baseUrl: process.env.LLAMA_CLOUD_BASE_URL,
apiKey: process.env.LLAMA_CLOUD_API_KEY,
});
const retriever = index.asRetriever({
similarityTopK: 5,
});
const chatEngine = new ContextChatEngine({ retriever });
const rl = readline.createInterface({ input, output });
while (true) {
const query = await rl.question("User: ");
const stream = await chatEngine.chat({ message: query, stream: true });
console.log();
for await (const chunk of stream) {
process.stdout.write(chunk.response);
}
}
}
main().catch(console.error);
+31
View File
@@ -0,0 +1,31 @@
import { stdin as input, stdout as output } from "node:process";
import readline from "node:readline/promises";
import { LlamaCloudIndex } from "llamaindex";
async function main() {
const index = new LlamaCloudIndex({
name: "test",
projectName: "default",
baseUrl: process.env.LLAMA_CLOUD_BASE_URL,
apiKey: process.env.LLAMA_CLOUD_API_KEY,
});
const queryEngine = index.asQueryEngine({
denseSimilarityTopK: 5,
});
const rl = readline.createInterface({ input, output });
while (true) {
const query = await rl.question("Query: ");
const stream = await queryEngine.query({
query,
stream: true,
});
console.log();
for await (const chunk of stream) {
process.stdout.write(chunk.response);
}
}
}
main().catch(console.error);
Binary file not shown.
+24
View File
@@ -0,0 +1,24 @@
import { Document, MarkdownNodeParser } from "llamaindex";
async function main() {
const markdownParser = new MarkdownNodeParser();
const splits = markdownParser.getNodesFromDocuments([
new Document({
text: `# Main Header
Main content
# Header 2
Header 2 content
## Sub-header
Sub-header content
`,
}),
]);
console.log(splits);
}
main();
+1 -1
View File
@@ -1,4 +1,4 @@
import { Ollama } from "llamaindex";
import { Ollama } from "llamaindex/llm/ollama";
(async () => {
const llm = new Ollama({ model: "llama2", temperature: 0.75 });
+51
View File
@@ -0,0 +1,51 @@
import {
Document,
ResponseSynthesizer,
TreeSummarize,
TreeSummarizePrompt,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
const treeSummarizePrompt: TreeSummarizePrompt = ({ context, query }) => {
return `Context information from multiple sources is below.
---------------------
${context}
---------------------
Given the information from multiple sources and not prior knowledge.
Answer the query in the style of a Shakespeare play"
Query: ${query}
Answer:`;
};
async function main() {
const documents = new Document({
text: "The quick brown fox jumps over the lazy dog",
});
const index = await VectorStoreIndex.fromDocuments([documents]);
const query = "The quick brown fox jumps over the lazy dog";
const ctx = serviceContextFromDefaults({});
const responseSynthesizer = new ResponseSynthesizer({
responseBuilder: new TreeSummarize(ctx),
});
const queryEngine = index.asQueryEngine({
responseSynthesizer,
});
console.log({
promptsToUse: queryEngine.getPrompts(),
});
queryEngine.updatePrompts({
"responseSynthesizer:summaryTemplate": treeSummarizePrompt,
});
await queryEngine.query({ query });
}
main();
+3 -59
View File
@@ -1,61 +1,5 @@
## Reader Examples
## LlamaIndex Reader Examples
These examples show how to use a specific reader class by loading a document and running a test query.
1. Make sure you are in `examples` directory
```bash
cd ./examples
```
2. Prepare `OPENAI_API_KEY` environment variable:
```bash
export OPENAI_API_KEY=your_openai_api_key
```
3. Run the following command to load documents and test query:
- MarkdownReader Example
```bash
npx ts-node readers/load-md.ts
```
- DocxReader Example
```bash
npx ts-node readers/load-docx.ts
```
- PdfReader Example
```bash
npx ts-node readers/load-pdf.ts
```
- HtmlReader Example
```bash
npx ts-node readers/load-html.ts
```
- CsvReader Example
```bash
npx ts-node readers/load-csv.ts
```
- NotionReader Example
```bash
export NOTION_TOKEN=your_notion_token
npx ts-node readers/load-notion.ts
```
- AssemblyAI Example
```bash
export ASSEMBLYAI_API_KEY=your_assemblyai_api_key
npx ts-node readers/load-assemblyai.ts
```shell
npm run start
```
+22
View File
@@ -0,0 +1,22 @@
{
"name": "llamaindex-loader-example",
"private": true,
"type": "module",
"scripts": {
"start": "node --loader ts-node/esm ./src/simple-directory-reader.ts",
"start:csv": "node --loader ts-node/esm ./src/csv.ts",
"start:docx": "node --loader ts-node/esm ./src/docx.ts",
"start:html": "node --loader ts-node/esm ./src/html.ts",
"start:markdown": "node --loader ts-node/esm ./src/markdown.ts",
"start:pdf": "node --loader ts-node/esm ./src/pdf.ts",
"start:llamaparse": "node --loader ts-node/esm ./src/llamaparse.ts"
},
"dependencies": {
"llamaindex": "latest"
},
"devDependencies": {
"@types/node": "^20.11.14",
"ts-node": "^10.9.2",
"typescript": "^5.3.3"
}
}
@@ -2,7 +2,7 @@ import { program } from "commander";
import { TranscribeParams, VectorStoreIndex } from "llamaindex";
import { AudioTranscriptReader } from "llamaindex/readers/AssemblyAIReader";
import { stdin as input, stdout as output } from "node:process";
import readline from "node:readline/promises";
import { createInterface } from "node:readline/promises";
program
.option("-a, --audio [string]", "URL or path of the audio file to transcribe")
@@ -35,7 +35,7 @@ program
// Create query engine
const queryEngine = index.asQueryEngine();
const rl = readline.createInterface({ input, output });
const rl = createInterface({ input, output });
while (true) {
const query = await rl.question("Ask a question: ");
@@ -10,7 +10,7 @@ import { PapaCSVReader } from "llamaindex/readers/CSVReader";
async function main() {
// Load CSV
const reader = new PapaCSVReader();
const path = "data/titanic_train.csv";
const path = "../data/titanic_train.csv";
const documents = await reader.loadData(path);
const serviceContext = serviceContextFromDefaults({
@@ -0,0 +1,26 @@
import type { BaseReader, Document, Metadata } from "llamaindex";
import {
FILE_EXT_TO_READER,
SimpleDirectoryReader,
TextFileReader,
} from "llamaindex/readers/SimpleDirectoryReader";
class ZipReader implements BaseReader {
loadData(...args: any[]): Promise<Document<Metadata>[]> {
throw new Error("Implement me");
}
}
const reader = new SimpleDirectoryReader();
const documents = await reader.loadData({
directoryPath: "../data",
defaultReader: new TextFileReader(),
fileExtToReader: {
...FILE_EXT_TO_READER,
zip: new ZipReader(),
},
});
documents.forEach((doc) => {
console.log(`document (${doc.id_}):`, doc.getText());
});
@@ -1,7 +1,7 @@
import { VectorStoreIndex } from "llamaindex";
import { DocxReader } from "llamaindex/readers/DocxReader";
const FILE_PATH = "./data/stars.docx";
const FILE_PATH = "../data/stars.docx";
const SAMPLE_QUERY = "Information about Zodiac";
async function main() {
@@ -4,7 +4,7 @@ import { HTMLReader } from "llamaindex/readers/HTMLReader";
async function main() {
// Load page
const reader = new HTMLReader();
const documents = await reader.loadData("data/18-1_Changelog.html");
const documents = await reader.loadData("../data/llamaindex.html");
// Split text and create embeddings. Store them in a VectorStoreIndex
const index = await VectorStoreIndex.fromDocuments(documents);
@@ -12,7 +12,7 @@ async function main() {
// Query the index
const queryEngine = index.asQueryEngine();
const response = await queryEngine.query({
query: "What were the notable changes in 18.1?",
query: "What can I do with LlamaIndex?",
});
// Output response
+21
View File
@@ -0,0 +1,21 @@
import { LlamaParseReader, VectorStoreIndex } from "llamaindex";
async function main() {
// Load PDF using LlamaParse
const reader = new LlamaParseReader({ resultType: "markdown" });
const documents = await reader.loadData("../data/TOS.pdf");
// Split text and create embeddings. Store them in a VectorStoreIndex
const index = await VectorStoreIndex.fromDocuments(documents);
// Query the index
const queryEngine = index.asQueryEngine();
const response = await queryEngine.query({
query: "What is the license grant in the TOS?",
});
// Output response
console.log(response.toString());
}
main().catch(console.error);
@@ -1,7 +1,7 @@
import { VectorStoreIndex } from "llamaindex";
import { MarkdownReader } from "llamaindex/readers/MarkdownReader";
const FILE_PATH = "./data/planets.md";
const FILE_PATH = "../data/planets.md";
const SAMPLE_QUERY = "List all planets";
async function main() {
@@ -3,7 +3,7 @@ import { program } from "commander";
import { VectorStoreIndex } from "llamaindex";
import { NotionReader } from "llamaindex/readers/NotionReader";
import { stdin as input, stdout as output } from "node:process";
import readline from "node:readline/promises";
import { createInterface } from "node:readline/promises";
program
.argument("[page]", "Notion page id (must be provided)")
@@ -70,7 +70,7 @@ program
// Create query engine
const queryEngine = index.asQueryEngine();
const rl = readline.createInterface({ input, output });
const rl = createInterface({ input, output });
while (true) {
const query = await rl.question("Query: ");
@@ -1,13 +1,10 @@
import { VectorStoreIndex } from "llamaindex";
import { PDFReader } from "llamaindex/readers/PDFReader";
import { resolve } from "node:path";
async function main() {
// Load PDF
const reader = new PDFReader();
const documents = await reader.loadData(
resolve(__dirname, "../data/brk-2022.pdf"),
);
const documents = await reader.loadData("../data/brk-2022.pdf");
// Split text and create embeddings. Store them in a VectorStoreIndex
const index = await VectorStoreIndex.fromDocuments(documents);
+36
View File
@@ -0,0 +1,36 @@
import { FireworksEmbedding, FireworksLLM, VectorStoreIndex } from "llamaindex";
import { PDFReader } from "llamaindex/readers/PDFReader";
import { serviceContextFromDefaults } from "llamaindex";
const embedModel = new FireworksEmbedding({
model: "nomic-ai/nomic-embed-text-v1.5",
});
const llm = new FireworksLLM({
model: "accounts/fireworks/models/mixtral-8x7b-instruct",
});
const serviceContext = serviceContextFromDefaults({ llm, embedModel });
async function main() {
// Load PDF
const reader = new PDFReader();
const documents = await reader.loadData("../data/brk-2022.pdf");
// Split text and create embeddings. Store them in a VectorStoreIndex
const index = await VectorStoreIndex.fromDocuments(documents, {
serviceContext,
});
// Query the index
const queryEngine = index.asQueryEngine();
const response = await queryEngine.query({
query: "What mistakes did Warren E. Buffett make?",
});
// Output response
console.log(response.toString());
}
main().catch(console.error);
+36
View File
@@ -0,0 +1,36 @@
import { OpenAI, OpenAIEmbedding, VectorStoreIndex } from "llamaindex";
import { PDFReader } from "llamaindex/readers/PDFReader";
import { serviceContextFromDefaults } from "llamaindex";
const embedModel = new OpenAIEmbedding({
model: "nomic-ai/nomic-embed-text-v1.5",
});
const llm = new OpenAI({
model: "accounts/fireworks/models/mixtral-8x7b-instruct",
});
const serviceContext = serviceContextFromDefaults({ llm, embedModel });
async function main() {
// Load PDF
const reader = new PDFReader();
const documents = await reader.loadData("../data/brk-2022.pdf");
// Split text and create embeddings. Store them in a VectorStoreIndex
const index = await VectorStoreIndex.fromDocuments(documents, {
serviceContext,
});
// Query the index
const queryEngine = index.asQueryEngine();
const response = await queryEngine.query({
query: "What mistakes did Warren E. Buffett make?",
});
// Output response
console.log(response.toString());
}
main().catch(console.error);
@@ -0,0 +1,10 @@
import { SimpleDirectoryReader } from "llamaindex/readers/SimpleDirectoryReader";
// or
// import { SimpleDirectoryReader } from 'llamaindex'
const reader = new SimpleDirectoryReader();
const documents = await reader.loadData("../data");
documents.forEach((doc) => {
console.log(`document (${doc.id_}):`, doc.getText());
});
View File
+11
View File
@@ -0,0 +1,11 @@
{
"compilerOptions": {
"target": "es2017",
"module": "node16",
"moduleResolution": "node16",
"outDir": "./dist",
"types": ["node"],
"skipLibCheck": true
},
"include": ["./src/**/*.ts"]
}
+55
View File
@@ -0,0 +1,55 @@
import {
CohereRerank,
Document,
OpenAI,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
import essay from "../essay";
async function main() {
const document = new Document({ text: essay, id_: "essay" });
const serviceContext = serviceContextFromDefaults({
llm: new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 }),
});
const index = await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
const retriever = index.asRetriever();
retriever.similarityTopK = 5;
const nodePostprocessor = new CohereRerank({
apiKey: "<COHERE_API_KEY>",
topN: 5,
});
const queryEngine = index.asQueryEngine({
retriever,
nodePostprocessors: [nodePostprocessor],
});
const baseQueryEngine = index.asQueryEngine({
retriever,
});
const response = await queryEngine.query({
query: "What did the author do growing up?",
});
// cohere response
console.log(response.response);
const baseResponse = await baseQueryEngine.query({
query: "What did the author do growing up?",
});
// response without cohere
console.log(baseResponse.response);
}
main().catch(console.error);
+1 -1
View File
@@ -1,6 +1,6 @@
{
"compilerOptions": {
"target": "es2016",
"target": "es2017",
"module": "esnext",
"moduleResolution": "bundler",
"esModuleInterop": true,
+1
View File
@@ -30,6 +30,7 @@ async function main() {
// Query the index
const queryEngine = index.asQueryEngine();
const response = await queryEngine.query({
query: "What did the author do in college?",
});
+1 -5
View File
@@ -18,17 +18,13 @@
},
"devDependencies": {
"@changesets/cli": "^2.27.1",
"@turbo/gen": "^1.12.2",
"@types/jest": "^29.5.12",
"eslint": "^8.56.0",
"eslint-config-custom": "workspace:*",
"husky": "^9.0.10",
"jest": "^29.7.0",
"lint-staged": "^15.2.2",
"prettier": "^3.2.5",
"prettier-plugin-organize-imports": "^3.2.4",
"ts-jest": "^29.1.2",
"turbo": "^1.12.2",
"turbo": "^1.12.3",
"typescript": "^5.3.3"
},
"packageManager": "pnpm@8.15.1",
+11
View File
@@ -0,0 +1,11 @@
{
"jsc": {
"parser": {
"syntax": "typescript"
},
"target": "esnext"
},
"module": {
"type": "commonjs"
}
}
+8
View File
@@ -0,0 +1,8 @@
{
"jsc": {
"parser": {
"syntax": "typescript"
},
"target": "esnext"
}
}
+50
View File
@@ -1,5 +1,55 @@
# llamaindex
## 0.1.16
### Patch Changes
- e8e21a0: build: set files in package.json
- Updated dependencies [e8e21a0]
- @llamaindex/env@0.0.3
## 0.1.15
### Patch Changes
- 3a6e287: build: improve tree-shake & reduce unused package import
## 0.1.14
### Patch Changes
- 7416a87: build: cjs file not found
- Updated dependencies [7416a87]
- @llamaindex/env@0.0.2
## 0.1.13
### Patch Changes
- b8be4c0: build: use ESM as default
- 65d8346: feat: abstract `@llamaindex/env` package
## 0.1.12
### Patch Changes
- a5e4e6d: Add using a managed index from LlamaCloud
- cfdd6db: fix: update pinecone vector store
- 59f9fb6: Add Fireworks to LlamaIndex
- 95add73: feat: multi-document agent
## 0.1.11
### Patch Changes
- 255ae7d: chore: update example (perfoms better with default model)
- cf3b757: feat: add filtering of metadata to PGVectorStore
- ee9f3f3: chore: refactor openai agent utils
- e78e9f4: feat(reranker): cohere reranker
- f205358: feat: markdown node parser
- dd05413: feat: use batching in vector store index
- 383933a: Add reader for LlamaParse
## 0.1.10
### Patch Changes
-6
View File
@@ -1,6 +0,0 @@
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
testPathIgnorePatterns: ["/lib/", "/node_modules/", "/dist/"],
};
+44 -148
View File
@@ -1,18 +1,22 @@
{
"name": "llamaindex",
"private": true,
"version": "0.1.10",
"version": "0.1.16",
"license": "MIT",
"type": "module",
"dependencies": {
"@anthropic-ai/sdk": "^0.13.0",
"@aws-crypto/sha256-js": "^5.2.0",
"@datastax/astra-db-ts": "^0.1.4",
"@llamaindex/cloud": "^0.0.1",
"@llamaindex/env": "workspace:*",
"@mistralai/mistralai": "^0.0.10",
"@notionhq/client": "^2.2.14",
"@pinecone-database/pinecone": "^1.1.3",
"@pinecone-database/pinecone": "^2.0.1",
"@qdrant/js-client-rest": "^1.7.0",
"@xenova/transformers": "^2.15.0",
"assemblyai": "^4.2.2",
"chromadb": "~1.7.3",
"cohere-ai": "^7.7.5",
"file-type": "^18.7.0",
"js-tiktoken": "^1.0.10",
"lodash": "^4.17.21",
@@ -33,159 +37,52 @@
"wink-nlp": "^1.14.3"
},
"devDependencies": {
"@aws-crypto/sha256-js": "^5.2.0",
"@types/edit-json-file": "^1.7.3",
"@types/jest": "^29.5.12",
"@swc/cli": "^0.3.9",
"@swc/core": "^1.4.2",
"@types/lodash": "^4.14.202",
"@types/node": "^18.19.14",
"@types/papaparse": "^5.3.14",
"@types/pg": "^8.11.0",
"bunchee": "^4.4.6",
"edit-json-file": "^1.8.0",
"concurrently": "^8.2.2",
"glob": "^10.3.10",
"madge": "^6.1.0",
"typescript": "^5.3.3"
},
"engines": {
"node": ">=18.0.0"
},
"types": "./dist/index.d.ts",
"main": "./dist/index.js",
"types": "./dist/type/index.d.ts",
"main": "./dist/cjs/index.js",
"exports": {
".": {
"types": "./dist/index.d.mts",
"import": "./dist/index.mjs",
"edge-light": "./dist/index.edge-light.mjs",
"require": "./dist/index.js"
"import": {
"types": "./dist/type/index.d.ts",
"default": "./dist/index.js"
},
"edge-light": {
"types": "./dist/type/index.d.ts",
"default": "./dist/index.edge-light.js"
},
"require": {
"types": "./dist/type/index.d.ts",
"default": "./dist/cjs/index.js"
}
},
"./env": {
"types": "./dist/env.d.mts",
"import": "./dist/env.mjs",
"edge-light": "./dist/env.edge-light.mjs",
"require": "./dist/env.js"
},
"./ChatEngine": {
"types": "./dist/ChatEngine.d.mts",
"import": "./dist/ChatEngine.mjs",
"require": "./dist/ChatEngine.js"
},
"./ChatHistory": {
"types": "./dist/ChatHistory.d.mts",
"import": "./dist/ChatHistory.mjs",
"require": "./dist/ChatHistory.js"
},
"./constants": {
"types": "./dist/constants.d.mts",
"import": "./dist/constants.mjs",
"require": "./dist/constants.js"
},
"./GlobalsHelper": {
"types": "./dist/GlobalsHelper.d.mts",
"import": "./dist/GlobalsHelper.mjs",
"require": "./dist/GlobalsHelper.js"
},
"./Node": {
"types": "./dist/Node.d.mts",
"import": "./dist/Node.mjs",
"require": "./dist/Node.js"
},
"./OutputParser": {
"types": "./dist/OutputParser.d.mts",
"import": "./dist/OutputParser.mjs",
"require": "./dist/OutputParser.js"
},
"./Prompt": {
"types": "./dist/Prompt.d.mts",
"import": "./dist/Prompt.mjs",
"require": "./dist/Prompt.js"
},
"./PromptHelper": {
"types": "./dist/PromptHelper.d.mts",
"import": "./dist/PromptHelper.mjs",
"require": "./dist/PromptHelper.js"
},
"./QueryEngine": {
"types": "./dist/QueryEngine.d.mts",
"import": "./dist/QueryEngine.mjs",
"require": "./dist/QueryEngine.js"
},
"./QuestionGenerator": {
"types": "./dist/QuestionGenerator.d.mts",
"import": "./dist/QuestionGenerator.mjs",
"require": "./dist/QuestionGenerator.js"
},
"./Response": {
"types": "./dist/Response.d.mts",
"import": "./dist/Response.mjs",
"require": "./dist/Response.js"
},
"./ServiceContext": {
"types": "./dist/ServiceContext.d.mts",
"import": "./dist/ServiceContext.mjs",
"require": "./dist/ServiceContext.js"
},
"./TextSplitter": {
"types": "./dist/TextSplitter.d.mts",
"import": "./dist/TextSplitter.mjs",
"require": "./dist/TextSplitter.js"
},
"./tools": {
"types": "./dist/tools.d.mts",
"import": "./dist/tools.mjs",
"require": "./dist/tools.js"
},
"./readers/AssemblyAIReader": {
"types": "./dist/readers/AssemblyAIReader.d.mts",
"import": "./dist/readers/AssemblyAIReader.mjs",
"require": "./dist/readers/AssemblyAIReader.js"
},
"./readers/CSVReader": {
"types": "./dist/readers/CSVReader.d.mts",
"import": "./dist/readers/CSVReader.mjs",
"require": "./dist/readers/CSVReader.js"
},
"./readers/DocxReader": {
"types": "./dist/readers/DocxReader.d.mts",
"import": "./dist/readers/DocxReader.mjs",
"require": "./dist/readers/DocxReader.js"
},
"./readers/HTMLReader": {
"types": "./dist/readers/HTMLReader.d.mts",
"import": "./dist/readers/HTMLReader.mjs",
"require": "./dist/readers/HTMLReader.js"
},
"./readers/ImageReader": {
"types": "./dist/readers/ImageReader.d.mts",
"import": "./dist/readers/ImageReader.mjs",
"require": "./dist/readers/ImageReader.js"
},
"./readers/MarkdownReader": {
"types": "./dist/readers/MarkdownReader.d.mts",
"import": "./dist/readers/MarkdownReader.mjs",
"require": "./dist/readers/MarkdownReader.js"
},
"./readers/NotionReader": {
"types": "./dist/readers/NotionReader.d.mts",
"import": "./dist/readers/NotionReader.mjs",
"require": "./dist/readers/NotionReader.js"
},
"./readers/PDFReader": {
"types": "./dist/readers/PDFReader.d.mts",
"import": "./dist/readers/PDFReader.mjs",
"require": "./dist/readers/PDFReader.js"
},
"./readers/SimpleDirectoryReader": {
"types": "./dist/readers/SimpleDirectoryReader.d.mts",
"import": "./dist/readers/SimpleDirectoryReader.mjs",
"require": "./dist/readers/SimpleDirectoryReader.js"
},
"./readers/SimpleMongoReader": {
"types": "./dist/readers/SimpleMongoReader.d.mts",
"import": "./dist/readers/SimpleMongoReader.mjs",
"require": "./dist/readers/SimpleMongoReader.js"
"./*": {
"import": {
"types": "./dist/type/*.d.ts",
"default": "./dist/*.js"
},
"require": {
"types": "./dist/type/*.d.ts",
"default": "./dist/cjs/*.js"
}
}
},
"files": [
"**"
"dist",
"CHANGELOG.md",
"examples"
],
"repository": {
"type": "git",
@@ -194,13 +91,12 @@
},
"scripts": {
"lint": "eslint .",
"test": "jest",
"build": "rm -rf ./dist && NODE_OPTIONS=\"--max-old-space-size=8192\" bunchee",
"postbuild": "pnpm run copy && pnpm run modify-package-json",
"copy": "cp -r package.json CHANGELOG.md ../../README.md ../../LICENSE examples src dist/",
"modify-package-json": "node ./scripts/modify-package-json.mjs",
"prepublish": "pnpm run modify-package-json && echo \"please cd ./dist and run pnpm publish\" && exit 1",
"dev": "NODE_OPTIONS=\"--max-old-space-size=8192\" bunchee -w",
"circular-check": "madge -c ./src/index.ts"
"build": "rm -rf ./dist && pnpm run build:esm && pnpm run build:cjs && pnpm run build:type",
"build:esm": "swc src -d dist --strip-leading-paths --config-file .swcrc",
"build:cjs": "swc src -d dist/cjs --strip-leading-paths --config-file .cjs.swcrc",
"build:type": "tsc -p tsconfig.json",
"postbuild": "node -e \"require('fs').writeFileSync('./dist/cjs/package.json', JSON.stringify({ type: 'commonjs' }))\"",
"circular-check": "madge -c ./src/index.ts",
"dev": "concurrently \"pnpm run build:esm --watch\" \"pnpm run build:cjs --watch\" \"pnpm run build:type --watch\""
}
}
@@ -1,25 +0,0 @@
#!/usr/bin/env node
/**
* This script is used to modify the package.json file in the dist folder
* so that it can be published to npm.
*/
import editJsonFile from "edit-json-file";
import fs from "node:fs/promises";
{
await fs.copyFile("./package.json", "./dist/package.json");
const file = editJsonFile("./dist/package.json");
file.unset("scripts");
file.unset("private");
await new Promise((resolve) => file.save(resolve));
}
{
const packageJson = await fs.readFile("./dist/package.json", "utf8");
const modifiedPackageJson = packageJson.replaceAll("./dist/", "./");
await fs.writeFile(
"./dist/package.json",
JSON.stringify(JSON.parse(modifiedPackageJson), null, 2),
"utf8",
);
}
+4 -7
View File
@@ -1,10 +1,7 @@
import { OpenAI } from "./llm/LLM";
import { ChatMessage, LLM, MessageType } from "./llm/types";
import {
defaultSummaryPrompt,
messagesToHistoryStr,
SummaryPrompt,
} from "./Prompt";
import { OpenAI } from "./llm/LLM.js";
import type { ChatMessage, LLM, MessageType } from "./llm/types.js";
import type { SummaryPrompt } from "./Prompt.js";
import { defaultSummaryPrompt, messagesToHistoryStr } from "./Prompt.js";
/**
* A ChatHistory is used to keep the state of back and forth chat messages
+8 -4
View File
@@ -1,7 +1,11 @@
import { encodingForModel } from "js-tiktoken";
import { Event, EventTag, EventType } from "./callbacks/CallbackManager";
import { randomUUID } from "./env";
import { randomUUID } from "@llamaindex/env";
import type {
Event,
EventTag,
EventType,
} from "./callbacks/CallbackManager.js";
export enum Tokenizers {
CL100K_BASE = "cl100k_base",
@@ -32,7 +36,7 @@ class GlobalsHelper {
};
}
tokenizer(encoding?: string) {
tokenizer(encoding?: Tokenizers) {
if (encoding && encoding !== Tokenizers.CL100K_BASE) {
throw new Error(`Tokenizer encoding ${encoding} not yet supported`);
}
@@ -43,7 +47,7 @@ class GlobalsHelper {
return this.defaultTokenizer!.encode.bind(this.defaultTokenizer);
}
tokenizerDecoder(encoding?: string) {
tokenizerDecoder(encoding?: Tokenizers) {
if (encoding && encoding !== Tokenizers.CL100K_BASE) {
throw new Error(`Tokenizer encoding ${encoding} not yet supported`);
}
+6 -5
View File
@@ -1,5 +1,5 @@
import { createSHA256, path, randomUUID } from "@llamaindex/env";
import _ from "lodash";
import { createSHA256, path, randomUUID } from "./env";
export enum NodeRelationship {
SOURCE = "SOURCE",
@@ -65,7 +65,8 @@ export abstract class BaseNode<T extends Metadata = Metadata> {
abstract getContent(metadataMode: MetadataMode): string;
abstract getMetadataStr(metadataMode: MetadataMode): string;
abstract setContent(value: any): void;
// todo: set value as a generic type
abstract setContent(value: unknown): void;
get sourceNode(): RelatedNodeInfo<T> | undefined {
const relationship = this.relationships[NodeRelationship.SOURCE];
@@ -353,10 +354,10 @@ export function splitNodesByType(nodes: BaseNode[]): {
imageNodes: ImageNode[];
textNodes: TextNode[];
} {
let imageNodes: ImageNode[] = [];
let textNodes: TextNode[] = [];
const imageNodes: ImageNode[] = [];
const textNodes: TextNode[] = [];
for (let node of nodes) {
for (const node of nodes) {
if (node instanceof ImageNode) {
imageNodes.push(node);
} else if (node instanceof TextNode) {
+4 -4
View File
@@ -1,5 +1,5 @@
import { SubQuestion } from "./engines/query/types";
import { BaseOutputParser, StructuredOutput } from "./types";
import type { SubQuestion } from "./engines/query/types.js";
import type { BaseOutputParser, StructuredOutput } from "./types.js";
/**
* Error class for output parsing. Due to the nature of LLMs, anytime we use LLM
@@ -44,8 +44,8 @@ export function parseJsonMarkdown(text: string) {
const left_square = text.indexOf("[");
const left_brace = text.indexOf("{");
var left: number;
var right: number;
let left: number;
let right: number;
if (left_square < left_brace && left_square != -1) {
left = left_square;
right = text.lastIndexOf("]");
+3 -3
View File
@@ -1,6 +1,6 @@
import { SubQuestion } from "./engines/query/types";
import { ChatMessage } from "./llm/types";
import { ToolMetadata } from "./types";
import type { SubQuestion } from "./engines/query/types.js";
import type { ChatMessage } from "./llm/types.js";
import type { ToolMetadata } from "./types.js";
/**
* A SimplePrompt is a function that takes a dictionary of inputs and returns a string.
+4 -4
View File
@@ -1,12 +1,12 @@
import { globalsHelper } from "./GlobalsHelper";
import { SimplePrompt } from "./Prompt";
import { SentenceSplitter } from "./TextSplitter";
import { globalsHelper } from "./GlobalsHelper.js";
import type { SimplePrompt } from "./Prompt.js";
import { SentenceSplitter } from "./TextSplitter.js";
import {
DEFAULT_CHUNK_OVERLAP_RATIO,
DEFAULT_CONTEXT_WINDOW,
DEFAULT_NUM_OUTPUTS,
DEFAULT_PADDING,
} from "./constants";
} from "./constants.js";
export function getEmptyPromptTxt(prompt: SimplePrompt) {
return prompt({});
+35 -11
View File
@@ -1,28 +1,52 @@
import { SubQuestionOutputParser } from "./OutputParser";
import {
SubQuestionPrompt,
buildToolsText,
defaultSubQuestionPrompt,
} from "./Prompt";
import { BaseQuestionGenerator, SubQuestion } from "./engines/query/types";
import { OpenAI } from "./llm/LLM";
import { LLM } from "./llm/types";
import { BaseOutputParser, StructuredOutput, ToolMetadata } from "./types";
import { SubQuestionOutputParser } from "./OutputParser.js";
import type { SubQuestionPrompt } from "./Prompt.js";
import { buildToolsText, defaultSubQuestionPrompt } from "./Prompt.js";
import type {
BaseQuestionGenerator,
SubQuestion,
} from "./engines/query/types.js";
import { OpenAI } from "./llm/LLM.js";
import type { LLM } from "./llm/types.js";
import { PromptMixin } from "./prompts/index.js";
import type {
BaseOutputParser,
StructuredOutput,
ToolMetadata,
} from "./types.js";
/**
* LLMQuestionGenerator uses the LLM to generate new questions for the LLM using tools and a user query.
*/
export class LLMQuestionGenerator implements BaseQuestionGenerator {
export class LLMQuestionGenerator
extends PromptMixin
implements BaseQuestionGenerator
{
llm: LLM;
prompt: SubQuestionPrompt;
outputParser: BaseOutputParser<StructuredOutput<SubQuestion[]>>;
constructor(init?: Partial<LLMQuestionGenerator>) {
super();
this.llm = init?.llm ?? new OpenAI();
this.prompt = init?.prompt ?? defaultSubQuestionPrompt;
this.outputParser = init?.outputParser ?? new SubQuestionOutputParser();
}
protected _getPrompts(): { [x: string]: SubQuestionPrompt } {
return {
subQuestion: this.prompt,
};
}
protected _updatePrompts(promptsDict: {
subQuestion: SubQuestionPrompt;
}): void {
if ("subQuestion" in promptsDict) {
this.prompt = promptsDict.subQuestion;
}
}
async generate(tools: ToolMetadata[], query: string): Promise<SubQuestion[]> {
const toolsStr = buildToolsText(tools);
const queryStr = query;
+1 -1
View File
@@ -1,4 +1,4 @@
import { BaseNode } from "./Node";
import type { BaseNode } from "./Node.js";
/**
* Response is the output of a LLM
+3 -3
View File
@@ -1,6 +1,6 @@
import { Event } from "./callbacks/CallbackManager";
import { NodeWithScore } from "./Node";
import { ServiceContext } from "./ServiceContext";
import type { Event } from "./callbacks/CallbackManager.js";
import type { NodeWithScore } from "./Node.js";
import type { ServiceContext } from "./ServiceContext.js";
/**
* Retrievers retrieve the nodes that most closely match our query in similarity.
+8 -5
View File
@@ -1,8 +1,11 @@
import { CallbackManager } from "./callbacks/CallbackManager";
import { BaseEmbedding, OpenAIEmbedding } from "./embeddings";
import { LLM, OpenAI } from "./llm";
import { NodeParser, SimpleNodeParser } from "./nodeParsers";
import { PromptHelper } from "./PromptHelper";
import { PromptHelper } from "./PromptHelper.js";
import { CallbackManager } from "./callbacks/CallbackManager.js";
import { OpenAIEmbedding } from "./embeddings/OpenAIEmbedding.js";
import type { BaseEmbedding } from "./embeddings/types.js";
import type { LLM } from "./llm/index.js";
import { OpenAI } from "./llm/index.js";
import { SimpleNodeParser } from "./nodeParsers/SimpleNodeParser.js";
import type { NodeParser } from "./nodeParsers/types.js";
/**
* The ServiceContext is a collection of components that are used in different parts of the application.
+13 -13
View File
@@ -1,7 +1,7 @@
import { EOL } from "./env";
import { EOL } from "@llamaindex/env";
// GitHub translated
import { globalsHelper } from "./GlobalsHelper";
import { DEFAULT_CHUNK_OVERLAP, DEFAULT_CHUNK_SIZE } from "./constants";
import { globalsHelper } from "./GlobalsHelper.js";
import { DEFAULT_CHUNK_OVERLAP, DEFAULT_CHUNK_SIZE } from "./constants.js";
class TextSplit {
textChunk: string;
@@ -130,7 +130,7 @@ export class SentenceSplitter {
getParagraphSplits(text: string, effectiveChunkSize?: number): string[] {
// get paragraph splits
let paragraphSplits: string[] = text.split(this.paragraphSeparator);
const paragraphSplits: string[] = text.split(this.paragraphSeparator);
let idx = 0;
if (effectiveChunkSize == undefined) {
return paragraphSplits;
@@ -155,9 +155,9 @@ export class SentenceSplitter {
}
getSentenceSplits(text: string, effectiveChunkSize?: number): string[] {
let paragraphSplits = this.getParagraphSplits(text, effectiveChunkSize);
const paragraphSplits = this.getParagraphSplits(text, effectiveChunkSize);
// Next we split the text using the chunk tokenizer fn/
let splits = [];
const splits = [];
for (const parText of paragraphSplits) {
const sentenceSplits = this.chunkingTokenizerFn(parText);
@@ -194,9 +194,9 @@ export class SentenceSplitter {
}));
}
let newSplits: SplitRep[] = [];
const newSplits: SplitRep[] = [];
for (const split of sentenceSplits) {
let splitTokens = this.tokenizer(split);
const splitTokens = this.tokenizer(split);
const splitLen = splitTokens.length;
if (splitLen <= effectiveChunkSize) {
newSplits.push({ text: split, numTokens: splitLen });
@@ -219,7 +219,7 @@ export class SentenceSplitter {
// go through sentence splits, combine to chunks that are within the chunk size
// docs represents final list of text chunks
let docs: TextSplit[] = [];
const docs: TextSplit[] = [];
// curChunkSentences represents the current list of sentence splits (that)
// will be merged into a chunk
let curChunkSentences: SplitRep[] = [];
@@ -287,18 +287,18 @@ export class SentenceSplitter {
return [];
}
let effectiveChunkSize = this.getEffectiveChunkSize(extraInfoStr);
let sentenceSplits = this.getSentenceSplits(text, effectiveChunkSize);
const effectiveChunkSize = this.getEffectiveChunkSize(extraInfoStr);
const sentenceSplits = this.getSentenceSplits(text, effectiveChunkSize);
// Check if any sentences exceed the chunk size. If they don't,
// force split by tokenizer
let newSentenceSplits = this.processSentenceSplits(
const newSentenceSplits = this.processSentenceSplits(
sentenceSplits,
effectiveChunkSize,
);
// combine sentence splits into chunks of text that can then be returned
let combinedTextSplits = this.combineTextSplits(
const combinedTextSplits = this.combineTextSplits(
newSentenceSplits,
effectiveChunkSize,
);
+5 -2
View File
@@ -1,2 +1,5 @@
export * from "./openai/base";
export * from "./openai/worker";
export * from "./openai/base.js";
export * from "./openai/worker.js";
export * from "./react/base.js";
export * from "./react/worker.js";
export * from "./types.js";
+32 -8
View File
@@ -1,12 +1,13 @@
import { CallbackManager } from "../../callbacks/CallbackManager";
import { ChatMessage, OpenAI } from "../../llm";
import { ObjectRetriever } from "../../objects/base";
import { BaseTool } from "../../types";
import { AgentRunner } from "../runner/base";
import { OpenAIAgentWorker } from "./worker";
import type { CallbackManager } from "../../callbacks/CallbackManager.js";
import type { ChatMessage } from "../../llm/index.js";
import { OpenAI } from "../../llm/index.js";
import type { ObjectRetriever } from "../../objects/base.js";
import type { BaseTool } from "../../types.js";
import { AgentRunner } from "../runner/base.js";
import { OpenAIAgentWorker } from "./worker.js";
type OpenAIAgentParams = {
tools: BaseTool[];
tools?: BaseTool[];
llm?: OpenAI;
memory?: any;
prefixMessages?: ChatMessage[];
@@ -14,7 +15,8 @@ type OpenAIAgentParams = {
maxFunctionCalls?: number;
defaultToolChoice?: string;
callbackManager?: CallbackManager;
toolRetriever?: ObjectRetriever<BaseTool>;
toolRetriever?: ObjectRetriever;
systemPrompt?: string;
};
/**
@@ -33,7 +35,29 @@ export class OpenAIAgent extends AgentRunner {
defaultToolChoice = "auto",
callbackManager,
toolRetriever,
systemPrompt,
}: OpenAIAgentParams) {
prefixMessages = prefixMessages || [];
llm = llm ?? new OpenAI({ model: "gpt-3.5-turbo-0613" });
if (systemPrompt) {
if (prefixMessages) {
throw new Error("Cannot provide both systemPrompt and prefixMessages");
}
prefixMessages = [
{
content: systemPrompt,
role: "system",
},
];
}
if (!llm?.metadata.isFunctionCallingModel) {
throw new Error("LLM model must be a function-calling model");
}
const stepEngine = new OpenAIAgentWorker({
tools,
callbackManager,
+1 -1
View File
@@ -1,4 +1,4 @@
import { ToolMetadata } from "../../types";
import type { ToolMetadata } from "../../types.js";
export type OpenAIFunction = {
type: "function";
+40 -35
View File
@@ -1,23 +1,27 @@
// Assuming that the necessary interfaces and classes (like BaseTool, OpenAI, ChatMessage, CallbackManager, etc.) are defined elsewhere
import { CallbackManager } from "../../callbacks/CallbackManager";
import { AgentChatResponse, ChatResponseMode } from "../../engines/chat";
import { randomUUID } from "../../env";
import { randomUUID } from "@llamaindex/env";
import type { CallbackManager } from "../../callbacks/CallbackManager.js";
import {
AgentChatResponse,
ChatResponseMode,
} from "../../engines/chat/types.js";
import type {
ChatMessage,
ChatResponse,
ChatResponseChunk,
OpenAI,
} from "../../llm";
import { ChatMemoryBuffer } from "../../memory/ChatMemoryBuffer";
import { ObjectRetriever } from "../../objects/base";
import { ToolOutput } from "../../tools/types";
import { callToolWithErrorHandling } from "../../tools/utils";
import { BaseTool } from "../../types";
import { AgentWorker, Task, TaskStep, TaskStepOutput } from "../types";
import { addUserStepToMemory, getFunctionByName } from "../utils";
import { OpenAIToolCall } from "./types/chat";
import { toOpenAiTool } from "./utils";
} from "../../llm/index.js";
import { OpenAI } from "../../llm/index.js";
import { ChatMemoryBuffer } from "../../memory/ChatMemoryBuffer.js";
import type { ObjectRetriever } from "../../objects/base.js";
import type { ToolOutput } from "../../tools/types.js";
import { callToolWithErrorHandling } from "../../tools/utils.js";
import type { BaseTool } from "../../types.js";
import type { AgentWorker, Task } from "../types.js";
import { TaskStep, TaskStepOutput } from "../types.js";
import { addUserStepToMemory, getFunctionByName } from "../utils.js";
import type { OpenAIToolCall } from "./types/chat.js";
import { toOpenAiTool } from "./utils.js";
const DEFAULT_MAX_FUNCTION_CALLS = 5;
@@ -69,13 +73,13 @@ async function callFunction(
}
type OpenAIAgentWorkerParams = {
tools: BaseTool[];
tools?: BaseTool[];
llm?: OpenAI;
prefixMessages?: ChatMessage[];
verbose?: boolean;
maxFunctionCalls?: number;
callbackManager?: CallbackManager | undefined;
toolRetriever?: ObjectRetriever<BaseTool>;
toolRetriever?: ObjectRetriever;
};
type CallFunctionOutput = {
@@ -88,20 +92,20 @@ type CallFunctionOutput = {
* This class is responsible for running the agent.
*/
export class OpenAIAgentWorker implements AgentWorker {
private _llm: OpenAI;
private _verbose: boolean;
private _maxFunctionCalls: number;
private llm: OpenAI;
private verbose: boolean;
private maxFunctionCalls: number;
public prefixMessages: ChatMessage[];
public callbackManager: CallbackManager | undefined;
private _getTools: (input: string) => BaseTool[];
private _getTools: (input: string) => Promise<BaseTool[]>;
/**
* Initialize.
*/
constructor({
tools,
tools = [],
llm,
prefixMessages,
verbose,
@@ -109,21 +113,21 @@ export class OpenAIAgentWorker implements AgentWorker {
callbackManager,
toolRetriever,
}: OpenAIAgentWorkerParams) {
this._llm = llm ?? new OpenAI({ model: "gpt-3.5-turbo-0613" });
this._verbose = verbose || false;
this._maxFunctionCalls = maxFunctionCalls;
this.llm = llm ?? new OpenAI({ model: "gpt-3.5-turbo-0613" });
this.verbose = verbose || false;
this.maxFunctionCalls = maxFunctionCalls;
this.prefixMessages = prefixMessages || [];
this.callbackManager = callbackManager || this._llm.callbackManager;
this.callbackManager = callbackManager || this.llm.callbackManager;
if (tools.length > 0 && toolRetriever) {
throw new Error("Cannot specify both tools and tool_retriever");
} else if (tools.length > 0) {
this._getTools = () => tools;
this._getTools = async () => tools;
} else if (toolRetriever) {
// @ts-ignore
this._getTools = (message: string) => toolRetriever.retrieve(message);
this._getTools = async (message: string) =>
toolRetriever.retrieve(message);
} else {
this._getTools = () => [];
this._getTools = async () => [];
}
}
@@ -191,6 +195,7 @@ export class OpenAIAgentWorker implements AgentWorker {
): AgentChatResponse | AsyncIterable<ChatResponseChunk> {
const aiMessage = chatResponse.message;
task.extraState.newMemory.put(aiMessage);
return new AgentChatResponse(aiMessage.content, task.extraState.sources);
}
@@ -207,7 +212,7 @@ export class OpenAIAgentWorker implements AgentWorker {
llmChatKwargs: any,
): Promise<AgentChatResponse> {
if (mode === ChatResponseMode.WAIT) {
const chatResponse = (await this._llm.chat({
const chatResponse = (await this.llm.chat({
stream: false,
...llmChatKwargs,
})) as unknown as ChatResponse;
@@ -236,7 +241,7 @@ export class OpenAIAgentWorker implements AgentWorker {
throw new Error("Invalid tool_call object");
}
const functionMessage = await callFunction(tools, toolCall, this._verbose);
const functionMessage = await callFunction(tools, toolCall, this.verbose);
const message = functionMessage[0];
const toolOutput = functionMessage[1];
@@ -282,7 +287,7 @@ export class OpenAIAgentWorker implements AgentWorker {
toolCalls: OpenAIToolCall[] | null,
nFunctionCalls: number,
): boolean {
if (nFunctionCalls > this._maxFunctionCalls) {
if (nFunctionCalls > this.maxFunctionCalls) {
return false;
}
@@ -298,7 +303,7 @@ export class OpenAIAgentWorker implements AgentWorker {
* @param input: input
* @returns: tools
*/
getTools(input: string): BaseTool[] {
async getTools(input: string): Promise<BaseTool[]> {
return this._getTools(input);
}
@@ -308,10 +313,10 @@ export class OpenAIAgentWorker implements AgentWorker {
mode: ChatResponseMode = ChatResponseMode.WAIT,
toolChoice: string | { [key: string]: any } = "auto",
): Promise<TaskStepOutput> {
const tools = this.getTools(task.input);
const tools = await this.getTools(task.input);
if (step.input) {
addUserStepToMemory(step, task.extraState.newMemory, this._verbose);
addUserStepToMemory(step, task.extraState.newMemory, this.verbose);
}
const openaiTools = tools.map((tool) =>
+54
View File
@@ -0,0 +1,54 @@
import type { CallbackManager } from "../../callbacks/CallbackManager.js";
import type { ChatMessage, LLM } from "../../llm/index.js";
import type { ObjectRetriever } from "../../objects/base.js";
import type { BaseTool } from "../../types.js";
import { AgentRunner } from "../runner/base.js";
import { ReActAgentWorker } from "./worker.js";
type ReActAgentParams = {
tools: BaseTool[];
llm?: LLM;
memory?: any;
prefixMessages?: ChatMessage[];
verbose?: boolean;
maxInteractions?: number;
defaultToolChoice?: string;
callbackManager?: CallbackManager;
toolRetriever?: ObjectRetriever;
};
/**
* An agent that uses OpenAI's API to generate text.
*
* @category OpenAI
*/
export class ReActAgent extends AgentRunner {
constructor({
tools,
llm,
memory,
prefixMessages,
verbose,
maxInteractions = 10,
defaultToolChoice = "auto",
callbackManager,
toolRetriever,
}: Partial<ReActAgentParams>) {
const stepEngine = new ReActAgentWorker({
tools: tools ?? [],
callbackManager,
llm,
maxInteractions,
toolRetriever,
verbose,
});
super({
agentWorker: stepEngine,
memory,
callbackManager,
defaultToolChoice,
chatHistory: prefixMessages,
});
}
}
@@ -0,0 +1,84 @@
import type { ChatMessage } from "../../llm/index.js";
import type { BaseTool } from "../../types.js";
import { getReactChatSystemHeader } from "./prompts.js";
import type { BaseReasoningStep } from "./types.js";
import { ObservationReasoningStep } from "./types.js";
function getReactToolDescriptions(tools: BaseTool[]): string[] {
const toolDescs: string[] = [];
for (const tool of tools) {
// @ts-ignore
const toolDesc = `> Tool Name: ${tool.metadata.name}\nTool Description: ${tool.metadata.description}\nTool Args: ${JSON.stringify(tool?.metadata?.parameters?.properties)}\n`;
toolDescs.push(toolDesc);
}
return toolDescs;
}
export interface BaseAgentChatFormatter {
format(
tools: BaseTool[],
chatHistory: ChatMessage[],
currentReasoning?: BaseReasoningStep[],
): ChatMessage[];
}
export class ReActChatFormatter implements BaseAgentChatFormatter {
systemHeader: string = "";
context: string = "'";
constructor(init?: Partial<ReActChatFormatter>) {
Object.assign(this, init);
}
format(
tools: BaseTool[],
chatHistory: ChatMessage[],
currentReasoning?: BaseReasoningStep[],
): ChatMessage[] {
currentReasoning = currentReasoning ?? [];
const formatArgs = {
toolDesc: getReactToolDescriptions(tools).join("\n"),
toolNames: tools.map((tool) => tool.metadata.name).join(", "),
context: "",
};
if (this.context) {
formatArgs["context"] = this.context;
}
const reasoningHistory = [];
for (const reasoningStep of currentReasoning) {
let message: ChatMessage | undefined;
if (reasoningStep instanceof ObservationReasoningStep) {
message = {
content: reasoningStep.getContent(),
role: "user",
};
} else {
message = {
content: reasoningStep.getContent(),
role: "system",
};
}
reasoningHistory.push(message);
}
const systemContent = getReactChatSystemHeader({
toolDesc: formatArgs.toolDesc,
toolNames: formatArgs.toolNames,
});
return [
{
content: systemContent,
role: "system",
},
...chatHistory,
...reasoningHistory,
];
}
}
@@ -0,0 +1,105 @@
import type { BaseReasoningStep } from "./types.js";
import {
ActionReasoningStep,
BaseOutputParser,
ResponseReasoningStep,
} from "./types.js";
function extractJsonStr(text: string): string {
const pattern = /\{.*\}/s;
const match = text.match(pattern);
if (!match) {
throw new Error(`Could not extract json string from output: ${text}`);
}
return match[0];
}
function extractToolUse(inputText: string): [string, string, string] {
const pattern =
/\s*Thought: (.*?)\nAction: ([a-zA-Z0-9_]+).*?\nAction Input: .*?(\{.*?\})/s;
const match = inputText.match(pattern);
if (!match) {
throw new Error(`Could not extract tool use from input text: ${inputText}`);
}
const thought = match[1].trim();
const action = match[2].trim();
const actionInput = match[3].trim();
return [thought, action, actionInput];
}
function actionInputParser(jsonStr: string): object {
const processedString = jsonStr.replace(/(?<!\w)\'|\'(?!\w)/g, '"');
const pattern = /"(\w+)":\s*"([^"]*)"/g;
const matches = [...processedString.matchAll(pattern)];
return Object.fromEntries(matches);
}
function extractFinalResponse(inputText: string): [string, string] {
const pattern = /\s*Thought:(.*?)Answer:(.*?)(?:$)/s;
const match = inputText.match(pattern);
if (!match) {
throw new Error(
`Could not extract final answer from input text: ${inputText}`,
);
}
const thought = match[1].trim();
const answer = match[2].trim();
return [thought, answer];
}
export class ReActOutputParser extends BaseOutputParser {
parse(output: string, isStreaming: boolean = false): BaseReasoningStep {
if (!output.includes("Thought:")) {
// NOTE: handle the case where the agent directly outputs the answer
// instead of following the thought-answer format
return new ResponseReasoningStep({
thought: "(Implicit) I can answer without any more tools!",
response: output,
isStreaming,
});
}
if (output.includes("Answer:")) {
const [thought, answer] = extractFinalResponse(output);
return new ResponseReasoningStep({
thought: thought,
response: answer,
isStreaming,
});
}
if (output.includes("Action:")) {
const [thought, action, action_input] = extractToolUse(output);
const json_str = extractJsonStr(action_input);
// First we try json, if this fails we use ast
let actionInputDict;
try {
actionInputDict = JSON.parse(json_str);
} catch (e) {
actionInputDict = actionInputParser(json_str);
}
return new ActionReasoningStep({
thought: thought,
action: action,
actionInput: actionInputDict,
});
}
throw new Error(`Could not parse output: ${output}`);
}
format(output: string): string {
throw new Error("Not implemented");
}
}
+56
View File
@@ -0,0 +1,56 @@
type ReactChatSystemHeaderParams = {
toolDesc: string;
toolNames: string;
};
export const getReactChatSystemHeader = ({
toolDesc,
toolNames,
}: ReactChatSystemHeaderParams) =>
`You are designed to help with a variety of tasks, from answering questions to providing summaries to other types of analyses.
## Tools
You have access to a wide variety of tools. You are responsible for using
the tools in any sequence you deem appropriate to complete the task at hand.
This may require breaking the task into subtasks and using different tools
to complete each subtask.
You have access to the following tools:
${toolDesc}
## Output Format
To answer the question, please use the following format.
"""
Thought: I need to use a tool to help me answer the question.
Action: tool name (one of ${toolNames}) if using a tool.
Action Input: the input to the tool, in a JSON format representing the kwargs (e.g. {{"input": "hello world", "num_beams": 5}})
"""
Please ALWAYS start with a Thought.
Please use a valid JSON format for the Action Input. Do NOT do this {{'input': 'hello world', 'num_beams': 5}}.
If this format is used, the user will respond in the following format:
""""
Observation: tool response
""""
You should keep repeating the above format until you have enough information
to answer the question without using any more tools. At that point, you MUST respond
in the one of the following two formats:
""""
Thought: I can answer without using any more tools.
Answer: [your answer here]
""""
""""
Thought: I cannot answer the question with the provided tools.
Answer: Sorry, I cannot answer your query.
""""
## Current Conversation
Below is the current conversation consisting of interleaving human and assistant messages.
`;
+88
View File
@@ -0,0 +1,88 @@
import type { ChatMessage } from "../../llm/index.js";
export interface BaseReasoningStep {
getContent(): string;
isDone(): boolean;
}
export class ObservationReasoningStep implements BaseReasoningStep {
observation: string;
constructor(init?: Partial<ObservationReasoningStep>) {
this.observation = init?.observation ?? "";
}
getContent(): string {
return `Observation: ${this.observation}`;
}
isDone(): boolean {
return false;
}
}
export class ActionReasoningStep implements BaseReasoningStep {
thought: string;
action: string;
actionInput: Record<string, any>;
constructor(init?: Partial<ActionReasoningStep>) {
this.thought = init?.thought ?? "";
this.action = init?.action ?? "";
this.actionInput = init?.actionInput ?? {};
}
getContent(): string {
return `Thought: ${this.thought}\nAction: ${this.action}\nAction Input: ${JSON.stringify(this.actionInput)}`;
}
isDone(): boolean {
return false;
}
}
export abstract class BaseOutputParser {
abstract parse(output: string, isStreaming?: boolean): BaseReasoningStep;
format(output: string) {
return output;
}
formatMessages(messages: ChatMessage[]): ChatMessage[] {
if (messages) {
if (messages[0].role === "system") {
messages[0].content = this.format(messages[0].content || "");
} else {
messages[messages.length - 1].content = this.format(
messages[messages.length - 1].content || "",
);
}
}
return messages;
}
}
export class ResponseReasoningStep implements BaseReasoningStep {
thought: string;
response: string;
isStreaming: boolean = false;
constructor(init?: Partial<ResponseReasoningStep>) {
this.thought = init?.thought ?? "";
this.response = init?.response ?? "";
this.isStreaming = init?.isStreaming ?? false;
}
getContent(): string {
if (this.isStreaming) {
return `Thought: ${this.thought}\nAnswer (Starts With): ${this.response} ...`;
} else {
return `Thought: ${this.thought}\nAnswer: ${this.response}`;
}
}
isDone(): boolean {
return true;
}
}
+397
View File
@@ -0,0 +1,397 @@
import { randomUUID } from "crypto";
import { CallbackManager } from "../../callbacks/CallbackManager.js";
import { AgentChatResponse } from "../../engines/chat/index.js";
import type { ChatResponse, LLM } from "../../llm/index.js";
import { OpenAI } from "../../llm/index.js";
import { ChatMemoryBuffer } from "../../memory/ChatMemoryBuffer.js";
import type { ObjectRetriever } from "../../objects/base.js";
import { ToolOutput } from "../../tools/index.js";
import type { BaseTool } from "../../types.js";
import type { AgentWorker, Task } from "../types.js";
import { TaskStep, TaskStepOutput } from "../types.js";
import { ReActChatFormatter } from "./formatter.js";
import { ReActOutputParser } from "./outputParser.js";
import type { BaseReasoningStep } from "./types.js";
import {
ActionReasoningStep,
ObservationReasoningStep,
ResponseReasoningStep,
} from "./types.js";
type ReActAgentWorkerParams = {
tools: BaseTool[];
llm?: LLM;
maxInteractions?: number;
reactChatFormatter?: ReActChatFormatter | undefined;
outputParser?: ReActOutputParser | undefined;
callbackManager?: CallbackManager | undefined;
verbose?: boolean | undefined;
toolRetriever?: ObjectRetriever | undefined;
};
/**
*
* @param step
* @param memory
* @param currentReasoning
* @param verbose
*/
function addUserStepToReasoning(
step: TaskStep,
memory: ChatMemoryBuffer,
currentReasoning: BaseReasoningStep[],
verbose: boolean = false,
): void {
if (step.stepState.isFirst) {
memory.put({
content: step.input,
role: "user",
});
step.stepState.isFirst = false;
} else {
const reasoningStep = new ObservationReasoningStep({
observation: step.input ?? undefined,
});
currentReasoning.push(reasoningStep);
if (verbose) {
console.log(`Added user message to memory: ${step.input}`);
}
}
}
/**
* ReAct agent worker.
*/
export class ReActAgentWorker implements AgentWorker {
llm: LLM;
verbose: boolean;
maxInteractions: number = 10;
reactChatFormatter: ReActChatFormatter;
outputParser: ReActOutputParser;
callbackManager: CallbackManager;
_getTools: (message: string) => Promise<BaseTool[]>;
constructor({
tools,
llm,
maxInteractions,
reactChatFormatter,
outputParser,
callbackManager,
verbose,
toolRetriever,
}: ReActAgentWorkerParams) {
this.llm = llm ?? new OpenAI({ model: "gpt-3.5-turbo-0613" });
this.callbackManager = callbackManager || new CallbackManager();
this.maxInteractions = maxInteractions ?? 10;
this.reactChatFormatter = reactChatFormatter ?? new ReActChatFormatter();
this.outputParser = outputParser ?? new ReActOutputParser();
this.verbose = verbose || false;
if (tools.length > 0 && toolRetriever) {
throw new Error("Cannot specify both tools and tool_retriever");
} else if (tools.length > 0) {
this._getTools = async () => tools;
} else if (toolRetriever) {
this._getTools = async (message: string) =>
toolRetriever.retrieve(message);
} else {
this._getTools = async () => [];
}
}
/**
* Initialize a task step.
* @param task - task
* @param kwargs - keyword arguments
* @returns - task step
*/
initializeStep(task: Task, kwargs?: any): TaskStep {
const sources: ToolOutput[] = [];
const currentReasoning: BaseReasoningStep[] = [];
const newMemory = new ChatMemoryBuffer();
const taskState = {
sources,
currentReasoning,
newMemory,
};
task.extraState = {
...task.extraState,
...taskState,
};
return new TaskStep(task.taskId, randomUUID(), task.input, {
isFirst: true,
});
}
/**
* Extract reasoning step from chat response.
* @param output - chat response
* @param isStreaming - whether the chat response is streaming
* @returns - [message content, reasoning steps, is done]
*/
extractReasoningStep(
output: ChatResponse,
isStreaming: boolean,
): [string, BaseReasoningStep[], boolean] {
if (!output.message.content) {
throw new Error("Got empty message.");
}
const messageContent = output.message.content;
const currentReasoning: BaseReasoningStep[] = [];
let reasoningStep;
try {
reasoningStep = this.outputParser.parse(
messageContent,
isStreaming,
) as ActionReasoningStep;
} catch (e) {
throw new Error(`Could not parse output: ${e}`);
}
if (this.verbose) {
console.log(`${reasoningStep.getContent()}\n`);
}
currentReasoning.push(reasoningStep);
if (reasoningStep.isDone()) {
return [messageContent, currentReasoning, true];
}
const actionReasoningStep = new ActionReasoningStep({
thought: reasoningStep.getContent(),
action: reasoningStep.action,
actionInput: reasoningStep.actionInput,
});
if (!(actionReasoningStep instanceof ActionReasoningStep)) {
throw new Error(`Expected ActionReasoningStep, got ${reasoningStep}`);
}
return [messageContent, currentReasoning, false];
}
/**
* Process actions.
* @param task - task
* @param tools - tools
* @param output - chat response
* @param isStreaming - whether the chat response is streaming
* @returns - [reasoning steps, is done]
*/
async _processActions(
task: Task,
tools: BaseTool[],
output: ChatResponse,
isStreaming: boolean = false,
): Promise<[BaseReasoningStep[], boolean]> {
const toolsDict: Record<string, BaseTool> = {};
for (const tool of tools) {
toolsDict[tool.metadata.name] = tool;
}
const [_, currentReasoning, isDone] = this.extractReasoningStep(
output,
isStreaming,
);
if (isDone) {
return [currentReasoning, true];
}
const reasoningStep = currentReasoning[
currentReasoning.length - 1
] as ActionReasoningStep;
const actionReasoningStep = new ActionReasoningStep({
thought: reasoningStep.getContent(),
action: reasoningStep.action,
actionInput: reasoningStep.actionInput,
});
const tool = toolsDict[actionReasoningStep.action];
const toolOutput = await tool?.call?.(actionReasoningStep.actionInput);
task.extraState.sources.push(
new ToolOutput(
toolOutput,
tool.metadata.name,
actionReasoningStep.actionInput,
toolOutput,
),
);
const observationStep = new ObservationReasoningStep({
observation: toolOutput,
});
currentReasoning.push(observationStep);
if (this.verbose) {
console.log(`${observationStep.getContent()}`);
}
return [currentReasoning, false];
}
/**
* Get response.
* @param currentReasoning - current reasoning steps
* @param sources - tool outputs
* @returns - agent chat response
*/
_getResponse(
currentReasoning: BaseReasoningStep[],
sources: ToolOutput[],
): AgentChatResponse {
if (currentReasoning.length === 0) {
throw new Error("No reasoning steps were taken.");
} else if (currentReasoning.length === this.maxInteractions) {
throw new Error("Reached max iterations.");
}
const responseStep = currentReasoning[currentReasoning.length - 1];
let responseStr: string;
if (responseStep instanceof ResponseReasoningStep) {
responseStr = responseStep.response;
} else {
responseStr = responseStep.getContent();
}
return new AgentChatResponse(responseStr, sources);
}
/**
* Get task step response.
* @param agentResponse - agent chat response
* @param step - task step
* @param isDone - whether the task is done
* @returns - task step output
*/
_getTaskStepResponse(
agentResponse: AgentChatResponse,
step: TaskStep,
isDone: boolean,
): TaskStepOutput {
let newSteps: TaskStep[] = [];
if (isDone) {
newSteps = [];
} else {
newSteps = [step.getNextStep(randomUUID(), undefined)];
}
return new TaskStepOutput(agentResponse, step, newSteps, isDone);
}
/**
* Run a task step.
* @param step - task step
* @param task - task
* @param kwargs - keyword arguments
* @returns - task step output
*/
async _runStep(
step: TaskStep,
task: Task,
kwargs?: any,
): Promise<TaskStepOutput> {
if (step.input) {
addUserStepToReasoning(
step,
task.extraState.newMemory,
task.extraState.currentReasoning,
this.verbose,
);
}
const tools = await this._getTools(task.input);
const inputChat = this.reactChatFormatter.format(
tools,
[...task.memory.getAll(), ...task.extraState.newMemory.getAll()],
task.extraState.currentReasoning,
);
const chatResponse = await this.llm.chat({
messages: inputChat,
});
const [reasoningSteps, isDone] = await this._processActions(
task,
tools,
chatResponse,
);
task.extraState.currentReasoning.push(...reasoningSteps);
const agentResponse = this._getResponse(
task.extraState.currentReasoning,
task.extraState.sources,
);
if (isDone) {
task.extraState.newMemory.put({
content: agentResponse.response,
role: "assistant",
});
}
return this._getTaskStepResponse(agentResponse, step, isDone);
}
/**
* Run a task step.
* @param step - task step
* @param task - task
* @param kwargs - keyword arguments
* @returns - task step output
*/
async runStep(
step: TaskStep,
task: Task,
kwargs?: any,
): Promise<TaskStepOutput> {
return await this._runStep(step, task);
}
/**
* Run a task step.
* @param step - task step
* @param task - task
* @param kwargs - keyword arguments
* @returns - task step output
*/
streamStep(
step: TaskStep,
task: Task,
kwargs?: any,
): Promise<TaskStepOutput> {
throw new Error("Method not implemented.");
}
/**
* Finalize a task.
* @param task - task
* @param kwargs - keyword arguments
*/
finalizeTask(task: Task, kwargs?: any): void {
task.memory.set(task.memory.get() + task.extraState.newMemory.get());
task.extraState.newMemory.reset();
}
}
+9 -8
View File
@@ -1,15 +1,16 @@
import { randomUUID } from "crypto";
import { CallbackManager } from "../../callbacks/CallbackManager";
import { CallbackManager } from "../../callbacks/CallbackManager.js";
import type { ChatEngineAgentParams } from "../../engines/chat/index.js";
import {
AgentChatResponse,
ChatEngineAgentParams,
ChatResponseMode,
} from "../../engines/chat";
import { ChatMessage, LLM } from "../../llm";
import { ChatMemoryBuffer } from "../../memory/ChatMemoryBuffer";
import { BaseMemory } from "../../memory/types";
import { AgentWorker, Task, TaskStep, TaskStepOutput } from "../types";
import { AgentState, BaseAgentRunner, TaskState } from "./types";
} from "../../engines/chat/index.js";
import type { ChatMessage, LLM } from "../../llm/index.js";
import { ChatMemoryBuffer } from "../../memory/ChatMemoryBuffer.js";
import type { BaseMemory } from "../../memory/types.js";
import type { AgentWorker, TaskStepOutput } from "../types.js";
import { Task, TaskStep } from "../types.js";
import { AgentState, BaseAgentRunner, TaskState } from "./types.js";
const validateStepFromArgs = (
taskId: string,

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