Bantuan FAQ

FAQ Assist menyarankan jawaban FAQ yang relevan kepada agen manusia selama percakapan dengan pengguna akhir. Fitur ini dapat digunakan untuk membantu agen manusia menjawab pertanyaan umum pengguna akhir saat agen manusia dan pengguna akhir sedang melakukan percakapan.

Agent Assist mengikuti percakapan dan mengurai dokumen FAQ yang disimpan di pusat informasi untuk menyarankan jawaban atas pertanyaan pengguna akhir. Agen manusia dapat memeriksa saran ini saat percakapan berlangsung dan membuat keputusan tentang saran mana yang akan dibagikan kepada pengguna akhir.

Dokumen ini akan memandu Anda melalui proses penggunaan API untuk menerapkan FAQ Assist dan mendapatkan saran dari fitur ini selama runtime. Anda memiliki opsi untuk menggunakan konsol Agent Assist guna menguji hasil Saran Artikel selama waktu desain, tetapi Anda harus memanggil API secara langsung selama runtime. Lihat bagian tutorial untuk mengetahui detail tentang pengujian performa fitur menggunakan konsol Agent Assist.

Sebelum memulai

Selesaikan hal-hal berikut sebelum memulai panduan ini:

  1. Aktifkan Dialogflow API untuk project Google Cloud .

Mengonfigurasi profil percakapan

Untuk mendapatkan saran dari Agent Assist, Anda harus membuat basis pengetahuan yang berisi dokumen yang diupload dan mengonfigurasi profil percakapan. Anda juga dapat melakukan tindakan ini menggunakan Konsol Agent Assist jika Anda memilih untuk tidak memanggil API secara langsung.

Membuat pusat informasi

Sebelum dapat mulai mengupload dokumen, Anda harus membuat basis pengetahuan terlebih dahulu untuk menyimpannya. Untuk membuat basis pengetahuan, panggil metode create pada jenis KnowledgeBase.

REST

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • PROJECT_ID: project ID GCP Anda
  • KNOWLEDGE_BASE_DISPLAY_NAME: nama pustaka informasi yang diinginkan

Metode HTTP dan URL:

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

Meminta isi JSON:

{
  "displayName": "KNOWLEDGE_BASE_DISPLAY_NAME"
}

Untuk mengirim permintaan Anda, perluas salah satu opsi berikut:

Anda akan melihat respons JSON seperti berikut:

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

Segmen jalur setelah knowledgeBases berisi ID basis pengetahuan baru Anda.

Python

Untuk melakukan autentikasi ke Agent Assist, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Membuat dokumen pengetahuan

Sekarang Anda dapat menambahkan dokumen ke pusat informasi. Untuk membuat dokumen di basis pengetahuan, panggil metode create pada jenis Document. Tetapkan KnowledgeType ke FAQ. Contoh ini menggunakan dokumen FAQ Cloud Storage yang diupload ke bucket Cloud Storage yang dibagikan secara publik. Saat Anda menyiapkan Saran Artikel di sistem Anda sendiri, dokumen harus dalam salah satu format berikut. Lihat dokumentasi dokumen pengetahuan untuk mengetahui informasi selengkapnya tentang praktik terbaik dokumen.

Dokumen FAQ dapat berupa salah satu dari tiga format berikut:

  • URL publik.
  • Jalur Cloud Storage ke file csv.
  • File csv (yang akan Anda sertakan dalam permintaan API).

Jika dalam format csv, dokumen Anda harus berisi dua kolom: Pertanyaan FAQ harus dicantumkan di kolom pertama, dan jawaban untuk setiap pertanyaan harus dicantumkan di kolom kedua. Setiap pertanyaan FAQ dan jawaban terkaitnya disebut pasangan FAQ. Pastikan file csv tidak berisi baris header. Jika dokumen Anda adalah URL publik, dokumen tersebut harus berupa halaman FAQ yang mencantumkan beberapa pasangan FAQ.

Lihat dokumentasi dokumen pengetahuan untuk mengetahui informasi praktik terbaik.

REST

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • PROJECT_ID: project ID GCP Anda
  • KNOWLEDGE_BASE_ID: ID pustaka pengetahuan Anda yang ditampilkan dari permintaan sebelumnya
  • DOCUMENT_DISPLAY_NAME: nama dokumen pengetahuan yang diinginkan

Metode HTTP dan URL:

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

Meminta isi JSON:

{
  "displayName": "DOCUMENT_DISPLAY_NAME",
  "mimeType": "text/html",
  "knowledgeTypes": "FAQ",
  "contentUri": "https://cloud.google.com/storage/docs/faq"
}

Untuk mengirim permintaan Anda, perluas salah satu opsi berikut:

Anda akan melihat respons JSON seperti berikut:

{
  "name": "projects/PROJECT_ID/operations/ks-add_document-MzA5NTY2MTc5Mzg2Mzc5NDY4OA"
}

Responsnya adalah operasi yang berjalan lama, yang dapat Anda polling untuk memeriksa penyelesaiannya.

Python

Untuk melakukan autentikasi ke Agent Assist, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Membuat profil percakapan

Profil percakapan mengonfigurasi serangkaian parameter yang mengontrol saran yang diberikan kepada agen selama percakapan. Langkah-langkah berikut akan membuat ConversationProfile dengan objek HumanAgentAssistantConfig. Anda juga dapat melakukan tindakan ini menggunakan Konsol Agent Assist jika tidak ingin memanggil API secara langsung.

Saran inline diaktifkan secara default. Secara opsional, Anda dapat mengaktifkan notifikasi Cloud Pub/Sub saat mengonfigurasi profil percakapan.

REST

Untuk membuat profil percakapan, panggil metode create pada resource ConversationProfile.

noSmallTalk: Jika true, saran tidak akan dipicu setelah pesan percakapan santai (seperti "halo", "apa kabar", dan sebagainya). Jika false, saran akan dipicu setelah pesan obrolan ringan.

onlyEndUser: Jika true, saran hanya akan dipicu setelah pesan pengguna akhir. Jika false, saran akan dipicu setelah pesan pengguna akhir dan agen manusia.

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • PROJECT_ID: project ID GCP Anda
  • KNOWLEDGE_BASE_ID: ID pustaka pengetahuan Anda

Metode HTTP dan URL:

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

Meminta isi 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,
           }
        }
      ]
    }
  }
}

Untuk mengirim permintaan Anda, perluas salah satu opsi berikut:

Anda akan melihat respons JSON seperti berikut:

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

Segmen jalur setelah conversationProfiles berisi ID profil percakapan baru Anda.

Python

Untuk melakukan autentikasi ke Agent Assist, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

(Opsional) Menetapkan setelan keamanan

Anda memiliki opsi untuk menetapkan parameter keamanan guna membantu mengatasi masalah seperti pengeditan data dan retensi data. Untuk melakukannya, Anda harus membuat resource SecuritySettings, lalu menautkannya ke profil percakapan menggunakan kolom securitySettings.

Setelan keamanan yang ditambahkan ke profil percakapan hanya memengaruhi perilaku pesan teks Agent Assist. Perilaku histori interaksi Dialogflow dikontrol oleh setelan keamanan Dialogflow, yang dapat Anda tetapkan menggunakan Konsol Dialogflow CX.

Menangani percakapan saat runtime

Membuat percakapan

Saat dialog dimulai antara pengguna akhir dan agen manusia atau virtual, Anda akan membuat percakapan. Untuk melihat saran, Anda juga harus membuat peserta pengguna akhir dan peserta agen manusia, lalu menambahkannya ke percakapan. Bagian berikut akan memandu Anda melalui proses ini.

Pertama, Anda harus membuat percakapan:

REST

Untuk membuat percakapan, panggil metode create pada resource Conversation.

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • PROJECT_ID: project ID Cloud Anda
  • LOCATION_ID: ID lokasi Anda
  • CONVERSATION_PROFILE_ID: ID yang Anda terima saat membuat profil percakapan

Metode HTTP dan URL:

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

Meminta isi JSON:

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

Untuk mengirim permintaan Anda, perluas salah satu opsi berikut:

Anda akan melihat respons JSON seperti berikut:

{
  "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"
}

Segmen jalur setelah conversations berisi ID percakapan baru Anda.

Python

Untuk melakukan autentikasi ke Agent Assist, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Membuat peserta pengguna akhir

Anda harus menambahkan peserta pengguna akhir dan agen manusia ke percakapan untuk melihat saran. Pertama, tambahkan peserta pengguna akhir ke percakapan:

REST

Untuk membuat peserta pengguna akhir, panggil metode create pada resource Participant.

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • PROJECT_ID: project ID Cloud Anda
  • LOCATION_ID: ID lokasi Anda
  • CONVERSATION_ID: ID percakapan Anda

Metode HTTP dan URL:

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

Meminta isi JSON:

{
  "role": "END_USER",
}

Untuk mengirim permintaan Anda, perluas salah satu opsi berikut:

Anda akan melihat respons JSON seperti berikut:

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

Segmen jalur setelah participants berisi ID peserta pengguna akhir baru Anda.

Python

Untuk melakukan autentikasi ke Agent Assist, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Membuat peserta agen manusia

Menambahkan peserta agen manusia ke percakapan:

REST

Untuk membuat peserta agen manusia, panggil metode create pada resource Participant.

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • PROJECT_ID: project ID Cloud Anda
  • LOCATION_ID: ID lokasi Anda
  • CONVERSATION_ID: ID percakapan Anda

Metode HTTP dan URL:

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

Meminta isi JSON:

{
  "role": "HUMAN_AGENT",
}

Untuk mengirim permintaan Anda, perluas salah satu opsi berikut:

Anda akan melihat respons JSON seperti berikut:

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

Segmen jalur setelah participants berisi ID peserta agen manusia baru Anda.

Python

Untuk melakukan autentikasi ke Agent Assist, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Menambahkan dan menganalisis pesan dari agen manusia

Setiap kali salah satu peserta mengetik pesan dalam percakapan, Anda harus mengirim pesan tersebut ke API untuk diproses. Agent Assist mendasarkan saran pada analisis pesan agen manusia dan pengguna akhir. Dalam contoh berikut, agen manusia memulai percakapan dengan bertanya "Bagaimana saya dapat membantu Anda?". Belum ada saran yang ditampilkan dalam respons.

REST

Untuk menambahkan dan menganalisis pesan agen manusia untuk percakapan, panggil metode analyzeContent pada resource Participant.

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • PROJECT_ID: project ID GCP Anda
  • CONVERSATION_ID: ID percakapan Anda
  • PARTICIPANT_ID: ID peserta agen manusia Anda

Metode HTTP dan URL:

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

Meminta isi JSON:

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

Untuk mengirim permintaan Anda, perluas salah satu opsi berikut:

Anda akan melihat respons JSON seperti berikut:

      {
        "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

Untuk melakukan autentikasi ke Agent Assist, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Menambahkan pesan dari pengguna akhir dan mendapatkan saran

Sebagai respons terhadap agen, pengguna akhir bertanya "Bagaimana cara mendaftar?". Respons berisi daftar jawaban yang disarankan untuk pertanyaan pengguna akhir serta skor keyakinan untuk setiap jawaban. Semua jawaban diambil dari satu dokumen pengetahuan FAQ yang telah kita tambahkan sebelumnya dalam tutorial ini. Nilai minimum keyakinan mengacu pada tingkat keyakinan model bahwa setiap saran FAQ relevan dengan permintaan agen. Nilai keyakinan yang lebih tinggi akan meningkatkan kemungkinan respons yang relevan ditampilkan, tetapi dapat menyebabkan lebih sedikit atau tidak ada respons yang ditampilkan jika tidak ada opsi yang tersedia yang memenuhi nilai minimum yang tinggi. Sebaiknya gunakan nilai skor keyakinan awal 0,4. Anda dapat menyesuaikan nilai ini nanti untuk meningkatkan hasil jika diperlukan.

Respons juga menyertakan source jawaban, dokumen pengetahuan yang menjadi asal jawaban. Anda harus memberikan jawaban yang disarankan kepada agen manusia, yang mungkin memilih untuk memberikan informasi ini kepada pengguna akhir.

REST

Untuk menambahkan dan menganalisis pesan pengguna akhir untuk percakapan, panggil metode analyzeContent pada resource Participant.

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • PROJECT_ID: project ID GCP Anda
  • CONVERSATION_ID: ID percakapan Anda
  • PARTICIPANT_ID: ID peserta pengguna akhir Anda

Metode HTTP dan URL:

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

Meminta isi JSON:

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

Untuk mengirim permintaan Anda, perluas salah satu opsi berikut:

Anda akan melihat respons JSON seperti berikut:

{
  "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

Untuk melakukan autentikasi ke Agent Assist, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Menyelesaikan percakapan

Saat percakapan berakhir, gunakan API untuk menyelesaikan percakapan.

REST

Untuk menyelesaikan percakapan, panggil metode complete pada resource conversations.

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • PROJECT_ID: project ID GCP Anda
  • CONVERSATION_ID: ID yang Anda terima saat membuat percakapan

Metode HTTP dan URL:

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

Untuk mengirim permintaan, perluas salah satu opsi berikut:

Anda akan melihat respons JSON seperti berikut:

{
  "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

Untuk melakukan autentikasi ke Agent Assist, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Opsi permintaan API

Bagian sebelumnya menunjukkan cara membuat ConversationProfile untuk menerima saran. Bagian berikut menguraikan beberapa fungsi opsional yang dapat Anda terapkan selama percakapan.

Notifikasi saran Pub/Sub

Di bagian sebelumnya, ConversationProfile hanya dibuat dengan asisten agen manusia. Selama percakapan, Anda harus memanggil API untuk menerima saran setelah setiap pesan ditambahkan ke percakapan. Jika lebih memilih untuk menerima peristiwa notifikasi untuk saran, Anda dapat menetapkan kolom notificationConfig saat membuat profil percakapan. Opsi ini menggunakan Cloud Pub/Sub untuk mengirim notifikasi saran ke aplikasi Anda saat percakapan berlangsung dan saran baru tersedia.