| 1 | import { |
| 2 | ChatCompletionCreateParams, |
| 3 | ChatCompletionMessageParam, |
| 4 | } from "openai/resources/index"; |
| 5 | |
| 6 | import { streamSse } from "@continuedev/fetch"; |
| 7 | import { |
| 8 | ChatMessage, |
| 9 | CompletionOptions, |
| 10 | LLMOptions, |
| 11 | Tool, |
| 12 | } from "../../index.js"; |
| 13 | import { renderChatMessage } from "../../util/messageContent.js"; |
| 14 | import { BaseLLM } from "../index.js"; |
| 15 | import { |
| 16 | fromChatCompletionChunk, |
| 17 | LlmApiRequestType, |
| 18 | toChatBody, |
| 19 | } from "../openaiTypeConverters.js"; |
| 20 | |
| 21 | const NON_CHAT_MODELS = [ |
| 22 | "text-davinci-002", |
| 23 | "text-davinci-003", |
| 24 | "code-davinci-002", |
| 25 | "text-ada-001", |
| 26 | "text-babbage-001", |
| 27 | "text-curie-001", |
| 28 | "davinci", |
| 29 | "curie", |
| 30 | "babbage", |
| 31 | "ada", |
| 32 | ]; |
| 33 | |
| 34 | function isChatOnlyModel(model: string): boolean { |
| 35 | // gpt and o-series models |
| 36 | return model.startsWith("gpt") || model.startsWith("o"); |
| 37 | } |
| 38 | |
| 39 | const formatMessageForO1OrGpt5 = (messages: ChatCompletionMessageParam[]) => { |
| 40 | return messages?.map((message: any) => { |
| 41 | if (message?.role === "system") { |
| 42 | return { |
| 43 | ...message, |
| 44 | role: "developer", |
| 45 | }; |
| 46 | } |
| 47 | |
| 48 | return message; |
| 49 | }); |
| 50 | }; |
| 51 | |
| 52 | class OpenAI extends BaseLLM { |
| 53 | public useLegacyCompletionsEndpoint: boolean | undefined = undefined; |
| 54 | |
| 55 | constructor(options: LLMOptions) { |
| 56 | super(options); |
| 57 | this.useLegacyCompletionsEndpoint = options.useLegacyCompletionsEndpoint; |
| 58 | this.apiVersion = options.apiVersion ?? "2023-07-01-preview"; |
| 59 | } |
| 60 | |
| 61 | static providerName = "openai"; |
| 62 | static defaultOptions: Partial<LLMOptions> | undefined = { |
| 63 | apiBase: "https://api.openai.com/v1/", |
| 64 | maxEmbeddingBatchSize: 128, |
| 65 | }; |
| 66 | |
| 67 | protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = [ |
| 68 | "chat", |
| 69 | "embed", |
| 70 | "list", |
| 71 | "rerank", |
| 72 | "streamChat", |
| 73 | "streamFim", |
| 74 | ]; |
| 75 | |
| 76 | protected _convertModelName(model: string): string { |
| 77 | return model; |
| 78 | } |
| 79 | |
| 80 | public isOSeriesOrGpt5Model(model?: string): boolean { |
| 81 | return !!model && (!!model.match(/^o[0-9]+/) || model.includes("gpt-5")); |
| 82 | } |
| 83 | |
| 84 | private isFireworksAiModel(model?: string): boolean { |
| 85 | return !!model && model.startsWith("accounts/fireworks/models"); |
| 86 | } |
| 87 | |
| 88 | protected supportsPrediction(model: string): boolean { |
| 89 | const SUPPORTED_MODELS = [ |
| 90 | "gpt-4o-mini", |
| 91 | "gpt-4o", |
| 92 | "mistral-large", |
| 93 | "Fast-Apply", |
| 94 | ]; |
| 95 | return SUPPORTED_MODELS.some((m) => model.includes(m)); |
| 96 | } |
| 97 | |
| 98 | private convertTool(tool: Tool): any { |
| 99 | return { |
| 100 | type: tool.type, |
| 101 | function: { |
| 102 | name: tool.function.name, |
| 103 | description: tool.function.description, |
| 104 | parameters: tool.function.parameters, |
| 105 | strict: tool.function.strict, |
| 106 | }, |
| 107 | }; |
| 108 | } |
| 109 | |
| 110 | protected extraBodyProperties(): Record<string, any> { |
| 111 | return {}; |
| 112 | } |
| 113 | |
| 114 | protected getMaxStopWords(): number { |
| 115 | const url = new URL(this.apiBase!); |
| 116 | |
| 117 | if (this.maxStopWords !== undefined) { |
| 118 | return this.maxStopWords; |
| 119 | } else if (url.host === "api.deepseek.com") { |
| 120 | return 16; |
| 121 | } else if ( |
| 122 | url.port === "1337" || |
| 123 | url.host === "api.openai.com" || |
| 124 | url.host === "api.groq.com" || |
| 125 | this.apiType === "azure" |
| 126 | ) { |
| 127 | return 4; |
| 128 | } else { |
| 129 | return Infinity; |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | protected _convertArgs( |
| 134 | options: CompletionOptions, |
| 135 | messages: ChatMessage[], |
| 136 | ): ChatCompletionCreateParams { |
| 137 | const finalOptions = toChatBody(messages, options); |
| 138 | |
| 139 | finalOptions.stop = options.stop?.slice(0, this.getMaxStopWords()); |
| 140 | |
| 141 | // OpenAI o1-preview and o1-mini or o3-mini: |
| 142 | if (this.isOSeriesOrGpt5Model(options.model)) { |
| 143 | // a) use max_completion_tokens instead of max_tokens |
| 144 | finalOptions.max_completion_tokens = options.maxTokens; |
| 145 | finalOptions.max_tokens = undefined; |
| 146 | |
| 147 | // b) don't support system message |
| 148 | finalOptions.messages = formatMessageForO1OrGpt5(finalOptions.messages); |
| 149 | } |
| 150 | |
| 151 | if (options.model === "o1") { |
| 152 | finalOptions.stream = false; |
| 153 | } |
| 154 | |
| 155 | if (options.prediction && this.supportsPrediction(options.model)) { |
| 156 | if (finalOptions.presence_penalty) { |
| 157 | // prediction doesn't support > 0 |
| 158 | finalOptions.presence_penalty = undefined; |
| 159 | } |
| 160 | if (finalOptions.frequency_penalty) { |
| 161 | // prediction doesn't support > 0 |
| 162 | finalOptions.frequency_penalty = undefined; |
| 163 | } |
| 164 | finalOptions.max_completion_tokens = undefined; |
| 165 | |
| 166 | finalOptions.prediction = options.prediction; |
| 167 | } else { |
| 168 | finalOptions.prediction = undefined; |
| 169 | } |
| 170 | |
| 171 | return finalOptions; |
| 172 | } |
| 173 | |
| 174 | protected _getHeaders() { |
| 175 | return { |
| 176 | "Content-Type": "application/json", |
| 177 | ...(this.apiKey && { Authorization: `Bearer ${this.apiKey}` }), |
| 178 | "api-key": this.apiKey ?? "", // For Azure |
| 179 | }; |
| 180 | } |
| 181 | |
| 182 | protected async _complete( |
| 183 | prompt: string, |
| 184 | signal: AbortSignal, |
| 185 | options: CompletionOptions, |
| 186 | ): Promise<string> { |
| 187 | let completion = ""; |
| 188 | for await (const chunk of this._streamChat( |
| 189 | [{ role: "user", content: prompt }], |
| 190 | signal, |
| 191 | options, |
| 192 | )) { |
| 193 | completion += chunk.content; |
| 194 | } |
| 195 | |
| 196 | return completion; |
| 197 | } |
| 198 | |
| 199 | protected _getEndpoint( |
| 200 | endpoint: "chat/completions" | "completions" | "models", |
| 201 | ) { |
| 202 | if (!this.apiBase) { |
| 203 | throw new Error( |
| 204 | "No API base URL provided. Please set the 'apiBase' option in config.json", |
| 205 | ); |
| 206 | } |
| 207 | |
| 208 | if (this.apiType?.includes("azure")) { |
| 209 | // Default is `azure-openai`, but previously was `azure` |
| 210 | const isAzureOpenAI = |
| 211 | this.apiType === "azure-openai" || this.apiType === "azure"; |
| 212 | |
| 213 | const path = isAzureOpenAI |
| 214 | ? `openai/deployments/${this.deployment}/${endpoint}` |
| 215 | : endpoint; |
| 216 | |
| 217 | const version = this.apiVersion ? `?api-version=${this.apiVersion}` : ""; |
| 218 | return new URL(`${path}${version}`, this.apiBase); |
| 219 | } |
| 220 | |
| 221 | return new URL(endpoint, this.apiBase); |
| 222 | } |
| 223 | |
| 224 | protected async *_streamComplete( |
| 225 | prompt: string, |
| 226 | signal: AbortSignal, |
| 227 | options: CompletionOptions, |
| 228 | ): AsyncGenerator<string> { |
| 229 | for await (const chunk of this._streamChat( |
| 230 | [{ role: "user", content: prompt }], |
| 231 | signal, |
| 232 | options, |
| 233 | )) { |
| 234 | yield renderChatMessage(chunk); |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | protected modifyChatBody( |
| 239 | body: ChatCompletionCreateParams, |
| 240 | ): ChatCompletionCreateParams { |
| 241 | body.stop = body.stop?.slice(0, this.getMaxStopWords()); |
| 242 | |
| 243 | // OpenAI o1-preview and o1-mini or o3-mini: |
| 244 | if (this.isOSeriesOrGpt5Model(body.model)) { |
| 245 | // a) use max_completion_tokens instead of max_tokens |
| 246 | body.max_completion_tokens = body.max_tokens; |
| 247 | body.max_tokens = undefined; |
| 248 | |
| 249 | // b) don't support system message |
| 250 | body.messages = formatMessageForO1OrGpt5(body.messages); |
| 251 | } |
| 252 | |
| 253 | if (body.model === "o1") { |
| 254 | // o1 doesn't support streaming |
| 255 | body.stream = false; |
| 256 | } |
| 257 | |
| 258 | if (body.prediction && this.supportsPrediction(body.model)) { |
| 259 | if (body.presence_penalty) { |
| 260 | // prediction doesn't support > 0 |
| 261 | body.presence_penalty = undefined; |
| 262 | } |
| 263 | if (body.frequency_penalty) { |
| 264 | // prediction doesn't support > 0 |
| 265 | body.frequency_penalty = undefined; |
| 266 | } |
| 267 | body.max_completion_tokens = undefined; |
| 268 | } |
| 269 | |
| 270 | if (body.tools?.length) { |
| 271 | if (this.isFireworksAiModel(body.model)) { |
| 272 | // fireworks.ai does not support parallel tool calls, but their api expects this to be true anyway otherwise they return an error. |
| 273 | // tooling works with them as a inference provider once this is set to true. |
| 274 | // https://docs.fireworks.ai/guides/function-calling#openai-compatibility |
| 275 | body.parallel_tool_calls = true; |
| 276 | } |
| 277 | // To ensure schema adherence: https://platform.openai.com/docs/guides/function-calling#parallel-function-calling-and-structured-outputs |
| 278 | // In practice, setting this to true and asking for multiple tool calls |
| 279 | // leads to "arguments" being something like '{"file": "test.ts"}{"file": "test.js"}' |
| 280 | // o3 does not support this |
| 281 | if (!body.model.startsWith("o3")) { |
| 282 | body.parallel_tool_calls = false; |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | return body; |
| 287 | } |
| 288 | |
| 289 | protected async *_legacystreamComplete( |
| 290 | prompt: string, |
| 291 | signal: AbortSignal, |
| 292 | options: CompletionOptions, |
| 293 | ): AsyncGenerator<string> { |
| 294 | const args: any = this._convertArgs(options, []); |
| 295 | args.prompt = prompt; |
| 296 | args.messages = undefined; |
| 297 | |
| 298 | const response = await this.fetch(this._getEndpoint("completions"), { |
| 299 | method: "POST", |
| 300 | headers: this._getHeaders(), |
| 301 | body: JSON.stringify({ |
| 302 | ...args, |
| 303 | stream: true, |
| 304 | ...this.extraBodyProperties(), |
| 305 | }), |
| 306 | signal, |
| 307 | }); |
| 308 | |
| 309 | for await (const value of streamSse(response)) { |
| 310 | if (value.choices?.[0]?.text && value.finish_reason !== "eos") { |
| 311 | yield value.choices[0].text; |
| 312 | } |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | protected async *_streamChat( |
| 317 | messages: ChatMessage[], |
| 318 | signal: AbortSignal, |
| 319 | options: CompletionOptions, |
| 320 | ): AsyncGenerator<ChatMessage> { |
| 321 | if ( |
| 322 | !isChatOnlyModel(options.model) && |
| 323 | this.supportsCompletions() && |
| 324 | (NON_CHAT_MODELS.includes(options.model) || |
| 325 | this.useLegacyCompletionsEndpoint || |
| 326 | options.raw) |
| 327 | ) { |
| 328 | for await (const content of this._legacystreamComplete( |
| 329 | renderChatMessage(messages[messages.length - 1]), |
| 330 | signal, |
| 331 | options, |
| 332 | )) { |
| 333 | yield { |
| 334 | role: "assistant", |
| 335 | content, |
| 336 | }; |
| 337 | } |
| 338 | return; |
| 339 | } |
| 340 | |
| 341 | const body = this._convertArgs(options, messages); |
| 342 | |
| 343 | const response = await this.fetch(this._getEndpoint("chat/completions"), { |
| 344 | method: "POST", |
| 345 | headers: this._getHeaders(), |
| 346 | body: JSON.stringify({ |
| 347 | ...body, |
| 348 | ...this.extraBodyProperties(), |
| 349 | }), |
| 350 | signal, |
| 351 | }); |
| 352 | |
| 353 | // Handle non-streaming response |
| 354 | if (body.stream === false) { |
| 355 | if (response.status === 499) { |
| 356 | return; // Aborted by user |
| 357 | } |
| 358 | const data = await response.json(); |
| 359 | yield data.choices[0].message; |
| 360 | return; |
| 361 | } |
| 362 | |
| 363 | for await (const value of streamSse(response)) { |
| 364 | const chunk = fromChatCompletionChunk(value); |
| 365 | if (chunk) { |
| 366 | yield chunk; |
| 367 | } |
| 368 | } |
| 369 | } |
| 370 | |
| 371 | protected async *_streamFim( |
| 372 | prefix: string, |
| 373 | suffix: string, |
| 374 | signal: AbortSignal, |
| 375 | options: CompletionOptions, |
| 376 | ): AsyncGenerator<string> { |
| 377 | const endpoint = new URL("fim/completions", this.apiBase); |
| 378 | const resp = await this.fetch(endpoint, { |
| 379 | method: "POST", |
| 380 | body: JSON.stringify({ |
| 381 | model: options.model, |
| 382 | prompt: prefix, |
| 383 | suffix, |
| 384 | max_tokens: options.maxTokens, |
| 385 | temperature: options.temperature, |
| 386 | top_p: options.topP, |
| 387 | frequency_penalty: options.frequencyPenalty, |
| 388 | presence_penalty: options.presencePenalty, |
| 389 | stop: options.stop, |
| 390 | stream: true, |
| 391 | ...this.extraBodyProperties(), |
| 392 | }), |
| 393 | headers: { |
| 394 | "Content-Type": "application/json", |
| 395 | Accept: "application/json", |
| 396 | "x-api-key": this.apiKey ?? "", |
| 397 | Authorization: `Bearer ${this.apiKey}`, |
| 398 | }, |
| 399 | signal, |
| 400 | }); |
| 401 | for await (const chunk of streamSse(resp)) { |
| 402 | yield chunk.choices[0].delta.content; |
| 403 | } |
| 404 | } |
| 405 | |
| 406 | async listModels(): Promise<string[]> { |
| 407 | const response = await this.fetch(this._getEndpoint("models"), { |
| 408 | method: "GET", |
| 409 | headers: this._getHeaders(), |
| 410 | }); |
| 411 | |
| 412 | const data = await response.json(); |
| 413 | return data.data.map((m: any) => m.id); |
| 414 | } |
| 415 | |
| 416 | private _getEmbedEndpoint() { |
| 417 | if (!this.apiBase) { |
| 418 | throw new Error( |
| 419 | "No API base URL provided. Please set the 'apiBase' option in config.json", |
| 420 | ); |
| 421 | } |
| 422 | |
| 423 | if (this.apiType === "azure") { |
| 424 | return new URL( |
| 425 | `openai/deployments/${this.deployment}/embeddings?api-version=${this.apiVersion}`, |
| 426 | this.apiBase, |
| 427 | ); |
| 428 | } |
| 429 | return new URL("embeddings", this.apiBase); |
| 430 | } |
| 431 | |
| 432 | protected async _embed(chunks: string[]): Promise<number[][]> { |
| 433 | const resp = await this.fetch(this._getEmbedEndpoint(), { |
| 434 | method: "POST", |
| 435 | body: JSON.stringify({ |
| 436 | input: chunks, |
| 437 | model: this.model, |
| 438 | ...this.extraBodyProperties(), |
| 439 | }), |
| 440 | headers: { |
| 441 | Authorization: `Bearer ${this.apiKey}`, |
| 442 | "Content-Type": "application/json", |
| 443 | "api-key": this.apiKey ?? "", // For Azure |
| 444 | }, |
| 445 | }); |
| 446 | |
| 447 | if (!resp.ok) { |
| 448 | throw new Error(await resp.text()); |
| 449 | } |
| 450 | |
| 451 | const data = (await resp.json()) as any; |
| 452 | return data.data.map((result: { embedding: number[] }) => result.embedding); |
| 453 | } |
| 454 | } |
| 455 | |
| 456 | export default OpenAI; |