From c1a8fb7e03603b73a9528533bb5f84a98bc4526e Mon Sep 17 00:00:00 2001 From: Test Date: Tue, 17 Sep 2024 19:17:48 -0700 Subject: [PATCH] add lazy system msg for anthropic --- core/core.ts | 59 +++++----- core/llm/index.ts | 24 +++- core/llm/llms/Anthropic.ts | 64 ++++++++++ extensions/vscode/package-lock.json | 4 +- extensions/vscode/package.json | 2 +- gui/src/components/FileIcon.tsx | 2 + .../components/markdown/CodeBlockToolbar.tsx | 110 +++++++++--------- .../markdown/CodeSnippetPreview.tsx | 6 +- .../components/markdown/PreWithToolbar.tsx | 4 +- .../markdown/StyledMarkdownPreview.tsx | 27 ++--- 10 files changed, 194 insertions(+), 108 deletions(-) diff --git a/core/core.ts b/core/core.ts index b07c35c54..f33ab17d4 100644 --- a/core/core.ts +++ b/core/core.ts @@ -119,7 +119,7 @@ export class Core { (resolve) => (continueServerClientResolve = resolve), ); - ideSettingsPromise.then((ideSettings) => { + void ideSettingsPromise.then((ideSettings) => { const continueServerClient = new ContinueServerClient( ideSettings.remoteConfigServerUrl, ideSettings.userToken, @@ -136,7 +136,7 @@ export class Core { ); // Index on initialization - this.ide.getWorkspaceDirs().then(async (dirs) => { + void this.ide.getWorkspaceDirs().then(async (dirs) => { // Respect pauseCodebaseIndexOnStart user settings if (ideSettings.pauseCodebaseIndexOnStart) { await this.messenger.request("indexProgress", { @@ -147,7 +147,7 @@ export class Core { return; } - this.refreshCodebaseIndex(dirs); + void this.refreshCodebaseIndex(dirs); }); }); @@ -172,11 +172,11 @@ export class Core { this.messenger.onError((err) => { console.error(err); - Telemetry.capture("core_messenger_error", { + void Telemetry.capture("core_messenger_error", { message: err.message, stack: err.stack, }); - this.ide.showToast("error", err.message); + void this.ide.showToast("error", err.message); }); // New @@ -186,7 +186,7 @@ export class Core { on("update/selectTabAutocompleteModel", async (msg) => { this.globalContext.update("selectedTabAutocompleteModel", msg.data); - this.configHandler.reloadConfig(); + void this.configHandler.reloadConfig(); }); // Special @@ -227,29 +227,29 @@ export class Core { on("config/addModel", (msg) => { const model = msg.data.model; addModel(model); - this.configHandler.reloadConfig(); + void this.configHandler.reloadConfig(); }); on("config/addOpenAiKey", (msg) => { addOpenAIKey(msg.data); - this.configHandler.reloadConfig(); + void this.configHandler.reloadConfig(); }); on("config/deleteModel", (msg) => { deleteModel(msg.data.title); - this.configHandler.reloadConfig(); + void this.configHandler.reloadConfig(); }); on("config/newPromptFile", async (msg) => { - createNewPromptFile( + void createNewPromptFile( this.ide, (await this.config()).experimental?.promptPath, ); - this.configHandler.reloadConfig(); + void this.configHandler.reloadConfig(); }); on("config/reload", (msg) => { - this.configHandler.reloadConfig(); + void this.configHandler.reloadConfig(); return this.configHandler.getSerializedConfig(); }); @@ -272,9 +272,12 @@ export class Core { } if (hasFailed) { - this.ide.showToast("info", `Failed to index ${msg.data.startUrl}`); + void this.ide.showToast("info", `Failed to index ${msg.data.startUrl}`); } else { - this.ide.showToast("info", `Successfully indexed ${msg.data.startUrl}`); + void this.ide.showToast( + "info", + `Successfully indexed ${msg.data.startUrl}`, + ); this.messenger.send("refreshSubmenuItems", undefined); } }); @@ -331,7 +334,7 @@ export class Core { fetchwithRequestOptions(url, init, config.requestOptions), }); - Telemetry.capture( + void Telemetry.capture( "useContextProvider", { name: provider.description.title, @@ -344,7 +347,7 @@ export class Core { id, })); } catch (e) { - this.ide.showToast( + void this.ide.showToast( "error", `Error getting context items from ${name}: ${e}`, ); @@ -368,7 +371,7 @@ export class Core { // Stop TTS on new StreamChat if (config.experimental?.readResponseTTS) { - TTS.kill(); + void TTS.kill(); } const model = await configHandler.llmFromTitle(msg.data.title); @@ -396,7 +399,7 @@ export class Core { } if (config.experimental?.readResponseTTS && "completion" in next.value) { - TTS.read(next.value?.completion); + void TTS.read(next.value?.completion); } return { done: true, content: next.value }; @@ -477,7 +480,7 @@ export class Core { TTS.messenger = this.messenger; on("tts/kill", async () => { - TTS.kill(); + void TTS.kill(); }); async function* runNodeJsSlashCommand( @@ -506,7 +509,7 @@ export class Core { throw new Error(`Unknown slash command ${slashCommandName}`); } - Telemetry.capture( + void Telemetry.capture( "useSlashCommand", { name: slashCommandName, @@ -529,7 +532,7 @@ export class Core { params, ide, addContextItem: (item) => { - messenger.request("addContextItem", { + void messenger.request("addContextItem", { item, historyIndex, }); @@ -636,7 +639,7 @@ export class Core { editConfigJson(editConfigJsonCallback); - this.configHandler.reloadConfig(); + void this.configHandler.reloadConfig(); }); on("addAutocompleteModel", (msg) => { @@ -646,7 +649,7 @@ export class Core { tabAutocompleteModel: msg.data.model, }; }); - this.configHandler.reloadConfig(); + void this.configHandler.reloadConfig(); }); on("stats/getTokensPerDay", async (msg) => { @@ -674,13 +677,13 @@ export class Core { // Triggered when progress bar is initialized. // If a non-default state has been stored, update the indexing display to that state if (this.indexingState.status !== "loading") { - this.messenger.request("indexProgress", this.indexingState); + void this.messenger.request("indexProgress", this.indexingState); } }); on("didChangeSelectedProfile", (msg) => { - this.configHandler.setSelectedProfile(msg.data.id); - this.configHandler.reloadConfig(); + void this.configHandler.setSelectedProfile(msg.data.id); + void this.configHandler.reloadConfig(); }); on("didChangeControlPlaneSessionInfo", async (msg) => { this.configHandler.updateControlPlaneSessionInfo(msg.data.sessionInfo); @@ -713,7 +716,7 @@ export class Core { updateToSend.progress = 1.0; } - this.messenger.request("indexProgress", updateToSend); + void this.messenger.request("indexProgress", updateToSend); this.indexingState = updateToSend; if (update.status === "failed") { @@ -722,7 +725,7 @@ export class Core { update.desc, update.debugInfo, ); - Telemetry.capture( + void Telemetry.capture( "indexing_error", { error: update.desc, diff --git a/core/llm/index.ts b/core/llm/index.ts index ee70973b3..046d7af3d 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -281,7 +281,8 @@ ${prompt}`; ) { let promptTokens = this.countTokens(prompt); let generatedTokens = this.countTokens(completion); - Telemetry.capture( + + void Telemetry.capture( "tokens_generated", { model: model, @@ -291,12 +292,14 @@ ${prompt}`; }, true, ); - DevDataSqliteDb.logTokensGenerated( + + void DevDataSqliteDb.logTokensGenerated( model, this.providerName, promptTokens, generatedTokens, ); + logDevData("tokens_generated", { model: model, provider: this.providerName, @@ -342,11 +345,11 @@ ${prompt}`; ) { if (resp.url.includes("codestral.mistral.ai")) { throw new Error( - 'You are using a Mistral API key, which is not compatible with the Codestral API. Please either obtain a Codestral API key, or use the Mistral API by setting "apiBase" to "https://api.mistral.ai/v1" in config.json.', + "You are using a Mistral API key, which is not compatible with the Codestral API. Please either obtain a Codestral API key, or use the Mistral API by setting 'apiBase' to 'https://api.mistral.ai/v1' in config.json.", ); } else { throw new Error( - 'You are using a Codestral API key, which is not compatible with the Mistral API. Please either obtain a Mistral API key, or use the the Codestral API by setting "apiBase" to "https://codestral.mistral.ai/v1" in config.json.', + "You are using a Codestral API key, which is not compatible with the Mistral API. Please either obtain a Mistral API key, or use the the Codestral API by setting 'apiBase' to 'https://codestral.mistral.ai/v1' in config.json.", ); } } @@ -542,6 +545,7 @@ ${prompt}`; const completion = await this._complete(prompt, completionOptions); this._logTokensGenerated(completionOptions.model, prompt, completion); + if (log && this.writeLog) { await this.writeLog(`Completion:\n\n${completion}\n\n`); } @@ -557,6 +561,17 @@ ${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 = {}, @@ -604,6 +619,7 @@ ${prompt}`; } this._logTokensGenerated(completionOptions.model, prompt, completion); + if (log && this.writeLog) { await this.writeLog(`Completion:\n\n${completion}\n\n`); } diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index 320dd9798..f0d90967d 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -20,6 +20,56 @@ 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. 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 +class Calculator { + constructor() { + this.result = 0; + } + add(number) { + this.result += number; + return this; + } +} +\`\`\` +User request: Add a subtract method + +Output: +\`\`\`javascript test.js +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, @@ -78,6 +128,18 @@ class Anthropic extends BaseLLM { 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 response = await this.fetch(new URL("messages", this.apiBase), { method: "POST", headers: { @@ -115,6 +177,8 @@ class Anthropic extends BaseLLM { yield { role: "assistant", content: value.delta.text }; } } + + this.systemMessage = curSystemMsg; } } diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 0eb4461d9..238a2c841 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.212", + "version": "0.9.213", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.212", + "version": "0.9.213", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 75df6f097..07160070d 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "0.9.212", + "version": "0.9.213", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" diff --git a/gui/src/components/FileIcon.tsx b/gui/src/components/FileIcon.tsx index ab1dd5257..d1be4fbbf 100644 --- a/gui/src/components/FileIcon.tsx +++ b/gui/src/components/FileIcon.tsx @@ -14,6 +14,7 @@ const FileIcon = ({ ? filename.split(" ") : [filename, ""]; filenameParts.pop(); + const getIcon = themeIcons({ blue: "#268bd2", grey: "#657b83", @@ -27,6 +28,7 @@ const FileIcon = ({ yellow: "#b58900", ignore: "#586e75", }); + // Sanitize the SVG string before rendering it const { svg, color } = getIcon(filenameParts.join(" ")); const sanitizedSVG = DOMPurify.sanitize(svg); diff --git a/gui/src/components/markdown/CodeBlockToolbar.tsx b/gui/src/components/markdown/CodeBlockToolbar.tsx index a22b1da83..884aa9ea4 100644 --- a/gui/src/components/markdown/CodeBlockToolbar.tsx +++ b/gui/src/components/markdown/CodeBlockToolbar.tsx @@ -17,7 +17,7 @@ const ToolbarDiv = styled.div` display: flex; justify-content: space-between; align-items: center; - background: ${vscEditorBackground}; + background: inherit; font-size: ${getFontSize() - 2}px; padding: 3px; padding-left: 4px; @@ -46,6 +46,7 @@ interface CodeBlockToolBarProps { bottom: boolean; language: string | undefined; isNextCodeBlock: boolean; + filename?: string; } const terminalLanguages = ["bash", "sh"]; @@ -98,34 +99,66 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { !props.isNextCodeBlock, ); + function onClickHeader() { + // TODO: Need to turn into relative or fq path + ideMessenger.post("showFile", { + filepath: props.filename, + }); + } + + function onClickCopy(e) { + const text = typeof props.text === "string" ? props.text : props.text; + if (isJetBrains()) { + ideMessenger.request("copyText", { text }); + } else { + navigator.clipboard.writeText(text); + } + + setCopied(true); + setTimeout(() => setCopied(false), 2000); + } + + function onClickActionButton() { + if (isTerminalCodeBlock(props.language, props.text)) { + let text = props.text; + if (text.startsWith("$ ")) { + text = text.slice(2); + } + ideMessenger.ide.runCommand(text); + return; + } + + if (applying) return; + ideMessenger.post("applyToCurrentFile", { + text: props.text, + }); + setApplying(true); + setTimeout(() => setApplying(false), 2000); + } + return (
{ - // Open the file - }} + onClick={onClickHeader} > - - {props.language} + {props.filename && ( + <> + + {props.filename}{" "} + + )}
-
- { - const text = - typeof props.text === "string" ? props.text : props.text; - if (isJetBrains()) { - ideMessenger.request("copyText", { text }); - } else { - navigator.clipboard.writeText(text); - } - setCopied(true); - setTimeout(() => setCopied(false), 2000); - }} - > +
+
{copied ? ( <> @@ -134,10 +167,7 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { ) : ( <> - + Copy )} @@ -148,26 +178,11 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { { - if (isTerminalCodeBlock(props.language, props.text)) { - let text = props.text; - if (text.startsWith("$ ")) { - text = text.slice(2); - } - ideMessenger.ide.runCommand(text); - return; - } - - if (applying) return; - ideMessenger.post("applyToCurrentFile", { - text: props.text, - }); - setApplying(true); - setTimeout(() => setApplying(false), 2000); - }} + onClick={onClickActionButton} >
{applying ? ( @@ -184,15 +199,6 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) {
)} - {/* { - ideMessenger.post("insertAtCursor", { text: props.text }); - }} - > - - */}
); diff --git a/gui/src/components/markdown/CodeSnippetPreview.tsx b/gui/src/components/markdown/CodeSnippetPreview.tsx index 80b8fe1a4..e1199b138 100644 --- a/gui/src/components/markdown/CodeSnippetPreview.tsx +++ b/gui/src/components/markdown/CodeSnippetPreview.tsx @@ -112,11 +112,7 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) { }} >
- + {props.item.name}
diff --git a/gui/src/components/markdown/PreWithToolbar.tsx b/gui/src/components/markdown/PreWithToolbar.tsx index 02c055a92..c15ddaa64 100644 --- a/gui/src/components/markdown/PreWithToolbar.tsx +++ b/gui/src/components/markdown/PreWithToolbar.tsx @@ -33,6 +33,7 @@ function PreWithToolbar(props: { children: any; language: string | null; codeBlockIndex: number; + filename?: string | undefined; }) { const uiConfig = useUIConfig(); const toolbarBottom = uiConfig?.codeBlockToolbarPosition == "bottom"; @@ -67,7 +68,8 @@ function PreWithToolbar(props: { text={copyValue} bottom={toolbarBottom} language={props.language} - > + filename={props.filename} + /> {props.children} ); diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index 9f309f17b..845ed445d 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -51,19 +51,9 @@ const StyledMarkdown = styled.div<{ } background-color: ${vscBackground}; - font-family: - var(--vscode-font-family), - system-ui, - -apple-system, - BlinkMacSystemFont, - "Segoe UI", - Roboto, - Oxygen, - Ubuntu, - Cantarell, - "Open Sans", - "Helvetica Neue", - sans-serif; + font-family: var(--vscode-font-family), system-ui, -apple-system, + BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, + "Open Sans", "Helvetica Neue", sans-serif; font-size: ${(props) => props.fontSize || getFontSize()}px; padding-left: 8px; padding-right: 8px; @@ -113,6 +103,12 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( } else if (node.lang.includes(".")) { node.lang = node.lang.split(".").slice(-1)[0]; } + + if (node.meta) { + node.data = node.data || {}; + node.data.hProperties = node.data.hProperties || {}; + node.data.hProperties.filename = node.meta; + } }); }; }, @@ -150,12 +146,13 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( ); }, pre: ({ node, ...preProps }) => { - const childrenClassName = preProps?.children?.[0]?.props?.className; + const { className, filename } = preProps?.children?.[0]?.props; return props.showCodeBorder ? (