arrow_back

Implementing an AI Chatbot with Dialogflow ES

Join Sign in

Implementing an AI Chatbot with Dialogflow ES

1 hour 1 Credit

GSP078

Google Cloud selp-paced labs logo

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.

Prerequisites

This is a fundamental level lab. Before taking it, you should be comfortable with at least the basics of machine learning and natural language processing. Here are some Qwiklabs that can get you up to speed:

Once you are prepared, scroll down to dive into Dataflow.

Setup and Requirements

Before you click the Start Lab button

Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources will be made available to you.

This hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that you use to sign in and access Google Cloud for the duration of the lab.

To complete this lab, you need:

  • Access to a standard internet browser (Chrome browser recommended).
Note: Use an Incognito or private browser window to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.
  • Time to complete the lab---remember, once you start, you cannot pause a lab.
Note: If you already have your own personal Google Cloud account or project, do not use it for this lab to avoid extra charges to your account.

How to start your lab and sign in to the Google Cloud Console

  1. Click the Start Lab button. If you need to pay for the lab, a pop-up opens for you to select your payment method. On the left is the Lab Details panel with the following:

    • The Open Google Console button
    • Time remaining
    • The temporary credentials that you must use for this lab
    • Other information, if needed, to step through this lab
  2. Click Open Google Console. The lab spins up resources, and then opens another tab that shows the Sign in page.

    Tip: Arrange the tabs in separate windows, side-by-side.

    Note: If you see the Choose an account dialog, click Use Another Account.
  3. If necessary, copy the Username from the Lab Details panel and paste it into the Sign in dialog. Click Next.

  4. Copy the Password from the Lab Details panel and paste it into the Welcome dialog. Click Next.

    Important: You must use the credentials from the left panel. Do not use your Google Cloud Skills Boost credentials. Note: Using your own Google Cloud account for this lab may incur extra charges.
  5. Click through the subsequent pages:

    • Accept the terms and conditions.
    • Do not add recovery options or two-factor authentication (because this is a temporary account).
    • Do not sign up for free trials.

After a few moments, the Cloud Console opens in this tab.

Note: You can view the menu with a list of Google Cloud Products and Services by clicking the Navigation menu at the top-left. Navigation menu icon

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 States)

location_firestore_datastore.png

  1. Click CREATE DATABASE

Create a Dialogflow agent

  1. In the Console, go to Navigation menu > APIs & Services > Enabled APIs & services.

    618f7fd1b8d1eb67.png

  2. Click on Enable APIs and Services:

    APIandServices_enableAPIs.png

  3. Search for Dialogflow:

    cfbaa6e3758ef1d3.png

  4. Click on the Dialogflow API and if the API is not Enabled, click Enable:

    5b6d77d70f5ee4c3.png

  5. In a new tab, go to dialogflow.cloud.google.com.

  6. Then check the Terms of Service. Click on Accept.

  7. From the left panel, select Create Agent.

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

agent.png

When you're ready, click Create.

Test Completed Task

Click Check my progress to verify your performed task. If you have successfully created a Dialogflow agent, you will see an assessment score.

Create a Dialogflow agent

Now you're ready to get started!

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

31c7b9da04dab9e6.png

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

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?"

Dialogflow_responses.png

Click Save in the top right corner.

Time to test what you built so far. On the right in the Try it now section, type "Hi" and press enter. You should see a Default Response.

11.png

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

Create Intents

Click on Intents in the left pane, then click on Create Intent:

cb7ceca6c1d78624.png

Name the intent "Submit Ticket".

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

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.

Click Save when you're done.

Test Completed Task

Click Check my progress to verify your performed task. If you have successfully created a custom intent, you will see an assessment score.

Create Intents

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.

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.

Click Save when you're done. Next you'll see how the variables are stored and recalled by Dialogflow.

Type in "issue" in Try it now and check the response you get:

59a5371aa01277bb.png

Type in ‘My name is Lily' and check the response you get:

3.png

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.

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.

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" })); }); };

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

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.

The result should look something like this:

2f506edabf29c1de.png

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

Test Completed Task

Click Check my progress to verify your performed task. If you have successfully allowed Fulfillment to store Help Ticket Data, you will see an assessment score.

Allow Fulfillment to Store Help Ticket Data

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

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

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

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.

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:

5.png

Verify that Tickets are Logged in Datastore

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

From the Cloud Console Navigation menu, go to Datastore.

nav_datastore.png

You should see the entry as shown below.

datastore.png

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

Test Completed Task

Click Check my progress to verify your performed task. If tickets get successfully logged in Datastore, you will see an assessment score.

Tickets are Logged in Datastore

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.

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

Click Enable.

Enable.png

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

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"

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.

Test your Understanding

Below are multiple choice questions to reinforce your understanding of this lab's concepts. Answer them to the best of your abilities.

Congratulations!

You're now a chatbot developer!

38616f8aa634e047.png

Finish your quest

This self-paced lab is part of the Machine Learning APIs quest. A quest is a series of related labs that form a learning path. Completing this quest earns you the badge above, to recognize your achievement. You can make your badge public and link to it in your online resume or social media account. Enroll in this quest and get immediate completion credit if you've taken this lab. See other available quests.

Take your next lab

Try out another lab on Machine Learning APIs, like Vertex AI Workbench Notebook: Qwik Start or Entity and Sentiment Analysis with the Natural Language API.

Next steps

Google Cloud training and certification

...helps you make the most of Google Cloud technologies. Our classes include technical skills and best practices to help you get up to speed quickly and continue your learning journey. We offer fundamental to advanced level training, with on-demand, live, and virtual options to suit your busy schedule. Certifications help you validate and prove your skill and expertise in Google Cloud technologies.

Manual Last Updated August 11, 2022
Lab Last Tested August 11, 2022

Copyright 2022 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.