-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlambda_function.py
186 lines (143 loc) · 5.77 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
### 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}
}
### 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
def validate_data(age, investment_amount, intent_request):
if investment_amount is not None:
investment_amount = parse_int(investment_amount)
if investment_amount < 5000:
return build_validation_result(False, "investmentAmount", "The minimum investment amount is $5,000 USD, could you please provide a greater amount?")
if age is not None:
age = parse_int(age)
if age < 0 or age > 64:
return build_validation_result(False, "age", "The maximum age to contract this service is 64, can you provide an age between 0 and 64 please?")
return build_validation_result(True, None, None)
### Intents Handlers ###
def recommend_portfolio(intent_request):
"""
Performs dialog management and fulfillment for recommending a portfolio.
"""
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":
# Perform basic validation on the supplied input slots.
# Use the elicitSlot dialog action to re-prompt
# for the first violation detected.
### YOUR DATA VALIDATION CODE STARTS HERE ###
slots = get_slots(intent_request)
validation_result = validate_data(age, investment_amount, intent_request)
if not validation_result["isValid"]:
slots[validation_result["violatedSlot"]] = None
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"]
return delegate(output_session_attributes, get_slots(intent_request))
# Get the initial investment recommendation
### YOUR FINAL INVESTMENT RECOMMENDATION CODE STARTS HERE ###
if risk_level == "none":
initial_recommendation="100% bonds (AGG), 0% equities (SPY)"
if risk_level == "very low":
initial_recommendation="80% bonds (AGG), 20% equities (SPY)"
if risk_level == "low":
initial_recommendation="60% bonds (AGG), 40% equities (SPY)"
if risk_level == "medium":
initial_recommendation="40% bonds (AGG), 60% equities (SPY)"
if risk_level == "high":
initial_recommendation="20% bonds (AGG), 80% equities (SPY)"
if risk_level == "very high":
initial_recommendation="0% bonds (AGG), 100% 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)