AWS AI Services Programming Series - Part2 (Lex)

   Go back to the Task List

  « 1: Pre-requisite    3: Configure Chat Bot »

2: Create Lambda Function

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.

  1. Login to the AWS Account and select a region where Amazon Lex is available. The workshop is using Ireland region.

  2. Goto the Lambda Console and click on the Create function button.

    Lex

  3. 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.

    Lex

  4. The function is created in no time. Goto the Function code area and replace the code with the following.

    Lex

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
  1. 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.

    Lex

  2. The Lambda function is ready. Let’s configure the bot in the next task.