知识连接器

知识连接器是对所定义意图的补充,可通过解析知识文档(例如常见问题解答或文章)来找出自动响应。如需配置知识连接器,您需要定义一个或多个知识库(即知识文档集合)。

您可以为代理启用知识库,让所有检测意图请求都能使用您的知识库找到自动响应。或者,您也可以在单独的检测意图请求中指定一个或多个知识库。

代理常常会同时使用知识连接器和定义的意图。知识连接器提供的响应精确率和控制比不上意图。 您应该定义意图来处理复杂的用户请求,让知识连接器处理简单的请求。

如需了解支持的语言列表,请参阅语言参考中的知识连接器列。

限制

知识连接器功能仅适用于 global 区域

启用测试版功能

确保已启用 Beta 版功能:

  1. 转到 Dialogflow ES 控制台
  2. 选择一个代理。
  3. 点击代理名称旁边的设置 按钮。
  4. 常规 (General) 标签页中向下滚动,并确保已启用 Beta 版功能 (Beta Features)。
  5. 如果您进行了更改,请点击保存 (Save)。

创建知识库和文档

按照知识库 How-to 中的说明创建知识库和文档。

知识连接器设置

您可以为代理启用或停用知识库。 对于所有未指定知识库的意图匹配请求,系统将考虑已启用的知识库。如需启用或停用知识库,请执行以下操作:

  1. 转到 Dialogflow ES 控制台
  2. 选择一个代理。
  3. 点击左侧边栏菜单中的知识 (Knowledge)。
  4. 从列表中选择一个或多个知识库。
  5. 点击启用停用

当最终用户表达式也与意图相匹配时,您可以指定您偏好知识结果的强度:

  1. 向下滚动到调整知识结果首选项部分。
  2. 从弱(偏向意图)到强(偏向知识)调整滑块。如需了解详情,请参阅下面的检测意图响应

配置响应

默认情况下,知识库配置有单个默认文本响应,其中填充了最匹配的知识答案。您可以更改此响应并添加富响应消息。知识回复针对每个知识库最多可包含三个答案,您可以在配置的响应中引用这些答案。如需添加响应,请执行以下操作:

  1. 知识 (Knowledge) 页面,点击您的知识库名称。
  2. 向下滚动到响应 (Responses) 部分,然后根据需要添加响应:
    1. 定义第一个响应时,请在您希望提供问题和答案的位置使用 $Knowledge.Question[1]$Knowledge.Answer[1]
    2. $Knowledge.Question$Knowledge.Answer 的索引从 1 开始,因此在添加更多响应时,请相应增加此索引的值。
  3. 修改完毕后,点击保存 (Save)。

在定义响应时,应考虑以下几点:

  • 如果定义的响应数量大于知识连接器响应所匹配的数量 N,则只会返回 N 条响应。
  • 与匹配明确定义的 intent 相比,准确性可能较低,我们建议尽可能向用户返回三条响应。

示例:

知识连接器集成屏幕截图

用知识库检测意图

在执行检测意向请求时,您可以为可能的响应指定一个或多个知识库。在请求中明确提供知识库会覆盖启用和停用知识库的设置。

下面的示例展示您如何使用 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 字段中找到知识查询错误信息。

管理知识库

如需详细了解如何管理知识库,请参阅管理知识库