Creating My First ChatBot Using Angular(5.0) And Dialogflow (API.AI)

First, let me tell you why you should require Chat Bots? Is it really helpful? and who are building bots etc..

Anyone who has ever tried to contact a company through customer care center might know how slow and frustrating process it is. You remember that audio tape “press 1 for this, press 2 for this, press * to go back to the menu, and blah blah blah….“?

Say, for example, if you want to activate a simple caller tune to your phone number, you have to spend at least 10 minutes to know the code to activate that caller tune, by hearing that audio tape and pressing so many numbers. And finally, if you had a good luck, then only you are able to activate your caller tune.

However, there is a great solution to this kind of problem, which is faster than the customer care center – the Chat Bots. Nowadays, Chat Bots can be made using AI also, so it doesn’t limit them.

“A chatbot is a service, powered by rules and sometimes artificial intelligence that you interact with via a chat interface.”

According to some people, Bots will completely kill the web and mobile apps. The main reasons for that are –

  • Bots are faster than the website and mobile apps, they replied instantly.
  • Mobile apps need to download and it occupies some memory of your phone whereas the bot doesn’t need to download it lives within your messenger only.
  • It is easier to use Bots and many more.

Messaging is the new browser and bots are the new apps.

Prerequisites

  • JavaScript
  • Angular-CLI
  • Dialogflow account (previously API.AI)
  • Visual Studio Code (optional)

Setting Up Dialogflow

  • Navigate to Dialogflow and log in to your account.Screenshot (95)
  • Then, press “Create Agent” to create your first agent.Screenshot (96)
  • After filling the required details, press “Create”.Screenshot (97)
  • Then, press the “Create Intent” button to create your first intent. Intents are usually user’s intention of asking questions. Dialogflow extracts the user intention from text using Natural Language Processing.
    • Add you intent/question in “user says” field, as shown below.Screenshot (101)
    • And, the answer should be in response field, as shown below.Screenshot (102)
  • The entire page will look like the following.Screenshot (98)
  • Now, you can also test your sentence in the console.Sketch

So far, we have created our Dialogflow Agent and Intent. Now, it’s time to create an Angular application to create a user interface and integrate our Dialogflow Agent to Angular.

Angular Application

  • You can create an Angular project using Angular-CLI.
ng new ngbotdemo
  • Integrate Dialogflow JavaScript SDK in our Angular project using the following command.
npm install api-ai-javascript  - - save-dev 
  • Store the Client access token from Dialogflow to your app inside environment.ts file, as shown below.

Sketch (1)

  • Now, store the client access token in environment.ts file.
export const environment = {  

 production: false,  

 dialogflow: {  

   angularBot: 'your-key'  

 };
  • Now, let us create the service using the following command.
ng g s chat
  • Inside the chat service, we will first import the following packages.
import { environment } from '../../environments/environment';
import { ApiAiClient } from 'api-ai-javascript';
import { Observable } from 'rxjs/Observable'import { BehaviorSubject } from 'rxjs/BehaviorSubject';
  • Then, we will create one message class inside the service, which has two members – msg (which will be used to store the content or message send by the user or bot) and from (which will be used to store the info of who sent that message, i.e., either ‘user’ or ‘Bot’).
export class Message {  

  constructor(public msg: string, public from: string) { }  

}
  • Now, let us create the instance of API.AI client – the JavaScript SDK for Dialogflow, and then, pass the client access token to that instance of API.AI client.
readonly token = environment.dialogflow.angularBot;
readonly _client = new ApiAiClient({ accessToken: this.token });

  • Now, it’s time to create a method that will interact with our bot, i.e., send and receive messages, as shown below.
talk(msg: string) {  

  const userMessage = new Message(msg, 'user');  

  this.update(userMessage);  

  return this._client.textRequest(msg)  

    .then(res => {  

      const speech = res.result.fulfillment.speech;  

      const botMessage = new Message(speech, 'bot');  

      this.update(botMessage);  

    });  

}
  • The full chat.service.ts will look like below.
import { Injectable } from '@angular/core';  

import { environment } from '../../environments/environment';  

import { ApiAiClient } from 'api-ai-javascript';  

import { Observable } from 'rxjs/Observable';  

import { BehaviorSubject } from 'rxjs/BehaviorSubject';  

  

export class Message {  

  constructor(public msg: string, public from: string) { }  

}  

  

@Injectable()  

export class ChatService {  

  readonly token = environment.dialogflow.angularBot;  

  readonly _client = new ApiAiClient({ accessToken: this.token });  

  conversation = new BehaviorSubject<Message[]>([]);  

  constructor() { }  

  // Sends and receives messages via DialogFlow  

  talk(msg: string) {  

    const userMessage = new Message(msg, 'user');  

    this.update(userMessage);  

    return this._client.textRequest(msg)  

      .then(res => {  

        const speech = res.result.fulfillment.speech;  

        const botMessage = new Message(speech, 'bot');  

        this.update(botMessage);  

      });  

  }  

  // Adds message to source  

  update(msg: Message) {  

    this.conversation.next([msg]);  

  }  
}

Here, I am injecting the chat-service inside the constructor. And calling my talk method when a user presses the Enter key or the Send button. I have used two-way binding to get the input from the input-box. For that, I have created the variable strMSg.

My chat-component.html will look like this.

<h1>My First ChatBot using Angular and Dialogflow</h1>  

<ng-container *ngFor="let m of messages | async">  

  
class="message" [ngClass]="{ 'from': m.from === 'bot',                                       'to':   m.from === 'user' }">       {{ m.msg }}     
   </ng-container>   <label for="nameField">Your Message</label>      <input [(ngModel)]="strMsg" (keyup.enter)="sendMessage()" type="text">      <br>   <button (click)="sendMessage()">Send</button>

OutputScreenshot (104)

 

Advertisements

1 thought on “Creating My First ChatBot Using Angular(5.0) And Dialogflow (API.AI)”

  1. Hi, this is great! Thanks a lot for sharing.
    Is there a version of this chatbot available with “talk” enabled? That is, with speech synthesis and speech recognition? I am building a talking chatbot using Angular 4/5 with speech synthesis and speech recognition and running into problems with event management in speech recognition. Looking for help. Please let me know.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s