Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

⚡️ perf(utils): reduce punctuation truncation probes (#17158)

愛美b23b3f737cfe
diff --git a/packages/utils/src/chunkers/trimBatchProbe/trimBatchProbe.test.ts b/packages/utils/src/chunkers/trimBatchProbe/trimBatchProbe.test.ts
index 7a4ea4efef0..1cbb32a1140 100644
--- a/packages/utils/src/chunkers/trimBatchProbe/trimBatchProbe.test.ts
+++ b/packages/utils/src/chunkers/trimBatchProbe/trimBatchProbe.test.ts
@@ -8,8 +8,12 @@ import {
truncateByPunctuation,
} from './trimBatchProbe';
+const mocks = vi.hoisted(() => ({
+ estimateTokenCount: vi.fn((str: string) => str.split(/\s+/).filter(Boolean).length),
+}));
+
vi.mock('tokenx', () => ({
- estimateTokenCount: (str: string) => str.split(/\s+/).filter(Boolean).length,
+ estimateTokenCount: mocks.estimateTokenCount,
}));
describe('trimBasedOnBatchProbe', () => {
@@ -155,6 +159,16 @@ describe('trimBasedOnBatchProbe', () => {
expect(result).toBe('drop these words');
});
+ it('stops after the first punctuation segment over the token limit', async () => {
+ mocks.estimateTokenCount.mockClear();
+ const text = Array.from({ length: 1024 }, (_, index) => `segment${index}.`).join(' ');
+
+ const result = await truncateByPunctuation(text, 3);
+
+ expect(result).toBe('segment1021. segment1022. segment1023.');
+ expect(mocks.estimateTokenCount).toHaveBeenCalledTimes(4);
+ });
+
it('hard truncates from tail with shrinking window', async () => {
const text = 'averylongtokenwithoutspacesorpunctuation';
const result = await hardTruncateFromTail(text, 2);
diff --git a/packages/utils/src/chunkers/trimBatchProbe/trimBatchProbe.ts b/packages/utils/src/chunkers/trimBatchProbe/trimBatchProbe.ts
index 51662cdefee..dc801ae5c9f 100644
--- a/packages/utils/src/chunkers/trimBatchProbe/trimBatchProbe.ts
+++ b/packages/utils/src/chunkers/trimBatchProbe/trimBatchProbe.ts
@@ -61,7 +61,7 @@ export const buildSegment = async <T>(
};
/**
- * Tries to preserve sentence/element boundaries by removing older punctuation-delimited chunks first.
+ * Preserves sentence/element boundaries by finding the longest punctuation-delimited suffix that fits.
*/
export const truncateByPunctuation = async (text: string, tokenLimit: number) => {
const segments = text
@@ -71,13 +71,19 @@ export const truncateByPunctuation = async (text: string, tokenLimit: number) =>
if (segments.length <= 1) return '';
- for (let i = segments.length; i >= 1; i -= 1) {
- const candidate = segments.slice(-i).join(' ');
- const tokenCount = await encodeAsync(candidate);
- if (tokenCount <= tokenLimit) return candidate;
+ // tokenx assigns no tokens to the spaces inserted by join(' '), so suffix cost is additive.
+ let start = segments.length;
+ let tokenCount = 0;
+
+ while (start > 0) {
+ const nextTokenCount = tokenCount + (await encodeAsync(segments[start - 1]));
+ if (nextTokenCount > tokenLimit) break;
+
+ tokenCount = nextTokenCount;
+ start -= 1;
}
- return '';
+ return segments.slice(start).join(' ');
};
/**