Elffuss BraidHub

kikocis/continue public

b4db4cbf8943 · 5.7 KiBRawPermalink
1import { streamSse } from "@continuedev/fetch";
2import { OpenAI } from "openai/index";
3import {
4 ChatCompletion,
5 ChatCompletionChunk,
6 ChatCompletionCreateParams,
7 ChatCompletionCreateParamsNonStreaming,
8 ChatCompletionCreateParamsStreaming,
9 Completion,
10 CompletionCreateParamsNonStreaming,
11 CompletionCreateParamsStreaming,
12 Model,
13} from "openai/resources/index";
14import { z } from "zod";
15import { OpenAIConfigSchema } from "../types.js";
16import { customFetch } from "../util.js";
17import {
18 BaseLlmApi,
19 CreateRerankResponse,
20 FimCreateParamsStreaming,
21 RerankCreateParams,
22} from "./base.js";
23
24export 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 // Necessary because `new OpenAI()` will throw an error if there is no API Key
32 apiKey: config.apiKey ?? "",
33 baseURL: this.apiBase,
34 fetch: customFetch(config.requestOptions),
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") || body.model.includes("gpt-5")) {
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 modifyCompletionBody<
62 T extends
63 | CompletionCreateParamsNonStreaming
64 | CompletionCreateParamsStreaming,
65 >(body: T): T {
66 return body;
67 }
68
69 modifyEmbedBody<T extends OpenAI.Embeddings.EmbeddingCreateParams>(
70 body: T,
71 ): T {
72 return body;
73 }
74
75 modifyFimBody<T extends FimCreateParamsStreaming>(body: T): T {
76 return body;
77 }
78
79 modifyRerankBody<T extends RerankCreateParams>(body: T): T {
80 return body;
81 }
82
83 protected getHeaders(): Record<string, string> {
84 return {
85 "Content-Type": "application/json",
86 Accept: "application/json",
87 "x-api-key": this.config.apiKey ?? "",
88 Authorization: `Bearer ${this.config.apiKey}`,
89 };
90 }
91
92 async chatCompletionNonStream(
93 body: ChatCompletionCreateParamsNonStreaming,
94 signal: AbortSignal,
95 ): Promise<ChatCompletion> {
96 const response = await this.openai.chat.completions.create(
97 this.modifyChatBody(body),
98 {
99 signal,
100 },
101 );
102 return response;
103 }
104
105 async *chatCompletionStream(
106 body: ChatCompletionCreateParamsStreaming,
107 signal: AbortSignal,
108 ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
109 const response = await this.openai.chat.completions.create(
110 this.modifyChatBody(body),
111 {
112 signal,
113 },
114 );
115 for await (const result of response) {
116 yield result;
117 }
118 }
119 async completionNonStream(
120 body: CompletionCreateParamsNonStreaming,
121 signal: AbortSignal,
122 ): Promise<Completion> {
123 const response = await this.openai.completions.create(
124 this.modifyCompletionBody(body),
125 { signal },
126 );
127 return response;
128 }
129 async *completionStream(
130 body: CompletionCreateParamsStreaming,
131 signal: AbortSignal,
132 ): AsyncGenerator<Completion, any, unknown> {
133 const response = await this.openai.completions.create(
134 this.modifyCompletionBody(body),
135 { signal },
136 );
137 for await (const result of response) {
138 yield result;
139 }
140 }
141 async *fimStream(
142 body: FimCreateParamsStreaming,
143 signal: AbortSignal,
144 ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
145 const endpoint = new URL("fim/completions", this.apiBase);
146 const modifiedBody = this.modifyFimBody(body);
147 const resp = await customFetch(this.config.requestOptions)(endpoint, {
148 method: "POST",
149 body: JSON.stringify({
150 model: modifiedBody.model,
151 prompt: modifiedBody.prompt,
152 suffix: modifiedBody.suffix,
153 max_tokens: modifiedBody.max_tokens,
154 max_completion_tokens: (modifiedBody as any).max_completion_tokens,
155 temperature: modifiedBody.temperature,
156 top_p: modifiedBody.top_p,
157 frequency_penalty: modifiedBody.frequency_penalty,
158 presence_penalty: modifiedBody.presence_penalty,
159 stop: modifiedBody.stop,
160 stream: true,
161 }),
162 headers: this.getHeaders(),
163 signal,
164 });
165 for await (const chunk of streamSse(resp as any)) {
166 if (chunk.choices && chunk.choices.length > 0) {
167 yield chunk;
168 }
169 }
170 }
171
172 async embed(
173 body: OpenAI.Embeddings.EmbeddingCreateParams,
174 ): Promise<OpenAI.Embeddings.CreateEmbeddingResponse> {
175 const response = await this.openai.embeddings.create(
176 this.modifyEmbedBody(body),
177 );
178 return response;
179 }
180
181 async rerank(body: RerankCreateParams): Promise<CreateRerankResponse> {
182 const endpoint = new URL("rerank", this.apiBase);
183 const modifiedBody = this.modifyRerankBody(body);
184 const response = await customFetch(this.config.requestOptions)(endpoint, {
185 method: "POST",
186 body: JSON.stringify(modifiedBody),
187 headers: this.getHeaders(),
188 });
189 const data = await response.json();
190 return data as any;
191 }
192
193 async list(): Promise<Model[]> {
194 return (await this.openai.models.list()).data;
195 }
196}