Sugestão de artigos

O recurso de sugestão de artigos do Agent Assist acompanha uma conversa entre um agente humano e um usuário final e oferece ao agente humano sugestões de documentos relevantes. Um agente humano pode examinar essas sugestões enquanto a conversa continua e decidir quais documentos ler ou compartilhar com o usuário final. Você pode usar a sugestão de artigo para ajudar um agente humano a entender e resolver problemas do usuário final enquanto o agente humano e o usuário final estão em uma conversa.

O Agent Assist oferece modelos básicos de sugestão de artigos que podem ser usados para sugerir artigos aos seus agentes. Se quiser, treine um modelo personalizado usando seus próprios dados de conversa enviados para melhorar a performance. Se você quiser treinar um modelo de sugestão personalizado para usar com a Sugestão de artigo, entre em contato com seu representante do Google.

Este documento explica o processo de uso da API para implementar a sugestão de artigos e receber sugestões desse recurso durante a execução. Você pode usar o console do Assistente de agente para testar os resultados da sugestão de artigos durante o tempo de design, mas precisa chamar a API diretamente durante a execução. Consulte a seção de tutoriais para detalhes sobre como testar o desempenho do recurso usando o console da Assistente de agente.

Antes de começar

Antes de começar este guia, faça o seguinte:

  1. Ative a API Dialogflow no seu projetoGoogle Cloud .

Configurar um perfil de conversa

Para receber sugestões do Agent Assist, crie uma base de conhecimento com os documentos enviados e configure um perfil de conversa. Você também pode realizar essas ações usando o console da Assistente de IA se preferir não chamar a API diretamente.

Criar uma base de conhecimento

Antes de começar a fazer upload de documentos, é necessário criar uma base de conhecimento para armazená-los. Para criar uma base de conhecimento, chame o método create no tipo KnowledgeBase.

REST

Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:

  • PROJECT_ID: ID do projeto do GCP
  • KNOWLEDGE_BASE_DISPLAY_NAME: nome desejado para a base de conhecimento

Método HTTP e URL:

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

Corpo JSON da solicitação:

{
  "displayName": "KNOWLEDGE_BASE_DISPLAY_NAME"
}

Para enviar a solicitação, expanda uma destas opções:

Você receberá uma resposta JSON semelhante a esta:

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

O segmento de caminho após knowledgeBases contém o novo ID da base de conhecimento.

Python

Para autenticar no Agent Assist, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

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

Criar um documento de conhecimento

Agora você pode adicionar documentos à base de conhecimento. Para criar um documento na base de conhecimento, chame o método create no tipo Document. Defina KnowledgeType como ARTICLE_SUGGESTION. Este exemplo usa um arquivo HTML com informações do pedido de devolução que foi enviado para um bucket do Cloud Storage compartilhado publicamente. Ao configurar a sugestão de artigos no seu próprio sistema, os documentos precisam estar em um dos seguintes formatos. Consulte a documentação sobre documentos de conhecimento para mais informações sobre práticas recomendadas.

Formatos de documentos de conhecimento:

  • Um arquivo armazenado em um bucket do Cloud Storage. É possível especificar o caminho ao chamar a API.
  • O conteúdo de texto de um documento, que pode ser enviado em uma solicitação de API.
  • Um URL público.

REST

Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:

  • PROJECT_ID: ID do projeto do GCP
  • KNOWLEDGE_BASE_ID: o código da base de conhecimento retornado pela solicitação anterior
  • DOCUMENT_DISPLAY_NAME: nome do documento de conhecimento desejado

Método HTTP e URL:

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

Corpo JSON da solicitação:

{
  "displayName": "DOCUMENT_DISPLAY_NAME",
  "mimeType": "text/html",
  "knowledgeTypes": "ARTICLE_SUGGESTION",
  "contentUri": "gs://agent-assist-public-examples/public_article_suggestion_example_returns.html"
}

Para enviar a solicitação, expanda uma destas opções:

Você receberá uma resposta JSON semelhante a esta:

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

A resposta é uma operação de longa duração, que pode ser pesquisada para verificar se foi concluída.

Python

Para autenticar no Agent Assist, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

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

Criar um perfil de conversa

Um perfil de conversa configura um conjunto de parâmetros que controlam as sugestões feitas a um agente durante uma conversa. As etapas a seguir criam um ConversationProfile com um objeto HumanAgentAssistantConfig. Você também pode realizar essas ações usando o console do Assistente de agente se preferir não chamar a API diretamente.

Recomendamos definir um limite de confiança inicial de 0,44 (0,1 se você estiver usando o modelo de referência legado). Se necessário, é possível aumentar o limite além do intervalo recomendado. Aumentar o limite resulta em maior acurácia e menor cobertura (menos sugestões). Diminuir o limite resulta em menor acurácia e maior cobertura (mais sugestões).

As sugestões inline ficam ativadas por padrão. Também é possível ativar as notificações do Cloud Pub/Sub ao configurar o perfil de conversa.

REST

Para criar um perfil de conversa, chame o método create no recurso ConversationProfile.

noSmallTalk: se true, as sugestões não serão acionadas após mensagens de conversa informal (como "oi", "tudo bem?" etc.). Se false, as sugestões serão acionadas após mensagens de conversa casual.

onlyEndUser: se true, as sugestões serão acionadas somente após as mensagens do usuário final. Se false, as sugestões serão acionadas após as mensagens do usuário final e do agente humano.

Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:

  • PROJECT_ID: ID do projeto do GCP
  • KNOWLEDGE_BASE_ID: código da base de conhecimento

Método HTTP e URL:

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

Corpo JSON da solicitação:

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

Para enviar a solicitação, expanda uma destas opções:

Você receberá uma resposta JSON semelhante a esta:

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

O segmento de caminho após conversationProfiles contém o novo ID do perfil de conversa.

Python

Para autenticar no Agent Assist, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

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

(Opcional) Defina as configurações de segurança

Você pode definir parâmetros de segurança para resolver problemas como edição e retenção de dados. Para isso, crie um recurso SecuritySettings e vincule-o a um perfil de conversa usando o campo securitySettings.

As configurações de segurança adicionadas a um perfil de conversa afetam o comportamento das mensagens de texto do Assistente de IA apenas. O comportamento do histórico de interações do Dialogflow é controlado pelas configurações de segurança do Dialogflow, que podem ser definidas usando o Console do Dialogflow CX.

Processar conversas no ambiente de execução

Criar uma conversa

Quando uma caixa de diálogo começa entre um usuário final e um agente humano ou virtual, você cria uma conversa. Para ver sugestões, você também precisa criar um participante usuário final e um agente humano e adicioná-los à conversa. As seções a seguir explicam esse processo.

Primeiro, crie uma conversa:

REST

Para criar uma conversa, chame o método create no recurso Conversation.

Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:

  • PROJECT_ID: o ID do projeto do Cloud
  • LOCATION_ID: o ID do local
  • CONVERSATION_PROFILE_ID: o ID que você recebeu ao criar o perfil de conversa

Método HTTP e URL:

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

Corpo JSON da solicitação:

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

Para enviar a solicitação, expanda uma destas opções:

Você receberá uma resposta JSON semelhante a esta:

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

O segmento de caminho após conversations contém o novo ID da conversa.

Python

Para autenticar no Agent Assist, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

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

Criar um participante do usuário final

Para ver sugestões, adicione os participantes do usuário final e do agente humano à conversa. Primeiro, adicione o participante usuário final à conversa:

REST

Para criar um participante do usuário final, chame o método create no recurso Participant.

Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:

  • PROJECT_ID: o ID do projeto do Cloud
  • LOCATION_ID: o ID do local
  • CONVERSATION_ID: o ID da conversa

Método HTTP e URL:

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

Corpo JSON da solicitação:

{
  "role": "END_USER",
}

Para enviar a solicitação, expanda uma destas opções:

Você receberá uma resposta JSON semelhante a esta:

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

O segmento de caminho após participants contém o novo ID do participante do usuário final.

Python

Para autenticar no Agent Assist, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

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

Criar um participante humano

Adicione um agente humano à conversa:

REST

Para criar um participante humano, chame o método create no recurso Participant.

Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:

  • PROJECT_ID: o ID do projeto do Cloud
  • LOCATION_ID: o ID do local
  • CONVERSATION_ID: o ID da conversa

Método HTTP e URL:

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

Corpo JSON da solicitação:

{
  "role": "HUMAN_AGENT",
}

Para enviar a solicitação, expanda uma destas opções:

Você receberá uma resposta JSON semelhante a esta:

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

O segmento de caminho após participants contém o ID do novo participante humano.

Python

Para autenticar no Agent Assist, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

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

Adicionar e analisar uma mensagem do agente humano

Sempre que um dos participantes digita uma mensagem na conversa, é necessário enviar essa mensagem à API para processamento. O Agent Assist baseia as sugestões dele na análise das mensagens do agente humano e do usuário final. No exemplo a seguir, o atendente humano inicia a conversa perguntando: "Como posso ajudar você?". Nenhuma sugestão é retornada na resposta.

REST

Para adicionar e analisar uma mensagem de um atendente humano na conversa, chame o método analyzeContent no recurso Participant.

Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:

  • PROJECT_ID: ID do projeto do GCP
  • CONVERSATION_ID: o ID da conversa
  • PARTICIPANT_ID: seu ID de participante agente humano

Método HTTP e URL:

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

Corpo JSON da solicitação:

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

Para enviar a solicitação, expanda uma destas opções:

Você receberá uma resposta JSON semelhante a esta:

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

Para autenticar no Agent Assist, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

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

Adicionar uma mensagem do usuário final e receber sugestões

Em resposta ao agente humano, o usuário final diz: "Quero devolver meu pedido". Desta vez, a resposta da API contém um documento sugerido com a pontuação de confiança associada. Neste tutorial, adicionamos um documento de conhecimento à base de conhecimento, e esse documento foi retornado. As pontuações de confiança variam de 0 a 1. Valores mais altos indicam uma maior probabilidade de o documento ser relevante para a conversa. Um snippet com os primeiros 100 caracteres do documento também é retornado. O snippet pode ajudar um agente humano a determinar rapidamente se o documento é útil. Recomendamos que você forneça essas informações ao seu agente humano, que pode compartilhar o documento recomendado com o usuário final.

REST

Para adicionar e analisar uma mensagem do usuário final na conversa, chame o método analyzeContent no recurso Participant.

Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:

  • PROJECT_ID: ID do projeto do GCP
  • CONVERSATION_ID: o ID da conversa
  • PARTICIPANT_ID: o ID do participante do usuário final

Método HTTP e URL:

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

Corpo JSON da solicitação:

{
  "textInput": {
    "text": "I want to return my order.",
    "languageCode": "en-US"
  }
}

Para enviar a solicitação, expanda uma destas opções:

Você receberá uma resposta JSON semelhante a esta:

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

Para autenticar no Agent Assist, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

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

Concluir a conversa

Quando a conversa terminar, use a API para concluir.

REST

Para concluir a conversa, chame o método complete no recurso conversations.

Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:

  • PROJECT_ID: ID do projeto do GCP
  • CONVERSATION_ID: o ID que você recebeu ao criar a conversa

Método HTTP e URL:

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

Para enviar a solicitação, expanda uma destas opções:

Você receberá uma resposta JSON semelhante a esta:

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

Para autenticar no Agent Assist, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

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

Opções de solicitação de API

As seções acima mostram como criar um ConversationProfile simples para receber sugestões. As seções a seguir descrevem algumas funcionalidades opcionais que podem ser implementadas durante uma conversa.

Notificações de sugestões do Pub/Sub

Nas seções anteriores, o ConversationProfile foi criado apenas com um assistente de agente humano. Durante a conversa, você precisava chamar a API para receber sugestões depois que cada mensagem era adicionada à conversa. Se preferir receber eventos de notificação para sugestões, defina o campo notificationConfig ao criar o perfil de conversa. Essa opção usa o Cloud Pub/Sub para enviar notificações de sugestões ao seu aplicativo à medida que a conversa avança e novas sugestões ficam disponíveis.