-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
106 lines (91 loc) · 3.79 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
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
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config({ path: 'environment.env' })
}
const mysql = require('mysql2/promise')
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
ssl: { rejectUnauthorized: true },
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
})
const express = require('express')
const app = express()
app.use(express.static('public'))
app.use(express.json())
// Start the server
const port = process.env.PORT || 3000
app.listen(port, '0.0.0.0', () => {
})
app.post('/submit-user-info', async (req, res) => {
const { name, age, gender, email, phone, contactTime } = req.body
// Process the input to handle empty strings for age, gender, and contactTime
const processedAge = age !== '' ? parseInt(age, 10) : null
const processedGender = gender !== '' ? gender : null
const processedContactTime = contactTime !== '' ? contactTime : null
try {
const query = 'INSERT INTO users (name, age, gender, email, phone, contactTime) VALUES (?, ?, ?, ?, ?, ?)'
const values = [name, processedAge, processedGender, email, phone, processedContactTime]
// Use the pool to execute your query
const [result] = await pool.execute(query, values)
res.json({ success: true, message: 'User info submitted successfully', result })
} catch (error) {
// Check if the error is due to a duplicate entry
if (error.code === 'ER_DUP_ENTRY' || error.sqlState === '23000') {
// Treat duplicate entry as a success for the user's perspective
console.log('Duplicate user info submission, treating as successful:', error)
res.json({ success: true, message: 'User info already submitted', result: {} })
} else {
// Handle other errors normally
console.error('Error inserting user info into database:', error)
res.status(500).json({ success: false, message: 'Error submitting user info', error: error.message })
}
}
})
const OpenAI = require('openai')
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY
})
async function handleChatMessage (req, res) {
// Prepare context and user message
const context = 'As an expert in the field of physical therapy, respond to the following message through the lens of a physical therapist. Be simple, clear, and concise in your resonses, and make them easy to read and take action on. Always end your response with a followup question relevant to their situation.'
const userMessage = req.body.message
const requestBody = {
messages: [
{
role: 'system',
content: context
},
{
role: 'user',
content: userMessage
}
],
model: 'gpt-3.5-turbo-0125',
n: 1
}
try {
const completion = await openai.chat.completions.create(requestBody)
const aiResponse = completion.choices[0].message.content
res.json({ message: aiResponse })
} catch (error) {
if (error.response && error.response.data) {
if (error.response.data.error.code === 'rate_limit_reached') {
res.status(503).json({ message: "I'm getting too many requests right now. Please try again in a few minutes." })
} else if (error.response.data.error.code === 'model_unavailable') {
res.status(503).json({ message: 'The requested model is unavailable currently. Please try another model or come back later.' })
} else {
console.error('Error communicating with OpenAI:', error)
res.status(500).json({ message: 'Something went wrong. Please try again later.' })
}
} else {
console.error('Error communicating with OpenAI:', error)
res.status(500).json({ message: 'Something went wrong. Please try again later.' })
}
}
}
// Route Handler
app.post('/chat-message', handleChatMessage)