🐛 support Azure OpenAI and local OpenAI compliant APIs

This commit is contained in:
Nate Sesti 2023-12-12 19:09:12 -08:00
parent f0b982278d
commit d729cebd83
4 changed files with 115 additions and 39 deletions

View file

@ -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(

View file

@ -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<LLMOptions> = {
apiBase: "https://api.openai.com",
};
protected _convertArgs(
options: any,
@ -42,27 +30,34 @@ class OpenAI extends LLM {
prompt: string,
options: CompletionOptions
): Promise<string> {
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<string> {
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<ChatMessage> {
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) {}
}
}
}

View file

@ -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();
}
}

View file

@ -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;
}