/**
 * This file is part of the NocoBase (R) project.
 * Copyright (c) 2020-2024 NocoBase Co., Ltd.
 * Authors: NocoBase Team.
 *
 * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
 * For more information, please refer to: https://www.nocobase.com/agreement.
 */

var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var gigachat_exports = {};
__export(gigachat_exports, {
  GigaChatProvider: () => GigaChatProvider,
  gigaChatProviderOptions: () => gigaChatProviderOptions
});
module.exports = __toCommonJS(gigachat_exports);
var import_node_https = require("node:https");
var import_gigachat = __toESM(require("gigachat"));
var import_langchain_gigachat = require("langchain-gigachat");
var import_plugin_ai = require("@nocobase/plugin-ai");
class GigaChatModelInternal extends import_langchain_gigachat.GigaChat {
  bindTools(tools, kwargs) {
    return this.withConfig({
      tools: tools == null ? void 0 : tools.map((t) => {
        var _a, _b;
        return {
          name: t.name,
          description: t.description,
          parameters: ((_b = (_a = t.schema).toJSONSchema) == null ? void 0 : _b.call(_a)) ?? t.schema
        };
      }),
      ...kwargs
    });
  }
}
class GigaChatProvider extends import_plugin_ai.LLMProvider {
  createModel() {
    const { apiKey: credentials, baseURL, authURL, scope, enableSSL } = this.serviceOptions || {};
    const { responseFormat } = this.modelOptions || {};
    const baseUrl = this.isUrlEmpty(baseURL) ? this.baseURL : baseURL;
    const authUrl = this.isUrlEmpty(authURL) ? this.authURL : authURL;
    const httpsAgent = new import_node_https.Agent({
      rejectUnauthorized: enableSSL ?? false
    });
    return new GigaChatModelInternal({
      credentials,
      baseUrl,
      authUrl,
      scope,
      ...this.modelOptions,
      invocationKwargs: {
        response_format: {
          type: responseFormat
        }
      },
      httpsAgent
    });
  }
  async listModels() {
    try {
      const {
        apiKey: credentials,
        baseURL,
        authURL,
        scope,
        enableSSL
      } = this.serviceOptions || {};
      const baseUrl = this.isUrlEmpty(baseURL) ? this.baseURL : baseURL;
      const authUrl = this.isUrlEmpty(authURL) ? this.authURL : authURL;
      const httpsAgent = new import_node_https.Agent({
        rejectUnauthorized: enableSSL ?? false
      });
      const giga = new import_gigachat.default({
        credentials,
        baseUrl,
        authUrl,
        scope,
        httpsAgent
      });
      const models = await giga.getModels();
      return { models: models.data };
    } catch (e) {
      return { code: 500, errMsg: e.message };
    }
  }
  get baseURL() {
    return "https://gigachat.devices.sberbank.ru/api/v1";
  }
  get authURL() {
    return "https://ngw.devices.sberbank.ru:9443/api/v2/oauth";
  }
  isUrlEmpty(baseURL) {
    return !baseURL || baseURL === null || baseURL.trim().length === 0;
  }
  parseResponseError(err) {
    var _a, _b;
    if ((err == null ? void 0 : err.name) === "AuthenticationError" || (err == null ? void 0 : err.name) === "ResponseError") {
      return `GigaChat service error: ${(_a = err.response) == null ? void 0 : _a.status} ${(_b = err.response) == null ? void 0 : _b.statusText}`;
    }
    return (err == null ? void 0 : err.message) ?? "Unexpected LLM service error";
  }
}
const gigaChatProviderOptions = {
  title: "GigaChat",
  provider: GigaChatProvider
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  GigaChatProvider,
  gigaChatProviderOptions
});
