From 73319c7eb706e9decf1ed9a8fa1d5bc3df6cd9ab Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 18 Sep 2024 23:57:45 -0700 Subject: [PATCH] combine system messages for all LLMs --- core/llm/constructMessages.ts | 84 ++++++++++++++++++++++++++++++++- core/llm/countTokens.ts | 22 +++++++-- core/llm/index.ts | 11 ----- core/llm/llms/Anthropic.ts | 75 ++--------------------------- gui/src/hooks/useChatHandler.ts | 2 +- 5 files changed, 107 insertions(+), 87 deletions(-) diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index aaf23563e..d339134e3 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -1,8 +1,90 @@ import { ChatHistory, ChatMessage, MessagePart } from "../index.js"; -export function constructMessages(history: ChatHistory): ChatMessage[] { +const SYSTEM_MESSAGE = `When generating new code: + +1. Always produce a single code block. +2. Never separate the code into multiple code blocks. +3. Only include the code that is being added. +4. Replace existing code with a "lazy" block like this: "// ... existing code ..." +5. You must always provide 1-2 lines of context above and below a "lazy" block +6. If the user submits a code block that contains a filename in the language specifier, always include the filename in any code block you generate based on that file. The filename should be on the same line as the language specifier in your code block. + +Example 1: +Input: +\`\`\`test.js +import addition from "addition" + +class Calculator { + constructor() { + this.result = 0; + } + + add(number) { + this.result += number; + return this; + } +} +\`\`\` +User request: Add a subtract method + +Output: +\`\`\`javascript test.js +// ... existing code ... +import subtraction from "subtraction" + +class Calculator { + // ... existing code ... + + subtract(number) { + this.result -= number; + return this; + } +} +\`\`\` + +Example 2: +Input: +\`\`\`javascript test.js (6-9) +function helloWorld() {} +\`\`\` + +Output: +\`\`\`javascript test.js +function helloWorld() { + // New code here +} +\`\`\` + +Always follow these guidelines when generating code responses.`; + +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, +): ChatMessage[] { const msgs = []; + // Only using this system message with Sonnet right now + if ( + // hasCodeBlockWithFilename(history[0].message.content) && + model.includes("sonnet") + ) { + msgs.push({ + role: "system" as const, + content: SYSTEM_MESSAGE, + }); + } + for (let i = 0; i < history.length; i++) { const historyItem = history[i]; diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 06cd4a3bb..0fbadf68b 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -332,7 +332,9 @@ function compileChatMessages( systemMessage: string | undefined = undefined, ): ChatMessage[] { const msgsCopy = msgs - ? msgs.map((msg) => ({ ...msg })).filter((msg) => msg.content !== "") + ? msgs + .map((msg) => ({ ...msg })) + .filter((msg) => msg.content !== "" && msg.role !== "system") : []; if (prompt) { @@ -343,10 +345,24 @@ function compileChatMessages( msgsCopy.push(promptMsg); } - if (systemMessage && systemMessage.trim() !== "") { + if ( + (systemMessage && systemMessage.trim() !== "") || + msgs?.[0].role === "system" + ) { + let content = ""; + if (msgs?.[0].role === "system") { + content = stripImages(msgs?.[0].content); + } + if (systemMessage && systemMessage.trim() !== "") { + const shouldAddNewLines = content !== ""; + if (shouldAddNewLines) { + content += "\n\n"; + } + content += systemMessage; + } const systemChatMsg: ChatMessage = { role: "system", - content: systemMessage, + content, }; // Insert as second to last // Later moved to top, but want second-priority to last user message diff --git a/core/llm/index.ts b/core/llm/index.ts index 046d7af3d..1f76ed64c 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -561,17 +561,6 @@ ${prompt}`; return { role: "assistant" as ChatMessageRole, content: completion }; } - 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); - } - async *streamChat( _messages: ChatMessage[], options: LLMFullCompletionOptions = {}, diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index 497629338..1f9bea56e 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -20,63 +20,6 @@ class Anthropic extends BaseLLM { apiBase: "https://api.anthropic.com/v1/", }; - static lazySystemMessage: string = `When generating new code: - -1. Always produce a single code block. -2. Never separate the code into multiple code blocks. -3. Only include the code that is being added. -4. Replace existing code with a "lazy" block like this: "// ... existing code ..." -5. You must always provide 1-2 lines of context above and below a "lazy" block -6. If the user submits a code block that contains a filename in the language specifier, always include the filename in any code block you generate based on that file. The filename should be on the same line as the language specifier in your code block. - -Example 1: -Input: -\`\`\`test.js -import addition from "addition" - -class Calculator { - constructor() { - this.result = 0; - } - - add(number) { - this.result += number; - return this; - } -} -\`\`\` -User request: Add a subtract method - -Output: -\`\`\`javascript test.js -// ... existing code ... -import subtraction from "subtraction" - -class Calculator { - // ... existing code ... - - subtract(number) { - this.result -= number; - return this; - } -} -\`\`\` - -Example 2: -Input: -\`\`\`javascript test.js (6-9) -function helloWorld() {} -\`\`\` - -Output: -\`\`\`javascript test.js -function helloWorld() { - // New code here -} -\`\`\` - -Always follow these guidelines when generating code responses.`; - private _convertArgs(options: CompletionOptions) { const finalOptions = { top_k: options.topK, @@ -135,17 +78,9 @@ Always follow these guidelines when generating code responses.`; const shouldCacheSystemMessage = !!this.systemMessage && !!this.cacheSystemMessage; - // This likely should be set in the base class where we wrap - // _streamChat in a try/catch - let curSystemMsg = this.systemMessage; - - // We only are doing lazy prompting with Sonnet right now - if ( - this.hasCodeBlockWithFilename(messages[0].content) && - options.model?.includes("sonnet") - ) { - this.systemMessage = `${this.systemMessage} ${Anthropic.lazySystemMessage}`; - } + const systemMessage: string = stripImages( + messages.filter((m) => m.role === "system")[0].content, + ); const response = await this.fetch(new URL("messages", this.apiBase), { method: "POST", @@ -169,7 +104,7 @@ Always follow these guidelines when generating code responses.`; cache_control: { type: "ephemeral" }, }, ] - : this.systemMessage, + : systemMessage, }), }); @@ -184,8 +119,6 @@ Always follow these guidelines when generating code responses.`; yield { role: "assistant", content: value.delta.text }; } } - - this.systemMessage = curSystemMsg; } } diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index aec90a4bf..0de66bd44 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -253,7 +253,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { }); posthog.capture("userInput", {}); - const messages = constructMessages(newHistory); + const messages = constructMessages(newHistory, defaultModel.model); // Determine if the input is a slash command let commandAndInput = getSlashCommandForInput(content);