| 1 | import { streamResponse, streamSse } from "@continuedev/fetch"; |
| 2 | import { |
| 3 | AssistantChatMessage, |
| 4 | ChatMessage, |
| 5 | Chunk, |
| 6 | CompletionOptions, |
| 7 | LLMOptions, |
| 8 | ToolCallDelta, |
| 9 | ToolResultChatMessage, |
| 10 | } from "../../index.js"; |
| 11 | import { BaseLLM } from "../index.js"; |
| 12 | import { fromChatCompletionChunk } from "../openaiTypeConverters.js"; |
| 13 | |
| 14 | let watsonxToken = { |
| 15 | expiration: 0, |
| 16 | token: "", |
| 17 | }; |
| 18 | |
| 19 | class 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 | let message_ = message as any; |
| 96 | if (message_.role === "tool") { |
| 97 | message_.tool_call_id = (message as ToolResultChatMessage).toolCallId; |
| 98 | delete message_.toolCallId; |
| 99 | } else if (message.role === "assistant" && !!message.toolCalls) { |
| 100 | message_.tool_calls = message.toolCalls.map((t) => ({ |
| 101 | ...t, |
| 102 | type: "function", |
| 103 | })); |
| 104 | delete message_.toolCalls; |
| 105 | delete message_.content; |
| 106 | } else if ( |
| 107 | message_.role === "user" && |
| 108 | typeof message_.content === "string" |
| 109 | ) { |
| 110 | message_.content = [{ type: "text", text: message_.content }]; |
| 111 | } |
| 112 | return message_; |
| 113 | } |
| 114 | |
| 115 | protected _convertArgs(options: any, messages: ChatMessage[]) { |
| 116 | const finalOptions = { |
| 117 | messages: messages.map(this._convertMessage).filter(Boolean), |
| 118 | model: options.model, |
| 119 | max_tokens: options.maxTokens, |
| 120 | temperature: options.temperature, |
| 121 | top_p: options.topP, |
| 122 | frequency_penalty: options.frequencyPenalty, |
| 123 | presence_penalty: options.presencePenalty, |
| 124 | }; |
| 125 | return finalOptions; |
| 126 | } |
| 127 | |
| 128 | protected _getHeaders() { |
| 129 | return { |
| 130 | "Content-Type": "application/json", |
| 131 | Authorization: `${ |
| 132 | watsonxToken.expiration === -1 ? "ZenApiKey" : "Bearer" |
| 133 | } ${watsonxToken.token}`, |
| 134 | }; |
| 135 | } |
| 136 | |
| 137 | protected async updateWatsonxToken() { |
| 138 | var now = new Date().getTime() / 1000; |
| 139 | if ( |
| 140 | watsonxToken === undefined || |
| 141 | now > watsonxToken.expiration || |
| 142 | watsonxToken.token === undefined |
| 143 | ) { |
| 144 | watsonxToken = await this.getBearerToken(); |
| 145 | } else { |
| 146 | console.log( |
| 147 | `Reusing token (expires in ${ |
| 148 | (watsonxToken.expiration - now) / 60 |
| 149 | } mins)`, |
| 150 | ); |
| 151 | } |
| 152 | if (watsonxToken.token === undefined) { |
| 153 | throw new Error("Something went wrong. Check your credentials, please."); |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | protected async _complete( |
| 158 | prompt: string, |
| 159 | signal: AbortSignal, |
| 160 | options: CompletionOptions, |
| 161 | ): Promise<string> { |
| 162 | let completion = ""; |
| 163 | for await (const chunk of this._streamChat( |
| 164 | [{ role: "user", content: prompt }], |
| 165 | signal, |
| 166 | options, |
| 167 | )) { |
| 168 | completion += chunk.content; |
| 169 | } |
| 170 | |
| 171 | return completion; |
| 172 | } |
| 173 | |
| 174 | protected async *_streamComplete( |
| 175 | prompt: string, |
| 176 | signal: AbortSignal, |
| 177 | options: CompletionOptions, |
| 178 | ): AsyncGenerator<string> { |
| 179 | await this.updateWatsonxToken(); |
| 180 | |
| 181 | const stopSequences = options.stop?.slice(0, 6) ?? []; |
| 182 | const url = this._getEndpoint("generation"); |
| 183 | const headers = this._getHeaders(); |
| 184 | |
| 185 | const parameters: any = { |
| 186 | decoding_method: "greedy", |
| 187 | max_new_tokens: options.maxTokens ?? 1024, |
| 188 | min_new_tokens: 1, |
| 189 | stop_sequences: stopSequences, |
| 190 | include_stop_sequence: false, |
| 191 | truncate_input_tokens: this.contextLength - (options.maxTokens ?? 1024), |
| 192 | repetition_penalty: options.frequencyPenalty || 1, |
| 193 | }; |
| 194 | if (!!options.temperature) { |
| 195 | parameters.decoding_method = "sample"; |
| 196 | parameters.temperature = options.temperature; |
| 197 | parameters.top_p = options.topP || 1.0; |
| 198 | parameters.top_k = options.topK || 100; |
| 199 | } |
| 200 | |
| 201 | const payload: any = { |
| 202 | input: prompt, |
| 203 | parameters: parameters, |
| 204 | }; |
| 205 | if (!this.deploymentId) { |
| 206 | payload.model_id = options.model; |
| 207 | payload.project_id = this.projectId; |
| 208 | } |
| 209 | |
| 210 | const response = await this.fetch(url, { |
| 211 | method: "POST", |
| 212 | headers: headers, |
| 213 | body: JSON.stringify(payload), |
| 214 | signal, |
| 215 | }); |
| 216 | |
| 217 | for await (const value of streamResponse(response)) { |
| 218 | const lines = value.split("\n"); |
| 219 | let generatedChunk = ""; |
| 220 | let generatedTextIndex = undefined; |
| 221 | lines.forEach((el: string) => { |
| 222 | // console.log(`${el}`); |
| 223 | if (el.startsWith("id:")) { |
| 224 | generatedTextIndex = parseInt(el.replace(/^id:\s+/, "")); |
| 225 | if (isNaN(generatedTextIndex)) { |
| 226 | console.error(`Unable to parse stream chunk ID: ${el}`); |
| 227 | } |
| 228 | } else if (el.startsWith("data:")) { |
| 229 | const dataStr = el.replace(/^data:\s+/, ""); |
| 230 | try { |
| 231 | const data = JSON.parse(dataStr); |
| 232 | data.results.forEach((result: any) => { |
| 233 | generatedChunk += result.generated_text || ""; |
| 234 | }); |
| 235 | } catch (e) { |
| 236 | // parsing error is expected with streaming response |
| 237 | // console.error(`Error parsing JSON string: ${dataStr}`, e); |
| 238 | } |
| 239 | } |
| 240 | }); |
| 241 | yield generatedChunk; |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | protected async *_streamChat( |
| 246 | messages: ChatMessage[], |
| 247 | signal: AbortSignal, |
| 248 | options: CompletionOptions, |
| 249 | ): AsyncGenerator<ChatMessage> { |
| 250 | await this.updateWatsonxToken(); |
| 251 | |
| 252 | const stopSequences = options.stop?.slice(0, 6) ?? []; |
| 253 | const url = this._getEndpoint("chat"); |
| 254 | const headers = this._getHeaders(); |
| 255 | |
| 256 | const payload: any = { |
| 257 | messages: messages.map(this._convertMessage).filter(Boolean), |
| 258 | max_tokens: options.maxTokens ?? 1024, |
| 259 | stop: stopSequences, |
| 260 | frequency_penalty: options.frequencyPenalty ?? 0, |
| 261 | presence_penalty: options.presencePenalty ?? 0, |
| 262 | }; |
| 263 | |
| 264 | if (!this.deploymentId) { |
| 265 | payload.model_id = options.model; |
| 266 | payload.project_id = this.projectId; |
| 267 | } |
| 268 | |
| 269 | if (!!options.temperature) { |
| 270 | payload.temperature = options.temperature; |
| 271 | } |
| 272 | if (!!options.topP) { |
| 273 | payload.top_p = options.topP; |
| 274 | } |
| 275 | if (!!options.tools) { |
| 276 | payload.tools = options.tools; |
| 277 | if (options.toolChoice) { |
| 278 | payload.tool_choice = options.toolChoice; |
| 279 | } else { |
| 280 | payload.tool_choice_option = "auto"; |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | const response = await this.fetch(url, { |
| 285 | method: "POST", |
| 286 | headers: headers, |
| 287 | body: JSON.stringify(payload), |
| 288 | signal, |
| 289 | }); |
| 290 | |
| 291 | let toolName; |
| 292 | let toolCallId = null; |
| 293 | let accumulatedArgs = ""; |
| 294 | |
| 295 | for await (const value of streamSse(response)) { |
| 296 | const message = fromChatCompletionChunk(value); |
| 297 | if (!!message) { |
| 298 | if ( |
| 299 | (message as AssistantChatMessage)?.toolCalls && |
| 300 | (message as AssistantChatMessage).toolCalls?.length !== 0 |
| 301 | ) { |
| 302 | let chunk = message as AssistantChatMessage; |
| 303 | if (!!chunk.toolCalls?.[0]?.id) { |
| 304 | toolCallId = chunk.toolCalls?.[0]?.id; |
| 305 | } |
| 306 | if (!!chunk.toolCalls?.[0]?.function?.name) { |
| 307 | accumulatedArgs = ""; |
| 308 | toolName = chunk.toolCalls[0].function.name; |
| 309 | continue; |
| 310 | } |
| 311 | if (!!toolName) { |
| 312 | if (value?.choices?.[0]?.finish_reason === "tool_calls") { |
| 313 | // If final assistant message has "tool_calls" as finish_reason |
| 314 | let args: string | undefined; |
| 315 | try { |
| 316 | accumulatedArgs += chunk.toolCalls?.[0]?.function?.arguments; |
| 317 | // Check if accumulated argument chunks are parsable |
| 318 | args = JSON.stringify(JSON.parse(accumulatedArgs)); |
| 319 | } catch (e) { |
| 320 | // Otherwise use arguments from final assistant tool call message |
| 321 | args = chunk.toolCalls?.[0]?.function?.arguments; |
| 322 | } |
| 323 | const toolCall = { |
| 324 | function: { name: toolName, arguments: args }, |
| 325 | id: toolCallId, |
| 326 | }; |
| 327 | chunk.toolCalls = [toolCall as ToolCallDelta]; |
| 328 | } else { |
| 329 | if (!!chunk.toolCalls?.[0]?.function?.arguments) |
| 330 | accumulatedArgs += chunk.toolCalls?.[0]?.function?.arguments; |
| 331 | continue; |
| 332 | } |
| 333 | } |
| 334 | yield chunk; |
| 335 | } else { |
| 336 | yield message; |
| 337 | } |
| 338 | } |
| 339 | } |
| 340 | } |
| 341 | |
| 342 | protected async _embed(chunks: string[]): Promise<number[][]> { |
| 343 | await this.updateWatsonxToken(); |
| 344 | |
| 345 | const payload: any = { |
| 346 | inputs: chunks, |
| 347 | parameters: { |
| 348 | truncate_input_tokens: 500, |
| 349 | return_options: { input_text: false }, |
| 350 | }, |
| 351 | model_id: this.model, |
| 352 | project_id: this.projectId, |
| 353 | }; |
| 354 | const headers = { |
| 355 | "Content-Type": "application/json", |
| 356 | Authorization: `${ |
| 357 | watsonxToken.expiration === -1 ? "ZenApiKey" : "Bearer" |
| 358 | } ${watsonxToken.token}`, |
| 359 | }; |
| 360 | const resp = await this.fetch( |
| 361 | new URL( |
| 362 | `${this.apiBase}/ml/v1/text/embeddings?version=${this.apiVersion}`, |
| 363 | ), |
| 364 | { |
| 365 | method: "POST", |
| 366 | body: JSON.stringify(payload), |
| 367 | headers: headers, |
| 368 | }, |
| 369 | ); |
| 370 | |
| 371 | if (!resp.ok) { |
| 372 | throw new Error(`Failed to embed chunk: ${await resp.text()}`); |
| 373 | } |
| 374 | const data = await resp.json(); |
| 375 | const embeddings = data.results; |
| 376 | |
| 377 | if (!embeddings || embeddings.length === 0) { |
| 378 | throw new Error("Watsonx generated empty embedding"); |
| 379 | } |
| 380 | return embeddings.map((e: any) => e.embedding); |
| 381 | } |
| 382 | |
| 383 | async rerank(query: string, chunks: Chunk[]): Promise<number[]> { |
| 384 | if (!query || !chunks.length) { |
| 385 | throw new Error("Query and chunks must not be empty"); |
| 386 | } |
| 387 | try { |
| 388 | await this.updateWatsonxToken(); |
| 389 | |
| 390 | const headers = { |
| 391 | "Content-Type": "application/json", |
| 392 | Authorization: `${ |
| 393 | watsonxToken.expiration === -1 ? "ZenApiKey" : "Bearer" |
| 394 | } ${watsonxToken.token}`, |
| 395 | }; |
| 396 | |
| 397 | const payload: any = { |
| 398 | inputs: chunks.map((chunk) => ({ text: chunk.content })), |
| 399 | query: query, |
| 400 | parameters: { |
| 401 | truncate_input_tokens: 500, |
| 402 | return_options: { |
| 403 | top_n: chunks.length, |
| 404 | }, |
| 405 | }, |
| 406 | model_id: this.model, |
| 407 | project_id: this.projectId, |
| 408 | }; |
| 409 | |
| 410 | const resp = await this.fetch( |
| 411 | new URL(`${this.apiBase}/ml/v1/text/rerank?version=${this.apiVersion}`), |
| 412 | { |
| 413 | method: "POST", |
| 414 | headers: headers, |
| 415 | body: JSON.stringify(payload), |
| 416 | }, |
| 417 | ); |
| 418 | |
| 419 | if (!resp.ok) { |
| 420 | throw new Error(`Failed to rerank chunks: ${await resp.text()}`); |
| 421 | } |
| 422 | const data = await resp.json(); |
| 423 | const ranking = data.results; |
| 424 | |
| 425 | if (!ranking) { |
| 426 | throw new Error("Empty response received from Watsonx"); |
| 427 | } |
| 428 | |
| 429 | // Sort results by index to maintain original order |
| 430 | return ranking |
| 431 | .sort((a: any, b: any) => a.index - b.index) |
| 432 | .map((result: any) => result.score); |
| 433 | } catch (error) { |
| 434 | console.error("Error in WatsonxReranker.rerank:", error); |
| 435 | throw error; |
| 436 | } |
| 437 | } |
| 438 | } |
| 439 | |
| 440 | export default WatsonX; |