const express = require(‘express’);
const axios = require(‘axios’);
const app = express();
app.use(express.json());
const OPENAI_API_KEY = ‘your-api-key’;
app.post(‘/chat’, async (req, res) => {
const userMessage = req.body.message;
try {
const response = await axios.post(‘https://api.openai.com/v1/chat/completions’, {
model: “gpt-4”,
messages: [{ role: “user”, content: userMessage }],
}, {
headers: {
‘Authorization’: `Bearer ${OPENAI_API_KEY}`,
}
});
res.json({ reply: response.data.choices[0].message.content });
} catch (error) {
res.status(500).send(“Error connecting to GPT API”);
}
});
app.listen(3000, () => console.log(‘Chat server running on http://localhost:3000’));