管理知識庫

知識庫代表您提供給 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 Type」設為 [text/html]
  5. 將「Knowledge Type」設為 [FAQ]
  6. 將「Data Source」設為 [URL]
  7. 在「網址」欄位中輸入 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 文字/html
抽取式 QA 文字/純文字、文字/html 文字/純文字、文字/html、應用程式/pdf 文字/純文字、文字/html、應用程式/pdf N/A

文字內容存在下列已知問題、限制與最佳做法:

通用:

  • 來自公開網址的檔案必須已由 Google 搜尋索引器檢索,這樣這些檔案才會存在於搜尋索引中。您可以使用 Google Search Console 檢查此結果。請注意,索引器不會讓內容保持最新狀態。 來源內容變更時,您必須明確更新知識文件。
  • CSV 檔案必須使用逗號做為分隔符號。
  • 目前尚未校正常見問題與知識庫文章之間的信心分數,因此如果您同時使用常見問題與知識庫文章,最佳結果不一定是分數最高的項目。
  • 建立回應時,Dialogflow 會從內容中移除 HTML 標記。因此,最好避免使用 HTML 標記,並盡可能使用純文字。
  • Google 助理回應有每個即時通訊泡泡 640 個字元的限制,因此與 Google 助理整合時,較長的答案會遭到截斷。
  • 文件大小上限為 50 MB。
  • 使用 Cloud Storage 檔案時,應使用您的使用者帳戶或服務帳戶所能存取的公開 URI 或私人 URI。

常見問題特定注意事項:

  • 如要採 CSV 格式,請在第一欄加入問題,在第二欄加入答案,並請不要加入標頭。
  • 如有可能,請使用 CSV,因為 CSV 的剖析結果最精確。
  • 不支援含有單一 QA 組的公開 HTML 內容。
  • 一份文件中 QA 組的數目不應超過 2000 個。
  • 不支援含有不同答案的重複問題。
  • 您可以使用任何常見問題文件;常見問題剖析器可處理大部分的常見問題格式。

擷取式問答特定注意事項:

  • 擷取式問答目前處於實驗階段。知識庫文章所使用的技術已在 Google 的「搜尋」與「助理」等產品中進行過嘗試與測試。歡迎提供您的寶貴意見,告訴我們在 Dialogflow 裡的執行效果。
  • 內含密集文字的內容效果最佳。 避免使用內含許多單句段落的內容。
  • 不支援表格與清單。
  • 一份文件中的段落數不得超過 2000 個。
  • 如果一篇文章很長 (超過 1000 個字),請嘗試將其分解為多篇較小的文章。如果這篇文章涵蓋多個問題,可以將其分解為涵蓋個別問題的較短文章。如果這篇文章只涵蓋一個問題,請將文章的重點放在問題說明上,並儘量讓問題的解決方法保持簡短。
  • 在理想情況下,應僅提供文章的核心內容 (問題說明和解決方法)。其他內容 (例如作者姓名、修改記錄、相關連結和廣告) 並不重要。
  • 請嘗試包含文章可以協助解決的問題的說明,以及/或這篇文章可以回答的查詢範例。

使用 Cloud Storage

如果內容不公開,建議將內容儲存在 Cloud Storage。建立知識文件時,請提供 Cloud Storage 物件的網址。

建立 Cloud Storage 值區和物件

建立 Cloud Storage 值區時:

  • 請務必選取您用於 Dialogflow 的 GCP 專案。
  • 確認您通常用來存取 Dialogflow API 的使用者帳戶或服務帳戶,具有讀取儲存空間物件的權限
  • 使用 Standard Storage 級別
  • 將「bucket location」(儲存空間位置) 設為最靠近您所在位置的位置。部分 API 呼叫需要地點 ID (例如 us-west1),因此請記下您的選擇。

按照 Cloud Storage 快速入門操作說明建立值區並上傳檔案。

將 Cloud Storage 物件提供給知識庫文件

如要提供內容,請按照下列步驟操作:

  • 按照上述步驟建立知識庫。
  • 按照上述步驟建立知識文件。在 Document 類型上呼叫 create 方法時,請將 contentUri 欄位設為 Cloud Storage 文件的網址。網址格式為 gs://bucket-name/object-name