-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
79 lines (64 loc) · 2.44 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const OpenAI = require("openai");
const twilio = require('twilio');
const {
initializeDatabase,
getConversationHistory,
updateConversationHistory
} = require('./conversationManager');
// Initialize Express and middleware
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
const PORT = process.env.PORT || 3000;
// Setup Twilio Client
const twilioClient = twilio(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);
// Setup OpenAI
const openai = new OpenAI(process.env.OPENAI_API_KEY);
// initialise the database
initializeDatabase();
app.get('/', (req, res) => {
res.send('WhatsGPT is running');
});
// Endpoint that Twilio will post to
app.post('/message', async (req, res) => {
const userId = req.body.From;
const incomingMsg = req.body.Body;
try {
// Retrieve conversation history for the user
let conversationHistory = await getConversationHistory(userId);
// Add the incoming message to the conversation history
conversationHistory.push({ role: "user", content: incomingMsg });
// Send the message to OpenAI API
const openaiResponse = await openai.chat.completions.create({
messages: [{
role: "system",
content: "You're a knowledgeable friend that your acquintances turn to for help. Your response should be brief. Use a single sentence if possible."
},
...conversationHistory],
model: "gpt-3.5-turbo",
});
// Extract the text from the OpenAI response
const message = openaiResponse.choices[0].message.content;
// Update conversation history with OpenAI's response
conversationHistory.push({ role: "assistant", content: message });
updateConversationHistory(userId, conversationHistory);
// Send the message back to the user on WhatsApp
await twilioClient.messages.create({
body: message,
from: process.env.TWILIO_WHATSAPP_NUMBER,
to: req.body.From
});
// Send a 200 response to Twilio
res.status(200).end();
} catch (error) {
console.error(error);
res.status(500).send("Internal Server Error");
}
});
module.exports = app;
// Start the server
if (require.main === module) {
app.listen(PORT, () => console.log(`Server is running on port ${PORT}`));
}