diff --git a/core/core.ts b/core/core.ts index 9888a78b6..730dbbb19 100644 --- a/core/core.ts +++ b/core/core.ts @@ -17,8 +17,8 @@ import { DataLogger } from "./data/log"; import { CodebaseIndexer } from "./indexing/CodebaseIndexer"; import DocsService from "./indexing/docs/DocsService"; import { countTokens } from "./llm/countTokens"; -import Ollama from "./llm/llms/Ollama"; import Lemonade from "./llm/llms/Lemonade"; +import Ollama from "./llm/llms/Ollama"; import { EditAggregator } from "./nextEdit/context/aggregateEdits"; import { createNewPromptFileV2 } from "./promptFiles/createNewPromptFile"; import { callTool } from "./tools/callTool"; @@ -729,20 +729,13 @@ export class Core { data.fileUri ?? "current-file-stream", ); // not super important since currently cancelling apply will cancel all streams it's one file at a time - return streamDiffLines({ - highlighted: data.highlighted, - prefix: data.prefix, - suffix: data.suffix, + return streamDiffLines( + data, llm, - // rules included for edit, NOT apply - rulesToInclude: data.includeRulesInSystemMessage - ? config.rules - : undefined, - input: data.input, - language: data.language, - overridePrompt: undefined, abortController, - }); + undefined, + data.includeRulesInSystemMessage ? config.rules : undefined, + ); }); on("cancelApply", async (msg) => { diff --git a/core/edit/constants.ts b/core/edit/constants.ts index ecc3340ca..0fcc4853e 100644 --- a/core/edit/constants.ts +++ b/core/edit/constants.ts @@ -1 +1,3 @@ export const EDIT_MODE_STREAM_ID = "edit-mode"; + +export const APPLY_UNIQUE_TOKEN = "<|!@#IS_APPLY!@#|>"; diff --git a/core/edit/recursiveStream.ts b/core/edit/recursiveStream.ts index a835fe357..5c9f2fef6 100644 --- a/core/edit/recursiveStream.ts +++ b/core/edit/recursiveStream.ts @@ -1,7 +1,14 @@ -import { ChatMessage, ILLM, Prediction, PromptLog } from ".."; +import { + ChatMessage, + ILLM, + Prediction, + PromptLog, + type StreamDiffLinesType, +} from ".."; import { DEFAULT_MAX_TOKENS } from "../llm/constants"; import { countTokens } from "../llm/countTokens"; import { renderChatMessage } from "../util/messageContent"; +import { APPLY_UNIQUE_TOKEN } from "./constants.js"; const INFINITE_STREAM_SAFETY = 0.9; @@ -17,6 +24,7 @@ const RECURSIVE_PROMPT = `Continue EXACTLY where you left`; export async function* recursiveStream( llm: ILLM, abortController: AbortController, + type: StreamDiffLinesType, prompt: ChatMessage[] | string, prediction: Prediction | undefined, currentBuffer = "", @@ -28,8 +36,11 @@ export async function* recursiveStream( let buffer = currentBuffer; // let whiteSpaceAtEndOfBuffer = buffer.match(/\s*$/)?.[0] ?? ""; // attempts at fixing whitespace bug with recursive boundaries + const injectApplyToken = type === "apply" && shouldInjectApplyToken(llm); if (typeof prompt === "string") { - const generator = llm.streamComplete(prompt, abortController.signal, { + const finalPrompt = injectApplyToken ? prompt + APPLY_UNIQUE_TOKEN : prompt; + + const generator = llm.streamComplete(finalPrompt, abortController.signal, { raw: true, prediction: undefined, reasoning: false, @@ -62,7 +73,11 @@ export async function* recursiveStream( } } } else { - const generator = llm.streamChat(prompt, abortController.signal, { + const promptMessages = injectApplyToken + ? appendTokenToLastMessage(prompt, APPLY_UNIQUE_TOKEN) + : prompt; + + const generator = llm.streamChat(promptMessages, abortController.signal, { raw: true, prediction: undefined, reasoning: false, @@ -104,3 +119,36 @@ export async function* recursiveStream( } } } + +function shouldInjectApplyToken(llm: ILLM): boolean { + const model = llm.model?.toLowerCase() ?? ""; + return ( + llm.underlyingProviderName === "inception" && model.includes("mercury") + ); +} + +function appendTokenToLastMessage( + messages: ChatMessage[], + token: string, +): ChatMessage[] { + if (messages.length === 0) { + return messages; + } + + const lastMessage = messages[messages.length - 1]; + if (typeof lastMessage.content !== "string") { + return messages; + } + + if (lastMessage.content.endsWith(token)) { + return messages; + } + + const updatedMessages = [...messages]; + updatedMessages[updatedMessages.length - 1] = { + ...lastMessage, + content: lastMessage.content + token, + }; + + return updatedMessages; +} diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index 53caa0df5..b76cad23e 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -4,6 +4,7 @@ import { ILLM, Prediction, RuleWithSource, + StreamDiffLinesPayload, ToolResultChatMessage, UserChatMessage, } from "../"; @@ -20,6 +21,7 @@ import { streamDiff } from "../diff/streamDiff"; import { streamLines } from "../diff/util"; import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRules"; import { gptEditPrompt } from "../llm/templates/edit"; +import { defaultApplyPrompt } from "../llm/templates/edit/gpt"; import { findLast } from "../util/findLast"; import { Telemetry } from "../util/posthog"; import { recursiveStream } from "./recursiveStream"; @@ -42,6 +44,20 @@ function constructEditPrompt( }); } +function constructApplyPrompt( + originalCode: string, + newCode: string, + llm: ILLM, +) { + const template = llm.promptTemplates?.apply ?? defaultApplyPrompt; + const rendered = llm.renderPromptTemplate(template, [], { + original_code: originalCode, + new_code: newCode, + }); + + return rendered; +} + export async function* addIndentation( diffLineGenerator: AsyncGenerator, indentation: string, @@ -58,27 +74,15 @@ function modelIsInept(model: string): boolean { return !(model.includes("gpt") || model.includes("claude")); } -export async function* streamDiffLines({ - prefix, - highlighted, - suffix, - llm, - abortController, - input, - language, - overridePrompt, - rulesToInclude, -}: { - prefix: string; - highlighted: string; - suffix: string; - llm: ILLM; - abortController: AbortController; - input: string; - language: string | undefined; - overridePrompt: ChatMessage[] | undefined; - rulesToInclude: RuleWithSource[] | undefined; -}): AsyncGenerator { +export async function* streamDiffLines( + options: StreamDiffLinesPayload, + llm: ILLM, + abortController: AbortController, + overridePrompt: ChatMessage[] | undefined, + rulesToInclude: RuleWithSource[] | undefined, +): AsyncGenerator { + const { type, prefix, highlighted, suffix, input, language } = options; + void Telemetry.capture( "inlineEdit", { @@ -104,7 +108,9 @@ export async function* streamDiffLines({ // For apply can be overridden with simply apply prompt let prompt = overridePrompt ?? - constructEditPrompt(prefix, highlighted, suffix, llm, input, language); + (type === "apply" + ? constructApplyPrompt(oldLines.join("\n"), options.newCode, llm) + : constructEditPrompt(prefix, highlighted, suffix, llm, input, language)); // Rules can be included with edit prompt // If any rules are present this will result in using chat instead of legacy completion @@ -159,7 +165,13 @@ export async function* streamDiffLines({ content: highlighted, }; - const completion = recursiveStream(llm, abortController, prompt, prediction); + const completion = recursiveStream( + llm, + abortController, + type, + prompt, + prediction, + ); let lines = streamLines(completion); diff --git a/core/index.d.ts b/core/index.d.ts index ae2633595..2d9b9b7ba 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1393,7 +1393,9 @@ export interface ApplyState { autoFormattingDiff?: string; } -export interface StreamDiffLinesPayload { +export type StreamDiffLinesType = "edit" | "apply"; +interface StreamDiffLinesOptionsBase { + type: StreamDiffLinesType; prefix: string; highlighted: string; suffix: string; @@ -1404,6 +1406,19 @@ export interface StreamDiffLinesPayload { fileUri?: string; } +interface StreamDiffLinesOptionsEdit extends StreamDiffLinesOptionsBase { + type: "edit"; +} + +interface StreamDiffLinesOptionsApply extends StreamDiffLinesOptionsBase { + type: "apply"; + newCode: string; +} + +type StreamDiffLinesPayload = + | StreamDiffLinesOptionsApply + | StreamDiffLinesOptionsEdit; + export interface HighlightedCodePayload { rangeInFileWithContents: RangeInFileWithContents; prompt?: string; diff --git a/core/llm/llms/Inception.ts b/core/llm/llms/Inception.ts index 9d2b67ea7..3abce6cba 100644 --- a/core/llm/llms/Inception.ts +++ b/core/llm/llms/Inception.ts @@ -2,6 +2,7 @@ import { streamSse } from "@continuedev/fetch"; import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; import { ChatCompletionCreateParams } from "@continuedev/openai-adapters"; +import { APPLY_UNIQUE_TOKEN } from "../../edit/constants.js"; import { UNIQUE_TOKEN } from "../../nextEdit/constants.js"; import OpenAI from "./OpenAI.js"; @@ -96,40 +97,21 @@ class Inception extends OpenAI { options: CompletionOptions, ): AsyncGenerator { if (this.isNextEdit(messages)) { - messages = this.removeNextEditToken(messages); - - // Use edit/completions endpoint. - const endpoint = new URL("edit/completions", this.apiBase); - - const resp = await this.fetch(endpoint, { - method: "POST", - body: JSON.stringify({ - model: options.model, - messages: messages, - max_tokens: options.maxTokens, - temperature: options.temperature, - top_p: options.topP, - frequency_penalty: options.frequencyPenalty, - presence_penalty: options.presencePenalty, - stop: options.stop, - stream: true, - }), - headers: { - "Content-Type": "application/json", - Accept: "application/json", - Authorization: `Bearer ${this.apiKey}`, - }, + messages = this.removeToken(messages, UNIQUE_TOKEN); + yield* this.streamSpecialEndpoint( + "edit/completions", + messages, signal, - }); - - for await (const chunk of streamSse(resp)) { - if (chunk.choices?.[0]?.delta?.content) { - yield { - role: "assistant", - content: chunk.choices[0].delta.content, - }; - } - } + options, + ); + } else if (this.isApply(messages)) { + messages = this.removeToken(messages, APPLY_UNIQUE_TOKEN); + yield* this.streamSpecialEndpoint( + "apply/completions", + messages, + signal, + options, + ); } else { // Use regular chat/completions endpoint - call parent OpenAI implementation. yield* super._streamChat(messages, signal, options); @@ -145,23 +127,68 @@ class Inception extends OpenAI { ); } - private removeNextEditToken(messages: ChatMessage[]): ChatMessage[] { + private isApply(messages: ChatMessage[]): boolean { + return messages.some( + (message) => + typeof message.content === "string" && + message.content.endsWith(APPLY_UNIQUE_TOKEN), + ); + } + + private removeToken(messages: ChatMessage[], token: string): ChatMessage[] { const lastMessage = messages[messages.length - 1]; if ( typeof lastMessage?.content === "string" && - lastMessage.content.endsWith(UNIQUE_TOKEN) + lastMessage.content.endsWith(token) ) { const cleanedMessages = [...messages]; cleanedMessages[cleanedMessages.length - 1] = { ...lastMessage, - content: lastMessage.content.slice(0, -UNIQUE_TOKEN.length), + content: lastMessage.content.slice(0, -token.length), }; return cleanedMessages; } return messages; } + + private async *streamSpecialEndpoint( + path: string, + messages: ChatMessage[], + signal: AbortSignal, + options: CompletionOptions, + ): AsyncGenerator { + const endpoint = new URL(path, this.apiBase); + + const resp = await this.fetch(endpoint, { + method: "POST", + body: JSON.stringify({ + model: options.model, + messages, + max_tokens: options.maxTokens, + temperature: options.temperature, + top_p: options.topP, + frequency_penalty: options.frequencyPenalty, + presence_penalty: options.presencePenalty, + stop: options.stop, + stream: true, + }), + headers: { + "Content-Type": "application/json", + Accept: "application/json", + Authorization: `Bearer ${this.apiKey}`, + }, + signal, + }); + + for await (const chunk of streamSse(resp)) { + const content = chunk.choices?.[0]?.delta?.content; + if (content) { + yield { role: "assistant", content }; + } + } + } } export default Inception; diff --git a/core/llm/templates/edit/gpt.ts b/core/llm/templates/edit/gpt.ts index 61d23a732..bafad3f3b 100644 --- a/core/llm/templates/edit/gpt.ts +++ b/core/llm/templates/edit/gpt.ts @@ -71,3 +71,10 @@ export const gptEditPrompt: PromptTemplateFunction = (history, otherData) => { return paragraphs.join("\n\n"); }; + +export const defaultApplyPrompt: PromptTemplateFunction = ( + history, + otherData, +) => { + return `${otherData.original_code}\n\nThe following code was suggested as an edit:\n\`\`\`\n${otherData.new_code}\n\`\`\`\nPlease apply it to the previous code.`; +}; diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt index 733b0bd86..a5ae5eb67 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt @@ -91,7 +91,8 @@ class ApplyToFileHandler( highlighted = currentContent, // Current file content suffix = "", // No suffix since we're rewriting the whole file modelTitle = null, // No model needed for search/replace instant apply - includeRulesInSystemMessage = false // No LLM involved, just diff generation + includeRulesInSystemMessage = false, // No LLM involved, just diff generation + isApply = true ) } @@ -145,7 +146,7 @@ class ApplyToFileHandler( // Stream the diffs diffStreamHandler.streamDiffLinesToEditor( - prompt, prefix, highlighted, suffix, llmTitle, false + prompt, prefix, highlighted, suffix, llmTitle, false, true ) } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt index 274b2d458..7792397e3 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt @@ -97,7 +97,8 @@ class DiffStreamHandler( highlighted: String, suffix: String, modelTitle: String?, - includeRulesInSystemMessage: Boolean + includeRulesInSystemMessage: Boolean, + isApply: Boolean ) { isRunning = true sendUpdate(ApplyStateStatus.STREAMING) @@ -112,7 +113,8 @@ class DiffStreamHandler( language = virtualFile?.fileType?.name, modelTitle = modelTitle, includeRulesInSystemMessage = includeRulesInSystemMessage, - fileUri = virtualFile?.url + fileUri = virtualFile?.url, + isApply = isApply ), null ) { response -> diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt index e0dbcb0c2..914f70552 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt @@ -205,7 +205,7 @@ fun openInlineEdit(project: Project?, editor: Editor) { val selectedModelStrippedOfCaret = (comboBoxRef.get().selectedItem as String).removeSuffix(DOWN_ARROW) customPanelRef.get().enter() diffStreamHandler.streamDiffLinesToEditor( - textArea.text, prefix, highlighted, suffix, selectedModelStrippedOfCaret, true + textArea.text, prefix, highlighted, suffix, selectedModelStrippedOfCaret, true, false ) } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt index cddcd035b..d937b0add 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt @@ -306,7 +306,8 @@ data class StreamDiffLinesPayload( val language: String?, val modelTitle: String?, val includeRulesInSystemMessage: Boolean, - val fileUri: String? + val fileUri: String?, + val isApply: Boolean ) data class AcceptOrRejectDiffPayload( diff --git a/extensions/vscode/src/apply/ApplyManager.ts b/extensions/vscode/src/apply/ApplyManager.ts index e57d9e815..e79d8fe16 100644 --- a/extensions/vscode/src/apply/ApplyManager.ts +++ b/extensions/vscode/src/apply/ApplyManager.ts @@ -244,6 +244,7 @@ export class ApplyManager { newCode: text, toolCallId, rulesToInclude: undefined, // No rules for apply + isApply: true, }); } else { // Non-streaming: accumulate LLM output, then apply via Myers diff @@ -295,17 +296,23 @@ export class ApplyManager { const streamedLines: string[] = []; // Use streamDiffLines to get the LLM output - const stream = streamDiffLines({ - highlighted: rangeContent, - prefix, - suffix, + const stream = streamDiffLines( + { + highlighted: rangeContent, + prefix, + suffix, + input: prompt, + language: getMarkdownLanguageTagForFile(fileUri), + type: "apply", + newCode, + includeRulesInSystemMessage: false, + modelTitle: llm.title ?? llm.model, + }, llm, - rulesToInclude: undefined, // No rules for apply - input: prompt, - language: getMarkdownLanguageTagForFile(fileUri), - overridePrompt: undefined, abortController, - }); + undefined, + undefined, + ); // Accumulate all the streamed content for await (const line of stream) { diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 05dd18300..aca5b0e29 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -8,8 +8,8 @@ import { EXTENSION_NAME } from "core/control-plane/env"; import { Core } from "core/core"; import { walkDirAsync } from "core/indexing/walkDir"; import { isModelInstaller } from "core/llm"; -import { startLocalOllama } from "core/util/ollamaHelper"; import { startLocalLemonade } from "core/util/lemonadeHelper"; +import { startLocalOllama } from "core/util/ollamaHelper"; import { getConfigJsonPath, getConfigYamlPath } from "core/util/paths"; import { Telemetry } from "core/util/posthog"; import * as vscode from "vscode"; @@ -153,6 +153,7 @@ const getCommandsMap: ( llm, range, rulesToInclude: config.rules, + isApply: false, }); } diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index e338656af..cdcf30000 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -302,6 +302,7 @@ export class VerticalDiffManager { newCode, toolCallId, rulesToInclude, + isApply, }: { input: string; llm: ILLM; @@ -311,6 +312,7 @@ export class VerticalDiffManager { newCode?: string; toolCallId?: string; rulesToInclude: undefined | RuleWithSource[]; + isApply: boolean; }): Promise { void vscode.commands.executeCommand( "setContext", @@ -468,17 +470,23 @@ export class VerticalDiffManager { const streamedLines: string[] = []; async function* recordedStream() { - const stream = streamDiffLines({ - highlighted: rangeContent, - prefix, - suffix, + const stream = streamDiffLines( + { + highlighted: rangeContent, + prefix, + suffix, + input, + language: getMarkdownLanguageTagForFile(fileUri), + type: isApply ? "apply" : "edit", + newCode: newCode ?? "", + includeRulesInSystemMessage: !!rulesToInclude && !isApply, + modelTitle: llm.title ?? llm.model, + }, llm, - rulesToInclude, - input, - language: getMarkdownLanguageTagForFile(fileUri), - overridePrompt, abortController, - }); + overridePrompt, + rulesToInclude, + ); for await (const line of stream) { if (line.type === "new" || line.type === "same") { diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 352e4fd66..9af399c73 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -229,6 +229,7 @@ export class VsCodeMessenger { new vscode.Position(end.line, end.character), ), rulesToInclude: config.rules, + isApply: false, }); // Log dev data diff --git a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts index af3b3f882..662a4e326 100644 --- a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts +++ b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts @@ -332,6 +332,7 @@ export class QuickEdit { quickEdit: this.previousInput, range: this.range, rulesToInclude: rules, + isApply: false, }); } diff --git a/packages/config-yaml/package-lock.json b/packages/config-yaml/package-lock.json index 00d44cbc7..9f9724af4 100644 --- a/packages/config-yaml/package-lock.json +++ b/packages/config-yaml/package-lock.json @@ -1,12 +1,12 @@ { "name": "@continuedev/config-yaml", - "version": "1.14.0", + "version": "1.17.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/config-yaml", - "version": "1.14.0", + "version": "1.17.0", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", diff --git a/packages/continue-sdk/package-lock.json b/packages/continue-sdk/package-lock.json index 90b6b3401..2d9966303 100644 --- a/packages/continue-sdk/package-lock.json +++ b/packages/continue-sdk/package-lock.json @@ -20,7 +20,7 @@ }, "../config-yaml": { "name": "@continuedev/config-yaml", - "version": "1.14.0", + "version": "1.17.0", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", diff --git a/packages/openai-adapters/src/apis/Inception.ts b/packages/openai-adapters/src/apis/Inception.ts index e32694277..eb5c2ba50 100644 --- a/packages/openai-adapters/src/apis/Inception.ts +++ b/packages/openai-adapters/src/apis/Inception.ts @@ -23,6 +23,7 @@ import { FimCreateParamsStreaming } from "./base.js"; // }; export const UNIQUE_TOKEN = "<|!@#IS_NEXT_EDIT!@#|>"; +export const APPLY_UNIQUE_TOKEN = "<|!@#IS_APPLY!@#|>"; export const INCEPTION_API_BASE = "https://api.inceptionlabs.ai/v1/"; export class InceptionApi extends OpenAIApi { constructor(config: InceptionConfig) { @@ -38,37 +39,7 @@ export class InceptionApi extends OpenAIApi { body: ChatCompletionCreateParamsStreaming, signal: AbortSignal, ): AsyncGenerator { - const endpoint = new URL("edit/completions", this.apiBase); - const resp = await customFetch(this.config.requestOptions)(endpoint, { - method: "POST", - body: JSON.stringify({ - model: body.model, - messages: body.messages, - max_tokens: body.max_tokens, - temperature: body.temperature, - top_p: body.top_p, - frequency_penalty: body.frequency_penalty, - presence_penalty: body.presence_penalty, - stop: body.stop, - stream: true, - }), - headers: { - "Content-Type": "application/json", - Accept: "application/json", - Authorization: `Bearer ${this.config.apiKey}`, - }, - signal, - }); - - for await (const chunk of streamSse(resp as any)) { - if (chunk.choices?.[0]?.delta?.content) { - yield chatChunk({ - content: chunk.choices[0].delta.content, - finish_reason: chunk.choices[0].finish_reason || null, - model: body.model, - }); - } - } + yield* this.streamCustomEndpoint("edit/completions", body, signal); } // Add custom edit completions method (non-streaming). @@ -76,30 +47,7 @@ export class InceptionApi extends OpenAIApi { body: ChatCompletionCreateParamsNonStreaming, signal: AbortSignal, ): Promise { - const endpoint = new URL("edit/completions", this.apiBase); - const resp = await customFetch(this.config.requestOptions)(endpoint, { - method: "POST", - body: JSON.stringify({ - model: body.model, - messages: body.messages, - max_tokens: body.max_tokens, - temperature: body.temperature, - top_p: body.top_p, - frequency_penalty: body.frequency_penalty, - presence_penalty: body.presence_penalty, - stop: body.stop, - stream: false, // Set to false for non-streaming - }), - headers: { - "Content-Type": "application/json", - Accept: "application/json", - Authorization: `Bearer ${this.config.apiKey}`, - }, - signal, - }); - - const data = await resp.json(); - return data as ChatCompletion; + return this.nonStreamCustomEndpoint("edit/completions", body, signal); } // Override the regular chat stream method to route to edit endpoint for next edit requests. @@ -108,8 +56,11 @@ export class InceptionApi extends OpenAIApi { signal: AbortSignal, ): AsyncGenerator { if (this.isNextEdit(body.messages)) { - body.messages = this.removeNextEditToken(body.messages); + body.messages = this.removeToken(body.messages, UNIQUE_TOKEN); yield* this.editCompletionStream(body, signal); + } else if (this.isApply(body.messages)) { + body.messages = this.removeToken(body.messages, APPLY_UNIQUE_TOKEN); + yield* this.applyCompletionStream(body, signal); } else { yield* super.chatCompletionStream(body, signal); } @@ -121,13 +72,30 @@ export class InceptionApi extends OpenAIApi { signal: AbortSignal, ): Promise { if (this.isNextEdit(body.messages)) { - body.messages = this.removeNextEditToken(body.messages); + body.messages = this.removeToken(body.messages, UNIQUE_TOKEN); return this.editCompletionNonStream(body, signal); + } else if (this.isApply(body.messages)) { + body.messages = this.removeToken(body.messages, APPLY_UNIQUE_TOKEN); + return this.applyCompletionNonStream(body, signal); } else { return super.chatCompletionNonStream(body, signal); } } + async *applyCompletionStream( + body: ChatCompletionCreateParamsStreaming, + signal: AbortSignal, + ): AsyncGenerator { + yield* this.streamCustomEndpoint("apply/completions", body, signal); + } + + async applyCompletionNonStream( + body: ChatCompletionCreateParamsNonStreaming, + signal: AbortSignal, + ): Promise { + return this.nonStreamCustomEndpoint("apply/completions", body, signal); + } + async *fimStream( body: FimCreateParamsStreaming, signal: AbortSignal, @@ -179,24 +147,103 @@ export class InceptionApi extends OpenAIApi { ); } + private isApply(messages: ChatCompletionMessageParam[]): boolean { + return messages.some( + (message) => + typeof message.content === "string" && + message.content.endsWith(APPLY_UNIQUE_TOKEN), + ); + } + // Remove the unique token from messages. - private removeNextEditToken( + private removeToken( messages: ChatCompletionMessageParam[], + token: string, ): ChatCompletionMessageParam[] { const lastMessage = messages[messages.length - 1]; if ( typeof lastMessage?.content === "string" && - lastMessage.content.endsWith(UNIQUE_TOKEN) + lastMessage.content.endsWith(token) ) { const cleanedMessages = [...messages]; cleanedMessages[cleanedMessages.length - 1] = { ...lastMessage, - content: lastMessage.content.slice(0, -UNIQUE_TOKEN.length), + content: lastMessage.content.slice(0, -token.length), }; return cleanedMessages; } return messages; } + + private async *streamCustomEndpoint( + path: string, + body: ChatCompletionCreateParamsStreaming, + signal: AbortSignal, + ): AsyncGenerator { + const endpoint = new URL(path, this.apiBase); + const resp = await customFetch(this.config.requestOptions)(endpoint, { + method: "POST", + body: JSON.stringify({ + model: body.model, + messages: body.messages, + max_tokens: body.max_tokens, + temperature: body.temperature, + top_p: body.top_p, + frequency_penalty: body.frequency_penalty, + presence_penalty: body.presence_penalty, + stop: body.stop, + stream: true, + }), + headers: { + "Content-Type": "application/json", + Accept: "application/json", + Authorization: `Bearer ${this.config.apiKey}`, + }, + signal, + }); + + for await (const chunk of streamSse(resp as any)) { + const deltaContent = chunk.choices?.[0]?.delta?.content; + if (deltaContent) { + yield chatChunk({ + content: deltaContent, + finish_reason: chunk.choices[0].finish_reason || null, + model: body.model, + }); + } + } + } + + private async nonStreamCustomEndpoint( + path: string, + body: ChatCompletionCreateParamsNonStreaming, + signal: AbortSignal, + ): Promise { + const endpoint = new URL(path, this.apiBase); + const resp = await customFetch(this.config.requestOptions)(endpoint, { + method: "POST", + body: JSON.stringify({ + model: body.model, + messages: body.messages, + max_tokens: body.max_tokens, + temperature: body.temperature, + top_p: body.top_p, + frequency_penalty: body.frequency_penalty, + presence_penalty: body.presence_penalty, + stop: body.stop, + stream: false, + }), + headers: { + "Content-Type": "application/json", + Accept: "application/json", + Authorization: `Bearer ${this.config.apiKey}`, + }, + signal, + }); + + const data = await resp.json(); + return data as ChatCompletion; + } }