Analyze a conversation using the API

Conversations can be viewed in Conversational Insights after a corresponding conversation object has been created. This how-to guide walks you through the process of analyzing a conversation using the REST API. If preferred, you can also perform these actions using the Insights console.

Prerequisites

  1. Enable the Cloud Storage and Insights APIs on your Google Cloud project.
  2. Import your conversation data.

Chat conversation

  1. Import the conversation's chat transcript as an object in your Cloud Storage bucket.

  2. Make a note of the object path, with the format gs://<bucket>/<object>.

The chat transcript file must be supplied as a JSON-formatted file that matches the CCAI conversation data format.

Voice conversation

  1. Import all the files from a Cloud Storage bucket. Audio and transcript files must be imported as objects in your Cloud Storage bucket.

  2. Make a note of the two object paths, with the format gs://<bucket>/<object>.

The transcript files must be the returned result of a Cloud Speech-to-Text API transcription. Specifically, they must match the response returned from audio recognition, which is identical for synchronous recognition and asynchronous recognition across all Speech-to-Text API versions. Other transcription formats are unsupported and will result in an error during conversation analysis.

Analyze a conversation

Once a Conversation object is created in Insights, it must be analyzed in order to produce useful results. A single conversation can be analyzed many times, and each separate analysis creates a new Analysis object.

An analysis runs a series of annotators against your conversation data and returns the results in the response. By default, the analysis will run all available annotators. Optionally, you can configure the analysis to run specified annotators only.

An analysis is a long-running operation. Calling the CreateAnalysis method creates an Operation object that represents the long-running process. After the operation is complete, the Operation object contains the result. You can poll the Operation object to check for completion.

Create a new analysis

REST

Refer to the conversations.analyses:create API endpoint for complete details.

Before using any of the request data, make the following replacements:

  • PROJECT_ID: your Google Cloud project ID.
  • CONVERSATION_ID: the ID of the conversation you want to analyze. This value was returned in the `createConversation` response.

HTTP method and URL:

POST https://contactcenterinsights.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/conversations/CONVERSATION_ID/analyses

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

{
  "name": "projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID"
}

Python

To authenticate to Insights, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

from google.cloud import contact_center_insights_v1


def create_analysis(conversation_name: str) -> contact_center_insights_v1.Analysis:
    """Creates an analysis.

    Args:
        conversation_name:
            The parent resource of the analysis.
            Format is 'projects/{project_id}/locations/{location_id}/conversations/{conversation_id}'.
            For example, 'projects/my-project/locations/us-central1/conversations/123456789'.

    Returns:
        An analysis.
    """
    # Construct an analysis.
    analysis = contact_center_insights_v1.Analysis()

    # Call the Insights client to create an analysis.
    insights_client = contact_center_insights_v1.ContactCenterInsightsClient()
    analysis_operation = insights_client.create_analysis(
        parent=conversation_name, analysis=analysis
    )
    analysis = analysis_operation.result(timeout=86400)
    print(f"Created {analysis.name}")
    return analysis

Java

To authenticate to Insights, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


import com.google.cloud.contactcenterinsights.v1.Analysis;
import com.google.cloud.contactcenterinsights.v1.ContactCenterInsightsClient;
import java.io.IOException;

public class CreateAnalysis {

  public static void main(String[] args) throws Exception, IOException {
    // TODO(developer): Replace this variable before running the sample.
    String conversationName =
        "projects/my_project_id/locations/us-central1/conversations/my_conversation_id";

    createAnalysis(conversationName);
  }

  public static Analysis createAnalysis(String conversationName) throws Exception, IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (ContactCenterInsightsClient client = ContactCenterInsightsClient.create()) {
      // Construct an analysis.
      Analysis analysis = Analysis.newBuilder().build();

      // Call the Insights client to create an analysis.
      Analysis response = client.createAnalysisAsync(conversationName, analysis).get();
      System.out.printf("Created %s%n", response.getName());
      return response;
    }
  }
}

Node.js

To authenticate to Insights, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const conversationName = 'projects/my_project_id/locations/us-central1/conversations/my_conversation_id';

// Imports the Contact Center Insights client.
const {
  ContactCenterInsightsClient,
} = require('@google-cloud/contact-center-insights');

// Instantiates a client.
const client = new ContactCenterInsightsClient();

async function createAnalysis() {
  const [operation] = await client.createAnalysis({
    parent: conversationName,
  });

  // Wait for the operation to complete.
  const [analysis] = await operation.promise();
  console.info(`Created ${analysis.name}`);
}
createAnalysis();

(Optional) Configure an analysis

REST

Refer to the conversations.analyses:create API endpoint for complete details. Include any annotators that you want to run in the annotatorSelector object and set them to true. Any annotators not included will default to false. If you don't specify any annotators in the annotatorSelector object all annotators will be run.

Before using any of the request data, make the following replacements:

  • PROJECT_ID: your Google Cloud project ID.
  • PHRASE_MATCHER(s): The fully qualified phrase matcher resource names of the phrase matchers you want to use for the phrase matcher annotator. If left empty, all active phrase matchers will run.
  • ISSUE_MODEL(s): The fully qualified resource names of the issue models you want to use for the issue model annotator. Only works if run_issue_model_annotator is true. If left empty, all deployed issue models will run. Currently limited to 1 deployed model.

HTTP method and URL:

POST https://contactcenterinsights.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/conversations/CONVERSATION_ID/analyses

Request JSON body:

{
  "annotatorSelector": {
    "run_interruption_annotator": {true/false},
    "run_silence_annotator": {true/false},
    "run_phrase_matcher_annotator": {true/false},
    "phrase_matchers": PHRASE_MATCHER(s),
    "run_sentiment_annotator": {true/false},
    "run_entity_annotator": {true/false},
    "run_intent_annotator": {true/false},
    "run_issue_model_annotator": {true/false}
    "issue_models": ISSUE_MODEL(s)
  }
}

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

{
  "name": "projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID"
}

Poll the operation

Creating an analysis returns a long-running operation. Long-running methods are asynchronous, and the operation might not be completed when the method returns a response. You can poll the operation to check on its status. See the long-running operations page for details and code samples.