From 115d069e62067858b10179bd0b2ec7144c771c32 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 9 Apr 2025 10:06:20 -0700 Subject: [PATCH 01/11] token-counts --- core/llm/constants.ts | 22 ------------- core/llm/countTokens.ts | 30 +++++++++-------- core/llm/index.ts | 40 +++++++---------------- packages/llm-info/src/providers/openai.ts | 6 ++++ 4 files changed, 33 insertions(+), 65 deletions(-) diff --git a/core/llm/constants.ts b/core/llm/constants.ts index 333c79e70..1eb81569e 100644 --- a/core/llm/constants.ts +++ b/core/llm/constants.ts @@ -7,38 +7,16 @@ const DEFAULT_ARGS = { temperature: DEFAULT_TEMPERATURE, }; -const GPT_4_CTX_LEN = 128_000; - -const CONTEXT_LENGTH_FOR_MODEL: { [name: string]: number } = { - "gpt-3.5-turbo": 4096, - "gpt-3.5-turbo-0613": 4096, - "gpt-3.5-turbo-16k": 16_384, - "gpt-35-turbo-16k": 16_384, - "gpt-35-turbo-0613": 4096, - "gpt-35-turbo": 4096, - "gpt-4": 4096, - "gpt-4-32k": 32_000, - "gpt-4-turbo-preview": 32_000, - "gpt-4o": GPT_4_CTX_LEN, - "gpt-4o-mini": GPT_4_CTX_LEN, - "gpt-4-vision": GPT_4_CTX_LEN, - "gpt-4-0125-preview": GPT_4_CTX_LEN, - "gpt-4-1106-preview": GPT_4_CTX_LEN, -}; - -const TOKEN_BUFFER_FOR_SAFETY = 350; const PROXY_URL = "http://localhost:65433"; const DEFAULT_MAX_CHUNK_SIZE = 500; // 512 - buffer for safety (in case of differing tokenizers) const DEFAULT_MAX_BATCH_SIZE = 64; export { - CONTEXT_LENGTH_FOR_MODEL, DEFAULT_ARGS, DEFAULT_CONTEXT_LENGTH, DEFAULT_MAX_BATCH_SIZE, DEFAULT_MAX_CHUNK_SIZE, DEFAULT_MAX_TOKENS, PROXY_URL, - TOKEN_BUFFER_FOR_SAFETY, }; diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 2fc01f9b8..0fae50656 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -4,6 +4,7 @@ import { ChatMessage, MessageContent, MessagePart, + Tool, UserChatMessage, } from "../index.js"; @@ -15,7 +16,6 @@ import { LlamaAsyncEncoder, } from "./asyncEncoder.js"; import { autodetectTemplateType } from "./autodetect.js"; -import { TOKEN_BUFFER_FOR_SAFETY } from "./constants.js"; import llamaTokenizer from "./llamaTokenizer.js"; import { isRuleActive } from "./rules/isRuleActive.js"; import { extractPathsFromCodeBlocks } from "./utils/extractPathsFromCodeBlocks.js"; @@ -220,6 +220,8 @@ function pruneStringFromTop( return encoding.decode(tokens.slice(tokens.length - maxTokens)); } +const MAX_TOKEN_BUFFER_FOR_SAFETY = 3000; + function pruneRawPromptFromTop( modelName: string, contextLength: number, @@ -227,20 +229,20 @@ function pruneRawPromptFromTop( tokensForCompletion: number, ): string { const maxTokens = - contextLength - tokensForCompletion - TOKEN_BUFFER_FOR_SAFETY; + contextLength - tokensForCompletion - Math.max(MAX_TOKEN_BUFFER_FOR_SAFETY, contextLength*; return pruneStringFromTop(modelName, maxTokens, prompt); } -function pruneRawPromptFromBottom( - modelName: string, - contextLength: number, - prompt: string, - tokensForCompletion: number, -): string { - const maxTokens = - contextLength - tokensForCompletion - TOKEN_BUFFER_FOR_SAFETY; - return pruneStringFromBottom(modelName, maxTokens, prompt); -} +// function pruneRawPromptFromBottom( +// modelName: string, +// contextLength: number, +// prompt: string, +// tokensForCompletion: number, +// ): string { +// const maxTokens = +// contextLength - tokensForCompletion - TOKEN_BUFFER_FOR_SAFETY; +// return pruneStringFromBottom(modelName, maxTokens, prompt); +// } function summarize(message: ChatMessage): string { return `${renderChatMessage(message).substring(0, 100)}...`; @@ -514,7 +516,7 @@ function compileChatMessages({ maxTokens, supportsImages, prompt, - functions, + tools, systemMessage, rules, }: { @@ -524,7 +526,7 @@ function compileChatMessages({ maxTokens: number; supportsImages: boolean; prompt: string | undefined; - functions: any[] | undefined; + tools: Tool[] | undefined; systemMessage: string | undefined; rules: Rule[]; }): ChatMessage[] { diff --git a/core/llm/index.ts b/core/llm/index.ts index 7544b5292..0c79c6974 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -40,7 +40,6 @@ import { modelSupportsImages, } from "./autodetect.js"; import { - CONTEXT_LENGTH_FOR_MODEL, DEFAULT_ARGS, DEFAULT_CONTEXT_LENGTH, DEFAULT_MAX_BATCH_SIZE, @@ -278,33 +277,6 @@ export abstract class BaseLLM implements ILLM { return Promise.resolve([]); } - private _compileChatMessages( - options: CompletionOptions, - messages: ChatMessage[], - functions?: any[], - ) { - let contextLength = this.contextLength; - if ( - options.model !== this.model && - options.model in CONTEXT_LENGTH_FOR_MODEL - ) { - contextLength = - CONTEXT_LENGTH_FOR_MODEL[options.model] || DEFAULT_CONTEXT_LENGTH; - } - - return compileChatMessages({ - modelName: options.model, - msgs: messages, - contextLength, - maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS, - supportsImages: this.supportsImages(), - prompt: undefined, - functions, - systemMessage: this.systemMessage, - rules: this.rules ?? [], - }); - } - private _templatePromptLikeMessages(prompt: string): string { if (!this.templateMessages) { return prompt; @@ -913,7 +885,17 @@ export abstract class BaseLLM implements ILLM { completionOptions = this._modifyCompletionOptions(completionOptions); - const messages = this._compileChatMessages(completionOptions, _messages); + const messages = compileChatMessages({ + modelName: completionOptions.model, + msgs: _messages, + contextLength: this.contextLength, + maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS, + supportsImages: this.supportsImages(), + prompt: undefined, + tools: options.tools, + systemMessage: this.systemMessage, + rules: this.rules ?? [], + }); const prompt = this.templateMessages ? this.templateMessages(messages) diff --git a/packages/llm-info/src/providers/openai.ts b/packages/llm-info/src/providers/openai.ts index b96461e4b..a15dd3089 100644 --- a/packages/llm-info/src/providers/openai.ts +++ b/packages/llm-info/src/providers/openai.ts @@ -8,6 +8,12 @@ export const OpenAi: ModelProvider = { contextLength: 16385, maxCompletionTokens: 4096, }, + { + model: "gpt-3.5-turbo-0613", + displayName: "GPT-3.5 Turbo", + contextLength: 16385, + maxCompletionTokens: 4096, + }, { model: "gpt-3.5-turbo-16k", displayName: "GPT-3.5 Turbo 16K", From 4e0ac878f7b66bc741a6bc3fb60e180aadcde4f1 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 13 Apr 2025 19:43:53 -0700 Subject: [PATCH 02/11] BROKEN - tools updates --- core/.eslintrc.json | 2 +- core/core.ts | 22 +-- core/llm/countTokens.ts | 275 ++++++++++++++++------------ core/llm/index.ts | 1 - core/tools/builtIn.ts | 2 + core/tools/callTool.ts | 73 +++++--- core/tools/toolError.ts | 14 ++ extensions/vscode/package-lock.json | 6 +- gui/src/redux/thunks/callTool.ts | 12 +- 9 files changed, 230 insertions(+), 177 deletions(-) create mode 100644 core/tools/toolError.ts diff --git a/core/.eslintrc.json b/core/.eslintrc.json index 4790b5c45..517558d32 100644 --- a/core/.eslintrc.json +++ b/core/.eslintrc.json @@ -13,7 +13,7 @@ "@typescript-eslint/semi": "off", "eqeqeq": "error", "complexity": ["error", { "max": 38 }], - "max-lines-per-function": ["error", { "max": 485 }], + "max-lines-per-function": ["error", { "max": 520 }], "max-statements": ["error", { "max": 114 }], "max-depth": ["error", { "max": 6 }], "max-nested-callbacks": ["error", { "max": 4 }], diff --git a/core/core.ts b/core/core.ts index e929a863b..43bfb8cd5 100644 --- a/core/core.ts +++ b/core/core.ts @@ -683,23 +683,13 @@ export class Core { const llm = await this.configHandler.llmFromTitle(selectedModelTitle); - const contextItems = await callTool( + const contextItems = await callTool(tool, toolCall.function.arguments, { + ide: this.ide, + llm, + fetch: (url, init) => + fetchwithRequestOptions(url, init, config.requestOptions), tool, - JSON.parse(toolCall.function.arguments || "{}"), - { - ide: this.ide, - llm, - fetch: (url, init) => - fetchwithRequestOptions(url, init, config.requestOptions), - tool, - }, - ); - - if (tool.faviconUrl) { - contextItems.forEach((item) => { - item.icon = tool.faviconUrl; - }); - } + }); return { contextItems }; }); diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 0fae50656..d3a5f152c 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -151,6 +151,51 @@ export function flattenMessages(msgs: ChatMessage[]): ChatMessage[] { return flattened; } +// https://community.openai.com/t/how-to-calculate-the-tokens-when-using-function-call/266573/10 +function countToolsTokens(tools: Tool[], modelName: string): number { + const count = (value: string) => + encodingForModel(modelName).encode(value).length; + + let numTokens = 12; + + for (const tool of tools) { + let functionTokens = count(tool.function.name); + if (tool.function.description) { + functionTokens += count(tool.function.description); + } + const props = tool.function.parameters?.properties; + if (props) { + for (const key in props) { + functionTokens += count(key); + const fields = props[key]; + if (fields) { + const fieldType = fields["type"]; + const fieldDesc = fields["description"]; + const fieldEnum = fields["enum"]; + if (fieldType && typeof fieldType === "string") { + functionTokens += 2; + functionTokens += count(fieldType); + } + if (fieldDesc && typeof fieldDesc === "string") { + functionTokens += 2; + functionTokens += count(fieldDesc); + } + if (fieldEnum && Array.isArray(fieldEnum)) { + functionTokens -= 3; + for (const e of fieldEnum) { + functionTokens += 3; + functionTokens += typeof e === "string" ? count(e) : 5; + } + } + } + } + } + numTokens += functionTokens; + } + + return numTokens + 12; +} + function countChatMessageTokens( modelName: string, chatMessage: ChatMessage, @@ -158,8 +203,38 @@ function countChatMessageTokens( // Doing simpler, safer version of what is here: // https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb // every message follows <|im_start|>{role/name}\n{content}<|end|>\n - const TOKENS_PER_MESSAGE: number = 4; - return countTokens(chatMessage.content, modelName) + TOKENS_PER_MESSAGE; + const BASE_TOKENS = 4; + const TOOL_CALL_EXTRA_TOKENS = 10; + const TOOL_OUTPUT_EXTRA_TOKENS = 10; + let tokens = BASE_TOKENS; + + if (chatMessage.content) { + tokens += countTokens(chatMessage.content, modelName); + } + + if ("toolCalls" in chatMessage && chatMessage.toolCalls) { + for (const call of chatMessage.toolCalls) { + tokens += TOOL_CALL_EXTRA_TOKENS; + tokens += countTokens(JSON.stringify(call), modelName); // TODO hone this + } + } + + if (chatMessage.role === "thinking") { + if (chatMessage.redactedThinking) { + tokens += countTokens(chatMessage.redactedThinking, modelName); + } + if (chatMessage.signature) { + tokens += countTokens(chatMessage.signature, modelName); + } + } + + if (chatMessage.role === "tool") { + tokens += TOOL_OUTPUT_EXTRA_TOKENS; // safety + if (chatMessage.toolCallId) { + tokens += countTokens(chatMessage.toolCallId, modelName); + } + } + return tokens; } function pruneLinesFromTop( @@ -220,7 +295,14 @@ function pruneStringFromTop( return encoding.decode(tokens.slice(tokens.length - maxTokens)); } -const MAX_TOKEN_BUFFER_FOR_SAFETY = 3000; +const MAX_TOKEN_SAFETY_BUFFER = 1000; +const TOKEN_BUFFER_PROPORTION = 0.07; +function getTokenBufferSafety(contextLength: number) { + return Math.min( + MAX_TOKEN_SAFETY_BUFFER, + contextLength * TOKEN_BUFFER_PROPORTION, + ); +} function pruneRawPromptFromTop( modelName: string, @@ -229,7 +311,7 @@ function pruneRawPromptFromTop( tokensForCompletion: number, ): string { const maxTokens = - contextLength - tokensForCompletion - Math.max(MAX_TOKEN_BUFFER_FOR_SAFETY, contextLength*; + contextLength - tokensForCompletion - getTokenBufferSafety(contextLength); return pruneStringFromTop(modelName, maxTokens, prompt); } @@ -245,128 +327,97 @@ function pruneRawPromptFromTop( // } function summarize(message: ChatMessage): string { - return `${renderChatMessage(message).substring(0, 100)}...`; + return `(Truncated message): ${renderChatMessage(message).substring(0, 100)}...`; } function pruneChatHistory( modelName: string, chatHistory: ChatMessage[], - contextLength: number, - tokensForCompletion: number, + inputTokensAvailable: number, ): ChatMessage[] { - let totalTokens = - tokensForCompletion + - chatHistory.reduce((acc, message) => { - return acc + countChatMessageTokens(modelName, message); - }, 0); - - // 0. Prune any messages that take up more than 1/3 of the context length - const zippedMessagesAndTokens: [ChatMessage, number][] = []; - - // Zipped ChatMessage with its token counts - chatHistory.forEach((message) => { - const zippedItem: [ChatMessage, number] = [ - message, - countTokens(message.content, modelName), - ]; - zippedMessagesAndTokens.push(zippedItem); + let currentTokens = 0; + const messagesWithTokens = chatHistory.map((message) => { + const tokens = countChatMessageTokens(modelName, message); + currentTokens += tokens; + return { + ...message, + tokens, + }; }); - const zippedLongerThanOneThird = zippedMessagesAndTokens.filter( - ([_message, tokens]: [ChatMessage, number]) => tokens > contextLength / 3, - ); + const sysMessage = messagesWithTokens.find((msg) => msg.role === "system"); + const sysMessageTokens = sysMessage?.tokens ?? 0; - zippedLongerThanOneThird.sort( - ( - [_messageA, tokensA]: [ChatMessage, number], - [_messageB, tokensB]: [ChatMessage, number], - ) => { - return tokensB - tokensA; - }, - ); + const lastUserMessage = messagesWithTokens.at(-1); + // if (lastMessage?.role === "user") + // General strategy: + // Walk from the oldest messages forward to last 5, removing while still above token limit + // Once at the last 5, attempt to summarize if summarizable + // Then, double check no latent tool responses that don't have their preceding calls + // Until under token count - const longerThanOneThird = zippedLongerThanOneThird.map( - ([message, _token]: [ChatMessage, number]) => message, - ); - const distanceFromThird = zippedLongerThanOneThird.map( - ([_message, token]: [ChatMessage, number]) => token - contextLength / 3, - ); - - for (let i = 0; i < longerThanOneThird.length; i++) { - // Prune line-by-line from the top - const message = longerThanOneThird[i]; - const content = renderChatMessage(message); - const deltaNeeded = totalTokens - contextLength; - const delta = Math.min(deltaNeeded, distanceFromThird[i]); - message.content = pruneStringFromTop( - modelName, - countTokens(message.content, modelName) - delta, - content, - ); - totalTokens -= delta; + // 1. Remove entire messages until the last 5 + while ( + messagesWithTokens.length > 5 && + currentTokens > inputTokensAvailable + ) { + const message = messagesWithTokens.shift()!; + currentTokens -= message.tokens; } - // 1. Replace beyond last 5 messages with summary - let i = 0; - while (totalTokens > contextLength && i < chatHistory.length - 5) { - const message = chatHistory[i]; - totalTokens -= countTokens(message.content, modelName); - totalTokens += countTokens(summarize(message), modelName); - message.content = summarize(message); - i++; - } - - // 2. Remove entire messages until the last 5 - while (chatHistory.length > 5 && totalTokens > contextLength) { - const message = chatHistory.shift()!; - totalTokens -= countTokens(message.content, modelName); + // At this point make sure no latent tool response without corresponding call + while (messagesWithTokens[0]?.role === "tool") { + const message = messagesWithTokens.shift()!; + currentTokens -= message.tokens; } // 3. Truncate message in the last 5, except last 1 - i = 0; + let i = 0; while ( - totalTokens > contextLength && - chatHistory.length > 0 && - i < chatHistory.length - 1 + totalTokens > inputTokensAvailable && + messagesWithTokens.length > 0 && + i < messagesWithTokens.length - 1 ) { - const message = chatHistory[i]; - totalTokens -= countTokens(message.content, modelName); + const message = messagesWithTokens[i]; + totalTokens -= message.tokens; totalTokens += countTokens(summarize(message), modelName); message.content = summarize(message); i++; } // 4. Remove entire messages in the last 5, except last 1 - while (totalTokens > contextLength && chatHistory.length > 1) { + while (totalTokens > inputTokensAvailable && messagesWithTokens.length > 1) { // If tool call/response detected prune both (can't have response with no call) // TODO prune lines from tool response before pruning both messages if ( - chatHistory.length > 2 && - messageHasToolCalls(chatHistory[0]) && - chatHistory[1].role === "tool" + messagesWithTokens.length > 2 && + messageHasToolCalls(messagesWithTokens[0]) && + messagesWithTokens[1].role === "tool" ) { - const firstMessage = chatHistory.shift()!; - const secondMessage = chatHistory.shift()!; - totalTokens -= countTokens(firstMessage.content, modelName); - totalTokens -= countTokens(secondMessage.content, modelName); + const firstMessage = messagesWithTokens.shift()!; + const secondMessage = messagesWithTokens.shift()!; + totalTokens -= firstMessage.tokens; + totalTokens -= secondMessage.tokens; } else { - const message = chatHistory.shift()!; - totalTokens -= countTokens(message.content, modelName); + const message = messagesWithTokens.shift()!; + totalTokens -= message.tokens; } } - // 5. Truncate last message - if (totalTokens > contextLength && chatHistory.length > 0) { - const message = chatHistory[0]; - message.content = pruneRawPromptFromTop( - modelName, - contextLength, - renderChatMessage(message), - tokensForCompletion, + if (currentTokens > inputTokensAvailable) { + throw new Error( + "Unable to prune chat history to fit into model's context window", ); - totalTokens = contextLength; } - return chatHistory; + + if (messagesWithTokens.length === 0) { + throw new Error("Error processing chat history"); + } + + return messagesWithTokens.map((msg) => { + const { tokens, ...rest } = msg; + return rest; + }); } function messageIsEmpty(message: ChatMessage): boolean { @@ -515,7 +566,6 @@ function compileChatMessages({ contextLength, maxTokens, supportsImages, - prompt, tools, systemMessage, rules, @@ -525,11 +575,22 @@ function compileChatMessages({ contextLength: number; maxTokens: number; supportsImages: boolean; - prompt: string | undefined; tools: Tool[] | undefined; systemMessage: string | undefined; rules: Rule[]; }): ChatMessage[] { + let toolTokens = 0; + if (tools) { + toolTokens = countToolsTokens(tools, modelName); + } + + const safetyBuffer = getTokenBufferSafety(contextLength); + if (toolTokens + maxTokens + safetyBuffer >= contextLength) { + throw new Error( + `maxTokens (${maxTokens}) is too close to contextLength (${contextLength}), which doesn't leave room for response.${toolTokens ? toolTokens + "tools tokens included in the request may also cause this issue" : ""}`, + ); + } + let msgsCopy = msgs ? msgs .map((msg) => ({ ...msg })) @@ -538,14 +599,6 @@ function compileChatMessages({ msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy); - if (prompt) { - const promptMsg: ChatMessage = { - role: "user", - content: prompt, - }; - msgsCopy.push(promptMsg); - } - const lastUserMessage = getLastUserMessage(msgsCopy); msgsCopy = addSystemMessage({ @@ -560,19 +613,6 @@ function compileChatMessages({ originalMessages: msgs, }); - let functionTokens = 0; - if (functions) { - for (const func of functions) { - functionTokens += countTokens(JSON.stringify(func), modelName); - } - } - - if (maxTokens + functionTokens + TOKEN_BUFFER_FOR_SAFETY >= contextLength) { - throw new Error( - `maxTokens (${maxTokens}) is too close to contextLength (${contextLength}), which doesn't leave room for response. Try increasing the contextLength parameter of the model in your config.json.`, - ); - } - // If images not supported, convert MessagePart[] to string if (!supportsImages) { for (const msg of msgsCopy) { @@ -586,8 +626,7 @@ function compileChatMessages({ const history = pruneChatHistory( modelName, msgsCopy, - contextLength, - functionTokens + maxTokens + TOKEN_BUFFER_FOR_SAFETY, + contextLength - toolTokens - maxTokens - safetyBuffer, ); if (history.length >= 2 && history[history.length - 2].role === "system") { diff --git a/core/llm/index.ts b/core/llm/index.ts index 0c79c6974..c53653aed 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -891,7 +891,6 @@ export abstract class BaseLLM implements ILLM { contextLength: this.contextLength, maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS, supportsImages: this.supportsImages(), - prompt: undefined, tools: options.tools, systemMessage: this.systemMessage, rules: this.rules ?? [], diff --git a/core/tools/builtIn.ts b/core/tools/builtIn.ts index 7cff1c70e..7afd88615 100644 --- a/core/tools/builtIn.ts +++ b/core/tools/builtIn.ts @@ -16,3 +16,5 @@ export enum BuiltInToolNames { } export const BUILT_IN_GROUP_NAME = "Built-In"; + +export const CLIENT_TOOLS = [BuiltInToolNames.EditExistingFile]; diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index 28a8f8c30..524fbaf47 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -12,6 +12,7 @@ import { readFileImpl } from "./implementations/readFile"; import { runTerminalCommandImpl } from "./implementations/runTerminalCommand"; import { searchWebImpl } from "./implementations/searchWeb"; import { viewDiffImpl } from "./implementations/viewDiff"; +import { toolErrorContextItem } from "./toolError"; async function callHttpTool( url: string, @@ -129,38 +130,54 @@ async function callToolFromUri( } } +// Handles calls for core/non-client tools +// Returns an error context item if the tool call fails export async function callTool( tool: Tool, - args: any, + callArgs: string, extras: ToolExtras, ): Promise { + const args = JSON.parse(callArgs || "{}"); const uri = tool.uri ?? tool.function.name; - - switch (uri) { - case BuiltInToolNames.ReadFile: - return await readFileImpl(args, extras); - // Note: Custom GUI handling for edit - case BuiltInToolNames.CreateNewFile: - return await createNewFileImpl(args, extras); - case BuiltInToolNames.GrepSearch: - return await grepSearchImpl(args, extras); - case BuiltInToolNames.FileGlobSearch: - return await fileGlobSearchImpl(args, extras); - case BuiltInToolNames.RunTerminalCommand: - return await runTerminalCommandImpl(args, extras); - case BuiltInToolNames.SearchWeb: - return await searchWebImpl(args, extras); - case BuiltInToolNames.ViewDiff: - return await viewDiffImpl(args, extras); - case BuiltInToolNames.LSTool: - return await lsToolImpl(args, extras); - case BuiltInToolNames.ReadCurrentlyOpenFile: - return await readCurrentlyOpenFileImpl(args, extras); - // case BuiltInToolNames.ViewRepoMap: - // return await viewRepoMapImpl(args, extras); - // case BuiltInToolNames.ViewSubdirectory: - // return await viewSubdirectoryImpl(args, extras); - default: - return await callToolFromUri(uri, args, extras); + try { + let contextItems: ContextItem[] = []; + switch (uri) { + case BuiltInToolNames.ReadFile: + contextItems = await readFileImpl(args, extras); + case BuiltInToolNames.CreateNewFile: + contextItems = await createNewFileImpl(args, extras); + case BuiltInToolNames.GrepSearch: + contextItems = await grepSearchImpl(args, extras); + case BuiltInToolNames.FileGlobSearch: + contextItems = await fileGlobSearchImpl(args, extras); + case BuiltInToolNames.RunTerminalCommand: + contextItems = await runTerminalCommandImpl(args, extras); + case BuiltInToolNames.SearchWeb: + contextItems = await searchWebImpl(args, extras); + case BuiltInToolNames.ViewDiff: + contextItems = await viewDiffImpl(args, extras); + case BuiltInToolNames.LSTool: + contextItems = await lsToolImpl(args, extras); + case BuiltInToolNames.ReadCurrentlyOpenFile: + contextItems = await readCurrentlyOpenFileImpl(args, extras); + // case BuiltInToolNames.ViewRepoMap: + // contextItems = await viewRepoMapImpl(args, extras); + // case BuiltInToolNames.ViewSubdirectory: + // contextItems = await viewSubdirectoryImpl(args, extras); + default: + contextItems = await callToolFromUri(uri, args, extras); + } + if (tool.faviconUrl) { + contextItems.forEach((item) => { + item.icon = tool.faviconUrl; + }); + } + return contextItems; + } catch (e) { + let errorMessage = `${e}`; + if (e instanceof Error) { + errorMessage = e.message; + } + return [toolErrorContextItem(uri, errorMessage)]; } } diff --git a/core/tools/toolError.ts b/core/tools/toolError.ts new file mode 100644 index 000000000..5cffc25d5 --- /dev/null +++ b/core/tools/toolError.ts @@ -0,0 +1,14 @@ +import { ContextItem } from ".."; + +export const toolErrorContextItem = ( + functionName: string, + errorMessage: string, +): ContextItem => { + return { + icon: "problems", + name: "Tool Call Error", + description: "Tool Call Failed", + content: `${functionName} failed with the message:\n\n${errorMessage}\n\nPlease try something else or request further instructions.`, + hidden: false, + }; +}; diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 108520e49..19b4e5384 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.21", + "version": "1.1.22", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.21", + "version": "1.1.22", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", @@ -106,7 +106,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.71", + "@continuedev/config-yaml": "^1.0.77", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", diff --git a/gui/src/redux/thunks/callTool.ts b/gui/src/redux/thunks/callTool.ts index bf15e7ae8..d75fa5897 100644 --- a/gui/src/redux/thunks/callTool.ts +++ b/gui/src/redux/thunks/callTool.ts @@ -58,7 +58,7 @@ export const callTool = createAsyncThunk( toolCallState.toolCallId, ); } catch (e) { - errorMessage = "Failed to call edit tool"; + errorMessage = `Failed to call ${toolCallState.toolCall.function.name} tool`; if (e instanceof Error) { errorMessage = e.message; } @@ -92,15 +92,7 @@ export const callTool = createAsyncThunk( const wrapped = await dispatch( streamResponseAfterToolCall({ toolCallId: toolCallState.toolCallId, - toolOutput: [ - { - icon: "problems", - name: "Tool Call Error", - description: "Tool Call Failed", - content: `${toolCallState.toolCall.function.name} failed with the message:\n\n${errorMessage}\n\nPlease try something else or request further instructions.`, - hidden: false, - }, - ], + toolOutput: [], }), ); unwrapResult(wrapped); From 4e55b7e06ea6aecf6067745251a6fff73d57d754 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 22 Apr 2025 12:08:26 -0700 Subject: [PATCH 03/11] client tool rearchitecture --- core/core.ts | 30 +++------ gui/src/redux/store.ts | 17 ++++- gui/src/redux/thunks/callTool.ts | 77 +++++----------------- gui/src/util/clientTools/callClientTool.ts | 45 +++++++++++++ gui/src/util/clientTools/editImpl.ts | 41 ++++++++++++ 5 files changed, 125 insertions(+), 85 deletions(-) create mode 100644 gui/src/util/clientTools/callClientTool.ts create mode 100644 gui/src/util/clientTools/editImpl.ts diff --git a/core/core.ts b/core/core.ts index c3a2d25b9..27edd993a 100644 --- a/core/core.ts +++ b/core/core.ts @@ -696,15 +696,6 @@ export class Core { throw new Error("No chat model selected"); } -<<<<<<< HEAD - const contextItems = await callTool(tool, toolCall.function.arguments, { - ide: this.ide, - llm, - fetch: (url, init) => - fetchwithRequestOptions(url, init, config.requestOptions), - tool, - }); -======= // Define a callback for streaming output updates const onPartialOutput = (params: { toolCallId: string; @@ -713,26 +704,21 @@ export class Core { this.messenger.send("toolCallPartialOutput", params); }; - const contextItems = await callTool( + const contextItems = await callTool(tool, toolCall.function.arguments, { + ide: this.ide, + llm: config.selectedModelByRole.chat, + fetch: (url, init) => + fetchwithRequestOptions(url, init, config.requestOptions), tool, - JSON.parse(toolCall.function.arguments || "{}"), - { - ide: this.ide, - llm: config.selectedModelByRole.chat, - fetch: (url, init) => - fetchwithRequestOptions(url, init, config.requestOptions), - tool, - toolCallId: toolCall.id, - onPartialOutput, - }, - ); + toolCallId: toolCall.id, + onPartialOutput, + }); if (tool.faviconUrl) { contextItems.forEach((item) => { item.icon = tool.faviconUrl; }); } ->>>>>>> b8c92f26cad325ff79eca6b5d01fd4ac47b4a88f return { contextItems }; }, diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index c69e65315..4a4d939c0 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -1,4 +1,9 @@ -import { combineReducers, configureStore } from "@reduxjs/toolkit"; +import { + combineReducers, + configureStore, + ThunkDispatch, + UnknownAction, +} from "@reduxjs/toolkit"; import { createLogger } from "redux-logger"; import { createMigrate, @@ -130,11 +135,19 @@ export function setupStore() { }); } +export type ThunkExtrasType = { ideMessenger: IIdeMessenger }; + export type ThunkApiType = { state: RootState; - extra: { ideMessenger: IIdeMessenger }; + extra: ThunkExtrasType; }; +export type AppThunkDispatch = ThunkDispatch< + RootState, + ThunkExtrasType, + UnknownAction +>; + export const store = setupStore(); export type RootState = ReturnType; diff --git a/gui/src/redux/thunks/callTool.ts b/gui/src/redux/thunks/callTool.ts index 99ac82bab..afd44362f 100644 --- a/gui/src/redux/thunks/callTool.ts +++ b/gui/src/redux/thunks/callTool.ts @@ -1,9 +1,7 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { ContextItem } from "core"; -import { BuiltInToolNames } from "core/tools/builtIn"; -import { EditToolArgs } from "core/tools/definitions/editFile"; -import { resolveRelativePathInDir } from "core/util/ideUtils"; -import { IIdeMessenger } from "../../context/IdeMessenger"; +import { CLIENT_TOOLS } from "core/tools/builtIn"; +import { callClientTool } from "../../util/clientTools/callClientTool"; import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; import { selectSelectedChatModel } from "../slices/configSlice"; import { @@ -11,7 +9,6 @@ import { cancelToolCall, setCalling, setToolCallOutput, - updateApplyState, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; @@ -38,43 +35,25 @@ export const callTool = createAsyncThunk( dispatch(setCalling()); - let errorMessage = ""; + let errorMessage: string | undefined = ""; let output: ContextItem[] | undefined = undefined; if ( - toolCallState.toolCall.function.name === BuiltInToolNames.EditExistingFile + CLIENT_TOOLS.find( + (toolName) => toolName === toolCallState.toolCall.function.name, + ) ) { - const args = JSON.parse( - toolCallState.toolCall.function.arguments || "{}", - ); - try { - if (!state.session.activeToolStreamId) { - throw new Error("Invalid apply state"); - } - await customGuiEditImpl( - args, - extra.ideMessenger, - state.session.activeToolStreamId[0], - toolCallState.toolCallId, - ); - } catch (e) { - errorMessage = `Failed to call ${toolCallState.toolCall.function.name} tool`; - if (e instanceof Error) { - errorMessage = e.message; - } - if (state.session.activeToolStreamId?.[0]) { - dispatch( - updateApplyState({ - streamId: state.session.activeToolStreamId[0], - status: "closed", - toolCallId: toolCallState.toolCallId, - numDiffs: 0, - filepath: args.filepath, - }), - ); - } - } + // Tool is called on client side + const { errorMessage: clientErrorMessage, output: clientOutput } = + await callClientTool(toolCallState.toolCall, { + dispatch, + ideMessenger: extra.ideMessenger, + activeToolStreamId: state.session.activeToolStreamId?.[0], + }); + output = clientOutput; + errorMessage = clientErrorMessage; } else { + // Tool is called on core side const result = await extra.ideMessenger.request("tools/call", { toolCall: toolCallState.toolCall, selectedModelTitle: selectedChatModel.title, @@ -112,27 +91,3 @@ export const callTool = createAsyncThunk( // okay for a tool to have no output and need some GUI trigger or other to trigger response e.g. edit tool }, ); - -async function customGuiEditImpl( - args: EditToolArgs, - ideMessenger: IIdeMessenger, - streamId: string, - toolCallId: string, -) { - const firstUriMatch = await resolveRelativePathInDir( - args.filepath, - ideMessenger.ide, - ); - if (!firstUriMatch) { - throw new Error(`${args.filepath} does not exist`); - } - const apply = await ideMessenger.request("applyToFile", { - streamId, - text: args.new_contents, - toolCallId, - filepath: firstUriMatch, - }); - if (apply.status === "error") { - throw new Error(apply.error); - } -} diff --git a/gui/src/util/clientTools/callClientTool.ts b/gui/src/util/clientTools/callClientTool.ts new file mode 100644 index 000000000..44bb7aadc --- /dev/null +++ b/gui/src/util/clientTools/callClientTool.ts @@ -0,0 +1,45 @@ +import { ContextItem, ToolCall } from "core"; +import { BuiltInToolNames } from "core/tools/builtIn"; +import { IIdeMessenger } from "../../context/IdeMessenger"; +import { AppThunkDispatch } from "../../redux/store"; +import { editToolImpl } from "./editImpl"; + +export interface ClientToolExtras { + dispatch: AppThunkDispatch; + ideMessenger: IIdeMessenger; + activeToolStreamId?: string; +} + +export interface ClientToolOutput { + output?: ContextItem[]; + errorMessage?: string; +} + +export type ClientToolImpl = ( + args: any, + toolCallId: string, + extras: ClientToolExtras, +) => Promise; + +export async function callClientTool( + toolCall: ToolCall, + extras: ClientToolExtras, +): Promise { + const args = JSON.parse(toolCall.function.arguments || "{}"); + let output: ContextItem[] | undefined = undefined; + try { + switch (toolCall.function.name) { + case BuiltInToolNames.EditExistingFile: + output = await editToolImpl(args, toolCall.id, extras); + default: + throw new Error(`Invalid client tool name ${toolCall.function.name}`); + } + return { output }; + } catch (e) { + let errorMessage = `Failed to call ${toolCall.function.name} tool`; + if (e instanceof Error) { + errorMessage = e.message; + } + return { errorMessage }; + } +} diff --git a/gui/src/util/clientTools/editImpl.ts b/gui/src/util/clientTools/editImpl.ts new file mode 100644 index 000000000..f4956e87e --- /dev/null +++ b/gui/src/util/clientTools/editImpl.ts @@ -0,0 +1,41 @@ +import { resolveRelativePathInDir } from "core/util/ideUtils"; +import { updateApplyState } from "../../redux/slices/sessionSlice"; +import { ClientToolImpl } from "./callClientTool"; + +export const editToolImpl: ClientToolImpl = async ( + args, + toolCallId, + extras, +) => { + if (!extras.activeToolStreamId) { + throw new Error("Invalid apply state"); + } + const firstUriMatch = await resolveRelativePathInDir( + args.filepath, + extras.ideMessenger.ide, + ); + if (!firstUriMatch) { + throw new Error(`${args.filepath} does not exist`); + } + const apply = await extras.ideMessenger.request("applyToFile", { + streamId: extras.activeToolStreamId, + text: args.new_contents, + toolCallId, + filepath: firstUriMatch, + }); + if (apply.status === "error") { + throw new Error(apply.error); + } + if (extras.activeToolStreamId) { + extras.dispatch( + updateApplyState({ + streamId: extras.activeToolStreamId, + status: "closed", + toolCallId, + numDiffs: 0, + filepath: args.filepath, + }), + ); + } + return undefined; +}; From 05a90d18af28909fa45ec16227168b9a97881bef Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 22 Apr 2025 12:13:18 -0700 Subject: [PATCH 04/11] remove selectedmodeltitle --- core/core.ts | 80 +++++++++---------- core/protocol/core.ts | 12 +-- .../mainInput/AtMentionDropdown/index.tsx | 6 -- .../utils/resolveEditorContent.ts | 8 -- gui/src/pages/gui/Chat.tsx | 6 +- gui/src/redux/thunks/callTool.ts | 1 - gui/src/redux/thunks/gatherContext.ts | 2 - gui/src/redux/thunks/session.ts | 1 - 8 files changed, 42 insertions(+), 74 deletions(-) diff --git a/core/core.ts b/core/core.ts index 27edd993a..7982e729c 100644 --- a/core/core.ts +++ b/core/core.ts @@ -676,55 +676,52 @@ export class Core { } }); - on( - "tools/call", - async ({ data: { toolCall, selectedModelTitle }, messageId }) => { - const { config } = await this.configHandler.loadConfig(); - if (!config) { - throw new Error("Config not loaded"); - } + on("tools/call", async ({ data: { toolCall } }) => { + const { config } = await this.configHandler.loadConfig(); + if (!config) { + throw new Error("Config not loaded"); + } - const tool = config.tools.find( - (t) => t.function.name === toolCall.function.name, - ); + const tool = config.tools.find( + (t) => t.function.name === toolCall.function.name, + ); - if (!tool) { - throw new Error(`Tool ${toolCall.function.name} not found`); - } + if (!tool) { + throw new Error(`Tool ${toolCall.function.name} not found`); + } - if (!config.selectedModelByRole.chat) { - throw new Error("No chat model selected"); - } + if (!config.selectedModelByRole.chat) { + throw new Error("No chat model selected"); + } - // Define a callback for streaming output updates - const onPartialOutput = (params: { - toolCallId: string; - contextItems: ContextItem[]; - }) => { - this.messenger.send("toolCallPartialOutput", params); - }; + // Define a callback for streaming output updates + const onPartialOutput = (params: { + toolCallId: string; + contextItems: ContextItem[]; + }) => { + this.messenger.send("toolCallPartialOutput", params); + }; - const contextItems = await callTool(tool, toolCall.function.arguments, { - ide: this.ide, - llm: config.selectedModelByRole.chat, - fetch: (url, init) => - fetchwithRequestOptions(url, init, config.requestOptions), - tool, - toolCallId: toolCall.id, - onPartialOutput, + const contextItems = await callTool(tool, toolCall.function.arguments, { + ide: this.ide, + llm: config.selectedModelByRole.chat, + fetch: (url, init) => + fetchwithRequestOptions(url, init, config.requestOptions), + tool, + toolCallId: toolCall.id, + onPartialOutput, + }); + + if (tool.faviconUrl) { + contextItems.forEach((item) => { + item.icon = tool.faviconUrl; }); + } - if (tool.faviconUrl) { - contextItems.forEach((item) => { - item.icon = tool.faviconUrl; - }); - } + return { contextItems }; + }); - return { contextItems }; - }, - ); - - on("isItemTooBig", async ({ data: { item, selectedModelTitle } }) => { + on("isItemTooBig", async ({ data: { item } }) => { return this.isItemTooBig(item); }); @@ -922,7 +919,6 @@ export class Core { query: string; fullInput: string; selectedCode: RangeInFile[]; - selectedModelTitle: string; }>, ) => { const { config } = await this.configHandler.loadConfig(); diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 38a51c098..f71c17071 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -101,7 +101,6 @@ export type ToCoreFromIdeOrWebviewProtocol = { query: string; fullInput: string; selectedCode: RangeInFile[]; - selectedModelTitle: string; }, ContextItemWithId[], ]; @@ -156,7 +155,6 @@ export type ToCoreFromIdeOrWebviewProtocol = { ]; "chatDescriber/describe": [ { - selectedModelTitle: string; text: string; }, string | undefined, @@ -202,16 +200,10 @@ export type ToCoreFromIdeOrWebviewProtocol = { addAutocompleteModel: [{ model: ModelDescription }, void]; "auth/getAuthUrl": [{ useOnboarding: boolean }, { url: string }]; - "tools/call": [ - { toolCall: ToolCall; selectedModelTitle: string }, - { contextItems: ContextItem[] }, - ]; + "tools/call": [{ toolCall: ToolCall }, { contextItems: ContextItem[] }]; "clipboardCache/add": [{ content: string }, void]; "controlPlane/openUrl": [{ path: string; orgSlug: string | undefined }, void]; - isItemTooBig: [ - { item: ContextItemWithId; selectedModelTitle: string | undefined }, - boolean, - ]; + isItemTooBig: [{ item: ContextItemWithId }, boolean]; didChangeControlPlaneSessionInfo: [ { sessionInfo: ControlPlaneSessionInfo | undefined }, void, diff --git a/gui/src/components/mainInput/AtMentionDropdown/index.tsx b/gui/src/components/mainInput/AtMentionDropdown/index.tsx index 9d5a10bec..999bdeb75 100644 --- a/gui/src/components/mainInput/AtMentionDropdown/index.tsx +++ b/gui/src/components/mainInput/AtMentionDropdown/index.tsx @@ -25,8 +25,6 @@ import { vscQuickInputBackground, } from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { useAppSelector } from "../../../redux/hooks"; -import { selectSelectedChatModel } from "../../../redux/slices/configSlice"; import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice"; import { fontSize } from "../../../util"; import FileIcon from "../../FileIcon"; @@ -162,8 +160,6 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => { const ideMessenger = useContext(IdeMessengerContext); - const selectedModelTitle = useAppSelector(selectSelectedChatModel); - const [selectedIndex, setSelectedIndex] = useState(0); const [subMenuTitle, setSubMenuTitle] = useState( @@ -191,7 +187,6 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => { query, fullInput: "", selectedCode, - selectedModelTitle: selectedModelTitle?.title ?? "", }, ); @@ -204,7 +199,6 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => { // Check if the context item exceeds the context length of the selected model const result = await ideMessenger.request("isItemTooBig", { item, - selectedModelTitle: selectedModelTitle?.title, }); if (result.status === "error") { diff --git a/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts b/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts index ad7858a0a..6ff74eb2c 100644 --- a/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts @@ -33,7 +33,6 @@ interface ResolveEditorContentInput { ideMessenger: IIdeMessenger; defaultContextProviders: DefaultContextProvider[]; availableSlashCommands: SlashCommandDescription[]; - selectedModelTitle: string; dispatch: Dispatch; } @@ -60,7 +59,6 @@ export async function resolveEditorContent({ ideMessenger, defaultContextProviders, availableSlashCommands, - selectedModelTitle, dispatch, }: ResolveEditorContentInput): Promise { const { parts, contextItemAttrs, selectedCode, slashCommandName } = @@ -84,7 +82,6 @@ export async function resolveEditorContent({ defaultContextProviders, parts, selectedCode, - selectedModelTitle, }); if (shouldGatherContext) { @@ -236,7 +233,6 @@ async function gatherContextItems({ defaultContextProviders, parts, selectedCode, - selectedModelTitle, }: { contextItemAttrs: MentionAttrs[]; modifiers: InputModifiers; @@ -244,7 +240,6 @@ async function gatherContextItems({ defaultContextProviders: DefaultContextProvider[]; parts: MessagePart[]; selectedCode: RangeInFile[]; - selectedModelTitle: string; }): Promise { let contextItems: ContextItemWithId[] = []; @@ -255,7 +250,6 @@ async function gatherContextItems({ query: item.query ?? "", fullInput: stripImages(parts), selectedCode, - selectedModelTitle, }); if (result.status === "success") { contextItems.push(...result.content); @@ -269,7 +263,6 @@ async function gatherContextItems({ query: "", fullInput: stripImages(parts), selectedCode, - selectedModelTitle, }); if (result.status === "success") { @@ -285,7 +278,6 @@ async function gatherContextItems({ query: provider.query ?? "", fullInput: stripImages(parts), selectedCode, - selectedModelTitle, }); if (result.status === "success") { return result.content; diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 8a76cdbf9..3028206ee 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -246,7 +246,6 @@ export function Chat() { defaultContextProviders: [], availableSlashCommands: [], dispatch, - selectedModelTitle: selectedChatModel.title, }); const prompt = [ @@ -340,9 +339,8 @@ export function Chat() { inputId={item.message.id} /> - ) : item.message.role === "tool" ? null : // item.message.role === "assistant" && item.message.toolCalls && diff --git a/gui/src/redux/thunks/callTool.ts b/gui/src/redux/thunks/callTool.ts index afd44362f..643e6c483 100644 --- a/gui/src/redux/thunks/callTool.ts +++ b/gui/src/redux/thunks/callTool.ts @@ -56,7 +56,6 @@ export const callTool = createAsyncThunk( // Tool is called on core side const result = await extra.ideMessenger.request("tools/call", { toolCall: toolCallState.toolCall, - selectedModelTitle: selectedChatModel.title, }); if (result.status === "error") { errorMessage = result.error; diff --git a/gui/src/redux/thunks/gatherContext.ts b/gui/src/redux/thunks/gatherContext.ts index 2ba244d3f..4b8f00286 100644 --- a/gui/src/redux/thunks/gatherContext.ts +++ b/gui/src/redux/thunks/gatherContext.ts @@ -58,7 +58,6 @@ export const gatherContext = createAsyncThunk< defaultContextProviders, availableSlashCommands: state.config.config.slashCommands, dispatch, - selectedModelTitle: selectedChatModel.title, }); // Automatically use currently open file @@ -72,7 +71,6 @@ export const gatherContext = createAsyncThunk< query: "non-mention-usage", fullInput: "", selectedCode: [], - selectedModelTitle: selectedChatModel.title, }, ); if (currentFileResponse.status === "success") { diff --git a/gui/src/redux/thunks/session.ts b/gui/src/redux/thunks/session.ts index 7572b1fe4..e9c0bffe8 100644 --- a/gui/src/redux/thunks/session.ts +++ b/gui/src/redux/thunks/session.ts @@ -180,7 +180,6 @@ export const saveCurrentSession = createAsyncThunk< "chatDescriber/describe", { text: assistantResponse, - selectedModelTitle: selectedChatModel.title, }, ); if (result.status === "success" && result.content) { From bfb4d413249fdd0e0a17f7d865328abf7e747829 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 22 Apr 2025 13:46:00 -0700 Subject: [PATCH 05/11] tool error makeover --- core/config/types.ts | 1 + core/core.ts | 10 +- core/index.d.ts | 1 + core/llm/constructMessages.ts | 17 +-- core/protocol/core.ts | 5 +- core/tools/callTool.ts | 32 +++-- core/tools/toolError.ts | 14 -- gui/src/components/mainInput/InputToolbar.tsx | 20 --- .../components/mainInput/Lump/LumpToolbar.tsx | 12 +- gui/src/hooks/useSetup.ts | 39 ++--- gui/src/pages/gui/ToolCallDiv/ToolCall.tsx | 5 +- gui/src/pages/gui/ToolCallDiv/index.tsx | 1 + gui/src/redux/slices/sessionSlice.ts | 130 +++++++++++------ gui/src/redux/thunks/callCurrentTool.ts | 133 ++++++++++++++++++ gui/src/redux/thunks/callTool.ts | 92 ------------ gui/src/redux/thunks/cancelCurrentToolCall.ts | 50 +++++++ gui/src/redux/thunks/cancelTool.ts | 39 ----- .../thunks/moveTerminalProcessToBackground.ts | 104 ++++++++------ gui/src/redux/thunks/streamNormalInput.ts | 10 +- .../thunks/streamResponseAfterToolCall.ts | 18 ++- gui/src/redux/util/index.ts | 13 +- gui/src/util/clientTools/callClientTool.ts | 28 ++-- gui/src/util/clientTools/editImpl.ts | 5 +- 23 files changed, 446 insertions(+), 333 deletions(-) delete mode 100644 core/tools/toolError.ts create mode 100644 gui/src/redux/thunks/callCurrentTool.ts delete mode 100644 gui/src/redux/thunks/callTool.ts create mode 100644 gui/src/redux/thunks/cancelCurrentToolCall.ts delete mode 100644 gui/src/redux/thunks/cancelTool.ts diff --git a/core/config/types.ts b/core/config/types.ts index f168bcbaa..690f17165 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -403,6 +403,7 @@ declare global { | "generated" | "calling" | "done" + | "errored" | "canceled"; // Will exist only on "assistant" messages with tool calls diff --git a/core/core.ts b/core/core.ts index 7982e729c..82a924589 100644 --- a/core/core.ts +++ b/core/core.ts @@ -702,7 +702,7 @@ export class Core { this.messenger.send("toolCallPartialOutput", params); }; - const contextItems = await callTool(tool, toolCall.function.arguments, { + return await callTool(tool, toolCall.function.arguments, { ide: this.ide, llm: config.selectedModelByRole.chat, fetch: (url, init) => @@ -711,14 +711,6 @@ export class Core { toolCallId: toolCall.id, onPartialOutput, }); - - if (tool.faviconUrl) { - contextItems.forEach((item) => { - item.icon = tool.faviconUrl; - }); - } - - return { contextItems }; }); on("isItemTooBig", async ({ data: { item } }) => { diff --git a/core/index.d.ts b/core/index.d.ts index 2d4a8ffc7..7a1a9ec84 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -428,6 +428,7 @@ export type ToolStatus = | "generating" | "generated" | "calling" + | "errored" | "done" | "canceled"; diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index 950ad2cbe..8947d04c0 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -7,7 +7,6 @@ import { } from "../"; import { findLast } from "../util/findLast"; import { normalizeToMessageParts } from "../util/messageContent"; -import { messageIsEmpty } from "./messages"; import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules"; export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL = @@ -92,12 +91,6 @@ export function constructMessages( ...historyItem.message, content, }); - } else if (historyItem.toolCallState?.status === "canceled") { - // Canceled tool call - msgs.push({ - ...historyItem.message, - content: CANCELED_TOOL_CALL_MESSAGE, - }); } else { msgs.push(historyItem.message); } @@ -119,15 +112,7 @@ export function constructMessages( }); } - // We dispatch an empty assistant chat message to the history on submission. Don't send it - const lastMessage = msgs.at(-1); - if ( - lastMessage && - lastMessage.role === "assistant" && - messageIsEmpty(lastMessage) - ) { - msgs.pop(); - } + // Note, last assistant message is removed on core side // Remove the "id" from all of the messages return msgs.map((msg) => { diff --git a/core/protocol/core.ts b/core/protocol/core.ts index f71c17071..45a01a976 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -200,7 +200,10 @@ export type ToCoreFromIdeOrWebviewProtocol = { addAutocompleteModel: [{ model: ModelDescription }, void]; "auth/getAuthUrl": [{ useOnboarding: boolean }, { url: string }]; - "tools/call": [{ toolCall: ToolCall }, { contextItems: ContextItem[] }]; + "tools/call": [ + { toolCall: ToolCall }, + { contextItems: ContextItem[]; errorMessage?: string }, + ]; "clipboardCache/add": [{ content: string }, void]; "controlPlane/openUrl": [{ path: string; orgSlug: string | undefined }, void]; isItemTooBig: [{ item: ContextItemWithId }, boolean]; diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index 1e401a865..d8eaf4ffd 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -13,7 +13,6 @@ import { readFileImpl } from "./implementations/readFile"; import { runTerminalCommandImpl } from "./implementations/runTerminalCommand"; import { searchWebImpl } from "./implementations/searchWeb"; import { viewDiffImpl } from "./implementations/viewDiff"; -import { toolErrorContextItem } from "./toolError"; async function callHttpTool( url: string, @@ -138,7 +137,10 @@ export async function callTool( tool: Tool, callArgs: string, extras: ToolExtras, -): Promise { +): Promise<{ + contextItems: ContextItem[]; + errorMessage: string | undefined; +}> { const args = JSON.parse(callArgs || "{}"); const uri = tool.uri ?? tool.function.name; try { @@ -146,28 +148,34 @@ export async function callTool( switch (uri) { case BuiltInToolNames.ReadFile: contextItems = await readFileImpl(args, extras); + break; case BuiltInToolNames.CreateNewFile: contextItems = await createNewFileImpl(args, extras); + break; case BuiltInToolNames.GrepSearch: contextItems = await grepSearchImpl(args, extras); + break; case BuiltInToolNames.FileGlobSearch: contextItems = await fileGlobSearchImpl(args, extras); + break; case BuiltInToolNames.RunTerminalCommand: contextItems = await runTerminalCommandImpl(args, extras); + break; case BuiltInToolNames.SearchWeb: contextItems = await searchWebImpl(args, extras); + break; case BuiltInToolNames.ViewDiff: contextItems = await viewDiffImpl(args, extras); + break; case BuiltInToolNames.LSTool: contextItems = await lsToolImpl(args, extras); + break; case BuiltInToolNames.ReadCurrentlyOpenFile: contextItems = await readCurrentlyOpenFileImpl(args, extras); + break; case BuiltInToolNames.CreateRuleBlock: - return await createRuleBlockImpl(args, extras); - // case BuiltInToolNames.ViewRepoMap: - // contextItems = await viewRepoMapImpl(args, extras); - // case BuiltInToolNames.ViewSubdirectory: - // contextItems = await viewSubdirectoryImpl(args, extras); + contextItems = await createRuleBlockImpl(args, extras); + break; default: contextItems = await callToolFromUri(uri, args, extras); } @@ -176,12 +184,18 @@ export async function callTool( item.icon = tool.faviconUrl; }); } - return contextItems; + return { + contextItems, + errorMessage: undefined, + }; } catch (e) { let errorMessage = `${e}`; if (e instanceof Error) { errorMessage = e.message; } - return [toolErrorContextItem(uri, errorMessage)]; + return { + contextItems: [], + errorMessage, + }; } } diff --git a/core/tools/toolError.ts b/core/tools/toolError.ts deleted file mode 100644 index 5cffc25d5..000000000 --- a/core/tools/toolError.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { ContextItem } from ".."; - -export const toolErrorContextItem = ( - functionName: string, - errorMessage: string, -): ContextItem => { - return { - icon: "problems", - name: "Tool Call Error", - description: "Tool Call Failed", - content: `${functionName} failed with the message:\n\n${errorMessage}\n\nPlease try something else or request further instructions.`, - hidden: false, - }; -}; diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 417267188..1303e96be 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -2,8 +2,6 @@ import { AtSymbolIcon, PhotoIcon } from "@heroicons/react/24/outline"; import { InputModifiers } from "core"; import { modelSupportsImages, modelSupportsTools } from "core/llm/autodetect"; import { useRef } from "react"; -import styled from "styled-components"; -import { vscInputBackground } from ".."; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectUseActiveFile } from "../../redux/selectors"; import { selectCurrentToolCall } from "../../redux/selectors/selectCurrentToolCall"; @@ -16,7 +14,6 @@ import { exitEditMode } from "../../redux/thunks"; import { loadLastSession } from "../../redux/thunks/session"; import { getAltKeyLabel, - getFontSize, getMetaKeyLabel, isMetaEquivalentKeyPressed, } from "../../util"; @@ -27,23 +24,6 @@ import { useFontSize } from "../ui/font"; import { EnterButton } from "./InputToolbar/EnterButton"; import HoverItem from "./InputToolbar/HoverItem"; -const StyledDiv = styled.div<{ isHidden?: boolean }>` - padding-top: 4px; - justify-content: space-between; - gap: 1px; - background-color: ${vscInputBackground}; - align-items: center; - font-size: ${getFontSize() - 2}px; - cursor: ${(props) => (props.isHidden ? "default" : "text")}; - opacity: ${(props) => (props.isHidden ? 0 : 1)}; - pointer-events: ${(props) => (props.isHidden ? "none" : "auto")}; - user-select: none; - - & > * { - flex: 0 0 auto; - } -`; - export interface ToolbarOptions { hideUseCodebase?: boolean; hideImageUpload?: boolean; diff --git a/gui/src/components/mainInput/Lump/LumpToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar.tsx index dd91d4e66..f2e0d8c6f 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar.tsx @@ -5,9 +5,9 @@ import { AnimatedEllipsis } from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; import { selectCurrentToolCall } from "../../../redux/selectors/selectCurrentToolCall"; -import { callTool } from "../../../redux/thunks/callTool"; +import { callCurrentTool } from "../../../redux/thunks/callCurrentTool"; +import { cancelCurrentToolCall } from "../../../redux/thunks/cancelCurrentToolCall"; import { cancelStream } from "../../../redux/thunks/cancelStream"; -import { cancelTool } from "../../../redux/thunks/cancelTool"; import { getFontSize, getMetaKeyLabel } from "../../../util"; import { EnterButton } from "../InputToolbar/EnterButton"; import { BlockSettingsTopToolbar } from "./BlockSettingsTopToolbar"; @@ -50,11 +50,11 @@ export function LumpToolbar() { if (metaKey && event.key === "Enter") { event.preventDefault(); event.stopPropagation(); - dispatch(callTool()); + dispatch(callCurrentTool()); } else if (metaKey && event.key === "Backspace") { event.preventDefault(); event.stopPropagation(); - dispatch(cancelTool()); + dispatch(cancelCurrentToolCall()); } } }; @@ -106,7 +106,7 @@ export function LumpToolbar() {
dispatch(cancelTool())} + onClick={() => dispatch(cancelCurrentToolCall())} data-testid="reject-tool-call-button" > {getMetaKeyLabel()} ⌫ Cancel @@ -114,7 +114,7 @@ export function LumpToolbar() { dispatch(callTool())} + onClick={() => dispatch(callCurrentTool())} data-testid="accept-tool-call-button" > {getMetaKeyLabel()} ⏎ Continue diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index e9d9223a8..b5d8e9685 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -19,7 +19,6 @@ import { acceptToolCall, addContextItemsAtIndex, setInactive, - setToolCallOutput, updateApplyState, } from "../redux/slices/sessionSlice"; import { setTTSActive } from "../redux/slices/uiSlice"; @@ -261,24 +260,26 @@ function useSetup() { "updateApplyState", async (state) => { dispatch(updateApplyState(state)); - if ( - activeToolStreamId && - state.streamId === activeToolStreamId[0] && - state.status === "closed" - ) { - // const output: ContextItem = { - // name: "Edit tool output", - // content: "Completed edit", - // description: "", - // }; - dispatch(acceptToolCall()); - dispatch(setToolCallOutput([])); - dispatch( - streamResponseAfterToolCall({ - toolCallId: activeToolStreamId[1], - toolOutput: [], - }), - ); + if (activeToolStreamId && state.status === "closed") { + const [streamId, toolCallId] = activeToolStreamId; + if (state.streamId === streamId) { + // const output: ContextItem = { + // name: "Edit tool output", + // content: "Completed edit", + // description: "", + // }; + dispatch( + acceptToolCall({ + toolCallId, + }), + ); + // dispatch(setToolCallOutput([])); + dispatch( + streamResponseAfterToolCall({ + toolCallId, + }), + ); + } } }, [activeToolStreamId], diff --git a/gui/src/pages/gui/ToolCallDiv/ToolCall.tsx b/gui/src/pages/gui/ToolCallDiv/ToolCall.tsx index 0abee8f3f..2d823b7f3 100644 --- a/gui/src/pages/gui/ToolCallDiv/ToolCall.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ToolCall.tsx @@ -62,7 +62,10 @@ export function getToolCallStatusMessage( calling the {defaultToolDescription} ); - } else if (toolCallState.status === "canceled") { + } else if ( + toolCallState.status === "canceled" || + toolCallState.status === "errored" + ) { intro = "tried to"; message = futureMessage; } diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index 06cf74515..4bdffccfd 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -56,6 +56,7 @@ export function ToolCallDiv(props: ToolCallDivProps) { case "done": return ; case "canceled": + case "errored": return ; } } diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 7c065a9ae..002b809db 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -29,7 +29,7 @@ import { findUriInDirs, getUriPathBasename } from "core/util/uri"; import { v4 as uuidv4 } from "uuid"; import { RootState } from "../store"; import { streamResponseThunk } from "../thunks/streamResponse"; -import { findCurrentToolCall } from "../util"; +import { findCurrentToolCall, findToolCall } from "../util"; // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array. // The proper fix is adding a UUID to all chat messages, but this is the temp workaround. @@ -624,54 +624,100 @@ export const sessionSlice = createSlice({ clearCodeToEdit: (state) => { state.codeToEdit = []; }, - // Related to currentToolCallState - setToolGenerated: (state) => { - const toolCallState = findCurrentToolCall(state.history); - if (!toolCallState) return; - - toolCallState.status = "generated"; - }, - setToolCallOutput: (state, action: PayloadAction) => { - const toolCallState = findCurrentToolCall(state.history); - if (!toolCallState) return; - - toolCallState.output = action.payload; + // TOOL CALL STATE + setToolGenerated: ( + state, + action: PayloadAction<{ + toolCallId: string; + }>, + ) => { + const toolCallState = findToolCall( + state.history, + action.payload.toolCallId, + ); + if (toolCallState) { + toolCallState.status = "generated"; + } }, updateToolCallOutput: ( state, - action: PayloadAction<{ toolCallId: string; contextItems: ContextItem[] }>, + action: PayloadAction<{ + toolCallId: string; + contextItems: ContextItem[]; + }>, ) => { - // Find the tool call with the given ID and update its output - const { toolCallId, contextItems } = action.payload; - - // Find the history item containing the tool call - const historyItem = state.history.find( - (item) => - item.toolCallState?.toolCallId === toolCallId + const toolCallState = findToolCall( + state.history, + action.payload.toolCallId, ); - - if (historyItem && historyItem.toolCallState) { - historyItem.toolCallState.output = contextItems; + if (toolCallState) { + toolCallState.output = action.payload.contextItems; } }, - cancelToolCall: (state) => { - const toolCallState = findCurrentToolCall(state.history); - if (!toolCallState) return; - - toolCallState.status = "canceled"; + cancelToolCall: ( + state, + action: PayloadAction<{ + toolCallId: string; + }>, + ) => { + if (action.payload.toolCallId === state.activeToolStreamId?.[1]) { + state.activeToolStreamId = undefined; + } + const toolCallState = findToolCall( + state.history, + action.payload.toolCallId, + ); + if (toolCallState) { + toolCallState.status = "canceled"; + } }, - acceptToolCall: (state) => { - state.activeToolStreamId = undefined; - const toolCallState = findCurrentToolCall(state.history); - if (!toolCallState) return; - - toolCallState.status = "done"; + errorToolCall: ( + state, + action: PayloadAction<{ + toolCallId: string; + }>, + ) => { + if (action.payload.toolCallId === state.activeToolStreamId?.[1]) { + state.activeToolStreamId = undefined; + } + const toolCallState = findToolCall( + state.history, + action.payload.toolCallId, + ); + if (toolCallState) { + toolCallState.status = "errored"; + } }, - setCalling: (state) => { - const toolCallState = findCurrentToolCall(state.history); - if (!toolCallState) return; - - toolCallState.status = "calling"; + acceptToolCall: ( + state, + action: PayloadAction<{ + toolCallId: string; + }>, + ) => { + if (action.payload.toolCallId === state.activeToolStreamId?.[1]) { + state.activeToolStreamId = undefined; + } + const toolCallState = findToolCall( + state.history, + action.payload.toolCallId, + ); + if (toolCallState) { + toolCallState.status = "done"; + } + }, + setToolCallCalling: ( + state, + action: PayloadAction<{ + toolCallId: string; + }>, + ) => { + const toolCallState = findToolCall( + state.history, + action.payload.toolCallId, + ); + if (toolCallState) { + toolCallState.status = "calling"; + } }, setMode: (state, action: PayloadAction) => { state.mode = action.payload; @@ -785,11 +831,11 @@ export const { clearCodeToEdit, addCodeToEdit, removeCodeToEdit, - setCalling, + setToolCallCalling, cancelToolCall, + errorToolCall, acceptToolCall, setToolGenerated, - setToolCallOutput, updateToolCallOutput, setMode, setAllSessionMetadata, diff --git a/gui/src/redux/thunks/callCurrentTool.ts b/gui/src/redux/thunks/callCurrentTool.ts new file mode 100644 index 000000000..61795de96 --- /dev/null +++ b/gui/src/redux/thunks/callCurrentTool.ts @@ -0,0 +1,133 @@ +import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; +import { ContextItem } from "core"; +import { CLIENT_TOOLS } from "core/tools/builtIn"; +import { callClientTool } from "../../util/clientTools/callClientTool"; +import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; +import { selectSelectedChatModel } from "../slices/configSlice"; +import { + acceptToolCall, + errorToolCall, + setToolCallCalling, + updateToolCallOutput, +} from "../slices/sessionSlice"; +import { ThunkApiType } from "../store"; +import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; + +export const callCurrentTool = createAsyncThunk( + "chat/callTool", + async (_, { dispatch, extra, getState }) => { + const state = getState(); + const toolCallState = selectCurrentToolCall(state); + + if (!toolCallState) { + return; + } + + if (toolCallState.status !== "generated") { + return; + } + + const selectedChatModel = selectSelectedChatModel(state); + + if (!selectedChatModel) { + throw new Error("No model selected"); + } + + const { toolCallId } = toolCallState; + + dispatch( + setToolCallCalling({ + toolCallId, + }), + ); + + let output: ContextItem[] | undefined = undefined; + let errorMessage: string | undefined = undefined; + let streamResponse: boolean; + + // IMPORTANT: + // Errors that occur while calling tool call implementations + // Are caught and passed in output as context items + // Errors that occur outside specifically calling the tool + // Should not be caught here - should be handled as normal stream errors + if ( + CLIENT_TOOLS.find( + (toolName) => toolName === toolCallState.toolCall.function.name, + ) + ) { + // Tool is called on client side + const { + output: clientToolOuput, + respondImmediately, + errorMessage: clientToolError, + } = await callClientTool(toolCallState.toolCall, { + dispatch, + ideMessenger: extra.ideMessenger, + activeToolStreamId: state.session.activeToolStreamId?.[0], + }); + output = clientToolOuput; + errorMessage = clientToolError; + streamResponse = respondImmediately; + } else { + // Tool is called on core side + const result = await extra.ideMessenger.request("tools/call", { + toolCall: toolCallState.toolCall, + }); + if (result.status === "error") { + throw new Error(result.error); + } else { + output = result.content.contextItems; + errorMessage = result.content.errorMessage; + } + streamResponse = true; + } + + if (errorMessage) { + dispatch( + updateToolCallOutput({ + toolCallId, + contextItems: [ + { + icon: "problems", + name: "Tool Call Error", + description: "Tool Call Failed", + content: `${toolCallState.toolCall.function.name} failed with the message: ${errorMessage}\n\nPlease try something else or request further instructions.`, + hidden: false, + }, + ], + }), + ); + } else if (output?.length) { + dispatch( + updateToolCallOutput({ + toolCallId, + contextItems: output, + }), + ); + } + + if (streamResponse) { + if (errorMessage) { + dispatch( + errorToolCall({ + toolCallId, + }), + ); + } else { + dispatch( + acceptToolCall({ + toolCallId, + }), + ); + } + + // Send to the LLM to continue the conversation + const wrapped = await dispatch( + streamResponseAfterToolCall({ + toolCallId, + }), + ); + unwrapResult(wrapped); + } + }, +); diff --git a/gui/src/redux/thunks/callTool.ts b/gui/src/redux/thunks/callTool.ts deleted file mode 100644 index 643e6c483..000000000 --- a/gui/src/redux/thunks/callTool.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; -import { ContextItem } from "core"; -import { CLIENT_TOOLS } from "core/tools/builtIn"; -import { callClientTool } from "../../util/clientTools/callClientTool"; -import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; -import { selectSelectedChatModel } from "../slices/configSlice"; -import { - acceptToolCall, - cancelToolCall, - setCalling, - setToolCallOutput, -} from "../slices/sessionSlice"; -import { ThunkApiType } from "../store"; -import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; - -export const callTool = createAsyncThunk( - "chat/callTool", - async (_, { dispatch, extra, getState }) => { - const state = getState(); - const toolCallState = selectCurrentToolCall(state); - - if (!toolCallState) { - return; - } - - if (toolCallState.status !== "generated") { - return; - } - - const selectedChatModel = selectSelectedChatModel(state); - - if (!selectedChatModel) { - throw new Error("No model selected"); - } - - dispatch(setCalling()); - - let errorMessage: string | undefined = ""; - let output: ContextItem[] | undefined = undefined; - - if ( - CLIENT_TOOLS.find( - (toolName) => toolName === toolCallState.toolCall.function.name, - ) - ) { - // Tool is called on client side - const { errorMessage: clientErrorMessage, output: clientOutput } = - await callClientTool(toolCallState.toolCall, { - dispatch, - ideMessenger: extra.ideMessenger, - activeToolStreamId: state.session.activeToolStreamId?.[0], - }); - output = clientOutput; - errorMessage = clientErrorMessage; - } else { - // Tool is called on core side - const result = await extra.ideMessenger.request("tools/call", { - toolCall: toolCallState.toolCall, - }); - if (result.status === "error") { - errorMessage = result.error; - } else { - output = result.content.contextItems; - } - } - - if (errorMessage) { - dispatch(cancelToolCall()); - - const wrapped = await dispatch( - streamResponseAfterToolCall({ - toolCallId: toolCallState.toolCallId, - toolOutput: [], - }), - ); - unwrapResult(wrapped); - } else if (output) { - dispatch(setToolCallOutput(output)); - dispatch(acceptToolCall()); - - // Send to the LLM to continue the conversation - const wrapped = await dispatch( - streamResponseAfterToolCall({ - toolCallId: toolCallState.toolCall.id, - toolOutput: output, - }), - ); - unwrapResult(wrapped); - } - // okay for a tool to have no output and need some GUI trigger or other to trigger response e.g. edit tool - }, -); diff --git a/gui/src/redux/thunks/cancelCurrentToolCall.ts b/gui/src/redux/thunks/cancelCurrentToolCall.ts new file mode 100644 index 000000000..f90d80ff6 --- /dev/null +++ b/gui/src/redux/thunks/cancelCurrentToolCall.ts @@ -0,0 +1,50 @@ +import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; +import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; +import { cancelToolCall, updateToolCallOutput } from "../slices/sessionSlice"; +import { ThunkApiType } from "../store"; +import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; + +export const cancelCurrentToolCall = createAsyncThunk< + void, + undefined, + ThunkApiType +>("chat/cancelTool", async (_, { dispatch, extra, getState }) => { + const state = getState(); + const toolCallState = selectCurrentToolCall(state); + + if (!toolCallState) { + return; + } + + if (toolCallState.status !== "generated") { + return; + } + + const { toolCallId } = toolCallState; + dispatch( + cancelToolCall({ + toolCallId, + }), + ); + + dispatch( + updateToolCallOutput({ + toolCallId, + contextItems: [ + { + name: "Tool Cancelled", + description: "Tool Cancelled", + content: + "The tool call was cancelled by the user. Please try something else or request further instructions.", + hidden: true, + }, + ], + }), + ); + const output = await dispatch( + streamResponseAfterToolCall({ + toolCallId, + }), + ); + unwrapResult(output); +}); diff --git a/gui/src/redux/thunks/cancelTool.ts b/gui/src/redux/thunks/cancelTool.ts deleted file mode 100644 index d46195674..000000000 --- a/gui/src/redux/thunks/cancelTool.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; -import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; -import { cancelToolCall } from "../slices/sessionSlice"; -import { ThunkApiType } from "../store"; -import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; - -export const cancelTool = createAsyncThunk( - "chat/cancelTool", - async (_, { dispatch, extra, getState }) => { - const state = getState(); - const toolCallState = selectCurrentToolCall(state); - - if (!toolCallState) { - return; - } - - if (toolCallState.status !== "generated") { - return; - } - - dispatch(cancelToolCall()); - - const output = await dispatch( - streamResponseAfterToolCall({ - toolCallId: toolCallState.toolCallId, - toolOutput: [ - { - name: "Tool Cancelled", - description: "Tool Cancelled", - content: - "The tool call was cancelled by the user. Please try something else or request further instructions.", - hidden: true, - }, - ], - }), - ); - unwrapResult(output); - }, -); diff --git a/gui/src/redux/thunks/moveTerminalProcessToBackground.ts b/gui/src/redux/thunks/moveTerminalProcessToBackground.ts index 1b592f549..c3f0a39d0 100644 --- a/gui/src/redux/thunks/moveTerminalProcessToBackground.ts +++ b/gui/src/redux/thunks/moveTerminalProcessToBackground.ts @@ -1,6 +1,10 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; import { ContextItem } from "core"; -import { abortStream, acceptToolCall, updateToolCallOutput } from "../slices/sessionSlice"; +import { + abortStream, + acceptToolCall, + updateToolCallOutput, +} from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; @@ -15,54 +19,64 @@ export const moveTerminalProcessToBackground = createAsyncThunk< void, { toolCallId: string }, ThunkApiType ->("chat/moveTerminalProcessToBackground", async ({ toolCallId }, { dispatch, getState, extra }) => { - // Find the current tool call - const state = getState(); - const toolCalls = state.session.history.filter( - (item) => item.toolCallState?.toolCallId === toolCallId - ); +>( + "chat/moveTerminalProcessToBackground", + async ({ toolCallId }, { dispatch, getState, extra }) => { + // Find the current tool call + const state = getState(); + const toolCalls = state.session.history.filter( + (item) => item.toolCallState?.toolCallId === toolCallId, + ); - if (toolCalls.length === 0) { - console.error("Could not find tool call with ID:", toolCallId); - return; - } - - const toolCall = toolCalls[0].toolCallState; - if (!toolCall) { - console.error("Tool call state is missing"); - return; - } - - const status = "Command moved to background. Further output will be ignored." - - const contextItems: ContextItem[] = [ - { - name: "Terminal", - description: "Terminal command output", - content: "\n" + status, - status: status, + if (toolCalls.length === 0) { + console.error("Could not find tool call with ID:", toolCallId); + return; } - ]; - // Abort any existing stream for this tool call - dispatch(abortStream()); + const toolCall = toolCalls[0].toolCallState; + if (!toolCall) { + console.error("Tool call state is missing"); + return; + } - // Update the tool call output - dispatch(updateToolCallOutput({ - toolCallId, - contextItems - })); + const status = + "Command moved to background. Further output will be ignored."; - // Mark the process as backgrounded so we ignore future events - await extra.ideMessenger.request("process/markAsBackgrounded", { toolCallId }); + const contextItems: ContextItem[] = [ + { + name: "Terminal", + description: "Terminal command output", + content: "\n" + status, + status: status, + }, + ]; - // Mark the tool call as "done" in the UI - // This will set isRunning to false in RunTerminalCommand.tsx - dispatch(acceptToolCall()); + // Abort any existing stream for this tool call + dispatch(abortStream()); - // Trigger an LLM response about the command being moved to background - dispatch(streamResponseAfterToolCall({ - toolCallId, - toolOutput: contextItems - })); -}); \ No newline at end of file + // Update the tool call output + dispatch( + updateToolCallOutput({ + toolCallId, + contextItems, + }), + ); + + // Mark the process as backgrounded so we ignore future events + await extra.ideMessenger.request("process/markAsBackgrounded", { + toolCallId, + }); + + // Mark the tool call as "done" in the UI + // This will set isRunning to false in RunTerminalCommand.tsx + dispatch(acceptToolCall({ toolCallId })); + + // Trigger an LLM response about the command being moved to background + dispatch(updateToolCallOutput({ toolCallId, contextItems })); + dispatch( + streamResponseAfterToolCall({ + toolCallId, + }), + ); + }, +); diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index c8b10dc37..819ec79ee 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -12,7 +12,7 @@ import { streamUpdate, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; -import { callTool } from "./callTool"; +import { callCurrentTool } from "./callCurrentTool"; export const streamNormalInput = createAsyncThunk< void, @@ -107,13 +107,17 @@ export const streamNormalInput = createAsyncThunk< // If it's a tool call that is automatically accepted, we should call it const toolCallState = selectCurrentToolCall(getState()); if (toolCallState) { - dispatch(setToolGenerated()); + dispatch( + setToolGenerated({ + toolCallId: toolCallState.toolCallId, + }), + ); if ( toolSettings[toolCallState.toolCall.function.name] === "allowedWithoutPermission" ) { - const response = await dispatch(callTool()); + const response = await dispatch(callCurrentTool()); unwrapResult(response); } } diff --git a/gui/src/redux/thunks/streamResponseAfterToolCall.ts b/gui/src/redux/thunks/streamResponseAfterToolCall.ts index 5a0083886..269402bf5 100644 --- a/gui/src/redux/thunks/streamResponseAfterToolCall.ts +++ b/gui/src/redux/thunks/streamResponseAfterToolCall.ts @@ -1,5 +1,5 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; -import { ChatMessage, ContextItem } from "core"; +import { ChatMessage } from "core"; import { constructMessages } from "core/llm/constructMessages"; import { renderContextItems } from "core/util/messageContent"; import { selectSelectedChatModel } from "../slices/configSlice"; @@ -9,20 +9,18 @@ import { streamUpdate, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; +import { findToolCall } from "../util"; import { resetStateForNewMessage } from "./resetStateForNewMessage"; import { streamNormalInput } from "./streamNormalInput"; import { streamThunkWrapper } from "./streamThunkWrapper"; export const streamResponseAfterToolCall = createAsyncThunk< void, - { - toolCallId: string; - toolOutput: ContextItem[]; - }, + { toolCallId: string }, ThunkApiType >( "chat/streamAfterToolCall", - async ({ toolCallId, toolOutput }, { dispatch, getState }) => { + async ({ toolCallId }, { dispatch, getState }) => { await dispatch( streamThunkWrapper(async () => { const state = getState(); @@ -33,6 +31,14 @@ export const streamResponseAfterToolCall = createAsyncThunk< throw new Error("No model selected"); } + const toolCallState = findToolCall(state.session.history, toolCallId); + + if (!toolCallState) { + throw new Error("Tool call not found"); + } + + const toolOutput = toolCallState.output ?? []; + resetStateForNewMessage(); await new Promise((resolve) => setTimeout(resolve, 0)); diff --git a/gui/src/redux/util/index.ts b/gui/src/redux/util/index.ts index 7c21c69bd..eab18ae60 100644 --- a/gui/src/redux/util/index.ts +++ b/gui/src/redux/util/index.ts @@ -2,7 +2,16 @@ import { ToolCallState } from "core"; import { RootState } from "../store"; export function findCurrentToolCall( - state: RootState["session"]["history"], + chatHistory: RootState["session"]["history"], ): ToolCallState | undefined { - return state[state.length - 1]?.toolCallState; + return chatHistory[chatHistory.length - 1]?.toolCallState; +} + +export function findToolCall( + chatHistory: RootState["session"]["history"], + toolCallId: string, +): ToolCallState | undefined { + return chatHistory.find( + (item) => item.toolCallState?.toolCallId === toolCallId, + )?.toolCallState; } diff --git a/gui/src/util/clientTools/callClientTool.ts b/gui/src/util/clientTools/callClientTool.ts index 44bb7aadc..6d451fe7e 100644 --- a/gui/src/util/clientTools/callClientTool.ts +++ b/gui/src/util/clientTools/callClientTool.ts @@ -11,35 +11,47 @@ export interface ClientToolExtras { } export interface ClientToolOutput { - output?: ContextItem[]; - errorMessage?: string; + output: ContextItem[] | undefined; + respondImmediately: boolean; +} + +export interface ClientToolResult extends ClientToolOutput { + errorMessage: string | undefined; } export type ClientToolImpl = ( args: any, toolCallId: string, extras: ClientToolExtras, -) => Promise; +) => Promise; export async function callClientTool( toolCall: ToolCall, extras: ClientToolExtras, -): Promise { +): Promise { const args = JSON.parse(toolCall.function.arguments || "{}"); - let output: ContextItem[] | undefined = undefined; try { + let output: ClientToolOutput; switch (toolCall.function.name) { case BuiltInToolNames.EditExistingFile: output = await editToolImpl(args, toolCall.id, extras); + break; default: throw new Error(`Invalid client tool name ${toolCall.function.name}`); } - return { output }; + return { + ...output, + errorMessage: undefined, + }; } catch (e) { - let errorMessage = `Failed to call ${toolCall.function.name} tool`; + let errorMessage = `${e}`; if (e instanceof Error) { errorMessage = e.message; } - return { errorMessage }; + return { + respondImmediately: true, + errorMessage, + output: undefined, + }; } } diff --git a/gui/src/util/clientTools/editImpl.ts b/gui/src/util/clientTools/editImpl.ts index f4956e87e..2a6d3e1d4 100644 --- a/gui/src/util/clientTools/editImpl.ts +++ b/gui/src/util/clientTools/editImpl.ts @@ -37,5 +37,8 @@ export const editToolImpl: ClientToolImpl = async ( }), ); } - return undefined; + return { + respondImmediately: false, + output: undefined, // No immediate output. + }; }; From afd72445487a15e314aeed021934f6519c55313e Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 22 Apr 2025 14:54:30 -0700 Subject: [PATCH 06/11] fix rules not being included in agent mode --- core/edit/streamDiffLines.ts | 14 ++-- core/llm/constructMessages.ts | 10 ++- core/llm/countTokens.ts | 75 ++++++++++++------- core/llm/messages.ts | 25 +++++++ core/llm/rules/getSystemMessageWithRules.ts | 4 +- extensions/vscode/package-lock.json | 12 --- .../mainInput/Lump/sections/RulesSection.tsx | 2 +- gui/src/pages/gui/ToolCallDiv/index.tsx | 1 + gui/src/redux/thunks/streamThunkWrapper.tsx | 2 +- 9 files changed, 90 insertions(+), 55 deletions(-) diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index 8092d7ab8..38178e737 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -4,6 +4,7 @@ import { ILLM, Prediction, RuleWithSource, + ToolResultChatMessage, UserChatMessage, } from "../"; import { @@ -104,15 +105,16 @@ export async function* streamDiffLines({ // Rules will be included with edit prompt // If any rules are present this will result in using chat instead of legacy completion - const lastUserMessage: UserChatMessage | undefined = + const lastUserMessage = typeof prompt === "string" - ? { + ? ({ role: "user", content: prompt, - } - : (findLast(prompt, (msg) => msg.role === "user") as - | UserChatMessage - | undefined); + } as UserChatMessage) + : (findLast( + prompt, + (msg) => msg.role === "user" || msg.role === "tool", + ) as UserChatMessage | ToolResultChatMessage | undefined); const systemMessage = getSystemMessageWithRules({ currentModel: llm.model, diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index 8947d04c0..51493e0dd 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -3,10 +3,12 @@ import { ChatMessage, RuleWithSource, TextMessagePart, + ToolResultChatMessage, UserChatMessage, } from "../"; import { findLast } from "../util/findLast"; import { normalizeToMessageParts } from "../util/messageContent"; +import { isUserOrToolMsg } from "./messages"; import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules"; export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL = @@ -96,13 +98,15 @@ export function constructMessages( } } - const userMessage = findLast(msgs, (msg) => msg.role === "user") as + const lastUserMsg = findLast(msgs, (msg) => isUserOrToolMsg) as | UserChatMessage + | ToolResultChatMessage | undefined; + const systemMessage = getSystemMessageWithRules({ baseSystemMessage: baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE, rules, - userMessage, + userMessage: lastUserMsg, currentModel: modelName, }); if (systemMessage.trim()) { @@ -112,8 +116,6 @@ export function constructMessages( }); } - // Note, last assistant message is removed on core side - // Remove the "id" from all of the messages return msgs.map((msg) => { const { id, ...rest } = msg as any; diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 40d356e4b..4ccfe1768 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -2,7 +2,6 @@ import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken"; import { ChatMessage, MessageContent, MessagePart, Tool } from "../index.js"; -import { findLast } from "../util/findLast.js"; import { renderChatMessage } from "../util/messageContent.js"; import { AsyncEncoder, @@ -15,6 +14,8 @@ import { addSpaceToAnyEmptyMessages, chatMessageIsEmpty, flattenMessages, + isUserOrToolMsg, + messageHasToolCallId, } from "./messages.js"; interface Encoding { encode: Tiktoken["encode"]; @@ -328,29 +329,47 @@ function compileChatMessages({ } } - const lastUserMsg = findLast(msgsCopy, (msg) => msg.role === "user"); - if (!lastUserMsg) { - throw new Error("Error parsing chat history: no user message found"); // should never happen - } + // Extract system message + const systemMsg = msgsCopy.find((msg) => msg.role === "system"); + msgsCopy = msgsCopy.filter((msg) => msg.role !== "system"); + // Remove any empty messages or non-user/tool trailing messages msgsCopy = msgsCopy.filter((msg) => !chatMessageIsEmpty(msg)); msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy); - // Remove any last messages that aren't user - // Then pop the user message too since we've already grabbed it - while (msgsCopy.at(-1)?.role !== "user") { + while (msgsCopy.length > 1) { + if (isUserOrToolMsg(msgsCopy.at(-1))) { + break; + } msgsCopy.pop(); } - msgsCopy.pop(); + + const lastUserOrToolMsg = msgsCopy.pop(); + if (!lastUserOrToolMsg || !isUserOrToolMsg(lastUserOrToolMsg)) { + throw new Error("Error parsing chat history: no user/tool message found"); // should never happen + } + + let lastToolCallsMsg: ChatMessage | undefined = undefined; + if (lastUserOrToolMsg.role === "tool") { + lastToolCallsMsg = msgsCopy.pop(); + if (!messageHasToolCallId(lastToolCallsMsg, lastUserOrToolMsg.toolCallId)) { + throw new Error( + `Error parsing chat history: tool call found to match tool output for id ${lastUserOrToolMsg.toolCallId}`, + ); + } + } + + let lastMessagesTokens = countChatMessageTokens(modelName, lastUserOrToolMsg); + if (lastToolCallsMsg) { + lastMessagesTokens += countChatMessageTokens(modelName, lastToolCallsMsg); + } // System message let systemMsgTokens = 0; - const systemMsg = msgsCopy.find((msg) => msg.role === "system"); if (systemMsg) { systemMsgTokens = countChatMessageTokens(modelName, systemMsg); } - msgsCopy = msgsCopy.filter((msg) => msg.role !== "system"); // Tools let toolTokens = 0; @@ -358,9 +377,6 @@ function compileChatMessages({ toolTokens = countToolsTokens(tools, modelName); } - // Last user message - const lastUserMsgTokens = countChatMessageTokens(modelName, lastUserMsg); - const countingSafetyBuffer = getTokenCountingBufferSafety(contextLength); const minOutputTokens = getMinResponseTokens(maxTokens); let inputTokensAvailable = @@ -368,20 +384,20 @@ function compileChatMessages({ inputTokensAvailable -= toolTokens; inputTokensAvailable -= systemMsgTokens; - inputTokensAvailable -= lastUserMsgTokens; + 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 properties: + Request had the following token counts: - contextLength: ${contextLength} - - token counting safety buffer: ${countingSafetyBuffer} - - toolTokens: ~${toolTokens} - - systemMsgTokens: ~${systemMsgTokens} - - lastUserMsgTokens: ~${lastUserMsgTokens} - - maxTokens: ${maxTokens}`, + - counting safety buffer: ${countingSafetyBuffer} + - tools: ~${toolTokens} + - system message: ~${systemMsgTokens} + - last user or tool + tool call message tokens: ~${lastMessagesTokens} + - max output tokens: ${maxTokens}`, ); } @@ -398,27 +414,28 @@ function compileChatMessages({ while (historyWithTokens.length > 0 && currentTotal > inputTokensAvailable) { const message = historyWithTokens.shift()!; + currentTotal -= message.tokens; // At this point make sure no latent tool response without corresponding call while (historyWithTokens[0]?.role === "tool") { const message = historyWithTokens.shift()!; currentTotal -= message.tokens; } - - currentTotal -= message.tokens; } // Now reassemble - const reassembled: ChatMessage[] = [ - ...historyWithTokens.map(({ tokens, ...rest }) => rest), - lastUserMsg, - ]; + const reassembled: ChatMessage[] = []; if (systemMsg) { - reassembled.unshift(systemMsg); + reassembled.push(systemMsg); } + reassembled.push(...historyWithTokens.map(({ tokens, ...rest }) => rest)); + if (lastToolCallsMsg) { + reassembled.push(lastToolCallsMsg); + } + reassembled.push(lastUserOrToolMsg); + // Flatten the messages (combines adjacent similar messages) const flattenedHistory = flattenMessages(reassembled); - return flattenedHistory; } diff --git a/core/llm/messages.ts b/core/llm/messages.ts index d3f7ab477..8a0312766 100644 --- a/core/llm/messages.ts +++ b/core/llm/messages.ts @@ -49,6 +49,31 @@ export function addSpaceToAnyEmptyMessages( }); } +export function isUserOrToolMsg(msg: ChatMessage | undefined): boolean { + if (!msg) { + return false; + } + return msg.role === "user" || msg.role === "tool"; +} + +export function isToolMessageForId( + msg: ChatMessage | undefined, + toolCallId: string, +): boolean { + return !!msg && msg.role === "tool" && msg.toolCallId === toolCallId; +} + +export function messageHasToolCallId( + msg: ChatMessage | undefined, + toolCallId: string, +): boolean { + return ( + !!msg && + msg.role === "assistant" && + !!msg.toolCalls?.find((call) => call.id === toolCallId) + ); +} + export function chatMessageIsEmpty(message: ChatMessage): boolean { switch (message.role) { case "system": diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index 2387145d4..6f3d48583 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -1,4 +1,4 @@ -import { RuleWithSource, UserChatMessage } from "../.."; +import { RuleWithSource, ToolResultChatMessage, UserChatMessage } from "../.."; import { renderChatMessage } from "../../util/messageContent"; import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks"; import { isRuleActive } from "./isRuleActive"; @@ -10,7 +10,7 @@ export const getSystemMessageWithRules = ({ currentModel, }: { baseSystemMessage?: string; - userMessage: UserChatMessage | undefined; + userMessage: UserChatMessage | ToolResultChatMessage | undefined; rules: RuleWithSource[]; currentModel: string; }) => { diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 50229fa80..4917b02cc 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,20 +1,12 @@ { "name": "continue", -<<<<<<< HEAD - "version": "1.1.22", -======= "version": "1.1.24", ->>>>>>> b8c92f26cad325ff79eca6b5d01fd4ac47b4a88f "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", -<<<<<<< HEAD - "version": "1.1.22", -======= "version": "1.1.24", ->>>>>>> b8c92f26cad325ff79eca6b5d01fd4ac47b4a88f "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", @@ -114,11 +106,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", -<<<<<<< HEAD - "@continuedev/config-yaml": "^1.0.77", -======= "@continuedev/config-yaml": "file:../packages/config-yaml", ->>>>>>> b8c92f26cad325ff79eca6b5d01fd4ac47b4a88f "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", diff --git a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx index 562d7e50b..0fae7611e 100644 --- a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx @@ -181,7 +181,7 @@ export function RulesSection() { } } // Add a displayed rule for the base system chat message when in chat mode - if (mode === "chat") { + if (mode === "chat" || mode === "agent") { const baseMessage = config.selectedModelByRole.chat?.baseChatSystemMessage; if (baseMessage) { diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index 4bdffccfd..19bb13c02 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -75,6 +75,7 @@ export function ToolCallDiv(props: ToolCallDivProps) { const icon = props.toolCall.function?.name && toolCallIcons[props.toolCall.function?.name]; + if (icon && props.toolCall.id) { return (
diff --git a/gui/src/redux/thunks/streamThunkWrapper.tsx b/gui/src/redux/thunks/streamThunkWrapper.tsx index 7bd5a82f9..b022019ef 100644 --- a/gui/src/redux/thunks/streamThunkWrapper.tsx +++ b/gui/src/redux/thunks/streamThunkWrapper.tsx @@ -19,7 +19,7 @@ export const streamThunkWrapper = createAsyncThunk< } finally { dispatch(setInactive()); const state = getState(); - if (state.session.mode === "chat") { + if (state.session.mode === "chat" || state.session.mode === "agent") { await dispatch( saveCurrentSession({ openNewSession: false, From 6364a850558d5e7632c72a3009c34cda82901594 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 22 Apr 2025 17:05:21 -0700 Subject: [PATCH 07/11] stream cancellation considerations --- core/llm/constructMessages.ts | 2 +- gui/src/hooks/useSetup.ts | 6 +++--- gui/src/redux/thunks/cancelStream.ts | 3 ++- gui/src/redux/thunks/streamThunkWrapper.tsx | 14 +++++++------- 4 files changed, 13 insertions(+), 12 deletions(-) diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index 51493e0dd..972d5d9e3 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -98,7 +98,7 @@ export function constructMessages( } } - const lastUserMsg = findLast(msgs, (msg) => isUserOrToolMsg) as + const lastUserMsg = findLast(msgs, isUserOrToolMsg) as | UserChatMessage | ToolResultChatMessage | undefined; diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index b5d8e9685..02347432b 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -18,11 +18,11 @@ import { updateIndexingStatus } from "../redux/slices/indexingSlice"; import { acceptToolCall, addContextItemsAtIndex, - setInactive, updateApplyState, } from "../redux/slices/sessionSlice"; import { setTTSActive } from "../redux/slices/uiSlice"; import { streamResponseAfterToolCall } from "../redux/thunks"; +import { cancelStream } from "../redux/thunks/cancelStream"; import { refreshSessionMetadata } from "../redux/thunks/session"; import { streamResponseThunk } from "../redux/thunks/streamResponse"; import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols"; @@ -138,7 +138,7 @@ function useSetup() { // ON LOAD useEffect(() => { // Override persisted state - dispatch(setInactive()); + dispatch(cancelStream()); const jetbrains = isJetBrains(); for (const colorVar of VSC_THEME_COLOR_VARS) { @@ -223,7 +223,7 @@ function useSetup() { ); useWebviewListener("setInactive", async () => { - dispatch(setInactive()); + dispatch(cancelStream()); }); useWebviewListener("setTTSActive", async (status) => { diff --git a/gui/src/redux/thunks/cancelStream.ts b/gui/src/redux/thunks/cancelStream.ts index c7346557c..515a02cfc 100644 --- a/gui/src/redux/thunks/cancelStream.ts +++ b/gui/src/redux/thunks/cancelStream.ts @@ -12,8 +12,9 @@ export const cancelStream = createAsyncThunk( dispatch(setInactive()); dispatch(abortStream()); + // In the case tool calls were being generated, + // Replace them with // If the assistant message is empty, then remove it and the user message, placing the user input in the main text box - // TODO: Waiting until next release dispatch(clearLastEmptyResponse()); }, ); diff --git a/gui/src/redux/thunks/streamThunkWrapper.tsx b/gui/src/redux/thunks/streamThunkWrapper.tsx index b022019ef..149782416 100644 --- a/gui/src/redux/thunks/streamThunkWrapper.tsx +++ b/gui/src/redux/thunks/streamThunkWrapper.tsx @@ -1,8 +1,9 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; import StreamErrorDialog from "../../pages/gui/StreamError"; -import { clearLastEmptyResponse, setInactive } from "../slices/sessionSlice"; +import { setInactive } from "../slices/sessionSlice"; import { setDialogMessage, setShowDialog } from "../slices/uiSlice"; import { ThunkApiType } from "../store"; +import { cancelStream } from "./cancelStream"; import { saveCurrentSession } from "./session"; export const streamThunkWrapper = createAsyncThunk< @@ -12,12 +13,6 @@ export const streamThunkWrapper = createAsyncThunk< >("chat/streamWrapper", async (runStream, { dispatch, extra, getState }) => { try { await runStream(); - } catch (e: unknown) { - dispatch(clearLastEmptyResponse()); - dispatch(setDialogMessage()); - dispatch(setShowDialog(true)); - } finally { - dispatch(setInactive()); const state = getState(); if (state.session.mode === "chat" || state.session.mode === "agent") { await dispatch( @@ -27,5 +22,10 @@ export const streamThunkWrapper = createAsyncThunk< }), ); } + dispatch(setInactive()); + } catch (e) { + dispatch(cancelStream()); + dispatch(setDialogMessage()); + dispatch(setShowDialog(true)); } }); From 047af8ac1bed60265ffbee7d5b766d07c6cb64e6 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 22 Apr 2025 18:36:59 -0700 Subject: [PATCH 08/11] fix broken tests --- core/llm/messages.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/llm/messages.test.ts b/core/llm/messages.test.ts index 6f5ba0a4c..3594eb679 100644 --- a/core/llm/messages.test.ts +++ b/core/llm/messages.test.ts @@ -1,5 +1,5 @@ import { ChatMessage } from ".."; -import { flattenMessages } from "./countTokens"; +import { flattenMessages } from "./messages"; describe("flattenMessages", () => { it("should return an empty array when given an empty array", () => { From 9668e3d924a6cfb8df7f56b65e723a59e4148c9e Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 22 Apr 2025 19:02:29 -0700 Subject: [PATCH 09/11] cleanup --- gui/src/hooks/useSetup.ts | 11 ++++++++--- gui/src/pages/gui/Chat.tsx | 4 +--- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 02347432b..c6e5c151a 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -260,8 +260,13 @@ function useSetup() { "updateApplyState", async (state) => { dispatch(updateApplyState(state)); - if (activeToolStreamId && state.status === "closed") { - const [streamId, toolCallId] = activeToolStreamId; + const lastHistoryMsg = history.at(-1); + const [streamId, toolCallId] = activeToolStreamId ?? []; + if ( + toolCallId && + state.status === "closed" && + lastHistoryMsg?.toolCallState?.toolCallId === toolCallId + ) { if (state.streamId === streamId) { // const output: ContextItem = { // name: "Edit tool output", @@ -282,7 +287,7 @@ function useSetup() { } } }, - [activeToolStreamId], + [activeToolStreamId, history], ); } diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 3028206ee..284f4f8cc 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -339,9 +339,7 @@ export function Chat() { inputId={item.message.id} /> - ) : item.message.role === - "tool" ? null : // toolCallId={item.message.toolCallId} // contextItems={item.contextItems} // + ) : item.message.role === "tool" ? null : // /> // toolCallId={item.message.toolCallId} // contextItems={item.contextItems} // Date: Wed, 23 Apr 2025 12:42:59 -0700 Subject: [PATCH 10/11] use parsed maxtokens --- core/llm/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/llm/index.ts b/core/llm/index.ts index ee7f895ad..9cb63d637 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -860,7 +860,7 @@ export abstract class BaseLLM implements ILLM { modelName: completionOptions.model, msgs: _messages, contextLength: this.contextLength, - maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS, + maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS, supportsImages: this.supportsImages(), tools: options.tools, }); From 16a3aa385f0b820b306cbcf5ebbeaf808550f0d1 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 23 Apr 2025 15:52:45 -0700 Subject: [PATCH 11/11] stylistic update --- core/llm/countTokens.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 4ccfe1768..218343538 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -379,9 +379,14 @@ function compileChatMessages({ const countingSafetyBuffer = getTokenCountingBufferSafety(contextLength); const minOutputTokens = getMinResponseTokens(maxTokens); - let inputTokensAvailable = - contextLength - countingSafetyBuffer - minOutputTokens; + let inputTokensAvailable = contextLength; + + // Leave space for output/safety + inputTokensAvailable -= countingSafetyBuffer; + inputTokensAvailable -= minOutputTokens; + + // Non-negotiable messages inputTokensAvailable -= toolTokens; inputTokensAvailable -= systemMsgTokens; inputTokensAvailable -= lastMessagesTokens;