"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HuggingfaceRouterChatProvider = void 0;
const logger_1 = __importDefault(require("../logger"));
const cache_1 = require("../cache");
const envars_1 = require("../envars");
const shared_1 = require("./shared");
class HuggingfaceRouterChatProvider {
    constructor(modelName, options = {}) {
        const { id, config } = options;
        this.modelName = modelName;
        this.id = id ? () => id : this.id;
        this.config = config || { stream: false, };
    }
    id() {
        return `huggingface:text-generation:${this.modelName}`;
    }
    toString() {
        return `[Huggingface Router Chat Provider ${this.modelName}]`;
    }
    getApiKey() {
        return this.config.apiKey || (0, envars_1.getEnvString)('HF_TOKEN') || (0, envars_1.getEnvString)('HF_API_TOKEN');
    }
    async callApi(prompt) {
        const url = this.config.apiEndpoint
            ? this.config.apiEndpoint
            : `https://router.huggingface.co/v1/chat/completions`;
        let response;
        try {
            const body = {
                messages: JSON.parse(prompt),
                model: this.modelName,
                stream: this.config.stream || false,
            };
            logger_1.default.debug(`Huggingface Router API request body: ${JSON.stringify(body)}`);
            response = await (0, cache_1.fetchWithCache)(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    ...(this.getApiKey() ? { Authorization: `Bearer ${this.getApiKey()}` } : {}),
                },
                body: JSON.stringify(body),
            }, shared_1.REQUEST_TIMEOUT_MS);
            logger_1.default.debug(`Huggingface Router API response: ${JSON.stringify(response.data)}`);
            if (response.data.error) {
                return {
                    error: ` Huggingface API call error: ${response.data.error}`,
                };
            }
            let data;
            // Handle the response data
            if (typeof response.data === 'string') {
                try {
                    data = JSON.parse(response.data);
                }
                catch {
                    return {
                        error: `Huggingface Router API returned invalid JSON response (status ${response.status}): ${response.data}\n\nRequest body: ${JSON.stringify(body, null, 2)}`,
                    };
                }
            }
            else {
                data = response.data;
            }
            const choice = data.choices?.[0];
            const message = choice?.message;
            let output = message.content;
            try {
                output = JSON.parse(output);
            }
            catch (err) {
                logger_1.default.warn(`Failed to parse JSON output: ${err}. Output was: ${output}`);
            }
            return {
                output,
                tokenUsage: {
                    total: data.usage?.total_tokens,
                    prompt: data.usage?.prompt_tokens,
                    completion: data.usage?.completion_tokens,
                    ...(data.usage?.completion_tokens_details
                        ? {
                            completionDetails: {
                                reasoning: data.usage.completion_tokens_details.reasoning_tokens,
                                acceptedPrediction: data.usage.completion_tokens_details.accepted_prediction_tokens,
                                rejectedPrediction: data.usage.completion_tokens_details.rejected_prediction_tokens,
                                audio: data.usage.completion_tokens_details.audio_tokens,
                            },
                        }
                        : {}),
                },
            };
        }
        catch (err) {
            return {
                error: `Huggingface Router API call error: ${String(err)}. Output:\n${response?.data}`,
            };
        }
    }
}
exports.HuggingfaceRouterChatProvider = HuggingfaceRouterChatProvider;
//# sourceMappingURL=huggingfaceRouter.js.map