-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlex-book-trip lambda function.py
521 lines (417 loc) · 21 KB
/
lex-book-trip lambda function.py
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
"""
This sample demonstrates an implementation of the Lex Code Hook Interface
in order to serve a sample bot which manages reservations for hotel rooms and car rentals.
Bot, Intent, and Slot models which are compatible with this sample can be found in the Lex Console
as part of the 'BookTrip' template.
For instructions on how to set up and test this bot, as well as additional samples,
visit the Lex Getting Started documentation http://docs.aws.amazon.com/lex/latest/dg/getting-started.html.
"""
import json
import datetime
import time
import os
import dateutil.parser
import logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# --- Helpers that build all of the responses ---
def elicit_slot(session_attributes, intent_name, slots, slot_to_elicit, message):
return {
'sessionAttributes': session_attributes,
'dialogAction': {
'type': 'ElicitSlot',
'intentName': intent_name,
'slots': slots,
'slotToElicit': slot_to_elicit,
'message': message
}
}
def confirm_intent(session_attributes, intent_name, slots, message):
return {
'sessionAttributes': session_attributes,
'dialogAction': {
'type': 'ConfirmIntent',
'intentName': intent_name,
'slots': slots,
'message': message
}
}
def close(session_attributes, fulfillment_state, message):
response = {
'sessionAttributes': session_attributes,
'dialogAction': {
'type': 'Close',
'fulfillmentState': fulfillment_state,
'message': message
}
}
return response
def delegate(session_attributes, slots):
return {
'sessionAttributes': session_attributes,
'dialogAction': {
'type': 'Delegate',
'slots': slots
}
}
# --- Helper Functions ---
def safe_int(n):
"""
Safely convert n value to int.
"""
if n is not None:
return int(n)
return n
def try_ex(func):
"""
Call passed in function in try block. If KeyError is encountered return None.
This function is intended to be used to safely access dictionary.
Note that this function would have negative impact on performance.
"""
try:
return func()
except KeyError:
return None
def generate_car_price(location, days, age, car_type):
"""
Generates a number within a reasonable range that might be expected for a flight.
The price is fixed for a given pair of locations.
"""
car_types = ['economy', 'standard', 'midsize', 'full size', 'minivan', 'luxury']
base_location_cost = 0
for i in range(len(location)):
base_location_cost += ord(location.lower()[i]) - 97
age_multiplier = 1.10 if age < 25 else 1
# Select economy is car_type is not found
if car_type not in car_types:
car_type = car_types[0]
return days * ((100 + base_location_cost) + ((car_types.index(car_type.lower()) * 50) * age_multiplier))
def generate_hotel_price(location, nights, room_type):
"""
Generates a number within a reasonable range that might be expected for a hotel.
The price is fixed for a pair of location and roomType.
"""
room_types = ['queen', 'king', 'deluxe']
cost_of_living = 0
for i in range(len(location)):
cost_of_living += ord(location.lower()[i]) - 97
return nights * (100 + cost_of_living + (100 + room_types.index(room_type.lower())))
def isvalid_car_type(car_type):
car_types = ['economy', 'standard', 'midsize', 'full size', 'minivan', 'luxury']
return car_type.lower() in car_types
def isvalid_city(city):
valid_cities = ['new york', 'los angeles', 'chicago', 'houston', 'philadelphia', 'phoenix', 'san antonio',
'san diego', 'dallas', 'san jose', 'austin', 'jacksonville', 'san francisco', 'indianapolis',
'columbus', 'fort worth', 'charlotte', 'detroit', 'el paso', 'seattle', 'denver', 'washington dc',
'memphis', 'boston', 'nashville', 'baltimore', 'portland']
return city.lower() in valid_cities
def isvalid_room_type(room_type):
room_types = ['queen', 'king', 'deluxe']
return room_type.lower() in room_types
def isvalid_date(date):
try:
dateutil.parser.parse(date)
return True
except ValueError:
return False
def get_day_difference(later_date, earlier_date):
later_datetime = dateutil.parser.parse(later_date).date()
earlier_datetime = dateutil.parser.parse(earlier_date).date()
return abs(later_datetime - earlier_datetime).days
def add_days(date, number_of_days):
new_date = dateutil.parser.parse(date).date()
new_date += datetime.timedelta(days=number_of_days)
return new_date.strftime('%Y-%m-%d')
def build_validation_result(isvalid, violated_slot, message_content):
return {
'isValid': isvalid,
'violatedSlot': violated_slot,
'message': {'contentType': 'PlainText', 'content': message_content}
}
def validate_book_car(slots):
pickup_city = try_ex(lambda: slots['PickUpCity'])
pickup_date = try_ex(lambda: slots['PickUpDate'])
return_date = try_ex(lambda: slots['ReturnDate'])
driver_age = safe_int(try_ex(lambda: slots['DriverAge']))
car_type = try_ex(lambda: slots['CarType'])
if pickup_city and not isvalid_city(pickup_city):
return build_validation_result(
False,
'PickUpCity',
'We currently do not support {} as a valid destination. Can you try a different city?'.format(pickup_city)
)
if pickup_date:
if not isvalid_date(pickup_date):
return build_validation_result(False, 'PickUpDate', 'I did not understand your departure date. When would you like to pick up your car rental?')
if datetime.datetime.strptime(pickup_date, '%Y-%m-%d').date() <= datetime.date.today():
return build_validation_result(False, 'PickUpDate', 'Reservations must be scheduled at least one day in advance. Can you try a different date?')
if return_date:
if not isvalid_date(return_date):
return build_validation_result(False, 'ReturnDate', 'I did not understand your return date. When would you like to return your car rental?')
if pickup_date and return_date:
if dateutil.parser.parse(pickup_date) >= dateutil.parser.parse(return_date):
return build_validation_result(False, 'ReturnDate', 'Your return date must be after your pick up date. Can you try a different return date?')
if get_day_difference(pickup_date, return_date) > 30:
return build_validation_result(False, 'ReturnDate', 'You can reserve a car for up to thirty days. Can you try a different return date?')
if driver_age is not None and driver_age < 18:
return build_validation_result(
False,
'DriverAge',
'Your driver must be at least eighteen to rent a car. Can you provide the age of a different driver?'
)
if car_type and not isvalid_car_type(car_type):
return build_validation_result(
False,
'CarType',
'I did not recognize that model. What type of car would you like to rent? '
'Popular cars are economy, midsize, or luxury')
return {'isValid': True}
def validate_hotel(slots):
location = try_ex(lambda: slots['Location'])
checkin_date = try_ex(lambda: slots['CheckInDate'])
nights = safe_int(try_ex(lambda: slots['Nights']))
room_type = try_ex(lambda: slots['RoomType'])
if location and not isvalid_city(location):
return build_validation_result(
False,
'Location',
'We currently do not support {} as a valid destination. Can you try a different city?'.format(location)
)
if checkin_date:
if not isvalid_date(checkin_date):
return build_validation_result(False, 'CheckInDate', 'I did not understand your check in date. When would you like to check in?')
if datetime.datetime.strptime(checkin_date, '%Y-%m-%d').date() <= datetime.date.today():
return build_validation_result(False, 'CheckInDate', 'Reservations must be scheduled at least one day in advance. Can you try a different date?')
if nights is not None and (nights < 1 or nights > 30):
return build_validation_result(
False,
'Nights',
'You can make a reservations for from one to thirty nights. How many nights would you like to stay for?'
)
if room_type and not isvalid_room_type(room_type):
return build_validation_result(False, 'RoomType', 'I did not recognize that room type. Would you like to stay in a queen, king, or deluxe room?')
return {'isValid': True}
""" --- Functions that control the bot's behavior --- """
def book_hotel(intent_request):
"""
Performs dialog management and fulfillment for booking a hotel.
Beyond fulfillment, the implementation for this intent demonstrates the following:
1) Use of elicitSlot in slot validation and re-prompting
2) Use of sessionAttributes to pass information that can be used to guide conversation
"""
location = try_ex(lambda: intent_request['currentIntent']['slots']['Location'])
checkin_date = try_ex(lambda: intent_request['currentIntent']['slots']['CheckInDate'])
nights = safe_int(try_ex(lambda: intent_request['currentIntent']['slots']['Nights']))
room_type = try_ex(lambda: intent_request['currentIntent']['slots']['RoomType'])
session_attributes = intent_request['sessionAttributes'] if intent_request['sessionAttributes'] is not None else {}
# Load confirmation history and track the current reservation.
reservation = json.dumps({
'ReservationType': 'Hotel',
'Location': location,
'RoomType': room_type,
'CheckInDate': checkin_date,
'Nights': nights
})
session_attributes['currentReservation'] = reservation
if intent_request['invocationSource'] == 'DialogCodeHook':
# Validate any slots which have been specified. If any are invalid, re-elicit for their value
validation_result = validate_hotel(intent_request['currentIntent']['slots'])
if not validation_result['isValid']:
slots = intent_request['currentIntent']['slots']
slots[validation_result['violatedSlot']] = None
return elicit_slot(
session_attributes,
intent_request['currentIntent']['name'],
slots,
validation_result['violatedSlot'],
validation_result['message']
)
# Otherwise, let native DM rules determine how to elicit for slots and prompt for confirmation. Pass price
# back in sessionAttributes once it can be calculated; otherwise clear any setting from sessionAttributes.
if location and checkin_date and nights and room_type:
# The price of the hotel has yet to be confirmed.
price = generate_hotel_price(location, nights, room_type)
session_attributes['currentReservationPrice'] = price
else:
try_ex(lambda: session_attributes.pop('currentReservationPrice'))
session_attributes['currentReservation'] = reservation
return delegate(session_attributes, intent_request['currentIntent']['slots'])
# Booking the hotel. In a real application, this would likely involve a call to a backend service.
logger.debug('bookHotel under={}'.format(reservation))
try_ex(lambda: session_attributes.pop('currentReservationPrice'))
try_ex(lambda: session_attributes.pop('currentReservation'))
session_attributes['lastConfirmedReservation'] = reservation
return close(
session_attributes,
'Fulfilled',
{
'contentType': 'PlainText',
'content': 'Thanks, I have placed your reservation. Please let me know if you would like to book a car '
'rental, or another hotel.'
}
)
def book_car(intent_request):
"""
Performs dialog management and fulfillment for booking a car.
Beyond fulfillment, the implementation for this intent demonstrates the following:
1) Use of elicitSlot in slot validation and re-prompting
2) Use of sessionAttributes to pass information that can be used to guide conversation
"""
slots = intent_request['currentIntent']['slots']
pickup_city = slots['PickUpCity']
pickup_date = slots['PickUpDate']
return_date = slots['ReturnDate']
driver_age = slots['DriverAge']
car_type = slots['CarType']
confirmation_status = intent_request['currentIntent']['confirmationStatus']
session_attributes = intent_request['sessionAttributes'] if intent_request['sessionAttributes'] is not None else {}
last_confirmed_reservation = try_ex(lambda: session_attributes['lastConfirmedReservation'])
if last_confirmed_reservation:
last_confirmed_reservation = json.loads(last_confirmed_reservation)
confirmation_context = try_ex(lambda: session_attributes['confirmationContext'])
# Load confirmation history and track the current reservation.
reservation = json.dumps({
'ReservationType': 'Car',
'PickUpCity': pickup_city,
'PickUpDate': pickup_date,
'ReturnDate': return_date,
'CarType': car_type
})
session_attributes['currentReservation'] = reservation
if pickup_city and pickup_date and return_date and driver_age and car_type:
# Generate the price of the car in case it is necessary for future steps.
price = generate_car_price(pickup_city, get_day_difference(pickup_date, return_date), driver_age, car_type)
session_attributes['currentReservationPrice'] = price
if intent_request['invocationSource'] == 'DialogCodeHook':
# Validate any slots which have been specified. If any are invalid, re-elicit for their value
validation_result = validate_book_car(intent_request['currentIntent']['slots'])
if not validation_result['isValid']:
slots[validation_result['violatedSlot']] = None
return elicit_slot(
session_attributes,
intent_request['currentIntent']['name'],
slots,
validation_result['violatedSlot'],
validation_result['message']
)
# Determine if the intent (and current slot settings) has been denied. The messaging will be different
# if the user is denying a reservation he initiated or an auto-populated suggestion.
if confirmation_status == 'Denied':
# Clear out auto-population flag for subsequent turns.
try_ex(lambda: session_attributes.pop('confirmationContext'))
try_ex(lambda: session_attributes.pop('currentReservation'))
if confirmation_context == 'AutoPopulate':
return elicit_slot(
session_attributes,
intent_request['currentIntent']['name'],
{
'PickUpCity': None,
'PickUpDate': None,
'ReturnDate': None,
'DriverAge': None,
'CarType': None
},
'PickUpCity',
{
'contentType': 'PlainText',
'content': 'Where would you like to make your car reservation?'
}
)
return delegate(session_attributes, intent_request['currentIntent']['slots'])
if confirmation_status == 'None':
# If we are currently auto-populating but have not gotten confirmation, keep requesting for confirmation.
if (not pickup_city and not pickup_date and not return_date and not driver_age and not car_type)\
or confirmation_context == 'AutoPopulate':
if last_confirmed_reservation and try_ex(lambda: last_confirmed_reservation['ReservationType']) == 'Hotel':
# If the user's previous reservation was a hotel - prompt for a rental with
# auto-populated values to match this reservation.
session_attributes['confirmationContext'] = 'AutoPopulate'
return confirm_intent(
session_attributes,
intent_request['currentIntent']['name'],
{
'PickUpCity': last_confirmed_reservation['Location'],
'PickUpDate': last_confirmed_reservation['CheckInDate'],
'ReturnDate': add_days(
last_confirmed_reservation['CheckInDate'], last_confirmed_reservation['Nights']
),
'CarType': None,
'DriverAge': None
},
{
'contentType': 'PlainText',
'content': 'Is this car rental for your {} night stay in {} on {}?'.format(
last_confirmed_reservation['Nights'],
last_confirmed_reservation['Location'],
last_confirmed_reservation['CheckInDate']
)
}
)
# Otherwise, let native DM rules determine how to elicit for slots and/or drive confirmation.
return delegate(session_attributes, intent_request['currentIntent']['slots'])
# If confirmation has occurred, continue filling any unfilled slot values or pass to fulfillment.
if confirmation_status == 'Confirmed':
# Remove confirmationContext from sessionAttributes so it does not confuse future requests
try_ex(lambda: session_attributes.pop('confirmationContext'))
if confirmation_context == 'AutoPopulate':
if not driver_age:
return elicit_slot(
session_attributes,
intent_request['currentIntent']['name'],
intent_request['currentIntent']['slots'],
'DriverAge',
{
'contentType': 'PlainText',
'content': 'How old is the driver of this car rental?'
}
)
elif not car_type:
return elicit_slot(
session_attributes,
intent_request['currentIntent']['name'],
intent_request['currentIntent']['slots'],
'CarType',
{
'contentType': 'PlainText',
'content': 'What type of car would you like? Popular models are '
'economy, midsize, and luxury.'
}
)
return delegate(session_attributes, intent_request['currentIntent']['slots'])
# Booking the car. In a real application, this would likely involve a call to a backend service.
logger.debug('bookCar at={}'.format(reservation))
del session_attributes['currentReservationPrice']
del session_attributes['currentReservation']
session_attributes['lastConfirmedReservation'] = reservation
return close(
session_attributes,
'Fulfilled',
{
'contentType': 'PlainText',
'content': 'Thanks, I have placed your reservation.'
}
)
# --- Intents ---
def dispatch(intent_request):
"""
Called when the user specifies an intent for this bot.
"""
logger.debug('dispatch userId={}, intentName={}'.format(intent_request['userId'], intent_request['currentIntent']['name']))
intent_name = intent_request['currentIntent']['name']
# Dispatch to your bot's intent handlers
if intent_name == 'BookHotel':
return book_hotel(intent_request)
elif intent_name == 'BookCar':
return book_car(intent_request)
raise Exception('Intent with name ' + intent_name + ' not supported')
# --- Main handler ---
def lambda_handler(event, context):
"""
Route the incoming request based on intent.
The JSON body of the request is provided in the event slot.
"""
# By default, treat the user request as coming from the America/New_York time zone.
os.environ['TZ'] = 'America/New_York'
time.tzset()
logger.debug('event.bot.name={}'.format(event['bot']['name']))
return dispatch(event)