Elffuss BraidHub

kikocis/continue public

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