const express = require('express');
const cors = require('cors');
const Groq = require('groq-sdk');
const bodyParser = require('body-parser');
require('dotenv').config();
const app = express();
const port = 8080;
app.use(bodyParser.json());
app.use(cors());
const GROQ_API_KEY = "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";
const groq = new Groq({ apiKey: GROQ_API_KEY });
async function getGroqChatCompletion(message) {
return groq.chat.completions.create({
messages: [
{
role: "user",
"content": "Based on the following list of items with their quantities: " + message + ", please provide a concise recipe. There are no dietary restrictions. Begin the response with 'Based on your pantry items, I suggest you make...'. If the list is empty, please display a message encouraging the user to add items to their pantry list. List the ingredients in the format: 'Ingredients: 2 cups of Milk, 3 Eggs, ...'." },
],
model: "llama3-8b-8192",
});
}
app.post('/send-message', (req, res) => {
// Convert the array of items to a string format
const items = req.body.message;
if (Array.isArray(items)) {
storedMessage = items.map(item => `${item.name}: ${item.quantity}`).join(', ');
} else {
storedMessage = items;
}
res.json({ message: 'Message received', data: storedMessage });
});
app.get('/get-recipe', async (req, res) => {
try {
if (!storedMessage) {
return res.status(400).json({ message: 'No message to generate recipe from' });
}
const chatCompletion = await getGroqChatCompletion(storedMessage);
res.json({ content: chatCompletion.choices[0]?.message?.content || "No content" });
} catch (error) {
console.error('Error fetching chat completion:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});