快速入門導覽課程:與 API 的互動

如果您未使用整合,則必須編寫可與使用者互動的程式碼。針對每個對話回合,程式碼會呼叫 Dialogflow API 來查詢服務機器人。本指南說明如何透過指令列使用 REST API,以及使用用戶端程式庫與代理程式互動。

事前準備

如果您不打算使用 API,可以略過本快速入門導覽課程。

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

  1. 瞭解 Dialogflow 基本概念
  2. 執行設定步驟
  3. 執行建構代理程式快速入門指南中的步驟。以下步驟將繼續處理您在該指南中開始使用的代理程式。如果您不再擁有該代理程式,可以下載 build-agent-quickstart.zip匯入檔案

工作階段

工作階段代表 Dialogflow 代理程式和使用者之間的對話。您可以在對話開始時建立一個工作階段,並將其用於每一回合的對話。當對話結束,您便停止使用該工作階段。

您不該將同一工作階段用於與不同使用者的並行對話。Dialogflow 會保留每個作用中工作階段目前有效的背景資訊。而且工作階段資料會由 Dialogflow 儲存 20 分鐘。

每個工作階段都是由系統產生的工作階段 ID 所決定。 您可透過在偵測意圖要求中提供新的工作階段 ID,來建立新的工作階段。工作階段 ID 是長度最多 36 個位元組的字串。您的系統負責產生不重複的工作階段 ID,其可以是隨機數字、經過雜湊處理的使用者 ID,或是方便產生的任何其他值。

偵測意圖

使用 API 互動時,您的服務會直接與使用者互動。針對每一回合對話,您的服務會呼叫 Sessions 類型的 detectIntentstreamingDetectIntent 方法,將使用者表達內容傳送到 Dialogflow。Dialogflow 使用相符意圖、行動、參數及為該意圖定義的回應等相關資訊來做出回應。您的服務會視需要執行動作,例如查詢資料庫或呼叫外部 API,並傳送訊息給使用者。此程序會一直持續到對話結束為止。

下列範例說明如何偵測意圖。每個範例都接受以下輸入的子集:

  • 專案 ID :使用您在設定步驟中所建立專案的專案 ID。
  • 工作階段 ID:基於測試代理程式之目的,您可使用任何識別碼。例如一般範例常用「123456789」。
  • 一或多個文本:這是單一的使用者表達內容或使用者表達內容清單。如果提供了多個表達內容,範例程式碼便會針對每個表達內容呼叫偵測意圖。請嘗試使用「我會法文」。
  • 語言代碼:使用者表達內容的語言代碼。對於此範例代理程式,請使用「en-US」。

REST

如要偵測意圖,請呼叫 Sessions 資源上的 detectIntent 方法。

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

  • PROJECT_ID:您的 Google Cloud 專案 ID
  • SESSION_ID:工作階段 ID

HTTP 方法和網址:

POST https://dialogflow.googleapis.com/v2/projects/PROJECT_ID/agent/sessions/SESSION_ID:detectIntent

JSON 要求主體:

{
  "query_input": {
    "text": {
      "text": "I know french",
      "language_code": "en-US"
    }
  }
}

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

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

{
  "responseId": "856510ca-f617-4e25-b0bb-a26c0a59e030-19db3199",
  "queryResult": {
    "queryText": "I know french",
    "parameters": {
      "language": "French",
      "language-programming": ""
    },
    "allRequiredParamsPresent": true,
    "fulfillmentText": "Wow! I didn't know you knew French. How long have you known French?",
    "fulfillmentMessages": [
      {
        "text": {
          "text": [
            "Wow! I didn't know you knew French. How long have you known French?"
          ]
        }
      }
    ],
    "outputContexts": [
      {
        "name": "projects/PROJECT_ID/agent/sessions/123456789/contexts/set-language-followup",
        "lifespanCount": 2,
        "parameters": {
          "language": "French",
          "language.original": "french",
          "language-programming": "",
          "language-programming.original": ""
        }
      }
    ],
    "intent": {
      "name": "projects/PROJECT_ID/agent/intents/fe45022f-e58a-484f-96e8-1cbd6628f648",
      "displayName": "set-language"
    },
    "intentDetectionConfidence": 1,
    "languageCode": "en"
  }
}

請注意回應的下列部分:

  • queryResult.intent 欄位包含相符的意圖。
  • queryResult.fulfillmentMessages 欄位的值包含意圖回應。這是您的系統應轉送給使用者的回應。
  • queryResult.parameters 欄位的值包含從使用者表達內容中擷取的參數。
  • queryResult.outputContext 欄位包含有效的背景資訊。

Go

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

func DetectIntentText(projectID, sessionID, text, languageCode string) (string, error) {
	ctx := context.Background()

	sessionClient, err := dialogflow.NewSessionsClient(ctx)
	if err != nil {
		return "", err
	}
	defer sessionClient.Close()

	if projectID == "" || sessionID == "" {
		return "", fmt.Errorf("detect.DetectIntentText received empty project (%s) or session (%s)", projectID, sessionID)
	}

	sessionPath := fmt.Sprintf("projects/%s/agent/sessions/%s", projectID, sessionID)
	textInput := dialogflowpb.TextInput{Text: text, LanguageCode: languageCode}
	queryTextInput := dialogflowpb.QueryInput_Text{Text: &textInput}
	queryInput := dialogflowpb.QueryInput{Input: &queryTextInput}
	request := dialogflowpb.DetectIntentRequest{Session: sessionPath, QueryInput: &queryInput}

	response, err := sessionClient.DetectIntent(ctx, &request)
	if err != nil {
		return "", err
	}

	queryResult := response.GetQueryResult()
	fulfillmentText := queryResult.GetFulfillmentText()
	return fulfillmentText, nil
}

Java

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


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

public class DetectIntentTexts {

  // DialogFlow API Detect Intent sample with text inputs.
  public static Map<String, QueryResult> detectIntentTexts(
      String projectId, List<String> texts, String sessionId, String languageCode)
      throws IOException, ApiException {
    Map<String, QueryResult> queryResults = Maps.newHashMap();
    // Instantiates a client
    try (SessionsClient sessionsClient = SessionsClient.create()) {
      // Set the session name using the sessionId (UUID) and projectID (my-project-id)
      SessionName session = SessionName.of(projectId, sessionId);
      System.out.println("Session Path: " + session.toString());

      // Detect intents for each text input
      for (String text : texts) {
        // Set the text (hello) and language code (en-US) for the query
        TextInput.Builder textInput =
            TextInput.newBuilder().setText(text).setLanguageCode(languageCode);

        // Build the query with the TextInput
        QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build();

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

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

        System.out.println("====================");
        System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
        System.out.format(
            "Detected Intent: %s (confidence: %f)\n",
            queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
        System.out.format(
            "Fulfillment Text: '%s'\n",
            queryResult.getFulfillmentMessagesCount() > 0
                ? queryResult.getFulfillmentMessages(0).getText()
                : "Triggered Default Fallback Intent");

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

Node.js

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


/**
 * TODO(developer): UPDATE these variables before running the sample.
 */
// projectId: ID of the GCP project where Dialogflow agent is deployed
// const projectId = 'PROJECT_ID';
// sessionId: String representing a random number or hashed user identifier
// const sessionId = '123456';
// queries: A set of sequential queries to be send to Dialogflow agent for Intent Detection
// const queries = [
//   'Reserve a meeting room in Toronto office, there will be 5 of us',
//   'Next monday at 3pm for 1 hour, please', // Tell the bot when the meeting is taking place
//   'B'  // Rooms are defined on the Dialogflow agent, default options are A, B, or C
// ]
// languageCode: Indicates the language Dialogflow agent should use to detect intents
// const languageCode = 'en';

// Imports the Dialogflow library
const dialogflow = require('@google-cloud/dialogflow');

// Instantiates a session client
const sessionClient = new dialogflow.SessionsClient();

async function detectIntent(
  projectId,
  sessionId,
  query,
  contexts,
  languageCode
) {
  // The path to identify the agent that owns the created intent.
  const sessionPath = sessionClient.projectAgentSessionPath(
    projectId,
    sessionId
  );

  // The text query request.
  const request = {
    session: sessionPath,
    queryInput: {
      text: {
        text: query,
        languageCode: languageCode,
      },
    },
  };

  if (contexts && contexts.length > 0) {
    request.queryParams = {
      contexts: contexts,
    };
  }

  const responses = await sessionClient.detectIntent(request);
  return responses[0];
}

async function executeQueries(projectId, sessionId, queries, languageCode) {
  // Keeping the context across queries let's us simulate an ongoing conversation with the bot
  let context;
  let intentResponse;
  for (const query of queries) {
    try {
      console.log(`Sending Query: ${query}`);
      intentResponse = await detectIntent(
        projectId,
        sessionId,
        query,
        context,
        languageCode
      );
      console.log('Detected intent');
      console.log(
        `Fulfillment Text: ${intentResponse.queryResult.fulfillmentText}`
      );
      // Use the context from this response for next queries
      context = intentResponse.queryResult.outputContexts;
    } catch (error) {
      console.log(error);
    }
  }
}
executeQueries(projectId, sessionId, queries, languageCode);

Python

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

def detect_intent_texts(project_id, 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."""
    from google.cloud import dialogflow

    session_client = dialogflow.SessionsClient()

    session = session_client.session_path(project_id, session_id)
    print("Session path: {}\n".format(session))

    for text in texts:
        text_input = dialogflow.TextInput(text=text, language_code=language_code)

        query_input = dialogflow.QueryInput(text=text_input)

        response = session_client.detect_intent(
            request={"session": session, "query_input": query_input}
        )

        print("=" * 20)
        print("Query text: {}".format(response.query_result.query_text))
        print(
            "Detected intent: {} (confidence: {})\n".format(
                response.query_result.intent.display_name,
                response.query_result.intent_detection_confidence,
            )
        )
        print("Fulfillment text: {}\n".format(response.query_result.fulfillment_text))

其他語言

C#:請按照用戶端程式庫頁面上的C# 設定說明操作,然後參閱 .NET 適用的 Dialogflow 參考說明文件

PHP:請按照用戶端程式庫頁面上的 PHP 設定操作說明操作,然後參閱 PHP 適用的 Dialogflow 參考文件

Ruby:請按照用戶端程式庫頁面上的 Ruby 設定說明操作,然後參閱 Ruby 適用的 Dialogflow 參考文件

正式化

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