-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
272 lines (240 loc) · 8.58 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
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
const express = require('express');
const bodyParser = require('body-parser');
const axios = require('axios');
const dotenv = require('dotenv');
const { Sequelize, DataTypes } = require('sequelize');
const OpenAI = require("openai");
const cors = require('cors');
dotenv.config();
const app = express();
const port = process.env.PORT || 5001;
// Middleware
app.use(cors());
app.use(bodyParser.json());
// Environment variables
const ROOMS_API = process.env.ROOMS_API || 'https://bot9assignement.deno.dev/rooms';
const BOOKING_API = process.env.BOOKING_API || 'https://bot9assignement.deno.dev/book';
// 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.JSON,
allowNull: false
},
bookingState: {
type: DataTypes.JSON,
allowNull: true
}
});
sequelize.sync({ force: true }).then(() => {
console.log('Database & tables created!');
});
// OpenAI configuration
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
// Input validation middleware
const validateChatInput = (req, res, next) => {
const { message, userId } = req.body;
if (!message || !userId) {
return res.status(400).json({ error: 'Missing required fields' });
}
next();
};
// Routes
app.get('/', (req, res) => {
res.send('Welcome to my hotel booking chatbot API.');
});
app.post('/chat', validateChatInput, async (req, res) => {
const { message, userId } = req.body;
try {
// Fetch or create conversation
let conversation = await Conversation.findOne({ where: { userId } });
if (!conversation) {
conversation = await Conversation.create({
userId,
messages: [],
bookingState: {
stage: 'initial',
fullName: null,
email: null,
checkInDate: null,
nights: null,
selectedRoomId: null
}
});
}
// Add user message to conversation
conversation.messages.push({ role: 'user', content: message });
// Prepare system message based on booking state
const systemMessage = generateSystemMessage(conversation.bookingState);
// Call OpenAI API
const completion = await openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages: [
{ role: "system", content: systemMessage },
...conversation.messages
],
functions: [
{
name: "get_room_options",
description: "Get available room options from the hotel",
parameters: {
type: "object",
properties: {},
required: []
}
},
{
name: "book_room",
description: "Book a room at the hotel",
parameters: {
type: "object",
properties: {
roomId: { type: "number" },
fullName: { type: "string" },
email: { type: "string" },
checkInDate: { type: "string" },
nights: { type: "number" }
},
required: ["roomId", "fullName", "email", "checkInDate", "nights"]
}
}
]
});
let aiResponse = completion.choices[0].message;
// Handle function calls
if (aiResponse.function_call) {
const functionName = aiResponse.function_call.name;
const functionArgs = JSON.parse(aiResponse.function_call.arguments);
if (functionName === 'get_room_options') {
const roomOptions = await axios.get(ROOMS_API);
aiResponse = { role: 'function', content: JSON.stringify(roomOptions.data) };
} else if (functionName === 'book_room') {
const bookingResult = await axios.post(BOOKING_API, functionArgs);
aiResponse = { role: 'function', content: JSON.stringify(bookingResult.data) };
// Reset booking state after successful booking
conversation.bookingState = {
stage: 'initial',
fullName: null,
email: null,
checkInDate: null,
nights: null,
selectedRoomId: null
};
}
} else {
// Update booking state based on AI response
updateBookingState(conversation.bookingState, aiResponse.content);
// Update booking stage
updateBookingStage(conversation.bookingState);
}
// Add AI response to conversation and save
conversation.messages.push(aiResponse);
await conversation.save();
res.json({ reply: aiResponse.content });
} catch (error) {
console.error('Error processing message:', error);
if (error.response) {
res.status(error.response.status).json({ error: error.response.data });
} else if (error.request) {
res.status(503).json({ error: 'Service unavailable' });
} else {
res.status(500).json({ error: 'Internal server error' });
}
}
});
function generateSystemMessage(bookingState) {
let systemMessage = `You are a helpful hotel booking assistant. The current booking state is: ${JSON.stringify(bookingState)}.
Guide the user through the booking process in this order:
1. Ask for their name, email, and check-in/check-out dates.
2. Calculate the duration of stay.
3. Show available room options.
4. Confirm booking details.
5. Complete the booking.
Do not repeat information unnecessarily. Make sure the conversation is dynamic and smooth.`;
if (bookingState.fullName) {
systemMessage += ` The user's name is ${bookingState.fullName}.`;
}
if (bookingState.email) {
systemMessage += ` The user's email is ${bookingState.email}.`;
}
if (bookingState.checkInDate) {
systemMessage += ` The check-in date is ${bookingState.checkInDate}.`;
}
if (bookingState.nights) {
systemMessage += ` The duration of stay is ${bookingState.nights} nights.`;
}
return systemMessage;
}
function updateBookingState(bookingState, content) {
if (!bookingState.fullName) {
bookingState.fullName = extractFullName(content);
}
if (!bookingState.email) {
bookingState.email = extractEmail(content);
}
if (!bookingState.checkInDate) {
bookingState.checkInDate = extractDate(content);
}
if (!bookingState.nights) {
bookingState.nights = extractNights(content);
}
if (!bookingState.selectedRoomId) {
bookingState.selectedRoomId = extractRoomId(content);
}
}
function updateBookingStage(bookingState) {
if (bookingState.fullName && bookingState.email && bookingState.checkInDate && bookingState.nights) {
bookingState.stage = 'ready_to_book';
} else if (bookingState.fullName || bookingState.email || bookingState.checkInDate || bookingState.nights) {
bookingState.stage = 'collecting_info';
} else {
bookingState.stage = 'initial';
}
}
function extractFullName(content) {
const fullNameMatch = content.match(/My name is (.*)|I am (.*)/);
if (fullNameMatch) {
return fullNameMatch[1].trim();
}
return null;
}
function extractEmail(content) {
const emailMatch = content.match(/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/);
if (emailMatch) {
return emailMatch[1];
}
return null;
}
function extractDate(content) {
const dateMatch = content.match(/\d{4}-\d{2}-\d{2}|\d{2}\/\d{2}\/\d{4}/);
if (dateMatch) {
return dateMatch[0];
}
return null;
}
function extractNights(content) {
const nightsMatch = content.match(/\d+ night(s)?/);
if (nightsMatch) {
return parseInt(nightsMatch[0]);
}
return null;
}
function extractRoomId(content) {
const roomIdMatch = content.match(/room (\d+)/);
if (roomIdMatch) {
return parseInt(roomIdMatch[1]);
}
return null;
}
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});