"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.LocalAiCompletionProvider = exports.LocalAiEmbeddingProvider = exports.LocalAiChatProvider = void 0;
const cache_1 = require("../cache");
const logger_1 = __importDefault(require("../logger"));
const shared_1 = require("./shared");
class LocalAiGenericProvider {
    constructor(modelName, options = {}) {
        const { id, config, env } = options;
        this.modelName = modelName;
        this.apiBaseUrl =
            config?.apiBaseUrl ||
                env?.LOCALAI_BASE_URL ||
                process.env.LOCALAI_BASE_URL ||
                'http://localhost:8080/v1';
        this.config = config || {};
        this.id = id ? () => id : this.id;
    }
    id() {
        return `localai:${this.modelName}`;
    }
    toString() {
        return `[LocalAI Provider ${this.modelName}]`;
    }
    // @ts-ignore: Prompt is not used in this implementation
    async callApi(prompt) {
        throw new Error('Not implemented');
    }
}
class LocalAiChatProvider extends LocalAiGenericProvider {
    async callApi(prompt) {
        const messages = (0, shared_1.parseChatPrompt)(prompt, [{ role: 'user', content: prompt }]);
        const body = {
            model: this.modelName,
            messages: messages,
            temperature: this.config.temperature || process.env.LOCALAI_TEMPERATURE || 0.7,
        };
        logger_1.default.debug(`Calling LocalAI API: ${JSON.stringify(body)}`);
        let data, cached = false;
        try {
            ({ data, cached } = (await (0, cache_1.fetchWithCache)(`${this.apiBaseUrl}/chat/completions`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(body),
            }, shared_1.REQUEST_TIMEOUT_MS)));
        }
        catch (err) {
            return {
                error: `API call error: ${String(err)}`,
            };
        }
        logger_1.default.debug(`\tLocalAI API chat completions response: ${JSON.stringify(data)}`);
        try {
            return {
                output: data.choices[0].message.content,
            };
        }
        catch (err) {
            return {
                error: `API response error: ${String(err)}: ${JSON.stringify(data)}`,
            };
        }
    }
}
exports.LocalAiChatProvider = LocalAiChatProvider;
class LocalAiEmbeddingProvider extends LocalAiGenericProvider {
    async callEmbeddingApi(text) {
        const body = {
            input: text,
            model: this.modelName,
        };
        let data, cached = false;
        try {
            ({ data, cached } = (await (0, cache_1.fetchWithCache)(`${this.apiBaseUrl}/embeddings`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(body),
            }, shared_1.REQUEST_TIMEOUT_MS)));
        }
        catch (err) {
            return {
                error: `API call error: ${String(err)}`,
            };
        }
        logger_1.default.debug(`\tLocalAI embeddings API response: ${JSON.stringify(data)}`);
        try {
            const embedding = data?.data?.[0]?.embedding;
            if (!embedding) {
                throw new Error('No embedding found in LocalAI embeddings API response');
            }
            return {
                embedding,
            };
        }
        catch (err) {
            return {
                error: `API response error: ${String(err)}: ${JSON.stringify(data)}`,
            };
        }
    }
}
exports.LocalAiEmbeddingProvider = LocalAiEmbeddingProvider;
class LocalAiCompletionProvider extends LocalAiGenericProvider {
    async callApi(prompt) {
        const body = {
            model: this.modelName,
            prompt,
            temperature: this.config.temperature || process.env.LOCALAI_TEMPERATURE || 0.7,
        };
        logger_1.default.debug(`Calling LocalAI API: ${JSON.stringify(body)}`);
        let data, cached = false;
        try {
            ({ data, cached } = (await (0, cache_1.fetchWithCache)(`${this.apiBaseUrl}/completions`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(body),
            }, shared_1.REQUEST_TIMEOUT_MS)));
        }
        catch (err) {
            return {
                error: `API call error: ${String(err)}`,
            };
        }
        logger_1.default.debug(`\tLocalAI completions API response: ${JSON.stringify(data)}`);
        try {
            return {
                output: data.choices[0].text,
            };
        }
        catch (err) {
            return {
                error: `API response error: ${String(err)}: ${JSON.stringify(data)}`,
            };
        }
    }
}
exports.LocalAiCompletionProvider = LocalAiCompletionProvider;
//# sourceMappingURL=localai.js.map