{"version":3,"file":"ibm.cjs","names":["IamAuthenticator","BearerTokenAuthenticator","CloudPakForDataAuthenticator","WatsonXAI","Gateway","toolCallId: string","num: number","arr: string[]","str: string","JsonOutputToolsParser","params: WatsonxToolsOutputParserParams<T>","result: unknown","e: any","OutputParserException","generations: ChatGeneration[]","tool","toolCall: ToolCall","obj: WatsonXAI.JsonObject | undefined","shape: Record<string, any>","z","params: Record<string, any>","keys: string[]","allowedKeys: string[]"],"sources":["../../src/utils/ibm.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/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<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,sBAAsB,CAAC,EAC3B,iBACA,mBACA,sBACA,mBACA,mBACA,cACA,YACA,YACY,KAAgC;AAC5C,KAAI,sBAAsB,SAAS,gBACjC,QAAO,IAAIA,oCAAiB,EAC1B,QAAQ,gBACT;UACQ,sBAAsB,iBAAiB,qBAChD,QAAO,IAAIC,4CAAyB,EAClC,aAAa,qBACd;UACQ,sBAAsB,QAE/B;MAAI,sBAAsB,qBAAqB,kBAAkB;GAC/D,MAAM,oBAAoB,gBAAgB;AAC1C,UAAO,IAAIC,gDAA6B;IACtC,UAAU;IACV,UAAU;IACV,KAAK,kBAAkB,OAAO,0BAA0B;IACxD,QAAQ;IACR,wBAAwB;GACzB;EACF;;AAEH,QAAO;AACR;AAED,MAAa,6BAA6B,CAAC,EACzC,iBACA,mBACA,sBACA,mBACA,mBACA,cACA,YACA,SACA,YACiD,KAA4B;AAC7E,KAAI,sBAAsB,SAAS,gBACjC,QAAOC,iCAAU,YAAY;EAC3B;EACA;EACA,eAAe,IAAIH,oCAAiB,EAClC,QAAQ,gBACT;CACF,EAAC;UACO,sBAAsB,iBAAiB,qBAChD,QAAOG,iCAAU,YAAY;EAC3B;EACA;EACA,eAAe,IAAIF,4CAAyB,EAC1C,aAAa,qBACd;CACF,EAAC;UACO,sBAAsB,QAE/B;MAAI,sBAAsB,qBAAqB,kBAAkB;GAC/D,MAAM,oBAAoB,gBAAgB;AAC1C,UAAOE,iCAAU,YAAY;IAC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