/**
 * 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 google_genai_exports = {};
__export(google_genai_exports, {
  GoogleGenAIEmbeddingProvider: () => GoogleGenAIEmbeddingProvider,
  GoogleGenAIProvider: () => GoogleGenAIProvider,
  googleGenAIProviderOptions: () => googleGenAIProviderOptions
});
module.exports = __toCommonJS(google_genai_exports);
var import_google_genai = require("@langchain/google-genai");
var import_provider = require("./provider");
var import_axios = __toESM(require("axios"));
var import_utils = require("../utils");
var import_ai_manager = require("../manager/ai-manager");
const GOOGLE_GEN_AI_URL = "https://generativelanguage.googleapis.com/v1beta/";
class GoogleGenAIProvider extends import_provider.LLMProvider {
  get baseURL() {
    return GOOGLE_GEN_AI_URL;
  }
  createModel() {
    const { apiKey } = this.serviceOptions || {};
    const { model, responseFormat } = this.modelOptions || {};
    return new import_google_genai.ChatGoogleGenerativeAI({
      apiKey,
      ...this.modelOptions,
      model,
      json: responseFormat === "json",
      verbose: true
    });
  }
  async listModels() {
    var _a, _b;
    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?key=${apiKey}`);
      return {
        models: (_a = res == null ? void 0 : res.data) == null ? void 0 : _a.models.map((model) => ({
          id: model.name
        }))
      };
    } catch (e) {
      return { code: ((_b = e.response) == null ? void 0 : _b.status) || 500, errMsg: e.message };
    }
  }
  parseResponseMessage(message) {
    var _a, _b, _c, _d, _e;
    const { content: rawContent, messageId, metadata, role, toolCalls, attachments, workContext } = message;
    const content = {
      ...rawContent,
      messageId,
      metadata,
      attachments,
      workContext
    };
    if (toolCalls) {
      content.tool_calls = toolCalls;
    }
    if (Array.isArray(content.content)) {
      const textMessage = content.content.find((msg) => msg.type === "text");
      content.content = textMessage == null ? void 0 : textMessage.text;
    }
    if ((_c = (_b = (_a = metadata == null ? void 0 : metadata.response_metadata) == null ? void 0 : _a.groundingMetadata) == null ? void 0 : _b.groundingChunks) == null ? void 0 : _c.length) {
      content.reference = content.reference ?? [];
      for (const groundingChunk of ((_e = (_d = metadata == null ? void 0 : metadata.response_metadata) == null ? void 0 : _d.groundingMetadata) == null ? void 0 : _e.groundingChunks) ?? []) {
        if (!groundingChunk.web) {
          continue;
        }
        content.reference.push({
          title: groundingChunk.web.title,
          url: groundingChunk.web.uri
        });
      }
    }
    return {
      key: messageId,
      content,
      role
    };
  }
  async parseAttachment(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: attachment.mimetype,
          data
        }
      };
    }
  }
  parseResponseMetadata(output) {
    var _a, _b;
    const [generation] = (output == null ? void 0 : output.generations) ?? [];
    const [chatGenerationChunk] = generation ?? [];
    return [
      (_a = chatGenerationChunk == null ? void 0 : chatGenerationChunk.message) == null ? void 0 : _a.id,
      { groundingMetadata: (_b = chatGenerationChunk == null ? void 0 : chatGenerationChunk.generationInfo) == null ? void 0 : _b.groundingMetadata }
    ];
  }
  getStructuredOutputOptions(structuredOutput) {
    const { responseFormat } = this.modelOptions || {};
    const { schema, name, description } = structuredOutput || {};
    if (!schema) {
      return;
    }
    const methods = {
      json_object: "jsonMode",
      json_schema: "jsonSchema"
    };
    const options = {
      includeRaw: true,
      name
    };
    const method = methods[responseFormat];
    if (method) {
      options.method = method;
    }
    return {
      schema: {
        ...schema,
        description: description ?? schema.description
      },
      options
    };
  }
  builtInTools() {
    var _a, _b;
    if (((_b = (_a = this.modelOptions) == null ? void 0 : _a.builtIn) == null ? void 0 : _b.webSearch) === true) {
      return [{ googleSearch: {} }];
    }
    return [];
  }
  isToolConflict() {
    return true;
  }
}
class GoogleGenAIEmbeddingProvider extends import_provider.EmbeddingProvider {
  getDefaultUrl() {
    return "https://generativelanguage.googleapis.com";
  }
  createEmbedding() {
    return new import_google_genai.GoogleGenerativeAIEmbeddings({
      apiKey: this.apiKey,
      baseUrl: this.baseUrl,
      model: this.model
    });
  }
}
const googleGenAIProviderOptions = {
  title: "Google generative AI",
  supportedModel: [import_ai_manager.SupportedModel.LLM, import_ai_manager.SupportedModel.EMBEDDING],
  models: {
    [import_ai_manager.SupportedModel.LLM]: ["models/gemini-3.0-pro-preview"],
    [import_ai_manager.SupportedModel.EMBEDDING]: ["gemini-embedding-001"]
  },
  provider: GoogleGenAIProvider,
  embedding: GoogleGenAIEmbeddingProvider,
  supportWebSearch: true
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  GoogleGenAIEmbeddingProvider,
  GoogleGenAIProvider,
  googleGenAIProviderOptions
});
