FAQ Assist

在與使用者對話時,常見問題小幫手會向真人服務專員建議相關的常見問題答案。這項功能可在真人服務專員與使用者對話時,協助真人服務專員回答常見的使用者問題。

Agent Assist 會追蹤對話內容,並剖析儲存在知識庫中的常見問題文件,為使用者問題提供建議答案。對話進行期間,真人服務專員可以查看這些建議,並決定要與使用者分享哪些建議。

本文將逐步說明如何使用 API 實作常見問題解答小幫手,並在執行階段取得這項功能的建議。您可以選擇在設計階段使用 Agent Assist 主控台測試文章建議結果,但必須在執行階段直接呼叫 API。如要瞭解如何使用 Agent Assist 控制台測試功能成效,請參閱教學課程專區

事前準備

開始閱讀本指南前,請先完成下列步驟:

  1. 為Google Cloud 專案啟用 Dialogflow API

設定對話設定檔

如要取得 Agent Assist 的建議,您必須建立知識庫,其中包含您上傳的文件,並設定對話設定檔。如果您不想直接呼叫 API,也可以使用 Agent Assist 控制台執行這些動作。

建立知識庫

上傳文件前,請先建立知識庫來存放文件。如要建立知識庫,請呼叫 KnowledgeBase 類型的 create 方法。

REST

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

  • PROJECT_ID:您的 GCP 專案 ID
  • KNOWLEDGE_BASE_DISPLAY_NAME:所需的知識庫名稱

HTTP 方法和網址:

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

JSON 要求主體:

{
  "displayName": "KNOWLEDGE_BASE_DISPLAY_NAME"
}

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

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

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

knowledgeBases 後方的路徑區段包含了您的新知識庫 ID。

Python

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

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))

建立知識文件

你現在可以將文件新增至知識庫。如要在知識庫中建立文件,請Document 類型上呼叫 create 方法。將 KnowledgeType 設為 FAQ。這個範例使用上傳至公開共用 Cloud Storage bucket 的 Cloud Storage 常見問題文件。在自家系統中設定文章建議時,文件必須採用下列其中一種格式。如要進一步瞭解文件最佳做法,請參閱知識文件說明文件

常見問題文件可採用下列其中一種格式:

  • 公開網址。
  • csv 檔案的 Cloud Storage 路徑。
  • csv 檔案 (您將在 API 要求中加入此檔案)。

如果文件採用 csv 格式,則必須包含兩欄:第一欄列出常見問題,第二欄列出每個問題的答案。每個常見問題和相關聯的答案都稱為「常見問題組合」。請確認 csv 檔案不含標頭列。如果文件是公開網址,則必須是列出多個常見問題組的常見問題頁面。

如需最佳做法資訊,請參閱知識文件說明文件

REST

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

  • PROJECT_ID:您的 GCP 專案 ID
  • KNOWLEDGE_BASE_ID:從之前要求傳回的知識庫 ID
  • DOCUMENT_DISPLAY_NAME:所需的知識文件名稱

HTTP 方法和網址:

POST https://dialogflow.googleapis.com/v2/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"
}

回應是長時間執行的作業,您可以輪詢檢查作業是否完成。

Python

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

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))

建立對話設定檔

對話設定檔會設定一組參數,控制對話期間向代理程式提供的建議。下列步驟會建立具有 HumanAgentAssistantConfig 物件的 ConversationProfile。如果您不想直接呼叫 API,也可以使用 Agent Assist 控制台執行這些動作。

系統預設會啟用行內建議。設定對話設定檔時,您可以選擇啟用 Cloud Pub/Sub 通知

REST

如要建立對話設定檔,請在 ConversationProfile 資源上呼叫 create 方法。

noSmallTalk:如果 true,系統就不會在閒聊訊息 (例如「你好」、「你好嗎」等) 後觸發建議。如果 false,系統會在 Small Talk 訊息後觸發建議。

onlyEndUser:如果設為 true,系統只會在使用者傳送訊息後觸發建議。如果設為 false,系統會在使用者和真人服務專員傳送訊息後,觸發建議。

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

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

HTTP 方法和網址:

POST https://dialogflow.googleapis.com/v2/projects/PROJECT_ID/conversationProfiles

JSON 要求主體:

{
  "displayName": "my-conversation-profile-display-name",
  "humanAgentAssistantConfig": {
    "humanAgentSuggestionConfig": {
      "featureConfigs": [
        {
          "suggestionFeature": {
            "type": "FAQ"
          },
          "queryConfig": {
            "knowledgeBaseQuerySource": {
              "knowledgeBases": ["projects/PROJECT_ID/knowledgeBases/KNOWLEDGE_BASE_ID"]
            }
          },
          "enableEventBasedSuggestion": false,
          "enableInlineSuggestion": true,
          "SuggestionTriggerSettings": {
             "noSmallTalk": true,
             "onlyEndUser": true,
           }
        }
      ]
    }
  }
}

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

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

{
  "name": "projects/PROJECT_ID/conversationProfiles/CONVERSATION_PROFILE_ID",
  "displayName": "my-conversation-profile-display-name",
  "humanAgentAssistantConfig": {
    ...
  }
}

conversationProfiles 後方的路徑區段包含了新的對話設定檔 ID。

Python

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

def create_conversation_profile_article_faq(
    project_id,
    display_name,
    article_suggestion_knowledge_base_id=None,
    faq_knowledge_base_id=None,
):
    """Creates a conversation profile with given values

    Args: project_id:  The GCP project linked with the conversation profile.
        display_name: The display name for the conversation profile to be
        created.
        article_suggestion_knowledge_base_id: knowledge base id for article
        suggestion.
        faq_knowledge_base_id: knowledge base id for faq."""

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

    conversation_profile = {
        "display_name": display_name,
        "human_agent_assistant_config": {
            "human_agent_suggestion_config": {"feature_configs": []}
        },
        "language_code": "en-US",
    }

    if article_suggestion_knowledge_base_id is not None:
        as_kb_path = dialogflow.KnowledgeBasesClient.knowledge_base_path(
            project_id, article_suggestion_knowledge_base_id
        )
        feature_config = {
            "suggestion_feature": {"type_": "ARTICLE_SUGGESTION"},
            "suggestion_trigger_settings": {
                "no_small_talk": True,
                "only_end_user": True,
            },
            "query_config": {
                "knowledge_base_query_source": {"knowledge_bases": [as_kb_path]},
                "max_results": 3,
            },
        }
        conversation_profile["human_agent_assistant_config"][
            "human_agent_suggestion_config"
        ]["feature_configs"].append(feature_config)
    if faq_knowledge_base_id is not None:
        faq_kb_path = dialogflow.KnowledgeBasesClient.knowledge_base_path(
            project_id, faq_knowledge_base_id
        )
        feature_config = {
            "suggestion_feature": {"type_": "FAQ"},
            "suggestion_trigger_settings": {
                "no_small_talk": True,
                "only_end_user": True,
            },
            "query_config": {
                "knowledge_base_query_source": {"knowledge_bases": [faq_kb_path]},
                "max_results": 3,
            },
        }
        conversation_profile["human_agent_assistant_config"][
            "human_agent_suggestion_config"
        ]["feature_configs"].append(feature_config)

    response = client.create_conversation_profile(
        parent=project_path, conversation_profile=conversation_profile
    )

    print("Conversation Profile created:")
    print("Display Name: {}".format(response.display_name))
    # Put Name is the last to make it easier to retrieve.
    print("Name: {}".format(response.name))
    return response

(選用) 設定安全性設定

您可以設定安全性參數,協助解決資料遮蓋和資料保留等問題。如要執行這項操作,您必須建立 SecuritySettings 資源,然後使用 securitySettings 欄位將該資源連結至對話設定檔

新增至對話設定檔的安全設定只會影響 Agent Assist 簡訊的行為。Dialogflow 互動記錄的行為是由 Dialogflow 的安全性設定控管,您可以使用 Dialogflow CX 主控台設定這些安全性設定。

在執行階段處理對話

建立對話

當使用者與真人或虛擬服務專員開始對話時,您會建立對話如要查看建議,您也必須建立使用者參與者和服務專員參與者,並將他們加入對話。以下各節將逐步說明這個程序。

首先,您必須建立對話:

REST

如要建立對話,請呼叫 Conversation 資源上的 create 方法。

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

  • PROJECT_ID:您的 Cloud 專案 ID
  • LOCATION_ID:您的位置 ID
  • CONVERSATION_PROFILE_ID:建立對話設定檔時收到的 ID

HTTP 方法和網址:

POST https://dialogflow.googleapis.com/v2/projects/PROJECT_ID/locations/LOCATION_ID/conversations

JSON 要求主體:

{
  "conversationProfile": "projects/PROJECT_ID/locations/LOCATION_ID/conversationProfiles/CONVERSATION_PROFILE_ID",
}

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

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

{
  "name": "projects/PROJECT_ID/locations/LOCATION_ID/conversations/CONVERSATION_ID",
  "lifecycleState": "IN_PROGRESS",
  "conversationProfile": "projects/PROJECT_ID/locations/LOCATION_ID/conversationProfiles/CONVERSATION_PROFILE_ID",
  "startTime": "2018-11-05T21:05:45.622Z"
}

conversations 後方的路徑區段包含新的對話 ID。

Python

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

def create_conversation(project_id, conversation_profile_id):
    """Creates a conversation with given values

    Args:
        project_id:  The GCP project linked with the conversation.
        conversation_profile_id: The conversation profile id used to create
        conversation."""

    client = dialogflow.ConversationsClient()
    conversation_profile_client = dialogflow.ConversationProfilesClient()
    project_path = client.common_project_path(project_id)
    conversation_profile_path = conversation_profile_client.conversation_profile_path(
        project_id, conversation_profile_id
    )
    conversation = {"conversation_profile": conversation_profile_path}
    response = client.create_conversation(
        parent=project_path, conversation=conversation
    )

    print("Life Cycle State: {}".format(response.lifecycle_state))
    print("Conversation Profile Name: {}".format(response.conversation_profile))
    print("Name: {}".format(response.name))
    return response

建立使用者參與者

您必須在對話中加入使用者和真人服務專員,才能查看建議。首先,請將使用者參與者新增至對話:

REST

如要建立使用者參與者,請在 Participant 資源上呼叫 create 方法。

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

  • PROJECT_ID:您的 Cloud 專案 ID
  • LOCATION_ID:您的位置 ID
  • CONVERSATION_ID:您的對話 ID

HTTP 方法和網址:

POST https://dialogflow.googleapis.com/v2/projects/PROJECT_ID/locations/LOCATION_ID/conversations/CONVERSATION_ID/participants

JSON 要求主體:

{
  "role": "END_USER",
}

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

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

{
  "name": "projects/PROJECT_ID/locations/LOCATION_ID/conversations/CONVERSATION_ID/participants/PARTICIPANT_ID",
  "role": "END_USER"
}

participants 後方的路徑區段包含新的使用者參與者 ID。

Python

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

def create_participant(project_id: str, conversation_id: str, role: str):
    from google.cloud import dialogflow_v2beta1 as dialogflow

    """Creates a participant in a given conversation.

    Args:
        project_id: The GCP project linked with the conversation profile.
        conversation_id: Id of the conversation.
        participant: participant to be created."""

    client = dialogflow.ParticipantsClient()
    conversation_path = dialogflow.ConversationsClient.conversation_path(
        project_id, conversation_id
    )
    if role in ROLES:
        response = client.create_participant(
            parent=conversation_path, participant={"role": role}, timeout=600
        )
        print("Participant Created.")
        print(f"Role: {response.role}")
        print(f"Name: {response.name}")

        return response

建立真人服務專員參與者

在對話中新增真人服務專員參與者:

REST

如要建立真人客服參與者,請呼叫 Participant 資源上的 create 方法。

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

  • PROJECT_ID:您的 Cloud 專案 ID
  • LOCATION_ID:您的位置 ID
  • CONVERSATION_ID:您的對話 ID

HTTP 方法和網址:

POST https://dialogflow.googleapis.com/v2/projects/PROJECT_ID/locations/LOCATION_ID/conversations/CONVERSATION_ID/participants

JSON 要求主體:

{
  "role": "HUMAN_AGENT",
}

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

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

{
  "name": "projects/PROJECT_ID/locations/LOCATION_ID/conversations/CONVERSATION_ID/participants/PARTICIPANT_ID",
  "role": "HUMAN_AGENT"
}

participants 後方的路徑區段包含新的人工服務專員參與者 ID。

Python

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

def create_participant(project_id: str, conversation_id: str, role: str):
    from google.cloud import dialogflow_v2beta1 as dialogflow

    """Creates a participant in a given conversation.

    Args:
        project_id: The GCP project linked with the conversation profile.
        conversation_id: Id of the conversation.
        participant: participant to be created."""

    client = dialogflow.ParticipantsClient()
    conversation_path = dialogflow.ConversationsClient.conversation_path(
        project_id, conversation_id
    )
    if role in ROLES:
        response = client.create_participant(
            parent=conversation_path, participant={"role": role}, timeout=600
        )
        print("Participant Created.")
        print(f"Role: {response.role}")
        print(f"Name: {response.name}")

        return response

新增及分析真人服務專員的訊息

每次對話參與者在對話中輸入訊息時,您都需要將該訊息傳送至 API 進行處理。Agent Assist 會根據真人服務專員和使用者訊息的分析結果提供建議。在下列範例中,真人服務專員會先詢問「需要什麼協助嗎?」。目前回覆中沒有任何建議。

REST

如要為對話新增及分析真人客服訊息,請在 Participant 資源上呼叫 analyzeContent 方法。

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

  • PROJECT_ID:您的 GCP 專案 ID
  • CONVERSATION_ID:您的對話 ID
  • PARTICIPANT_ID:真人服務專員參與者 ID

HTTP 方法和網址:

POST https://dialogflow.googleapis.com/v2/projects/PROJECT_ID/conversations/CONVERSATION_ID/participants/PARTICIPANT_ID:analyzeContent

JSON 要求主體:

{
  "textInput": {
    "text": "How may I help you?",
    "languageCode": "en-US"
  }
}

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

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

      {
        "message": {
          "name": "projects/PROJECT_ID/conversations/CONVERSATION_ID/messages/MESSAGE_ID",
          "content": "How may I help you?",
          "languageCode": "en-US",
          "participant": "PARTICIPANT_ID",
          "participantRole": "HUMAN_AGENT",
          "createTime": "2020-02-13T00:01:30.683Z"
        },
        "humanAgentSuggestionResults": [
          {
            "suggestArticlesResponse": {
              "latestMessage": "projects/PROJECT_ID/conversations/CONVERSATION_ID/messages/MESSAGE_ID",
              "contextSize": 1
            }
          }
        ]
      }
    }
  ]
}

Python

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

def analyze_content_text(
    project_id: str, conversation_id: str, participant_id: str, text: str
):
    from google.cloud import dialogflow_v2beta1 as dialogflow

    """Analyze text message content from a participant.

    Args:
        project_id: The GCP project linked with the conversation profile.
        conversation_id: Id of the conversation.
        participant_id: Id of the participant.
        text: the text message that participant typed."""

    client = dialogflow.ParticipantsClient()
    participant_path = client.participant_path(
        project_id, conversation_id, participant_id
    )
    text_input = {"text": text, "language_code": "en-US"}
    response = client.analyze_content(
        participant=participant_path, text_input=text_input
    )
    print("AnalyzeContent Response:")
    print(f"Reply Text: {response.reply_text}")

    for suggestion_result in response.human_agent_suggestion_results:
        if suggestion_result.error is not None:
            print(f"Error: {suggestion_result.error.message}")
        if suggestion_result.suggest_articles_response:
            for answer in suggestion_result.suggest_articles_response.article_answers:
                print(f"Article Suggestion Answer: {answer.title}")
                print(f"Answer Record: {answer.answer_record}")
        if suggestion_result.suggest_faq_answers_response:
            for answer in suggestion_result.suggest_faq_answers_response.faq_answers:
                print(f"Faq Answer: {answer.answer}")
                print(f"Answer Record: {answer.answer_record}")
        if suggestion_result.suggest_smart_replies_response:
            for (
                answer
            ) in suggestion_result.suggest_smart_replies_response.smart_reply_answers:
                print(f"Smart Reply: {answer.reply}")
                print(f"Answer Record: {answer.answer_record}")

    for suggestion_result in response.end_user_suggestion_results:
        if suggestion_result.error:
            print(f"Error: {suggestion_result.error.message}")
        if suggestion_result.suggest_articles_response:
            for answer in suggestion_result.suggest_articles_response.article_answers:
                print(f"Article Suggestion Answer: {answer.title}")
                print(f"Answer Record: {answer.answer_record}")
        if suggestion_result.suggest_faq_answers_response:
            for answer in suggestion_result.suggest_faq_answers_response.faq_answers:
                print(f"Faq Answer: {answer.answer}")
                print(f"Answer Record: {answer.answer_record}")
        if suggestion_result.suggest_smart_replies_response:
            for (
                answer
            ) in suggestion_result.suggest_smart_replies_response.smart_reply_answers:
                print(f"Smart Reply: {answer.reply}")
                print(f"Answer Record: {answer.answer_record}")

    return response

新增使用者訊息並取得建議

使用者向代理程式詢問「How do I sign up?」(如何註冊?)。回應會列出使用者問題的建議答案,以及每個答案的信賴分數。所有答案都來自我們在本教學課程稍早新增的單一常見問題知識文件。信心門檻是指模型對每項常見問題建議與服務專員要求相關的信心程度。可信度值越高,系統就越有可能傳回相關回覆,但如果沒有任何可用選項符合高門檻值,系統可能會傳回較少或沒有任何回覆。建議起始信心分數值為 0.4。日後如有需要,可以調整這個值來提升成效。

回覆中也會納入答案的 source,以及答案的來源知識文件。請將建議答案提供給真人服務專員,他們可能會選擇將這項資訊提供給使用者。

REST

如要為對話新增及分析使用者訊息,請在 Participant 資源上呼叫 analyzeContent 方法。

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

  • PROJECT_ID:您的 GCP 專案 ID
  • CONVERSATION_ID:您的對話 ID
  • PARTICIPANT_ID:您的參與者 ID

HTTP 方法和網址:

POST https://dialogflow.googleapis.com/v2/projects/PROJECT_ID/conversations/CONVERSATION_ID/participants/PARTICIPANT_ID:analyzeContent

JSON 要求主體:

{
  "textInput": {
    "text": "How do I sign up?",
    "languageCode": "en-US"
  }
}

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

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

{
  "message": {
    "name": "projects/PROJECT_ID/conversations/fiiJBeHnQIa6Zx_DUKNlEg/messages/Rjv8ErKYS_yIqVR9SW4CpA",
    "content": "How may I help you?",
    "languageCode": "en-US",
    "participant": "PaZQyeiTQgCOyliHkZjs0Q",
    "participantRole": "HUMAN_AGENT",
    "createTime": "1970-01-01T00:00:00Z"
  },
  "humanAgentSuggestionResults": [
    {
      "suggestFaqAnswersResponse": {
        "faqAnswers": [
          {
            "answer": "Sign up for Cloud Storage by turning on the Cloud Storage service in the Google Cloud Platform Console.",
            "confidence": 0.07266401,
            "question": "How do I sign up?",
            "source": "projects/PROJECT_ID/knowledgeBases/NjQ2MzI1MDQwNTQ2MjYzODU5Mg/documents/NTMxOTA4MTAxMzQxMjg4ODU3Ng",
            "metadata": {
              "document_display_name": "my-document-display-name"
            },
            "answerRecord": "projects/PROJECT_ID/answerRecords/MTU0MzE0NDQwOTAwNzEyODU3NjA"
          },
          {
            "answer": "Consider storing your data in a multi-regional or dual-regional bucket location if high availability is a top requirement. This ensures that your data is stored in at least two geographically separated regions, providing continued availability even in the rare event of a region-wide outage, including ones caused by natural disasters. All data, regardless of storage class, is stored redundantly across regions in these types of locations, which allows you to use storage lifecycle management without giving up high availability.",
            "confidence": 0.06937904,
            "question": "How can I maximize the availability of my data?",
            "source": "projects/PROJECT_ID/knowledgeBases/NjQ2MzI1MDQwNTQ2MjYzODU5Mg/documents/NTMxOTA4MTAxMzQxMjg4ODU3Ng",
            "metadata": {
              "document_display_name": "my-document-display-name"
            },
            "answerRecord": "projects/PROJECT_ID/answerRecords/MzkwMjIyOTA0NDAwMjgxNjAwMA"
          },
          {
            "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.",
            "confidence": 0.069021806,
            "question": "How do I give product feedback?",
            "source": "projects/PROJECT_ID/knowledgeBases/NjQ2MzI1MDQwNTQ2MjYzODU5Mg/documents/NTMxOTA4MTAxMzQxMjg4ODU3Ng",
            "metadata": {
              "document_display_name": "my-document-display-name"
            },
            "answerRecord": "projects/PROJECT_ID/answerRecords/MTMxMjU2MDEwODA4NTc1OTE4MDg"
          },
          {
            "answer": "Read the Pricing page for detailed information on pricing, including how Cloud Storage calculates bandwidth and storage usage.",
            "confidence": 0.06681696,
            "question": "Where can I find pricing information?",
            "source": "projects/PROJECT_ID/knowledgeBases/NjQ2MzI1MDQwNTQ2MjYzODU5Mg/documents/NTMxOTA4MTAxMzQxMjg4ODU3Ng",
            "metadata": {
              "document_display_name": "my-document-display-name"
            },
            "answerRecord": "projects/PROJECT_ID/answerRecords/ODUxMzkxNTA2MjQzMDIwMzkwNA"
          },
          {
            "answer": "Use Object Versioning. The Object Versioning feature keeps an archived version of an object whenever you overwrite or delete the live version. If you accidentally delete an object, you can copy an archived version of it back to the live version. It's recommended that you use Object Versioning in conjunction with Object Lifecycle Management. Doing so ensures that you don't have multiple, unnecessary copies of an object, which are each subject to storage costs. Caution: Object Versioning does not protect your data if you delete the entire bucket. As an alternative, use object holds. When you place an object hold on an object, it cannot be deleted or overwritten.",
            "confidence": 0.06453417,
            "question": "How do I protect myself from accidental data deletion?",
            "source": "projects/PROJECT_ID/knowledgeBases/NjQ2MzI1MDQwNTQ2MjYzODU5Mg/documents/NTMxOTA4MTAxMzQxMjg4ODU3Ng",
            "metadata": {
              "document_display_name": "my-document-display-name"
            },
            "answerRecord": "projects/PROJECT_ID/answerRecords/MTc3MzcyODcwOTkyODQ5Nzk3MTI"
          },
          {
            "answer": "You can share an individual object with a user or group by adding an entry to that object's access control list (ACL) that grants the user or group READ permission. For step-by-step instructions, see Changing ACLs.",
            "confidence": 0.06336816,
            "question": "I want to let someone download an individual object. How do I do that?",
            "source": "projects/PROJECT_ID/knowledgeBases/NjQ2MzI1MDQwNTQ2MjYzODU5Mg/documents/NTMxOTA4MTAxMzQxMjg4ODU3Ng",
            "metadata": {
              "document_display_name": "my-document-display-name"
            },
            "answerRecord": "projects/PROJECT_ID/answerRecords/MTAxOTkyNTI4MjQ4NTY5ODU2MA"
          },
          {
            "answer": "You can simply install and use the Google Cloud CLI to download the data, even without a Google account. You do not need to activate Cloud Storage or turn on billing for this purpose. You also do not need to create credentials or authenticate to Cloud Storage.",
            "confidence": 0.061990723,
            "question": "I am just trying to download or access some data that is available to the public. How can I do that?",
            "source": "projects/PROJECT_ID/knowledgeBases/NjQ2MzI1MDQwNTQ2MjYzODU5Mg/documents/NTMxOTA4MTAxMzQxMjg4ODU3Ng",
            "metadata": {
              "document_display_name": "my-document-display-name"
            },
            "answerRecord": "projects/PROJECT_ID/answerRecords/MTAyNDMyOTczMTkzNDA0NzQzNjg"
          },
          {
            "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 & Cloud Bigtable).",
            "confidence": 0.060459033,
            "question": "I believe some content hosted on your service is inappropriate, how do I report it?",
            "source": "projects/PROJECT_ID/knowledgeBases/NjQ2MzI1MDQwNTQ2MjYzODU5Mg/documents/NTMxOTA4MTAxMzQxMjg4ODU3Ng",
            "metadata": {
              "document_display_name": "my-document-display-name"
            },
            "answerRecord": "projects/PROJECT_ID/answerRecords/NTYzMTYxMTMwMDkxMzA4NjQ2NA"
          },
          {
            "answer": "For most common Cloud Storage operations, you only need to specify the relevant bucket's name, not the project associated with the bucket. In general, you only need to specify a project identifier when creating a bucket or listing buckets in a project. For more information, see When to specify a project. To find which project contains a specific bucket: If you are searching over a moderate number of projects and buckets, use the Google Cloud Platform Console, select each project, and view the buckets it contains. Otherwise, go to the storage.bucket.get page in the API Explorer and enter the bucket's name in the bucket field. When you click Authorize and Execute, the associated project number appears as part of the response. To get the project name, use the project number in the following terminal command: gcloud projects list | grep [PROJECT_NUMBER]",
            "confidence": 0.05914715,
            "question": "I created a bucket, but don't remember which project I created it in. How can I find it?",
            "source": "projects/PROJECT_ID/knowledgeBases/NjQ2MzI1MDQwNTQ2MjYzODU5Mg/documents/NTMxOTA4MTAxMzQxMjg4ODU3Ng",
            "metadata": {
              "document_display_name": "my-document-display-name"
            },
            "answerRecord": "projects/PROJECT_ID/answerRecords/MTQ4NTQ5ODMzMzc3Njc4NjIyNzI"
          },
          {
            "answer": "Cloud Storage is designed for 99.999999999% (11 9's) annual durability, which is appropriate for even primary storage and business-critical applications. This high durability level is achieved through erasure coding that stores data pieces redundantly across multiple devices located in multiple availability zones. Objects written to Cloud Storage must be redundantly stored in at least two different availability zones before the write is acknowledged as successful. Checksums are stored and regularly revalidated to proactively verify that the data integrity of all data at rest as well as to detect corruption of data in transit. If required, corrections are automatically made using redundant data. Customers can optionally enable object versioning to add protection against accidental deletion.",
            "confidence": 0.05035359,
            "question": "How durable is my data in Cloud Storage?",
            "source": "projects/PROJECT_ID/knowledgeBases/NjQ2MzI1MDQwNTQ2MjYzODU5Mg/documents/NTMxOTA4MTAxMzQxMjg4ODU3Ng",
            "metadata": {
              "document_display_name": "my-document-display-name"
            },
            "answerRecord": "projects/PROJECT_ID/answerRecords/MzMyNTc2ODI5MTY5OTM5MjUxMg"
          }
        ],
        "latestMessage": "projects/PROJECT_ID/conversations/fiiJBeHnQIa6Zx_DUKNlEg/messages/Rjv8ErKYS_yIqVR9SW4CpA",
        "contextSize": 1
      }
    }
  ]
}

Python

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

def analyze_content_text(
    project_id: str, conversation_id: str, participant_id: str, text: str
):
    from google.cloud import dialogflow_v2beta1 as dialogflow

    """Analyze text message content from a participant.

    Args:
        project_id: The GCP project linked with the conversation profile.
        conversation_id: Id of the conversation.
        participant_id: Id of the participant.
        text: the text message that participant typed."""

    client = dialogflow.ParticipantsClient()
    participant_path = client.participant_path(
        project_id, conversation_id, participant_id
    )
    text_input = {"text": text, "language_code": "en-US"}
    response = client.analyze_content(
        participant=participant_path, text_input=text_input
    )
    print("AnalyzeContent Response:")
    print(f"Reply Text: {response.reply_text}")

    for suggestion_result in response.human_agent_suggestion_results:
        if suggestion_result.error is not None:
            print(f"Error: {suggestion_result.error.message}")
        if suggestion_result.suggest_articles_response:
            for answer in suggestion_result.suggest_articles_response.article_answers:
                print(f"Article Suggestion Answer: {answer.title}")
                print(f"Answer Record: {answer.answer_record}")
        if suggestion_result.suggest_faq_answers_response:
            for answer in suggestion_result.suggest_faq_answers_response.faq_answers:
                print(f"Faq Answer: {answer.answer}")
                print(f"Answer Record: {answer.answer_record}")
        if suggestion_result.suggest_smart_replies_response:
            for (
                answer
            ) in suggestion_result.suggest_smart_replies_response.smart_reply_answers:
                print(f"Smart Reply: {answer.reply}")
                print(f"Answer Record: {answer.answer_record}")

    for suggestion_result in response.end_user_suggestion_results:
        if suggestion_result.error:
            print(f"Error: {suggestion_result.error.message}")
        if suggestion_result.suggest_articles_response:
            for answer in suggestion_result.suggest_articles_response.article_answers:
                print(f"Article Suggestion Answer: {answer.title}")
                print(f"Answer Record: {answer.answer_record}")
        if suggestion_result.suggest_faq_answers_response:
            for answer in suggestion_result.suggest_faq_answers_response.faq_answers:
                print(f"Faq Answer: {answer.answer}")
                print(f"Answer Record: {answer.answer_record}")
        if suggestion_result.suggest_smart_replies_response:
            for (
                answer
            ) in suggestion_result.suggest_smart_replies_response.smart_reply_answers:
                print(f"Smart Reply: {answer.reply}")
                print(f"Answer Record: {answer.answer_record}")

    return response

完成對話

對話結束後,請使用 API 完成對話。

REST

如要完成對話,請呼叫 conversations 資源上的 complete 方法。

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

  • PROJECT_ID:您的 GCP 專案 ID
  • CONVERSATION_ID:建立對話時收到的 ID

HTTP 方法和網址:

POST https://dialogflow.googleapis.com/v2/projects/PROJECT_ID/conversations/CONVERSATION_ID:complete

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

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

{
  "name": "projects/PROJECT_ID/conversations/CONVERSATION_ID",
  "lifecycleState": "COMPLETED",
  "conversationProfile": "projects/PROJECT_ID/conversationProfiles/CONVERSATION_PROFILE_ID",
  "startTime": "2018-11-05T21:05:45.622Z",
  "endTime": "2018-11-06T03:50:26.930Z"
}

Python

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

def complete_conversation(project_id, conversation_id):
    """Completes the specified conversation. Finished conversations are purged from the database after 30 days.

    Args:
        project_id: The GCP project linked with the conversation.
        conversation_id: Id of the conversation."""

    client = dialogflow.ConversationsClient()
    conversation_path = client.conversation_path(project_id, conversation_id)
    conversation = client.complete_conversation(name=conversation_path)
    print("Completed Conversation.")
    print("Life Cycle State: {}".format(conversation.lifecycle_state))
    print("Conversation Profile Name: {}".format(conversation.conversation_profile))
    print("Name: {}".format(conversation.name))
    return conversation

API 要求選項

前幾節說明如何建立 ConversationProfile,以便接收建議。以下各節將說明一些可在對話期間實作的選用功能。

Pub/Sub 建議通知

在先前的章節中,我們只使用真人服務專員助理建立 ConversationProfile。在對話期間,您需要呼叫 API,才能在每次將訊息新增至對話後收到建議。如要接收建議的通知事件,可以在建立對話設定檔時設定 notificationConfig 欄位。這個選項會使用 Cloud Pub/Sub,在對話進行期間和有新建議時,將建議通知傳送至應用程式。