Select Page

Recently, I’ve been working on integrating a chatbot with Angular version 7 as part of our latest project, Optimal Visualisation Engine (OVE).  In this blog, I’ll run you through how to integrate an AWS Lex chatbot with your Angular application (I’ve assumed you’ve already created a cool chatbot using AWS Lex).

 

Getting started

Install Angular on your machine and initialise an Angular application if you haven’t already.

To Integrate Lex Chatbot install aws-sdk and types definition using npm.  This provides JavaScript API for AWS services and gives you type definitions for node.

npm install aws-sdk -S
npm install --save-dev @types/node

Since the aws-sdk assumes global to be present and this is removed from angular 6+ add the following to your pollyfil.ts file

(window as any).global = window;

Add the following to your tsconfig.json file.

"types": ["node"]

Import the AWS SDK to your component.

import * as AWS from 'aws-sdk';

Create a type (Interface) for the chat messages

export interface Messages {
      Owner:string;
      Message:string;
}

Initialise the following variables

chatMessages: Array<Messages> = [{
                Owner: 'ChatBot', 
                Message: 'Hello, I can help you order flowers'}];
sessionAttributes = {};
lexRuntime: AWSSDK.LexRuntime;
lexUserId = 'userID' + Date.now(); // Client application userID
ChatInput = '';

LexRuntime: Chatbot uses the runtime API to understand user utterances (voice or text). 2 commands are available in LexRunTime. PostContent and PostText. PostContect is used to send text or Voice. I am using PostText since I am using only text messages.

In ngOnInit method

ngOnInit() {
  AWSSDK.config.region = 'us-east-1'; // Region
  AWSSDK.config.credentials = new AWSSDK.CognitoIdentityCredentials({
     IdentityPoolId: 'us-east-1:...'//your Identity poolId
  });
  this.lexRuntime = new AWSSDK.LexRuntime();
}

Paste the following to the template file of your component.

//Display the input and the response
<p *ngFor= 'let m of chatMessages' class="{{m.Owner}}">{{m.Owner}}: {{m.Message}}</p> 
<form class="chatForm" #chatform="ngForm" style="margin-top: 10px"                    
                (ngSubmit)="pushChat(chatform.value)">  
//input text field for the user input chat    
<input type="text" id="chatInput" size="32" value="" placeholder='Type a message...' 
                 autocomplete="off" [(ngModel)]=ChatInput  name="chatInput" > 
</form>


Create the push chat method in the component.ts file. This method is called when the user enters an input message and sends this message to Amazon Lex using the Runtime API.

public pushChat(data1: any) {

      if (data1.chatInput !== '') {
      this.chatMessages.push({Owner: 'User', Message: data1.chatInput});
      this.ChatInput = '';
      const params = {
          botAlias: '$LATEST', // 
          botName: 'OrderFlowersBot', // your chatbot name 
          userId: this.lexUserId,
          inputText: data1.chatInput,
          sessionAttributes: this.sessionAttributes
      };
      this.lexRuntime.postText(params, (err, data) => {
          if (err) {
             console.log(err, err.stack);
          }
          if (data) {
             this.sessionAttributes = data.sessionAttributes;
             this.chatMessages.push({Owner: 'Chatbot', Message: data.message});
          }
      });
   }
}

Here you go. Type something in your text box and press enter the Chatbot will talk to you.

Params
  • botName: (string) Name of the Amazon Lex bot.
  • botAlias: (string) Alias of the Amazon Lex bot.
  • userId: (string) The ID of the client application user. Amazon Lex uses this to identify a user’s conversation with your bot. At runtime, each request must contain the userID field.
  • inputText: (string) User input text
  • sessionAttributes — (string) Application-specific information passed between Amazon Lex and a client application.
CallBack
  • err (Error) — the error object returned from the request. Set to null if the request is successful.
  • data (Object) — the de-serialized data returned from the request. Set to null if a request error occurs. The data object has the following properties:
    • contentType — (String) Content type as specified in the Accept HTTP header in the request.
    • intentName — (String) Current user intent that Amazon Lex is aware of.
    • slots — (String) Map of zero or more intent slots (name/value pairs) Amazon Lex detected from the user input during the conversation.
    • sessionAttributes — (String) Map of key/value pairs representing the session-specific context information.
    • message — (String) The message to convey to the user. The message can come from the bot’s configuration or from a Lambda function.
    • messageFormat — (String) The format of the response message. One of the following values:
    • dialogState — (String) Identifies the current state of user interaction. eg. ElicitIntent, ConfirmIntent, ElicitSlot, Fulfilled
    • slotToElicit — (String) If the dialogState value is ElicitSlot, returns the name of the slot for which Amazon Lex is eliciting a value.
    • inputTranscript — (String) The text used to process the request.
This documentation will help you learn more about AWS LexRuntime Service.


Thanks

Salin

 

Salin is the newest member of our dev team and is currently learning a whole lot of tech, she recently blogged about using Blender when you’re new to 3D modelling.  

If you know an up-and-coming developer, give them this resource to help get them started with relational databases.

%d bloggers like this: