Call CCAI conversation analysis by task type

Updated at:

This document explains how to install and use the Java SDK for the Contact Center AI-Conversation Analysis AIO Application and outlines important precautions.

Prerequisites

Get workspaceId and appId

workspaceId

image
  1. Go to the Workspaces page.
  2. In the workspace list, find the Workspace ID. This value corresponds to the workspaceId parameter.

appId

image
  1. Go to the Marketplace page and click View Details for the Contact Center AI-Conversation Analysis AIO Application.
  2. Click My Applications at the top of the page to display a list of application cards.
  3. The App ID on each card corresponds to the appId parameter.

Install the SDK

Sync Java

<dependency>

<groupId>com.aliyun</groupId>

<artifactId>contactcenterai20240603</artifactId>

<version>3.6.4</version>

</dependency>

Async Java

<dependency>

<groupId>com.aliyun</groupId>

<artifactId>alibabacloud-contactcenterai20240603</artifactId>

<version>3.0.12</version>

</dependency>

Code examples

NoteTo run the code, replace YOUR_WORKSPACEID with your workspaceId, YOUR_ACCESS_KEY_ID with your AccessKeyID, YOUR_ACCESS_KEY_SECRET with your AccessKeySecret, and YOUR_APPID with your appId. To avoid exposing your access key, we recommend setting AccessKeyID and AccessKeySecret as environment variables.

Asynchronous streaming call

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.core.http.HttpMethod;
import com.aliyun.sdk.gateway.pop.Configuration;
import com.aliyun.sdk.gateway.pop.auth.SignatureAlgorithm;
import com.aliyun.sdk.gateway.pop.auth.SignatureVersion;
import com.aliyun.sdk.service.contactcenterai20240603.AsyncClient;
import com.aliyun.sdk.service.contactcenterai20240603.models.*;
import darabonba.core.RequestConfiguration;
import darabonba.core.ResponseIterable;
import darabonba.core.ResponseIterator;
import darabonba.core.client.ClientOverrideConfiguration;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CcaiPaasTest {

    private static String accessKeyId="YOUR_ACCESS_KEY_ID";
    private static String accessKeySecret="YOUR_ACCESS_KEY_SECRET";
    private static String workspaceId="YOUR_WORKSPACEID";
    private static String appId="YOUR_APPID";

    private static StaticCredentialProvider provider = StaticCredentialProvider.create(
            Credential.builder()
                    .accessKeyId(accessKeyId)
                    .accessKeySecret(accessKeySecret)
                    .build()
    );

    private static AsyncClient client = AsyncClient.builder()
            .region("cn-shanghai")
            .credentialsProvider(provider)
            .serviceConfiguration(Configuration.create()
                    .setSignatureVersion(SignatureVersion.V3)
                    .setSignatureAlgorithmV3(SignatureAlgorithm.ACS3_HMAC_SHA256)
            ).overrideConfiguration(
                    ClientOverrideConfiguration.create()
                            .setProtocol("HTTPS")
                            .setEndpointOverride("contactcenterai.cn-shanghai.aliyuncs.com")
            ).build();

    public static void main(String[] args) throws Exception{

        List<AnalyzeConversationRequest.Sentences>  messageList = new ArrayList<>();
        messageList.add(AnalyzeConversationRequest.Sentences.builder().role("agent").text("Which aspect of social insurance and housing fund would you like to ask about?").build());
        messageList.add(AnalyzeConversationRequest.Sentences.builder().role("user").text("How can I claim my social insurance and housing fund?").build());

        List<String> resultTypes=new ArrayList<>();
        resultTypes.add("summary");

        AnalyzeConversationRequest.Dialogue dialogue=AnalyzeConversationRequest.Dialogue.builder().sessionId("session-01")
                .sentences(messageList).build();

        AnalyzeConversationRequest completionParam = AnalyzeConversationRequest.builder().modelCode("tyxmPlus").resultTypes(resultTypes)
                .workspaceId(workspaceId).appId(appId).dialogue(dialogue).requestConfiguration(RequestConfiguration.create()
                        .setHttpMethod(HttpMethod.POST)).stream(true).build();
        System.out.println(JSON.toJSONString(completionParam));

        ResponseIterable<AnalyzeConversationResponseBody> x = client.analyzeConversationWithResponseIterable(completionParam);
        ResponseIterator<AnalyzeConversationResponseBody> iterator = x.iterator();
        String lastTxt="";
        while (iterator.hasNext()) {
            AnalyzeConversationResponseBody event = iterator.next();
            //System.out.println(event.getText());
            //System.out.println(event.getFinishReason());
            //System.out.println(event.getRequestId());
            lastTxt=event.getText();
        }

        System.out.println("ALL***********************");
        System.out.println(lastTxt);
        System.out.println("Successful request headers:");
        System.out.println(x.getStatusCode());
        System.out.println(x.getHeaders());
    }
}

Synchronous non-streaming call

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.contactcenterai20240603.Client;
import com.aliyun.contactcenterai20240603.models.*;
import com.aliyun.teaopenapi.models.Config;
import java.util.*;

public class CcaiPaasTest {

    public static void main(String[] args) throws Exception{

        String accessKeyId = "YOUR_ACCESS_KEY_ID";
        String accessKeySecret = "YOUR_ACCESS_KEY_SECRET";
        String workspaceId = "YOUR_WORKSPACEID";
        String appId = "YOUR_APPID";

        Config config = new Config();
        config.setAccessKeyId(accessKeyId).setAccessKeySecret(accessKeySecret).setEndpoint("contactcenterai.cn-shanghai.aliyuncs.com")
                .setRegionId("cn-shanghai").setProtocol("HTTPS");

        Client client = new Client(config);
        com.aliyun.contactcenterai20240603.models.AnalyzeConversationRequest request = new com.aliyun.contactcenterai20240603.models.AnalyzeConversationRequest();

        com.aliyun.contactcenterai20240603.models.AnalyzeConversationRequest.AnalyzeConversationRequestDialogue dialogue = new com.aliyun.contactcenterai20240603.models.AnalyzeConversationRequest.AnalyzeConversationRequestDialogue();
        List<com.aliyun.contactcenterai20240603.models.AnalyzeConversationRequest.AnalyzeConversationRequestDialogueSentences> sentenceList = new ArrayList<>();
        com.aliyun.contactcenterai20240603.models.AnalyzeConversationRequest.AnalyzeConversationRequestDialogueSentences sentences1 = new com.aliyun.contactcenterai20240603.models.AnalyzeConversationRequest.AnalyzeConversationRequestDialogueSentences();
        sentences1.setRole("agent");
        sentences1.setText("Which aspect of social insurance and housing fund would you like to ask about?");
        sentenceList.add(sentences1);

        com.aliyun.contactcenterai20240603.models.AnalyzeConversationRequest.AnalyzeConversationRequestDialogueSentences sentences2 = new com.aliyun.contactcenterai20240603.models.AnalyzeConversationRequest.AnalyzeConversationRequestDialogueSentences();
        sentences2.setRole("user");
        sentences2.setText("How do I check my account?");
        sentenceList.add(sentences2);
        dialogue.setSentences(sentenceList);
        dialogue.setSessionId("session-1111");
        request.setDialogue(dialogue);

        request.setSceneName("China Mobile");
        request.setResultTypes(Arrays.asList("summary"));
        request.setStream(false);

        com.aliyun.contactcenterai20240603.models.AnalyzeConversationResponse response = client.analyzeConversation(workspaceId, appId, request);
        System.out.println(JSONObject.toJSONString(response));
    }

}
// Sample code. Replace the placeholders for your Alibaba Cloud AK and SK, and your CCAI workspace ID (workspaceId) and app ID (appId).
// Use this version of tea-utils: go get github.com/alibabacloud-go/tea-utils/v2@v2.0.5-0.20240708091240-f3d7eca052de

// This file is auto-generated, don't edit it. Thanks.
package main

import (
	"fmt"
	"io"
	"os"

	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	openapiutil "github.com/alibabacloud-go/openapi-util/service"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
)

/**
 * API Information
 * @param path params
 * @return OpenApi.Params
 */
func CreateApiInfo() (_result *openapi.Params) {
	params := &openapi.Params{
		// API name
		Action: tea.String("AnalyzeConversation"),
		// API version
		Version: tea.String("2024-06-03"),
		// API protocol
		Protocol: tea.String("HTTPS"),
		// HTTP method
		Method:   tea.String("POST"),
		AuthType: tea.String("AK"),
		Style:    tea.String("ROA"),
		// API path
		Pathname: tea.String("/YOUR_CCAI_WORKSPACEID/ccai/app/YOUR_CCAI_APP_ID/analyze_conversation"),
		// Request body format
		ReqBodyType: tea.String("json"),
		// The response body must be binary, which allows `CallApi` to stream the response for Server-Sent Events (SSE) processing.
		BodyType: tea.String("binary"),
	}
	_result = params
	return _result
}

func _main(args []*string) (_err error) {
	// Leaking source code can expose your access key and compromise the security of all resources in your account. The following code is for reference only.
	// We recommend that you use a more secure method, such as STS. For more information about authentication methods, see https://help.aliyun.com/document_detail/378661.html.
	config := &openapi.Config{
		AccessKeyId:     tea.String("YOUR_ALIYUN_AK"),
		AccessKeySecret: tea.String("YOUR_ALIYUN_SK"),
	}
	config.Endpoint = tea.String("contactcenterai.cn-shanghai.aliyuncs.com")
	client, err := openapi.NewClient(config)
	if err != nil {
		return err
	}

	params := CreateApiInfo()
	// query params
	queries := map[string]interface{}{}
	queries["workspaceId"] = tea.String("YOUR_CCAI_WORKSPACEID")
	queries["appId"] = tea.String("YOUR_CCAI_APP_ID")

	body := map[string]interface{}{
		"dialogue": map[string]interface{}{
			"sentences": []map[string]*string{map[string]*string{
				"role": tea.String("agent"),
				"text": tea.String("Hello. What can I help you with?"),
			}, map[string]*string{
				"role": tea.String("user"),
				"text": tea.String("How do I claim game coins?"),
			}, map[string]*string{
				"role": tea.String("agent"),
				"text": tea.String("Please log in to your account and check whether there are any recommended game coins waiting to be claimed. If so, you will receive a push notification."),
			}, map[string]*string{
				"role": tea.String("user"),
				"text": tea.String("OK, thanks."),
			}},
			"sessionId": "2323",
		},
		"modelCode":   "tyxmPlus",
		"resultTypes": []*string{tea.String("question_solution")},
		"stream":      false,
	}

	// runtime options
	runtime := &util.RuntimeOptions{}
	request := &openapi.OpenApiRequest{
		Query: openapiutil.Query(queries),
		Body:  body,
		//Body:  tea.String("{\n  \"stream\": false,\n  \"modelCode\": \"tyxmPlus\",\n  \"dialogue\": {\n    \"sentences\": [\n      {\n        \"role\": \"user\",\n        \"text\": \"The account owner is cheating with infinite blessings in the Simulated Universe\\nContact: ******\\nImage upload:\\nVideo upload:\\n\"\n      },\n      {\n        \"role\": \"agent\",\n        \"text\": \"Hello, passenger, welcome aboard the Astral Express! Please provide the following information: *Game:\\n*Reported Character UID:\"\n      },\n      {\n        \"role\": \"user\",\n        \"text\": \"Pass ID******\\n\\n2024-06-10 18:25:52 [Player] ***:\\nuid******\\n\"\n      },\n      {\n        \"role\": \"agent\",\n        \"text\": \"We have already recorded and submitted your issue for verification. We will inform you of the result in the service progress or online service. Please pay attention to the relevant notifications. We apologize for the inconvenience.\\n\"\n      },\n      {\n        \"role\": \"agent\",\n        \"text\": \"Your inquiry is complete. A friendly reminder from your service agent: don't forget to use your Trailblaze Power! We wish you wonderful memories on your journey of exploration. We hope you can take a moment to rate our service. Goodbye!\\n\"\n      }\n    ],\n    \"sessionId\": \"ss01\"\n  },\n  \"resultTypes\": [\n    \"question_solution\"\n  ],\n  \"serviceInspection\": {\n    \"inspectionIntroduction\": \"Please check for any inappropriate behavior from the customer service agent, including making excessive promises or deliberately phishing for private customer information.\",\n    \"sceneIntroduction\": \"Insurance sales scenario\",\n    \"inspectionContents\": [\n      {\n        \"title\": \"Did the agent make excessive promises?\",\n        \"content\": \"During the customer interaction, did the agent make promises that exceed the established service standards? For example, if the fastest delivery time is 12 hours, the agent cannot promise a faster delivery.\"\n      }\n    ]\n  },\n  \"fields\": [\n    {\n      \"code\": \"name\",\n      \"name\": \"Name\",\n      \"desc\": \"The user's name\"\n    },\n    {\n      \"code\": \"question\",\n      \"name\": \"Question\",\n      \"desc\": \"The user's question\"\n    }\n  ]\n}"),
	}

	// The return value is a map that contains the response body, headers, and HTTP status code.
	resp, err := client.CallApi(params, request, runtime)
	if err != nil {
		return err
	}

	fmt.Println(resp["headers"])
        fmt.Println(resp["statusCode"])

        // Read the response body as a string.
        events, err := util.ReadAsString(resp["body"].(io.ReadCloser))

        if err != nil {
	    fmt.Printf("Error: %v\n", err)
	    return err
        }

        fmt.Println(tea.StringValue(events))

        return nil
}

func main() {
	err := _main(tea.StringSlice(os.Args[1:]))
	if err != nil {
		panic(err)
	}
}

Asynchronous non-streaming call

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.core.http.HttpMethod;
import com.aliyun.sdk.gateway.pop.Configuration;
import com.aliyun.sdk.gateway.pop.auth.SignatureAlgorithm;
import com.aliyun.sdk.gateway.pop.auth.SignatureVersion;
import com.aliyun.sdk.service.contactcenterai20240603.AsyncClient;
import com.aliyun.sdk.service.contactcenterai20240603.models.*;
import darabonba.core.RequestConfiguration;
import darabonba.core.ResponseIterable;
import darabonba.core.ResponseIterator;
import darabonba.core.client.ClientOverrideConfiguration;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CcaiPaasTest {

    private static String accessKeyId="YOUR_ACCESS_KEY_ID";
    private static String accessKeySecret="YOUR_ACCESS_KEY_SECRET";
    private static String workspaceId="YOUR_WORKSPACEID";
    private static String appId="YOUR_APPID";

    private static StaticCredentialProvider provider = StaticCredentialProvider.create(
            Credential.builder()
                    .accessKeyId(accessKeyId)
                    .accessKeySecret(accessKeySecret)
                    .build()
    );

    private static AsyncClient client = AsyncClient.builder()
            .region("cn-shanghai")
            .credentialsProvider(provider)
            .serviceConfiguration(Configuration.create()
                    .setSignatureVersion(SignatureVersion.V3)
                    .setSignatureAlgorithmV3(SignatureAlgorithm.ACS3_HMAC_SHA256)
            ).overrideConfiguration(
                    ClientOverrideConfiguration.create()
                            .setProtocol("HTTPS")
                            .setEndpointOverride("contactcenterai.cn-shanghai.aliyuncs.com")
            ).build();

    public static void main(String[] args) throws Exception{

        List<AnalyzeConversationRequest.Sentences> messageList = new ArrayList<>();
        messageList.add(AnalyzeConversationRequest.Sentences.builder().role("agent").text("Which aspect of social insurance and housing fund would you like to ask about?").build());
        messageList.add(AnalyzeConversationRequest.Sentences.builder().role("user").text("How do I check my account?").build());

        List<String> resultTypes = new ArrayList<>();
        resultTypes.add("summary");

        AnalyzeConversationRequest.Dialogue dialogue = AnalyzeConversationRequest.Dialogue.builder().sessionId("session-01")
                .sentences(messageList).build();

        AnalyzeConversationRequest completionParam = AnalyzeConversationRequest.builder().modelCode("tyxmPlus").resultTypes(resultTypes)
                .workspaceId(workspaceId).appId(appId).dialogue(dialogue).requestConfiguration(RequestConfiguration.create()
                        .setHttpMethod(HttpMethod.POST)).stream(false).build();
        System.out.println(JSON.toJSONString(completionParam));

        CompletableFuture<AnalyzeConversationResponse> x = client.analyzeConversation(completionParam);
        AnalyzeConversationResponse generateCompletionResponse = x.get(10, TimeUnit.SECONDS);
        System.out.println("ALL***********************");
        System.out.println(JSON.toJSONString(generateCompletionResponse.getBody()));
        System.out.println(generateCompletionResponse.getBody().getText());
        System.out.println(generateCompletionResponse.getBody().getRequestId());

    }
}

Synchronous streaming call

// Sample code. Replace the placeholders for your Alibaba Cloud AK and SK, and your CCAI workspace ID (workspaceId) and app ID (appId).
// Use this version of tea-utils: go get github.com/alibabacloud-go/tea-utils/v2@v2.0.5-0.20240708091240-f3d7eca052de

// This file is auto-generated, don't edit it. Thanks.
package main

import (
	"fmt"
	"io"
	"os"

	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	openapiutil "github.com/alibabacloud-go/openapi-util/service"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
)

/**
 * API Information
 * @param path params
 * @return OpenApi.Params
 */
func CreateApiInfo() (_result *openapi.Params) {
	params := &openapi.Params{
		// API name
		Action: tea.String("AnalyzeConversation"),
		// API version
		Version: tea.String("2024-06-03"),
		// API protocol
		Protocol: tea.String("HTTPS"),
		// HTTP method
		Method:   tea.String("POST"),
		AuthType: tea.String("AK"),
		Style:    tea.String("ROA"),
		// API path
		Pathname: tea.String("/YOUR_CCAI_WORKSPACEID/ccai/app/YOUR_CCAI_APP_ID/analyze_conversation"),
		// Request body format
		ReqBodyType: tea.String("json"),
		// The response body must be binary, which allows `CallApi` to stream the response for Server-Sent Events (SSE) processing.
		BodyType: tea.String("binary"),
	}
	_result = params
	return _result
}

func _main(args []*string) (_err error) {
	// Leaking source code can expose your access key and compromise the security of all resources in your account. The following code is for reference only.
	// We recommend that you use a more secure method, such as STS. For more information about authentication methods, see https://help.aliyun.com/document_detail/378661.html.
	config := &openapi.Config{
		AccessKeyId:     tea.String("YOUR_ALIYUN_AK"),
		AccessKeySecret: tea.String("YOUR_ALIYUN_SK"),
	}
	config.Endpoint = tea.String("contactcenterai.cn-shanghai.aliyuncs.com")
	client, err := openapi.NewClient(config)
	if err != nil {
		return err
	}

	params := CreateApiInfo()
	// query params
	queries := map[string]interface{}{}
	queries["workspaceId"] = tea.String("YOUR_CCAI_WORKSPACEID")
	queries["appId"] = tea.String("YOUR_CCAI_APP_ID")

	body := map[string]interface{}{
		"dialogue": map[string]interface{}{
			"sentences": []map[string]*string{map[string]*string{
				"role": tea.String("agent"),
				"text": tea.String("Hello. What can I help you with?"),
			}, map[string]*string{
				"role": tea.String("user"),
				"text": tea.String("How do I claim game coins?"),
			}, map[string]*string{
				"role": tea.String("agent"),
				"text": tea.String("Please log in to your account and check whether there are any recommended game coins waiting to be claimed. If so, you will receive a push notification."),
			}, map[string]*string{
				"role": tea.String("user"),
				"text": tea.String("OK, thanks."),
			}},
			"sessionId": "2323",
		},
		"modelCode":   "tyxmPlus",
		"resultTypes": []*string{tea.String("question_solution")},
		"stream":      true,
	}

	// runtime options
	runtime := &util.RuntimeOptions{}
	request := &openapi.OpenApiRequest{
		Query: openapiutil.Query(queries),
		Body:  body,
		//Body:  tea.String("{\n  \"stream\": false,\n  \"modelCode\": \"tyxmPlus\",\n  \"dialogue\": {\n    \"sentences\": [\n      {\n        \"role\": \"user\",\n        \"text\": \"The account owner is cheating with infinite blessings in the Simulated Universe\\nContact: ******\\nImage upload:\\nVideo upload:\\n\"\n      },\n      {\n        \"role\": \"agent\",\n        \"text\": \"Hello, passenger, welcome aboard the Astral Express! Please provide the following information: *Game:\\n*Reported Character UID:\"\n      },\n      {\n        \"role\": \"user\",\n        \"text\": \"Pass ID******\\n\\n2024-06-10 18:25:52 [Player] ***:\\nuid******\\n\"\n      },\n      {\n        \"role\": \"agent\",\n        \"text\": \"We have already recorded and submitted your issue for verification. We will inform you of the result in the service progress or online service. Please pay attention to the relevant notifications. We apologize for the inconvenience.\\n\"\n      },\n      {\n        \"role\": \"agent\",\n        \"text\": \"Your inquiry is complete. A friendly reminder from your service agent: don't forget to use your Trailblaze Power! We wish you wonderful memories on your journey of exploration. We hope you can take a moment to rate our service. Goodbye!\\n\"\n      }\n    ],\n    \"sessionId\": \"ss01\"\n  },\n  \"resultTypes\": [\n    \"question_solution\"\n  ],\n  \"serviceInspection\": {\n    \"inspectionIntroduction\": \"Please check for any inappropriate behavior from the customer service agent, including making excessive promises or deliberately phishing for private customer information.\",\n    \"sceneIntroduction\": \"Insurance sales scenario\",\n    \"inspectionContents\": [\n      {\n        \"title\": \"Did the agent make excessive promises?\",\n        \"content\": \"During the customer interaction, did the agent make promises that exceed the established service standards? For example, if the fastest delivery time is 12 hours, the agent cannot promise a faster delivery.\"\n      }\n    ]\n  },\n  \"fields\": [\n    {\n      \"code\": \"name\",\n      \"name\": \"Name\",\n      \"desc\": \"The user's name\"\n    },\n    {\n      \"code\": \"question\",\n      \"name\": \"Question\",\n      \"desc\": \"The user's question\"\n    }\n  ]\n}"),
	}

	// The return value is a map that contains the response body, headers, and HTTP status code.
	resp, err := client.CallApi(params, request, runtime)
	if err != nil {
		return err
	}

	fmt.Println(resp["headers"])
	fmt.Println(resp["statusCode"])

	// Iterate through the Server-Sent Events (SSE).
	eventChan, errChan := util.ReadAsSSE(resp["body"].(io.ReadCloser))
	for {
		select {
		case event, ok := <-eventChan:
			if !ok {
				return nil
			}
			fmt.Println("-------------------------------------")
			fmt.Printf("Event ID: %s, Event name: %s, Data: %s\n", event.ID, event.Event, event.Data)
		case err, ok := <-errChan:
			if ok && err != nil {
				fmt.Printf("Error: %v\n", err)
				return err
			}
		}
	}

}

func main() {
	err := _main(tea.StringSlice(os.Args[1:]))
	if err != nil {
		panic(err)
	}
}