Elffuss BraidHub

kikocis/continue public

main · 5.8 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 // Add stream_options to include usage in streaming responses
39 if (body.stream) {
40 (body as any).stream_options = { include_usage: true };
41 }
42
43 // o-series models - only apply for official OpenAI API
44 const isOfficialOpenAIAPI = this.apiBase === "https://api.openai.com/v1/";
45 if (isOfficialOpenAIAPI) {
46 if (body.model.startsWith("o") || body.model.includes("gpt-5")) {
47 // a) use max_completion_tokens instead of max_tokens
48 body.max_completion_tokens = body.max_tokens;
49 body.max_tokens = undefined;
50
51 // b) use "developer" message role rather than "system"
52 body.messages = body.messages.map((message) => {
53 if (message.role === "system") {
54 return { ...message, role: "developer" } as any;
55 }
56 return message;
57 });
58 }
59 if (body.tools?.length && !body.model.startsWith("o3")) {
60 body.parallel_tool_calls = false;
61 }
62 }
63 return body;
64 }
65
66 modifyCompletionBody<
67 T extends
68 | CompletionCreateParamsNonStreaming
69 | CompletionCreateParamsStreaming,
70 >(body: T): T {
71 return body;
72 }
73
74 modifyEmbedBody<T extends OpenAI.Embeddings.EmbeddingCreateParams>(
75 body: T,
76 ): T {
77 return body;
78 }
79
80 modifyFimBody<T extends FimCreateParamsStreaming>(body: T): T {
81 return body;
82 }
83
84 modifyRerankBody<T extends RerankCreateParams>(body: T): T {
85 return body;
86 }
87
88 protected getHeaders(): Record<string, string> {
89 return {
90 "Content-Type": "application/json",
91 Accept: "application/json",
92 "x-api-key": this.config.apiKey ?? "",
93 Authorization: `Bearer ${this.config.apiKey}`,
94 };
95 }
96
97 async chatCompletionNonStream(
98 body: ChatCompletionCreateParamsNonStreaming,
99 signal: AbortSignal,
100 ): Promise<ChatCompletion> {
101 const response = await this.openai.chat.completions.create(
102 this.modifyChatBody(body),
103 {
104 signal,
105 },
106 );
107 return response;
108 }
109
110 async *chatCompletionStream(
111 body: ChatCompletionCreateParamsStreaming,
112 signal: AbortSignal,
113 ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
114 const response = await this.openai.chat.completions.create(
115 this.modifyChatBody(body),
116 {
117 signal,
118 },
119 );
120 for await (const result of response) {
121 yield result;
122 }
123 }
124 async completionNonStream(
125 body: CompletionCreateParamsNonStreaming,
126 signal: AbortSignal,
127 ): Promise<Completion> {
128 const response = await this.openai.completions.create(
129 this.modifyCompletionBody(body),
130 { signal },
131 );
132 return response;
133 }
134 async *completionStream(
135 body: CompletionCreateParamsStreaming,
136 signal: AbortSignal,
137 ): AsyncGenerator<Completion, any, unknown> {
138 const response = await this.openai.completions.create(
139 this.modifyCompletionBody(body),
140 { signal },
141 );
142 for await (const result of response) {
143 yield result;
144 }
145 }
146 async *fimStream(
147 body: FimCreateParamsStreaming,
148 signal: AbortSignal,
149 ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
150 const endpoint = new URL("fim/completions", this.apiBase);
151 const modifiedBody = this.modifyFimBody(body);
152 const resp = await customFetch(this.config.requestOptions)(endpoint, {
153 method: "POST",
154 body: JSON.stringify({
155 model: modifiedBody.model,
156 prompt: modifiedBody.prompt,
157 suffix: modifiedBody.suffix,
158 max_tokens: modifiedBody.max_tokens,
159 max_completion_tokens: (modifiedBody as any).max_completion_tokens,
160 temperature: modifiedBody.temperature,
161 top_p: modifiedBody.top_p,
162 frequency_penalty: modifiedBody.frequency_penalty,
163 presence_penalty: modifiedBody.presence_penalty,
164 stop: modifiedBody.stop,
165 stream: true,
166 }),
167 headers: this.getHeaders(),
168 signal,
169 });
170 for await (const chunk of streamSse(resp as any)) {
171 if (chunk.choices && chunk.choices.length > 0) {
172 yield chunk;
173 }
174 }
175 }
176
177 async embed(
178 body: OpenAI.Embeddings.EmbeddingCreateParams,
179 ): Promise<OpenAI.Embeddings.CreateEmbeddingResponse> {
180 const response = await this.openai.embeddings.create(
181 this.modifyEmbedBody(body),
182 );
183 return response;
184 }
185
186 async rerank(body: RerankCreateParams): Promise<CreateRerankResponse> {
187 const endpoint = new URL("rerank", this.apiBase);
188 const modifiedBody = this.modifyRerankBody(body);
189 const response = await customFetch(this.config.requestOptions)(endpoint, {
190 method: "POST",
191 body: JSON.stringify(modifiedBody),
192 headers: this.getHeaders(),
193 });
194 const data = await response.json();
195 return data as any;
196 }
197
198 async list(): Promise<Model[]> {
199 return (await this.openai.models.list()).data;
200 }
201}