-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
187 lines (160 loc) · 4.74 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
require('dotenv').config();
const express = require('express');
const { Sequelize, DataTypes } = require('sequelize');
const OpenAI = require('openai');
const axios = require('axios');
const nodemailer = require('nodemailer');
const cors = require('cors');
const path = require('path');
const app = express();
const port = process.env.PORT || 3000;
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
// Database setup
const sequelize = new Sequelize({
dialect: 'sqlite',
storage: './database.sqlite'
});
const Conversation = sequelize.define('Conversation', {
userId: {
type: DataTypes.STRING,
allowNull: false
},
messages: {
type: DataTypes.TEXT,
allowNull: false,
get() {
return JSON.parse(this.getDataValue('messages'));
},
set(value) {
this.setDataValue('messages', JSON.stringify(value));
}
}
});
sequelize.sync();
// OpenAI setup
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY
});
async function getChatbotResponse(messages) {
const response = await openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages: messages,
functions: [
{
name: "get_room_options",
description: "Get available room options",
parameters: {
type: "object",
properties: {},
required: []
}
},
{
name: "book_room",
description: "Book a room",
parameters: {
type: "object",
properties: {
roomId: { type: "integer" },
fullName: { type: "string" },
email: { type: "string" },
nights: { type: "integer" }
},
required: ["roomId", "fullName", "email", "nights"]
}
}
],
function_call: "auto"
});
return response.choices[0].message;
}
// Hotel API functions
async function getRoomOptions() {
try {
const response = await axios.get('https://bot9assignement.deno.dev/rooms');
return response.data;
} catch (error) {
console.error('Error fetching room options:', error);
throw error;
}
}
async function bookRoom(bookingDetails) {
try {
const response = await axios.post('https://bot9assignement.deno.dev/book', bookingDetails);
// Send email to the user
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASSWORD
}
});
const mailOptions = {
from: '[email protected]',
to: bookingDetails.email,
subject: 'Hotel Booking Confirmation',
text: `
Here are the details of your booking:
Room ID: ${bookingDetails.roomId}
Room Name: ${response.data.name}
Full Name: ${bookingDetails.fullName}
Email: ${bookingDetails.email}
Nights: ${bookingDetails.nights}
Total Cost: $${response.data.price * bookingDetails.nights}
`
};
await transporter.sendMail(mailOptions);
return response.data;
} catch (error) {
console.error('Error booking room:', error);
throw error;
}
}
// Main chat endpoint
app.post('/chat', async (req, res) => {
try {
const { userId, message } = req.body;
let conversation = await Conversation.findOne({ where: { userId } });
if (!conversation) {
conversation = await Conversation.create({ userId, messages: [] });
}
const messages = conversation.messages;
messages.push({ role: 'user', content: message });
const botResponse = await getChatbotResponse(messages);
if (botResponse.function_call) {
const functionName = botResponse.function_call.name;
const functionArgs = JSON.parse(botResponse.function_call.arguments);
let functionResult;
if (functionName === 'get_room_options') {
functionResult = await getRoomOptions();
} else if (functionName === 'book_room') {
functionResult = await bookRoom(functionArgs);
}
messages.push(botResponse);
messages.push({
role: 'function',
name: functionName,
content: JSON.stringify(functionResult)
});
const finalResponse = await getChatbotResponse(messages);
messages.push(finalResponse);
} else {
messages.push(botResponse);
}
await conversation.update({ messages });
const responseText = messages[messages.length - 1].content;
res.json({ response: responseText });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'An error occurred while processing your request.' });
}
});
// Serve the main page
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});