| 20 | } from "./base.js"; |
| 21 | |
| 22 | export 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({ |
nothing calls this directly
no outgoing calls
no test coverage detected