66 lines
2.4 KiB
JavaScript
66 lines
2.4 KiB
JavaScript
// import axios from 'axios';
|
|
// import Document from '../models/Document.js';
|
|
|
|
// const MISTRAL_API_KEY = process.env.MISTRAL_API_KEY;
|
|
// const MISTRAL_URL = "https://api.mistral.ai/chat/completions";
|
|
|
|
// export const chatWithAI = async (req, res) => {
|
|
// try {
|
|
// const { department, message } = req.body;
|
|
|
|
// // Fetch relevant documents
|
|
// const docs = await Document.find({ department });
|
|
// const context = docs.map(doc => doc.content).join("\n");
|
|
|
|
// // Call Mistral API
|
|
// const response = await axios.post(
|
|
// MISTRAL_URL,
|
|
// {
|
|
// messages: [{ role: "system", content: `You are an AI assistant for ${department} department.` },
|
|
// { role: "user", content: `Based on these documents: ${context} \n User Query: ${message}` }]
|
|
// },
|
|
// { headers: { Authorization: `Bearer ${MISTRAL_API_KEY}` } }
|
|
// );
|
|
|
|
// res.json({ response: response.data.choices[0].message.content });
|
|
// } catch (error) {
|
|
// console.error(error);
|
|
// res.status(500).json({ error: "Error processing the request" });
|
|
// }
|
|
// };
|
|
|
|
import { Mistral } from '@mistralai/mistralai';
|
|
import Document from '../models/Document.js';
|
|
import dotenv from 'dotenv';
|
|
|
|
dotenv.config();
|
|
|
|
|
|
const MISTRAL_API_KEY = process.env.MISTRAL_API_KEY;
|
|
console.log(MISTRAL_API_KEY);
|
|
const client = new Mistral({ apiKey: MISTRAL_API_KEY });
|
|
|
|
export const chatWithAI = async (req, res) => {
|
|
try {
|
|
const { department, message } = req.body;
|
|
|
|
// Fetch relevant documents
|
|
const docs = await Document.find({ department });
|
|
const context = docs.map(doc => doc.content).join("\n");
|
|
|
|
// Call Mistral API
|
|
const chatResponse = await client.chat.complete({
|
|
model: "mistral-large-latest",
|
|
messages: [
|
|
{ role: "system", content: `You are an AI assistant for ${department} department.` },
|
|
{ role: "user", content: `Based on these documents: ${context}\nUser Query: ${message} if you do not have exact information you can give general response of 1 to 1.5 line ` }
|
|
]
|
|
});
|
|
|
|
res.json({ response: chatResponse.choices[0].message.content });
|
|
} catch (error) {
|
|
console.error(error);
|
|
res.status(500).json({ error: "Error processing the request" });
|
|
}
|
|
};
|