From e1adede7c34fbb16b9367e3d8d6d21c7d88f2ca4 Mon Sep 17 00:00:00 2001 From: Raven Scott Date: Sat, 8 Jun 2024 19:06:25 -0400 Subject: [PATCH] update gitignore --- .gitignore | 1 + chatBot/commands/ai.js | 77 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 chatBot/commands/ai.js diff --git a/.gitignore b/.gitignore index 13abed9..cac78ed 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ shared-storage storage_* storage chatBot/.env +commands/ai.js \ No newline at end of file diff --git a/chatBot/commands/ai.js b/chatBot/commands/ai.js new file mode 100644 index 0000000..8afe960 --- /dev/null +++ b/chatBot/commands/ai.js @@ -0,0 +1,77 @@ +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); + }); + } +};