| 1 | import { streamSse } from "@continuedev/fetch"; |
| 2 | import { OpenAI } from "openai/index"; |
| 3 | import { |
| 4 | ChatCompletion, |
| 5 | ChatCompletionChunk, |
| 6 | ChatCompletionCreateParams, |
| 7 | ChatCompletionCreateParamsNonStreaming, |
| 8 | ChatCompletionCreateParamsStreaming, |
| 9 | Completion, |
| 10 | CompletionCreateParamsNonStreaming, |
| 11 | CompletionCreateParamsStreaming, |
| 12 | Model, |
| 13 | } from "openai/resources/index"; |
| 14 | import { z } from "zod"; |
| 15 | import { OpenAIConfigSchema } from "../types.js"; |
| 16 | import { customFetch } from "../util.js"; |
| 17 | import { |
| 18 | BaseLlmApi, |
| 19 | CreateRerankResponse, |
| 20 | FimCreateParamsStreaming, |
| 21 | RerankCreateParams, |
| 22 | } from "./base.js"; |
| 23 | |
| 24 | export class OpenAIApi implements BaseLlmApi { |
| 25 | openai: OpenAI; |
| 26 | apiBase: string = "https://api.openai.com/v1/"; |
| 27 | |
| 28 | constructor(protected config: z.infer<typeof OpenAIConfigSchema>) { |
| 29 | this.apiBase = config.apiBase ?? this.apiBase; |
| 30 | this.openai = new OpenAI({ |
| 31 | apiKey: config.apiKey, |
| 32 | baseURL: this.apiBase, |
| 33 | fetch: customFetch(config.requestOptions), |
| 34 | }); |
| 35 | } |
| 36 | |
| 37 | modifyChatBody<T extends ChatCompletionCreateParams>(body: T): T { |
| 38 | // o-series models - only apply for official OpenAI API |
| 39 | const isOfficialOpenAIAPI = this.apiBase === "https://api.openai.com/v1/"; |
| 40 | if (isOfficialOpenAIAPI) { |
| 41 | if (body.model.startsWith("o")) { |
| 42 | // a) use max_completion_tokens instead of max_tokens |
| 43 | body.max_completion_tokens = body.max_tokens; |
| 44 | body.max_tokens = undefined; |
| 45 | |
| 46 | // b) use "developer" message role rather than "system" |
| 47 | body.messages = body.messages.map((message) => { |
| 48 | if (message.role === "system") { |
| 49 | return { ...message, role: "developer" } as any; |
| 50 | } |
| 51 | return message; |
| 52 | }); |
| 53 | } |
| 54 | if (body.tools?.length && !body.model.startsWith("o3")) { |
| 55 | body.parallel_tool_calls = false; |
| 56 | } |
| 57 | } |
| 58 | return body; |
| 59 | } |
| 60 | |
| 61 | async chatCompletionNonStream( |
| 62 | body: ChatCompletionCreateParamsNonStreaming, |
| 63 | signal: AbortSignal, |
| 64 | ): Promise<ChatCompletion> { |
| 65 | const response = await this.openai.chat.completions.create( |
| 66 | this.modifyChatBody(body), |
| 67 | { |
| 68 | signal, |
| 69 | }, |
| 70 | ); |
| 71 | return response; |
| 72 | } |
| 73 | async *chatCompletionStream( |
| 74 | body: ChatCompletionCreateParamsStreaming, |
| 75 | signal: AbortSignal, |
| 76 | ): AsyncGenerator<ChatCompletionChunk, any, unknown> { |
| 77 | const response = await this.openai.chat.completions.create( |
| 78 | this.modifyChatBody(body), |
| 79 | { |
| 80 | signal, |
| 81 | }, |
| 82 | ); |
| 83 | for await (const result of response) { |
| 84 | yield result; |
| 85 | } |
| 86 | } |
| 87 | async completionNonStream( |
| 88 | body: CompletionCreateParamsNonStreaming, |
| 89 | signal: AbortSignal, |
| 90 | ): Promise<Completion> { |
| 91 | const response = await this.openai.completions.create(body, { signal }); |
| 92 | return response; |
| 93 | } |
| 94 | async *completionStream( |
| 95 | body: CompletionCreateParamsStreaming, |
| 96 | signal: AbortSignal, |
| 97 | ): AsyncGenerator<Completion, any, unknown> { |
| 98 | const response = await this.openai.completions.create(body, { signal }); |
| 99 | for await (const result of response) { |
| 100 | yield result; |
| 101 | } |
| 102 | } |
| 103 | async *fimStream( |
| 104 | body: FimCreateParamsStreaming, |
| 105 | signal: AbortSignal, |
| 106 | ): AsyncGenerator<ChatCompletionChunk, any, unknown> { |
| 107 | const endpoint = new URL("fim/completions", this.apiBase); |
| 108 | const resp = await customFetch(this.config.requestOptions)(endpoint, { |
| 109 | method: "POST", |
| 110 | body: JSON.stringify({ |
| 111 | model: body.model, |
| 112 | prompt: body.prompt, |
| 113 | suffix: body.suffix, |
| 114 | max_tokens: body.max_tokens, |
| 115 | max_completion_tokens: (body as any).max_completion_tokens, |
| 116 | temperature: body.temperature, |
| 117 | top_p: body.top_p, |
| 118 | frequency_penalty: body.frequency_penalty, |
| 119 | presence_penalty: body.presence_penalty, |
| 120 | stop: body.stop, |
| 121 | stream: true, |
| 122 | }), |
| 123 | headers: { |
| 124 | "Content-Type": "application/json", |
| 125 | Accept: "application/json", |
| 126 | "x-api-key": this.config.apiKey ?? "", |
| 127 | Authorization: `Bearer ${this.config.apiKey}`, |
| 128 | }, |
| 129 | signal, |
| 130 | }); |
| 131 | for await (const chunk of streamSse(resp as any)) { |
| 132 | if (chunk.choices && chunk.choices.length > 0) { |
| 133 | yield chunk; |
| 134 | } |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | async embed( |
| 139 | body: OpenAI.Embeddings.EmbeddingCreateParams, |
| 140 | ): Promise<OpenAI.Embeddings.CreateEmbeddingResponse> { |
| 141 | const response = await this.openai.embeddings.create(body); |
| 142 | return response; |
| 143 | } |
| 144 | |
| 145 | async rerank(body: RerankCreateParams): Promise<CreateRerankResponse> { |
| 146 | const endpoint = new URL("rerank", this.apiBase); |
| 147 | const response = await customFetch(this.config.requestOptions)(endpoint, { |
| 148 | method: "POST", |
| 149 | body: JSON.stringify(body), |
| 150 | headers: { |
| 151 | "Content-Type": "application/json", |
| 152 | Accept: "application/json", |
| 153 | "x-api-key": this.config.apiKey ?? "", |
| 154 | Authorization: `Bearer ${this.config.apiKey}`, |
| 155 | }, |
| 156 | }); |
| 157 | const data = await response.json(); |
| 158 | return data as any; |
| 159 | } |
| 160 | |
| 161 | async list(): Promise<Model[]> { |
| 162 | return (await this.openai.models.list()).data; |
| 163 | } |
| 164 | } |