Compare commits

..

30 Commits

Author SHA1 Message Date
github-actions[bot] ca348a6570 Release 0.2.12 (#770)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-04-26 13:11:23 +07:00
Marcus Schiesser 44a7fd72e8 ci: publish github release on tag pushes (#771) 2024-04-26 13:09:25 +07:00
Thuc Pham d8d952d937 feat: init gemini llm (#769) 2024-04-26 11:04:33 +07:00
github-actions[bot] 216ba1f22b Release 0.2.11 (#765)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-04-25 17:53:17 -07:00
Marcus Schiesser 74686f5776 ci: add version to release PR (#766) 2024-04-25 10:55:02 +07:00
Marcus Schiesser 1ebf9e67a4 ci: add release action (#764) 2024-04-25 10:09:55 +07:00
Alex Yang aeefc77da0 test: load large amount of data won't cause error (#762) 2024-04-24 15:04:29 -05:00
ezirmusitua 13d8d7cbbe fix: use Array.prototype.flat (#760)
Co-authored-by: Alex Yang <himself65@outlook.com>
2024-04-24 14:36:12 -05:00
Alex Yang 9c34e44b85 ci: coverage node.js 22 (#761) 2024-04-24 14:19:12 -05:00
Thuc Pham cb2dc802d9 docs: update next config for external packages (#759) 2024-04-24 17:27:20 +08:00
Ziniu Yu 5a6cc0e32e feat: support jina ai embedding and reranker (#734) 2024-04-24 15:45:36 +07:00
Marcus Schiesser a63256eb84 feat: add default file metadata (#758) 2024-04-24 13:54:29 +07:00
Alex Yang 0a160b97a0 fix(docs): api generation (#756) 2024-04-23 14:24:17 -05:00
Thuc Pham 95602c7959 feat: overide generate hash function for image document (#751)
Co-authored-by: Marcus Schiesser <mail@marcusschiesser.de>
2024-04-23 11:56:37 +07:00
Alex Yang 20bc466ca1 chore: bump notion reader (#753) 2024-04-22 15:14:06 -05:00
Thuc Pham efb1c56ba5 fix: return buffer when loading image data (#749) 2024-04-22 15:28:19 +07:00
Alex Yang 286499388d fix: agent class should implement ChatEngine interface (#746) 2024-04-22 02:13:29 -05:00
Alex Yang 460c6574cc fix: rename ReACTAgent to ReActAgent (#748) 2024-04-22 00:57:43 -05:00
Marcus Schiesser 8b0e0e3cc8 docs: use dedicated embedding model for ollama (#745) 2024-04-22 10:40:39 +07:00
Alex Yang 87142b29fa chore: update changeset 2024-04-21 20:32:57 -05:00
Alex Yang 501b844f0f refactor: use official ollama sdk (#744) 2024-04-21 20:31:16 -05:00
Alex Yang 03157dc295 feat: use json format for tool result (#742) 2024-04-21 19:27:10 -05:00
Alex Yang ef80b684f7 chore: fix llamaindex node_modules link (#743) 2024-04-21 18:21:15 -05:00
Alex Yang 472e70feee refactor: full typed & iterator of agent worker/runner (part 3) (#728)
Fixes: https://github.com/run-llama/LlamaIndexTS/issues/692, https://github.com/run-llama/LlamaIndexTS/issues/557

Refs: https://github.com/run-llama/llama_index/blob/5a6ffe32faa75db0b4737d1e7a85e6fe4afe94af/docs/module_guides/deploying/agents/agent_runner.md
2024-04-19 17:52:36 -05:00
Alex Yang cfb90f7666 docs: update (#738) 2024-04-19 15:17:48 -05:00
Mike Fortman 2e3a287a27 refactor: astra options (#737) 2024-04-19 11:57:34 -05:00
Marcus Schiesser 635fbb8618 release 0.2.10 2024-04-19 16:14:44 +08:00
Marcus Schiesser d2d34acb31 Add streaming for replicate (Llama 3) (#735) 2024-04-19 15:09:20 +07:00
Yi Ding cf70edbede llama 3 support (#731)
Co-authored-by: Alex Yang <himself65@outlook.com>
2024-04-18 17:08:40 -07:00
Mike Fortman 79b7d246bd chore: update deps Astra (#733) 2024-04-18 17:55:31 -05:00
149 changed files with 7266 additions and 7763 deletions
+1 -1
View File
@@ -72,5 +72,5 @@ module.exports = {
},
},
],
ignorePatterns: ["dist/", "lib/"],
ignorePatterns: ["dist/", "lib/", "deps/"],
};
+1 -1
View File
@@ -13,7 +13,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v2
- uses: pnpm/action-setup@v3
- name: Setup Node.js
uses: actions/setup-node@v4
with:
+1 -1
View File
@@ -14,7 +14,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v2
- uses: pnpm/action-setup@v3
- name: Setup Node.js
uses: actions/setup-node@v4
with:
+37
View File
@@ -0,0 +1,37 @@
name: Publish to GitHub Releases
on:
push:
tags:
- "llamaindex@*"
jobs:
build-and-publish:
runs-on: ubuntu-latest
steps:
- name: Checkout Repo
uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
cache: "pnpm"
- name: Install dependencies
run: pnpm install
- name: Build tarball
run: |
pnpm pack
working-directory: packages/core
- name: Create release
uses: ncipollo/release-action@v1
with:
artifacts: "packages/core/llamaindex-*.tgz"
name: Release ${{ github.ref }}
bodyFile: "packages/core/CHANGELOG.md"
token: ${{ secrets.GITHUB_TOKEN }}
+57
View File
@@ -0,0 +1,57 @@
name: Release
on:
push:
branches:
- main
concurrency: ${{ github.workflow }}-${{ github.ref }}
jobs:
release:
name: Release
runs-on: ubuntu-latest
steps:
- name: Checkout Repo
uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
cache: "pnpm"
- name: Install dependencies
run: pnpm install
- name: Add auth token to .npmrc file
run: |
cat << EOF >> ".npmrc"
//registry.npmjs.org/:_authToken=$NPM_TOKEN
EOF
env:
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Get changeset status
id: get-changeset-status
run: |
pnpm changeset status --output .changeset/status.json
new_version=$(jq -r '.releases[] | select(.name == "llamaindex") | .newVersion' < .changeset/status.json)
rm -v .changeset/status.json
echo "new-version=${new_version}" >> "$GITHUB_OUTPUT"
- name: Create Release Pull Request or Publish to npm
id: changesets
uses: changesets/action@v1
with:
commit: Release ${{ steps.get-changeset-status.outputs.new-version }}
title: Release ${{ steps.get-changeset-status.outputs.new-version }}
# update version PR with the latest changesets
version: pnpm new-version
# build package and call changeset publish
publish: pnpm release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
+10 -8
View File
@@ -17,16 +17,18 @@ jobs:
strategy:
fail-fast: false
matrix:
node-version: [18.x, 20.x, 21.x]
node-version: [18.x, 20.x, 22.x]
name: E2E on Node.js ${{ matrix.node-version }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v2
- uses: pnpm/action-setup@v3
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
node-version: ${{ matrix.node-version }}
cache: "pnpm"
- name: Install dependencies
run: pnpm install
@@ -37,13 +39,13 @@ jobs:
strategy:
fail-fast: false
matrix:
node-version: [18.x, 20.x, 21.x]
node-version: [18.x, 20.x, 22.x]
name: Test on Node.js ${{ matrix.node-version }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v2
- uses: pnpm/action-setup@v3
- name: Setup Node.js
uses: actions/setup-node@v4
with:
@@ -58,7 +60,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v2
- uses: pnpm/action-setup@v3
- name: Setup Node.js
uses: actions/setup-node@v4
with:
@@ -87,7 +89,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v2
- uses: pnpm/action-setup@v3
- name: Setup Node.js
uses: actions/setup-node@v4
with:
@@ -105,7 +107,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v2
- uses: pnpm/action-setup@v3
- name: Setup Node.js
uses: actions/setup-node@v4
with:
+3
View File
@@ -1,2 +1,5 @@
auto-install-peers = true
enable-pre-post-scripts = true
prefer-workspace-packages = true
save-workspace-protocol = true
link-workspace-packages = true
+5 -11
View File
@@ -91,16 +91,10 @@ Please send a descriptive changeset for each PR.
## Publishing (maintainers only)
To publish a new version of the library, first create a new version:
The [Release Github Action](.github/workflows/release.yml) is automatically generating and updating a
PR called "Release {version}".
```shell
pnpm new-version
```
This PR will update the `package.json` and `CHANGELOG.md` files of each package according to
the current changesets in the [.changeset](.changeset/) folder.
If everything looks good, commit the generated files and release the new version:
```shell
pnpm release
git push # push to the main branch
git push --tags
```
If this PR is merged it will automatically add version tags to the repository and publish the updated packages to NPM.
-81
View File
@@ -1,81 +0,0 @@
# Turborepo starter
This is an official starter Turborepo.
## Using this example
Run the following command:
```sh
npx create-turbo@latest
```
## What's inside?
This Turborepo includes the following packages/apps:
### Apps and Packages
- `docs`: a [Next.js](https://nextjs.org/) app
- `web`: another [Next.js](https://nextjs.org/) app
- `ui`: a stub React component library shared by both `web` and `docs` applications
- `eslint-config-custom`: `eslint` configurations (includes `eslint-config-next` and `eslint-config-prettier`)
- `tsconfig`: `tsconfig.json`s used throughout the monorepo
Each package/app is 100% [TypeScript](https://www.typescriptlang.org/).
### Utilities
This Turborepo has some additional tools already setup for you:
- [TypeScript](https://www.typescriptlang.org/) for static type checking
- [ESLint](https://eslint.org/) for code linting
- [Prettier](https://prettier.io) for code formatting
### Build
To build all apps and packages, run the following command:
```
cd my-turborepo
pnpm build
```
### Develop
To develop all apps and packages, run the following command:
```
cd my-turborepo
pnpm dev
```
### Remote Caching
Turborepo can use a technique known as [Remote Caching](https://turbo.build/repo/docs/core-concepts/remote-caching) to share cache artifacts across machines, enabling you to share build caches with your team and CI/CD pipelines.
By default, Turborepo will cache locally. To enable Remote Caching you will need an account with Vercel. If you don't have an account you can [create one](https://vercel.com/signup), then enter the following commands:
```
cd my-turborepo
npx turbo login
```
This will authenticate the Turborepo CLI with your [Vercel account](https://vercel.com/docs/concepts/personal-accounts/overview).
Next, you can link your Turborepo to your Remote Cache by running the following command from the root of your Turborepo:
```
npx turbo link
```
## Useful Links
Learn more about the power of Turborepo:
- [Tasks](https://turbo.build/repo/docs/core-concepts/monorepos/running-tasks)
- [Caching](https://turbo.build/repo/docs/core-concepts/caching)
- [Remote Caching](https://turbo.build/repo/docs/core-concepts/remote-caching)
- [Filtering](https://turbo.build/repo/docs/core-concepts/monorepos/filtering)
- [Configuration Options](https://turbo.build/repo/docs/reference/configuration)
- [CLI Usage](https://turbo.build/repo/docs/reference/command-line-reference)
+14 -7
View File
@@ -114,14 +114,21 @@ Add the following config to your `next.config.js` to ignore specific packages in
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
serverComponentsExternalPackages: ["pdf2json", "@zilliz/milvus2-sdk-node"],
serverComponentsExternalPackages: [
"pdf2json",
"@zilliz/milvus2-sdk-node",
"sharp",
"onnxruntime-node",
],
},
webpack: (config) => {
config.resolve.alias = {
...config.resolve.alias,
sharp$: false,
"onnxruntime-node$": false,
};
config.externals.push({
pdf2json: "commonjs pdf2json",
"@zilliz/milvus2-sdk-node": "commonjs @zilliz/milvus2-sdk-node",
sharp: "commonjs sharp",
"onnxruntime-node": "commonjs onnxruntime-node",
});
return config;
},
};
@@ -183,7 +190,7 @@ You'll find a complete example of using the Edge runtime with LlamaIndexTS here:
- OpenAI GPT-3.5-turbo and GPT-4
- Anthropic Claude 3 (Opus, Sonnet, and Haiku) and the legacy models (Claude 2 and Instant)
- Groq LLMs
- Llama2 Chat LLMs (70B, 13B, and 7B parameters)
- Llama2/3 Chat LLMs (70B, 13B, and 7B parameters)
- MistralAI Chat LLMs
- Fireworks Chat LLMs
+16
View File
@@ -1,5 +1,21 @@
# docs
## 0.0.6
### Patch Changes
- Updated dependencies [d8d952d]
- llamaindex@0.2.12
## 0.0.5
### Patch Changes
- Updated dependencies [87142b2]
- Updated dependencies [5a6cc0e]
- Updated dependencies [87142b2]
- llamaindex@0.2.11
## 0.0.4
### Patch Changes
+3 -77
View File
@@ -4,81 +4,7 @@ A built-in agent that can take decisions and reasoning based on the tools provid
## OpenAI Agent
```ts
import { FunctionTool, OpenAIAgent } from "llamaindex";
import CodeBlock from "@theme/CodeBlock";
import CodeSource from "!raw-loader!../../../../examples/agent/openai";
// 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 dividend to divide",
},
b: {
type: "number",
description: "The divisor to divide by",
},
},
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],
});
// Chat with the agent
const response = await agent.chat({
message: "How much is 5 + 5? then divide by 2",
});
// Print the response
console.log(String(response));
}
main().then(() => {
console.log("Done");
});
```
<CodeBlock language="ts">{CodeSource}</CodeBlock>
+7 -1
View File
@@ -11,4 +11,10 @@ An “agent” is an automated reasoning and decision engine. It takes in a user
LlamaIndex.TS comes with a few built-in agents, but you can also create your own. The built-in agents include:
- [OpenAI Agent](./openai.mdx)
- OpenAI Agent
- Anthropic Agent
- ReACT Agent
## Examples
- [OpenAI Agent](../../examples/agent.mdx)
@@ -1,307 +0,0 @@
# 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,
Settings,
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
Settings.llm = new OpenAI({
model: "gpt-4",
});
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({
storageContext: storageContext,
nodes,
});
// create the summary index for broader search
const summaryIndex = await SummaryIndex.init({
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,
});
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,
{
storageContext,
},
);
// create the top agent
const topAgent = new OpenAIAgent({
toolRetriever: await objectIndex.asRetriever({}),
llm,
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)
-185
View File
@@ -1,185 +0,0 @@
---
sidebar_position: 0
---
# OpenAI Agent
OpenAI API that supports function calling, its never been easier to build your own agent!
In this notebook tutorial, we showcase how to write your own OpenAI agent
## 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
```
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 OpenAIAgent
Now we can create an OpenAIAgent with the function tools.
```ts
const agent = new OpenAIAgent({
tools: [sumFunctionTool, divideFunctionTool],
});
```
## 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));
```
## Full code
```ts
import { FunctionTool, OpenAIAgent } 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],
});
// Chat with the agent
const response = await agent.chat({
message: "How much is 5 + 5? then divide by 2",
});
// Print the response
console.log(String(response));
}
main().then(() => {
console.log("Done");
});
```
@@ -1,130 +0,0 @@
---
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.
## 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
```
Then you can import the necessary classes and functions.
```ts
import {
OpenAIAgent,
SimpleDirectoryReader,
VectorStoreIndex,
QueryEngineTool,
} from "llamaindex";
```
## Create a vector index
Now we can create a vector index from a set of documents.
```ts
// 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 QueryEngineTool
Now we can create a QueryEngineTool from the vector index.
```ts
// 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
```ts
// Create an OpenAIAgent with the query engine tool tools
const agent = new OpenAIAgent({
tools: [queryEngineTool],
});
```
## Chat with the agent
Now we can chat with the agent.
```ts
const response = await agent.chat({
message: "What was his salary?",
});
console.log(String(response));
```
## Full code
```ts
import {
OpenAIAgent,
SimpleDirectoryReader,
VectorStoreIndex,
QueryEngineTool,
} 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],
});
// 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");
});
```
@@ -1,201 +0,0 @@
# 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],
});
```
## 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],
});
// 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");
});
```
@@ -0,0 +1,33 @@
# Gemini
To use Gemini embeddings, you need to import `GeminiEmbedding` from `llamaindex`.
```ts
import { GeminiEmbedding, Settings } from "llamaindex";
// Update Embed Model
Settings.embedModel = new GeminiEmbedding();
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const queryEngine = index.asQueryEngine();
const query = "What is the meaning of life?";
const results = await queryEngine.query({
query,
});
```
Per default, `GeminiEmbedding` is using the `gemini-pro` model. You can change the model by passing the `model` parameter to the constructor.
For example:
```ts
import { GEMINI_MODEL, GeminiEmbedding } from "llamaindex";
Settings.embedModel = new GeminiEmbedding({
model: GEMINI_MODEL.GEMINI_PRO_LATEST,
});
```
@@ -0,0 +1,21 @@
# Jina AI
To use Jina AI embeddings, you need to import `JinaAIEmbedding` from `llamaindex`.
```ts
import { JinaAIEmbedding, Settings } from "llamaindex";
Settings.embedModel = new JinaAIEmbedding();
const document = new Document({ text: essay, id_: "essay" });
const index = await VectorStoreIndex.fromDocuments([document]);
const queryEngine = index.asQueryEngine();
const query = "What is the meaning of life?";
const results = await queryEngine.query({
query,
});
```
@@ -1,11 +1,19 @@
# Ollama
To use Ollama embeddings, you need to import `Ollama` from `llamaindex`.
To use Ollama embeddings, you need to import `OllamaEmbedding` from `llamaindex`.
Note that you need to pull the embedding model first before using it.
In the example below, we're using the [`nomic-embed-text`](https://ollama.com/library/nomic-embed-text) model, so you have to call:
```shell
ollama pull nomic-embed-text
```
```ts
import { Ollama, Settings } from "llamaindex";
import { OllamaEmbedding, Settings } from "llamaindex";
Settings.embedModel = new Ollama();
Settings.embedModel = new OllamaEmbedding({ model: "nomic-embed-text" });
const document = new Document({ text: essay, id_: "essay" });
@@ -0,0 +1,71 @@
# Gemini
## Usage
```ts
import { Gemini, Settings, GEMINI_MODEL } from "llamaindex";
Settings.llm = new Gemini({
model: GEMINI_MODEL.GEMINI_PRO,
});
```
## 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]);
```
## Query
```ts
const queryEngine = index.asQueryEngine();
const query = "What is the meaning of life?";
const results = await queryEngine.query({
query,
});
```
## Full Example
```ts
import {
Gemini,
Document,
VectorStoreIndex,
Settings,
GEMINI_MODEL,
} from "llamaindex";
Settings.llm = new Gemini({
model: GEMINI_MODEL.GEMINI_PRO,
});
async function main() {
const document = new Document({ text: essay, id_: "essay" });
// Load and index documents
const index = await VectorStoreIndex.fromDocuments([document]);
// 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,71 @@
# Jina AI Reranker
The Jina AI Reranker is a postprocessor that uses the Jina AI Reranker 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 [Jina AI](https://jina.ai/reranker). Once you have your API key you can import the necessary modules and create a new instance of the `JinaAIReranker` class.
```ts
import {
JinaAIReranker,
Document,
OpenAI,
VectorStoreIndex,
Settings,
} 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" });
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 });
const index = await VectorStoreIndex.fromDocuments([document]);
```
## 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 JinaAIReranker class
Then you can create a new instance of the `JinaAIReranker` class and pass in the number of results you want to return.
The Jina AI Reranker API key is set in the `JINAAI_API_KEY` environment variable.
```bash
export JINAAI_API_KEY=<YOUR API KEY>
```
```ts
const nodePostprocessor = new JinaAIReranker({
topN: 5,
});
```
## 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?");
```
+1 -1
View File
@@ -163,7 +163,7 @@ const config = {
"docusaurus-plugin-typedoc",
{
entryPoints: ["../../packages/core/src/index.ts"],
tsconfig: "../../packages/core/tsconfig.json",
tsconfig: "../../tsconfig.json",
readme: "none",
sourceLinkTemplate:
"https://github.com/run-llama/LlamaIndexTS/blob/{gitRevision}/{path}#L{line}",
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "docs",
"version": "0.0.4",
"version": "0.0.6",
"private": true,
"scripts": {
"docusaurus": "docusaurus",
@@ -20,6 +20,7 @@
"@llamaindex/examples": "workspace:*",
"@mdx-js/react": "^3.0.1",
"clsx": "^2.1.0",
"llamaindex": "workspace:*",
"postcss": "^8.4.38",
"prism-react-renderer": "^2.3.1",
"raw-loader": "^4.0.2",
+1 -1
View File
@@ -125,7 +125,7 @@ async function main() {
const topAgent = new OpenAIAgent({
toolRetriever: await objectIndex.asRetriever({}),
llm: new OpenAI({ model: "gpt-4" }),
prefixMessages: [
chatHistory: [
{
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.",
+40 -54
View File
@@ -1,72 +1,58 @@
import { FunctionTool, OpenAIAgent } from "llamaindex";
// Define a function to sum two numbers
function sumNumbers({ a, b }: { a: number; b: number }) {
return `${a + b}`;
}
// Define a function to divide two numbers
function divideNumbers({ a, b }: { a: number; b: 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"],
} as const;
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"],
} as const;
async function main() {
// Create a function tool from the sum function
const functionTool = new FunctionTool(sumNumbers, {
const sumNumbers = FunctionTool.from(
({ a, b }: { a: number; b: number }) => `${a + b}`,
{
name: "sumNumbers",
description: "Use this function to sum two numbers",
parameters: sumJSON,
});
parameters: {
type: "object",
properties: {
a: {
type: "number",
description: "The first number",
},
b: {
type: "number",
description: "The second number",
},
},
required: ["a", "b"],
},
},
);
// Create a function tool from the divide function
const functionTool2 = new FunctionTool(divideNumbers, {
const divideNumbers = FunctionTool.from(
({ a, b }: { a: number; b: number }) => `${a / b}`,
{
name: "divideNumbers",
description: "Use this function to divide two numbers",
parameters: divideJSON,
});
parameters: {
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"],
},
},
);
// Create an OpenAIAgent with the function tools
async function main() {
const agent = new OpenAIAgent({
tools: [functionTool, functionTool2],
tools: [sumNumbers, divideNumbers],
});
// Chat with the agent
const response = await agent.chat({
message: "How much is 5 + 5? then divide by 2",
});
// Print the response
console.log(String(response));
}
+2 -2
View File
@@ -68,12 +68,12 @@ async function main() {
});
// Chat with the agent
const response = await agent.chat({
const { response } = await agent.chat({
message: "Divide 16 by 2 then add 20",
});
// Print the response
console.log(String(response));
console.log(response.message);
}
void main().then(() => {
+4 -15
View File
@@ -62,29 +62,18 @@ async function main() {
});
// Create a task to sum and divide numbers
const task = agent.createTask("How much is 5 + 5? then divide by 2");
const task = await agent.createTask("How much is 5 + 5? then divide by 2");
let count = 0;
while (true) {
const stepOutput = await agent.runStep(task.taskId);
for await (const stepOutput of task) {
console.log(`Runnning step ${count++}`);
console.log(`======== OUTPUT ==========`);
if (stepOutput.output.response) {
console.log(stepOutput.output.response);
} else {
console.log(stepOutput.output.sources);
}
console.log(stepOutput.output.message.content);
console.log(`==========================`);
if (stepOutput.isLast) {
const finalResponse = await agent.finalizeResponse(
task.taskId,
stepOutput,
);
console.log({ finalResponse });
break;
console.log(stepOutput.output.message.content);
}
}
}
+4 -24
View File
@@ -31,31 +31,11 @@ async function main() {
tools: [queryEngineTool],
});
const task = agent.createTask("What was his salary?");
const { response } = await agent.chat({
message: "What was his salary?",
});
let count = 0;
while (true) {
const stepOutput = await agent.runStep(task.taskId);
console.log(`Runnning step ${count++}`);
console.log(`======== OUTPUT ==========`);
if (stepOutput.output.response) {
console.log(stepOutput.output.response);
} else {
console.log(stepOutput.output.sources);
}
console.log(`==========================`);
if (stepOutput.isLast) {
const finalResponse = await agent.finalizeResponse(
task.taskId,
stepOutput,
);
console.log({ finalResponse });
break;
}
}
console.log(response.message.content);
}
void main().then(() => {
+8 -15
View File
@@ -1,4 +1,4 @@
import { FunctionTool, ReActAgent } from "llamaindex";
import { Anthropic, FunctionTool, ReActAgent } from "llamaindex";
// Define a function to sum two numbers
function sumNumbers({ a, b }: { a: number; b: number }) {
@@ -7,6 +7,7 @@ function sumNumbers({ a, b }: { a: number; b: number }) {
// Define a function to divide two numbers
function divideNumbers({ a, b }: { a: number; b: number }) {
console.log("get input", a, b);
return `${a / b}`;
}
@@ -58,29 +59,21 @@ async function main() {
// Create an OpenAIAgent with the function tools
const agent = new ReActAgent({
llm: new Anthropic({
model: "claude-3-opus",
}),
tools: [functionTool, functionTool2],
});
const task = agent.createTask("Divide 16 by 2 then add 20");
const task = await agent.createTask("Divide 16 by 2 then add 20");
let count = 0;
while (true) {
const stepOutput = await agent.runStep(task.taskId);
for await (const stepOutput of task) {
console.log(`Runnning step ${count++}`);
console.log(`======== OUTPUT ==========`);
console.log(stepOutput.output);
console.log(stepOutput);
console.log(`==========================`);
if (stepOutput.isLast) {
const finalResponse = await agent.finalizeResponse(
task.taskId,
stepOutput,
);
console.log({ finalResponse });
break;
}
}
}
+1 -1
View File
@@ -13,7 +13,7 @@ Here are two sample scripts which work well with the sample data in the Astra Po
1. Set your env variables:
- `ASTRA_DB_APPLICATION_TOKEN`: The generated app token for your Astra database
- `ASTRA_DB_ENDPOINT`: The API endpoint for your Astra database
- `ASTRA_DB_API_ENDPOINT`: The API endpoint for your Astra database
- `ASTRA_DB_NAMESPACE`: (Optional) The namespace where your collection is stored defaults to `default_keyspace`
- `OPENAI_API_KEY`: Your OpenAI key
+1 -2
View File
@@ -34,10 +34,9 @@ async function main() {
];
const astraVS = new AstraDBVectorStore();
await astraVS.create(collectionName, {
await astraVS.createAndConnect(collectionName, {
vector: { dimension: 1536, metric: "cosine" },
});
await astraVS.connect(collectionName);
const ctx = await storageContextFromDefaults({ vectorStore: astraVS });
const index = await VectorStoreIndex.fromDocuments(docs, {
+1 -1
View File
@@ -13,7 +13,7 @@ async function main() {
const docs = await reader.loadData("./data/movie_reviews.csv");
const astraVS = new AstraDBVectorStore({ contentKey: "reviewtext" });
await astraVS.create(collectionName, {
await astraVS.createAndConnect(collectionName, {
vector: { dimension: 1536, metric: "cosine" },
});
await astraVS.connect(collectionName);
+7 -2
View File
@@ -1,4 +1,8 @@
import { AstraDBVectorStore, VectorStoreIndex } from "llamaindex";
import {
AstraDBVectorStore,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
const collectionName = "movie_reviews";
@@ -7,7 +11,8 @@ async function main() {
const astraVS = new AstraDBVectorStore({ contentKey: "reviewtext" });
await astraVS.connect(collectionName);
const index = await VectorStoreIndex.fromVectorStore(astraVS);
const ctx = serviceContextFromDefaults();
const index = await VectorStoreIndex.fromVectorStore(astraVS, ctx);
const retriever = await index.asRetriever({ similarityTopK: 20 });
+15
View File
@@ -0,0 +1,15 @@
import { GEMINI_MODEL, GeminiEmbedding } from "llamaindex";
async function main() {
if (!process.env.GOOGLE_API_KEY) {
throw new Error("Please set the GOOGLE_API_KEY environment variable.");
}
const embedModel = new GeminiEmbedding({
model: GEMINI_MODEL.GEMINI_PRO,
});
const texts = ["hello", "world"];
const embeddings = await embedModel.getTextEmbeddingsBatch(texts);
console.log(`\nWe have ${embeddings.length} embeddings`);
}
main().catch(console.error);
+21
View File
@@ -0,0 +1,21 @@
import { Gemini, GEMINI_MODEL } from "llamaindex";
(async () => {
if (!process.env.GOOGLE_API_KEY) {
throw new Error("Please set the GOOGLE_API_KEY environment variable.");
}
const gemini = new Gemini({
model: GEMINI_MODEL.GEMINI_PRO,
});
const result = await gemini.chat({
messages: [
{ content: "You want to talk in rhymes.", role: "system" },
{
content:
"How much wood would a woodchuck chuck if a woodchuck could chuck wood?",
role: "user",
},
],
});
console.log(result);
})();
+40
View File
@@ -0,0 +1,40 @@
import { stdin as input, stdout as output } from "node:process";
import readline from "node:readline/promises";
import { ChatMessage, OpenAI, ReplicateLLM } from "llamaindex";
(async () => {
const gpt4 = new OpenAI({ model: "gpt-4-turbo", temperature: 0.9 });
const l3 = new ReplicateLLM({
model: "llama-3-70b-instruct",
temperature: 0.9,
});
const rl = readline.createInterface({ input, output });
const start = await rl.question("Start: ");
const history: ChatMessage[] = [
{
content:
"Prefer shorter answers. Keep your response to 100 words or less.",
role: "system",
},
{ content: start, role: "user" },
];
while (true) {
const next = history.length % 2 === 1 ? gpt4 : l3;
const r = await next.chat({
messages: history.map(({ content, role }) => ({
content,
role: next === l3 ? role : role === "user" ? "assistant" : "user",
})),
});
history.push({
content: r.message.content,
role: next === l3 ? "assistant" : "user",
});
await rl.question(
(next === l3 ? "Llama 3: " : "GPT 4 Turbo: ") + r.message.content,
);
}
})();
+13
View File
@@ -0,0 +1,13 @@
import { ReplicateLLM } from "llamaindex";
(async () => {
const tres = new ReplicateLLM({ model: "llama-3-70b-instruct" });
const stream = await tres.chat({
messages: [{ content: "Hello, world!", role: "user" }],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.delta);
}
console.log("\n\ndone");
})();
-2
View File
@@ -4,7 +4,6 @@ import {
VectorStoreIndex,
storageContextFromDefaults,
} from "llamaindex";
import { DocStoreStrategy } from "llamaindex/ingestion/strategies/index";
import * as path from "path";
@@ -32,7 +31,6 @@ async function generateDatasource() {
});
await VectorStoreIndex.fromDocuments(documents, {
storageContext,
docStoreStrategy: DocStoreStrategy.NONE,
});
});
console.log(`Storage successfully generated in ${ms / 1000}s.`);
+4 -2
View File
@@ -1,7 +1,9 @@
import { OllamaEmbedding } from "llamaindex";
import { Ollama } from "llamaindex/llm/ollama";
(async () => {
const llm = new Ollama({ model: "llama2", temperature: 0.75 });
const llm = new Ollama({ model: "llama3" });
const embedModel = new OllamaEmbedding({ model: "nomic-embed-text" });
{
const response = await llm.chat({
messages: [{ content: "Tell me a joke.", role: "user" }],
@@ -35,7 +37,7 @@ import { Ollama } from "llamaindex/llm/ollama";
console.log(); // newline
}
{
const embedding = await llm.getTextEmbedding("Hello world!");
const embedding = await embedModel.getTextEmbedding("Hello world!");
console.log("Embedding:", embedding);
}
})();
+7 -4
View File
@@ -4,15 +4,15 @@
"version": "0.0.4",
"dependencies": {
"@aws-crypto/sha256-js": "^5.2.0",
"@datastax/astra-db-ts": "^0.1.4",
"@datastax/astra-db-ts": "^1.0.1",
"@notionhq/client": "^2.2.15",
"@pinecone-database/pinecone": "^1.1.3",
"@zilliz/milvus2-sdk-node": "^2.3.5",
"@zilliz/milvus2-sdk-node": "^2.4.1",
"chromadb": "^1.8.1",
"commander": "^11.1.0",
"dotenv": "^16.4.5",
"js-tiktoken": "^1.0.10",
"llamaindex": "latest",
"js-tiktoken": "^1.0.11",
"llamaindex": "*",
"mongodb": "^6.5.0",
"pathe": "^1.1.2"
},
@@ -24,5 +24,8 @@
},
"scripts": {
"lint": "eslint ."
},
"stackblitz": {
"startCommand": "npm start"
}
}
+11 -10
View File
@@ -3,20 +3,21 @@
"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"
"start": "node --import tsx ./src/simple-directory-reader.ts",
"start:csv": "node --import tsx ./src/csv.ts",
"start:docx": "node --import tsx ./src/docx.ts",
"start:html": "node --import tsx ./src/html.ts",
"start:markdown": "node --import tsx ./src/markdown.ts",
"start:pdf": "node --import tsx ./src/pdf.ts",
"start:llamaparse": "node --import tsx ./src/llamaparse.ts",
"start:notion": "node --import tsx ./src/notion.ts"
},
"dependencies": {
"llamaindex": "latest"
"llamaindex": "*"
},
"devDependencies": {
"@types/node": "^20.12.7",
"ts-node": "^10.9.2",
"typescript": "^5.4.3"
"tsx": "^4.7.2",
"typescript": "^5.4.5"
}
}
+2 -2
View File
@@ -7,7 +7,7 @@ import { createInterface } from "node:readline/promises";
program
.argument("[page]", "Notion page id (must be provided)")
.action(async (page, _options, command) => {
.action(async (page, _options) => {
// Initializing a client
if (!process.env.NOTION_TOKEN) {
@@ -55,7 +55,7 @@ program
.filter((page) => page !== null);
console.log("Found pages:");
console.table(pages);
console.log(`To run, run ts-node ${command.name()} [page id]`);
console.log(`To run, run with [page id]`);
return;
}
}
+3 -3
View File
@@ -1,5 +1,5 @@
import { encodingForModel } from "js-tiktoken";
import { OpenAI } from "llamaindex";
import { ChatMessage, OpenAI, type LLMStartEvent } from "llamaindex";
import { Settings } from "llamaindex/Settings";
import { extractText } from "llamaindex/llm/utils";
@@ -12,9 +12,9 @@ const llm = new OpenAI({
let tokenCount = 0;
Settings.callbackManager.on("llm-start", (event) => {
Settings.callbackManager.on("llm-start", (event: LLMStartEvent) => {
const { messages } = event.detail.payload;
tokenCount += messages.reduce((count, message) => {
messages.reduce((count: number, message: ChatMessage) => {
return count + encoding.encode(extractText(message.content)).length;
}, 0);
console.log("Token count:", tokenCount);
+2 -1
View File
@@ -1,12 +1,13 @@
{
"compilerOptions": {
"target": "es2017",
"target": "ES2022",
"module": "esnext",
"moduleResolution": "bundler",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"lib": ["ES2022"],
"outDir": "./lib",
"tsBuildInfoFile": "./lib/.tsbuildinfo",
"incremental": true,
+1 -1
View File
@@ -33,7 +33,7 @@
"turbo": "^1.13.2",
"typescript": "^5.4.5"
},
"packageManager": "pnpm@9.0.1+sha256.46d50ee2afecb42b185ebbd662dc7bdd52ef5be56bf035bb615cab81a75345df",
"packageManager": "pnpm@9.0.5",
"pnpm": {
"overrides": {
"trim": "1.0.1",
+3 -2
View File
@@ -1,3 +1,4 @@
.turbo
README.md
LICENSE
/README.md
LICENSE
*.tgz
+20
View File
@@ -1,5 +1,25 @@
# llamaindex
## 0.2.12
### Patch Changes
- d8d952d: feat: add gemini llm and embedding
## 0.2.11
### Patch Changes
- 87142b2: refactor: use ollama official sdk
- 5a6cc0e: feat: support jina ai embedding and reranker
- 87142b2: feat: support output to json format
## 0.2.10
### Patch Changes
- cf70edb: Llama 3 support
## 0.2.9
### Patch Changes
+1 -1
View File
@@ -1,3 +1,3 @@
import { OpenAI } from "./open_ai.js";
import { OpenAI } from "./openai.js";
export class Anthropic extends OpenAI {}
@@ -46,10 +46,10 @@ export class OpenAI implements LLM {
if (llmCompleteMockStorage.llmEventStart.length > 0) {
const chatMessage =
llmCompleteMockStorage.llmEventStart.shift()!["messages"];
strictEqual(chatMessage.length, params.messages.length);
strictEqual(params.messages.length, chatMessage.length);
for (let i = 0; i < chatMessage.length; i++) {
strictEqual(chatMessage[i].role, params.messages[i].role);
deepStrictEqual(chatMessage[i].content, params.messages[i].content);
strictEqual(params.messages[i].role, chatMessage[i].role);
deepStrictEqual(params.messages[i].content, chatMessage[i].content);
}
if (llmCompleteMockStorage.llmEventEnd.length > 0) {
@@ -89,9 +89,9 @@ export class OpenAI implements LLM {
if (llmCompleteMockStorage.llmEventStart.length > 0) {
const chatMessage =
llmCompleteMockStorage.llmEventStart.shift()!["messages"];
strictEqual(chatMessage.length, 1);
strictEqual(chatMessage[0].role, "user");
strictEqual(chatMessage[0].content, params.prompt);
strictEqual(1, chatMessage.length);
strictEqual("user", chatMessage[0].role);
strictEqual(params.prompt, chatMessage[0].content);
}
if (llmCompleteMockStorage.llmEventEnd.length > 0) {
const response = llmCompleteMockStorage.llmEventEnd.shift()!["response"];
+11 -9
View File
@@ -1,7 +1,8 @@
import { consola } from "consola";
import { Anthropic, FunctionTool, Settings, type LLM } from "llamaindex";
import { AnthropicAgent } from "llamaindex/agent/anthropic";
import { ok } from "node:assert";
import { extractText } from "llamaindex/llm/utils";
import { ok, strictEqual } from "node:assert";
import { beforeEach, test } from "node:test";
import { sumNumbersTool } from "./fixtures/tools.js";
import { mockLLMEvent } from "./utils.js";
@@ -70,12 +71,13 @@ await test("anthropic agent", async (t) => {
},
],
});
const result = await agent.chat({
const { response, sources } = await agent.chat({
message: "What is the weather in San Francisco?",
});
consola.debug("response:", result.response);
ok(typeof result.response === "string");
ok(result.response.includes("35"));
consola.debug("response:", response.message.content);
strictEqual(sources.length, 1);
ok(extractText(response.message.content).includes("35"));
});
await t.test("async function", async () => {
@@ -111,8 +113,8 @@ await test("anthropic agent", async (t) => {
const { response } = await agent.chat({
message: "My name is Alex Yang. What is my unique id?",
});
consola.debug("response:", response);
ok(response.includes(uniqueId));
consola.debug("response:", response.message.content);
ok(extractText(response.message.content).includes(uniqueId));
});
await t.test("sum numbers", async () => {
@@ -120,10 +122,10 @@ await test("anthropic agent", async (t) => {
tools: [sumNumbersTool],
});
const response = await openaiAgent.chat({
const { response } = await openaiAgent.chat({
message: "how much is 1 + 1?",
});
ok(response.response.includes("2"));
ok(extractText(response.message.content).includes("2"));
});
});
@@ -0,0 +1,2 @@
Alex is a male.
What's very important, Alex is not in the Brazil.
+21
View File
@@ -45,3 +45,24 @@ export const divideNumbersTool = FunctionTool.from(divideNumbers, {
required: ["a", "b"],
},
});
// should always return the 72 degrees
export const getWeatherTool = FunctionTool.from(
async ({ city }: { city: string }) => {
return `The weather in ${city} is 72 degrees`;
},
{
name: "getWeather",
description: "Get the weather for a city",
parameters: {
type: "object",
properties: {
city: {
type: "string",
description: "The city to get the weather for",
},
},
required: ["city"],
},
},
);
+165 -17
View File
@@ -2,18 +2,30 @@ import { consola } from "consola";
import {
Document,
FunctionTool,
ObjectIndex,
OpenAI,
OpenAIAgent,
QueryEngineTool,
Settings,
SimpleNodeParser,
SimpleToolNodeMapping,
SubQuestionQueryEngine,
SummaryIndex,
VectorStoreIndex,
type LLM,
type ToolOutput,
} from "llamaindex";
import { extractText } from "llamaindex/llm/utils";
import { ok, strictEqual } from "node:assert";
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { beforeEach, test } from "node:test";
import { divideNumbersTool, sumNumbersTool } from "./fixtures/tools.js";
import { mockLLMEvent } from "./utils.js";
import {
divideNumbersTool,
getWeatherTool,
sumNumbersTool,
} from "./fixtures/tools.js";
import { mockLLMEvent, testRootDir } from "./utils.js";
let llm: LLM;
beforeEach(async () => {
@@ -84,9 +96,140 @@ await test("gpt-4-turbo", async (t) => {
const { response } = await agent.chat({
message: "What is the weather in San Jose?",
});
consola.debug("response:", response);
ok(typeof response === "string");
ok(response.includes("45"));
consola.debug("response:", response.message.content);
ok(extractText(response.message.content).includes("45"));
});
});
await test("agent system prompt", async (t) => {
await mockLLMEvent(t, "openai_agent_system_prompt");
await t.test("chat", async (t) => {
const agent = new OpenAIAgent({
tools: [getWeatherTool],
systemPrompt:
"You are a pirate. You MUST speak every words staring with a 'Arhgs'",
});
const { response } = await agent.chat({
message: "What is the weather in San Francisco?",
});
consola.debug("response:", response.message.content);
ok(extractText(response.message.content).includes("72"));
ok(extractText(response.message.content).includes("Arhg"));
});
});
await test("agent with object retriever", async (t) => {
await mockLLMEvent(t, "agent_with_object_retriever");
const alexInfoPath = join(testRootDir, "./fixtures/data/Alex.txt");
const alexInfoText = await readFile(alexInfoPath, "utf-8");
const alexDocument = new Document({ text: alexInfoText, id_: alexInfoPath });
const nodes = new SimpleNodeParser({
chunkSize: 200,
chunkOverlap: 20,
}).getNodesFromDocuments([alexDocument]);
const summaryIndex = await SummaryIndex.init({
nodes,
});
const summaryQueryEngine = summaryIndex.asQueryEngine();
const queryEngineTools = [
FunctionTool.from(
({ query }: { query?: string }) => {
throw new Error("This tool should not be called");
},
{
name: "vector_tool",
description:
"This tool should not be called, never use this tool in any cases.",
parameters: {
type: "object",
properties: {
query: { type: "string", nullable: true },
},
},
},
),
new QueryEngineTool({
queryEngine: summaryQueryEngine,
metadata: {
name: "summary_tool",
description: `Useful for any requests that short information about Alex.
For questions about Alex, please use this tool.
For questions about more specific sections, please use the vector_tool.`,
},
}),
];
const originalCall = queryEngineTools[1].call.bind(queryEngineTools[1]);
const mockCall = t.mock.fn(({ query }: { query: string }) => {
return originalCall({ query });
});
queryEngineTools[1].call = mockCall;
const toolMapping = SimpleToolNodeMapping.fromObjects(queryEngineTools);
const objectIndex = await ObjectIndex.fromObjects(
queryEngineTools,
toolMapping,
VectorStoreIndex,
);
const toolRetriever = await objectIndex.asRetriever({});
const agent = new OpenAIAgent({
toolRetriever,
systemPrompt:
"Please always use the tools provided to answer a question. Do not rely on prior knowledge.",
});
strictEqual(mockCall.mock.callCount(), 0);
const { response } = await agent.chat({
message:
"What's the summary of Alex? Does he live in Brazil based on the brief information? Return yes or no.",
});
strictEqual(mockCall.mock.callCount(), 1);
consola.debug("response:", response.message.content);
ok(extractText(response.message.content).toLowerCase().includes("no"));
});
await test("agent with object function call", async (t) => {
await mockLLMEvent(t, "agent_with_object_function_call");
await t.test("basic", async () => {
const agent = new OpenAIAgent({
tools: [
FunctionTool.from(
({ location }: { location: string }) => ({
location,
temperature: 72,
weather: "cloudy",
rain_prediction: 0.89,
}),
{
name: "get_weather",
description: "Get the weather",
parameters: {
type: "object",
properties: {
location: { type: "string" },
},
required: ["location"],
},
},
),
],
});
const { response, sources } = await agent.chat({
message: "What is the weather in San Francisco?",
});
consola.debug("response:", response.message.content);
strictEqual(sources.length, 1);
ok(extractText(response.message.content).includes("72"));
});
});
@@ -113,12 +256,13 @@ await test("agent", async (t) => {
},
],
});
const result = await agent.chat({
const { response, sources } = await agent.chat({
message: "What is the weather in San Francisco?",
});
consola.debug("response:", result.response);
ok(typeof result.response === "string");
ok(result.response.includes("35"));
consola.debug("response:", response.message.content);
strictEqual(sources.length, 1);
ok(extractText(response.message.content).includes("35"));
});
await t.test("async function", async () => {
@@ -151,11 +295,11 @@ await test("agent", async (t) => {
const agent = new OpenAIAgent({
tools: [showUniqueId],
});
const { response } = await agent.chat({
const { response, sources } = await agent.chat({
message: "My name is Alex Yang. What is my unique id?",
});
consola.debug("response:", response);
ok(response.includes(uniqueId));
strictEqual(sources.length, 1);
ok(extractText(response.message.content).includes(uniqueId));
});
await t.test("sum numbers", async () => {
@@ -163,11 +307,12 @@ await test("agent", async (t) => {
tools: [sumNumbersTool],
});
const response = await openaiAgent.chat({
const { response, sources } = await openaiAgent.chat({
message: "how much is 1 + 1?",
});
ok(response.response.includes("2"));
strictEqual(sources.length, 1);
ok(extractText(response.message.content).includes("2"));
});
});
@@ -181,18 +326,21 @@ await test("agent stream", async (t) => {
tools: [sumNumbersTool, divideNumbersTool],
});
const { response } = await agent.chat({
const stream = await agent.chat({
message: "Divide 16 by 2 then add 20",
stream: true,
});
let message = "";
let soruces: ToolOutput[] = [];
for await (const chunk of response) {
message += chunk.response;
for await (const { response, sources: _sources } of stream) {
message += response.delta;
soruces = _sources;
}
strictEqual(fn.mock.callCount(), 2);
strictEqual(soruces.length, 2);
ok(message.includes("28"));
Settings.callbackManager.off("llm-tool-call", fn);
});
+29
View File
@@ -0,0 +1,29 @@
import { OpenAI, ReActAgent, Settings, type LLM } from "llamaindex";
import { extractText } from "llamaindex/llm/utils";
import { ok } from "node:assert";
import { beforeEach, test } from "node:test";
import { getWeatherTool } from "./fixtures/tools.js";
import { mockLLMEvent } from "./utils.js";
let llm: LLM;
beforeEach(async () => {
Settings.llm = new OpenAI({
model: "gpt-3.5-turbo",
});
llm = Settings.llm;
});
await test("react agent", async (t) => {
await mockLLMEvent(t, "react-agent");
await t.test("get weather", async () => {
const agent = new ReActAgent({
tools: [getWeatherTool],
});
const { response } = await agent.chat({
stream: false,
message: "What is the weather like in San Francisco?",
});
ok(extractText(response.message.content).includes("72"));
});
});
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,80 @@
{
"llmEventStart": [
{
"id": "PRESERVE_0",
"messages": [
{
"role": "user",
"content": "What is the weather in San Francisco?"
}
]
},
{
"id": "PRESERVE_1",
"messages": [
{
"role": "user",
"content": "What is the weather in San Francisco?"
},
{
"content": "",
"role": "assistant",
"options": {
"toolCall": {
"id": "call_lR2r0rpfqNX11jukJvEUdByv",
"name": "get_weather",
"input": "{\"location\":\"San Francisco\"}"
}
}
},
{
"content": "{\n location: San Francisco,\n temperature: 72,\n weather: cloudy,\n rain_prediction: 0.89\n}",
"role": "user",
"options": {
"toolResult": {
"result": {
"location": "San Francisco",
"temperature": 72,
"weather": "cloudy",
"rain_prediction": 0.89
},
"isError": false,
"id": "call_lR2r0rpfqNX11jukJvEUdByv"
}
}
}
]
}
],
"llmEventEnd": [
{
"id": "PRESERVE_0",
"response": {
"raw": null,
"message": {
"content": "",
"role": "assistant",
"options": {
"toolCall": {
"id": "call_lR2r0rpfqNX11jukJvEUdByv",
"name": "get_weather",
"input": "{\"location\":\"San Francisco\"}"
}
}
}
}
},
{
"id": "PRESERVE_1",
"response": {
"raw": null,
"message": {
"content": "The weather in San Francisco is currently cloudy with a temperature of 72°F. There is a 89% chance of rain.",
"role": "assistant",
"options": {}
}
}
}
],
"llmEventStream": []
}
@@ -0,0 +1,103 @@
{
"llmEventStart": [
{
"id": "PRESERVE_0",
"messages": [
{
"content": "Please always use the tools provided to answer a question. Do not rely on prior knowledge.",
"role": "system"
},
{
"role": "user",
"content": "What's the summary of Alex? Does he live in Brazil based on the brief information? Return yes or no."
}
]
},
{
"id": "PRESERVE_1",
"messages": [
{
"content": "Context information is below.\n---------------------\nAlex is a male. What's very important, Alex is not in the Brazil.\n---------------------\nGiven the context information and not prior knowledge, answer the query.\nQuery: Alex\nAnswer:",
"role": "user"
}
]
},
{
"id": "PRESERVE_2",
"messages": [
{
"content": "Please always use the tools provided to answer a question. Do not rely on prior knowledge.",
"role": "system"
},
{
"role": "user",
"content": "What's the summary of Alex? Does he live in Brazil based on the brief information? Return yes or no."
},
{
"content": "",
"role": "assistant",
"options": {
"toolCall": {
"id": "call_EVThrsiOylO0p6ZmGdsA31x9",
"name": "summary_tool",
"input": "{\"query\": \"Alex\"}"
}
}
},
{
"content": "Alex is not in Brazil.",
"role": "user",
"options": {
"toolResult": {
"result": "Alex is not in Brazil.",
"isError": false,
"id": "call_EVThrsiOylO0p6ZmGdsA31x9"
}
}
}
]
}
],
"llmEventEnd": [
{
"id": "PRESERVE_0",
"response": {
"raw": null,
"message": {
"content": "",
"role": "assistant",
"options": {
"toolCall": {
"id": "call_EVThrsiOylO0p6ZmGdsA31x9",
"name": "summary_tool",
"input": "{\"query\": \"Alex\"}"
}
}
}
}
},
{
"id": "PRESERVE_1",
"response": {
"raw": null,
"message": {
"content": "Alex is not in Brazil.",
"role": "assistant",
"options": {}
}
}
},
{
"id": "PRESERVE_2",
"response": {
"raw": null,
"message": {
"content": "No, Alex does not live in Brazil based on the brief information available.",
"role": "assistant",
"options": {}
}
}
}
],
"llmEventStream": []
}
@@ -0,0 +1,83 @@
{
"llmEventStart": [
{
"id": "PRESERVE_0",
"messages": [
{
"content": "You are a pirate. You MUST speak every words staring with a 'Arhgs'",
"role": "system"
},
{
"role": "user",
"content": "What is the weather in San Francisco?"
}
]
},
{
"id": "PRESERVE_1",
"messages": [
{
"content": "You are a pirate. You MUST speak every words staring with a 'Arhgs'",
"role": "system"
},
{
"role": "user",
"content": "What is the weather in San Francisco?"
},
{
"content": "",
"role": "assistant",
"options": {
"toolCall": {
"id": "call_h4gSNrz7MhhkOod7W4WKZ1iZ",
"name": "getWeather",
"input": "{\"city\":\"San Francisco\"}"
}
}
},
{
"content": "The weather in San Francisco is 72 degrees",
"role": "user",
"options": {
"toolResult": {
"result": "The weather in San Francisco is 72 degrees",
"isError": false,
"id": "call_h4gSNrz7MhhkOod7W4WKZ1iZ"
}
}
}
]
}
],
"llmEventEnd": [
{
"id": "PRESERVE_0",
"response": {
"raw": null,
"message": {
"content": "",
"role": "assistant",
"options": {
"toolCall": {
"id": "call_h4gSNrz7MhhkOod7W4WKZ1iZ",
"name": "getWeather",
"input": "{\"city\":\"San Francisco\"}"
}
}
}
}
},
{
"id": "PRESERVE_1",
"response": {
"raw": null,
"message": {
"content": "Arhgs the weather in San Francisco be 72 degrees.",
"role": "assistant",
"options": {}
}
}
}
],
"llmEventStream": []
}
@@ -0,0 +1,63 @@
{
"llmEventStart": [
{
"id": "PRESERVE_0",
"messages": [
{
"role": "system",
"content": "You are designed to help with a variety of tasks, from answering questions to providing summaries to other types of analyses.\n\n## Tools\nYou have access to a wide variety of tools. You are responsible for using\nthe tools in any sequence you deem appropriate to complete the task at hand.\nThis may require breaking the task into subtasks and using different tools\nto complete each subtask.\n\nYou have access to the following tools:\n- getWeather: Get the weather for a city with schema: {\"type\":\"object\",\"properties\":{\"city\":{\"type\":\"string\",\"description\":\"The city to get the weather for\"}},\"required\":[\"city\"]}\n\n## Output Format\nTo answer the question, please use the following format.\n\n\"\"\"\nThought: I need to use a tool to help me answer the question.\nAction: tool name (one of getWeather) if using a tool.\nAction Input: the input to the tool, in a JSON format representing the kwargs (e.g. {{\"input\": \"hello world\", \"num_beams\": 5}})\n\"\"\"\n\nPlease ALWAYS start with a Thought.\n\nPlease use a valid JSON format for the Action Input. Do NOT do this {{'input': 'hello world', 'num_beams': 5}}.\n\nIf this format is used, the user will respond in the following format:\n\n\"\"\"\"\nObservation: tool response\n\"\"\"\"\n\nYou should keep repeating the above format until you have enough information\nto answer the question without using any more tools. At that point, you MUST respond\nin the one of the following two formats:\n\n\"\"\"\"\nThought: I can answer without using any more tools.\nAnswer: [your answer here]\n\"\"\"\"\n\n\"\"\"\"\nThought: I cannot answer the question with the provided tools.\nAnswer: Sorry, I cannot answer your query.\n\"\"\"\"\n\n## Current Conversation\nBelow is the current conversation consisting of interleaving human and assistant messages."
},
{
"role": "user",
"content": "What is the weather like in San Francisco?"
}
]
},
{
"id": "PRESERVE_1",
"messages": [
{
"role": "system",
"content": "You are designed to help with a variety of tasks, from answering questions to providing summaries to other types of analyses.\n\n## Tools\nYou have access to a wide variety of tools. You are responsible for using\nthe tools in any sequence you deem appropriate to complete the task at hand.\nThis may require breaking the task into subtasks and using different tools\nto complete each subtask.\n\nYou have access to the following tools:\n- getWeather: Get the weather for a city with schema: {\"type\":\"object\",\"properties\":{\"city\":{\"type\":\"string\",\"description\":\"The city to get the weather for\"}},\"required\":[\"city\"]}\n\n## Output Format\nTo answer the question, please use the following format.\n\n\"\"\"\nThought: I need to use a tool to help me answer the question.\nAction: tool name (one of getWeather) if using a tool.\nAction Input: the input to the tool, in a JSON format representing the kwargs (e.g. {{\"input\": \"hello world\", \"num_beams\": 5}})\n\"\"\"\n\nPlease ALWAYS start with a Thought.\n\nPlease use a valid JSON format for the Action Input. Do NOT do this {{'input': 'hello world', 'num_beams': 5}}.\n\nIf this format is used, the user will respond in the following format:\n\n\"\"\"\"\nObservation: tool response\n\"\"\"\"\n\nYou should keep repeating the above format until you have enough information\nto answer the question without using any more tools. At that point, you MUST respond\nin the one of the following two formats:\n\n\"\"\"\"\nThought: I can answer without using any more tools.\nAnswer: [your answer here]\n\"\"\"\"\n\n\"\"\"\"\nThought: I cannot answer the question with the provided tools.\nAnswer: Sorry, I cannot answer your query.\n\"\"\"\"\n\n## Current Conversation\nBelow is the current conversation consisting of interleaving human and assistant messages."
},
{
"role": "user",
"content": "What is the weather like in San Francisco?"
},
{
"role": "assistant",
"content": "Thought: I need to use a tool to help me answer the question.\nAction: getWeather\nInput: {\n city: San Francisco\n}"
},
{
"role": "user",
"content": "Observation: The weather in San Francisco is 72 degrees"
}
]
}
],
"llmEventEnd": [
{
"id": "PRESERVE_0",
"response": {
"raw": null,
"message": {
"content": "Thought: I need to use a tool to help me answer the question.\nAction: getWeather\nAction Input: {\"city\": \"San Francisco\"}",
"role": "assistant",
"options": {}
}
}
},
{
"id": "PRESERVE_1",
"response": {
"raw": null,
"message": {
"content": "Thought: I can answer without using any more tools.\nAnswer: The weather in San Francisco is 72 degrees.",
"role": "assistant",
"options": {}
}
}
}
],
"llmEventStream": []
}
+11 -8
View File
@@ -50,6 +50,11 @@ export async function mockLLMEvent(
...event.detail.payload,
// @ts-expect-error id is not UUID, but it is fine for testing
id: idMap.get(event.detail.payload.id)!,
response: {
...event.detail.payload.response,
// hide raw object since it might too big
raw: null,
},
});
}
@@ -58,6 +63,11 @@ export async function mockLLMEvent(
...event.detail.payload,
// @ts-expect-error id is not UUID, but it is fine for testing
id: idMap.get(event.detail.payload.id)!,
chunk: {
...event.detail.payload.chunk,
// hide raw object since it might too big
raw: null,
},
});
}
@@ -92,14 +102,7 @@ export async function mockLLMEvent(
Settings.callbackManager.off("llm-start", captureLLMStart);
// eslint-disable-next-line turbo/no-undeclared-env-vars
if (process.env.UPDATE_SNAPSHOT === "1") {
const data = JSON.stringify(newLLMCompleteMockStorage, null, 2)
.replace(/"id": "(?!PRESERVE_).*"/g, '"id": "HIDDEN"')
.replace(/"created": \d+/g, `"created": 114514`)
.replace(
/"system_fingerprint": ".*"/g,
'"system_fingerprint": "HIDDEN"',
)
.replace(/"tool_call_id": ".*"/g, '"tool_call_id": "HIDDEN"');
const data = JSON.stringify(newLLMCompleteMockStorage, null, 2);
await writeFile(
join(testRootDir, "snapshot", `${snapshotName}.snap`),
data,
+4 -7
View File
@@ -4,14 +4,11 @@
"outDir": "./lib",
"module": "node16",
"moduleResolution": "node16",
"target": "ESNext"
"target": "ESNext",
"lib": ["ES2022"],
"types": ["node"]
},
"include": [
"./**/*.ts",
"./mock-module.js",
"./mock-register.js",
"./fixtures"
],
"include": ["./node", "./mock-module.js", "./mock-register.js", "./fixtures"],
"references": [
{
"path": "../../core/tsconfig.json"
+18 -14
View File
@@ -1,38 +1,39 @@
{
"name": "llamaindex",
"version": "0.2.9",
"version": "0.2.12",
"expectedMinorVersion": "2",
"license": "MIT",
"type": "module",
"dependencies": {
"@anthropic-ai/sdk": "^0.20.4",
"@anthropic-ai/sdk": "^0.20.6",
"@aws-crypto/sha256-js": "^5.2.0",
"@datastax/astra-db-ts": "^0.1.4",
"@datastax/astra-db-ts": "^1.0.1",
"@google/generative-ai": "^0.8.0",
"@grpc/grpc-js": "^1.10.6",
"@llamaindex/cloud": "0.0.5",
"@llamaindex/env": "workspace:*",
"@mistralai/mistralai": "^0.1.3",
"@notionhq/client": "^2.2.15",
"@pinecone-database/pinecone": "^2.2.0",
"@qdrant/js-client-rest": "^1.8.2",
"@types/lodash": "^4.17.0",
"@types/node": "^20.12.7",
"@types/papaparse": "^5.3.14",
"@types/pg": "^8.11.5",
"@xenova/transformers": "^2.16.1",
"@zilliz/milvus2-sdk-node": "^2.3.5",
"@xenova/transformers": "^2.17.1",
"@zilliz/milvus2-sdk-node": "^2.4.1",
"ajv": "^8.12.0",
"assemblyai": "^4.3.4",
"assemblyai": "^4.4.1",
"chromadb": "~1.7.3",
"cohere-ai": "^7.9.3",
"js-tiktoken": "^1.0.10",
"cohere-ai": "^7.9.5",
"js-tiktoken": "^1.0.11",
"lodash": "^4.17.21",
"magic-bytes.js": "^1.10.0",
"mammoth": "^1.7.1",
"md-utils-ts": "^2.0.0",
"mongodb": "^6.5.0",
"notion-md-crawler": "^0.0.2",
"openai": "^4.33.0",
"notion-md-crawler": "^1.0.0",
"ollama": "^0.5.0",
"openai": "^4.38.0",
"papaparse": "^5.4.1",
"pathe": "^1.1.2",
"pdf2json": "^3.0.5",
@@ -40,17 +41,20 @@
"pgvector": "^0.1.8",
"portkey-ai": "^0.1.16",
"rake-modified": "^1.0.8",
"replicate": "^0.25.2",
"string-strip-html": "^13.4.8",
"wikipedia": "^2.1.2",
"wink-nlp": "^1.14.3"
},
"peerDependencies": {
"@notionhq/client": "^2.2.15"
},
"devDependencies": {
"@notionhq/client": "^2.2.15",
"@swc/cli": "^0.3.12",
"@swc/core": "^1.4.13",
"@swc/core": "^1.4.16",
"concurrently": "^8.2.2",
"glob": "^10.3.12",
"madge": "^6.1.0",
"madge": "^7.0.0",
"typescript": "^5.4.5"
},
"engines": {
+1 -1
View File
@@ -1,7 +1,7 @@
import { globalsHelper } from "./GlobalsHelper.js";
import type { SummaryPrompt } from "./Prompt.js";
import { defaultSummaryPrompt, messagesToHistoryStr } from "./Prompt.js";
import { OpenAI } from "./llm/open_ai.js";
import { OpenAI } from "./llm/openai.js";
import type { ChatMessage, LLM, MessageType } from "./llm/types.js";
import { extractText } from "./llm/utils.js";
+31
View File
@@ -326,6 +326,37 @@ export class ImageNode<T extends Metadata = Metadata> extends TextNode<T> {
const absPath = path.resolve(this.id_);
return new URL(`file://${absPath}`);
}
// Calculates the image part of the hash
private generateImageHash() {
const hashFunction = createSHA256();
if (this.image instanceof Blob) {
// TODO: ideally we should use the blob's content to calculate the hash:
// hashFunction.update(new Uint8Array(await this.image.arrayBuffer()));
// as this is async, we're using the node's ID for the time being
hashFunction.update(this.id_);
} else if (this.image instanceof URL) {
hashFunction.update(this.image.toString());
} else if (typeof this.image === "string") {
hashFunction.update(this.image);
} else {
throw new Error(
`Unknown image type: ${typeof this.image}. Can't calculate hash`,
);
}
return hashFunction.digest();
}
generateHash() {
const hashFunction = createSHA256();
// calculates hash based on hash of both components (image and text)
hashFunction.update(super.generateHash());
hashFunction.update(this.generateImageHash());
return hashFunction.digest();
}
}
export class ImageDocument<T extends Metadata = Metadata> extends ImageNode<T> {
+1 -1
View File
@@ -5,7 +5,7 @@ import type {
BaseQuestionGenerator,
SubQuestion,
} from "./engines/query/types.js";
import { OpenAI } from "./llm/open_ai.js";
import { OpenAI } from "./llm/openai.js";
import type { LLM } from "./llm/types.js";
import { PromptMixin } from "./prompts/index.js";
import type {
+1 -1
View File
@@ -1,7 +1,7 @@
import { PromptHelper } from "./PromptHelper.js";
import { OpenAIEmbedding } from "./embeddings/OpenAIEmbedding.js";
import type { BaseEmbedding } from "./embeddings/types.js";
import { OpenAI } from "./llm/open_ai.js";
import { OpenAI } from "./llm/openai.js";
import type { LLM } from "./llm/types.js";
import { SimpleNodeParser } from "./nodeParsers/SimpleNodeParser.js";
import type { NodeParser } from "./nodeParsers/types.js";
+1 -1
View File
@@ -1,6 +1,6 @@
import { CallbackManager } from "./callbacks/CallbackManager.js";
import { OpenAIEmbedding } from "./embeddings/OpenAIEmbedding.js";
import { OpenAI } from "./llm/open_ai.js";
import { OpenAI } from "./llm/openai.js";
import { PromptHelper } from "./PromptHelper.js";
import { SimpleNodeParser } from "./nodeParsers/SimpleNodeParser.js";
+73
View File
@@ -0,0 +1,73 @@
# Agent
> This is an internal code design document for the agent API.
>
> APIs are not exactly the same as the final version, but it is a good reference for what we are going to do.
Most of the agent logic is same with Python, but we have some changes to make it more suitable for JavaScript.
> https://github.com/run-llama/llama_index/tree/6b97753dec4a9c33b16c63a8333ddba3f49ec40f/docs/docs/module_guides/deploying/agents
## API Changes
### Classes changes
- Task: we don't have `Task` class in JS, we use `ReadableStream` instead.
- TaskStep: this is the step for each task run, includes like the input, the context, etc. This class will be used in taskHandler.
- TaskOutput: this is the output for each task run, includes like is last step, the output, etc.
### taskHandler
taskHandler is a function that takes a TaskStep and returns a TaskOutput.
```typescript
type TaskHandler = (step: TaskStep) => Promise<TaskOutput>;
```
### `createTask` to be AsyncGenerator
We use async generator to create task, since it's more suitable for JavaScript.
```typescript
const agent = new MyAgent();
const task = agent.createTask();
for await (const taskOutput of task) {
// do something
}
```
### `from_*` -> `from`
In python, there is `from_tools`, `from_defaults`... etc.
But in JS/TS, we normalize them to `from`, since we can do this way
using [function overloads](https://www.typescriptlang.org/docs/handbook/2/functions.html#function-overloads) in
TypeScript.
```typescript
class Agent {
from(tools: BaseTool[]): Agent;
from(defaults: Defaults): Agent;
from(toolsOrDefaults: BaseTool[] | Defaults): Agent {
// runtime check
}
}
```
### No sync method for chat/query method
Force all methods to be async, since the all LLMs returns Promise.
### Cancelable
Use `AbortController` to cancel the task.
```typescript
const controller = new AbortController();
const task = agent.createTask({ signal: controller.signal });
process.on("SIGINT", () => controller.abort());
for await (const taskOutput of task) {
// do something
}
```
+93 -139
View File
@@ -1,27 +1,23 @@
import { Settings } from "../Settings.js";
import {
AgentChatResponse,
type ChatEngineParamsNonStreaming,
type ChatEngineParamsStreaming,
} from "../engines/chat/index.js";
import { wrapEventCaller } from "../internal/context/EventCaller.js";
import { getCallbackManager } from "../internal/settings/CallbackManager.js";
import { prettifyError } from "../internal/utils.js";
import { stringifyJSONToMessageContent } from "../internal/utils.js";
import { Anthropic } from "../llm/anthropic.js";
import type {
ChatMessage,
ChatResponse,
ToolCallLLMMessageOptions,
} from "../llm/index.js";
import { extractText } from "../llm/utils.js";
import type { ToolCallLLMMessageOptions } from "../llm/index.js";
import { ObjectRetriever } from "../objects/index.js";
import type { BaseToolWithCall } from "../types.js";
import {
AgentRunner,
AgentWorker,
type AgentChatResponse,
type AgentParamsBase,
type TaskHandler,
} from "./base.js";
import { callTool } from "./utils.js";
const MAX_TOOL_CALLS = 10;
type AnthropicParamsBase = {
llm?: Anthropic;
chatHistory?: ChatMessage<ToolCallLLMMessageOptions>[];
};
type AnthropicParamsBase = AgentParamsBase<Anthropic>;
type AnthropicParamsWithTools = AnthropicParamsBase & {
tools: BaseToolWithCall[];
@@ -35,136 +31,94 @@ export type AnthropicAgentParams =
| AnthropicParamsWithTools
| AnthropicParamsWithToolRetriever;
type AgentContext = {
toolCalls: number;
llm: Anthropic;
tools: BaseToolWithCall[];
messages: ChatMessage<ToolCallLLMMessageOptions>[];
shouldContinue: (context: AgentContext) => boolean;
};
type TaskResult = {
response: ChatResponse<ToolCallLLMMessageOptions>;
chatHistory: ChatMessage<ToolCallLLMMessageOptions>[];
};
async function task(
context: AgentContext,
input: ChatMessage<ToolCallLLMMessageOptions>,
): Promise<TaskResult> {
const { llm, tools, messages } = context;
const nextMessages: ChatMessage<ToolCallLLMMessageOptions>[] = [
...messages,
input,
];
const response = await llm.chat({
stream: false,
tools,
messages: nextMessages,
});
const options = response.message.options ?? {};
if ("toolCall" in options) {
const { toolCall } = options;
const { input, name, id } = toolCall;
const targetTool = tools.find((tool) => tool.metadata.name === name);
let output: string;
let isError = true;
if (!context.shouldContinue(context)) {
output = "Error: Tool call limit reached";
} else if (!targetTool) {
output = `Error: Tool ${name} not found`;
} else {
try {
getCallbackManager().dispatchEvent("llm-tool-call", {
payload: {
toolCall: {
name,
input,
},
},
});
output = await targetTool.call(input);
isError = false;
} catch (error: unknown) {
output = prettifyError(error);
}
}
return task(
{
...context,
toolCalls: context.toolCalls + 1,
messages: [...nextMessages, response.message],
},
{
content: output,
role: "user",
options: {
toolResult: {
isError,
id,
},
},
},
);
} else {
return { response, chatHistory: [...nextMessages, response.message] };
}
export class AnthropicAgentWorker extends AgentWorker<Anthropic> {
taskHandler = AnthropicAgent.taskHandler;
}
export class AnthropicAgent {
readonly #llm: Anthropic;
readonly #tools:
| BaseToolWithCall[]
| ((query: string) => Promise<BaseToolWithCall[]>) = [];
#chatHistory: ChatMessage<ToolCallLLMMessageOptions>[] = [];
export class AnthropicAgent extends AgentRunner<Anthropic> {
constructor(params: AnthropicAgentParams) {
this.#llm =
params.llm ?? Settings.llm instanceof Anthropic
? (Settings.llm as Anthropic)
: new Anthropic();
if ("tools" in params) {
this.#tools = params.tools;
} else if ("toolRetriever" in params) {
this.#tools = params.toolRetriever.retrieve.bind(params.toolRetriever);
}
if (Array.isArray(params.chatHistory)) {
this.#chatHistory = params.chatHistory;
}
super({
llm:
params.llm ?? Settings.llm instanceof Anthropic
? (Settings.llm as Anthropic)
: new Anthropic(),
chatHistory: params.chatHistory ?? [],
systemPrompt: params.systemPrompt ?? null,
runner: new AnthropicAgentWorker(),
tools:
"tools" in params
? params.tools
: params.toolRetriever.retrieve.bind(params.toolRetriever),
});
}
static shouldContinue(context: AgentContext): boolean {
return context.toolCalls < MAX_TOOL_CALLS;
}
createStore = AgentRunner.defaultCreateStore;
public reset(): void {
this.#chatHistory = [];
}
getTools(query: string): Promise<BaseToolWithCall[]> | BaseToolWithCall[] {
return typeof this.#tools === "function" ? this.#tools(query) : this.#tools;
}
@wrapEventCaller
async chat(
params: ChatEngineParamsNonStreaming,
): Promise<Promise<AgentChatResponse>> {
const { chatHistory, response } = await task(
{
llm: this.#llm,
tools: await this.getTools(extractText(params.message)),
toolCalls: 0,
messages: [...this.#chatHistory],
// do we need this?
shouldContinue: AnthropicAgent.shouldContinue,
},
{
role: "user",
content: params.message,
options: {},
},
);
this.#chatHistory = [...chatHistory];
return new AgentChatResponse(extractText(response.message.content));
): Promise<AgentChatResponse<ToolCallLLMMessageOptions>>;
async chat(params: ChatEngineParamsStreaming): Promise<never>;
override async chat(
params: ChatEngineParamsNonStreaming | ChatEngineParamsStreaming,
) {
if (params.stream) {
throw new Error("Anthropic does not support streaming");
}
return super.chat(params);
}
static taskHandler: TaskHandler<Anthropic> = async (step) => {
const { input } = step;
const { llm, getTools, stream } = step.context;
if (input) {
step.context.store.messages = [...step.context.store.messages, input];
}
const lastMessage = step.context.store.messages.at(-1)!.content;
const tools = await getTools(lastMessage);
if (stream === true) {
throw new Error("Anthropic does not support streaming");
}
const response = await llm.chat({
stream,
tools,
messages: step.context.store.messages,
});
step.context.store.messages = [
...step.context.store.messages,
response.message,
];
const options = response.message.options ?? {};
if ("toolCall" in options) {
const { toolCall } = options;
const targetTool = tools.find(
(tool) => tool.metadata.name === toolCall.name,
);
const toolOutput = await callTool(targetTool, toolCall);
step.context.store.toolOutputs.push(toolOutput);
return {
taskStep: step,
output: {
raw: response.raw,
message: {
content: stringifyJSONToMessageContent(toolOutput.output),
role: "user",
options: {
toolResult: {
result: toolOutput.output,
isError: toolOutput.isError,
id: toolCall.id,
},
},
},
},
isLast: false,
};
} else {
return {
taskStep: step,
output: response,
isLast: true,
};
}
};
}
+430
View File
@@ -0,0 +1,430 @@
import { pipeline, randomUUID } from "@llamaindex/env";
import {
type ChatEngine,
type ChatEngineParamsNonStreaming,
type ChatEngineParamsStreaming,
} from "../engines/chat/index.js";
import { wrapEventCaller } from "../internal/context/EventCaller.js";
import { getCallbackManager } from "../internal/settings/CallbackManager.js";
import { isAsyncIterable } from "../internal/utils.js";
import type {
ChatMessage,
ChatResponse,
ChatResponseChunk,
LLM,
MessageContent,
} from "../llm/index.js";
import { extractText } from "../llm/utils.js";
import type { BaseToolWithCall, ToolOutput, UUID } from "../types.js";
import { consumeAsyncIterable } from "./utils.js";
export const MAX_TOOL_CALLS = 10;
export type AgentTaskContext<
Model extends LLM,
Store extends object = {},
AdditionalMessageOptions extends object = Model extends LLM<
object,
infer AdditionalMessageOptions
>
? AdditionalMessageOptions
: never,
> = {
readonly stream: boolean;
readonly toolCallCount: number;
readonly llm: Model;
readonly getTools: (
input: MessageContent,
) => BaseToolWithCall[] | Promise<BaseToolWithCall[]>;
shouldContinue: (
taskStep: Readonly<TaskStep<Model, Store, AdditionalMessageOptions>>,
) => boolean;
store: {
toolOutputs: ToolOutput[];
messages: ChatMessage<AdditionalMessageOptions>[];
} & Store;
};
export type TaskStep<
Model extends LLM,
Store extends object = {},
AdditionalMessageOptions extends object = Model extends LLM<
object,
infer AdditionalMessageOptions
>
? AdditionalMessageOptions
: never,
> = {
id: UUID;
input: ChatMessage<AdditionalMessageOptions> | null;
context: AgentTaskContext<Model, Store, AdditionalMessageOptions>;
// linked list
prevStep: TaskStep<Model, Store, AdditionalMessageOptions> | null;
nextSteps: Set<TaskStep<Model, Store, AdditionalMessageOptions>>;
};
export type TaskStepOutput<
Model extends LLM,
Store extends object = {},
AdditionalMessageOptions extends object = Model extends LLM<
object,
infer AdditionalMessageOptions
>
? AdditionalMessageOptions
: never,
> =
| {
taskStep: TaskStep<Model, Store, AdditionalMessageOptions>;
output:
| null
| ChatResponse<AdditionalMessageOptions>
| ReadableStream<ChatResponseChunk<AdditionalMessageOptions>>;
isLast: false;
}
| {
taskStep: TaskStep<Model, Store, AdditionalMessageOptions>;
output:
| ChatResponse<AdditionalMessageOptions>
| ReadableStream<ChatResponseChunk<AdditionalMessageOptions>>;
isLast: true;
};
export type TaskHandler<
Model extends LLM,
Store extends object = {},
AdditionalMessageOptions extends object = Model extends LLM<
object,
infer AdditionalMessageOptions
>
? AdditionalMessageOptions
: never,
> = (
step: TaskStep<Model, Store, AdditionalMessageOptions>,
) => Promise<TaskStepOutput<Model, Store, AdditionalMessageOptions>>;
/**
* @internal
*/
export async function* createTaskImpl<
Model extends LLM,
Store extends object = {},
AdditionalMessageOptions extends object = Model extends LLM<
object,
infer AdditionalMessageOptions
>
? AdditionalMessageOptions
: never,
>(
handler: TaskHandler<Model, Store, AdditionalMessageOptions>,
context: AgentTaskContext<Model, Store, AdditionalMessageOptions>,
_input: ChatMessage<AdditionalMessageOptions>,
): AsyncGenerator<TaskStepOutput<Model, Store, AdditionalMessageOptions>> {
let isDone = false;
let input: ChatMessage<AdditionalMessageOptions> | null = _input;
let prevStep: TaskStep<Model, Store, AdditionalMessageOptions> | null = null;
while (!isDone) {
const step: TaskStep<Model, Store, AdditionalMessageOptions> = {
id: randomUUID(),
input,
context,
prevStep,
nextSteps: new Set(),
};
if (prevStep) {
prevStep.nextSteps.add(step);
}
const prevToolCallCount = step.context.toolCallCount;
if (!step.context.shouldContinue(step)) {
throw new Error("Tool call count exceeded limit");
}
getCallbackManager().dispatchEvent("agent-start", {
payload: {},
});
const taskOutput = await handler(step);
const { isLast, output, taskStep } = taskOutput;
// do not consume last output
if (!isLast) {
if (output) {
input = isAsyncIterable(output)
? await consumeAsyncIterable(output)
: output.message;
} else {
input = null;
}
}
context = {
...taskStep.context,
store: {
...taskStep.context.store,
},
toolCallCount: prevToolCallCount + 1,
};
if (isLast) {
isDone = true;
getCallbackManager().dispatchEvent("agent-end", {
payload: {},
});
}
prevStep = taskStep;
yield taskOutput;
}
}
export type AgentStreamChatResponse<Options extends object> = {
response: ChatResponseChunk<Options>;
// sources of the response, will emit when new tool outputs are available
sources?: ToolOutput[];
};
export type AgentChatResponse<Options extends object> = {
response: ChatResponse<Options>;
sources: ToolOutput[];
};
export type AgentRunnerParams<
AI extends LLM,
Store extends object = {},
AdditionalMessageOptions extends object = AI extends LLM<
object,
infer AdditionalMessageOptions
>
? AdditionalMessageOptions
: never,
> = {
llm: AI;
chatHistory: ChatMessage<AdditionalMessageOptions>[];
systemPrompt: MessageContent | null;
runner: AgentWorker<AI, Store, AdditionalMessageOptions>;
tools:
| BaseToolWithCall[]
| ((query: MessageContent) => Promise<BaseToolWithCall[]>);
};
export type AgentParamsBase<
AI extends LLM,
AdditionalMessageOptions extends object = AI extends LLM<
object,
infer AdditionalMessageOptions
>
? AdditionalMessageOptions
: never,
> = {
llm?: AI;
chatHistory?: ChatMessage<AdditionalMessageOptions>[];
systemPrompt?: MessageContent;
};
/**
* Worker will schedule tasks and handle the task execution
*/
export abstract class AgentWorker<
AI extends LLM,
Store extends object = {},
AdditionalMessageOptions extends object = AI extends LLM<
object,
infer AdditionalMessageOptions
>
? AdditionalMessageOptions
: never,
> {
#taskSet = new Set<TaskStep<AI, Store, AdditionalMessageOptions>>();
abstract taskHandler: TaskHandler<AI, Store, AdditionalMessageOptions>;
public createTask(
query: string,
context: AgentTaskContext<AI, Store, AdditionalMessageOptions>,
): ReadableStream<TaskStepOutput<AI, Store, AdditionalMessageOptions>> {
const taskGenerator = createTaskImpl(this.taskHandler, context, {
role: "user",
content: query,
});
return new ReadableStream<
TaskStepOutput<AI, Store, AdditionalMessageOptions>
>({
start: async (controller) => {
for await (const stepOutput of taskGenerator) {
this.#taskSet.add(stepOutput.taskStep);
controller.enqueue(stepOutput);
if (stepOutput.isLast) {
let currentStep: TaskStep<
AI,
Store,
AdditionalMessageOptions
> | null = stepOutput.taskStep;
while (currentStep) {
this.#taskSet.delete(currentStep);
currentStep = currentStep.prevStep;
}
controller.close();
}
}
},
});
}
[Symbol.toStringTag] = "AgentWorker";
}
/**
* Runner will manage the task execution and provide a high-level API for the user
*/
export abstract class AgentRunner<
AI extends LLM,
Store extends object = {},
AdditionalMessageOptions extends object = AI extends LLM<
object,
infer AdditionalMessageOptions
>
? AdditionalMessageOptions
: never,
> implements
ChatEngine<
AgentChatResponse<AdditionalMessageOptions>,
ReadableStream<AgentStreamChatResponse<AdditionalMessageOptions>>
>
{
readonly #llm: AI;
readonly #tools:
| BaseToolWithCall[]
| ((query: MessageContent) => Promise<BaseToolWithCall[]>);
readonly #systemPrompt: MessageContent | null = null;
#chatHistory: ChatMessage<AdditionalMessageOptions>[];
readonly #runner: AgentWorker<AI, Store, AdditionalMessageOptions>;
// create extra store
abstract createStore(): Store;
static defaultCreateStore(): object {
return Object.create(null);
}
protected constructor(
params: AgentRunnerParams<AI, Store, AdditionalMessageOptions>,
) {
const { llm, chatHistory, runner, tools } = params;
this.#llm = llm;
this.#chatHistory = chatHistory;
this.#runner = runner;
if (params.systemPrompt) {
this.#systemPrompt = params.systemPrompt;
}
this.#tools = tools;
}
get llm() {
return this.#llm;
}
get chatHistory(): ChatMessage<AdditionalMessageOptions>[] {
return this.#chatHistory;
}
public reset(): void {
this.#chatHistory = [];
}
public getTools(
query: MessageContent,
): Promise<BaseToolWithCall[]> | BaseToolWithCall[] {
return typeof this.#tools === "function" ? this.#tools(query) : this.#tools;
}
static shouldContinue<
AI extends LLM,
Store extends object = {},
AdditionalMessageOptions extends object = AI extends LLM<
object,
infer AdditionalMessageOptions
>
? AdditionalMessageOptions
: never,
>(task: Readonly<TaskStep<AI, Store, AdditionalMessageOptions>>): boolean {
return task.context.toolCallCount < MAX_TOOL_CALLS;
}
// fixme: this shouldn't be async
async createTask(message: MessageContent, stream: boolean = false) {
const initialMessages = [...this.#chatHistory];
if (this.#systemPrompt !== null) {
const systemPrompt = this.#systemPrompt;
const alreadyHasSystemPrompt = initialMessages
.filter((msg) => msg.role === "system")
.some((msg) => Object.is(msg.content, systemPrompt));
if (!alreadyHasSystemPrompt) {
initialMessages.push({
content: systemPrompt,
role: "system",
});
}
}
return this.#runner.createTask(extractText(message), {
stream,
toolCallCount: 0,
llm: this.#llm,
getTools: (message) => this.getTools(message),
store: {
...this.createStore(),
messages: initialMessages,
toolOutputs: [] as ToolOutput[],
},
shouldContinue: AgentRunner.shouldContinue,
});
}
async chat(
params: ChatEngineParamsNonStreaming,
): Promise<AgentChatResponse<AdditionalMessageOptions>>;
async chat(
params: ChatEngineParamsStreaming,
): Promise<ReadableStream<AgentStreamChatResponse<AdditionalMessageOptions>>>;
@wrapEventCaller
async chat(
params: ChatEngineParamsNonStreaming | ChatEngineParamsStreaming,
): Promise<
| AgentChatResponse<AdditionalMessageOptions>
| ReadableStream<AgentStreamChatResponse<AdditionalMessageOptions>>
> {
const task = await this.createTask(params.message, !!params.stream);
const stepOutput = await pipeline(
task,
async (
iter: AsyncIterable<
TaskStepOutput<AI, Store, AdditionalMessageOptions>
>,
) => {
for await (const stepOutput of iter) {
if (stepOutput.isLast) {
return stepOutput;
}
}
throw new Error("Task did not complete");
},
);
const { output, taskStep } = stepOutput;
this.#chatHistory = [...taskStep.context.store.messages];
if (isAsyncIterable(output)) {
return output.pipeThrough<
AgentStreamChatResponse<AdditionalMessageOptions>
>(
new TransformStream({
transform(chunk, controller) {
controller.enqueue({
response: chunk,
get sources() {
return [...taskStep.context.store.toolOutputs];
},
});
},
}),
);
} else {
return {
response: output,
get sources() {
return [...taskStep.context.store.toolOutputs];
},
} satisfies AgentChatResponse<AdditionalMessageOptions>;
}
}
}
+18 -7
View File
@@ -1,7 +1,18 @@
// Not exporting the AnthropicAgent because it is not ready to ship yet.
// export { AnthropicAgent, type AnthropicAgentParams } from "./anthropic.js";
export * from "./openai/base.js";
export * from "./openai/worker.js";
export * from "./react/base.js";
export * from "./react/worker.js";
export * from "./types.js";
export {
AnthropicAgent,
AnthropicAgentWorker,
type AnthropicAgentParams,
} from "./anthropic.js";
export {
OpenAIAgent,
OpenAIAgentWorker,
type OpenAIAgentParams,
} from "./openai.js";
export {
ReACTAgentWorker,
ReActAgent,
type ReACTAgentParams,
} from "./react.js";
// todo: ParallelAgent
// todo: CustomAgent
// todo: ReactMultiModal
+195
View File
@@ -0,0 +1,195 @@
import { pipeline } from "@llamaindex/env";
import { Settings } from "../Settings.js";
import { stringifyJSONToMessageContent } from "../internal/utils.js";
import type {
ChatResponseChunk,
ToolCall,
ToolCallLLMMessageOptions,
} from "../llm/index.js";
import { OpenAI } from "../llm/openai.js";
import { ObjectRetriever } from "../objects/index.js";
import type { BaseToolWithCall } from "../types.js";
import {
AgentRunner,
AgentWorker,
type AgentParamsBase,
type TaskHandler,
} from "./base.js";
import { callTool } from "./utils.js";
type OpenAIParamsBase = AgentParamsBase<OpenAI>;
type OpenAIParamsWithTools = OpenAIParamsBase & {
tools: BaseToolWithCall[];
};
type OpenAIParamsWithToolRetriever = OpenAIParamsBase & {
toolRetriever: ObjectRetriever<BaseToolWithCall>;
};
export type OpenAIAgentParams =
| OpenAIParamsWithTools
| OpenAIParamsWithToolRetriever;
export class OpenAIAgentWorker extends AgentWorker<OpenAI> {
taskHandler = OpenAIAgent.taskHandler;
}
export class OpenAIAgent extends AgentRunner<OpenAI> {
constructor(params: OpenAIAgentParams) {
super({
llm:
params.llm ?? Settings.llm instanceof OpenAI
? (Settings.llm as OpenAI)
: new OpenAI(),
chatHistory: params.chatHistory ?? [],
runner: new OpenAIAgentWorker(),
systemPrompt: params.systemPrompt ?? null,
tools:
"tools" in params
? params.tools
: params.toolRetriever.retrieve.bind(params.toolRetriever),
});
}
createStore = AgentRunner.defaultCreateStore;
static taskHandler: TaskHandler<OpenAI> = async (step) => {
const { input } = step;
const { llm, stream, getTools } = step.context;
if (input) {
step.context.store.messages = [...step.context.store.messages, input];
}
const lastMessage = step.context.store.messages.at(-1)!.content;
const tools = await getTools(lastMessage);
const response = await llm.chat({
// @ts-expect-error
stream,
tools,
messages: [...step.context.store.messages],
});
if (!stream) {
step.context.store.messages = [
...step.context.store.messages,
response.message,
];
const options = response.message.options ?? {};
if ("toolCall" in options) {
const { toolCall } = options;
const targetTool = tools.find(
(tool) => tool.metadata.name === toolCall.name,
);
const toolOutput = await callTool(targetTool, toolCall);
step.context.store.toolOutputs.push(toolOutput);
return {
taskStep: step,
output: {
raw: response.raw,
message: {
content: stringifyJSONToMessageContent(toolOutput.output),
role: "user",
options: {
toolResult: {
result: toolOutput.output,
isError: toolOutput.isError,
id: toolCall.id,
},
},
},
},
isLast: false,
};
} else {
return {
taskStep: step,
output: response,
isLast: true,
};
}
} else {
const responseChunkStream = new ReadableStream<
ChatResponseChunk<ToolCallLLMMessageOptions>
>({
async start(controller) {
for await (const chunk of response) {
controller.enqueue(chunk);
}
controller.close();
},
});
const [pipStream, finalStream] = responseChunkStream.tee();
const reader = pipStream.getReader();
const { value } = await reader.read();
reader.releaseLock();
if (value === undefined) {
throw new Error(
"first chunk value is undefined, this should not happen",
);
}
// check if first chunk has tool calls, if so, this is a function call
// otherwise, it's a regular message
const hasToolCall = !!(value.options && "toolCall" in value.options);
if (hasToolCall) {
// you need to consume the response to get the full toolCalls
const toolCalls = await pipeline(
pipStream,
async (
iter: AsyncIterable<ChatResponseChunk<ToolCallLLMMessageOptions>>,
) => {
const toolCalls = new Map<string, ToolCall>();
for await (const chunk of iter) {
if (chunk.options && "toolCall" in chunk.options) {
const toolCall = chunk.options.toolCall;
toolCalls.set(toolCall.id, toolCall);
}
}
return [...toolCalls.values()];
},
);
for (const toolCall of toolCalls) {
const targetTool = tools.find(
(tool) => tool.metadata.name === toolCall.name,
);
step.context.store.messages = [
...step.context.store.messages,
{
role: "assistant" as const,
content: "",
options: {
toolCall,
},
},
];
const toolOutput = await callTool(targetTool, toolCall);
step.context.store.messages = [
...step.context.store.messages,
{
role: "user" as const,
content: stringifyJSONToMessageContent(toolOutput.output),
options: {
toolResult: {
result: toolOutput.output,
isError: toolOutput.isError,
id: toolCall.id,
},
},
},
];
step.context.store.toolOutputs.push(toolOutput);
}
return {
taskStep: step,
output: null,
isLast: false,
};
} else {
return {
taskStep: step,
output: finalStream,
isLast: true,
};
}
}
};
}
-80
View File
@@ -1,80 +0,0 @@
import { Settings } from "../../Settings.js";
import type { ChatMessage } from "../../llm/index.js";
import { OpenAI } from "../../llm/index.js";
import type { BaseMemory } from "../../memory/types.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[];
llm?: OpenAI;
memory?: BaseMemory;
prefixMessages?: ChatMessage[];
maxFunctionCalls?: number;
defaultToolChoice?: string;
toolRetriever?: ObjectRetriever<BaseTool>;
systemPrompt?: string;
};
/**
* An agent that uses OpenAI's API to generate text.
*
* @category OpenAI
*/
export class OpenAIAgent extends AgentRunner {
constructor({
tools,
llm,
memory,
prefixMessages,
maxFunctionCalls = 5,
defaultToolChoice = "auto",
toolRetriever,
systemPrompt,
}: OpenAIAgentParams) {
if (!llm) {
if (Settings.llm instanceof OpenAI) {
llm = Settings.llm;
} else {
console.warn("No OpenAI model provided, creating a new one");
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?.supportToolCall) {
throw new Error("LLM model must be a function-calling model");
}
const stepEngine = new OpenAIAgentWorker({
tools,
llm,
prefixMessages,
maxFunctionCalls,
toolRetriever,
});
super({
agentWorker: stepEngine,
llm,
memory,
defaultToolChoice,
// @ts-expect-error 2322
chatHistory: prefixMessages,
});
}
}
@@ -1,13 +0,0 @@
export type OpenAIToolCall = ChatCompletionMessageToolCall;
export interface Function {
arguments: string;
name: string;
type: "function";
}
export interface ChatCompletionMessageToolCall {
id: string;
function: Function;
type: "function";
}
-397
View File
@@ -1,397 +0,0 @@
import { pipeline, randomUUID } from "@llamaindex/env";
import type { ChatCompletionToolChoiceOption } from "openai/resources/chat/completions";
import { Response } from "../../Response.js";
import { Settings } from "../../Settings.js";
import {
AgentChatResponse,
ChatResponseMode,
StreamingAgentChatResponse,
} from "../../engines/chat/types.js";
import {
OpenAI,
isFunctionCallingModel,
type ChatMessage,
type ChatResponseChunk,
type LLMChatParamsBase,
type OpenAIAdditionalChatOptions,
type ToolCallLLMMessageOptions,
type ToolCallOptions,
} from "../../llm/index.js";
import { extractText } from "../../llm/utils.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";
async function callFunction(
tools: BaseTool[],
toolCall: ToolCallOptions["toolCall"],
): Promise<[ChatMessage<ToolCallLLMMessageOptions>, ToolOutput]> {
const id = toolCall.id;
const name = toolCall.name;
const input = toolCall.input;
if (Settings.debug) {
console.log("=== Calling Function ===");
console.log(`Calling function: ${name} with args: ${input}`);
}
const tool = getFunctionByName(tools, name);
// Call tool
// Use default error message
const output = await callToolWithErrorHandling(tool, input);
if (Settings.debug) {
console.log(`Got output ${output}`);
console.log("==========================");
}
return [
{
content: `${output}`,
role: "user",
options: {
toolResult: {
id,
isError: false,
},
},
},
output,
];
}
type OpenAIAgentWorkerParams = {
tools?: BaseTool[];
llm?: OpenAI;
prefixMessages?: ChatMessage[];
maxFunctionCalls?: number;
toolRetriever?: ObjectRetriever<BaseTool>;
};
type CallFunctionOutput = {
message: ChatMessage;
toolOutput: ToolOutput;
};
export class OpenAIAgentWorker
implements AgentWorker<LLMChatParamsBase<OpenAIAdditionalChatOptions>>
{
private llm: OpenAI;
private maxFunctionCalls: number = 5;
public prefixMessages: ChatMessage[];
private _getTools: (input: string) => Promise<BaseTool[]>;
constructor({
tools = [],
llm,
prefixMessages,
maxFunctionCalls,
toolRetriever,
}: OpenAIAgentWorkerParams) {
this.llm =
llm ?? isFunctionCallingModel(Settings.llm)
? (Settings.llm as OpenAI)
: new OpenAI({
model: "gpt-3.5-turbo-0613",
});
if (maxFunctionCalls) {
this.maxFunctionCalls = maxFunctionCalls;
}
this.prefixMessages = prefixMessages || [];
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) {
// fixme: this won't work, type mismatch
this._getTools = async (message: string) =>
toolRetriever.retrieve(message);
} else {
this._getTools = async () => [];
}
}
public getAllMessages(task: Task): ChatMessage<ToolCallLLMMessageOptions>[] {
return [
...this.prefixMessages,
...task.memory.get(),
...task.extraState.newMemory.get(),
];
}
public getLatestToolCall(task: Task): ToolCallOptions["toolCall"] | null {
const chatHistory: ChatMessage[] = task.extraState.newMemory.getAll();
if (chatHistory.length === 0) {
return null;
}
// @ts-expect-error fixme
return chatHistory[chatHistory.length - 1].options?.toolCall;
}
private _getLlmChatParams(
task: Task,
tools: BaseTool[],
toolChoice: ChatCompletionToolChoiceOption = "auto",
): LLMChatParamsBase<OpenAIAdditionalChatOptions, ToolCallLLMMessageOptions> {
const llmChatParams = {
messages: this.getAllMessages(task),
tools: undefined as BaseTool[] | undefined,
additionalChatOptions: {} as OpenAIAdditionalChatOptions,
} satisfies LLMChatParamsBase<
OpenAIAdditionalChatOptions,
ToolCallLLMMessageOptions
>;
if (tools.length > 0) {
llmChatParams.tools = tools;
llmChatParams.additionalChatOptions.tool_choice = toolChoice;
}
return llmChatParams;
}
private _processMessage(
task: Task,
aiMessage: ChatMessage,
): AgentChatResponse {
task.extraState.newMemory.put(aiMessage);
return new AgentChatResponse(
extractText(aiMessage.content),
task.extraState.sources,
);
}
private async _getStreamAiResponse(
task: Task,
llmChatParams: LLMChatParamsBase<
OpenAIAdditionalChatOptions,
ToolCallLLMMessageOptions
>,
): Promise<StreamingAgentChatResponse | AgentChatResponse> {
const stream = await this.llm.chat({
stream: true,
...llmChatParams,
});
const responseChunkStream = new ReadableStream<
ChatResponseChunk<ToolCallLLMMessageOptions>
>({
async start(controller) {
for await (const chunk of stream) {
controller.enqueue(chunk);
}
controller.close();
},
});
const [pipStream, finalStream] = responseChunkStream.tee();
const reader = pipStream.getReader();
const { value } = await reader.read();
reader.releaseLock();
if (value === undefined) {
throw new Error("first chunk value is undefined, this should not happen");
}
// check if first chunk has tool calls, if so, this is a function call
// otherwise, it's a regular message
const hasToolCall: boolean = !!(
value.options && "toolCall" in value.options
);
if (hasToolCall) {
return this._processMessage(task, {
content: await pipeline(finalStream, async (iterator) => {
let content = "";
for await (const value of iterator) {
content += value.delta;
}
return content;
}),
role: "assistant",
options: value.options,
});
} else {
const [responseStream, chunkStream] = finalStream.tee();
let content = "";
return new StreamingAgentChatResponse(
responseStream.pipeThrough<Response>({
readable: new ReadableStream({
async start(controller) {
for await (const chunk of chunkStream) {
controller.enqueue(new Response(chunk.delta));
}
controller.close();
},
}),
writable: new WritableStream({
write(chunk) {
content += chunk.delta;
},
close() {
task.extraState.newMemory.put({
content,
role: "assistant",
});
},
}),
}),
task.extraState.sources,
);
}
}
private async _getAgentResponse(
task: Task,
mode: ChatResponseMode,
llmChatParams: LLMChatParamsBase<
OpenAIAdditionalChatOptions,
ToolCallLLMMessageOptions
>,
): Promise<AgentChatResponse | StreamingAgentChatResponse> {
if (mode === ChatResponseMode.WAIT) {
const chatResponse = await this.llm.chat({
stream: false,
...llmChatParams,
});
return this._processMessage(
task,
chatResponse.message,
) as AgentChatResponse;
} else if (mode === ChatResponseMode.STREAM) {
return this._getStreamAiResponse(task, llmChatParams);
}
throw new Error("Invalid mode");
}
async callFunction(
tools: BaseTool[],
toolCall: ToolCallOptions["toolCall"],
): Promise<CallFunctionOutput> {
const functionMessage = await callFunction(tools, toolCall);
const message = functionMessage[0];
const toolOutput = functionMessage[1];
return {
message,
toolOutput,
};
}
initializeStep(task: Task): TaskStep {
const sources: ToolOutput[] = [];
const newMemory = new ChatMemoryBuffer({
tokenLimit: task.memory.tokenLimit,
});
const taskState = {
sources,
nFunctionCalls: 0,
newMemory,
};
task.extraState = {
...task.extraState,
...taskState,
};
return new TaskStep(task.taskId, randomUUID(), task.input);
}
private _shouldContinue(
toolCall: ToolCallOptions["toolCall"] | null,
nFunctionCalls: number,
): toolCall is ToolCallOptions["toolCall"] {
if (nFunctionCalls > this.maxFunctionCalls) {
return false;
}
return !!toolCall;
}
async getTools(input: string): Promise<BaseTool[]> {
return this._getTools(input);
}
private async _runStep(
step: TaskStep,
task: Task,
mode: ChatResponseMode = ChatResponseMode.WAIT,
toolChoice: ChatCompletionToolChoiceOption = "auto",
): Promise<TaskStepOutput> {
const tools = await this.getTools(task.input);
if (step.input) {
addUserStepToMemory(step, task.extraState.newMemory);
}
const llmChatParams = this._getLlmChatParams(task, tools, toolChoice);
const agentChatResponse = await this._getAgentResponse(
task,
mode,
llmChatParams,
);
const latestToolCall = this.getLatestToolCall(task) ?? null;
let isDone: boolean;
let newSteps: TaskStep[];
if (!this._shouldContinue(latestToolCall, task.extraState.nFunctionCalls)) {
isDone = true;
newSteps = [];
} else {
isDone = false;
const { message, toolOutput } = await this.callFunction(
tools,
latestToolCall,
);
task.extraState.sources.push(toolOutput);
task.extraState.newMemory.put(message);
task.extraState.nFunctionCalls += 1;
newSteps = [step.getNextStep(randomUUID(), undefined)];
}
return new TaskStepOutput(agentChatResponse, step, newSteps, isDone);
}
async runStep(
step: TaskStep,
task: Task,
chatParams: LLMChatParamsBase<OpenAIAdditionalChatOptions>,
): Promise<TaskStepOutput> {
const toolChoice = chatParams?.additionalChatOptions?.tool_choice ?? "auto";
return this._runStep(step, task, ChatResponseMode.WAIT, toolChoice);
}
async streamStep(
step: TaskStep,
task: Task,
chatParams: LLMChatParamsBase<OpenAIAdditionalChatOptions>,
): Promise<TaskStepOutput> {
const toolChoice = chatParams?.additionalChatOptions?.tool_choice ?? "auto";
return this._runStep(step, task, ChatResponseMode.STREAM, toolChoice);
}
finalizeTask(task: Task): void {
task.memory.set(task.memory.get().concat(task.extraState.newMemory.get()));
task.extraState.newMemory.reset();
}
}
+405
View File
@@ -0,0 +1,405 @@
import { pipeline, randomUUID } from "@llamaindex/env";
import { Settings } from "../Settings.js";
import { getReACTAgentSystemHeader } from "../internal/prompt/react.js";
import {
isAsyncIterable,
stringifyJSONToMessageContent,
} from "../internal/utils.js";
import {
type ChatMessage,
type ChatResponse,
type ChatResponseChunk,
type LLM,
} from "../llm/index.js";
import { extractText } from "../llm/utils.js";
import { ObjectRetriever } from "../objects/index.js";
import type {
BaseTool,
BaseToolWithCall,
JSONObject,
JSONValue,
} from "../types.js";
import {
AgentRunner,
AgentWorker,
type AgentParamsBase,
type TaskHandler,
} from "./base.js";
import {
callTool,
consumeAsyncIterable,
createReadableStream,
} from "./utils.js";
type ReACTAgentParamsBase = AgentParamsBase<LLM>;
type ReACTAgentParamsWithTools = ReACTAgentParamsBase & {
tools: BaseToolWithCall[];
};
type ReACTAgentParamsWithToolRetriever = ReACTAgentParamsBase & {
toolRetriever: ObjectRetriever<BaseToolWithCall>;
};
export type ReACTAgentParams =
| ReACTAgentParamsWithTools
| ReACTAgentParamsWithToolRetriever;
type BaseReason = {
type: unknown;
};
type ObservationReason = BaseReason & {
type: "observation";
observation: JSONValue;
};
type ActionReason = BaseReason & {
type: "action";
thought: string;
action: string;
input: JSONObject;
};
type ResponseReason = BaseReason & {
type: "response";
thought: string;
response: ChatResponse | AsyncIterable<ChatResponseChunk>;
};
type Reason = ObservationReason | ActionReason | ResponseReason;
function reasonFormatter(reason: Reason): string | Promise<string> {
switch (reason.type) {
case "observation":
return `Observation: ${stringifyJSONToMessageContent(reason.observation)}`;
case "action":
return `Thought: ${reason.thought}\nAction: ${reason.action}\nInput: ${stringifyJSONToMessageContent(
reason.input,
)}`;
case "response": {
if (isAsyncIterable(reason.response)) {
return consumeAsyncIterable(reason.response).then(
(message) =>
`Thought: ${reason.thought}\nAnswer: ${extractText(message.content)}`,
);
} else {
return `Thought: ${reason.thought}\nAnswer: ${extractText(
reason.response.message.content,
)}`;
}
}
}
}
function extractJsonStr(text: string): string {
const pattern = /\{.*}/s;
const match = text.match(pattern);
if (!match) {
throw new SyntaxError(`Could not extract json string from output: ${text}`);
}
return match[0];
}
function extractFinalResponse(
inputText: string,
): [thought: string, answer: 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];
}
function extractToolUse(
inputText: string,
): [thought: string, action: string, input: string] {
const pattern =
/\s*Thought: (.*?)\nAction: ([a-zA-Z0-9_]+).*?\.*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): JSONObject {
const processedString = jsonStr.replace(/(?<!\w)'|'(?!\w)/g, '"');
const pattern = /"(\w+)":\s*"([^"]*)"/g;
const matches = [...processedString.matchAll(pattern)];
return Object.fromEntries(matches);
}
type ReACTOutputParser = <Options extends object>(
output: ChatResponse<Options> | AsyncIterable<ChatResponseChunk<Options>>,
) => Promise<Reason>;
const reACTOutputParser: ReACTOutputParser = async (
output,
): Promise<Reason> => {
let reason: Reason | null = null;
if (isAsyncIterable(output)) {
const [peakStream, finalStream] = createReadableStream(output).tee();
const type = await pipeline(peakStream, async (iter) => {
let content = "";
for await (const chunk of iter) {
content += chunk.delta;
if (content.includes("Action:")) {
return "action";
} else if (content.includes("Answer:")) {
return "answer";
} else if (content.includes("Thought:")) {
return "thought";
}
}
});
// step 2: do the parsing from content
switch (type) {
case "action": {
// have to consume the stream to get the full content
const response = await consumeAsyncIterable(finalStream);
const { content } = response;
const [thought, action, input] = extractToolUse(content);
const jsonStr = extractJsonStr(input);
let json: JSONObject;
try {
json = JSON.parse(jsonStr);
} catch (e) {
json = actionInputParser(jsonStr);
}
reason = {
type: "action",
thought,
action,
input: json,
};
break;
}
case "thought": {
const thought = "(Implicit) I can answer without any more tools!";
reason = {
type: "response",
thought,
// bypass the response, because here we don't need to do anything with it
response: finalStream,
};
break;
}
case "answer": {
const response = await consumeAsyncIterable(finalStream);
const { content } = response;
const [thought, answer] = extractFinalResponse(content);
reason = {
type: "response",
thought,
response: {
raw: response,
message: {
role: "assistant",
content: answer,
},
},
};
break;
}
default: {
throw new Error(`Invalid type: ${type}`);
}
}
} else {
const content = extractText(output.message.content);
const type = content.includes("Answer:")
? "answer"
: content.includes("Action:")
? "action"
: "thought";
// step 2: do the parsing from content
switch (type) {
case "action": {
const [thought, action, input] = extractToolUse(content);
const jsonStr = extractJsonStr(input);
let json: JSONObject;
try {
json = JSON.parse(jsonStr);
} catch (e) {
json = actionInputParser(jsonStr);
}
reason = {
type: "action",
thought,
action,
input: json,
};
break;
}
case "thought": {
const thought = "(Implicit) I can answer without any more tools!";
reason = {
type: "response",
thought,
response: {
raw: output,
message: {
role: "assistant",
content: extractText(output.message.content),
},
},
};
break;
}
case "answer": {
const [thought, answer] = extractFinalResponse(content);
reason = {
type: "response",
thought,
response: {
raw: output,
message: {
role: "assistant",
content: answer,
},
},
};
break;
}
default: {
throw new Error(`Invalid type: ${type}`);
}
}
}
if (reason === null) {
throw new TypeError("Reason is null");
}
return reason;
};
type ReACTAgentStore = {
reasons: Reason[];
};
type ChatFormatter = <Options extends object>(
tools: BaseTool[],
messages: ChatMessage<Options>[],
currentReasons: Reason[],
) => Promise<ChatMessage<Options>[]>;
const chatFormatter: ChatFormatter = async <Options extends object>(
tools: BaseTool[],
messages: ChatMessage<Options>[],
currentReasons: Reason[],
): Promise<ChatMessage<Options>[]> => {
const header = getReACTAgentSystemHeader(tools);
const reasonMessages: ChatMessage<Options>[] = [];
for (const reason of currentReasons) {
const response = await reasonFormatter(reason);
reasonMessages.push({
role: reason.type === "observation" ? "user" : "assistant",
content: response,
});
}
return [
{
role: "system",
content: header,
},
...messages,
...reasonMessages,
];
};
export class ReACTAgentWorker extends AgentWorker<LLM, ReACTAgentStore> {
taskHandler = ReActAgent.taskHandler;
}
export class ReActAgent extends AgentRunner<LLM, ReACTAgentStore> {
constructor(
params: ReACTAgentParamsWithTools | ReACTAgentParamsWithToolRetriever,
) {
super({
llm: params.llm ?? Settings.llm,
chatHistory: params.chatHistory ?? [],
runner: new ReACTAgentWorker(),
systemPrompt: params.systemPrompt ?? null,
tools:
"tools" in params
? params.tools
: params.toolRetriever.retrieve.bind(params.toolRetriever),
});
}
createStore() {
return {
reasons: [],
};
}
static taskHandler: TaskHandler<LLM, ReACTAgentStore> = async (step) => {
const { llm, stream, getTools } = step.context;
const input = step.input;
if (input) {
step.context.store.messages.push(input);
}
const lastMessage = step.context.store.messages.at(-1)!.content;
const tools = await getTools(lastMessage);
const messages = await chatFormatter(
tools,
step.context.store.messages,
step.context.store.reasons,
);
const response = await llm.chat({
// @ts-expect-error
stream,
messages,
});
const reason = await reACTOutputParser(response);
step.context.store.reasons = [...step.context.store.reasons, reason];
if (reason.type === "response") {
return {
isLast: true,
output: response,
taskStep: step,
};
} else {
if (reason.type === "action") {
const tool = tools.find((tool) => tool.metadata.name === reason.action);
const toolOutput = await callTool(tool, {
id: randomUUID(),
input: reason.input,
name: reason.action,
});
step.context.store.reasons = [
...step.context.store.reasons,
{
type: "observation",
observation: toolOutput.output,
},
];
}
return {
isLast: false,
output: null,
taskStep: step,
};
}
};
}
-48
View File
@@ -1,48 +0,0 @@
import type { ChatMessage, LLM } from "../../llm/index.js";
import type { BaseMemory } from "../../memory/types.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?: BaseMemory;
prefixMessages?: ChatMessage[];
maxInteractions?: number;
defaultToolChoice?: string;
toolRetriever?: ObjectRetriever<BaseTool>;
};
/**
* An agent that uses OpenAI's API to generate text.
*
* @category OpenAI
*/
export class ReActAgent extends AgentRunner {
constructor({
tools,
llm,
memory,
prefixMessages,
maxInteractions = 10,
defaultToolChoice = "auto",
toolRetriever,
}: Partial<ReActAgentParams>) {
const stepEngine = new ReActAgentWorker({
tools: tools ?? [],
llm,
maxInteractions,
toolRetriever,
});
super({
agentWorker: stepEngine,
memory,
defaultToolChoice,
// @ts-expect-error 2322
chatHistory: prefixMessages,
});
}
}
@@ -1,84 +0,0 @@
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: "assistant",
};
}
reasoningHistory.push(message);
}
const systemContent = getReactChatSystemHeader({
toolDesc: formatArgs.toolDesc,
toolNames: formatArgs.toolNames,
});
return [
{
content: systemContent,
role: "system",
},
...chatHistory,
...reasoningHistory,
];
}
}
@@ -1,105 +0,0 @@
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");
}
}
-91
View File
@@ -1,91 +0,0 @@
import type { ChatMessage } from "../../llm/index.js";
import { extractText } from "../../llm/utils.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(
extractText(messages[0].content) || "",
);
} else {
messages[messages.length - 1].content = this.format(
extractText(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;
}
}
-325
View File
@@ -1,325 +0,0 @@
import { randomUUID } from "@llamaindex/env";
import type { ChatMessage } from "cohere-ai/api";
import { Settings } from "../../Settings.js";
import { AgentChatResponse } from "../../engines/chat/index.js";
import { getCallbackManager } from "../../internal/settings/CallbackManager.js";
import { type ChatResponse, type LLM } from "../../llm/index.js";
import { extractText } from "../../llm/utils.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;
toolRetriever?: ObjectRetriever<BaseTool> | undefined;
};
function addUserStepToReasoning(
step: TaskStep,
memory: ChatMemoryBuffer,
currentReasoning: BaseReasoningStep[],
): 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 (Settings.debug) {
console.log(`Added user message to memory: ${step.input}`);
}
}
}
type ChatParams = {
messages: ChatMessage[];
tools?: BaseTool[];
};
/**
* ReAct agent worker.
*/
export class ReActAgentWorker implements AgentWorker<ChatParams> {
llm: LLM;
maxInteractions: number = 10;
reactChatFormatter: ReActChatFormatter;
outputParser: ReActOutputParser;
_getTools: (message: string) => Promise<BaseTool[]>;
constructor({
tools,
llm,
maxInteractions,
reactChatFormatter,
outputParser,
toolRetriever,
}: ReActAgentWorkerParams) {
this.llm = llm ?? Settings.llm;
this.maxInteractions = maxInteractions ?? 10;
this.reactChatFormatter = reactChatFormatter ?? new ReActChatFormatter();
this.outputParser = outputParser ?? new ReActOutputParser();
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 () => [];
}
}
initializeStep(task: Task): TaskStep {
const sources: ToolOutput[] = [];
const currentReasoning: BaseReasoningStep[] = [];
const newMemory = new ChatMemoryBuffer({
tokenLimit: task.memory.tokenLimit,
});
const taskState = {
sources,
currentReasoning,
newMemory,
};
task.extraState = {
...task.extraState,
...taskState,
};
return new TaskStep(task.taskId, randomUUID(), task.input, {
isFirst: true,
});
}
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(
extractText(messageContent),
isStreaming,
) as ActionReasoningStep;
} catch (e) {
throw new Error(`Could not parse output: ${e}`);
}
if (Settings.debug) {
console.log(`${reasoningStep.getContent()}\n`);
}
currentReasoning.push(reasoningStep);
if (reasoningStep.isDone()) {
return [extractText(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 [extractText(messageContent), currentReasoning, false];
}
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];
getCallbackManager().dispatchEvent("llm-tool-call", {
payload: {
toolCall: {
name: tool.metadata.name,
input: JSON.stringify(actionReasoningStep.actionInput),
},
},
});
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 (Settings.debug) {
console.log(`${observationStep.getContent()}`);
}
return [currentReasoning, false];
}
_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);
}
_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);
}
async _runStep(step: TaskStep, task: Task): Promise<TaskStepOutput> {
if (step.input) {
addUserStepToReasoning(
step,
task.extraState.newMemory,
task.extraState.currentReasoning,
);
}
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);
}
async runStep(step: TaskStep, task: Task): Promise<TaskStepOutput> {
return await this._runStep(step, task);
}
streamStep(): Promise<TaskStepOutput> {
throw new Error("Method not implemented.");
}
finalizeTask(task: Task): void {
task.memory.set(task.memory.get() + task.extraState.newMemory.get());
task.extraState.newMemory.reset();
}
}
-384
View File
@@ -1,384 +0,0 @@
import { randomUUID } from "@llamaindex/env";
import type { ChatHistory } from "../../ChatHistory.js";
import type { ChatEngineAgentParams } from "../../engines/chat/index.js";
import {
AgentChatResponse,
ChatResponseMode,
StreamingAgentChatResponse,
} from "../../engines/chat/index.js";
import type { 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,
input?: string | null,
step?: any,
kwargs?: any,
): TaskStep | undefined => {
if (step) {
if (input) {
throw new Error("Cannot specify both `step` and `input`");
}
return step;
} else {
if (!input) return;
return new TaskStep(taskId, step, input, kwargs);
}
};
type AgentRunnerParams = {
agentWorker: AgentWorker;
chatHistory?: ChatHistory;
state?: AgentState;
memory?: BaseMemory;
llm?: LLM;
initTaskStateKwargs?: Record<string, any>;
deleteTaskOnFinish?: boolean;
defaultToolChoice?: string;
};
export class AgentRunner extends BaseAgentRunner {
agentWorker: AgentWorker;
state: AgentState;
memory: BaseMemory;
initTaskStateKwargs: Record<string, any>;
deleteTaskOnFinish: boolean;
defaultToolChoice: string;
/**
* Creates an AgentRunner.
*/
constructor(params: AgentRunnerParams) {
super();
this.agentWorker = params.agentWorker;
this.state = params.state ?? new AgentState();
this.memory =
params.memory ??
new ChatMemoryBuffer({
llm: params.llm,
chatHistory: params.chatHistory,
});
this.initTaskStateKwargs = params.initTaskStateKwargs ?? {};
this.deleteTaskOnFinish = params.deleteTaskOnFinish ?? false;
this.defaultToolChoice = params.defaultToolChoice ?? "auto";
}
/**
* Creates a task.
* @param input
* @param kwargs
*/
createTask(input: string, kwargs?: any): Task {
let extraState;
if (!this.initTaskStateKwargs) {
if (kwargs && "extraState" in kwargs) {
if (extraState) {
delete extraState["extraState"];
}
}
} else {
if (kwargs && "extraState" in kwargs) {
throw new Error(
"Cannot specify both `extraState` and `initTaskStateKwargs`",
);
} else {
extraState = this.initTaskStateKwargs;
}
}
const task = new Task({
taskId: randomUUID(),
input,
memory: this.memory,
extraState,
...kwargs,
});
const initialStep = this.agentWorker.initializeStep(task);
const taskState = new TaskState({
task,
stepQueue: [initialStep],
});
this.state.taskDict[task.taskId] = taskState;
return task;
}
/**
* Deletes the task.
* @param taskId
*/
deleteTask(taskId: string): void {
delete this.state.taskDict[taskId];
}
/**
* Returns the list of tasks.
*/
listTasks(): Task[] {
return Object.values(this.state.taskDict).map(
(taskState) => taskState.task,
);
}
/**
* Returns the task.
*/
getTask(taskId: string): Task {
return this.state.taskDict[taskId].task;
}
/**
* Returns the completed steps in the task.
* @param taskId
* @param kwargs
*/
getCompletedSteps(taskId: string): TaskStepOutput[] {
return this.state.taskDict[taskId].completedSteps;
}
/**
* Returns the next steps in the task.
* @param taskId
* @param kwargs
*/
getUpcomingSteps(taskId: string, kwargs: any): TaskStep[] {
return this.state.taskDict[taskId].stepQueue;
}
private async _runStep(
taskId: string,
step?: TaskStep,
mode: ChatResponseMode = ChatResponseMode.WAIT,
kwargs?: any,
): Promise<TaskStepOutput> {
const task = this.state.getTask(taskId);
const curStep = step || this.state.getStepQueue(taskId).shift();
let curStepOutput: TaskStepOutput;
if (!curStep) {
throw new Error(`No step found for task ${taskId}`);
}
if (mode === ChatResponseMode.WAIT) {
curStepOutput = await this.agentWorker.runStep(curStep, task, kwargs);
} else if (mode === ChatResponseMode.STREAM) {
curStepOutput = await this.agentWorker.streamStep(curStep, task, kwargs);
} else {
throw new Error(`Invalid mode: ${mode}`);
}
const nextSteps = curStepOutput.nextSteps;
this.state.addSteps(taskId, nextSteps);
this.state.addCompletedStep(taskId, [curStepOutput]);
return curStepOutput;
}
/**
* Runs the next step in the task.
* @param taskId
* @param kwargs
* @param step
* @returns
*/
async runStep(
taskId: string,
input?: string | null,
step?: TaskStep,
kwargs: any = {},
): Promise<TaskStepOutput> {
const curStep = validateStepFromArgs(taskId, input, step, kwargs);
return this._runStep(taskId, curStep, ChatResponseMode.WAIT, kwargs);
}
/**
* Runs the step and returns the response.
* @param taskId
* @param input
* @param step
* @param kwargs
*/
async streamStep(
taskId: string,
input: string,
step?: TaskStep,
kwargs?: any,
): Promise<TaskStepOutput> {
const curStep = validateStepFromArgs(taskId, input, step, kwargs);
return this._runStep(taskId, curStep, ChatResponseMode.STREAM, kwargs);
}
/**
* Finalizes the response and returns it.
* @param taskId
* @param kwargs
* @param stepOutput
* @returns
*/
async finalizeResponse(
taskId: string,
stepOutput: TaskStepOutput,
kwargs?: any,
): Promise<AgentChatResponse | StreamingAgentChatResponse> {
if (!stepOutput) {
stepOutput =
this.getCompletedSteps(taskId)[
this.getCompletedSteps(taskId).length - 1
];
}
if (!stepOutput.isLast) {
throw new Error(
"finalizeResponse can only be called on the last step output",
);
}
if (!(stepOutput.output instanceof StreamingAgentChatResponse)) {
if (!(stepOutput.output instanceof AgentChatResponse)) {
throw new Error(
`When \`isLast\` is True, cur_step_output.output must be AGENT_CHAT_RESPONSE_TYPE: ${stepOutput.output}`,
);
}
}
this.agentWorker.finalizeTask(this.getTask(taskId), kwargs);
if (this.deleteTaskOnFinish) {
this.deleteTask(taskId);
}
return stepOutput.output;
}
protected async _chat({
message,
toolChoice,
stream,
}: ChatEngineAgentParams): Promise<AgentChatResponse>;
protected async _chat({
message,
toolChoice,
stream,
}: ChatEngineAgentParams & {
stream: true;
}): Promise<StreamingAgentChatResponse>;
protected async _chat({
message,
toolChoice,
stream,
}: ChatEngineAgentParams): Promise<
AgentChatResponse | StreamingAgentChatResponse
> {
const task = this.createTask(message as string);
let resultOutput;
const mode = stream ? ChatResponseMode.STREAM : ChatResponseMode.WAIT;
while (true) {
const curStepOutput = await this._runStep(task.taskId, undefined, mode, {
toolChoice,
});
if (curStepOutput.isLast) {
resultOutput = curStepOutput;
break;
}
toolChoice = "auto";
}
return this.finalizeResponse(task.taskId, resultOutput);
}
/**
* Sends a message to the LLM and returns the response.
* @param message
* @param chatHistory
* @param toolChoice
* @returns
*/
public async chat({
message,
chatHistory,
toolChoice,
stream,
}: ChatEngineAgentParams & {
stream?: false;
}): Promise<AgentChatResponse>;
public async chat({
message,
chatHistory,
toolChoice,
stream,
}: ChatEngineAgentParams & {
stream: true;
}): Promise<StreamingAgentChatResponse>;
public async chat({
message,
chatHistory,
toolChoice,
stream,
}: ChatEngineAgentParams): Promise<
AgentChatResponse | StreamingAgentChatResponse
> {
if (!toolChoice) {
toolChoice = this.defaultToolChoice;
}
const chatResponse = await this._chat({
message,
chatHistory,
toolChoice,
stream,
});
return chatResponse;
}
protected _getPromptModules(): string[] {
return [];
}
protected _getPrompts(): string[] {
return [];
}
/**
* Resets the agent.
*/
reset(): void {
this.state = new AgentState();
}
getCompletedStep(
taskId: string,
stepId: string,
kwargs: any,
): TaskStepOutput {
const completedSteps = this.getCompletedSteps(taskId);
for (const stepOutput of completedSteps) {
if (stepOutput.taskStep.stepId === stepId) {
return stepOutput;
}
}
throw new Error(`Step ${stepId} not found in task ${taskId}`);
}
/**
* Undoes the step.
* @param taskId
*/
undoStep(taskId: string): void {}
}
-106
View File
@@ -1,106 +0,0 @@
import type {
AgentChatResponse,
StreamingAgentChatResponse,
} from "../../engines/chat/index.js";
import type { Task, TaskStep, TaskStepOutput } from "../types.js";
import { BaseAgent } from "../types.js";
export class TaskState {
task!: Task;
stepQueue!: TaskStep[];
completedSteps!: TaskStepOutput[];
constructor(init?: Partial<TaskState>) {
Object.assign(this, init);
}
}
export abstract class BaseAgentRunner extends BaseAgent {
constructor(init?: Partial<BaseAgentRunner>) {
super();
}
abstract createTask(input: string, kwargs: any): Task;
abstract deleteTask(taskId: string): void;
abstract getTask(taskId: string, kwargs: any): Task;
abstract listTasks(kwargs: any): Task[];
abstract getUpcomingSteps(taskId: string, kwargs: any): TaskStep[];
abstract getCompletedSteps(taskId: string, kwargs: any): TaskStepOutput[];
getCompletedStep(
taskId: string,
stepId: string,
kwargs: any,
): TaskStepOutput {
const completedSteps = this.getCompletedSteps(taskId, kwargs);
for (const stepOutput of completedSteps) {
if (stepOutput.taskStep.stepId === stepId) {
return stepOutput;
}
}
throw new Error(`Step ${stepId} not found in task ${taskId}`);
}
abstract runStep(
taskId: string,
input: string,
step: TaskStep,
kwargs: any,
): Promise<TaskStepOutput>;
abstract streamStep(
taskId: string,
input: string,
step: TaskStep,
kwargs?: any,
): Promise<TaskStepOutput>;
abstract finalizeResponse(
taskId: string,
stepOutput: TaskStepOutput,
kwargs?: any,
): Promise<AgentChatResponse | StreamingAgentChatResponse>;
abstract undoStep(taskId: string): void;
}
export class AgentState {
taskDict!: Record<string, TaskState>;
constructor(init?: Partial<AgentState>) {
Object.assign(this, init);
if (!this.taskDict) {
this.taskDict = {};
}
}
getTask(taskId: string): Task {
return this.taskDict[taskId].task;
}
getCompletedSteps(taskId: string): TaskStepOutput[] {
return this.taskDict[taskId].completedSteps || [];
}
getStepQueue(taskId: string): TaskStep[] {
return this.taskDict[taskId].stepQueue || [];
}
addSteps(taskId: string, steps: TaskStep[]): void {
if (!this.taskDict[taskId].stepQueue) {
this.taskDict[taskId].stepQueue = [];
}
this.taskDict[taskId].stepQueue.push(...steps);
}
addCompletedStep(taskId: string, stepOutputs: TaskStepOutput[]): void {
if (!this.taskDict[taskId].completedSteps) {
this.taskDict[taskId].completedSteps = [];
}
this.taskDict[taskId].completedSteps.push(...stepOutputs);
}
}
+4
View File
@@ -0,0 +1,4 @@
import type { BaseEvent } from "../internal/type.js";
export type AgentStartEvent = BaseEvent<{}>;
export type AgentEndEvent = BaseEvent<{}>;
-202
View File
@@ -1,202 +0,0 @@
import type {
AgentChatResponse,
ChatEngineAgentParams,
StreamingAgentChatResponse,
} from "../engines/chat/index.js";
import type { BaseMemory } from "../memory/types.js";
import type { QueryEngineParamsNonStreaming } from "../types.js";
export interface AgentWorker<ExtraParams extends object = object> {
initializeStep(task: Task, params?: ExtraParams): TaskStep;
runStep(
step: TaskStep,
task: Task,
params?: ExtraParams,
): Promise<TaskStepOutput>;
streamStep(
step: TaskStep,
task: Task,
params?: ExtraParams,
): Promise<TaskStepOutput>;
finalizeTask(task: Task, params?: ExtraParams): void;
}
interface BaseChatEngine {
chat(
params: ChatEngineAgentParams,
): Promise<AgentChatResponse | StreamingAgentChatResponse>;
}
interface BaseQueryEngine {
query(
params: QueryEngineParamsNonStreaming,
): Promise<AgentChatResponse | StreamingAgentChatResponse>;
}
/**
* BaseAgent is the base class for all agents.
*/
export abstract class BaseAgent implements BaseChatEngine, BaseQueryEngine {
protected _getPrompts(): string[] {
return [];
}
protected _getPromptModules(): string[] {
return [];
}
abstract chat(
params: ChatEngineAgentParams,
): Promise<AgentChatResponse | StreamingAgentChatResponse>;
abstract reset(): void;
/**
* query is the main entrypoint for the agent. It takes a query and returns a response.
* @param params
* @returns
*/
async query(
params: QueryEngineParamsNonStreaming,
): Promise<AgentChatResponse | StreamingAgentChatResponse> {
// Handle non-streaming query
const agentResponse = await this.chat({
message: params.query,
chatHistory: [],
});
return agentResponse;
}
}
type TaskParams = {
taskId: string;
input: string;
memory: BaseMemory;
extraState: Record<string, any>;
};
/**
* Task is a unit of work for the agent.
* @param taskId: taskId
*/
export class Task {
taskId: string;
input: string;
memory: BaseMemory;
extraState: Record<string, any>;
constructor({ taskId, input, memory, extraState }: TaskParams) {
this.taskId = taskId;
this.input = input;
this.memory = memory;
this.extraState = extraState ?? {};
}
}
interface ITaskStep {
taskId: string;
stepId: string;
input?: string | null;
stepState: Record<string, any>;
nextSteps: Record<string, TaskStep>;
prevSteps: Record<string, TaskStep>;
isReady: boolean;
getNextStep(
stepId: string,
input?: string,
stepState?: Record<string, any>,
): TaskStep;
linkStep(nextStep: TaskStep): void;
}
/**
* TaskStep is a unit of work for the agent.
* @param taskId: taskId
* @param stepId: stepId
* @param input: input
* @param stepState: stepState
*/
export class TaskStep implements ITaskStep {
taskId: string;
stepId: string;
input?: string | null;
stepState: Record<string, any> = {};
nextSteps: Record<string, TaskStep> = {};
prevSteps: Record<string, TaskStep> = {};
isReady: boolean = true;
constructor(
taskId: string,
stepId: string,
input?: string | null,
stepState?: Record<string, any> | null,
) {
this.taskId = taskId;
this.stepId = stepId;
this.input = input;
this.stepState = stepState ?? this.stepState;
}
/*
* getNextStep is a function that returns the next step.
* @param stepId: stepId
* @param input: input
* @param stepState: stepState
* @returns: TaskStep
*/
getNextStep(
stepId: string,
input?: string,
stepState?: Record<string, unknown>,
): TaskStep {
return new TaskStep(
this.taskId,
stepId,
input,
stepState ?? this.stepState,
);
}
/*
* linkStep is a function that links the next step.
* @param nextStep: nextStep
* @returns: void
*/
linkStep(nextStep: TaskStep): void {
this.nextSteps[nextStep.stepId] = nextStep;
nextStep.prevSteps[this.stepId] = this;
}
}
/**
* TaskStepOutput is a unit of work for the agent.
* @param output: output
* @param taskStep: taskStep
* @param nextSteps: nextSteps
* @param isLast: isLast
*/
export class TaskStepOutput {
output: AgentChatResponse | StreamingAgentChatResponse;
taskStep: TaskStep;
nextSteps: TaskStep[];
isLast: boolean;
constructor(
output: AgentChatResponse | StreamingAgentChatResponse,
taskStep: TaskStep,
nextSteps: TaskStep[],
isLast: boolean = false,
) {
this.output = output;
this.taskStep = taskStep;
this.nextSteps = nextSteps;
this.isLast = isLast;
}
toString(): string {
return String(this.output);
}
}
+104 -27
View File
@@ -1,35 +1,112 @@
import { Settings } from "../Settings.js";
import type { ChatMessage } from "../llm/index.js";
import type { ChatMemoryBuffer } from "../memory/ChatMemoryBuffer.js";
import type { BaseTool } from "../types.js";
import type { TaskStep } from "./types.js";
import { getCallbackManager } from "../internal/settings/CallbackManager.js";
import { isAsyncIterable, prettifyError } from "../internal/utils.js";
import type {
ChatMessage,
ChatResponseChunk,
TextChatMessage,
ToolCall,
} from "../llm/index.js";
import type { BaseTool, JSONValue, ToolOutput } from "../types.js";
export function addUserStepToMemory(
step: TaskStep,
memory: ChatMemoryBuffer,
): void {
if (!step.input) {
return;
export async function callTool(
tool: BaseTool | undefined,
toolCall: ToolCall,
): Promise<ToolOutput> {
if (!tool) {
const output = `Tool ${toolCall.name} does not exist.`;
return {
tool,
input: toolCall.input,
output,
isError: true,
};
}
const userMessage: ChatMessage = {
content: step.input,
role: "user",
const call = tool.call;
let output: JSONValue;
if (!call) {
output = `Tool ${tool.metadata.name} (remote:${toolCall.name}) does not have a implementation.`;
return {
tool,
input: toolCall.input,
output,
isError: true,
};
}
try {
let input = toolCall.input;
if (typeof input === "string") {
input = JSON.parse(input);
}
getCallbackManager().dispatchEvent("llm-tool-call", {
payload: {
toolCall: { ...toolCall },
},
});
output = await call.call(tool, input);
const toolOutput: ToolOutput = {
tool,
input: toolCall.input,
output,
isError: false,
};
getCallbackManager().dispatchEvent("llm-tool-result", {
payload: {
toolCall: { ...toolCall },
toolResult: { ...toolOutput },
},
});
return toolOutput;
} catch (e) {
output = prettifyError(e);
}
return {
tool,
input: toolCall.input,
output,
isError: true,
};
}
memory.put(userMessage);
if (Settings.debug) {
console.log(`Added user message to memory!: ${userMessage.content}`);
export async function consumeAsyncIterable<Options extends object>(
input: ChatMessage<Options>,
): Promise<ChatMessage<Options>>;
export async function consumeAsyncIterable<Options extends object>(
input: AsyncIterable<ChatResponseChunk<Options>>,
): Promise<TextChatMessage<Options>>;
export async function consumeAsyncIterable<Options extends object>(
input: ChatMessage<Options> | AsyncIterable<ChatResponseChunk<Options>>,
): Promise<ChatMessage<Options>> {
if (isAsyncIterable(input)) {
const result: ChatMessage<Options> = {
content: "",
// only assistant will give streaming response
role: "assistant",
options: {} as Options,
};
for await (const chunk of input) {
result.content += chunk.delta;
if (chunk.options) {
result.options = {
...result.options,
...chunk.options,
};
}
}
return result;
} else {
return input;
}
}
export function getFunctionByName(tools: BaseTool[], name: string): BaseTool {
const exist = tools.find((tool) => tool.metadata.name === name);
if (!exist) {
throw new Error(`Tool with name ${name} not found`);
}
return exist;
export function createReadableStream<T>(
asyncIterable: AsyncIterable<T>,
): ReadableStream<T> {
return new ReadableStream<T>({
async start(controller) {
for await (const chunk of asyncIterable) {
controller.enqueue(chunk);
}
controller.close();
},
});
}
@@ -1,6 +1,7 @@
import type { Anthropic } from "@anthropic-ai/sdk";
import { CustomEvent } from "@llamaindex/env";
import type { NodeWithScore } from "../Node.js";
import type { AgentEndEvent, AgentStartEvent } from "../agent/type.js";
import {
EventCaller,
getEventCaller,
@@ -10,6 +11,7 @@ import type {
LLMStartEvent,
LLMStreamEvent,
LLMToolCallEvent,
LLMToolResultEvent,
} from "../llm/types.js";
export class LlamaIndexCustomEvent<T = any> extends CustomEvent<T> {
@@ -47,10 +49,15 @@ export interface LlamaIndexEventMaps {
* @deprecated
*/
stream: CustomEvent<StreamCallbackResponse>;
// llm events
"llm-start": LLMStartEvent;
"llm-end": LLMEndEvent;
"llm-tool-call": LLMToolCallEvent;
"llm-tool-result": LLMToolResultEvent;
"llm-stream": LLMStreamEvent;
// agent events
"agent-start": AgentStartEvent;
"agent-end": AgentEndEvent;
}
//#region @deprecated remove in the next major version
@@ -205,9 +212,10 @@ export class CallbackManager implements CallbackManagerMethods {
if (!handlers) {
return;
}
const clone = structuredClone(detail);
queueMicrotask(() => {
handlers.forEach((handler) =>
handler(LlamaIndexCustomEvent.fromEvent(event, detail)),
handler(LlamaIndexCustomEvent.fromEvent(event, clone)),
);
});
}
+2 -2
View File
@@ -5,7 +5,7 @@ import { RetrieverQueryEngine } from "../engines/query/RetrieverQueryEngine.js";
import type { TransformComponent } from "../ingestion/types.js";
import type { BaseNodePostprocessor } from "../postprocessors/types.js";
import type { BaseSynthesizer } from "../synthesizers/types.js";
import type { BaseQueryEngine } from "../types.js";
import type { QueryEngine } from "../types.js";
import type { CloudRetrieveParams } from "./LlamaCloudRetriever.js";
import { LlamaCloudRetriever } from "./LlamaCloudRetriever.js";
import { getPipelineCreate } from "./config.js";
@@ -178,7 +178,7 @@ export class LlamaCloudIndex {
preFilters?: unknown;
nodePostprocessors?: BaseNodePostprocessor[];
} & CloudRetrieveParams,
): BaseQueryEngine {
): QueryEngine {
const retriever = new LlamaCloudRetriever({
...this.params,
...params,
@@ -0,0 +1,43 @@
import {
GEMINI_MODEL,
GeminiSessionStore,
type GeminiConfig,
type GeminiSession,
} from "../llm/gemini.js";
import { BaseEmbedding } from "./types.js";
/**
* GeminiEmbedding is an alias for Gemini that implements the BaseEmbedding interface.
*/
export class GeminiEmbedding extends BaseEmbedding {
model: GEMINI_MODEL;
temperature: number;
topP: number;
maxTokens?: number;
session: GeminiSession;
constructor(init?: GeminiConfig) {
super();
this.model = init?.model ?? GEMINI_MODEL.GEMINI_PRO;
this.temperature = init?.temperature ?? 0.1;
this.topP = init?.topP ?? 1;
this.maxTokens = init?.maxTokens ?? undefined;
this.session = init?.session ?? GeminiSessionStore.get();
}
private async getEmbedding(prompt: string): Promise<number[]> {
const client = this.session.gemini.getGenerativeModel({
model: this.model,
});
const result = await client.embedContent(prompt);
return result.embedding.values;
}
getTextEmbedding(text: string): Promise<number[]> {
return this.getEmbedding(text);
}
getQueryEmbedding(query: string): Promise<number[]> {
return this.getTextEmbedding(query);
}
}
@@ -0,0 +1,29 @@
import { getEnv } from "@llamaindex/env";
import { OpenAIEmbedding } from "./OpenAIEmbedding.js";
export class JinaAIEmbedding extends OpenAIEmbedding {
constructor(init?: Partial<OpenAIEmbedding>) {
const {
apiKey = getEnv("JINAAI_API_KEY"),
additionalSessionOptions = {},
model = "jina-embeddings-v2-base-en",
...rest
} = init ?? {};
if (!apiKey) {
throw new Error(
"Set Jina AI API Key in JINAAI_API_KEY env variable. Get one for free or top up your key at https://jina.ai/embeddings",
);
}
additionalSessionOptions.baseURL =
additionalSessionOptions.baseURL ?? "https://api.jina.ai/v1";
super({
apiKey,
additionalSessionOptions,
model,
...rest,
});
}
}
@@ -6,8 +6,8 @@ import {
getAzureModel,
shouldUseAzure,
} from "../llm/azure.js";
import type { OpenAISession } from "../llm/open_ai.js";
import { getOpenAISession } from "../llm/open_ai.js";
import type { OpenAISession } from "../llm/openai.js";
import { getOpenAISession } from "../llm/openai.js";
import { BaseEmbedding } from "./types.js";
export const ALL_OPENAI_EMBEDDING_MODELS = {
+2
View File
@@ -1,5 +1,7 @@
export * from "./ClipEmbedding.js";
export * from "./GeminiEmbedding.js";
export * from "./HuggingFaceEmbedding.js";
export * from "./JinaAIEmbedding.js";
export * from "./MistralAIEmbedding.js";
export * from "./MultiModalEmbedding.js";
export { OllamaEmbedding } from "./OllamaEmbedding.js";
@@ -12,7 +12,7 @@ import { wrapEventCaller } from "../../internal/context/EventCaller.js";
import type { ChatMessage, LLM } from "../../llm/index.js";
import { extractText, streamReducer } from "../../llm/utils.js";
import { PromptMixin } from "../../prompts/index.js";
import type { BaseQueryEngine } from "../../types.js";
import type { QueryEngine } from "../../types.js";
import type {
ChatEngine,
ChatEngineParamsNonStreaming,
@@ -33,13 +33,13 @@ export class CondenseQuestionChatEngine
extends PromptMixin
implements ChatEngine
{
queryEngine: BaseQueryEngine;
queryEngine: QueryEngine;
chatHistory: ChatHistory;
llm: LLM;
condenseMessagePrompt: CondenseQuestionPrompt;
constructor(init: {
queryEngine: BaseQueryEngine;
queryEngine: QueryEngine;
chatHistory: ChatMessage[];
serviceContext?: ServiceContext;
condenseMessagePrompt?: CondenseQuestionPrompt;
+8 -55
View File
@@ -3,7 +3,6 @@ import type { NodeWithScore } from "../../Node.js";
import type { Response } from "../../Response.js";
import type { ChatMessage } from "../../llm/index.js";
import type { MessageContent } from "../../llm/types.js";
import type { ToolOutput } from "../../tools/types.js";
/**
* Represents the base parameters for ChatEngine.
@@ -24,21 +23,21 @@ export interface ChatEngineParamsNonStreaming extends ChatEngineParamsBase {
stream?: false | null;
}
export interface ChatEngineAgentParams extends ChatEngineParamsBase {
toolChoice?: string | Record<string, any>;
stream?: boolean;
}
/**
* A ChatEngine is used to handle back and forth chats between the application and the LLM.
*/
export interface ChatEngine {
export interface ChatEngine<
// synchronous response
R = Response,
// asynchronous response
AR extends AsyncIterable<unknown> = AsyncIterable<R>,
> {
/**
* Send message along with the class's current chat history to the LLM.
* @param params
*/
chat(params: ChatEngineParamsStreaming): Promise<AsyncIterable<Response>>;
chat(params: ChatEngineParamsNonStreaming): Promise<Response>;
chat(params: ChatEngineParamsStreaming): Promise<AR>;
chat(params: ChatEngineParamsNonStreaming): Promise<R>;
/**
* Resets the chat history so that it's empty.
@@ -57,49 +56,3 @@ export interface Context {
export interface ContextGenerator {
generate(message: string): Promise<Context>;
}
export enum ChatResponseMode {
WAIT = "wait",
STREAM = "stream",
}
export class AgentChatResponse {
response: string;
sources: ToolOutput[];
sourceNodes?: NodeWithScore[];
constructor(
response: string,
sources?: ToolOutput[],
sourceNodes?: NodeWithScore[],
) {
this.response = response;
this.sources = sources || [];
this.sourceNodes = sourceNodes || [];
}
protected _getFormattedSources() {
throw new Error("Not implemented yet");
}
toString() {
return this.response ?? "";
}
}
export class StreamingAgentChatResponse {
response: AsyncIterable<Response>;
sources: ToolOutput[];
sourceNodes?: NodeWithScore[];
constructor(
response: AsyncIterable<Response>,
sources?: ToolOutput[],
sourceNodes?: NodeWithScore[],
) {
this.response = response;
this.sources = sources ?? [];
this.sourceNodes = sourceNodes ?? [];
}
}
@@ -7,7 +7,7 @@ import { PromptMixin } from "../../prompts/Mixin.js";
import type { BaseSynthesizer } from "../../synthesizers/index.js";
import { ResponseSynthesizer } from "../../synthesizers/index.js";
import type {
BaseQueryEngine,
QueryEngine,
QueryEngineParamsNonStreaming,
QueryEngineParamsStreaming,
} from "../../types.js";
@@ -15,10 +15,7 @@ import type {
/**
* A query engine that uses a retriever to query an index and then synthesizes the response.
*/
export class RetrieverQueryEngine
extends PromptMixin
implements BaseQueryEngine
{
export class RetrieverQueryEngine extends PromptMixin implements QueryEngine {
retriever: BaseRetriever;
responseSynthesizer: BaseSynthesizer;
nodePostprocessors: BaseNodePostprocessor[];
@@ -7,14 +7,14 @@ import type { BaseSelector } from "../../selectors/index.js";
import { LLMSingleSelector } from "../../selectors/index.js";
import { TreeSummarize } from "../../synthesizers/index.js";
import type {
BaseQueryEngine,
QueryBundle,
QueryEngine,
QueryEngineParamsNonStreaming,
QueryEngineParamsStreaming,
} from "../../types.js";
type RouterQueryEngineTool = {
queryEngine: BaseQueryEngine;
queryEngine: QueryEngine;
description: string;
};
@@ -54,9 +54,9 @@ async function combineResponses(
/**
* A query engine that uses multiple query engines and selects the best one.
*/
export class RouterQueryEngine extends PromptMixin implements BaseQueryEngine {
export class RouterQueryEngine extends PromptMixin implements QueryEngine {
private selector: BaseSelector;
private queryEngines: BaseQueryEngine[];
private queryEngines: QueryEngine[];
private metadatas: RouterQueryEngineMetadata[];
private summarizer: TreeSummarize;
private verbose: boolean;
@@ -11,8 +11,8 @@ import {
} from "../../synthesizers/index.js";
import type {
BaseQueryEngine,
BaseTool,
QueryEngine,
QueryEngineParamsNonStreaming,
QueryEngineParamsStreaming,
ToolMetadata,
@@ -24,10 +24,7 @@ import type { BaseQuestionGenerator, SubQuestion } from "./types.js";
/**
* SubQuestionQueryEngine decomposes a question into subquestions and then
*/
export class SubQuestionQueryEngine
extends PromptMixin
implements BaseQueryEngine
{
export class SubQuestionQueryEngine extends PromptMixin implements QueryEngine {
responseSynthesizer: BaseSynthesizer;
questionGen: BaseQuestionGenerator;
queryEngines: BaseTool[];
+2
View File
@@ -1,3 +1,5 @@
export * from "./index.edge.js";
export * from "./readers/index.js";
export * from "./storage/index.js";
// Ollama is only compatible with the Node.js runtime
export { Ollama, type OllamaParams } from "./llm/ollama.js";
+2 -2
View File
@@ -8,7 +8,7 @@ import type { BaseDocumentStore } from "../storage/docStore/types.js";
import type { BaseIndexStore } from "../storage/indexStore/types.js";
import type { VectorStore } from "../storage/vectorStore/types.js";
import type { BaseSynthesizer } from "../synthesizers/types.js";
import type { BaseQueryEngine } from "../types.js";
import type { QueryEngine } from "../types.js";
import { IndexStruct } from "./IndexStruct.js";
import { IndexStructType } from "./json-to-index-struct.js";
@@ -87,7 +87,7 @@ export abstract class BaseIndex<T> {
abstract asQueryEngine(options?: {
retriever?: BaseRetriever;
responseSynthesizer?: BaseSynthesizer;
}): BaseQueryEngine;
}): QueryEngine;
/**
* Insert a document into the index.

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