AWS AI Services Programming Series - Part2 (Lex)

   Go back to the Task List

  « 4: Configure the Development Environment    6. Clean up »

5: Create Chat Client

The development environment is ready. Let’s develop a chat client.

  1. In AWS Cloud9 console, click on the New File option under the File menu.

    Lex

  2. A new Untitled1 file gets created. Write the following code in the Untitled1 file.

    Lex

    import boto3 
    
    client = boto3.client('lex-runtime')
    
    theuser =  "dojouser"
    thebotname =  "calculatorbot"
    thebotalias =  "dojoalias"
    
    theinput = raw_input("what do you want to do?: ")
    
    while True:
        response = client.post_text(botName=thebotname, botAlias=thebotalias, userId= theuser,  inputText=theinput)
           
        if response["message"].find("Your result") != -1:
            print(response["message"])
            break;
           
    theinput = raw_input((response["message"]) + ": ")
    

    `

  3. In the code above, you first create client to Lex Runtime. You then ask user to type in something which can help in invoking the right chat bot intent. You then pass the input to Lex runtime with parameters - bot name, bot alias, a unique user name and the user input to invoke the right intent. The correct intent is identified and invoked. It will start throwing back questions based on the configuration in the slots. It also captures the user input for the questions. It keeps going till all questions are answered. Then the chat bot uses the Lambda function to calculate the result and return back to the user. At this point of time the chat session ends.

  4. Click on the Save option under the File menu. On the Save As popup, type in dojochatclient.py as the file name and click on the Save button. The code is saved in the file.

    Lex

  5. In the console window, execute python dojochatclient.py command to run the dojochatclient.py code. It will start the chat bot interaction and you respond to the questions.

    Polly

  6. This was an example code to create a chat client which works with Amazon Lex Chat Bot. This finishes the workshop. Please follow the next task to clean-up the resources so that you don’t incur any cost post the workshop.