| 1 | import { AzureKeyCredential, OpenAIClient } from "@azure/openai"; |
| 2 | |
| 3 | import dotenv from "dotenv"; |
| 4 | import { |
| 5 | Completion, |
| 6 | CompletionCreateParamsNonStreaming, |
| 7 | CompletionCreateParamsStreaming, |
| 8 | } from "openai/resources/completions.js"; |
| 9 | import { |
| 10 | ChatCompletion, |
| 11 | ChatCompletionChunk, |
| 12 | ChatCompletionCreateParamsNonStreaming, |
| 13 | ChatCompletionCreateParamsStreaming, |
| 14 | CreateEmbeddingResponse, |
| 15 | EmbeddingCreateParams, |
| 16 | Model, |
| 17 | } from "openai/resources/index.js"; |
| 18 | import { AzureConfig } from "../types.js"; |
| 19 | import { embedding } from "../util.js"; |
| 20 | import { |
| 21 | BaseLlmApi, |
| 22 | CreateRerankResponse, |
| 23 | FimCreateParamsStreaming, |
| 24 | RerankCreateParams, |
| 25 | } from "./base.js"; |
| 26 | |
| 27 | dotenv.config(); |
| 28 | |
| 29 | const HTTPS_PROXY = process.env.HTTPS_PROXY; |
| 30 | const HTTP_PROXY = process.env.HTTP_PROXY; |
| 31 | |
| 32 | const MS_TOKEN = 30; |
| 33 | |
| 34 | export class AzureOpenAIApi implements BaseLlmApi { |
| 35 | private client: OpenAIClient; |
| 36 | |
| 37 | constructor(private config: AzureConfig) { |
| 38 | let proxyOptions; |
| 39 | const PROXY = HTTPS_PROXY ?? HTTP_PROXY; |
| 40 | if (PROXY) { |
| 41 | const url = new URL(PROXY); |
| 42 | proxyOptions = { |
| 43 | host: (url.protocol ? url.protocol + "//" : "") + url.hostname, |
| 44 | port: Number(url.port || 80), |
| 45 | username: url.username, |
| 46 | password: url.password, |
| 47 | }; |
| 48 | } |
| 49 | |
| 50 | if (!config.apiBase || !config.apiKey) { |
| 51 | throw new Error("Azure OpenAI API requires apiBase and apiKey"); |
| 52 | } |
| 53 | |
| 54 | this.client = new OpenAIClient( |
| 55 | config.apiBase, |
| 56 | new AzureKeyCredential(config.apiKey), |
| 57 | { |
| 58 | proxyOptions, |
| 59 | }, |
| 60 | ); |
| 61 | } |
| 62 | |
| 63 | private _bodyToOptions( |
| 64 | body: |
| 65 | | ChatCompletionCreateParamsStreaming |
| 66 | | ChatCompletionCreateParamsNonStreaming, |
| 67 | signal: AbortSignal, |
| 68 | ) { |
| 69 | return { |
| 70 | maxTokens: body.max_tokens ?? undefined, |
| 71 | temperature: body.temperature ?? undefined, |
| 72 | topP: body.top_p ?? undefined, |
| 73 | frequencyPenalty: body.frequency_penalty ?? undefined, |
| 74 | presencePenalty: body.presence_penalty ?? undefined, |
| 75 | stop: |
| 76 | typeof body.stop === "string" ? [body.stop] : (body.stop ?? undefined), |
| 77 | abortSignal: signal, |
| 78 | }; |
| 79 | } |
| 80 | |
| 81 | async chatCompletionNonStream( |
| 82 | body: ChatCompletionCreateParamsNonStreaming, |
| 83 | signal: AbortSignal, |
| 84 | ): Promise<ChatCompletion> { |
| 85 | const completion = await this.client.getChatCompletions( |
| 86 | body.model, |
| 87 | body.messages, |
| 88 | this._bodyToOptions(body, signal), |
| 89 | ); |
| 90 | return { |
| 91 | ...completion, |
| 92 | object: "chat.completion", |
| 93 | model: body.model, |
| 94 | created: completion.created.getTime(), |
| 95 | usage: completion.usage |
| 96 | ? { |
| 97 | total_tokens: completion.usage.totalTokens, |
| 98 | completion_tokens: completion.usage.completionTokens, |
| 99 | prompt_tokens: completion.usage.promptTokens, |
| 100 | } |
| 101 | : undefined, |
| 102 | choices: completion.choices.map((choice) => ({ |
| 103 | ...choice, |
| 104 | logprobs: null, |
| 105 | finish_reason: "stop", |
| 106 | message: { |
| 107 | role: "assistant", |
| 108 | content: choice.message?.content ?? null, |
| 109 | refusal: null, |
| 110 | }, |
| 111 | })), |
| 112 | }; |
| 113 | } |
| 114 | async *chatCompletionStream( |
| 115 | body: ChatCompletionCreateParamsStreaming, |
| 116 | signal: AbortSignal, |
| 117 | ): AsyncGenerator<ChatCompletionChunk> { |
| 118 | const events = await this.client.streamChatCompletions( |
| 119 | body.model, |
| 120 | body.messages, |
| 121 | this._bodyToOptions(body, signal), |
| 122 | ); |
| 123 | |
| 124 | const eventBuffer: ChatCompletionChunk[] = []; |
| 125 | let done = false; |
| 126 | let tokensOutput = 0; |
| 127 | const ms = MS_TOKEN; |
| 128 | (async () => { |
| 129 | for await (const event of events) { |
| 130 | eventBuffer.push({ |
| 131 | ...event, |
| 132 | object: "chat.completion.chunk", |
| 133 | model: body.model, |
| 134 | created: event.created.getTime(), |
| 135 | choices: event.choices.map((choice: any) => ({ |
| 136 | ...choice, |
| 137 | logprobs: undefined, |
| 138 | finish_reason: null, |
| 139 | delta: { |
| 140 | role: (choice.delta?.role as any) ?? "assistant", |
| 141 | content: choice.delta?.content ?? "", |
| 142 | }, |
| 143 | })), |
| 144 | usage: undefined, |
| 145 | }); |
| 146 | } |
| 147 | done = true; |
| 148 | })(); |
| 149 | |
| 150 | while (!done) { |
| 151 | if (eventBuffer.length > 0) { |
| 152 | const event = eventBuffer.shift()!; |
| 153 | yield event; |
| 154 | tokensOutput += event.choices[0]?.delta.content?.length ?? 0; |
| 155 | } else { |
| 156 | await new Promise((resolve) => setTimeout(resolve, 5)); |
| 157 | continue; |
| 158 | } |
| 159 | |
| 160 | if (tokensOutput < 100 && eventBuffer.length > 30) { |
| 161 | await new Promise((resolve) => setTimeout(resolve, ms / 3)); |
| 162 | } else if (eventBuffer.length < 12) { |
| 163 | await new Promise((resolve) => |
| 164 | setTimeout(resolve, ms + 20 * (12 - eventBuffer.length)), |
| 165 | ); |
| 166 | } else if (eventBuffer.length > 40) { |
| 167 | await new Promise((resolve) => setTimeout(resolve, ms / 2)); |
| 168 | } else { |
| 169 | // await new Promise((resolve) => setTimeout(resolve, Math.max(25, 50 - 2 * eventBuffer.length))); |
| 170 | await new Promise((resolve) => setTimeout(resolve, ms)); |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | for (const event of eventBuffer) yield event; |
| 175 | } |
| 176 | async completionNonStream( |
| 177 | body: CompletionCreateParamsNonStreaming, |
| 178 | signal: AbortSignal, |
| 179 | ): Promise<Completion> { |
| 180 | const { prompt, logprobs, ...restOfBody } = body; |
| 181 | const messages = [ |
| 182 | { |
| 183 | role: "user" as any, |
| 184 | content: prompt as any, |
| 185 | }, |
| 186 | ]; |
| 187 | const resp = await this.chatCompletionNonStream( |
| 188 | { |
| 189 | messages, |
| 190 | ...restOfBody, |
| 191 | }, |
| 192 | signal, |
| 193 | ); |
| 194 | return { |
| 195 | ...resp, |
| 196 | object: "text_completion", |
| 197 | choices: resp.choices.map((choice) => ({ |
| 198 | ...choice, |
| 199 | text: choice.message.content ?? "", |
| 200 | finish_reason: "stop", |
| 201 | logprobs: null, |
| 202 | })), |
| 203 | }; |
| 204 | } |
| 205 | async *completionStream( |
| 206 | body: CompletionCreateParamsStreaming, |
| 207 | signal: AbortSignal, |
| 208 | ): AsyncGenerator<Completion> { |
| 209 | const { prompt, logprobs, ...restOfBody } = body; |
| 210 | const messages = [ |
| 211 | { |
| 212 | role: "user" as any, |
| 213 | content: prompt as any, |
| 214 | }, |
| 215 | ]; |
| 216 | for await (const event of this.chatCompletionStream( |
| 217 | { |
| 218 | messages, |
| 219 | ...restOfBody, |
| 220 | }, |
| 221 | signal, |
| 222 | )) { |
| 223 | yield { |
| 224 | ...event, |
| 225 | object: "text_completion", |
| 226 | usage: { |
| 227 | completion_tokens: event.usage?.completion_tokens ?? 0, |
| 228 | prompt_tokens: event.usage?.prompt_tokens ?? 0, |
| 229 | total_tokens: event.usage?.total_tokens ?? 0, |
| 230 | }, |
| 231 | choices: event.choices.map((choice) => ({ |
| 232 | ...choice, |
| 233 | text: choice.delta.content ?? "", |
| 234 | finish_reason: "stop", |
| 235 | logprobs: null, |
| 236 | })), |
| 237 | }; |
| 238 | } |
| 239 | } |
| 240 | fimStream( |
| 241 | body: FimCreateParamsStreaming, |
| 242 | ): AsyncGenerator<ChatCompletionChunk> { |
| 243 | throw new Error( |
| 244 | "Azure OpenAI does not support fill-in-the-middle (FIM) completions.", |
| 245 | ); |
| 246 | } |
| 247 | |
| 248 | async embed(body: EmbeddingCreateParams): Promise<CreateEmbeddingResponse> { |
| 249 | const input = typeof body.input === "string" ? [body.input] : body.input; |
| 250 | const response = await this.client.getEmbeddings(body.model, input as any, { |
| 251 | dimensions: body.dimensions, |
| 252 | model: body.model, |
| 253 | }); |
| 254 | |
| 255 | const output = embedding({ |
| 256 | data: response.data.map((item) => item.embedding), |
| 257 | model: body.model, |
| 258 | usage: { |
| 259 | prompt_tokens: response.usage.promptTokens, |
| 260 | total_tokens: response.usage.totalTokens, |
| 261 | }, |
| 262 | }); |
| 263 | |
| 264 | return output; |
| 265 | } |
| 266 | |
| 267 | async rerank(body: RerankCreateParams): Promise<CreateRerankResponse> { |
| 268 | throw new Error("Azure OpenAI does not support reranking."); |
| 269 | } |
| 270 | |
| 271 | list(): Promise<Model[]> { |
| 272 | throw new Error("Method not implemented."); |
| 273 | } |
| 274 | } |