知識連接器

知識連接器可與已定義的意圖彼此互補。知識連接器可剖析知識文件 (例如常見問題或文章) 來找出自動化回應。如要設定知識連接器,您必須定義一或多個知識庫 (即知識文件集合)。

您可以為代理程式啟用知識庫,讓所有偵測意圖要求可以使用您的知識庫找到自動化回應。您也可以在個人的偵測意圖要求中指定一或多個知識庫。

代理程式常常會同時使用知識連接器和已定義的意圖。相較於意圖,知識連接器的回應精確度較低,也較無法控制。如果是複雜的使用者要求,您應該要定義意圖來處理;如果是簡單的要求,則應讓知識連接器來處理。

如需支援的語言清單,請參閱語言參考資料中的「知識連接器」欄。

限制

知識連結器功能僅適用於global 區域

啟用 Beta 版功能

確認已啟用 Beta 版功能:

  1. 前往 Dialogflow ES 主控台
  2. 選取代理程式。
  3. 按一下代理程式名稱旁邊的設定 按鈕。
  4. 在「General」分頁中向下捲動,並確保「Beta Features」已設為啟用。
  5. 如果您變更了設定,請按一下「儲存」

建立知識庫和文件

按照知識庫操作說明中的指示建立知識庫和文件。

知識連接器的設定

您可以為代理程式啟用或停用知識庫。 如果意圖比對要求未指定知識庫,系統會考慮使用已啟用的知識庫。如要啟用或停用知識庫,請按照下列步驟操作:

  1. 前往 Dialogflow ES 主控台
  2. 選取代理程式。
  3. 按一下左側欄選單中的「知識」
  4. 從清單中選取一或多個知識庫。
  5. 按一下「啟用」或「停用」

如果使用者表達內容也符合意圖,您可以指定知識結果的偏好程度:

  1. 向下捲動至「調整知識結果偏好設定」部分。
  2. 調整滑桿,從較弱 (偏好意圖) 到較強 (偏好知識)。詳情請參閱下方的「偵測意圖回應」。

設定回覆

根據預設,知識庫會設定單一預設文字回覆,並填入最相符的知識答案。你可以變更這項回覆,並新增豐富的回覆訊息。每個知識庫最多可提供三個答案,您可以在設定的回覆中參考這些答案。如要新增回覆:

  1. 在「知識」頁面中,按一下知識庫名稱。
  2. 向下捲動至「Responses」(回應) 區段,然後新增所需回應:
    1. 定義第一個回應時,請將 $Knowledge.Question[1]$Knowledge.Answer[1] 用於您想提供問題和答案的位置。
    2. $Knowledge.Question$Knowledge.Answer 的索引是從 1 開始,因此當您新增其他回應時,請一併增加這項索引。
  3. 編輯完成後,請按一下「儲存」

定義回應時應考慮下列幾點:

  • 如果知識連接器回應相符項目的數量為 N,而定義的回應數量超過這個值,系統只會傳回 N 個回應。
  • 相較於比對已明確定義的意圖,這種做法的準確率可能較低,因此建議您在可能的情況下,向使用者傳回三個回應。

範例:

知識連接器整合服務螢幕擷圖

透過知識庫偵測意圖

提出偵測意圖要求時,您可以指定一或多個知識庫,用於提供可能的回應。在要求中明確提供知識庫,會覆寫已啟用和已停用知識庫的設定。

以下範例說明如何使用 Dialogflow 主控台、REST API (包括指令列) 或用戶端程式庫來偵測意圖。如要使用 API,請在 Sessions 類型上呼叫 detectIntent 方法。

網路使用者介面

您可以透過 Dialogflow 模擬工具與代理程式互動及接收知識連接器回應,方法如下:

  1. 按照上述步驟啟用知識庫
  2. 按照上述步驟定義回應
  3. 在模擬工具中輸入「如何申請?」

REST

Sessions 類型上呼叫 detectIntent 方法,然後在 queryParams 欄位中指定知識庫。

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

  • PROJECT_ID:您的 GCP 專案 ID
  • KNOWLEDGE_BASE_ID:您的知識庫 ID

HTTP 方法和網址:

POST https://dialogflow.googleapis.com/v2beta1/projects/PROJECT_ID/agent/sessions/123456789:detectIntent

JSON 要求主體:

{
 "queryInput": {
   "text": {
     "text": "How do I sign up?",
     "languageCode": "en-US"
   }
 },
 "queryParams": {
   "knowledgeBaseNames": ["projects/PROJECT_ID/knowledgeBases/KNOWLEDGE_BASE_ID"]
 }
}

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

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

{
  ...
  "queryResult": {
    "queryText": "How do I sign up?",
    "parameters": {},
    "allRequiredParamsPresent": true,
    "fulfillmentText": "Sign up for Cloud Storage by turning on the Cloud Storage service in the Google Cloud Platform Console.",
    "intent": {
      "name": "projects/my-gcp-project/agent/intents/487c7242-a769-408a-a339-47b95e10dac4",
      "displayName": "Knowledge.KnowledgeBase.MzkzNTAyMDE3NDQxNDk3MDg4MA"
    },
    "intentDetectionConfidence": 0.99371547,
    "languageCode": "en-us",
    "knowledgeAnswers": {
      "answers": [
        {
          "answer": "Sign up for Cloud Storage by turning on the Cloud Storage service in the Google Cloud Platform Console.",
          "matchConfidenceLevel": "HIGH",
          "matchConfidence": 0.99371547
        },
        {
          "answer": "Certain types of content are not allowed on this service; please refer to the Terms of Services and Platform Policies for details. If you believe a piece of content is in violation of our policies, report it here (select See more products, then Google Cloud Storage and Cloud Bigtable).",
          "matchConfidenceLevel": "LOW",
          "matchConfidence": 0.0012244871
        },
        {
          "answer": "From the Cloud Storage documentation click \"Send feedback\" near the top right of the page. This will open a feedback form. Your comments will be reviewed by the Cloud Storage team.",
          "matchConfidenceLevel": "LOW",
          "matchConfidence": 0.0011537358
        }
      ]
    }
  }
}

Java

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


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

public class DetectIntentKnowledge {

  // DialogFlow API Detect Intent sample with querying knowledge connector.
  public static Map<String, KnowledgeAnswers> detectIntentKnowledge(
      String projectId,
      String knowledgeBaseName,
      String sessionId,
      String languageCode,
      List<String> texts)
      throws IOException, ApiException {
    // Instantiates a client
    Map<String, KnowledgeAnswers> allKnowledgeAnswers = Maps.newHashMap();
    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 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();

        QueryParameters queryParameters =
            QueryParameters.newBuilder().addKnowledgeBaseNames(knowledgeBaseName).build();

        DetectIntentRequest detectIntentRequest =
            DetectIntentRequest.newBuilder()
                .setSession(session.toString())
                .setQueryInput(queryInput)
                .setQueryParams(queryParameters)
                .build();
        // Performs the detect intent request
        DetectIntentResponse response = sessionsClient.detectIntent(detectIntentRequest);

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

        System.out.format("Knowledge results:\n");
        System.out.format("====================\n");
        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");
        KnowledgeAnswers knowledgeAnswers = queryResult.getKnowledgeAnswers();
        for (Answer answer : knowledgeAnswers.getAnswersList()) {
          System.out.format(" - Answer: '%s'\n", answer.getAnswer());
          System.out.format(" - Confidence: '%s'\n", answer.getMatchConfidence());
        }

        KnowledgeAnswers answers = queryResult.getKnowledgeAnswers();
        allKnowledgeAnswers.put(text, answers);
      }
    }
    return allKnowledgeAnswers;
  }
}

Node.js

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

// Imports the Dialogflow client library
const dialogflow = require('@google-cloud/dialogflow').v2beta1;
// Instantiate a DialogFlow client.
const sessionClient = new dialogflow.SessionsClient();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const projectId = 'ID of GCP project associated with your Dialogflow agent';
// const sessionId = `user specific ID of session, e.g. 12345`;
// const languageCode = 'BCP-47 language code, e.g. en-US';
// const knowledgeBaseId = `the ID of your KnowledgeBase`;
// const query = `phrase(s) to pass to detect, e.g. I'd like to reserve a room for six people`;

// Define session path
const sessionPath = sessionClient.projectAgentSessionPath(
  projectId,
  sessionId
);
const knowledgeBasePath =
  'projects/' + projectId + '/knowledgeBases/' + knowledgeBaseId + '';

// The audio query request
const request = {
  session: sessionPath,
  queryInput: {
    text: {
      text: query,
      languageCode: languageCode,
    },
  },
  queryParams: {
    knowledgeBaseNames: [knowledgeBasePath],
  },
};

const responses = await sessionClient.detectIntent(request);
const result = responses[0].queryResult;
console.log(`Query text: ${result.queryText}`);
console.log(`Detected Intent: ${result.intent.displayName}`);
console.log(`Confidence: ${result.intentDetectionConfidence}`);
console.log(`Query Result: ${result.fulfillmentText}`);
if (result.knowledgeAnswers && result.knowledgeAnswers.answers) {
  const answers = result.knowledgeAnswers.answers;
  console.log(`There are ${answers.length} answer(s);`);
  answers.forEach(a => {
    console.log(`   answer: ${a.answer}`);
    console.log(`   confidence: ${a.matchConfidence}`);
    console.log(`   match confidence level: ${a.matchConfidenceLevel}`);
  });
}

Python

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

def detect_intent_knowledge(
    project_id, session_id, language_code, knowledge_base_id, texts
):
    """Returns the result of detect intent with querying Knowledge Connector.

    Args:
    project_id: The GCP project linked with the agent you are going to query.
    session_id: Id of the session, using the same `session_id` between requests
              allows continuation of the conversation.
    language_code: Language of the queries.
    knowledge_base_id: The Knowledge base's id to query against.
    texts: A list of text queries to send.
    """
    from google.cloud import dialogflow_v2beta1 as dialogflow

    session_client = dialogflow.SessionsClient()

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

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

        query_input = dialogflow.QueryInput(text=text_input)

        knowledge_base_path = dialogflow.KnowledgeBasesClient.knowledge_base_path(
            project_id, knowledge_base_id
        )

        query_params = dialogflow.QueryParameters(
            knowledge_base_names=[knowledge_base_path]
        )

        request = dialogflow.DetectIntentRequest(
            session=session_path, query_input=query_input, query_params=query_params
        )
        response = session_client.detect_intent(request=request)

        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))
        print("Knowledge results:")
        knowledge_answers = response.query_result.knowledge_answers
        for answers in knowledge_answers.answers:
            print(" - Answer: {}".format(answers.answer))
            print(" - Confidence: {}".format(answers.match_confidence))

偵測意圖回應

Sessions 類型 detectIntent 方法的回應是 DetectIntentResponse。有多種因素會影響回應欄位的填入方式。

如果已定義的意圖和知識庫皆為可能的相符項目,系統會依各個項目的比對信心值和「知識結果偏好設定」(請參閱知識連接器的設定一節),判斷哪個項目為指定相符項目。DetectIntentResponse.queryResult 欄位會填入指定相符項目,DetectIntentResponse.alternativeQueryResults 欄位則會填入其他可能的相符項目。這兩個欄位均包含 QueryResult 訊息。

如果知識庫提供可能的相符項目:

  • QueryResult.knowledgeAnswers 會填入一連串可能的知識答案,依比對信心值大至小的順序排列。
  • 如果知識庫已定義複合式回應,QueryResult.fulfillmentMessages 會填入複合式回應訊息。

執行偵測意圖要求時,知識查詢可能會失敗。在這種情況下,系統會選取已定義的意圖,這樣整體偵測意圖要求就不會失敗。您可以在 DetectIntentResponse.alternativeQueryResults[i].diagnosticInfo 欄位中查看知識查詢錯誤資訊。

管理知識庫

如要進一步瞭解如何管理知識庫,請參閱管理知識庫