diff --git a/core/autocomplete/lineStream.ts b/core/autocomplete/lineStream.ts index d3ac0b715..1ee0c5e88 100644 --- a/core/autocomplete/lineStream.ts +++ b/core/autocomplete/lineStream.ts @@ -70,11 +70,11 @@ export async function* stopAtSimilarLine( } } -const LINES_TO_STOP_AT = ["# End of file."]; +const LINES_TO_STOP_AT = ["# End of file.", " line.trim().includes(stopAt))) { break; } yield line; @@ -85,7 +85,8 @@ function shouldRemoveLineBeforeStart(line: string): boolean { return ( line.trimStart().startsWith("```") || line.trim() === "[CODE]" || - line.trim() === "" + line.trim() === "" || + line.trim() === "" ); } diff --git a/core/commands/slash/edit.ts b/core/commands/slash/edit.ts index 8cb85e442..ef303ff6a 100644 --- a/core/commands/slash/edit.ts +++ b/core/commands/slash/edit.ts @@ -8,7 +8,7 @@ import { } from "../../autocomplete/lineStream"; import { streamLines } from "../../diff/util"; import { stripImages } from "../../llm/countTokens"; -import { dedentAndGetCommonWhitespace, renderPromptTemplate } from "../../util"; +import { dedentAndGetCommonWhitespace } from "../../util"; import { RangeInFileWithContents, contextItemToRangeInFileWithContents, @@ -446,7 +446,7 @@ const EditSlashCommand: SlashCommand = { const template = llm.promptTemplates?.edit; let generator: AsyncGenerator; if (template) { - let rendered = renderPromptTemplate( + let rendered = llm.renderPromptTemplate( template, // typeof template === 'string' ? template : template.prompt, messages.slice(0, messages.length - 1), diff --git a/core/index.d.ts b/core/index.d.ts index f1c2ab35a..b5b157aaa 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -43,6 +43,14 @@ export interface LLMReturnValue { prompt: string; completion: string; } + +export type PromptTemplate = + | string + | (( + history: ChatMessage[], + otherData: Record, + ) => string | ChatMessage[]); + export interface ILLM extends LLMOptions { get providerName(): ModelProvider; @@ -90,7 +98,18 @@ export interface ILLM extends LLMOptions { supportsImages(): boolean; + supportsCompletions(): boolean; + + supportsPrefill(): boolean; + listModels(): Promise; + + renderPromptTemplate( + template: PromptTemplate, + history: ChatMessage[], + otherData: Record, + canPutWordsInModelsMouth?: boolean, + ): string | ChatMessage[]; } export type ContextProviderType = "normal" | "query" | "submenu"; @@ -243,7 +262,6 @@ export type ChatHistory = ChatHistoryItem[]; // LLM export interface LLMFullCompletionOptions extends BaseCompletionOptions { - raw?: boolean; log?: boolean; model?: string; @@ -573,6 +591,7 @@ interface BaseCompletionOptions { maxTokens?: number; numThreads?: number; keepAlive?: number; + raw?: boolean; } export interface ModelDescription { diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index 4be960b99..08e51c32f 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -19,13 +19,13 @@ import { alpacaEditPrompt, claudeEditPrompt, codeLlama70bEditPrompt, - codellamaEditPrompt, deepseekEditPrompt, gemmaEditPrompt, gptEditPrompt, mistralEditPrompt, neuralChatEditPrompt, openchatEditPrompt, + osModelsEditPrompt, phindEditPrompt, simplifiedEditPrompt, xWinCoderEditPrompt, @@ -160,7 +160,7 @@ function autodetectTemplateType(model: string): TemplateType | undefined { return "alpaca"; } - if (lower.includes("mistral")) { + if (lower.includes("mistral") || lower.includes("mixtral")) { return "llama2"; } @@ -218,6 +218,22 @@ function autodetectTemplateFunction( return null; } +const USES_OS_MODELS_EDIT_PROMPT: TemplateType[] = [ + "alpaca", + "chatml", + // "codellama-70b", Doesn't respond well to this prompt + "deepseek", + "gemma", + "llama2", + "llava", + "neural-chat", + "openchat", + "phi2", + "phind", + "xwin-coder", + "zephyr", +]; + function autodetectPromptTemplates( model: string, explicitTemplate: TemplateType | undefined = undefined, @@ -227,7 +243,11 @@ function autodetectPromptTemplates( let editTemplate = null; - if (templateType === "phind") { + if (templateType && USES_OS_MODELS_EDIT_PROMPT.includes(templateType)) { + // This is overriding basically everything else + // Will probably delete the rest later, but for now it's easy to revert + editTemplate = osModelsEditPrompt; + } else if (templateType === "phind") { editTemplate = phindEditPrompt; } else if (templateType === "phi2") { editTemplate = simplifiedEditPrompt; @@ -237,7 +257,7 @@ function autodetectPromptTemplates( if (model.includes("mistral")) { editTemplate = mistralEditPrompt; } else { - editTemplate = codellamaEditPrompt; + editTemplate = osModelsEditPrompt; } } else if (templateType === "alpaca") { editTemplate = alpacaEditPrompt; diff --git a/core/llm/index.ts b/core/llm/index.ts index a7e186ab7..e8f4ec550 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -8,6 +8,7 @@ import { LLMReturnValue, ModelName, ModelProvider, + PromptTemplate, RequestOptions, TemplateType, } from ".."; @@ -46,6 +47,23 @@ export abstract class BaseLLM implements ILLM { return modelSupportsImages(this.providerName, this.model); } + supportsCompletions(): boolean { + if (this.providerName === "openai") { + if ( + this.apiBase?.includes("api.groq.com") || + this.apiBase?.includes(":1337") + ) { + // Jan + Groq don't support completions : ( + return false; + } + } + return true; + } + + supportsPrefill(): boolean { + return ["ollama", "anthropic"].includes(this.providerName); + } + uniqueId: string; model: string; @@ -237,7 +255,6 @@ ${prompt}`; const log = options.log ?? true; const raw = options.raw ?? false; delete options.log; - delete options.raw; const completionOptions: CompletionOptions = mergeJson( this.completionOptions, @@ -443,10 +460,45 @@ ${prompt}`; }; } - private _shouldRequestDirectly() { - if (typeof window === "undefined") { - return true; + public renderPromptTemplate( + template: PromptTemplate, + history: ChatMessage[], + otherData: Record, + canPutWordsInModelsMouth: boolean = false, + ): string | ChatMessage[] { + if (typeof template === "string") { + let data: any = { + history: history, + ...otherData, + }; + if (history.length > 0 && history[0].role == "system") { + data["system_message"] = history.shift()!.content; + } + + const compiledTemplate = Handlebars.compile(template); + return compiledTemplate(data); + } else { + const rendered = template(history, { + ...otherData, + supportsCompletions: this.supportsCompletions() ? "true" : "false", + supportsPrefill: this.supportsPrefill() ? "true" : "false", + }); + if ( + typeof rendered !== "string" && + rendered[rendered.length - 1]?.role === "assistant" && + !canPutWordsInModelsMouth + ) { + // Some providers don't allow you to put words in the model's mouth + // So we have to manually compile the prompt template and use + // raw /completions, not /chat/completions + const templateMessages = autodetectTemplateFunction( + this.model, + this.providerName, + autodetectTemplateType(this.model), + ); + return templateMessages(rendered); + } + return rendered; } - return window?.ide !== "vscode"; } } diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index da31df620..6254e1e26 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -164,8 +164,10 @@ class OpenAI extends BaseLLM { ): AsyncGenerator { if ( !CHAT_ONLY_MODELS.includes(options.model) && + this.supportsCompletions() && (NON_CHAT_MODELS.includes(options.model) || - this.useLegacyCompletionsEndpoint) + this.useLegacyCompletionsEndpoint || + options.raw) ) { for await (const content of this._legacystreamComplete( stripImages(messages[messages.length - 1]?.content || ""), diff --git a/core/llm/templates/chat.ts b/core/llm/templates/chat.ts index 8f004abb8..cb39f8827 100644 --- a/core/llm/templates/chat.ts +++ b/core/llm/templates/chat.ts @@ -1,6 +1,46 @@ import { ChatMessage } from "../.."; import { stripImages } from "../countTokens"; +function templateFactory( + systemMessage: (msg: ChatMessage) => string, + userPrompt: string, + assistantPrompt: string, + separator: string, + prefix?: string, + emptySystemMessage?: string, +): (msgs: ChatMessage[]) => string { + return (msgs: ChatMessage[]) => { + let prompt = prefix ?? ""; + + // Skip assistant messages at the beginning + while (msgs.length > 0 && msgs[0].role === "assistant") { + msgs.shift(); + } + + if (msgs.length > 0 && msgs[0].role === "system") { + prompt += systemMessage(msgs.shift()!); + } else if (emptySystemMessage) { + prompt += emptySystemMessage; + } + + for (let i = 0; i < msgs.length; i++) { + const msg = msgs[i]; + prompt += msg.role === "user" ? userPrompt : assistantPrompt; + prompt += msg.content; + if (i < msgs.length - 1) { + prompt += separator; + } + } + + if (msgs.length > 0 && msgs[msgs.length - 1].role === "user") { + prompt += separator; + prompt += assistantPrompt; + } + + return prompt; + }; +} + /** * @description Template for LLAMA2 messages: * @@ -43,7 +83,10 @@ function llama2TemplateMessages(msgs: ChatMessage[]): string { if (msgs[i].role === "user") { prompt += `[INST] ${msgs[i].content} [/INST]`; } else { - prompt += msgs[i].content + "\n"; + prompt += msgs[i].content; + if (i < msgs.length - 1) { + prompt += "\n"; + } } } @@ -73,77 +116,41 @@ function anthropicTemplateMessages(messages: ChatMessage[]): string { return prompt; } -function llavaTemplateMessages(msgs: ChatMessage[]): string { - `A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions. +`A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions. USER: {prompt} ASSISTANT:`; +const llavaTemplateMessages = templateFactory( + () => "", + "USER: ", + "ASSISTANT: ", + "\n", + "A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions.", +); - let prompt = - "A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions."; +const zephyrTemplateMessages = templateFactory( + (msg) => `<|system|>${msg.content}\n`, + "<|user|>\n", + "<|assistant|>\n", + "\n", + undefined, + "<|system|> \n", +); - for (const msg of msgs) { - prompt += msg.role === "user" ? "USER: " : "ASSISTANT: "; - prompt += msg.content; +const chatmlTemplateMessages = templateFactory( + (msg) => `<|im_start|>${msg.role}\n${msg.content}<|im_end|>\n`, + "<|im_start|>user\n", + "<|im_start|>assistant\n", + "<|im_end|>\n", +); - prompt += "\n"; - } - - prompt += "ASSISTANT: "; - - return prompt; -} - -function zephyrTemplateMessages(msgs: ChatMessage[]): string { - let prompt = ""; - - if (msgs[0].role === "system") { - prompt += `<|system|>${msgs[0].content}\n`; - msgs.shift(); - } else { - prompt += "<|system|> \n"; - } - - for (const msg of msgs) { - prompt += msg.role === "user" ? "<|user|>\n" : "<|assistant|>\n"; - prompt += `${msg.content}\n`; - } - - prompt += "<|assistant|>\n"; - - return prompt; -} - -function chatmlTemplateMessages(messages: ChatMessage[]): string { - let prompt = ""; - - for (const msg of messages) { - prompt += `<|im_start|>${msg.role}\n${msg.content}<|im_end|>\n`; - } - - prompt += "<|im_start|>assistant\n"; - return prompt; -} - -function templateAlpacaMessages(msgs: ChatMessage[]): string { - let prompt = ""; - - if (msgs[0].role === "system") { - prompt += `${msgs[0].content}\n\n`; - msgs.shift(); - } else { - prompt += - "Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n"; - } - - for (const msg of msgs) { - prompt += msg.role === "user" ? "### Instruction:\n" : "### Response:\n"; - prompt += `${msg.content}\n\n`; - } - - prompt += "### Response:\n"; - - return prompt; -} +const templateAlpacaMessages = templateFactory( + (msg) => `${msg.content}\n\n`, + "### Instruction:\n", + "### Response:\n", + "\n\n", + undefined, + "Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n", +); function deepseekTemplateMessages(msgs: ChatMessage[]): string { let prompt = ""; @@ -163,63 +170,45 @@ function deepseekTemplateMessages(msgs: ChatMessage[]): string { } prompt += `${msg.content}`; - prompt += msg.role === "user" ? "\n" : "<|EOT|>\n"; + + if (i < msgs.length - 1) { + prompt += msg.role === "user" ? "\n" : "<|EOT|>\n"; + } } - return prompt + "### Response:\n"; + if (msgs.length > 0 && msgs[msgs.length - 1].role === "user") { + prompt += "\n"; + prompt += "### Response:\n"; + } + + return prompt; } // See https://huggingface.co/microsoft/phi-2#qa-format -function phi2TemplateMessages(msgs: ChatMessage[]): string { - const HUMAN_PROMPT = "\n\nInstruct:"; - const AI_PROMPT = "\n\nOutput:"; - let prompt = ""; +const phi2TemplateMessages = templateFactory( + (msg) => `\n\nInstruct: ${msg.content} `, + "\n\nInstruct: ", + "\n\nOutput: ", + " ", +); - for (const msg of msgs) { - prompt += `${ - msg.role === "user" || msg.role === "system" ? HUMAN_PROMPT : AI_PROMPT - } ${msg.content} `; - } - - prompt += AI_PROMPT; - return prompt; -} - -function phindTemplateMessages(msgs: ChatMessage[]): string { - let prompt = ""; - - if (msgs[0].role === "system") { - prompt += `### System Prompt\n${msgs[0].content}\n\n`; - msgs.shift(); - } - - for (const msg of msgs) { - prompt += msg.role === "user" ? "### User Message\n" : "### Assistant\n"; - prompt += `${msg.content}\n`; - } - - prompt += "### Assistant\n"; - - return prompt; -} +const phindTemplateMessages = templateFactory( + (msg) => `### System Prompt\n${msg.content}\n\n`, + "### User Message\n", + "### Assistant\n", + "\n", +); /** * OpenChat Template, used by CodeNinja * GPT4 Correct User: Hello<|end_of_turn|>GPT4 Correct Assistant: Hi<|end_of_turn|>GPT4 Correct User: How are you today?<|end_of_turn|>GPT4 Correct Assistant: */ -function openchatTemplateMessages(msgs: ChatMessage[]): string { - let prompt = ""; - - for (const msg of msgs) { - prompt += - msg.role === "user" ? "GPT4 Correct User: " : "GPT4 Correct Assistant: "; - prompt += msg.content + "<|end_of_turn|>"; - } - - prompt += "GPT4 Correct Assistant: "; - - return prompt; -} +const openchatTemplateMessages = templateFactory( + () => "", + "GPT4 Correct User: ", + "GPT4 Correct Assistant: ", + "<|end_of_turn|>", +); /** * Chat template used by https://huggingface.co/TheBloke/XwinCoder-13B-GPTQ @@ -229,47 +218,25 @@ function openchatTemplateMessages(msgs: ChatMessage[]): string { : {prompt} : */ -function xWinCoderTemplateMessages(msgs: ChatMessage[]): string { - let prompt = ": "; - if (msgs[0].role === "system") { - prompt += msgs.shift()!.content; - } else { - prompt += - "You are an AI coding assistant that helps people with programming. Write a response that appropriately completes the user's request."; - } - - for (let msg of msgs) { - prompt += "\n"; - prompt += msg.role === "user" ? "" : ""; - prompt += ": " + msg.content; - } - - prompt += ": "; - - return prompt; -} +const xWinCoderTemplateMessages = templateFactory( + (msg) => `: ${msg.content}`, + "\n: ", + "\n: ", + "", + undefined, + ": You are an AI coding assistant that helps people with programming. Write a response that appropriately completes the user's request.", +); /** * NeuralChat Template * ### System:\n{system_input}\n### User:\n{user_input}\n### Assistant:\n */ -function neuralChatTemplateMessages(msgs: ChatMessage[]): string { - let prompt = ""; - - if (msgs[0].role === "system") { - prompt += `### System:\n${msgs[0].content}\n`; - msgs.shift(); - } - - for (const msg of msgs) { - prompt += msg.role === "user" ? "### User:\n" : "### Assistant:\n"; - prompt += `${msg.content}\n`; - } - - prompt += "### Assistant:\n"; - - return prompt; -} +const neuralChatTemplateMessages = templateFactory( + (msg) => `### System:\n${msg.content}\n`, + "### User:\n", + "### Assistant:\n", + "\n", +); /** 'Source: system\n\n System prompt Source: user\n\n First user query Source: assistant\n\n Model response to first query Source: user\n\n Second user query Source: assistant\nDestination: user\n\n ' @@ -292,18 +259,12 @@ function codeLlama70bTemplateMessages(msgs: ChatMessage[]): string { What is Cramer's Rule? model */ - -function gemmaTemplateMessage(msgs: ChatMessage[]): string { - let prompt = ""; - for (const msg of msgs) { - prompt += `${ - msg.role === "assistant" ? "model" : "user" - }\n${stripImages(msg.content).trim()}\n`; - } - - prompt += "model\n"; - return prompt; -} +const gemmaTemplateMessage = templateFactory( + () => "", + "user\n", + "model\n", + "\n", +); export { anthropicTemplateMessages, diff --git a/core/llm/templates/edit.ts b/core/llm/templates/edit.ts index b1d6f7b89..717d943cb 100644 --- a/core/llm/templates/edit.ts +++ b/core/llm/templates/edit.ts @@ -1,5 +1,4 @@ -import { ChatMessage } from "../.."; -import { PromptTemplate } from "../../util"; +import { ChatMessage, PromptTemplate } from "../.."; const simplifiedEditPrompt = `Consider the following code: \`\`\`{{{language}}} @@ -62,14 +61,72 @@ Here is the rewritten code:`); const codellamaInfillEditPrompt = "{{filePrefix}}{{fileSuffix}}"; -const codellamaEditPrompt = `\`\`\`{{{language}}} -{{{codeToEdit}}} -\`\`\` -[INST] You are an expert programmer and personal assistant. Your task is to rewrite the above code with these instructions: "{{{userInput}}}" +const START_TAG = ""; +const osModelsEditPrompt: PromptTemplate = (history, otherData) => { + // "No sufix" means either there is no suffix OR + // it's a clean break at end of function or something + // (what we're trying to avoid is just the language model trying to complete the closing brackets of a function or something) + const firstCharOfFirstLine = otherData.suffix?.split("\n")[0]?.[0]?.trim(); + const isSuffix = + otherData.suffix?.trim() !== "" && + // First character of first line is whitespace + // Otherwise we assume it's a clean break + !firstCharOfFirstLine; + const suffixTag = isSuffix ? "" : ""; + const suffixExplanation = isSuffix + ? ' When you get to "", end your response.' + : ""; -Your answer should be given inside of a code block. It should use the same kind of indentation as above. -[/INST] Sure! Here's the rewritten code you requested: -\`\`\`{{{language}}}`; + // If neither prefilling nor /v1/completions are supported, we have to use a chat prompt without putting words in the model's mouth + if ( + otherData.supportsCompletions !== "true" && + otherData.supportsPrefill !== "true" + ) { + return gptEditPrompt(history, otherData); + } + + // Use a different prompt when there's neither prefix nor suffix + if (otherData.prefix.trim() === "" && otherData.suffix.trim() === "") { + return [ + { + role: "user", + content: `\`\`\`${otherData.language} +${otherData.codeToEdit} +${suffixTag} +\`\`\` + +Please rewrite the entire code block above in order to satisfy the following request: "${otherData.userInput}".${suffixExplanation}`, + }, + { + role: "assistant", + content: `Sure! Here's the entire rewritten code block: +\`\`\`${otherData.language} +`, + }, + ]; + } + + return [ + { + role: "user", + content: `\`\`\`${otherData.language} +${otherData.prefix}${START_TAG} +${otherData.codeToEdit} +${suffixTag} +\`\`\` + +Please rewrite the entire code block above, editing the portion below "${START_TAG}" in order to satisfy the following request: "${otherData.userInput}".${suffixExplanation} +`, + }, + { + role: "assistant", + content: `Sure! Here's the entire code block, including the rewritten portion: +\`\`\`${otherData.language} +${otherData.prefix}${START_TAG} +`, + }, + ]; +}; const mistralEditPrompt = `[INST] You are a helpful code assistant. Your task is to rewrite the following code with these instructions: "{{{userInput}}}" \`\`\`{{{language}}} @@ -218,7 +275,6 @@ export { alpacaEditPrompt, claudeEditPrompt, codeLlama70bEditPrompt, - codellamaEditPrompt, codellamaInfillEditPrompt, deepseekEditPrompt, gemmaEditPrompt, @@ -226,6 +282,7 @@ export { mistralEditPrompt, neuralChatEditPrompt, openchatEditPrompt, + osModelsEditPrompt, phindEditPrompt, simplestEditPrompt, simplifiedEditPrompt, diff --git a/core/util/index.ts b/core/util/index.ts index e92634483..e48f5f217 100644 --- a/core/util/index.ts +++ b/core/util/index.ts @@ -1,6 +1,3 @@ -import Handlebars from "handlebars"; -import { ChatMessage } from ".."; - export function removeQuotesAndEscapes(output: string): string { output = output.trim(); @@ -92,34 +89,6 @@ export function dedentAndGetCommonWhitespace(s: string): [string, string] { return [lines.map((x) => x.replace(lcp, "")).join("\n"), lcp]; } -export type PromptTemplate = - | string - | (( - history: ChatMessage[], - otherData: Record, - ) => string | ChatMessage[]); - -export function renderPromptTemplate( - template: PromptTemplate, - history: ChatMessage[], - otherData: Record, -): string | ChatMessage[] { - if (typeof template === "string") { - let data: any = { - history: history, - ...otherData, - }; - if (history.length > 0 && history[0].role == "system") { - data["system_message"] = history.shift()!.content; - } - - const compiledTemplate = Handlebars.compile(template); - return compiledTemplate(data); - } else { - return template(history, otherData); - } -} - export function getBasename(filepath: string, n: number = 1): string { return filepath.split(/[\\/]/).pop() ?? ""; } diff --git a/core/util/verticalEdit.ts b/core/util/verticalEdit.ts index 876b713f0..3265e04c4 100644 --- a/core/util/verticalEdit.ts +++ b/core/util/verticalEdit.ts @@ -4,12 +4,11 @@ import { filterEnglishLinesAtEnd, filterEnglishLinesAtStart, filterLeadingAndTrailingNewLineInsertion, - fixCodeLlamaFirstLineIndentation, + stopAtLines, } from "../autocomplete/lineStream"; import { streamDiff } from "../diff/streamDiff"; import { streamLines } from "../diff/util"; import { gptEditPrompt } from "../llm/templates/edit"; -import { renderPromptTemplate } from "../util"; function constructPrompt( prefix: string, @@ -20,7 +19,7 @@ function constructPrompt( language: string | undefined, ): string | ChatMessage[] { const template = llm.promptTemplates?.edit ?? gptEditPrompt; - return renderPromptTemplate(template, [], { + return llm.renderPromptTemplate(template, [], { userInput, prefix, codeToEdit: highlighted, @@ -77,15 +76,17 @@ export async function* streamDiffLines( const completion = typeof prompt === "string" - ? llm.streamComplete(prompt) + ? llm.streamComplete(prompt, { raw: true }) : llm.streamChat(prompt); let lines = streamLines(completion); lines = filterEnglishLinesAtStart(lines); lines = filterCodeBlockLines(lines); + lines = stopAtLines(lines); if (inept) { - lines = filterEnglishLinesAtEnd(fixCodeLlamaFirstLineIndentation(lines)); + // lines = fixCodeLlamaFirstLineIndentation(lines); + lines = filterEnglishLinesAtEnd(lines); } let diffLines = streamDiff(oldLines, lines); diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index b45de441e..9e0ae07c4 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -11,6 +11,7 @@ import { Telemetry } from "core/util/posthog"; import { ContinueGUIWebviewViewProvider } from "./debugPanel"; import { DiffManager } from "./diff/horizontal"; import { VerticalPerLineDiffManager } from "./diff/verticalPerLine/manager"; +import { getPlatform } from "./util/util"; import { VsCodeWebviewProtocol } from "./webviewProtocol"; function getFullScreenTab() { @@ -196,7 +197,7 @@ const commandsMap: ( placeHolder: selectionEmpty ? `Type instructions to generate code${addContextMsg}` : `Describe how to edit the highlighted code${addContextMsg}`, - title: "Continue Quick Edit", + title: `${getPlatform() === "mac" ? "Cmd" : "Ctrl"}+I`, prompt: `[${defaultModelTitle}]`, }; if (previousInput) { diff --git a/extensions/vscode/src/diff/verticalPerLine/handler.ts b/extensions/vscode/src/diff/verticalPerLine/handler.ts index fed6e0737..f6973e054 100644 --- a/extensions/vscode/src/diff/verticalPerLine/handler.ts +++ b/extensions/vscode/src/diff/verticalPerLine/handler.ts @@ -126,6 +126,8 @@ export class VerticalPerLineDiffHandler { } this.deletionBuffer = []; this.insertedInCurrentBlock = 0; + + this.refreshCodeLens(); } private incrementCurrentLineIndex() { @@ -314,6 +316,8 @@ export class VerticalPerLineDiffHandler { await this.insertDeletionBuffer(); this.clearIndexLineDecorations(); + this.refreshCodeLens(); + // Reject on user typing // const listener = vscode.workspace.onDidChangeTextDocument((e) => { // if (e.document.uri.fsPath === this.filepath) { diff --git a/extensions/vscode/src/diff/verticalPerLine/manager.ts b/extensions/vscode/src/diff/verticalPerLine/manager.ts index 4c0fabf06..fd41f9886 100644 --- a/extensions/vscode/src/diff/verticalPerLine/manager.ts +++ b/extensions/vscode/src/diff/verticalPerLine/manager.ts @@ -1,4 +1,5 @@ import { ConfigHandler } from "core/config/handler"; +import { pruneLinesFromBottom, pruneLinesFromTop } from "core/llm/countTokens"; import { getMarkdownLanguageTagForFile } from "core/util"; import { Telemetry } from "core/util/posthog"; import { streamDiffLines } from "core/util/verticalEdit"; @@ -175,17 +176,25 @@ export class VerticalPerLineDiffManager { ); } - const rangeContent = editor.document.getText(selectedRange); - const prefix = editor.document.getText( - new vscode.Range(new vscode.Position(0, 0), selectedRange.start), - ); - const suffix = editor.document.getText( - new vscode.Range( - selectedRange.end, - new vscode.Position(editor.document.lineCount, 0), - ), - ); const llm = await this.configHandler.llmFromTitle(modelTitle); + const rangeContent = editor.document.getText(selectedRange); + const prefix = pruneLinesFromTop( + editor.document.getText( + new vscode.Range(new vscode.Position(0, 0), selectedRange.start), + ), + llm.contextLength / 4, + llm.model, + ); + const suffix = pruneLinesFromBottom( + editor.document.getText( + new vscode.Range( + selectedRange.end, + new vscode.Position(editor.document.lineCount, 0), + ), + ), + llm.contextLength / 4, + llm.model, + ); // Unselect the range editor.selection = new vscode.Selection(