使用 Gemini 建構適用於 Google Chat 的應用程式

1. 事前準備

什麼是採用 Gemini 的 Google Chat 應用程式?

採用 Gemini 的 Google Chat 應用程式會執行以下作業:

  • 將您的服務和資源加入 Google Chat,讓使用者不必離開對話就能取得資訊及採取行動。
  • 與生成式 AI 模型 Gemini 整合,以便在特定時間建立或搜尋文字或圖片等資料,簡化工作流程。

為何要整合 Google Chat 應用程式與 Gemini?

生成式 AI 模型 (例如 Gemini) 的常見用途分為以下幾類:

  • 內容創作與強化。生成行銷文案、製作社群媒體貼文、製作寫實圖片、創作音樂,或是協助製作影片內容。
  • 資料搜尋:從非結構化知識庫中擷取重要深入分析資料、產生冗長的文字、將內容分類,或是以更快的速度和速度翻譯語言。
  • 對話:以自然、資訊豐富且充滿創意的對話交流。

Google Chat 內建這些功能,可以直接在熟悉的 Google Chat 介面中整合這些功能,對於想改善使用者體驗和工作效率的使用者來說都是大好機會。

必要條件

建構項目

在本程式碼研究室中,您將使用 Gemini 建構三個 Google Chat 應用程式,以涵蓋上一節介紹的三種用途。

問題管理應用程式 (內容製作和強化)

這個應用程式會執行以下作業:

  • 管理基本互動、應用程式首頁和應用程式驗證,從建立到關閉等問題。
  • 監控訊息,並針對活動和配件小工具提供多元包容協助。

使用 Gemini 執行以下作業:

  • 根據訊息記錄和問題詳細資料產生問題報告。
  • 使用封閉式提示將不含多元包容的字詞分類。

採用的主要技術為 Vertex AI、Gemini、Apps Script 和 Google Workspace API (管理員、Chat、文件、事件)。

22efdecff4601417.png

2d127c63518673b2.png

9aea694937f2f3ed.png

這個應用程式需要 Gemini 才能理解及回答自然語言的問題,以及從非結構化資料傳回來源參照。

採用的主要技術包括 Dialogflow CX 資料儲存庫代理程式、Dialogflow CX Webhook、Google Cloud Functions 和 Gemini。

9468866bfe848bb8.png

意見回饋應用程式 (對話)

這個應用程式需要 Gemini 才能收集及儲存自然語言對話的評論。

採用的主要技術為 Dialogflow CX 代理程式、Dialogflow CX 工具、OpenAPI、Google Cloud Functions 和 Gemini。

99a7a0295f122f31.png

課程內容

  • 如何透過 Vertex AI 整合 Google Chat 應用程式與 Gemini。
  • 如何整合 Google Chat 應用程式與 Dialogflow CX 代理程式。
  • 如何使用 Google Chat 的最新功能:應用程式主畫面、Google Chat 事件和配件小工具。

軟硬體需求

2. 做好準備

初始化資源

在本節中,您將透過偏好的網路瀏覽器存取及設定下列資源。

Apps Script 專案

Apps Script 控制台中,按照下列步驟操作:

  1. 按一下「設定」,然後啟用 Google Apps Script API。

ea06c593b347b9d1.png

  1. 選取所需專案。
  2. 按一下「專案設定」。
  3. 勾選「在編輯器中顯示『appsscript.json』資訊清單檔案」核取方塊。
  4. 將專案重新命名為 Chat Apps Gemini

12c1485bd248b766.png

Google Cloud 專案

Google Cloud 控制台中,按照下列步驟操作:

  1. 選取所需專案。
  2. 依序點選「選單」圖示 >「API 和服務」>「OAuth 同意畫面」>「編輯應用程式」,然後將「應用程式名稱」設為 Chat Apps Gemini

  1. 前往 Google Chat API 設定,然後將「應用程式名稱」和「說明」設為 Chat Apps Gemini

a71f040755da3b8b.png

Google Chat

Google Chat 中按照下列步驟操作:

  1. 視需要與 Google Chat 應用程式發起即時通訊。
  2. 請傳送訊息 (例如 Hello),確保運作正常。

9625418251528ae9.png

將原始碼和資源下載至本機

  1. 下載這個 GitHub 存放區

  1. 在偏好的開發環境中開啟 apps-script/chat-apps-gemini 目錄,然後前往終端機中的同一個目錄。

da9478df97c99194.png

安裝及設定 clasp

我們使用 clasp 輕鬆編輯本機環境的原始碼版本,並將版本推送至 Apps Script 專案。

  1. 在本機環境中安裝最新版的 nodenpmclasp
npm install -g @google/clasp
  1. 使用您的帳戶登入
clasp login

8bc2434e6dc6f22a.png

如果成功,網路瀏覽器會顯示基本確認畫面,並更新包含用戶端憑證的 .clasprc.json 檔案。你可以在終端機中查看所在位置。

e1d833eb4d5b3a8f.png

3. 應用程式 1:建構

查看概念

Vertex AI

Vertex AI 提供建構及使用生成式 AI 所需的一切資源,包含 AI 解決方案、虛擬服務專員建構工具、超過 130 個基礎模型,以及整合式 AI 平台。

c9e9c7a1945b22ac.png

Gemini

Gemini 是 Google 提供的多模態大型語言模型,可透過 Vertex AI 存取。這項技術能幫助人們發揮潛能,增強想像力、激發好奇心,並提高生產力。

進階 Chat 服務

進階 Chat 服務可讓您透過 Apps Script 使用 Google Chat API。這可讓指令碼尋找、建立及修改 Chat 聊天室、新增或移除聊天室成員,以及讀取或發布含有文字、資訊卡、附件和回應的訊息。

審查架構

8c9c7b7328a69ea6.png

這個 Google Chat 應用程式是採用 Apps Script 所打造。運作方式如下:

  1. 使用者透過即時訊息或聊天室傳送訊息給應用程式。
  2. 系統會處理訊息,並在 Apps Script 專案中導入這個應用程式,並與 Google Cloud 專案建立關聯。
  3. 這個應用程式整合了 Google 文件和 Google Chat API。
  4. 應用程式會使用屬性服務保留指令碼屬性中的資料。
  5. 應用程式會傳送即時訊息或原始聊天室中的同步回應。

查看流程

建立問題

7ca0e8ba3c8255bb.png

排解專屬聊天室的問題

51b47714c378a24b.png

從專屬聊天室關閉問題

89e50228deeab0f9.png

查看原始碼

Apps Script 專案包含下列指令碼:

  • Configuration:根據環境要編輯的常數。
  • ChatApp:處理 Google Chat 互動事件,包括訊息、資訊卡點擊、斜線指令和對話方塊。
  • Storage:依賴屬性服務的公用程式函式。
  • ChatAppAuth:需要 Google Chat 應用程式驗證的公用程式函式。
  • Docs:需要 Google 文件的公用程式功能。
  • VertexAi:仰賴 Vertex AI 的公用程式函式。

產生內含 Gemini 和即時通訊空間記錄的報表文件時,會使用以下部分:

appsscript.json

// Enables the Admin SDK Directory and Chat services, which you need to retrieve
// messages and usernames.

"enabledAdvancedServices": [
  ...
  {
    "userSymbol": "AdminDirectory",
    "version": "directory_v1",
    "serviceId": "admin"
  },
  {
    "userSymbol": "Chat",
    "version": "v1",
    "serviceId": "chat"
  }
  ...
]
// Includes the OAuth scopes to request the Admin SDK Directory, Google Chat,
// Google Docs, and Vertex AI APIs.

"oauthScopes": [
  ...
  "https://www.googleapis.com/auth/admin.directory.user.readonly",
  "https://www.googleapis.com/auth/chat.messages.readonly",
  "https://www.googleapis.com/auth/documents",
  "https://www.googleapis.com/auth/cloud-platform",
  ...
]

Configuration.js

// Relies on two constants: the first one is the Google Cloud project ID and the
// second one is the Vertex AI location to be used.

...
const PROJECT_ID = 'replace-with-gcp-project-id';
const VERTEX_AI_LOCATION_ID = 'us-central1';
...

ChatApp.js

// The slash command process function retrieves history, generates content, and passes
// it to the report generator.

function processSlashCommand(event) {
  ...
  if (event.message.slashCommand.commandId == CLOSE_COMMAND_ID
    && event.message.space.type !== "DM") {
    ...
    const history = exportSpaceHistory(spaceId);
    const summary = summarizeSpace(history);
    const docUrl = createReport(
      issue.title, issue.description, resolution, history, summary
    );
    ...
  }
  ...
}
/**
 * Fetches and concatenates the 100 first space messages by using the Google Chat API.
 *
 * Messages with slash commands are filtered (app command invocations).
 *
 * @return {string} concatenate space messages in the format "Sender's name: Message"
 */
function exportSpaceHistory(spaceName) {
  const messages = Chat.Spaces.Messages.list(spaceName, { 'pageSize': 100 }).messages;
  // Returns results after fetching message sender display names.
  let users = new Map();
  return messages
    .filter(message => message.slashCommand === undefined)
    .map(message =>
      `${getUserDisplayName(users, message.sender.name)}: ${message.text}`
    ).join('\n');
}
/**
 * Fetches a user's display name by using the Admin Directory API.
 *
 * A cache is used to only call the API once per user.
 *
 * @param {Map} cache the map containing users previously fetched
 * @param {string} userId the user ID to fetch
 * @return {string} the user's display name
 */
function getUserDisplayName(cache, userId) {
  if (cache.has(userId)) {
    return cache.get(userId);
  }
  let displayName = 'Unknown User';
  try {
    const user = AdminDirectory.Users.get(
      userId.replace("users/", ""),
      { projection: 'BASIC', viewType: 'domain_public' });
    displayName = user.name.displayName ? user.name.displayName : user.name.fullName;
  } catch (e) {
    // Ignores errors, uses 'Unknown User' by default.
  }
  cache.set(userId, displayName);
  return displayName;
}

VertexAi.js

/**
 * Summarizes a Google Chat space history with the Gemini Pro model using
 * Vertex AI API.
 *
 * @param {string} history the history
 * @return {string} the summary
 */
function summarizeSpace(history) {
  const url = `https://${VERTEX_AI_LOCATION_ID}-aiplatform.googleapis.com/v1`
    + `/projects/${PROJECT_ID}/locations/${VERTEX_AI_LOCATION_ID}`
    + "/publishers/google/models/gemini-1.0-pro:generateContent";
  const options = {
    method: "POST",
    headers: { Authorization: "Bearer " + ScriptApp.getOAuthToken() },
    contentType: "application/json",
    payload: JSON.stringify({
      contents: {
        role: "user",
        parts: {
          text: "Summarize the following conversation between engineers resolving"
              + " an issue in a few sentences.\n\n" + history
        }
      },
      safetySettings: {
        category: "HARM_CATEGORY_SEXUALLY_EXPLICIT",
        threshold: "BLOCK_LOW_AND_ABOVE"
      },
      generationConfig: {
        temperature: 0.2,
        topP: 0.8,
        topK: 40
      }
    })
  };

  return JSON.parse(UrlFetchApp.fetch(url, options).getContentText())
    .candidates[0].content.parts[0].text;
}

Docs.js

// The report generator function adds two sections: the first one is for the summary and the second one is for history.
function createReport(..., history, summary) {
  ...
  body.appendParagraph("Summary").setHeading(DocumentApp.ParagraphHeading.HEADING1);
  body.appendParagraph(summary);
  body.appendParagraph("History").setHeading(DocumentApp.ParagraphHeading.HEADING1);
  body.appendParagraph(history);
  ...
}

更新 Google Cloud 專案

啟用 API

  1. Google Cloud 控制台,啟用 Google 文件Google Admin SDKVertex AI API:

  1. 依序點選「選單」圖示 >「API 和服務」>「已啟用的 API 和服務」,然後確認 API 已啟用。

啟動服務帳戶

Google Cloud 控制台中,按照下列步驟操作:

  1. 依序點選「選單」圖示 ⋮ >「IAM 與管理員」>「服務帳戶」>「+ 建立服務帳戶」

74cf57426419f39.png

  1. 將「Service account name」(服務帳戶名稱) 設為 chat-app
  2. 將「Service account description」設為 Chat app auth
  3. 按一下「建立並繼續」
  4. 按一下 [完成]。系統會將您重新導向至「Service accounts」(服務帳戶) 頁面,方便您查看您建立的服務帳戶。

ca0468f1f93990f9.png

  1. 選取新建立的服務帳戶。
  2. 選取「金鑰」分頁標籤。
  3. 按一下「新增金鑰」
  4. 按一下「建立新的金鑰」
  5. 選取「JSON」
  6. 點選「建立」

9f7e6ea020978ab0.png

對話方塊隨即關閉,系統也會自動將新建立的公開/私密金鑰組下載至本機環境,做為 JSON 檔案。稍後當您編輯 Apps Script 專案的原始碼時,會用到其中的內容。

更新 Google Chat API 設定

Google Cloud 控制台中,按照下列步驟操作:

  1. 新增斜線指令。
  2. 將「Name」(名稱) 設定為 /create
  3. 將「Command ID」(指令 ID) 設為 1
  4. 將「Description」設為 Create a new issue
  5. 勾選「開啟對話方塊」核取方塊。
  6. 新增其他斜線指令。
  7. 將「Name」(名稱) 設定為 /close
  8. 將「Command ID」(指令 ID) 設為 2
  9. 將「Description」設為 Close an issue
  10. 點選「儲存」

bee2e7b63659ab33.png

更新 Apps Script 專案

  • 將本機終端機中的現有目錄變更為 issue-management/1-baseline。其中包含原始碼。將原始碼推送到 Apps Script 專案之前,您必須先設定幾件事。

設定原始碼

  1. Configuration.js 檔案中名為 CHAT_CREDENTIALS 的 JSON 常數設為您之前下載的私密金鑰檔案內容。

d721f6bff73c5304.png

  1. Google Cloud 控制台中,依序點選「選單」圖示 ⋮ >「IAM 與管理」>「設定」

  1. 複製專案 ID。

82592fa0bd113469.png

  1. Configuration.js 檔案中名為 PROJECT_ID 的字串常數設為專案 ID。

383cee561130ceba.png

配置 clasp 設定

如要初始化 clasp 設定,將原始碼推送至正確的 Apps Script 專案,請按照下列步驟操作:

  1. Apps Script 控制台中,選取專案。
  2. 選取「專案設定」
  3. 按一下「ID」下方的「複製」。

20ea033b6de882c6.png

  1. 在目前的目錄中建立 .clasp.json 檔案。
  2. <your-script-id> 替換成複製的 ID。
  3. 將結果複製到 .clasp.json 檔案。
  4. 儲存 .clasp.json 檔案。
{
  "scriptId": "<your-script-id>"
}

推送原始碼

  • 執行下列指令:
$clasp push
? Manifest file has been updated. Do you want to push and overwrite? Yes
└─ appsscript.json
└─ ChatApp.js
└─ ChatAppAuth.js
└─ Configuration.js
└─ Docs.js
└─ Storage.js
└─ VertexAi.js
Pushed 7 files.

立即試用

  1. Google Chat 中,透過即時訊息傳送 Hello! 給應用程式。應用程式不會回覆,但會顯示提示設定訊息。

4c1fc68121dcffed.png

  1. 按一下「設定」
  2. 選取你的 Google 帳戶。
  3. 驗證。
  4. 查看並允許存取應用程式。

4a2fd7ac5918bf1a.png

如果成功,您會在網頁上看到基本確認畫面,以及應用程式對於原始訊息的實際回應。

acb9065568fe47d2.png

2d6ef9c62f47e082.png

  1. 使用斜線指令 /create,傳送其他即時訊息給應用程式。

be3f3c6eb0f929c1.png

  1. 在對話方塊中,將「Title」設為 Issue Title 1
  2. 將「Description」設為問題 Description 1
  3. 點選「建立」

22efdecff4601417.png

應用程式會執行以下作業:

  1. 點選此按鈕即可關閉對話方塊。
  2. 針對標題相同的新問題建立專用聊天室。
  3. 加入新建立的聊天室。
  4. 在新建的聊天室中傳送含有問題說明的訊息。
  5. 傳送即時訊息給你,並附上新建聊天室的連結。

3253cec2392e281f.png

  1. 在新建立的聊天室中,傳送含有斜線指令 /close 和解析度 (例如 Not reproducible) 的訊息。

132cc4acfc10b98c.png

應用程式會執行以下作業:

  1. 在 Google 文件中建立報告文件。
  2. 傳送問題專屬的聊天室訊息,並附上新建報告文件的連結。

2d127c63518673b2.png

  1. 開啟報告文件。內含基本資訊、歷史記錄和摘要。

9aea694937f2f3ed.png

4. 選用:應用程式 1:新增應用程式首頁

查看概念

「應用程式首頁」是可自訂的資訊卡訊息,當使用者透過 Chat 應用程式透過即時訊息存取「首頁」分頁時,Chat 應用程式就會將這類訊息傳送給使用者。這類訊息通常用於顯示應用程式說明文件或總覽。技術上來說,我們會根據與卡片訊息相同的核心原則,設計專屬的事件來處理事件。

65f56f70f67a32e4.png

查看流程

管理問題

10663f5fc107fb3f.png

查看原始碼

需要編輯 Apps Script 專案。

ChatApp.js

/**
 * Handles app home requests in Google Chat.
 * 
 * Displays the latest status of all issues.
 */
function onAppHome() {
  // Generates one card section per issue.
  var sections = [];
  for (var issueKey in appProperties.getProperties()) {
    const issue = JSON.parse(appProperties.getProperty(issueKey));
    if (issue.spaceId) {
      sections.push({
        header: `${issue.status} - ${issue.title}`,
        widgets: [{ textParagraph: {
            text: `Description: ${issue.description}`
          }}, { textParagraph: {
            text: `Resolution: ${issue.resolution}`
          }}, { buttonList: { buttons: [{
              text: "Open space",
              onClick: { openLink: {
                url: `https://mail.google.com/mail/u/0/#chat/space/${issue.spaceId}`
              }}
            }, {
              text: "Open report",
              onClick: { openLink: {
                url: issue.reportUrl !== "" ? issue.reportUrl : "docs.new"
              }},
              disabled: issue.reportUrl === ""
          }]}
        }]
      });
    }
  }

  return { action: { navigations: [{ push_card: {
    sections: sections
  }}]}};
}

更新 Google Cloud 專案

Google Cloud 控制台中,按照下列步驟操作:

  1. 在「互動功能」部分下方,勾選「支援應用程式首頁」核取方塊。

97159c1c69ca8303.png

請在本機環境中按照下列步驟操作:

  1. 將終端機中的現有目錄變更為 issue-management/2-app-home。當中包含您需要使用的原始碼。
  2. issue-management/1-baseline/.clasp.json 檔案複製到目前的目錄。
  3. issue-management/1-baseline/Configuration.js 檔案複製到目前的目錄,以便取代現有目錄。
  4. 執行下列指令:
clasp push

試用

Google Chat 中按照下列步驟操作:

  1. 傳送含有斜線指令 /create 的即時訊息給應用程式。應用程式會開啟對話方塊。
  2. 將「Title」設為 Issue Title 2
  3. 將「Description」設為問題 Description 2
  4. 點選「建立」

3b2a8690e758f965.png

  1. 使用 Google Chat 應用程式在聊天室中選取「首頁」分頁標籤,即可查看你建立的問題詳細資料。

ed8e32da0e6f2ac6.png

5. 選用:應用程式 1:新增空間監控功能

查看概念

Pub/Sub

Pub/Sub 是可擴充的非同步訊息服務,可將產生這些訊息的服務訊息服務分離。Pub/Sub 可讓您建立事件生產端和消費者的系統,稱為「發布者」和「訂閱者」。發布者會透過廣播事件,而非同步遠端程序呼叫 (RPC),與訂閱者進行非同步通訊。

發布者會將事件傳送至 Pub/Sub 服務,而無需考量系統處理這些事件的方式或時間。接著,Pub/Sub 會將事件傳送至所有回應的服務。在透過 RPC 進行通訊的系統中,發布者必須等待訂閱者接收資料。不過,Pub/Sub 中的非同步整合可提高整體系統的彈性與穩定性。

主題:代表訊息動態消息的具名資源。您必須先建立主題,然後才能發布或訂閱該主題。

訂閱項目:如要接收發布至某個主題的訊息,您必須建立該主題的訂閱項目。訂閱者用戶端會接收並處理發布至主題的訊息。一個主題可以有多個訂閱項目,但特定訂閱項目屬於單一主題。

Google Workspace 活動

Google Workspace 活動代表 Google Workspace 資源的異動,例如建立、更新或刪除資源。應用程式可以訂閱 Google Workspace 資源,以非同步方式接收及處理相關活動。

7816e477b112bfb6.png

以下說明 Google Workspace Event API 如何透過訂閱傳送事件至應用程式:

  1. 應用程式會訂閱 Google Workspace 應用程式中的資源 (例如聊天室)。
  2. 應用程式訂閱的變更資源。
  3. Google Workspace 應用程式會將事件傳送至 Pub/Sub 的主題,做為應用程式 Google Workspace 訂閱項目的通知端點。這個事件包含資源變更的資料。
  4. 應用程式會處理含有事件的 Pub/Sub 訊息,並在必要時採取行動。

查看流程

建立問題 (更新)

6d7a9d7a68666a80.png

排解專用聊天室的問題 (更新)

17e60f052f222456.png

透過專用聊天室關閉問題 (更新)

742d490ea0b6fe3a.png

處理訂閱

de3017100dec6401.png

查看原始碼

需要編輯 Apps Script 專案。

appsscript.json

// Enables the Workspace Events service.

"enabledAdvancedServices": [
  ...
  {
    "userSymbol": "WorkspaceEvents",
    "version": "v1",
    "serviceId": "workspaceevents"
  }
  ...
]

Configuration.js

// Adds two constants: the first one is the Pub/Sub topic ID and the second one
// is the Pub/Sub subscription ID to be used to retrieve Google Workspace events.

...
const GWS_PUBSUB_TOPIC_ID = `projects/${PROJECT_ID}/topics/workspace-events`;
const GWS_PUBSUB_SUBSCRIPTION_ID =
  `projects/${PROJECT_ID}/subscriptions/workspace-events-sub`;
...

ChatApp.js

// Edits the function to delete the subscription at issue closure.

function processSlashCommand(event) {
  ...
  if (event.message.slashCommand.commandId == CLOSE_COMMAND_ID
    && event.message.space.type !== "DM") {
    ...
    deleteSubscription(issue.subscriptionId);
    ...
  }
  ...
}
// Edits the function to create the subscription.

function createIssue(event) {
  ...
  const subscriptionId = createSpaceSubscription(spaceUrl);
  const createdIssue = saveCreatedIssue(..., subscriptionId);
  ...
}
// Edits the function to delete the subscription.

function onRemoveFromSpace(event) {
  ...
  deleteSubscription(issue.subscriptionId);
  ...
}

Storage.js

// Edits the function to keep track of the subscription ID.

function saveCreatedIssue(..., spaceId, subscriptionId) {
  ...
  appProperties.setProperty(spaceId, JSON.stringify({
    ...
    subscriptionId: subscriptionId,
    ...
  }));
  ...
}

WorkspaceEvent.js

/**
 * Creates a new subscription to Google Workspace Events associated to a
 * Google Chat space.
 * 
 * The subscription scope includes message creation events and resources.
 * 
 * @param {string} spaceId the space ID to create a subscription for
 * @return the ID of the newly created subscription
 */
function createSpaceSubscription(spaceId) {
  const operation = WorkspaceEvents.Subscriptions.create({
    targetResource: `//chat.googleapis.com/${spaceId}`,
    eventTypes: ["google.workspace.chat.message.v1.created"],
    notificationEndpoint: { pubsubTopic: GWS_PUBSUB_TOPIC_ID },
    payloadOptions: { includeResource: true },
  });

  return operation.response.name;
}
/**
 * Processes events from subscription by using the Google Cloud PubSub API.
 * 
 * It pulls and acknowledges each event.
 */
function processSubscription() {
  const response = UrlFetchApp.fetch(
    `https://pubsub.googleapis.com/v1/${GWS_PUBSUB_SUBSCRIPTION_ID}:pull`,
    {
      method: "POST",
      contentType: "application/json",
      headers: { "Authorization": "Bearer " + ScriptApp.getOAuthToken() },
      payload: JSON.stringify({ maxMessages: 10 })
    }
  );

  const messages = JSON.parse(response.getContentText()).receivedMessages;
  for (var messageIndex in messages) {
    const message = messages[messageIndex];
    const ceType = message.message.attributes["ce-type"];
    const dataStr = Utilities.newBlob(Utilities.base64Decode(message.message.data))
      .getDataAsString();
    if (ceType === "google.workspace.events.subscription.v1.expirationReminder") {
      // Renews subscription.
      renewSubscription(JSON.parse(dataStr).subscription.name);
    } else if (ceType === "google.workspace.chat.message.v1.created") {
      // Processes the message text when it's sent in a space.
      const chatMessage = JSON.parse(dataStr).message;
      if (chatMessage.sender.type !== "BOT") {
        console.log("Message was processed.");
      }
    }
    // Acknowledges successful processing to avoid getting it again next time.
    ackSubscription(message.ackId);
  }
}
/**
 * Acknowledges a subscription event by using the Google Cloud PubSub API.
 * 
 * @param {string} ackId the ID of the event acknowledgment to send
 */
function ackSubscription(ackId) {
  UrlFetchApp.fetch(
    `https://pubsub.googleapis.com/v1/${GWS_PUBSUB_SUBSCRIPTION_ID}:acknowledge`,
    {
      method: "POST",
      contentType: "application/json",
      headers: { "Authorization": "Bearer " + ScriptApp.getOAuthToken() },
      payload: JSON.stringify({
        ackIds: [ackId]
      })
    }
  );
}
/**
 * Renews a subscription to Google Workspace Events.
 * 
 * The default time to live option is used.
 * 
 * @param {string} subscriptionId the ID of the subscription to renew
 */
function renewSubscription(subscriptionId) {
  WorkspaceEvents.Subscriptions.patch({ttl: '0s'}, subscriptionId);
}
/**
 * Deletes a subscription to Google Workspace Events.
 * 
 * @param {string} subscriptionId the ID of the subscription to delete
 */
function deleteSubscription(subscriptionId) {
  WorkspaceEvents.Subscriptions.remove(subscriptionId);
}

更新 Google Cloud 專案

啟用 API

  1. 在 Google Cloud 控制台中,啟用 Google Workspace 事件和 Pub/Sub。

  1. 依序點選「選單」圖示 ⋮ >「API 和服務」>「已啟用的 API 和服務」,然後確認兩者均已啟用。

開始訂閱

您必須建立並訂閱 Pub/Sub 主題,才能發布所有工作區事件。

Google Cloud 控制台中,按照下列步驟操作:

  1. 依序前往「選單」⋮ >「Pub/Sub」>「主題」

  1. 按一下「建立主題」
  2. 將「Topic ID」(主題 ID) 設為 workspace-events
  3. 選取「新增預設訂閱項目」核取方塊。
  4. 點選「建立」

b39f9a0aec7c9939.png

如要授予透過 Google Chat 將 Pub/Sub 訊息發布至您新建主題的權限,請按照下列步驟操作:

  1. 從清單中選取主題。
  2. 選取 [權限] 分頁標籤。
  3. chat-api-push@system.gserviceaccount.com 新增至「新增主體」
  4. 為「角色」選取「Pub/Sub 發布者」
  5. 點選「儲存」

8d4016c37532503.png

更新 Apps Script 專案

Google Cloud 控制台中,按照下列步驟操作:

  1. 依序點選「選單」圖示 ⋮ >「IAM 與管理」>「設定」

  1. 複製專案 ID。

82592fa0bd113469.png

請在本機環境中按照下列步驟操作:

  1. 將終端機中的現有目錄變更為 issue-management/3-message-monitoring。其中包含您需要的原始碼。
  2. Configuration.js 檔案中名為 PROJECT_ID 的字串常數設為複製的專案 ID。
  3. Configuration.js 檔案中名為 CHAT_CREDENTIALS 的 JSON 常數設為您之前下載的私密金鑰檔案內容。
  4. issue-management/2-app-home/.clasp.json 檔案複製到目前的目錄。
  5. 執行下列指令:
clasp push

試用

Google Chat 中按照下列步驟操作:

  1. 傳送含有斜線指令 /create 的即時訊息給應用程式。應用程式會開啟對話方塊。
  2. 將「Title」設為 Issue Title 3
  3. 將「Description」設為問題 Description 3
  4. 點選「建立」
  5. 在新建立的聊天室中傳送幾則討論問題的訊息。
  6. 傳送含有斜線指令 /close 和解析度 (例如 Fixed) 的訊息。

Google Cloud 控制台中,按照下列步驟操作:

  1. 依序前往「選單」⋮ >「Pub/Sub」>「訂閱項目」

  1. 選取訂閱項目 workspace-events-sub
  2. 選取「訊息」分頁標籤。
  3. 按一下「提取」。表格會顯示您傳送至新建聊天室的訊息相關的訊息。

82631c9792d83889.png

Apps Script 控制台中,按照下列步驟操作:

  1. 選取所需專案。
  2. 選取「編輯器」
  3. 選取 WorkspaceEvent.gs 檔案。
  4. 在「Run」部分選取 processSubscription
  5. 按一下 Run,您可以在執行記錄中看到訊息已處理完成的狀態。

c612e8fa2bd0a163.png

Google Cloud 控制台中,按照下列步驟操作:

  1. 依序前往「選單」⋮ >「Pub/Sub」>「訂閱項目」

  1. 選取訂閱項目 workspace-events-sub
  2. 選取「訊息」分頁標籤。
  3. 按一下「提取」。表格不會再顯示你傳送至新建聊天室的內容相關訊息。

e185454cac862a7b.png

  • Google Chat 中,您於使用斜線指令 /create 建立了第三個問題時,請在 Google Chat 中另外傳送幾則討論這個問題的訊息。

Google Cloud 控制台中,按照下列步驟操作:

  1. 依序前往「選單」⋮ >「Pub/Sub」>「訂閱項目」

  1. 選取訂閱項目 workspace-events-sub
  2. 選取「訊息」分頁標籤。
  3. 按一下「提取」。表格不會顯示你傳送至新建聊天室的內容相關訊息,

6. 選用:應用程式 1:新增多元包容說明

查看概念

生成式 AI 提示是編寫操作說明或疑問的秘訣,可引導生成式 AI 模型採用特定類型的輸出內容。常見的做法是在提示中新增規則和條件,藉此篩選答案。這麼做可讓輸出內容安全、相關、一致且符合期望。

查看流程

處理訂閱 (更新)

780d0802f77dd180.png

查看原始碼

需要編輯 Apps Script 專案。

WorkspaceEvent.js

// Edits the function to replace logging by an actual card message.

function processSubscription() {
  ...
  for (var messageIndex in messages) {
    ...
    } else if (ceType === "google.workspace.chat.message.v1.created") {
      ...
      const inclusivityCheck = getInclusivityFeedback(chatMessage.text);
      if (inclusivityCheck !== "It's inclusive!") {
        createAppMessageUsingChatService({
          cardsV2: [{ cardId: "1", card: { header: {
              title: "Inclusivity",
              subtitle: `The following words are not inclusive: ${inclusivityCheck}`
          }}}]
        },
        chatMessage.space.name);
      }
      ...
    }
    ...
  }
  ...
}

VertexAi.js

/**
 * Gets feedback on inclusivity for a text with the Gemini Pro model using
 * Vertex AI API.
 * 
 * Returns "It's inclusive!" when it is otherwise a list of word(s) that might not
 * be optimal.
 *
 * @param {string} text the text
 * @return {string} the feedback
 */
function getInclusivityFeedback(text) {
  const url = `https://${VERTEX_AI_LOCATION_ID}-aiplatform.googleapis.com/v1`
    + `/projects/${PROJECT_ID}/locations/${VERTEX_AI_LOCATION_ID}`
    + "/publishers/google/models/gemini-1.0-pro:generateContent";
  const options =  {
    method: "POST",
    headers: { Authorization: "Bearer " + ScriptApp.getOAuthToken() },
    contentType: "application/json",
    payload: JSON.stringify({
      contents: {
        role: "user",
        parts: {
          text: "Are there any words that obviously go against inclusivity "
            + "in this text:"
            + `\n\n----------\n${text}\n----------\n\n`
            + "If there are not, answer \"It's inclusive!\" "
            + "otherwise answer by listing them separated by commas. "
            + "Do not answer with any explanation."
        }
      },
      safetySettings: {
        category: "HARM_CATEGORY_SEXUALLY_EXPLICIT",
        threshold: "BLOCK_LOW_AND_ABOVE"
      },
      generationConfig: {
        temperature: 0.2,
        topP: 0.8,
        topK: 40
      }
    })
  };

  return JSON.parse(UrlFetchApp.fetch(url, options).getContentText())
    .candidates[0].content.parts[0].text;
}

更新 Apps Script 專案

請在本機環境中按照下列步驟操作:

  1. 將終端機中的現有目錄變更為 issue-management/4-inclusivity-help。其中含有您需要的原始碼。
  2. issue-management/3-message-monitoring/.clasp.json 檔案複製到目前的目錄。
  3. issue-management/3-message-monitoring/Configuration.js 檔案複製到目前的目錄,以便取代現有目錄。
  4. 執行下列指令:
clasp push

試用

Google Chat 中按照下列步驟操作:

  1. 傳送含有斜線指令 /create 的即時訊息給應用程式。應用程式會開啟對話方塊。
  2. 將「Title」設為 Issue Title 4
  3. 將「Description」設為問題 Description 4
  4. 點選「建立」
  5. 在新建立的聊天室中傳送 It happened to me last week as well

Apps Script 控制台中,按照下列步驟操作:

  1. 選取所需專案。
  2. 選取「編輯器」
  3. 選取 WorkspaceEvent.gs 檔案。
  4. 在「Run」部分選取 processSubscription
  5. 按一下「執行」。您可以在執行記錄中查看訊息已處理完成的狀態。

Google Chat 中按照下列步驟操作:

  1. 請注意,應用程式不會在新建立的聊天室中傳送任何多元包容說明。
  2. 在新建的聊天室中傳送訊息,I had to add myself from the master to fix it

Apps Script 控制台中,按照下列步驟操作:

  1. 選取所需專案。
  2. 選取「編輯器」
  3. 選取 WorkspaceEvent.gs 檔案。
  4. 在「Run」部分選取 processSubscription
  5. 按一下「執行」。您可以在執行記錄中查看訊息已處理完成的狀態。在 Google Chat 中,應用程式會在新建立的聊天室中傳送多元包容說明訊息。

7936342847acbe2d.png

7. 選用:應用程式 1:新增偏好設定

.

查看概念

配件小工具是一種無邊框小工具,會顯示在應用程式傳送的訊息底部,讓使用者能在特定訊息發生時快速做出回應。從技術上來說,它與資訊卡按鈕的核心原則相同。

eebe88238f6b13f.png

查看流程

停用多元包容說明

1bb7a8592ee6221e.png

查看原始碼

需要編輯 Apps Script 專案。

ChatApp.js

// Edits the function to handle the inclusivity help disablement action for a
// given space.

function onCardClick(event) {
  ...
  if (event.action.actionMethodName === "disableInclusivityHelp") {
    disableInclusivityHelp(event.common.parameters.spaceId);
  }
}

Storage.js

// Edits the function to keep track of the inclusivity help setting.

function saveCreatedIssue(title, description, spaceId, subscriptionId) {
  appProperties.setProperty(spaceId, JSON.stringify({
    ...
    inclusivityHelp: true,
    ...
  }));
  ...
}
/**
 * Disables inclusivity help in a space.
 * 
 * @param {string} spaceId the ID of dedicated space of the issue
 */
function disableInclusivityHelp(spaceId) {
  var issue = JSON.parse(appProperties.getProperty(spaceId));
  issue.inclusivityHelp = false;
  appProperties.setProperty(spaceId, JSON.stringify(issue));
}
/**
 * Checks whether the app should help with inclusivity in a given space.
 * 
 * @param {string} spaceId the ID of dedicated space of the issue
 * @return whether the app should help with inclusivity
 */
function shouldHelpWithInclusivity(spaceId) {
  return JSON.parse(appProperties.getProperty(spaceId)).inclusivityHelp;
}

WorkspaceEvent.js

// Edits the function to display the accessory widget to the existing card message.

function processSubscription() {
  ...
  for (var messageIndex in messages) {
    ...
    } else if (ceType === "google.workspace.chat.message.v1.created") {
      ...
      if (... && shouldHelpWithInclusivity(chatMessage.space.name)) {
        createAppMessageUsingChatService({
          ...
          accessoryWidgets: [{ buttonList: { buttons: [{
            altText: "Disable inclusivity help",
            icon: {
              iconUrl: "https://upload.wikimedia.org/.../Stop_hand_rugen.png"
            },
            onClick: { action: {
              function: "disableInclusivityHelp",
              parameters: [{
                key: "spaceId",
                value: chatMessage.space.name
              }]
            }}
          }]}}]
        }, ...);
        ...
      }
      ...
    }
    ...
  }
  ...
}

更新 Apps Script 專案

請在本機環境中按照下列步驟操作:

  1. 將終端機中的現有目錄變更為 issue-management/5-disable-help。其中包含您需要的原始碼。
  2. issue-management/4-inclusivity-help/.clasp.json 檔案複製到目前的目錄。
  3. issue-management/4-inclusivity-help/Configuration.js 檔案複製到目前的目錄,以便取代現有目錄。
  4. 執行下列指令:
clasp push

試用

停用說明

  • Google Chat 中,針對使用斜線指令 /create 建立的第四個問題,在聊天室中傳送訊息 I had to add myself from the master to fix

Apps Script 控制台中,按照下列步驟操作:

  1. 選取所需專案。
  2. 選取「編輯器」
  3. 選取 WorkspaceEvent.gs 檔案。
  4. 在「Run」部分選取 processSubscription
  5. 按一下「執行」。您可以在執行記錄中查看訊息已處理完成的狀態。

Google Chat 中按照下列步驟操作:

  1. 請注意,應用程式傳送了具有包容性協助的訊息,說明與配件小工具相關的問題,
  2. 按一下配件小工具即可停用包容性說明。

de722cff1928dec9.png

檢查停用狀態

  • Google Chat 中,針對使用斜線指令 /create 建立的第四個問題,在聊天室中傳送訊息 I had to add myself from the master to fix

Apps Script 控制台中,按照下列步驟操作:

  1. 選取所需專案。
  2. 選取「編輯器」
  3. 選取 WorkspaceEvent.gs 檔案。
  4. 在「Run」部分選取 processSubscription
  5. 按一下「執行」。您可以在執行記錄中查看訊息已處理完成的狀態。在 Google Chat 中,由於應用程式已停用,因此應用程式未在訊息中指出專屬聊天室。

347d659db53b73e9.png

8. 應用程式 2:建構

查看概念

生成式 AI 基礎

更重要的是將 AI 模型連結至可驗證的知識來源,讓模型變得更加可靠且可靠。這項技術有助於防止 AI 生成資訊,並讓回覆與情境相關,並降低偏誤。

自然語言

與人工或電腦語言相比,人類日常溝通時使用的語言或書面語言。

Cloud Storage

Cloud Storage 可讓您在世界各地隨時儲存及擷取大小不限的資料。這項功能適用於多種情況,包括提供網站內容、儲存資料以供封存和災難復原之用,或是透過直接下載的方式將大量資料物件發布給使用者。

Dialogflow CX 資料儲存庫

Dialogflow CX 能與資料儲存庫整合,這裡提供資料儲存庫代理程式的網站和文件集合,用來解決使用者對特定資料的問題。針對特定問題,資料儲存庫代理程式會從指定的來源內容搜尋答案,然後將調查結果總結為連貫的回應。並提供支援連結,方便使用者查看回覆來源。

審查架構

9d3342d12f3b4dda.png

這個 Google Chat 應用程式是以 Dialogflow CX 建構而成,運作方式如下:

  1. 使用者透過即時訊息或聊天室傳送訊息給應用程式。
  2. 應用程式是 Dialogflow CX 代理程式,與 Google Cloud 專案相關聯,會處理訊息。
  3. 應用程式整合了位於 Cloud Storage 的資料儲存庫。
  4. 應用程式會傳送即時訊息或原始聊天室中的同步回應。

查看流程

回答問題

aad9fb5a7ca48956.png

查看原始碼

您需要的唯一來源不是程式碼,而是用於依據資料。

google-chat-overview.pdf

包含 Google Chat 應用程式的非結構化資訊,也就是 Google Workspace 開發人員網站的印刷版本。

e9b91c4587b1a3a0.png

更新 Google Cloud 專案

在 Google Cloud 控制台中按照下列步驟操作:

  1. 啟用 Dialogflow 和 Cloud Storage API。

  1. 啟用 Vertex AI Agent Builder API。

  1. 依序點選「選單」圖示 >「API 和服務」>「已啟用的 API 和服務」,然後確認所有 API 已啟用。

.

建立 Dialogflow CX 資料儲存庫代理程式

初始化知識資料

Google Cloud 控制台中,按照下列步驟操作:

  1. 依序按一下「選單」圖示 ⋮ >「Cloud Storage」>「值區」

4f15978ae9f1b687.png

  1. 點選「建立」
  2. 將「name」設為 gchat-knowledge
  3. 點選「建立」

6b38c6d4d2c41bba.png

  1. 選取 gchat-knowledge 值區。
  2. 按一下「上傳檔案」
  3. 從本機環境選取 knowledge-app/grounding/google-chat-overview.pdf 檔案。

df89acb22e1762af.png

建立應用程式

Google Cloud 控制台中,按照下列步驟操作:

  1. 依序點選「Menu」圖示 >「Agent builder」>「Apps」

  1. 點選「New app」(新增應用程式)
  2. 選取即時通訊類型。

44276003074bcf14.png

  1. Company name 設為貴公司名稱。
  2. Agent name 設為 knowledge
  3. 點選「繼續」

c4fedfd7556f723b.png

  1. 按一下「建立新的資料儲存庫」
  2. 選取 Cloud Storage 做為資料來源。

6e2440ecf0f8f9bd.png

  1. 選取「檔案」
  2. 點選「瀏覽」
  3. 選取 google-chat-overview.pdf 檔案。
  4. 點選「繼續」
  5. 將資料儲存庫名稱設為 gchat-knowledge-ds
  6. 點選「建立」

a675df7490b83900.png

  1. 選取資料表中的 gchat-knowledge-ds 資料儲存庫。
  2. 點選「建立」

f121d580771ed96.png

  1. 幾分鐘後,依序點選「選單」圖示 ⋮ >「Agent builder」>「Apps」,就會看到這個應用程式。

d929a7431dd84968.png

  1. 依序點選「Menu」圖示 >「Agent builder」>「Data stores」。

  1. 按一下 gchat-knowledge-ds 資料儲存庫。文件數量為 1,表示已就緒。

558319790a0accf2.png

完成並測試應用程式

請在 Dialogflow CX 主控台中按照下列步驟操作:

  1. 選取 Google Cloud 專案。
  2. 選取「Confirm」(知識) 代理程式。

ca9b2fb4be92e8e4.png

  1. 依序選取「Agent settings」>「Generative AI」>「Geerative agent」
  2. 將模型從「文字組合」切換為 Gemini Pro
  3. 點選「儲存」

68cc4713ec9b25a0.png

  1. 按一下「Test agent」
  2. 傳送 What is Google Chat?。服務專員回覆了有意義的內容。

8e3a2cb02469041a.png

整合 Google Chat 應用程式

請在 Dialogflow CX 主控台中按照下列步驟操作:

  1. 選取 Google Cloud 專案。
  2. 在知識代理程式的資料列中,依序按一下 1e7ede7abae4aa3c.png>「複製名稱」

e19f61185158110d.png

Google Cloud 控制台中,按照下列步驟操作:

  1. 前往 Google Chat API 設定頁面。

  1. 在「連線設定」下方選取「Dialogflow」
  2. 在「Dialogflow settings」下方,選取「Dialogflow CX」
  3. 將「Agent or Environment resource name」設為您複製的代理程式名稱。
  4. 移除兩個斜線指令。

505ff39a50880904.png

  1. Google Chat 中,透過即時訊息傳送 What is Google Chat? 給 Google Chat 應用程式。服務專員回覆的內容有意義的結果。

abda9e43b81fb0ea.png

9. 選用:應用程式 2:新增來源

查看概念

Dialogflow CX Webhook

託管商業邏輯或呼叫其他服務的服務。在 Dialogflow CX 工作階段中,Webhook 可以利用自然語言處理程序擷取的資料,產生動態回應、驗證收集到的資料,或是在後端觸發動作。

Cloud Functions

Cloud Functions 非常適合用於建構無伺服器後端、即時資料處理,以及建立智慧型應用程式。完全不必佈建、管理、修補或更新伺服器,可自動調整資源配置,並具備高可用性和容錯能力。

查看流程

回答問題 (更新)

92767c07c7b252aa.png

查看原始碼

您需要的唯一程式碼是使用函式,將服務專員回應內容調整至 Google Chat 訊息。做為 Webhook 使用。

package.json

// The function relies on the Cloud Functions framework to run.

{
  "name": "agent-response-adapter",
  "version": "0.0.1",
  "dependencies": {
    "@google-cloud/functions-framework": "^3.0.0"
  },
  ...
}

index.js

/** 
 * Handles all incoming requests.
 *
 * It takes a Dialogflow CX agent response as input and returns a
 * valid Google Chat card message with both the text and source links
 */
functions.http('agent-response-adapter', (request, response) => {
  // Creates Google Chat buttons based on the data store agent response
  // grounding details.
  var linkTitles = [];
  var linkButtons = [];
  const grounding = request.body.messages[1].payload.richContent[0][0];
  if (grounding.type === "match_citations") {
    // Supports citation match type.
    grounding.citations.forEach((citation) => {
      // Avoid duplications.
      if (linkTitles.indexOf(citation.title) < 0) {
        linkButtons.push({
          text: citation.title,
          onClick: { openLink: {
            url: citation.actionLink
          }}
        });
        linkTitles.push(citation.title);
      }
    });
  } else if (grounding.type === "info") {
    // Supports info type.
    if (linkTitles.indexOf(grounding.title) < 0) {
      linkButtons.push({
        text: grounding.title,
        onClick: { openLink: {
          url: grounding.actionLink
        }}
      });
      linkTitles.push(grounding.title);
    }
  }

  // Sends the Dialogflow CX fulfillment response to replace the agent response
  // with the Chat message with text and source buttons.
  response.send({ fulfillment_response: {
    merge_behavior: "REPLACE",
    messages: [{ payload: {
      // Reuses the original data store agent response text.
      text: request.body.messages[0].text.text[0],
      cardsV2: [{
        cardId: "sourcesCard",
        card: { sections: [{
          header: "Sources",
          widgets: [{ buttonList: {
            buttons: linkButtons
          }}]
        }]}
      }]
    }}]
  }});
});

更新 Google Cloud 專案

在 Google Cloud 控制台中按照下列步驟操作:

  1. 啟用 Cloud Build、Cloud Functions、Cloud Logging、Artifact Registry 和 Cloud Run API。

  1. 依序點選「選單」圖示 >「API 和服務」>「已啟用的 API 和服務」,然後確認 API 已啟用。

更新 Dialogflow CX 資料儲存庫代理程式

您必須部署 Cloud 函式並更新 Dialogflow CX Webhook,才能在可能的情況下透過多個來源觸發函式。

傳回多個來源

根據預設,新的資料儲存庫代理程式最多只能傳回一個來源,但您可以做其他變更。

請在 Dialogflow CX 主控台中按照下列步驟操作:

  1. 選取 Google Cloud 專案。
  2. 選取「Confirm」(知識) 代理程式。
  3. 選取「起始網頁」
  4. 選取「編輯資料儲存庫」
  5. 在「Agent response」下方,將「Data store response options」設為 5
  6. 點選「儲存」

f5932d03057df645.png

啟動 Cloud 函式

Google Cloud 控制台中,按照下列步驟操作:

  1. 依序點選「選單」圖示 ⋮ >「Cloud Functions」

  1. 按一下「建立函式」
  2. 在「Basics」(基本) 下方,將「name」(名稱) 設為 function-1
  3. 在「驗證」下方,選取「允許未經驗證的叫用」圓形按鈕
  4. 在「執行階段、建構作業、連線和安全性設定」下方,將「執行個體數量上限」設為 3
  5. 點選「下一步」

bd3790a9285f9c07.png

  1. 將「進入點」設為 agent-response-adapter
  2. 將預設內容替換為 knowledge-app/agent-response-adapter 目錄中的檔案。
  3. 點選「Deploy」

b379bb8ca0fc1079.png

  1. 請等待幾分鐘讓函式部署,然後複製網址。

eaae08cf048b9b1c.png

啟動 Webhook

您必須設定 Dialogflow CX 代理程式,才能使用 Webhook 觸發新部署的函式。

請在 Dialogflow CX 主控台中按照下列步驟操作:

  1. 選取 Google Cloud 專案。
  2. 選取「Confirm」(知識) 代理程式。
  3. 依序選取「Manage」>「Webhooks」>「Create」
  4. 將「Display name」設為 Google Chat Response Adapter
  5. Webhook 網址設為先前複製的網址。
  6. 點選「儲存」

5f3c6804d52b87c1.png

  1. 按一下「Build」
  2. 選取「起始網頁」
  3. 選取「編輯資料儲存庫」
  4. 在「Webhook 設定」下方,按一下「Enable Webhook」切換鈕。
  5. 選取「適用於 Webhook 的 Google Chat 回應轉接程式」
  6. 將「tag」設為 arbitrary_tag
  7. 點選「儲存」

442fcaaec9b8f2e3.png

測試應用程式

  • Google Chat 中,透過即時訊息傳送 What is Google Chat? 到 Google Chat 應用程式。服務專員會在回覆內容中,提供有意義的資訊,以及含有資料來源的資訊卡 (如果有的話)。

9468866bfe848bb8.png

10. 應用程式 3:建構

查看概念

對話互動

他們會透過自然語言,在兩個或更多人之間傳遞資訊或想法。這與技術介面通常依賴無狀態、高度結構化和無法容忍的交換庫。

OpenAPI 規格

能讓您在 API 生命週期的每個階段中,以一致的方式傳遞資訊。是 HTTP API 的規格語言,能定義結構和語法,而這不屬於建立 API 時使用的程式設計語言。API 規格通常是以 YAML 或 JSON 格式編寫,方便共用及使用規格。

Dialogflow CX 代理程式

代理程式應用程式的基本構成要素。代理程式應用程式通常包含許多「代理程式」,每個代理程式都經過定義,可處理特定工作。虛擬服務專員資料會提供給 LLM,因此可提供回答問題和執行工作所需的資訊。每個代理程式都能提供資訊、向外部服務執行查詢,或將對話延遲處理給 Dialogflow CX 流程或其他代理程式來處理子工作。

Dialogflow CX 工具

工具可用來將代理程式應用程式連線至外部系統。這些系統可以增強虛擬服務專員應用程式的知識,讓他們有效率地執行複雜工作。

審查架構

9d3342d12f3b4dda.png

這個 Google Chat 應用程式是以 Dialogflow CX 建構而成,運作方式如下:

  1. 使用者透過即時訊息或聊天室傳送訊息給應用程式。
  2. 應用程式是 Dialogflow CX 代理程式,與 Google Cloud 專案相關聯,會處理訊息。
  3. 應用程式會與代理程式整合。
  4. 應用程式會傳送即時訊息或原始聊天室中的同步回應。

查看流程

收集評論

a67a5b8b513bfc2c.png

查看原始碼

您需要的唯一程式碼是模擬代理程式做為工具使用的後端服務。

package.json

// The function relies on the Cloud Functions framework to run.

{
  "name": "feedback-app-backend",
  "version": "0.0.1",
  "dependencies": {
    "@google-cloud/functions-framework": "^3.0.0"
  },
  ...
}

index.js

/** 
 * Handles all incoming requests.
 * 
 * It always returns OK in plain text.
 */
functions.http('feedback-app-backend', (request, response) => {
    response.send('OK');
});

service-openapi.yaml

// Defines the backend service structure and how to request it.

openapi: 3.1.0
info:
  title: Review Store
  license:
    name: Apache 2.0
    identifier: Apache-2.0
  version: 0.0.1
servers:
  - url: https://us-central1-project-0.cloudfunctions.net
paths:
  /store-review:
    post:
      operationId: storeReview
      summary: Store a new review
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                stars:
                  type: integer
                  format: int64
      responses:
        '200':
          description: success
          content:
            application/json:
              schema:
                type: string

啟動後端服務模擬畫面

您將部署 Cloud 函式來模擬後端服務,Dialogflow CX 代理程式應用程式需要整合並呼叫為工具。

Google Cloud 控制台中,按照下列步驟操作:

  1. 依序點選「選單」圖示 ⋮ >「Cloud Functions」

  1. 按一下「建立函式」
  2. 在「Basics」(基本) 下方,將「name」(名稱) 設為 function-2
  3. 在「驗證」下方,選取「允許未經驗證的叫用」圓形按鈕。
  4. 在「執行階段、建構作業、連線和安全性設定」下方,將「執行個體數量上限」設為 3
  5. 點選「下一步」

e8cf0ee7441bf634.png

  1. 將「進入點」設為 feedback-app-backend
  2. 將預設內容替換為 feedback-app 目錄中的檔案。
  3. 點選「Deploy」

bdb5cf9f503aa7f6.png

  1. 請等待幾分鐘讓函式部署,然後複製網址。

建立 Dialogflow CX 代理程式應用程式

建立應用程式

Google Cloud 控制台中,按照下列步驟操作:

  1. 依序點選「Menu」圖示 >「Agent builder」>「Apps」

  1. 點選「New app」(新增應用程式)
  2. 選取「Agent」(代理程式)
  3. 將「Display name」設為 Feedback App
  4. 點選「建立」

7ef3dbacee96c5aa.png

啟動工具

Google Cloud 控制台中,按照下列步驟操作:

  1. 依序點選「Menu」圖示 >「Agent builder」>「Apps」

  1. 選取「Feedback App」代理程式。
  2. 依序點選「工具」>「+ 建立」
  3. 將「Name」(名稱) 設定為 review
  4. 選取「OpenAPI」OpenAPI
  5. description 設為下列值:
The tool takes the number of stars as a parameter of the store review method and saves it in a database for later use.
  1. feedback-app/service-openapi.yaml 檔案中的 $URL 替換成先前複製的網址。
  2. YAML Schema 設為 feedback-app/service-openapi.yaml 檔案的編輯內容內容。
  3. 點選「儲存」

58085d6d56b603f7.png

啟動代理程式

Google Cloud 控制台中,按照下列步驟操作:

  1. 依序點選「Menu」圖示 >「Agent builder」>「Apps」

  1. 選取「Feedback App」代理程式。
  2. 依序選取「Agents」>「Default Generative Agent」
  3. 將「Agent name」(代理程式名稱) 設為 Feedback collector
  4. goal 設為下列值:
You are an agent that collects reviews from Google Chat app developers.
A review may be between 0 and 5 stars. The more stars, the more positive the review.
  1. instructions設為下列值:
If the developer didn't provide the number of stars, ask for the number of stars.
After the developer provides the number of stars of the review, confirm the number with the developer and use ${TOOL: review} to store the review with the number of stars.
If ${TOOL: review} fails, apologize and ask to try again later. Otherwise, thank the developer for the review.
  1. 點選「儲存」

ebee7fdfa826b487.png

測試應用程式

Google Cloud 控制台中,按照下列步驟操作:

  1. 依序點選「Menu」圖示 >「Agent builder」>「Apps」

  1. 選取「Feedback App」代理程式。
  2. 前往「預覽代理程式」
  3. 在「Agent」(代理程式) 下方,選取「FeedbackCollector」(意見回饋收集器)
  4. 在「選取生成式模型」下方,選取「gemini-pro」
  5. 傳送 Hello! 訊息即可開始。

90ca8cb7b2c1cb4b.png

Google Cloud 控制台中,按照下列步驟操作:

  1. 依序點選「選單」圖示 ⋮ >「Cloud Functions」

  1. 依序選取「function-2」>「Logs」。部分記錄會將 Google-Dialogflow 顯示為來電者。

48bfdf1788004d18.png

整合 Google Chat 應用程式

請在 Dialogflow CX 主控台中按照下列步驟操作:

  1. 選取 Google Cloud 專案。
  2. 按一下 Feedback App 代理程式的動作選單。
  3. 按一下「複製名稱」

Google Cloud 控制台中,按照下列步驟操作:

  1. 前往 Google Chat API 設定。

  1. 將「Agent or Environment resource name」設為您之前複製的代理程式名稱。

df16619a1cb85cf8.png

  • Google Chat 中透過即時訊息傳送 Hello! 給 Google Chat 應用程式,即可開始使用。代理程式回應的方式與您在 Dialogflow CX 控制台中的測試類似。

99a7a0295f122f31.png

11. 清除

刪除 Google Cloud 專案

如要避免系統向您的 Google Cloud 帳戶收取您在本程式碼研究室中所用資源的費用,建議您刪除 Google Cloud 專案。

Google Cloud 控制台中,按照下列步驟操作:

  1. 依序點選「選單」圖示 ⋮ >「IAM 與管理」>「設定」

  1. 按一下「Shut down」(關閉)
  2. 輸入專案 ID。
  3. 按一下「仍要關閉」

407699a4e03afea6.png

刪除 Apps Script 專案

建議您一併刪除 Apps Script 專案。

Apps Script 控制台中,按照下列步驟操作:

  1. 選取所需專案。
  2. 按一下動作選單。
  3. 按一下「移除」

fa3a42d7d2201eb9.png

12. 恭喜

恭喜!您已成功使用 Gemini 建構 Google Chat 應用程式!

後續步驟

我們僅在此程式碼研究室中展示簡易的應用實例,但請考慮在 Google Chat 應用程式中,考慮使用許多擴充區域,例如:

  • 整合其他生成式 AI 模型 (包括自訂模型)。
  • 支援其他類型的媒體,例如音訊、圖片和影片。
  • 使用多模態。
  • 利用較長的背景期間和意見回饋循環。
  • 在 Marketplace 發布可投入實際工作環境的 Google Chat 應用程式。YouTube 影片、說明文件網站、程式碼範例和教學課程等為開發人員提供多種資源,
  • 為貴機構啟用 Google Chat。匯入模式功能可讓您輕鬆上手。

瞭解詳情