"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CohereEmbeddings = void 0;
const cohere_ai_1 = require("cohere-ai");
const env_1 = require("@langchain/core/utils/env");
const embeddings_1 = require("@langchain/core/embeddings");
const chunk_array_1 = require("@langchain/core/utils/chunk_array");
/**
 * A class for generating embeddings using the Cohere API.
 */
class CohereEmbeddings extends embeddings_1.Embeddings {
    /**
     * Constructor for the CohereEmbeddings class.
     * @param fields - An optional object with properties to configure the instance.
     */
    constructor(fields) {
        const fieldsWithDefaults = { maxConcurrency: 2, ...fields };
        super(fieldsWithDefaults);
        Object.defineProperty(this, "model", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: "small"
        });
        Object.defineProperty(this, "batchSize", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: 48
        });
        Object.defineProperty(this, "inputType", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: void 0
        });
        Object.defineProperty(this, "client", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: void 0
        });
        const apiKey = fieldsWithDefaults?.apiKey || (0, env_1.getEnvironmentVariable)("COHERE_API_KEY");
        if (!apiKey) {
            throw new Error("Cohere API key not found");
        }
        this.client = new cohere_ai_1.CohereClient({
            token: apiKey,
        });
        this.model = fieldsWithDefaults?.model ?? this.model;
        this.batchSize = fieldsWithDefaults?.batchSize ?? this.batchSize;
        this.inputType = fieldsWithDefaults?.inputType;
    }
    /**
     * Generates embeddings for an array of texts.
     * @param texts - An array of strings to generate embeddings for.
     * @returns A Promise that resolves to an array of embeddings.
     */
    async embedDocuments(texts) {
        const batches = (0, chunk_array_1.chunkArray)(texts, this.batchSize);
        const batchRequests = batches.map((batch) => this.embeddingWithRetry({
            model: this.model,
            texts: batch,
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            inputType: this.inputType,
        }));
        const batchResponses = await Promise.all(batchRequests);
        const embeddings = [];
        for (let i = 0; i < batchResponses.length; i += 1) {
            const batch = batches[i];
            const { embeddings: batchResponse } = batchResponses[i];
            for (let j = 0; j < batch.length; j += 1) {
                if ("float" in batchResponse && batchResponse.float) {
                    embeddings.push(batchResponse.float[j]);
                }
                else if (Array.isArray(batchResponse)) {
                    embeddings.push(batchResponse[j]);
                }
            }
        }
        return embeddings;
    }
    /**
     * Generates an embedding for a single text.
     * @param text - A string to generate an embedding for.
     * @returns A Promise that resolves to an array of numbers representing the embedding.
     */
    async embedQuery(text) {
        const { embeddings } = await this.embeddingWithRetry({
            model: this.model,
            texts: [text],
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            inputType: this.inputType,
        });
        if ("float" in embeddings && embeddings.float) {
            return embeddings.float[0];
        }
        else if (Array.isArray(embeddings)) {
            return embeddings[0];
        }
        else {
            throw new Error(`Invalid response from Cohere API. Received: ${JSON.stringify(embeddings, null, 2)}`);
        }
    }
    /**
     * Generates embeddings with retry capabilities.
     * @param request - An object containing the request parameters for generating embeddings.
     * @returns A Promise that resolves to the API response.
     */
    async embeddingWithRetry(request) {
        return this.caller.call(async () => {
            let response;
            try {
                response = await this.client.embed(request);
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
            }
            catch (e) {
                e.status = e.status ?? e.statusCode;
                throw e;
            }
            return response;
        });
    }
    get lc_secrets() {
        return {
            apiKey: "COHERE_API_KEY",
            api_key: "COHERE_API_KEY",
        };
    }
    get lc_aliases() {
        return {
            apiKey: "cohere_api_key",
            api_key: "cohere_api_key",
        };
    }
}
exports.CohereEmbeddings = CohereEmbeddings;
