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

1. บทนำ

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

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

538029740db09f49.png

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

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

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

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

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

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

be9f32a18ebb4a5b.png

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

d5fd99b68b7e62e0.png

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

e9d9abbe843823df.png

3. เพิ่มรายละเอียดการเชื่อมต่อ BigQuery ไปยัง Dialogflow Fulfillment

  1. เปิด Agent ของ Dialogflow และเปิดใช้ตัวแก้ไขในบรรทัดของ Fulfillment โปรดดูห้องทดลองก่อนหน้านี้ หากต้องการความช่วยเหลือ
  1. ตรวจสอบว่า "package.json" ในเครื่องมือแก้ไขในบรรทัดของ Fulfillment ของ Dialogflow มีทรัพยากร Dependency ของ BigQuery "@google-cloud/bigquery": "0.12.0" โปรดตรวจสอบว่าคุณใช้ BigQuery เวอร์ชันล่าสุด ณ เวลาที่คุณติดตามบทความนี้
  2. ใน index.js ให้สร้าง "addToBigQuery" เพื่อเพิ่มวันที่ เวลา และประเภทการนัดหมายในตาราง BigQuery
  3. เพิ่ม projectID, datasetID และ tableID ในส่วน TODO ของไฟล์ index.js เพื่อเชื่อมต่อตาราง BigQuery และชุดข้อมูลกับ Fulfillment อย่างถูกต้อง
{
  "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. Intent Map จะเรียกฟังก์ชัน "makeAppointment&quot; เพื่อกำหนดเวลานัดหมายใน 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 เพื่อรับข้อมูลเชิงลึก ตอนนี้คุณเป็นนักพัฒนาแชทบ็อตแล้ว

โปรดดูแหล่งข้อมูลอื่นๆ ต่อไปนี้

1217326c0c490fa.png