วิธีผสานรวม Dialogflow กับ BigQuery

1. บทนำ

ในบทความนี้ เราจะมาดูวิธีที่ Dialogflow เชื่อมต่อกับ BigQuery และจัดเก็บข้อมูลที่รวบรวมไว้ระหว่างประสบการณ์การสนทนา เราจะใช้เอเจนต์เดียวกันกับที่สร้างในแล็บก่อนหน้า "เครื่องมือตั้งเวลาการนัดหมาย" ในโปรเจ็กต์ GCP ของตัวแทน เราจะสร้างชุดข้อมูลและตารางใน BigQuery จากนั้นเราจะแก้ไขการดำเนินการตามคำสั่งเดิมด้วยรหัสชุดข้อมูลและตาราง BigQuery สุดท้าย เราจะทดสอบเพื่อดูว่าระบบบันทึกการโต้ตอบใน BigQuery หรือไม่

ต่อไปนี้คือแผนภาพลําดับเหตุการณ์จากผู้ใช้ไปยังการปฏิบัติตามคําสั่งและ BigQuery

538029740db09f49.png

สิ่งที่คุณจะได้เรียนรู้

  • วิธีสร้างชุดข้อมูลและตารางใน BigQuery
  • วิธีตั้งค่ารายละเอียดการเชื่อมต่อ BigQuery ในการดำเนินการตามคำสั่งของ Dialogflow
  • วิธีทดสอบการดำเนินการตามคำสั่งซื้อ

ข้อกำหนดเบื้องต้น

  • แนวคิดและโครงสร้างพื้นฐานของ Dialogflow หากต้องการดูวิดีโอสอน Dialogflow เบื้องต้นที่ครอบคลุมการออกแบบการสนทนาขั้นพื้นฐาน ให้ดูวิดีโอต่อไปนี้
  • สร้างแชทบอทเครื่องมือจัดกำหนดการนัดหมายโดยใช้ Dialogflow
  • ทำความเข้าใจเอนทิตีใน Dialogflow
  • การดำเนินการตามคำสั่ง: ผสานรวม Dialogflow กับ Google ปฏิทิน

2. สร้างชุดข้อมูลและตารางใน BigQuery

  1. ไปที่ Google Cloud Console
  2. ใน Cloud Console ให้ไปที่ไอคอนเมนู ☰ > ข้อมูลขนาดใหญ่ > BigQuery
  3. ในส่วนทรัพยากรในบานหน้าต่างด้านซ้าย ให้คลิกรหัสโปรเจ็กต์ เมื่อเลือกแล้ว คุณจะเห็นสร้างชุดข้อมูลทางด้านขวา
  4. คลิกสร้างชุดข้อมูลและตั้งชื่อ

be9f32a18ebb4a5b.png

  1. เมื่อสร้างชุดข้อมูลแล้ว ให้คลิกชุดข้อมูลจากแผงด้านซ้าย คุณจะเห็น CREATE TABLE ทางด้านขวา
  2. คลิกสร้างตาราง ระบุชื่อตาราง แล้วคลิกสร้างตารางที่ด้านล่างของหน้าจอ

d5fd99b68b7e62e0.png

  1. เมื่อสร้างตารางแล้ว ให้คลิกตารางจากแผงด้านซ้าย คุณจะเห็นปุ่ม "แก้ไขสคีมา" ทางด้านขวา
  2. คลิกปุ่มแก้ไขสคีมา แล้วคลิกปุ่มเพิ่มช่อง เพิ่มฟิลด์ "date" แล้วทำซ้ำสำหรับ "time" และ "type"
  3. จด "DatasetID" และ "tableID" ไว้

e9d9abbe843823df.png

3. เพิ่มรายละเอียดการเชื่อมต่อ BigQuery ลงในการจัดการของ Dialogflow

  1. เปิดเอเจนต์ Dialogflow แล้วเปิดใช้เครื่องมือแก้ไขแบบอินไลน์ของ Fulfillment โปรดดูแล็บก่อนหน้า หากต้องการความช่วยเหลือเกี่ยวกับเรื่องนี้
  1. ตรวจสอบว่า "package.json" ในเครื่องมือแก้ไขแบบอินไลน์ของ Fulfillment ของ Dialogflow มีการอ้างอิง BigQuery "@google-cloud/bigquery": "0.12.0". โปรดตรวจสอบว่าคุณใช้ BigQuery เวอร์ชันล่าสุดในขณะที่อ่านบทความนี้
  2. ใน index.js ให้สร้างฟังก์ชัน "addToBigQuery" เพื่อเพิ่มวันที่ เวลา และประเภทการนัดหมายในตาราง BigQuery
  3. เพิ่ม projectID, datasetID และ tableID ในส่วน TODO ของไฟล์ index.js เพื่อเชื่อมต่อตาราง BigQuery และชุดข้อมูลกับการปฏิบัติตามคำสั่งอย่างถูกต้อง
{
  "name": "dialogflowFirebaseFulfillment",
  "description": "Dialogflow fulfillment for the bike shop sample",
  "version": "0.0.1",
  "private": true,
  "license": "Apache Version 2.0",
  "author": "Google Inc.",
  "engines": {
    "node": "6"
  },
  "scripts": {
    "lint": "semistandard --fix \"**/*.js\"",
    "start": "firebase deploy --only functions",
    "deploy": "firebase deploy --only functions"
  },
  "dependencies": {
    "firebase-functions": "2.0.2",
    "firebase-admin": "^5.13.1",
    "actions-on-google": "2.2.0", 
    "googleapis": "^27.0.0",
    "dialogflow-fulfillment": "0.5.0",
    "@google-cloud/bigquery": "^0.12.0"
  }
}
'use strict';

const functions = require('firebase-functions');
const {google} = require('googleapis');
const {WebhookClient} = require('dialogflow-fulfillment');
const BIGQUERY = require('@google-cloud/bigquery');


// Enter your calendar ID below and service account JSON below
const calendarId = "XXXXXXXXXXXXXXXXXX@group.calendar.google.com";
const serviceAccount = {}; // Starts with {"type": "service_account",...

// Set up Google Calendar Service account credentials
const serviceAccountAuth = new google.auth.JWT({
  email: serviceAccount.client_email,
  key: serviceAccount.private_key,
  scopes: 'https://www.googleapis.com/auth/calendar'
});

const calendar = google.calendar('v3');
process.env.DEBUG = 'dialogflow:*'; // enables lib debugging statements

const timeZone = 'America/Los_Angeles';
const timeZoneOffset = '-07:00';

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });
  console.log("Parameters", agent.parameters);
  const appointment_type = agent.parameters.AppointmentType;

// Function to create appointment in calendar  
function makeAppointment (agent) {
    // Calculate appointment start and end datetimes (end = +1hr from start)
    const dateTimeStart = new Date(Date.parse(agent.parameters.date.split('T')[0] + 'T' + agent.parameters.time.split('T')[1].split('-')[0] + timeZoneOffset));
    const dateTimeEnd = new Date(new Date(dateTimeStart).setHours(dateTimeStart.getHours() + 1));
    const appointmentTimeString = dateTimeStart.toLocaleString(
      'en-US',
      { month: 'long', day: 'numeric', hour: 'numeric', timeZone: timeZone }
    );
  
// Check the availability of the time, and make an appointment if there is time on the calendar
    return createCalendarEvent(dateTimeStart, dateTimeEnd, appointment_type).then(() => {
      agent.add(`Ok, let me see if we can fit you in. ${appointmentTimeString} is fine!.`);

// Insert data into a table
      addToBigQuery(agent, appointment_type);
    }).catch(() => {
      agent.add(`I'm sorry, there are no slots available for ${appointmentTimeString}.`);
    });
  }

  let intentMap = new Map();
  intentMap.set('Schedule Appointment', makeAppointment);
  agent.handleRequest(intentMap);
});

//Add data to BigQuery
function addToBigQuery(agent, appointment_type) {
    const date_bq = agent.parameters.date.split('T')[0];
    const time_bq = agent.parameters.time.split('T')[1].split('-')[0];
    /**
    * TODO(developer): Uncomment the following lines before running the sample.
    */
    //const projectId = '<INSERT your own project ID here>'; 
    //const datasetId = "<INSERT your own dataset name here>";
    //const tableId = "<INSERT your own table name here>";
    const bigquery = new BIGQUERY({
      projectId: projectId
    });
   const rows = [{date: date_bq, time: time_bq, type: appointment_type}];
  
   bigquery
  .dataset(datasetId)
  .table(tableId)
  .insert(rows)
  .then(() => {
    console.log(`Inserted ${rows.length} rows`);
  })
  .catch(err => {
    if (err && err.name === 'PartialFailureError') {
      if (err.errors && err.errors.length > 0) {
        console.log('Insert errors:');
        err.errors.forEach(err => console.error(err));
      }
    } else {
      console.error('ERROR:', err);
    }
  });
  agent.add(`Added ${date_bq} and ${time_bq} into the table`);
}

// Function to create appointment in google calendar  
function createCalendarEvent (dateTimeStart, dateTimeEnd, appointment_type) {
  return new Promise((resolve, reject) => {
    calendar.events.list({
      auth: serviceAccountAuth, // List events for time period
      calendarId: calendarId,
      timeMin: dateTimeStart.toISOString(),
      timeMax: dateTimeEnd.toISOString()
    }, (err, calendarResponse) => {
      // Check if there is a event already on the Calendar
      if (err || calendarResponse.data.items.length > 0) {
        reject(err || new Error('Requested time conflicts with another appointment'));
      } else {
        // Create event for the requested time period
        calendar.events.insert({ auth: serviceAccountAuth,
          calendarId: calendarId,
          resource: {summary: appointment_type +' Appointment', description: appointment_type,
            start: {dateTime: dateTimeStart},
            end: {dateTime: dateTimeEnd}}
        }, (err, event) => {
          err ? reject(err) : resolve(event);
        }
        );
      }
    });
  });
}

ทําความเข้าใจลําดับเหตุการณ์จากโค้ด

  1. แผนที่ความตั้งใจจะเรียกฟังก์ชัน "makeAppointment" เพื่อกำหนดเวลานัดหมายใน Google ปฏิทิน
  2. ภายในฟังก์ชันเดียวกัน ระบบจะเรียกใช้ฟังก์ชัน "addToBigQuery" เพื่อส่งข้อมูลที่จะบันทึกลงใน BigQuery

4. ทดสอบแชทบอทและตาราง BigQuery

มาทดสอบแชทบอทกัน คุณสามารถทดสอบในโปรแกรมจำลอง หรือใช้การผสานรวมเว็บหรือ Google Home ที่เราได้เรียนรู้ในบทความก่อนหน้า

  • ผู้ใช้: "นัดหมายการจดทะเบียนยานพาหนะเวลา 14:00 น. พรุ่งนี้"
  • คำตอบของแชทบอท: "ได้ค่ะ เดี๋ยวฉันจะดูว่าเราจะจัดเวลาให้คุณได้ไหม วันที่ 6 สิงหาคม เวลา 14:00 น. ก็ได้"

96d3784c103daf5e.png

  • ตรวจสอบตาราง BigQuery หลังจากได้รับการตอบกลับ ใช้การค้นหา "SELECT * FROM projectID.datasetID.tableID"

dcbc9f1c06277a21.png

5. ล้างข้อมูล

หากคุณวางแผนที่จะทำแล็บอื่นๆ ในชุดนี้ อย่าล้างข้อมูลตอนนี้ ให้ทำหลังจากที่ทำแล็บทั้งหมดในชุดนี้เสร็จแล้ว

ลบ Agent ของ Dialogflow

  • คลิกไอคอนรูปเฟือง 30a9fea7cfa77c1a.png ข้างตัวแทนที่มีอยู่

520c1c6bb9f46ea6.png

  • ในแท็บทั่วไป ให้เลื่อนลงไปที่ด้านล่างแล้วคลิกลบเอเจนต์นี้
  • พิมพ์ DELETE ในหน้าต่างที่ปรากฏขึ้น แล้วคลิกลบ

6. ยินดีด้วย

คุณสร้างแชทบอทและผสานรวมกับ BigQuery เพื่อรับข้อมูลเชิงลึก ตอนนี้คุณเป็นนักพัฒนาแชทบ็อตแล้ว

ดูแหล่งข้อมูลอื่นๆ เหล่านี้

  • ดูตัวอย่างโค้ดได้ที่หน้า Dialogflow Github

1217326c0c490fa.png