diff --git a/core/index.d.ts b/core/index.d.ts index ef043a2ce..c2bc7487b 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1712,23 +1712,12 @@ export interface CompleteOnboardingPayload { apiKey?: string; } -export type PruningStatus = "deleted-last-input" | "pruned" | "not-pruned"; - export interface CompiledMessagesResult { compiledChatMessages: ChatMessage[]; - pruningStatus: PruningStatus; + didPrune: boolean; + contextPercentage: number; } 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; -} diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index add0b983b..852638d1c 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -5,7 +5,6 @@ import { CompiledMessagesResult, MessageContent, MessagePart, - PruningStatus, Tool, } from "../index.js"; import { autodetectTemplateType } from "./autodetect.js"; @@ -363,9 +362,6 @@ function getTokenCountingBufferSafety(contextLength: number) { } const MIN_RESPONSE_TOKENS = 1000; -function getMinResponseTokens(maxTokens: number) { - return Math.min(MIN_RESPONSE_TOKENS, maxTokens); -} function pruneRawPromptFromTop( modelName: string, @@ -425,6 +421,8 @@ function compileChatMessages({ supportsImages: boolean; tools?: Tool[]; }): CompiledMessagesResult { + let didPrune = false; + let msgsCopy: ChatMessage[] = msgs.map((m) => ({ ...m })); // If images not supported, convert MessagePart[] to string @@ -446,22 +444,15 @@ function compileChatMessages({ msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy); - while (msgsCopy.length > 1) { - if (isUserOrToolMsg(msgsCopy.at(-1))) { - break; - } - msgsCopy.pop(); + // 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); } - // // 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); - // } - // System message let systemMsgTokens = 0; if (systemMsg) { @@ -475,7 +466,7 @@ function compileChatMessages({ } const countingSafetyBuffer = getTokenCountingBufferSafety(contextLength); - const minOutputTokens = getMinResponseTokens(maxTokens); + const minOutputTokens = Math.min(MIN_RESPONSE_TOKENS, maxTokens); let inputTokensAvailable = contextLength; @@ -486,19 +477,19 @@ 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) { throw new Error( `Not enough context available to include the system message, last user message, and tools. - There must be at least ${minOutputTokens} tokens remaining for output. - Request had the following token counts: - - contextLength: ${contextLength} - - counting safety buffer: ${countingSafetyBuffer} - - tools: ~${toolTokens} - - system message: ~${systemMsgTokens} - - max output tokens: ${maxTokens}`, + There must be at least ${minOutputTokens} tokens remaining for output. + Request had the following token counts: + - contextLength: ${contextLength} + - counting safety buffer: ${countingSafetyBuffer} + - tools: ~${toolTokens} + - system message: ~${systemMsgTokens} + - max output tokens: ${maxTokens}`, ); } @@ -513,12 +504,10 @@ function compileChatMessages({ }; }); - let pruningStatus: PruningStatus = "not-pruned"; - while (historyWithTokens.length > 0 && currentTotal > inputTokensAvailable) { const message = historyWithTokens.shift()!; currentTotal -= message.tokens; - pruningStatus = "pruned"; + didPrune = true; // At this point make sure no latent tool response without corresponding call while (historyWithTokens[0]?.role === "tool") { @@ -527,18 +516,24 @@ 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 { compiledChatMessages: reassembled, pruningStatus }; + const inputTokens = + currentTotal + systemMsgTokens + toolTokens + lastMessagesTokens; + const availableTokens = + contextLength - countingSafetyBuffer - minOutputTokens; + const contextPercentage = inputTokens / availableTokens; + return { + compiledChatMessages: reassembled, + didPrune, + contextPercentage, + }; } export { diff --git a/core/llm/index.ts b/core/llm/index.ts index 0eff12799..fa16b8591 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -940,7 +940,7 @@ export abstract class BaseLLM implements ILLM { let messages = _messages; // If not precompiled, compile the chat messages - if (!messageOptions || messageOptions.precompiled === false) { + if (!messageOptions?.precompiled) { const { compiledChatMessages } = compileChatMessages({ modelName: completionOptions.model, msgs: _messages, diff --git a/gui/src/components/StepContainer/StepContainer.tsx b/gui/src/components/StepContainer/StepContainer.tsx index 395b74827..84d681936 100644 --- a/gui/src/components/StepContainer/StepContainer.tsx +++ b/gui/src/components/StepContainer/StepContainer.tsx @@ -25,9 +25,6 @@ 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); // Calculate dimming and indicator state based on latest summary index diff --git a/gui/src/components/mainInput/ContextStatus.tsx b/gui/src/components/mainInput/ContextStatus.tsx new file mode 100644 index 000000000..3b73fa36a --- /dev/null +++ b/gui/src/components/mainInput/ContextStatus.tsx @@ -0,0 +1,77 @@ +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; +import { saveCurrentSession } from "../../redux/thunks/session"; +import { ToolTip } from "../gui/Tooltip"; + +const ContextStatus = () => { + const dispatch = useAppDispatch(); + const contextPercentage = useAppSelector( + (state) => state.session.contextPercentage, + ); + const history = useAppSelector((state) => state.session.history); + const percent = Math.round((contextPercentage ?? 0) * 100); + const isPruned = useAppSelector((state) => state.session.isPruned); + if (!isPruned && percent < 60) { + return null; + } + + const barColorClass = isPruned + ? "bg-error" + : percent > 80 + ? "bg-warning" + : "bg-description"; + + return ( +
+ +
+ + {`${percent}% of context filled`} + + {isPruned && ( + + {`Oldest messages are being removed`} + + )} + {history.length > 0 && ( +
+ Start a{" "} + { + void dispatch( + saveCurrentSession({ + openNewSession: true, + generateTitle: false, + }), + ); + }} + > + New Session + +
+ )} +
+
+
+
+
+
+ ); +}; + +export default ContextStatus; diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index d95a0a118..c731b761b 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -10,9 +10,6 @@ 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; @@ -43,9 +40,6 @@ 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, ); @@ -125,19 +119,6 @@ function ContinueInputBox(props: ContinueInputBoxProps) { /> )} - {props.isLastUserInput && - warningMessage && - (warningMessage.category === "exceeded-context-length" ? ( - - ) : ( - - ))} ); } diff --git a/gui/src/components/mainInput/InlineErrorMessage.tsx b/gui/src/components/mainInput/InlineErrorMessage.tsx new file mode 100644 index 000000000..d23fc7813 --- /dev/null +++ b/gui/src/components/mainInput/InlineErrorMessage.tsx @@ -0,0 +1,48 @@ +import { useContext } from "react"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; +import { setInlineErrorMessage } from "../../redux/slices/sessionSlice"; + +export type InlineErrorMessageType = "out-of-context"; + +export default function InlineErrorMessage() { + const dispatch = useAppDispatch(); + const ideMessenger = useContext(IdeMessengerContext); + const inlineErrorMessage = useAppSelector( + (state) => state.session.inlineErrorMessage, + ); + if (inlineErrorMessage === "out-of-context") { + return ( +
+

+ {`Message exceeds context limit.`} +

+
+
{ + ideMessenger.post("config/openProfile", { + profileId: undefined, + }); + }} + > + Open config + Config +
+ | + { + dispatch(setInlineErrorMessage(undefined)); + }} + > + Hide + +
+
+ ); + } + return null; +} diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 4967c9d90..9be9f25d9 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -19,6 +19,7 @@ import ModelSelect from "../modelSelection/ModelSelect"; import { ModeSelect } from "../ModeSelect"; import { Button } from "../ui"; import { useFontSize } from "../ui/font"; +import ContextStatus from "./ContextStatus"; import HoverItem from "./InputToolbar/HoverItem"; export interface ToolbarOptions { @@ -170,6 +171,7 @@ function InputToolbar(props: InputToolbarProps) { fontSize: tinyFont, }} > + {!isInEdit && } {!props.toolbarOptions?.hideUseCodebase && !isInEdit && ( ))} @@ -432,21 +431,19 @@ export function Chat() {
{history.length === 0 && lastSessionId && !isInEdit && ( -
- { - await dispatch( - loadLastSession({ - saveCurrentSession: true, - }), - ); - }} - className="flex items-center gap-2" - > - - Last Session - -
+ { + await dispatch( + loadLastSession({ + saveCurrentSession: true, + }), + ); + }} + className="flex items-center gap-2" + > + + Last Session + )}
diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 805c3a5a7..8ede0e55f 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -23,7 +23,6 @@ import { Tool, ToolCallDelta, ToolCallState, - WarningMessage, } from "core"; import { BuiltInToolNames } from "core/tools/builtIn"; import { NEW_SESSION_TITLE } from "core/util/constants"; @@ -34,6 +33,7 @@ import { import { findUriInDirs, getUriPathBasename } from "core/util/uri"; import { findLastIndex } from "lodash"; import { v4 as uuidv4 } from "uuid"; +import { type InlineErrorMessageType } from "../../components/mainInput/InlineErrorMessage"; import { toolCallCtxItemToCtxItemWithId } from "../../pages/gui/ToolCallDiv/utils"; import { addToolCallDeltaToState } from "../../util/toolCallState"; import { RootState } from "../store"; @@ -224,8 +224,10 @@ type SessionState = { }; newestToolbarPreviewForInput: Record; hasReasoningEnabled?: boolean; + isPruned?: boolean; + contextPercentage?: number; + inlineErrorMessage?: InlineErrorMessageType; compactionLoading: Record; // Track compaction loading by message index - warningMessage?: WarningMessage; }; const initialState: SessionState = { @@ -431,12 +433,17 @@ export const sessionSlice = createSlice({ }, contextItems: [], }); + state.inlineErrorMessage = undefined; + state.isPruned = false; + state.contextPercentage = undefined; } }, deleteMessage: (state, action: PayloadAction) => { // Deletes the current assistant message and the previous user message state.history.splice(action.payload - 1, 2); - state.warningMessage = undefined; + state.inlineErrorMessage = undefined; + state.isPruned = false; + state.contextPercentage = undefined; }, updateHistoryItemAtIndex: ( state, @@ -647,6 +654,10 @@ export const sessionSlice = createSlice({ state.isStreaming = false; state.symbols = {}; + state.inlineErrorMessage = undefined; + state.isPruned = false; + state.contextPercentage = undefined; + if (payload) { state.history = payload.history as any; state.title = payload.title; @@ -913,11 +924,17 @@ export const sessionSlice = createSlice({ delete state.compactionLoading[index]; } }, - setWarningMessage: ( + setInlineErrorMessage: ( state, - action: PayloadAction, + action: PayloadAction, ) => { - state.warningMessage = action.payload; + state.inlineErrorMessage = action.payload; + }, + setIsPruned: (state, action: PayloadAction) => { + state.isPruned = action.payload; + }, + setContextPercentage: (state, action: PayloadAction) => { + state.contextPercentage = action.payload; }, }, selectors: { @@ -1002,8 +1019,10 @@ export const { setNewestToolbarPreviewForInput, setIsInEdit, setHasReasoningEnabled, + setInlineErrorMessage, + setIsPruned, + setContextPercentage, setCompactionLoading, - setWarningMessage, } = sessionSlice.actions; export const { selectIsGatheringContext } = sessionSlice.selectors; diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 3f56f4bbd..6c722817b 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -11,9 +11,11 @@ import { addPromptCompletionPair, setActive, setAppliedRulesAtIndex, + setContextPercentage, setInactive, + setInlineErrorMessage, + setIsPruned, setToolGenerated, - setWarningMessage, streamUpdate, } from "../slices/sessionSlice"; import { AppThunkDispatch, RootState, ThunkApiType } from "../store"; @@ -184,42 +186,29 @@ export const streamNormalInput = createAsyncThunk< ); dispatch(setActive()); - // Remove the warning message before each compileChat call - dispatch(setWarningMessage(undefined)); + dispatch(setInlineErrorMessage(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", - }), - ); + if (precompiledRes.error.includes("Not enough context")) { + dispatch(setInlineErrorMessage("out-of-context")); dispatch(setInactive()); return; + } else { + throw new Error(precompiledRes.error); + } } + const { compiledChatMessages, didPrune, contextPercentage } = + precompiledRes.content; + + dispatch(setIsPruned(didPrune)); + dispatch(setContextPercentage(contextPercentage)); + // Send request and stream response const streamAborter = state.session.streamAborter; const gen = extra.ideMessenger.llmStreamChat( diff --git a/packages/shared-release.config.js b/packages/shared-release.config.js index 8063d6937..49373804c 100644 --- a/packages/shared-release.config.js +++ b/packages/shared-release.config.js @@ -25,4 +25,4 @@ export default function createReleaseConfig(packageName) { "@semantic-release/github", ], }; -} \ No newline at end of file +}