-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
47 lines (38 loc) Β· 1.26 KB
/
server.js
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
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const cors = require('cors');
const dotenv = require('dotenv');
const { Configuration, OpenAIApi } = require('openai');
// import OpenAI from "openai";
dotenv.config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(bodyParser.json());
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
// Serve static files from root
app.use(express.static(path.join(__dirname, '/')));
app.post('/chat', async (req, res) => {
const userMessage = req.body.message;
try {
const response = await openai.createChatCompletion({
model: "gpt-3.5-turbo",
messages: [
{ role: "system", content: "You are Tom Riddle." },
{ role: "user", content: userMessage }
],
});
const reply = response.data.choices[0].message.content;
res.json({ response: reply });
} catch (error) {
console.error('Error:', error);
res.status(500).json({ error: 'An error occurred' });
}
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});