Google Cloud: Implementing an AI Chatbot with Dialogflow

Share At:

How to Create a Chatbot with Dialogflow, NodeJS, and Webhooks

Overview

Dialogflow is a natural language understanding platform that makes it easy to design and integrate a conversational user interface into your mobile app, web application, device, bot, etc. Dialogflow can analyze multiple types of input from your customers, including text or audio inputs (like from a phone or voice recording). It can also respond to your customers either through text or with synthetic speech.

In this lab, you will build a Google Assistant chatbot that submits helpdesk tickets. The following is a diagram of the chatbot application on Google Cloud:

b4c6dcdb2577c898.png

The exercises are ordered to reflect a common cloud developer process. You will:

  • Set up your lab and learn how to work with Dialogflow and your Google Cloud environment.
  • Deploy a simple Dialogflow application.
  • Deploy a simple cloud function within Google Cloud to connect with Dialogflow.
  • Test your chatbot.

What you’ll learn

By the end of this lab, you will have an understanding of the following:

  • Basics concepts and constructs of Dialogflow, including intent, entity and context.
  • Chatbot workflow.
  • Life of a conversation.

Dialogflow Concepts and Constructs

Dialogflow is a conversation building tool. It takes the human language and cleverly splits it into intents and arguments.

Agents are best described as NLU (Natural Language Understanding) modules. These can be included in your app, product, or service, and transforms natural user requests into actionable data. This transformation occurs when a user input matches one of the intents inside your agent.

Intents are the predefined or developer-defined components of agents that process a user’s request. An intent represents a mapping between what a user says and what action should be taken by your software.

Intent interfaces have the following sections:

  • User says
  • Action
  • Response
  • Contexts

Entities are powerful tools used for extracting parameter values from natural language inputs. Any important data you want to get from a user’s request will have a corresponding entity.

The entities used in a particular agent will depend on the parameter values that are expected to be returned as a result of the agent functioning. In other words, a developer does not need to create entities for every possible concept mentioned in the agent – only for those needed for actionable data.

There are 3 types of entities:

  • System: defined by Dialogflow
  • Developer: defined by a developer
  • User: built for each individual end-user in every request

It’s important to distinguish between the three different types of system entities:

  • System mapping: Has reference values
  • System enum: Has no reference values
  • System composite: Contains other entities with aliases and returns object type values

Contexts represent the current context of a user’s request. This is helpful for differentiating phrases which may be vague or have different meanings depending on the user’s preferences, geographic location, the current page in an app, or the topic of conversation.

For example, if a user is listening to music and finds a band that catches their interest, they might say something like: “I want to hear more of them”. As a developer, you can include the name of the band in the context with the request, so that the agent can use it in other intents.

Fulfillment is a webhook that allows you to pass information from a matched intent into a web service and get a result from it.

All of this new information may be overwhelming, but not to panic — it should all come together once you start developing your Google Assistant chatbot in the following section.

Deploy a simple Dialogflow application to submit helpdesk tickets

Enable Cloud Datastore

Cloud Datastore is a highly scalable NoSQL database for your applications. Cloud Datastore automatically handles sharding and replication, providing you with a highly available and durable database that scales automatically to handle your applications’ load.

  1. Create a new database instance, open the Datastore section in the Cloud Console.
  2. In the Console, go to Navigation menu > Datastore
  3. The screen should look like this:
firestore_datastore.png
  1. Click the SELECT DATASTORE MODE
  2. From the dropdown Select a location choose nam5(United State)
  1. Click CREATE DATABASE

Create a Dialogflow agent

  1. In the Console, go to Navigation menu > APIs & Services > Dashboard.
  2. Click on Enable APIs and Services:
  3. Search for Dialogflow:
  4. Click on the Dialogflow API and if the API is not Enabled, click Enable:
  1. In a new tab, go to dialogflow.cloud.google.com. Click the Sign in with Google button, and put the credentials.
  2. Then check the Terms of Service. Click on Accept.
  3. Click Create New Agent.
  1. Now add the agent information as you see in the screenshot below:
  • Agent name: Helpdesk
  • Default Time zone: America/Denver
  • Google Project: Your Project ID

9. When you’re ready, click Create.

Now you’re ready to get started!

10. The Default Welcome Intent is automatically created. Click on it to open it:

11. In the Training phrases section, add some expressions that a user could potentially say. The most common would be “Hi”, “Hello”, “Good morning”. Add these now. Your screen should look something like this:

f2d046829e539da2.png

12. Scroll down to the Responses section. Here is where you’ll set up the “Text response” that will automatically respond to users. These are all ready to go. If you want, add some more, like, “Hi! How can I help?”

13. Click Save in the top right corner.

14. Time to test what you built so far. On the right in the Try it now section, say “Hi” and stop the recording when done. You should see a Default Response.

Pretty cool, right? Now things will get more interesting.

Create Intents

  1. Click on Intents in the left pane, then click on Create Intent:
cb7ceca6c1d78624.png

2. Name the intent “Submit Ticket”.

3. Go to the “Training phrases” section and click on Add Training Phrases. Add the following:

  • Ticket
  • Submit ticket
  • Problem
  • Issue
  • I want to submit a ticket
  • I have a problem

4. Scroll down to the “Responses” section and click on Add Response. Enter the following:

  • Sure! I can help you with that. Please provide your name for the ticket.

5. Click Save when you’re done.

6. Now click on Intents in the left-hand panel, and mouse over your newly created “Submit Ticket” intent. Click “Add follow up intent” and then select custom.

7. Click on the new “Submit Ticket – custom” intent to edit it. Fill in the details and make sure they resemble the screenshot below:

  • Intent name: Submit Ticket – collect name
  • Training phrases: I am bob
  • Training phrases: My name is Lily
  • Responses: Thanks $person! Now describe your issue.
person.png

As you add your training phrases, notice that when you type “My name is Lily” a default entity is created called person (if it doesn’t appear by default, please select @sys.person for Lily and bob manually). In the Text response section, a $ is added before person to represent a variable. This will let the chatbot echo the user’s name back to them.

8. Click Save when you’re done.

9. Next you’ll see how the variables are stored and recalled by Dialogflow.

Say “issue” in Try it now and check the response you get:

10. Say ‘My name is Lily’ and check the response you get:

Notice under Contexts that Dialogflow automatically added a context of “SubmitTicket-followup”.

Allow Fulfillment to Store Help Ticket Data

Now you’ll enable Fulfillment so the help ticket information can be submitted to a database, Google Cloud Datastore in this case. It will take a few minutes for your resources to be available.

  1. Click on Fulfillment in the left panel and switch the Inline Editor toggle to “Enabled”.

You may get an error saying “Your Google Cloud resources are still being provisioned, please refresh the page and try again in a few minutes.” If you do, just wait a short time and reload your page.

2. Copy the following code and paste it in the index.js tab, replacing the existing content:

'use strict';
const http = require('http');
// Imports the Google Cloud client library
const Datastore = require('@google-cloud/datastore');
// Your Google Cloud Platform project ID
const projectId = 'REPLACE_WITH_YOUR_PROJECT_ID';
// Instantiates a client
const datastore = Datastore({
  projectId: projectId
});
// The kind for the new entity
const kind = 'ticket';
exports.dialogflowFirebaseFulfillment = (req, res) => {
  console.log('Dialogflow Request body: ' + JSON.stringify(req.body));
  // Get the city and date from the request
  let ticketDescription = req.body.queryResult['queryText']; // incidence is a required param
  //let name = req.body.result.contexts[0].parameters['person.original'];
  let username = req.body.queryResult.outputContexts[1].parameters['person.original'];
  let phone_number = req.body.queryResult.outputContexts[1].parameters['phone-number.original'];
  console.log('description is ' +ticketDescription);
  console.log('name is '+ username);
  console.log('phone number is '+ phone_number);
  function randomIntInc (low, high) {
    return Math.floor(Math.random() * (high - low + 1) + low);
  }
  let ticketnum = randomIntInc(11111,99999);
  // The Cloud Datastore key for the new entity
  const taskKey = datastore.key(kind);
  // Prepares the new entity
  const task = {
    key: taskKey,
    data: {
      description: ticketDescription,
      username: username,
      phoneNumber: phone_number,
      ticketNumber: ticketnum
    }
  };
  console.log("incidence is  " , task);
  // Saves the entity
  datastore.save(task)
  .then(() => {
    console.log(`Saved ${task.key}: ${task.data.description}`);
    res.setHeader('Content-Type', 'application/json');
    //Response to send to Dialogflow
    res.send(JSON.stringify({ 'fulfillmentText': "I have successfully logged your ticket, the ticket number is " + ticketnum + ". Someone from the helpdesk will reach out to you within 24 hours."}));
    //res.send(JSON.stringify({ 'fulfillmentText': "I have successfully logged your ticket, the ticket number is " + ticketnum + ". Someone from the helpdesk will reach out to you within 24 hours.", 'fulfillmentMessages': "I have successfully logged your ticket, the ticket number is " + ticketnum +  ". Someone from the helpdesk will reach out to you within 24 hours."}));
  })
  .catch((err) => {
    console.error('ERROR:', err);
    res.setHeader('Content-Type', 'application/json');
    res.send(JSON.stringify({ 'speech': "Error occurred while saving, try again later", 'displayText': "Error occurred while saving, try again later" }));    
  });
};

3. Then edit the index.js file:

  • On line 6, replace REPLACE_WITH_YOUR_PROJECT_ID with your Project ID (in single quotes). Your project ID is on the Qwiklabs page with the credentials, where you started the lab.

The result should look something like this (but with your own project name substituted):

4. Then click on the package.json tab add this dependency:

"@google-cloud/datastore": "^1.1.0"

Remember to add a comma after the last item in the dependency list.

5. The result should look something like this:

6. Then click the Deploy button. Wait until you see a message that the deployment was successful (this might take a little while).

In Google cloud console, you will see similar to this:

7. Next, go back to Intents in the left panel. Click the down arrow next to “Submit Ticket” to reveal its follow-up intents.

8. Mouse over “Submit Ticket – collect name” and click “Add follow up intent”, then select Custom.

Click on the newly created intent “Submit Ticket – collect name – custom” to open it for editing.

76bf5a56ba1530af.png

9. Name the intent “Submit Ticket – collect description”.

Enter some user expressions into Training phrases as shown below. Here is what we selected for Training phrases:

  • Everything is hosed
  • My laptop won’t start
  • Nothing works
  • My phone screen is broken

Use the following screenshot as a reference:

3f8ba916caf7f2b3.png

10. Scroll to the bottom of the screen click on the Fulfillment arrow to toggle the section. Click on Enable webhook call for this intent.

When you’re finished, click Save.

11. At this point, the Dialogflow should be set up. Test it in the “Try it now” panel by entering the following conversation:

  1. Hi
  2. I would like to submit a ticket
  3. My name is John
  4. My phone screen is broken

You should see a default response that resembles the following:

Verify that Tickets are Logged in Datastore

Now verify that the support ticket is getting logged in Datastore.

  1. From the Cloud Console Navigation menu, go to Datastore.
nav_datastore.png

2. You should see the entry as shown below.

This verifies that your chatbot is working and logging tickets, awesome!

Testing your Chatbot

Dialogflow provides many types of integrations for your chatbot. Now take a look at a sample web user interface for the chatbot.

  1. Click on Integrations in the Dialogflow left panel and then click on the Web Demo integration. Web_demo.png

2. Click Enable.

3. Now, click on the URL link to launch Web Demo: 

https://bot.dialogflow.com/8a9244f8-706b-437d-bb3f-99829c6c51f7

4. Start using the chat interface by typing in the Ask something… section! If you are using a Chrome browser, if you click the microphone icon and you can speak your questions to the chatbot. Start chatting with the chatbot using the following conversation:

  • Type “Hi” and hit Enter. The chatbot should respond as before.
  • Then enter/say “Submit ticket”
  • Provide the name “My name is Lily”
  • Provide the ticket details of “My phone screen is broken”

5. You should receive a dialog output that says a ticket has been submitted. You can also check in datastore to see if the ticket has been logged. The web demo is in it’s early stages, so if it doesn’t work as expected try to run the commands again or refresh the page.

6. Verify if the ticket is generated. You will see that a Ticket has been generated for Lily.

Happy Learning !!!


Share At:
4 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Back To Top

Contact Us