diff --git a/core/.eslintrc.json b/core/.eslintrc.json index fbd390fb4..fa760cc0c 100644 --- a/core/.eslintrc.json +++ b/core/.eslintrc.json @@ -13,7 +13,7 @@ "@typescript-eslint/semi": "off", "eqeqeq": "error", "complexity": ["error", { "max": 36 }], - "max-lines-per-function": ["error", { "max": 472 }], + "max-lines-per-function": ["error", { "max": 500 }], "max-statements": ["error", { "max": 108 }], "max-depth": ["error", { "max": 6 }], "max-nested-callbacks": ["error", { "max": 4 }], 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 dc43785e6..848b9b143 100644 --- a/core/core.ts +++ b/core/core.ts @@ -682,59 +682,44 @@ 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, - 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, - }, - ); + return 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; - }); - } - - return { contextItems }; - }, - ); - - on("isItemTooBig", async ({ data: { item, selectedModelTitle } }) => { + on("isItemTooBig", async ({ data: { item } }) => { return this.isItemTooBig(item); }); @@ -932,7 +917,6 @@ export class Core { query: string; fullInput: string; selectedCode: RangeInFile[]; - selectedModelTitle: string; }>, ) => { const { config } = await this.configHandler.loadConfig(); 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/index.d.ts b/core/index.d.ts index 2884798c2..877f308ae 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/constants.ts b/core/llm/constants.ts index 8532aa33b..19b067d15 100644 --- a/core/llm/constants.ts +++ b/core/llm/constants.ts @@ -7,26 +7,6 @@ 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) @@ -38,12 +18,10 @@ export enum LLMConfigurationStatuses { } 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/constructMessages.ts b/core/llm/constructMessages.ts index 950ad2cbe..972d5d9e3 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -3,11 +3,12 @@ import { ChatMessage, RuleWithSource, TextMessagePart, + ToolResultChatMessage, UserChatMessage, } from "../"; import { findLast } from "../util/findLast"; import { normalizeToMessageParts } from "../util/messageContent"; -import { messageIsEmpty } from "./messages"; +import { isUserOrToolMsg } from "./messages"; import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules"; export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL = @@ -92,24 +93,20 @@ 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); } } - const userMessage = findLast(msgs, (msg) => msg.role === "user") as + const lastUserMsg = findLast(msgs, isUserOrToolMsg) as | UserChatMessage + | ToolResultChatMessage | undefined; + const systemMessage = getSystemMessageWithRules({ baseSystemMessage: baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE, rules, - userMessage, + userMessage: lastUserMsg, currentModel: modelName, }); if (systemMessage.trim()) { @@ -119,16 +116,6 @@ 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(); - } - // 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 fbe532208..218343538 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -1,6 +1,6 @@ import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken"; -import { ChatMessage, MessageContent, MessagePart } from "../index.js"; +import { ChatMessage, MessageContent, MessagePart, Tool } from "../index.js"; import { renderChatMessage } from "../util/messageContent.js"; import { @@ -9,13 +9,13 @@ import { LlamaAsyncEncoder, } from "./asyncEncoder.js"; import { autodetectTemplateType } from "./autodetect.js"; -import { TOKEN_BUFFER_FOR_SAFETY } from "./constants.js"; import llamaTokenizer from "./llamaTokenizer.js"; import { addSpaceToAnyEmptyMessages, chatMessageIsEmpty, flattenMessages, - messageHasToolCalls, + isUserOrToolMsg, + messageHasToolCallId, } from "./messages.js"; interface Encoding { encode: Tiktoken["encode"]; @@ -124,6 +124,51 @@ function countTokens( } } +// 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, @@ -131,8 +176,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( @@ -193,6 +268,20 @@ function pruneStringFromTop( return encoding.decode(tokens.slice(tokens.length - maxTokens)); } +const MAX_TOKEN_SAFETY_BUFFER = 1000; +const TOKEN_SAFETY_PROPORTION = 0.02; +function getTokenCountingBufferSafety(contextLength: number) { + return Math.min( + MAX_TOKEN_SAFETY_BUFFER, + contextLength * TOKEN_SAFETY_PROPORTION, + ); +} + +const MIN_RESPONSE_TOKENS = 1000; +function getMinResponseTokens(maxTokens: number) { + return Math.min(MIN_RESPONSE_TOKENS, maxTokens); +} + function pruneRawPromptFromTop( modelName: string, contextLength: number, @@ -200,184 +289,36 @@ function pruneRawPromptFromTop( tokensForCompletion: number, ): string { const maxTokens = - contextLength - tokensForCompletion - TOKEN_BUFFER_FOR_SAFETY; + contextLength - + tokensForCompletion - + getTokenCountingBufferSafety(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 summarize(message: ChatMessage): string { - return `${renderChatMessage(message).substring(0, 100)}...`; -} - -function pruneChatHistory( - modelName: string, - msgs: ChatMessage[], - contextLength: number, - tokensForCompletion: number, -): ChatMessage[] { - // Move system message to 2nd to last to give it priority - const systemMessage = msgs.find((msg) => msg.role === "system"); - const chatHistory: ChatMessage[] = msgs.filter( - (msg) => msg.role !== "system", - ); - if (systemMessage) { - chatHistory.splice(-1, 0, systemMessage); - } - - 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); - }); - - const zippedLongerThanOneThird = zippedMessagesAndTokens.filter( - ([_message, tokens]: [ChatMessage, number]) => tokens > contextLength / 3, - ); - - zippedLongerThanOneThird.sort( - ( - [_messageA, tokensA]: [ChatMessage, number], - [_messageB, tokensB]: [ChatMessage, number], - ) => { - return tokensB - tokensA; - }, - ); - - 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. 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); - } - - // 3. Truncate message in the last 5, except last 1 - i = 0; - while ( - totalTokens > contextLength && - chatHistory.length > 0 && - i < chatHistory.length - 1 - ) { - const message = chatHistory[i]; - totalTokens -= countTokens(message.content, modelName); - 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) { - // 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" - ) { - const firstMessage = chatHistory.shift()!; - const secondMessage = chatHistory.shift()!; - totalTokens -= countTokens(firstMessage.content, modelName); - totalTokens -= countTokens(secondMessage.content, modelName); - } else { - const message = chatHistory.shift()!; - totalTokens -= countTokens(message.content, modelName); - } - } - - // 5. Truncate last message - if (totalTokens > contextLength && chatHistory.length > 0) { - const message = chatHistory[0]; - message.content = pruneRawPromptFromTop( - modelName, - contextLength, - renderChatMessage(message), - tokensForCompletion, - ); - totalTokens = contextLength; - } - - // put system message back if applicable - if ( - chatHistory.length > 1 && - chatHistory[chatHistory.length - 2].role === "system" - ) { - const movedSystemMessage = chatHistory.splice(-2, 1)[0]; - chatHistory.unshift(movedSystemMessage); - } - - return chatHistory; -} - +/* + Goal: reconcile chat messages with available context length + Guidelines: + - Always keep last user message, system message, and tools + - Never allow tool output without the corresponding tool call + - Remove older messages first +*/ function compileChatMessages({ modelName, msgs, contextLength, maxTokens, supportsImages, + tools, }: { modelName: string; msgs: ChatMessage[]; contextLength: number; maxTokens: number; supportsImages: boolean; + tools?: Tool[]; }): ChatMessage[] { let msgsCopy: ChatMessage[] = msgs.map((m) => ({ ...m })); - msgsCopy = msgsCopy.filter((msg) => !chatMessageIsEmpty(msg)); - - msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy); - // If images not supported, convert MessagePart[] to string if (!supportsImages) { for (const msg of msgsCopy) { @@ -388,15 +329,118 @@ function compileChatMessages({ } } - const history = pruneChatHistory( - modelName, - msgsCopy, - contextLength, - maxTokens + TOKEN_BUFFER_FOR_SAFETY, - ); + // Extract system message + const systemMsg = msgsCopy.find((msg) => msg.role === "system"); + msgsCopy = msgsCopy.filter((msg) => msg.role !== "system"); - const flattenedHistory = flattenMessages(history); + // Remove any empty messages or non-user/tool trailing messages + msgsCopy = msgsCopy.filter((msg) => !chatMessageIsEmpty(msg)); + msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy); + + while (msgsCopy.length > 1) { + if (isUserOrToolMsg(msgsCopy.at(-1))) { + break; + } + 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; + if (systemMsg) { + systemMsgTokens = countChatMessageTokens(modelName, systemMsg); + } + + // Tools + let toolTokens = 0; + if (tools) { + toolTokens = countToolsTokens(tools, modelName); + } + + const countingSafetyBuffer = getTokenCountingBufferSafety(contextLength); + const minOutputTokens = getMinResponseTokens(maxTokens); + + let inputTokensAvailable = contextLength; + + // Leave space for output/safety + inputTokensAvailable -= countingSafetyBuffer; + inputTokensAvailable -= minOutputTokens; + + // Non-negotiable messages + inputTokensAvailable -= toolTokens; + inputTokensAvailable -= systemMsgTokens; + inputTokensAvailable -= lastMessagesTokens; + + // Make sure there's enough context for the non-excludable items + if (inputTokensAvailable < 0) { + throw new Error( + `Not enough context available to include the system message, last user message, and tools. + There must be at least ${minOutputTokens} tokens remaining for output. + Request had the following token counts: + - contextLength: ${contextLength} + - counting safety buffer: ${countingSafetyBuffer} + - tools: ~${toolTokens} + - system message: ~${systemMsgTokens} + - last user or tool + tool call message tokens: ~${lastMessagesTokens} + - max output tokens: ${maxTokens}`, + ); + } + + // Now remove messages till we're under the limit + let currentTotal = 0; + const historyWithTokens = msgsCopy.map((message) => { + const tokens = countChatMessageTokens(modelName, message); + currentTotal += tokens; + return { + ...message, + tokens, + }; + }); + + 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; + } + } + + // Now reassemble + const reassembled: ChatMessage[] = []; + if (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; } @@ -404,7 +448,6 @@ export { compileChatMessages, countTokens, countTokensAsync, - flattenMessages, pruneLinesFromBottom, pruneLinesFromTop, pruneRawPromptFromTop, diff --git a/core/llm/index.ts b/core/llm/index.ts index e3d8004bb..9cb63d637 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, @@ -281,28 +280,6 @@ export abstract class BaseLLM implements ILLM { return Promise.resolve([]); } - private _compileChatMessages( - options: CompletionOptions, - messages: ChatMessage[], - ) { - 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(), - }); - } - private _templatePromptLikeMessages(prompt: string): string { if (!this.templateMessages) { return prompt; @@ -879,7 +856,14 @@ 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: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS, + supportsImages: this.supportsImages(), + tools: options.tools, + }); const prompt = this.templateMessages ? this.templateMessages(messages) 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", () => { 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/core/protocol/core.ts b/core/protocol/core.ts index 38a51c098..45a01a976 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, @@ -203,15 +201,12 @@ export type ToCoreFromIdeOrWebviewProtocol = { "auth/getAuthUrl": [{ useOnboarding: boolean }, { url: string }]; "tools/call": [ - { toolCall: ToolCall; selectedModelTitle: string }, - { contextItems: ContextItem[] }, + { toolCall: ToolCall }, + { contextItems: ContextItem[]; errorMessage?: string }, ]; "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/core/tools/builtIn.ts b/core/tools/builtIn.ts index 5e269c232..9f70b1a22 100644 --- a/core/tools/builtIn.ts +++ b/core/tools/builtIn.ts @@ -17,3 +17,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 c8b36aa90..d8eaf4ffd 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -130,40 +130,72 @@ async function callToolFromUri( } } +// Handles calls for core/non-client tools +// Returns an error context item if the tool call fails +// Note: Edit tool is handled on client export async function callTool( tool: Tool, - args: any, + callArgs: string, extras: ToolExtras, -): Promise { +): Promise<{ + contextItems: ContextItem[]; + errorMessage: string | undefined; +}> { + 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.CreateRuleBlock: - return await createRuleBlockImpl(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); + 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: + contextItems = await createRuleBlockImpl(args, extras); + break; + default: + contextItems = await callToolFromUri(uri, args, extras); + } + if (tool.faviconUrl) { + contextItems.forEach((item) => { + item.icon = tool.faviconUrl; + }); + } + return { + contextItems, + errorMessage: undefined, + }; + } catch (e) { + let errorMessage = `${e}`; + if (e instanceof Error) { + errorMessage = e.message; + } + return { + contextItems: [], + errorMessage, + }; } } diff --git a/gui/src/components/mainInput/AtMentionDropdown/index.tsx b/gui/src/components/mainInput/AtMentionDropdown/index.tsx index d8c7d5316..ee699ac77 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/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/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/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/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index e9d9223a8..c6e5c151a 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -18,12 +18,11 @@ import { updateIndexingStatus } from "../redux/slices/indexingSlice"; import { acceptToolCall, addContextItemsAtIndex, - setInactive, - setToolCallOutput, 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"; @@ -139,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) { @@ -224,7 +223,7 @@ function useSetup() { ); useWebviewListener("setInactive", async () => { - dispatch(setInactive()); + dispatch(cancelStream()); }); useWebviewListener("setTTSActive", async (status) => { @@ -261,27 +260,34 @@ function useSetup() { "updateApplyState", async (state) => { dispatch(updateApplyState(state)); + const lastHistoryMsg = history.at(-1); + const [streamId, toolCallId] = activeToolStreamId ?? []; if ( - activeToolStreamId && - state.streamId === activeToolStreamId[0] && - state.status === "closed" + toolCallId && + state.status === "closed" && + lastHistoryMsg?.toolCallState?.toolCallId === toolCallId ) { - // const output: ContextItem = { - // name: "Edit tool output", - // content: "Completed edit", - // description: "", - // }; - dispatch(acceptToolCall()); - dispatch(setToolCallOutput([])); - dispatch( - streamResponseAfterToolCall({ - toolCallId: activeToolStreamId[1], - toolOutput: [], - }), - ); + if (state.streamId === streamId) { + // const output: ContextItem = { + // name: "Edit tool output", + // content: "Completed edit", + // description: "", + // }; + dispatch( + acceptToolCall({ + toolCallId, + }), + ); + // dispatch(setToolCallOutput([])); + dispatch( + streamResponseAfterToolCall({ + toolCallId, + }), + ); + } } }, - [activeToolStreamId], + [activeToolStreamId, history], ); } diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 8a76cdbf9..284f4f8cc 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,10 +339,7 @@ export function Chat() { inputId={item.message.id} /> - ) : item.message.role === "tool" ? null : // + ) : item.message.role === "tool" ? null : // /> // toolCallId={item.message.toolCallId} // contextItems={item.contextItems} // 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..19bb13c02 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 ; } } @@ -74,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/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/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/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 cb875f805..000000000 --- a/gui/src/redux/thunks/callTool.ts +++ /dev/null @@ -1,146 +0,0 @@ -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 { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; -import { selectSelectedChatModel } from "../slices/configSlice"; -import { - acceptToolCall, - cancelToolCall, - setCalling, - setToolCallOutput, - updateApplyState, -} 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 = ""; - let output: ContextItem[] | undefined = undefined; - - if ( - toolCallState.toolCall.function.name === BuiltInToolNames.EditExistingFile - ) { - 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 edit 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, - }), - ); - } - } - } else { - const result = await extra.ideMessenger.request("tools/call", { - toolCall: toolCallState.toolCall, - selectedModelTitle: selectedChatModel.title, - }); - 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: [ - { - 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, - }, - ], - }), - ); - 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 - }, -); - -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/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/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/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/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/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/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) { 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/thunks/streamThunkWrapper.tsx b/gui/src/redux/thunks/streamThunkWrapper.tsx index 7bd5a82f9..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,14 +13,8 @@ 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") { + if (state.session.mode === "chat" || state.session.mode === "agent") { await dispatch( saveCurrentSession({ openNewSession: false, @@ -27,5 +22,10 @@ export const streamThunkWrapper = createAsyncThunk< }), ); } + dispatch(setInactive()); + } catch (e) { + dispatch(cancelStream()); + dispatch(setDialogMessage()); + dispatch(setShowDialog(true)); } }); 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 new file mode 100644 index 000000000..6d451fe7e --- /dev/null +++ b/gui/src/util/clientTools/callClientTool.ts @@ -0,0 +1,57 @@ +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[] | undefined; + respondImmediately: boolean; +} + +export interface ClientToolResult extends ClientToolOutput { + errorMessage: string | undefined; +} + +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 || "{}"); + 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, + errorMessage: undefined, + }; + } catch (e) { + let errorMessage = `${e}`; + if (e instanceof Error) { + errorMessage = e.message; + } + return { + respondImmediately: true, + errorMessage, + output: undefined, + }; + } +} diff --git a/gui/src/util/clientTools/editImpl.ts b/gui/src/util/clientTools/editImpl.ts new file mode 100644 index 000000000..2a6d3e1d4 --- /dev/null +++ b/gui/src/util/clientTools/editImpl.ts @@ -0,0 +1,44 @@ +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 { + respondImmediately: false, + output: undefined, // No immediate output. + }; +}; 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",