Elffuss BraidHub

kikocis/continue public

cfbd8cf979f7 · 11.9 KiBRawPermalink
1import {
2 ChatCompletionCreateParams,
3 ChatCompletionMessageParam,
4} from "openai/resources/index";
5
6import {
7 ChatMessage,
8 CompletionOptions,
9 LLMOptions,
10 Tool,
11} from "../../index.js";
12import { renderChatMessage } from "../../util/messageContent.js";
13import { BaseLLM } from "../index.js";
14import {
15 fromChatCompletionChunk,
16 LlmApiRequestType,
17 toChatBody,
18} from "../openaiTypeConverters.js";
19import { streamSse } from "../stream.js";
20
21const 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
34function isChatOnlyModel(model: string): boolean {
35 // gpt and o-series models
36 return model.startsWith("gpt") || model.startsWith("o");
37}
38
39const formatMessageForO1 = (messages: ChatCompletionMessageParam[]) => {
40 return messages?.map((message: any) => {
41 if (message?.role === "system") {
42 return {
43 ...message,
44 role: "user",
45 };
46 }
47
48 return message;
49 });
50};
51
52class 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 private isO3orO1Model(model?: string): boolean {
81 return !!model && (model.startsWith("o1") || model.startsWith("o3"));
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.isO3orO1Model(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 = formatMessageForO1(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 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.isO3orO1Model(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 = formatMessageForO1(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 const data = await response.json();
356 yield data.choices[0].message;
357 return;
358 }
359
360 for await (const value of streamSse(response)) {
361 const chunk = fromChatCompletionChunk(value);
362 if (chunk) {
363 yield chunk;
364 }
365 }
366 }
367
368 protected async *_streamFim(
369 prefix: string,
370 suffix: string,
371 signal: AbortSignal,
372 options: CompletionOptions,
373 ): AsyncGenerator<string> {
374 const endpoint = new URL("fim/completions", this.apiBase);
375 const resp = await this.fetch(endpoint, {
376 method: "POST",
377 body: JSON.stringify({
378 model: options.model,
379 prompt: prefix,
380 suffix,
381 max_tokens: options.maxTokens,
382 temperature: options.temperature,
383 top_p: options.topP,
384 frequency_penalty: options.frequencyPenalty,
385 presence_penalty: options.presencePenalty,
386 stop: options.stop,
387 stream: true,
388 ...this.extraBodyProperties(),
389 }),
390 headers: {
391 "Content-Type": "application/json",
392 Accept: "application/json",
393 "x-api-key": this.apiKey ?? "",
394 Authorization: `Bearer ${this.apiKey}`,
395 },
396 signal,
397 });
398 for await (const chunk of streamSse(resp)) {
399 yield chunk.choices[0].delta.content;
400 }
401 }
402
403 async listModels(): Promise<string[]> {
404 const response = await this.fetch(this._getEndpoint("models"), {
405 method: "GET",
406 headers: this._getHeaders(),
407 });
408
409 const data = await response.json();
410 return data.data.map((m: any) => m.id);
411 }
412
413 private _getEmbedEndpoint() {
414 if (!this.apiBase) {
415 throw new Error(
416 "No API base URL provided. Please set the 'apiBase' option in config.json",
417 );
418 }
419
420 if (this.apiType === "azure") {
421 return new URL(
422 `openai/deployments/${this.deployment}/embeddings?api-version=${this.apiVersion}`,
423 this.apiBase,
424 );
425 }
426 return new URL("embeddings", this.apiBase);
427 }
428
429 protected async _embed(chunks: string[]): Promise<number[][]> {
430 const resp = await this.fetch(this._getEmbedEndpoint(), {
431 method: "POST",
432 body: JSON.stringify({
433 input: chunks,
434 model: this.model,
435 ...this.extraBodyProperties(),
436 }),
437 headers: {
438 Authorization: `Bearer ${this.apiKey}`,
439 "Content-Type": "application/json",
440 "api-key": this.apiKey ?? "", // For Azure
441 },
442 });
443
444 if (!resp.ok) {
445 throw new Error(await resp.text());
446 }
447
448 const data = (await resp.json()) as any;
449 return data.data.map((result: { embedding: number[] }) => result.embedding);
450 }
451}
452
453export default OpenAI;