import { Embeddings } from "@langchain/core/embeddings";
import { chunkArray } from "@langchain/core/utils/chunk_array";
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import { Embedding } from "@baiducloud/qianfan";
export class BaiduQianfanEmbeddings extends Embeddings {
    constructor(fields) {
        const fieldsWithDefaults = { maxConcurrency: 2, ...fields };
        super(fieldsWithDefaults);
        Object.defineProperty(this, "modelName", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: "Embedding-V1"
        });
        Object.defineProperty(this, "batchSize", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: 16
        });
        Object.defineProperty(this, "stripNewLines", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: true
        });
        Object.defineProperty(this, "qianfanAK", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: void 0
        });
        Object.defineProperty(this, "qianfanSK", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: void 0
        });
        Object.defineProperty(this, "qianfanAccessKey", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: void 0
        });
        Object.defineProperty(this, "qianfanSecretKey", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: void 0
        });
        Object.defineProperty(this, "accessToken", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: void 0
        });
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        Object.defineProperty(this, "embeddings", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: void 0
        });
        this.qianfanAK =
            fieldsWithDefaults?.qianfanAK ?? getEnvironmentVariable("QIANFAN_AK");
        this.qianfanSK =
            fieldsWithDefaults?.qianfanSK ?? getEnvironmentVariable("QIANFAN_SK");
        this.qianfanAccessKey =
            fieldsWithDefaults?.qianfanAccessKey ??
                getEnvironmentVariable("QIANFAN_ACCESS_KEY");
        this.qianfanSecretKey =
            fieldsWithDefaults?.qianfanSecretKey ??
                getEnvironmentVariable("QIANFAN_SECRET_KEY");
        // 优先使用安全认证AK/SK鉴权
        if (this.qianfanAccessKey && this.qianfanSecretKey) {
            this.embeddings = new Embedding({
                QIANFAN_ACCESS_KEY: this.qianfanAccessKey,
                QIANFAN_SECRET_KEY: this.qianfanSecretKey,
            });
        }
        else if (this.qianfanAK && this.qianfanSK) {
            this.embeddings = new Embedding({
                QIANFAN_AK: this.qianfanAK,
                QIANFAN_SK: this.qianfanSK,
            });
        }
        else {
            throw new Error("Please provide AK/SK");
        }
        this.modelName = fieldsWithDefaults?.modelName ?? this.modelName;
        if (this.modelName === "tao-8k") {
            if (fieldsWithDefaults?.batchSize && fieldsWithDefaults.batchSize !== 1) {
                throw new Error("tao-8k model supports only a batchSize of 1. Please adjust your batchSize accordingly");
            }
            this.batchSize = 1;
        }
        else {
            this.batchSize = fieldsWithDefaults?.batchSize ?? this.batchSize;
        }
        this.stripNewLines =
            fieldsWithDefaults?.stripNewLines ?? this.stripNewLines;
    }
    /**
     * Method to generate embeddings for an array of documents. Splits the
     * documents into batches and makes requests to the BaiduQianFan API to generate
     * embeddings.
     * @param texts Array of documents to generate embeddings for.
     * @returns Promise that resolves to a 2D array of embeddings for each document.
     */
    async embedDocuments(texts) {
        const batches = chunkArray(this.stripNewLines ? texts.map((t) => t.replace(/\n/g, " ")) : texts, this.batchSize);
        const batchRequests = batches.map((batch) => {
            const params = this.getParams(batch);
            return this.embeddingWithRetry(params);
        });
        const batchResponses = await Promise.all(batchRequests);
        const embeddings = [];
        for (let i = 0; i < batchResponses.length; i += 1) {
            const batch = batches[i];
            const batchResponse = batchResponses[i] || [];
            for (let j = 0; j < batch.length; j += 1) {
                embeddings.push(batchResponse[j]);
            }
        }
        return embeddings;
    }
    /**
     * Method to generate an embedding for a single document. Calls the
     * embeddingWithRetry method with the document as the input.
     * @param text Document to generate an embedding for.
     * @returns Promise that resolves to an embedding for the document.
     */
    async embedQuery(text) {
        const params = this.getParams([
            this.stripNewLines ? text.replace(/\n/g, " ") : text,
        ]);
        const embeddings = (await this.embeddingWithRetry(params)) || [[]];
        return embeddings[0];
    }
    /**
     * Method to generate an embedding params.
     * @param texts Array of documents to generate embeddings for.
     * @returns an embedding params.
     */
    getParams(texts) {
        return {
            input: texts,
        };
    }
    /**
     * Private method to make a request to the BaiduAI API to generate
     * embeddings. Handles the retry logic and returns the response from the
     * API.
     * @param request Request to send to the BaiduAI API.
     * @returns Promise that resolves to the response from the API.
     */
    async embeddingWithRetry(body) {
        const embeddingData = await this.embeddings.embedding(body, this.modelName);
        if ("error_code" in embeddingData && embeddingData.error_code) {
            throw new Error(`${embeddingData.error_code}: ${embeddingData.error_msg}`);
        }
        return embeddingData.data.map(({ embedding }) => embedding);
    }
}
