/**
 * 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 provider_exports = {};
__export(provider_exports, {
  EmbeddingProvider: () => EmbeddingProvider,
  LLMProvider: () => LLMProvider,
  ToolDefinition: () => ToolDefinition
});
module.exports = __toCommonJS(provider_exports);
var import_axios = __toESM(require("axios"));
var import_utils = require("../utils");
var import_langchain = require("langchain");
var import_stream = require("@langchain/core/utils/stream");
var import_document_loader = require("../document-loader");
var import_node_path = __toESM(require("node:path"));
class LLMProvider {
  app;
  serviceOptions;
  modelOptions;
  chatModel;
  get baseURL() {
    return null;
  }
  constructor(opts) {
    const { app, serviceOptions, modelOptions } = opts;
    this.app = app;
    this.serviceOptions = app.environment.renderJsonTemplate(serviceOptions);
    if (modelOptions) {
      this.modelOptions = modelOptions;
      this.chatModel = this.createModel();
    }
  }
  prepareChain(context) {
    var _a, _b, _c, _d;
    let chain = this.chatModel;
    const toolDefinitions = (_a = context.tools) == null ? void 0 : _a.map(ToolDefinition.from("ToolsEntry"));
    if ((_b = this.builtInTools()) == null ? void 0 : _b.length) {
      const tools = [...this.builtInTools()];
      if (!this.isToolConflict() && (toolDefinitions == null ? void 0 : toolDefinitions.length)) {
        tools.push(...toolDefinitions);
      }
      chain = (_c = chain.bindTools) == null ? void 0 : _c.call(chain, tools);
    } else if (toolDefinitions == null ? void 0 : toolDefinitions.length) {
      chain = (_d = chain.bindTools) == null ? void 0 : _d.call(chain, toolDefinitions);
    }
    if (context.structuredOutput) {
      const { schema, options } = this.getStructuredOutputOptions(context.structuredOutput) || {};
      if (schema) {
        chain = chain.withStructuredOutput(schema, options);
      }
    }
    return chain;
  }
  async invoke(context, options) {
    const chain = this.prepareChain(context);
    return chain.invoke(context.messages, options);
  }
  async stream(context, options) {
    const chain = this.prepareChain(context);
    return chain.streamEvents(context.messages, options);
  }
  async listModels() {
    var _a, _b, _c, _d;
    const options = this.serviceOptions || {};
    const apiKey = options.apiKey;
    let baseURL = options.baseURL || this.baseURL;
    if (!baseURL) {
      return { code: 400, errMsg: "baseURL is required" };
    }
    if (!apiKey) {
      return { code: 400, errMsg: "API Key required" };
    }
    if (baseURL && baseURL.endsWith("/")) {
      baseURL = baseURL.slice(0, -1);
    }
    try {
      const res = await import_axios.default.get(`${baseURL}/models`, {
        headers: {
          Authorization: `Bearer ${apiKey}`
        }
      });
      return { models: res == null ? void 0 : res.data.data };
    } catch (e) {
      const status = ((_a = e.response) == null ? void 0 : _a.status) || 500;
      const data = (_b = e.response) == null ? void 0 : _b.data;
      const errorMsg = ((_c = data == null ? void 0 : data.error) == null ? void 0 : _c.message) || (data == null ? void 0 : data.message) || (typeof (data == null ? void 0 : data.error) === "string" ? data.error : void 0) || (typeof data === "string" ? data : void 0) || ((_d = e.response) == null ? void 0 : _d.statusText) || e.message;
      return { code: status, errMsg: errorMsg };
    }
  }
  parseResponseMessage(message) {
    return (0, import_utils.parseResponseMessage)(message);
  }
  parseResponseChunk(chunk) {
    return (0, import_utils.stripToolCallTags)(chunk);
  }
  async parseAttachment(ctx, attachment) {
    if (this.isApiSupportedAttachment(attachment)) {
      return await this.convertToContent(ctx, attachment);
    } else if (this.isDocumentLoaderSupportedAttachment(attachment)) {
      return await this.loadDocument(ctx, attachment);
    } else {
      const safeFilename = attachment.filename ? import_node_path.default.basename(attachment.filename) : "document";
      return {
        placement: "system",
        content: `The user has uploaded a ${attachment.mimetype} file (filename: ${safeFilename}). Please inform the user directly that you do not support parsing ${attachment.mimetype} content.`
      };
    }
  }
  isApiSupportedAttachment(attachment) {
    const media = ["image/"];
    const pdf = ["application/pdf"];
    const supportedMedia = media.some((it) => {
      var _a;
      return (_a = attachment == null ? void 0 : attachment.mimetype) == null ? void 0 : _a.startsWith(it);
    });
    const supportedPdf = pdf.some((it) => {
      var _a;
      return (_a = attachment == null ? void 0 : attachment.mimetype) == null ? void 0 : _a.includes(it);
    });
    return supportedMedia || supportedPdf;
  }
  isDocumentLoaderSupportedAttachment(attachment) {
    const ext = import_node_path.default.extname((attachment == null ? void 0 : attachment.filename) ?? "").toLocaleLowerCase();
    return import_document_loader.SUPPORTED_DOCUMENT_EXTNAMES.includes(ext);
  }
  async convertToContent(ctx, attachment) {
    const fileManager = this.app.pm.get("file-manager");
    const url = await fileManager.getFileURL(attachment);
    const data = await (0, import_utils.encodeFile)(ctx, decodeURIComponent(url));
    if (attachment.mimetype.startsWith("image/")) {
      return {
        placement: "contentBlocks",
        content: {
          type: "image_url",
          image_url: {
            url: `data:image/${attachment.mimetype.split("/")[1]};base64,${data}`
          }
        }
      };
    } else {
      return {
        placement: "contentBlocks",
        content: {
          type: "file",
          mimeType: attachment.mimetype,
          metadata: {
            filename: attachment.filename
          },
          data
        }
      };
    }
  }
  async loadDocument(_ctx, attachment) {
    const safeFilename = attachment.filename ? import_node_path.default.basename(attachment.filename) : "document";
    const parsed = await this.documentLoader.load(attachment);
    if (!parsed.supported) {
      return {
        placement: "system",
        content: `File ${safeFilename} is not a supported document type for text parsing.`
      };
    }
    if (parsed.text.length === 0) {
      return {
        placement: "system",
        content: `The file provided by the user is an empty file, file name is "${safeFilename}"`
      };
    }
    return {
      placement: "system",
      content: `<parsed_document filename="${safeFilename}">
${parsed.text}
</parsed_document>`
    };
  }
  getStructuredOutputOptions(structuredOutput) {
    const { responseFormat } = this.modelOptions || {};
    const { schema, name, description, strict } = structuredOutput || {};
    if (!schema) {
      return;
    }
    const methods = {
      json_object: "jsonMode",
      json_schema: "jsonSchema"
    };
    const options = {
      includeRaw: true,
      name,
      method: methods[responseFormat]
    };
    if (strict) {
      options["strict"] = strict;
    }
    return {
      schema: {
        name,
        description,
        parameters: schema
      },
      options
    };
  }
  async testFlight() {
    try {
      const result = await this.chatModel.invoke("hello");
    } catch (error) {
      return {
        status: "error",
        code: 1,
        message: error.message
      };
    }
    return {
      status: "success",
      code: 0
    };
  }
  builtInTools() {
    return [];
  }
  isToolConflict() {
    return false;
  }
  resolveTools(toolDefinitions) {
    const builtIn = this.builtInTools();
    if (builtIn.length > 0 && toolDefinitions.length > 0 && this.isToolConflict()) {
      return [...builtIn];
    }
    return [...builtIn, ...toolDefinitions];
  }
  parseWebSearchAction(chunk) {
    return [];
  }
  parseReasoningContent(chunk) {
    return null;
  }
  parseResponseMetadata(output) {
    return [null, null];
  }
  parseResponseError(err) {
    return (err == null ? void 0 : err.message) ?? "Unexpected LLM service error";
  }
  get documentLoader() {
    return this.aiPlugin.documentLoaders.cached;
  }
  get aiPlugin() {
    return this.app.pm.get("ai");
  }
}
class EmbeddingProvider {
  constructor(opts) {
    this.opts = opts;
    const { app, serviceOptions, modelOptions } = this.opts;
    this.app = app;
    this.serviceOptions = app.environment.renderJsonTemplate(serviceOptions ?? {});
    this.modelOptions = modelOptions;
  }
  app;
  serviceOptions;
  modelOptions;
  get apiKey() {
    const { apiKey } = this.serviceOptions ?? {};
    if (!apiKey) {
      throw new Error("apiKey is required");
    }
    return apiKey;
  }
  get baseURL() {
    var _a;
    const baseURL = ((_a = this.serviceOptions) == null ? void 0 : _a.baseURL) ?? this.getDefaultUrl();
    if (!baseURL) {
      throw new Error("baseURL is required");
    }
    return baseURL;
  }
  get model() {
    const { model } = this.modelOptions ?? {};
    if (!model) {
      throw new Error("Embedding model is required");
    }
    return model;
  }
}
class ToolDefinition {
  constructor(from, _tool) {
    this.from = from;
    this._tool = _tool;
  }
  static from(from) {
    return (tool2) => new ToolDefinition(from, tool2).tool;
  }
  get tool() {
    if (this.from === "ToolsEntry") {
      return this.convertToolOptions();
    } else {
      throw new Error("not supported tool definitions");
    }
  }
  convertToolOptions() {
    const {
      invoke,
      definition: { name, description, schema }
    } = this._tool;
    return (0, import_langchain.tool)((input, { toolCall, context }) => invoke(context.ctx, input, toolCall.id), {
      name,
      description,
      schema,
      returnDirect: false
    });
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  EmbeddingProvider,
  LLMProvider,
  ToolDefinition
});
