1. Giới thiệu
Trong bài viết này, chúng ta sẽ tìm hiểu cách Dialogflow kết nối với BigQuery và lưu trữ thông tin được thu thập trong trải nghiệm đàm thoại. Chúng ta sẽ sử dụng cùng một Agent mà chúng ta đã tạo trong các phòng thí nghiệm trước đây " Appointment Scheduler". Trong dự án GCP của Agent, chúng ta sẽ tạo một tập dữ liệu và một bảng trong BigQuery. Sau đó, chúng ta sẽ chỉnh sửa yêu cầu thực hiện ban đầu bằng mã nhận dạng tập dữ liệu và bảng BigQuery. Cuối cùng, chúng ta sẽ kiểm tra xem các lượt tương tác có được ghi lại trong BigQuery hay không.
Sau đây là sơ đồ trình tự của các sự kiện từ người dùng đến việc thực hiện và BigQuery.

Kiến thức bạn sẽ học được
- Cách tạo tập dữ liệu và bảng trong BigQuery
- Cách thiết lập thông tin kết nối BigQuery trong tính năng thực hiện của Dialogflow.
- Cách kiểm tra việc thực hiện đơn đặt hàng
Điều kiện tiên quyết
- Các khái niệm và cấu trúc cơ bản của Dialogflow. Để xem các video hướng dẫn giới thiệu về Dialogflow đề cập đến thiết kế đàm thoại cơ bản, hãy xem các video sau:
- Tạo một chatbot Lên lịch hẹn bằng Dialogflow.
- Tìm hiểu về thực thể trong Dialogflow.
- Thực hiện: Tích hợp Dialogflow với Lịch Google.
2. Tạo tập dữ liệu và bảng trong BigQuery
- Chuyển đến Google Cloud Console
- Trong bảng điều khiển Cloud, hãy chuyển đến biểu tượng trình đơn ☰ > Dữ liệu lớn > BigQuery
- Trong phần Tài nguyên ở ngăn bên trái, hãy nhấp vào mã dự án. Sau khi chọn, bạn sẽ thấy nút TẠO TẬP DỮ LIỆU ở bên phải
- Nhấp vào TẠO TẬP DỮ LIỆU rồi đặt tên cho tập dữ liệu.

- Sau khi tạo tập dữ liệu, hãy nhấp vào tập dữ liệu đó trong bảng điều khiển bên trái. Bạn sẽ thấy CREATE TABLE ở bên phải.
- Nhấp vào CREATE TABLE (Tạo bảng), nhập Tên bảng rồi nhấp vào Create table (Tạo bảng) ở cuối màn hình.

- Sau khi tạo bảng, hãy nhấp vào bảng đó trong bảng điều khiển bên trái. Bạn sẽ thấy nút "Chỉnh sửa giản đồ" ở bên phải.
- Nhấp vào nút Chỉnh sửa giản đồ rồi nhấp vào nút Thêm trường. Thêm trường "date" và lặp lại thao tác tương tự cho "time" và "type".
- Ghi lại "DatasetID" và "tableID"

3. Thêm thông tin chi tiết về kết nối BigQuery vào tính năng Thực hiện của Dialogflow
- Mở Nhân viên hỗ trợ Dialogflow và bật trình chỉnh sửa nội dung thực hiện trực tuyến. Hãy tham khảo phòng thí nghiệm trước đó nếu bạn cần trợ giúp về vấn đề này .
- Đảm bảo rằng "package.json" trong trình chỉnh sửa nội tuyến của Dialogflow fulfillment có chứa một phần phụ thuộc BigQuery. "@google-cloud/bigquery": "0.12.0". Hãy đảm bảo rằng bạn sử dụng phiên bản BigQuery mới nhất tại thời điểm bạn đang đọc bài viết này.
- Trong index.js, hãy tạo hàm "addToBigQuery" để thêm ngày, giờ và loại cuộc hẹn vào bảng BigQuery.
- Thêm projectID, datasetID và tableID vào phần TODO của tệp index.js để kết nối đúng cách bảng BigQuery và tập dữ liệu với yêu cầu thực hiện của bạn.
{
"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);
}
);
}
});
});
}
Tìm hiểu trình tự các sự kiện từ mã
- Bản đồ ý định gọi hàm "makeAppointment" để lên lịch hẹn trên Lịch Google
- Trong cùng một hàm, một lệnh gọi được thực hiện đến hàm "addToBigQuery" để gửi dữ liệu cần ghi vào BigQuery.
4. Kiểm thử Chatbot và Bảng BigQuery!
Hãy kiểm thử chatbot của chúng ta. Bạn có thể kiểm thử trong trình mô phỏng hoặc sử dụng tính năng tích hợp web hoặc Google Home mà chúng ta đã tìm hiểu trong các bài viết trước.
- Người dùng: "Đặt lịch hẹn đăng ký xe lúc 2 giờ chiều mai"
- Phản hồi của chatbot: "Ok, let me see if we can fit you in. Ngày 6 tháng 8, 2 giờ chiều là được!"

- Kiểm tra bảng BigQuery sau khi nhận được phản hồi. Sử dụng truy vấn "SELECT * FROM
projectID.datasetID.tableID"

5. Dọn dẹp
Nếu bạn dự định thực hiện các phòng thí nghiệm khác trong loạt bài này, thì đừng dọn dẹp ngay bây giờ mà hãy dọn dẹp sau khi hoàn thành tất cả các phòng thí nghiệm trong loạt bài này.
Xoá tác nhân Dialogflow
- Nhấp vào biểu tượng bánh răng
bên cạnh tác nhân hiện có

- Trong thẻ Chung, hãy di chuyển xuống dưới cùng rồi nhấp vào Xoá Agent này.
- Nhập XOÁ vào cửa sổ xuất hiện rồi nhấp vào Xoá.
6. Xin chúc mừng!
Bạn đã tạo một chatbot và tích hợp chatbot đó với BigQuery để thu thập thông tin chi tiết. Bạn hiện là nhà phát triển chatbot!
Hãy tham khảo các tài nguyên khác sau đây:
- Hãy xem các mã mẫu tại trang Dialogflow Github.
