Compare commits

..

5 Commits

Author SHA1 Message Date
Alex Yang dbf2813b1d fix: change default claude model 2025-06-30 15:14:10 -07:00
Marcus Schiesser 0fcc92f632 fix: sentence splitter must not trim whitespaces (#2046) 2025-06-30 17:32:04 +07:00
Marcus Schiesser 515a8b9111 fix: error logging for fromPersistPath (#2049) 2025-06-30 13:41:13 +07:00
github-actions[bot] 7e8efc6284 Release @llamaindex/tools@0.1.2 (#2048) 2025-06-30 11:40:54 +07:00
Wassim Chegham 0fcf65126d chore: export type MCPClientOptions (#2047)
Co-authored-by: Marcus Schiesser <marcus.schiesser@googlemail.com>
2025-06-28 10:55:07 +07:00
18 changed files with 291 additions and 99 deletions
+5
View File
@@ -0,0 +1,5 @@
---
"@llamaindex/core": patch
---
Fix: split sentences must not trim whitespaces
+6
View File
@@ -0,0 +1,6 @@
---
"llamaindex": patch
"@llamaindex/core": patch
---
Fix logging for fromPersistPath
+1 -1
View File
@@ -10,7 +10,7 @@ import { mockLLMEvent } from "./utils.js";
let llm: LLM;
beforeEach(async () => {
Settings.llm = new Anthropic({
model: "claude-3-opus",
model: "claude-3.5-sonnet",
});
llm = Settings.llm;
});
+1 -1
View File
@@ -59,7 +59,7 @@ async function main() {
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
model: "claude-3-opus",
model: "claude-3.5-sonnet",
});
// Create an ReActAgent with the function tools
@@ -61,7 +61,7 @@ async function main() {
// Create an OpenAIAgent with the function tools
const agent = new ReActAgent({
llm: new Anthropic({
model: "claude-3-opus",
model: "claude-3.5-sonnet",
}),
tools: [functionTool, functionTool2],
});
@@ -17,7 +17,7 @@ export class SentenceWindowNodeParser extends NodeParser<TextNode[]> {
windowSize: number;
windowMetadataKey: string;
originalTextMetadataKey: string;
sentenceSplitter: TextSplitterFn = splitBySentenceTokenizer();
sentenceSplitter: TextSplitterFn = splitBySentenceTokenizer([], true);
idGenerator: () => string = () => randomUUID();
constructor(params?: z.input<typeof sentenceWindowNodeParserSchema>) {
+1 -1
View File
@@ -1,5 +1,5 @@
declare class SentenceTokenizer {
constructor(abbreviations?: string[]);
constructor(abbreviations?: string[], trimSentences?: boolean);
tokenize(text: string): string[];
}
@@ -1,3 +1,24 @@
/*
Copyright (c) 2024, Hugo W.L. ter Doest
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
var __getOwnPropNames = Object.getOwnPropertyNames;
var __commonJS = (cb, mod) =>
function __require() {
@@ -30,32 +51,47 @@ var require_tokenizer = __commonJS({
// lib/natural/tokenizers/sentence_tokenizer.js
var require_sentence_tokenizer = __commonJS({
"lib/natural/tokenizers/sentence_tokenizer.js"(exports, module) {
var Tokenizer = require_tokenizer();
var NUM = "NUMBER";
var DELIM = "DELIM";
var URI = "URI";
var ABBREV = "ABBREV";
var DEBUG = false;
const Tokenizer = require_tokenizer();
// Strings that will be used to create placeholders
const NUM = "NUMBER";
const DELIM = "DELIM";
const URI = "URI";
const ABBREV = "ABBREV";
const DEBUG = false;
function generateUniqueCode(base, index) {
// Surround the placeholder with {{}} to prevent shorter numbers to be recognized
// in larger numbers
return `{{${base}_${index}}}`;
}
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
var SentenceTokenizer = class extends Tokenizer {
constructor(abbreviations) {
class SentenceTokenizer extends Tokenizer {
constructor(abbreviations, trimSentences) {
super();
if (abbreviations) {
this.abbreviations = abbreviations;
} else {
this.abbreviations = [];
}
if (trimSentences === undefined) {
this.trimSentences = true;
} else {
this.trimSentences = trimSentences;
}
this.replacementMap = null;
this.replacementCounter = 0;
}
replaceUrisWithPlaceholders(text) {
const urlPattern =
/(https?:\/\/\S+|www\.\S+|ftp:\/\/\S+|(mailto:)?[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}|file:\/\/\S+)/gi;
const modifiedText = text.replace(urlPattern, (match) => {
const placeholder = generateUniqueCode(
URI,
@@ -64,8 +100,10 @@ var require_sentence_tokenizer = __commonJS({
this.replacementMap.set(placeholder, match);
return placeholder;
});
return modifiedText;
}
replaceAbbreviations(text) {
if (this.abbreviations.length === 0) {
return text;
@@ -79,9 +117,14 @@ var require_sentence_tokenizer = __commonJS({
this.replacementMap.set(code, match);
return code;
});
return replacedText;
}
replaceDelimitersWithPlaceholders(text) {
// Regular expression for sentence delimiters optionally followed by a bracket or quote
// Multiple delimiters with spaces in between are allowed
// The expression makes sure that the sentence delimiter group ends with a sentence delimiter
const delimiterPattern = /([.?!… ]*)([.?!…])(["'”’)}\]]?)/g;
const modifiedText = text.replace(
delimiterPattern,
@@ -94,32 +137,42 @@ var require_sentence_tokenizer = __commonJS({
return placeholder;
},
);
return modifiedText;
}
splitOnPlaceholders(text, placeholders) {
if (this.delimiterMap.size === 0) {
return [text];
}
const keys = Array.from(this.delimiterMap.keys());
const pattern = new RegExp(`(${keys.map(escapeRegExp).join("|")})`);
const parts = text.split(pattern);
const sentences = [];
for (let i = 0; i < parts.length; i += 2) {
const sentence = parts[i];
const placeholder = parts[i + 1] || "";
sentences.push(sentence + placeholder);
}
return sentences;
}
replaceNumbersWithCode(text) {
// Regular expression to match numbers, including decimal points and commas
const numberPattern = /\b\d{1,3}(?:,\d{3})*(?:\.\d+)?\b/g;
const replacedText = text.replace(numberPattern, (match) => {
const code = generateUniqueCode(NUM, this.replacementCounter++);
this.replacementMap.set(code, match);
return code;
});
return replacedText;
}
revertReplacements(text) {
let originalText = text;
for (const [
@@ -129,16 +182,20 @@ var require_sentence_tokenizer = __commonJS({
const pattern = new RegExp(escapeRegExp(placeholder), "g");
originalText = originalText.replace(pattern, replacement);
}
return originalText;
}
revertDelimiters(text) {
let originalText = text;
for (const [placeholder, replacement] of this.delimiterMap.entries()) {
const pattern = new RegExp(escapeRegExp(placeholder), "g");
originalText = originalText.replace(pattern, replacement);
}
return originalText;
}
tokenize(text) {
this.replacementCounter = 0;
this.replacementMap = /* @__PURE__ */ new Map();
@@ -148,32 +205,43 @@ var require_sentence_tokenizer = __commonJS({
"---Start of sentence tokenization-----------------------",
);
DEBUG && console.log("Original input: >>>" + text + "<<<");
// Replace abbreviations
const result1 = this.replaceAbbreviations(text);
DEBUG &&
console.log(
"Phase 1: replacing abbreviations: " + JSON.stringify(result1),
);
// Replace URIs
const result2 = this.replaceUrisWithPlaceholders(result1);
DEBUG &&
console.log("Phase 2: replacing URIs: " + JSON.stringify(result2));
// Replace delimiters followed by optional quotes, brackets, and braces
const result3 = this.replaceNumbersWithCode(result2);
DEBUG &&
console.log(
"Phase 3: replacing numbers with placeholders: " +
JSON.stringify(result3),
);
// Replace delimiters followed by optional quotes, brackets, and braces
const result4 = this.replaceDelimitersWithPlaceholders(result3);
DEBUG &&
console.log(
"Phase 4: replacing delimiters with placeholders: " +
JSON.stringify(result4),
);
// Split on placeholders for sentence delimiters
const sentences = this.splitOnPlaceholders(result4);
DEBUG &&
console.log(
"Phase 5: splitting into sentences on placeholders: " +
JSON.stringify(sentences),
);
// Replace back all abbreviations, URIs, and delimiters
const newSentences = sentences.map((s) => {
const s1 = this.revertReplacements(s);
return this.revertDelimiters(s1);
@@ -183,13 +251,17 @@ var require_sentence_tokenizer = __commonJS({
"Phase 6: replacing back abbreviations, URIs, numbers and delimiters: " +
JSON.stringify(newSentences),
);
const trimmedSentences = this.trim(newSentences);
DEBUG &&
console.log(
"Phase 7: trimming array of empty sentences: " +
JSON.stringify(trimmedSentences),
);
const trimmedSentences2 = trimmedSentences.map((sent) => sent.trim());
const trimmedSentences2 = trimmedSentences.map((sent) =>
this.trimSentences ? sent.trim() : sent,
);
DEBUG &&
console.log(
"Phase 8: trimming sentences from surrounding whitespace: " +
@@ -213,9 +285,10 @@ var require_sentence_tokenizer = __commonJS({
console.log(
"---------------------------------------------------------",
);
return trimmedSentences2;
}
};
}
module.exports = SentenceTokenizer;
},
});
+10 -6
View File
@@ -37,13 +37,17 @@ export const splitByChar = (): TextSplitterFn => {
export const splitBySentenceTokenizer = (
extraAbbreviations: string[] | undefined = [],
trimSentences: boolean = false,
): TextSplitterFn => {
const tokenizer = new SentenceTokenizer([
...abbreviations.english,
...abbreviations.spanish,
// Add the extra abbreviations provided by the user, e.g. for business-specific context
...extraAbbreviations,
]);
const tokenizer = new SentenceTokenizer(
[
...abbreviations.english,
...abbreviations.spanish,
// Add the extra abbreviations provided by the user, e.g. for business-specific context
...extraAbbreviations,
],
trimSentences,
);
return (text: string) => {
try {
return tokenizer.tokenize(text);
+12 -8
View File
@@ -101,17 +101,21 @@ export class SimpleKVStore extends BaseKVStore {
static async fromPersistPath(persistPath: string): Promise<SimpleKVStore> {
const dirPath = path.dirname(persistPath);
if (!(await exists(dirPath))) {
await fs.mkdir(dirPath);
await fs.mkdir(dirPath, { recursive: true });
}
let data: DataType = {};
try {
const fileData = await fs.readFile(persistPath);
data = JSON.parse(fileData.toString());
} catch (e) {
console.error(
`No valid data found at path: ${persistPath} starting new store.`,
);
if (!(await exists(persistPath))) {
console.info(`Starting new store from path: ${persistPath}`);
} else {
try {
const fileData = await fs.readFile(persistPath);
data = JSON.parse(fileData.toString());
} catch (e) {
throw new Error(`Failed to load data from path: ${persistPath}`, {
cause: e,
});
}
}
const store = new SimpleKVStore(data);
@@ -3,6 +3,7 @@ import {
splitBySentenceTokenizer,
} from "@llamaindex/core/node-parser";
import { Document } from "@llamaindex/core/schema";
import { Tokenizers, tokenizers } from "@llamaindex/env/tokenizers";
import { describe, expect, test } from "vitest";
describe("sentence splitter", () => {
@@ -75,20 +76,26 @@ describe("sentence splitter", () => {
expect(splits).toEqual(["This is a sentence. This is another sentence."]);
});
test("overall split long text", () => {
test("keep the space, if there's no split", () => {
const text = "The short sentence. The long long long long sentence.";
const sentenceSplitter = new SentenceSplitter({
chunkSize: 10,
chunkSize: 1024,
chunkOverlap: 0,
});
const splits = sentenceSplitter.splitText(
"The first short sentence. The first long long long sentence. The second short sentence. The second long long long sentence.",
);
expect(splits).toEqual([
"The first short sentence.",
"The first long long long sentence.",
"The second short sentence.",
"The second long long long sentence.",
]);
const splits = sentenceSplitter.splitText(text);
expect(splits).toEqual([text]);
});
test("split at tokenizer limit", () => {
const tokenizer = tokenizers.tokenizer(Tokenizers.CL100K_BASE);
const text = "The short sentence. The long long long long sentence.";
const sentenceSplitter = new SentenceSplitter({
tokenizer,
chunkSize: tokenizer.encode(text).length,
chunkOverlap: 0,
});
const splits = sentenceSplitter.splitText(text + " " + text);
expect(splits).toEqual([text, text]);
});
test("doesn't split decimals", () => {
@@ -280,18 +280,17 @@ export class SimpleVectorStore extends BaseVectorStore {
}
let dataDict: Record<string, unknown> = {};
try {
const fileData = await fs.readFile(persistPath);
dataDict = JSON.parse(fileData.toString());
} catch (e) {
console.error(
`No valid data found at path: ${persistPath} starting new store.`,
);
// persist empty data, to ignore this error in the future
await SimpleVectorStore.persistData(
persistPath,
new SimpleVectorStoreData(),
);
if (!(await exists(persistPath))) {
console.info(`Starting new store from path: ${persistPath}`);
} else {
try {
const fileData = await fs.readFile(persistPath);
dataDict = JSON.parse(fileData.toString());
} catch (e) {
throw new Error(`Failed to load data from path: ${persistPath}`, {
cause: e,
});
}
}
const data = new SimpleVectorStoreData();
@@ -1,43 +0,0 @@
import { OpenAIEmbedding } from "@llamaindex/openai";
import {
Settings,
storageContextFromDefaults,
type StorageContext,
} from "llamaindex";
import { existsSync, rmSync } from "node:fs";
import { mkdtemp } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
afterAll,
beforeAll,
describe,
expect,
test,
vi,
vitest,
} from "vitest";
const testDir = await mkdtemp(join(tmpdir(), "test-"));
vitest.spyOn(console, "error");
describe("StorageContext", () => {
let storageContext: StorageContext;
beforeAll(async () => {
Settings.embedModel = new OpenAIEmbedding();
storageContext = await storageContextFromDefaults({
persistDir: testDir,
});
});
test("initializes", async () => {
vi.mocked(console.error).mockImplementation(() => {}); // silence console.error
expect(existsSync(testDir)).toBe(true);
expect(storageContext).toBeDefined();
});
afterAll(() => {
rmSync(testDir, { recursive: true });
});
});
@@ -0,0 +1,130 @@
import { OpenAIEmbedding } from "@llamaindex/openai";
import {
Document,
Settings,
SimpleDocumentStore,
SimpleIndexStore,
SimpleVectorStore,
storageContextFromDefaults,
VectorStoreIndex,
} from "llamaindex";
import { existsSync, rmSync, writeFileSync } from "node:fs";
import { access, mkdtemp } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
afterEach,
beforeAll,
beforeEach,
describe,
expect,
test,
vi,
} from "vitest";
import { mockEmbeddingModel } from "../utility/mockOpenAI.js";
describe("StorageContext", () => {
let testDir: string;
beforeAll(async () => {
const embedModel = new OpenAIEmbedding();
mockEmbeddingModel(embedModel);
Settings.embedModel = embedModel;
});
beforeEach(async () => {
testDir = await mkdtemp(join(tmpdir(), "test-"));
});
test("initializes", async () => {
const storageContext = await storageContextFromDefaults({
persistDir: testDir,
});
expect(existsSync(testDir)).toBe(true);
expect(storageContext).toBeDefined();
});
test("persists and loads", async () => {
const doc = new Document({ text: "test document" });
const consoleInfoSpy = vi
.spyOn(console, "info")
.mockImplementation(() => {});
// storage context from individual stores
const storageContext = await storageContextFromDefaults({
docStore: await SimpleDocumentStore.fromPersistDir(testDir),
vectorStore: await SimpleVectorStore.fromPersistDir(testDir),
indexStore: await SimpleIndexStore.fromPersistDir(testDir),
});
const index = await VectorStoreIndex.fromDocuments([doc], {
storageContext,
});
expect(consoleInfoSpy).toHaveBeenCalledTimes(3);
expect(consoleInfoSpy).toHaveBeenCalledWith(
expect.stringContaining("Starting new store"),
);
expect(index).toBeDefined();
const retriever = index.asRetriever();
const result = await retriever.retrieve("test");
expect(result).toBeDefined();
expect(result.length).toBe(1);
// Check that the test data files exist
await expectTestDataFilesExist(testDir);
consoleInfoSpy.mockClear();
// Now, load it again. Since data was persisted, we should not see the error.
const newStorageContext = await storageContextFromDefaults({
docStore: await SimpleDocumentStore.fromPersistDir(testDir),
vectorStore: await SimpleVectorStore.fromPersistDir(testDir),
indexStore: await SimpleIndexStore.fromPersistDir(testDir),
});
const loadedIndex = await VectorStoreIndex.init({
storageContext: newStorageContext,
});
const loadedRetriever = loadedIndex.asRetriever();
const loadedResult = await loadedRetriever.retrieve("test");
expect(loadedResult).toBeDefined();
expect(loadedResult.length).toBe(1);
await expectTestDataFilesExist(testDir);
expect(consoleInfoSpy).not.toHaveBeenCalled();
consoleInfoSpy.mockRestore();
});
test("throws error on corrupted data", async () => {
// test SimpleKVStore
const docStorePath = join(testDir, "doc_store.json");
writeFileSync(docStorePath, "corrupted data");
await expect(SimpleDocumentStore.fromPersistDir(testDir)).rejects.toThrow(
/Failed to load data from path/,
);
// test SimpleVectorStore
const vectorStorePath = join(testDir, "vector_store.json");
writeFileSync(vectorStorePath, "corrupted data");
await expect(SimpleVectorStore.fromPersistDir(testDir)).rejects.toThrow(
/Failed to load data from path/,
);
});
afterEach(() => {
rmSync(testDir, { recursive: true, force: true });
});
});
async function expectTestDataFilesExist(testDir: string) {
const docStorePath = `${testDir}/doc_store.json`;
const vectorStorePath = `${testDir}/vector_store.json`;
const indexStorePath = `${testDir}/index_store.json`;
expect(await access(docStorePath)).toBeUndefined();
expect(await access(vectorStorePath)).toBeUndefined();
expect(await access(indexStorePath)).toBeUndefined();
}
@@ -65,7 +65,7 @@ export const BEDROCK_MODELS = {
ANTHROPIC_CLAUDE_2_1: "anthropic.claude-v2:1",
ANTHROPIC_CLAUDE_3_SONNET: "anthropic.claude-3-sonnet-20240229-v1:0",
ANTHROPIC_CLAUDE_3_HAIKU: "anthropic.claude-3-haiku-20240307-v1:0",
ANTHROPIC_CLAUDE_3_OPUS: "anthropic.claude-3-opus-20240229-v1:0",
ANTHROPIC_CLAUDE_3_OPUS: "anthropic.claude-3.5-sonnet-20240229-v1:0",
ANTHROPIC_CLAUDE_3_5_SONNET: "anthropic.claude-3-5-sonnet-20240620-v1:0",
ANTHROPIC_CLAUDE_3_5_SONNET_V2: "anthropic.claude-3-5-sonnet-20241022-v2:0",
ANTHROPIC_CLAUDE_3_5_HAIKU: "anthropic.claude-3-5-haiku-20241022-v1:0",
@@ -99,7 +99,7 @@ export type BEDROCK_MODELS =
export const INFERENCE_BEDROCK_MODELS = {
US_ANTHROPIC_CLAUDE_3_HAIKU: "us.anthropic.claude-3-haiku-20240307-v1:0",
US_ANTHROPIC_CLAUDE_3_5_HAIKU: "us.anthropic.claude-3-5-haiku-20241022-v1:0",
US_ANTHROPIC_CLAUDE_3_OPUS: "us.anthropic.claude-3-opus-20240229-v1:0",
US_ANTHROPIC_CLAUDE_3_OPUS: "us.anthropic.claude-3.5-sonnet-20240229-v1:0",
US_ANTHROPIC_CLAUDE_3_SONNET: "us.anthropic.claude-3-sonnet-20240229-v1:0",
US_ANTHROPIC_CLAUDE_3_5_SONNET:
"us.anthropic.claude-3-5-sonnet-20240620-v1:0",
+6
View File
@@ -1,5 +1,11 @@
# @llamaindex/tools
## 0.1.2
### Patch Changes
- 0fcf651: chore: export type MCPClientOptions
## 0.1.1
### Patch Changes
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@llamaindex/tools",
"description": "LlamaIndex Tools",
"version": "0.1.1",
"version": "0.1.2",
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
+2 -1
View File
@@ -59,7 +59,8 @@ type SSEMCPClientOptions = SSEClientTransportOptions & URLMCPOptions;
type StreamableHTTPMCPClientOptions = StreamableHTTPClientTransportOptions &
URLMCPOptions;
type MCPClientOptions =
// Export MCPClientOptions type for external consumers to use
export type MCPClientOptions =
| StdioMCPClientOptions
| SSEMCPClientOptions
| StreamableHTTPMCPClientOptions;