From ee7bea7c19e3f52a50a8c9a0d26f242757dfd8a5 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 21 Nov 2024 18:31:50 -0800 Subject: [PATCH] renderChatMessage, return ContextItem[] from tools, and other refactoring --- core/commands/index.ts | 16 ++-- core/commands/slash/comment.ts | 19 ----- core/commands/slash/commit.ts | 11 +-- core/commands/slash/draftIssue.ts | 12 ++- core/commands/slash/multifileEdit.ts | 9 ++- core/commands/slash/onboard.ts | 11 +-- core/commands/slash/review.ts | 11 +-- core/commands/slash/share.ts | 4 +- core/config/promptFile.ts | 14 ++-- core/context/retrieval/repoMapRequest.ts | 15 ++-- core/core.ts | 6 +- core/diff/util.ts | 4 +- core/index.d.ts | 31 +++++-- core/llm/constructMessages.ts | 51 +++++------- core/llm/countTokens.ts | 36 +++++---- core/llm/images.ts | 11 --- core/llm/index.ts | 25 ++++-- core/llm/llms/Anthropic.ts | 11 ++- core/llm/llms/Bedrock.ts | 12 +-- core/llm/llms/Cloudflare.ts | 6 +- core/llm/llms/Cohere.ts | 6 +- core/llm/llms/Flowise.ts | 6 +- core/llm/llms/FreeTrial.ts | 16 +++- core/llm/llms/Gemini.ts | 18 +++-- core/llm/llms/Ollama.ts | 57 +++++++------ core/llm/llms/OpenAI.ts | 14 +++- core/llm/llms/VertexAI.ts | 80 +++++++++---------- core/llm/llms/WatsonX.ts | 40 +++++----- core/llm/templates/chat.ts | 8 +- .../v1/slashCommandFromPromptFile.ts | 9 ++- core/protocol/core.ts | 3 +- core/tools/createNewFile.ts | 1 + core/tools/exactSearch.ts | 10 ++- core/tools/runTerminalCommand.ts | 11 ++- core/tools/searchWeb.ts | 2 +- core/tools/viewDiff.ts | 8 +- core/tools/viewRepoMap.ts | 8 +- core/tools/viewSubdirectory.ts | 8 +- core/util/chatDescriber.ts | 2 - core/util/messageContent.ts | 45 +++++++++++ .../vscode/src/extension/VsCodeMessenger.ts | 2 +- .../StepContainer/MultifileEditActions.tsx | 7 +- .../StepContainer/ResponseActions.tsx | 4 +- .../StepContainer/StepContainer.tsx | 8 +- gui/src/components/mainInput/resolveInput.ts | 2 +- gui/src/hooks/useChatHandler.ts | 12 ++- gui/src/hooks/useHistory.tsx | 4 +- gui/src/pages/edit/index.tsx | 7 +- gui/src/pages/gui/Chat.tsx | 4 +- .../ToolCallDiv/FunctionSpecificHeader.tsx | 27 +++++-- .../gui/ToolCallDiv/ToolCallButtonsDiv.tsx | 6 +- gui/src/redux/slices/stateSlice.ts | 26 +++--- manual-testing-sandbox/test.ts | 41 ++++++++++ 53 files changed, 498 insertions(+), 319 deletions(-) delete mode 100644 core/commands/slash/comment.ts delete mode 100644 core/llm/images.ts create mode 100644 core/util/messageContent.ts create mode 100644 manual-testing-sandbox/test.ts diff --git a/core/commands/index.ts b/core/commands/index.ts index cb5e162f7..492b7f90a 100644 --- a/core/commands/index.ts +++ b/core/commands/index.ts @@ -1,6 +1,6 @@ import { CustomCommand, SlashCommand, SlashCommandDescription } from "../"; -import { stripImages } from "../llm/images"; import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString"; +import { renderChatMessage } from "../util/messageContent"; import SlashCommands from "./slash"; @@ -29,7 +29,8 @@ export function slashFromCustomCommand( const messages = [...history]; // Find the last chat message with this slash command and replace it with the user input for (let i = messages.length - 1; i >= 0; i--) { - const { role, content } = messages[i]; + const message = messages[i]; + const { role, content } = message; if (role !== "user") { continue; } @@ -41,7 +42,7 @@ export function slashFromCustomCommand( ) ) { messages[i] = { - ...messages[i], + ...message, content: content.map((part) => { return part.text?.startsWith(`/${customCommand.name}`) ? { ...part, text: promptUserInput } @@ -53,13 +54,16 @@ export function slashFromCustomCommand( typeof content === "string" && content.startsWith(`/${customCommand.name}`) ) { - messages[i] = { ...messages[i], content: promptUserInput }; + messages[i] = { ...message, content: promptUserInput }; break; } } - for await (const chunk of llm.streamChat(messages, new AbortController().signal)) { - yield stripImages(chunk.content); + for await (const chunk of llm.streamChat( + messages, + new AbortController().signal, + )) { + yield renderChatMessage(chunk); } }, }; diff --git a/core/commands/slash/comment.ts b/core/commands/slash/comment.ts deleted file mode 100644 index adadb026c..000000000 --- a/core/commands/slash/comment.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { SlashCommand } from "../../"; - -import EditSlashCommand from "./edit"; - -const CommentSlashCommand: SlashCommand = { - name: "comment", - description: "Write comments for highlighted code", - run: async function* (sdk) { - for await (const update of EditSlashCommand.run({ - ...sdk, - input: - "Write comments for this code. Do not change anything about the code itself.", - })) { - yield update; - } - }, -}; - -export default CommentSlashCommand; diff --git a/core/commands/slash/commit.ts b/core/commands/slash/commit.ts index 7d5f22a90..d6f9bef1f 100644 --- a/core/commands/slash/commit.ts +++ b/core/commands/slash/commit.ts @@ -1,5 +1,5 @@ import { SlashCommand } from "../../index.js"; -import { stripImages } from "../../llm/images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; const CommitMessageCommand: SlashCommand = { name: "commit", @@ -14,10 +14,11 @@ const CommitMessageCommand: SlashCommand = { } const prompt = `${diff}\n\nGenerate a commit message for the above set of changes. First, give a single sentence, no more than 80 characters. Then, after 2 line breaks, give a list of no more than 5 short bullet points, each no more than 40 characters. Output nothing except for the commit message, and don't surround it in quotes.`; - for await (const chunk of llm.streamChat([ - { role: "user", content: prompt }, - ], new AbortController().signal)) { - yield stripImages(chunk.content); + for await (const chunk of llm.streamChat( + [{ role: "user", content: prompt }], + new AbortController().signal, + )) { + yield renderChatMessage(chunk); } }, }; diff --git a/core/commands/slash/draftIssue.ts b/core/commands/slash/draftIssue.ts index 268c68384..a640dbd25 100644 --- a/core/commands/slash/draftIssue.ts +++ b/core/commands/slash/draftIssue.ts @@ -1,6 +1,6 @@ import { ChatMessage, SlashCommand } from "../../index.js"; -import { stripImages } from "../../llm/images.js"; import { removeQuotesAndEscapes } from "../../util/index.js"; +import { renderChatMessage } from "../../util/messageContent.js"; const PROMPT = ( input: string, @@ -30,7 +30,8 @@ const DraftIssueCommand: SlashCommand = { return; } let title = await llm.complete( - `Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `, new AbortController().signal, + `Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `, + new AbortController().signal, { maxTokens: 20 }, ); @@ -43,9 +44,12 @@ const DraftIssueCommand: SlashCommand = { { role: "user", content: PROMPT(input, title) }, ]; - for await (const chunk of llm.streamChat(messages, new AbortController().signal)) { + for await (const chunk of llm.streamChat( + messages, + new AbortController().signal, + )) { body += chunk.content; - yield stripImages(chunk.content); + yield renderChatMessage(chunk); } const url = `${params.repositoryUrl}/issues/new?title=${encodeURIComponent( diff --git a/core/commands/slash/multifileEdit.ts b/core/commands/slash/multifileEdit.ts index c8cf64679..d7b3edcb5 100644 --- a/core/commands/slash/multifileEdit.ts +++ b/core/commands/slash/multifileEdit.ts @@ -1,5 +1,5 @@ import { SlashCommand } from "../.."; -import { stripImages } from "../../llm/images"; +import { renderChatMessage } from "../../util/messageContent"; const MultiFileEditSlashCommand: SlashCommand = { name: "multifile-edit", @@ -39,8 +39,11 @@ const MultiFileEditSlashCommand: SlashCommand = { const content = createPrompt(filesToEditStr, additionalContextStr, input); - for await (const chunk of llm.streamChat([{ role: "user", content }], new AbortController().signal)) { - yield stripImages(chunk.content); + for await (const chunk of llm.streamChat( + [{ role: "user", content }], + new AbortController().signal, + )) { + yield renderChatMessage(chunk); } }, }; diff --git a/core/commands/slash/onboard.ts b/core/commands/slash/onboard.ts index 4d8aa3a38..b9a39aa0b 100644 --- a/core/commands/slash/onboard.ts +++ b/core/commands/slash/onboard.ts @@ -9,7 +9,7 @@ import { defaultIgnoreFile, gitIgArrayFromFile, } from "../../indexing/ignore"; -import { stripImages } from "../../llm/images"; +import { renderChatMessage } from "../../util/messageContent"; const LANGUAGE_DEP_MGMT_FILENAMES = [ "package.json", // JavaScript (Node.js) @@ -45,10 +45,11 @@ const OnboardSlashCommand: SlashCommand = { const context = await gatherProjectContext(workspaceDir, ide); const prompt = createOnboardingPrompt(context); - for await (const chunk of llm.streamChat([ - { role: "user", content: prompt }, - ], new AbortController().signal)) { - yield stripImages(chunk.content); + for await (const chunk of llm.streamChat( + [{ role: "user", content: prompt }], + new AbortController().signal, + )) { + yield renderChatMessage(chunk); } }, }; diff --git a/core/commands/slash/review.ts b/core/commands/slash/review.ts index 77357647a..a3a2be6a7 100644 --- a/core/commands/slash/review.ts +++ b/core/commands/slash/review.ts @@ -1,5 +1,5 @@ import { ChatMessage, SlashCommand } from "../../index.js"; -import { stripImages } from "../../llm/images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; const prompt = ` Review the following code, focusing on Readability, Maintainability, Code Smells, Speed, and Memory Performance. Provide feedback with these guidelines: @@ -43,10 +43,11 @@ const ReviewMessageCommand: SlashCommand = { const content = `${prompt} \r\n ${reviewText}`; - for await (const chunk of llm.streamChat([ - { role: "user", content: content }, - ], new AbortController().signal)) { - yield stripImages(chunk.content); + for await (const chunk of llm.streamChat( + [{ role: "user", content: content }], + new AbortController().signal, + )) { + yield renderChatMessage(chunk); } }, }; diff --git a/core/commands/slash/share.ts b/core/commands/slash/share.ts index 5ee1fd938..4b69f4c62 100644 --- a/core/commands/slash/share.ts +++ b/core/commands/slash/share.ts @@ -4,7 +4,7 @@ import path from "path"; import { languageForFilepath } from "../../autocomplete/constants/AutocompleteLanguageInfo.js"; import { SlashCommand } from "../../index.js"; -import { stripImages } from "../../llm/images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; // If useful elsewhere, helper funcs should move to core/util/index.ts or similar function getOffsetDatetime(date: Date): Date { @@ -48,7 +48,7 @@ const ShareSlashCommand: SlashCommand = { // message in the chat history, this will omit it for (const msg of history.slice(0, history.length - 1)) { let msgText = msg.content; - msgText = stripImages(msg.content); + msgText = renderChatMessage(msg); if (msg.role === "user" && msgText.search("```") > -1) { msgText = reformatCodeBlocks(msgText); diff --git a/core/config/promptFile.ts b/core/config/promptFile.ts index 1ec963513..b369e6338 100644 --- a/core/config/promptFile.ts +++ b/core/config/promptFile.ts @@ -4,9 +4,9 @@ import Handlebars from "handlebars"; import * as YAML from "yaml"; import { walkDir } from "../indexing/walkDir"; -import { stripImages } from "../llm/images"; import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString"; import { getBasename } from "../util/index"; +import { renderChatMessage } from "../util/messageContent"; import type { ChatMessage, @@ -125,8 +125,11 @@ export function slashCommandFromPromptFile( systemMessage, ); - for await (const chunk of context.llm.streamChat(messages, new AbortController().signal)) { - yield stripImages(chunk.content); + for await (const chunk of context.llm.streamChat( + messages, + new AbortController().signal, + )) { + yield renderChatMessage(chunk); } context.llm.systemMessage = originalSystemMessage; @@ -233,7 +236,8 @@ function updateChatHistory( const messages = [...history]; for (let i = messages.length - 1; i >= 0; i--) { - const { role, content } = messages[i]; + const message = messages[i]; + const { role, content } = message; if (role !== "user") { continue; } @@ -251,7 +255,7 @@ function updateChatHistory( typeof content === "string" && content.startsWith(`/${commandName}`) ) { - messages[i] = { ...messages[i], content: renderedPrompt }; + messages[i] = { ...message, content: renderedPrompt }; break; } } diff --git a/core/context/retrieval/repoMapRequest.ts b/core/context/retrieval/repoMapRequest.ts index 8dc55df9d..57f2b339e 100644 --- a/core/context/retrieval/repoMapRequest.ts +++ b/core/context/retrieval/repoMapRequest.ts @@ -1,7 +1,7 @@ import { Chunk, ContinueConfig, IDE, ILLM } from "../.."; import { getModelByRole } from "../../config/util"; -import { stripImages } from "../../llm/images"; import generateRepoMap from "../../util/generateRepoMap"; +import { renderChatMessage } from "../../util/messageContent"; const SUPPORTED_MODEL_TITLE_FAMILIES = [ "claude-3", @@ -58,11 +58,14 @@ After this, your response should begin with a tag, followed by a list This is the question that you should select relevant files for: "${input}"`; - const response = await llm.chat([ - { role: "user", content: prompt }, - { role: "assistant", content: "" }, - ], new AbortController().signal); - const content = stripImages(response.content); + const response = await llm.chat( + [ + { role: "user", content: prompt }, + { role: "assistant", content: "" }, + ], + new AbortController().signal, + ); + const content = renderChatMessage(response); console.debug("Repo map retrieval response: ", content); if (!content.includes("\n")) { diff --git a/core/core.ts b/core/core.ts index ad1ed3be7..e844146f9 100644 --- a/core/core.ts +++ b/core/core.ts @@ -756,13 +756,13 @@ export class Core { ); if (!tool) { - return { error: "Tool not found", result: undefined }; + throw new Error(`Tool ${toolCall.function.name} not found`); } const config = await this.configHandler.loadConfig(); const llm = await this.getSelectedModel(); - const result = await tool.action( + const contextItems = await tool.action( JSON.parse(toolCall.function.arguments || "{}"), { ide: this.ide, @@ -771,7 +771,7 @@ export class Core { fetchwithRequestOptions(url, init, config.requestOptions), }, ); - return { result }; + return { contextItems }; }); } diff --git a/core/diff/util.ts b/core/diff/util.ts index 839ab15b1..c56e88504 100644 --- a/core/diff/util.ts +++ b/core/diff/util.ts @@ -1,7 +1,7 @@ import { distance } from "fastest-levenshtein"; import { ChatMessage } from "../index.js"; -import { stripImages } from "../llm/images.js"; +import { renderChatMessage } from "../util/messageContent.js"; export type LineStream = AsyncGenerator; @@ -103,7 +103,7 @@ export async function* streamLines( try { for await (const update of streamCompletion) { const chunk = - typeof update === "string" ? update : stripImages(update.content); + typeof update === "string" ? update : renderChatMessage(update); buffer += chunk; const lines = buffer.split("\n"); buffer = lines.pop() ?? ""; diff --git a/core/index.d.ts b/core/index.d.ts index e025ccdb6..dcd375643 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -293,13 +293,34 @@ export interface ToolCallDelta { }; } -export interface ChatMessage { - role: ChatMessageRole; - content: MessageContent; - toolCalls?: ToolCallDelta[]; +export interface ToolResultChatMessage { + role: "tool"; + content: string; toolCallId?: string; } +export interface UserChatMessage { + role: "user"; + content: MessageContent; +} + +export interface AssistantChatMessage { + role: "assistant"; + content: MessageContent; + toolCalls?: ToolCallDelta[]; +} + +export interface SystemChatMessage { + role: "system"; + content: string; +} + +export type ChatMessage = + | UserChatMessage + | AssistantChatMessage + | SystemChatMessage + | ToolResultChatMessage; + export interface ContextItemId { providerTitle: string; itemId: string; @@ -860,7 +881,7 @@ export interface Tool { parameters?: Record; strict?: boolean | null; }; - action: (parameters: any, extras: ToolExtras) => Promise; + action: (parameters: any, extras: ToolExtras) => Promise; } interface BaseCompletionOptions { diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index 836d6c442..823fd97f2 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -1,4 +1,5 @@ import { ChatHistory, ChatMessage, MessagePart } from "../index.js"; +import { normalizeToMessageParts } from "../util/messageContent.js"; const SYSTEM_MESSAGE = `When generating new code: @@ -61,17 +62,6 @@ Always follow these guidelines when generating code responses. Other rules: - Avoid calling tools unless they are absolutely necessary. For example, if you are asked a simple programming question you do not need web search. As another example, if the user asks you to explain something about code, do not create a new file.`; -function hasCodeBlockWithFilename(content: ChatMessage["content"]): boolean { - const contentStr = typeof content === "string" ? content : content[0].text; - - if (!contentStr) { - return false; - } - - const codeBlockRegex = /```[\w\W]*?\.[\w\W]*/; - return codeBlockRegex.test(contentStr); -} - export function constructMessages( history: ChatHistory, model: string, @@ -92,28 +82,27 @@ export function constructMessages( for (let i = 0; i < history.length; i++) { const historyItem = history[i]; - let content = Array.isArray(historyItem.message.content) - ? historyItem.message.content - : [{ type: "text", text: historyItem.message.content } as MessagePart]; + if (historyItem.message.role === "user") { + // Gather context items for user messages + let content = normalizeToMessageParts(historyItem.message); - const ctxItems = historyItem.contextItems.map((ctxItem) => { - return { type: "text", text: `${ctxItem.content}\n` } as MessagePart; - }); + const ctxItems = historyItem.contextItems.map((ctxItem) => { + return { type: "text", text: `${ctxItem.content}\n` } as MessagePart; + }); - content = [...ctxItems, ...content]; - - msgs.push({ - ...historyItem.message, - content, - }); - - // Remove the "id" from all of the messages - msgs.forEach((msg: any) => { - if (msg.id !== undefined) { - delete msg.id; - } - }); + content = [...ctxItems, ...content]; + msgs.push({ + ...historyItem.message, + content, + }); + } else { + msgs.push(historyItem.message); + } } - return msgs; + // Remove the "id" from all of the messages + return msgs.map((msg) => { + const { id, ...rest } = msg as any; + return rest; + }); } diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 871e5ee84..896cfe337 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -2,6 +2,7 @@ import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken"; import { ChatMessage, MessageContent, MessagePart } from "../index.js"; +import { renderChatMessage } from "../util/messageContent.js"; import { AsyncEncoder, GPTAsyncEncoder, @@ -9,7 +10,6 @@ import { } from "./asyncEncoder.js"; import { autodetectTemplateType } from "./autodetect.js"; import { TOKEN_BUFFER_FOR_SAFETY } from "./constants.js"; -import { stripImages } from "./images.js"; import llamaTokenizer from "./llamaTokenizer.js"; interface Encoding { encode: Tiktoken["encode"]; @@ -115,21 +115,28 @@ function countTokens( } } +function messageHasToolCalls(msg: ChatMessage): boolean { + return msg.role === "assistant" && !!msg.toolCalls; +} + export function flattenMessages(msgs: ChatMessage[]): ChatMessage[] { const flattened: ChatMessage[] = []; + for (let i = 0; i < msgs.length; i++) { const msg = msgs[i]; + if ( flattened.length > 0 && flattened[flattened.length - 1].role === msg.role && - !msg.toolCalls && - !flattened[flattened.length - 1].toolCalls + !messageHasToolCalls(msg) && + !messageHasToolCalls(flattened[flattened.length - 1]) ) { flattened[flattened.length - 1].content += `\n\n${msg.content || ""}`; } else { flattened.push(msg); } } + return flattened; } @@ -224,11 +231,8 @@ function pruneRawPromptFromBottom( return pruneStringFromBottom(modelName, maxTokens, prompt); } -function summarize(message: MessageContent): string { - if (Array.isArray(message)) { - return `${stripImages(message).substring(0, 100)}...`; - } - return `${message.substring(0, 100)}...`; +function summarize(message: ChatMessage): string { + return `${renderChatMessage(message).substring(0, 100)}...`; } function pruneChatHistory( @@ -259,7 +263,7 @@ function pruneChatHistory( for (let i = 0; i < longerThanOneThird.length; i++) { // Prune line-by-line from the top const message = longerThanOneThird[i]; - const content = stripImages(message.content); + const content = renderChatMessage(message); const deltaNeeded = totalTokens - contextLength; const delta = Math.min(deltaNeeded, distanceFromThird[i]); message.content = pruneStringFromTop( @@ -275,8 +279,8 @@ function pruneChatHistory( while (totalTokens > contextLength && i < chatHistory.length - 5) { const message = chatHistory[0]; totalTokens -= countTokens(message.content, modelName); - totalTokens += countTokens(summarize(message.content), modelName); - message.content = summarize(message.content); + totalTokens += countTokens(summarize(message), modelName); + message.content = summarize(message); i++; } @@ -299,8 +303,8 @@ function pruneChatHistory( ) { const message = chatHistory[i]; totalTokens -= countTokens(message.content, modelName); - totalTokens += countTokens(summarize(message.content), modelName); - message.content = summarize(message.content); + totalTokens += countTokens(summarize(message), modelName); + message.content = summarize(message); i++; } @@ -316,7 +320,7 @@ function pruneChatHistory( message.content = pruneRawPromptFromTop( modelName, contextLength, - stripImages(message.content), + renderChatMessage(message), tokensForCompletion, ); totalTokens = contextLength; @@ -378,7 +382,7 @@ function compileChatMessages( ) { let content = ""; if (msgs?.[0].role === "system") { - content = stripImages(msgs?.[0].content); + content = renderChatMessage(msgs?.[0]); } if (systemMessage && systemMessage.trim() !== "") { const shouldAddNewLines = content !== ""; @@ -413,7 +417,7 @@ function compileChatMessages( if (!supportsImages) { for (const msg of msgsCopy) { if ("content" in msg && Array.isArray(msg.content)) { - const content = stripImages(msg.content); + const content = renderChatMessage(msg); msg.content = content; } } diff --git a/core/llm/images.ts b/core/llm/images.ts deleted file mode 100644 index 912ae48ca..000000000 --- a/core/llm/images.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { MessageContent } from "../index.js"; - -export function stripImages(content: MessageContent): string { - if (Array.isArray(content)) { - return content - .filter((part) => part.type === "text") - .map((part) => part.text) - .join("\n"); - } - return content; - } \ No newline at end of file diff --git a/core/llm/index.ts b/core/llm/index.ts index 1156120a6..e46231ec4 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -24,6 +24,7 @@ import mergeJson from "../util/merge.js"; import { Telemetry } from "../util/posthog.js"; import { withExponentialBackoff } from "../util/withExponentialBackoff.js"; +import { renderChatMessage } from "../util/messageContent.js"; import { autodetectPromptTemplates, autodetectTemplateFunction, @@ -41,7 +42,6 @@ import { countTokens, pruneRawPromptFromTop, } from "./countTokens.js"; -import { stripImages } from "./images.js"; import CompletionOptionsForModels from "./templates/options.js"; export abstract class BaseLLM implements ILLM { @@ -372,7 +372,8 @@ export abstract class BaseLLM implements ILLM { `HTTP ${e.response.status} ${e.response.statusText} from ${e.response.url}\n\n${e.response.body}`, ); } else { - if (e.name !== "AbortError") { // Don't pollute console with abort errors. Check on name instead of instanceof, to avoid importing node-fetch here + if (e.name !== "AbortError") { + // Don't pollute console with abort errors. Check on name instead of instanceof, to avoid importing node-fetch here console.debug( `${e.message}\n\nCode: ${e.code}\nError number: ${e.errno}\nSyscall: ${e.erroredSysCall}\nType: ${e.type}\n\n${e.stack}`, ); @@ -414,7 +415,7 @@ export abstract class BaseLLM implements ILLM { let formatted = ""; for (const msg of msgsCopy) { if ("content" in msg && Array.isArray(msg.content)) { - const content = stripImages(msg.content); + const content = renderChatMessage(msg); msg.content = content; } formatted += `<${msg.role}>\n${msg.content || ""}\n\n`; @@ -533,7 +534,11 @@ export abstract class BaseLLM implements ILLM { }; } - async complete(_prompt: string, signal: AbortSignal, options: LLMFullCompletionOptions = {}) { + async complete( + _prompt: string, + signal: AbortSignal, + options: LLMFullCompletionOptions = {}, + ) { const { completionOptions, log, raw } = this._parseCompletionOptions(options); @@ -568,7 +573,11 @@ export abstract class BaseLLM implements ILLM { return completion; } - async chat(messages: ChatMessage[], signal: AbortSignal, options: LLMFullCompletionOptions = {}) { + async chat( + messages: ChatMessage[], + signal: AbortSignal, + options: LLMFullCompletionOptions = {}, + ) { let completion = ""; for await (const chunk of this.streamChat(messages, signal, options)) { completion += chunk.content; @@ -668,7 +677,11 @@ export abstract class BaseLLM implements ILLM { } } - protected async _complete(prompt: string, signal: AbortSignal, options: CompletionOptions) { + protected async _complete( + prompt: string, + signal: AbortSignal, + options: CompletionOptions, + ) { let completion = ""; for await (const chunk of this._streamComplete(prompt, signal, options)) { completion += chunk; diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index a5068e49b..c6fcc9bdf 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -4,7 +4,7 @@ import { LLMOptions, ModelProvider, } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamSse } from "../stream.js"; @@ -48,7 +48,7 @@ class Anthropic extends BaseLLM { { type: "tool_result", tool_use_id: message.toolCallId, - content: stripImages(message.content) || undefined, + content: renderChatMessage(message) || undefined, }, ], }; @@ -133,7 +133,7 @@ class Anthropic extends BaseLLM { ): AsyncGenerator { const messages = [{ role: "user" as const, content: prompt }]; for await (const update of this._streamChat(messages, signal, options)) { - yield stripImages(update.content); + yield renderChatMessage(update); } } @@ -144,9 +144,8 @@ class Anthropic extends BaseLLM { ): AsyncGenerator { const shouldCacheSystemMessage = !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage; - const systemMessage: string = stripImages( - messages.filter((m) => m.role === "system")[0]?.content, - ); + const systemMessage: string = + messages.filter((m) => m.role === "system")[0]?.content ?? ""; const msgs = this.convertMessages(messages); const response = await this.fetch(new URL("messages", this.apiBase), { diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 01a0201eb..7ca2783fa 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -11,7 +11,7 @@ import { MessageContent, ModelProvider, } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; class Bedrock extends BaseLLM { @@ -42,7 +42,7 @@ class Bedrock extends BaseLLM { ): AsyncGenerator { const messages = [{ role: "user" as const, content: prompt }]; for await (const update of this._streamChat(messages, signal, options)) { - yield stripImages(update.content); + yield renderChatMessage(update); } } @@ -86,7 +86,7 @@ class Bedrock extends BaseLLM { const input = this._generateConverseInput(messages, options); const command = new ConverseStreamCommand(input); - const response = await client.send(command, { abortSignal: signal}); + const response = await client.send(command, { abortSignal: signal }); if (response.stream) { for await (const chunk of response.stream) { @@ -122,7 +122,9 @@ class Bedrock extends BaseLLM { // TODO: Additionally, consider implementing a global exception handler for the providers to give users clearer feedback. // For example, differentiate between client-side errors (4XX status codes) and server-side issues (5XX status codes), // providing meaningful error messages to improve the user experience. - stopSequences: options.stop?.filter((stop) => stop.trim() !== "").slice(0, 4), + stopSequences: options.stop + ?.filter((stop) => stop.trim() !== "") + .slice(0, 4), }, }; } @@ -164,7 +166,7 @@ class Bedrock extends BaseLLM { try { return await fromIni({ profile: this.profile, - ignoreCache: true + ignoreCache: true, })(); } catch (e) { console.warn( diff --git a/core/llm/llms/Cloudflare.ts b/core/llm/llms/Cloudflare.ts index 07e2e427c..215e97b37 100644 --- a/core/llm/llms/Cloudflare.ts +++ b/core/llm/llms/Cloudflare.ts @@ -1,5 +1,5 @@ import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamSse } from "../stream.js"; @@ -36,7 +36,7 @@ export default class Cloudflare extends BaseLLM { model: this.model, ...this._convertArgs(options), }), - signal + signal, }); for await (const value of streamSse(resp)) { @@ -56,7 +56,7 @@ export default class Cloudflare extends BaseLLM { signal, options, )) { - yield stripImages(chunk.content); + yield renderChatMessage(chunk); } } } diff --git a/core/llm/llms/Cohere.ts b/core/llm/llms/Cohere.ts index 98135c7cc..a43df7a62 100644 --- a/core/llm/llms/Cohere.ts +++ b/core/llm/llms/Cohere.ts @@ -4,7 +4,7 @@ import { LLMOptions, ModelProvider, } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamJSON } from "../stream.js"; @@ -51,7 +51,7 @@ class Cohere extends BaseLLM { ): AsyncGenerator { const messages = [{ role: "user" as const, content: prompt }]; for await (const update of this._streamChat(messages, signal, options)) { - yield stripImages(update.content); + yield renderChatMessage(update); } } @@ -75,7 +75,7 @@ class Cohere extends BaseLLM { chat_history: this._convertMessages(messages), preamble: this.systemMessage, }), - signal + signal, }); if (options.stream === false) { diff --git a/core/llm/llms/Flowise.ts b/core/llm/llms/Flowise.ts index ecca89d16..8c5b0f459 100644 --- a/core/llm/llms/Flowise.ts +++ b/core/llm/llms/Flowise.ts @@ -6,7 +6,7 @@ import { LLMOptions, ModelProvider, } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; interface IFlowiseApiOptions { @@ -126,7 +126,7 @@ class Flowise extends BaseLLM { ): AsyncGenerator { const message: ChatMessage = { role: "user", content: prompt }; for await (const chunk of this._streamChat([message], signal, options)) { - yield stripImages(chunk.content); + yield renderChatMessage(chunk); } } @@ -141,7 +141,7 @@ class Flowise extends BaseLLM { method: "POST", headers: this._getHeaders(), body: JSON.stringify({ ...requestBody, socketIOClientId: socket.id }), - signal + signal, }).then((res) => res.json()); while (await socketInfo.hasNextToken()) { diff --git a/core/llm/llms/FreeTrial.ts b/core/llm/llms/FreeTrial.ts index 8f80c7418..895d6c42f 100644 --- a/core/llm/llms/FreeTrial.ts +++ b/core/llm/llms/FreeTrial.ts @@ -74,7 +74,7 @@ class FreeTrial extends BaseLLM { prompt, ...args, }), - signal + signal, }); let completion = ""; @@ -82,10 +82,18 @@ class FreeTrial extends BaseLLM { yield value; completion += value; } - this._countTokens(completion, args.model, false); + void this._countTokens(completion, args.model, false); } protected _convertMessage(message: ChatMessage) { + if (message.role === "tool") { + return { + role: "tool", + content: message.content, + tool_call_id: message.toolCallId, + }; + } + if (typeof message.content === "string") { return message; } @@ -123,7 +131,7 @@ class FreeTrial extends BaseLLM { messages: messages.map(this._convertMessage), ...args, }), - signal + signal, }); let completion = ""; @@ -158,7 +166,7 @@ class FreeTrial extends BaseLLM { suffix, ...args, }), - signal + signal, }); let completion = ""; diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index ada603240..e9cc484c8 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -5,7 +5,7 @@ import { MessagePart, ModelProvider, } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; @@ -19,7 +19,8 @@ class Gemini extends BaseLLM { }; // Function to convert completion options to Gemini format - public convertArgs(options: CompletionOptions) { // should be public for use within VertexAI + public convertArgs(options: CompletionOptions) { + // should be public for use within VertexAI const finalOptions: any = {}; // Initialize an empty object // Map known options @@ -54,17 +55,19 @@ class Gemini extends BaseLLM { signal, options, )) { - yield stripImages(message.content); + yield renderChatMessage(message); } } - public removeSystemMessage(messages: ChatMessage[]) { // should be public for use within VertexAI + public removeSystemMessage(messages: ChatMessage[]) { + // should be public for use within VertexAI const msgs = [...messages]; if (msgs[0]?.role === "system") { const sysMsg = msgs.shift()?.content; // @ts-ignore if (msgs[0]?.role === "user") { + // @ts-ignore msgs[0].content = `System message - follow these instructions in every response: ${sysMsg}\n\n---\n\n${msgs[0].content}`; } } @@ -143,6 +146,9 @@ class Gemini extends BaseLLM { if (msg.role === "system" && !isV1API) { return null; // Don't include system message in contents } + if (msg.role === "tool") { + return null; + } return { role: msg.role === "assistant" ? "model" : "user", parts: @@ -165,7 +171,7 @@ class Gemini extends BaseLLM { const response = await this.fetch(apiURL, { method: "POST", body: JSON.stringify(body), - signal + signal, }); let buffer = ""; @@ -234,7 +240,7 @@ class Gemini extends BaseLLM { const response = await this.fetch(apiURL, { method: "POST", body: JSON.stringify(body), - signal + signal, }); const data = await response.json(); yield { role: "assistant", content: data.candidates[0].content }; diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index dcaa078ba..69de3f1d9 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -4,13 +4,11 @@ import { LLMOptions, ModelProvider, } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; -interface OllamaChatMessage extends ChatMessage { - images?: string[]; -} +type OllamaChatMessage = ChatMessage & { images?: string[] }; // See https://github.com/ollama/ollama/blob/main/docs/modelfile.md for details on each parameter interface ModelFileParams { @@ -37,31 +35,29 @@ interface ModelFileParams { // See https://github.com/ollama/ollama/blob/main/docs/api.md interface BaseOptions { - model: string; // the model name + model: string; // the model name options?: ModelFileParams; // additional model parameters listed in the documentation for the Modelfile such as temperature - format?: "json"; // the format to return a response in. Currently, the only accepted value is json - stream?: boolean; // if false the response will be returned as a single response object, rather than a stream of objects - keep_alive?: number; // controls how long the model will stay loaded into memory following the request (default: 5m) + format?: "json"; // the format to return a response in. Currently, the only accepted value is json + stream?: boolean; // if false the response will be returned as a single response object, rather than a stream of objects + keep_alive?: number; // controls how long the model will stay loaded into memory following the request (default: 5m) } interface GenerateOptions extends BaseOptions { - prompt: string; // the prompt to generate a response for - suffix?: string; // the text after the model response - images?: string[]; // a list of base64-encoded images (for multimodal models such as llava) - system?: string; // system message to (overrides what is defined in the Modelfile) - template?: string; // the prompt template to use (overrides what is defined in the Modelfile) - context?: string; // the context parameter returned from a previous request to /generate, this can be used to keep a short conversational memory - raw?: boolean; // if true no formatting will be applied to the prompt. You may choose to use the raw parameter if you are specifying a full templated prompt in your request to the API + prompt: string; // the prompt to generate a response for + suffix?: string; // the text after the model response + images?: string[]; // a list of base64-encoded images (for multimodal models such as llava) + system?: string; // system message to (overrides what is defined in the Modelfile) + template?: string; // the prompt template to use (overrides what is defined in the Modelfile) + context?: string; // the context parameter returned from a previous request to /generate, this can be used to keep a short conversational memory + raw?: boolean; // if true no formatting will be applied to the prompt. You may choose to use the raw parameter if you are specifying a full templated prompt in your request to the API } interface ChatOptions extends BaseOptions { - messages: OllamaChatMessage[]; // the messages of the chat, this can be used to keep a chat memory + messages: OllamaChatMessage[]; // the messages of the chat, this can be used to keep a chat memory // Not supported yet - tools: tools for the model to use if supported. Requires stream to be set to false // And correspondingly, tool calls in OllamaChatMessage } - - class Ollama extends BaseLLM { static providerName: ModelProvider = "ollama"; static defaultOptions: Partial = { @@ -196,9 +192,11 @@ class Ollama extends BaseLLM { }; } - private _convertMessage( - message: ChatMessage - ) { + private _convertMessage(message: ChatMessage) { + if (message.role === "tool") { + return null; + } + if (typeof message.content === "string") { return message; } @@ -214,18 +212,18 @@ class Ollama extends BaseLLM { return { role: message.role, - content: stripImages(message.content), - images + content: renderChatMessage(message), + images, }; } private _getChatOptions( options: CompletionOptions, - messages: ChatMessage[] + messages: ChatMessage[], ): ChatOptions { return { model: this._getModel(), - messages: messages.map(this._convertMessage), + messages: messages.map(this._convertMessage).filter(Boolean) as any, options: this._getModelFileParams(options), keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes stream: options.stream, @@ -236,7 +234,7 @@ class Ollama extends BaseLLM { private _getGenerateOptions( options: CompletionOptions, prompt: string, - suffix?: string + suffix?: string, ): GenerateOptions { return { model: this._getModel(), @@ -271,7 +269,7 @@ class Ollama extends BaseLLM { Authorization: `Bearer ${this.apiKey}`, }, body: JSON.stringify(this._getGenerateOptions(options, prompt)), - signal + signal, }); let buffer = ""; @@ -312,7 +310,7 @@ class Ollama extends BaseLLM { Authorization: `Bearer ${this.apiKey}`, }, body: JSON.stringify(this._getChatOptions(options, messages)), - signal + signal, }); let buffer = ""; @@ -354,7 +352,6 @@ class Ollama extends BaseLLM { signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { - const response = await this.fetch(this.getEndpoint("api/generate"), { method: "POST", headers: { @@ -362,7 +359,7 @@ class Ollama extends BaseLLM { Authorization: `Bearer ${this.apiKey}`, }, body: JSON.stringify(this._getGenerateOptions(options, prefix, suffix)), - signal + signal, }); let buffer = ""; diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index eb9c3d7c9..10683c8a8 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -4,7 +4,7 @@ import { LLMOptions, ModelProvider, } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamSse } from "../stream.js"; @@ -56,6 +56,14 @@ class OpenAI extends BaseLLM { }; protected _convertMessage(message: ChatMessage) { + if (message.role === "tool") { + return { + role: "tool", + content: message.content, + tool_call_id: message.toolCallId, + }; + } + if (typeof message.content === "string") { return message; } else if (!message.content.some((item) => item.type !== "text")) { @@ -215,7 +223,7 @@ class OpenAI extends BaseLLM { signal, options, )) { - yield stripImages(chunk.content); + yield renderChatMessage(chunk); } } @@ -258,7 +266,7 @@ class OpenAI extends BaseLLM { options.raw) ) { for await (const content of this._legacystreamComplete( - stripImages(messages[messages.length - 1]?.content || ""), + renderChatMessage(messages[messages.length - 1]), signal, options, )) { diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index c17aac90d..c9254eacc 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -4,13 +4,11 @@ import { ChatMessage, CompletionOptions, LLMOptions, - MessagePart, ModelProvider, } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; -import { streamSse } from "../stream.js"; -import { streamResponse } from "../stream.js"; +import { streamResponse, streamSse } from "../stream.js"; import Anthropic from "./Anthropic.js"; import Gemini from "./Gemini.js"; @@ -40,16 +38,17 @@ class VertexAI extends BaseLLM { super(_options); this.apiBase ??= VertexAI.getDefaultApiBaseFrom(_options); this.vertexProvider = - _options.model.includes("mistral") || _options.model.includes("codestral") || _options.model.includes("mixtral") + _options.model.includes("mistral") || + _options.model.includes("codestral") || + _options.model.includes("mixtral") ? "mistral" : _options.model.includes("claude") ? "anthropic" : _options.model.includes("gemini") - ? "gemini" : - "unknown"; + ? "gemini" + : "unknown"; this.anthropicInstance = new Anthropic(_options); this.geminiInstance = new Gemini(_options); - } async fetch(url: RequestInfo | URL, init?: RequestInit) { @@ -82,18 +81,18 @@ class VertexAI extends BaseLLM { }; } - protected async *StreamChatAnthropic( messages: ChatMessage[], options: CompletionOptions, ): AsyncGenerator { - const shouldCacheSystemMessage = !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage; - const systemMessage: string = stripImages( - messages.filter((m) => m.role === "system")[0]?.content, + const shouldCacheSystemMessage = + !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage; + const systemMessage: string = renderChatMessage( + messages.filter((m) => m.role === "system")[0], ); const apiURL = new URL( `publishers/anthropic/models/${options.model}:streamRawPredict`, - this.apiBase + this.apiBase, ); const response = await this.fetch(apiURL, { @@ -108,12 +107,12 @@ class VertexAI extends BaseLLM { messages: this.anthropicInstance.convertMessages(messages), system: shouldCacheSystemMessage ? [ - { - type: "text", - text: this.systemMessage, - cache_control: { type: "ephemeral" }, - }, - ] + { + type: "text", + text: this.systemMessage, + cache_control: { type: "ephemeral" }, + }, + ] : systemMessage, }), }); @@ -125,14 +124,15 @@ class VertexAI extends BaseLLM { } for await (const value of streamSse(response)) { - if (value.type == "message_start") {console.log(value);} + if (value.type == "message_start") { + console.log(value); + } if (value.delta?.text) { yield { role: "assistant", content: value.delta.text }; } } } - //Gemini private async *streamChatGemini( @@ -152,6 +152,10 @@ class VertexAI extends BaseLLM { if (msg.role === "system" && !isV1API) { return null; // Don't include system message in contents } + if (msg.role === "tool") { + return null; + } + return { role: msg.role === "assistant" ? "model" : "user", parts: @@ -168,8 +172,8 @@ class VertexAI extends BaseLLM { // if this.systemMessage is defined, reformat it for Gemini API ...(this.systemMessage && !isV1API && { - systemInstruction: { parts: [{ text: this.systemMessage }] }, - }), + systemInstruction: { parts: [{ text: this.systemMessage }] }, + }), }; const response = await this.fetch(apiURL, { method: "POST", @@ -265,7 +269,6 @@ class VertexAI extends BaseLLM { //Mistral - protected async *StreamChatMistral( messages: ChatMessage[], options: CompletionOptions, @@ -330,7 +333,7 @@ class VertexAI extends BaseLLM { const response = await this.fetch(apiURL, { method: "POST", body: JSON.stringify(body), - signal + signal, }); for await (const chunk of streamSse(response)) { @@ -338,8 +341,6 @@ class VertexAI extends BaseLLM { } } - - //gecko protected async *streamFimGecko( prefix: string, @@ -347,15 +348,18 @@ class VertexAI extends BaseLLM { signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { - const endpoint = new URL("publishers/google/models/code-gecko:predict", this.apiBase); + const endpoint = new URL( + "publishers/google/models/code-gecko:predict", + this.apiBase, + ); const resp = await this.fetch(endpoint, { method: "POST", body: JSON.stringify({ instances: [ { prefix: prefix, - suffix: suffix - } + suffix: suffix, + }, ], parameters: { temperature: options.temperature, @@ -363,10 +367,9 @@ class VertexAI extends BaseLLM { stopSequences: options.stop?.splice(0, 5), frequencyPenalty: options.frequencyPenalty, presencePenalty: options.frequencyPenalty, - } - + }, }), - signal + signal, }); // Streaming is not supported by code-gecko // TODO: convert to non-streaming fim method when one exist in continue. @@ -409,7 +412,7 @@ class VertexAI extends BaseLLM { signal, options, )) { - yield stripImages(message.content); + yield renderChatMessage(message); } } @@ -419,9 +422,6 @@ class VertexAI extends BaseLLM { signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { - - - if (this.model === "code-gecko") { yield* this.streamFimGecko(prefix, suffix, signal, options); } else if (this.model.includes("codestral")) { @@ -429,21 +429,15 @@ class VertexAI extends BaseLLM { } else { throw new Error(`Unsupported model: ${this.model}`); } - - } supportsFim(): boolean { return ["code-gecko", "codestral-latest"].includes(this.model); } - - } async function delay(seconds: number) { return new Promise((resolve) => setTimeout(resolve, seconds * 1000)); } - - export default VertexAI; diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts index 808557692..fb82dacf9 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -4,25 +4,22 @@ import { LLMOptions, ModelProvider, } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; let watsonxToken = { - expiration: 0, - token: "" + expiration: 0, + token: "", }; class WatsonX extends BaseLLM { - constructor(options: LLMOptions) { super(options); } async getBearerToken(): Promise<{ token: string; expiration: number }> { - if ( - this.apiBase?.includes("cloud.ibm.com") - ) { + if (this.apiBase?.includes("cloud.ibm.com")) { // watsonx SaaS const wxToken = await ( await fetch( @@ -82,11 +79,9 @@ class WatsonX extends BaseLLM { } getWatsonxEndpoint(): string { - return ( - this.deploymentId ? - `${this.apiBase}/ml/v1/deployments/${this.deploymentId}/text/generation_stream?version=${this.apiVersion}`: - `${this.apiBase}/ml/v1/text/generation_stream?version=${this.apiVersion}` - ); + return this.deploymentId + ? `${this.apiBase}/ml/v1/deployments/${this.deploymentId}/text/generation_stream?version=${this.apiVersion}` + : `${this.apiBase}/ml/v1/text/generation_stream?version=${this.apiVersion}`; } static providerName: ModelProvider = "watsonx"; @@ -96,6 +91,10 @@ class WatsonX extends BaseLLM { return message; } + if (message.role === "tool") { + return null; + } + const parts = message.content.map((part) => { const msg: any = { type: part.type, @@ -119,7 +118,7 @@ class WatsonX extends BaseLLM { protected _convertArgs(options: any, messages: ChatMessage[]) { const finalOptions = { - messages: messages.map(this._convertMessage), + messages: messages.map(this._convertMessage).filter(Boolean), model: this._convertModelName(options.model), max_tokens: options.maxTokens, temperature: options.temperature, @@ -133,8 +132,9 @@ class WatsonX extends BaseLLM { protected _getHeaders() { return { "Content-Type": "application/json", - Authorization: `${watsonxToken.expiration === -1 ? "ZenApiKey" : "Bearer" - } ${watsonxToken.token}`, + Authorization: `${ + watsonxToken.expiration === -1 ? "ZenApiKey" : "Bearer" + } ${watsonxToken.token}`, }; } @@ -165,7 +165,7 @@ class WatsonX extends BaseLLM { signal, options, )) { - yield stripImages(chunk.content); + yield renderChatMessage(chunk); } } @@ -183,7 +183,8 @@ class WatsonX extends BaseLLM { watsonxToken = await this.getBearerToken(); } else { console.log( - `Reusing token (expires in ${(watsonxToken.expiration - now) / 60 + `Reusing token (expires in ${ + (watsonxToken.expiration - now) / 60 } mins)`, ); } @@ -191,7 +192,8 @@ class WatsonX extends BaseLLM { throw new Error("Something went wrong. Check your credentials, please."); } const stopSequences = - options.stop?.slice(0,6) ?? (options.model?.includes("granite") ? ["Question:"] : []); + options.stop?.slice(0, 6) ?? + (options.model?.includes("granite") ? ["Question:"] : []); const url = this.getWatsonxEndpoint(); const headers = this._getHeaders(); @@ -224,7 +226,7 @@ class WatsonX extends BaseLLM { method: "POST", headers: headers, body: JSON.stringify(payload), - signal + signal, }); if (!response.ok || response.body === null) { diff --git a/core/llm/templates/chat.ts b/core/llm/templates/chat.ts index 9d26620f4..a4b999b05 100644 --- a/core/llm/templates/chat.ts +++ b/core/llm/templates/chat.ts @@ -1,5 +1,5 @@ import { ChatMessage } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; function templateFactory( systemMessage: (msg: ChatMessage) => string, @@ -64,7 +64,7 @@ function llama2TemplateMessages(msgs: ChatMessage[]): string { let prompt = ""; let hasSystem = msgs[0].role === "system"; - if (hasSystem && stripImages(msgs[0].content).trim() === "") { + if (hasSystem && renderChatMessage(msgs[0]).trim() === "") { hasSystem = false; msgs = msgs.slice(1); } @@ -158,7 +158,7 @@ function deepseekTemplateMessages(msgs: ChatMessage[]): string { prompt += "You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer.\n"; if (msgs[0].role === "system") { - system = stripImages(msgs.shift()!.content); + system = renderChatMessage(msgs.shift()!); } for (let i = 0; i < msgs.length; i++) { @@ -245,7 +245,7 @@ function codeLlama70bTemplateMessages(msgs: ChatMessage[]): string { let prompt = ""; for (const msg of msgs) { - prompt += `Source: ${msg.role}\n\n ${stripImages(msg.content).trim()}`; + prompt += `Source: ${msg.role}\n\n ${renderChatMessage(msg).trim()}`; prompt += " "; } diff --git a/core/promptFiles/v1/slashCommandFromPromptFile.ts b/core/promptFiles/v1/slashCommandFromPromptFile.ts index 9e4f0c194..7d3750ad4 100644 --- a/core/promptFiles/v1/slashCommandFromPromptFile.ts +++ b/core/promptFiles/v1/slashCommandFromPromptFile.ts @@ -1,8 +1,8 @@ import * as YAML from "yaml"; import { ContinueSDK, SlashCommand } from "../.."; -import { stripImages } from "../../llm/images"; import { getBasename } from "../../util/index"; +import { renderChatMessage } from "../../util/messageContent"; import { getContextProviderHelpers } from "./getContextProviderHelpers"; import { renderTemplatedString } from "./renderTemplatedString"; @@ -90,8 +90,11 @@ export function slashCommandFromPromptFile( systemMessage, ); - for await (const chunk of context.llm.streamChat(messages, new AbortController().signal)) { - yield stripImages(chunk.content); + for await (const chunk of context.llm.streamChat( + messages, + new AbortController().signal, + )) { + yield renderChatMessage(chunk); } }, }; diff --git a/core/protocol/core.ts b/core/protocol/core.ts index f49fde837..a3f11f4ea 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -4,6 +4,7 @@ import { ProfileDescription } from "../config/ConfigHandler"; import type { BrowserSerializedContinueConfig, ChatMessage, + ContextItem, ContextItemWithId, ContextSubmenuItem, DiffLine, @@ -160,5 +161,5 @@ export type ToCoreFromIdeOrWebviewProtocol = { "profiles/switch": [{ id: string }, undefined]; "auth/getAuthUrl": [undefined, { url: string }]; - "tools/call": [{ toolCall: ToolCall }, { result: any }]; + "tools/call": [{ toolCall: ToolCall }, { contextItems: ContextItem[] }]; }; diff --git a/core/tools/createNewFile.ts b/core/tools/createNewFile.ts index 4d0b1c7a1..50a067f5e 100644 --- a/core/tools/createNewFile.ts +++ b/core/tools/createNewFile.ts @@ -14,6 +14,7 @@ export const createNewFileTool: Tool = { } await extras.ide.writeFile(filepath, args.contents); await extras.ide.openFile(filepath); + return []; }, function: { name: "create_new_file", diff --git a/core/tools/exactSearch.ts b/core/tools/exactSearch.ts index 2735b24a0..81bd061a4 100644 --- a/core/tools/exactSearch.ts +++ b/core/tools/exactSearch.ts @@ -3,8 +3,14 @@ import { Tool } from ".."; export const exactSearchTool: Tool = { type: "function", action: async (args, extras) => { - const results = await extras.ide.getSearchResults(args.query); - return results; + const content = await extras.ide.getSearchResults(args.query); + return [ + { + name: "Search results", + description: "Results from exact search", + content, + }, + ]; }, function: { name: "exact_search", diff --git a/core/tools/runTerminalCommand.ts b/core/tools/runTerminalCommand.ts index 4982ec972..6788c46d5 100644 --- a/core/tools/runTerminalCommand.ts +++ b/core/tools/runTerminalCommand.ts @@ -3,7 +3,16 @@ import { Tool } from ".."; export const runTerminalCommandTool: Tool = { type: "function", action: async (args, extras) => { - await extras.ide.runCommand(args.command); + const output = await extras.ide.runCommand(args.command); + + return []; + // return [ + // { + // description: "The contents of the terminal", + // content: output, + // name: "Terminal", + // }, + // ]; }, function: { name: "run_terminal_command", diff --git a/core/tools/searchWeb.ts b/core/tools/searchWeb.ts index 4a7c32788..3f5ded0b7 100644 --- a/core/tools/searchWeb.ts +++ b/core/tools/searchWeb.ts @@ -5,7 +5,7 @@ export const searchWebTool: Tool = { type: "function", action: async (args, extras) => { const webResults = await fetchSearchResults(args.query, 5, extras.fetch); - return webResults.map((result) => result.content).join("\n\n"); + return webResults; }, function: { name: "search_web", diff --git a/core/tools/viewDiff.ts b/core/tools/viewDiff.ts index 82439c54c..6bb327e2c 100644 --- a/core/tools/viewDiff.ts +++ b/core/tools/viewDiff.ts @@ -4,7 +4,13 @@ export const viewDiffTool: Tool = { type: "function", action: async (args, extras) => { const diff = await extras.ide.getDiff(true); - return diff; + return [ + { + name: "Diff", + description: "The current git diff", + content: diff, + }, + ]; }, function: { name: "view_diff", diff --git a/core/tools/viewRepoMap.ts b/core/tools/viewRepoMap.ts index c96f5ed27..9466c6be6 100644 --- a/core/tools/viewRepoMap.ts +++ b/core/tools/viewRepoMap.ts @@ -5,7 +5,13 @@ export const viewRepoMapTool: Tool = { type: "function", action: async (args, extras) => { const repoMap = await generateRepoMap(extras.llm, extras.ide, {}); - return repoMap; + return [ + { + name: "Repo map", + description: "Overview of the repository structure", + content: repoMap, + }, + ]; }, function: { name: "view_repo_map", diff --git a/core/tools/viewSubdirectory.ts b/core/tools/viewSubdirectory.ts index c3e83a39a..583266c52 100644 --- a/core/tools/viewSubdirectory.ts +++ b/core/tools/viewSubdirectory.ts @@ -8,7 +8,13 @@ export const viewSubdirectoryTool: Tool = { const repoMap = await generateRepoMap(extras.llm, extras.ide, { dirs: [directory_path], }); - return repoMap; + return [ + { + name: "Repo map", + description: `Map of ${directory_path}`, + content: repoMap, + }, + ]; }, function: { name: "view_subdirectory", diff --git a/core/util/chatDescriber.ts b/core/util/chatDescriber.ts index b8ca609a2..b52fd7696 100644 --- a/core/util/chatDescriber.ts +++ b/core/util/chatDescriber.ts @@ -1,5 +1,4 @@ import { ILLM, LLMFullCompletionOptions } from ".."; -import { stripImages } from "../llm/images"; import { removeQuotesAndEscapes } from "."; @@ -35,7 +34,6 @@ export class ChatDescriber { } // Clean up and distill the message we want to send to the LLM - message = stripImages(message); message = removeCodeBlocksAndTrim(message); if (!message) { diff --git a/core/util/messageContent.ts b/core/util/messageContent.ts new file mode 100644 index 000000000..b42bb082a --- /dev/null +++ b/core/util/messageContent.ts @@ -0,0 +1,45 @@ +import { + ChatMessage, + ContextItem, + MessageContent, + MessagePart, +} from "../index.js"; + +export function stripImages(messageContent: MessageContent): string { + if (typeof messageContent === "string") { + return messageContent; + } + + return messageContent + .filter((part) => part.type === "text") + .map((part) => part.text) + .join("\n"); +} + +export function renderChatMessage(message: ChatMessage): string { + switch (message.role) { + case "user": + case "assistant": + case "system": + return stripImages(message.content); + case "tool": + return message.content; + } +} + +export function renderContextItems(contextItems: ContextItem[]): string { + return contextItems.map((item) => item.content).join("\n\n"); +} + +export function normalizeToMessageParts(message: ChatMessage): MessagePart[] { + switch (message.role) { + case "user": + case "assistant": + case "system": + return Array.isArray(message.content) + ? message.content + : [{ type: "text", text: message.content }]; + case "tool": + return [{ type: "text", text: message.content }]; + } +} diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 3b5baad5f..28bce52b9 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -4,7 +4,6 @@ import * as path from "node:path"; import { ConfigHandler } from "core/config/ConfigHandler"; import { getModelByRole } from "core/config/util"; import { applyCodeBlock } from "core/edit/lazy/applyCodeBlock"; -import { stripImages } from "core/llm/images"; import { FromCoreProtocol, FromWebviewProtocol, @@ -22,6 +21,7 @@ import { InProcessMessenger, Message } from "core/util/messenger"; import { getConfigJsonPath } from "core/util/paths"; import * as vscode from "vscode"; +import { stripImages } from "core/util/messageContent"; import { VerticalDiffManager } from "../diff/vertical/manager"; import EditDecorationManager from "../quickEdit/EditDecorationManager"; import { diff --git a/gui/src/components/StepContainer/MultifileEditActions.tsx b/gui/src/components/StepContainer/MultifileEditActions.tsx index 5fb7122df..d3c292ce4 100644 --- a/gui/src/components/StepContainer/MultifileEditActions.tsx +++ b/gui/src/components/StepContainer/MultifileEditActions.tsx @@ -1,10 +1,11 @@ +import { ChatHistoryItem } from "core"; import { useSelector } from "react-redux"; import { RootState } from "../../redux/store"; import AcceptRejectAllButtons from "./AcceptRejectAllButtons"; import FeedbackButtons from "./FeedbackButtons"; import UndoAndRedoButtons from "./UndoAndRedoButtons"; -import { ChatHistoryItem } from "core"; -import { stripImages } from "core/llm/images"; + +import { renderChatMessage } from "core/util/messageContent"; import { CopyIconButton } from "../gui/CopyIconButton"; export interface MultifileEditActionsProps { @@ -53,7 +54,7 @@ export default function MultifileEditActions({
diff --git a/gui/src/components/StepContainer/ResponseActions.tsx b/gui/src/components/StepContainer/ResponseActions.tsx index 138e93c6a..7f61e2241 100644 --- a/gui/src/components/StepContainer/ResponseActions.tsx +++ b/gui/src/components/StepContainer/ResponseActions.tsx @@ -1,6 +1,6 @@ import { BarsArrowDownIcon, TrashIcon } from "@heroicons/react/24/outline"; import { ChatHistoryItem } from "core"; -import { stripImages } from "core/llm/images"; +import { renderChatMessage } from "core/util/messageContent"; import { useSelector } from "react-redux"; import { RootState } from "../../redux/store"; import { CopyIconButton } from "../gui/CopyIconButton"; @@ -54,7 +54,7 @@ export default function ResponseActions({ diff --git a/gui/src/components/StepContainer/StepContainer.tsx b/gui/src/components/StepContainer/StepContainer.tsx index 610cfd0f9..6aeaee32e 100644 --- a/gui/src/components/StepContainer/StepContainer.tsx +++ b/gui/src/components/StepContainer/StepContainer.tsx @@ -1,5 +1,5 @@ import { ChatHistoryItem } from "core"; -import { stripImages } from "core/llm/images"; +import { renderChatMessage } from "core/util/messageContent"; import { useEffect, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import styled from "styled-components"; @@ -42,7 +42,7 @@ export default function StepContainer(props: StepContainerProps) { useEffect(() => { if (!active) { - const content = stripImages(props.item.message.content).trim(); + const content = renderChatMessage(props.item.message).trim(); const endingPunctuation = [".", "?", "!", "```", ":"]; // If not ending in punctuation or emoji, we assume the response got truncated @@ -88,12 +88,12 @@ export default function StepContainer(props: StepContainerProps) { className="max-w-full overflow-x-auto whitespace-pre-wrap break-words p-4" style={{ fontSize: getFontSize() - 2 }} > - {stripImages(props.item.message.content)} + {renderChatMessage(props.item.message)} ) : ( )} diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index 64acba85a..09f38869c 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -7,7 +7,7 @@ import { MessagePart, RangeInFile, } from "core"; -import { stripImages } from "core/llm/images"; +import { stripImages } from "core/util/messageContent"; import { IIdeMessenger } from "../../context/IdeMessenger"; interface MentionAttrs { diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index 21face2a7..a6de4883d 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -4,6 +4,7 @@ import { ChatHistory, ChatHistoryItem, ChatMessage, + ContextItem, ContextItemWithId, InputModifiers, MessageContent, @@ -12,8 +13,11 @@ import { SlashCommandDescription, } from "core"; import { constructMessages } from "core/llm/constructMessages"; -import { stripImages } from "core/llm/images"; import { getBasename, getRelativePath } from "core/util"; +import { + renderChatMessage, + renderContextItems, +} from "core/util/messageContent"; import { usePostHog } from "posthog-js/react"; import { useEffect, useRef, useState } from "react"; import { useSelector } from "react-redux"; @@ -122,7 +126,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { } // Convert to actual slash command object with runnable function - return [slashCommand, stripImages(input)]; + return [slashCommand, renderChatMessage({ role: "user", content: input })]; }; async function _streamSlashCommand( @@ -352,14 +356,14 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { async function streamResponseAfterToolCall( toolCallId: string, - toolOutput: string, + toolOutput: ContextItem[], ) { await handleErrors(async () => { resetStateForNewMessage(); const newMessage: ChatMessage = { role: "tool", - content: toolOutput, + content: renderContextItems(toolOutput), toolCallId, }; diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index bb5935653..d4a09421e 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -1,7 +1,6 @@ import { Dispatch } from "@reduxjs/toolkit"; import { PersistedSessionInfo, SessionInfo } from "core"; -import { stripImages } from "core/llm/images"; import { useCallback, useContext } from "react"; import { useSelector } from "react-redux"; import { IdeMessengerContext } from "../context/IdeMessenger"; @@ -10,6 +9,7 @@ import { defaultModelSelector } from "../redux/selectors/modelSelectors"; import { newSession } from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; +import { renderChatMessage } from "core/util/messageContent"; const MAX_TITLE_LENGTH = 100; @@ -79,7 +79,7 @@ function useHistory(dispatch: Dispatch) { let title = stateCopy.title === "New Session" ? truncateText( - stripImages(stateCopy.history[0].message.content) + renderChatMessage(stateCopy.history[0].message) .split("\n") .filter((l) => l.trim() !== "") .slice(-1)[0] || "", diff --git a/gui/src/pages/edit/index.tsx b/gui/src/pages/edit/index.tsx index c601c9650..602b2c0f1 100644 --- a/gui/src/pages/edit/index.tsx +++ b/gui/src/pages/edit/index.tsx @@ -1,7 +1,7 @@ import { ArrowLeftIcon } from "@heroicons/react/24/outline"; import { Editor, JSONContent } from "@tiptap/core"; import { InputModifiers } from "core"; -import { stripImages } from "core/llm/images"; +import { renderChatMessage } from "core/util/messageContent"; import { useContext, useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; import { useNavigate } from "react-router-dom"; @@ -178,7 +178,10 @@ function Edit() { const prompt = [ ...contextItems.map((item) => item.content), - stripImages(userInstructions), + renderChatMessage({ + role: "user", + content: userInstructions, + }), ].join("\n\n"); ideMessenger.post("edit/sendPrompt", { prompt, diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index d7e41bfde..b1ffbf25c 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -6,7 +6,7 @@ import { } from "@heroicons/react/24/outline"; import { JSONContent } from "@tiptap/react"; import { InputModifiers } from "core"; -import { stripImages } from "core/llm/images"; +import { renderChatMessage } from "core/util/messageContent"; import { usePostHog } from "posthog-js/react"; import { Fragment, @@ -350,7 +350,7 @@ export function Chat() { /> ) : item.message.role === "tool" ? ( ) : item.message.role === "assistant" && diff --git a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificHeader.tsx b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificHeader.tsx index 207945a8e..fea85ca9f 100644 --- a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificHeader.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificHeader.tsx @@ -10,22 +10,33 @@ export function FunctionSpecificHeader(props: FunctionSpecificHeaderProps) { props.toolCall.function.arguments, ); + let message; + switch (props.toolCall.function.name) { case "create_new_file": - return "Continue wants to create a new file"; + message = "Continue wants to create a new file"; + break; case "run_terminal_command": - return "Continue wants to run a terminal command."; + message = "Continue wants to run a terminal command."; + break; case "exact_search": - return "Continue wants to search your codebase"; + message = "Continue wants to search your codebase"; + break; case "search_web": - return "Continue wants to search the internet"; + message = "Continue wants to search the internet"; + break; case "view_diff": - return "Continue wants to view the current git diff"; + message = "Continue wants to view the current git diff"; + break; case "view_repo_map": - return "Continue wants to view a map of your repository"; + message = "Continue wants to view a map of your repository"; + break; case "view_subdirectory": - return `Continue wants to view the contents of ${incrementalJson.directory_path ?? "a subdirectory"}`; + message = `Continue wants to view the contents of ${incrementalJson.directory_path ?? "a subdirectory"}`; + break; default: - return `Continue wants to use the ${props.toolCall.function.name} function.`; + message = `Continue wants to use the ${props.toolCall.function.name} function.`; } + + return
{message}
; } diff --git a/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx b/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx index 3ea14c8bf..7143769ac 100644 --- a/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx @@ -85,11 +85,9 @@ export function ToolCallButtons(props: ToolCallButtonsProps) { clearTimeout(timer); if (result.status === "success") { + const contextItems = result.content.contextItems; // Send to the LLM to continue the conversation - streamResponseAfterToolCall( - toolCallState.toolCall.id, - result.content.result, - ); + streamResponseAfterToolCall(toolCallState.toolCall.id, contextItems); } } diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index ff5db6c02..cf2e6fa96 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -11,8 +11,8 @@ import { } from "core"; import { BrowserSerializedContinueConfig } from "core/config/load"; import { ConfigValidationError } from "core/config/validation"; -import { stripImages } from "core/llm/images"; import { ApplyState } from "core/protocol/ideWebview"; +import { renderChatMessage } from "core/util/messageContent"; import { v4 as uuidv4, v4 } from "uuid"; import { ToolState } from "../../pages/gui/ToolCallDiv/types"; @@ -30,9 +30,15 @@ type ChatHistoryItemWithMessageId = ChatHistoryItem & { type State = { currentToolCallState: CurrentToolCallState; history: ChatHistoryItemWithMessageId[]; - ttsActive: boolean; active: boolean; isGatheringContext: boolean; + checkpoints: Checkpoint[]; + applyStates: ApplyState[]; + nextCodeBlockToApplyIndex: number; + streamAborter: AbortController; + curCheckpointIndex: number; + + ttsActive: boolean; config: BrowserSerializedContinueConfig; title: string; sessionId: string; @@ -40,11 +46,6 @@ type State = { mainEditorContent?: JSONContent; selectedProfileId: string; configError: ConfigValidationError[] | undefined; - checkpoints: Checkpoint[]; - curCheckpointIndex: number; - applyStates: ApplyState[]; - nextCodeBlockToApplyIndex: number; - streamAborter: AbortController; isMultifileEdit: boolean; }; @@ -227,7 +228,7 @@ export const stateSlice = createSlice({ message: { ...payload.message, id: uuidv4() }, editorState: { type: "doc", - content: stripImages(payload.message.content) + content: renderChatMessage(payload.message) .split("\n") .map((line) => ({ type: "paragraph", @@ -281,6 +282,7 @@ export const stateSlice = createSlice({ (lastMessage.message.role !== action.payload.role || // This is when a tool call comes after assistant text (lastMessage.message.content !== "" && + action.payload.role === "assistant" && action.payload.toolCalls?.length)) ) { // Create a new message @@ -292,8 +294,12 @@ export const stateSlice = createSlice({ // Add to the existing message const msg = state.history[state.history.length - 1].message; if (action.payload.content) { - msg.content += stripImages(action.payload.content); - } else if (action.payload.toolCalls) { + msg.content += renderChatMessage(action.payload); + } else if ( + action.payload.role === "assistant" && + action.payload.toolCalls && + msg.role === "assistant" + ) { if (!msg.toolCalls) { msg.toolCalls = []; } diff --git a/manual-testing-sandbox/test.ts b/manual-testing-sandbox/test.ts new file mode 100644 index 000000000..9cf524421 --- /dev/null +++ b/manual-testing-sandbox/test.ts @@ -0,0 +1,41 @@ +class Calculator { + private result: number; + + constructor() { + this.result = 0; + } + + add(number: number): Calculator { + this.result += number; + return this; + } + + subtract(number: number): Calculator { + this.result -= number; + return this; + } + + multiply(number: number): Calculator { + this.result *= number; + return this; + } + + divide(number: number): Calculator { + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + } + + getResult(): number { + return this.result; + } + + reset(): Calculator { + this.result = 0; + return this; + } +} + +export default Calculator; \ No newline at end of file