管理知识库

知识库是您提供给 Dialogflow 的知识文档的集合。您的知识文档中包含的信息可能有助于与最终用户的对话。在寻找对最终用户表达的响应时,某些 Dialogflow 功能会使用知识库。本指南介绍如何创建和管理知识库。

知识库在代理级别应用

准备工作

在阅读本指南之前,请先完成以下事项:

  1. 阅读 Dialogflow 基础知识
  2. 执行设置步骤

创建知识库

下面的示例展示您如何使用 Dialogflow 控制台、REST API(包括命令行)或客户端库来创建知识库。如需使用 API,请调用 KnowledgeBase 类型的 create 方法。

网页界面

使用 Dialogflow 控制台创建知识库:

  1. 转到 Dialogflow ES 控制台
  2. 选择一个代理
  3. 点击左侧边栏菜单上的知识 (Knowledge)
  4. 点击创建知识库 (Create Knowledge Base)
  5. 输入知识库名称
  6. 点击保存

REST

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的 GCP 项目 ID
  • KNOWLEDGE_BASE_DISPLAY_NAME:所需的知识库名称

HTTP 方法和网址:

POST https://dialogflow.googleapis.com/v2beta1/projects/PROJECT_ID/knowledgeBases

请求 JSON 正文:

{
  "displayName": "KNOWLEDGE_BASE_DISPLAY_NAME"
}

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "name": "projects/PROJECT_ID/knowledgeBases/NDA4MTM4NzE2MjMwNDUxMjAwMA",
  "displayName": "KNOWLEDGE_BASE_DISPLAY_NAME"
}

记下 name 字段的值。这是您的新知识库的名称。 knowledgeBases 后面的路径段是您的新知识库 ID。 请保存此 ID,以供后续请求使用。

Java

要向 Dialogflow 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.api.gax.rpc.ApiException;
import com.google.cloud.dialogflow.v2.KnowledgeBase;
import com.google.cloud.dialogflow.v2.KnowledgeBasesClient;
import com.google.cloud.dialogflow.v2.LocationName;
import java.io.IOException;

public class KnowledgeBaseManagement {

  public static void main(String[] args) throws ApiException, IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String location = "my-location";

    // Set display name of the new knowledge base
    String knowledgeBaseDisplayName = "my-knowledge-base-display-name";

    // Create a knowledge base
    createKnowledgeBase(projectId, location, knowledgeBaseDisplayName);
  }

  // Create a Knowledge base
  public static void createKnowledgeBase(String projectId, String location, String displayName)
      throws ApiException, IOException {
    // Instantiates a client
    try (KnowledgeBasesClient knowledgeBasesClient = KnowledgeBasesClient.create()) {
      KnowledgeBase targetKnowledgeBase =
          KnowledgeBase.newBuilder().setDisplayName(displayName).build();
      LocationName parent = LocationName.of(projectId, location);
      KnowledgeBase createdKnowledgeBase =
          knowledgeBasesClient.createKnowledgeBase(parent, targetKnowledgeBase);
      System.out.println("====================");
      System.out.format("Knowledgebase created:\n");
      System.out.format("Display Name: %s\n", createdKnowledgeBase.getDisplayName());
      System.out.format("Name: %s\n", createdKnowledgeBase.getName());
    }
  }
}

Node.js

要向 Dialogflow 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

// Instantiate a DialogFlow client.
const client = new dialogflow.KnowledgeBasesClient();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const projectId = 'ID of GCP project associated with your Dialogflow agent';
// const displayName = `your knowledge base display name, e.g. myKnowledgeBase`;

const formattedParent = 'projects/' + projectId;
const knowledgeBase = {
  displayName: displayName,
};
const request = {
  parent: formattedParent,
  knowledgeBase: knowledgeBase,
};

const [result] = await client.createKnowledgeBase(request);
console.log(`Name: ${result.name}`);
console.log(`displayName: ${result.displayName}`);

Python

要向 Dialogflow 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

def create_knowledge_base(project_id, display_name):
    """Creates a Knowledge base.

    Args:
        project_id: The GCP project linked with the agent.
        display_name: The display name of the Knowledge base."""
    from google.cloud import dialogflow_v2beta1 as dialogflow

    client = dialogflow.KnowledgeBasesClient()
    project_path = client.common_project_path(project_id)

    knowledge_base = dialogflow.KnowledgeBase(display_name=display_name)

    response = client.create_knowledge_base(
        parent=project_path, knowledge_base=knowledge_base
    )

    print("Knowledge Base created:\n")
    print("Display Name: {}\n".format(response.display_name))
    print("Name: {}\n".format(response.name))

为知识库添加文档

您的新知识库目前没有文档,因此您应该向其中添加文档。如需了解所有受支持内容选项的说明,请参阅下文支持的内容部分。您可在此示例中使用Cloud Storage 常见问题解答文档。

下面的示例展示您如何使用 Dialogflow 控制台、REST API(包括命令行)或客户端库来创建知识文档。如需使用 API,请调用 Document 类型的 create 方法。

网页界面

使用 Dialogflow 控制台创建知识文档:

  1. 如果您并非按照上文所述步骤继续执行操作,请前往您的知识库设置:
    1. 转到 Dialogflow ES 控制台
    2. 选择一个代理
    3. 点击左侧边栏菜单上的知识 (Knowledge)
    4. 点击您的知识库名称
  2. 点击新建文档 (New Document) 或创建第一个文档 (Create the first one)
  3. 输入文档名称
  4. 对于 Mime 类型 (Mime Type),选择 text/html
  5. 对于知识库类型 (Knowledge Type),选择常见问题解答 (FAQ)
  6. 对于数据源 (Data Source),选择网址 (URL)
  7. 网址 (URL) 字段中输入 https://cloud.google.com/storage/docs/faq
  8. 点击创建 (CREATE)

REST

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的 GCP 项目 ID
  • KNOWLEDGE_BASE_ID:上一项请求返回的您的知识库 ID
  • DOCUMENT_DISPLAY_NAME:所需的知识文档名称

HTTP 方法和网址:

POST https://dialogflow.googleapis.com/v2beta1/projects/PROJECT_ID/knowledgeBases/KNOWLEDGE_BASE_ID/documents

请求 JSON 正文:

{
  "displayName": "DOCUMENT_DISPLAY_NAME",
  "mimeType": "text/html",
  "knowledgeTypes": "FAQ",
  "contentUri": "https://cloud.google.com/storage/docs/faq"
}

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "name": "projects/PROJECT_ID/operations/ks-add_document-MzA5NTY2MTc5Mzg2Mzc5NDY4OA"
}

operations 后面的路径段是您的操作 ID。

Java

要向 Dialogflow 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.api.gax.longrunning.OperationFuture;
import com.google.api.gax.rpc.ApiException;
import com.google.cloud.dialogflow.v2.CreateDocumentRequest;
import com.google.cloud.dialogflow.v2.Document;
import com.google.cloud.dialogflow.v2.Document.KnowledgeType;
import com.google.cloud.dialogflow.v2.DocumentsClient;
import com.google.cloud.dialogflow.v2.KnowledgeOperationMetadata;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class DocumentManagement {

  public static void createDocument(
      String knowledgeBaseName,
      String displayName,
      String mimeType,
      String knowledgeType,
      String contentUri)
      throws IOException, ApiException, InterruptedException, ExecutionException, TimeoutException {
    // Instantiates a client
    try (DocumentsClient documentsClient = DocumentsClient.create()) {
      Document document =
          Document.newBuilder()
              .setDisplayName(displayName)
              .setContentUri(contentUri)
              .setMimeType(mimeType)
              .addKnowledgeTypes(KnowledgeType.valueOf(knowledgeType))
              .build();
      CreateDocumentRequest createDocumentRequest =
          CreateDocumentRequest.newBuilder()
              .setDocument(document)
              .setParent(knowledgeBaseName)
              .build();
      OperationFuture<Document, KnowledgeOperationMetadata> response =
          documentsClient.createDocumentAsync(createDocumentRequest);
      Document createdDocument = response.get(300, TimeUnit.SECONDS);
      System.out.format("Created Document:\n");
      System.out.format(" - Display Name: %s\n", createdDocument.getDisplayName());
      System.out.format(" - Document Name: %s\n", createdDocument.getName());
      System.out.format(" - MIME Type: %s\n", createdDocument.getMimeType());
      System.out.format(" - Knowledge Types:\n");
      for (KnowledgeType knowledgeTypeId : document.getKnowledgeTypesList()) {
        System.out.format("  - %s \n", knowledgeTypeId.getValueDescriptor());
      }
      System.out.format(" - Source: %s \n", document.getContentUri());
    }
  }
}

Node.js

要向 Dialogflow 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

//   // Instantiate a DialogFlow Documents client.
//   const client = new dialogflow.DocumentsClient({
//     projectId: projectId,
//   });

//   /**
//    * TODO(developer): Uncomment the following lines before running the sample.
//    */
//   // const projectId = 'ID of GCP project associated with your Dialogflow agent';
//   // const knowledgeBaseFullName = `the full path of your knowledge base, e.g my-Gcloud-project/myKnowledgeBase`;
//   // const documentPath = `path of the document you'd like to add, e.g. https://dialogflow.com/docs/knowledge-connectors`;
//   // const documentName = `displayed name of your document in knowledge base, e.g. myDoc`;
//   // const knowledgeTypes = `The Knowledge type of the Document. e.g. FAQ`;
//   // const mimeType = `The mime_type of the Document. e.g. text/csv, text/html,text/plain, text/pdf etc.`;

//   const request = {
//     parent: knowledgeBaseFullName,
//     document: {
//       knowledgeTypes: [knowledgeTypes],
//       displayName: documentName,
//       contentUri: documentPath,
//       source: 'contentUri',
//       mimeType: mimeType,
//     },
//   };

//   const [operation] = await client.createDocument(request);
//   const [response] = await operation.promise();

//   console.log('Document created');
//   console.log(`Content URI...${response.contentUri}`);
//   console.log(`displayName...${response.displayName}`);
//   console.log(`mimeType...${response.mimeType}`);
//   console.log(`name...${response.name}`);
//   console.log(`source...${response.source}`);

Python

要向 Dialogflow 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

def create_document(
    project_id, knowledge_base_id, display_name, mime_type, knowledge_type, content_uri
):
    """Creates a Document.

    Args:
        project_id: The GCP project linked with the agent.
        knowledge_base_id: Id of the Knowledge base.
        display_name: The display name of the Document.
        mime_type: The mime_type of the Document. e.g. text/csv, text/html,
            text/plain, text/pdf etc.
        knowledge_type: The Knowledge type of the Document. e.g. FAQ,
            EXTRACTIVE_QA.
        content_uri: Uri of the document, e.g. gs://path/mydoc.csv,
            http://mypage.com/faq.html."""
    from google.cloud import dialogflow_v2beta1 as dialogflow

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

    document = dialogflow.Document(
        display_name=display_name, mime_type=mime_type, content_uri=content_uri
    )

    document.knowledge_types.append(
        getattr(dialogflow.Document.KnowledgeType, knowledge_type)
    )

    response = client.create_document(parent=knowledge_base_path, document=document)
    print("Waiting for results...")
    document = response.result(timeout=120)
    print("Created Document:")
    print(" - Display Name: {}".format(document.display_name))
    print(" - Knowledge ID: {}".format(document.name))
    print(" - MIME Type: {}".format(document.mime_type))
    print(" - Knowledge Types:")
    for knowledge_type in document.knowledge_types:
        print("    - {}".format(KNOWLEDGE_TYPES[knowledge_type]))
    print(" - Source: {}\n".format(document.content_uri))

文档创建属于一项长时间运行的操作,可能需要大量时间才能完成。 您可以轮询此操作的状态以查看它是否已完成。 完成后,该操作将包含新创建的文档 ID。 保存此 ID 供日后处理。 如需了解详情,请参阅长时间运行的操作

管理知识文档

更新知识文档内容

如果您更新了由知识文档引用的内容,知识文档可能不会自动刷新。只有在您以公开网址形式提供内容并且为文档勾选了启用自动重新加载选项时,该内容才会自动刷新。

如需手动刷新 Cloud Storage 或公开网址文档内容,请对 Document 类型调用 reload 方法。

如需手动刷新上传的原始内容,请在 Document 类型上使用 deletecreate 方法重新创建文档。

列出知识文档

您可以列出知识库中的所有知识文档。 如需使用 API,请调用 Document 类型的 list 方法。

删除知识文档

您可以删除知识库中的知识文档。 如需使用 API,请调用 Document 类型的 delete 方法。 如果您没有文档 ID,则可以按照上述说明列出文档。

支持的内容

支持以下知识文档类型:

  • 常见问题解答:文档内容包含问题和答案对,可以采用 HTML 或 CSV 格式。系统可以对典型的常见问题解答 HTML 格式进行准确解析,但可能无法解析某些不常见的格式。CSV 的第一列必须是问题,第二列必须是答案,并且没有标题行。由于这种格式十分明确,因此总能得到准确解析。
  • 抽样质量检查:提取非结构化文本并用于问题解答的文档。

下表按知识类型和来源展示了支持的 MIME 类型

知识类型\来源 上传的文件 (Document.content)(不推荐使用) 上传的文件 (Document.raw_content)(推荐使用) 来自 Cloud Storage 的文件 (Document.contentUri) 来自公开网址的文件 (Document.contentUri)
常见问题解答 文本/csv 文本/csv 文本/csv text/html
抽样质量检查 文本/纯文本、文本/html 文本/纯文本、文本/html、应用/pdf 文本/纯文本、文本/html、应用/pdf 不适用

对于文档内容,存在以下已知问题、限制和最佳做法:

普遍:

  • 来自公共网址的文件必须已被 Google 搜索索引器抓取,因此存在于搜索索引中。您可以使用 Google Search Console 检查是否满足此项要求。请注意,索引器不会及时更新您的内容。 当源内容发生变化时,您必须明确更新您的知识文档。
  • CSV 文件必须使用逗号作为分隔符。
  • 常见问题解答和知识库文章的置信度分数尚未采用统一标准,因此如果同时使用常见问题解答和知识库文章,最佳结果并不一定是得分最高的答案。
  • Dialogflow 在创建响应时从内容中删除 HTML 标记。 因此,最好避免使用 HTML 标记并尽可能使用纯文本。
  • Google 助理响应的每个聊天气泡内容长度限制为 640 个字符,因此在集成 Google 助理时,系统会截短超过此限制的答案。
  • 最大文档大小为 50 MB。
  • 使用 Cloud Storage 文件时,您应该使用用户账号或服务账号可以访问的公开 URI 或私有 URI。

常见问题解答特定注意事项:

  • CSV 的第一列必须是问题,第二列必须是答案,并且没有标题行。
  • 尽可能使用 CSV,因为 CSV 解析最准确。
  • 不支持具有单个 QA 对的公开 HTML 内容。
  • 一个文档中的 QA 对数量不应超过 2000。
  • 不支持具有不同答案的重复问题。
  • 您可以使用任何常见问题解答文档,知识库的 FAQ 解析器可以处理大多数常见问题解答格式。

抽样质量检查特定注意事项:

  • 抽样质量检查目前处于实验阶段。 它基于在 Google 的搜索和智能助理等产品中试用并测试的类似技术。请向我们发送反馈,反映 Dialogflow 的工作表现。
  • 具有密集文字的内容效果最佳。 避免使用有许多单句段落的内容。
  • 不支持表格和列表。
  • 一个文档中的段落数不应超过 2000。
  • 如果文章很长(大于 1000 个字词),请尝试将其分为多篇小文章。 如果文章涵盖了多个问题,可以将其分为涵盖各个问题的简短文章。 如果文章只涵盖一个问题,请将文章的重点放在问题说明上,并尽量让问题的解决方法保持简短。
  • 理想情况下,应只提供文章的核心内容(问题说明和解决方法)。 作者姓名、修改历史记录、相关链接和广告等其他内容并不重要。
  • 请尝试描述文章可以帮助解决的问题和/或添加此文章可以回答的示例提问。

使用 Cloud Storage

如果您的内容不是公开的,建议您将内容存储在 Cloud Storage 中。创建知识文档时,请为 Cloud Storage 对象提供网址。

创建 Cloud Storage 存储分区和对象

创建 Cloud Storage 存储桶时,请注意以下几点:

  • 务必选择用于 Dialogflow 的 GCP 项目。
  • 确保通常用于访问 Dialogflow API 的用户账号或服务账号具有存储桶对象的读取权限
  • 使用 Standard 存储类别
  • 存储桶位置设置为离您最近的位置。 您需要为某些 API 调用提供位置 ID(例如 us-west1),因此请记下您的选择。

按照 Cloud Storage 快速入门中的说明创建存储桶并上传文件。

为知识库文档提供 Cloud Storage 对象

要提供您的内容,请执行以下操作:

  • 按照上文所述创建知识库。
  • 按照上文所述创建知识文档。 调用 Document 类型的 create 方法时,请将 contentUri 字段设置为 Cloud Storage 文档的网址。 此网址的格式为 gs://bucket-name/object-name