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

1. 事前準備

什麼是與 Gemini 搭配使用的 Google Chat 應用程式?

與 Gemini 搭配使用的 Google Chat 應用程式執行下列操作:

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

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

Gemini 等生成式 AI 模型的一般用途分為以下類別:

  • 內容創作及強化。生成行銷文案、撰寫社群媒體貼文、製作逼真的圖片、創作音樂,或協助製作影片內容。
  • 資料搜尋:從非結構化的知識庫中擷取關鍵深入分析資訊、總結冗長的文字、將內容分類,或是以更高的準確率和速度翻譯語言。
  • 對話:以自然、實用又有創意的對話方式,展開互動。

這些功能在熟悉的 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 Docs API 和 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. 將「服務帳戶說明」設為 Chat app auth
  3. 按一下 [建立並繼續]
  4. 按一下 [完成]。系統會將您重新導向至「Service accounts」(服務帳戶) 頁面,方便您查看您建立的服務帳戶。

ca0468f1f93990f9.png

  1. 選取新建立的服務帳戶。
  2. 選取「金鑰」分頁標籤。
  3. 按一下「新增金鑰」
  4. 按一下「建立新的金鑰」
  5. 選取「JSON」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.

試用 it

  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 Events 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 Event 和 PubSub。

  1. 按一下「選單」圖示 ⋮ >。API 與服務 >已啟用的 API 與服務,然後確認這兩項服務已啟用。

啟動訂閱

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

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

  1. 依序輕觸「選單」圖示 ⋮ >。Pub/Sub >主題

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

b39f9a0aec7c9939.png

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

  1. 從清單中選取主題。
  2. 選取 [權限] 分頁標籤。
  3. chat-api-push@system.gserviceaccount.com 新增至「新增主體」
  4. 在「Role」(角色) 部分選取「Pub/Sub Publisher」
  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」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」workspace-events-sub
  2. 選取「訊息」分頁標籤。
  3. 按一下「提取」。表格不會再顯示與您傳送至新建聊天室的內容相關的訊息。

e185454cac862a7b.png

  • Google Chat聊天室中,針對你使用斜線指令建立的第三個問題/create傳送幾則討論問題的訊息。

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

  1. 依序輕觸「選單」圖示 ⋮ >。Pub/Sub >訂閱項目

  1. 選取訂閱方案「workspace-events-sub」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 模型更貼近事實和可靠性。這項技術可避免 AI 生成資訊,並能協助回覆符合情境,減少偏誤。

自然語言

與人工/電腦語言相比,人類在日常通訊中說或撰寫的任何語言。

Cloud Storage

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

Dialogflow CX 資料儲存庫

Dialogflow CX 整合了資料儲存庫,這些資料是由資料儲存庫代理程式使用的網站和文件集合,可針對使用者的問題找出解答。針對特定問題,資料儲存庫代理程式會從指定的來源內容搜尋答案,並將調查結果總結成連貫的回應。並提供回應來源的輔助連結,讓使用者瞭解詳情。

審查架構

9d3342d12f3b4dda.png

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

  1. 使用者透過即時訊息或聊天室,傳送訊息給應用程式。
  2. 應用程式是與 Google Cloud 專案相關聯的 Dialogflow CX 代理程式,會處理訊息。
  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 與服務,並確認所有 APIS 已啟用。

建立 Dialogflow CX Data Store 虛擬服務專員

開始運用知識資料

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. 按一下「選單」圖示 ⋮ >。虛擬服務專員建立工具 >應用程式

  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. 等待幾分鐘後,按一下「選單」圖示 ⋮ >。虛擬服務專員建立工具 >應用程式,您會發現你可以看到該應用程式。

d929a7431dd84968.png

  1. 按一下「選單」圖示 ⋮ >。虛擬服務專員建立工具 >資料儲存庫

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

558319790a0accf2.png

完成並測試應用程式

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

  1. 選取 Google Cloud 專案。
  2. 選取「knowledge」代理程式。

ca9b2fb4be92e8e4.png

  1. 選取 代理程式設定 >生成式 AI >生成式虛擬服務專員
  2. 將模型從「Text Bison」切換至 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 設定」下方,選取「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. 選取「knowledge」代理程式。
  3. 選取「起始網頁」
  4. 選取「編輯資料儲存庫」
  5. 在「代理程式回應部分」下方,將「Data store response options」設為 5
  6. 按一下 [儲存]

f5932d03057df645.png

啟動 Cloud 函式

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

  1. 按一下「選單」圖示 ⋮ >。Cloud Functions

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

bd3790a9285f9c07.png

  1. 將「進入點」設為 agent-response-adapter
  2. 將預設內容替換為位於 knowledge-app/agent-response-adapter 目錄中的檔案。
  3. 按一下「部署」

b379bb8ca0fc1079.png

  1. 在等待函式部署的幾分鐘期間,複製網址。

eaae08cf048b9b1c.png

啟動 Webhook

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

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

  1. 選取 Google Cloud 專案。
  2. 選取「knowledge」代理程式。
  3. 依序選取「管理」>「>」Webhook >建立
  4. 將「Display name」(顯示名稱) 設為 Google Chat Response Adapter
  5. 將「Webhook 網址」設為您先前複製的網址。
  6. 按一下 [儲存]

5f3c6804d52b87c1.png

  1. 按一下「Build」
  2. 選取「起始網頁」
  3. 選取「編輯資料儲存庫」
  4. 在「Webhook 設定」下方,按一下「啟用 Webhook」切換按鈕。
  5. 選取「Webhook 適用的 Google Chat 回應轉接器」
  6. 將「標記」設為 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. 應用程式是與 Google Cloud 專案相關聯的 Dialogflow CX 代理程式,會處理訊息。
  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. 在「基本」下方,將「名稱」設為 function-2
  3. 在「驗證」下方,選取「允許未經驗證的叫用」圓形按鈕。
  4. 在「執行階段、建構、連線和安全性設定」下方,將「執行個體數量上限」設為 3
  5. 點選「下一步」

e8cf0ee7441bf634.png

  1. 將「進入點」設為 feedback-app-backend
  2. 將預設內容替換為位於 feedback-app 目錄中的檔案。
  3. 按一下「部署」

bdb5cf9f503aa7f6.png

  1. 在等待函式部署的幾分鐘期間,複製網址。

建立 Dialogflow CX 虛擬服務專員應用程式

建立應用程式

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

  1. 按一下「選單」圖示 ⋮ >。虛擬服務專員建立工具 >應用程式

  1. 點選「New app」(新增應用程式)
  2. 選取「Agent」
  3. 將「Display name」(顯示名稱) 設為 Feedback App
  4. 按一下「建立」

7ef3dbacee96c5aa.png

啟動工具

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

  1. 按一下「選單」圖示 ⋮ >。虛擬服務專員建立工具 >應用程式

  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. 按一下「選單」圖示 ⋮ >。虛擬服務專員建立工具 >應用程式

  1. 選取「Feedback App」代理程式。
  2. 選取 [Agents] > [Agents]預設的生成式虛擬服務專員
  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. 操作說明設為下列值:
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. 按一下「選單」圖示 ⋮ >。虛擬服務專員建立工具 >應用程式

  1. 選取「Feedback App」代理程式。
  2. 前往「預先發布版服務專員」
  3. 在「Agent」下方,選取「FeedbackCollector」
  4. 在「選取生成式模型」下方,選取「gemini-pro」
  5. 傳送「Hello!」訊息即可開始。

90ca8cb7b2c1cb4b.png

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

  1. 按一下「選單」圖示 ⋮ >。Cloud Functions

  1. 選取 function-2 >記錄。某些記錄會將 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。匯入模式功能方便您快速上手。

瞭解詳情