1. Pengantar
Dalam artikel ini, kita akan mempelajari bagaimana Dialogflow terhubung dengan BigQuery dan menyimpan informasi yang dikumpulkan selama pengalaman percakapan. Kami akan menggunakan Agen yang sama dengan yang kami buat di lab sebelumnya " Penjadwal Janji Temu". Dalam project GCP Agen, kita akan membuat set data dan tabel di BigQuery. Kemudian kita akan mengedit fulfillment asli dengan set data BigQuery dan ID tabel. Terakhir, kita akan menguji untuk melihat apakah interaksi dicatat di BigQuery.
Berikut adalah diagram urutan peristiwa dari pengguna ke fulfillment dan BigQuery.
Yang akan Anda pelajari
- Cara membuat set data dan tabel di BigQuery
- Cara menyiapkan detail koneksi BigQuery dalam fulfillment Dialogflow.
- Cara menguji fulfillment
Prasyarat
- Konsep dan konstruksi dasar Dialogflow. Untuk video tutorial pengantar Dialogflow yang mencakup desain percakapan dasar, lihat video berikut:
- Buat Chatbot Penjadwal Janji Temu menggunakan Dialogflow.
- Memahami Entity di Dialogflow.
- Fulfillment: Mengintegrasikan Dialogflow dengan Google Kalender.
2. Membuat Set Data dan Tabel di BigQuery
- Buka Konsol Google Cloud
- Di Konsol Cloud, buka ikon menu Name > {i>Big Data<i} > BigQuery
- Di bawah Resources pada panel kiri, klik project ID. Setelah dipilih, Anda akan melihat CREATE DATASET di sebelah kanan
- Tekan klik pada CREATE DATASET dan beri nama.
- Setelah set data dibuat, klik set data tersebut dari panel kiri. Anda akan melihat CREATE TABLE di sebelah kanan.
- Tekan klik pada {i>CREATE TABLE<i}, berikan nama Tabel dan klik {i>Create table<i} di bagian bawah layar.
- Setelah tabel dibuat, klik tabel dari panel kiri. Anda akan melihat tombol "Edit Skema" di sisi kanan.
- Tekan klik pada tombol Edit Schema kemudian klik tombol Add Field. Tambahkan "date" dan ulangi hal yang sama untuk "time" dan "type".
- Catat "DatasetID" dan "DatasetID"
3. Menambahkan detail koneksi BigQuery ke Dialogflow Fulfillment
- Buka Agen Dialogflow dan aktifkan editor inline Fulfillment. Lihat lab sebelumnya jika Anda memerlukan bantuan terkait hal ini .
- Pastikan "package.json" di editor inline fulfillment Dialogflow berisi dependensi BigQuery. "@google-cloud/bigquery": "0.12.0". Pastikan Anda menggunakan BigQuery versi terbaru pada saat mengikuti artikel ini.
- Di index.js, buat "addToBigQuery" untuk menambahkan tanggal, waktu, dan jenis janji temu di tabel BigQuery.
- Tambahkan projectID, datasetID, dan tableID di bagian TODO pada file index.js untuk menghubungkan tabel BigQuery dan set data dengan benar ke fulfillment Anda.
{
"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);
}
);
}
});
});
}
Memahami urutan peristiwa dari kode
- Peta intent memanggil fungsi "makeAppointment" untuk menjadwalkan janji temu di Google Kalender
- Dalam fungsi yang sama, panggilan akan dilakukan ke "addToBigQuery" fungsi untuk mengirim data yang akan masuk ke BigQuery.
4. Uji Chatbot dan Tabel BigQuery Anda.
Mari kita uji chatbot kami. Anda dapat mengujinya di simulator atau menggunakan integrasi web atau Google Home yang telah kita pelajari di artikel sebelumnya.
- Pengguna: "Tetapkan janji temu untuk pendaftaran kendaraan pukul 2 siang besok"
- Tanggapan Chatbot: "Oke, sebentar lagi kita akan membahasnya. 6 Agustus, jam 2 siang sudah cukup!."
- Periksa tabel BigQuery setelah menemukan respons. Gunakan kueri "SELECT * FROM
projectID.datasetID.tableID
"
5. Pembersihan
Jika Anda berencana mengerjakan lab lain dalam seri ini, jangan lakukan pembersihan sekarang. Lakukan setelah Anda menyelesaikan semua lab dalam seri ini.
Menghapus Agen Dialogflow
- Klik ikon roda gigi
di samping agen yang ada
- Di tab Umum, scroll ke bawah, lalu klik Hapus Agen ini.
- Ketik HAPUS ke dalam jendela yang muncul, lalu klik Hapus.
6. Selamat!
Anda telah membuat chatbot dan mengintegrasikannya dengan BigQuery untuk mendapatkan insight. Sekarang Anda menjadi developer chatbot!
Lihat referensi lainnya:
- Lihat contoh kode di halaman GitHub Dialogflow.