Merge pull request #5138 from continuedev/dallin/tools-makeover

Tools architecture and error handling updates
This commit is contained in:
Dallin Romney 2025-04-23 18:17:33 -07:00 • committed by GitHub
commit 3cb27e43b9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
41 changed files with 902 additions and 700 deletions

View file

@ -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 }],

View file

@ -403,6 +403,7 @@ declare global {
| "generated"
| "calling"
| "done"
| "errored"
| "canceled";
// Will exist only on "assistant" messages with tool calls

View file

@ -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();

View file

@ -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,

1
core/index.d.ts vendored
View file

@ -428,6 +428,7 @@ export type ToolStatus =
| "generating"
| "generated"
| "calling"
| "errored"
| "done"
| "canceled";

View file

@ -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,
};

View file

@ -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;

View file

@ -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,

View file

@ -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)

View file

@ -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", () => {

View file

@ -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":

View file

@ -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;
}) => {

View file

@ -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,

View file

@ -17,3 +17,5 @@ export enum BuiltInToolNames {
}
export const BUILT_IN_GROUP_NAME = "Built-In";
export const CLIENT_TOOLS = [BuiltInToolNames.EditExistingFile];

View file

@ -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<ContextItem[]> {
): 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,
};
}
}

View file

@ -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<string | undefined>(
@ -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") {

View file

@ -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;

View file

@ -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() {
<div className="flex gap-2 pb-0.5">
<StopButton
className="text-gray-400"
onClick={() => dispatch(cancelTool())}
onClick={() => dispatch(cancelCurrentToolCall())}
data-testid="reject-tool-call-button"
>
{getMetaKeyLabel()} ⌫ Cancel
@ -114,7 +114,7 @@ export function LumpToolbar() {
<EnterButton
isPrimary={true}
className="text-gray-400"
onClick={() => dispatch(callTool())}
onClick={() => dispatch(callCurrentTool())}
data-testid="accept-tool-call-button"
>
{getMetaKeyLabel()} ⏎ Continue

View file

@ -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) {

View file

@ -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<ResolveEditorContentOutput> {
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<ContextItemWithId[]> {
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;

View file

@ -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],
);
}

View file

@ -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 : // <ToolOutput
// contextItems={item.contextItems}
// toolCallId={item.message.toolCallId}
// />
) : item.message.role === "tool" ? null : // /> // toolCallId={item.message.toolCallId} // contextItems={item.contextItems} // <ToolOutput
item.message.role === "assistant" &&
item.message.toolCalls &&
item.toolCallState ? (

View file

@ -62,7 +62,10 @@ export function getToolCallStatusMessage(
<span>calling the</span> {defaultToolDescription}
</>
);
} else if (toolCallState.status === "canceled") {
} else if (
toolCallState.status === "canceled" ||
toolCallState.status === "errored"
) {
intro = "tried to";
message = futureMessage;
}

View file

@ -56,6 +56,7 @@ export function ToolCallDiv(props: ToolCallDivProps) {
case "done":
return <CheckIcon className="text-green-500" />;
case "canceled":
case "errored":
return <XMarkIcon className="text-red-500" />;
}
}
@ -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 (
<div className="ml-4 mt-2">

View file

@ -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<ContextItem[]>) => {
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<MessageModes>) => {
state.mode = action.payload;
@ -785,11 +831,11 @@ export const {
clearCodeToEdit,
addCodeToEdit,
removeCodeToEdit,
setCalling,
setToolCallCalling,
cancelToolCall,
errorToolCall,
acceptToolCall,
setToolGenerated,
setToolCallOutput,
updateToolCallOutput,
setMode,
setAllSessionMetadata,

View file

@ -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<typeof rootReducer>;

View file

@ -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<void, undefined, ThunkApiType>(
"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);
}
},
);

View file

@ -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<void, undefined, ThunkApiType>(
"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);
}
}

View file

@ -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);
});

View file

@ -12,8 +12,9 @@ export const cancelStream = createAsyncThunk<void, undefined, ThunkApiType>(
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());
},
);

View file

@ -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<void, undefined, ThunkApiType>(
"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);
},
);

View file

@ -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") {

View file

@ -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
}));
});
// 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,
}),
);
},
);

View file

@ -180,7 +180,6 @@ export const saveCurrentSession = createAsyncThunk<
"chatDescriber/describe",
{
text: assistantResponse,
selectedModelTitle: selectedChatModel.title,
},
);
if (result.status === "success" && result.content) {

View file

@ -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);
}
}

View file

@ -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));

View file

@ -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(<StreamErrorDialog error={e} />));
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(<StreamErrorDialog error={e} />));
dispatch(setShowDialog(true));
}
});

View file

@ -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;
}

View file

@ -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<ClientToolOutput>;
export async function callClientTool(
toolCall: ToolCall,
extras: ClientToolExtras,
): Promise<ClientToolResult> {
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,
};
}
}

View file

@ -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.
};
};

View file

@ -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",