자료 추천

Agent Assist 자료 추천 기능은 상담사와 최종 사용자 간의 대화를 따라가며 상담사에게 관련 문서를 추천합니다. 상담사가 대화 중에 추천받은 문서를 검토하고 읽거나 최종 사용자와 공유할 문서를 결정할 수 있습니다. 자료 추천을 사용하여 상담사가 최종 사용자와 대화 중에 최종 사용자 문제를 이해하고 해결하도록 지원할 수 있습니다.

Agent Assist는 에이전트에 자료를 추천하는 데 사용할 수 있는 기준 자료 추천 모델을 제공합니다. 원하는 경우 업로드된 자체 대화 데이터를 사용하여 커스텀 모델을 학습시켜 성능을 개선할 수 있습니다. 자료 추천에 사용할 커스텀 추천 모델을 학습시키려면 Google 담당자에게 문의하세요.

이 문서에서는 API를 사용하여 자료 추천을 구현하고 런타임 중에 이 기능을 통해 추천 답변을 받는 과정을 안내합니다. 설계 시 Agent Assist 콘솔을 사용하여 자료 추천 결과를 테스트할 수도 있지만 런타임 중에 직접 API를 호출해야 합니다. Agent Assist 콘솔을 사용한 기능 성능 테스트에 대한 자세한 내용은 가이드 섹션을 참조하세요.

시작하기 전에

이 가이드를 시작하기 전에 다음을 수행해야 합니다.

  1. GCP 프로젝트에 Dialogflow API를 사용 설정합니다.
  2. 프로젝트에 Data Labeling API를 사용 설정합니다.

대화 프로필 구성하기

Agent Assist에서 추천을 받으려면 업로드된 문서가 포함된 기술 자료를 만들고 대화 프로필을 구성해야 합니다. API를 직접 호출하지 않으려면 Agent Assist 콘솔을 사용하여 이러한 작업을 수행할 수도 있습니다.

기술 자료 만들기

문서 업로드를 시작하려면 먼저 기술 자료를 만들어야 합니다. 기술 자료를 만들려면 KnowledgeBase 유형에서 create 메서드를 호출합니다.

REST 및 명령줄

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: GCP 프로젝트 ID
  • KNOWLEDGE_BASE_DISPLAY_NAME: 원하는 기술 자료 이름

HTTP 메서드 및 URL:

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

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("Knowledge ID: {}\n".format(response.name))

기술 문서 만들기

이제 기술 자료에 문서를 추가할 수 있습니다. 기술 자료에 문서를 만들려면 Document 유형의 create 메서드를 호출합니다. KnowledgeTypeARTICLE_SUGGESTION로 설정합니다. 이 예시에서는 공개적으로 공유된 Cloud Storage 버킷에 업로드된 반품 주문 정보가 포함된 HTML 파일을 사용합니다. 고유 시스템에서 자료 추천을 설정할 때 문서는 다음 형식 중 하나여야 합니다. 문서 권장사항에 대한 자세한 내용은 기술 문서 설명서를 참조하세요.

기술 문서 형식:

  • Cloud Storage 버킷에 저장된 파일입니다. API를 호출할 때 경로를 지정할 수 있습니다.
  • API 요청으로 보낼 수 있는 문서의 텍스트 콘텐츠
  • 공개 URL

REST 및 명령줄

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: GCP 프로젝트 ID
  • KNOWLEDGE_BASE_ID: 이전 요청에서 반환된 기술 자료 ID
  • DOCUMENT_DISPLAY_NAME: 원하는 기술 문서 이름

HTTP 메서드 및 URL:

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

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)로 설정하는 것이 좋습니다. 필요한 경우 임곗값을 추천 범위 이상으로 늘릴 수 있습니다. 임곗값을 늘리면 정확도가 높아지고 적용 범위 결과가 낮아집니다(추천 수가 적음). 반대로 임곗값을 줄이면 정확성이 떨어지고 적용 범위가 높아집니다(추천 수가 많음).

REST 및 명령줄

대화 프로필을 만들려면 ConversationProfile 리소스에서 create 메서드를 호출합니다.

noSmallTalk: true인 경우 스몰 토크 메시지(예: 'hi', 'how are you' 등) 다음에 추천이 트리거되지 않습니다. false인 경우 스몰 토크 메시지 다음에 추천이 트리거됩니다.

onlyEndUser: true인 경우 최종 사용자 메시지 다음에만 추천이 트리거됩니다. false인 경우 최종 사용자 및 상담사 메시지 다음에 추천이 트리거됩니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: GCP 프로젝트 ID
  • KNOWLEDGE_BASE_ID: 기술 자료 ID

HTTP 메서드 및 URL:

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

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 CX 콘솔을 사용하여 설정할 수 있는 Dialogflow의 보안 설정에 의해 제어됩니다.

런타임 중 대화 처리

대화 만들기

최종 사용자와 상담사 또는 가상 에이전트의 대화가 시작될 때 대화를 만듭니다. 추천을 보려면 최종 사용자 참여자와 상담사 참여자를 모두 만들어 대화에 추가해야 합니다. 다음 섹션에서는 이러한 프로세스를 안내합니다.

먼저 대화를 만들어야 합니다.

REST 및 명령줄

대화를 만들려면 Conversation 리소스에서 create 메서드를 호출합니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: GCP 프로젝트 ID
  • CONVERSATION_PROFILE_ID: 대화 프로필을 만들 때 받은 ID

HTTP 메서드 및 URL:

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

JSON 요청 본문:

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

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 JSON 응답이 표시됩니다.

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

conversations 다음의 경로 세그먼트에 새 대화 ID가 있습니다.

Python

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: GCP 프로젝트 ID
  • CONVERSATION_ID: 대화 ID

HTTP 메서드 및 URL:

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

JSON 요청 본문:

{
  "role": "END_USER",
}

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 JSON 응답이 표시됩니다.

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

participants 다음의 경로 세그먼트에 새로운 최종 사용자 참여자 ID가 있습니다.

Python

def create_participant(project_id, conversation_id, role):
    """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("Role: {}".format(response.role))
        print("Name: {}".format(response.name))

        return response

상담사 참여자 만들기

상담사 참여자를 대화에 추가합니다.

REST 및 명령줄

상담사 참여자를 만들려면 Participant 리소스에서 create 메서드를 호출합니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: GCP 프로젝트 ID
  • CONVERSATION_ID: 대화 ID

HTTP 메서드 및 URL:

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

JSON 요청 본문:

{
  "role": "HUMAN_AGENT",
}

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 JSON 응답이 표시됩니다.

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

participants 다음의 경로 세그먼트에 새로운 상담사 참여자 ID가 있습니다.

Python

def create_participant(project_id, conversation_id, role):
    """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("Role: {}".format(response.role))
        print("Name: {}".format(response.name))

        return response

상담사의 메시지 추가 및 분석

참여자가 대화에 메시지를 입력할 때마다 처리를 위해 해당 메시지를 API에 전송해야 합니다. Agent Assist에서는 상담사 및 최종 사용자 메시지 분석을 기반으로 추천을 제공합니다. 다음 예시에서는 상담사가 'How may I help you?'라고 묻는 대화를 시작합니다. 아직 응답에 추천이 반환되지 않습니다.

REST 및 명령줄

대화의 상담사 메시지를 추가하고 분석하려면 Participant 리소스에서 analyzeContent 메서드를 호출합니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: GCP 프로젝트 ID
  • CONVERSATION_ID: 대화 ID
  • PARTICIPANT_ID: 상담사 참여자 ID

HTTP 메서드 및 URL:

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

def analyze_content_text(project_id, conversation_id, participant_id, text):
    """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("Reply Text: {}".format(response.reply_text))

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

    for suggestion_result in response.end_user_suggestion_results:
        if suggestion_result.error:
            print("Error: {}".format(suggestion_result.error.message))
        if suggestion_result.suggest_articles_response:
            for answer in suggestion_result.suggest_articles_response.article_answers:
                print("Article Suggestion Answer: {}".format(answer.title))
                print("Answer Record: {}".format(answer.answer_record))
        if suggestion_result.suggest_faq_answers_response:
            for answer in suggestion_result.suggest_faq_answers_response.faq_answers:
                print("Faq Answer: {}".format(answer.answer))
                print("Answer Record: {}".format(answer.answer_record))
        if suggestion_result.suggest_smart_replies_response:
            for (
                answer
            ) in suggestion_result.suggest_smart_replies_response.smart_reply_answers:
                print("Smart Reply: {}".format(answer.reply))
                print("Answer Record: {}".format(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 메서드 및 URL:

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

def analyze_content_text(project_id, conversation_id, participant_id, text):
    """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("Reply Text: {}".format(response.reply_text))

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

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

    return response

대화 완료

대화가 끝나면 API를 사용하여 대화를 완료합니다.

REST 및 명령줄

대화를 완료하려면 conversations 리소스에서 complete 메서드를 호출합니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: GCP 프로젝트 ID
  • CONVERSATION_ID: 대화를 만들 때 받은 ID

HTTP 메서드 및 URL:

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

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를 사용하여 애플리케이션에 추천 알림을 보냅니다.