From d729cebd83c1bf5319f6a017682f0f7cfdaef7e5 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Tue, 12 Dec 2023 19:09:12 -0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20support=20Azure=20OpenAI=20and?= =?UTF-8?q?=20local=20OpenAI=20compliant=20APIs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/llm/index.ts | 13 ++++ core/llm/llms/OpenAI.ts | 105 ++++++++++++++++++--------- core/util/paths.ts | 19 ++++- extensions/vscode/src/ideProtocol.ts | 17 ++++- 4 files changed, 115 insertions(+), 39 deletions(-) diff --git a/core/llm/index.ts b/core/llm/index.ts index bb537f9d6..581711a35 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -134,6 +134,11 @@ export interface LLMOptions { llmRequestHook?: (model: string, prompt: string) => any; apiKey?: string; apiBase?: string; + + // Azure options + engine?: string; + apiVersion?: string; + apiType?: string; } interface LLMFullCompletionOptions { @@ -174,6 +179,10 @@ export abstract class LLM implements LLMOptions { apiKey?: string; apiBase?: string; + engine?: string; + apiVersion?: string; + apiType?: string; + constructor(options: LLMOptions) { // Set default options options = { @@ -206,6 +215,10 @@ export abstract class LLM implements LLMOptions { this.llmRequestHook = options.llmRequestHook; this.apiKey = options.apiKey; this.apiBase = options.apiBase; + + this.engine = options.engine; + this.apiVersion = options.apiVersion; + this.apiType = options.apiType; } private _compileChatMessages( diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 487df5f98..0de5ba505 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -1,24 +1,12 @@ -import OpenAIClient from "openai"; import { ChatCompletionCreateParamsBase } from "openai/resources/chat/completions"; import { LLM, LLMOptions } from ".."; import { ModelProvider } from "../../config"; import { ChatMessage, CompletionOptions } from "../types"; class OpenAI extends LLM { static providerName: ModelProvider = "openai"; - - private _openai: OpenAIClient; - - constructor(options: LLMOptions) { - super(options); - - this._openai = new OpenAIClient({ - apiKey: this.apiKey, - baseURL: this.apiBase, - timeout: this.requestOptions?.timeout, - defaultHeaders: this.requestOptions?.headers, - dangerouslyAllowBrowser: true, - }); - } + static defaultOptions: Partial = { + apiBase: "https://api.openai.com", + }; protected _convertArgs( options: any, @@ -42,27 +30,34 @@ class OpenAI extends LLM { prompt: string, options: CompletionOptions ): Promise { - const response = await this._openai.chat.completions.create({ - ...this._convertArgs(options, [{ role: "user", content: prompt }]), - stream: false, - }); + let completion = ""; + for await (const chunk of this._streamChat( + [{ role: "user", content: prompt }], + options + )) { + completion += chunk.content; + } - return response.choices[0].message.content || ""; + return completion; } protected async *_streamComplete( prompt: string, options: CompletionOptions ): AsyncGenerator { - const response = await this._openai.chat.completions.create({ - ...this._convertArgs(options, [{ role: "user", content: prompt }]), - stream: true, - }); + for await (const chunk of this._streamChat( + [{ role: "user", content: prompt }], + options + )) { + yield chunk.content; + } + } - for await (const message of response) { - if (message.choices[0].delta.content) { - yield message.choices[0].delta.content; - } + private _getChatUrl() { + if (this.apiType === "azure") { + return `${this.apiBase}/openai/deployments/${this.engine}/chat/completions?api-version=${this.apiVersion}`; + } else { + return this.apiBase + "/v1/chat/completions"; } } @@ -70,14 +65,56 @@ class OpenAI extends LLM { messages: ChatMessage[], options: CompletionOptions ): AsyncGenerator { - const response = await this._openai.chat.completions.create({ - ...this._convertArgs(options, messages), - stream: true, + const response = await fetch(this._getChatUrl(), { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${this.apiKey}`, + "api-key": this.apiKey || "", // For Azure + }, + body: JSON.stringify({ + ...this._convertArgs(options, messages), + stream: true, + }), }); - for await (const message of response) { - if (message.choices[0].delta.content) { - yield { role: "assistant", content: message.choices[0].delta.content }; + // Receive as SSE + if (response.body === null) { + return; + } + let buffer = ""; + const reader = response.body.getReader(); + while (true) { + const { done, value } = await reader.read(); + if (done) { + break; + } + buffer += new TextDecoder("utf-8").decode(value); + let position; + while ((position = buffer.indexOf("\n")) >= 0) { + const line = buffer.slice(0, position); + buffer = buffer.slice(position + 1); + if (line.startsWith("data: ") && !line.startsWith("data: [DONE]")) { + const result = JSON.parse(line.slice(6)); + if (result.choices?.[0]?.delta?.content) { + yield result.choices[0].delta; + } + } + } + } + if (buffer.length > 0) { + if (buffer.startsWith("data: ") && !buffer.startsWith("data: [DONE]")) { + const result = JSON.parse(buffer.slice(6)); + if (result.choices?.[0]?.delta?.content) { + yield result.choices[0].delta; + } + } else { + try { + const result = JSON.parse(buffer); + if (result.error) { + throw new Error(result.error); + } + } catch (e) {} } } } diff --git a/core/util/paths.ts b/core/util/paths.ts index 633366ac0..ba94fda3e 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -46,7 +46,7 @@ export function devDataPath(): string { } export function getDevDataFilePath(fileName: string): string { - return path.join(devDataPath(), fileName); + return path.join(devDataPath(), fileName + ".jsonl"); } export function editConfigJson( @@ -58,3 +58,20 @@ export function editConfigJson( fs.writeFileSync(getConfigJsonPath(), JSON.stringify(configJson, null, 2)); return configJson; } + +function getMigrationsFolderPath(): string { + const migrationsPath = path.join(getContinueGlobalPath(), ".migrations"); + if (!fs.existsSync(migrationsPath)) { + fs.mkdirSync(migrationsPath); + } + return migrationsPath; +} + +export function migrate(id: string, callback: () => void) { + const migrationsPath = getMigrationsFolderPath(); + const migrationPath = path.join(migrationsPath, id); + if (!fs.existsSync(migrationPath)) { + fs.writeFileSync(migrationPath, ""); + callback(); + } +} diff --git a/extensions/vscode/src/ideProtocol.ts b/extensions/vscode/src/ideProtocol.ts index ddf929710..8373e1a5d 100644 --- a/extensions/vscode/src/ideProtocol.ts +++ b/extensions/vscode/src/ideProtocol.ts @@ -1,6 +1,10 @@ import { SerializedContinueConfig } from "core/config/index"; import { IDE } from "core/ide/types"; -import { getConfigJsonPath, getContinueGlobalPath } from "core/util/paths"; +import { + getConfigJsonPath, + getContinueGlobalPath, + migrate, +} from "core/util/paths"; import * as fs from "fs"; import * as vscode from "vscode"; import { ideProtocolClient } from "./activation/activate"; @@ -15,10 +19,15 @@ class VsCodeIde implements IDE { vscode.workspace.getConfiguration("continue").get("telemetryEnabled"); // Migrate to camelCase - replace all instances of "snake_case" with "camelCase" - contents = contents.replace(/(_\w)/g, function (m) { - return m[1].toUpperCase(); + migrate("camelCaseConfig", () => { + contents = contents + .replace(/(_\w)/g, function (m) { + return m[1].toUpperCase(); + }) + .replace("openai-aiohttp", "openai"); + + fs.writeFileSync(configPath, contents, "utf8"); }); - fs.writeFileSync(configPath, contents, "utf8"); return config; }