-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
62 lines (47 loc) · 1.84 KB
/
index.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const { OpenAI } = require('openai');
const ejs = require('ejs');
const path = require('path');
require('dotenv').config(); // Load environment variables from .env file
const app = express();
const port = process.env.PORT || 3000;
// Initialize OpenAI client with API key from .env
const openai = new OpenAI({
apiKey: process.env.API_KEY, // Use environment variable for API key
});
app.use(express.static("public"));
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views")); // Ensure the correct path to views
app.use(cors());
app.use(bodyParser.json());
app.get('/', (req, res) => res.render('pages/home'));
app.get('/about', (req, res) => res.render('pages/about'));
app.get('/contact', (req, res) => res.render('pages/contact'));
// In-memory conversation history storage
let conversationHistory = [];
app.post('/chat', async (req, res) => {
const userMessage = req.body.message;
// Add user message to history
conversationHistory.push({ role: 'user', content: userMessage });
try {
const response = await openai.chat.completions.create({
model: 'gpt-3.5-turbo',
messages: conversationHistory,
max_tokens: 150,
});
const botResponse = response.choices[0].message.content.trim();
// Add bot response to history
conversationHistory.push({ role: 'assistant', content: botResponse });
res.json({ response: botResponse });
} catch (error) {
console.error('Error:', error);
res.status(500).json({ error: 'Something went wrong with the API request' });
}
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
// Export the app (no app.listen())
module.exports = app;