const express = require('express');
const OpenAI = require('openai').default;
const app = express();
const port = 3000;
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
app.use(express.json());
app.post('/api/send', async (req, res) => {
console.log("Received request with body:", req.body);
try {
const chatCompletion = await openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages: [{ role: 'user', content: req.body.message }],
});
console.log("OpenAI API full response:", chatCompletion);
if (chatCompletion.data && chatCompletion.data.choices) {
const firstChoice = chatCompletion.data.choices[0];
console.log("First choice message object:", firstChoice.message);
res.status(200).json({ response: firstChoice.message.content });
} else {
console.error('Unexpected response structure from OpenAI:', chatCompletion);
res.status(500).send('Error: Unexpected response structure from OpenAI');
}
} catch (error) {
console.error('Error processing request:', error);
res.status(500).send('Error processing your request');
}
});
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});
Check the type of object you are receiving and its structure right before the line where the error happens.