The very first step is to create a Lambda function which will work as the backend service for the chat bot. For the workshop, you are creating a simple Lambda function which performs four mathematical operations add, subtract, multiply and divide. This Lambda function is used by the chat bot to provide calculation interaction.
-
Login to the AWS Account and select a region where Amazon Lex is available. The workshop is using Ireland region.
-
Goto the Lambda Console and click on the Create function button.
-
On the next screen, select Author from scratch option. Type in dojobotfunction as the function name. Select Python 3.8 as the Runtime. Select Create a new role with basic Lambda permissions option for the Permissions. Click on the Create function button.
-
The function is created in no time. Goto the Function code area and replace the code with the following.
import json
def lambda_handler(event, context):
data1 = event['currentIntent']['slots']['dataone']
data2 = event['currentIntent']['slots']['datatwo']
op = event['currentIntent']['slots']['op']
result = 0
if op == '+':
result = int(data1) + int(data2)
elif op == '-':
result = int(data1) - int(data2)
elif op == '*':
result = int(data1) * int(data2)
elif op == '/':
result = int(data1) / int(data2)
else:
result = 0
response = { "dialogAction": { "type": "Close", "fulfillmentState": "Fulfilled", "message": { "contentType": "PlainText", "content": "Your result is " + str(result) } } }
return response
-
The code above is very simple. The function takes input from the Lex chat bot slots. Then performs the calculation and returns the result. The slots will make more sense once you configure bot in the next task. Click on the Save in the top-right corner of the page to save the function.
-
The Lambda function is ready. Let’s configure the bot in the next task.