스마트 편지쓰기

스마트 편지쓰기 기능은 상담사가 최종 사용자와 텍스트 채팅을 하는 동안 지원합니다. 상담사가 시작한 문장을 완성하는 문구를 제안합니다. 이 기능을 사용하여 상담사 채팅 인터페이스의 맞춤 제안 기능을 구현할 수 있습니다.

상담사가 채팅 인터페이스에 입력하는 동안 텍스트 추천을 받습니다. 이 가이드에서는 API를 직접 호출하여 스마트 작성 기능을 구현하는 방법을 안내합니다. 원하는 경우 Agent Assist 콘솔을 사용하여 모델을 학습시키고 시뮬레이터를 사용하여 성능을 테스트할 수 있습니다. 자세한 내용은 스마트 작성 시뮬레이터 튜토리얼을 참고하세요.

스마트 작성을 자체 시스템과 통합하고 제안의 품질을 개선하는 방법에 관한 가이드라인은 스마트 작성 권장사항 문서를 참고하세요.

시작하기 전에

이 가이드를 읽기 전에 다음을 완료하세요.

  1. 프로젝트에 Dialog Flow API를 사용 설정합니다.

개인 식별 정보 및 아동 데이터

이 API로 데이터를 전송하면 API에서 모든 개인 식별 정보(PII)를 수정하려고 시도합니다. 모델에 PII가 포함되지 않도록 하려면 데이터를 API로 보내기 전에 삭제해야 합니다. 수정된 단어를 단순히 삭제하는 대신 `REDACTED_NUMBER` 또는 `REDACTED_NAME` 과 같은 자리표시자로 바꿉니다.

또한 아동에게서 수집한 정보가 데이터에 포함된 경우 아동 데이터를 API로 보내기 전에 삭제해야 합니다.

모델 학습 및 배포

Agent Assist 스마트 답장 모델은 대화 데이터 세트를 사용하여 학습됩니다. 대화 데이터 세트에는 직접 업로드한 스크립트 데이터가 포함됩니다. 이 섹션에서는 대화 데이터 세트를 만들고, 대화 데이터를 업로드하고, 모델을 학습시키고 배포하는 과정을 안내합니다. API를 직접 호출하지 않으려면 Agent Assist 콘솔을 사용하여 이러한 작업을 수행할 수도 있습니다.

대화 데이터 세트 만들기

대화 스크립트 업로드를 시작하려면 먼저 대화 데이터 세트를 만들어야 합니다. ConversationDataset 리소스에서 create 메서드를 호출하여 대화 데이터 세트를 만듭니다.

응답에 대화 데이터 세트 ID가 포함됩니다.

대화 스크립트를 대화 데이터 세트로 가져오기

Agent Assist에서 처리할 수 있도록 채팅 대화 데이터를 대화 데이터 세트에 업로드합니다. 각 대화의 스크립트가 JSON 형식이고 Cloud Storage 버킷에 저장되어 있는지 확인합니다. 대화 데이터 세트에 30,000개 이상의 대화가 포함되어 있어야 합니다. 그렇지 않은 경우 모델 학습이 실패합니다. 일반적으로 대화가 많을수록 모델 품질이 향상됩니다. 최대한 많은 사용 사례를 충분히 다루려면 3개월 이상의 대화를 업로드하는 것이 좋습니다. 대화 데이터 세트의 최대 메시지 수는 1,000,000개입니다.

ConversationDataset 리소스에서 importConversationData 메서드를 호출하여 대화를 가져옵니다.

필수 필드:

  • 이전에 만든 대화 데이터 세트 ID입니다.
  • inputConfig 경로는 Cloud Storage 버킷의 대화 스크립트 데이터로 연결됩니다.

응답은 완료 여부를 확인하기 위해 폴링할 수 있는 장기 실행 작업입니다.

대화 모델 만들기

ConversationModel 리소스에서 create 메서드를 호출하여 대화 모델을 만듭니다. 이 작업은 모델의 허용 목록도 만듭니다.

필수 필드:

  • datasets에서 이전에 만든 대화 데이터 세트 ID를 사용하여 단일 데이터 세트를 제공합니다.
  • smartReplyModelMetadata를 빈 객체로 설정하거나 필드를 채워 기본값을 재정의합니다.

응답은 완료 여부를 확인하기 위해 폴링할 수 있는 장기 실행 작업입니다. 완료되면 모델 ID와 허용 목록 ID가 작업의 메타데이터에 포함됩니다.

  • 모델 ID: name
  • 허용 목록 ID: smart_reply_model_metadata.associated_allowlist_info.document

대화 모델 배포

ConversationModel 리소스에서 deploy 메서드를 호출하여 대화 모델을 배포합니다.

필수 입력란:

  • conversationModels 사용: 이전에 만든 대화 모델 ID를 입력합니다.

허용 목록 관리

각 모델에는 허용 목록이 연결되어 있으며, 이는 대화 모델을 만들 때 자동으로 생성됩니다. 허용 목록에는 런타임에 인적 상담사에게 표시될 수 있는 대화 데이터 세트에서 생성된 모든 대답이 포함됩니다. 이 섹션에서는 허용 목록 생성 및 관리를 설명합니다. API를 직접 호출하지 않으려면 Agent Assist 콘솔을 사용하여 이러한 작업을 수행할 수도 있습니다.

허용 목록 콘텐츠를 CSV 파일로 내보내기

모델을 생성하면 새 모델과 연결된 허용 목록이 자동으로 생성됩니다. 허용 목록은 고유 ID가 있는 문서 리소스입니다. 모델이 생성되면 ID가 smart_reply_model_metadata.associated_allowlist_info.document에 반환됩니다. 허용 목록에 있는 메시지를 검토하고 변경하려면 Cloud Storage 버킷으로 내보내야 합니다.

Document 리소스에서 export 메서드를 호출하여 문서를 Cloud Storage 버킷의 CSV 파일로 내보냅니다. smart_messaging_partial_update 필드는 선택사항이지만 향후 허용 목록을 업데이트하는 방법에 영향을 미칩니다. true로 설정하면 내보낸 CSV 파일에 각 메시지의 고유 ID가 포함된 열이 포함됩니다. 메시지 ID를 사용하여 전체 문서 대신 지정된 메시지만 업데이트할 수 있습니다. smart_messaging_partial_updatefalse로 설정되거나 설정되지 않은 경우 추가 열이 파일에 표시되지 않으며 허용 목록을 업데이트하려면 전체 문서를 업데이트해야 합니다.

필수 입력란:

  • gcsDestination 경로는 Cloud Storage 버킷으로 이동합니다.

응답은 완료 여부를 확인하기 위해 폴링할 수 있는 장기 실행 작업입니다. 그런 다음 요청에 제공한 CSV 파일이 응답 후보로 채워집니다.

허용 목록 검토

생성된 허용 목록에는 대화 데이터를 기반으로 스마트 답장이 자동으로 생성한 대답이 포함됩니다. 이제 필요에 따라 이러한 대답을 검토하고 업데이트할 수 있습니다. Cloud Storage 버킷에서 CSV 파일을 다운로드하고 필요에 맞게 수정하고 파일을 Cloud Storage 버킷에 다시 업로드합니다. 허용 목록에 있는 대답만 인간 상담사에게 표시될 수 있습니다.

대답을 수정하는 경우 맞춤법과 문법만 수정하고 메시지의 의미는 변경하지 않는 것이 좋습니다. 수정된 텍스트가 모델의 의미에서 벗어날수록 메시지가 표시될 가능성이 낮아집니다.

필요한 경우 새 메시지를 만들 수도 있습니다. 수정된 메시지와 마찬가지로 생성된 메시지는 런타임 중에 표시될 가능성이 낮습니다.

허용 목록 업데이트

CSV 파일 업데이트를 완료한 후 이를 사용하여 Document 리소스를 업데이트할 수 있습니다. 전체 허용 목록을 업데이트하거나 지정된 메시지만 업데이트할 수 있습니다. 지정된 메시지만 업데이트하려면 허용 목록을 내보낼 때 smart_messaging_partial_updatetrue로 설정해야 합니다. 이미 이 작업을 완료한 경우 내보낸 CSV 파일에서 자동으로 생성된 열을 사용하여 업데이트할 메시지를 표시합니다.

Document 리소스에서 reload 메서드를 호출하여 허용 목록을 업데이트합니다. 지정된 메시지만 업데이트하려면 ReloadDocumentRequest에서 smart_messaging_partial_updatetrue로 설정합니다. 전체 허용 목록을 업데이트하려면 smart_messaging_partial_update를 설정하지 않거나 false로 설정합니다.

필수 필드:

  • gcsSourceCSV 파일의 Cloud Storage 경로입니다.
  • name의 경우 대화 모델을 만들 때 생성된 허용 목록 리소스 이름을 사용합니다.

요청 예시:

{
  "name":"projects/project-id/knowledgeBases/knowledge-base-id/documents/allowlist-id",
  "gcsSource" {
      "uri": "gs://revised_smart_reply_allowlist_path"
   }
}

학습된 모델의 성능 평가

모델을 배포하고 모델의 허용 목록을 만든 후 모델의 성능을 테스트할 수 있습니다. 테스트 데이터 세트도 제공해야 합니다. 학습된 스마트 답장 모델과 연결된 허용 목록에서 생성된 응답이 테스트 데이터 세트의 실제 상담사 메시지와 비교됩니다. 테스트 데이터 세트는 실제 대화 데이터로 구성되어야 하지만 모델을 학습하는 데 사용한 대화 데이터 세트의 데이터는 포함해서는 안 됩니다. 예를 들어 1개월 분량의 대화 트래픽이 있는 경우 3주 분량의 대화 데이터를 사용하여 대화 데이터 세트를 만들고 나머지 1주 분량의 데이터를 사용하여 테스트 데이터 세트를 만들 수 있습니다. 테스트 데이터 세트에는 최소 1,000개의 대화가 포함되어야 하지만, 일반적으로 테스트 데이터 세트에 대화가 많을수록 평가 측정항목이 더 신뢰할 수 있습니다. 테스트 데이터 세트 형식은 대화 데이터 세트 형식과 동일합니다.

새 모델 평가를 만들려면 ConversationModel 리소스에서 CreateConversationModelEvaluation 메서드를 호출합니다. 이 메서드는 장기 실행 작업을 반환합니다. 작업을 폴링하여 상태를 확인할 수 있으며, 상태는 INITIALIZING, RUNNING, SUCCEEDED, CANCELLED, FAILED 중 하나로 반환됩니다.

필수 필드:

  • InputDataset: 모델의 성능을 테스트하는 데 사용될 테스트 데이터 세트입니다.
  • allowlist_document: 테스트할 스마트 답장 모델과 연결된 허용 목록입니다.

장기 실행 작업이 완료되면 ConversationModelEvaluation 리소스가 반환됩니다. 다음 두 가지 측정항목이 포함됩니다.

  • allowlist_coverage: 허용 목록에 포함된 테스트 데이터 세트의 에이전트 메시지 비율입니다.
  • recall: 테스트 데이터 세트의 에이전트 메시지 중 허용 목록에 포함되고 스마트 답장 모델에서 표시된 상위 3개 추천에 표시되는 메시지의 비율입니다.

대화 프로필 구성하기

대화 프로필은 대화 중 에이전트에 제공되는 추천을 제어하는 매개변수 집합을 구성합니다. 다음 단계에서는 HumanAgentAssistantConfig 객체로 ConversationProfile을 만듭니다. API를 직접 호출하지 않으려면 Agent Assist 콘솔을 사용하여 이러한 작업을 수행할 수도 있습니다.

대화 프로필 만들기

대화 프로필을 만들려면 ConversationProfile 리소스에서 create 메서드를 호출합니다. 기술 자료 ID, 문서 ID, 프로젝트 ID, 모델 ID를 제공합니다.

다음은 JSON 예시입니다.
{
  "displayName": "smart_compose_assist",
  "humanAgentAssistantConfig": {
    "humanAgentSuggestionConfig": {
      "featureConfigs": [
        {
          "suggestionFeature": {
            "type": "SMART_COMPOSE"
          },
          "queryConfig": {
            "documentQuerySource": {
              "documents": "projects/PROJECT_ID/knowledgeBases/KNOWLEDGE_BASE_ID/documents/DOCUMENT_ID"
            },
           "maxResults": "1"
          },
         "conversationModelConfig": {
           "model": "projects/PROJECT_ID/conversationModels/MODEL_ID"
         }
        }
      ]
    }
  }
}

응답에 새 대화 프로필 ID가 포함됩니다.

런타임에 대화 처리

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

대화 만들기

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

REST

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

  • PROJECT_ID: 클라우드 프로젝트 ID입니다.
  • LOCATION_ID: 위치 ID
  • CONVERSATION_PROFILE_ID: 대화 프로필을 만들 때 받은 ID

HTTP 메서드 및 URL:

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

최종 사용자 참여자 만들기

추천을 보려면 최종 사용자 및 상담사 참여자를 모두 대화에 추가해야 합니다. 최종 사용자 참여자를 만들려면 Participant 리소스에서 create 메서드를 호출합니다. 대화 ID를 제공하고 role 필드에 END_USER를 입력합니다.

REST

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

  • PROJECT_ID: 클라우드 프로젝트 ID입니다.
  • LOCATION_ID: 위치 ID
  • CONVERSATION_ID: 대화 ID

HTTP 메서드 및 URL:

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

상담사 참여자 만들기

상담사 참여자를 만들려면 Participant 리소스에서 create 메서드를 호출합니다. 대화 ID를 제공하고 role 필드에 HUMAN_AGENT를 입력합니다.

REST

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

  • PROJECT_ID: 클라우드 프로젝트 ID입니다.
  • LOCATION_ID: 위치 ID
  • CONVERSATION_ID: 대화 ID

HTTP 메서드 및 URL:

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에서는 상담사 및 최종 사용자 메시지 분석을 기반으로 추천을 제공합니다. 대화의 상담사 메시지를 추가하고 분석하려면 Participant 리소스에서 analyzeContent 메서드를 호출합니다. 대화 ID 및 상담사 참여자 ID를 제공합니다.

REST

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

  • 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": [
    {
      "suggestSmartRepliesResponse": {
      "smartReplyAnswers": [
          {
            "reply": "I am here to help you.",
            "confidence": 0.5,
            "answerRecord": "projects/PROJECT_ID/answerRecords/ANSWER_RECORD_ID_1"
          },
          {
            "reply": "Sorry for the wait, we have a high volume of chats right now.",
            "confidence": 0.3,
            "answerRecord": "projects/PROJECT_ID/answerRecords/ANSWER_RECORD_ID_2"
          },
          {
            "reply": "Thank you for contacting us!",
            "confidence": 0.1,
            "answerRecord": "projects/PROJECT_ID/answerRecords/ANSWER_RECORD_ID_3"
          }
        ]
      }
    }
  ]
}

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

최종 사용자가 보낸 메시지 추가 및 분석

대화의 최종 사용자 메시지를 추가하고 분석하려면 Participant 리소스에서 analyzeContent 메서드를 호출합니다. 대화 ID 및 최종 사용자 참여자 ID를 제공합니다.

응답에 메시지 ID가 포함됩니다. 다음 단계에서 추천을 획득합니다.

REST

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

  • 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 reserve a room.",
    "languageCode": "en-US"
  }
}

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

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

{
  "message": {
    "name": "projects/PROJECT_ID/conversations/CONVERSATION_ID/messages/MESSAGE_ID",
    "content": "I want to reserve a room.",
    "languageCode": "en-US",
    "participant": "PARTICIPANT_ID",
    "participantRole": "END_USER",
    "createTime": "2020-02-13T00:07:35.925Z"
  },
  "humanAgentSuggestionResults": [
    {
      "suggestSmartRepliesResponse": {
      "smartReplyAnswers": [
          {
            "reply": "Where would you like to reserve a room?",
            "confidence": 0.5,
            "answerRecord": "projects/PROJECT_ID/answerRecords/ANSWER_RECORD_ID_1"
          },
          {
            "reply": "What type of rooms would you like to reserve?",
            "confidence": 0.3,
            "answerRecord": "projects/PROJECT_ID/answerRecords/ANSWER_RECORD_ID_2"
          },
          {
            "reply": "How long do you want to stay?",
            "confidence": 0.1,
            "answerRecord": "projects/PROJECT_ID/answerRecords/ANSWER_RECORD_ID_3"
          }
        ]
      }
    }
  ]
}

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

추천 받기(선택사항)

언제든지 추천을 받을 수 있습니다. 원하는 경우 메시지 ID를 지정하여 메시지에 따른 추천을 받을 수 있습니다. 이 필드를 설정하지 않으면 기본적으로 참여자의 최신 메시지를 기반으로 추천이 제공됩니다. 추천을 받으려면 Suggestion 리소스에서 suggestSmartReplies 메서드를 호출합니다. 대화 ID, 상담사 참여자 ID, 참여자의 메시지 ID(선택사항)를 입력합니다.

응답에 상담사를 위한 스마트 답장 추천이 포함됩니다.

REST

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

  • 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 reserve a room.",
    "languageCode": "en-US"
  }
}

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

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

{
  "message": {
    "name": "projects/PROJECT_ID/conversations/CONVERSATION_ID/messages/MESSAGE_ID",
    "content": "I want to reserve a room.",
    "languageCode": "en-US",
    "participant": "PARTICIPANT_ID",
    "participantRole": "END_USER",
    "createTime": "2020-02-13T00:07:35.925Z"
  },
  "humanAgentSuggestionResults": [
    {
      "suggestSmartRepliesResponse": {
      "smartReplyAnswers": [
          {
            "reply": "Where would you like to reserve a room?",
            "confidence": 0.5,
            "answerRecord": "projects/PROJECT_ID/answerRecords/ANSWER_RECORD_ID_1"
          },
          {
            "reply": "What type of rooms would you like to reserve?",
            "confidence": 0.3,
            "answerRecord": "projects/PROJECT_ID/answerRecords/ANSWER_RECORD_ID_2"
          },
          {
            "reply": "How long do you want to stay?",
            "confidence": 0.1,
            "answerRecord": "projects/PROJECT_ID/answerRecords/ANSWER_RECORD_ID_3"
          }
        ]
      }
    }
  ]
}

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

대화 완료

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

REST

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

  • 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

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