推薦文章

Agent Assist 文章建議功能會追蹤真人服務專員與使用者之間的對話,並向真人服務專員提供相關文件建議。在對話過程中,人工服務專員可以查看這些建議,並決定要閱讀或與使用者分享哪些文件。在真人服務專員與使用者對話時,真人服務專員可以透過文章建議功能,瞭解並解決使用者的問題。

Agent Assist 提供基礎文章建議模型,可供您使用,為服務專員建議文章。您也可以選擇使用自行上傳的對話資料訓練自訂模型,藉此提升成效。如要訓練自訂建議模型,以便搭配文章建議功能使用,請與 Google 代表聯絡。

本文將逐步說明如何使用 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 設為 ARTICLE_SUGGESTION。這個範例使用含有退貨單資訊的 HTML 檔案,該檔案已上傳至公開共用的 Cloud Storage bucket。在自家系統中設定文章建議時,文件必須採用下列其中一種格式。如要進一步瞭解文件最佳做法,請參閱知識文件說明文件

知識文件格式:

  • 儲存在 Cloud Storage bucket 中的檔案。呼叫 API 時,您可以指定路徑。
  • 文件的文字內容,可透過 API 要求傳送。
  • 公開網址。

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": "ARTICLE_SUGGESTION",
  "contentUri": "gs://agent-assist-public-examples/public_article_suggestion_example_returns.html"
}

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

您應該會收到如下的 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 控制台執行這些動作。

建議您將初始信賴度門檻設為 0.44 (如果使用舊版基準模型,則為 0.1)。如有需要,您可以將門檻提高到超出建議範圍。提高門檻可提高準確度,但涵蓋範圍會縮小 (建議較少);降低門檻可提高涵蓋範圍 (建議較多),但準確度會降低。

系統預設會啟用行內建議。設定對話設定檔時,您可以選擇啟用 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 要求主體:

{
  "name": "projects/PROJECT_ID/conversationProfiles/CONVERSATION_PROFILE_ID",
  "displayName": "my-conversation-profile-display-name",
  "humanAgentAssistantConfig": {
    "notificationConfig": {},
    "humanAgentSuggestionConfig": {
      "featureConfigs": [
        {
          "enableInlineSuggestion": true,
          "SuggestionTriggerSettings": {
            "noSmallTalk": true,
            "onlyEndUser": true,
          },
          "suggestionFeature": {
            "type": "ARTICLE_SUGGESTION"
          },
          "queryConfig": {
            "knowledgeBaseQuerySource": {
              "knowledgeBases": [
                "projects/PROJECT_ID/knowledgeBases/KNOWLEDGE_BASE_ID"
              ]
            }
          }
        }
      ]
    }
  },
  "sttConfig": {},
  "languageCode": "en-US"
}

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

您應該會收到如下的 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

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

使用者對真人服務專員說「I want to return my order」(我想退貨)。這次 API 回應會包含建議文件和對應的信心分數。在本教學課程稍早,我們將一份知識文件新增至知識庫,而系統傳回了該文件。可信度分數介於 0 至 1 之間,分數越高,表示文件與對話內容的關聯性越高。系統也會傳回包含文件前 100 個字元的片段。 摘要可協助服務專員快速判斷文件是否有用。建議您將這項資訊提供給真人服務專員,他們可能會選擇與使用者分享建議的文件。

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": "I want to return my order.",
    "languageCode": "en-US"
  }
}

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

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

{
  "message": {
    "name": "projects/PROJECT_ID/conversations/CONVERSATION_ID/messages/MESSAGE_ID",
    "content": "I want to return my order.",
    "languageCode": "en-US",
    "participant": "PARTICIPANT_ID",
    "participantRole": "END_USER",
    "createTime": "2020-02-13T00:07:35.925Z"
  },
  "humanAgentSuggestionResults": [
    {
      "suggestArticlesResponse": {
        "articleAnswers": [
          {
            "title": "Return an order",
            "uri": "gs://agent-assist-public-examples/public_article_suggestion_example_returns.html",
            "snippets": [
              "\u003cb\u003eReturn\u003c/b\u003e an \u003cb\u003eorder\u003c/b\u003e. Follow the steps below for Made-up Store \u003cb\u003ereturns\u003c/b\u003e. At this time, \nwe don't offer exchanges. In most cases, you can drop off \u003cb\u003ereturns\u003c/b\u003e at any Made-up\n ..."
            ],
            "metadata": {
              "title": "Return an order",
              "snippet": "\n  \n\n\u003ch1\u003eReturn an order\u003c/h1\u003e \nFollow the steps below for Made-up Store returns. At this time, we do...",
              "document_display_name": "my-kdoc"
            },
            "answerRecord": "projects/PROJECT_ID/answerRecords/ANSWER_RECORD_ID"
          }
        ],
        "latestMessage": "projects/PROJECT_ID/conversations/CONVERSATION_ID/messages/MESSAGE_ID",
        "contextSize": 2
      }
    }
  ]
}

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,在對話進行期間和有新建議時,將建議通知傳送至應用程式。