Merge branch 'nate/azure-openai-adapters' into watsonx-vi

This commit is contained in:
Nate 2025-05-28 18:26:31 -07:00
commit cd38bfb7fe
6 changed files with 17 additions and 414 deletions

View file

@ -9,7 +9,6 @@
"version": "1.0.26",
"license": "Apache-2.0",
"dependencies": {
"@azure/openai": "^1.0.0-beta.12",
"@continuedev/config-types": "^1.0.5",
"@continuedev/config-yaml": "^1.0.51",
"@continuedev/fetch": "^1.0.11",
@ -43,126 +42,6 @@
"node": ">=6.0.0"
}
},
"node_modules/@azure-rest/core-client": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/@azure-rest/core-client/-/core-client-1.4.0.tgz",
"integrity": "sha512-ozTDPBVUDR5eOnMIwhggbnVmOrka4fXCs8n8mvUo4WLLc38kki6bAOByDoVZZPz/pZy2jMt2kwfpvy/UjALj6w==",
"dependencies": {
"@azure/abort-controller": "^2.0.0",
"@azure/core-auth": "^1.3.0",
"@azure/core-rest-pipeline": "^1.5.0",
"@azure/core-tracing": "^1.0.1",
"@azure/core-util": "^1.0.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/abort-controller": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/@azure/abort-controller/-/abort-controller-2.1.2.tgz",
"integrity": "sha512-nBrLsEWm4J2u5LpAPjxADTlq3trDgVZZXHNKabeXZtpq3d3AbN/KGO82R87rdDz5/lYB024rtEf10/q0urNgsA==",
"dependencies": {
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/core-auth": {
"version": "1.7.2",
"resolved": "https://registry.npmjs.org/@azure/core-auth/-/core-auth-1.7.2.tgz",
"integrity": "sha512-Igm/S3fDYmnMq1uKS38Ae1/m37B3zigdlZw+kocwEhh5GjyKjPrXKO2J6rzpC1wAxrNil/jX9BJRqBshyjnF3g==",
"dependencies": {
"@azure/abort-controller": "^2.0.0",
"@azure/core-util": "^1.1.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/core-rest-pipeline": {
"version": "1.16.2",
"resolved": "https://registry.npmjs.org/@azure/core-rest-pipeline/-/core-rest-pipeline-1.16.2.tgz",
"integrity": "sha512-Hnhm/PG9/SQ07JJyLDv3l9Qr8V3xgAe1hFoBYzt6LaalMxfL/ZqFaZf/bz5VN3pMcleCPwl8ivlS2Fjxq/iC8Q==",
"dependencies": {
"@azure/abort-controller": "^2.0.0",
"@azure/core-auth": "^1.4.0",
"@azure/core-tracing": "^1.0.1",
"@azure/core-util": "^1.9.0",
"@azure/logger": "^1.0.0",
"http-proxy-agent": "^7.0.0",
"https-proxy-agent": "^7.0.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/core-sse": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/@azure/core-sse/-/core-sse-2.1.2.tgz",
"integrity": "sha512-yf+pFIu8yCzXu9RbH2+8kp9vITIKJLHgkLgFNA6hxiDHK3fxeP596cHUj4c8Cm8JlooaUnYdHmF84KCZt3jbmw==",
"dependencies": {
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/core-tracing": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@azure/core-tracing/-/core-tracing-1.1.2.tgz",
"integrity": "sha512-dawW9ifvWAWmUm9/h+/UQ2jrdvjCJ7VJEuCJ6XVNudzcOwm53BFZH4Q845vjfgoUAM8ZxokvVNxNxAITc502YA==",
"dependencies": {
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/core-util": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/@azure/core-util/-/core-util-1.9.1.tgz",
"integrity": "sha512-OLsq0etbHO1MA7j6FouXFghuHrAFGk+5C1imcpQ2e+0oZhYF07WLA+NW2Vqs70R7d+zOAWiWM3tbE1sXcDN66g==",
"dependencies": {
"@azure/abort-controller": "^2.0.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/logger": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/@azure/logger/-/logger-1.1.3.tgz",
"integrity": "sha512-J8/cIKNQB1Fc9fuYqBVnrppiUtW+5WWJPCj/tAokC5LdSTwkWWttN+jsRgw9BLYD7JDBx7PceiqOBxJJ1tQz3Q==",
"dependencies": {
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/openai": {
"version": "1.0.0-beta.12",
"resolved": "https://registry.npmjs.org/@azure/openai/-/openai-1.0.0-beta.12.tgz",
"integrity": "sha512-qKblxr6oVa8GsyNzY+/Ub9VmEsPYKhBrUrPaNEQiM+qrxnBPVm9kaeqGFFb/U78Q2zOabmhF9ctYt3xBW0nWnQ==",
"dependencies": {
"@azure-rest/core-client": "^1.1.7",
"@azure/core-auth": "^1.4.0",
"@azure/core-rest-pipeline": "^1.13.0",
"@azure/core-sse": "^2.0.0",
"@azure/core-util": "^1.4.0",
"@azure/logger": "^1.0.3",
"tslib": "^2.4.0"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@babel/code-frame": {
"version": "7.24.7",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.24.7.tgz",
@ -4271,11 +4150,6 @@
}
}
},
"node_modules/tslib": {
"version": "2.6.3",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.3.tgz",
"integrity": "sha512-xNvxJEOUiWPGhUuUdQgAJPKOOJfGnIyKySOc09XkKsgdUV/3E2zvwZYdejjmRgPCgcym1juLH3226yA7sEFJKQ=="
},
"node_modules/type-detect": {
"version": "4.0.8",
"resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz",

View file

@ -12,7 +12,6 @@
"author": "Nate Sesti and Ty Dunn",
"license": "Apache-2.0",
"dependencies": {
"@azure/openai": "^1.0.0-beta.12",
"@continuedev/config-types": "^1.0.5",
"@continuedev/config-yaml": "^1.0.51",
"@continuedev/fetch": "^1.0.11",

View file

@ -1,274 +0,0 @@
import { AzureKeyCredential, OpenAIClient } from "@azure/openai";
import dotenv from "dotenv";
import {
Completion,
CompletionCreateParamsNonStreaming,
CompletionCreateParamsStreaming,
} from "openai/resources/completions.js";
import {
ChatCompletion,
ChatCompletionChunk,
ChatCompletionCreateParamsNonStreaming,
ChatCompletionCreateParamsStreaming,
CreateEmbeddingResponse,
EmbeddingCreateParams,
Model,
} from "openai/resources/index.js";
import { AzureConfig } from "../types.js";
import { embedding } from "../util.js";
import {
BaseLlmApi,
CreateRerankResponse,
FimCreateParamsStreaming,
RerankCreateParams,
} from "./base.js";
dotenv.config();
const HTTPS_PROXY = process.env.HTTPS_PROXY;
const HTTP_PROXY = process.env.HTTP_PROXY;
const MS_TOKEN = 30;
export class AzureOpenAIApi implements BaseLlmApi {
private client: OpenAIClient;
constructor(private config: AzureConfig) {
let proxyOptions;
const PROXY = HTTPS_PROXY ?? HTTP_PROXY;
if (PROXY) {
const url = new URL(PROXY);
proxyOptions = {
host: (url.protocol ? url.protocol + "//" : "") + url.hostname,
port: Number(url.port || 80),
username: url.username,
password: url.password,
};
}
if (!config.apiBase || !config.apiKey) {
throw new Error("Azure OpenAI API requires apiBase and apiKey");
}
this.client = new OpenAIClient(
config.apiBase,
new AzureKeyCredential(config.apiKey),
{
proxyOptions,
},
);
}
private _bodyToOptions(
body:
| ChatCompletionCreateParamsStreaming
| ChatCompletionCreateParamsNonStreaming,
signal: AbortSignal,
) {
return {
maxTokens: body.max_tokens ?? undefined,
temperature: body.temperature ?? undefined,
topP: body.top_p ?? undefined,
frequencyPenalty: body.frequency_penalty ?? undefined,
presencePenalty: body.presence_penalty ?? undefined,
stop:
typeof body.stop === "string" ? [body.stop] : (body.stop ?? undefined),
abortSignal: signal,
};
}
async chatCompletionNonStream(
body: ChatCompletionCreateParamsNonStreaming,
signal: AbortSignal,
): Promise<ChatCompletion> {
const completion = await this.client.getChatCompletions(
body.model,
body.messages,
this._bodyToOptions(body, signal),
);
return {
...completion,
object: "chat.completion",
model: body.model,
created: completion.created.getTime(),
usage: completion.usage
? {
total_tokens: completion.usage.totalTokens,
completion_tokens: completion.usage.completionTokens,
prompt_tokens: completion.usage.promptTokens,
}
: undefined,
choices: completion.choices.map((choice) => ({
...choice,
logprobs: null,
finish_reason: "stop",
message: {
role: "assistant",
content: choice.message?.content ?? null,
refusal: null,
},
})),
};
}
async *chatCompletionStream(
body: ChatCompletionCreateParamsStreaming,
signal: AbortSignal,
): AsyncGenerator<ChatCompletionChunk> {
const events = await this.client.streamChatCompletions(
body.model,
body.messages,
this._bodyToOptions(body, signal),
);
const eventBuffer: ChatCompletionChunk[] = [];
let done = false;
let tokensOutput = 0;
const ms = MS_TOKEN;
(async () => {
for await (const event of events) {
eventBuffer.push({
...event,
object: "chat.completion.chunk",
model: body.model,
created: event.created.getTime(),
choices: event.choices.map((choice: any) => ({
...choice,
logprobs: undefined,
finish_reason: null,
delta: {
role: (choice.delta?.role as any) ?? "assistant",
content: choice.delta?.content ?? "",
},
})),
usage: undefined,
});
}
done = true;
})();
while (!done) {
if (eventBuffer.length > 0) {
const event = eventBuffer.shift()!;
yield event;
tokensOutput += event.choices[0]?.delta.content?.length ?? 0;
} else {
await new Promise((resolve) => setTimeout(resolve, 5));
continue;
}
if (tokensOutput < 100 && eventBuffer.length > 30) {
await new Promise((resolve) => setTimeout(resolve, ms / 3));
} else if (eventBuffer.length < 12) {
await new Promise((resolve) =>
setTimeout(resolve, ms + 20 * (12 - eventBuffer.length)),
);
} else if (eventBuffer.length > 40) {
await new Promise((resolve) => setTimeout(resolve, ms / 2));
} else {
// await new Promise((resolve) => setTimeout(resolve, Math.max(25, 50 - 2 * eventBuffer.length)));
await new Promise((resolve) => setTimeout(resolve, ms));
}
}
for (const event of eventBuffer) yield event;
}
async completionNonStream(
body: CompletionCreateParamsNonStreaming,
signal: AbortSignal,
): Promise<Completion> {
const { prompt, logprobs, ...restOfBody } = body;
const messages = [
{
role: "user" as any,
content: prompt as any,
},
];
const resp = await this.chatCompletionNonStream(
{
messages,
...restOfBody,
},
signal,
);
return {
...resp,
object: "text_completion",
choices: resp.choices.map((choice) => ({
...choice,
text: choice.message.content ?? "",
finish_reason: "stop",
logprobs: null,
})),
};
}
async *completionStream(
body: CompletionCreateParamsStreaming,
signal: AbortSignal,
): AsyncGenerator<Completion> {
const { prompt, logprobs, ...restOfBody } = body;
const messages = [
{
role: "user" as any,
content: prompt as any,
},
];
for await (const event of this.chatCompletionStream(
{
messages,
...restOfBody,
},
signal,
)) {
yield {
...event,
object: "text_completion",
usage: {
completion_tokens: event.usage?.completion_tokens ?? 0,
prompt_tokens: event.usage?.prompt_tokens ?? 0,
total_tokens: event.usage?.total_tokens ?? 0,
},
choices: event.choices.map((choice) => ({
...choice,
text: choice.delta.content ?? "",
finish_reason: "stop",
logprobs: null,
})),
};
}
}
fimStream(
body: FimCreateParamsStreaming,
): AsyncGenerator<ChatCompletionChunk> {
throw new Error(
"Azure OpenAI does not support fill-in-the-middle (FIM) completions.",
);
}
async embed(body: EmbeddingCreateParams): Promise<CreateEmbeddingResponse> {
const input = typeof body.input === "string" ? [body.input] : body.input;
const response = await this.client.getEmbeddings(body.model, input as any, {
dimensions: body.dimensions,
model: body.model,
});
const output = embedding({
data: response.data.map((item) => item.embedding),
model: body.model,
usage: {
prompt_tokens: response.usage.promptTokens,
total_tokens: response.usage.totalTokens,
},
});
return output;
}
async rerank(body: RerankCreateParams): Promise<CreateRerankResponse> {
throw new Error("Azure OpenAI does not support reranking.");
}
list(): Promise<Model[]> {
throw new Error("Method not implemented.");
}
}

View file

@ -12,7 +12,7 @@ import {
Model,
} from "openai/resources/index";
import { z } from "zod";
import { OpenAIConfigSchema } from "../types.js";
import { AzureConfigSchema, OpenAIConfigSchema } from "../types.js";
import { customFetch } from "../util.js";
import {
BaseLlmApi,
@ -25,7 +25,11 @@ export class OpenAIApi implements BaseLlmApi {
openai: OpenAI;
apiBase: string = "https://api.openai.com/v1/";
constructor(protected config: z.infer<typeof OpenAIConfigSchema>) {
constructor(
protected config: z.infer<
typeof OpenAIConfigSchema | typeof AzureConfigSchema
>,
) {
this.apiBase = config.apiBase ?? this.apiBase;
this.openai = new OpenAI({
apiKey: config.apiKey,

View file

@ -35,14 +35,6 @@ export class WatsonXApi implements BaseLlmApi {
this.deploymentId = config.env.deploymentId;
}
private async getHeaders(): Promise<Record<string, string>> {
const bearer = await this.getBearerToken();
return {
"Content-Type": "application/json",
Authorization: `Bearer ${bearer.token}`,
};
}
async getBearerToken(): Promise<{ token: string; expiration: number }> {
if (this.apiBase?.includes("cloud.ibm.com")) {
// watsonx SaaS
@ -185,6 +177,16 @@ export class WatsonXApi implements BaseLlmApi {
return payload;
}
private async getHeaders(): Promise<Record<string, string>> {
const bearer = await this.getBearerToken();
const isZenApiKey = bearer.expiration === -1;
return {
"Content-Type": "application/json",
Authorization: `${isZenApiKey ? "ZenApiKey" : "Bearer"} ${bearer.token}`,
};
}
async chatCompletionNonStream(
body: ChatCompletionCreateParamsNonStreaming,
signal: AbortSignal,

View file

@ -1,7 +1,6 @@
import dotenv from "dotenv";
import { z } from "zod";
import { AnthropicApi } from "./apis/Anthropic.js";
import { AzureOpenAIApi } from "./apis/AzureOpenAI.js";
import { CohereApi } from "./apis/Cohere.js";
import { DeepSeekApi } from "./apis/DeepSeek.js";
import { GeminiApi } from "./apis/Gemini.js";
@ -30,9 +29,8 @@ function openAICompatible(
export function constructLlmApi(config: LLMConfig): BaseLlmApi | undefined {
switch (config.provider) {
case "openai":
return new OpenAIApi(config);
case "azure":
return new AzureOpenAIApi(config);
return new OpenAIApi(config);
case "cohere":
return new CohereApi(config);
case "anthropic":