"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var EmbeddingsOpenAi_node_exports = {};
__export(EmbeddingsOpenAi_node_exports, {
  EmbeddingsOpenAi: () => EmbeddingsOpenAi
});
module.exports = __toCommonJS(EmbeddingsOpenAi_node_exports);
var import_openai = require("@langchain/openai");
var import_n8n_workflow = require("n8n-workflow");
var import_logWrapper = require("../../../utils/logWrapper");
var import_httpProxyAgent = require("../../../utils/httpProxyAgent");
var import_sharedFields = require("../../../utils/sharedFields");
var import_di = require("@n8n/di");
var import_config = require("@n8n/config");
const modelParameter = {
  displayName: "Model",
  name: "model",
  type: "options",
  description: 'The model which will generate the embeddings. <a href="https://platform.openai.com/docs/models/overview">Learn more</a>.',
  typeOptions: {
    loadOptions: {
      routing: {
        request: {
          method: "GET",
          url: '={{ $parameter.options?.baseURL?.split("/").slice(-1).pop() || $credentials?.url?.split("/").slice(-1).pop() || "v1" }}/models'
        },
        output: {
          postReceive: [
            {
              type: "rootProperty",
              properties: {
                property: "data"
              }
            },
            {
              type: "filter",
              properties: {
                // If the baseURL is not set or is set to api.openai.com, include only embedding models
                pass: `={{
									($parameter.options?.baseURL && !$parameter.options?.baseURL?.startsWith('https://api.openai.com/')) ||
									($credentials?.url && !$credentials.url.startsWith('https://api.openai.com/')) ||
									$responseItem.id.includes('embed')
								}}`
              }
            },
            {
              type: "setKeyValue",
              properties: {
                name: "={{$responseItem.id}}",
                value: "={{$responseItem.id}}"
              }
            },
            {
              type: "sort",
              properties: {
                key: "name"
              }
            }
          ]
        }
      }
    }
  },
  routing: {
    send: {
      type: "body",
      property: "model"
    }
  },
  default: "text-embedding-3-small"
};
class EmbeddingsOpenAi {
  constructor() {
    this.description = {
      displayName: "Embeddings OpenAI",
      name: "embeddingsOpenAi",
      icon: { light: "file:openAiLight.svg", dark: "file:openAiLight.dark.svg" },
      credentials: [
        {
          name: "openAiApi",
          required: true
        }
      ],
      group: ["transform"],
      version: [1, 1.1, 1.2],
      description: "Use Embeddings OpenAI",
      defaults: {
        name: "Embeddings OpenAI"
      },
      codex: {
        categories: ["AI"],
        subcategories: {
          AI: ["Embeddings"]
        },
        resources: {
          primaryDocumentation: [
            {
              url: "https://docs.n8n.io/integrations/builtin/cluster-nodes/sub-nodes/n8n-nodes-langchain.embeddingsopenai/"
            }
          ]
        }
      },
      inputs: [],
      outputs: [import_n8n_workflow.NodeConnectionTypes.AiEmbedding],
      outputNames: ["Embeddings"],
      requestDefaults: {
        ignoreHttpStatusErrors: true,
        baseURL: '={{ $parameter.options?.baseURL?.split("/").slice(0,-1).join("/") || $credentials.url?.split("/").slice(0,-1).join("/") || "https://api.openai.com" }}'
      },
      properties: [
        (0, import_sharedFields.getConnectionHintNoticeField)([import_n8n_workflow.NodeConnectionTypes.AiVectorStore]),
        {
          ...modelParameter,
          default: "text-embedding-ada-002",
          displayOptions: {
            show: {
              "@version": [1]
            }
          }
        },
        {
          ...modelParameter,
          displayOptions: {
            hide: {
              "@version": [1]
            }
          }
        },
        {
          displayName: "Options",
          name: "options",
          placeholder: "Add Option",
          description: "Additional options to add",
          type: "collection",
          default: {},
          options: [
            {
              displayName: "Dimensions",
              name: "dimensions",
              default: void 0,
              description: "The number of dimensions the resulting output embeddings should have. Only supported in text-embedding-3 and later models.",
              type: "options",
              options: [
                {
                  name: "256",
                  value: 256
                },
                {
                  name: "512",
                  value: 512
                },
                {
                  name: "1024",
                  value: 1024
                },
                {
                  name: "1536",
                  value: 1536
                },
                {
                  name: "3072",
                  value: 3072
                }
              ]
            },
            {
              displayName: "Base URL",
              name: "baseURL",
              default: "https://api.openai.com/v1",
              description: "Override the default base URL for the API",
              type: "string",
              displayOptions: {
                hide: {
                  "@version": [{ _cnd: { gte: 1.2 } }]
                }
              }
            },
            {
              displayName: "Batch Size",
              name: "batchSize",
              default: 512,
              typeOptions: { maxValue: 2048 },
              description: "Maximum number of documents to send in each request",
              type: "number"
            },
            {
              displayName: "Strip New Lines",
              name: "stripNewLines",
              default: true,
              description: "Whether to strip new lines from the input text",
              type: "boolean"
            },
            {
              displayName: "Timeout",
              name: "timeout",
              default: -1,
              description: "Maximum amount of time a request is allowed to take in seconds. Set to -1 for no timeout.",
              type: "number"
            },
            {
              displayName: "Encoding Format",
              name: "encodingFormat",
              type: "options",
              description: "The format to return the embeddings in",
              default: void 0,
              options: [
                {
                  name: "Float",
                  value: "float"
                },
                {
                  name: "Base64",
                  value: "base64"
                }
              ]
            }
          ]
        }
      ]
    };
  }
  async supplyData(itemIndex) {
    this.logger.debug("Supply data for embeddings");
    const credentials = await this.getCredentials("openAiApi");
    const options = this.getNodeParameter("options", itemIndex, {});
    if (options.timeout === -1) {
      options.timeout = void 0;
    }
    const { openAiDefaultHeaders: defaultHeaders } = import_di.Container.get(import_config.AiConfig);
    const configuration = {
      defaultHeaders
    };
    if (options.baseURL) {
      configuration.baseURL = options.baseURL;
    } else if (credentials.url) {
      configuration.baseURL = credentials.url;
    }
    if (configuration.baseURL) {
      configuration.fetchOptions = {
        dispatcher: (0, import_httpProxyAgent.getProxyAgent)(configuration.baseURL ?? "https://api.openai.com/v1")
      };
    }
    const embeddings = new import_openai.OpenAIEmbeddings({
      model: this.getNodeParameter("model", itemIndex, "text-embedding-3-small"),
      apiKey: credentials.apiKey,
      ...options,
      configuration
    });
    return {
      response: (0, import_logWrapper.logWrapper)(embeddings, this)
    };
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  EmbeddingsOpenAi
});
//# sourceMappingURL=EmbeddingsOpenAi.node.js.map