This repository has been archived by the owner on Feb 17, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
289 lines (237 loc) · 10.6 KB
/
app.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
const express = require('express');
const bodyParser = require('body-parser');
const axios = require('axios');
const crypto = require('crypto');
const cors = require('cors');
const { Configuration, OpenAIApi } = require("openai");
const { promisify } = require('util');
const natural = require('natural');
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
require('dotenv').config();
const app = express();
openai.apiKey = process.env.OPENAI_API_KEY;
// Log all calls and request for debugging
app.use((req, res, next) => {
console.log('Received request:', req.method, req.url, req.body);
const originalSend = res.send;
res.send = function (body) {
console.log('Sending response:', res.statusCode, body);
originalSend.call(res, body);
};
next();
});
// Use Index.html as a default landing page
app.get('/', function(req, res){
res.sendFile('index.html', { root: __dirname + "/" } );
});
// CORS to pass the Access Control Check
app.use(cors({
origin: 'https://reco-ai.cyclic.app/'
}));
// If the request is from facebook Verify it
function verifyRequestSignature(req, res, buf) {
const signature = req.headers['x-hub-signature'];
// Check if the request is not coming from Facebook
if (req.headers['user-agent'] !== 'facebookexternalhit/1.1') {
return;
}
if (!signature) {
throw new Error('Signature not present in request headers');
}
const [algorithm, signatureHash] = signature.split('=');
const expectedHash = crypto.createHmac(algorithm, process.env.APP_SECRET)
.update(buf)
.digest('hex');
if (!crypto.timingSafeEqual(Buffer.from(signatureHash), Buffer.from(expectedHash))) {
throw new Error('Could not validate the request signature.');
}
}
// Use the body-parser middleware and verify request signature
app.use(bodyParser.json({ verify: verifyRequestSignature }));
// Caching for faster processing
const cache = {};
// Webhook for receiving messages from Facebook Messenger
app.post('/webhook', async (req, res) => {
try {
const { object, entry: entries, standby } = req.body;
// Function to check if a message is from the user
const isUserMessage = (message) => {
return message.message && message.message.text && !message.message.is_echo;
}
// Function to request thread ownership for a conversation
const requestThreadOwnership = async (recipientId) => {
try {
const response = await axios.post(
`https://graph.facebook.com/v16.0/me/take_thread_control?access_token=${process.env.PAGE_ACCESS_TOKEN}`,
{
recipient: {
id: recipientId,
},
metadata: 'Requesting thread ownership for standby event',
}
);
console.log('Requested thread ownership:', response.data);
} catch (error) {
console.error('Error requesting thread ownership:', error);
}
}
// Check if the request is a standby event
if (object === 'page' && standby) {
console.log('Received standby event:', standby);
// Check if there are user queries/questions in the standby event
if (standby.some(isUserMessage)) {
const userMsg = standby.find(isUserMessage).message.text;
const userId = standby[0].sender.id;
// Request thread ownership for the conversation
await requestThreadOwnership(userId);
// Check cache for previous response
if (cache[userId] && cache[userId].msg === userMsg) {
console.log('Response found in cache:', cache[userId].response);
await sendResponse(userId, cache[userId].response);
} else {
// Get user message and send it to ChatGPT for processing
const response = await generateResponse(userMsg);
// Send response back to user via Facebook Messenger API
await sendResponse(userId, response);
// Store response in cache
cache[userId] = { msg: userMsg, response };
console.log('Sent response to standby event.');
}
} else {
res.sendStatus(200);
console.log('No user query/message found in the standby event.');
}
}
// Check if the request is a regular message event or a message in standby channel
else if (object === 'page' && entries) {
const messaging = entries[0].messaging;
// Add a check to make sure that messaging exists and is an array.
if (Array.isArray(messaging)) {
await Promise.all(messaging.map(async (message) => {
if (isUserMessage(message)) {
const userMsg = message.message.text;
const userId = message.sender.id;
// Check cache for previous response
if (cache[userId] && cache[userId].msg === userMsg) {
console.log('Response found in cache:', cache[userId].response);
await sendResponse(userId, cache[userId].response);
} else {
// Get user message and send it to ChatGPT for processing
const response = await generateResponse(userMsg);
// Send response back to user via Facebook Messenger API
await sendResponse(userId, response);
// Store response in cache
cache[userId] = { msg: userMsg, response };
}
}
}));
}
res.sendStatus(200);
}
else {
res.sendStatus(404);
return;
}
} catch (error) {
console.error(error);
res.sendStatus(500);
}
});
// API Endpoint for OpenAI Communication
app.post('/api/message', async (req, res) => {
try {
const { message } = req.body.object || {};
// Check if message is present in request body
if (!message) {
return res.status(400).json({ error: 'Message is missing from request body.' });
}
// Validate message
if (typeof message !== 'string' || message.trim().length === 0) {
return res.status(400).json({ error: 'Invalid message format.' });
}
// Generate response
const response = await generateResponse(message);
res.json({ success: true, response });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Failed to generate response.' });
}
});
// Define a global variables
let conversationHistory = "";
const stopwords = ['a', 'an', 'the', 'in', 'on', 'at', 'to', 'of', 'for', 'with', 'is', 'are'];
const greetingClassifier = new natural.BayesClassifier();
// Train the greeting classifier
greetingClassifier.addDocument('hello', 'greeting');
greetingClassifier.addDocument('hi', 'greeting');
greetingClassifier.addDocument('hey', 'greeting');
greetingClassifier.addDocument('good morning', 'greeting');
greetingClassifier.addDocument('good afternoon', 'greeting');
greetingClassifier.addDocument('good evening', 'greeting');
greetingClassifier.train();
// Generate responses using OpenAI
async function generateResponse(message, conversationHistory) {
try {
// Define the prompt for OpenAI API
const prompt = "Act as Reco, you are a friendly and enthusiastic mathematical assistant. Your goal is to answer Grade 10 Mathematical problems with accuracy and reliability . You should focus on topics covered in the K-12 curriculum, specifically Grade 10 mathematics lessons.\n\nIf the questions falls outside the scope of Grade 10 mathematics, then respectfully decline to answer and ask for another response. Take note that if the questions are greetings, then reply with a greeting.\n\nMake sure to analyze the queries carefully. Pay attention to entry and exit words in the query of the respondent to improve the conversation flow and make the conversation Human-Like as possible.\n\n";
// Classify the intent of the user's message
const greetingProbability = greetingClassifier.getClassifications(message.toLowerCase())[0].value;
const isGreeting = greetingProbability > 0.7;
// If the message is not a greeting, assume it is a query and send to OpenAI for processing
if (!isGreeting || (!message.toLowerCase().startsWith("hello") && !message.toLowerCase().startsWith("hi") && !message.toLowerCase().startsWith("hey") && !message.toLowerCase().startsWith("good morning") && !message.toLowerCase().startsWith("good afternoon") && !message.toLowerCase().startsWith("good evening"))) {
const completions = await openai.createCompletion({
model: "text-davinci-003",
prompt: prompt + message,
temperature: 0.5,
max_tokens: 1024,
top_p: 1,
frequency_penalty: 0.05,
presence_penalty: 0.05,
});
// Check if API response is valid
if (!completions || completions.status !== 200 || !completions.data || !completions.data.choices || !completions.data.choices[0]) {
console.log('OpenAI API response:', completions);
throw new Error(`Failed to generate response. Status: ${completions.status}. Data: ${JSON.stringify(completions.data)}`);
}
// Extract response text from API response
const responseText = completions.data.choices[0].text.trim();
return responseText;
} else {
// If message is a greeting, add a personalized message
const personalizedGreeting = `Hello! I'm ReCo, your math teacher. How can I assist you with your math questions today?`;
return personalizedGreeting;
}
} catch (err) {
console.error(err);
throw new Error('Failed to generate response');
}
}
// Send response back to user via Facebook Messenger API
async function sendResponse(recipientId, response) {
try {
// Check if recipient ID is valid
const recipientResponse = await axios.get(`https://graph.facebook.com/v16.0/${recipientId}?fields=name&access_token=${process.env.PAGE_ACCESS_TOKEN}`);
if (recipientResponse.status !== 200 || !recipientResponse.data.name) {
console.log(`Invalid recipient ID: ${recipientId}`);
return;
}
// Send message
const messageResponse = await axios.post(`https://graph.facebook.com/v16.0/me/messages?access_token=${process.env.PAGE_ACCESS_TOKEN}`, {
messaging_type: 'RESPONSE',
recipient: {
id: recipientId,
},
message: {
text: response,
},
});
return messageResponse.data;
} catch (error) {
console.error(`Error sending message: ${error}`);
}
}
// Start the server
app.listen(process.env.PORT || 3000, () => console.log('Webhook is listening!'));