arrow_back

Integrating BigQuery ML with Dialogflow ES Chatbot

Join Sign in

Integrating BigQuery ML with Dialogflow ES Chatbot

1 hour 1 Credit

GSP431

Google Cloud self-paced labs logo

Overview

Wouldn’t it be awesome to have an accurate estimate of how long it will take for tech support to resolve your issue? In this lab you will train a simple machine learning model for predicting helpdesk response time using BigQuery Machine Learning. You will then build a simple chatbot using Dialogflow, and learn how to integrate your trained BigQuery ML model with your helpdesk chatbot. The final solution will provide an estimate of response time to users at the moment a request is generated.

The exercises are ordered to reflect a common cloud developer experience:

  1. Train a model using BigQuery Machine Learning
  2. Deploy a simple Dialogflow application
  3. Use an inline code editor within Dialogflow for deploying a Node.js fulfillment script that integrates BigQuery
  4. Test your chatbot

What you'll learn

  • How to train a machine learning model using BigQuery ML
  • How to evaluate and improve a machine learning model using BigQuery ML
  • How to import intents & entities into a Dialogflow agent
  • How to implement custom Node.js fulfillment scripts
  • How to integrate BigQuery with Dialogflow

Prerequisites

  • Basic concepts and constructs of Dialogflow. Check out these Tutorials & Samples for an introductory Dialogflow tutorial that covers basic conversational design and fulfillment using a webhook.
  • Basic SQL and Node.js (or any coding language) knowledge.

Solution feedback/lab help

Setup lab

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 Cloud 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 Cloud console (or right-click and select Open Link in Incognito Window if you are running the Chrome browser).

    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 below and paste it into the Sign in dialog.

    {{{user_0.username | "Username"}}}

    You can also find the Username in the Lab Details panel.

  4. Click Next.

  5. Copy the Password below and paste it into the Welcome dialog.

    {{{user_0.password | "Password"}}}

    You can also find the Password in the Lab Details panel.

  6. Click Next.

    Important: You must use the credentials the lab provides you. Do not use your Google Cloud account credentials. Note: Using your own Google Cloud account for this lab may incur extra charges.
  7. 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 Google Cloud console opens in this tab.

Note: To view a menu with a list of Google Cloud products and services, click the Navigation menu at the top-left. Navigation menu icon

Activate Cloud Shell

Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud. Cloud Shell provides command-line access to your Google Cloud resources.

  1. Click Activate Cloud Shell Activate Cloud Shell icon at the top of the Google Cloud console.

When you are connected, you are already authenticated, and the project is set to your Project_ID, . The output contains a line that declares the Project_ID for this session:

Your Cloud Platform project in this session is set to {{{project_0.project_id | "PROJECT_ID"}}}

gcloud is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.

  1. (Optional) You can list the active account name with this command:
gcloud auth list
  1. Click Authorize.

Output:

ACTIVE: * ACCOUNT: {{{user_0.username | "ACCOUNT"}}} To set the active account, run: $ gcloud config set account `ACCOUNT`
  1. (Optional) You can list the project ID with this command:
gcloud config list project

Output:

[core] project = {{{project_0.project_id | "PROJECT_ID"}}} Note: For full documentation of gcloud, in Google Cloud, refer to the gcloud CLI overview guide.

Add data for lab

  • Run the following commands to create a bucket in your current project, then add the data needed to build a table for this lab:
PROJECT_ID=`gcloud config get-value project` BUCKET=${PROJECT_ID}-bucket gsutil mb gs://$BUCKET gsutil cp -r gs://spls/gsp431/* gs://$BUCKET

Task 1. Train a model using BigQuery machine learning

Open the BigQuery console

  1. In the Google Cloud Console, select Navigation menu > BigQuery.

The Welcome to BigQuery in the Cloud Console message box opens. This message box provides a link to the quickstart guide and the release notes.

  1. Click Done.

The BigQuery console opens.

  1. In the left pane, under Explorer section, click on the View actions icon next to your project ID, then select Create dataset.

The option 'Create dataset' highlighted within the project menu.

  1. For Dataset ID, type helpdesk.

  2. Select us(multiple regions in United States) as the location.

  3. Click Create dataset.

Test completed task

To check your progress in this lab, click Check my progress below. A checkmark means you're on track.

Create a BigQuery dataset
  1. In the left menu, click the View actions icon next to helpdesk dataset you just created, then select Open in > New Tab.

  2. Click Create table.

The 'Create table' button highlighted within the Helpdesk dataset tab.

  1. Use the following parameters to create a new table leaving the defaults for all other fields:

Properties

Values

Create table from

Google Cloud Storage

Select file from GCS bucket

YOUR BUCKET/ml/issues.csv

File format

CSV

Table name

issues

Auto detect

Check the check-box for Schema

Advanced options > Header rows to skip

1

Note: Replace YOUR BUCKET with the bucket id through Navigation menu > Cloud Storage.
  1. Click Create table.

This will trigger a job that loads the source data into a new BigQuery table. It will take about 30 seconds for the job to complete, and you can view it by selecting Job History from the bottom.

Test completed task

To check your progress in this lab, click Check my progress below. A checkmark means you're on track.

Create a new table in BigQuery dataset
  1. In BigQuery click + Compose new query and add the following query:
SELECT * FROM `helpdesk.issues` LIMIT 1000
  1. Click Run and examine the data.

In the next query, the data fields category and resolutiontime are used to build a machine learning model that predicts how long it will take to resolve an issue. The model type is a simple linear regression, and the trained model will be named predict_eta_v0 in the helpdesk dataset.

  1. Clear the previous query from the editor and run this query, it takes about 1 minute to complete:
CREATE OR REPLACE MODEL `helpdesk.predict_eta_v0` OPTIONS(model_type='linear_reg') AS SELECT category, resolutiontime as label FROM `helpdesk.issues`

Test completed task

To check your progress in this lab, click Check my progress below. A checkmark means you're on track.

Build an ML model to predicts time taken to resolve an issue
  1. Clear the previous query from the editor and run the following query to evaluate the machine learning model you just created. The metrics generated by this query tell us how well the model is likely to perform.
WITH eval_table AS ( SELECT category, resolutiontime as label FROM helpdesk.issues ) SELECT * FROM ML.EVALUATE(MODEL helpdesk.predict_eta_v0, TABLE eval_table)

The query results, along with metrics such as variance, score, and errors.

Using the evaluation metrics, we can see that the model doesn't perform very well. When the r2\_score and explained\_variance metrics are close to 0, our algorithm is having difficulty distinguishing the signal in our data from the noise.

We are going to use a few more fields during training and see if there is an improvement: seniority, experience & type. The final trained model will be named predict_eta.

  1. Clear the previous query from the editor, and run the following query:
CREATE OR REPLACE MODEL `helpdesk.predict_eta` OPTIONS(model_type='linear_reg') AS SELECT seniority, experience, category, type, resolutiontime as label FROM `helpdesk.issues`
  1. Now, run the following query to evaluate the updated machine learning model you just created:
WITH eval_table AS ( SELECT seniority, experience, category, type, resolutiontime as label FROM helpdesk.issues ) SELECT * FROM ML.EVALUATE(MODEL helpdesk.predict_eta, TABLE eval_table)

Test completed task

To check your progress in this lab, click Check my progress below. A checkmark means you're on track.

Run the query to evaluate the ML model

After adding the additional fields during training, we can see that our model has improved. When the metrics r2\_score and explained\_variance are close to 1, there is evidence to suggest that our model is capturing a strong linear relationship. We can also see that our error metrics are lower than before, which means our model will likely perform better.

The new query results, with an r2 score of 0.7047503529486896, and an explained variance of 0.7047507586451964.

  • Now we can execute a query to get a prediction of resolution time for a given scenario:
WITH pred_table AS ( SELECT 5 as seniority, '3-Advanced' as experience, 'Billing' as category, 'Request' as type ) SELECT * FROM ML.PREDICT(MODEL `helpdesk.predict_eta`, TABLE pred_table)

The query results which will indicate the average response time, i.e. seniority, experience, category, and type.

When seniority is 5, experience is 3-Advanced, category is Billing, and type is Request, our model is saying that the average response time is 3.74 days.

Task 2. Create a Dialogflow agent

In a new browser tab, create an Agent at Dialogflow.

  1. Go to Dialogflow.com.

  2. If required, click Sign-in with Google, then use the credentials you logged into this lab with.

  3. Check Yes, I have read and accept the agreement, and then Accept the agreement.

  4. In the left menu, click on Create Agent.

  5. Name your agent and select other properties such as language and time zone.

  6. Set Google Project to your Qwiklabs ID.

    The DFflow-agent dialog box, along with the information that's been entered, such as language, project name, and time zone.

  7. When you're ready, click Create.

Test completed task

To check your progress in this lab, click Check my progress below. A checkmark means you're on track.

Create a Dialogflow Agent

Task 3. Import intents & entities for a simple helpdesk agent

To save time, instead of configuring an agent from scratch, you are going to import the intents and entities for an existing helpdesk agent.

Import an IT helpdesk agent

  1. Download settings file from GitHub and save it to your local computer.

  2. Still in the Diagflow console, click the hamburger icon in the top left to open the left panel.

  3. Click the gear icon (Gear icon) next to your existing agent.

The gear icon highlighted next to the DFflow-agent.

  1. Click on Export and Import tab from the list of settings.
  2. Select Import from zip.
  3. Select the ml-helpdesk-agent.zip file from your local computer.
  4. Type IMPORT in the given textbox and click Import.
  5. Click Done.
  6. Once the import completes, use the left panel to navigate to Intents.
  7. Examine the intents that were imported.

Submit Ticket is the main intent, which has the follow-up intents Submit Ticket - Email and Submit Ticket - Issue Category.

  • Submit Ticket - Email is used to collect a user's email address.
  • Submit Ticket - Issue Category is used to collect the issue description from the user and automatically infer a support category.
  1. Use the left panel to navigate to Entities and look at the @category entity.

This entity will be used to map a request description that the user provides to support category. The support category will be used for predicting response time.

Test completed task

To check your progress in this lab, click Check my progress below. A checkmark means you're on track.

Import an IT Helpdesk Agent

Task 4. Use the Inline Editor to create a fulfillment that integrates with BigQuery

Note: The code doesn't store the ticket. It only sends a decorated message back to the user to demonstrate the possibilities.
  1. Click on Fulfillment in the left panel and switch the Inline Editor toggle to Enabled.

The Inline Editor's toggle set as enabled on the Fulfillment page.

Note: 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.
  1. Copy the following code and paste it in the index.js tab, replacing the existing content:
/** * Copyright 2020 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; const functions = require("firebase-functions"); const { WebhookClient } = require("dialogflow-fulfillment"); const { Card, Payload } = require("dialogflow-fulfillment"); const { BigQuery } = require("@google-cloud/bigquery"); const bigquery = new BigQuery({ projectId: "your-project-id" // ** CHANGE THIS ** }); process.env.DEBUG = "dialogflow:debug"; function welcome(agent) { agent.add(`Welcome to my agent!`); } function fallback(agent) { agent.add(`I didn't understand`); agent.add(`I'm sorry, can you try again?`); } async function etaPredictionFunction(agent) { const issueCategory = agent.getContext('submitticket-email-followup').parameters.category; const sqlQuery = `WITH pred_table AS (SELECT 5 as seniority, "3-Advanced" as experience, @category as category, "Request" as type) SELECT cast(predicted_label as INT64) as predicted_label FROM ML.PREDICT(MODEL helpdesk.predict_eta, TABLE pred_table)`; const options = { query: sqlQuery, location: "US", params: { category: issueCategory } }; const [rows] = await bigquery.query(options); return rows; } async function ticketCollection(agent) { const email = agent.getContext('submitticket-email-followup').parameters.email; const issueCategory = agent.getContext('submitticket-email-followup').parameters.category; let etaPrediction = await etaPredictionFunction(agent); agent.setContext({ name: "submitticket-collectname-followup", lifespan: 2 }); agent.add(`Your ticket has been created. Someone will contact you shortly at ${email}. The estimated response time is ${etaPrediction[0].predicted_label} days.`); } exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => { const agent = new WebhookClient({ request, response }); console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers)); console.log('Dialogflow Request body: ' + JSON.stringify(request.body)); let intentMap = new Map(); intentMap.set("Default Welcome Intent", welcome); intentMap.set("Default Fallback Intent", fallback); intentMap.set("Submit Ticket - Issue Category", ticketCollection); agent.handleRequest(intentMap); });
  1. While in this file update the BIGQUERY_CLIENT variable.
  2. Replace your-project-id with your Project ID.

Notice that your fulfillment script contains the ML.PREDICT function in Query statement. This is what is going to return a prediction of response time back to the client. Dialogflow will automatically categorize the ticket description and send the category to BigQuery ML for predicting issue response time.

The ML.Prediction function highlighted within the fulfillment script: ML.PREDICT(MODEL helpdest.predict_eta, TABLE pred_table)'.

  1. Copy the following code and paste it in the package.json tab, replacing the existing content:
{ "name": "dialogflowFirebaseFulfillment", "description": "This is the default fulfillment for a Dialogflow agents using Cloud Functions for Firebase", "version": "0.0.1", "private": true, "license": "Apache Version 2.0", "author": "Google Inc.", "engines": { "node": "10" }, "scripts": { "start": "firebase serve --only functions:dialogflowFirebaseFulfillment", "deploy": "firebase deploy --only functions:dialogflowFirebaseFulfillment" }, "dependencies": { "actions-on-google": "^2.2.0", "firebase-admin": "^5.13.1", "firebase-functions": "^2.0.2", "dialogflow": "^0.6.0", "dialogflow-fulfillment": "^0.5.0", "@google-cloud/bigquery": "^4.7.0" } }
  1. Click the Deploy button. Wait until you see a message that the deployment was successful. This may take a few minutes.
Note: If the deployment fails, try refreshing and clicking Deploy one more time.

Test completed task

To check your progress in this lab, click Check my progress below. A checkmark means you're on track.

Create a Fulfillment that Integrates with BigQuery

Task 5. Enable webhook for fulfillment

  1. Go back to Intents in the left panel.

  2. Click the down arrow next to Submit Ticket to reveal its follow-up intents.

  3. Click on the last follow-up intent Submit Ticket - Issue Category to open it for editing.

The latest follow-up intent highlighted within the ticket path, i.e. Submit Ticket - Issue Category.

  1. Scroll to the bottom, in the Fulfillment section, verify that Enable webhook call for this intent is turned on.

The option 'Enable webhook call for this intent' turned on.

Task 6. Test your chatbot

At this point, the Dialogflow should be set up.

  • Test it in the Try it now panel on the right by typing in the following conversation, one line at a time:
  1. Hi
  2. I would like to submit a ticket
  3. My email is student@qwiklabs.net
  4. I can't login

The test console, wherein there's a text area to try it out.

The output from #4 should look like:

The text output 'I can't log in' along with the default response.

Note: If you don't see the expected output depicted above, go back to the Fulfillment section of the agent and redeploy the code you copied into the Inline Editor. Also verify that you updated the projectId specified in the code to match your project.

Task 7. Understanding the BigQuery integration

Remember that your BigQuery ML model required other fields to return a prediction: seniority and experience. If this were a real world app, you could programmatically get the user's seniority & experience from a company database using the name or company ID they provide. For this example assume 5 as seniority and 3-Advanced as experience.

The seniority and experience highlighted within the prediction: SELECT 5 as seniority, "3-Advanced" as experience,.

Note: Extra credit

Change the fulfillment script so that your response time prediction is based on a user with 2 as seniority instead of 5. Then retest the bot.

How does this change the Estimated ETA?

To extend this example further, you could also collect the seniority and experience information from the chatbot user by leveraging the Slot Filling functionality in Dialogflow. Read the article Webhook for slot filling to learn more about slot filling in Dialogflow.

Task 8. Test using a one-click integration

Dialogflow provides many types of integrations for your chatbot. Take a look now at a sample web user interface.

  1. Click on Integrations in the Dialogflow left panel.

  2. Click the Web Demo integration.

  3. Click Enable .

Several tiled integrations, including Web Demo, Hangouts Chat, and Slack.

The 'Enable' button highlighted within the Web Demo integration.

  1. Click on the URL link to launch Web Demo:

The highlighted Web Demo URL.

Start using the chat interface by typing in the Ask something... section. If you are using a Chrome browser, click the microphone icon to ask the chatbot your questions. 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 email is student@qwiklabs.net"
  • Provide the ticket details of "My printer is broken"

Congratulations!

You have trained a machine learning model for predicting helpdesk response time using BigQuery Machine Learning.

Finish your quest

This self-paced lab is part of the BigQuery for Machine Learning and Applying BigQuery ML's Classification, Regression, and Demand Forecasting for Retail Applications quests. A quest is a series of related labs that form a learning path. Completing a quest earns you a badge to recognize your achievement. You can make your badge or badges public and link to them in your online resume or social media account. Enroll in any quest that contains this lab and get immediate completion credit. See the Google Cloud Skills Boost catalog to see all available quests.

Next steps/learn more:

Manual last updated Aug 10, 2022

Lab last tested Aug 4, 2022

Copyright 2023 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.