Spaces:
Paused
Paused
File size: 6,122 Bytes
8de10f9 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 |
import { promises as fs } from 'fs';
import path from 'path';
import fetch from 'node-fetch';
import pkg from '@whiskeysockets/baileys';
const { generateWAMessageFromContent, proto } = pkg;
import config from '../../config.cjs';
const __filename = new URL(import.meta.url).pathname;
const __dirname = path.dirname(__filename);
const chatHistoryFile = path.resolve(__dirname, '../mistral_history.json');
const mistralSystemPrompt = "you are a good assistant.";
async function readChatHistoryFromFile() {
try {
const data = await fs.readFile(chatHistoryFile, "utf-8");
return JSON.parse(data);
} catch (err) {
return {};
}
}
async function writeChatHistoryToFile(chatHistory) {
try {
await fs.writeFile(chatHistoryFile, JSON.stringify(chatHistory, null, 2));
} catch (err) {
console.error('Error writing chat history to file:', err);
}
}
async function updateChatHistory(chatHistory, sender, message) {
if (!chatHistory[sender]) {
chatHistory[sender] = [];
}
chatHistory[sender].push(message);
if (chatHistory[sender].length > 20) {
chatHistory[sender].shift();
}
await writeChatHistoryToFile(chatHistory);
}
async function deleteChatHistory(chatHistory, userId) {
delete chatHistory[userId];
await writeChatHistoryToFile(chatHistory);
}
const mistral = async (m, Matrix) => {
const chatHistory = await readChatHistoryFromFile();
const text = m.body.toLowerCase();
if (text === "/forget") {
await deleteChatHistory(chatHistory, m.sender);
await Matrix.sendMessage(m.from, { text: 'Conversation deleted successfully' }, { quoted: m });
return;
}
const prefix = config.PREFIX;
const cmd = m.body.startsWith(prefix) ? m.body.slice(prefix.length).split(' ')[0].toLowerCase() : '';
const prompt = m.body.slice(prefix.length + cmd.length).trim();
const validCommands = ['ai', 'gpt', 'mistral'];
if (validCommands.includes(cmd)) {
if (!prompt) {
await Matrix.sendMessage(m.from, { text: 'Please give me a prompt' }, { quoted: m });
return;
}
try {
const senderChatHistory = chatHistory[m.sender] || [];
const messages = [
{ role: "system", content: mistralSystemPrompt },
...senderChatHistory,
{ role: "user", content: prompt }
];
await m.React("⏳");
const response = await fetch('https://matrixcoder.tech/api/ai', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
type: "text-generation",
model: "hf/meta-llama/meta-llama-3-8b-instruct",
messages: messages
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const responseData = await response.json();
await updateChatHistory(chatHistory, m.sender, { role: "user", content: prompt });
await updateChatHistory(chatHistory, m.sender, { role: "assistant", content: responseData.result.response });
const answer = responseData.result.response;
const codeMatch = answer.match(/```([\s\S]*?)```/);
if (codeMatch) {
const code = codeMatch[1];
let msg = generateWAMessageFromContent(m.from, {
viewOnceMessage: {
message: {
messageContextInfo: {
deviceListMetadata: {},
deviceListMetadataVersion: 2
},
interactiveMessage: proto.Message.InteractiveMessage.create({
body: proto.Message.InteractiveMessage.Body.create({
text: answer
}),
footer: proto.Message.InteractiveMessage.Footer.create({
text: "> © ᴘᴏᴡᴇʀᴇᴅ ʙʏ ᴇᴛʜɪx-ᴍᴅ"
}),
header: proto.Message.InteractiveMessage.Header.create({
title: "",
subtitle: "",
hasMediaAttachment: false
}),
nativeFlowMessage: proto.Message.InteractiveMessage.NativeFlowMessage.create({
buttons: [
{
name: "cta_copy",
buttonParamsJson: JSON.stringify({
display_text: "Copy Your Code",
id: "copy_code",
copy_code: code
})
}
]
})
})
}
}
}, {});
await Matrix.relayMessage(msg.key.remoteJid, msg.message, {
messageId: msg.key.id
});
} else {
await Matrix.sendMessage(m.from, { text: answer }, { quoted: m });
}
await m.React("✅");
} catch (err) {
await Matrix.sendMessage(m.from, { text: "Something went wrong" }, { quoted: m });
console.error('Error: ', err);
await m.React("❌");
}
}
};
export default mistral;
|