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