mirror of
https://github.com/run-llama/LlamaIndexTS.git
synced 2026-07-09 11:25:43 -04:00
Compare commits
18 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f0a1cc51b4 | |||
| fee3280799 | |||
| 54925bf1ae | |||
| 91d02a4fc0 | |||
| 086b94038e | |||
| 5d5716b339 | |||
| fb6db454d4 | |||
| e4d4e0d024 | |||
| 17724d961e | |||
| 6776910c93 | |||
| 15962b36f0 | |||
| 3d9a802734 | |||
| 9cd8f8b0cf | |||
| b44330cbc6 | |||
| 3d5ba0873c | |||
| d917cdc3fa | |||
| b370edf329 | |||
| ec59acd329 |
+7
-7
@@ -4,11 +4,11 @@
|
||||
|
||||
This is a monorepo built with Turborepo
|
||||
|
||||
Right now there are two packages of importance:
|
||||
Right now, for first-time contributors, these three packages are of the highest importance:
|
||||
|
||||
packages/llamaindex which is the main NPM library llamaindex
|
||||
|
||||
examples is where the demo code lives
|
||||
- `packages/llamaindex` which is the main NPM library `llamaindex`
|
||||
- `examples` is where the demo code lives
|
||||
- `apps/docs` is where the code for the documentation of https://ts.llamaindex.ai/ is located
|
||||
|
||||
### Turborepo docs
|
||||
|
||||
@@ -43,11 +43,11 @@ pnpm run test
|
||||
|
||||
To write new test cases write them in [packages/llamaindex/tests](/packages/llamaindex/tests)
|
||||
|
||||
We use Jest https://jestjs.io/ to write our test cases. Jest comes with a bunch of built in assertions using the expect function: https://jestjs.io/docs/expect
|
||||
We use Vitest https://vitest.dev to write our test cases. Vitest comes with a bunch of built-in assertions using the expect function: https://vitest.dev/api/expect.html#expect
|
||||
|
||||
### Demo applications
|
||||
|
||||
There is an existing ["example"](/examples/README.md) demos folder with mainly NodeJS scripts. Feel free to add additional demos to that folder. If you would like to try out your changes in the core package with a new demo, you need to run the build command in the README.
|
||||
There is an existing ["example"](/examples/README.md) demos folder with mainly NodeJS scripts. Feel free to add additional demos to that folder. If you would like to try out your changes in the `llamaindex` package with a new demo, you need to run the build command in the README.
|
||||
|
||||
You can create new demo applications in the apps folder. Just run pnpm init in the folder after you create it to create its own package.json
|
||||
|
||||
@@ -81,7 +81,7 @@ Any changes you make should be reflected in the browser. If you need to regenera
|
||||
|
||||
## Changeset
|
||||
|
||||
We use [changesets](https://github.com/changesets/changesets) for managing versions and changelogs. To create a new changeset, run:
|
||||
We use [changesets](https://github.com/changesets/changesets) for managing versions and changelogs. To create a new changeset, run in the root folder:
|
||||
|
||||
```
|
||||
pnpm changeset
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
"llamaindex": minor
|
||||
"docs": minor
|
||||
---
|
||||
|
||||
Add deepseek llm class
|
||||
@@ -1,5 +1,39 @@
|
||||
# docs
|
||||
|
||||
## 0.0.51
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 086b940: feat: add DeepSeek LLM
|
||||
- 5d5716b: feat: add a reader for JSON data
|
||||
- Updated dependencies [086b940]
|
||||
- Updated dependencies [5d5716b]
|
||||
- Updated dependencies [91d02a4]
|
||||
- Updated dependencies [fb6db45]
|
||||
- llamaindex@0.5.10
|
||||
|
||||
## 0.0.50
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [15962b3]
|
||||
- llamaindex@0.5.9
|
||||
|
||||
## 0.0.49
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [3d5ba08]
|
||||
- Updated dependencies [d917cdc]
|
||||
- llamaindex@0.5.8
|
||||
|
||||
## 0.0.48
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [ec59acd]
|
||||
- llamaindex@0.5.7
|
||||
|
||||
## 0.0.47
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -20,7 +20,7 @@ Copy the URL in your browser and select the server you want your bot to join.
|
||||
#### DiscordReader()
|
||||
|
||||
- `discordToken?`: The Discord bot token.
|
||||
- `makeRequest?`: Optionally provide a custom request function for edge environments, e.g. `fetch`. See discord.js for more info.
|
||||
- `requestHandler?`: Optionally provide a custom request function for edge environments, e.g. `fetch`. See discord.js for more info.
|
||||
|
||||
#### DiscordReader.loadData
|
||||
|
||||
|
||||
@@ -16,7 +16,15 @@ It is a simple reader that reads all files from a directory and its subdirectori
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
|
||||
Currently, it supports reading `.txt`, `.pdf`, `.csv`, `.md`, `.docx`, `.htm`, `.html`, `.jpg`, `.jpeg`, `.png` and `.gif` files, but support for other file types is planned.
|
||||
Currently, the following readers are mapped to specific file types:
|
||||
|
||||
- [TextFileReader](../../api/classes/TextFileReader.md): `.txt`
|
||||
- [PDFReader](../../api/classes/PDFReader.md): `.pdf`
|
||||
- [PapaCSVReader](../../api/classes/PapaCSVReader.md): `.csv`
|
||||
- [MarkdownReader](../../api/classes/MarkdownReader.md): `.md`
|
||||
- [DocxReader](../../api/classes/DocxReader.md): `.docx`
|
||||
- [HTMLReader](../../api/classes/HTMLReader.md): `.htm`, `.html`
|
||||
- [ImageReader](../../api/classes/ImageReader.md): `.jpg`, `.jpeg`, `.png`, `.gif`
|
||||
|
||||
You can modify the reader three different ways:
|
||||
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
# JSONReader
|
||||
|
||||
A simple JSON data loader with various options.
|
||||
Either parses the entire string, cleaning it and treat each line as an embedding or performs a recursive depth-first traversal yielding JSON paths.
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { JSONReader } from "llamaindex";
|
||||
|
||||
const file = "../../PATH/TO/FILE";
|
||||
const content = new TextEncoder().encode("JSON_CONTENT");
|
||||
|
||||
const reader = new JSONReader({ levelsBack: 0, collapseLength: 100 });
|
||||
const docsFromFile = reader.loadData(file);
|
||||
const docsFromContent = reader.loadDataAsContent(content);
|
||||
```
|
||||
|
||||
### Options
|
||||
|
||||
Basic:
|
||||
|
||||
- `ensureAscii?`: Wether to ensure only ASCII characters be present in the output by converting non-ASCII characters to their unicode escape sequence. Default is `false`.
|
||||
|
||||
- `isJsonLines?`: Wether the JSON is in JSON Lines format. If true, will split into lines, remove empty one and parse each line as JSON. Default is `false`
|
||||
|
||||
- `cleanJson?`: Whether to clean the JSON by filtering out structural characters (`{}, [], and ,`). If set to false, it will just parse the JSON, not removing structural characters. Default is `true`.
|
||||
|
||||
Depth-First-Traversal:
|
||||
|
||||
- `levelsBack?`: Specifies how many levels up the JSON structure to include in the output. `cleanJson` will be ignored. If set to 0, all levels are included. If undefined, parses the entire JSON, treat each line as an embedding and create a document per top-level array. Default is `undefined`
|
||||
|
||||
- `collapseLength?`: The maximum length of JSON string representation to be collapsed into a single line. Only applicable when `levelsBack` is set. Default is `undefined`
|
||||
|
||||
#### Examples
|
||||
|
||||
<!-- prettier-ignore-start -->
|
||||
Input:
|
||||
|
||||
```json
|
||||
{"a": {"1": {"key1": "value1"}, "2": {"key2": "value2"}}, "b": {"3": {"k3": "v3"}, "4": {"k4": "v4"}}}
|
||||
```
|
||||
|
||||
Default options:
|
||||
|
||||
`LevelsBack` = `undefined` & `cleanJson` = `true`
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
"a": {
|
||||
"1": {
|
||||
"key1": "value1"
|
||||
"2": {
|
||||
"key2": "value2"
|
||||
"b": {
|
||||
"3": {
|
||||
"k3": "v3"
|
||||
"4": {
|
||||
"k4": "v4"
|
||||
```
|
||||
|
||||
Depth-First Traversal all levels:
|
||||
|
||||
`levelsBack` = `0`
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
a 1 key1 value1
|
||||
a 2 key2 value2
|
||||
b 3 k3 v3
|
||||
b 4 k4 v4
|
||||
```
|
||||
|
||||
Depth-First Traversal and Collapse:
|
||||
|
||||
`levelsBack` = `0` & `collapseLength` = `35`
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
a 1 {"key1":"value1"}
|
||||
a 2 {"key2":"value2"}
|
||||
b {"3":{"k3":"v3"},"4":{"k4":"v4"}}
|
||||
```
|
||||
|
||||
Depth-First Traversal limited levels:
|
||||
|
||||
`levelsBack` = `2`
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
1 key1 value1
|
||||
2 key2 value2
|
||||
3 k3 v3
|
||||
4 k4 v4
|
||||
```
|
||||
|
||||
Uncleaned JSON:
|
||||
|
||||
`levelsBack` = `undefined` & `cleanJson` = `false`
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
{"a":{"1":{"key1":"value1"},"2":{"key2":"value2"}},"b":{"3":{"k3":"v3"},"4":{"k4":"v4"}}}
|
||||
```
|
||||
|
||||
ASCII-Conversion:
|
||||
|
||||
Input:
|
||||
|
||||
```json
|
||||
{ "message": "こんにちは世界" }
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
"message": "\u3053\u3093\u306b\u3061\u306f\u4e16\u754c"
|
||||
```
|
||||
|
||||
JSON Lines Format:
|
||||
|
||||
Input:
|
||||
|
||||
```json
|
||||
{"tweet": "Hello world"}\n{"tweet": "こんにちは世界"}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
"tweet": "Hello world"
|
||||
|
||||
"tweet": "こんにちは世界"
|
||||
```
|
||||
<!-- prettier-ignore-end -->
|
||||
|
||||
## API Reference
|
||||
|
||||
- [JSONReader](../../api/classes/JSONReader.md)
|
||||
@@ -41,7 +41,9 @@ They can be divided into two groups.
|
||||
- `doNotCache?` Optional. Set to true to not cache the document.
|
||||
- `fastMode?` Optional. Set to true to use the fast mode. This mode will skip OCR of images, and table/heading reconstruction. Note: Non-compatible with `gpt4oMode`.
|
||||
- `doNotUnrollColumns?` Optional. Set to true to keep the text according to document layout. Reduce reconstruction accuracy, and LLMs/embeddings performances in most cases.
|
||||
- `pageSeparator?` Optional. The page separator to use. Defaults is `\\n---\\n`.
|
||||
- `pageSeparator?` Optional. A templated page separator to use to split the text. If the results contain `{page_number}` (e.g. JSON mode), it will be replaced by the next page number. If not set the default separator `\\n---\\n` will be used.
|
||||
- `pagePrefix?` Optional. A templated prefix to add to the beginning of each page. If the results contain `{page_number}`, it will be replaced by the page number.
|
||||
- `pageSuffix?` Optional. A templated suffix to add to the end of each page. If the results contain `{page_number}`, it will be replaced by the page number.
|
||||
- `gpt4oMode` Deprecated. Use vendorMultimodal params. Set to true to use GPT-4o to extract content. Default is `false`.
|
||||
- `gpt4oApiKey?` Deprecated. Use vendorMultimodal params. Optional. Set the GPT-4o API key. Lowers the cost of parsing by using your own API key. Your OpenAI account will be charged. Can also be set in the environment variable `LLAMA_CLOUD_GPT4O_API_KEY`.
|
||||
- `boundingBox?` Optional. Specify an area of the document to parse. Expects the bounding box margins as a string in clockwise order, e.g. `boundingBox = "0.1,0,0,0"` to not parse the top 10% of the document.
|
||||
|
||||
@@ -29,6 +29,9 @@ META_LLAMA2_13B_CHAT = "meta.llama2-13b-chat-v1";
|
||||
META_LLAMA2_70B_CHAT = "meta.llama2-70b-chat-v1";
|
||||
META_LLAMA3_8B_INSTRUCT = "meta.llama3-8b-instruct-v1:0";
|
||||
META_LLAMA3_70B_INSTRUCT = "meta.llama3-70b-instruct-v1:0";
|
||||
META_LLAMA3_1_8B_INSTRUCT = "meta.llama3-1-8b-instruct-v1:0"; // available on us-west-2
|
||||
META_LLAMA3_1_70B_INSTRUCT = "meta.llama3-1-70b-instruct-v1:0"; // available on us-west-2
|
||||
META_LLAMA3_1_405B_INSTRUCT = "meta.llama3-1-405b-instruct-v1:0"; // preview only, available on us-west-2
|
||||
```
|
||||
|
||||
Sonnet, Haiku and Opus are multimodal, image_url only supports base64 data url format, e.g. `data:image/jpeg;base64,SGVsbG8sIFdvcmxkIQ==`
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
# DeepSeek LLM
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { DeepSeekLLM, Settings } from "llamaindex";
|
||||
|
||||
Settings.llm = new DeepSeekLLM({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
model: "deepseek-coder", // or "deepseek-chat"
|
||||
});
|
||||
```
|
||||
|
||||
## Example
|
||||
|
||||
```ts
|
||||
import { DeepSeekLLM, Document, VectorStoreIndex, Settings } from "llamaindex";
|
||||
|
||||
const deepseekLlm = new DeepSeekLLM({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
model: "deepseek-coder", // or "deepseek-chat"
|
||||
});
|
||||
|
||||
async function main() {
|
||||
const response = await llm.deepseekLlm.chat({
|
||||
messages: [
|
||||
{
|
||||
role: "system",
|
||||
content: "You are an AI assistant",
|
||||
},
|
||||
{
|
||||
role: "user",
|
||||
content: "Tell me about San Francisco",
|
||||
},
|
||||
],
|
||||
stream: false,
|
||||
});
|
||||
console.log(response);
|
||||
}
|
||||
```
|
||||
|
||||
# Limitations
|
||||
|
||||
Currently does not support function calling.
|
||||
|
||||
[Currently does not support json-output param while still is very good at json generating.](https://platform.deepseek.com/api-docs/faq#does-your-api-support-json-output)
|
||||
|
||||
## API platform
|
||||
|
||||
- [DeepSeek platform](https://platform.deepseek.com/)
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "docs",
|
||||
"version": "0.0.47",
|
||||
"version": "0.0.51",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"docusaurus": "docusaurus",
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
import {
|
||||
Document,
|
||||
SentenceSplitter,
|
||||
Settings,
|
||||
SimpleNodeParser,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
|
||||
export const STORAGE_DIR = "./data";
|
||||
|
||||
// Update node parser
|
||||
Settings.nodeParser = new SimpleNodeParser({
|
||||
Settings.nodeParser = new SentenceSplitter({
|
||||
chunkSize: 512,
|
||||
chunkOverlap: 20,
|
||||
splitLongSentences: true,
|
||||
});
|
||||
(async () => {
|
||||
// generate a document with a very long sentence (9000 words long)
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
"start:pdf": "node --import tsx ./src/pdf.ts",
|
||||
"start:llamaparse": "node --import tsx ./src/llamaparse.ts",
|
||||
"start:notion": "node --import tsx ./src/notion.ts",
|
||||
"start:assemblyai": "node --import tsx ./src/assemblyai.ts",
|
||||
"start:llamaparse-dir": "node --import tsx ./src/simple-directory-reader-with-llamaparse.ts",
|
||||
"start:llamaparse-json": "node --import tsx ./src/llamaparse-json.ts",
|
||||
"start:discord": "node --import tsx ./src/discord.ts"
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { JSONReader } from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Data
|
||||
const file = "../data/tinytweets.json";
|
||||
const nonAsciiContent = '{"message": "こんにちは世界"}';
|
||||
const jsonlContent = '{"tweet": "Hello world"}\n{"tweet": "こんにちは世界"}';
|
||||
|
||||
// Convert strings to Uint8Array for loadDataAsContent
|
||||
const nonAsciiBuffer = new TextEncoder().encode(nonAsciiContent);
|
||||
const jsonlBuffer = new TextEncoder().encode(jsonlContent);
|
||||
|
||||
// Default settings
|
||||
const reader1 = new JSONReader();
|
||||
const docs1 = await reader1.loadData(file);
|
||||
console.log(docs1[0]);
|
||||
|
||||
// Unclean JSON
|
||||
const reader2 = new JSONReader({ cleanJson: false });
|
||||
const docs2 = await reader2.loadData(file);
|
||||
console.log(docs2[0]);
|
||||
|
||||
// Depth first yield of JSON structural paths, going back 2 levels
|
||||
const reader3 = new JSONReader({ levelsBack: 2 });
|
||||
const docs3 = await reader3.loadData(file);
|
||||
console.log(docs3[0]);
|
||||
|
||||
// Depth first yield of all levels
|
||||
const reader4 = new JSONReader({ levelsBack: 0 });
|
||||
const docs4 = await reader4.loadData(file);
|
||||
console.log(docs4[0]);
|
||||
|
||||
// Depth first yield of all levels, collapse structural paths below length 100
|
||||
const reader5 = new JSONReader({ levelsBack: 0, collapseLength: 100 });
|
||||
const docs5 = await reader5.loadData(file);
|
||||
console.log(docs5[0]);
|
||||
|
||||
// Convert ASCII to unichode escape sequences
|
||||
const reader6 = new JSONReader({ ensureAscii: true });
|
||||
const docs6 = await reader6.loadDataAsContent(nonAsciiBuffer);
|
||||
console.log(docs6[0]);
|
||||
|
||||
// JSON Lines Format
|
||||
const reader7 = new JSONReader({ isJsonLines: true });
|
||||
const docs7 = await reader7.loadDataAsContent(jsonlBuffer);
|
||||
console.log(docs7[0]);
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
+1
-1
@@ -8,7 +8,7 @@ async function main() {
|
||||
|
||||
const textSplitter = new SentenceSplitter();
|
||||
|
||||
const chunks = textSplitter.splitTextWithOverlaps(essay);
|
||||
const chunks = textSplitter.splitText(essay);
|
||||
|
||||
console.log(chunks);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,41 @@
|
||||
# @llamaindex/autotool-02-next-example
|
||||
|
||||
## 0.1.35
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [086b940]
|
||||
- Updated dependencies [5d5716b]
|
||||
- Updated dependencies [91d02a4]
|
||||
- Updated dependencies [fb6db45]
|
||||
- llamaindex@0.5.10
|
||||
- @llamaindex/autotool@2.0.0
|
||||
|
||||
## 0.1.34
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [15962b3]
|
||||
- llamaindex@0.5.9
|
||||
- @llamaindex/autotool@2.0.0
|
||||
|
||||
## 0.1.33
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [3d5ba08]
|
||||
- Updated dependencies [d917cdc]
|
||||
- llamaindex@0.5.8
|
||||
- @llamaindex/autotool@2.0.0
|
||||
|
||||
## 0.1.32
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [ec59acd]
|
||||
- llamaindex@0.5.7
|
||||
- @llamaindex/autotool@2.0.0
|
||||
|
||||
## 0.1.31
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@llamaindex/autotool-02-next-example",
|
||||
"private": true,
|
||||
"version": "0.1.31",
|
||||
"version": "0.1.35",
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
|
||||
@@ -51,7 +51,7 @@
|
||||
"unplugin": "^1.10.1"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"llamaindex": "^0.5.6",
|
||||
"llamaindex": "^0.5.10",
|
||||
"openai": "^4",
|
||||
"typescript": "^4"
|
||||
},
|
||||
|
||||
@@ -1,5 +1,20 @@
|
||||
# @llamaindex/community
|
||||
|
||||
## 0.0.25
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [91d02a4]
|
||||
- @llamaindex/core@0.1.5
|
||||
|
||||
## 0.0.24
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 3d9a802: feat: added llama 3.1
|
||||
- Updated dependencies [15962b3]
|
||||
- @llamaindex/core@0.1.4
|
||||
|
||||
## 0.0.23
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
## Current Features:
|
||||
|
||||
- Bedrock support for the Anthropic Claude Models [usage](https://ts.llamaindex.ai/modules/llms/available_llms/bedrock)
|
||||
- Bedrock support for the Meta LLama 2 and 3 Models [usage](https://ts.llamaindex.ai/modules/llms/available_llms/bedrock)
|
||||
- Bedrock support for the Meta LLama 2, 3 and 3.1 Models [usage](https://ts.llamaindex.ai/modules/llms/available_llms/bedrock)
|
||||
|
||||
## LICENSE
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@llamaindex/community",
|
||||
"description": "Community package for LlamaIndexTS",
|
||||
"version": "0.0.23",
|
||||
"version": "0.0.25",
|
||||
"type": "module",
|
||||
"types": "dist/type/index.d.ts",
|
||||
"main": "dist/cjs/index.js",
|
||||
|
||||
@@ -60,6 +60,9 @@ export enum BEDROCK_MODELS {
|
||||
META_LLAMA2_70B_CHAT = "meta.llama2-70b-chat-v1",
|
||||
META_LLAMA3_8B_INSTRUCT = "meta.llama3-8b-instruct-v1:0",
|
||||
META_LLAMA3_70B_INSTRUCT = "meta.llama3-70b-instruct-v1:0",
|
||||
META_LLAMA3_1_8B_INSTRUCT = "meta.llama3-1-8b-instruct-v1:0",
|
||||
META_LLAMA3_1_70B_INSTRUCT = "meta.llama3-1-70b-instruct-v1:0",
|
||||
META_LLAMA3_1_405B_INSTRUCT = "meta.llama3-1-405b-instruct-v1:0",
|
||||
MISTRAL_7B_INSTRUCT = "mistral.mistral-7b-instruct-v0:2",
|
||||
MISTRAL_MIXTRAL_7B_INSTRUCT = "mistral.mixtral-8x7b-instruct-v0:1",
|
||||
MISTRAL_MIXTRAL_LARGE_2402 = "mistral.mistral-large-2402-v1:0",
|
||||
@@ -94,6 +97,9 @@ const CHAT_ONLY_MODELS = {
|
||||
[BEDROCK_MODELS.META_LLAMA2_70B_CHAT]: 4096,
|
||||
[BEDROCK_MODELS.META_LLAMA3_8B_INSTRUCT]: 8192,
|
||||
[BEDROCK_MODELS.META_LLAMA3_70B_INSTRUCT]: 8192,
|
||||
[BEDROCK_MODELS.META_LLAMA3_1_8B_INSTRUCT]: 128000,
|
||||
[BEDROCK_MODELS.META_LLAMA3_1_70B_INSTRUCT]: 128000,
|
||||
[BEDROCK_MODELS.META_LLAMA3_1_405B_INSTRUCT]: 128000,
|
||||
[BEDROCK_MODELS.MISTRAL_7B_INSTRUCT]: 32000,
|
||||
[BEDROCK_MODELS.MISTRAL_MIXTRAL_7B_INSTRUCT]: 32000,
|
||||
[BEDROCK_MODELS.MISTRAL_MIXTRAL_LARGE_2402]: 32000,
|
||||
@@ -121,6 +127,9 @@ export const STREAMING_MODELS = new Set([
|
||||
BEDROCK_MODELS.META_LLAMA2_70B_CHAT,
|
||||
BEDROCK_MODELS.META_LLAMA3_8B_INSTRUCT,
|
||||
BEDROCK_MODELS.META_LLAMA3_70B_INSTRUCT,
|
||||
BEDROCK_MODELS.META_LLAMA3_1_8B_INSTRUCT,
|
||||
BEDROCK_MODELS.META_LLAMA3_1_70B_INSTRUCT,
|
||||
BEDROCK_MODELS.META_LLAMA3_1_405B_INSTRUCT,
|
||||
BEDROCK_MODELS.MISTRAL_7B_INSTRUCT,
|
||||
BEDROCK_MODELS.MISTRAL_MIXTRAL_7B_INSTRUCT,
|
||||
BEDROCK_MODELS.MISTRAL_MIXTRAL_LARGE_2402,
|
||||
@@ -160,6 +169,9 @@ export const BEDROCK_MODEL_MAX_TOKENS: Partial<Record<BEDROCK_MODELS, number>> =
|
||||
[BEDROCK_MODELS.META_LLAMA2_70B_CHAT]: 2048,
|
||||
[BEDROCK_MODELS.META_LLAMA3_8B_INSTRUCT]: 2048,
|
||||
[BEDROCK_MODELS.META_LLAMA3_70B_INSTRUCT]: 2048,
|
||||
[BEDROCK_MODELS.META_LLAMA3_1_8B_INSTRUCT]: 2048,
|
||||
[BEDROCK_MODELS.META_LLAMA3_1_70B_INSTRUCT]: 2048,
|
||||
[BEDROCK_MODELS.META_LLAMA3_1_405B_INSTRUCT]: 2048,
|
||||
};
|
||||
|
||||
const DEFAULT_BEDROCK_PARAMS = {
|
||||
|
||||
@@ -1,5 +1,22 @@
|
||||
# @llamaindex/core
|
||||
|
||||
## 0.1.5
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 91d02a4: feat: support transform component callable
|
||||
|
||||
## 0.1.4
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 15962b3: feat: node parser refactor
|
||||
|
||||
Align the text splitter logic with Python; it has almost the same logic as Python; Zod checks for input and better error messages and event system.
|
||||
|
||||
This change will not be considered a breaking change since it doesn't have a significant output difference from the last version,
|
||||
but some edge cases will change, like the page separator and parameter for the constructor.
|
||||
|
||||
## 0.1.3
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -1,9 +1,23 @@
|
||||
{
|
||||
"name": "@llamaindex/core",
|
||||
"type": "module",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.5",
|
||||
"description": "LlamaIndex Core Module",
|
||||
"exports": {
|
||||
"./node-parser": {
|
||||
"require": {
|
||||
"types": "./dist/node-parser/index.d.cts",
|
||||
"default": "./dist/node-parser/index.cjs"
|
||||
},
|
||||
"import": {
|
||||
"types": "./dist/node-parser/index.d.ts",
|
||||
"default": "./dist/node-parser/index.js"
|
||||
},
|
||||
"default": {
|
||||
"types": "./dist/node-parser/index.d.ts",
|
||||
"default": "./dist/node-parser/index.js"
|
||||
}
|
||||
},
|
||||
"./query-engine": {
|
||||
"require": {
|
||||
"types": "./dist/query-engine/index.d.cts",
|
||||
@@ -117,7 +131,8 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"ajv": "^8.16.0",
|
||||
"bunchee": "5.3.0-beta.0"
|
||||
"bunchee": "5.3.0-beta.0",
|
||||
"natural": "^7.1.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@llamaindex/env": "workspace:*",
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { type Tokenizers } from "@llamaindex/env";
|
||||
import type { MessageContentDetail } from "../llms";
|
||||
import type { TransformComponent } from "../schema";
|
||||
import { BaseNode, MetadataMode } from "../schema";
|
||||
import { BaseNode, MetadataMode, TransformComponent } from "../schema";
|
||||
import { extractSingleText } from "../utils";
|
||||
import { truncateMaxTokens } from "./tokenizer.js";
|
||||
import { SimilarityType, similarity } from "./utils.js";
|
||||
@@ -20,12 +19,29 @@ export type BaseEmbeddingOptions = {
|
||||
logProgress?: boolean;
|
||||
};
|
||||
|
||||
export abstract class BaseEmbedding
|
||||
implements TransformComponent<BaseEmbeddingOptions>
|
||||
{
|
||||
export abstract class BaseEmbedding extends TransformComponent {
|
||||
embedBatchSize = DEFAULT_EMBED_BATCH_SIZE;
|
||||
embedInfo?: EmbeddingInfo;
|
||||
|
||||
constructor() {
|
||||
super(
|
||||
async (
|
||||
nodes: BaseNode[],
|
||||
options?: BaseEmbeddingOptions,
|
||||
): Promise<BaseNode[]> => {
|
||||
const texts = nodes.map((node) => node.getContent(MetadataMode.EMBED));
|
||||
|
||||
const embeddings = await this.getTextEmbeddingsBatch(texts, options);
|
||||
|
||||
for (let i = 0; i < nodes.length; i++) {
|
||||
nodes[i].embedding = embeddings[i];
|
||||
}
|
||||
|
||||
return nodes;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
similarity(
|
||||
embedding1: number[],
|
||||
embedding2: number[],
|
||||
@@ -78,21 +94,6 @@ export abstract class BaseEmbedding
|
||||
);
|
||||
}
|
||||
|
||||
async transform(
|
||||
nodes: BaseNode[],
|
||||
options?: BaseEmbeddingOptions,
|
||||
): Promise<BaseNode[]> {
|
||||
const texts = nodes.map((node) => node.getContent(MetadataMode.EMBED));
|
||||
|
||||
const embeddings = await this.getTextEmbeddingsBatch(texts, options);
|
||||
|
||||
for (let i = 0; i < nodes.length; i++) {
|
||||
nodes[i].embedding = embeddings[i];
|
||||
}
|
||||
|
||||
return nodes;
|
||||
}
|
||||
|
||||
truncateMaxTokens(input: string[]): string[] {
|
||||
return input.map((s) => {
|
||||
// truncate to max tokens
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { Tokenizer } from "@llamaindex/env";
|
||||
import {
|
||||
type CallbackManager,
|
||||
getCallbackManager,
|
||||
@@ -9,8 +10,22 @@ import {
|
||||
setChunkSize,
|
||||
withChunkSize,
|
||||
} from "./settings/chunk-size";
|
||||
import {
|
||||
getTokenizer,
|
||||
setTokenizer,
|
||||
withTokenizer,
|
||||
} from "./settings/tokenizer";
|
||||
|
||||
export const Settings = {
|
||||
get tokenizer() {
|
||||
return getTokenizer();
|
||||
},
|
||||
set tokenizer(tokenizer) {
|
||||
setTokenizer(tokenizer);
|
||||
},
|
||||
withTokenizer<Result>(tokenizer: Tokenizer, fn: () => Result): Result {
|
||||
return withTokenizer(tokenizer, fn);
|
||||
},
|
||||
get chunkSize(): number | undefined {
|
||||
return getChunkSize();
|
||||
},
|
||||
|
||||
@@ -6,6 +6,7 @@ import type {
|
||||
ToolCall,
|
||||
ToolOutput,
|
||||
} from "../../llms";
|
||||
import { TextNode } from "../../schema";
|
||||
import { EventCaller, getEventCaller } from "../../utils/event-caller";
|
||||
import type { UUID } from "../type";
|
||||
|
||||
@@ -33,12 +34,32 @@ export type LLMStreamEvent = {
|
||||
chunk: ChatResponseChunk;
|
||||
};
|
||||
|
||||
export type ChunkingStartEvent = {
|
||||
text: string[];
|
||||
};
|
||||
|
||||
export type ChunkingEndEvent = {
|
||||
chunks: string[];
|
||||
};
|
||||
|
||||
export type NodeParsingStartEvent = {
|
||||
documents: TextNode[];
|
||||
};
|
||||
|
||||
export type NodeParsingEndEvent = {
|
||||
nodes: TextNode[];
|
||||
};
|
||||
|
||||
export interface LlamaIndexEventMaps {
|
||||
"llm-start": LLMStartEvent;
|
||||
"llm-end": LLMEndEvent;
|
||||
"llm-tool-call": LLMToolCallEvent;
|
||||
"llm-tool-result": LLMToolResultEvent;
|
||||
"llm-stream": LLMStreamEvent;
|
||||
"chunking-start": ChunkingStartEvent;
|
||||
"chunking-end": ChunkingEndEvent;
|
||||
"node-parsing-start": NodeParsingStartEvent;
|
||||
"node-parsing-end": NodeParsingEndEvent;
|
||||
}
|
||||
|
||||
export class LlamaIndexCustomEvent<T = any> extends CustomEvent<T> {
|
||||
@@ -116,14 +137,10 @@ export const globalCallbackManager = new CallbackManager();
|
||||
const callbackManagerAsyncLocalStorage =
|
||||
new AsyncLocalStorage<CallbackManager>();
|
||||
|
||||
let currentCallbackManager: CallbackManager | null = null;
|
||||
let currentCallbackManager: CallbackManager = globalCallbackManager;
|
||||
|
||||
export function getCallbackManager(): CallbackManager {
|
||||
return (
|
||||
callbackManagerAsyncLocalStorage.getStore() ??
|
||||
currentCallbackManager ??
|
||||
globalCallbackManager
|
||||
);
|
||||
return callbackManagerAsyncLocalStorage.getStore() ?? currentCallbackManager;
|
||||
}
|
||||
|
||||
export function setCallbackManager(callbackManager: CallbackManager) {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { AsyncLocalStorage } from "@llamaindex/env";
|
||||
|
||||
const chunkSizeAsyncLocalStorage = new AsyncLocalStorage<number | undefined>();
|
||||
let globalChunkSize: number | null = null;
|
||||
let globalChunkSize: number = 1024;
|
||||
|
||||
export function getChunkSize(): number | undefined {
|
||||
export function getChunkSize(): number {
|
||||
return globalChunkSize ?? chunkSizeAsyncLocalStorage.getStore();
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { AsyncLocalStorage, type Tokenizer, tokenizers } from "@llamaindex/env";
|
||||
|
||||
const chunkSizeAsyncLocalStorage = new AsyncLocalStorage<Tokenizer>();
|
||||
let globalTokenizer: Tokenizer = tokenizers.tokenizer();
|
||||
|
||||
export function getTokenizer(): Tokenizer {
|
||||
return globalTokenizer ?? chunkSizeAsyncLocalStorage.getStore();
|
||||
}
|
||||
|
||||
export function setTokenizer(tokenizer: Tokenizer | undefined) {
|
||||
if (tokenizer !== undefined) {
|
||||
globalTokenizer = tokenizer;
|
||||
}
|
||||
}
|
||||
|
||||
export function withTokenizer<Result>(
|
||||
tokenizer: Tokenizer,
|
||||
fn: () => Result,
|
||||
): Result {
|
||||
return chunkSizeAsyncLocalStorage.run(tokenizer, fn);
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import { Settings } from "../global";
|
||||
import {
|
||||
BaseNode,
|
||||
buildNodeFromSplits,
|
||||
MetadataMode,
|
||||
NodeRelationship,
|
||||
TextNode,
|
||||
TransformComponent,
|
||||
} from "../schema";
|
||||
|
||||
export abstract class NodeParser extends TransformComponent {
|
||||
includeMetadata: boolean = true;
|
||||
includePrevNextRel: boolean = true;
|
||||
|
||||
constructor() {
|
||||
super(async (nodes: BaseNode[]): Promise<BaseNode[]> => {
|
||||
return this.getNodesFromDocuments(nodes as TextNode[]);
|
||||
});
|
||||
}
|
||||
|
||||
protected postProcessParsedNodes(
|
||||
nodes: TextNode[],
|
||||
parentDocMap: Map<string, TextNode>,
|
||||
): TextNode[] {
|
||||
nodes.forEach((node, i) => {
|
||||
const parentDoc = parentDocMap.get(node.sourceNode?.nodeId || "");
|
||||
|
||||
if (parentDoc) {
|
||||
const startCharIdx = parentDoc.text.indexOf(
|
||||
node.getContent(MetadataMode.NONE),
|
||||
);
|
||||
if (startCharIdx >= 0) {
|
||||
node.startCharIdx = startCharIdx;
|
||||
node.endCharIdx =
|
||||
startCharIdx + node.getContent(MetadataMode.NONE).length;
|
||||
}
|
||||
if (this.includeMetadata && node.metadata && parentDoc.metadata) {
|
||||
node.metadata = { ...node.metadata, ...parentDoc.metadata };
|
||||
}
|
||||
}
|
||||
|
||||
if (this.includePrevNextRel && node.sourceNode) {
|
||||
const previousNode = i > 0 ? nodes[i - 1] : null;
|
||||
const nextNode = i < nodes.length - 1 ? nodes[i + 1] : null;
|
||||
|
||||
if (
|
||||
previousNode &&
|
||||
previousNode.sourceNode &&
|
||||
previousNode.sourceNode.nodeId === node.sourceNode.nodeId
|
||||
) {
|
||||
node.relationships = {
|
||||
...node.relationships,
|
||||
[NodeRelationship.PREVIOUS]: previousNode.asRelatedNodeInfo(),
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
nextNode &&
|
||||
nextNode.sourceNode &&
|
||||
nextNode.sourceNode.nodeId === node.sourceNode.nodeId
|
||||
) {
|
||||
node.relationships = {
|
||||
...node.relationships,
|
||||
[NodeRelationship.NEXT]: nextNode.asRelatedNodeInfo(),
|
||||
};
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return nodes;
|
||||
}
|
||||
|
||||
protected abstract parseNodes(
|
||||
documents: TextNode[],
|
||||
showProgress?: boolean,
|
||||
): TextNode[];
|
||||
|
||||
public getNodesFromDocuments(documents: TextNode[]): TextNode[] {
|
||||
const docsId: Map<string, TextNode> = new Map(
|
||||
documents.map((doc) => [doc.id_, doc]),
|
||||
);
|
||||
const callbackManager = Settings.callbackManager;
|
||||
|
||||
callbackManager.dispatchEvent("node-parsing-start", {
|
||||
documents,
|
||||
});
|
||||
|
||||
const nodes = this.postProcessParsedNodes(
|
||||
this.parseNodes(documents),
|
||||
docsId,
|
||||
);
|
||||
|
||||
callbackManager.dispatchEvent("node-parsing-end", {
|
||||
nodes,
|
||||
});
|
||||
|
||||
return nodes;
|
||||
}
|
||||
}
|
||||
|
||||
export abstract class TextSplitter extends NodeParser {
|
||||
abstract splitText(text: string): string[];
|
||||
|
||||
public splitTexts(texts: string[]): string[] {
|
||||
return texts.flatMap((text) => this.splitText(text));
|
||||
}
|
||||
|
||||
protected parseNodes(nodes: TextNode[]): TextNode[] {
|
||||
return nodes.reduce<TextNode[]>((allNodes, node) => {
|
||||
const splits = this.splitText(node.getContent(MetadataMode.ALL));
|
||||
const nodes = buildNodeFromSplits(splits, node);
|
||||
return allNodes.concat(nodes);
|
||||
}, []);
|
||||
}
|
||||
}
|
||||
|
||||
export abstract class MetadataAwareTextSplitter extends TextSplitter {
|
||||
abstract splitTextMetadataAware(text: string, metadata: string): string[];
|
||||
|
||||
splitTextsMetadataAware(texts: string[], metadata: string[]): string[] {
|
||||
if (texts.length !== metadata.length) {
|
||||
throw new TypeError("`texts` and `metadata` must have the same length");
|
||||
}
|
||||
return texts.flatMap((text, i) =>
|
||||
this.splitTextMetadataAware(text, metadata[i]),
|
||||
);
|
||||
}
|
||||
|
||||
protected getMetadataString(node: TextNode): string {
|
||||
const embedStr = node.getMetadataStr(MetadataMode.EMBED);
|
||||
const llmStr = node.getMetadataStr(MetadataMode.LLM);
|
||||
if (embedStr.length > llmStr.length) {
|
||||
return embedStr;
|
||||
} else {
|
||||
return llmStr;
|
||||
}
|
||||
}
|
||||
|
||||
protected parseNodes(nodes: TextNode[]): TextNode[] {
|
||||
return nodes.reduce<TextNode[]>((allNodes, node) => {
|
||||
const metadataStr = this.getMetadataString(node);
|
||||
const splits = this.splitTextMetadataAware(
|
||||
node.getContent(MetadataMode.ALL),
|
||||
metadataStr,
|
||||
);
|
||||
return allNodes.concat(buildNodeFromSplits(splits, node));
|
||||
}, []);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* Current logic is based on the following implementation:
|
||||
* @link @link https://github.com/run-llama/llama_index/blob/cc0ea90e7e72b8e4f5069aac981d56bb1d568323/llama-index-core/llama_index/core/node_parser
|
||||
*/
|
||||
import { SentenceSplitter } from "./sentence-splitter";
|
||||
|
||||
/**
|
||||
* @deprecated Use `SentenceSplitter` instead
|
||||
*/
|
||||
export const SimpleNodeParser = SentenceSplitter;
|
||||
|
||||
export { MetadataAwareTextSplitter, NodeParser, TextSplitter } from "./base";
|
||||
export { MarkdownNodeParser } from "./markdown";
|
||||
export { SentenceSplitter } from "./sentence-splitter";
|
||||
export { SentenceWindowNodeParser } from "./sentence-window";
|
||||
export type { SplitterParams } from "./type";
|
||||
export {
|
||||
splitByChar,
|
||||
splitByPhraseRegex,
|
||||
splitByRegex,
|
||||
splitBySentenceTokenizer,
|
||||
splitBySep,
|
||||
} from "./utils";
|
||||
export type { TextSplitterFn } from "./utils";
|
||||
@@ -0,0 +1,87 @@
|
||||
import {
|
||||
buildNodeFromSplits,
|
||||
type Metadata,
|
||||
MetadataMode,
|
||||
TextNode,
|
||||
} from "../schema";
|
||||
import { NodeParser } from "./base";
|
||||
|
||||
export class MarkdownNodeParser extends NodeParser {
|
||||
override parseNodes(nodes: TextNode[], showProgress?: boolean): TextNode[] {
|
||||
return nodes.reduce<TextNode[]>((allNodes, node) => {
|
||||
const markdownNodes = this.getNodesFromNode(node);
|
||||
return allNodes.concat(markdownNodes);
|
||||
}, []);
|
||||
}
|
||||
|
||||
protected getNodesFromNode(node: TextNode): TextNode[] {
|
||||
const text = node.getContent(MetadataMode.NONE);
|
||||
const markdownNodes: TextNode[] = [];
|
||||
const lines = text.split("\n");
|
||||
let metadata: { [key: string]: string } = {};
|
||||
let codeBlock = false;
|
||||
let currentSection = "";
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.trim().startsWith("```")) {
|
||||
codeBlock = !codeBlock;
|
||||
}
|
||||
const headerMatch = /^(#+)\s(.*)/.exec(line);
|
||||
if (headerMatch && !codeBlock) {
|
||||
if (currentSection !== "") {
|
||||
markdownNodes.push(
|
||||
this.buildNodeFromSplit(currentSection.trim(), node, metadata),
|
||||
);
|
||||
}
|
||||
metadata = this.updateMetadata(
|
||||
metadata,
|
||||
headerMatch[2],
|
||||
headerMatch[1].trim().length,
|
||||
);
|
||||
currentSection = `${headerMatch[2]}\n`;
|
||||
} else {
|
||||
currentSection += line + "\n";
|
||||
}
|
||||
}
|
||||
|
||||
if (currentSection !== "") {
|
||||
markdownNodes.push(
|
||||
this.buildNodeFromSplit(currentSection.trim(), node, metadata),
|
||||
);
|
||||
}
|
||||
|
||||
return markdownNodes;
|
||||
}
|
||||
|
||||
private updateMetadata(
|
||||
headersMetadata: { [key: string]: string },
|
||||
newHeader: string,
|
||||
newHeaderLevel: number,
|
||||
): { [key: string]: string } {
|
||||
const updatedHeaders: { [key: string]: string } = {};
|
||||
|
||||
for (let i = 1; i < newHeaderLevel; i++) {
|
||||
const key = `Header_${i}`;
|
||||
if (key in headersMetadata) {
|
||||
updatedHeaders[key] = headersMetadata[key];
|
||||
}
|
||||
}
|
||||
|
||||
updatedHeaders[`Header_${newHeaderLevel}`] = newHeader;
|
||||
return updatedHeaders;
|
||||
}
|
||||
|
||||
private buildNodeFromSplit(
|
||||
textSplit: string,
|
||||
node: TextNode,
|
||||
metadata: Metadata,
|
||||
): TextNode {
|
||||
const newNode = buildNodeFromSplits([textSplit], node, undefined)[0];
|
||||
|
||||
if (this.includeMetadata) {
|
||||
newNode.metadata = { ...newNode.metadata, ...metadata };
|
||||
}
|
||||
|
||||
return newNode;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
import type { Tokenizer } from "@llamaindex/env";
|
||||
import { z } from "zod";
|
||||
import { Settings } from "../global";
|
||||
import { sentenceSplitterSchema } from "../schema";
|
||||
import { MetadataAwareTextSplitter } from "./base";
|
||||
import type { SplitterParams } from "./type";
|
||||
import {
|
||||
splitByChar,
|
||||
splitByRegex,
|
||||
splitBySentenceTokenizer,
|
||||
splitBySep,
|
||||
type TextSplitterFn,
|
||||
} from "./utils";
|
||||
|
||||
type _Split = {
|
||||
text: string;
|
||||
isSentence: boolean;
|
||||
tokenSize: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse text with a preference for complete sentences.
|
||||
*/
|
||||
export class SentenceSplitter extends MetadataAwareTextSplitter {
|
||||
/**
|
||||
* The token chunk size for each chunk.
|
||||
*/
|
||||
chunkSize: number = 1024;
|
||||
/**
|
||||
* The token overlap of each chunk when splitting.
|
||||
*/
|
||||
chunkOverlap: number = 200;
|
||||
/**
|
||||
* Default separator for splitting into words
|
||||
*/
|
||||
separator: string = " ";
|
||||
/**
|
||||
* Separator between paragraphs.
|
||||
*/
|
||||
paragraphSeparator: string = "\n\n\n";
|
||||
/**
|
||||
* Backup regex for splitting into sentences.
|
||||
*/
|
||||
secondaryChunkingRegex: string = "[^,.;。?!]+[,.;。?!]?";
|
||||
|
||||
#chunkingTokenizerFn = splitBySentenceTokenizer();
|
||||
#splitFns: Set<TextSplitterFn> = new Set();
|
||||
#subSentenceSplitFns: Set<TextSplitterFn> = new Set();
|
||||
#tokenizer: Tokenizer;
|
||||
|
||||
constructor(
|
||||
params?: z.input<typeof sentenceSplitterSchema> & SplitterParams,
|
||||
) {
|
||||
super();
|
||||
if (params) {
|
||||
const parsedParams = sentenceSplitterSchema.parse(params);
|
||||
this.chunkSize = parsedParams.chunkSize;
|
||||
this.chunkOverlap = parsedParams.chunkOverlap;
|
||||
this.separator = parsedParams.separator;
|
||||
this.paragraphSeparator = parsedParams.paragraphSeparator;
|
||||
this.secondaryChunkingRegex = parsedParams.secondaryChunkingRegex;
|
||||
}
|
||||
this.#tokenizer = params?.tokenizer ?? Settings.tokenizer;
|
||||
this.#splitFns.add(splitBySep(this.paragraphSeparator));
|
||||
this.#splitFns.add(this.#chunkingTokenizerFn);
|
||||
|
||||
this.#subSentenceSplitFns.add(splitByRegex(this.secondaryChunkingRegex));
|
||||
this.#subSentenceSplitFns.add(splitBySep(this.separator));
|
||||
this.#subSentenceSplitFns.add(splitByChar());
|
||||
}
|
||||
|
||||
splitTextMetadataAware(text: string, metadata: string): string[] {
|
||||
const metadataLength = this.tokenSize(metadata);
|
||||
const effectiveChunkSize = this.chunkSize - metadataLength;
|
||||
if (effectiveChunkSize <= 0) {
|
||||
throw new Error(
|
||||
`Metadata length (${metadataLength}) is longer than chunk size (${this.chunkSize}). Consider increasing the chunk size or decreasing the size of your metadata to avoid this.`,
|
||||
);
|
||||
} else if (effectiveChunkSize < 50) {
|
||||
console.log(
|
||||
`Metadata length (${metadataLength}) is close to chunk size (${this.chunkSize}). Resulting chunks are less than 50 tokens. Consider increasing the chunk size or decreasing the size of your metadata to avoid this.`,
|
||||
);
|
||||
}
|
||||
return this._splitText(text, effectiveChunkSize);
|
||||
}
|
||||
|
||||
splitText(text: string): string[] {
|
||||
return this._splitText(text, this.chunkSize);
|
||||
}
|
||||
|
||||
_splitText(text: string, chunkSize: number): string[] {
|
||||
if (text === "") return [text];
|
||||
|
||||
const callbackManager = Settings.callbackManager;
|
||||
|
||||
callbackManager.dispatchEvent("chunking-start", {
|
||||
text: [text],
|
||||
});
|
||||
const splits = this.#split(text, chunkSize);
|
||||
const chunks = this.#merge(splits, chunkSize);
|
||||
|
||||
callbackManager.dispatchEvent("chunking-end", {
|
||||
chunks,
|
||||
});
|
||||
return chunks;
|
||||
}
|
||||
|
||||
#split(text: string, chunkSize: number): _Split[] {
|
||||
const tokenSize = this.tokenSize(text);
|
||||
if (tokenSize <= chunkSize) {
|
||||
return [
|
||||
{
|
||||
text,
|
||||
isSentence: true,
|
||||
tokenSize,
|
||||
},
|
||||
];
|
||||
}
|
||||
const [textSplitsByFns, isSentence] = this.#getSplitsByFns(text);
|
||||
const textSplits: _Split[] = [];
|
||||
|
||||
for (const textSplit of textSplitsByFns) {
|
||||
const tokenSize = this.tokenSize(textSplit);
|
||||
if (tokenSize <= chunkSize) {
|
||||
textSplits.push({
|
||||
text: textSplit,
|
||||
isSentence,
|
||||
tokenSize,
|
||||
});
|
||||
} else {
|
||||
const recursiveTextSplits = this.#split(textSplit, chunkSize);
|
||||
textSplits.push(...recursiveTextSplits);
|
||||
}
|
||||
}
|
||||
return textSplits;
|
||||
}
|
||||
|
||||
#getSplitsByFns(text: string): [splits: string[], isSentence: boolean] {
|
||||
for (const splitFn of this.#splitFns) {
|
||||
const splits = splitFn(text);
|
||||
if (splits.length > 1) {
|
||||
return [splits, true];
|
||||
}
|
||||
}
|
||||
for (const splitFn of this.#subSentenceSplitFns) {
|
||||
const splits = splitFn(text);
|
||||
if (splits.length > 1) {
|
||||
return [splits, false];
|
||||
}
|
||||
}
|
||||
return [[text], true];
|
||||
}
|
||||
|
||||
#merge(splits: _Split[], chunkSize: number): string[] {
|
||||
const chunks: string[] = [];
|
||||
let currentChunk: [string, number][] = [];
|
||||
let lastChunk: [string, number][] = [];
|
||||
let currentChunkLength = 0;
|
||||
let newChunk = true;
|
||||
|
||||
const closeChunk = (): void => {
|
||||
chunks.push(currentChunk.map(([text]) => text).join(""));
|
||||
lastChunk = currentChunk;
|
||||
currentChunk = [];
|
||||
currentChunkLength = 0;
|
||||
newChunk = true;
|
||||
|
||||
let lastIndex = lastChunk.length - 1;
|
||||
while (
|
||||
lastIndex >= 0 &&
|
||||
currentChunkLength + lastChunk[lastIndex][1] <= this.chunkOverlap
|
||||
) {
|
||||
const [text, length] = lastChunk[lastIndex];
|
||||
currentChunkLength += length;
|
||||
currentChunk.unshift([text, length]);
|
||||
lastIndex -= 1;
|
||||
}
|
||||
};
|
||||
|
||||
while (splits.length > 0) {
|
||||
const curSplit = splits[0];
|
||||
if (curSplit.tokenSize > chunkSize) {
|
||||
throw new Error("Single token exceeded chunk size");
|
||||
}
|
||||
if (currentChunkLength + curSplit.tokenSize > chunkSize && !newChunk) {
|
||||
closeChunk();
|
||||
} else {
|
||||
if (
|
||||
curSplit.isSentence ||
|
||||
currentChunkLength + curSplit.tokenSize <= chunkSize ||
|
||||
newChunk
|
||||
) {
|
||||
currentChunkLength += curSplit.tokenSize;
|
||||
currentChunk.push([curSplit.text, curSplit.tokenSize]);
|
||||
splits.shift();
|
||||
newChunk = false;
|
||||
} else {
|
||||
closeChunk();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Handle the last chunk
|
||||
if (!newChunk) {
|
||||
chunks.push(currentChunk.map(([text]) => text).join(""));
|
||||
}
|
||||
|
||||
return this.#postprocessChunks(chunks);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove whitespace only chunks and remove leading and trailing whitespace.
|
||||
*/
|
||||
#postprocessChunks(chunks: string[]): string[] {
|
||||
const newChunks: string[] = [];
|
||||
for (const chunk of chunks) {
|
||||
const trimmedChunk = chunk.trim();
|
||||
if (trimmedChunk !== "") {
|
||||
newChunks.push(trimmedChunk);
|
||||
}
|
||||
}
|
||||
return newChunks;
|
||||
}
|
||||
|
||||
tokenSize = (text: string) => this.#tokenizer.encode(text).length;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
declare class SentenceTokenizer {
|
||||
tokenize(text: string): string[];
|
||||
}
|
||||
|
||||
export { SentenceTokenizer as default };
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,85 @@
|
||||
import { randomUUID } from "@llamaindex/env";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
buildNodeFromSplits,
|
||||
Document,
|
||||
sentenceWindowNodeParserSchema,
|
||||
TextNode,
|
||||
} from "../schema";
|
||||
import { NodeParser } from "./base";
|
||||
import { splitBySentenceTokenizer, type TextSplitterFn } from "./utils";
|
||||
|
||||
export class SentenceWindowNodeParser extends NodeParser {
|
||||
static DEFAULT_WINDOW_SIZE = 3;
|
||||
static DEFAULT_WINDOW_METADATA_KEY = "window";
|
||||
static DEFAULT_ORIGINAL_TEXT_METADATA_KEY = "originalText";
|
||||
|
||||
windowSize: number;
|
||||
windowMetadataKey: string;
|
||||
originalTextMetadataKey: string;
|
||||
sentenceSplitter: TextSplitterFn = splitBySentenceTokenizer();
|
||||
idGenerator: () => string = () => randomUUID();
|
||||
|
||||
constructor(params?: z.input<typeof sentenceWindowNodeParserSchema>) {
|
||||
super();
|
||||
if (params) {
|
||||
const parsedParams = sentenceWindowNodeParserSchema.parse(params);
|
||||
this.windowSize = parsedParams.windowSize;
|
||||
this.windowMetadataKey = parsedParams.windowMetadataKey;
|
||||
this.originalTextMetadataKey = parsedParams.originalTextMetadataKey;
|
||||
} else {
|
||||
this.windowSize = SentenceWindowNodeParser.DEFAULT_WINDOW_SIZE;
|
||||
this.windowMetadataKey =
|
||||
SentenceWindowNodeParser.DEFAULT_WINDOW_METADATA_KEY;
|
||||
this.originalTextMetadataKey =
|
||||
SentenceWindowNodeParser.DEFAULT_ORIGINAL_TEXT_METADATA_KEY;
|
||||
}
|
||||
}
|
||||
|
||||
override parseNodes(nodes: TextNode[], showProgress?: boolean): TextNode[] {
|
||||
return nodes.reduce<TextNode[]>((allNodes, node) => {
|
||||
const nodes = this.buildWindowNodesFromDocuments([node]);
|
||||
return allNodes.concat(nodes);
|
||||
}, []);
|
||||
}
|
||||
|
||||
buildWindowNodesFromDocuments(documents: Document[]): TextNode[] {
|
||||
const allNodes: TextNode[] = [];
|
||||
|
||||
for (const doc of documents) {
|
||||
const text = doc.text;
|
||||
const textSplits = this.sentenceSplitter(text);
|
||||
const nodes = buildNodeFromSplits(
|
||||
textSplits,
|
||||
doc,
|
||||
undefined,
|
||||
this.idGenerator,
|
||||
);
|
||||
|
||||
nodes.forEach((node, i) => {
|
||||
const windowNodes = nodes.slice(
|
||||
Math.max(0, i - this.windowSize),
|
||||
Math.min(i + this.windowSize + 1, nodes.length),
|
||||
);
|
||||
|
||||
node.metadata[this.windowMetadataKey] = windowNodes
|
||||
.map((n) => n.text)
|
||||
.join(" ");
|
||||
node.metadata[this.originalTextMetadataKey] = node.text;
|
||||
|
||||
node.excludedEmbedMetadataKeys.push(
|
||||
this.windowMetadataKey,
|
||||
this.originalTextMetadataKey,
|
||||
);
|
||||
node.excludedLlmMetadataKeys.push(
|
||||
this.windowMetadataKey,
|
||||
this.originalTextMetadataKey,
|
||||
);
|
||||
});
|
||||
|
||||
allNodes.push(...nodes);
|
||||
}
|
||||
|
||||
return allNodes;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import type { Tokenizer } from "@llamaindex/env";
|
||||
|
||||
export type SplitterParams = {
|
||||
tokenizer?: Tokenizer;
|
||||
};
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { TextSplitter } from "./base";
|
||||
import SentenceTokenizerNew from "./sentence-tokenizer-parser.js";
|
||||
|
||||
export type TextSplitterFn = (text: string) => string[];
|
||||
|
||||
const truncateText = (text: string, textSplitter: TextSplitter): string => {
|
||||
const chunks = textSplitter.splitText(text);
|
||||
return chunks[0];
|
||||
};
|
||||
|
||||
const splitTextKeepSeparator = (text: string, separator: string): string[] => {
|
||||
const parts = text.split(separator);
|
||||
const result = parts.map((part, index) =>
|
||||
index > 0 ? separator + part : part,
|
||||
);
|
||||
return result.filter((s) => s);
|
||||
};
|
||||
|
||||
export const splitBySep = (
|
||||
sep: string,
|
||||
keepSep: boolean = true,
|
||||
): TextSplitterFn => {
|
||||
if (keepSep) {
|
||||
return (text: string) => splitTextKeepSeparator(text, sep);
|
||||
} else {
|
||||
return (text: string) => text.split(sep);
|
||||
}
|
||||
};
|
||||
|
||||
export const splitByChar = (): TextSplitterFn => {
|
||||
return (text: string) => text.split("");
|
||||
};
|
||||
|
||||
let sentenceTokenizer: SentenceTokenizerNew | null = null;
|
||||
|
||||
export const splitBySentenceTokenizer = (): TextSplitterFn => {
|
||||
if (!sentenceTokenizer) {
|
||||
sentenceTokenizer = new SentenceTokenizerNew();
|
||||
}
|
||||
const tokenizer = sentenceTokenizer;
|
||||
return (text: string) => {
|
||||
return tokenizer.tokenize(text);
|
||||
};
|
||||
};
|
||||
|
||||
export const splitByRegex = (regex: string): TextSplitterFn => {
|
||||
return (text: string) => text.match(new RegExp(regex, "g")) || [];
|
||||
};
|
||||
|
||||
export const splitByPhraseRegex = (): TextSplitterFn => {
|
||||
const regex = "[^,.;]+[,.;]?";
|
||||
return splitByRegex(regex);
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
export * from "./node";
|
||||
export type { TransformComponent } from "./type";
|
||||
export { TransformComponent } from "./type";
|
||||
export { EngineResponse } from "./type/engine–response";
|
||||
export * from "./zod";
|
||||
|
||||
@@ -450,3 +450,48 @@ export function splitNodesByType(nodes: BaseNode[]): NodesByType {
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function buildNodeFromSplits(
|
||||
textSplits: string[],
|
||||
doc: BaseNode,
|
||||
refDoc: BaseNode = doc,
|
||||
idGenerator: (idx: number, refDoc: BaseNode) => string = () => randomUUID(),
|
||||
) {
|
||||
const nodes: TextNode[] = [];
|
||||
const relationships = {
|
||||
[NodeRelationship.SOURCE]: refDoc.asRelatedNodeInfo(),
|
||||
};
|
||||
|
||||
textSplits.forEach((textChunk, i) => {
|
||||
if (doc instanceof ImageDocument) {
|
||||
const imageNode = new ImageNode({
|
||||
id_: idGenerator(i, doc),
|
||||
text: textChunk,
|
||||
image: doc.image,
|
||||
embedding: doc.embedding,
|
||||
excludedEmbedMetadataKeys: [...doc.excludedEmbedMetadataKeys],
|
||||
excludedLlmMetadataKeys: [...doc.excludedLlmMetadataKeys],
|
||||
metadataSeparator: doc.metadataSeparator,
|
||||
textTemplate: doc.textTemplate,
|
||||
relationships: { ...relationships },
|
||||
});
|
||||
nodes.push(imageNode);
|
||||
} else if (doc instanceof Document || doc instanceof TextNode) {
|
||||
const node = new TextNode({
|
||||
id_: idGenerator(i, doc),
|
||||
text: textChunk,
|
||||
embedding: doc.embedding,
|
||||
excludedEmbedMetadataKeys: [...doc.excludedEmbedMetadataKeys],
|
||||
excludedLlmMetadataKeys: [...doc.excludedLlmMetadataKeys],
|
||||
metadataSeparator: doc.metadataSeparator,
|
||||
textTemplate: doc.textTemplate,
|
||||
relationships: { ...relationships },
|
||||
});
|
||||
nodes.push(node);
|
||||
} else {
|
||||
throw new Error(`Unknown document type: ${doc.type}`);
|
||||
}
|
||||
});
|
||||
|
||||
return nodes;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,30 @@
|
||||
import { randomUUID } from "@llamaindex/env";
|
||||
import type { BaseNode } from "./node";
|
||||
|
||||
export interface TransformComponent<Options extends Record<string, unknown>> {
|
||||
transform(nodes: BaseNode[], options?: Options): Promise<BaseNode[]>;
|
||||
interface TransformComponentSignature {
|
||||
<Options extends Record<string, unknown>>(
|
||||
nodes: BaseNode[],
|
||||
options?: Options,
|
||||
): Promise<BaseNode[]>;
|
||||
}
|
||||
|
||||
export interface TransformComponent extends TransformComponentSignature {
|
||||
id: string;
|
||||
}
|
||||
|
||||
export class TransformComponent {
|
||||
constructor(transformFn: TransformComponentSignature) {
|
||||
Object.defineProperties(
|
||||
transformFn,
|
||||
Object.getOwnPropertyDescriptors(this.constructor.prototype),
|
||||
);
|
||||
const transform = function transform(
|
||||
...args: Parameters<TransformComponentSignature>
|
||||
) {
|
||||
return transformFn(...args);
|
||||
};
|
||||
Reflect.setPrototypeOf(transform, new.target.prototype);
|
||||
transform.id = randomUUID();
|
||||
return transform;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { Settings } from "../global";
|
||||
|
||||
export const anyFunctionSchema = z.function(z.tuple([]).rest(z.any()), z.any());
|
||||
|
||||
@@ -16,3 +17,62 @@ export const baseToolSchema = z.object({
|
||||
export const baseToolWithCallSchema = baseToolSchema.extend({
|
||||
call: z.function(),
|
||||
});
|
||||
|
||||
export const sentenceSplitterSchema = z
|
||||
.object({
|
||||
chunkSize: z
|
||||
.number({
|
||||
description: "The token chunk size for each chunk.",
|
||||
})
|
||||
.gt(0)
|
||||
.optional()
|
||||
.default(() => Settings.chunkSize ?? 1024),
|
||||
chunkOverlap: z
|
||||
.number({
|
||||
description: "The token overlap of each chunk when splitting.",
|
||||
})
|
||||
.gte(0)
|
||||
.optional()
|
||||
.default(200),
|
||||
separator: z
|
||||
.string({
|
||||
description: "Default separator for splitting into words",
|
||||
})
|
||||
.default(" "),
|
||||
paragraphSeparator: z
|
||||
.string({
|
||||
description: "Separator between paragraphs.",
|
||||
})
|
||||
.optional()
|
||||
.default("\n\n\n"),
|
||||
secondaryChunkingRegex: z
|
||||
.string({
|
||||
description: "Backup regex for splitting into sentences.",
|
||||
})
|
||||
.optional()
|
||||
.default("[^,.;。?!]+[,.;。?!]?"),
|
||||
})
|
||||
.refine(
|
||||
(data) => data.chunkOverlap < data.chunkSize,
|
||||
"Chunk overlap must be less than chunk size.",
|
||||
);
|
||||
|
||||
export const sentenceWindowNodeParserSchema = z.object({
|
||||
windowSize: z
|
||||
.number({
|
||||
description:
|
||||
"The number of sentences on each side of a sentence to capture.",
|
||||
})
|
||||
.gt(0)
|
||||
.default(3),
|
||||
windowMetadataKey: z
|
||||
.string({
|
||||
description: "The metadata key to store the sentence window under.",
|
||||
})
|
||||
.default("window"),
|
||||
originalTextMetadataKey: z
|
||||
.string({
|
||||
description: "The metadata key to store the original sentence in.",
|
||||
})
|
||||
.default("originalText"),
|
||||
});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { AsyncLocalStorage, randomUUID } from "@llamaindex/env";
|
||||
import { getCallbackManager } from "../global/settings/callback-manager";
|
||||
import { Settings } from "../global";
|
||||
import type { ChatResponse, ChatResponseChunk, LLM, LLMChat } from "../llms";
|
||||
|
||||
export function wrapLLMEvent<
|
||||
@@ -21,7 +21,7 @@ export function wrapLLMEvent<
|
||||
LLMChat<AdditionalChatOptions, AdditionalMessageOptions>["chat"]
|
||||
> {
|
||||
const id = randomUUID();
|
||||
getCallbackManager().dispatchEvent("llm-start", {
|
||||
Settings.callbackManager.dispatchEvent("llm-start", {
|
||||
id,
|
||||
messages: params[0].messages,
|
||||
});
|
||||
@@ -55,7 +55,7 @@ export function wrapLLMEvent<
|
||||
...chunk.options,
|
||||
};
|
||||
}
|
||||
getCallbackManager().dispatchEvent("llm-stream", {
|
||||
Settings.callbackManager.dispatchEvent("llm-stream", {
|
||||
id,
|
||||
chunk,
|
||||
});
|
||||
@@ -63,14 +63,14 @@ export function wrapLLMEvent<
|
||||
yield chunk;
|
||||
}
|
||||
snapshot(() => {
|
||||
getCallbackManager().dispatchEvent("llm-end", {
|
||||
Settings.callbackManager.dispatchEvent("llm-end", {
|
||||
id,
|
||||
response: finalResponse,
|
||||
});
|
||||
});
|
||||
};
|
||||
} else {
|
||||
getCallbackManager().dispatchEvent("llm-end", {
|
||||
Settings.callbackManager.dispatchEvent("llm-end", {
|
||||
id,
|
||||
response,
|
||||
});
|
||||
|
||||
+10
-10
@@ -1,5 +1,5 @@
|
||||
import { MarkdownNodeParser } from "@llamaindex/core/node-parser";
|
||||
import { Document, MetadataMode } from "@llamaindex/core/schema";
|
||||
import { MarkdownNodeParser } from "llamaindex/nodeParsers/index";
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
describe("MarkdownNodeParser", () => {
|
||||
@@ -19,8 +19,8 @@ Header 2 content
|
||||
]);
|
||||
|
||||
expect(splits.length).toBe(2);
|
||||
expect(splits[0].metadata).toEqual({ "Header 1": "Main Header" });
|
||||
expect(splits[1].metadata).toEqual({ "Header 1": "Header 2" });
|
||||
expect(splits[0].metadata).toEqual({ Header_1: "Main Header" });
|
||||
expect(splits[1].metadata).toEqual({ Header_1: "Header 2" });
|
||||
expect(splits[0].getContent(MetadataMode.NONE)).toStrictEqual(
|
||||
"Main Header\n\nHeader 1 content",
|
||||
);
|
||||
@@ -89,16 +89,16 @@ Content
|
||||
}),
|
||||
]);
|
||||
expect(splits.length).toBe(4);
|
||||
expect(splits[0].metadata).toEqual({ "Header 1": "Main Header" });
|
||||
expect(splits[0].metadata).toEqual({ Header_1: "Main Header" });
|
||||
expect(splits[1].metadata).toEqual({
|
||||
"Header 1": "Main Header",
|
||||
"Header 2": "Sub-header",
|
||||
Header_1: "Main Header",
|
||||
Header_2: "Sub-header",
|
||||
});
|
||||
expect(splits[2].metadata).toEqual({
|
||||
"Header 1": "Main Header",
|
||||
"Header 2": "Sub-header",
|
||||
"Header 3": "Sub-sub header",
|
||||
Header_1: "Main Header",
|
||||
Header_2: "Sub-header",
|
||||
Header_3: "Sub-sub header",
|
||||
});
|
||||
expect(splits[3].metadata).toEqual({ "Header 1": "New title" });
|
||||
expect(splits[3].metadata).toEqual({ Header_1: "New title" });
|
||||
});
|
||||
});
|
||||
+17
-5
@@ -1,12 +1,13 @@
|
||||
import { SentenceSplitter } from "@llamaindex/core/node-parser";
|
||||
import { Document } from "@llamaindex/core/schema";
|
||||
import { SimpleNodeParser } from "llamaindex/nodeParsers/index";
|
||||
import { tokenizers } from "@llamaindex/env";
|
||||
import { beforeEach, describe, expect, test } from "vitest";
|
||||
|
||||
describe("SimpleNodeParser", () => {
|
||||
let simpleNodeParser: SimpleNodeParser;
|
||||
describe("SentenceSplitter", () => {
|
||||
let sentenceSplitter: SentenceSplitter;
|
||||
|
||||
beforeEach(() => {
|
||||
simpleNodeParser = new SimpleNodeParser({
|
||||
sentenceSplitter = new SentenceSplitter({
|
||||
chunkSize: 1024,
|
||||
chunkOverlap: 20,
|
||||
});
|
||||
@@ -19,7 +20,7 @@ describe("SimpleNodeParser", () => {
|
||||
excludedLlmMetadataKeys: ["animals"],
|
||||
excludedEmbedMetadataKeys: ["animals"],
|
||||
});
|
||||
const result = simpleNodeParser.getNodesFromDocuments([doc]);
|
||||
const result = sentenceSplitter.getNodesFromDocuments([doc]);
|
||||
expect(result.length).toEqual(1);
|
||||
const node = result[0];
|
||||
// check not the same object
|
||||
@@ -37,4 +38,15 @@ describe("SimpleNodeParser", () => {
|
||||
// check relationship
|
||||
expect(node.sourceNode?.nodeId).toBe(doc.id_);
|
||||
});
|
||||
|
||||
test("split long text", async () => {
|
||||
const longSentence = "is ".repeat(9000) + ".";
|
||||
const document = new Document({ text: longSentence, id_: "1" });
|
||||
const result = sentenceSplitter.getNodesFromDocuments([document]);
|
||||
expect(result.length).toEqual(9);
|
||||
result.forEach((node) => {
|
||||
const { length } = tokenizers.tokenizer().encode(node.text);
|
||||
expect(length).toBeLessThanOrEqual(1024);
|
||||
});
|
||||
});
|
||||
});
|
||||
+5
-6
@@ -1,8 +1,5 @@
|
||||
import { SentenceWindowNodeParser } from "@llamaindex/core/node-parser";
|
||||
import { Document, MetadataMode } from "@llamaindex/core/schema";
|
||||
import {
|
||||
DEFAULT_WINDOW_METADATA_KEY,
|
||||
SentenceWindowNodeParser,
|
||||
} from "llamaindex/nodeParsers/index";
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
describe("Tests for the SentenceWindowNodeParser class", () => {
|
||||
@@ -11,7 +8,7 @@ describe("Tests for the SentenceWindowNodeParser class", () => {
|
||||
expect(sentenceWindowNodeParser).toBeDefined();
|
||||
});
|
||||
test("testing the getNodesFromDocuments method", () => {
|
||||
const sentenceWindowNodeParser = SentenceWindowNodeParser.fromDefaults({
|
||||
const sentenceWindowNodeParser = new SentenceWindowNodeParser({
|
||||
windowSize: 1,
|
||||
});
|
||||
const doc = new Document({ text: "Hello. Cat Mouse. Dog." });
|
||||
@@ -25,7 +22,9 @@ describe("Tests for the SentenceWindowNodeParser class", () => {
|
||||
"Dog.",
|
||||
]);
|
||||
expect(
|
||||
resultingNodes.map((n) => n.metadata[DEFAULT_WINDOW_METADATA_KEY]),
|
||||
resultingNodes.map(
|
||||
(n) => n.metadata[SentenceWindowNodeParser.DEFAULT_WINDOW_METADATA_KEY],
|
||||
),
|
||||
).toEqual([
|
||||
"Hello. Cat Mouse.",
|
||||
"Hello. Cat Mouse. Dog.",
|
||||
+15
-14
@@ -1,7 +1,4 @@
|
||||
import {
|
||||
SentenceSplitter,
|
||||
cjkSentenceTokenizer,
|
||||
} from "llamaindex/TextSplitter";
|
||||
import { SentenceSplitter } from "@llamaindex/core/node-parser";
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
describe("SentenceSplitter", () => {
|
||||
@@ -10,14 +7,16 @@ describe("SentenceSplitter", () => {
|
||||
expect(sentenceSplitter).toBeDefined();
|
||||
});
|
||||
|
||||
test("chunk size should less than chunk", async () => {});
|
||||
|
||||
test("splits paragraphs w/o effective chunk size", () => {
|
||||
const sentenceSplitter = new SentenceSplitter({
|
||||
paragraphSeparator: "\n\n\n",
|
||||
chunkSize: 9,
|
||||
chunkOverlap: 0,
|
||||
});
|
||||
// generate the same line as above but correct syntax errors
|
||||
const splits = sentenceSplitter.getParagraphSplits(
|
||||
const splits = sentenceSplitter.splitText(
|
||||
"This is a paragraph.\n\n\nThis is another paragraph.",
|
||||
undefined,
|
||||
);
|
||||
expect(splits).toEqual([
|
||||
"This is a paragraph.",
|
||||
@@ -30,9 +29,8 @@ describe("SentenceSplitter", () => {
|
||||
paragraphSeparator: "\n",
|
||||
});
|
||||
// generate the same line as above but correct syntax errors
|
||||
const splits = sentenceSplitter.getParagraphSplits(
|
||||
const splits = sentenceSplitter.splitText(
|
||||
"This is a paragraph.\nThis is another paragraph.",
|
||||
1000,
|
||||
);
|
||||
expect(splits).toEqual([
|
||||
"This is a paragraph.\nThis is another paragraph.",
|
||||
@@ -40,10 +38,12 @@ describe("SentenceSplitter", () => {
|
||||
});
|
||||
|
||||
test("splits sentences", () => {
|
||||
const sentenceSplitter = new SentenceSplitter();
|
||||
const splits = sentenceSplitter.getSentenceSplits(
|
||||
const sentenceSplitter = new SentenceSplitter({
|
||||
chunkSize: 9,
|
||||
chunkOverlap: 0,
|
||||
});
|
||||
const splits = sentenceSplitter.splitText(
|
||||
"This is a sentence. This is another sentence.",
|
||||
undefined,
|
||||
);
|
||||
expect(splits).toEqual([
|
||||
"This is a sentence.",
|
||||
@@ -89,9 +89,10 @@ describe("SentenceSplitter", () => {
|
||||
|
||||
test("splits cjk", () => {
|
||||
const sentenceSplitter = new SentenceSplitter({
|
||||
chunkSize: 12,
|
||||
chunkSize: 30,
|
||||
chunkOverlap: 0,
|
||||
chunkingTokenizerFn: cjkSentenceTokenizer,
|
||||
secondaryChunkingRegex:
|
||||
'.*?([﹒﹔﹖﹗.;。!?]["’”」』]{0,2}|:(?=["‘“「『]{1,2}|$))',
|
||||
});
|
||||
|
||||
const splits = sentenceSplitter.splitText(
|
||||
@@ -1,5 +1,37 @@
|
||||
# @llamaindex/experimental
|
||||
|
||||
## 0.0.60
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [086b940]
|
||||
- Updated dependencies [5d5716b]
|
||||
- Updated dependencies [91d02a4]
|
||||
- Updated dependencies [fb6db45]
|
||||
- llamaindex@0.5.10
|
||||
|
||||
## 0.0.59
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [15962b3]
|
||||
- llamaindex@0.5.9
|
||||
|
||||
## 0.0.58
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [3d5ba08]
|
||||
- Updated dependencies [d917cdc]
|
||||
- llamaindex@0.5.8
|
||||
|
||||
## 0.0.57
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [ec59acd]
|
||||
- llamaindex@0.5.7
|
||||
|
||||
## 0.0.56
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@llamaindex/experimental",
|
||||
"description": "Experimental package for LlamaIndexTS",
|
||||
"version": "0.0.56",
|
||||
"version": "0.0.60",
|
||||
"type": "module",
|
||||
"types": "dist/type/index.d.ts",
|
||||
"main": "dist/cjs/index.js",
|
||||
|
||||
@@ -1,5 +1,43 @@
|
||||
# llamaindex
|
||||
|
||||
## 0.5.10
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 086b940: feat: add DeepSeek LLM
|
||||
- 5d5716b: feat: add a reader for JSON data
|
||||
- 91d02a4: feat: support transform component callable
|
||||
- fb6db45: feat: add pageSeparator params to LlamaParseReader
|
||||
- Updated dependencies [91d02a4]
|
||||
- @llamaindex/core@0.1.5
|
||||
|
||||
## 0.5.9
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 15962b3: feat: node parser refactor
|
||||
|
||||
Align the text splitter logic with Python; it has almost the same logic as Python; Zod checks for input and better error messages and event system.
|
||||
|
||||
This change will not be considered a breaking change since it doesn't have a significant output difference from the last version,
|
||||
but some edge cases will change, like the page separator and parameter for the constructor.
|
||||
|
||||
- Updated dependencies [15962b3]
|
||||
- @llamaindex/core@0.1.4
|
||||
|
||||
## 0.5.8
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 3d5ba08: fix: update user agent in AssemblyAI
|
||||
- d917cdc: Add azure interpreter tool to tool factory
|
||||
|
||||
## 0.5.7
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- ec59acd: fix: bundling issue with pnpm
|
||||
|
||||
## 0.5.6
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -1,5 +1,37 @@
|
||||
# @llamaindex/cloudflare-worker-agent-test
|
||||
|
||||
## 0.0.44
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [086b940]
|
||||
- Updated dependencies [5d5716b]
|
||||
- Updated dependencies [91d02a4]
|
||||
- Updated dependencies [fb6db45]
|
||||
- llamaindex@0.5.10
|
||||
|
||||
## 0.0.43
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [15962b3]
|
||||
- llamaindex@0.5.9
|
||||
|
||||
## 0.0.42
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [3d5ba08]
|
||||
- Updated dependencies [d917cdc]
|
||||
- llamaindex@0.5.8
|
||||
|
||||
## 0.0.41
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [ec59acd]
|
||||
- llamaindex@0.5.7
|
||||
|
||||
## 0.0.40
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@llamaindex/cloudflare-worker-agent-test",
|
||||
"version": "0.0.40",
|
||||
"version": "0.0.44",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
|
||||
@@ -1,5 +1,37 @@
|
||||
# @llamaindex/next-agent-test
|
||||
|
||||
## 0.1.44
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [086b940]
|
||||
- Updated dependencies [5d5716b]
|
||||
- Updated dependencies [91d02a4]
|
||||
- Updated dependencies [fb6db45]
|
||||
- llamaindex@0.5.10
|
||||
|
||||
## 0.1.43
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [15962b3]
|
||||
- llamaindex@0.5.9
|
||||
|
||||
## 0.1.42
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [3d5ba08]
|
||||
- Updated dependencies [d917cdc]
|
||||
- llamaindex@0.5.8
|
||||
|
||||
## 0.1.41
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [ec59acd]
|
||||
- llamaindex@0.5.7
|
||||
|
||||
## 0.1.40
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@llamaindex/next-agent-test",
|
||||
"version": "0.1.40",
|
||||
"version": "0.1.44",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
|
||||
@@ -1,5 +1,37 @@
|
||||
# test-edge-runtime
|
||||
|
||||
## 0.1.43
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [086b940]
|
||||
- Updated dependencies [5d5716b]
|
||||
- Updated dependencies [91d02a4]
|
||||
- Updated dependencies [fb6db45]
|
||||
- llamaindex@0.5.10
|
||||
|
||||
## 0.1.42
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [15962b3]
|
||||
- llamaindex@0.5.9
|
||||
|
||||
## 0.1.41
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [3d5ba08]
|
||||
- Updated dependencies [d917cdc]
|
||||
- llamaindex@0.5.8
|
||||
|
||||
## 0.1.40
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [ec59acd]
|
||||
- llamaindex@0.5.7
|
||||
|
||||
## 0.1.39
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@llamaindex/nextjs-edge-runtime-test",
|
||||
"version": "0.1.39",
|
||||
"version": "0.1.43",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
|
||||
@@ -1,5 +1,37 @@
|
||||
# @llamaindex/next-node-runtime
|
||||
|
||||
## 0.0.25
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [086b940]
|
||||
- Updated dependencies [5d5716b]
|
||||
- Updated dependencies [91d02a4]
|
||||
- Updated dependencies [fb6db45]
|
||||
- llamaindex@0.5.10
|
||||
|
||||
## 0.0.24
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [15962b3]
|
||||
- llamaindex@0.5.9
|
||||
|
||||
## 0.0.23
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [3d5ba08]
|
||||
- Updated dependencies [d917cdc]
|
||||
- llamaindex@0.5.8
|
||||
|
||||
## 0.0.22
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [ec59acd]
|
||||
- llamaindex@0.5.7
|
||||
|
||||
## 0.0.21
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@llamaindex/next-node-runtime-test",
|
||||
"version": "0.0.21",
|
||||
"version": "0.0.25",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
|
||||
@@ -1,5 +1,37 @@
|
||||
# @llamaindex/waku-query-engine-test
|
||||
|
||||
## 0.0.44
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [086b940]
|
||||
- Updated dependencies [5d5716b]
|
||||
- Updated dependencies [91d02a4]
|
||||
- Updated dependencies [fb6db45]
|
||||
- llamaindex@0.5.10
|
||||
|
||||
## 0.0.43
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [15962b3]
|
||||
- llamaindex@0.5.9
|
||||
|
||||
## 0.0.42
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [3d5ba08]
|
||||
- Updated dependencies [d917cdc]
|
||||
- llamaindex@0.5.8
|
||||
|
||||
## 0.0.41
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [ec59acd]
|
||||
- llamaindex@0.5.7
|
||||
|
||||
## 0.0.40
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@llamaindex/waku-query-engine-test",
|
||||
"version": "0.0.40",
|
||||
"version": "0.0.44",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
|
||||
@@ -1,15 +1,26 @@
|
||||
import { TransformComponent } from "@llamaindex/core/schema";
|
||||
import {
|
||||
BaseEmbedding,
|
||||
BaseNode,
|
||||
SimilarityType,
|
||||
type BaseEmbedding,
|
||||
type EmbeddingInfo,
|
||||
type MessageContentDetail,
|
||||
} from "llamaindex";
|
||||
|
||||
export class OpenAIEmbedding implements BaseEmbedding {
|
||||
export class OpenAIEmbedding
|
||||
extends TransformComponent
|
||||
implements BaseEmbedding
|
||||
{
|
||||
embedInfo?: EmbeddingInfo | undefined;
|
||||
embedBatchSize = 512;
|
||||
|
||||
constructor() {
|
||||
super(async (nodes: BaseNode[], _options?: any): Promise<BaseNode[]> => {
|
||||
nodes.forEach((node) => (node.embedding = [0]));
|
||||
return nodes;
|
||||
});
|
||||
}
|
||||
|
||||
async getQueryEmbedding(query: MessageContentDetail) {
|
||||
return [0];
|
||||
}
|
||||
@@ -34,11 +45,6 @@ export class OpenAIEmbedding implements BaseEmbedding {
|
||||
return 1;
|
||||
}
|
||||
|
||||
async transform(nodes: BaseNode[], _options?: any): Promise<BaseNode[]> {
|
||||
nodes.forEach((node) => (node.embedding = [0]));
|
||||
return nodes;
|
||||
}
|
||||
|
||||
truncateMaxTokens(input: string[]): string[] {
|
||||
return input;
|
||||
}
|
||||
|
||||
@@ -7,8 +7,8 @@ import {
|
||||
OpenAI,
|
||||
OpenAIAgent,
|
||||
QueryEngineTool,
|
||||
SentenceSplitter,
|
||||
Settings,
|
||||
SimpleNodeParser,
|
||||
SimpleToolNodeMapping,
|
||||
SubQuestionQueryEngine,
|
||||
SummaryIndex,
|
||||
@@ -124,7 +124,7 @@ await test("agent with object retriever", async (t) => {
|
||||
const alexInfoText = await readFile(alexInfoPath, "utf-8");
|
||||
const alexDocument = new Document({ text: alexInfoText, id_: alexInfoPath });
|
||||
|
||||
const nodes = new SimpleNodeParser({
|
||||
const nodes = new SentenceSplitter({
|
||||
chunkSize: 200,
|
||||
chunkOverlap: 20,
|
||||
}).getNodesFromDocuments([alexDocument]);
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
"options": {
|
||||
"toolCall": [
|
||||
{
|
||||
"id": "call_sH6QfjsymHW7JFl68j8AY6xg",
|
||||
"id": "call_8kF02T5eJKwUL5hCGF8upWgn",
|
||||
"name": "Weather",
|
||||
"input": "{\"location\":\"San Francisco\"}"
|
||||
}
|
||||
@@ -30,13 +30,13 @@
|
||||
}
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "35 degrees and sunny in San Francisco",
|
||||
"role": "user",
|
||||
"options": {
|
||||
"toolResult": {
|
||||
"result": "35 degrees and sunny in San Francisco",
|
||||
"isError": false,
|
||||
"id": "call_sH6QfjsymHW7JFl68j8AY6xg"
|
||||
"id": "call_8kF02T5eJKwUL5hCGF8upWgn"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -64,7 +64,7 @@
|
||||
"options": {
|
||||
"toolCall": [
|
||||
{
|
||||
"id": "call_V7zs8cyDT5FqJhjwBqcCydgA",
|
||||
"id": "call_xsgmMFgliEDiOmZuLaBjUiXE",
|
||||
"name": "unique_id",
|
||||
"input": "{\"firstName\":\"Alex\",\"lastName\":\"Yang\"}"
|
||||
}
|
||||
@@ -72,13 +72,13 @@
|
||||
}
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "123456789",
|
||||
"role": "user",
|
||||
"options": {
|
||||
"toolResult": {
|
||||
"result": "123456789",
|
||||
"isError": false,
|
||||
"id": "call_V7zs8cyDT5FqJhjwBqcCydgA"
|
||||
"id": "call_xsgmMFgliEDiOmZuLaBjUiXE"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -106,7 +106,7 @@
|
||||
"options": {
|
||||
"toolCall": [
|
||||
{
|
||||
"id": "call_BrlGGU6GDGWr0hrwXt9qZKyt",
|
||||
"id": "call_OTMrLMikpT37PLm6KOIG5LCF",
|
||||
"name": "sumNumbers",
|
||||
"input": "{\"a\":1,\"b\":1}"
|
||||
}
|
||||
@@ -114,13 +114,13 @@
|
||||
}
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "2",
|
||||
"role": "user",
|
||||
"options": {
|
||||
"toolResult": {
|
||||
"result": "2",
|
||||
"isError": false,
|
||||
"id": "call_BrlGGU6GDGWr0hrwXt9qZKyt"
|
||||
"id": "call_OTMrLMikpT37PLm6KOIG5LCF"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -138,7 +138,7 @@
|
||||
"options": {
|
||||
"toolCall": [
|
||||
{
|
||||
"id": "call_sH6QfjsymHW7JFl68j8AY6xg",
|
||||
"id": "call_8kF02T5eJKwUL5hCGF8upWgn",
|
||||
"name": "Weather",
|
||||
"input": "{\"location\":\"San Francisco\"}"
|
||||
}
|
||||
@@ -168,7 +168,7 @@
|
||||
"options": {
|
||||
"toolCall": [
|
||||
{
|
||||
"id": "call_V7zs8cyDT5FqJhjwBqcCydgA",
|
||||
"id": "call_xsgmMFgliEDiOmZuLaBjUiXE",
|
||||
"name": "unique_id",
|
||||
"input": "{\"firstName\":\"Alex\",\"lastName\":\"Yang\"}"
|
||||
}
|
||||
@@ -198,7 +198,7 @@
|
||||
"options": {
|
||||
"toolCall": [
|
||||
{
|
||||
"id": "call_BrlGGU6GDGWr0hrwXt9qZKyt",
|
||||
"id": "call_OTMrLMikpT37PLm6KOIG5LCF",
|
||||
"name": "sumNumbers",
|
||||
"input": "{\"a\":1,\"b\":1}"
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
"toolCall": [
|
||||
{
|
||||
"name": "divideNumbers",
|
||||
"id": "call_V4daSdWk9QeYeSMKLBisNbSf",
|
||||
"id": "call_XgB0tixgYDhGXXSgdY19XDmt",
|
||||
"input": {
|
||||
"a": 16,
|
||||
"b": 2
|
||||
@@ -31,7 +31,7 @@
|
||||
},
|
||||
{
|
||||
"name": "sumNumbers",
|
||||
"id": "call_n2OlBxlaoeMIMVeU9DeDfiPX",
|
||||
"id": "call_nXP1Rc85Ntdv5XcI6FBWmB6d",
|
||||
"input": "{\"a\": 8, \"b\": 20}"
|
||||
}
|
||||
]
|
||||
@@ -44,7 +44,7 @@
|
||||
"toolResult": {
|
||||
"result": "8",
|
||||
"isError": false,
|
||||
"id": "call_V4daSdWk9QeYeSMKLBisNbSf"
|
||||
"id": "call_XgB0tixgYDhGXXSgdY19XDmt"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -55,7 +55,7 @@
|
||||
"toolResult": {
|
||||
"result": "28",
|
||||
"isError": false,
|
||||
"id": "call_n2OlBxlaoeMIMVeU9DeDfiPX"
|
||||
"id": "call_nXP1Rc85Ntdv5XcI6FBWmB6d"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -74,7 +74,7 @@
|
||||
"toolCall": [
|
||||
{
|
||||
"name": "sumNumbers",
|
||||
"id": "call_n2OlBxlaoeMIMVeU9DeDfiPX",
|
||||
"id": "call_nXP1Rc85Ntdv5XcI6FBWmB6d",
|
||||
"input": "{\"a\": 8, \"b\": 20}"
|
||||
}
|
||||
]
|
||||
@@ -87,7 +87,7 @@
|
||||
"response": {
|
||||
"raw": null,
|
||||
"message": {
|
||||
"content": "The result of dividing 16 by 2 is 8. When you add 20 to 8, the total is 28.",
|
||||
"content": "After dividing 16 by 2, we get 8. Adding 20 to 8 gives us 28.",
|
||||
"role": "assistant",
|
||||
"options": {}
|
||||
}
|
||||
@@ -103,7 +103,7 @@
|
||||
"toolCall": [
|
||||
{
|
||||
"name": "divideNumbers",
|
||||
"id": "call_V4daSdWk9QeYeSMKLBisNbSf",
|
||||
"id": "call_XgB0tixgYDhGXXSgdY19XDmt",
|
||||
"input": "{\"a\": 16, \"b\": 2}"
|
||||
}
|
||||
]
|
||||
@@ -119,7 +119,7 @@
|
||||
"toolCall": [
|
||||
{
|
||||
"name": "divideNumbers",
|
||||
"id": "call_V4daSdWk9QeYeSMKLBisNbSf",
|
||||
"id": "call_XgB0tixgYDhGXXSgdY19XDmt",
|
||||
"input": "{\"a\": 16, \"b\": 2}"
|
||||
}
|
||||
]
|
||||
@@ -135,7 +135,7 @@
|
||||
"toolCall": [
|
||||
{
|
||||
"name": "divideNumbers",
|
||||
"id": "call_V4daSdWk9QeYeSMKLBisNbSf",
|
||||
"id": "call_XgB0tixgYDhGXXSgdY19XDmt",
|
||||
"input": "{\"a\": 16, \"b\": 2}"
|
||||
}
|
||||
]
|
||||
@@ -151,7 +151,7 @@
|
||||
"toolCall": [
|
||||
{
|
||||
"name": "divideNumbers",
|
||||
"id": "call_V4daSdWk9QeYeSMKLBisNbSf",
|
||||
"id": "call_XgB0tixgYDhGXXSgdY19XDmt",
|
||||
"input": "{\"a\": 16, \"b\": 2}"
|
||||
}
|
||||
]
|
||||
@@ -167,7 +167,7 @@
|
||||
"toolCall": [
|
||||
{
|
||||
"name": "divideNumbers",
|
||||
"id": "call_V4daSdWk9QeYeSMKLBisNbSf",
|
||||
"id": "call_XgB0tixgYDhGXXSgdY19XDmt",
|
||||
"input": "{\"a\": 16, \"b\": 2}"
|
||||
}
|
||||
]
|
||||
@@ -183,7 +183,7 @@
|
||||
"toolCall": [
|
||||
{
|
||||
"name": "divideNumbers",
|
||||
"id": "call_V4daSdWk9QeYeSMKLBisNbSf",
|
||||
"id": "call_XgB0tixgYDhGXXSgdY19XDmt",
|
||||
"input": {
|
||||
"a": 16,
|
||||
"b": 2
|
||||
@@ -202,7 +202,7 @@
|
||||
"toolCall": [
|
||||
{
|
||||
"name": "sumNumbers",
|
||||
"id": "call_n2OlBxlaoeMIMVeU9DeDfiPX",
|
||||
"id": "call_nXP1Rc85Ntdv5XcI6FBWmB6d",
|
||||
"input": "{\"a\": 8, \"b\": 20}"
|
||||
}
|
||||
]
|
||||
@@ -218,7 +218,7 @@
|
||||
"toolCall": [
|
||||
{
|
||||
"name": "sumNumbers",
|
||||
"id": "call_n2OlBxlaoeMIMVeU9DeDfiPX",
|
||||
"id": "call_nXP1Rc85Ntdv5XcI6FBWmB6d",
|
||||
"input": "{\"a\": 8, \"b\": 20}"
|
||||
}
|
||||
]
|
||||
@@ -234,7 +234,7 @@
|
||||
"toolCall": [
|
||||
{
|
||||
"name": "sumNumbers",
|
||||
"id": "call_n2OlBxlaoeMIMVeU9DeDfiPX",
|
||||
"id": "call_nXP1Rc85Ntdv5XcI6FBWmB6d",
|
||||
"input": "{\"a\": 8, \"b\": 20}"
|
||||
}
|
||||
]
|
||||
@@ -250,7 +250,7 @@
|
||||
"toolCall": [
|
||||
{
|
||||
"name": "sumNumbers",
|
||||
"id": "call_n2OlBxlaoeMIMVeU9DeDfiPX",
|
||||
"id": "call_nXP1Rc85Ntdv5XcI6FBWmB6d",
|
||||
"input": "{\"a\": 8, \"b\": 20}"
|
||||
}
|
||||
]
|
||||
@@ -263,23 +263,7 @@
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": "The"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": " result"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": " of"
|
||||
"delta": "After"
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -335,7 +319,23 @@
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": " is"
|
||||
"delta": ","
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": " we"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": " get"
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -367,23 +367,7 @@
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": " When"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": " you"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": " add"
|
||||
"delta": " Adding"
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -431,7 +415,7 @@
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": ","
|
||||
"delta": " gives"
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -439,23 +423,7 @@
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": " the"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": " total"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": " is"
|
||||
"delta": " us"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
"options": {
|
||||
"toolCall": [
|
||||
{
|
||||
"id": "call_uERMumWlJLTO2GW93X6C2W3N",
|
||||
"id": "call_FNnPEPNeSDmdDj7b5x4LIxBG",
|
||||
"name": "get_weather",
|
||||
"input": "{\"location\":\"San Francisco\"}"
|
||||
}
|
||||
@@ -30,8 +30,8 @@
|
||||
}
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "{\n location: San Francisco,\n temperature: 72,\n weather: cloudy,\n rain_prediction: 0.89\n}",
|
||||
"role": "user",
|
||||
"options": {
|
||||
"toolResult": {
|
||||
"result": {
|
||||
@@ -41,7 +41,7 @@
|
||||
"rain_prediction": 0.89
|
||||
},
|
||||
"isError": false,
|
||||
"id": "call_uERMumWlJLTO2GW93X6C2W3N"
|
||||
"id": "call_FNnPEPNeSDmdDj7b5x4LIxBG"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -59,7 +59,7 @@
|
||||
"options": {
|
||||
"toolCall": [
|
||||
{
|
||||
"id": "call_uERMumWlJLTO2GW93X6C2W3N",
|
||||
"id": "call_FNnPEPNeSDmdDj7b5x4LIxBG",
|
||||
"name": "get_weather",
|
||||
"input": "{\"location\":\"San Francisco\"}"
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
"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:",
|
||||
"content": "Context information is below.\n---------------------\nAlex is a male.\nWhat'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"
|
||||
}
|
||||
]
|
||||
@@ -26,7 +26,7 @@
|
||||
"id": "PRESERVE_2",
|
||||
"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: Brazil\nAnswer:",
|
||||
"content": "Context information is below.\n---------------------\nAlex is a male.\nWhat's very important, Alex is not in the Brazil.\n---------------------\nGiven the context information and not prior knowledge, answer the query.\nQuery: Brazil\nAnswer:",
|
||||
"role": "user"
|
||||
}
|
||||
]
|
||||
@@ -48,12 +48,12 @@
|
||||
"options": {
|
||||
"toolCall": [
|
||||
{
|
||||
"id": "call_vv1XW3xv4j2us5sZOtzCU2lL",
|
||||
"id": "call_xkMkcEJYa2vVFUpg1Ng3UZTK",
|
||||
"name": "summary_tool",
|
||||
"input": "{\"query\": \"Alex\"}"
|
||||
},
|
||||
{
|
||||
"id": "call_V36LMHbwUJkEa20A3GoA4wIr",
|
||||
"id": "call_BYhP9Coo4NIBJDFaEKRA5qSl",
|
||||
"name": "summary_tool",
|
||||
"input": "{\"query\": \"Brazil\"}"
|
||||
}
|
||||
@@ -61,24 +61,24 @@
|
||||
}
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Alex is not in Brazil.",
|
||||
"role": "user",
|
||||
"options": {
|
||||
"toolResult": {
|
||||
"result": "Alex is not in Brazil.",
|
||||
"isError": false,
|
||||
"id": "call_vv1XW3xv4j2us5sZOtzCU2lL"
|
||||
"id": "call_xkMkcEJYa2vVFUpg1Ng3UZTK"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Alex is not in Brazil.",
|
||||
"role": "user",
|
||||
"options": {
|
||||
"toolResult": {
|
||||
"result": "Alex is not in Brazil.",
|
||||
"isError": false,
|
||||
"id": "call_V36LMHbwUJkEa20A3GoA4wIr"
|
||||
"id": "call_BYhP9Coo4NIBJDFaEKRA5qSl"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -96,12 +96,12 @@
|
||||
"options": {
|
||||
"toolCall": [
|
||||
{
|
||||
"id": "call_vv1XW3xv4j2us5sZOtzCU2lL",
|
||||
"id": "call_xkMkcEJYa2vVFUpg1Ng3UZTK",
|
||||
"name": "summary_tool",
|
||||
"input": "{\"query\": \"Alex\"}"
|
||||
},
|
||||
{
|
||||
"id": "call_V36LMHbwUJkEa20A3GoA4wIr",
|
||||
"id": "call_BYhP9Coo4NIBJDFaEKRA5qSl",
|
||||
"name": "summary_tool",
|
||||
"input": "{\"query\": \"Brazil\"}"
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user has not asked a question that requires using any of the available tools. They have simply requested that I respond with the word \"Yes\".\n</thinking>\n\nYes"
|
||||
"text": "<thinking>\nThe user has simply asked me to respond with the word \"Yes\". This is a very straightforward request that does not require the use of any tools. I have all the information I need to directly provide the response the user has requested.\n</thinking>\n\nYes"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
@@ -43,7 +43,7 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user has not asked a question that requires using any of the available tools. They have simply requested that I respond with the word \"Yes\".\n</thinking>\n\nYes"
|
||||
"text": "<thinking>\nThe user has simply asked me to respond with the word \"Yes\". This is a very straightforward request that does not require the use of any tools. I have all the information I need to directly provide the response the user has requested.\n</thinking>\n\nYes"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
@@ -57,7 +57,7 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user has not asked a question that requires using any of the available tools. They have simply requested that I respond with the word \"No\".\n</thinking>\n\nNo"
|
||||
"text": "<thinking>\nThe user has now asked me to respond with the word \"No\" instead of \"Yes\". Once again, this is a very simple and direct request. No additional information or tool usage is needed. I can immediately provide the response the user has requested by simply replying with the word \"No\".\n</thinking>\n\nNo"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
@@ -80,7 +80,7 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user has not asked a question that requires using any of the available tools. They have simply requested that I respond with the word \"Yes\".\n</thinking>\n\nYes"
|
||||
"text": "<thinking>\nThe user has simply asked me to respond with the word \"Yes\". This is a very straightforward request that does not require the use of any tools. I have all the information I need to directly provide the response the user has requested.\n</thinking>\n\nYes"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
@@ -94,7 +94,7 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user has not asked a question that requires using any of the available tools. They have simply requested that I respond with the word \"No\".\n</thinking>\n\nNo"
|
||||
"text": "<thinking>\nThe user has now asked me to respond with the word \"No\" instead of \"Yes\". Once again, this is a very simple and direct request. No additional information or tool usage is needed. I can immediately provide the response the user has requested by simply replying with the word \"No\".\n</thinking>\n\nNo"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
@@ -108,7 +108,7 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user has not asked a question that requires using any of the available tools. They have simply requested that I respond with the word \"Maybe\".\n</thinking>\n\nMaybe"
|
||||
"text": "<thinking>\nThe user has made another simple request, this time asking me to respond with the word \"Maybe\". Just like the previous requests for \"Yes\" and \"No\", I have all the necessary information to fulfill this request without needing to use any tools or gather additional details. I can provide the requested response by replying with only the word \"Maybe\".\n</thinking>\n\nMaybe"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
@@ -131,7 +131,7 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user has not asked a question that requires using any of the available tools. They have simply requested that I respond with the word \"Yes\".\n</thinking>\n\nYes"
|
||||
"text": "<thinking>\nThe user has simply asked me to respond with the word \"Yes\". This is a very straightforward request that does not require the use of any tools. I have all the information I need to directly provide the response the user has requested.\n</thinking>\n\nYes"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
@@ -145,7 +145,7 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user has not asked a question that requires using any of the available tools. They have simply requested that I respond with the word \"No\".\n</thinking>\n\nNo"
|
||||
"text": "<thinking>\nThe user has now asked me to respond with the word \"No\" instead of \"Yes\". Once again, this is a very simple and direct request. No additional information or tool usage is needed. I can immediately provide the response the user has requested by simply replying with the word \"No\".\n</thinking>\n\nNo"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
@@ -159,7 +159,7 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user has not asked a question that requires using any of the available tools. They have simply requested that I respond with the word \"Maybe\".\n</thinking>\n\nMaybe"
|
||||
"text": "<thinking>\nThe user has made another simple request, this time asking me to respond with the word \"Maybe\". Just like the previous requests for \"Yes\" and \"No\", I have all the necessary information to fulfill this request without needing to use any tools or gather additional details. I can provide the requested response by replying with only the word \"Maybe\".\n</thinking>\n\nMaybe"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
@@ -173,14 +173,14 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user has asked for the weather in a specific city, San Francisco. The relevant tool to answer this is the getWeather function.\n\nLooking at the required parameters for getWeather:\ncity (string): The user directly provided the city \"San Francisco\"\n\nSince the required \"city\" parameter has been provided, we can proceed with the getWeather function call.\n</thinking>"
|
||||
"text": "<thinking>\nThe user has asked for the current weather in San Francisco. To answer this, I will need to use the getWeather tool.\n\nLooking at the parameters for getWeather, I see it requires a single parameter:\n- city (string): The city to get the weather for \n\nThe user has directly provided the value for the city parameter in their request - they want the weather for San Francisco.\n\nI have all the required information to make the getWeather tool call, so I will proceed with calling the tool with \"San Francisco\" as the city parameter value.\n</thinking>"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
"options": {
|
||||
"toolCall": [
|
||||
{
|
||||
"id": "toolu_017MxwaxaLYkmt4dpP5HKzFe",
|
||||
"id": "toolu_01Q5tWdx8CTrqUaQty8C1PD5",
|
||||
"name": "getWeather",
|
||||
"input": {
|
||||
"city": "San Francisco"
|
||||
@@ -196,7 +196,7 @@
|
||||
"toolResult": {
|
||||
"result": "The weather in San Francisco is 72 degrees",
|
||||
"isError": false,
|
||||
"id": "toolu_017MxwaxaLYkmt4dpP5HKzFe"
|
||||
"id": "toolu_01Q5tWdx8CTrqUaQty8C1PD5"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -213,7 +213,7 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user has not asked a question that requires using any of the available tools. They have simply requested that I respond with the word \"Yes\".\n</thinking>\n\nYes"
|
||||
"text": "<thinking>\nThe user has simply asked me to respond with the word \"Yes\". This is a very straightforward request that does not require the use of any tools. I have all the information I need to directly provide the response the user has requested.\n</thinking>\n\nYes"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
@@ -227,7 +227,7 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user has not asked a question that requires using any of the available tools. They have simply requested that I respond with the word \"No\".\n</thinking>\n\nNo"
|
||||
"text": "<thinking>\nThe user has now asked me to respond with the word \"No\" instead of \"Yes\". Once again, this is a very simple and direct request. No additional information or tool usage is needed. I can immediately provide the response the user has requested by simply replying with the word \"No\".\n</thinking>\n\nNo"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
@@ -241,7 +241,7 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user has not asked a question that requires using any of the available tools. They have simply requested that I respond with the word \"Maybe\".\n</thinking>\n\nMaybe"
|
||||
"text": "<thinking>\nThe user has made another simple request, this time asking me to respond with the word \"Maybe\". Just like the previous requests for \"Yes\" and \"No\", I have all the necessary information to fulfill this request without needing to use any tools or gather additional details. I can provide the requested response by replying with only the word \"Maybe\".\n</thinking>\n\nMaybe"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
@@ -255,14 +255,14 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user has asked for the weather in a specific city, San Francisco. The relevant tool to answer this is the getWeather function.\n\nLooking at the required parameters for getWeather:\ncity (string): The user directly provided the city \"San Francisco\"\n\nSince the required \"city\" parameter has been provided, we can proceed with the getWeather function call.\n</thinking>"
|
||||
"text": "<thinking>\nThe user has asked for the current weather in San Francisco. To answer this, I will need to use the getWeather tool.\n\nLooking at the parameters for getWeather, I see it requires a single parameter:\n- city (string): The city to get the weather for \n\nThe user has directly provided the value for the city parameter in their request - they want the weather for San Francisco.\n\nI have all the required information to make the getWeather tool call, so I will proceed with calling the tool with \"San Francisco\" as the city parameter value.\n</thinking>"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
"options": {
|
||||
"toolCall": [
|
||||
{
|
||||
"id": "toolu_017MxwaxaLYkmt4dpP5HKzFe",
|
||||
"id": "toolu_01Q5tWdx8CTrqUaQty8C1PD5",
|
||||
"name": "getWeather",
|
||||
"input": {
|
||||
"city": "San Francisco"
|
||||
@@ -278,7 +278,7 @@
|
||||
"toolResult": {
|
||||
"result": "The weather in San Francisco is 72 degrees",
|
||||
"isError": false,
|
||||
"id": "toolu_017MxwaxaLYkmt4dpP5HKzFe"
|
||||
"id": "toolu_01Q5tWdx8CTrqUaQty8C1PD5"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -286,7 +286,7 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "The current weather in San Francisco is 72 degrees."
|
||||
"text": "Based on the result from calling the getWeather tool, the current weather in San Francisco is 72 degrees."
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
@@ -309,7 +309,7 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user has not asked a question that requires using any of the available tools. They have simply requested that I respond with the word \"Yes\".\n</thinking>\n\nYes"
|
||||
"text": "<thinking>\nThe user has simply asked me to respond with the word \"Yes\". This is a very straightforward request that does not require the use of any tools. I have all the information I need to directly provide the response the user has requested.\n</thinking>\n\nYes"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
@@ -323,7 +323,7 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user has not asked a question that requires using any of the available tools. They have simply requested that I respond with the word \"No\".\n</thinking>\n\nNo"
|
||||
"text": "<thinking>\nThe user has now asked me to respond with the word \"No\" instead of \"Yes\". Once again, this is a very simple and direct request. No additional information or tool usage is needed. I can immediately provide the response the user has requested by simply replying with the word \"No\".\n</thinking>\n\nNo"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
@@ -337,7 +337,7 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user has not asked a question that requires using any of the available tools. They have simply requested that I respond with the word \"Maybe\".\n</thinking>\n\nMaybe"
|
||||
"text": "<thinking>\nThe user has made another simple request, this time asking me to respond with the word \"Maybe\". Just like the previous requests for \"Yes\" and \"No\", I have all the necessary information to fulfill this request without needing to use any tools or gather additional details. I can provide the requested response by replying with only the word \"Maybe\".\n</thinking>\n\nMaybe"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
@@ -351,14 +351,14 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user has asked for the weather in a specific city, San Francisco. The relevant tool to answer this is the getWeather function.\n\nLooking at the required parameters for getWeather:\ncity (string): The user directly provided the city \"San Francisco\"\n\nSince the required \"city\" parameter has been provided, we can proceed with the getWeather function call.\n</thinking>"
|
||||
"text": "<thinking>\nThe user has asked for the current weather in San Francisco. To answer this, I will need to use the getWeather tool.\n\nLooking at the parameters for getWeather, I see it requires a single parameter:\n- city (string): The city to get the weather for \n\nThe user has directly provided the value for the city parameter in their request - they want the weather for San Francisco.\n\nI have all the required information to make the getWeather tool call, so I will proceed with calling the tool with \"San Francisco\" as the city parameter value.\n</thinking>"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
"options": {
|
||||
"toolCall": [
|
||||
{
|
||||
"id": "toolu_017MxwaxaLYkmt4dpP5HKzFe",
|
||||
"id": "toolu_01Q5tWdx8CTrqUaQty8C1PD5",
|
||||
"name": "getWeather",
|
||||
"input": {
|
||||
"city": "San Francisco"
|
||||
@@ -374,7 +374,7 @@
|
||||
"toolResult": {
|
||||
"result": "The weather in San Francisco is 72 degrees",
|
||||
"isError": false,
|
||||
"id": "toolu_017MxwaxaLYkmt4dpP5HKzFe"
|
||||
"id": "toolu_01Q5tWdx8CTrqUaQty8C1PD5"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -382,7 +382,7 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "The current weather in San Francisco is 72 degrees."
|
||||
"text": "Based on the result from calling the getWeather tool, the current weather in San Francisco is 72 degrees."
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
@@ -396,14 +396,14 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user has asked for the weather in a specific city, Shanghai. The relevant tool to answer this is the getWeather function.\n\nLooking at the required parameters for getWeather:\ncity (string): The user directly provided the city \"Shanghai\"\n\nSince the required \"city\" parameter has been provided, we can proceed with the getWeather function call.\n</thinking>"
|
||||
"text": "<thinking>\nThe user has now asked for the current weather in Shanghai. This is very similar to the previous request for San Francisco's weather. I will once again need to use the getWeather tool to answer this.\n\nThe getWeather tool requires the following parameter:\n- city (string): The city to get the weather for\n\nThe user has provided the city they want the weather for directly in their request - in this case, the city is Shanghai.\n\nSince I have the value for the required city parameter, I can go ahead and call the getWeather tool, passing in \"Shanghai\" as the city.\n</thinking>"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
"options": {
|
||||
"toolCall": [
|
||||
{
|
||||
"id": "toolu_013ZnATGKhvPkt2jjxdFheDK",
|
||||
"id": "toolu_01HxDqJpm33QxDXAExTxm6zu",
|
||||
"name": "getWeather",
|
||||
"input": {
|
||||
"city": "Shanghai"
|
||||
@@ -419,7 +419,7 @@
|
||||
"toolResult": {
|
||||
"result": "The weather in Shanghai is 72 degrees",
|
||||
"isError": false,
|
||||
"id": "toolu_013ZnATGKhvPkt2jjxdFheDK"
|
||||
"id": "toolu_01HxDqJpm33QxDXAExTxm6zu"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -435,7 +435,7 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user has not asked a question that requires using any of the available tools. They have simply requested that I respond with the word \"Yes\".\n</thinking>\n\nYes"
|
||||
"text": "<thinking>\nThe user has simply asked me to respond with the word \"Yes\". This is a very straightforward request that does not require the use of any tools. I have all the information I need to directly provide the response the user has requested.\n</thinking>\n\nYes"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
@@ -451,7 +451,7 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user has not asked a question that requires using any of the available tools. They have simply requested that I respond with the word \"No\".\n</thinking>\n\nNo"
|
||||
"text": "<thinking>\nThe user has now asked me to respond with the word \"No\" instead of \"Yes\". Once again, this is a very simple and direct request. No additional information or tool usage is needed. I can immediately provide the response the user has requested by simply replying with the word \"No\".\n</thinking>\n\nNo"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
@@ -467,7 +467,7 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user has not asked a question that requires using any of the available tools. They have simply requested that I respond with the word \"Maybe\".\n</thinking>\n\nMaybe"
|
||||
"text": "<thinking>\nThe user has made another simple request, this time asking me to respond with the word \"Maybe\". Just like the previous requests for \"Yes\" and \"No\", I have all the necessary information to fulfill this request without needing to use any tools or gather additional details. I can provide the requested response by replying with only the word \"Maybe\".\n</thinking>\n\nMaybe"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
@@ -483,14 +483,14 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user has asked for the weather in a specific city, San Francisco. The relevant tool to answer this is the getWeather function.\n\nLooking at the required parameters for getWeather:\ncity (string): The user directly provided the city \"San Francisco\"\n\nSince the required \"city\" parameter has been provided, we can proceed with the getWeather function call.\n</thinking>"
|
||||
"text": "<thinking>\nThe user has asked for the current weather in San Francisco. To answer this, I will need to use the getWeather tool.\n\nLooking at the parameters for getWeather, I see it requires a single parameter:\n- city (string): The city to get the weather for \n\nThe user has directly provided the value for the city parameter in their request - they want the weather for San Francisco.\n\nI have all the required information to make the getWeather tool call, so I will proceed with calling the tool with \"San Francisco\" as the city parameter value.\n</thinking>"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
"options": {
|
||||
"toolCall": [
|
||||
{
|
||||
"id": "toolu_017MxwaxaLYkmt4dpP5HKzFe",
|
||||
"id": "toolu_01Q5tWdx8CTrqUaQty8C1PD5",
|
||||
"name": "getWeather",
|
||||
"input": {
|
||||
"city": "San Francisco"
|
||||
@@ -509,7 +509,7 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "The current weather in San Francisco is 72 degrees."
|
||||
"text": "Based on the result from calling the getWeather tool, the current weather in San Francisco is 72 degrees."
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
@@ -525,14 +525,14 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user has asked for the weather in a specific city, Shanghai. The relevant tool to answer this is the getWeather function.\n\nLooking at the required parameters for getWeather:\ncity (string): The user directly provided the city \"Shanghai\"\n\nSince the required \"city\" parameter has been provided, we can proceed with the getWeather function call.\n</thinking>"
|
||||
"text": "<thinking>\nThe user has now asked for the current weather in Shanghai. This is very similar to the previous request for San Francisco's weather. I will once again need to use the getWeather tool to answer this.\n\nThe getWeather tool requires the following parameter:\n- city (string): The city to get the weather for\n\nThe user has provided the city they want the weather for directly in their request - in this case, the city is Shanghai.\n\nSince I have the value for the required city parameter, I can go ahead and call the getWeather tool, passing in \"Shanghai\" as the city.\n</thinking>"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
"options": {
|
||||
"toolCall": [
|
||||
{
|
||||
"id": "toolu_013ZnATGKhvPkt2jjxdFheDK",
|
||||
"id": "toolu_01HxDqJpm33QxDXAExTxm6zu",
|
||||
"name": "getWeather",
|
||||
"input": {
|
||||
"city": "Shanghai"
|
||||
@@ -551,7 +551,7 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "The current weather in Shanghai is 72 degrees."
|
||||
"text": "The getWeather tool indicates that the current weather in Shanghai is 72 degrees."
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
|
||||
@@ -20,14 +20,14 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user has asked for the weather in a specific location, San Francisco. The Weather tool is the relevant function to answer this request, as it returns weather information for a given location.\n\nThe Weather tool requires a single parameter:\n- location (string, required): The user has directly provided the location as \"San Francisco\".\n\nSince the required location parameter has been provided, we have enough information to call the Weather tool.\n</thinking>"
|
||||
"text": "<thinking>\nThe Weather tool is relevant to answer this question, as it can provide weather information for a specified location.\n\nThe Weather tool requires a \"location\" parameter. The user has directly provided the location of \"San Francisco\" in their request.\n\nSince the required \"location\" parameter has been provided, we can proceed with calling the Weather tool to get the weather information for San Francisco. No other tools are needed.\n</thinking>"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
"options": {
|
||||
"toolCall": [
|
||||
{
|
||||
"id": "toolu_011YcKkPygw2woJZrVWRRMwH",
|
||||
"id": "toolu_01Y6KpbYCFw4XGtvyXEmeTrB",
|
||||
"name": "Weather",
|
||||
"input": {
|
||||
"location": "San Francisco"
|
||||
@@ -43,7 +43,7 @@
|
||||
"toolResult": {
|
||||
"result": "35 degrees and sunny in San Francisco",
|
||||
"isError": false,
|
||||
"id": "toolu_011YcKkPygw2woJZrVWRRMwH"
|
||||
"id": "toolu_01Y6KpbYCFw4XGtvyXEmeTrB"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -69,14 +69,14 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe unique_id function takes firstName and lastName as required parameters. The user has provided their first name (Alex) and last name (Yang) in the request, so we have all the necessary information to call the function.\n</thinking>"
|
||||
"text": "<thinking>\nThe unique_id tool looks relevant for answering this request, as it can provide a unique identifier for a user given their first and last name. \nThe tool requires two parameters:\n- firstName (string)\n- lastName (string)\nLooking at the user's request, they have provided both their first name (Alex) and last name (Yang). So we have all the required parameters to call the unique_id tool.\n</thinking>"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
"options": {
|
||||
"toolCall": [
|
||||
{
|
||||
"id": "toolu_012ZLUq5SWsghkXUjsEXsB1f",
|
||||
"id": "toolu_01Q7wYKoNtpGAphTbRSv51fE",
|
||||
"name": "unique_id",
|
||||
"input": {
|
||||
"firstName": "Alex",
|
||||
@@ -93,7 +93,7 @@
|
||||
"toolResult": {
|
||||
"result": "123456789",
|
||||
"isError": false,
|
||||
"id": "toolu_012ZLUq5SWsghkXUjsEXsB1f"
|
||||
"id": "toolu_01Q7wYKoNtpGAphTbRSv51fE"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -119,14 +119,14 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user is asking to sum the numbers 1 and 1. The relevant tool is the sumNumbers function, which takes two number parameters a and b.\nThe user has directly provided the values for the required parameters:\na = 1 \nb = 1\nSince all the required parameters are provided, we can proceed with calling the function.\n</thinking>"
|
||||
"text": "<thinking>\nThe user is asking to sum the numbers 1 and 1. The sumNumbers tool is directly relevant for this request.\n\nLooking at the required parameters for sumNumbers:\na (number): The user provided the value 1 for this\nb (number): The user also provided the value 1 for this\n\nSince the user has directly provided values for all the required parameters, we can proceed with calling the sumNumbers tool without needing any additional information from the user.\n</thinking>"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
"options": {
|
||||
"toolCall": [
|
||||
{
|
||||
"id": "toolu_01SQD2XkaXkDNLQ2xaFzmguG",
|
||||
"id": "toolu_01AxEUd1s1UmhPc6Y91LBSmw",
|
||||
"name": "sumNumbers",
|
||||
"input": {
|
||||
"a": 1,
|
||||
@@ -143,7 +143,7 @@
|
||||
"toolResult": {
|
||||
"result": "2",
|
||||
"isError": false,
|
||||
"id": "toolu_01SQD2XkaXkDNLQ2xaFzmguG"
|
||||
"id": "toolu_01AxEUd1s1UmhPc6Y91LBSmw"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -159,14 +159,14 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user has asked for the weather in a specific location, San Francisco. The Weather tool is the relevant function to answer this request, as it returns weather information for a given location.\n\nThe Weather tool requires a single parameter:\n- location (string, required): The user has directly provided the location as \"San Francisco\".\n\nSince the required location parameter has been provided, we have enough information to call the Weather tool.\n</thinking>"
|
||||
"text": "<thinking>\nThe Weather tool is relevant to answer this question, as it can provide weather information for a specified location.\n\nThe Weather tool requires a \"location\" parameter. The user has directly provided the location of \"San Francisco\" in their request.\n\nSince the required \"location\" parameter has been provided, we can proceed with calling the Weather tool to get the weather information for San Francisco. No other tools are needed.\n</thinking>"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
"options": {
|
||||
"toolCall": [
|
||||
{
|
||||
"id": "toolu_011YcKkPygw2woJZrVWRRMwH",
|
||||
"id": "toolu_01Y6KpbYCFw4XGtvyXEmeTrB",
|
||||
"name": "Weather",
|
||||
"input": {
|
||||
"location": "San Francisco"
|
||||
@@ -201,14 +201,14 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe unique_id function takes firstName and lastName as required parameters. The user has provided their first name (Alex) and last name (Yang) in the request, so we have all the necessary information to call the function.\n</thinking>"
|
||||
"text": "<thinking>\nThe unique_id tool looks relevant for answering this request, as it can provide a unique identifier for a user given their first and last name. \nThe tool requires two parameters:\n- firstName (string)\n- lastName (string)\nLooking at the user's request, they have provided both their first name (Alex) and last name (Yang). So we have all the required parameters to call the unique_id tool.\n</thinking>"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
"options": {
|
||||
"toolCall": [
|
||||
{
|
||||
"id": "toolu_012ZLUq5SWsghkXUjsEXsB1f",
|
||||
"id": "toolu_01Q7wYKoNtpGAphTbRSv51fE",
|
||||
"name": "unique_id",
|
||||
"input": {
|
||||
"firstName": "Alex",
|
||||
@@ -244,14 +244,14 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "<thinking>\nThe user is asking to sum the numbers 1 and 1. The relevant tool is the sumNumbers function, which takes two number parameters a and b.\nThe user has directly provided the values for the required parameters:\na = 1 \nb = 1\nSince all the required parameters are provided, we can proceed with calling the function.\n</thinking>"
|
||||
"text": "<thinking>\nThe user is asking to sum the numbers 1 and 1. The sumNumbers tool is directly relevant for this request.\n\nLooking at the required parameters for sumNumbers:\na (number): The user provided the value 1 for this\nb (number): The user also provided the value 1 for this\n\nSince the user has directly provided values for all the required parameters, we can proceed with calling the sumNumbers tool without needing any additional information from the user.\n</thinking>"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
"options": {
|
||||
"toolCall": [
|
||||
{
|
||||
"id": "toolu_01SQD2XkaXkDNLQ2xaFzmguG",
|
||||
"id": "toolu_01AxEUd1s1UmhPc6Y91LBSmw",
|
||||
"name": "sumNumbers",
|
||||
"input": {
|
||||
"a": 1,
|
||||
@@ -271,7 +271,7 @@
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "So 1 + 1 = 2."
|
||||
"text": "So 1 + 1 = 2"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
"options": {
|
||||
"toolCall": [
|
||||
{
|
||||
"id": "call_Xa2Kxa2zUE073mnougPWzRlh",
|
||||
"id": "call_UMsqyh51lvDjy2JvMKFoyai3",
|
||||
"name": "Weather",
|
||||
"input": "{\"location\":\"San Jose\"}"
|
||||
}
|
||||
@@ -30,13 +30,13 @@
|
||||
}
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "45 degrees and sunny in San Jose",
|
||||
"role": "user",
|
||||
"options": {
|
||||
"toolResult": {
|
||||
"result": "45 degrees and sunny in San Jose",
|
||||
"isError": false,
|
||||
"id": "call_Xa2Kxa2zUE073mnougPWzRlh"
|
||||
"id": "call_UMsqyh51lvDjy2JvMKFoyai3"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,7 @@
|
||||
"options": {
|
||||
"toolCall": [
|
||||
{
|
||||
"id": "call_Xa2Kxa2zUE073mnougPWzRlh",
|
||||
"id": "call_UMsqyh51lvDjy2JvMKFoyai3",
|
||||
"name": "Weather",
|
||||
"input": "{\"location\":\"San Jose\"}"
|
||||
}
|
||||
|
||||
@@ -49,7 +49,7 @@
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"delta": "Hello",
|
||||
"delta": "Hello! How can",
|
||||
"options": {}
|
||||
}
|
||||
},
|
||||
@@ -57,55 +57,7 @@
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"delta": "!",
|
||||
"options": {}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"delta": " How",
|
||||
"options": {}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"delta": " can",
|
||||
"options": {}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"delta": " I",
|
||||
"options": {}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"delta": " assist",
|
||||
"options": {}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"delta": " you",
|
||||
"options": {}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_1",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"delta": " today",
|
||||
"delta": " I assist you today",
|
||||
"options": {}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
"options": {
|
||||
"toolCall": [
|
||||
{
|
||||
"id": "call_1SlugFuJ7rhwsmXd5aRnJhPe",
|
||||
"id": "call_i3rlYaBlvhTf60phYJh8irvZ",
|
||||
"name": "getWeather",
|
||||
"input": "{\"city\":\"San Francisco\"}"
|
||||
}
|
||||
@@ -38,13 +38,13 @@
|
||||
}
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"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_1SlugFuJ7rhwsmXd5aRnJhPe"
|
||||
"id": "call_i3rlYaBlvhTf60phYJh8irvZ"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -62,7 +62,7 @@
|
||||
"options": {
|
||||
"toolCall": [
|
||||
{
|
||||
"id": "call_1SlugFuJ7rhwsmXd5aRnJhPe",
|
||||
"id": "call_i3rlYaBlvhTf60phYJh8irvZ",
|
||||
"name": "getWeather",
|
||||
"input": "{\"city\":\"San Francisco\"}"
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
"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:",
|
||||
"content": "Context information is below.\n---------------------\nBill Gates stole from Apple.\n Steve Jobs stole from Xerox.\n---------------------\nGiven the context information and not prior knowledge, answer the query.\nQuery: What idea did Bill Gates get?\nAnswer:",
|
||||
"role": "user"
|
||||
}
|
||||
]
|
||||
@@ -22,7 +22,7 @@
|
||||
"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:",
|
||||
"content": "Context information is below.\n---------------------\nSub question: What idea did Bill Gates get?\nResponse: Bill Gates got the idea from Apple.\n---------------------\nGiven the context information and not prior knowledge, answer the query.\nQuery: What did Bill Gates steal from?\nAnswer:",
|
||||
"role": "user"
|
||||
}
|
||||
]
|
||||
@@ -34,7 +34,7 @@
|
||||
"response": {
|
||||
"raw": null,
|
||||
"message": {
|
||||
"content": "```json\n[\n {\n \"subQuestion\": \"What is Bill Gates' idea\",\n \"toolName\": \"bill_gates_idea\"\n }\n]\n```",
|
||||
"content": "```json\n[\n {\n \"subQuestion\": \"What idea did Bill Gates get?\",\n \"toolName\": \"bill_gates_idea\"\n }\n]\n```",
|
||||
"role": "assistant",
|
||||
"options": {}
|
||||
}
|
||||
@@ -45,7 +45,7 @@
|
||||
"response": {
|
||||
"raw": null,
|
||||
"message": {
|
||||
"content": "Bill Gates' idea was to steal from Apple.",
|
||||
"content": "Bill Gates got the idea from Apple.",
|
||||
"role": "assistant",
|
||||
"options": {}
|
||||
}
|
||||
@@ -56,7 +56,7 @@
|
||||
"response": {
|
||||
"raw": null,
|
||||
"message": {
|
||||
"content": "Bill Gates stole from Apple.",
|
||||
"content": "Bill Gates stole the idea from Apple.",
|
||||
"role": "assistant",
|
||||
"options": {}
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@
|
||||
"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\"}",
|
||||
"content": "Thought: I need to use a tool to help me answer the question.\nAction: getWeather\nAction Input: {\"city\": \"San Francisco\"}",
|
||||
"role": "assistant",
|
||||
"options": {}
|
||||
}
|
||||
@@ -177,15 +177,7 @@
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": "."
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "PRESERVE_0",
|
||||
"chunk": {
|
||||
"raw": null,
|
||||
"options": {},
|
||||
"delta": " \n"
|
||||
"delta": ".\n"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
@@ -42,7 +42,7 @@ export async function mockLLMEvent(
|
||||
newLLMCompleteMockStorage.llmEventStart.push({
|
||||
...event.detail,
|
||||
// @ts-expect-error id is not UUID, but it is fine for testing
|
||||
id: idMap.get(event.detail.payload.id)!,
|
||||
id: idMap.get(event.detail.id)!,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ export async function mockLLMEvent(
|
||||
newLLMCompleteMockStorage.llmEventEnd.push({
|
||||
...event.detail,
|
||||
// @ts-expect-error id is not UUID, but it is fine for testing
|
||||
id: idMap.get(event.detail.payload.id)!,
|
||||
id: idMap.get(event.detail.id)!,
|
||||
response: {
|
||||
...event.detail.response,
|
||||
// hide raw object since it might too big
|
||||
@@ -63,7 +63,7 @@ export async function mockLLMEvent(
|
||||
newLLMCompleteMockStorage.llmEventStream.push({
|
||||
...event.detail,
|
||||
// @ts-expect-error id is not UUID, but it is fine for testing
|
||||
id: idMap.get(event.detail.payload.id)!,
|
||||
id: idMap.get(event.detail.id)!,
|
||||
chunk: {
|
||||
...event.detail.chunk,
|
||||
// hide raw object since it might too big
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "llamaindex",
|
||||
"version": "0.5.6",
|
||||
"version": "0.5.10",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"keywords": [
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { tokenizers, type Tokenizer } from "@llamaindex/env";
|
||||
import { SentenceSplitter } from "@llamaindex/core/node-parser";
|
||||
import { type Tokenizer, tokenizers } from "@llamaindex/env";
|
||||
import type { SimplePrompt } from "./Prompt.js";
|
||||
import { SentenceSplitter } from "./TextSplitter.js";
|
||||
import {
|
||||
DEFAULT_CHUNK_OVERLAP_RATIO,
|
||||
DEFAULT_CONTEXT_WINDOW,
|
||||
@@ -107,8 +107,7 @@ export class PromptHelper {
|
||||
throw new Error("Got 0 as available chunk size");
|
||||
}
|
||||
const chunkOverlap = this.chunkOverlapRatio * chunkSize;
|
||||
const textSplitter = new SentenceSplitter({ chunkSize, chunkOverlap });
|
||||
return textSplitter;
|
||||
return new SentenceSplitter({ chunkSize, chunkOverlap });
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import type { BaseEmbedding } from "@llamaindex/core/embeddings";
|
||||
import type { LLM } from "@llamaindex/core/llms";
|
||||
import {
|
||||
type NodeParser,
|
||||
SentenceSplitter,
|
||||
} from "@llamaindex/core/node-parser";
|
||||
import { PromptHelper } from "./PromptHelper.js";
|
||||
import { OpenAIEmbedding } from "./embeddings/OpenAIEmbedding.js";
|
||||
import { OpenAI } from "./llm/openai.js";
|
||||
import { SimpleNodeParser } from "./nodeParsers/SimpleNodeParser.js";
|
||||
import type { NodeParser } from "./nodeParsers/types.js";
|
||||
|
||||
/**
|
||||
* The ServiceContext is a collection of components that are used in different parts of the application.
|
||||
@@ -33,7 +35,7 @@ export function serviceContextFromDefaults(options?: ServiceContextOptions) {
|
||||
embedModel: options?.embedModel ?? new OpenAIEmbedding(),
|
||||
nodeParser:
|
||||
options?.nodeParser ??
|
||||
new SimpleNodeParser({
|
||||
new SentenceSplitter({
|
||||
chunkSize: options?.chunkSize,
|
||||
chunkOverlap: options?.chunkOverlap,
|
||||
}),
|
||||
|
||||
@@ -5,10 +5,13 @@ import {
|
||||
import { OpenAI } from "./llm/openai.js";
|
||||
|
||||
import { PromptHelper } from "./PromptHelper.js";
|
||||
import { SimpleNodeParser } from "./nodeParsers/SimpleNodeParser.js";
|
||||
|
||||
import type { BaseEmbedding } from "@llamaindex/core/embeddings";
|
||||
import type { LLM } from "@llamaindex/core/llms";
|
||||
import {
|
||||
type NodeParser,
|
||||
SentenceSplitter,
|
||||
} from "@llamaindex/core/node-parser";
|
||||
import { AsyncLocalStorage, getEnv } from "@llamaindex/env";
|
||||
import type { ServiceContext } from "./ServiceContext.js";
|
||||
import {
|
||||
@@ -16,7 +19,6 @@ import {
|
||||
setEmbeddedModel,
|
||||
withEmbeddedModel,
|
||||
} from "./internal/settings/EmbedModel.js";
|
||||
import type { NodeParser } from "./nodeParsers/types.js";
|
||||
|
||||
export type PromptConfig = {
|
||||
llm?: string;
|
||||
@@ -108,7 +110,7 @@ class GlobalSettings implements Config {
|
||||
|
||||
get nodeParser(): NodeParser {
|
||||
if (this.#nodeParser === null) {
|
||||
this.#nodeParser = new SimpleNodeParser({
|
||||
this.#nodeParser = new SentenceSplitter({
|
||||
chunkSize: this.chunkSize,
|
||||
chunkOverlap: this.chunkOverlap,
|
||||
});
|
||||
|
||||
@@ -1,309 +0,0 @@
|
||||
import { EOL, tokenizers, type Tokenizer } from "@llamaindex/env";
|
||||
// GitHub translated
|
||||
import { DEFAULT_CHUNK_OVERLAP, DEFAULT_CHUNK_SIZE } from "./constants.js";
|
||||
|
||||
class TextSplit {
|
||||
textChunk: string;
|
||||
numCharOverlap: number | undefined;
|
||||
|
||||
constructor(
|
||||
textChunk: string,
|
||||
numCharOverlap: number | undefined = undefined,
|
||||
) {
|
||||
this.textChunk = textChunk;
|
||||
this.numCharOverlap = numCharOverlap;
|
||||
}
|
||||
}
|
||||
|
||||
type SplitRep = { text: string; numTokens: number };
|
||||
|
||||
const defaultregex = /[.?!][\])'"`’”]*(?:\s|$)/g;
|
||||
export const defaultSentenceTokenizer = (text: string): string[] => {
|
||||
const slist = [];
|
||||
const iter = text.matchAll(defaultregex);
|
||||
let lastIdx = 0;
|
||||
for (const match of iter) {
|
||||
slist.push(text.slice(lastIdx, match.index! + 1));
|
||||
lastIdx = match.index! + 1;
|
||||
}
|
||||
slist.push(text.slice(lastIdx));
|
||||
return slist.filter((s) => s.length > 0);
|
||||
};
|
||||
|
||||
// Refs: https://github.com/fxsjy/jieba/issues/575#issuecomment-359637511
|
||||
const resentencesp =
|
||||
/([﹒﹔﹖﹗.;。!?]["’”」』]{0,2}|:(?=["‘“「『]{1,2}|$))/;
|
||||
/**
|
||||
* Tokenizes sentences. Suitable for Chinese, Japanese, and Korean. Use instead of `defaultSentenceTokenizer`.
|
||||
* @param text
|
||||
* @returns string[]
|
||||
*/
|
||||
export function cjkSentenceTokenizer(sentence: string): string[] {
|
||||
const slist = [];
|
||||
const parts = sentence.split(resentencesp);
|
||||
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const part = parts[i];
|
||||
if (resentencesp.test(part) && slist.length > 0) {
|
||||
slist[slist.length - 1] += part;
|
||||
} else if (part) {
|
||||
slist.push(part);
|
||||
}
|
||||
}
|
||||
|
||||
return slist.filter((s) => s.length > 0);
|
||||
}
|
||||
|
||||
export const defaultParagraphSeparator = EOL + EOL + EOL;
|
||||
|
||||
// In theory there's also Mac style \r only, but it's pre-OSX and I don't think
|
||||
// many documents will use it.
|
||||
|
||||
/**
|
||||
* SentenceSplitter is our default text splitter that supports splitting into sentences, paragraphs, or fixed length chunks with overlap.
|
||||
*
|
||||
* One of the advantages of SentenceSplitter is that even in the fixed length chunks it will try to keep sentences together.
|
||||
*/
|
||||
export class SentenceSplitter {
|
||||
public chunkSize: number;
|
||||
public chunkOverlap: number;
|
||||
|
||||
private tokenizer: Tokenizer;
|
||||
private paragraphSeparator: string;
|
||||
private chunkingTokenizerFn: (text: string) => string[];
|
||||
private splitLongSentences: boolean;
|
||||
|
||||
constructor(options?: {
|
||||
chunkSize?: number;
|
||||
chunkOverlap?: number;
|
||||
tokenizer?: Tokenizer;
|
||||
paragraphSeparator?: string;
|
||||
chunkingTokenizerFn?: (text: string) => string[];
|
||||
splitLongSentences?: boolean;
|
||||
}) {
|
||||
const {
|
||||
chunkSize = DEFAULT_CHUNK_SIZE,
|
||||
chunkOverlap = DEFAULT_CHUNK_OVERLAP,
|
||||
tokenizer = null,
|
||||
paragraphSeparator = defaultParagraphSeparator,
|
||||
chunkingTokenizerFn,
|
||||
splitLongSentences = false,
|
||||
} = options ?? {};
|
||||
|
||||
if (chunkOverlap > chunkSize) {
|
||||
throw new Error(
|
||||
`Got a larger chunk overlap (${chunkOverlap}) than chunk size (${chunkSize}), should be smaller.`,
|
||||
);
|
||||
}
|
||||
this.chunkSize = chunkSize;
|
||||
this.chunkOverlap = chunkOverlap;
|
||||
|
||||
this.tokenizer = tokenizer ?? tokenizers.tokenizer();
|
||||
|
||||
this.paragraphSeparator = paragraphSeparator;
|
||||
this.chunkingTokenizerFn = chunkingTokenizerFn ?? defaultSentenceTokenizer;
|
||||
this.splitLongSentences = splitLongSentences;
|
||||
}
|
||||
|
||||
private getEffectiveChunkSize(extraInfoStr?: string): number {
|
||||
// get "effective" chunk size by removing the metadata
|
||||
let effectiveChunkSize;
|
||||
if (extraInfoStr != undefined) {
|
||||
const numExtraTokens =
|
||||
this.tokenizer.encode(`${extraInfoStr}\n\n`).length + 1;
|
||||
effectiveChunkSize = this.chunkSize - numExtraTokens;
|
||||
if (effectiveChunkSize <= 0) {
|
||||
throw new Error(
|
||||
"Effective chunk size is non positive after considering extra_info",
|
||||
);
|
||||
}
|
||||
} else {
|
||||
effectiveChunkSize = this.chunkSize;
|
||||
}
|
||||
return effectiveChunkSize;
|
||||
}
|
||||
|
||||
getParagraphSplits(text: string, effectiveChunkSize?: number): string[] {
|
||||
// get paragraph splits
|
||||
const paragraphSplits: string[] = text.split(this.paragraphSeparator);
|
||||
let idx = 0;
|
||||
if (effectiveChunkSize == undefined) {
|
||||
return paragraphSplits;
|
||||
}
|
||||
|
||||
// merge paragraphs that are too small
|
||||
while (idx < paragraphSplits.length) {
|
||||
if (
|
||||
idx < paragraphSplits.length - 1 &&
|
||||
paragraphSplits[idx].length < effectiveChunkSize
|
||||
) {
|
||||
paragraphSplits[idx] = [
|
||||
paragraphSplits[idx],
|
||||
paragraphSplits[idx + 1],
|
||||
].join(this.paragraphSeparator);
|
||||
paragraphSplits.splice(idx + 1, 1);
|
||||
} else {
|
||||
idx += 1;
|
||||
}
|
||||
}
|
||||
return paragraphSplits;
|
||||
}
|
||||
|
||||
getSentenceSplits(text: string, effectiveChunkSize?: number): string[] {
|
||||
const paragraphSplits = this.getParagraphSplits(text, effectiveChunkSize);
|
||||
// Next we split the text using the chunk tokenizer fn/
|
||||
const splits = [];
|
||||
for (const parText of paragraphSplits) {
|
||||
const sentenceSplits = this.chunkingTokenizerFn(parText);
|
||||
|
||||
if (!sentenceSplits) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const sentence_split of sentenceSplits) {
|
||||
splits.push(sentence_split.trim());
|
||||
}
|
||||
}
|
||||
return splits;
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits sentences into chunks if necessary.
|
||||
*
|
||||
* This isn't great behavior because it can split down the middle of a
|
||||
* word or in non-English split down the middle of a Unicode codepoint
|
||||
* so the splitting is turned off by default. If you need it, please
|
||||
* set the splitLongSentences option to true.
|
||||
* @param sentenceSplits
|
||||
* @param effectiveChunkSize
|
||||
* @returns
|
||||
*/
|
||||
private processSentenceSplits(
|
||||
sentenceSplits: string[],
|
||||
effectiveChunkSize: number,
|
||||
): SplitRep[] {
|
||||
if (!this.splitLongSentences) {
|
||||
return sentenceSplits.map((split) => ({
|
||||
text: split,
|
||||
numTokens: this.tokenizer.encode(split).length,
|
||||
}));
|
||||
}
|
||||
|
||||
const newSplits: SplitRep[] = [];
|
||||
for (const split of sentenceSplits) {
|
||||
const splitTokens = this.tokenizer.encode(split);
|
||||
const splitLen = splitTokens.length;
|
||||
if (splitLen <= effectiveChunkSize) {
|
||||
newSplits.push({ text: split, numTokens: splitLen });
|
||||
} else {
|
||||
for (let i = 0; i < splitLen; i += effectiveChunkSize) {
|
||||
const cur_split = this.tokenizer.decode(
|
||||
splitTokens.slice(i, i + effectiveChunkSize),
|
||||
);
|
||||
newSplits.push({ text: cur_split, numTokens: effectiveChunkSize });
|
||||
}
|
||||
}
|
||||
}
|
||||
return newSplits;
|
||||
}
|
||||
|
||||
combineTextSplits(
|
||||
newSentenceSplits: SplitRep[],
|
||||
effectiveChunkSize: number,
|
||||
): TextSplit[] {
|
||||
// go through sentence splits, combine to chunks that are within the chunk size
|
||||
|
||||
// docs represents final list of text chunks
|
||||
const docs: TextSplit[] = [];
|
||||
// curChunkSentences represents the current list of sentence splits (that)
|
||||
// will be merged into a chunk
|
||||
let curChunkSentences: SplitRep[] = [];
|
||||
let curChunkTokens = 0;
|
||||
|
||||
for (let i = 0; i < newSentenceSplits.length; i++) {
|
||||
// if adding newSentenceSplits[i] to curDocBuffer would exceed effectiveChunkSize,
|
||||
// then we need to add the current curDocBuffer to docs
|
||||
if (
|
||||
curChunkTokens + newSentenceSplits[i].numTokens >
|
||||
effectiveChunkSize
|
||||
) {
|
||||
if (curChunkSentences.length > 0) {
|
||||
// push curent doc list to docs
|
||||
docs.push(
|
||||
new TextSplit(
|
||||
curChunkSentences
|
||||
.map((sentence) => sentence.text)
|
||||
.join(" ")
|
||||
.trim(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const lastChunkSentences = curChunkSentences;
|
||||
|
||||
// reset docs list
|
||||
curChunkTokens = 0;
|
||||
curChunkSentences = [];
|
||||
|
||||
// add the last sentences from the last chunk until we've hit the overlap
|
||||
// do it in reverse order
|
||||
for (let j = lastChunkSentences.length - 1; j >= 0; j--) {
|
||||
if (
|
||||
curChunkTokens + lastChunkSentences[j].numTokens >
|
||||
this.chunkOverlap
|
||||
) {
|
||||
break;
|
||||
}
|
||||
curChunkSentences.unshift(lastChunkSentences[j]);
|
||||
curChunkTokens += lastChunkSentences[j].numTokens + 1;
|
||||
}
|
||||
}
|
||||
|
||||
curChunkSentences.push(newSentenceSplits[i]);
|
||||
curChunkTokens += newSentenceSplits[i].numTokens + 1;
|
||||
}
|
||||
docs.push(
|
||||
new TextSplit(
|
||||
curChunkSentences
|
||||
.map((sentence) => sentence.text)
|
||||
.join(" ")
|
||||
.trim(),
|
||||
),
|
||||
);
|
||||
return docs;
|
||||
}
|
||||
|
||||
splitTextWithOverlaps(text: string, extraInfoStr?: string): TextSplit[] {
|
||||
// Split incoming text and return chunks with overlap size.
|
||||
// Has a preference for complete sentences, phrases, and minimal overlap.
|
||||
|
||||
// here is the typescript code (skip callback manager)
|
||||
if (text == "") {
|
||||
return [];
|
||||
}
|
||||
|
||||
const effectiveChunkSize = this.getEffectiveChunkSize(extraInfoStr);
|
||||
const sentenceSplits = this.getSentenceSplits(text, effectiveChunkSize);
|
||||
|
||||
// Check if any sentences exceed the chunk size. If they don't,
|
||||
// force split by tokenizer
|
||||
const newSentenceSplits = this.processSentenceSplits(
|
||||
sentenceSplits,
|
||||
effectiveChunkSize,
|
||||
);
|
||||
|
||||
// combine sentence splits into chunks of text that can then be returned
|
||||
const combinedTextSplits = this.combineTextSplits(
|
||||
newSentenceSplits,
|
||||
effectiveChunkSize,
|
||||
);
|
||||
|
||||
return combinedTextSplits;
|
||||
}
|
||||
|
||||
splitText(text: string, extraInfoStr?: string): string[] {
|
||||
const text_splits = this.splitTextWithOverlaps(text);
|
||||
const chunks = text_splits.map((text_split) => text_split.textChunk);
|
||||
return chunks;
|
||||
}
|
||||
}
|
||||
@@ -11,10 +11,10 @@ import type { CloudConstructorParams } from "./constants.js";
|
||||
import { getAppBaseUrl, initService } from "./utils.js";
|
||||
|
||||
import { PipelinesService, ProjectsService } from "@llamaindex/cloud/api";
|
||||
import { SentenceSplitter } from "@llamaindex/core/node-parser";
|
||||
import { getEnv } from "@llamaindex/env";
|
||||
import { Settings } from "../Settings.js";
|
||||
import { OpenAIEmbedding } from "../embeddings/OpenAIEmbedding.js";
|
||||
import { SimpleNodeParser } from "../nodeParsers/SimpleNodeParser.js";
|
||||
|
||||
export class LlamaCloudIndex {
|
||||
params: CloudConstructorParams;
|
||||
@@ -147,13 +147,13 @@ export class LlamaCloudIndex {
|
||||
static async fromDocuments(
|
||||
params: {
|
||||
documents: Document[];
|
||||
transformations?: TransformComponent<any>[];
|
||||
transformations?: TransformComponent[];
|
||||
verbose?: boolean;
|
||||
} & CloudConstructorParams,
|
||||
): Promise<LlamaCloudIndex> {
|
||||
initService(params);
|
||||
const defaultTransformations: TransformComponent<any>[] = [
|
||||
new SimpleNodeParser(),
|
||||
const defaultTransformations: TransformComponent[] = [
|
||||
new SentenceSplitter(),
|
||||
new OpenAIEmbedding({
|
||||
apiKey: getEnv("OPENAI_API_KEY"),
|
||||
}),
|
||||
|
||||
@@ -3,26 +3,26 @@ import type {
|
||||
PipelineCreate,
|
||||
PipelineType,
|
||||
} from "@llamaindex/cloud/api";
|
||||
import { SentenceSplitter } from "@llamaindex/core/node-parser";
|
||||
import { BaseNode, type TransformComponent } from "@llamaindex/core/schema";
|
||||
import { OpenAIEmbedding } from "../embeddings/OpenAIEmbedding.js";
|
||||
import { SimpleNodeParser } from "../nodeParsers/SimpleNodeParser.js";
|
||||
|
||||
export type GetPipelineCreateParams = {
|
||||
pipelineName: string;
|
||||
pipelineType: PipelineType;
|
||||
transformations?: TransformComponent<any>[];
|
||||
transformations?: TransformComponent[];
|
||||
inputNodes?: BaseNode[];
|
||||
};
|
||||
|
||||
function getTransformationConfig(
|
||||
transformation: TransformComponent<any>,
|
||||
transformation: TransformComponent,
|
||||
): ConfiguredTransformationItem {
|
||||
if (transformation instanceof SimpleNodeParser) {
|
||||
if (transformation instanceof SentenceSplitter) {
|
||||
return {
|
||||
configurable_transformation_type: "SENTENCE_AWARE_NODE_PARSER",
|
||||
component: {
|
||||
chunk_size: transformation.textSplitter.chunkSize, // TODO: set to public in SentenceSplitter
|
||||
chunk_overlap: transformation.textSplitter.chunkOverlap, // TODO: set to public in SentenceSplitter
|
||||
chunk_size: transformation.chunkSize, // TODO: set to public in SentenceSplitter
|
||||
chunk_overlap: transformation.chunkOverlap, // TODO: set to public in SentenceSplitter
|
||||
include_metadata: transformation.includeMetadata,
|
||||
include_prev_next_rel: transformation.includePrevNextRel,
|
||||
},
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import type { BaseNode, TransformComponent } from "@llamaindex/core/schema";
|
||||
import { MetadataMode, TextNode } from "@llamaindex/core/schema";
|
||||
import {
|
||||
BaseNode,
|
||||
MetadataMode,
|
||||
TextNode,
|
||||
TransformComponent,
|
||||
} from "@llamaindex/core/schema";
|
||||
import { defaultNodeTextTemplate } from "./prompts.js";
|
||||
|
||||
/*
|
||||
* Abstract class for all extractors.
|
||||
*/
|
||||
export abstract class BaseExtractor implements TransformComponent<any> {
|
||||
export abstract class BaseExtractor extends TransformComponent {
|
||||
isTextNodeOnly: boolean = true;
|
||||
showProgress: boolean = true;
|
||||
metadataMode: MetadataMode = MetadataMode.ALL;
|
||||
@@ -13,16 +17,18 @@ export abstract class BaseExtractor implements TransformComponent<any> {
|
||||
inPlace: boolean = true;
|
||||
numWorkers: number = 4;
|
||||
|
||||
abstract extract(nodes: BaseNode[]): Promise<Record<string, any>[]>;
|
||||
|
||||
async transform(nodes: BaseNode[], options?: any): Promise<BaseNode[]> {
|
||||
return this.processNodes(
|
||||
nodes,
|
||||
options?.excludedEmbedMetadataKeys,
|
||||
options?.excludedLlmMetadataKeys,
|
||||
);
|
||||
constructor() {
|
||||
super(async (nodes: BaseNode[], options?: any): Promise<BaseNode[]> => {
|
||||
return this.processNodes(
|
||||
nodes,
|
||||
options?.excludedEmbedMetadataKeys,
|
||||
options?.excludedLlmMetadataKeys,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
abstract extract(nodes: BaseNode[]): Promise<Record<string, any>[]>;
|
||||
|
||||
/**
|
||||
*
|
||||
* @param nodes Nodes to extract metadata from.
|
||||
|
||||
@@ -50,6 +50,5 @@ export * from "./ServiceContext.js";
|
||||
export { Settings } from "./Settings.js";
|
||||
export * from "./storage/StorageContext.js";
|
||||
export * from "./synthesizers/index.js";
|
||||
export * from "./TextSplitter.js";
|
||||
export * from "./tools/index.js";
|
||||
export * from "./types.js";
|
||||
|
||||
@@ -172,7 +172,7 @@ export class VectorStoreIndex extends BaseIndex<IndexDict> {
|
||||
const embedModel =
|
||||
this.embedModel ?? this.vectorStores[type as ModalityType]?.embedModel;
|
||||
if (embedModel && nodes) {
|
||||
await embedModel.transform(nodes, {
|
||||
await embedModel(nodes, {
|
||||
logProgress: options?.logProgress,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import { docToJson, jsonToDoc } from "../storage/docStore/utils.js";
|
||||
import { SimpleKVStore } from "../storage/kvStore/SimpleKVStore.js";
|
||||
import type { BaseKVStore } from "../storage/kvStore/types.js";
|
||||
|
||||
const transformToJSON = (obj: TransformComponent<any>) => {
|
||||
const transformToJSON = (obj: TransformComponent) => {
|
||||
const seen: any[] = [];
|
||||
|
||||
const replacer = (key: string, value: any) => {
|
||||
@@ -26,7 +26,7 @@ const transformToJSON = (obj: TransformComponent<any>) => {
|
||||
|
||||
export function getTransformationHash(
|
||||
nodes: BaseNode[],
|
||||
transform: TransformComponent<any>,
|
||||
transform: TransformComponent,
|
||||
) {
|
||||
const nodesStr: string = nodes
|
||||
.map((node) => node.getContent(MetadataMode.ALL))
|
||||
@@ -35,7 +35,7 @@ export function getTransformationHash(
|
||||
const transformString: string = transformToJSON(transform);
|
||||
|
||||
const hash = createSHA256();
|
||||
hash.update(nodesStr + transformString);
|
||||
hash.update(nodesStr + transformString + transform.id);
|
||||
return hash.digest();
|
||||
}
|
||||
|
||||
|
||||
@@ -26,12 +26,12 @@ type IngestionRunArgs = {
|
||||
type TransformRunArgs = {
|
||||
inPlace?: boolean;
|
||||
cache?: IngestionCache;
|
||||
docStoreStrategy?: TransformComponent<any>;
|
||||
docStoreStrategy?: TransformComponent;
|
||||
};
|
||||
|
||||
export async function runTransformations(
|
||||
nodesToRun: BaseNode[],
|
||||
transformations: TransformComponent<any>[],
|
||||
transformations: TransformComponent[],
|
||||
transformOptions: any = {},
|
||||
{ inPlace = true, cache, docStoreStrategy }: TransformRunArgs = {},
|
||||
): Promise<BaseNode[]> {
|
||||
@@ -40,7 +40,7 @@ export async function runTransformations(
|
||||
nodes = [...nodesToRun];
|
||||
}
|
||||
if (docStoreStrategy) {
|
||||
nodes = await docStoreStrategy.transform(nodes);
|
||||
nodes = await docStoreStrategy(nodes);
|
||||
}
|
||||
for (const transform of transformations) {
|
||||
if (cache) {
|
||||
@@ -49,18 +49,18 @@ export async function runTransformations(
|
||||
if (cachedNodes) {
|
||||
nodes = cachedNodes;
|
||||
} else {
|
||||
nodes = await transform.transform(nodes, transformOptions);
|
||||
nodes = await transform(nodes, transformOptions);
|
||||
await cache.put(hash, nodes);
|
||||
}
|
||||
} else {
|
||||
nodes = await transform.transform(nodes, transformOptions);
|
||||
nodes = await transform(nodes, transformOptions);
|
||||
}
|
||||
}
|
||||
return nodes;
|
||||
}
|
||||
|
||||
export class IngestionPipeline {
|
||||
transformations: TransformComponent<any>[] = [];
|
||||
transformations: TransformComponent[] = [];
|
||||
documents?: Document[];
|
||||
reader?: BaseReader;
|
||||
vectorStore?: VectorStore;
|
||||
@@ -70,7 +70,7 @@ export class IngestionPipeline {
|
||||
cache?: IngestionCache;
|
||||
disableCache: boolean = false;
|
||||
|
||||
private _docStoreStrategy?: TransformComponent<any>;
|
||||
private _docStoreStrategy?: TransformComponent;
|
||||
|
||||
constructor(init?: Partial<IngestionPipeline>) {
|
||||
Object.assign(this, init);
|
||||
|
||||
@@ -1,31 +1,30 @@
|
||||
import type { BaseNode, TransformComponent } from "@llamaindex/core/schema";
|
||||
import { BaseNode, TransformComponent } from "@llamaindex/core/schema";
|
||||
import type { BaseDocumentStore } from "../../storage/docStore/types.js";
|
||||
|
||||
/**
|
||||
* Handle doc store duplicates by checking all hashes.
|
||||
*/
|
||||
export class DuplicatesStrategy implements TransformComponent<any> {
|
||||
export class DuplicatesStrategy extends TransformComponent {
|
||||
private docStore: BaseDocumentStore;
|
||||
|
||||
constructor(docStore: BaseDocumentStore) {
|
||||
super(async (nodes: BaseNode[]): Promise<BaseNode[]> => {
|
||||
const hashes = await this.docStore.getAllDocumentHashes();
|
||||
const currentHashes = new Set<string>();
|
||||
const nodesToRun: BaseNode[] = [];
|
||||
|
||||
for (const node of nodes) {
|
||||
if (!(node.hash in hashes) && !currentHashes.has(node.hash)) {
|
||||
await this.docStore.setDocumentHash(node.id_, node.hash);
|
||||
nodesToRun.push(node);
|
||||
currentHashes.add(node.hash);
|
||||
}
|
||||
}
|
||||
|
||||
await this.docStore.addDocuments(nodesToRun, true);
|
||||
|
||||
return nodesToRun;
|
||||
});
|
||||
this.docStore = docStore;
|
||||
}
|
||||
|
||||
async transform(nodes: BaseNode[]): Promise<BaseNode[]> {
|
||||
const hashes = await this.docStore.getAllDocumentHashes();
|
||||
const currentHashes = new Set<string>();
|
||||
const nodesToRun: BaseNode[] = [];
|
||||
|
||||
for (const node of nodes) {
|
||||
if (!(node.hash in hashes) && !currentHashes.has(node.hash)) {
|
||||
await this.docStore.setDocumentHash(node.id_, node.hash);
|
||||
nodesToRun.push(node);
|
||||
currentHashes.add(node.hash);
|
||||
}
|
||||
}
|
||||
|
||||
await this.docStore.addDocuments(nodesToRun, true);
|
||||
|
||||
return nodesToRun;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { BaseNode, TransformComponent } from "@llamaindex/core/schema";
|
||||
import { BaseNode, TransformComponent } from "@llamaindex/core/schema";
|
||||
import type { BaseDocumentStore } from "../../storage/docStore/types.js";
|
||||
import type { VectorStore } from "../../storage/vectorStore/types.js";
|
||||
import { classify } from "./classify.js";
|
||||
@@ -7,43 +7,42 @@ import { classify } from "./classify.js";
|
||||
* Handle docstore upserts by checking hashes and ids.
|
||||
* Identify missing docs and delete them from docstore and vector store
|
||||
*/
|
||||
export class UpsertsAndDeleteStrategy implements TransformComponent<any> {
|
||||
export class UpsertsAndDeleteStrategy extends TransformComponent {
|
||||
protected docStore: BaseDocumentStore;
|
||||
protected vectorStores?: VectorStore[];
|
||||
|
||||
constructor(docStore: BaseDocumentStore, vectorStores?: VectorStore[]) {
|
||||
super(async (nodes: BaseNode[]): Promise<BaseNode[]> => {
|
||||
const { dedupedNodes, missingDocs, unusedDocs } = await classify(
|
||||
this.docStore,
|
||||
nodes,
|
||||
);
|
||||
|
||||
// remove unused docs
|
||||
for (const refDocId of unusedDocs) {
|
||||
await this.docStore.deleteRefDoc(refDocId, false);
|
||||
if (this.vectorStores) {
|
||||
for (const vectorStore of this.vectorStores) {
|
||||
await vectorStore.delete(refDocId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// remove missing docs
|
||||
for (const docId of missingDocs) {
|
||||
await this.docStore.deleteDocument(docId, true);
|
||||
if (this.vectorStores) {
|
||||
for (const vectorStore of this.vectorStores) {
|
||||
await vectorStore.delete(docId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await this.docStore.addDocuments(dedupedNodes, true);
|
||||
|
||||
return dedupedNodes;
|
||||
});
|
||||
this.docStore = docStore;
|
||||
this.vectorStores = vectorStores;
|
||||
}
|
||||
|
||||
async transform(nodes: BaseNode[]): Promise<BaseNode[]> {
|
||||
const { dedupedNodes, missingDocs, unusedDocs } = await classify(
|
||||
this.docStore,
|
||||
nodes,
|
||||
);
|
||||
|
||||
// remove unused docs
|
||||
for (const refDocId of unusedDocs) {
|
||||
await this.docStore.deleteRefDoc(refDocId, false);
|
||||
if (this.vectorStores) {
|
||||
for (const vectorStore of this.vectorStores) {
|
||||
await vectorStore.delete(refDocId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// remove missing docs
|
||||
for (const docId of missingDocs) {
|
||||
await this.docStore.deleteDocument(docId, true);
|
||||
if (this.vectorStores) {
|
||||
for (const vectorStore of this.vectorStores) {
|
||||
await vectorStore.delete(docId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await this.docStore.addDocuments(dedupedNodes, true);
|
||||
|
||||
return dedupedNodes;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { BaseNode, TransformComponent } from "@llamaindex/core/schema";
|
||||
import { BaseNode, TransformComponent } from "@llamaindex/core/schema";
|
||||
import type { BaseDocumentStore } from "../../storage/docStore/types.js";
|
||||
import type { VectorStore } from "../../storage/vectorStore/types.js";
|
||||
import { classify } from "./classify.js";
|
||||
@@ -6,28 +6,27 @@ import { classify } from "./classify.js";
|
||||
/**
|
||||
* Handles doc store upserts by checking hashes and ids.
|
||||
*/
|
||||
export class UpsertsStrategy implements TransformComponent<any> {
|
||||
export class UpsertsStrategy extends TransformComponent {
|
||||
protected docStore: BaseDocumentStore;
|
||||
protected vectorStores?: VectorStore[];
|
||||
|
||||
constructor(docStore: BaseDocumentStore, vectorStores?: VectorStore[]) {
|
||||
super(async (nodes: BaseNode[]): Promise<BaseNode[]> => {
|
||||
const { dedupedNodes, unusedDocs } = await classify(this.docStore, nodes);
|
||||
// remove unused docs
|
||||
for (const refDocId of unusedDocs) {
|
||||
await this.docStore.deleteRefDoc(refDocId, false);
|
||||
if (this.vectorStores) {
|
||||
for (const vectorStore of this.vectorStores) {
|
||||
await vectorStore.delete(refDocId);
|
||||
}
|
||||
}
|
||||
}
|
||||
// add non-duplicate docs
|
||||
await this.docStore.addDocuments(dedupedNodes, true);
|
||||
return dedupedNodes;
|
||||
});
|
||||
this.docStore = docStore;
|
||||
this.vectorStores = vectorStores;
|
||||
}
|
||||
|
||||
async transform(nodes: BaseNode[]): Promise<BaseNode[]> {
|
||||
const { dedupedNodes, unusedDocs } = await classify(this.docStore, nodes);
|
||||
// remove unused docs
|
||||
for (const refDocId of unusedDocs) {
|
||||
await this.docStore.deleteRefDoc(refDocId, false);
|
||||
if (this.vectorStores) {
|
||||
for (const vectorStore of this.vectorStores) {
|
||||
await vectorStore.delete(refDocId);
|
||||
}
|
||||
}
|
||||
}
|
||||
// add non-duplicate docs
|
||||
await this.docStore.addDocuments(dedupedNodes, true);
|
||||
return dedupedNodes;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { TransformComponent } from "@llamaindex/core/schema";
|
||||
import { TransformComponent } from "@llamaindex/core/schema";
|
||||
import type { BaseDocumentStore } from "../../storage/docStore/types.js";
|
||||
import type { VectorStore } from "../../storage/vectorStore/types.js";
|
||||
import { DuplicatesStrategy } from "./DuplicatesStrategy.js";
|
||||
@@ -19,9 +19,9 @@ export enum DocStoreStrategy {
|
||||
NONE = "none", // no-op strategy
|
||||
}
|
||||
|
||||
class NoOpStrategy implements TransformComponent<any> {
|
||||
async transform(nodes: any[]): Promise<any[]> {
|
||||
return nodes;
|
||||
class NoOpStrategy extends TransformComponent {
|
||||
constructor() {
|
||||
super(async (nodes) => nodes);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ export function createDocStoreStrategy(
|
||||
docStoreStrategy: DocStoreStrategy,
|
||||
docStore?: BaseDocumentStore,
|
||||
vectorStores: VectorStore[] = [],
|
||||
): TransformComponent<any> {
|
||||
): TransformComponent {
|
||||
if (docStoreStrategy === DocStoreStrategy.NONE) {
|
||||
return new NoOpStrategy();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { getEnv } from "@llamaindex/env";
|
||||
import { OpenAI } from "./openai.js";
|
||||
|
||||
export const DEEPSEEK_MODELS = {
|
||||
"deepseek-coder": { contextWindow: 128000 },
|
||||
"deepseek-chat": { contextWindow: 128000 },
|
||||
};
|
||||
|
||||
type DeepSeekModelName = keyof typeof DEEPSEEK_MODELS;
|
||||
const DEFAULT_MODEL: DeepSeekModelName = "deepseek-coder";
|
||||
|
||||
export class DeepSeekLLM extends OpenAI {
|
||||
constructor(init?: Partial<OpenAI> & { model?: DeepSeekModelName }) {
|
||||
const {
|
||||
apiKey = getEnv("DEEPSEEK_API_KEY"),
|
||||
additionalSessionOptions = {},
|
||||
model = DEFAULT_MODEL,
|
||||
...rest
|
||||
} = init ?? {};
|
||||
|
||||
if (!apiKey) {
|
||||
throw new Error("Set DeepSeek Key in DEEPSEEK_API_KEY env variable");
|
||||
}
|
||||
|
||||
additionalSessionOptions.baseURL =
|
||||
additionalSessionOptions.baseURL ?? "https://api.deepseek.com/v1";
|
||||
|
||||
super({
|
||||
apiKey,
|
||||
additionalSessionOptions,
|
||||
model,
|
||||
...rest,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -34,5 +34,6 @@ export {
|
||||
ReplicateSession,
|
||||
} from "./replicate_ai.js";
|
||||
|
||||
export { DeepSeekLLM } from "./deepseek.js";
|
||||
export { TogetherLLM } from "./together.js";
|
||||
export * from "./types.js";
|
||||
|
||||
@@ -32,6 +32,12 @@ export default function withLlamaIndex(config: any) {
|
||||
"@google-cloud/vertexai": false,
|
||||
"groq-sdk": false,
|
||||
};
|
||||
// Following lines will fix issues with onnxruntime-node when using pnpm
|
||||
// See: https://github.com/vercel/next.js/issues/43433
|
||||
webpackConfig.externals.push({
|
||||
"onnxruntime-node": "commonjs onnxruntime-node",
|
||||
sharp: "commonjs sharp",
|
||||
});
|
||||
return webpackConfig;
|
||||
};
|
||||
return config;
|
||||
|
||||
@@ -1,109 +0,0 @@
|
||||
import type { BaseNode, Metadata } from "@llamaindex/core/schema";
|
||||
import { MetadataMode, TextNode } from "@llamaindex/core/schema";
|
||||
import type { NodeParser } from "./types.js";
|
||||
|
||||
export class MarkdownNodeParser implements NodeParser {
|
||||
includeMetadata: boolean;
|
||||
includePrevNextRel: boolean;
|
||||
|
||||
constructor(init?: {
|
||||
includeMetadata?: boolean;
|
||||
includePrevNextRel?: boolean;
|
||||
}) {
|
||||
this.includeMetadata = init?.includeMetadata ?? true;
|
||||
this.includePrevNextRel = init?.includePrevNextRel ?? true;
|
||||
}
|
||||
|
||||
async transform(nodes: BaseNode[], _options?: any): Promise<BaseNode[]> {
|
||||
return this.getNodesFromDocuments(nodes);
|
||||
}
|
||||
|
||||
static fromDefaults(init?: {
|
||||
includeMetadata?: boolean;
|
||||
includePrevNextRel?: boolean;
|
||||
}): MarkdownNodeParser {
|
||||
return new MarkdownNodeParser(init);
|
||||
}
|
||||
|
||||
buildNodeFromSplit(
|
||||
textSplit: string,
|
||||
node: BaseNode<Metadata>,
|
||||
metadata: Metadata,
|
||||
): BaseNode<Metadata> {
|
||||
const newNode = new TextNode({
|
||||
text: textSplit,
|
||||
relationships: {
|
||||
PARENT: [
|
||||
{
|
||||
...node,
|
||||
nodeId: node.id_,
|
||||
},
|
||||
],
|
||||
},
|
||||
metadata: this.includeMetadata ? metadata : {},
|
||||
});
|
||||
return newNode;
|
||||
}
|
||||
|
||||
updateMetadata(
|
||||
headersMetadata: Metadata,
|
||||
newHeader: string,
|
||||
newHeaderLevel: number,
|
||||
): Metadata {
|
||||
const updatedHeaders: Metadata = {};
|
||||
for (let i = 1; i < newHeaderLevel; i++) {
|
||||
const key = `Header ${i}`;
|
||||
if (key in headersMetadata) {
|
||||
updatedHeaders[key] = headersMetadata[key];
|
||||
}
|
||||
}
|
||||
updatedHeaders[`Header ${newHeaderLevel}`] = newHeader;
|
||||
return updatedHeaders;
|
||||
}
|
||||
|
||||
getNodesFromNode(node: BaseNode<Metadata>): BaseNode<Metadata>[] {
|
||||
const text = node.getContent(MetadataMode.NONE);
|
||||
const markdownNodes: BaseNode<Metadata>[] = [];
|
||||
const lines = text.split("\n");
|
||||
let metadata: Metadata = {};
|
||||
let codeBlock = false;
|
||||
let currentSection = "";
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.startsWith("```")) {
|
||||
codeBlock = !codeBlock;
|
||||
}
|
||||
const headerMatch = line.match(/^(#+)\s(.*)/);
|
||||
if (headerMatch && !codeBlock) {
|
||||
if (currentSection !== "") {
|
||||
markdownNodes.push(
|
||||
this.buildNodeFromSplit(currentSection.trim(), node, metadata),
|
||||
);
|
||||
}
|
||||
metadata = this.updateMetadata(
|
||||
metadata,
|
||||
headerMatch[2],
|
||||
headerMatch[1].length,
|
||||
);
|
||||
currentSection = `${headerMatch[2]}\n`;
|
||||
} else {
|
||||
currentSection += line + "\n";
|
||||
}
|
||||
}
|
||||
|
||||
markdownNodes.push(
|
||||
this.buildNodeFromSplit(currentSection.trim(), node, metadata),
|
||||
);
|
||||
|
||||
return markdownNodes;
|
||||
}
|
||||
|
||||
getNodesFromDocuments(documents: BaseNode<Metadata>[]): BaseNode<Metadata>[] {
|
||||
let allNodes: BaseNode<Metadata>[] = [];
|
||||
for (const node of documents) {
|
||||
const nodes = this.getNodesFromNode(node);
|
||||
allNodes = allNodes.concat(nodes);
|
||||
}
|
||||
return allNodes;
|
||||
}
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
import type { BaseNode } from "@llamaindex/core/schema";
|
||||
import { SentenceSplitter } from "../TextSplitter.js";
|
||||
import type { NodeParser } from "./types.js";
|
||||
import { getNodesFromDocument } from "./utils.js";
|
||||
|
||||
export const DEFAULT_WINDOW_SIZE = 3;
|
||||
export const DEFAULT_WINDOW_METADATA_KEY = "window";
|
||||
export const DEFAULT_OG_TEXT_METADATA_KEY = "original_text";
|
||||
|
||||
export class SentenceWindowNodeParser implements NodeParser {
|
||||
/**
|
||||
* The text splitter to use.
|
||||
*/
|
||||
textSplitter: SentenceSplitter;
|
||||
/**
|
||||
* The number of sentences on each side of a sentence to capture.
|
||||
*/
|
||||
windowSize: number = DEFAULT_WINDOW_SIZE;
|
||||
/**
|
||||
* The metadata key to store the sentence window under.
|
||||
*/
|
||||
windowMetadataKey: string = DEFAULT_WINDOW_METADATA_KEY;
|
||||
/**
|
||||
* The metadata key to store the original sentence in.
|
||||
*/
|
||||
originalTextMetadataKey: string = DEFAULT_OG_TEXT_METADATA_KEY;
|
||||
/**
|
||||
* Whether to include metadata in the nodes.
|
||||
*/
|
||||
includeMetadata: boolean = true;
|
||||
/**
|
||||
* Whether to include previous and next relationships in the nodes.
|
||||
*/
|
||||
includePrevNextRel: boolean = true;
|
||||
|
||||
constructor(init?: Partial<SentenceWindowNodeParser>) {
|
||||
Object.assign(this, init);
|
||||
this.textSplitter = init?.textSplitter ?? new SentenceSplitter();
|
||||
}
|
||||
|
||||
static fromDefaults(
|
||||
init?: Partial<SentenceWindowNodeParser>,
|
||||
): SentenceWindowNodeParser {
|
||||
return new SentenceWindowNodeParser(init);
|
||||
}
|
||||
|
||||
async transform(nodes: BaseNode[], _options?: any): Promise<BaseNode[]> {
|
||||
return this.getNodesFromDocuments(nodes);
|
||||
}
|
||||
|
||||
getNodesFromDocuments(documents: BaseNode[]) {
|
||||
return documents
|
||||
.map((document) => this.buildWindowNodesFromDocument(document))
|
||||
.flat();
|
||||
}
|
||||
|
||||
protected buildWindowNodesFromDocument(doc: BaseNode): BaseNode[] {
|
||||
const nodes = getNodesFromDocument(
|
||||
doc,
|
||||
this.textSplitter.getSentenceSplits.bind(this.textSplitter),
|
||||
this.includeMetadata,
|
||||
this.includePrevNextRel,
|
||||
);
|
||||
|
||||
for (let i = 0; i < nodes.length; i++) {
|
||||
const node = nodes[i];
|
||||
const windowNodes = nodes.slice(
|
||||
Math.max(0, i - this.windowSize),
|
||||
Math.min(i + this.windowSize + 1, nodes.length),
|
||||
);
|
||||
|
||||
node.metadata[this.windowMetadataKey] = windowNodes
|
||||
.map((n) => n.getText())
|
||||
.join(" ");
|
||||
node.metadata[this.originalTextMetadataKey] = node.getText();
|
||||
|
||||
node.excludedEmbedMetadataKeys.push(
|
||||
this.windowMetadataKey,
|
||||
this.originalTextMetadataKey,
|
||||
);
|
||||
node.excludedLlmMetadataKeys.push(
|
||||
this.windowMetadataKey,
|
||||
this.originalTextMetadataKey,
|
||||
);
|
||||
}
|
||||
|
||||
return nodes;
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
import type { BaseNode } from "@llamaindex/core/schema";
|
||||
import { SentenceSplitter } from "../TextSplitter.js";
|
||||
import { DEFAULT_CHUNK_OVERLAP, DEFAULT_CHUNK_SIZE } from "../constants.js";
|
||||
import type { NodeParser } from "./types.js";
|
||||
import { getNodesFromDocument } from "./utils.js";
|
||||
|
||||
/**
|
||||
* SimpleNodeParser is the default NodeParser. It splits documents into TextNodes using a splitter, by default SentenceSplitter
|
||||
*/
|
||||
export class SimpleNodeParser implements NodeParser {
|
||||
/**
|
||||
* The text splitter to use.
|
||||
*/
|
||||
textSplitter: SentenceSplitter;
|
||||
/**
|
||||
* Whether to include metadata in the nodes.
|
||||
*/
|
||||
includeMetadata: boolean;
|
||||
/**
|
||||
* Whether to include previous and next relationships in the nodes.
|
||||
*/
|
||||
includePrevNextRel: boolean;
|
||||
|
||||
constructor(init?: {
|
||||
textSplitter?: SentenceSplitter;
|
||||
includeMetadata?: boolean;
|
||||
includePrevNextRel?: boolean;
|
||||
chunkSize?: number;
|
||||
chunkOverlap?: number;
|
||||
splitLongSentences?: boolean;
|
||||
}) {
|
||||
this.textSplitter =
|
||||
init?.textSplitter ??
|
||||
new SentenceSplitter({
|
||||
chunkSize: init?.chunkSize ?? DEFAULT_CHUNK_SIZE,
|
||||
chunkOverlap: init?.chunkOverlap ?? DEFAULT_CHUNK_OVERLAP,
|
||||
splitLongSentences: init?.splitLongSentences ?? false,
|
||||
});
|
||||
this.includeMetadata = init?.includeMetadata ?? true;
|
||||
this.includePrevNextRel = init?.includePrevNextRel ?? true;
|
||||
}
|
||||
|
||||
async transform(nodes: BaseNode[], _options?: any): Promise<BaseNode[]> {
|
||||
return this.getNodesFromDocuments(nodes);
|
||||
}
|
||||
|
||||
static fromDefaults(init?: {
|
||||
chunkSize?: number;
|
||||
chunkOverlap?: number;
|
||||
includeMetadata?: boolean;
|
||||
includePrevNextRel?: boolean;
|
||||
}): SimpleNodeParser {
|
||||
return new SimpleNodeParser(init);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate Node objects from documents
|
||||
* @param documents
|
||||
*/
|
||||
getNodesFromDocuments(documents: BaseNode[]) {
|
||||
return documents
|
||||
.map((document) =>
|
||||
getNodesFromDocument(
|
||||
document,
|
||||
this.textSplitter.splitText.bind(this.textSplitter),
|
||||
this.includeMetadata,
|
||||
this.includePrevNextRel,
|
||||
),
|
||||
)
|
||||
.flat();
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1 @@
|
||||
export * from "./MarkdownNodeParser.js";
|
||||
export * from "./SentenceWindowNodeParser.js";
|
||||
export * from "./SimpleNodeParser.js";
|
||||
export * from "./types.js";
|
||||
export * from "@llamaindex/core/node-parser";
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
import type { BaseNode, TransformComponent } from "@llamaindex/core/schema";
|
||||
|
||||
/**
|
||||
* A NodeParser generates Nodes from Documents
|
||||
*/
|
||||
export interface NodeParser extends TransformComponent<any> {
|
||||
/**
|
||||
* Generates an array of nodes from an array of documents.
|
||||
* @param documents - The documents to generate nodes from.
|
||||
* @returns An array of nodes.
|
||||
*/
|
||||
getNodesFromDocuments(documents: BaseNode[]): BaseNode[];
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
import type { BaseNode } from "@llamaindex/core/schema";
|
||||
import {
|
||||
Document,
|
||||
ImageDocument,
|
||||
NodeRelationship,
|
||||
TextNode,
|
||||
} from "@llamaindex/core/schema";
|
||||
import _ from "lodash";
|
||||
|
||||
type TextSplitter = (s: string) => string[];
|
||||
|
||||
/**
|
||||
* Splits the text of a document into smaller parts.
|
||||
* @param document - The document to split.
|
||||
* @param textSplitter - The text splitter to use.
|
||||
* @returns An array of text splits.
|
||||
*/
|
||||
function getTextSplitsFromDocument(
|
||||
document: Document,
|
||||
textSplitter: TextSplitter,
|
||||
) {
|
||||
const text = document.getText();
|
||||
return textSplitter(text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates an array of nodes from a document.
|
||||
* @param doc
|
||||
* @param textSplitter - The text splitter to use.
|
||||
* @param includeMetadata - Whether to include metadata in the nodes.
|
||||
* @param includePrevNextRel - Whether to include previous and next relationships in the nodes.
|
||||
* @returns An array of nodes.
|
||||
*/
|
||||
export function getNodesFromDocument(
|
||||
doc: BaseNode,
|
||||
textSplitter: TextSplitter,
|
||||
includeMetadata: boolean = true,
|
||||
includePrevNextRel: boolean = true,
|
||||
): TextNode[] {
|
||||
if (doc instanceof ImageDocument) {
|
||||
// TODO: use text splitter on text of image documents
|
||||
return [doc];
|
||||
}
|
||||
if (!(doc instanceof Document)) {
|
||||
throw new Error("Expected either an Image Document or Document");
|
||||
}
|
||||
const document = doc as Document;
|
||||
const nodes: TextNode[] = [];
|
||||
|
||||
const textSplits = getTextSplitsFromDocument(document, textSplitter);
|
||||
|
||||
textSplits.forEach((textSplit) => {
|
||||
const node = new TextNode({
|
||||
text: textSplit,
|
||||
metadata: includeMetadata ? _.cloneDeep(document.metadata) : {},
|
||||
excludedEmbedMetadataKeys: _.cloneDeep(
|
||||
document.excludedEmbedMetadataKeys,
|
||||
),
|
||||
excludedLlmMetadataKeys: _.cloneDeep(document.excludedLlmMetadataKeys),
|
||||
});
|
||||
node.relationships[NodeRelationship.SOURCE] = document.asRelatedNodeInfo();
|
||||
nodes.push(node);
|
||||
});
|
||||
|
||||
if (includePrevNextRel) {
|
||||
nodes.forEach((node, index) => {
|
||||
if (index > 0) {
|
||||
node.relationships[NodeRelationship.PREVIOUS] =
|
||||
nodes[index - 1].asRelatedNodeInfo();
|
||||
}
|
||||
if (index < nodes.length - 1) {
|
||||
node.relationships[NodeRelationship.NEXT] =
|
||||
nodes[index + 1].asRelatedNodeInfo();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return nodes;
|
||||
}
|
||||
@@ -11,7 +11,14 @@ import { AssemblyAI } from "assemblyai";
|
||||
import type { BaseReader } from "./type.js";
|
||||
|
||||
type AssemblyAIOptions = Partial<BaseServiceParams>;
|
||||
|
||||
const defaultOptions = {
|
||||
userAgent: {
|
||||
integration: {
|
||||
name: "LlamaIndexTS",
|
||||
version: "1.0.1",
|
||||
},
|
||||
},
|
||||
};
|
||||
/**
|
||||
* Base class for AssemblyAI Readers.
|
||||
*/
|
||||
@@ -37,7 +44,10 @@ abstract class AssemblyAIReader implements BaseReader {
|
||||
);
|
||||
}
|
||||
|
||||
this.client = new AssemblyAI(options as BaseServiceParams);
|
||||
this.client = new AssemblyAI({
|
||||
...defaultOptions,
|
||||
...options,
|
||||
} as BaseServiceParams);
|
||||
}
|
||||
|
||||
abstract loadData(params: TranscribeParams | string): Promise<Document[]>;
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
import type { JSONValue } from "@llamaindex/core/global";
|
||||
import { Document } from "@llamaindex/core/schema";
|
||||
import { FileReader } from "./type.js";
|
||||
|
||||
export interface JSONReaderOptions {
|
||||
/**
|
||||
* Whether to ensure only ASCII characters.
|
||||
* Converts non-ASCII characters to their unicode escape sequence.
|
||||
* @default false
|
||||
*/
|
||||
ensureAscii?: boolean;
|
||||
|
||||
/**
|
||||
* Whether the JSON is in JSON Lines format.
|
||||
* Split into lines, remove empty lines, parse each line as JSON.
|
||||
* @default false
|
||||
*/
|
||||
isJsonLines?: boolean;
|
||||
|
||||
/**
|
||||
* Whether to clean the JSON by filtering out structural characters (`{}, [], and ,`).
|
||||
* If set to false, it will just parse the JSON, not removing structural characters.
|
||||
* @default true
|
||||
*/
|
||||
cleanJson?: boolean;
|
||||
|
||||
/**
|
||||
* Specifies how many levels up the JSON structure to include in the output. cleanJson will be ignored.
|
||||
* If set to 0, all levels are included. If undefined, parses the entire JSON and treats each line as an embedding.
|
||||
* @default undefined
|
||||
*/
|
||||
levelsBack?: number;
|
||||
|
||||
/**
|
||||
* The maximum length of JSON string representation to be collapsed into a single line.
|
||||
* Only applicable when `levelsBack` is set.
|
||||
* @default undefined
|
||||
*/
|
||||
collapseLength?: number;
|
||||
}
|
||||
|
||||
export class JSONReaderError extends Error {}
|
||||
export class JSONParseError extends JSONReaderError {}
|
||||
export class JSONStringifyError extends JSONReaderError {}
|
||||
|
||||
/**
|
||||
* A reader that reads JSON data and returns an array of Document objects.
|
||||
* Supports various options to modify the output.
|
||||
*/
|
||||
export class JSONReader<T extends JSONValue> extends FileReader {
|
||||
private options: JSONReaderOptions;
|
||||
|
||||
constructor(options: JSONReaderOptions = {}) {
|
||||
super();
|
||||
this.options = {
|
||||
ensureAscii: false,
|
||||
isJsonLines: false,
|
||||
cleanJson: true,
|
||||
...options,
|
||||
};
|
||||
this.validateOptions();
|
||||
}
|
||||
private validateOptions(): void {
|
||||
const { levelsBack, collapseLength } = this.options;
|
||||
if (levelsBack !== undefined && levelsBack < 0) {
|
||||
throw new JSONReaderError("levelsBack must not be negative");
|
||||
}
|
||||
if (collapseLength !== undefined && collapseLength < 0) {
|
||||
throw new JSONReaderError("collapseLength must not be negative");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads JSON data and returns an array of Document objects.
|
||||
*
|
||||
* @param {Uint8Array} content - The JSON data as a Uint8Array.
|
||||
* @return {Promise<Document[]>} A Promise that resolves to an array of Document objects.
|
||||
*/
|
||||
async loadDataAsContent(content: Uint8Array): Promise<Document[]> {
|
||||
const jsonStr = new TextDecoder("utf-8").decode(content);
|
||||
const parser = this.parseJsonString(jsonStr);
|
||||
const documents: Document[] = [];
|
||||
|
||||
for await (const data of parser) {
|
||||
documents.push(await this.createDocument(data));
|
||||
}
|
||||
return documents;
|
||||
}
|
||||
|
||||
private async *parseJsonString(jsonStr: string): AsyncGenerator<T> {
|
||||
if (this.options.isJsonLines) {
|
||||
yield* this.parseJsonLines(jsonStr);
|
||||
} else {
|
||||
yield* this.parseJson(jsonStr);
|
||||
}
|
||||
}
|
||||
|
||||
private async *parseJsonLines(jsonStr: string): AsyncGenerator<T> {
|
||||
// Process each line as a separate JSON object for JSON Lines format
|
||||
for (const line of jsonStr.split("\n")) {
|
||||
if (line.trim() !== "") {
|
||||
try {
|
||||
yield JSON.parse(line.trim());
|
||||
} catch (e) {
|
||||
throw new JSONParseError(
|
||||
`Error parsing JSON Line: ${e} in "${line.trim()}"`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async *parseJson(jsonStr: string): AsyncGenerator<T> {
|
||||
try {
|
||||
// TODO: Add streaming to handle large JSON files
|
||||
const parsedData = JSON.parse(jsonStr);
|
||||
|
||||
if (!this.options.cleanJson) {
|
||||
// Yield the parsed data directly if cleanJson is false
|
||||
yield parsedData;
|
||||
} else if (Array.isArray(parsedData)) {
|
||||
// Check if it's an Array, if so yield each item seperately, i.e. create a document per top-level array of the json
|
||||
for (const item of parsedData) {
|
||||
yield item;
|
||||
}
|
||||
} else {
|
||||
// If not an array, just yield the parsed data
|
||||
yield parsedData;
|
||||
}
|
||||
} catch (e) {
|
||||
throw new JSONParseError(`Error parsing JSON: ${e} in "${jsonStr}"`);
|
||||
}
|
||||
}
|
||||
|
||||
private async createDocument(data: T): Promise<Document> {
|
||||
const docText: string =
|
||||
this.options.levelsBack === undefined
|
||||
? this.formatJsonString(data)
|
||||
: await this.prepareDepthFirstYield(data);
|
||||
|
||||
return new Document({
|
||||
text: this.options.ensureAscii ? this.convertToAscii(docText) : docText,
|
||||
metadata: {
|
||||
doc_length: docText.length,
|
||||
traversal_data: {
|
||||
levels_back: this.options.levelsBack,
|
||||
collapse_length: this.options.collapseLength,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private async prepareDepthFirstYield(data: T): Promise<string> {
|
||||
const levelsBack = this.options.levelsBack ?? 0;
|
||||
const results: string[] = [];
|
||||
for await (const value of this.depthFirstYield(
|
||||
data,
|
||||
levelsBack === 0 ? Infinity : levelsBack,
|
||||
[],
|
||||
this.options.collapseLength,
|
||||
)) {
|
||||
results.push(value);
|
||||
}
|
||||
return results.join("\n");
|
||||
}
|
||||
|
||||
// Note: JSON.stringify does not differentiate between indent "undefined/null"(= no whitespaces) and "0"(= no whitespaces, but linebreaks)
|
||||
// as python json.dumps does. Thats why we use indent 1 and remove the leading spaces.
|
||||
|
||||
private formatJsonString(data: T): string {
|
||||
try {
|
||||
const jsonStr = JSON.stringify(
|
||||
data,
|
||||
null,
|
||||
this.options.cleanJson ? 1 : 0,
|
||||
);
|
||||
if (this.options.cleanJson) {
|
||||
// Clean JSON by removing structural characters and unnecessary whitespace
|
||||
return jsonStr
|
||||
.split("\n")
|
||||
.filter((line) => !/^[{}\[\],]*$/.test(line.trim()))
|
||||
.map((line) => line.trimStart()) // Removes the indent
|
||||
.join("\n");
|
||||
}
|
||||
return jsonStr;
|
||||
} catch (e) {
|
||||
throw new JSONStringifyError(
|
||||
`Error stringifying JSON: ${e} in "${data}"`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A generator function that determines the next step in traversing the JSON data.
|
||||
* If the serialized JSON string is not null, it yields the string and returns.
|
||||
* If the JSON data is an object, it delegates the traversal to the depthFirstTraversal method.
|
||||
* Otherwise, it yields the JSON data as a string.
|
||||
*
|
||||
* @param jsonData - The JSON data to traverse.
|
||||
* @param levelsBack - The number of levels up the JSON structure to include in the output.
|
||||
* @param path - The current path in the JSON structure.
|
||||
* @param collapseLength - The maximum length of JSON string representation to be collapsed into a single line.
|
||||
* @throws {JSONReaderError} - Throws an error if there is an issue during the depth-first traversal.
|
||||
*/
|
||||
private async *depthFirstYield(
|
||||
jsonData: T,
|
||||
levelsBack: number,
|
||||
path: string[],
|
||||
collapseLength?: number,
|
||||
): AsyncGenerator<string> {
|
||||
try {
|
||||
const jsonStr = this.serializeAndCollapse(
|
||||
jsonData,
|
||||
levelsBack,
|
||||
path,
|
||||
collapseLength,
|
||||
);
|
||||
if (jsonStr !== null) {
|
||||
yield jsonStr;
|
||||
return;
|
||||
}
|
||||
|
||||
if (jsonData !== null && typeof jsonData === "object") {
|
||||
yield* this.depthFirstTraversal(
|
||||
jsonData,
|
||||
levelsBack,
|
||||
path,
|
||||
collapseLength,
|
||||
);
|
||||
} else {
|
||||
yield `${path.slice(-levelsBack).join(" ")} ${String(jsonData)}`;
|
||||
}
|
||||
} catch (e) {
|
||||
throw new JSONReaderError(
|
||||
`Error during depth first traversal at path ${path.join(" ")}: ${e}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private serializeAndCollapse(
|
||||
jsonData: T,
|
||||
levelsBack: number,
|
||||
path: string[],
|
||||
collapseLength?: number,
|
||||
): string | null {
|
||||
try {
|
||||
const jsonStr = JSON.stringify(jsonData);
|
||||
return collapseLength !== undefined && jsonStr.length <= collapseLength
|
||||
? `${path.slice(-levelsBack).join(" ")} ${jsonStr}`
|
||||
: null;
|
||||
} catch (e) {
|
||||
throw new JSONStringifyError(`Error stringifying JSON data: ${e}`);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* A generator function that performs a depth-first traversal of the JSON data.
|
||||
* If the JSON data is an array, it traverses each item in the array.
|
||||
* If the JSON data is an object, it traverses each key-value pair in the object.
|
||||
* For each traversed item or value, it performs a depth-first yield.
|
||||
*
|
||||
* @param jsonData - The JSON data to traverse.
|
||||
* @param levelsBack - The number of levels up the JSON structure to include in the output.
|
||||
* @param path - The current path in the JSON structure.
|
||||
* @param collapseLength - The maximum length of JSON string representation to be collapsed into a single line.
|
||||
* @throws {JSONReaderError} - Throws an error if there is an issue during the depth-first traversal of the object.
|
||||
*/
|
||||
private async *depthFirstTraversal(
|
||||
jsonData: T,
|
||||
levelsBack: number,
|
||||
path: string[],
|
||||
collapseLength?: number,
|
||||
): AsyncGenerator<string> {
|
||||
try {
|
||||
if (Array.isArray(jsonData)) {
|
||||
for (const item of jsonData) {
|
||||
yield* this.depthFirstYield(item, levelsBack, path, collapseLength);
|
||||
}
|
||||
} else if (jsonData !== null && typeof jsonData === "object") {
|
||||
const originalLength = path.length;
|
||||
for (const [key, value] of Object.entries(jsonData)) {
|
||||
path.push(key);
|
||||
if (value !== null) {
|
||||
yield* this.depthFirstYield(
|
||||
value as T,
|
||||
levelsBack,
|
||||
path,
|
||||
collapseLength,
|
||||
);
|
||||
}
|
||||
path.length = originalLength; // Reset path length to original. Avoids cloning the path array every time.
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
throw new JSONReaderError(
|
||||
`Error during depth-first traversal of object: ${e}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private convertToAscii(str: string): string {
|
||||
return str.replace(
|
||||
/[\u007F-\uFFFF]/g,
|
||||
(char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user