Asistencia con preguntas frecuentes

Asistencia para preguntas frecuentes sugiere respuestas relevantes a los agentes humanos durante una conversación con un usuario final. Esta función se puede usar para ayudar a un agente humano a responder preguntas habituales de los usuarios finales mientras el agente humano y el usuario final mantienen una conversación.

Agent Assist sigue la conversación y analiza los documentos de preguntas frecuentes almacenados en bases de conocimientos para sugerir respuestas a las preguntas de los usuarios finales. Un agente humano puede examinar estas sugerencias mientras se desarrolla la conversación y decidir cuáles compartir con el usuario final.

En este documento se explica cómo usar la API para implementar Asistente de preguntas frecuentes y obtener sugerencias de esta función durante el tiempo de ejecución. Tienes la opción de usar la consola de Asistente para probar los resultados de Sugerencia de artículos durante el tiempo de diseño, pero debes llamar a la API directamente durante el tiempo de ejecución. Consulta la sección de tutoriales para obtener información sobre cómo probar el rendimiento de las funciones con la consola de Agent Assist.

Antes de empezar

Antes de empezar a leer esta guía, haz lo siguiente:

  1. Habilita la API Dialogflow en tu proyecto deGoogle Cloud .

Configurar un perfil de conversación

Para recibir sugerencias de Agent Assist, debes crear una base de conocimientos que contenga los documentos que hayas subido y configurar un perfil de conversación. También puedes realizar estas acciones con la consola de Asistente si prefieres no llamar a la API directamente.

Crear una base de conocimientos

Antes de empezar a subir documentos, debes crear una base de conocimientos en la que colocarlos. Para crear una base de conocimientos, llama al método create del tipo KnowledgeBase.

REST

Antes de usar los datos de la solicitud, haz las siguientes sustituciones:

  • PROJECT_ID: tu ID de proyecto de GCP
  • KNOWLEDGE_BASE_DISPLAY_NAME: nombre de la base de conocimientos que quieras

Método HTTP y URL:

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

Cuerpo JSON de la solicitud:

{
  "displayName": "KNOWLEDGE_BASE_DISPLAY_NAME"
}

Para enviar tu solicitud, despliega una de estas opciones:

Deberías recibir una respuesta JSON similar a la siguiente:

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

El segmento de ruta después de knowledgeBases contiene el nuevo ID de la base de conocimientos.

Python

Para autenticarte en Agent Assist, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo 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))

Crear un documento de conocimientos

Ahora puedes añadir documentos a la base de conocimientos. Para crear un documento en la base de conocimientos, llama al método create en el tipo Document. Asigna el valor FAQ a KnowledgeType. En este ejemplo se usa el documento de preguntas frecuentes de Cloud Storage que se ha subido a un segmento de Cloud Storage compartido públicamente. Cuando configures Sugerencias de artículos en tu sistema, los documentos deben tener uno de los siguientes formatos. Consulta la documentación sobre documentos de conocimientos para obtener más información sobre las prácticas recomendadas para los documentos.

El documento de preguntas frecuentes puede estar en uno de estos tres formatos:

  • Una URL pública.
  • Ruta de Cloud Storage a un archivo csv.
  • Un archivo csv (que incluirás en la solicitud a la API).

Si tu documento está en formato csv, debe contener dos columnas: las preguntas frecuentes deben aparecer en la primera columna y las respuestas a cada pregunta, en la segunda. Cada pregunta de la sección de preguntas frecuentes y su respuesta asociada se denomina par de preguntas frecuentes. Asegúrate de que el archivo csv no contenga una fila de encabezado. Si el documento es una URL pública, debe ser una página de preguntas frecuentes que incluya varios pares de preguntas y respuestas.

Consulta la documentación de artículos de conocimientos para obtener información sobre las prácticas recomendadas.

REST

Antes de usar los datos de la solicitud, haz las siguientes sustituciones:

  • PROJECT_ID: tu ID de proyecto de GCP
  • KNOWLEDGE_BASE_ID: el ID de la base de conocimientos devuelto en la solicitud anterior.
  • DOCUMENT_DISPLAY_NAME: nombre del documento de conocimientos deseado

Método HTTP y URL:

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

Cuerpo JSON de la solicitud:

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

Para enviar tu solicitud, despliega una de estas opciones:

Deberías recibir una respuesta JSON similar a la siguiente:

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

La respuesta es una operación de larga duración, que puedes sondear para comprobar si se ha completado.

Python

Para autenticarte en Agent Assist, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo 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))

Crear un perfil de conversación

Un perfil de conversación configura un conjunto de parámetros que controlan las sugerencias que se le hacen a un agente durante una conversación. Con los pasos que se indican a continuación, se crea un ConversationProfile con un objeto HumanAgentAssistantConfig. También puedes realizar estas acciones con la consola de Asistente para agentes si prefieres no llamar a la API directamente.

Las sugerencias insertadas están habilitadas de forma predeterminada. También puedes habilitar las notificaciones de Cloud Pub/Sub al configurar el perfil de conversación.

REST

Para crear un perfil de conversación, llama al método create del recurso ConversationProfile.

noSmallTalk: Si true, las sugerencias no se activarán después de mensajes de charla informal (como "hola", "¿cómo estás?", etc.). Si false, las sugerencias se activarán después de los mensajes de Small Talk.

onlyEndUser: Si se le asigna el valor true, las sugerencias se activarán solo después de los mensajes del usuario final. Si false, las sugerencias se activarán después de los mensajes del usuario final y del agente humano.

Antes de usar los datos de la solicitud, haz las siguientes sustituciones:

  • PROJECT_ID: tu ID de proyecto de GCP
  • KNOWLEDGE_BASE_ID: el ID de tu base de conocimientos

Método HTTP y URL:

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

Cuerpo JSON de la solicitud:

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

Para enviar tu solicitud, despliega una de estas opciones:

Deberías recibir una respuesta JSON similar a la siguiente:

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

El segmento de ruta después de conversationProfiles contiene tu nuevo ID de perfil de conversación.

Python

Para autenticarte en Agent Assist, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo 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) Configurar los ajustes de seguridad

Puedes definir parámetros de seguridad para abordar problemas como la ocultación y la conservación de datos. Para ello, debes crear un recurso SecuritySettings y, a continuación, vincularlo a un perfil de conversación mediante el campo securitySettings.

Los ajustes de seguridad que se añaden a un perfil de conversación afectan al comportamiento de los mensajes de texto de Asistente del agente únicamente. El comportamiento del historial de interacciones de Dialogflow se controla mediante los ajustes de seguridad de Dialogflow, que puedes configurar con la consola de Dialogflow CX.

Gestionar conversaciones en tiempo de ejecución

Crear una conversación

Cuando se inicia un diálogo entre un usuario final y un agente humano o virtual, se crea una conversación. Para ver sugerencias, también debes crear un participante de usuario final y un participante de agente humano, y añadirlos a la conversación. En las siguientes secciones se explica este proceso.

Primero, debes crear una conversación:

REST

Para crear una conversación, llama al método create en el recurso Conversation.

Antes de usar los datos de la solicitud, haz las siguientes sustituciones:

  • PROJECT_ID: tu ID de proyecto de Cloud
  • LOCATION_ID: tu ID de ubicación
  • CONVERSATION_PROFILE_ID: el ID que has recibido al crear el perfil de conversación

Método HTTP y URL:

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

Cuerpo JSON de la solicitud:

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

Para enviar tu solicitud, despliega una de estas opciones:

Deberías recibir una respuesta JSON similar a la siguiente:

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

El segmento de ruta después de conversations contiene tu nuevo ID de conversación.

Python

Para autenticarte en Agent Assist, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo 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

Crear un participante usuario final

Para ver sugerencias, debes añadir a la conversación tanto al participante usuario final como al agente humano. Primero, añade al participante usuario final a la conversación:

REST

Para crear un participante usuario final, llama al método create en el recurso Participant.

Antes de usar los datos de la solicitud, haz las siguientes sustituciones:

  • PROJECT_ID: tu ID de proyecto de Cloud
  • LOCATION_ID: tu ID de ubicación
  • CONVERSATION_ID: tu ID de conversación

Método HTTP y URL:

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

Cuerpo JSON de la solicitud:

{
  "role": "END_USER",
}

Para enviar tu solicitud, despliega una de estas opciones:

Deberías recibir una respuesta JSON similar a la siguiente:

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

El segmento de ruta después de participants contiene tu nuevo ID de participante de usuario final.

Python

Para autenticarte en Agent Assist, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo 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

Crear un participante de agente humano

Añade un agente humano a la conversación:

REST

Para crear un participante agente humano, llama al método create en el recurso Participant.

Antes de usar los datos de la solicitud, haz las siguientes sustituciones:

  • PROJECT_ID: tu ID de proyecto de Cloud
  • LOCATION_ID: tu ID de ubicación
  • CONVERSATION_ID: tu ID de conversación

Método HTTP y URL:

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

Cuerpo JSON de la solicitud:

{
  "role": "HUMAN_AGENT",
}

Para enviar tu solicitud, despliega una de estas opciones:

Deberías recibir una respuesta JSON similar a la siguiente:

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

El segmento de ruta después de participants contiene el nuevo ID de participante del agente humano.

Python

Para autenticarte en Agent Assist, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo 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

Añadir y analizar un mensaje del agente humano

Cada vez que uno de los participantes escriba un mensaje en la conversación, deberá enviar ese mensaje a la API para que lo procese. Agent Assist basa sus sugerencias en el análisis de los mensajes de los agentes humanos y los usuarios finales. En el siguiente ejemplo, el agente humano inicia la conversación preguntando "¿En qué puedo ayudarte?". Aún no se ha devuelto ninguna sugerencia en la respuesta.

REST

Para añadir y analizar un mensaje de agente humano en la conversación, llama al método analyzeContent en el recurso Participant.

Antes de usar los datos de la solicitud, haz las siguientes sustituciones:

  • PROJECT_ID: tu ID de proyecto de GCP
  • CONVERSATION_ID: tu ID de conversación
  • PARTICIPANT_ID: tu ID de participante humano

Método HTTP y URL:

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

Cuerpo JSON de la solicitud:

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

Para enviar tu solicitud, despliega una de estas opciones:

Deberías recibir una respuesta JSON similar a la siguiente:

      {
        "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 autenticarte en Agent Assist, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo 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

Añadir un mensaje del usuario final y obtener sugerencias

En respuesta al agente, el usuario final pregunta "¿Cómo me registro?". La respuesta contiene una lista de respuestas sugeridas a la pregunta del usuario final, así como una puntuación de confianza para cada una. Todas las respuestas se han extraído del documento de conocimientos de las preguntas frecuentes que hemos añadido anteriormente en este tutorial. El umbral de confianza hace referencia al nivel de confianza del modelo de que cada sugerencia de preguntas frecuentes es relevante para la solicitud del agente. Cuanto mayor sea el valor de confianza, más probabilidades habrá de que se devuelvan respuestas relevantes, pero puede que se devuelvan menos respuestas o ninguna si ninguna de las opciones disponibles cumple el umbral alto. Te recomendamos que empieces con un valor de puntuación de confianza de 0,4. Puedes ajustar este valor más adelante para mejorar los resultados si es necesario.

La respuesta también incluye el source de la respuesta, el documento de conocimientos del que procede la respuesta. Debes proporcionar las respuestas sugeridas a tu agente humano, que puede decidir si facilita esta información al usuario final.

REST

Para añadir y analizar un mensaje de usuario final de la conversación, llama al método analyzeContent del recurso Participant.

Antes de usar los datos de la solicitud, haz las siguientes sustituciones:

  • PROJECT_ID: tu ID de proyecto de GCP
  • CONVERSATION_ID: tu ID de conversación
  • PARTICIPANT_ID: tu ID de participante de usuario final

Método HTTP y URL:

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

Cuerpo JSON de la solicitud:

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

Para enviar tu solicitud, despliega una de estas opciones:

Deberías recibir una respuesta JSON similar a la siguiente:

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

Para autenticarte en Agent Assist, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo 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

Completar la conversación

Cuando finalice la conversación, usa la API para completarla.

REST

Para completar la conversación, llama al método complete del recurso conversations.

Antes de usar los datos de la solicitud, haz las siguientes sustituciones:

  • PROJECT_ID: tu ID de proyecto de GCP
  • CONVERSATION_ID: el ID que recibiste al crear la conversación

Método HTTP y URL:

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

Para enviar tu solicitud, despliega una de estas opciones:

Deberías recibir una respuesta JSON similar a la siguiente:

{
  "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 autenticarte en Agent Assist, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo 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

Opciones de solicitud a la API

En las secciones anteriores se muestra cómo crear un ConversationProfile para recibir sugerencias. En las siguientes secciones se describen algunas funciones opcionales que puedes implementar durante una conversación.

Notificaciones de sugerencias de Pub/Sub

En las secciones anteriores, se ha creado el ConversationProfile solo con un asistente de agente humano. Durante la conversación, tenías que llamar a la API para recibir sugerencias después de añadir cada mensaje a la conversación. Si prefieres recibir eventos de notificación de sugerencias, puedes definir el campo notificationConfig al crear el perfil de conversación. Esta opción usa Cloud Pub/Sub para enviar notificaciones de sugerencias a tu aplicación a medida que avanza la conversación y hay nuevas sugerencias disponibles.