-
Notifications
You must be signed in to change notification settings - Fork 0
/
lambda_function.py
669 lines (522 loc) · 20.8 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
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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
### Required Libraries ###
from datetime import datetime
from dateutil.relativedelta import relativedelta
### Functionality Helper Functions ###
def parse_int(n):
"""
Securely converts a non-integer value to integer.
"""
try:
return int(n)
except ValueError:
return float("nan")
def build_validation_result(is_valid, violated_slot, message_content):
"""
Define a result message structured as Lex response.
"""
if message_content is None:
return {"isValid": is_valid, "violatedSlot": violated_slot}
return {
"isValid": is_valid,
"violatedSlot": violated_slot,
"message": {"contentType": "PlainText", "content": message_content},
}
def validate_data(age, investment_amount, intent_request):
if age is not None:
age = parse_int(age)
if age >= 65:
return build_validation_result(
False,
'age',
'Opps, you are already retired',
)
if age < 0:
return build_validation_result(
False,
'age',
'I can not believe you are not born yet,'
'please count how many years you lived so far.',
)
if investment_amount is not None:
investment_amount = parse_int(
investment_amount
)
if investment_amount < 5000:
return build_validation_result(
False,
"investmentAmount",
"Minimum Amount to start is 5,000 dollars, "
"please increase your initial investment to enjoy your retirement.",
)
# A True results is returned if age or amount are valid
return build_validation_result(True, None, None)
### Dialog Actions Helper Functions ###
def get_slots(intent_request):
"""
Fetch all the slots and their values from the current intent.
"""
return intent_request["currentIntent"]["slots"]
def elicit_slot(session_attributes, intent_name, slots, slot_to_elicit, message):
"""
Defines an elicit slot type response.
"""
return {
"sessionAttributes": session_attributes,
"dialogAction": {
"type": "ElicitSlot",
"intentName": intent_name,
"slots": slots,
"slotToElicit": slot_to_elicit,
"message": message,
},
}
def delegate(session_attributes, slots):
"""
Defines a delegate slot type response.
"""
return {
"sessionAttributes": session_attributes,
"dialogAction": {"type": "Delegate", "slots": slots},
}
def close(session_attributes, fulfillment_state, message):
"""
Defines a close slot type response.
"""
response = {
"sessionAttributes": session_attributes,
"dialogAction": {
"type": "Close",
"fulfillmentState": fulfillment_state,
"message": message,
},
}
return response
### Intents Handlers ###
def recommend_portfolio(intent_request):
"""
Performs dialog management and fulfillment for recommending a portfolio.
"""
# Gets slots' values
first_name = get_slots(intent_request)["firstName"]
age = get_slots(intent_request)["age"]
investment_amount = get_slots(intent_request)["investmentAmount"]
risk_level = get_slots(intent_request)["riskLevel"]
source = intent_request["invocationSource"]
if source == "DialogCodeHook":
# This code performs basic validation on the supplied input slots.
# Gets all the slots
slots = get_slots(intent_request)
# Validates user's input using the validate_data function
validation_result = validate_data(age, investment_amount, intent_request)
# Perform basic validation on the supplied input slots.
# Use the elicitSlot dialog action to re-prompt
# for the first violation detected.
if not validation_result["isValid"]:
slots[validation_result["violatedSlot"]] = None # Cleans invalid slot
# Returns an elicitSlot dialog to request new data for the invalid slot
return elicit_slot(
intent_request["sessionAttributes"],
intent_request["currentIntent"]["name"],
slots,
validation_result["violatedSlot"],
validation_result["message"],
)
# Fetch current session attibutes
output_session_attributes = intent_request["sessionAttributes"]
# Once all slots are valid, a delegate dialog is returned
# to Lex to choose the next course of action.
return delegate(output_session_attributes, get_slots(intent_request))
# Get the initial investment recommendation
if risk_level == 'None':
initial_recommendation = '100% Bonds (AGG)'
elif risk_level == 'Very Low':
initial_recommendation = '80% Bonds (AGG) and 20% Equities (SPY)'
elif risk_level == 'Low':
initial_recommendation = '6% Bonds (AGG) and 40% Equities (SPY)'
elif risk_level == 'Medium':
initial_recommendation = '40% Bonds (AGG) and 60% Equities (SPY)'
elif risk_level == 'High':
initial_recommendation = '20% Bonds (AGG) and 80% Equities (SPY)'
elif risk_level == 'Very High':
initial_recommendation = '100% Equities (SPY)'
# Return a message with the initial recommendation based on the risk level.
return close(
intent_request["sessionAttributes"],
"Fulfilled",
{
"contentType": "PlainText",
"content": """{} thank you for your information;
based on the risk level you defined, my recommendation is to choose an investment portfolio with {}
""".format(
first_name, initial_recommendation
),
},
)
### Intents Dispatcher ###
def dispatch(intent_request):
"""
Called when the user specifies an intent for this bot.
"""
intent_name = intent_request["currentIntent"]["name"]
# Dispatch to bot's intent handlers
if intent_name == "RecommendPortfolio":
return recommend_portfolio(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.
"""
return dispatch(event)
from dateutil.relativedelta import relativedelta
### Functionality Helper Functions ###
def parse_int(n):
"""
Securely converts a non-integer value to integer.
"""
try:
return int(n)
except ValueError:
return float("nan")
def build_validation_result(is_valid, violated_slot, message_content):
"""
Define a result message structured as Lex response.
"""
if message_content is None:
return {"isValid": is_valid, "violatedSlot": violated_slot}
return {
"isValid": is_valid,
"violatedSlot": violated_slot,
"message": {"contentType": "PlainText", "content": message_content},
}
def validate_data(age, investment_amount, intent_request):
"""
Validates the data provided by the user.
"""
# Validate that the user is less than 65 years old
if age is not None:
if age > 65 or age < 0:
return build_validation_result(
False,
"age",
"You should be less than 65 years old to use this service, "
"please provide a different age.",
)
# Validate the investment amount,
# it should be equal or greater than 5000
if investment_amount is not None:
investment_amount = parse_int(
investment_amount
) # Since parameters are strings it's important to cast values
if investment_amount < 5000:
return build_validation_result(
False,
"investmentAmount",
"The amount to invest should be greater than 5000, "
"please provide a correct amount in USD to invest.",
)
# A True results is returned if age or amount are valid
return build_validation_result(True, None, None)
### Dialog Actions Helper Functions ###
def get_slots(intent_request):
"""
Fetch all the slots and their values from the current intent.
"""
return intent_request["currentIntent"]["slots"]
def elicit_slot(session_attributes, intent_name, slots, slot_to_elicit, message):
"""
Defines an elicit slot type response.
"""
return {
"sessionAttributes": session_attributes,
"dialogAction": {
"type": "ElicitSlot",
"intentName": intent_name,
"slots": slots,
"slotToElicit": slot_to_elicit,
"message": message,
},
}
def delegate(session_attributes, slots):
"""
Defines a delegate slot type response.
"""
return {
"sessionAttributes": session_attributes,
"dialogAction": {"type": "Delegate", "slots": slots},
}
def close(session_attributes, fulfillment_state, message):
"""
Defines a close slot type response.
"""
response = {
"sessionAttributes": session_attributes,
"dialogAction": {
"type": "Close",
"fulfillmentState": fulfillment_state,
"message": message,
},
}
return response
### Intents Handlers ###
def recommend_portfolio(intent_request):
"""
Performs dialog management and fulfillment for recommending a portfolio.
"""
# Gets slots' values
first_name = get_slots(intent_request)["firstName"]
age = get_slots(intent_request)["age"]
investment_amount = get_slots(intent_request)["investmentAmount"]
risk_level = get_slots(intent_request)["riskLevel"]
source = intent_request["invocationSource"]
if age:
age = int(age)
if risk_level:
risk_level = risk_level.lower()
if source == "DialogCodeHook":
# This code performs basic validation on the supplied input slots.
### YOUR DATA VALIDATION CODE STARTS HERE ###
# Gets all the slots
slots = get_slots(intent_request)
# Validates user's input using the validate_data function
validation_result = validate_data(age, investment_amount, intent_request)
# Perform basic validation on the supplied input slots.
# Use the elicitSlot dialog action to re-prompt
# for the first violation detected.
if not validation_result["isValid"]:
slots[validation_result["violatedSlot"]] = None # Cleans invalid slot
# Returns an elicitSlot dialog to request new data for the invalid slot
return elicit_slot(
intent_request["sessionAttributes"],
intent_request["currentIntent"]["name"],
slots,
validation_result["violatedSlot"],
validation_result["message"],
)
### YOUR DATA VALIDATION CODE ENDS HERE ###
# Fetch current session attibutes
output_session_attributes = intent_request["sessionAttributes"]
# Once all slots are valid, a delegate dialog is returned
# to Lex to choose the next course of action.
return delegate(output_session_attributes, get_slots(intent_request))
# Get the initial investment recommendation
### YOUR FINAL INVESTMENT RECOMMENDATION CODE STARTS HERE ###
if risk_level == 'very high':
initial_recommendation = '0% bonds (AGG), 100% equities (SPY)'
elif risk_level == 'high':
initial_recommendation = '20% bonds (AGG), 80% equities (SPY)'
elif risk_level == 'medium':
initial_recommendation = '40% bonds (AGG), 60% equities (SPY)'
elif risk_level == 'low':
initial_recommendation = '60% bonds (AGG), 40% equities (SPY)'
elif risk_level == 'very low':
initial_recommendation = '80% bonds (AGG), 20% equities (SPY)'
elif risk_level == 'none':
initial_recommendation = '100% bonds (AGG), 0% equities (SPY)'
### YOUR FINAL INVESTMENT RECOMMENDATION CODE ENDS HERE ###
# Return a message with the initial recommendation based on the risk level.
return close(
intent_request["sessionAttributes"],
"Fulfilled",
{
"contentType": "PlainText",
"content": """{} thank you for your information;
based on the risk level you defined, my recommendation is to choose an investment portfolio with {}
""".format(
first_name, initial_recommendation
),
},
)
### Intents Dispatcher ###
def dispatch(intent_request):
"""
Called when the user specifies an intent for this bot.
"""
intent_name = intent_request["currentIntent"]["name"]
# Dispatch to bot's intent handlers
if intent_name == "RecommendPortfolio":
return recommend_portfolio(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.
"""
return dispatch(event)
from dateutil.relativedelta import relativedelta
### Functionality Helper Functions ###
def parse_int(n):
"""
Securely converts a non-integer value to integer.
"""
try:
return int(n)
except ValueError:
return float("nan")
def build_validation_result(is_valid, violated_slot, message_content):
"""
Define a result message structured as Lex response.
"""
if message_content is None:
return {"isValid": is_valid, "violatedSlot": violated_slot}
return {
"isValid": is_valid,
"violatedSlot": violated_slot,
"message": {"contentType": "PlainText", "content": message_content},
}
def validate_data(age, investment_amount, intent_request):
"""
Validates the data provided by the user.
"""
# Validate that the user is less than 65 years old
if age is not None:
age = int(age)
if age > 65:
return build_validation_result(
False,
"age",
"Opps, you are already retired. This service is to plan for retirement. ",
)
if age < 0:
return build_validation_result(
False,
'age',
'I can not believe you are not born yet,'
'please count how many years you lived so far.',
)
# Validate the investment amount,
# it should be equal or greater than 5000
if investment_amount is not None:
investment_amount = parse_int(
investment_amount
) # Since parameters are strings it's important to cast values
if investment_amount < 5000:
return build_validation_result(
False,
"investmentAmount",
"Minimum Amount to start is 5,000 dollars, "
"please increase your initial investment to enjoy your retirement.",
)
# A True results is returned if age or amount are valid
return build_validation_result(True, None, None)
### Dialog Actions Helper Functions ###
def get_slots(intent_request):
"""
Fetch all the slots and their values from the current intent.
"""
return intent_request["currentIntent"]["slots"]
def elicit_slot(session_attributes, intent_name, slots, slot_to_elicit, message):
"""
Defines an elicit slot type response.
"""
return {
"sessionAttributes": session_attributes,
"dialogAction": {
"type": "ElicitSlot",
"intentName": intent_name,
"slots": slots,
"slotToElicit": slot_to_elicit,
"message": message,
},
}
def delegate(session_attributes, slots):
"""
Defines a delegate slot type response.
"""
return {
"sessionAttributes": session_attributes,
"dialogAction": {"type": "Delegate", "slots": slots},
}
def close(session_attributes, fulfillment_state, message):
"""
Defines a close slot type response.
"""
response = {
"sessionAttributes": session_attributes,
"dialogAction": {
"type": "Close",
"fulfillmentState": fulfillment_state,
"message": message,
},
}
return response
### Intents Handlers ###
def recommend_portfolio(intent_request):
"""
Performs dialog management and fulfillment for recommending a portfolio.
"""
# Gets slots' values
first_name = get_slots(intent_request)["firstName"]
age = get_slots(intent_request)["age"]
investment_amount = get_slots(intent_request)["investmentAmount"]
risk_level = get_slots(intent_request)["riskLevel"]
source = intent_request["invocationSource"]
if source == "DialogCodeHook":
# This code performs basic validation on the supplied input slots.
# Gets all the slots
slots = get_slots(intent_request)
# Validates user's input using the validate_data function
validation_result = validate_data(age, investment_amount, intent_request)
# Perform basic validation on the supplied input slots.
# Use the elicitSlot dialog action to re-prompt
# for the first violation detected.
if not validation_result["isValid"]:
slots[validation_result["violatedSlot"]] = None # Cleans invalid slot
# Returns an elicitSlot dialog to request new data for the invalid slot
return elicit_slot(
intent_request["sessionAttributes"],
intent_request["currentIntent"]["name"],
slots,
validation_result["violatedSlot"],
validation_result["message"],
)
# Fetch current session attibutes
output_session_attributes = intent_request["sessionAttributes"]
# Once all slots are valid, a delegate dialog is returned
# to Lex to choose the next course of action.
return delegate(output_session_attributes, get_slots(intent_request))
# Get the initial investment recommendation
if risk_level == 'Very High':
initial_recommendation = '0% bonds (AGG) and 100% equities (SPY)'
elif risk_level == 'High':
initial_recommendation = '20% bonds (AGG) and 80% equities (SPY)'
elif risk_level == 'Medium':
initial_recommendation = '40% bonds (AGG) and 60% equities (SPY)'
elif risk_level == 'Low':
initial_recommendation = '60% bonds (AGG) and 40% equities (SPY)'
elif risk_level == 'Very Low':
initial_recommendation = '80% bonds (AGG) and 20% equities (SPY)'
elif risk_level == 'None':
initial_recommendation = '100% bonds (AGG) and 0% equities (SPY)'
# Return a message with the initial recommendation based on the risk level.
return close(
intent_request["sessionAttributes"],
"Fulfilled",
{
"contentType": "PlainText",
"content": """{} thank you for your information;
based on the risk level you defined, my recommendation is to choose an investment portfolio with {}
""".format(
first_name, initial_recommendation
),
},
)
### Intents Dispatcher ###
def dispatch(intent_request):
"""
Called when the user specifies an intent for this bot.
"""
intent_name = intent_request["currentIntent"]["name"]
# Dispatch to bot's intent handlers
if intent_name == "RecommendPortfolio":
return recommend_portfolio(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.
"""
return dispatch(event)