Elffuss BraidHub

kikocis/continue public

main · 10.2 KiBRawPermalink
1import { streamSse } from "@continuedev/fetch";
2import { OpenAI } from "openai/index";
3import {
4 ChatCompletion,
5 ChatCompletionChunk,
6 ChatCompletionCreateParamsNonStreaming,
7 ChatCompletionCreateParamsStreaming,
8 Completion,
9 CompletionCreateParamsNonStreaming,
10 CompletionCreateParamsStreaming,
11} from "openai/resources/index";
12import { ChatCompletionCreateParams } from "openai/resources/index.js";
13import { WatsonXConfig } from "../types.js";
14import { chatCompletion, customFetch } from "../util.js";
15import {
16 BaseLlmApi,
17 CreateRerankResponse,
18 FimCreateParamsStreaming,
19 RerankCreateParams,
20} from "./base.js";
21
22export class WatsonXApi implements BaseLlmApi {
23 apiBase: string;
24 apiVersion: string = "2023-05-29";
25 projectId?: string;
26 deploymentId?: string;
27
28 constructor(protected config: WatsonXConfig) {
29 this.apiBase = config.apiBase ?? "https://us-south.ml.cloud.ibm.com";
30 if (!this.apiBase.endsWith("/")) {
31 this.apiBase += "/";
32 }
33 this.apiVersion = config.env.apiVersion ?? this.apiVersion;
34 this.projectId = config.env.projectId;
35 this.deploymentId = config.env.deploymentId;
36 }
37
38 async getBearerToken(): Promise<{ token: string; expiration: number }> {
39 if (this.apiBase?.includes("cloud.ibm.com")) {
40 // watsonx SaaS
41 const wxToken = (await (
42 await customFetch(this.config.requestOptions)(
43 `https://iam.cloud.ibm.com/identity/token?apikey=${this.config.apiKey}&grant_type=urn:ibm:params:oauth:grant-type:apikey`,
44 {
45 method: "POST",
46 headers: {
47 "Content-Type": "application/x-www-form-urlencoded",
48 Accept: "application/json",
49 },
50 },
51 )
52 ).json()) as any;
53 return {
54 token: wxToken["access_token"],
55 expiration: wxToken["expiration"],
56 };
57 } else {
58 // watsonx Software
59 // if (this.config.env.bearerTokenRequired) {
60 // In certain WatsonX environments, ZenApiKey authentication is disabled,
61 // and it's necessary to call this endpoint with username+api_key to get a bearer token.
62 // See the docs: https://www.ibm.com/docs/en/watsonx/w-and-w/2.1.0?topic=keys-generating-bearer-token
63 // Ask @sestinj why the rest is commented out.
64 const base64Decoded = Buffer.from(
65 this.config.apiKey ?? "",
66 "base64",
67 ).toString();
68 const [username, api_key] = base64Decoded.split(":");
69
70 const wxToken = (await (
71 await customFetch(this.config.requestOptions)(
72 new URL("icp4d-api/v1/authorize", this.apiBase),
73 {
74 method: "POST",
75 headers: {
76 "Content-Type": "application/json",
77 Accept: "application/json",
78 },
79 body: JSON.stringify({
80 username: username?.trim(),
81 api_key: api_key?.trim(),
82 }),
83 },
84 )
85 ).json()) as any;
86
87 return {
88 token: wxToken["access_token"] ?? wxToken["token"],
89 expiration: 0,
90 };
91 // } else if (!this.config.apiKey?.includes(":")) {
92 // // Using ZenApiKey auth
93 // return {
94 // token: this.config.apiKey ?? "",
95 // expiration: -1,
96 // };
97 // } else {
98 // // Using username/password auth
99 // const userPass = this.config.apiKey?.split(":");
100 // const wxToken = (await (
101 // await customFetch(this.config.requestOptions)(
102 // `${this.apiBase}/icp4d-api/v1/authorize`,
103 // {
104 // method: "POST",
105 // headers: {
106 // "Content-Type": "application/json",
107 // Accept: "application/json",
108 // },
109 // body: JSON.stringify({
110 // username: userPass[0],
111 // password: userPass[1],
112 // }),
113 // },
114 // )
115 // ).json()) as any;
116 // const wxTokenExpiry = (await (
117 // await customFetch(this.config.requestOptions)(
118 // `${this.apiBase}/usermgmt/v1/user/tokenExpiry`,
119 // {
120 // method: "GET",
121 // headers: {
122 // Accept: "application/json",
123 // Authorization: `Bearer ${wxToken["token"]}`,
124 // },
125 // },
126 // )
127 // ).json()) as any;
128 // return {
129 // token: wxToken["token"],
130 // expiration: wxTokenExpiry["exp"],
131 // };
132 // }
133 }
134 }
135
136 private getEndpoint(endpoint: string): string {
137 return `${this.apiBase}ml/v1/${this.deploymentId ? `deployments/${this.deploymentId}/` : ""}text/${endpoint}_stream?version=${this.apiVersion}`;
138 }
139
140 private _convertBody(oaiBody: ChatCompletionCreateParams) {
141 const stopSequences = oaiBody.stop
142 ? Array.isArray(oaiBody.stop)
143 ? oaiBody.stop.filter((s) => s.trim() !== "")
144 : [oaiBody.stop]
145 : undefined;
146
147 const payload: any = {
148 messages: oaiBody.messages,
149 max_tokens: oaiBody.max_tokens ?? 1024,
150 stop: stopSequences,
151 frequency_penalty: oaiBody.frequency_penalty,
152 presence_penalty: oaiBody.presence_penalty,
153 };
154
155 if (!this.deploymentId) {
156 payload.model_id = oaiBody.model;
157 payload.project_id = this.projectId;
158 }
159
160 if (oaiBody.temperature !== undefined) {
161 payload.temperature = oaiBody.temperature;
162 }
163
164 if (oaiBody.top_p !== undefined) {
165 payload.top_p = oaiBody.top_p;
166 }
167
168 if (oaiBody.tools) {
169 payload.tools = oaiBody.tools;
170 if (oaiBody.tool_choice) {
171 payload.tool_choice = oaiBody.tool_choice;
172 } else {
173 payload.tool_choice_option = "auto";
174 }
175 }
176
177 return payload;
178 }
179
180 private async getHeaders(): Promise<Record<string, string>> {
181 const bearer = await this.getBearerToken();
182 // const isZenApiKey = bearer.expiration === -1;
183
184 return {
185 "Content-Type": "application/json",
186 // Authorization: `${isZenApiKey ? "ZenApiKey" : "Bearer"} ${bearer.token}`,
187 Authorization: `Bearer ${bearer.token}`,
188 };
189 }
190
191 async chatCompletionNonStream(
192 body: ChatCompletionCreateParamsNonStreaming,
193 signal: AbortSignal,
194 ): Promise<ChatCompletion> {
195 const generator = this.chatCompletionStream(
196 {
197 ...body,
198 stream: true,
199 },
200 signal,
201 );
202
203 let content = "";
204 for await (const chunk of generator) {
205 content += chunk.choices[0].delta.content ?? "";
206 }
207 return chatCompletion({
208 content,
209 model: body.model,
210 });
211 }
212
213 async *chatCompletionStream(
214 body: ChatCompletionCreateParamsStreaming,
215 signal: AbortSignal,
216 ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
217 const url = this.getEndpoint("chat");
218 const headers = await this.getHeaders();
219 const stringifiedBody = JSON.stringify({
220 time_limit: 8000,
221 ...this._convertBody(body),
222 stream: true,
223 });
224 const response = await customFetch(this.config.requestOptions)(url, {
225 method: "POST",
226 headers,
227 body: stringifiedBody,
228 signal,
229 });
230
231 if (!response.ok || !response.body) {
232 throw new Error(
233 `Failed to stream chat completion: ${await response.text()}`,
234 );
235 }
236
237 for await (const value of streamSse(response as any)) {
238 if (!value.choices?.[0]) {
239 continue;
240 }
241 yield value;
242 }
243 }
244
245 async completionNonStream(
246 body: CompletionCreateParamsNonStreaming,
247 signal: AbortSignal,
248 ): Promise<Completion> {
249 throw new Error("Method not implemented.");
250 }
251
252 async *completionStream(
253 body: CompletionCreateParamsStreaming,
254 signal: AbortSignal,
255 ): AsyncGenerator<Completion, any, unknown> {
256 const params = {
257 decoding_method: body.temperature ? "sample" : "greedy",
258 max_new_tokens: body.max_tokens ?? 1024,
259 min_new_tokens: 1,
260 stop_sequences: body.stop
261 ? Array.isArray(body.stop)
262 ? body.stop
263 : [body.stop]
264 : [],
265 include_stop_sequence: false,
266 repetition_penalty: body.frequency_penalty || 1,
267 temperature: body.temperature,
268 top_p: body.top_p,
269 top_k: 100,
270 };
271
272 const payload: any = {
273 input: body.prompt,
274 parameters: params,
275 };
276
277 if (!this.deploymentId) {
278 payload.model_id = body.model;
279 payload.project_id = this.projectId;
280 }
281
282 const url = this.getEndpoint("generation");
283 const response = await customFetch(this.config.requestOptions)(url, {
284 method: "POST",
285 headers: await this.getHeaders(),
286 body: JSON.stringify(payload),
287 signal,
288 });
289
290 if (!response.ok || !response.body) {
291 throw new Error(`Failed to stream completion: ${await response.text()}`);
292 }
293
294 let generatedText = "";
295 for await (const value of streamSse(response as any)) {
296 const lines = value.toString().split("\n");
297 let generatedChunk = "";
298
299 lines.forEach((line: string) => {
300 if (line.startsWith("data:")) {
301 const dataStr = line.replace(/^data:\s+/, "");
302 try {
303 const data = JSON.parse(dataStr);
304 data.results.forEach((result: any) => {
305 generatedChunk += result.generated_text || "";
306 });
307 } catch (e) {
308 // parsing error is expected with streaming response
309 }
310 }
311 });
312
313 if (generatedChunk) {
314 generatedText += generatedChunk;
315 yield {
316 id: `watsonx-${Date.now()}`,
317 object: "text_completion",
318 created: Date.now(),
319 model: body.model,
320 choices: [
321 {
322 text: generatedChunk,
323 index: 0,
324 logprobs: null,
325 finish_reason: "stop",
326 },
327 ],
328 };
329 }
330 }
331 }
332
333 async *fimStream(
334 body: FimCreateParamsStreaming,
335 signal: AbortSignal,
336 ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
337 throw new Error("Method not implemented.");
338 }
339
340 async embed(
341 body: OpenAI.Embeddings.EmbeddingCreateParams,
342 ): Promise<OpenAI.Embeddings.CreateEmbeddingResponse> {
343 throw new Error("Method not implemented.");
344 }
345
346 async rerank(body: RerankCreateParams): Promise<CreateRerankResponse> {
347 throw new Error("Method not implemented.");
348 }
349
350 async list(): Promise<OpenAI.Models.Model[]> {
351 throw new Error("Method not implemented.");
352 }
353}