與 API 互動

每個會話回合都會發生互動。在互動期間,使用者會將輸入內容傳送至 Conversational Agents (Dialogflow CX),而 Conversational Agents (Dialogflow CX) 會傳送回應。實作系統以處理互動時,您有兩種選擇:使用 API 或整合。

使用 API 時,系統需要處理下列項目:

  • 建構代理程式。
  • 為使用者提供使用者介面。
  • 針對每個對話回合呼叫 Dialogflow API,將使用者輸入內容傳送至 API。
  • 除非您的對話方回應完全是靜態的 (不常見),否則您需要代管Webhook 服務,以便處理支援 Webhook 的執行要求

使用整合時,您的系統只需處理下列項目:

  • 建構代理程式。
  • 視需要實作 Webhook 服務。

下圖顯示會話階段的步驟。

API 流程圖。

  1. 使用者輸入或說出內容,稱為「使用者輸入內容」
  2. 使用者介面或整合系統會接收輸入內容,並在偵測意圖要求中轉送至 Dialogflow API。
  3. Dialogflow API 會收到偵測意圖要求。它會將輸入內容比對至意圖或表單參數,視需要設定參數,並更新工作階段狀態。如果需要呼叫支援 Webhook 的執行要求,系統會將 Webhook 要求傳送至 Webhook 服務,否則請前往步驟 6。
  4. 您的 Webhook 服務會收到 Webhook 要求。您的服務會採取任何必要動作,例如呼叫外部 API、查詢或更新資料庫等。
  5. Webhook 服務會建立回應,並將 Webhook 回應傳回 Conversational Agents (Dialogflow CX)。
  6. Conversational Agents (Dialogflow CX) 會建立檢測意圖回應。如果呼叫 Webhook,則會使用 Webhook 回應中提供的回應。如果未呼叫 webhook,系統會使用在代理程式中定義的靜態回應。Conversational Agents (Dialogflow CX) 會將偵測意圖回應傳送至使用者介面或整合系統。
  7. 您的使用者介面或整合系統會收到意圖偵測回應,並將文字或音訊回應轉寄給使用者。
  8. 使用者看到或聽到回應。

指南用途

本指南說明如何針對未使用整合服務的服務機器人,為單一對話輪次呼叫 API (上圖第 2 步驟)。本指南不會說明如何為使用者實作使用者介面。

事前準備

閱讀本指南之前,請先完成下列工作:

  1. 請參閱流程基本概念
  2. 執行設定步驟
  3. 建立新的代理程式,或繼續使用您在使用流程建構代理程式使用劇本建構代理程式時建立的代理程式

收集 ID

下列範例需要幾個 ID 做為輸入內容。如要找出專案 ID、區域 ID 和服務專員 ID,請按照下列步驟操作:

Dialogflow CX 主控台

  1. 開啟 Dialogflow CX 控制台
  2. 選取 Google Cloud 專案即可開啟代理程式選取器。
  3. 按一下清單中某個服務專員的 選項選單。
  4. 按一下「複製名稱」 按鈕。
  5. 這會複製代理程式的完整識別名稱,包括專案 ID、區域 ID 和代理程式 ID,格式如下:
    projects/PROJECT_ID/locations/REGION_ID/agents/AGENT_ID

AI Applications 控制台

  1. 前往 AI Applications 控制台:

    AI 應用程式控制台

  2. 主控台頂端會顯示專案 ID。

  3. 「位置」欄會顯示區域 ID。

  4. 選取應用程式。

  5. agents/ 後方的瀏覽器網址路徑區段包含了代理程式應用程式 ID。

您也需要會話 ID。「工作階段」代表 Conversational Agents (Dialogflow CX) 代理程式與使用者之間的對話。您可以在對話開始時建立專屬的工作階段 ID,並將其用於每一回合的對話。為了試用 API,您可以使用任何長度不超過 36 個位元組的字串 ID,例如 test-session-123

呼叫偵測意圖

以下範例會呼叫 Sessions.detectIntent 方法。

選取工作階段參照項目的通訊協定和版本:

通訊協定 V3 V3beta1
REST 工作階段資源 工作階段資源
RPC 工作階段介面 工作階段介面
C++ SessionsClient 不適用
C# SessionsClient 不適用
Go SessionsClient 不適用
Java SessionsClient SessionsClient
Node.js SessionsClient SessionsClient
PHP 不適用 不適用
Python SessionsClient SessionsClient
Ruby 不適用 不適用

REST

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_ID:您的 Google Cloud 專案 ID
  • AGENT_ID:你的代理人 ID
  • REGION_ID:您的區域 ID
  • SESSION_ID:您的工作階段 ID
  • END_USER_INPUT:使用者輸入內容

HTTP 方法和網址:

POST https://REGION_ID-dialogflow.googleapis.com/v3/projects/PROJECT_ID/locations/REGION_ID/agents/AGENT_ID/sessions/SESSION_ID:detectIntent

JSON 要求主體:

{
  "queryInput": {
    "text": {
      "text": "END_USER_INPUT"
    },
    "languageCode": "en"
  },
  "queryParams": {
    "timeZone": "America/Los_Angeles"
  }
}

如要傳送要求,請展開以下其中一個選項:

您應該會收到如下的 JSON 回應:

{
  "responseId": "38e8f23d-eed2-445e-a3e7-149b242dd669",
  "queryResult": {
    "text": "I want to buy a shirt",
    "languageCode": "en",
    "responseMessages": [
      {
        "text": {
          "text": [
            "Ok, let's start a new order."
          ]
        }
      },
      {
        "text": {
          "text": [
            "I'd like to collect a bit more information from you."
          ]
        }
      },
      {
        "text": {
          "text": [
            "What color would you like?"
          ]
        }
      },
      {}
    ],
    "currentPage": {
      "name": "projects/PROJECT_ID/locations/us-central1/agents/133b0350-f2d2-4928-b0b3-5b332259d0f7/flows/00000000-0000-0000-0000-000000000000/pages/ce0b88c4-9292-455c-9c59-ec153dad94cc",
      "displayName": "New Order"
    },
    "intent": {
      "name": "projects/PROJECT_ID/locations/us-central1/agents/133b0350-f2d2-4928-b0b3-5b332259d0f7/intents/0adebb70-a727-4687-b8bc-fbbc2ac0b665",
      "displayName": "order.new"
    },
    "intentDetectionConfidence": 1,
    "diagnosticInfo": { ... },
    "match": {
      "intent": {
        "name": "projects/PROJECT_ID/locations/us-central1/agents/133b0350-f2d2-4928-b0b3-5b332259d0f7/intents/0adebb70-a727-4687-b8bc-fbbc2ac0b665",
        "displayName": "order.new"
      },
      "resolvedInput": "I want to buy a shirt",
      "matchType": "INTENT",
      "confidence": 1
    }
  }
}

Java

如要向 Dialogflow 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證機制」。


import com.google.api.gax.rpc.ApiException;
import com.google.cloud.dialogflow.cx.v3beta1.DetectIntentRequest;
import com.google.cloud.dialogflow.cx.v3beta1.DetectIntentResponse;
import com.google.cloud.dialogflow.cx.v3beta1.QueryInput;
import com.google.cloud.dialogflow.cx.v3beta1.QueryResult;
import com.google.cloud.dialogflow.cx.v3beta1.SessionName;
import com.google.cloud.dialogflow.cx.v3beta1.SessionsClient;
import com.google.cloud.dialogflow.cx.v3beta1.SessionsSettings;
import com.google.cloud.dialogflow.cx.v3beta1.TextInput;
import com.google.common.collect.Maps;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class DetectIntent {

  // DialogFlow API Detect Intent sample with text inputs.
  public static Map<String, QueryResult> detectIntent(
      String projectId,
      String locationId,
      String agentId,
      String sessionId,
      List<String> texts,
      String languageCode)
      throws IOException, ApiException {
    SessionsSettings.Builder sessionsSettingsBuilder = SessionsSettings.newBuilder();
    if (locationId.equals("global")) {
      sessionsSettingsBuilder.setEndpoint("dialogflow.googleapis.com:443");
    } else {
      sessionsSettingsBuilder.setEndpoint(locationId + "-dialogflow.googleapis.com:443");
    }
    SessionsSettings sessionsSettings = sessionsSettingsBuilder.build();

    Map<String, QueryResult> queryResults = Maps.newHashMap();
    // Instantiates a client.

    // Note: close() needs to be called on the SessionsClient object to clean up resources
    // such as threads. In the example below, try-with-resources is used,
    // which automatically calls close().
    try (SessionsClient sessionsClient = SessionsClient.create(sessionsSettings)) {
      // Set the session name using the projectID (my-project-id), locationID (global), agentID
      // (UUID), and sessionId (UUID).
      SessionName session =
          SessionName.ofProjectLocationAgentSessionName(projectId, locationId, agentId, sessionId);

      // TODO : Uncomment if you want to print session path
      // System.out.println("Session Path: " + session.toString());

      // Detect intents for each text input.
      for (String text : texts) {
        // Set the text (hello) for the query.
        TextInput.Builder textInput = TextInput.newBuilder().setText(text);

        // Build the query with the TextInput and language code (en-US).
        QueryInput queryInput =
            QueryInput.newBuilder().setText(textInput).setLanguageCode(languageCode).build();

        // Build the DetectIntentRequest with the SessionName and QueryInput.
        DetectIntentRequest request =
            DetectIntentRequest.newBuilder()
                .setSession(session.toString())
                .setQueryInput(queryInput)
                .build();

        // Performs the detect intent request.
        DetectIntentResponse response = sessionsClient.detectIntent(request);

        // Display the query result.
        QueryResult queryResult = response.getQueryResult();

        // TODO : Uncomment if you want to print queryResult
        // System.out.println("====================");
        // System.out.format("Query Text: '%s'\n", queryResult.getText());
        // System.out.format(
        //     "Detected Intent: %s (confidence: %f)\n",
        //     queryResult.getIntent().getDisplayName(),
        //         queryResult.getIntentDetectionConfidence());

        queryResults.put(text, queryResult);
      }
    }
    return queryResults;
  }
}

Node.js

如要向 Dialogflow 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證機制」。

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'my-project';
// const location = 'global';
// const agentId = 'my-agent';
// const query = 'Hello';
// const languageCode = 'en'

// Imports the Google Cloud Some API library
const {SessionsClient} = require('@google-cloud/dialogflow-cx');
/**
 * Example for regional endpoint:
 *   const location = 'us-central1'
 *   const client = new SessionsClient({apiEndpoint: 'us-central1-dialogflow.googleapis.com'})
 */
const client = new SessionsClient();

async function detectIntentText() {
  const sessionId = Math.random().toString(36).substring(7);
  const sessionPath = client.projectLocationAgentSessionPath(
    projectId,
    location,
    agentId,
    sessionId
  );
  const request = {
    session: sessionPath,
    queryInput: {
      text: {
        text: query,
      },
      languageCode,
    },
  };
  const [response] = await client.detectIntent(request);
  for (const message of response.queryResult.responseMessages) {
    if (message.text) {
      console.log(`Agent Response: ${message.text.text}`);
    }
  }
  if (response.queryResult.match.intent) {
    console.log(
      `Matched Intent: ${response.queryResult.match.intent.displayName}`
    );
  }
  console.log(
    `Current Page: ${response.queryResult.currentPage.displayName}`
  );
}

detectIntentText();

Python

如要向 Dialogflow 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證機制」。

def run_sample():
    # TODO(developer): Replace these values when running the function
    project_id = "YOUR-PROJECT-ID"
    # For more information about regionalization see https://cloud.google.com/dialogflow/cx/docs/how/region
    location_id = "YOUR-LOCATION-ID"
    # For more info on agents see https://cloud.google.com/dialogflow/cx/docs/concept/agent
    agent_id = "YOUR-AGENT-ID"
    agent = f"projects/{project_id}/locations/{location_id}/agents/{agent_id}"
    # For more information on sessions see https://cloud.google.com/dialogflow/cx/docs/concept/session
    session_id = uuid.uuid4()
    texts = ["Hello"]
    # For more supported languages see https://cloud.google.com/dialogflow/es/docs/reference/language
    language_code = "en-us"

    detect_intent_texts(agent, session_id, texts, language_code)


def detect_intent_texts(agent, session_id, texts, language_code):
    """Returns the result of detect intent with texts as inputs.

    Using the same `session_id` between requests allows continuation
    of the conversation."""
    session_path = f"{agent}/sessions/{session_id}"
    print(f"Session path: {session_path}\n")
    client_options = None
    agent_components = AgentsClient.parse_agent_path(agent)
    location_id = agent_components["location"]
    if location_id != "global":
        api_endpoint = f"{location_id}-dialogflow.googleapis.com:443"
        print(f"API Endpoint: {api_endpoint}\n")
        client_options = {"api_endpoint": api_endpoint}
    session_client = SessionsClient(client_options=client_options)

    for text in texts:
        text_input = session.TextInput(text=text)
        query_input = session.QueryInput(text=text_input, language_code=language_code)
        request = session.DetectIntentRequest(
            session=session_path, query_input=query_input
        )
        response = session_client.detect_intent(request=request)

        print("=" * 20)
        print(f"Query text: {response.query_result.text}")
        response_messages = [
            " ".join(msg.text.text) for msg in response.query_result.response_messages
        ]
        print(f"Response text: {' '.join(response_messages)}\n")

正式化

在實際工作環境中執行服務前,請務必實作實際工作環境最佳做法