Skip to content

Commit 746981e

Browse files
committed
update trimmer logic
1 parent 95bf0ae commit 746981e

File tree

1 file changed

+23
-4
lines changed

1 file changed

+23
-4
lines changed

app/src/tokenizer/chat-history-trimmer.ts

+23-4
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,29 @@ export class ChatHistoryTrimmer {
4646
return this.output;
4747
}
4848

49+
const systemPrompt = this.messages.find(m => m.role === 'system');
50+
const firstUserMessage = this.messages.find(m => m.role === 'user');
4951
const last = this.messages[this.messages.length - 1];
52+
53+
this.output = [
54+
tokenizer.truncateMessage(systemPrompt!, 100),
55+
];
56+
57+
if (firstUserMessage === last) {
58+
this.output.push(tokenizer.truncateMessage(firstUserMessage, this.options.maxTokens - 100));
59+
} else {
60+
this.output.push(tokenizer.truncateMessage(firstUserMessage!, 100));
61+
this.output.push(tokenizer.truncateMessage(last, this.options.maxTokens - 200));
62+
}
63+
64+
excessTokens = this.countExcessTokens();
65+
if (excessTokens === 0) {
66+
return this.output;
67+
}
68+
5069
this.output = [
5170
tokenizer.truncateMessage(last, this.options.maxTokens),
52-
]
71+
];
5372

5473
return this.output;
5574
}
@@ -82,13 +101,13 @@ export class ChatHistoryTrimmer {
82101
const output: OpenAIMessage[] = [...this.output];
83102

84103
for (let i = 0; i < this.output.length && tokenizer.countTokensForMessages(output) > this.options.maxTokens; i++) {
85-
if (i == lastMessageIndex) {
104+
if (i === lastMessageIndex) {
86105
continue;
87106
}
88-
if (i !== systemPromptIndex && !this.options.preserveSystemPrompt) {
107+
if (i === systemPromptIndex || this.options.preserveSystemPrompt) {
89108
continue;
90109
}
91-
if (i !== firstUserMessageIndex && this.options.preserveFirstUserMessage) {
110+
if (i === firstUserMessageIndex || this.options.preserveFirstUserMessage) {
92111
continue;
93112
}
94113
output[i].content = '';

0 commit comments

Comments
 (0)