import unirest from 'unirest'; async function chatWithAI(messages) { const controller = new AbortController(); const timeout = setTimeout(() => { controller.abort(); }, 900000); // 15 minutes timeout return new Promise((resolve, reject) => { const req = unirest.post(`http://${process.env.ROOT_IP}:${process.env.ROOT_PORT}/v1/chat/completions`) .headers({ 'accept': 'application/json', 'Content-Type': 'application/json' }) .send({ messages, max_tokens: Number(process.env.MAX_TOKENS), // add the max_tokens parameter here repeat_penalty: Number(process.env.REPEAT_PENALTY) }) .end(response => { clearTimeout(timeout); if (response.error) { console.error(response.error); reject("An error occurred while processing your request. Please try again later."); // Generic error message } else { const choice = response.body.choices[0]; resolve(choice.message.content); } }); controller.signal.addEventListener('abort', () => { req.abort(); reject("Request timed out."); }); }); } function getResponseMessage(content) { const conversation = { messages: [ { role: 'user', content: process.env.INIT_PROMPT }, { role: 'user', content: content } ] }; return chatWithAI(conversation.messages).then(response => { if (response && response.trim()) { const limit = 1980; if (response.length > limit) { const chunks = response.match(new RegExp(`.{1,${limit}}`, 'g')); if (chunks.length >= 15) return "Response chunks too large. Try again."; return chunks.join('\n\n'); } else { return response.replace("@", ""); } } else { return "I didn't understand that. Can you please rephrase?"; // Generic empty response message } }); } export default { handler: function(bot, args, message) { const userMessage = args.join(' ').replace('!ai', '').trim(); // Combine all args to form the user's message and remove !ai console.log(`Processed message: ${userMessage}`); // Log environment variables for debugging console.log(`ROOT_IP: ${process.env.ROOT_IP}`); console.log(`ROOT_PORT: ${process.env.ROOT_PORT}`); getResponseMessage(userMessage).then(response => { bot.sendMessage(response); }).catch(error => { bot.sendMessage(error); }); } };