mirror of
https://github.com/run-llama/LlamaIndexTS.git
synced 2026-07-09 11:25:43 -04:00
Compare commits
60 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 216ba1f22b | |||
| 74686f5776 | |||
| 1ebf9e67a4 | |||
| aeefc77da0 | |||
| 13d8d7cbbe | |||
| 9c34e44b85 | |||
| cb2dc802d9 | |||
| 5a6cc0e32e | |||
| a63256eb84 | |||
| 0a160b97a0 | |||
| 95602c7959 | |||
| 20bc466ca1 | |||
| efb1c56ba5 | |||
| 286499388d | |||
| 460c6574cc | |||
| 8b0e0e3cc8 | |||
| 87142b29fa | |||
| 501b844f0f | |||
| 03157dc295 | |||
| ef80b684f7 | |||
| 472e70feee | |||
| cfb90f7666 | |||
| 2e3a287a27 | |||
| 635fbb8618 | |||
| d2d34acb31 | |||
| cf70edbede | |||
| 79b7d246bd | |||
| bcc3d0b4d1 | |||
| 238ca86534 | |||
| 1f3efe8947 | |||
| 89324b4067 | |||
| 8cc848aee6 | |||
| cd54a7a66b | |||
| dca02f7277 | |||
| b757fa9aa3 | |||
| bc594a0674 | |||
| 208282d62f | |||
| 060880abfe | |||
| 728b35e774 | |||
| bdaa043404 | |||
| a55cf8d870 | |||
| cf4244fd3a | |||
| 76c3fd64ad | |||
| 701e0ac2be | |||
| a285f8ba3a | |||
| 663821cdf6 | |||
| c4b95494ac | |||
| 980fb4e5a3 | |||
| 96f8f40291 | |||
| 1c698df6e0 | |||
| 298cb433be | |||
| 63af7dd99d | |||
| af5df1d083 | |||
| a3b44093c2 | |||
| c80bf3311f | |||
| 7940d249b0 | |||
| 4a07c81f71 | |||
| 7d56cdf045 | |||
| 0affe621d5 | |||
| 93932b1a9c |
@@ -1,12 +1,22 @@
|
||||
module.exports = {
|
||||
root: true,
|
||||
extends: [
|
||||
"next",
|
||||
"turbo",
|
||||
"prettier",
|
||||
"plugin:@typescript-eslint/recommended-type-checked-only",
|
||||
],
|
||||
parserOptions: {
|
||||
project: true,
|
||||
__tsconfigRootDir: __dirname,
|
||||
},
|
||||
settings: {
|
||||
react: {
|
||||
version: "999.999.999",
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
"@next/next/no-html-link-for-pages": "off",
|
||||
"max-params": ["error", 4],
|
||||
"prefer-const": "error",
|
||||
"@typescript-eslint/no-floating-promises": [
|
||||
"error",
|
||||
{
|
||||
@@ -54,22 +64,13 @@ module.exports = {
|
||||
"@typescript-eslint/triple-slash-reference": "off",
|
||||
"@typescript-eslint/unbound-method": "off",
|
||||
},
|
||||
// NOTE I think because we've temporarily removed all of the NextJS stuff
|
||||
// from the turborepo not having next in the devDeps causes an error on only
|
||||
// clean clones of the repo
|
||||
// Not sure if this is a missing dependency in the package.json or just my not
|
||||
// understanding how turborepo is supposed to work.
|
||||
// Anyways, planning to add back a Next.JS example soon
|
||||
parserOptions: {
|
||||
babelOptions: {
|
||||
presets: [require.resolve("next/babel")],
|
||||
overrides: [
|
||||
{
|
||||
files: ["examples/**/*.ts"],
|
||||
rules: {
|
||||
"turbo/no-undeclared-env-vars": "off",
|
||||
},
|
||||
},
|
||||
project: true,
|
||||
__tsconfigRootDir: __dirname,
|
||||
},
|
||||
settings: {
|
||||
react: {
|
||||
version: "999.999.999",
|
||||
},
|
||||
},
|
||||
],
|
||||
ignorePatterns: ["dist/", "lib/", "deps/"],
|
||||
};
|
||||
@@ -1,23 +0,0 @@
|
||||
module.exports = {
|
||||
root: true,
|
||||
// This tells ESLint to load the config from the package `eslint-config-custom`
|
||||
extends: ["custom"],
|
||||
settings: {
|
||||
next: {
|
||||
rootDir: ["apps/*/"],
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
"max-params": ["error", 4],
|
||||
"prefer-const": "error",
|
||||
},
|
||||
overrides: [
|
||||
{
|
||||
files: ["examples/**/*.ts"],
|
||||
rules: {
|
||||
"turbo/no-undeclared-env-vars": "off",
|
||||
},
|
||||
},
|
||||
],
|
||||
ignorePatterns: ["dist/", "lib/"],
|
||||
};
|
||||
@@ -13,9 +13,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v2
|
||||
with:
|
||||
version: latest
|
||||
- uses: pnpm/action-setup@v3
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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 }}
|
||||
@@ -1,6 +1,12 @@
|
||||
name: Run Tests
|
||||
|
||||
on: [push, pull_request]
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
@@ -8,14 +14,21 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
e2e:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
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
|
||||
@@ -26,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:
|
||||
@@ -47,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:
|
||||
@@ -57,6 +70,9 @@ jobs:
|
||||
run: pnpm install
|
||||
- name: Build
|
||||
run: pnpm run build --filter llamaindex
|
||||
- name: Use Build For Examples
|
||||
run: pnpm link ../packages/core/
|
||||
working-directory: ./examples
|
||||
- name: Run Type Check
|
||||
run: pnpm run type-check
|
||||
- name: Run Circular Dependency Check
|
||||
@@ -73,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:
|
||||
@@ -91,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:
|
||||
|
||||
@@ -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
|
||||
|
||||
Vendored
+2
-1
@@ -10,8 +10,9 @@
|
||||
"name": "Debug Example",
|
||||
"skipFiles": ["<node_internals>/**"],
|
||||
"runtimeExecutable": "pnpm",
|
||||
"console": "integratedTerminal",
|
||||
"cwd": "${workspaceFolder}/examples",
|
||||
"runtimeArgs": ["ts-node", "${fileBasename}"]
|
||||
"runtimeArgs": ["npx", "tsx", "${file}"]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
+5
-11
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
@@ -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;
|
||||
},
|
||||
};
|
||||
@@ -154,7 +161,7 @@ If you need any of those classes, you have to import them instead directly. Here
|
||||
import { PineconeVectorStore } from "@llamaindex/edge/storage/vectorStore/PineconeVectorStore";
|
||||
```
|
||||
|
||||
As the `PDFReader` is not with the Edge runtime, here's how to use the `SimpleDirectoryReader` with the `LlamaParseReader` to load PDFs:
|
||||
As the `PDFReader` is not working with the Edge runtime, here's how to use the `SimpleDirectoryReader` with the `LlamaParseReader` to load PDFs:
|
||||
|
||||
```typescript
|
||||
import { SimpleDirectoryReader } from "@llamaindex/edge/readers/SimpleDirectoryReader";
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -1,5 +1,14 @@
|
||||
# docs
|
||||
|
||||
## 0.0.5
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [87142b2]
|
||||
- Updated dependencies [5a6cc0e]
|
||||
- Updated dependencies [87142b2]
|
||||
- llamaindex@0.2.11
|
||||
|
||||
## 0.0.4
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -4,82 +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],
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
// 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>
|
||||
|
||||
@@ -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,309 +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,
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
documentAgents[title] = agent;
|
||||
queryEngines[title] = vectorIndex.asQueryEngine();
|
||||
}
|
||||
```
|
||||
|
||||
## Build Top-Level Agent
|
||||
|
||||
Now we define the top-level agent that can answer questions over the set of document agents.
|
||||
|
||||
This agent takes in all document agents as tools. This specific agent RetrieverOpenAIAgent performs tool retrieval before tool use (unlike a default agent that tries to put all tools in the prompt).
|
||||
|
||||
Here we use a top-k retriever, but we encourage you to customize the tool retriever method!
|
||||
|
||||
Firstly, we create a tool for each document agent
|
||||
|
||||
```ts
|
||||
const allTools: QueryEngineTool[] = [];
|
||||
```
|
||||
|
||||
```ts
|
||||
for (const title of wikiTitles) {
|
||||
const wikiSummary = `
|
||||
This content contains Wikipedia articles about ${title}.
|
||||
Use this tool if you want to answer any questions about ${title}
|
||||
`;
|
||||
|
||||
const docTool = new QueryEngineTool({
|
||||
queryEngine: documentAgents[title],
|
||||
metadata: {
|
||||
name: `tool_${title}`,
|
||||
description: wikiSummary,
|
||||
},
|
||||
});
|
||||
|
||||
allTools.push(docTool);
|
||||
}
|
||||
```
|
||||
|
||||
Our top level agent will use this document agents as tools and use toolRetriever to retrieve the best tool to answer a question.
|
||||
|
||||
```ts
|
||||
// map the tools to nodes
|
||||
const toolMapping = SimpleToolNodeMapping.fromObjects(allTools);
|
||||
|
||||
// create the object index
|
||||
const objectIndex = await ObjectIndex.fromObjects(
|
||||
allTools,
|
||||
toolMapping,
|
||||
VectorStoreIndex,
|
||||
{
|
||||
storageContext,
|
||||
},
|
||||
);
|
||||
|
||||
// create the top agent
|
||||
const topAgent = new OpenAIAgent({
|
||||
toolRetriever: await objectIndex.asRetriever({}),
|
||||
llm,
|
||||
verbose: true,
|
||||
prefixMessages: [
|
||||
{
|
||||
content:
|
||||
"You are an agent designed to answer queries about a set of given countries. Please always use the tools provided to answer a question. Do not rely on prior knowledge.",
|
||||
role: "system",
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Use the Agent
|
||||
|
||||
Now we can use the agent to answer questions.
|
||||
|
||||
```ts
|
||||
const response = await topAgent.chat({
|
||||
message: "Tell me the differences between Brazil and Canada economics?",
|
||||
});
|
||||
|
||||
// print output
|
||||
console.log(response);
|
||||
```
|
||||
|
||||
You can find the full code for this example [here](https://github.com/run-llama/LlamaIndexTS/tree/main/examples/agent/multi-document-agent.ts)
|
||||
@@ -1,187 +0,0 @@
|
||||
---
|
||||
sidebar_position: 0
|
||||
---
|
||||
|
||||
# OpenAI Agent
|
||||
|
||||
OpenAI API that supports function calling, it’s 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],
|
||||
verbose: true,
|
||||
});
|
||||
```
|
||||
|
||||
## Chat with the agent
|
||||
|
||||
Now we can chat with the agent.
|
||||
|
||||
```ts
|
||||
const response = await agent.chat({
|
||||
message: "How much is 5 + 5? then divide by 2",
|
||||
});
|
||||
|
||||
console.log(String(response));
|
||||
```
|
||||
|
||||
## 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],
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
// 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,132 +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],
|
||||
verbose: true,
|
||||
});
|
||||
```
|
||||
|
||||
## 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],
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
// Chat with the agent
|
||||
const response = await agent.chat({
|
||||
message: "What was his salary?",
|
||||
});
|
||||
|
||||
// Print the response
|
||||
console.log(String(response));
|
||||
}
|
||||
|
||||
main().then(() => {
|
||||
console.log("Done");
|
||||
});
|
||||
```
|
||||
@@ -1,203 +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],
|
||||
verbose: true,
|
||||
});
|
||||
```
|
||||
|
||||
## Chat with the agent
|
||||
|
||||
Now we can chat with the agent.
|
||||
|
||||
```ts
|
||||
const response = await agent.chat({
|
||||
message: "How much is 5 + 5? then divide by 2",
|
||||
});
|
||||
|
||||
console.log(String(response));
|
||||
```
|
||||
|
||||
The output will be:
|
||||
|
||||
```bash
|
||||
Thought: I need to use a tool to help me answer the question.
|
||||
Action: sumNumbers
|
||||
Action Input: {"a":5,"b":5}
|
||||
|
||||
Observation: 10
|
||||
Thought: I can answer without using any more tools.
|
||||
Answer: The sum of 5 and 5 is 10, and when divided by 2, the result is 5.
|
||||
|
||||
The sum of 5 and 5 is 10, and when divided by 2, the result is 5.
|
||||
```
|
||||
|
||||
## Full code
|
||||
|
||||
```ts
|
||||
import { FunctionTool, ReActAgent } from "llamaindex";
|
||||
|
||||
// Define a function to sum two numbers
|
||||
function sumNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
// Define a function to divide two numbers
|
||||
function divideNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a / b;
|
||||
}
|
||||
|
||||
// Define the parameters of the sum function as a JSON schema
|
||||
const sumJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The first number",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The second number",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
// Define the parameters of the divide function as a JSON schema
|
||||
const divideJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The argument a to divide",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The argument b to divide",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
async function main() {
|
||||
// Create a function tool from the sum function
|
||||
const sumFunctionTool = new FunctionTool(sumNumbers, {
|
||||
name: "sumNumbers",
|
||||
description: "Use this function to sum two numbers",
|
||||
parameters: sumJSON,
|
||||
});
|
||||
|
||||
// Create a function tool from the divide function
|
||||
const divideFunctionTool = new FunctionTool(divideNumbers, {
|
||||
name: "divideNumbers",
|
||||
description: "Use this function to divide two numbers",
|
||||
parameters: divideJSON,
|
||||
});
|
||||
|
||||
// Create an OpenAIAgent with the function tools
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [sumFunctionTool, divideFunctionTool],
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
// Chat with the agent
|
||||
const response = await agent.chat({
|
||||
message: "I want to sum 5 and 5 and then divide by 2",
|
||||
});
|
||||
|
||||
// Print the response
|
||||
console.log(String(response));
|
||||
}
|
||||
|
||||
main().then(() => {
|
||||
console.log("Done");
|
||||
});
|
||||
```
|
||||
@@ -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" });
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { Ollama, Settings } from "llamaindex";
|
||||
import { Ollama, Settings, DeuceChatStrategy } from "llamaindex";
|
||||
|
||||
Settings.llm = new LlamaDeuce({ chatStrategy: DeuceChatStrategy.META });
|
||||
```
|
||||
@@ -11,7 +11,12 @@ Settings.llm = new LlamaDeuce({ chatStrategy: DeuceChatStrategy.META });
|
||||
## Usage with Replication
|
||||
|
||||
```ts
|
||||
import { Ollama, ReplicateSession, Settings } from "llamaindex";
|
||||
import {
|
||||
Ollama,
|
||||
ReplicateSession,
|
||||
Settings,
|
||||
DeuceChatStrategy,
|
||||
} from "llamaindex";
|
||||
|
||||
const replicateSession = new ReplicateSession({
|
||||
replicateKey,
|
||||
@@ -48,7 +53,13 @@ const results = await queryEngine.query({
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import { LlamaDeuce, Document, VectorStoreIndex, Settings } from "llamaindex";
|
||||
import {
|
||||
LlamaDeuce,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
Settings,
|
||||
DeuceChatStrategy,
|
||||
} from "llamaindex";
|
||||
|
||||
// Use the LlamaDeuce LLM
|
||||
Settings.llm = new LlamaDeuce({ chatStrategy: DeuceChatStrategy.META });
|
||||
|
||||
@@ -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?");
|
||||
```
|
||||
@@ -14,6 +14,9 @@ Configure a variable once, and you'll be able to do things like the following:
|
||||
|
||||
Each provider has similarities and differences. Take a look below for the full set of guides for each one!
|
||||
|
||||
- [OpenLLMetry](#openllmetry)
|
||||
- [Langtrace](#langtrace)
|
||||
|
||||
## OpenLLMetry
|
||||
|
||||
[OpenLLMetry](https://github.com/traceloop/openllmetry-js) is an open-source project based on OpenTelemetry for tracing and monitoring
|
||||
@@ -33,3 +36,29 @@ traceloop.initialize({
|
||||
disableBatch: true,
|
||||
});
|
||||
```
|
||||
|
||||
## Langtrace
|
||||
|
||||
Enhance your observability with Langtrace, a robust open-source tool supports OpenTelemetry and is designed to trace, evaluate, and manage LLM applications seamlessly. Langtrace integrates directly with LlamaIndex, offering detailed, real-time insights into performance metrics such as accuracy, evaluations, and latency.
|
||||
|
||||
#### Install
|
||||
|
||||
- Self-host or sign-up and generate an API key using [Langtrace](https://www.langtrace.ai) Cloud
|
||||
|
||||
```bash
|
||||
npm install @langtrase/typescript-sdk
|
||||
```
|
||||
|
||||
#### Initialize
|
||||
|
||||
```js
|
||||
import * as Langtrace from "@langtrase/typescript-sdk";
|
||||
Langtrace.init({ api_key: "<YOUR_API_KEY>" });
|
||||
```
|
||||
|
||||
Features:
|
||||
|
||||
- OpenTelemetry compliant, ensuring broad compatibility with observability platforms.
|
||||
- Provides comprehensive logs and detailed traces of all components.
|
||||
- Real-time monitoring of accuracy, evaluations, usage, costs, and latency.
|
||||
- For more configuration options and details, visit [Langtrace Docs](https://docs.langtrace.ai/introduction).
|
||||
|
||||
@@ -6,7 +6,7 @@ This page shows how to track LLM cost using APIs.
|
||||
|
||||
The callback manager is a class that manages the callback functions.
|
||||
|
||||
You can register `llm-start`, and `llm-end` callbacks to the callback manager for tracking the cost.
|
||||
You can register `llm-start`, `llm-end`, and `llm-stream` callbacks to the callback manager for tracking the cost.
|
||||
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../examples/recipes/cost-analysis";
|
||||
|
||||
@@ -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}",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "docs",
|
||||
"version": "0.0.4",
|
||||
"version": "0.0.5",
|
||||
"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",
|
||||
@@ -32,7 +33,7 @@
|
||||
"@docusaurus/theme-classic": "^3.2.1",
|
||||
"@docusaurus/types": "^3.2.1",
|
||||
"@tsconfig/docusaurus": "^2.0.3",
|
||||
"@types/node": "^18.19.31",
|
||||
"@types/node": "^20.12.7",
|
||||
"docusaurus-plugin-typedoc": "^0.22.0",
|
||||
"typedoc": "^0.25.13",
|
||||
"typedoc-plugin-markdown": "^3.17.1",
|
||||
|
||||
@@ -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
@@ -1,72 +1,58 @@
|
||||
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"],
|
||||
};
|
||||
|
||||
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"],
|
||||
};
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { Anthropic, FunctionTool, ReActAgent } from "llamaindex";
|
||||
|
||||
// Define a function to sum two numbers
|
||||
function sumNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a + b;
|
||||
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 }): number {
|
||||
return a / b;
|
||||
function divideNumbers({ a, b }: { a: number; b: number }) {
|
||||
return `${a / b}`;
|
||||
}
|
||||
|
||||
// Define the parameters of the sum function as a JSON schema
|
||||
@@ -24,7 +24,7 @@ const sumJSON = {
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
} as const;
|
||||
|
||||
const divideJSON = {
|
||||
type: "object",
|
||||
@@ -39,7 +39,7 @@ const divideJSON = {
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
} as const;
|
||||
|
||||
async function main() {
|
||||
// Create a function tool from the sum function
|
||||
@@ -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(() => {
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { FunctionTool, OpenAIAgent } from "llamaindex";
|
||||
|
||||
// Define a function to sum two numbers
|
||||
function sumNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a + b;
|
||||
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 }): number {
|
||||
return a / b;
|
||||
function divideNumbers({ a, b }: { a: number; b: number }) {
|
||||
return `${a / b}`;
|
||||
}
|
||||
|
||||
// Define the parameters of the sum function as a JSON schema
|
||||
@@ -24,22 +24,22 @@ const sumJSON = {
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
} as const;
|
||||
|
||||
const divideJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The dividend a to divide",
|
||||
description: "The dividend",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The divisor b to divide by",
|
||||
description: "The divisor",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
} as const;
|
||||
|
||||
async function main() {
|
||||
// Create a function tool from the sum function
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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(() => {
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { FunctionTool, ReActAgent } from "llamaindex";
|
||||
import { Anthropic, FunctionTool, ReActAgent } from "llamaindex";
|
||||
|
||||
// Define a function to sum two numbers
|
||||
function sumNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a + b;
|
||||
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 }): number {
|
||||
return a / b;
|
||||
function divideNumbers({ a, b }: { a: number; b: number }) {
|
||||
console.log("get input", a, b);
|
||||
return `${a / b}`;
|
||||
}
|
||||
|
||||
// Define the parameters of the sum function as a JSON schema
|
||||
@@ -24,7 +25,7 @@ const sumJSON = {
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
} as const;
|
||||
|
||||
const divideJSON = {
|
||||
type: "object",
|
||||
@@ -39,7 +40,7 @@ const divideJSON = {
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
} as const;
|
||||
|
||||
async function main() {
|
||||
// Create a function tool from the sum function
|
||||
@@ -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,13 +1,13 @@
|
||||
import { FunctionTool, OpenAIAgent } from "llamaindex";
|
||||
|
||||
// Define a function to sum two numbers
|
||||
function sumNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a + b;
|
||||
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 }): number {
|
||||
return a / b;
|
||||
function divideNumbers({ a, b }: { a: number; b: number }) {
|
||||
return `${a / b}`;
|
||||
}
|
||||
|
||||
// Define the parameters of the sum function as a JSON schema
|
||||
@@ -24,7 +24,7 @@ const sumJSON = {
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
} as const;
|
||||
|
||||
const divideJSON = {
|
||||
type: "object",
|
||||
@@ -39,18 +39,18 @@ const divideJSON = {
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
} as const;
|
||||
|
||||
async function main() {
|
||||
// Create a function tool from the sum function
|
||||
const functionTool = new FunctionTool(sumNumbers, {
|
||||
const functionTool = FunctionTool.from(sumNumbers, {
|
||||
name: "sumNumbers",
|
||||
description: "Use this function to sum two numbers",
|
||||
parameters: sumJSON,
|
||||
});
|
||||
|
||||
// Create a function tool from the divide function
|
||||
const functionTool2 = new FunctionTool(divideNumbers, {
|
||||
const functionTool2 = FunctionTool.from(divideNumbers, {
|
||||
name: "divideNumbers",
|
||||
description: "Use this function to divide two numbers",
|
||||
parameters: divideJSON,
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { FunctionTool, Settings, WikipediaTool } from "llamaindex";
|
||||
import { AnthropicAgent } from "llamaindex/agent/anthropic";
|
||||
|
||||
Settings.callbackManager.on("llm-tool-call", (event) => {
|
||||
console.log("llm-tool-call", event.detail.payload.toolCall);
|
||||
});
|
||||
|
||||
const agent = new AnthropicAgent({
|
||||
tools: [
|
||||
FunctionTool.from<{ location: string }>(
|
||||
(query) => {
|
||||
return `The weather in ${query.location} is sunny`;
|
||||
},
|
||||
{
|
||||
name: "weather",
|
||||
description: "Get the weather",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
location: {
|
||||
type: "string",
|
||||
description: "The location to get the weather for",
|
||||
},
|
||||
},
|
||||
required: ["location"],
|
||||
},
|
||||
},
|
||||
),
|
||||
new WikipediaTool(),
|
||||
],
|
||||
});
|
||||
|
||||
async function main() {
|
||||
// https://docs.anthropic.com/claude/docs/tool-use#tool-use-best-practices-and-limitations
|
||||
const { response } = await agent.chat({
|
||||
message:
|
||||
"What is the weather in New York? What's the history of New York from Wikipedia in 3 sentences?",
|
||||
});
|
||||
|
||||
console.log(response);
|
||||
}
|
||||
|
||||
void main();
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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, {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 });
|
||||
|
||||
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
})();
|
||||
@@ -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");
|
||||
})();
|
||||
+4
-2
@@ -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);
|
||||
}
|
||||
})();
|
||||
|
||||
+11
-7
@@ -4,24 +4,28 @@
|
||||
"version": "0.0.4",
|
||||
"dependencies": {
|
||||
"@aws-crypto/sha256-js": "^5.2.0",
|
||||
"@datastax/astra-db-ts": "^0.1.4",
|
||||
"@notionhq/client": "^2.2.14",
|
||||
"@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": "workspace:latest",
|
||||
"js-tiktoken": "^1.0.11",
|
||||
"llamaindex": "*",
|
||||
"mongodb": "^6.5.0",
|
||||
"pathe": "^1.1.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^18.19.31",
|
||||
"@types/node": "^20.12.7",
|
||||
"ts-node": "^10.9.2",
|
||||
"typescript": "^5.4.4"
|
||||
"tsx": "^4.7.2",
|
||||
"typescript": "^5.4.5"
|
||||
},
|
||||
"scripts": {
|
||||
"lint": "eslint ."
|
||||
},
|
||||
"stackblitz": {
|
||||
"startCommand": "npm start"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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.11.14",
|
||||
"ts-node": "^10.9.2",
|
||||
"typescript": "^5.4.3"
|
||||
"@types/node": "^20.12.7",
|
||||
"tsx": "^4.7.2",
|
||||
"typescript": "^5.4.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,36 +1,44 @@
|
||||
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";
|
||||
|
||||
const encoding = encodingForModel("gpt-4-0125-preview");
|
||||
|
||||
const llm = new OpenAI({
|
||||
model: "gpt-4-0125-preview",
|
||||
// currently is "gpt-4-turbo-2024-04-09"
|
||||
model: "gpt-4-turbo",
|
||||
});
|
||||
|
||||
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);
|
||||
// https://openai.com/pricing
|
||||
// $10.00 / 1M tokens
|
||||
console.log(`Price: $${(tokenCount / 1_000_000) * 10}`);
|
||||
});
|
||||
Settings.callbackManager.on("llm-end", (event) => {
|
||||
const { response } = event.detail.payload;
|
||||
tokenCount += encoding.encode(extractText(response.message.content)).length;
|
||||
console.log("Token count:", tokenCount);
|
||||
// https://openai.com/pricing
|
||||
// $30.00 / 1M tokens
|
||||
console.log(`Price: $${(tokenCount / 1_000_000) * 30}`);
|
||||
console.log(`Total Price: $${(tokenCount / 1_000_000) * 10}`);
|
||||
});
|
||||
|
||||
const question = "Hello, how are you?";
|
||||
Settings.callbackManager.on("llm-stream", (event) => {
|
||||
const { chunk } = event.detail.payload;
|
||||
const { delta } = chunk;
|
||||
tokenCount += encoding.encode(extractText(delta)).length;
|
||||
if (tokenCount > 20) {
|
||||
// This is just an example, you can set your own limit or handle it differently
|
||||
throw new Error("Token limit exceeded!");
|
||||
}
|
||||
});
|
||||
Settings.callbackManager.on("llm-end", () => {
|
||||
// https://openai.com/pricing
|
||||
// $30.00 / 1M tokens
|
||||
console.log(`Total Price: $${(tokenCount / 1_000_000) * 30}`);
|
||||
});
|
||||
|
||||
const question = "Hello, how are you? Please response about 50 tokens.";
|
||||
console.log("Question:", question);
|
||||
void llm
|
||||
.chat({
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { ChatResponseChunk, OpenAI } from "llamaindex";
|
||||
import { OpenAI } from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
const llm = new OpenAI({ model: "gpt-4-turbo" });
|
||||
|
||||
const args: Parameters<typeof llm.chat>[0] = {
|
||||
additionalChatOptions: {
|
||||
tool_choice: "auto",
|
||||
@@ -34,11 +33,13 @@ async function main() {
|
||||
};
|
||||
|
||||
const stream = await llm.chat({ ...args, stream: true });
|
||||
let chunk: ChatResponseChunk | null = null;
|
||||
for await (chunk of stream) {
|
||||
for await (const chunk of stream) {
|
||||
process.stdout.write(chunk.delta);
|
||||
if (chunk.options && "toolCall" in chunk.options) {
|
||||
console.log("Tool call:");
|
||||
console.log(chunk.options.toolCall);
|
||||
}
|
||||
}
|
||||
console.log(chunk?.additionalKwargs?.toolCalls[0]);
|
||||
}
|
||||
|
||||
(async function () {
|
||||
|
||||
@@ -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,
|
||||
|
||||
+17
-4
@@ -1,6 +1,11 @@
|
||||
import fs from "node:fs/promises";
|
||||
|
||||
import { Document, VectorStoreIndex } from "llamaindex";
|
||||
import {
|
||||
Document,
|
||||
MetadataMode,
|
||||
NodeWithScore,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Load essay from abramov.txt in Node
|
||||
@@ -16,12 +21,20 @@ async function main() {
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine();
|
||||
const response = await queryEngine.query({
|
||||
const { response, sourceNodes } = await queryEngine.query({
|
||||
query: "What did the author do in college?",
|
||||
});
|
||||
|
||||
// Output response
|
||||
console.log(response.toString());
|
||||
// Output response with sources
|
||||
console.log(response);
|
||||
|
||||
if (sourceNodes) {
|
||||
sourceNodes.forEach((source: NodeWithScore, index: number) => {
|
||||
console.log(
|
||||
`\n${index}: Score: ${source.score} - ${source.node.getContent(MetadataMode.NONE).substring(0, 50)}...\n`,
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
|
||||
+10
-5
@@ -15,25 +15,30 @@
|
||||
"release": "pnpm run check-minor-version && pnpm run build:release && changeset publish",
|
||||
"release-snapshot": "pnpm run check-minor-version && pnpm run build:release && changeset publish --tag snapshot",
|
||||
"check-minor-version": "node ./scripts/check-minor-version",
|
||||
"new-version": "pnpm run build:release && changeset version && pnpm run check-minor-version",
|
||||
"new-version": "changeset version && pnpm run check-minor-version && pnpm run build:release",
|
||||
"new-snapshot": "pnpm run build:release && changeset version --snapshot"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@changesets/cli": "^2.27.1",
|
||||
"@typescript-eslint/eslint-plugin": "^7.7.0",
|
||||
"eslint": "^8.57.0",
|
||||
"eslint-config-custom": "workspace:*",
|
||||
"eslint-config-next": "^13.5.6",
|
||||
"eslint-config-prettier": "^8.10.0",
|
||||
"eslint-config-turbo": "^1.13.2",
|
||||
"eslint-plugin-react": "7.28.0",
|
||||
"husky": "^9.0.11",
|
||||
"lint-staged": "^15.2.2",
|
||||
"prettier": "^3.2.5",
|
||||
"prettier-plugin-organize-imports": "^3.2.4",
|
||||
"turbo": "^1.13.2",
|
||||
"typescript": "^5.4.4"
|
||||
"typescript": "^5.4.5"
|
||||
},
|
||||
"packageManager": "pnpm@8.15.6+sha256.01c01eeb990e379b31ef19c03e9d06a14afa5250b82e81303f88721c99ff2e6f",
|
||||
"packageManager": "pnpm@9.0.5",
|
||||
"pnpm": {
|
||||
"overrides": {
|
||||
"trim": "1.0.1",
|
||||
"@babel/traverse": "7.23.2"
|
||||
"@babel/traverse": "7.23.2",
|
||||
"protobufjs": "7.2.6"
|
||||
}
|
||||
},
|
||||
"lint-staged": {
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
.turbo
|
||||
README.md
|
||||
/README.md
|
||||
LICENSE
|
||||
@@ -1,5 +1,56 @@
|
||||
# llamaindex
|
||||
|
||||
## 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
|
||||
|
||||
- 76c3fd6: Add score to source nodes response
|
||||
- 208282d: feat: init anthropic agent
|
||||
|
||||
remove the `tool` | `function` type in `MessageType`. Replace with `assistant` instead.
|
||||
This is because these two types are only available for `OpenAI`.
|
||||
Since `OpenAI` deprecates the function type, we support the Claude 3 tool call.
|
||||
|
||||
## 0.2.8
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Add ToolsFactory to generate agent tools
|
||||
|
||||
## 0.2.7
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 96f8f40: fix: agent stream
|
||||
- Updated dependencies
|
||||
- @llamaindex/env@0.0.7
|
||||
|
||||
## 0.2.6
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- a3b4409: Fix agent streaming with new OpenAI models
|
||||
|
||||
## 0.2.5
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 7d56cdf: Allow OpenAIAgent to be called without tools
|
||||
|
||||
## 0.2.4
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { BaseNode, SimilarityType, type BaseEmbedding } from "llamaindex";
|
||||
|
||||
export class OpenAIEmbedding implements BaseEmbedding {
|
||||
embedBatchSize = 512;
|
||||
|
||||
async getQueryEmbedding(query: string) {
|
||||
return [0];
|
||||
}
|
||||
|
||||
async getTextEmbedding(text: string) {
|
||||
return [0];
|
||||
}
|
||||
|
||||
async getTextEmbeddings(texts: string[]) {
|
||||
return [[0]];
|
||||
}
|
||||
|
||||
async getTextEmbeddingsBatch(texts: string[]) {
|
||||
return [[0]];
|
||||
}
|
||||
|
||||
similarity(
|
||||
embedding1: number[],
|
||||
embedding2: number[],
|
||||
mode?: SimilarityType,
|
||||
) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
async transform(nodes: BaseNode[], _options?: any): Promise<BaseNode[]> {
|
||||
nodes.forEach((node) => (node.embedding = [0]));
|
||||
return nodes;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import { OpenAI } from "./openai.js";
|
||||
|
||||
export class Anthropic extends OpenAI {}
|
||||
@@ -1,68 +0,0 @@
|
||||
import { faker } from "@faker-js/faker";
|
||||
import type {
|
||||
ChatResponse,
|
||||
ChatResponseChunk,
|
||||
CompletionResponse,
|
||||
LLM,
|
||||
LLMChatParamsNonStreaming,
|
||||
LLMChatParamsStreaming,
|
||||
LLMCompletionParamsNonStreaming,
|
||||
LLMCompletionParamsStreaming,
|
||||
} from "llamaindex/llm/types";
|
||||
|
||||
export function getOpenAISession() {
|
||||
return {};
|
||||
}
|
||||
|
||||
export function isFunctionCallingModel() {
|
||||
return true;
|
||||
}
|
||||
|
||||
export class OpenAI implements LLM {
|
||||
get metadata() {
|
||||
return {
|
||||
model: "mock-model",
|
||||
temperature: 0.1,
|
||||
topP: 1,
|
||||
contextWindow: 2048,
|
||||
tokenizer: undefined,
|
||||
isFunctionCallingModel: true,
|
||||
};
|
||||
}
|
||||
chat(
|
||||
params: LLMChatParamsStreaming<Record<string, unknown>>,
|
||||
): Promise<AsyncIterable<ChatResponseChunk>>;
|
||||
chat(
|
||||
params: LLMChatParamsNonStreaming<Record<string, unknown>>,
|
||||
): Promise<ChatResponse>;
|
||||
chat(
|
||||
params:
|
||||
| LLMChatParamsStreaming<Record<string, unknown>>
|
||||
| LLMChatParamsNonStreaming<Record<string, unknown>>,
|
||||
): unknown {
|
||||
if (params.stream) {
|
||||
return {
|
||||
[Symbol.asyncIterator]: async function* () {
|
||||
yield {
|
||||
delta: faker.word.words(),
|
||||
} satisfies ChatResponseChunk;
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
message: {
|
||||
content: faker.lorem.paragraph(),
|
||||
role: "assistant",
|
||||
},
|
||||
} satisfies ChatResponse;
|
||||
}
|
||||
complete(
|
||||
params: LLMCompletionParamsStreaming,
|
||||
): Promise<AsyncIterable<CompletionResponse>>;
|
||||
complete(
|
||||
params: LLMCompletionParamsNonStreaming,
|
||||
): Promise<CompletionResponse>;
|
||||
async complete(params: unknown): Promise<unknown> {
|
||||
throw new Error("Method not implemented.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import type {
|
||||
ChatResponse,
|
||||
ChatResponseChunk,
|
||||
CompletionResponse,
|
||||
LLM,
|
||||
LLMChatParamsNonStreaming,
|
||||
LLMChatParamsStreaming,
|
||||
LLMCompletionParamsNonStreaming,
|
||||
LLMCompletionParamsStreaming,
|
||||
} from "llamaindex/llm/types";
|
||||
import { extractText } from "llamaindex/llm/utils";
|
||||
import { deepStrictEqual, strictEqual } from "node:assert";
|
||||
import { llmCompleteMockStorage } from "../../node/utils.js";
|
||||
|
||||
export function getOpenAISession() {
|
||||
return {};
|
||||
}
|
||||
|
||||
export function isFunctionCallingModel() {
|
||||
return true;
|
||||
}
|
||||
|
||||
export class OpenAI implements LLM {
|
||||
supportToolCall = true;
|
||||
get metadata() {
|
||||
return {
|
||||
model: "mock-model",
|
||||
temperature: 0.1,
|
||||
topP: 1,
|
||||
contextWindow: 2048,
|
||||
tokenizer: undefined,
|
||||
isFunctionCallingModel: true,
|
||||
};
|
||||
}
|
||||
chat(
|
||||
params: LLMChatParamsStreaming<Record<string, unknown>>,
|
||||
): Promise<AsyncIterable<ChatResponseChunk>>;
|
||||
chat(
|
||||
params: LLMChatParamsNonStreaming<Record<string, unknown>>,
|
||||
): Promise<ChatResponse>;
|
||||
chat(
|
||||
params:
|
||||
| LLMChatParamsStreaming<Record<string, unknown>>
|
||||
| LLMChatParamsNonStreaming<Record<string, unknown>>,
|
||||
): unknown {
|
||||
if (llmCompleteMockStorage.llmEventStart.length > 0) {
|
||||
const chatMessage =
|
||||
llmCompleteMockStorage.llmEventStart.shift()!["messages"];
|
||||
strictEqual(params.messages.length, chatMessage.length);
|
||||
for (let i = 0; i < chatMessage.length; i++) {
|
||||
strictEqual(params.messages[i].role, chatMessage[i].role);
|
||||
deepStrictEqual(params.messages[i].content, chatMessage[i].content);
|
||||
}
|
||||
|
||||
if (llmCompleteMockStorage.llmEventEnd.length > 0) {
|
||||
const { id, response } = llmCompleteMockStorage.llmEventEnd.shift()!;
|
||||
if (params.stream) {
|
||||
return {
|
||||
[Symbol.asyncIterator]: async function* () {
|
||||
while (true) {
|
||||
const idx = llmCompleteMockStorage.llmEventStream.findIndex(
|
||||
(e) => e.id === id,
|
||||
);
|
||||
if (idx === -1) {
|
||||
break;
|
||||
}
|
||||
const chunk = llmCompleteMockStorage.llmEventStream[idx].chunk;
|
||||
llmCompleteMockStorage.llmEventStream.splice(idx, 1);
|
||||
yield chunk;
|
||||
}
|
||||
},
|
||||
};
|
||||
} else {
|
||||
return response;
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new Error("Method not implemented.");
|
||||
}
|
||||
complete(
|
||||
params: LLMCompletionParamsStreaming,
|
||||
): Promise<AsyncIterable<CompletionResponse>>;
|
||||
complete(
|
||||
params: LLMCompletionParamsNonStreaming,
|
||||
): Promise<CompletionResponse>;
|
||||
async complete(
|
||||
params: LLMCompletionParamsStreaming | LLMCompletionParamsNonStreaming,
|
||||
): Promise<AsyncIterable<CompletionResponse> | CompletionResponse> {
|
||||
if (llmCompleteMockStorage.llmEventStart.length > 0) {
|
||||
const chatMessage =
|
||||
llmCompleteMockStorage.llmEventStart.shift()!["messages"];
|
||||
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"];
|
||||
return {
|
||||
raw: response,
|
||||
text: extractText(response.message.content),
|
||||
} satisfies CompletionResponse;
|
||||
}
|
||||
throw new Error("Method not implemented.");
|
||||
}
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
/* eslint-disable @typescript-eslint/no-floating-promises */
|
||||
import { consola } from "consola";
|
||||
import {
|
||||
OpenAI,
|
||||
OpenAIAgent,
|
||||
Settings,
|
||||
type LLM,
|
||||
type LLMEndEvent,
|
||||
type LLMStartEvent,
|
||||
} from "llamaindex";
|
||||
import { ok } from "node:assert";
|
||||
import type { WriteStream } from "node:fs";
|
||||
import { createWriteStream } from "node:fs";
|
||||
import { mkdir } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { after, before, beforeEach, describe, test } from "node:test";
|
||||
import { inspect } from "node:util";
|
||||
|
||||
let llm: LLM;
|
||||
let fsStream: WriteStream;
|
||||
before(async () => {
|
||||
const logUrl = new URL(
|
||||
join(
|
||||
"..",
|
||||
"logs",
|
||||
`basic.e2e.${new Date().toISOString().replace(/:/g, "-").replace(/\./g, "-")}.log`,
|
||||
),
|
||||
import.meta.url,
|
||||
);
|
||||
await mkdir(new URL(".", logUrl), { recursive: true });
|
||||
fsStream = createWriteStream(logUrl, {
|
||||
encoding: "utf-8",
|
||||
});
|
||||
});
|
||||
|
||||
after(() => {
|
||||
fsStream.end();
|
||||
});
|
||||
|
||||
beforeEach((s) => {
|
||||
fsStream.write("start: " + s.name + "\n");
|
||||
});
|
||||
|
||||
const llmEventStartHandler = (event: LLMStartEvent) => {
|
||||
const { payload } = event.detail;
|
||||
fsStream.write(
|
||||
"llmEventStart: " +
|
||||
inspect(payload, {
|
||||
depth: Infinity,
|
||||
}) +
|
||||
"\n",
|
||||
);
|
||||
};
|
||||
|
||||
const llmEventEndHandler = (event: LLMEndEvent) => {
|
||||
const { payload } = event.detail;
|
||||
fsStream.write(
|
||||
"llmEventEnd: " +
|
||||
inspect(payload, {
|
||||
depth: Infinity,
|
||||
}) +
|
||||
"\n",
|
||||
);
|
||||
};
|
||||
|
||||
before(() => {
|
||||
Settings.llm = new OpenAI({
|
||||
model: "gpt-3.5-turbo",
|
||||
});
|
||||
llm = Settings.llm;
|
||||
Settings.callbackManager.on("llm-start", llmEventStartHandler);
|
||||
Settings.callbackManager.on("llm-end", llmEventEndHandler);
|
||||
});
|
||||
|
||||
after(() => {
|
||||
Settings.callbackManager.off("llm-start", llmEventStartHandler);
|
||||
Settings.callbackManager.off("llm-end", llmEventEndHandler);
|
||||
});
|
||||
|
||||
describe("llm", () => {
|
||||
test("llm.chat", async () => {
|
||||
const response = await llm.chat({
|
||||
messages: [
|
||||
{
|
||||
content: "Hello",
|
||||
role: "user",
|
||||
},
|
||||
],
|
||||
});
|
||||
consola.debug("response:", response);
|
||||
ok(typeof response.message.content === "string");
|
||||
});
|
||||
|
||||
test("stream llm.chat", async () => {
|
||||
const iter = await llm.chat({
|
||||
stream: true,
|
||||
messages: [
|
||||
{
|
||||
content: "hello",
|
||||
role: "user",
|
||||
},
|
||||
],
|
||||
});
|
||||
for await (const chunk of iter) {
|
||||
consola.debug("chunk:", chunk);
|
||||
ok(typeof chunk.delta === "string");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("agent", () => {
|
||||
test("agent.chat", async () => {
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [
|
||||
{
|
||||
call: async () => {
|
||||
return "35 degrees and sunny in San Francisco";
|
||||
},
|
||||
metadata: {
|
||||
name: "Weather",
|
||||
description: "Get the weather",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
location: { type: "string" },
|
||||
},
|
||||
required: ["location"],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
const result = await agent.chat({
|
||||
message: "What is the weather in San Francisco?",
|
||||
});
|
||||
consola.debug("response:", result.response);
|
||||
ok(typeof result.response === "string");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,131 @@
|
||||
import { consola } from "consola";
|
||||
import { Anthropic, FunctionTool, Settings, type LLM } from "llamaindex";
|
||||
import { AnthropicAgent } from "llamaindex/agent/anthropic";
|
||||
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";
|
||||
|
||||
let llm: LLM;
|
||||
beforeEach(async () => {
|
||||
Settings.llm = new Anthropic({
|
||||
model: "claude-3-opus",
|
||||
});
|
||||
llm = Settings.llm;
|
||||
});
|
||||
|
||||
await test("anthropic llm", async (t) => {
|
||||
await mockLLMEvent(t, "llm-anthropic");
|
||||
await t.test("llm.chat", async () => {
|
||||
const response = await llm.chat({
|
||||
messages: [
|
||||
{
|
||||
content: "Hello",
|
||||
role: "user",
|
||||
options: {},
|
||||
},
|
||||
],
|
||||
});
|
||||
consola.debug("response:", response);
|
||||
ok(typeof response.message.content === "string");
|
||||
});
|
||||
|
||||
await t.test("stream llm.chat", async () => {
|
||||
const iter = await llm.chat({
|
||||
stream: true,
|
||||
messages: [
|
||||
{
|
||||
content: "hello",
|
||||
role: "user",
|
||||
},
|
||||
],
|
||||
});
|
||||
for await (const chunk of iter) {
|
||||
consola.debug("chunk:", chunk);
|
||||
ok(typeof chunk.delta === "string");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
await test("anthropic agent", async (t) => {
|
||||
await mockLLMEvent(t, "anthropic-agent");
|
||||
await t.test("chat", async () => {
|
||||
const agent = new AnthropicAgent({
|
||||
tools: [
|
||||
{
|
||||
call: async () => {
|
||||
return "35 degrees and sunny in San Francisco";
|
||||
},
|
||||
metadata: {
|
||||
name: "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("35"));
|
||||
});
|
||||
|
||||
await t.test("async function", async () => {
|
||||
const uniqueId = "123456789";
|
||||
const showUniqueId = FunctionTool.from<{
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
}>(
|
||||
async ({ firstName, lastName }) => {
|
||||
ok(typeof firstName === "string");
|
||||
ok(typeof lastName === "string");
|
||||
const fullName = firstName + lastName;
|
||||
ok(fullName.toLowerCase().includes("alex"));
|
||||
ok(fullName.toLowerCase().includes("yang"));
|
||||
return uniqueId;
|
||||
},
|
||||
{
|
||||
name: "unique_id",
|
||||
description: "show user unique id",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
firstName: { type: "string" },
|
||||
lastName: { type: "string" },
|
||||
},
|
||||
required: ["firstName", "lastName"],
|
||||
},
|
||||
},
|
||||
);
|
||||
const agent = new AnthropicAgent({
|
||||
tools: [showUniqueId],
|
||||
});
|
||||
const { response } = await agent.chat({
|
||||
message: "My name is Alex Yang. What is my unique id?",
|
||||
});
|
||||
consola.debug("response:", response.message.content);
|
||||
ok(extractText(response.message.content).includes(uniqueId));
|
||||
});
|
||||
|
||||
await t.test("sum numbers", async () => {
|
||||
const openaiAgent = new AnthropicAgent({
|
||||
tools: [sumNumbersTool],
|
||||
});
|
||||
|
||||
const { response } = await openaiAgent.chat({
|
||||
message: "how much is 1 + 1?",
|
||||
});
|
||||
|
||||
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.
|
||||
@@ -0,0 +1,68 @@
|
||||
import { FunctionTool } from "llamaindex";
|
||||
|
||||
function sumNumbers({ a, b }: { a: number; b: number }) {
|
||||
return `${a + b}`;
|
||||
}
|
||||
|
||||
function divideNumbers({ a, b }: { a: number; b: number }) {
|
||||
return `${a / b}`;
|
||||
}
|
||||
|
||||
export const sumNumbersTool = FunctionTool.from(sumNumbers, {
|
||||
name: "sumNumbers",
|
||||
description: "Use this function to sum two numbers",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The first number",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The second number",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
},
|
||||
});
|
||||
|
||||
export const divideNumbersTool = FunctionTool.from(divideNumbers, {
|
||||
name: "divideNumbers",
|
||||
description: "Use this function to divide two numbers",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The first number",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The second number",
|
||||
},
|
||||
},
|
||||
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"],
|
||||
},
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,381 @@
|
||||
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,
|
||||
getWeatherTool,
|
||||
sumNumbersTool,
|
||||
} from "./fixtures/tools.js";
|
||||
import { mockLLMEvent, testRootDir } from "./utils.js";
|
||||
|
||||
let llm: LLM;
|
||||
beforeEach(async () => {
|
||||
Settings.llm = new OpenAI({
|
||||
model: "gpt-3.5-turbo",
|
||||
});
|
||||
llm = Settings.llm;
|
||||
});
|
||||
|
||||
await test("openai llm", async (t) => {
|
||||
await mockLLMEvent(t, "llm");
|
||||
await t.test("llm.chat", async () => {
|
||||
const response = await llm.chat({
|
||||
messages: [
|
||||
{
|
||||
content: "Hello",
|
||||
role: "user",
|
||||
},
|
||||
],
|
||||
});
|
||||
consola.debug("response:", response);
|
||||
ok(typeof response.message.content === "string");
|
||||
});
|
||||
|
||||
await t.test("stream llm.chat", async () => {
|
||||
const iter = await llm.chat({
|
||||
stream: true,
|
||||
messages: [
|
||||
{
|
||||
content: "hello",
|
||||
role: "user",
|
||||
},
|
||||
],
|
||||
});
|
||||
for await (const chunk of iter) {
|
||||
consola.debug("chunk:", chunk);
|
||||
ok(typeof chunk.delta === "string");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
await test("gpt-4-turbo", async (t) => {
|
||||
const llm = new OpenAI({ model: "gpt-4-turbo" });
|
||||
Settings.llm = llm;
|
||||
await mockLLMEvent(t, "gpt-4-turbo");
|
||||
await t.test("agent", async () => {
|
||||
const agent = new OpenAIAgent({
|
||||
llm,
|
||||
tools: [
|
||||
{
|
||||
call: async () => {
|
||||
return "45 degrees and sunny in San Jose";
|
||||
},
|
||||
metadata: {
|
||||
name: "Weather",
|
||||
description: "Get the weather",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
location: { type: "string" },
|
||||
},
|
||||
required: ["location"],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
const { response } = await agent.chat({
|
||||
message: "What is the weather in San Jose?",
|
||||
});
|
||||
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"));
|
||||
});
|
||||
});
|
||||
|
||||
await test("agent", async (t) => {
|
||||
await mockLLMEvent(t, "agent");
|
||||
await t.test("chat", async () => {
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [
|
||||
{
|
||||
call: async () => {
|
||||
return "35 degrees and sunny in San Francisco";
|
||||
},
|
||||
metadata: {
|
||||
name: "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("35"));
|
||||
});
|
||||
|
||||
await t.test("async function", async () => {
|
||||
const uniqueId = "123456789";
|
||||
const showUniqueId = FunctionTool.from<{
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
}>(
|
||||
async ({ firstName, lastName }) => {
|
||||
ok(typeof firstName === "string");
|
||||
ok(typeof lastName === "string");
|
||||
const fullName = firstName + lastName;
|
||||
ok(fullName.toLowerCase().includes("alex"));
|
||||
ok(fullName.toLowerCase().includes("yang"));
|
||||
return uniqueId;
|
||||
},
|
||||
{
|
||||
name: "unique_id",
|
||||
description: "show user unique id",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
firstName: { type: "string" },
|
||||
lastName: { type: "string" },
|
||||
},
|
||||
required: ["firstName", "lastName"],
|
||||
},
|
||||
},
|
||||
);
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [showUniqueId],
|
||||
});
|
||||
const { response, sources } = await agent.chat({
|
||||
message: "My name is Alex Yang. What is my unique id?",
|
||||
});
|
||||
strictEqual(sources.length, 1);
|
||||
ok(extractText(response.message.content).includes(uniqueId));
|
||||
});
|
||||
|
||||
await t.test("sum numbers", async () => {
|
||||
const openaiAgent = new OpenAIAgent({
|
||||
tools: [sumNumbersTool],
|
||||
});
|
||||
|
||||
const { response, sources } = await openaiAgent.chat({
|
||||
message: "how much is 1 + 1?",
|
||||
});
|
||||
|
||||
strictEqual(sources.length, 1);
|
||||
ok(extractText(response.message.content).includes("2"));
|
||||
});
|
||||
});
|
||||
|
||||
await test("agent stream", async (t) => {
|
||||
await mockLLMEvent(t, "agent_stream");
|
||||
await t.test("sum numbers stream", async (t) => {
|
||||
const fn = t.mock.fn(() => {});
|
||||
Settings.callbackManager.on("llm-tool-call", fn);
|
||||
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [sumNumbersTool, divideNumbersTool],
|
||||
});
|
||||
|
||||
const stream = await agent.chat({
|
||||
message: "Divide 16 by 2 then add 20",
|
||||
stream: true,
|
||||
});
|
||||
|
||||
let message = "";
|
||||
let soruces: ToolOutput[] = [];
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
|
||||
await test("queryEngine", async (t) => {
|
||||
await mockLLMEvent(t, "queryEngine_subquestion");
|
||||
await t.test("subquestion", async () => {
|
||||
const fn = t.mock.fn(() => {});
|
||||
Settings.callbackManager.on("llm-tool-call", fn);
|
||||
const document = new Document({
|
||||
text: "Bill Gates stole from Apple.\n Steve Jobs stole from Xerox.",
|
||||
});
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
const queryEngineTools = [
|
||||
new QueryEngineTool({
|
||||
queryEngine: index.asQueryEngine(),
|
||||
metadata: {
|
||||
name: "bill_gates_idea",
|
||||
description: "Get what Bill Gates idea from.",
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
const queryEngine = SubQuestionQueryEngine.fromDefaults({
|
||||
queryEngineTools,
|
||||
});
|
||||
|
||||
const { response } = await queryEngine.query({
|
||||
query: "What did Bill Gates steal from?",
|
||||
});
|
||||
|
||||
ok(response.includes("Apple"));
|
||||
strictEqual(fn.mock.callCount(), 0);
|
||||
Settings.callbackManager.off("llm-tool-call", fn);
|
||||
});
|
||||
});
|
||||
@@ -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"));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,370 @@
|
||||
{
|
||||
"llmEventStart": [
|
||||
{
|
||||
"id": "PRESERVE_0",
|
||||
"messages": [
|
||||
{
|
||||
"content": "What is the weather in San Francisco?",
|
||||
"role": "user"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"messages": [
|
||||
{
|
||||
"content": "What is the weather in San Francisco?",
|
||||
"role": "user"
|
||||
},
|
||||
{
|
||||
"content": "",
|
||||
"role": "assistant",
|
||||
"options": {
|
||||
"toolCall": {
|
||||
"id": "HIDDEN",
|
||||
"name": "Weather",
|
||||
"input": "{\"location\":\"San Francisco\"}"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"content": "35 degrees and sunny in San Francisco",
|
||||
"role": "user",
|
||||
"options": {
|
||||
"toolResult": {
|
||||
"id": "HIDDEN",
|
||||
"isError": false
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_2",
|
||||
"messages": [
|
||||
{
|
||||
"content": "My name is Alex Yang. What is my unique id?",
|
||||
"role": "user"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_3",
|
||||
"messages": [
|
||||
{
|
||||
"content": "My name is Alex Yang. What is my unique id?",
|
||||
"role": "user"
|
||||
},
|
||||
{
|
||||
"content": "",
|
||||
"role": "assistant",
|
||||
"options": {
|
||||
"toolCall": {
|
||||
"id": "HIDDEN",
|
||||
"name": "unique_id",
|
||||
"input": "{\"firstName\":\"Alex\",\"lastName\":\"Yang\"}"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"content": "123456789",
|
||||
"role": "user",
|
||||
"options": {
|
||||
"toolResult": {
|
||||
"id": "HIDDEN",
|
||||
"isError": false
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_4",
|
||||
"messages": [
|
||||
{
|
||||
"content": "how much is 1 + 1?",
|
||||
"role": "user"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_5",
|
||||
"messages": [
|
||||
{
|
||||
"content": "how much is 1 + 1?",
|
||||
"role": "user"
|
||||
},
|
||||
{
|
||||
"content": "",
|
||||
"role": "assistant",
|
||||
"options": {
|
||||
"toolCall": {
|
||||
"id": "HIDDEN",
|
||||
"name": "sumNumbers",
|
||||
"input": "{\"a\":1,\"b\":1}"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"content": "2",
|
||||
"role": "user",
|
||||
"options": {
|
||||
"toolResult": {
|
||||
"id": "HIDDEN",
|
||||
"isError": false
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"llmEventEnd": [
|
||||
{
|
||||
"id": "PRESERVE_0",
|
||||
"response": {
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"object": "chat.completion",
|
||||
"created": 114514,
|
||||
"model": "gpt-3.5-turbo-0125",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"message": {
|
||||
"role": "assistant",
|
||||
"content": null,
|
||||
"tool_calls": [
|
||||
{
|
||||
"id": "HIDDEN",
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "Weather",
|
||||
"arguments": "{\"location\":\"San Francisco\"}"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"logprobs": null,
|
||||
"finish_reason": "tool_calls"
|
||||
}
|
||||
],
|
||||
"usage": {
|
||||
"prompt_tokens": 49,
|
||||
"completion_tokens": 15,
|
||||
"total_tokens": 64
|
||||
},
|
||||
"system_fingerprint": "HIDDEN"
|
||||
},
|
||||
"message": {
|
||||
"content": "",
|
||||
"role": "assistant",
|
||||
"options": {
|
||||
"toolCall": {
|
||||
"id": "HIDDEN",
|
||||
"name": "Weather",
|
||||
"input": "{\"location\":\"San Francisco\"}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"response": {
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"object": "chat.completion",
|
||||
"created": 114514,
|
||||
"model": "gpt-3.5-turbo-0125",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"message": {
|
||||
"role": "assistant",
|
||||
"content": "The weather in San Francisco is currently 35 degrees and sunny."
|
||||
},
|
||||
"logprobs": null,
|
||||
"finish_reason": "stop"
|
||||
}
|
||||
],
|
||||
"usage": {
|
||||
"prompt_tokens": 78,
|
||||
"completion_tokens": 14,
|
||||
"total_tokens": 92
|
||||
},
|
||||
"system_fingerprint": "HIDDEN"
|
||||
},
|
||||
"message": {
|
||||
"content": "The weather in San Francisco is currently 35 degrees and sunny.",
|
||||
"role": "assistant",
|
||||
"options": {}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_2",
|
||||
"response": {
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"object": "chat.completion",
|
||||
"created": 114514,
|
||||
"model": "gpt-3.5-turbo-0125",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"message": {
|
||||
"role": "assistant",
|
||||
"content": null,
|
||||
"tool_calls": [
|
||||
{
|
||||
"id": "HIDDEN",
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "unique_id",
|
||||
"arguments": "{\"firstName\":\"Alex\",\"lastName\":\"Yang\"}"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"logprobs": null,
|
||||
"finish_reason": "tool_calls"
|
||||
}
|
||||
],
|
||||
"usage": {
|
||||
"prompt_tokens": 59,
|
||||
"completion_tokens": 18,
|
||||
"total_tokens": 77
|
||||
},
|
||||
"system_fingerprint": "HIDDEN"
|
||||
},
|
||||
"message": {
|
||||
"content": "",
|
||||
"role": "assistant",
|
||||
"options": {
|
||||
"toolCall": {
|
||||
"id": "HIDDEN",
|
||||
"name": "unique_id",
|
||||
"input": "{\"firstName\":\"Alex\",\"lastName\":\"Yang\"}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_3",
|
||||
"response": {
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"object": "chat.completion",
|
||||
"created": 114514,
|
||||
"model": "gpt-3.5-turbo-0125",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"message": {
|
||||
"role": "assistant",
|
||||
"content": "Your unique id is 123456789."
|
||||
},
|
||||
"logprobs": null,
|
||||
"finish_reason": "stop"
|
||||
}
|
||||
],
|
||||
"usage": {
|
||||
"prompt_tokens": 88,
|
||||
"completion_tokens": 10,
|
||||
"total_tokens": 98
|
||||
},
|
||||
"system_fingerprint": "HIDDEN"
|
||||
},
|
||||
"message": {
|
||||
"content": "Your unique id is 123456789.",
|
||||
"role": "assistant",
|
||||
"options": {}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_4",
|
||||
"response": {
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"object": "chat.completion",
|
||||
"created": 114514,
|
||||
"model": "gpt-3.5-turbo-0125",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"message": {
|
||||
"role": "assistant",
|
||||
"content": null,
|
||||
"tool_calls": [
|
||||
{
|
||||
"id": "HIDDEN",
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "sumNumbers",
|
||||
"arguments": "{\"a\":1,\"b\":1}"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"logprobs": null,
|
||||
"finish_reason": "tool_calls"
|
||||
}
|
||||
],
|
||||
"usage": {
|
||||
"prompt_tokens": 70,
|
||||
"completion_tokens": 18,
|
||||
"total_tokens": 88
|
||||
},
|
||||
"system_fingerprint": "HIDDEN"
|
||||
},
|
||||
"message": {
|
||||
"content": "",
|
||||
"role": "assistant",
|
||||
"options": {
|
||||
"toolCall": {
|
||||
"id": "HIDDEN",
|
||||
"name": "sumNumbers",
|
||||
"input": "{\"a\":1,\"b\":1}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_5",
|
||||
"response": {
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"object": "chat.completion",
|
||||
"created": 114514,
|
||||
"model": "gpt-3.5-turbo-0125",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"message": {
|
||||
"role": "assistant",
|
||||
"content": "1 + 1 is equal to 2."
|
||||
},
|
||||
"logprobs": null,
|
||||
"finish_reason": "stop"
|
||||
}
|
||||
],
|
||||
"usage": {
|
||||
"prompt_tokens": 97,
|
||||
"completion_tokens": 11,
|
||||
"total_tokens": 108
|
||||
},
|
||||
"system_fingerprint": "HIDDEN"
|
||||
},
|
||||
"message": {
|
||||
"content": "1 + 1 is equal to 2.",
|
||||
"role": "assistant",
|
||||
"options": {}
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"llmEventStream": []
|
||||
}
|
||||
@@ -0,0 +1,382 @@
|
||||
{
|
||||
"llmEventStart": [
|
||||
{
|
||||
"id": "PRESERVE_0",
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Divide 16 by 2 then add 20"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Divide 16 by 2 then add 20"
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"options": {
|
||||
"toolCall": {
|
||||
"name": "divideNumbers",
|
||||
"id": "call_t0vy4M815ncAQnfRqoflW5hn",
|
||||
"input": "{\"a\": 16, \"b\": 2}"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "8",
|
||||
"options": {
|
||||
"toolResult": {
|
||||
"result": "8",
|
||||
"isError": false,
|
||||
"id": "call_t0vy4M815ncAQnfRqoflW5hn"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"options": {
|
||||
"toolCall": {
|
||||
"name": "sumNumbers",
|
||||
"id": "call_08QNOtWYlDoqPPXHMtbvr7A2",
|
||||
"input": "{\"a\": 8, \"b\": 20}"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "28",
|
||||
"options": {
|
||||
"toolResult": {
|
||||
"result": "28",
|
||||
"isError": false,
|
||||
"id": "call_08QNOtWYlDoqPPXHMtbvr7A2"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"llmEventEnd": [
|
||||
{
|
||||
"id": "PRESERVE_0",
|
||||
"response": {
|
||||
"raw": null,
|
||||
"message": {
|
||||
"content": "",
|
||||
"role": "assistant",
|
||||
"options": {
|
||||
"toolCall": {
|
||||
"name": "sumNumbers",
|
||||
"id": "call_08QNOtWYlDoqPPXHMtbvr7A2",
|
||||
"input": "{\"a\": 8, \"b\": 20}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"response": {
|
||||
"raw": null,
|
||||
"message": {
|
||||
"content": "The result of dividing 16 by 2 and then adding 20 is 28.",
|
||||
"role": "assistant",
|
||||
"options": {}
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"llmEventStream": [
|
||||
{
|
||||
"id": "PRESERVE_0",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {
|
||||
"toolCall": {
|
||||
"name": "divideNumbers",
|
||||
"id": "call_t0vy4M815ncAQnfRqoflW5hn",
|
||||
"input": "{\"a\": 16, \"b\": 2}"
|
||||
}
|
||||
},
|
||||
"delta": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_0",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {
|
||||
"toolCall": {
|
||||
"name": "divideNumbers",
|
||||
"id": "call_t0vy4M815ncAQnfRqoflW5hn",
|
||||
"input": "{\"a\": 16, \"b\": 2}"
|
||||
}
|
||||
},
|
||||
"delta": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_0",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {
|
||||
"toolCall": {
|
||||
"name": "divideNumbers",
|
||||
"id": "call_t0vy4M815ncAQnfRqoflW5hn",
|
||||
"input": "{\"a\": 16, \"b\": 2}"
|
||||
}
|
||||
},
|
||||
"delta": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_0",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {
|
||||
"toolCall": {
|
||||
"name": "divideNumbers",
|
||||
"id": "call_t0vy4M815ncAQnfRqoflW5hn",
|
||||
"input": "{\"a\": 16, \"b\": 2}"
|
||||
}
|
||||
},
|
||||
"delta": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_0",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {
|
||||
"toolCall": {
|
||||
"name": "divideNumbers",
|
||||
"id": "call_t0vy4M815ncAQnfRqoflW5hn",
|
||||
"input": "{\"a\": 16, \"b\": 2}"
|
||||
}
|
||||
},
|
||||
"delta": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_0",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {
|
||||
"toolCall": {
|
||||
"name": "sumNumbers",
|
||||
"id": "call_08QNOtWYlDoqPPXHMtbvr7A2",
|
||||
"input": "{\"a\": 8, \"b\": 20}"
|
||||
}
|
||||
},
|
||||
"delta": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_0",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {
|
||||
"toolCall": {
|
||||
"name": "sumNumbers",
|
||||
"id": "call_08QNOtWYlDoqPPXHMtbvr7A2",
|
||||
"input": "{\"a\": 8, \"b\": 20}"
|
||||
}
|
||||
},
|
||||
"delta": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_0",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {
|
||||
"toolCall": {
|
||||
"name": "sumNumbers",
|
||||
"id": "call_08QNOtWYlDoqPPXHMtbvr7A2",
|
||||
"input": "{\"a\": 8, \"b\": 20}"
|
||||
}
|
||||
},
|
||||
"delta": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_0",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {
|
||||
"toolCall": {
|
||||
"name": "sumNumbers",
|
||||
"id": "call_08QNOtWYlDoqPPXHMtbvr7A2",
|
||||
"input": "{\"a\": 8, \"b\": 20}"
|
||||
}
|
||||
},
|
||||
"delta": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_0",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {
|
||||
"toolCall": {
|
||||
"name": "sumNumbers",
|
||||
"id": "call_08QNOtWYlDoqPPXHMtbvr7A2",
|
||||
"input": "{\"a\": 8, \"b\": 20}"
|
||||
}
|
||||
},
|
||||
"delta": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": "The"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": " result"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": " of"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": " dividing"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": " "
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": "16"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": " by"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": " "
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": "2"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": " and"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": " then"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": " adding"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": " "
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": "20"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": " is"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": " "
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": "28"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": "."
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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,403 @@
|
||||
{
|
||||
"llmEventStart": [
|
||||
{
|
||||
"id": "PRESERVE_0",
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "What is the weather in San Francisco?",
|
||||
"options": {}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "What is the weather in San Francisco?",
|
||||
"options": {}
|
||||
},
|
||||
{
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user is asking for the weather in a specific location, San Francisco. The Weather function is the relevant tool to answer this request, as it returns weather information for a given location.\n\nThe Weather function has one required parameter:\n- location (string): The user has directly provided the location of \"San Francisco\"\n\nSince the required location parameter has been provided by the user, we have all the necessary information to call the Weather function.\n</thinking>"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
"options": {
|
||||
"toolCall": {
|
||||
"id": "HIDDEN",
|
||||
"name": "Weather",
|
||||
"input": {
|
||||
"location": "San Francisco"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"content": "35 degrees and sunny in San Francisco",
|
||||
"role": "user",
|
||||
"options": {
|
||||
"toolResult": {
|
||||
"isError": false,
|
||||
"id": "HIDDEN"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_2",
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "My name is Alex Yang. What is my unique id?",
|
||||
"options": {}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_3",
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "My name is Alex Yang. What is my unique id?",
|
||||
"options": {}
|
||||
},
|
||||
{
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe unique_id function is the relevant tool to answer the user's request for their unique ID. It requires two parameters:\nfirstName: The user provided their first name, which is \"Alex\"\nlastName: The user also provided their last name, \"Yang\"\nSince the user has provided all the required parameters, we can proceed with calling the unique_id function.\n</thinking>"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
"options": {
|
||||
"toolCall": {
|
||||
"id": "HIDDEN",
|
||||
"name": "unique_id",
|
||||
"input": {
|
||||
"firstName": "Alex",
|
||||
"lastName": "Yang"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"content": "123456789",
|
||||
"role": "user",
|
||||
"options": {
|
||||
"toolResult": {
|
||||
"isError": false,
|
||||
"id": "HIDDEN"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_4",
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "how much is 1 + 1?",
|
||||
"options": {}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_5",
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "how much is 1 + 1?",
|
||||
"options": {}
|
||||
},
|
||||
{
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user is asking to sum the numbers 1 and 1. The relevant tool to use is the sumNumbers function, which takes two number parameters a and b.\nThe user has directly provided the values for the parameters:\na = 1 \nb = 1\nSince all the required parameters have been provided, we can proceed with calling the function.\n</thinking>"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
"options": {
|
||||
"toolCall": {
|
||||
"id": "HIDDEN",
|
||||
"name": "sumNumbers",
|
||||
"input": {
|
||||
"a": 1,
|
||||
"b": 1
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"content": "2",
|
||||
"role": "user",
|
||||
"options": {
|
||||
"toolResult": {
|
||||
"isError": false,
|
||||
"id": "HIDDEN"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"llmEventEnd": [
|
||||
{
|
||||
"id": "PRESERVE_0",
|
||||
"response": {
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"type": "message",
|
||||
"role": "assistant",
|
||||
"model": "claude-3-opus-20240229",
|
||||
"stop_sequence": null,
|
||||
"usage": {
|
||||
"input_tokens": 462,
|
||||
"output_tokens": 147
|
||||
},
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user is asking for the weather in a specific location, San Francisco. The Weather function is the relevant tool to answer this request, as it returns weather information for a given location.\n\nThe Weather function has one required parameter:\n- location (string): The user has directly provided the location of \"San Francisco\"\n\nSince the required location parameter has been provided by the user, we have all the necessary information to call the Weather function.\n</thinking>"
|
||||
},
|
||||
{
|
||||
"type": "tool_use",
|
||||
"id": "HIDDEN",
|
||||
"name": "Weather",
|
||||
"input": {
|
||||
"location": "San Francisco"
|
||||
}
|
||||
}
|
||||
],
|
||||
"stop_reason": "tool_use"
|
||||
},
|
||||
"message": {
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user is asking for the weather in a specific location, San Francisco. The Weather function is the relevant tool to answer this request, as it returns weather information for a given location.\n\nThe Weather function has one required parameter:\n- location (string): The user has directly provided the location of \"San Francisco\"\n\nSince the required location parameter has been provided by the user, we have all the necessary information to call the Weather function.\n</thinking>"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
"options": {
|
||||
"toolCall": {
|
||||
"id": "HIDDEN",
|
||||
"name": "Weather",
|
||||
"input": {
|
||||
"location": "San Francisco"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"response": {
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"type": "message",
|
||||
"role": "assistant",
|
||||
"model": "claude-3-opus-20240229",
|
||||
"stop_sequence": null,
|
||||
"usage": {
|
||||
"input_tokens": 628,
|
||||
"output_tokens": 18
|
||||
},
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "The current weather in San Francisco is 35 degrees and sunny."
|
||||
}
|
||||
],
|
||||
"stop_reason": "end_turn"
|
||||
},
|
||||
"message": {
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "The current weather in San Francisco is 35 degrees and sunny."
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
"options": {}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_2",
|
||||
"response": {
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"type": "message",
|
||||
"role": "assistant",
|
||||
"model": "claude-3-opus-20240229",
|
||||
"stop_sequence": null,
|
||||
"usage": {
|
||||
"input_tokens": 482,
|
||||
"output_tokens": 152
|
||||
},
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe unique_id function is the relevant tool to answer the user's request for their unique ID. It requires two parameters:\nfirstName: The user provided their first name, which is \"Alex\"\nlastName: The user also provided their last name, \"Yang\"\nSince the user has provided all the required parameters, we can proceed with calling the unique_id function.\n</thinking>"
|
||||
},
|
||||
{
|
||||
"type": "tool_use",
|
||||
"id": "HIDDEN",
|
||||
"name": "unique_id",
|
||||
"input": {
|
||||
"firstName": "Alex",
|
||||
"lastName": "Yang"
|
||||
}
|
||||
}
|
||||
],
|
||||
"stop_reason": "tool_use"
|
||||
},
|
||||
"message": {
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe unique_id function is the relevant tool to answer the user's request for their unique ID. It requires two parameters:\nfirstName: The user provided their first name, which is \"Alex\"\nlastName: The user also provided their last name, \"Yang\"\nSince the user has provided all the required parameters, we can proceed with calling the unique_id function.\n</thinking>"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
"options": {
|
||||
"toolCall": {
|
||||
"id": "HIDDEN",
|
||||
"name": "unique_id",
|
||||
"input": {
|
||||
"firstName": "Alex",
|
||||
"lastName": "Yang"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_3",
|
||||
"response": {
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"type": "message",
|
||||
"role": "assistant",
|
||||
"model": "claude-3-opus-20240229",
|
||||
"stop_sequence": null,
|
||||
"usage": {
|
||||
"input_tokens": 648,
|
||||
"output_tokens": 13
|
||||
},
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "Your unique ID is 123456789."
|
||||
}
|
||||
],
|
||||
"stop_reason": "end_turn"
|
||||
},
|
||||
"message": {
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "Your unique ID is 123456789."
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
"options": {}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_4",
|
||||
"response": {
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"type": "message",
|
||||
"role": "assistant",
|
||||
"model": "claude-3-opus-20240229",
|
||||
"stop_sequence": null,
|
||||
"usage": {
|
||||
"input_tokens": 498,
|
||||
"output_tokens": 151
|
||||
},
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user is asking to sum the numbers 1 and 1. The relevant tool to use is the sumNumbers function, which takes two number parameters a and b.\nThe user has directly provided the values for the parameters:\na = 1 \nb = 1\nSince all the required parameters have been provided, we can proceed with calling the function.\n</thinking>"
|
||||
},
|
||||
{
|
||||
"type": "tool_use",
|
||||
"id": "HIDDEN",
|
||||
"name": "sumNumbers",
|
||||
"input": {
|
||||
"a": 1,
|
||||
"b": 1
|
||||
}
|
||||
}
|
||||
],
|
||||
"stop_reason": "tool_use"
|
||||
},
|
||||
"message": {
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user is asking to sum the numbers 1 and 1. The relevant tool to use is the sumNumbers function, which takes two number parameters a and b.\nThe user has directly provided the values for the parameters:\na = 1 \nb = 1\nSince all the required parameters have been provided, we can proceed with calling the function.\n</thinking>"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
"options": {
|
||||
"toolCall": {
|
||||
"id": "HIDDEN",
|
||||
"name": "sumNumbers",
|
||||
"input": {
|
||||
"a": 1,
|
||||
"b": 1
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_5",
|
||||
"response": {
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"type": "message",
|
||||
"role": "assistant",
|
||||
"model": "claude-3-opus-20240229",
|
||||
"stop_sequence": null,
|
||||
"usage": {
|
||||
"input_tokens": 661,
|
||||
"output_tokens": 16
|
||||
},
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "So 1 + 1 = 2."
|
||||
}
|
||||
],
|
||||
"stop_reason": "end_turn"
|
||||
},
|
||||
"message": {
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "So 1 + 1 = 2."
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
"options": {}
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"llmEventStream": []
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
{
|
||||
"llmEventStart": [
|
||||
{
|
||||
"id": "PRESERVE_0",
|
||||
"messages": [
|
||||
{
|
||||
"content": "What is the weather in San Jose?",
|
||||
"role": "user"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"messages": [
|
||||
{
|
||||
"content": "What is the weather in San Jose?",
|
||||
"role": "user"
|
||||
},
|
||||
{
|
||||
"content": "",
|
||||
"role": "assistant",
|
||||
"options": {
|
||||
"toolCall": {
|
||||
"id": "HIDDEN",
|
||||
"name": "Weather",
|
||||
"input": "{\"location\":\"San Jose\"}"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"content": "45 degrees and sunny in San Jose",
|
||||
"role": "user",
|
||||
"options": {
|
||||
"toolResult": {
|
||||
"id": "HIDDEN",
|
||||
"isError": false
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"llmEventEnd": [
|
||||
{
|
||||
"id": "PRESERVE_0",
|
||||
"response": {
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"object": "chat.completion",
|
||||
"created": 114514,
|
||||
"model": "gpt-3.5-turbo-0125",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"message": {
|
||||
"role": "assistant",
|
||||
"content": null,
|
||||
"tool_calls": [
|
||||
{
|
||||
"id": "HIDDEN",
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "Weather",
|
||||
"arguments": "{\"location\":\"San Jose\"}"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"logprobs": null,
|
||||
"finish_reason": "tool_calls"
|
||||
}
|
||||
],
|
||||
"usage": {
|
||||
"prompt_tokens": 49,
|
||||
"completion_tokens": 15,
|
||||
"total_tokens": 64
|
||||
},
|
||||
"system_fingerprint": "HIDDEN"
|
||||
},
|
||||
"message": {
|
||||
"content": "",
|
||||
"role": "assistant",
|
||||
"options": {
|
||||
"toolCall": {
|
||||
"id": "HIDDEN",
|
||||
"name": "Weather",
|
||||
"input": "{\"location\":\"San Jose\"}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"response": {
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"object": "chat.completion",
|
||||
"created": 114514,
|
||||
"model": "gpt-3.5-turbo-0125",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"message": {
|
||||
"role": "assistant",
|
||||
"content": "The weather in San Jose is currently 45 degrees and sunny."
|
||||
},
|
||||
"logprobs": null,
|
||||
"finish_reason": "stop"
|
||||
}
|
||||
],
|
||||
"usage": {
|
||||
"prompt_tokens": 78,
|
||||
"completion_tokens": 14,
|
||||
"total_tokens": 92
|
||||
},
|
||||
"system_fingerprint": "HIDDEN"
|
||||
},
|
||||
"message": {
|
||||
"content": "The weather in San Jose is currently 45 degrees and sunny.",
|
||||
"role": "assistant",
|
||||
"options": {}
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"llmEventStream": []
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
{
|
||||
"llmEventStart": [
|
||||
{
|
||||
"id": "PRESERVE_0",
|
||||
"messages": [
|
||||
{
|
||||
"content": "Hello",
|
||||
"role": "user",
|
||||
"options": {}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"messages": [
|
||||
{
|
||||
"content": "hello",
|
||||
"role": "user"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"llmEventEnd": [
|
||||
{
|
||||
"id": "PRESERVE_0",
|
||||
"response": {
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"type": "message",
|
||||
"role": "assistant",
|
||||
"model": "claude-3-opus-20240229",
|
||||
"stop_sequence": null,
|
||||
"usage": {
|
||||
"input_tokens": 8,
|
||||
"output_tokens": 12
|
||||
},
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "Hello! How can I assist you today?"
|
||||
}
|
||||
],
|
||||
"stop_reason": "end_turn"
|
||||
},
|
||||
"message": {
|
||||
"content": "Hello! How can I assist you today?",
|
||||
"role": "assistant",
|
||||
"options": {}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"response": {
|
||||
"raw": [
|
||||
{
|
||||
"raw": {
|
||||
"type": "content_block_delta",
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"type": "text_delta",
|
||||
"text": "Hello"
|
||||
}
|
||||
},
|
||||
"delta": "Hello",
|
||||
"options": {}
|
||||
},
|
||||
{
|
||||
"raw": {
|
||||
"type": "content_block_delta",
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"type": "text_delta",
|
||||
"text": "!"
|
||||
}
|
||||
},
|
||||
"delta": "!",
|
||||
"options": {}
|
||||
},
|
||||
{
|
||||
"raw": {
|
||||
"type": "content_block_delta",
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"type": "text_delta",
|
||||
"text": " How"
|
||||
}
|
||||
},
|
||||
"delta": " How",
|
||||
"options": {}
|
||||
},
|
||||
{
|
||||
"raw": {
|
||||
"type": "content_block_delta",
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"type": "text_delta",
|
||||
"text": " can"
|
||||
}
|
||||
},
|
||||
"delta": " can",
|
||||
"options": {}
|
||||
},
|
||||
{
|
||||
"raw": {
|
||||
"type": "content_block_delta",
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"type": "text_delta",
|
||||
"text": " I"
|
||||
}
|
||||
},
|
||||
"delta": " I",
|
||||
"options": {}
|
||||
},
|
||||
{
|
||||
"raw": {
|
||||
"type": "content_block_delta",
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"type": "text_delta",
|
||||
"text": " assist"
|
||||
}
|
||||
},
|
||||
"delta": " assist",
|
||||
"options": {}
|
||||
},
|
||||
{
|
||||
"raw": {
|
||||
"type": "content_block_delta",
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"type": "text_delta",
|
||||
"text": " you"
|
||||
}
|
||||
},
|
||||
"delta": " you",
|
||||
"options": {}
|
||||
},
|
||||
{
|
||||
"raw": {
|
||||
"type": "content_block_delta",
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"type": "text_delta",
|
||||
"text": " today"
|
||||
}
|
||||
},
|
||||
"delta": " today",
|
||||
"options": {}
|
||||
},
|
||||
{
|
||||
"raw": {
|
||||
"type": "content_block_delta",
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"type": "text_delta",
|
||||
"text": "?"
|
||||
}
|
||||
},
|
||||
"delta": "?",
|
||||
"options": {}
|
||||
}
|
||||
],
|
||||
"message": {
|
||||
"content": "Hello! How can I assist you today?",
|
||||
"role": "assistant",
|
||||
"options": {}
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"llmEventStream": [
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": {
|
||||
"type": "content_block_delta",
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"type": "text_delta",
|
||||
"text": "Hello"
|
||||
}
|
||||
},
|
||||
"delta": "Hello",
|
||||
"options": {}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": {
|
||||
"type": "content_block_delta",
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"type": "text_delta",
|
||||
"text": "!"
|
||||
}
|
||||
},
|
||||
"delta": "!",
|
||||
"options": {}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": {
|
||||
"type": "content_block_delta",
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"type": "text_delta",
|
||||
"text": " How"
|
||||
}
|
||||
},
|
||||
"delta": " How",
|
||||
"options": {}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": {
|
||||
"type": "content_block_delta",
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"type": "text_delta",
|
||||
"text": " can"
|
||||
}
|
||||
},
|
||||
"delta": " can",
|
||||
"options": {}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": {
|
||||
"type": "content_block_delta",
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"type": "text_delta",
|
||||
"text": " I"
|
||||
}
|
||||
},
|
||||
"delta": " I",
|
||||
"options": {}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": {
|
||||
"type": "content_block_delta",
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"type": "text_delta",
|
||||
"text": " assist"
|
||||
}
|
||||
},
|
||||
"delta": " assist",
|
||||
"options": {}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": {
|
||||
"type": "content_block_delta",
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"type": "text_delta",
|
||||
"text": " you"
|
||||
}
|
||||
},
|
||||
"delta": " you",
|
||||
"options": {}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": {
|
||||
"type": "content_block_delta",
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"type": "text_delta",
|
||||
"text": " today"
|
||||
}
|
||||
},
|
||||
"delta": " today",
|
||||
"options": {}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": {
|
||||
"type": "content_block_delta",
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"type": "text_delta",
|
||||
"text": "?"
|
||||
}
|
||||
},
|
||||
"delta": "?",
|
||||
"options": {}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,476 @@
|
||||
{
|
||||
"llmEventStart": [
|
||||
{
|
||||
"id": "PRESERVE_0",
|
||||
"messages": [
|
||||
{
|
||||
"content": "Hello",
|
||||
"role": "user"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"messages": [
|
||||
{
|
||||
"content": "hello",
|
||||
"role": "user"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"llmEventEnd": [
|
||||
{
|
||||
"id": "PRESERVE_0",
|
||||
"response": {
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"object": "chat.completion",
|
||||
"created": 114514,
|
||||
"model": "gpt-3.5-turbo-0125",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"message": {
|
||||
"role": "assistant",
|
||||
"content": "Hello! How can I assist you today?"
|
||||
},
|
||||
"logprobs": null,
|
||||
"finish_reason": "stop"
|
||||
}
|
||||
],
|
||||
"usage": {
|
||||
"prompt_tokens": 8,
|
||||
"completion_tokens": 9,
|
||||
"total_tokens": 17
|
||||
},
|
||||
"system_fingerprint": "HIDDEN"
|
||||
},
|
||||
"message": {
|
||||
"content": "Hello! How can I assist you today?",
|
||||
"role": "assistant",
|
||||
"options": {}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"response": {
|
||||
"raw": [
|
||||
{
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"object": "chat.completion.chunk",
|
||||
"created": 114514,
|
||||
"model": "gpt-3.5-turbo-0125",
|
||||
"system_fingerprint": "HIDDEN",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"content": "Hello"
|
||||
},
|
||||
"logprobs": null,
|
||||
"finish_reason": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"options": {},
|
||||
"delta": "Hello"
|
||||
},
|
||||
{
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"object": "chat.completion.chunk",
|
||||
"created": 114514,
|
||||
"model": "gpt-3.5-turbo-0125",
|
||||
"system_fingerprint": "HIDDEN",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"content": "!"
|
||||
},
|
||||
"logprobs": null,
|
||||
"finish_reason": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"options": {},
|
||||
"delta": "!"
|
||||
},
|
||||
{
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"object": "chat.completion.chunk",
|
||||
"created": 114514,
|
||||
"model": "gpt-3.5-turbo-0125",
|
||||
"system_fingerprint": "HIDDEN",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"content": " How"
|
||||
},
|
||||
"logprobs": null,
|
||||
"finish_reason": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"options": {},
|
||||
"delta": " How"
|
||||
},
|
||||
{
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"object": "chat.completion.chunk",
|
||||
"created": 114514,
|
||||
"model": "gpt-3.5-turbo-0125",
|
||||
"system_fingerprint": "HIDDEN",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"content": " can"
|
||||
},
|
||||
"logprobs": null,
|
||||
"finish_reason": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"options": {},
|
||||
"delta": " can"
|
||||
},
|
||||
{
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"object": "chat.completion.chunk",
|
||||
"created": 114514,
|
||||
"model": "gpt-3.5-turbo-0125",
|
||||
"system_fingerprint": "HIDDEN",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"content": " I"
|
||||
},
|
||||
"logprobs": null,
|
||||
"finish_reason": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"options": {},
|
||||
"delta": " I"
|
||||
},
|
||||
{
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"object": "chat.completion.chunk",
|
||||
"created": 114514,
|
||||
"model": "gpt-3.5-turbo-0125",
|
||||
"system_fingerprint": "HIDDEN",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"content": " assist"
|
||||
},
|
||||
"logprobs": null,
|
||||
"finish_reason": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"options": {},
|
||||
"delta": " assist"
|
||||
},
|
||||
{
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"object": "chat.completion.chunk",
|
||||
"created": 114514,
|
||||
"model": "gpt-3.5-turbo-0125",
|
||||
"system_fingerprint": "HIDDEN",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"content": " you"
|
||||
},
|
||||
"logprobs": null,
|
||||
"finish_reason": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"options": {},
|
||||
"delta": " you"
|
||||
},
|
||||
{
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"object": "chat.completion.chunk",
|
||||
"created": 114514,
|
||||
"model": "gpt-3.5-turbo-0125",
|
||||
"system_fingerprint": "HIDDEN",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"content": " today"
|
||||
},
|
||||
"logprobs": null,
|
||||
"finish_reason": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"options": {},
|
||||
"delta": " today"
|
||||
},
|
||||
{
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"object": "chat.completion.chunk",
|
||||
"created": 114514,
|
||||
"model": "gpt-3.5-turbo-0125",
|
||||
"system_fingerprint": "HIDDEN",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"content": "?"
|
||||
},
|
||||
"logprobs": null,
|
||||
"finish_reason": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"options": {},
|
||||
"delta": "?"
|
||||
}
|
||||
],
|
||||
"message": {
|
||||
"content": "Hello! How can I assist you today?",
|
||||
"role": "assistant",
|
||||
"options": {}
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"llmEventStream": [
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"object": "chat.completion.chunk",
|
||||
"created": 114514,
|
||||
"model": "gpt-3.5-turbo-0125",
|
||||
"system_fingerprint": "HIDDEN",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"content": "Hello"
|
||||
},
|
||||
"logprobs": null,
|
||||
"finish_reason": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"options": {},
|
||||
"delta": "Hello"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"object": "chat.completion.chunk",
|
||||
"created": 114514,
|
||||
"model": "gpt-3.5-turbo-0125",
|
||||
"system_fingerprint": "HIDDEN",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"content": "!"
|
||||
},
|
||||
"logprobs": null,
|
||||
"finish_reason": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"options": {},
|
||||
"delta": "!"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"object": "chat.completion.chunk",
|
||||
"created": 114514,
|
||||
"model": "gpt-3.5-turbo-0125",
|
||||
"system_fingerprint": "HIDDEN",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"content": " How"
|
||||
},
|
||||
"logprobs": null,
|
||||
"finish_reason": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"options": {},
|
||||
"delta": " How"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"object": "chat.completion.chunk",
|
||||
"created": 114514,
|
||||
"model": "gpt-3.5-turbo-0125",
|
||||
"system_fingerprint": "HIDDEN",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"content": " can"
|
||||
},
|
||||
"logprobs": null,
|
||||
"finish_reason": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"options": {},
|
||||
"delta": " can"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"object": "chat.completion.chunk",
|
||||
"created": 114514,
|
||||
"model": "gpt-3.5-turbo-0125",
|
||||
"system_fingerprint": "HIDDEN",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"content": " I"
|
||||
},
|
||||
"logprobs": null,
|
||||
"finish_reason": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"options": {},
|
||||
"delta": " I"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"object": "chat.completion.chunk",
|
||||
"created": 114514,
|
||||
"model": "gpt-3.5-turbo-0125",
|
||||
"system_fingerprint": "HIDDEN",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"content": " assist"
|
||||
},
|
||||
"logprobs": null,
|
||||
"finish_reason": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"options": {},
|
||||
"delta": " assist"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"object": "chat.completion.chunk",
|
||||
"created": 114514,
|
||||
"model": "gpt-3.5-turbo-0125",
|
||||
"system_fingerprint": "HIDDEN",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"content": " you"
|
||||
},
|
||||
"logprobs": null,
|
||||
"finish_reason": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"options": {},
|
||||
"delta": " you"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"object": "chat.completion.chunk",
|
||||
"created": 114514,
|
||||
"model": "gpt-3.5-turbo-0125",
|
||||
"system_fingerprint": "HIDDEN",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"content": " today"
|
||||
},
|
||||
"logprobs": null,
|
||||
"finish_reason": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"options": {},
|
||||
"delta": " today"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"object": "chat.completion.chunk",
|
||||
"created": 114514,
|
||||
"model": "gpt-3.5-turbo-0125",
|
||||
"system_fingerprint": "HIDDEN",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"content": "?"
|
||||
},
|
||||
"logprobs": null,
|
||||
"finish_reason": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"options": {},
|
||||
"delta": "?"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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,133 @@
|
||||
{
|
||||
"llmEventStart": [
|
||||
{
|
||||
"id": "PRESERVE_0",
|
||||
"messages": [
|
||||
{
|
||||
"content": "Given a user question, and a list of tools, output a list of relevant sub-questions that when composed can help answer the full user question:\n\n# Example 1\n<Tools>\n```json\n{\n \"uber_10k\": \"Provides information about Uber financials for year 2021\",\n \"lyft_10k\": \"Provides information about Lyft financials for year 2021\"\n}\n```\n\n<User Question>\nCompare and contrast the revenue growth and EBITDA of Uber and Lyft for year 2021\n\n<Output>\n```json\n[\n {\n \"subQuestion\": \"What is the revenue growth of Uber\",\n \"toolName\": \"uber_10k\"\n },\n {\n \"subQuestion\": \"What is the EBITDA of Uber\",\n \"toolName\": \"uber_10k\"\n },\n {\n \"subQuestion\": \"What is the revenue growth of Lyft\",\n \"toolName\": \"lyft_10k\"\n },\n {\n \"subQuestion\": \"What is the EBITDA of Lyft\",\n \"toolName\": \"lyft_10k\"\n }\n]\n```\n\n# Example 2\n<Tools>\n```json\n{\n \"bill_gates_idea\": \"Get what Bill Gates idea from.\"\n}\n```\n\n<User Question>\nWhat did Bill Gates steal from?\n\n<Output>\n",
|
||||
"role": "user"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"messages": [
|
||||
{
|
||||
"content": "Context information is below.\n---------------------\nBill Gates stole from Apple. Steve Jobs stole from Xerox.\n---------------------\nGiven the context information and not prior knowledge, answer the query.\nQuery: What is Bill Gates' idea\nAnswer:",
|
||||
"role": "user"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_2",
|
||||
"messages": [
|
||||
{
|
||||
"content": "Context information is below.\n---------------------\nSub question: What is Bill Gates' idea\nResponse: Bill Gates' idea was to steal from Apple.\n---------------------\nGiven the context information and not prior knowledge, answer the query.\nQuery: What did Bill Gates steal from?\nAnswer:",
|
||||
"role": "user"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"llmEventEnd": [
|
||||
{
|
||||
"id": "PRESERVE_0",
|
||||
"response": {
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"object": "chat.completion",
|
||||
"created": 114514,
|
||||
"model": "gpt-3.5-turbo-0125",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"message": {
|
||||
"role": "assistant",
|
||||
"content": "```json\n[\n {\n \"subQuestion\": \"What is Bill Gates' idea\",\n \"toolName\": \"bill_gates_idea\"\n }\n]\n```"
|
||||
},
|
||||
"logprobs": null,
|
||||
"finish_reason": "stop"
|
||||
}
|
||||
],
|
||||
"usage": {
|
||||
"prompt_tokens": 290,
|
||||
"completion_tokens": 35,
|
||||
"total_tokens": 325
|
||||
},
|
||||
"system_fingerprint": "HIDDEN"
|
||||
},
|
||||
"message": {
|
||||
"content": "```json\n[\n {\n \"subQuestion\": \"What is Bill Gates' idea\",\n \"toolName\": \"bill_gates_idea\"\n }\n]\n```",
|
||||
"role": "assistant",
|
||||
"options": {}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"response": {
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"object": "chat.completion",
|
||||
"created": 114514,
|
||||
"model": "gpt-3.5-turbo-0125",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"message": {
|
||||
"role": "assistant",
|
||||
"content": "Bill Gates' idea was to steal from Apple."
|
||||
},
|
||||
"logprobs": null,
|
||||
"finish_reason": "stop"
|
||||
}
|
||||
],
|
||||
"usage": {
|
||||
"prompt_tokens": 53,
|
||||
"completion_tokens": 10,
|
||||
"total_tokens": 63
|
||||
},
|
||||
"system_fingerprint": "HIDDEN"
|
||||
},
|
||||
"message": {
|
||||
"content": "Bill Gates' idea was to steal from Apple.",
|
||||
"role": "assistant",
|
||||
"options": {}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_2",
|
||||
"response": {
|
||||
"raw": {
|
||||
"id": "HIDDEN",
|
||||
"object": "chat.completion",
|
||||
"created": 114514,
|
||||
"model": "gpt-3.5-turbo-0125",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"message": {
|
||||
"role": "assistant",
|
||||
"content": "Bill Gates stole from Apple."
|
||||
},
|
||||
"logprobs": null,
|
||||
"finish_reason": "stop"
|
||||
}
|
||||
],
|
||||
"usage": {
|
||||
"prompt_tokens": 62,
|
||||
"completion_tokens": 6,
|
||||
"total_tokens": 68
|
||||
},
|
||||
"system_fingerprint": "HIDDEN"
|
||||
},
|
||||
"message": {
|
||||
"content": "Bill Gates stole from Apple.",
|
||||
"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": []
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
/* eslint-disable turbo/no-undeclared-env-vars */
|
||||
import {
|
||||
Settings,
|
||||
type LLMEndEvent,
|
||||
type LLMStartEvent,
|
||||
type LLMStreamEvent,
|
||||
} from "llamaindex";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { type test } from "node:test";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
type MockStorage = {
|
||||
llmEventStart: LLMStartEvent["detail"]["payload"][];
|
||||
llmEventEnd: LLMEndEvent["detail"]["payload"][];
|
||||
llmEventStream: LLMStreamEvent["detail"]["payload"][];
|
||||
};
|
||||
|
||||
export const llmCompleteMockStorage: MockStorage = {
|
||||
llmEventStart: [],
|
||||
llmEventEnd: [],
|
||||
llmEventStream: [],
|
||||
};
|
||||
|
||||
export const testRootDir = fileURLToPath(new URL(".", import.meta.url));
|
||||
|
||||
export async function mockLLMEvent(
|
||||
t: Parameters<NonNullable<Parameters<typeof test>[0]>>[0],
|
||||
snapshotName: string,
|
||||
) {
|
||||
const idMap = new Map<string, string>();
|
||||
let counter = 0;
|
||||
const newLLMCompleteMockStorage: MockStorage = {
|
||||
llmEventStart: [],
|
||||
llmEventEnd: [],
|
||||
llmEventStream: [],
|
||||
};
|
||||
|
||||
function captureLLMStart(event: LLMStartEvent) {
|
||||
idMap.set(event.detail.payload.id, `PRESERVE_${counter++}`);
|
||||
newLLMCompleteMockStorage.llmEventStart.push({
|
||||
...event.detail.payload,
|
||||
// @ts-expect-error id is not UUID, but it is fine for testing
|
||||
id: idMap.get(event.detail.payload.id)!,
|
||||
});
|
||||
}
|
||||
|
||||
function captureLLMEnd(event: LLMEndEvent) {
|
||||
newLLMCompleteMockStorage.llmEventEnd.push({
|
||||
...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,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function captureLLMStream(event: LLMStreamEvent) {
|
||||
newLLMCompleteMockStorage.llmEventStream.push({
|
||||
...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,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
await readFile(join(testRootDir, "snapshot", `${snapshotName}.snap`), {
|
||||
encoding: "utf-8",
|
||||
})
|
||||
.then((data) => {
|
||||
const result = JSON.parse(data) as MockStorage;
|
||||
result["llmEventEnd"].forEach((event) => {
|
||||
llmCompleteMockStorage.llmEventEnd.push(event);
|
||||
});
|
||||
result["llmEventStart"].forEach((event) => {
|
||||
llmCompleteMockStorage.llmEventStart.push(event);
|
||||
});
|
||||
result["llmEventStream"].forEach((event) => {
|
||||
llmCompleteMockStorage.llmEventStream.push(event);
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
if (error.code === "ENOENT") {
|
||||
console.warn("Snapshot file not found, will create a new one");
|
||||
return;
|
||||
}
|
||||
});
|
||||
Settings.callbackManager.on("llm-start", captureLLMStart);
|
||||
Settings.callbackManager.on("llm-end", captureLLMEnd);
|
||||
Settings.callbackManager.on("llm-stream", captureLLMStream);
|
||||
|
||||
t.after(async () => {
|
||||
Settings.callbackManager.off("llm-stream", captureLLMStream);
|
||||
Settings.callbackManager.off("llm-end", captureLLMEnd);
|
||||
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);
|
||||
await writeFile(
|
||||
join(testRootDir, "snapshot", `${snapshotName}.snap`),
|
||||
data,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
newLLMCompleteMockStorage.llmEventEnd.length !==
|
||||
llmCompleteMockStorage.llmEventEnd.length
|
||||
) {
|
||||
throw new Error("New LLMEndEvent does not match, please update snapshot");
|
||||
}
|
||||
if (
|
||||
newLLMCompleteMockStorage.llmEventStart.length !==
|
||||
llmCompleteMockStorage.llmEventStart.length
|
||||
) {
|
||||
throw new Error(
|
||||
"New LLMStartEvent does not match, please update snapshot",
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
newLLMCompleteMockStorage.llmEventStream.length !==
|
||||
llmCompleteMockStorage.llmEventStream.length
|
||||
) {
|
||||
throw new Error(
|
||||
"New LLMStreamEvent does not match, please update snapshot",
|
||||
);
|
||||
}
|
||||
});
|
||||
// cleanup
|
||||
t.after(() => {
|
||||
llmCompleteMockStorage.llmEventEnd = [];
|
||||
llmCompleteMockStorage.llmEventStart = [];
|
||||
llmCompleteMockStorage.llmEventStream = [];
|
||||
});
|
||||
}
|
||||
@@ -5,7 +5,8 @@
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"e2e": "node --import tsx --import ./mock-register.js --test ./node/*.e2e.ts",
|
||||
"e2e:nomock": "node --import tsx --test ./node/*.e2e.ts"
|
||||
"e2e:nomock": "node --import tsx --test ./node/*.e2e.ts",
|
||||
"e2e:updatesnap": "UPDATE_SNAPSHOT=1 node --import tsx --test ./node/*.e2e.ts"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@faker-js/faker": "^8.4.1",
|
||||
|
||||
@@ -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"
|
||||
|
||||
+20
-16
@@ -1,37 +1,38 @@
|
||||
{
|
||||
"name": "llamaindex",
|
||||
"version": "0.2.4",
|
||||
"version": "0.2.11",
|
||||
"expectedMinorVersion": "2",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "^0.18.0",
|
||||
"@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",
|
||||
"@grpc/grpc-js": "^1.10.6",
|
||||
"@llamaindex/cloud": "0.0.5",
|
||||
"@llamaindex/env": "workspace:*",
|
||||
"@mistralai/mistralai": "^0.1.3",
|
||||
"@notionhq/client": "^2.2.14",
|
||||
"@pinecone-database/pinecone": "^2.2.0",
|
||||
"@qdrant/js-client-rest": "^1.8.2",
|
||||
"@types/lodash": "^4.17.0",
|
||||
"@types/node": "^18.19.31",
|
||||
"@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",
|
||||
"assemblyai": "^4.3.4",
|
||||
"@xenova/transformers": "^2.17.1",
|
||||
"@zilliz/milvus2-sdk-node": "^2.4.1",
|
||||
"ajv": "^8.12.0",
|
||||
"assemblyai": "^4.4.1",
|
||||
"chromadb": "~1.7.3",
|
||||
"cohere-ai": "^7.9.2",
|
||||
"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",
|
||||
@@ -39,18 +40,21 @@
|
||||
"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",
|
||||
"typescript": "^5.4.4"
|
||||
"madge": "^7.0.0",
|
||||
"typescript": "^5.4.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
|
||||
@@ -1,27 +1,29 @@
|
||||
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";
|
||||
|
||||
/**
|
||||
* A ChatHistory is used to keep the state of back and forth chat messages
|
||||
*/
|
||||
export abstract class ChatHistory {
|
||||
abstract get messages(): ChatMessage[];
|
||||
export abstract class ChatHistory<
|
||||
AdditionalMessageOptions extends object = object,
|
||||
> {
|
||||
abstract get messages(): ChatMessage<AdditionalMessageOptions>[];
|
||||
/**
|
||||
* Adds a message to the chat history.
|
||||
* @param message
|
||||
*/
|
||||
abstract addMessage(message: ChatMessage): void;
|
||||
abstract addMessage(message: ChatMessage<AdditionalMessageOptions>): void;
|
||||
|
||||
/**
|
||||
* Returns the messages that should be used as input to the LLM.
|
||||
*/
|
||||
abstract requestMessages(
|
||||
transientMessages?: ChatMessage[],
|
||||
): Promise<ChatMessage[]>;
|
||||
transientMessages?: ChatMessage<AdditionalMessageOptions>[],
|
||||
): Promise<ChatMessage<AdditionalMessageOptions>[]>;
|
||||
|
||||
/**
|
||||
* Resets the chat history so that it's empty.
|
||||
@@ -31,7 +33,7 @@ export abstract class ChatHistory {
|
||||
/**
|
||||
* Returns the new messages since the last call to this function (or since calling the constructor)
|
||||
*/
|
||||
abstract newMessages(): ChatMessage[];
|
||||
abstract newMessages(): ChatMessage<AdditionalMessageOptions>[];
|
||||
}
|
||||
|
||||
export class SimpleChatHistory extends ChatHistory {
|
||||
@@ -108,6 +110,7 @@ export class SummaryChatHistory extends ChatHistory {
|
||||
context: messagesToHistoryStr(messagesToSummarize),
|
||||
}),
|
||||
role: "user" as MessageType,
|
||||
options: {},
|
||||
},
|
||||
];
|
||||
// remove oldest message until the chat history is short enough for the context window
|
||||
@@ -116,7 +119,9 @@ export class SummaryChatHistory extends ChatHistory {
|
||||
this.tokenizer(promptMessages[0].content).length > this.tokensToSummarize
|
||||
);
|
||||
|
||||
const response = await this.llm.chat({ messages: promptMessages });
|
||||
const response = await this.llm.chat({
|
||||
messages: promptMessages,
|
||||
});
|
||||
return { content: response.message.content, role: "memory" };
|
||||
}
|
||||
|
||||
|
||||
@@ -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> {
|
||||
|
||||
@@ -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,14 +1,14 @@
|
||||
import type { BaseNode } from "./Node.js";
|
||||
import type { NodeWithScore } from "./Node.js";
|
||||
|
||||
/**
|
||||
* Response is the output of a LLM
|
||||
*/
|
||||
export class Response {
|
||||
response: string;
|
||||
sourceNodes?: BaseNode[];
|
||||
sourceNodes?: NodeWithScore[];
|
||||
metadata: Record<string, unknown> = {};
|
||||
|
||||
constructor(response: string, sourceNodes?: BaseNode[]) {
|
||||
constructor(response: string, sourceNodes?: NodeWithScore[]) {
|
||||
this.response = response;
|
||||
this.sourceNodes = sourceNodes || [];
|
||||
}
|
||||
|
||||
@@ -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,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";
|
||||
|
||||
@@ -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
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,124 @@
|
||||
import { Settings } from "../Settings.js";
|
||||
import {
|
||||
type ChatEngineParamsNonStreaming,
|
||||
type ChatEngineParamsStreaming,
|
||||
} from "../engines/chat/index.js";
|
||||
import { stringifyJSONToMessageContent } from "../internal/utils.js";
|
||||
import { Anthropic } from "../llm/anthropic.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";
|
||||
|
||||
type AnthropicParamsBase = AgentParamsBase<Anthropic>;
|
||||
|
||||
type AnthropicParamsWithTools = AnthropicParamsBase & {
|
||||
tools: BaseToolWithCall[];
|
||||
};
|
||||
|
||||
type AnthropicParamsWithToolRetriever = AnthropicParamsBase & {
|
||||
toolRetriever: ObjectRetriever<BaseToolWithCall>;
|
||||
};
|
||||
|
||||
export type AnthropicAgentParams =
|
||||
| AnthropicParamsWithTools
|
||||
| AnthropicParamsWithToolRetriever;
|
||||
|
||||
export class AnthropicAgentWorker extends AgentWorker<Anthropic> {
|
||||
taskHandler = AnthropicAgent.taskHandler;
|
||||
}
|
||||
|
||||
export class AnthropicAgent extends AgentRunner<Anthropic> {
|
||||
constructor(params: AnthropicAgentParams) {
|
||||
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),
|
||||
});
|
||||
}
|
||||
|
||||
createStore = AgentRunner.defaultCreateStore;
|
||||
|
||||
async chat(
|
||||
params: ChatEngineParamsNonStreaming,
|
||||
): 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,
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -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>;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,18 @@
|
||||
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
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
import { Settings } from "../../Settings.js";
|
||||
import type { ChatMessage } from "../../llm/index.js";
|
||||
import { OpenAI } from "../../llm/index.js";
|
||||
import type { ObjectRetriever } from "../../objects/base.js";
|
||||
import type { BaseTool } from "../../types.js";
|
||||
import { AgentRunner } from "../runner/base.js";
|
||||
import { OpenAIAgentWorker } from "./worker.js";
|
||||
|
||||
type OpenAIAgentParams = {
|
||||
tools?: BaseTool[];
|
||||
llm?: OpenAI;
|
||||
memory?: any;
|
||||
prefixMessages?: ChatMessage[];
|
||||
maxFunctionCalls?: number;
|
||||
defaultToolChoice?: string;
|
||||
toolRetriever?: ObjectRetriever;
|
||||
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?.metadata.isFunctionCallingModel) {
|
||||
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,
|
||||
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";
|
||||
}
|
||||
@@ -1,374 +0,0 @@
|
||||
import { 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,
|
||||
} from "../../llm/index.js";
|
||||
import {
|
||||
extractText,
|
||||
streamConverter,
|
||||
streamReducer,
|
||||
} 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";
|
||||
import type { OpenAIToolCall } from "./types/chat.js";
|
||||
|
||||
async function callFunction(
|
||||
tools: BaseTool[],
|
||||
toolCall: OpenAIToolCall,
|
||||
): Promise<[ChatMessage, ToolOutput]> {
|
||||
const id_ = toolCall.id;
|
||||
const functionCall = toolCall.function;
|
||||
const name = toolCall.function.name;
|
||||
const argumentsStr = toolCall.function.arguments;
|
||||
|
||||
if (Settings.debug) {
|
||||
console.log("=== Calling Function ===");
|
||||
console.log(`Calling function: ${name} with args: ${argumentsStr}`);
|
||||
}
|
||||
|
||||
const tool = getFunctionByName(tools, name);
|
||||
const argumentDict = JSON.parse(argumentsStr);
|
||||
|
||||
// Call tool
|
||||
// Use default error message
|
||||
const output = await callToolWithErrorHandling(tool, argumentDict, null);
|
||||
|
||||
if (Settings.debug) {
|
||||
console.log(`Got output ${output}`);
|
||||
console.log("==========================");
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
content: String(output),
|
||||
role: "tool",
|
||||
additionalKwargs: {
|
||||
name,
|
||||
tool_call_id: id_,
|
||||
},
|
||||
},
|
||||
output,
|
||||
];
|
||||
}
|
||||
|
||||
type OpenAIAgentWorkerParams = {
|
||||
tools?: BaseTool[];
|
||||
llm?: OpenAI;
|
||||
prefixMessages?: ChatMessage[];
|
||||
maxFunctionCalls?: number;
|
||||
toolRetriever?: ObjectRetriever;
|
||||
};
|
||||
|
||||
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 (Array.isArray(tools) && tools.length > 0 && toolRetriever) {
|
||||
throw new Error("Cannot specify both tools and tool_retriever");
|
||||
} else if (Array.isArray(tools)) {
|
||||
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[] {
|
||||
return [
|
||||
...this.prefixMessages,
|
||||
...task.memory.get(),
|
||||
...task.extraState.newMemory.get(),
|
||||
];
|
||||
}
|
||||
|
||||
public getLatestToolCalls(task: Task): OpenAIToolCall[] | null {
|
||||
const chatHistory: ChatMessage[] = task.extraState.newMemory.getAll();
|
||||
|
||||
if (chatHistory.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return chatHistory[chatHistory.length - 1].additionalKwargs?.toolCalls;
|
||||
}
|
||||
|
||||
private _getLlmChatParams(
|
||||
task: Task,
|
||||
openaiTools: BaseTool[],
|
||||
toolChoice: ChatCompletionToolChoiceOption = "auto",
|
||||
): LLMChatParamsBase<OpenAIAdditionalChatOptions> {
|
||||
const llmChatParams = {
|
||||
messages: this.getAllMessages(task),
|
||||
tools: [] as BaseTool[],
|
||||
additionalChatOptions: {} as OpenAIAdditionalChatOptions,
|
||||
} satisfies LLMChatParamsBase<OpenAIAdditionalChatOptions>;
|
||||
|
||||
if (openaiTools.length > 0) {
|
||||
llmChatParams.tools = openaiTools;
|
||||
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>,
|
||||
): Promise<StreamingAgentChatResponse | AgentChatResponse> {
|
||||
const stream = await this.llm.chat({
|
||||
stream: true,
|
||||
...llmChatParams,
|
||||
});
|
||||
// read first chunk from stream to find out if we need to call tools
|
||||
const iterator = stream[Symbol.asyncIterator]();
|
||||
let { value } = await iterator.next();
|
||||
let content = value.delta;
|
||||
const hasToolCalls = value.additionalKwargs?.toolCalls.length > 0;
|
||||
|
||||
if (hasToolCalls) {
|
||||
// consume stream until we have all the tool calls and return a non-streamed response
|
||||
for await (value of stream) {
|
||||
content += value.delta;
|
||||
}
|
||||
return this._processMessage(task, {
|
||||
content,
|
||||
role: "assistant",
|
||||
additionalKwargs: value.additionalKwargs,
|
||||
});
|
||||
}
|
||||
|
||||
const newStream = streamConverter.bind(this)(
|
||||
streamReducer({
|
||||
stream,
|
||||
initialValue: content,
|
||||
reducer: (accumulator, part) => (accumulator += part.delta),
|
||||
finished: (accumulator) => {
|
||||
task.extraState.newMemory.put({
|
||||
content: accumulator,
|
||||
role: "assistant",
|
||||
});
|
||||
},
|
||||
}),
|
||||
(r: ChatResponseChunk) => new Response(r.delta),
|
||||
);
|
||||
|
||||
return new StreamingAgentChatResponse(newStream, task.extraState.sources);
|
||||
}
|
||||
|
||||
private async _getAgentResponse(
|
||||
task: Task,
|
||||
mode: ChatResponseMode,
|
||||
llmChatParams: LLMChatParamsBase<OpenAIAdditionalChatOptions>,
|
||||
): 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: OpenAIToolCall,
|
||||
): Promise<CallFunctionOutput> {
|
||||
const functionCall = toolCall.function;
|
||||
|
||||
if (!functionCall) {
|
||||
throw new Error("Invalid tool_call object");
|
||||
}
|
||||
|
||||
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(
|
||||
toolCalls: OpenAIToolCall[] | null,
|
||||
nFunctionCalls: number,
|
||||
): boolean {
|
||||
if (nFunctionCalls > this.maxFunctionCalls) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (toolCalls?.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
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 latestToolCalls = this.getLatestToolCalls(task) || [];
|
||||
|
||||
let isDone: boolean;
|
||||
let newSteps: TaskStep[] = [];
|
||||
|
||||
if (
|
||||
!this._shouldContinue(latestToolCalls, task.extraState.nFunctionCalls)
|
||||
) {
|
||||
isDone = true;
|
||||
newSteps = [];
|
||||
} else {
|
||||
isDone = false;
|
||||
for (const toolCall of latestToolCalls) {
|
||||
const { message, toolOutput } = await this.callFunction(
|
||||
tools,
|
||||
toolCall,
|
||||
);
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
import type { ChatMessage, LLM } from "../../llm/index.js";
|
||||
import type { ObjectRetriever } from "../../objects/base.js";
|
||||
import type { BaseTool } from "../../types.js";
|
||||
import { AgentRunner } from "../runner/base.js";
|
||||
import { ReActAgentWorker } from "./worker.js";
|
||||
|
||||
type ReActAgentParams = {
|
||||
tools: BaseTool[];
|
||||
llm?: LLM;
|
||||
memory?: any;
|
||||
prefixMessages?: ChatMessage[];
|
||||
maxInteractions?: number;
|
||||
defaultToolChoice?: string;
|
||||
toolRetriever?: ObjectRetriever;
|
||||
};
|
||||
|
||||
/**
|
||||
* 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,
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -1,316 +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 { 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 | 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];
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,383 +0,0 @@
|
||||
import { randomUUID } from "@llamaindex/env";
|
||||
import type { ChatEngineAgentParams } from "../../engines/chat/index.js";
|
||||
import {
|
||||
AgentChatResponse,
|
||||
ChatResponseMode,
|
||||
StreamingAgentChatResponse,
|
||||
} from "../../engines/chat/index.js";
|
||||
import type { ChatMessage, LLM } from "../../llm/index.js";
|
||||
import { ChatMemoryBuffer } from "../../memory/ChatMemoryBuffer.js";
|
||||
import type { BaseMemory } from "../../memory/types.js";
|
||||
import type { AgentWorker, TaskStepOutput } from "../types.js";
|
||||
import { Task, TaskStep } from "../types.js";
|
||||
import { AgentState, BaseAgentRunner, TaskState } from "./types.js";
|
||||
const validateStepFromArgs = (
|
||||
taskId: string,
|
||||
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?: ChatMessage[];
|
||||
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;
|
||||
|
||||
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 {}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import type { BaseEvent } from "../internal/type.js";
|
||||
|
||||
export type AgentStartEvent = BaseEvent<{}>;
|
||||
export type AgentEndEvent = BaseEvent<{}>;
|
||||
@@ -1,201 +0,0 @@
|
||||
import type {
|
||||
AgentChatResponse,
|
||||
ChatEngineAgentParams,
|
||||
StreamingAgentChatResponse,
|
||||
} from "../engines/chat/index.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: any;
|
||||
extraState: Record<string, any>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Task is a unit of work for the agent.
|
||||
* @param taskId: taskId
|
||||
*/
|
||||
export class Task {
|
||||
taskId: string;
|
||||
input: string;
|
||||
|
||||
memory: any;
|
||||
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);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user