{"version":3,"file":"ibm.cjs","names":["IamAuthenticator","BearerTokenAuthenticator","CloudPakForDataAuthenticator","WatsonXAI","Gateway","JsonOutputToolsParser","OutputParserException","z"],"sources":["../../src/utils/ibm.ts"],"sourcesContent":["/* oxlint-disable typescript/no-explicit-any */\nimport { WatsonXAI } from \"@ibm-cloud/watsonx-ai\";\nimport {\n  IamAuthenticator,\n  BearerTokenAuthenticator,\n  CloudPakForDataAuthenticator,\n  Authenticator,\n} from \"ibm-cloud-sdk-core\";\nimport {\n  JsonOutputKeyToolsParserParamsInterop,\n  JsonOutputToolsParser,\n} from \"@langchain/core/output_parsers/openai_tools\";\nimport { OutputParserException } from \"@langchain/core/output_parsers\";\nimport { z } from \"zod/v3\";\nimport { ChatGeneration } from \"@langchain/core/outputs\";\nimport { AIMessageChunk } from \"@langchain/core/messages\";\nimport { ToolCall } from \"@langchain/core/messages/tool\";\nimport {\n  InteropZodType,\n  interopSafeParseAsync,\n} from \"@langchain/core/utils/types\";\nimport { Gateway } from \"@ibm-cloud/watsonx-ai/gateway\";\nimport { WatsonxAuth, WatsonxInit } from \"../types/ibm.js\";\n\nconst createAuthenticator = ({\n  watsonxAIApikey,\n  watsonxAIAuthType,\n  watsonxAIBearerToken,\n  watsonxAIUsername,\n  watsonxAIPassword,\n  watsonxAIUrl,\n  disableSSL,\n  serviceUrl,\n}: WatsonxAuth): Authenticator | undefined => {\n  if (watsonxAIAuthType === \"iam\" && watsonxAIApikey) {\n    return new IamAuthenticator({\n      apikey: watsonxAIApikey,\n    });\n  } else if (watsonxAIAuthType === \"bearertoken\" && watsonxAIBearerToken) {\n    return new BearerTokenAuthenticator({\n      bearerToken: watsonxAIBearerToken,\n    });\n  } else if (watsonxAIAuthType === \"cp4d\") {\n    // cp4d auth requires username with either Password of ApiKey but not both.\n    if (watsonxAIUsername && (watsonxAIPassword || watsonxAIApikey)) {\n      const watsonxCPDAuthUrl = watsonxAIUrl ?? serviceUrl;\n      return new CloudPakForDataAuthenticator({\n        username: watsonxAIUsername,\n        password: watsonxAIPassword,\n        url: watsonxCPDAuthUrl.concat(\"/icp4d-api/v1/authorize\"),\n        apikey: watsonxAIApikey,\n        disableSslVerification: disableSSL,\n      });\n    }\n  }\n  return undefined;\n};\n\nexport const authenticateAndSetInstance = ({\n  watsonxAIApikey,\n  watsonxAIAuthType,\n  watsonxAIBearerToken,\n  watsonxAIUsername,\n  watsonxAIPassword,\n  watsonxAIUrl,\n  disableSSL,\n  version,\n  serviceUrl,\n}: WatsonxAuth & Omit<WatsonxInit, \"authenticator\">): WatsonXAI | undefined => {\n  if (watsonxAIAuthType === \"iam\" && watsonxAIApikey) {\n    return WatsonXAI.newInstance({\n      version,\n      serviceUrl,\n      authenticator: new IamAuthenticator({\n        apikey: watsonxAIApikey,\n      }),\n    });\n  } else if (watsonxAIAuthType === \"bearertoken\" && watsonxAIBearerToken) {\n    return WatsonXAI.newInstance({\n      version,\n      serviceUrl,\n      authenticator: new BearerTokenAuthenticator({\n        bearerToken: watsonxAIBearerToken,\n      }),\n    });\n  } else if (watsonxAIAuthType === \"cp4d\") {\n    // cp4d auth requires username with either Password of ApiKey but not both.\n    if (watsonxAIUsername && (watsonxAIPassword || watsonxAIApikey)) {\n      const watsonxCPDAuthUrl = watsonxAIUrl ?? serviceUrl;\n      return WatsonXAI.newInstance({\n        version,\n        serviceUrl,\n        disableSslVerification: disableSSL,\n        authenticator: new CloudPakForDataAuthenticator({\n          username: watsonxAIUsername,\n          password: watsonxAIPassword,\n          url: watsonxCPDAuthUrl.concat(\"/icp4d-api/v1/authorize\"),\n          apikey: watsonxAIApikey,\n          disableSslVerification: disableSSL,\n        }),\n      });\n    }\n  } else\n    return WatsonXAI.newInstance({\n      version,\n      serviceUrl,\n    });\n  return undefined;\n};\n\nexport function authenticateAndSetGatewayInstance({\n  watsonxAIApikey,\n  watsonxAIAuthType,\n  watsonxAIBearerToken,\n  watsonxAIUsername,\n  watsonxAIPassword,\n  watsonxAIUrl,\n  disableSSL,\n  version,\n  serviceUrl,\n}: WatsonxAuth & Omit<WatsonxInit, \"authenticator\">) {\n  const authenticator = createAuthenticator({\n    watsonxAIApikey,\n    watsonxAIAuthType,\n    watsonxAIBearerToken,\n    watsonxAIUsername,\n    watsonxAIPassword,\n    watsonxAIUrl,\n    disableSSL,\n    serviceUrl,\n  });\n\n  return new Gateway({\n    version,\n    serviceUrl,\n    authenticator,\n  });\n}\n\n// Mistral enforces a specific pattern for tool call IDs\n// Thanks to Mistral for implementing this, I was unable to import which is why this is copied 1:1\nconst TOOL_CALL_ID_PATTERN = /^[a-zA-Z0-9]{9}$/;\n\nexport function _isValidMistralToolCallId(toolCallId: string): boolean {\n  return TOOL_CALL_ID_PATTERN.test(toolCallId);\n}\n\nfunction _base62Encode(num: number): string {\n  let numCopy = num;\n  const base62 =\n    \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n  if (numCopy === 0) return base62[0];\n  const arr: string[] = [];\n  const base = base62.length;\n  while (numCopy) {\n    arr.push(base62[numCopy % base]);\n    numCopy = Math.floor(numCopy / base);\n  }\n  return arr.reverse().join(\"\");\n}\n\nfunction _simpleHash(str: string): number {\n  let hash = 0;\n  for (let i = 0; i < str.length; i += 1) {\n    const char = str.charCodeAt(i);\n    hash = (hash << 5) - hash + char;\n    hash &= hash; // Convert to 32-bit integer\n  }\n  return Math.abs(hash);\n}\n\nexport function _convertToolCallIdToMistralCompatible(\n  toolCallId: string\n): string {\n  if (_isValidMistralToolCallId(toolCallId)) {\n    return toolCallId;\n  } else {\n    const hash = _simpleHash(toolCallId);\n    const base62Str = _base62Encode(hash);\n    if (base62Str.length >= 9) {\n      return base62Str.slice(0, 9);\n    } else {\n      return base62Str.padStart(9, \"0\");\n    }\n  }\n}\n\ninterface WatsonxToolsOutputParserParams<\n  T extends Record<string, any>,\n> extends JsonOutputKeyToolsParserParamsInterop<T> {}\n\nexport class WatsonxToolsOutputParser<\n  T extends Record<string, any> = Record<string, any>,\n> extends JsonOutputToolsParser<T> {\n  static lc_name() {\n    return \"WatsonxToolsOutputParser\";\n  }\n\n  lc_namespace = [\"langchain\", \"watsonx\", \"output_parsers\"];\n\n  returnId = false;\n\n  keyName: string;\n\n  returnSingle = false;\n\n  zodSchema?: InteropZodType<T>;\n\n  latestCorrect?: ToolCall;\n\n  constructor(params: WatsonxToolsOutputParserParams<T>) {\n    super(params);\n    this.keyName = params.keyName;\n    this.returnSingle = params.returnSingle ?? this.returnSingle;\n    this.zodSchema = params.zodSchema;\n  }\n\n  protected async _validateResult(result: unknown): Promise<T> {\n    let parsedResult = result;\n    if (typeof result === \"string\") {\n      try {\n        parsedResult = JSON.parse(result);\n      } catch (e: any) {\n        throw new OutputParserException(\n          `Failed to parse. Text: \"${JSON.stringify(\n            result,\n            null,\n            2\n          )}\". Error: ${JSON.stringify(e.message)}`,\n          result\n        );\n      }\n    } else {\n      parsedResult = result;\n    }\n    if (this.zodSchema === undefined) {\n      return parsedResult as T;\n    }\n    const zodParsedResult = await interopSafeParseAsync(\n      this.zodSchema,\n      parsedResult\n    );\n    if (zodParsedResult.success) {\n      return zodParsedResult.data;\n    } else {\n      throw new OutputParserException(\n        `Failed to parse. Text: \"${JSON.stringify(\n          result,\n          null,\n          2\n        )}\". Error: ${JSON.stringify(zodParsedResult.error.issues)}`,\n        JSON.stringify(result, null, 2)\n      );\n    }\n  }\n\n  async parsePartialResult(generations: ChatGeneration[]): Promise<T> {\n    const tools = generations.flatMap((generation) => {\n      const message = generation.message as AIMessageChunk;\n      if (!Array.isArray(message.tool_calls)) {\n        return [];\n      }\n      const tool = message.tool_calls;\n      return tool;\n    });\n\n    if (tools[0] === undefined) {\n      if (this.latestCorrect) {\n        tools.push(this.latestCorrect);\n      } else {\n        const toolCall: ToolCall = { name: \"\", args: {} };\n        tools.push(toolCall);\n      }\n    }\n\n    const [tool] = tools;\n    tool.name = \"\";\n    this.latestCorrect = tool;\n    return tool.args as T;\n  }\n}\n\nexport function jsonSchemaToZod(obj: WatsonXAI.JsonObject | undefined) {\n  if (obj?.properties && obj.type === \"object\") {\n    const shape: Record<string, any> = {};\n\n    Object.keys(obj.properties).forEach((key) => {\n      if (obj.properties) {\n        const prop = obj.properties[key];\n\n        let zodType;\n        if (prop.type === \"string\") {\n          zodType = z.string();\n          if (prop?.pattern) {\n            zodType = zodType.regex(prop.pattern, \"Invalid pattern\");\n          }\n        } else if (\n          prop.type === \"number\" ||\n          prop.type === \"integer\" ||\n          prop.type === \"float\"\n        ) {\n          zodType = z.number();\n          if (typeof prop?.minimum === \"number\") {\n            zodType = zodType.min(prop.minimum, {\n              message: `${key} must be at least ${prop.minimum}`,\n            });\n          }\n          if (prop?.maximum)\n            zodType = zodType.lte(prop.maximum, {\n              message: `${key} must be maximum of ${prop.maximum}`,\n            });\n        } else if (prop.type === \"boolean\") zodType = z.boolean();\n        else if (prop.type === \"array\")\n          zodType = z.array(\n            prop.items ? jsonSchemaToZod(prop.items) : z.string()\n          );\n        else if (prop.type === \"object\") {\n          zodType = jsonSchemaToZod(prop);\n        } else throw new Error(`Unsupported type: ${prop.type}`);\n\n        if (prop.description) {\n          zodType = zodType.describe(prop.description);\n        }\n\n        if (!obj.required?.includes(key)) {\n          zodType = zodType.optional();\n        }\n\n        shape[key] = zodType;\n      }\n    });\n    return z.object(shape);\n  }\n  throw new Error(\"Unsupported root schema type\");\n}\n\nexport const expectOneOf = (\n  params: Record<string, any>,\n  keys: string[],\n  exactlyOneOf = false\n) => {\n  const provided = keys.filter(\n    (key) => key in params && params[key] !== undefined\n  );\n  if (exactlyOneOf && provided.length !== 1) {\n    throw new Error(\n      `Expected exactly one of: ${keys.join(\", \")}. Got: ${provided.join(\", \")}`\n    );\n  } else if (!exactlyOneOf && provided.length > 1) {\n    throw new Error(\n      `Expected one of: ${keys.join(\", \")} or none. Got: ${provided.join(\", \")}`\n    );\n  }\n};\n\nexport const checkValidProps = (\n  params: Record<string, any>,\n  allowedKeys: string[]\n) => {\n  const unexpected = Object.keys(params).filter(\n    (key) => !allowedKeys.includes(key)\n  );\n  if (unexpected.length > 0) {\n    throw new Error(\n      `Unexpected properties: ${unexpected.join(\n        \", \"\n      )}. Expected only: ${allowedKeys.join(\", \")}.`\n    );\n  }\n};\n"],"mappings":";;;;;;;;;AAwBA,MAAM,uBAAuB,EAC3B,iBACA,mBACA,sBACA,mBACA,mBACA,cACA,YACA,iBAC4C;AAC5C,KAAI,sBAAsB,SAAS,gBACjC,QAAO,IAAIA,mBAAAA,iBAAiB,EAC1B,QAAQ,iBACT,CAAC;UACO,sBAAsB,iBAAiB,qBAChD,QAAO,IAAIC,mBAAAA,yBAAyB,EAClC,aAAa,sBACd,CAAC;UACO,sBAAsB;MAE3B,sBAAsB,qBAAqB,iBAE7C,QAAO,IAAIC,mBAAAA,6BAA6B;GACtC,UAAU;GACV,UAAU;GACV,MAJwB,gBAAgB,YAIjB,OAAO,0BAA0B;GACxD,QAAQ;GACR,wBAAwB;GACzB,CAAC;;;AAMR,MAAa,8BAA8B,EACzC,iBACA,mBACA,sBACA,mBACA,mBACA,cACA,YACA,SACA,iBAC6E;AAC7E,KAAI,sBAAsB,SAAS,gBACjC,QAAOC,sBAAAA,UAAU,YAAY;EAC3B;EACA;EACA,eAAe,IAAIH,mBAAAA,iBAAiB,EAClC,QAAQ,iBACT,CAAC;EACH,CAAC;UACO,sBAAsB,iBAAiB,qBAChD,QAAOG,sBAAAA,UAAU,YAAY;EAC3B;EACA;EACA,eAAe,IAAIF,mBAAAA,yBAAyB,EAC1C,aAAa,sBACd,CAAC;EACH,CAAC;UACO,sBAAsB;MAE3B,sBAAsB,qBAAqB,kBAAkB;GAC/D,MAAM,oBAAoB,gBAAgB;AAC1C,UAAOE,sBAAAA,UAAU,YAAY;IAC3B;IACA;IACA,wBAAwB;IACxB,eAAe,IAAID,mBAAAA,6BAA6B;KAC9C,UAAU;KACV,UAAU;KACV,KAAK,kBAAkB,OAAO,0BAA0B;KACxD,QAAQ;KACR,wBAAwB;KACzB,CAAC;IACH,CAA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