Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Show warning message when last user input get pruned #4816

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions core/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,8 @@ export type ChatMessageRole =
| "assistant"
| "thinking"
| "system"
| "tool";
| "tool"
| "warning";

export type TextMessagePart = {
type: "text";
Expand Down Expand Up @@ -385,12 +386,18 @@ export interface SystemChatMessage {
content: string;
}

export interface WarningChatMessage {
role: "warning";
content: string;
}

export type ChatMessage =
| UserChatMessage
| AssistantChatMessage
| ThinkingChatMessage
| SystemChatMessage
| ToolResultChatMessage;
| ToolResultChatMessage
| WarningChatMessage;

export interface ContextItemId {
providerTitle: string;
Expand Down
31 changes: 20 additions & 11 deletions core/llm/countTokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ class LlamaEncoding implements Encoding {
}

class NonWorkerAsyncEncoder implements AsyncEncoder {
constructor(private readonly encoding: Encoding) { }
constructor(private readonly encoding: Encoding) {}

async close(): Promise<void> { }
async close(): Promise<void> {}

async encode(text: string): Promise<number[]> {
return this.encoding.encode(text);
Expand Down Expand Up @@ -243,13 +243,15 @@ function pruneChatHistory(
chatHistory: ChatMessage[],
contextLength: number,
tokensForCompletion: number,
): ChatMessage[] {
): [ChatMessage[], boolean] {
let totalTokens =
tokensForCompletion +
chatHistory.reduce((acc, message) => {
return acc + countChatMessageTokens(modelName, message);
}, 0);

let shouldWarn = false;

// 0. Prune any messages that take up more than 1/3 of the context length
const longestMessages = [...chatHistory];
longestMessages.sort((a, b) => b.content.length - a.content.length);
Expand All @@ -275,6 +277,7 @@ function pruneChatHistory(
content,
);
totalTokens -= delta;
shouldWarn = true;
}

// 1. Replace beyond last 5 messages with summary
Expand Down Expand Up @@ -327,9 +330,10 @@ function pruneChatHistory(
tokensForCompletion,
);
totalTokens = contextLength;
shouldWarn = true;
}

return chatHistory;
return [chatHistory, shouldWarn];
}

function messageIsEmpty(message: ChatMessage): boolean {
Expand Down Expand Up @@ -367,6 +371,7 @@ function chatMessageIsEmpty(message: ChatMessage): boolean {
!message.toolCalls
);
case "thinking":
case "warning":
case "tool":
return false;
}
Expand All @@ -381,11 +386,16 @@ function compileChatMessages(
prompt: string | undefined = undefined,
functions: any[] | undefined = undefined,
systemMessage: string | undefined = undefined,
): ChatMessage[] {
): [ChatMessage[], boolean] {
let msgsCopy = msgs
? msgs
.map((msg) => ({ ...msg }))
.filter((msg) => !chatMessageIsEmpty(msg) && msg.role !== "system")
.map((msg) => ({ ...msg }))
.filter(
(msg) =>
!chatMessageIsEmpty(msg) &&
msg.role !== "system" &&
msg.role !== "warning",
)
: [];

msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy);
Expand Down Expand Up @@ -445,7 +455,7 @@ function compileChatMessages(
}
}

const history = pruneChatHistory(
const [history, shouldWarn] = pruneChatHistory(
modelName,
msgsCopy,
contextLength,
Expand All @@ -459,7 +469,7 @@ function compileChatMessages(

const flattenedHistory = flattenMessages(history);

return flattenedHistory;
return [flattenedHistory, shouldWarn];
}

export {
Expand All @@ -470,6 +480,5 @@ export {
pruneLinesFromTop,
pruneRawPromptFromTop,
pruneStringFromBottom,
pruneStringFromTop
pruneStringFromTop,
};

28 changes: 19 additions & 9 deletions core/llm/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,11 +195,11 @@ export abstract class BaseLLM implements ILLM {
options.completionOptions?.maxTokens ??
(llmInfo?.maxCompletionTokens
? Math.min(
llmInfo.maxCompletionTokens,
// Even if the model has a large maxTokens, we don't want to use that every time,
// because it takes away from the context length
this.contextLength / 4,
)
llmInfo.maxCompletionTokens,
// Even if the model has a large maxTokens, we don't want to use that every time,
// because it takes away from the context length
this.contextLength / 4,
)
: DEFAULT_MAX_TOKENS),
};
this.requestOptions = options.requestOptions;
Expand Down Expand Up @@ -766,7 +766,18 @@ export abstract class BaseLLM implements ILLM {

completionOptions = this._modifyCompletionOptions(completionOptions);

const messages = this._compileChatMessages(completionOptions, _messages);
const [messages, shouldWarn] = this._compileChatMessages(
completionOptions,
_messages,
);

if (shouldWarn) {
yield {
role: "warning",
content:
"The context has reached its limit. This may lead to less accurate or incomplete answers.",
};
}

const prompt = this.templateMessages
? this.templateMessages(messages)
Expand Down Expand Up @@ -840,7 +851,6 @@ export abstract class BaseLLM implements ILLM {
signal,
completionOptions,
)) {

if (chunk.role === "assistant") {
completion += chunk.content;
yield chunk;
Expand Down Expand Up @@ -948,15 +958,15 @@ export abstract class BaseLLM implements ILLM {
);
}

protected async * _streamComplete(
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
throw new Error("Not implemented");
}

protected async * _streamChat(
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
Expand Down
Loading
Loading