File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed
packages/core/src/utils/ai Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments