Skip to content

Commit 29e4eda

Browse files
committed
add message truncation utility for gen_ai byte limits
1 parent 632f0b9 commit 29e4eda

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
export function getByteSize(str: string): number {
2+
return new TextEncoder().encode(str).length;
3+
}
4+
5+
export function truncateMessagesByBytes(messages: unknown[], maxBytes: number): unknown[] {
6+
if (!Array.isArray(messages) || messages.length === 0) {
7+
return messages;
8+
}
9+
10+
const messagesJson = JSON.stringify(messages);
11+
const totalBytes = getByteSize(messagesJson);
12+
13+
if (totalBytes <= maxBytes) {
14+
return messages;
15+
}
16+
17+
let truncatedMessages = [...messages];
18+
19+
while (truncatedMessages.length > 0) {
20+
const truncatedJson = JSON.stringify(truncatedMessages);
21+
const truncatedBytes = getByteSize(truncatedJson);
22+
23+
if (truncatedBytes <= maxBytes) {
24+
break;
25+
}
26+
27+
truncatedMessages.shift();
28+
}
29+
30+
return truncatedMessages;
31+
}
32+
33+
export const DEFAULT_GEN_AI_MESSAGES_BYTE_LIMIT = 100000;
34+
35+
export function truncateGenAiMessages(messages: unknown[]): unknown[] {
36+
return truncateMessagesByBytes(messages, DEFAULT_GEN_AI_MESSAGES_BYTE_LIMIT);
37+
}

0 commit comments

Comments
 (0)