Impostare un TTL (time-to-live) per i dati delle conversazioni

Panoramica

Esistono due modi per impostare la scadenza di una conversazione in CX Insights: utilizzando il campo expire_time o il campo ttl. Puoi utilizzare il campo expire_time per impostare un timestamp che indica quando scadrà la conversazione oppure il campo ttl per impostare una durata (in secondi) fino alla scadenza della conversazione. Se una conversazione ha sia un valore expire_time che ttl, CX Insights utilizza il valore expire_time.

Le conversazioni impostate per scadere utilizzando il campo expire_time o ttl verranno eliminate 24 ore dopo il raggiungimento del periodo di scadenza specificato. Per tutti i dettagli, consulta la documentazione della risorsa Conversazione. Questa pagina mostra come impostare un TTL sia per le singole conversazioni sia per tutte le conversazioni in un determinato progetto.

Se una conversazione non è impostata per scadere, rimarrà in CX Insights a tempo indeterminato, anche se le conversazioni possono sempre essere eliminate manualmente.

Crea una conversazione con un valore TTL

Il seguente esempio mostra come impostare un valore TTL per una singola conversazione appena creata utilizzando il campo ttl in una risorsa Conversation.

REST

Prima di utilizzare i dati della richiesta, apporta le sostituzioni seguenti:

  • PROJECT_ID: il tuo ID progetto Google Cloud .
  • TRANSCRIPT_URI: l'URI Cloud Storage che punta a un file contenente la trascrizione della conversazione.
  • MEDIUM: imposta su PHONE_CALL o CHAT a seconda del tipo di dati. Se non specificato, il valore predefinito è PHONE_CALL.
  • SECONDS: il time-to-live (tempo fino alla scadenza della conversazione) in secondi e frazioni di secondo.

Metodo HTTP e URL:

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

Corpo JSON della richiesta:

{
  "data_source": {
    "gcs_source": {
      "transcript_uri": "TRANSCRIPT_URI"
    }
  },
  "medium": "MEDIUM",
  "ttl": {
    "seconds": "SECONDS"
  }
}

Per inviare la richiesta, espandi una di queste opzioni:

Dovresti ricevere una risposta JSON simile alla seguente:

{
  "name": "projects/PROJECT_ID/locations/us-central1/conversations/CONVERSATION_ID",
  "dataSource": {
    "gcsSource": {
      "transcriptUri": "gs://cloud-samples-data/ccai/chat_sample.json"
    }
  },
  "createTime": "2021-01-20T10:10:10.123000Z",
  "transcript": {
    "transcriptSegments": [
      ...
      {
        "text": "Thanks for confirming",
        "words": [
          {
            "word": "Thanks"
          },
          {
            "word": "for"
          },
          {
            "word": "confirming"
          }
        ],
        "languageCode": "en-US",
        "channelTag": 2,
        "messageTime": "2021-01-10T10:10:15.123000Z",
        "segmentParticipant": {
          "role": "HUMAN_AGENT",
          "userId": "555"
        }
      },
      ...
    ]
  },
  "medium": "CHAT",
  "duration": "5.00s",
  "turnCount": 10,
  "startTime": "2021-01-10T10:10:10.123000Z"
  "expireTime":"2021-01-21T10:10:10.123000Z",
}

Python

Per eseguire l'autenticazione in CX Insights, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

from google.cloud import contact_center_insights_v1
from google.protobuf import duration_pb2


def create_conversation_with_ttl(
    project_id: str,
    transcript_uri: str = "gs://cloud-samples-data/ccai/chat_sample.json",
    audio_uri: str = "gs://cloud-samples-data/ccai/voice_6912.txt",
) -> contact_center_insights_v1.Conversation:
    """Creates a conversation with a TTL value.

    Args:
        project_id:
            The project identifier. For example, 'my-project'.
        transcript_uri:
            The Cloud Storage URI that points to a file that contains the
            conversation transcript. Format is 'gs://{bucket_name}/{file.json}'.
            For example, 'gs://cloud-samples-data/ccai/chat_sample.json'.
        audio_uri:
            The Cloud Storage URI that points to a file that contains the
            conversation audio. Format is 'gs://{bucket_name}/{file.json}'.
            For example, 'gs://cloud-samples-data/ccai/voice_6912.txt'.

    Returns:
        A conversation.
    """
    # Construct a parent resource.
    parent = (
        contact_center_insights_v1.ContactCenterInsightsClient.common_location_path(
            project_id, "us-central1"
        )
    )

    # Construct a conversation.
    conversation = contact_center_insights_v1.Conversation()
    conversation.data_source.gcs_source.transcript_uri = transcript_uri
    conversation.data_source.gcs_source.audio_uri = audio_uri
    conversation.medium = contact_center_insights_v1.Conversation.Medium.CHAT

    # Construct a TTL.
    ttl = duration_pb2.Duration()
    ttl.seconds = 86400
    conversation.ttl = ttl

    # Call the Insights client to create a conversation.
    insights_client = contact_center_insights_v1.ContactCenterInsightsClient()
    conversation = insights_client.create_conversation(
        parent=parent, conversation=conversation
    )

    print(f"Created {conversation.name}")
    return conversation

Java

Per eseguire l'autenticazione in CX Insights, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configura l'autenticazione per un ambiente di sviluppo locale.


import com.google.cloud.contactcenterinsights.v1.ContactCenterInsightsClient;
import com.google.cloud.contactcenterinsights.v1.Conversation;
import com.google.cloud.contactcenterinsights.v1.ConversationDataSource;
import com.google.cloud.contactcenterinsights.v1.CreateConversationRequest;
import com.google.cloud.contactcenterinsights.v1.GcsSource;
import com.google.cloud.contactcenterinsights.v1.LocationName;
import com.google.protobuf.Duration;
import java.io.IOException;

public class CreateConversationWithTtl {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my_project_id";
    String transcriptUri = "gs://cloud-samples-data/ccai/chat_sample.json";
    String audioUri = "gs://cloud-samples-data/ccai/voice_6912.txt";

    createConversationWithTtl(projectId, transcriptUri, audioUri);
  }

  public static Conversation createConversationWithTtl(
      String projectId, String transcriptUri, String audioUri) throws 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 a parent resource.
      LocationName parent = LocationName.of(projectId, "us-central1");

      // Construct a conversation.
      Conversation conversation =
          Conversation.newBuilder()
              .setDataSource(
                  ConversationDataSource.newBuilder()
                      .setGcsSource(
                          GcsSource.newBuilder()
                              .setTranscriptUri(transcriptUri)
                              .setAudioUri(audioUri)
                              .build())
                      .build())
              .setMedium(Conversation.Medium.CHAT)
              .setTtl(Duration.newBuilder().setSeconds(86400).build())
              .build();

      // Construct a request.
      CreateConversationRequest request =
          CreateConversationRequest.newBuilder()
              .setParent(parent.toString())
              .setConversation(conversation)
              .build();

      // Call the Insights client to create a conversation.
      Conversation response = client.createConversation(request);
      System.out.printf("Created %s%n", response.getName());
      return response;
    }
  }
}

Node.js

Per eseguire l'autenticazione in CX Insights, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'my_project_id';
// const transcriptUri = 'gs://cloud-samples-data/ccai/chat_sample.json';
// const audioUri = 'gs://cloud-samples-data/ccai/voice_6912.txt';

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

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

async function createConversationWithTtl() {
  const [conversation] = await client.createConversation({
    parent: client.locationPath(projectId, 'us-central1'),
    conversation: {
      dataSource: {
        gcsSource: {
          transcriptUri: transcriptUri,
          audioUri: audioUri,
        },
      },
      medium: 'CHAT',
      ttl: {
        seconds: 86400,
      },
    },
  });
  console.info(`Created ${conversation.name}`);
}
createConversationWithTtl();

Impostare un TTL a livello di progetto per tutte le conversazioni in arrivo

Il seguente esempio di codice mostra come impostare un TTL a livello di progetto utilizzando il campo conversation_ttl in una risorsa Settings. Questo TTL verrà applicato a tutte le conversazioni in arrivo che non specificano un tempo di scadenza separato o un valore TTL diverso.

REST

Prima di utilizzare i dati della richiesta, apporta le sostituzioni seguenti:

  • PROJECT_ID: il tuo ID progetto Google Cloud .
  • SECONDS: il time-to-live (tempo fino alla scadenza della conversazione) in secondi e frazioni di secondo.

Metodo HTTP e URL:

POST https://contactcenterinsights.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/settings?updateMask=conversation_ttl

Corpo JSON della richiesta:

{
  "conversation_ttl": {
    "seconds": "SECONDS"
  }
}

Per inviare la richiesta, espandi una di queste opzioni:

Dovresti ricevere una risposta JSON simile alla seguente:

{
  "name": "projects/$PROJECT/locations/us-central1/settings",
  "createTime": "2021-01-20T10:10:10.123000Z",
  "updateTime": "2021-01-20T11:11:11.456000Z",
  "conversationTtl": "86400s"
}

Python

Per eseguire l'autenticazione in CX Insights, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

from google.api_core import protobuf_helpers
from google.cloud import contact_center_insights_v1
from google.protobuf import duration_pb2


def set_project_ttl(project_id: str) -> None:
    """Sets a project-level TTL for all incoming conversations.

    Args:
        project_id:
            The project identifier. For example, 'my-project'.

    Returns:
        None.
    """
    # Construct a settings resource.
    settings = contact_center_insights_v1.Settings()
    settings.name = (
        contact_center_insights_v1.ContactCenterInsightsClient.settings_path(
            project_id, "us-central1"
        )
    )

    conversation_ttl = duration_pb2.Duration()
    conversation_ttl.seconds = 86400
    settings.conversation_ttl = conversation_ttl

    # Construct an update mask to only update the fields that are set on the settings resource.
    update_mask = protobuf_helpers.field_mask(None, type(settings).pb(settings))

    # Construct an Insights client that will authenticate via Application Default Credentials.
    # See authentication details at https://cloud.google.com/docs/authentication/production.
    insights_client = contact_center_insights_v1.ContactCenterInsightsClient()

    # Call the Insights client to set a project-level TTL.
    insights_client.update_settings(settings=settings, update_mask=update_mask)

    # Call the Insights client to get the project-level TTL to confirm that it was set.
    new_conversation_ttl = insights_client.get_settings(
        name=settings.name
    ).conversation_ttl
    print(
        "Set TTL for all incoming conversations to {} day".format(
            new_conversation_ttl.days
        )
    )

Java

Per eseguire l'autenticazione in CX Insights, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configura l'autenticazione per un ambiente di sviluppo locale.


import com.google.cloud.contactcenterinsights.v1.ContactCenterInsightsClient;
import com.google.cloud.contactcenterinsights.v1.Settings;
import com.google.cloud.contactcenterinsights.v1.SettingsName;
import com.google.protobuf.Duration;
import com.google.protobuf.FieldMask;
import java.io.IOException;

public class SetProjectTtl {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace this variable before running the sample.
    String projectId = "my_project_id";

    setProjectTtl(projectId);
  }

  public static void setProjectTtl(String projectId) throws 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 a settings resource.
      SettingsName name = SettingsName.of(projectId, "us-central1");
      Settings settings =
          Settings.newBuilder()
              .setName(name.toString())
              .setConversationTtl(Duration.newBuilder().setSeconds(86400).build())
              .build();

      // Construct an update mask.
      FieldMask updateMask = FieldMask.newBuilder().addPaths("conversation_ttl").build();

      // Call the Insights client to set a project-level TTL.
      Settings response = client.updateSettings(settings, updateMask);
      System.out.printf("Set TTL for all incoming conversations to 1 day");
    }
  }
}

Node.js

Per eseguire l'autenticazione in CX Insights, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const projectId = 'my_project_id';

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

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

async function setProjectTtl() {
  await client.updateSettings({
    settings: {
      name: client.settingsPath(projectId, 'us-central1'),
      conversationTtl: {
        seconds: 86400,
      },
    },
    updateMask: {
      paths: ['conversation_ttl'],
    },
  });
  console.info('Set TTL for all incoming conversations to 1 day');
}
setProjectTtl();