Dialogflow を BigQuery と統合する方法

1. はじめに

この記事では、Dialogflow が会話中に BigQuery に接続し、収集された情報を保存する仕組みについて説明します。以前のラボで作成したものと同じエージェントを使用します。予約スケジューラ」を使用する。エージェントの GCP プロジェクトで、BigQuery にデータセットとテーブルを作成します。次に、BigQuery データセットとテーブル ID を使用して元のフルフィルメントを編集します。最後に、インタラクションが BigQuery に記録されているかどうかをテストします。

以下は、ユーザーからフルフィルメントと BigQuery までのイベントのシーケンス図です。

538029740db09f49.png

学習内容

  • BigQuery でデータセットとテーブルを作成する方法
  • Dialogflow フルフィルメントで BigQuery 接続の詳細を設定する方法。
  • フルフィルメントをテストする方法

前提条件

  • Dialogflow の基本コンセプトと構成。基本的な会話の設計について説明している Dialogflow 入門チュートリアル動画については、次の動画をご覧ください。
  • Dialogflow を使用して予約スケジューラ chatbot を構築する。
  • Dialogflow のエンティティについて
  • フルフィルメント: Dialogflow を Google カレンダーと統合します。

2. BigQuery でデータセットとテーブルを作成する

  1. Google Cloud コンソールに移動します。
  2. Cloud コンソールで、メニュー アイコン gcr >ビッグデータ >BigQuery
  3. 左側のペインにある [リソース] で、プロジェクト ID をクリックします。選択すると、右側に [データセットを作成] が表示されます。
  4. [データセットを作成] をクリックし、名前を付けます。

be9f32a18ebb4a5b.png

  1. データセットが作成されたら、左側のパネルでデータセットをクリックします。右側に [CREATE TABLE] と表示されています。
  2. [テーブルを作成] をクリックし、テーブル名を入力して、画面下部の [テーブルを作成] をクリックします。

d5fd99b68b7e62e0.png

  1. テーブルが作成されたら、左側のパネルでテーブルをクリックします。右側に [スキーマを編集] ボタンが表示されます。
  2. [スキーマを編集] ボタンをクリックし、[フィールドを追加] ボタンをクリックします。「日付」を追加「time」についても同様に繰り返します。そして "type"。
  3. 「DatasetID」と「tableID」をメモしておきます。DatasetID"DatasetID"

e9d9abbe843823df.png

3. BigQuery 接続の詳細を Dialogflow Fulfillment に追加する

  1. Dialogflow エージェントを開き、フルフィルメント インライン エディタを有効にします。この点についてサポートが必要な場合は、前の ラボをご覧ください。
  1. Dialogflow フルフィルメント インライン エディタの package.json" に BigQuery の依存関係が含まれていることを確認します。"@google-cloud/bigquery": "0.12.0"。この記事を進める時点で、必ず最新バージョンの BigQuery を使用してください。
  2. index.js で「addToBigQuery」を作成します。関数を使用して、BigQuery テーブルに日付、時刻、予約タイプを追加します。
  3. index.js ファイルの TODO セクションに、projectIDdatasetIDtableID を追加して、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&quot;」関数を呼び出して、Google カレンダーで予約のスケジュールを設定します。
  2. 同じ関数内で「addToBigQuery」が呼び出されます。BigQuery に記録するデータを送信します。

4. chatbot と BigQuery テーブルをテストする

chatbot をテストしましょう。シミュレータでテストするか、以前の記事で学んだウェブまたは Google Home の統合を使用できます。

  • お客様: 「明日の午後 2 時に車両登録の予定を設定して」
  • chatbot からの回答: 「承知いたしました。よろしければ、こちらでサポートさせていただきます。8 月 6 日午後 2 時で結構です。」

96d3784c103daf5e.png

  • レスポンスの後に BigQuery テーブルを確認します。クエリ「SELECT * FROM projectID.datasetID.tableID」を使用します。

dcbc9f1c06277a21.png

5. クリーンアップ

このシリーズの他のラボを実行する予定の場合は、今はクリーンアップを行わず、シリーズのすべてのラボを完了した後にクリーンアップを行います。

Dialogflow エージェントを削除する

  • 既存のエージェントの横にある歯車アイコン 30a9fea7cfa77c1a.png をクリックします。

520c1c6bb9f46ea6.png

  • [General] タブで下にスクロールし、[Delete this Agent] をクリックします。
  • 表示されたウィンドウに「DELETE」と入力し、[削除] をクリックします。

6. 完了

chatbot を作成し、BigQuery と統合してインサイトを獲得しました。これで chatbot の開発が可能になりました。

以下のリソースもご覧ください。

1217326c0c490fa.png