"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GroqProvider = void 0;
const groq_sdk_1 = __importDefault(require("groq-sdk"));
const cache_1 = require("../cache");
const logger_1 = __importDefault(require("../logger"));
const util_1 = require("../util");
const shared_1 = require("./shared");
class GroqProvider {
    constructor(modelName, options = {}) {
        this.id = () => `groq:${this.modelName}`;
        const { config, env } = options;
        this.modelName = modelName;
        this.config = config || {};
        this.apiKey = this.config.apiKey || env?.GROQ_API_KEY || process.env.GROQ_API_KEY;
        this.groq = new groq_sdk_1.default({
            apiKey: this.apiKey,
            maxRetries: 2,
            timeout: shared_1.REQUEST_TIMEOUT_MS,
        });
    }
    getModelName() {
        return this.modelName;
    }
    getApiKey() {
        return this.apiKey;
    }
    toString() {
        return `[Groq Provider ${this.modelName}]`;
    }
    async callApi(prompt, context, options) {
        const messages = [
            {
                role: 'system',
                content: this.config.systemPrompt || 'You are a helpful assistant.',
            },
            ...(0, shared_1.parseChatPrompt)(prompt, [{ role: 'user', content: prompt }]),
        ];
        const params = {
            messages,
            model: this.config.model || this.modelName,
            temperature: this.config.temperature ?? 0.7,
            max_completion_tokens: this.config.max_completion_tokens ?? this.config.max_tokens ?? 1000,
            top_p: this.config.top_p ?? 1,
            tools: this.config.tools ? (0, util_1.maybeLoadFromExternalFile)(this.config.tools) : undefined,
            tool_choice: this.config.tool_choice ?? 'auto',
        };
        if (context?.vars && this.config.tools) {
            params.tools = (0, util_1.maybeLoadFromExternalFile)((0, util_1.renderVarsInObject)(this.config.tools, context.vars));
        }
        const cacheKey = `groq:${JSON.stringify(params)}`;
        if ((0, cache_1.isCacheEnabled)()) {
            const cachedResult = await (0, cache_1.getCache)().get(cacheKey);
            if (cachedResult) {
                logger_1.default.debug(`Returning cached response for ${prompt}: ${JSON.stringify(cachedResult)}`);
                return {
                    ...cachedResult,
                    tokenUsage: {
                        ...cachedResult.tokenUsage,
                        cached: cachedResult.tokenUsage?.total,
                    },
                };
            }
        }
        try {
            const chatCompletion = await this.groq.chat.completions.create(params);
            if (!chatCompletion?.choices?.[0]) {
                throw new Error('Invalid response from Groq API');
            }
            const { message } = chatCompletion.choices[0];
            let output = message.content || '';
            if (message.tool_calls?.length) {
                const toolCalls = message.tool_calls.map((toolCall) => ({
                    id: toolCall.id,
                    type: toolCall.type,
                    function: {
                        name: toolCall.function.name,
                        arguments: toolCall.function.arguments,
                    },
                }));
                output = JSON.stringify(toolCalls);
                // Handle function tool callbacks
                if (this.config.functionToolCallbacks) {
                    for (const toolCall of message.tool_calls) {
                        if (toolCall.function && this.config.functionToolCallbacks[toolCall.function.name]) {
                            const functionResult = await this.config.functionToolCallbacks[toolCall.function.name](toolCall.function.arguments);
                            output += `\n\n[Function Result: ${functionResult}]`;
                        }
                    }
                }
            }
            const result = {
                output,
                tokenUsage: {
                    total: chatCompletion.usage?.total_tokens,
                    prompt: chatCompletion.usage?.prompt_tokens,
                    completion: chatCompletion.usage?.completion_tokens,
                },
            };
            if ((0, cache_1.isCacheEnabled)()) {
                try {
                    await (0, cache_1.getCache)().set(cacheKey, result);
                }
                catch (err) {
                    logger_1.default.error(`Failed to cache response: ${String(err)}`);
                }
            }
            return result;
        }
        catch (err) {
            logger_1.default.error(`Groq API call error: ${err}`);
            const errorMessage = err.status ? `${err.status} ${err.name}: ${err.message}` : `${err}`;
            return { error: `API call error: ${errorMessage}` };
        }
    }
}
exports.GroqProvider = GroqProvider;
//# sourceMappingURL=groq.js.map