-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlambda_function.py
286 lines (214 loc) · 9.28 KB
/
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
import json
import datetime
import time
import os
import dateutil.parser
import logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# --- Helpers that build all 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_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_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_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 bots 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.'
}
)
# --- 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 bots intent handlers
if intent_name == 'BookHotel':
return book_hotel(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)