Feat: adding a warning message system and implementing compile chat mechanism
This feature include the following changes:
- Implemented llm/compileChat that gives the webview the ability to precompile the chat messages
before sending them to llm/streamChat where the webview can gather the pruning information and
provide users better guides.
- Added a optional parameter to llm/streamChat that can be used to indicate whether the chat
messages being passed is procompiled or not, so we don't compile the chat messages twice.
Because it's an optional parameter, we don't affect the behavior of llm/stream when it's
called at other places.
- Added a warning message box for the last ContinueInputBox which will display the warning
messages and also provide some useful guides.
https://github.com/Granite-Code/granite-code/issues/22
This commit is contained in:
parent
0330924d2e
commit
d130fef631
18 changed files with 313 additions and 24 deletions
12
core/core.ts
12
core/core.ts
|
|
@ -481,6 +481,18 @@ export class Core {
|
|||
});
|
||||
on("llm/listModels", this.handleListModels.bind(this));
|
||||
|
||||
on("llm/compileChat", async (msg) => {
|
||||
const { messages, options } = msg.data;
|
||||
const model = (await this.configHandler.loadConfig()).config
|
||||
?.selectedModelByRole.chat;
|
||||
|
||||
if (!model) {
|
||||
throw new Error("No chat model selected");
|
||||
}
|
||||
|
||||
return model.compileChatMessages(messages, options);
|
||||
});
|
||||
|
||||
// Provide messenger to utils so they can interact with GUI + state
|
||||
TTS.messenger = this.messenger;
|
||||
ChatDescriber.messenger = this.messenger;
|
||||
|
|
|
|||
27
core/index.d.ts
vendored
27
core/index.d.ts
vendored
|
|
@ -122,6 +122,7 @@ export interface ILLM
|
|||
messages: ChatMessage[],
|
||||
signal: AbortSignal,
|
||||
options?: LLMFullCompletionOptions,
|
||||
messageOptions?: MessageOption,
|
||||
): AsyncGenerator<ChatMessage, PromptLog>;
|
||||
|
||||
chat(
|
||||
|
|
@ -130,6 +131,11 @@ export interface ILLM
|
|||
options?: LLMFullCompletionOptions,
|
||||
): Promise<ChatMessage>;
|
||||
|
||||
compileChatMessages(
|
||||
messages: ChatMessage[],
|
||||
options: LLMFullCompletionOpeions,
|
||||
): CompiledChatMessagesReport;
|
||||
|
||||
embed(chunks: string[]): Promise<number[][]>;
|
||||
|
||||
rerank(query: string, chunks: Chunk[]): Promise<number[]>;
|
||||
|
|
@ -1682,3 +1688,24 @@ export interface CompleteOnboardingPayload {
|
|||
provider?: string;
|
||||
apiKey?: string;
|
||||
}
|
||||
|
||||
export type PruningStatus = "deleted-last-input" | "pruned" | "not-pruned";
|
||||
|
||||
export interface CompiledMessagesResult {
|
||||
compiledChatMessages: ChatMessage[];
|
||||
pruningStatus: PruningStatus;
|
||||
}
|
||||
|
||||
export interface MessageOption {
|
||||
precompiled: boolean;
|
||||
}
|
||||
|
||||
export type WarningMessageLevel = "warning" | "fatal";
|
||||
|
||||
export type WarningCategory = "exceeded-context-length" | "deleted-last-input";
|
||||
|
||||
export interface WarningMessage {
|
||||
message: string;
|
||||
level: WarningMessageLevel;
|
||||
category: WarningCategory;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,13 @@
|
|||
import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken";
|
||||
|
||||
import { ChatMessage, MessageContent, MessagePart, Tool } from "../index.js";
|
||||
import {
|
||||
ChatMessage,
|
||||
CompiledMessagesResult,
|
||||
MessageContent,
|
||||
MessagePart,
|
||||
PruningStatus,
|
||||
Tool,
|
||||
} from "../index.js";
|
||||
import { autodetectTemplateType } from "./autodetect.js";
|
||||
import {
|
||||
addSpaceToAnyEmptyMessages,
|
||||
|
|
@ -417,7 +424,7 @@ function compileChatMessages({
|
|||
maxTokens: number;
|
||||
supportsImages: boolean;
|
||||
tools?: Tool[];
|
||||
}): ChatMessage[] {
|
||||
}): CompiledMessagesResult {
|
||||
let msgsCopy: ChatMessage[] = msgs.map((m) => ({ ...m }));
|
||||
|
||||
// If images not supported, convert MessagePart[] to string
|
||||
|
|
@ -446,14 +453,14 @@ function compileChatMessages({
|
|||
msgsCopy.pop();
|
||||
}
|
||||
|
||||
// Extract the tool sequence from the end of the message array
|
||||
const toolSequence = extractToolSequence(msgsCopy);
|
||||
// // Extract the tool sequence from the end of the message array
|
||||
// const toolSequence = extractToolSequence(msgsCopy);
|
||||
|
||||
// Count tokens for all messages in the tool sequence
|
||||
let lastMessagesTokens = 0;
|
||||
for (const msg of toolSequence) {
|
||||
lastMessagesTokens += countChatMessageTokens(modelName, msg);
|
||||
}
|
||||
// // Count tokens for all messages in the tool sequence
|
||||
// let lastMessagesTokens = 0;
|
||||
// for (const msg of toolSequence) {
|
||||
// lastMessagesTokens += countChatMessageTokens(modelName, msg);
|
||||
// }
|
||||
|
||||
// System message
|
||||
let systemMsgTokens = 0;
|
||||
|
|
@ -479,7 +486,7 @@ function compileChatMessages({
|
|||
// Non-negotiable messages
|
||||
inputTokensAvailable -= toolTokens;
|
||||
inputTokensAvailable -= systemMsgTokens;
|
||||
inputTokensAvailable -= lastMessagesTokens;
|
||||
// inputTokensAvailable -= lastMessagesTokens;
|
||||
|
||||
// Make sure there's enough context for the non-excludable items
|
||||
if (inputTokensAvailable < 0) {
|
||||
|
|
@ -491,7 +498,6 @@ function compileChatMessages({
|
|||
- counting safety buffer: ${countingSafetyBuffer}
|
||||
- tools: ~${toolTokens}
|
||||
- system message: ~${systemMsgTokens}
|
||||
- last user or tool + tool call message tokens: ~${lastMessagesTokens}
|
||||
- max output tokens: ${maxTokens}`,
|
||||
);
|
||||
}
|
||||
|
|
@ -507,9 +513,12 @@ function compileChatMessages({
|
|||
};
|
||||
});
|
||||
|
||||
let pruningStatus: PruningStatus = "not-pruned";
|
||||
|
||||
while (historyWithTokens.length > 0 && currentTotal > inputTokensAvailable) {
|
||||
const message = historyWithTokens.shift()!;
|
||||
currentTotal -= message.tokens;
|
||||
pruningStatus = "pruned";
|
||||
|
||||
// At this point make sure no latent tool response without corresponding call
|
||||
while (historyWithTokens[0]?.role === "tool") {
|
||||
|
|
@ -518,15 +527,18 @@ function compileChatMessages({
|
|||
}
|
||||
}
|
||||
|
||||
if (historyWithTokens.length === 0) {
|
||||
pruningStatus = "deleted-last-input";
|
||||
}
|
||||
|
||||
// Now reassemble
|
||||
const reassembled: ChatMessage[] = [];
|
||||
if (systemMsg) {
|
||||
reassembled.push(systemMsg);
|
||||
}
|
||||
reassembled.push(...historyWithTokens.map(({ tokens, ...rest }) => rest));
|
||||
reassembled.push(...toolSequence);
|
||||
|
||||
return reassembled;
|
||||
return { compiledChatMessages: reassembled, pruningStatus };
|
||||
}
|
||||
|
||||
export {
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@ import {
|
|||
ILLMLogger,
|
||||
LLMFullCompletionOptions,
|
||||
LLMOptions,
|
||||
MessageOption,
|
||||
ModelCapability,
|
||||
ModelInstaller,
|
||||
PromptLog,
|
||||
|
|
@ -867,6 +868,23 @@ export abstract class BaseLLM implements ILLM {
|
|||
return { role: "assistant" as const, content: completion };
|
||||
}
|
||||
|
||||
compileChatMessages(
|
||||
message: ChatMessage[],
|
||||
options: LLMFullCompletionOptions,
|
||||
) {
|
||||
let { completionOptions } = this._parseCompletionOptions(options);
|
||||
completionOptions = this._modifyCompletionOptions(completionOptions);
|
||||
|
||||
return compileChatMessages({
|
||||
modelName: completionOptions.model,
|
||||
msgs: message,
|
||||
contextLength: this.contextLength,
|
||||
maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
|
||||
supportsImages: this.supportsImages(),
|
||||
tools: options.tools,
|
||||
});
|
||||
}
|
||||
|
||||
protected modifyChatBody(
|
||||
body: ChatCompletionCreateParams,
|
||||
): ChatCompletionCreateParams {
|
||||
|
|
@ -891,6 +909,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
_messages: ChatMessage[],
|
||||
signal: AbortSignal,
|
||||
options: LLMFullCompletionOptions = {},
|
||||
messageOptions?: MessageOption,
|
||||
): AsyncGenerator<ChatMessage, PromptLog> {
|
||||
let { completionOptions, logEnabled } =
|
||||
this._parseCompletionOptions(options);
|
||||
|
|
@ -901,14 +920,21 @@ export abstract class BaseLLM implements ILLM {
|
|||
|
||||
completionOptions = this._modifyCompletionOptions(completionOptions);
|
||||
|
||||
const messages = compileChatMessages({
|
||||
modelName: completionOptions.model,
|
||||
msgs: _messages,
|
||||
contextLength: this.contextLength,
|
||||
maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
|
||||
supportsImages: this.supportsImages(),
|
||||
tools: options.tools,
|
||||
});
|
||||
let messages = _messages;
|
||||
|
||||
// If not precompiled, compile the chat messages
|
||||
if (!messageOptions || messageOptions.precompiled === false) {
|
||||
const { compiledChatMessages } = compileChatMessages({
|
||||
modelName: completionOptions.model,
|
||||
msgs: _messages,
|
||||
contextLength: this.contextLength,
|
||||
maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
|
||||
supportsImages: this.supportsImages(),
|
||||
tools: options.tools,
|
||||
});
|
||||
|
||||
messages = compiledChatMessages;
|
||||
}
|
||||
|
||||
const prompt = this.templateMessages
|
||||
? this.templateMessages(messages)
|
||||
|
|
|
|||
|
|
@ -24,7 +24,12 @@ export async function* llmStreamChat(
|
|||
void TTS.kill();
|
||||
}
|
||||
|
||||
const { legacySlashCommandData, completionOptions, messages } = msg.data;
|
||||
const {
|
||||
legacySlashCommandData,
|
||||
completionOptions,
|
||||
messages,
|
||||
messageOptions,
|
||||
} = msg.data;
|
||||
|
||||
const model = config.selectedModelByRole.chat;
|
||||
|
||||
|
|
@ -117,6 +122,7 @@ export async function* llmStreamChat(
|
|||
messages,
|
||||
abortController.signal,
|
||||
completionOptions,
|
||||
messageOptions,
|
||||
);
|
||||
let next = await gen.next();
|
||||
while (!next.done) {
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ import { GlobalContextModelSelections } from "../util/GlobalContext";
|
|||
import {
|
||||
BrowserSerializedContinueConfig,
|
||||
ChatMessage,
|
||||
CompiledMessagesResult,
|
||||
CompleteOnboardingPayload,
|
||||
ContextItem,
|
||||
ContextItemWithId,
|
||||
|
|
@ -25,6 +26,7 @@ import {
|
|||
FileSymbolMap,
|
||||
IdeSettings,
|
||||
LLMFullCompletionOptions,
|
||||
MessageOption,
|
||||
ModelDescription,
|
||||
PromptLog,
|
||||
RangeInFile,
|
||||
|
|
@ -159,6 +161,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
messages: ChatMessage[];
|
||||
completionOptions: LLMFullCompletionOptions;
|
||||
title: string;
|
||||
messageOptions?: MessageOption;
|
||||
legacySlashCommandData?: {
|
||||
command: SlashCommandDescWithSource;
|
||||
input: string;
|
||||
|
|
@ -170,6 +173,10 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
AsyncGenerator<ChatMessage, PromptLog>,
|
||||
];
|
||||
streamDiffLines: [StreamDiffLinesPayload, AsyncGenerator<DiffLine>];
|
||||
"llm/compileChat": [
|
||||
{ messages: ChatMessage[]; options: LLMFullCompletionOptions },
|
||||
CompiledMessagesResult,
|
||||
];
|
||||
"chatDescriber/describe": [
|
||||
{
|
||||
text: string;
|
||||
|
|
|
|||
|
|
@ -41,6 +41,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
|
|||
"llm/complete",
|
||||
"llm/streamChat",
|
||||
"llm/listModels",
|
||||
"llm/compileChat",
|
||||
"streamDiffLines",
|
||||
"chatDescriber/describe",
|
||||
"stats/getTokensPerDay",
|
||||
|
|
|
|||
|
|
@ -107,6 +107,7 @@ class MessageTypes {
|
|||
"llm/complete",
|
||||
"llm/streamChat",
|
||||
"llm/listModels",
|
||||
"llm/compileChat",
|
||||
"streamDiffLines",
|
||||
"chatDescriber/describe",
|
||||
"stats/getTokensPerDay",
|
||||
|
|
|
|||
|
|
@ -23,6 +23,9 @@ export default function StepContainer(props: StepContainerProps) {
|
|||
const historyItemAfterThis = useAppSelector(
|
||||
(state) => state.session.history[props.index + 1],
|
||||
);
|
||||
const warningMessage = useAppSelector(
|
||||
(state) => state.session.warningMessage,
|
||||
);
|
||||
const uiConfig = useAppSelector(selectUIConfig);
|
||||
|
||||
const isNextMsgAssistantOrThinking =
|
||||
|
|
|
|||
|
|
@ -10,6 +10,9 @@ import { GradientBorder } from "./GradientBorder";
|
|||
import { ToolbarOptions } from "./InputToolbar";
|
||||
import { Lump } from "./Lump";
|
||||
import { TipTapEditor } from "./TipTapEditor";
|
||||
import WarningMessageBox from "./WarningMessageBox";
|
||||
import EditConfigAction from "./WarningMessageBox/Actions/EditConfigAction";
|
||||
import NewSessionAction from "./WarningMessageBox/Actions/NewSessionAction";
|
||||
|
||||
interface ContinueInputBoxProps {
|
||||
isLastUserInput: boolean;
|
||||
|
|
@ -40,6 +43,9 @@ const EDIT_DISALLOWED_CONTEXT_PROVIDERS = [
|
|||
|
||||
function ContinueInputBox(props: ContinueInputBoxProps) {
|
||||
const isStreaming = useAppSelector((state) => state.session.isStreaming);
|
||||
const warningMessage = useAppSelector(
|
||||
(state) => state.session.warningMessage,
|
||||
);
|
||||
const availableSlashCommands = useAppSelector(
|
||||
selectSlashCommandComboBoxInputs,
|
||||
);
|
||||
|
|
@ -119,6 +125,19 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
|
|||
/>
|
||||
</div>
|
||||
)}
|
||||
{props.isLastUserInput &&
|
||||
warningMessage &&
|
||||
(warningMessage.category === "exceeded-context-length" ? (
|
||||
<WarningMessageBox
|
||||
warningMessage={warningMessage}
|
||||
actions={[NewSessionAction]}
|
||||
/>
|
||||
) : (
|
||||
<WarningMessageBox
|
||||
warningMessage={warningMessage}
|
||||
actions={[EditConfigAction]}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,15 @@
|
|||
import { useContext } from "react";
|
||||
import { IdeMessengerContext } from "../../../../context/IdeMessenger";
|
||||
export default function EditConfigAction() {
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
return (
|
||||
<span
|
||||
onClick={() =>
|
||||
ideMessenger.post("config/openProfile", { profileId: undefined })
|
||||
}
|
||||
className="hover:underline"
|
||||
>
|
||||
Open configuration file
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
import { useAppDispatch } from "../../../../redux/hooks";
|
||||
import { newSession } from "../../../../redux/slices/sessionSlice";
|
||||
export default function NewSessionAction() {
|
||||
const dispatch = useAppDispatch();
|
||||
return (
|
||||
<span onClick={() => dispatch(newSession())} className="hover:underline">
|
||||
Start a new session
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
import { ReactNode, useEffect, useRef, useState } from "react";
|
||||
export default function ExpendableBox({ children }: { children: ReactNode }) {
|
||||
const [isExpended, setIsExpended] = useState(false);
|
||||
const [showTrigger, setShowTrigger] = useState(true);
|
||||
const expendableDivRef = useRef<HTMLDivElement>(null);
|
||||
const toggleExpendable = () => {
|
||||
setIsExpended((pre) => !pre);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (expendableDivRef.current) {
|
||||
expendableDivRef.current.style.maxHeight = isExpended ? "600px" : "0px";
|
||||
}
|
||||
|
||||
if (isExpended) {
|
||||
setShowTrigger(false);
|
||||
} else {
|
||||
setTimeout(() => setShowTrigger(true), 200);
|
||||
}
|
||||
}, [isExpended]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col">
|
||||
<div
|
||||
onClick={toggleExpendable}
|
||||
className={`h-[9px] w-[9px] self-end ${showTrigger ? "" : "hidden"} bg-warning my-2 mr-4 rounded-lg`}
|
||||
></div>
|
||||
|
||||
<div
|
||||
onClick={toggleExpendable}
|
||||
ref={expendableDivRef}
|
||||
style={{
|
||||
transition: "max-height 0.3s ease-in-out",
|
||||
overflowY: "hidden",
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
55
gui/src/components/mainInput/WarningMessageBox/index.tsx
Normal file
55
gui/src/components/mainInput/WarningMessageBox/index.tsx
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
import { WarningMessage } from "core";
|
||||
import { ReactElement } from "react";
|
||||
import ExpendableBox from "./ExpendableBox";
|
||||
|
||||
function MessageBox({
|
||||
warningMessage,
|
||||
actions,
|
||||
}: {
|
||||
warningMessage: WarningMessage;
|
||||
actions?: (() => ReactElement)[];
|
||||
}) {
|
||||
const warningMessageTextColor =
|
||||
warningMessage.level === "fatal" ? "text-error" : "text-warning";
|
||||
const warningMessageBorderColor =
|
||||
warningMessage.level === "fatal" ? "border-error" : "border-warning";
|
||||
return (
|
||||
<div
|
||||
className={`relative m-2 flex flex-col rounded-md border border-solid ${warningMessageBorderColor} bg-transparent p-4`}
|
||||
>
|
||||
<p className={`thread-message ${warningMessageTextColor}`}>
|
||||
<b>Warning: </b>
|
||||
{`${warningMessage.message}`}
|
||||
</p>
|
||||
{actions && (
|
||||
<div>
|
||||
<p>{`Recommended Action${actions.length > 1 ? "s" : ""}:`}</p>
|
||||
<ul>
|
||||
{actions.map((action, ind) => {
|
||||
return <li key={`warning-action-${ind}`}>{action()}</li>;
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function WarningMessageBox({
|
||||
warningMessage,
|
||||
actions,
|
||||
}: {
|
||||
warningMessage: WarningMessage;
|
||||
actions?: (() => ReactElement)[];
|
||||
}) {
|
||||
if (warningMessage.category === "exceeded-context-length") {
|
||||
return (
|
||||
<ExpendableBox
|
||||
children={
|
||||
<MessageBox warningMessage={warningMessage} actions={actions} />
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return <MessageBox warningMessage={warningMessage} actions={actions} />;
|
||||
}
|
||||
|
|
@ -84,6 +84,10 @@ const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = {
|
|||
},
|
||||
],
|
||||
},
|
||||
"llm/compileChat": {
|
||||
compiledChatMessages: [],
|
||||
pruningStatus: "not-pruned",
|
||||
},
|
||||
};
|
||||
|
||||
const DEFAULT_CHAT_RESPONSE: ChatMessage[] = [
|
||||
|
|
|
|||
|
|
@ -113,6 +113,9 @@ export function Chat() {
|
|||
const jetbrains = useMemo(() => {
|
||||
return isJetBrains();
|
||||
}, []);
|
||||
const warningMessage = useAppSelector(
|
||||
(state) => state.session.warningMessage,
|
||||
);
|
||||
|
||||
useAutoScroll(stepsDivRef, history);
|
||||
|
||||
|
|
|
|||
|
|
@ -21,8 +21,9 @@ import {
|
|||
SessionMetadata,
|
||||
ThinkingChatMessage,
|
||||
Tool,
|
||||
ToolCallState,
|
||||
ToolCallDelta,
|
||||
ToolCallState,
|
||||
WarningMessage,
|
||||
} from "core";
|
||||
import { BuiltInToolNames } from "core/tools/builtIn";
|
||||
import { NEW_SESSION_TITLE } from "core/util/constants";
|
||||
|
|
@ -223,6 +224,7 @@ type SessionState = {
|
|||
};
|
||||
newestToolbarPreviewForInput: Record<string, string>;
|
||||
hasReasoningEnabled?: boolean;
|
||||
warningMessage?: WarningMessage;
|
||||
};
|
||||
|
||||
const initialState: SessionState = {
|
||||
|
|
@ -424,6 +426,7 @@ export const sessionSlice = createSlice({
|
|||
deleteMessage: (state, action: PayloadAction<number>) => {
|
||||
// Deletes the current assistant message and the previous user message
|
||||
state.history.splice(action.payload - 1, 2);
|
||||
state.warningMessage = undefined;
|
||||
},
|
||||
updateHistoryItemAtIndex: (
|
||||
state,
|
||||
|
|
@ -889,6 +892,12 @@ export const sessionSlice = createSlice({
|
|||
state.newestToolbarPreviewForInput[payload.inputId] =
|
||||
payload.contextItemId;
|
||||
},
|
||||
setWarningMessage: (
|
||||
state,
|
||||
action: PayloadAction<WarningMessage | undefined>,
|
||||
) => {
|
||||
state.warningMessage = action.payload;
|
||||
},
|
||||
},
|
||||
selectors: {
|
||||
selectIsGatheringContext: (state) => {
|
||||
|
|
@ -972,6 +981,7 @@ export const {
|
|||
setNewestToolbarPreviewForInput,
|
||||
setIsInEdit,
|
||||
setHasReasoningEnabled,
|
||||
setWarningMessage,
|
||||
} = sessionSlice.actions;
|
||||
|
||||
export const { selectIsGatheringContext } = sessionSlice.selectors;
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ import {
|
|||
setAppliedRulesAtIndex,
|
||||
setInactive,
|
||||
setToolGenerated,
|
||||
setWarningMessage,
|
||||
streamUpdate,
|
||||
} from "../slices/sessionSlice";
|
||||
import { AppThunkDispatch, RootState, ThunkApiType } from "../store";
|
||||
|
|
@ -183,6 +184,41 @@ export const streamNormalInput = createAsyncThunk<
|
|||
);
|
||||
|
||||
dispatch(setActive());
|
||||
// Remove the warning message before each compileChat call
|
||||
dispatch(setWarningMessage(undefined));
|
||||
const precompiledRes = await extra.ideMessenger.request("llm/compileChat", {
|
||||
messages,
|
||||
options: completionOptions,
|
||||
});
|
||||
|
||||
if (precompiledRes.status === "error") {
|
||||
throw new Error(precompiledRes.error);
|
||||
}
|
||||
|
||||
const { compiledChatMessages, pruningStatus } = precompiledRes.content;
|
||||
|
||||
switch (pruningStatus) {
|
||||
case "pruned":
|
||||
dispatch(
|
||||
setWarningMessage({
|
||||
message: `Chat history exceeds model's context length (${state.config.config.selectedModelByRole.chat?.contextLength} tokens). Old messages will not be included.`,
|
||||
level: "warning",
|
||||
category: "exceeded-context-length",
|
||||
}),
|
||||
);
|
||||
break;
|
||||
case "deleted-last-input":
|
||||
dispatch(
|
||||
setWarningMessage({
|
||||
message:
|
||||
"The provided context items are too large. Please trim the context item to fit the model's context length or increase the model's context length by editing the configuration.",
|
||||
level: "fatal",
|
||||
category: "deleted-last-input",
|
||||
}),
|
||||
);
|
||||
dispatch(setInactive());
|
||||
return;
|
||||
}
|
||||
|
||||
// Send request and stream response
|
||||
const streamAborter = state.session.streamAborter;
|
||||
|
|
@ -190,8 +226,9 @@ export const streamNormalInput = createAsyncThunk<
|
|||
{
|
||||
completionOptions,
|
||||
title: selectedChatModel.title,
|
||||
messages: messages,
|
||||
messages: compiledChatMessages,
|
||||
legacySlashCommandData,
|
||||
messageOptions: { precompiled: true },
|
||||
},
|
||||
streamAborter.signal,
|
||||
);
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue