Elffuss BraidHub

kikocis/continue public

71fd2e7d4456 · 11.3 KiBRawPermalink
1import {
2 ChatMessage,
3 Chunk,
4 CompletionOptions,
5 LLMOptions,
6} from "../../index.js";
7import {
8 fromChatCompletionChunk,
9} from "../openaiTypeConverters.js";
10import { renderChatMessage } from "../../util/messageContent.js";
11import { BaseLLM } from "../index.js";
12import { streamResponse, streamSse } from "../stream.js";
13
14let watsonxToken = {
15 expiration: 0,
16 token: "",
17};
18
19class WatsonX extends BaseLLM {
20 static defaultOptions: Partial<LLMOptions> | undefined = {
21 maxEmbeddingBatchSize: 1000,
22 };
23
24 constructor(options: LLMOptions) {
25 super(options);
26 }
27
28 async getBearerToken(): Promise<{ token: string; expiration: number }> {
29 if (this.apiBase?.includes("cloud.ibm.com")) {
30 // watsonx SaaS
31 const wxToken = await (
32 await this.fetch(
33 `https://iam.cloud.ibm.com/identity/token?apikey=${this.apiKey}&grant_type=urn:ibm:params:oauth:grant-type:apikey`,
34 {
35 method: "POST",
36 headers: {
37 "Content-Type": "application/x-www-form-urlencoded",
38 Accept: "application/json",
39 },
40 },
41 )
42 ).json();
43 return {
44 token: wxToken["access_token"],
45 expiration: wxToken["expiration"],
46 };
47 } else {
48 // watsonx Software
49 if (!this.apiKey?.includes(":")) {
50 // Using ZenApiKey auth
51 return {
52 token: this.apiKey ?? "",
53 expiration: -1,
54 };
55 } else {
56 // Using username/password auth
57 const userPass = this.apiKey?.split(":");
58 const wxToken = await (
59 await this.fetch(`${this.apiBase}/icp4d-api/v1/authorize`, {
60 method: "POST",
61 headers: {
62 "Content-Type": "application/json",
63 Accept: "application/json",
64 },
65 body: JSON.stringify({
66 username: userPass[0],
67 password: userPass[1],
68 }),
69 })
70 ).json();
71 const wxTokenExpiry = await (
72 await this.fetch(`${this.apiBase}/usermgmt/v1/user/tokenExpiry`, {
73 method: "GET",
74 headers: {
75 Accept: "application/json",
76 Authorization: `Bearer ${wxToken["token"]}`,
77 },
78 })
79 ).json();
80 return {
81 token: wxToken["token"],
82 expiration: wxTokenExpiry["exp"],
83 };
84 }
85 }
86 }
87
88 _getEndpoint(endpoint: string): string {
89 return `${this.apiBase}/ml/v1/${this.deploymentId ? `deployments/${this.deploymentId}/` : ""}text/${endpoint}_stream?version=${this.apiVersion}`
90 }
91
92 static providerName = "watsonx";
93
94 protected _convertMessage(message: ChatMessage) {
95 if (typeof message.content === "string") {
96 return message;
97 }
98
99 if (message.role === "tool") {
100 return null;
101 }
102
103 const parts = message.content.map((part) => {
104 if (part.type === "imageUrl") {
105 return {
106 type: "image_url",
107 image_url: { ...part.imageUrl, detail: "low" },
108 };
109 }
110 return {
111 type: "text",
112 text: part.text,
113 };
114 });
115 return {
116 ...message,
117 content: parts,
118 };
119 }
120
121 protected _convertArgs(options: any, messages: ChatMessage[]) {
122 const finalOptions = {
123 messages: messages.map(this._convertMessage).filter(Boolean),
124 model: options.model,
125 max_tokens: options.maxTokens,
126 temperature: options.temperature,
127 top_p: options.topP,
128 frequency_penalty: options.frequencyPenalty,
129 presence_penalty: options.presencePenalty,
130 };
131 return finalOptions;
132 }
133
134 protected _getHeaders() {
135 return {
136 "Content-Type": "application/json",
137 Authorization: `${
138 watsonxToken.expiration === -1 ? "ZenApiKey" : "Bearer"
139 } ${watsonxToken.token}`,
140 };
141 }
142
143 protected async updateWatsonxToken() {
144 var now = new Date().getTime() / 1000;
145 if (
146 watsonxToken === undefined ||
147 now > watsonxToken.expiration ||
148 watsonxToken.token === undefined
149 ) {
150 watsonxToken = await this.getBearerToken();
151 } else {
152 console.log(
153 `Reusing token (expires in ${
154 (watsonxToken.expiration - now) / 60
155 } mins)`,
156 );
157 }
158 if (watsonxToken.token === undefined) {
159 throw new Error("Something went wrong. Check your credentials, please.");
160 }
161 }
162
163 protected async _complete(
164 prompt: string,
165 signal: AbortSignal,
166 options: CompletionOptions,
167 ): Promise<string> {
168 let completion = "";
169 for await (const chunk of this._streamChat(
170 [{ role: "user", content: prompt }],
171 signal,
172 options,
173 )) {
174 completion += chunk.content;
175 }
176
177 return completion;
178 }
179
180 protected async *_streamComplete(
181 prompt: string,
182 signal: AbortSignal,
183 options: CompletionOptions,
184 ): AsyncGenerator<string> {
185
186 await this.updateWatsonxToken();
187
188 const stopSequences = options.stop?.slice(0, 6) ?? [];
189 const url = this._getEndpoint("generation");
190 const headers = this._getHeaders();
191
192 const parameters: any = {
193 decoding_method: "greedy",
194 max_new_tokens: options.maxTokens ?? 1024,
195 min_new_tokens: 1,
196 stop_sequences: stopSequences,
197 include_stop_sequence: false,
198 truncate_input_tokens: this.contextLength - (options.maxTokens ?? 1024),
199 repetition_penalty: options.frequencyPenalty || 1,
200 };
201 if (!!options.temperature) {
202 parameters.decoding_method = "sample";
203 parameters.temperature = options.temperature;
204 parameters.top_p = options.topP || 1.0;
205 parameters.top_k = options.topK || 100;
206 }
207
208 const payload: any = {
209 input: prompt,
210 parameters: parameters,
211 };
212 if (!this.deploymentId) {
213 payload.model_id = options.model;
214 payload.project_id = this.projectId;
215 }
216
217 var response = await this.fetch(url, {
218 method: "POST",
219 headers: headers,
220 body: JSON.stringify(payload),
221 signal,
222 });
223
224 if (!response.ok || response.body === null) {
225 throw new Error(
226 "Something went wrong. No response received, check your connection",
227 );
228 } else {
229 for await (const value of streamResponse(response)) {
230 const lines = value.split("\n");
231 let generatedChunk = "";
232 let generatedTextIndex = undefined;
233 lines.forEach((el: string) => {
234 // console.log(`${el}`);
235 if (el.startsWith("id:")) {
236 generatedTextIndex = parseInt(el.replace(/^id:\s+/, ""));
237 if (isNaN(generatedTextIndex)) {
238 console.error(`Unable to parse stream chunk ID: ${el}`);
239 }
240 } else if (el.startsWith("data:")) {
241 const dataStr = el.replace(/^data:\s+/, "");
242 try {
243 const data = JSON.parse(dataStr);
244 data.results.forEach((result: any) => {
245 generatedChunk += result.generated_text || "";
246 });
247 } catch (e) {
248 // parsing error is expected with streaming response
249 // console.error(`Error parsing JSON string: ${dataStr}`, e);
250 }
251 }
252 });
253 yield generatedChunk
254 }
255 }
256 }
257
258 protected async *_streamChat(
259 messages: ChatMessage[],
260 signal: AbortSignal,
261 options: CompletionOptions,
262 ): AsyncGenerator<ChatMessage> {
263 await this.updateWatsonxToken();
264
265 const stopSequences = options.stop?.slice(0, 6) ?? [];
266 const url = this._getEndpoint("chat");
267 const headers = this._getHeaders();
268
269 const payload: any = {
270 messages: messages,
271 max_tokens: options.maxTokens ?? 1024,
272 stop: stopSequences,
273 frequency_penalty: options.frequencyPenalty || 1,
274 presence_penalty: options.presencePenalty || 1,
275 };
276
277 if (!this.deploymentId) {
278 payload.model_id = options.model;
279 payload.project_id = this.projectId;
280 }
281
282 if (!!options.temperature) {
283 payload.temperature = options.temperature;
284 }
285 if (!!options.topP) {
286 payload.top_p = options.topP;
287 }
288 if (!!options.tools) {
289 payload.tools = options.tools;
290 if (options.toolChoice) {
291 payload.tool_choice = options.toolChoice;
292 } else {
293 payload.tool_choice_option = "auto";
294 }
295 }
296
297 var response = await this.fetch(url, {
298 method: "POST",
299 headers: headers,
300 body: JSON.stringify(payload),
301 signal,
302 });
303
304 if (!response.ok || response.body === null) {
305 throw new Error(
306 "Something went wrong. No response received, check your connection",
307 );
308 } else {
309 for await (const value of streamSse(response)) {
310 const chunk = fromChatCompletionChunk(value);
311 if (chunk) {
312 yield chunk;
313 }
314 }
315 }
316 }
317
318 protected async _embed(chunks: string[]): Promise<number[][]> {
319 await this.updateWatsonxToken();
320
321 const payload: any = {
322 inputs: chunks,
323 parameters: {
324 truncate_input_tokens: 500,
325 return_options: { input_text: false },
326 },
327 model_id: this.model,
328 project_id: this.projectId,
329 };
330 const headers = {
331 "Content-Type": "application/json",
332 Authorization: `${
333 watsonxToken.expiration === -1 ? "ZenApiKey" : "Bearer"
334 } ${watsonxToken.token}`,
335 };
336 const resp = await this.fetch(
337 new URL(
338 `${this.apiBase}/ml/v1/text/embeddings?version=${this.apiVersion}`,
339 ),
340 {
341 method: "POST",
342 body: JSON.stringify(payload),
343 headers: headers,
344 },
345 );
346
347 if (!resp.ok) {
348 throw new Error(`Failed to embed chunk: ${await resp.text()}`);
349 }
350 const data = await resp.json();
351 const embeddings = data.results;
352
353 if (!embeddings || embeddings.length === 0) {
354 throw new Error("Watsonx generated empty embedding");
355 }
356 return embeddings.map((e: any) => e.embedding);
357 }
358
359 async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
360 if (!query || !chunks.length) {
361 throw new Error("Query and chunks must not be empty");
362 }
363 try {
364 await this.updateWatsonxToken();
365
366 const headers = {
367 "Content-Type": "application/json",
368 Authorization: `${
369 watsonxToken.expiration === -1 ? "ZenApiKey" : "Bearer"
370 } ${watsonxToken.token}`,
371 };
372
373 const payload: any = {
374 inputs: chunks.map((chunk) => ({ text: chunk.content })),
375 query: query,
376 parameters: {
377 truncate_input_tokens: 500,
378 return_options: {
379 top_n: chunks.length,
380 },
381 },
382 model_id: this.model,
383 project_id: this.projectId,
384 };
385
386 const resp = await this.fetch(
387 new URL(`${this.apiBase}/ml/v1/text/rerank?version=${this.apiVersion}`),
388 {
389 method: "POST",
390 headers: headers,
391 body: JSON.stringify(payload),
392 },
393 );
394
395 if (!resp.ok) {
396 throw new Error(`Failed to rerank chunks: ${await resp.text()}`);
397 }
398 const data = await resp.json();
399 const ranking = data.results;
400
401 if (!ranking) {
402 throw new Error("Empty response received from Watsonx");
403 }
404
405 // Sort results by index to maintain original order
406 return ranking
407 .sort((a: any, b: any) => a.index - b.index)
408 .map((result: any) => result.score);
409 } catch (error) {
410 console.error("Error in WatsonxReranker.rerank:", error);
411 throw error;
412 }
413 }
414}
415
416export default WatsonX;