Text Moderation 2.0 PLUS SDK

更新时间:
复制 MD 格式

This topic explains how to integrate the Text Moderation Enhanced PLUS service SDK.

Step 1: Activate the service

Visit the Activate Service page to activate the Text Moderation Enhanced service.

After you activate the Text Moderation Enhanced service, the default billing method is pay-as-you-go. You are charged daily for your usage. If you do not use the service, you are not charged. The system automatically bills you for your usage after you start using the API. You can also purchase a resource plan. Resource plans offer tiered discounts compared to pay-as-you-go and are ideal for users with predictable and high usage.

Step 2: Grant RAM user permissions

Before you integrate the SDK or call an API, you must grant permissions to a RAM user. You can create an AccessKey for your Alibaba Cloud account or a RAM user. Use an AccessKey to verify your identity when you call Alibaba Cloud APIs. For more information, see Obtain an AccessKey.

Grant permissions to a RAM user

  1. Log on to the RAM console using your Alibaba Cloud account.

  2. Create a RAM user. For details, see Create a RAM user.

  3. Grant the AliyunYundunGreenWebFullAccess system policy to the RAM user. This policy grants full access to Content Moderation. For details, see Manage RAM user permissions.

    The RAM user can now call the Content Moderation API.

Step 3: Integrate the SDK

The following regions are supported:

Region

Public endpoint

VPC endpoint

Services

China (Shanghai)

green-cip.cn-shanghai.aliyuncs.com

green-cip-vpc.cn-shanghai.aliyuncs.com

ugc_moderation_byllm, ugc_moderation_byllm_pro, nickname_detection_pro, chat_detection_pro, comment_detection_pro, ad_compliance_detection_pro, text_aigc_detector, ugc_moderation_byllm_ec

China (Beijing)

green-cip.cn-beijing.aliyuncs.com

green-cip-vpc.cn-beijing.aliyuncs.com

China (Hangzhou)

green-cip.cn-hangzhou.aliyuncs.com

green-cip-vpc.cn-hangzhou.aliyuncs.com

China (Shenzhen)

green-cip.cn-shenzhen.aliyuncs.com

green-cip-vpc.cn-shenzhen.aliyuncs.com

China (Chengdu)

green-cip.cn-chengdu.aliyuncs.com

Not available

China (Hong Kong)

green-cip.cn-hongkong.aliyuncs.com

green-cip-vpc.cn-hongkong.aliyuncs.com

ugc_moderation_byllm_cb

Singapore

green-cip.ap-southeast-1.aliyuncs.com

green-cip-vpc.ap-southeast-1.aliyuncs.com

ugc_moderation_byllm_cb, comment_multilingual_pro_cb

UK (London)

green-cip.eu-west-1.aliyuncs.com

Not available

US (Virginia)

green-cip.us-east-1.aliyuncs.com

green-cip-vpc.us-east-1.aliyuncs.com

US (Silicon Valley)

green-cip.us-west-1.aliyuncs.com

Not available

Germany (Frankfurt)

green-cip.eu-central-1.aliyuncs.com

green-cip-vpc.eu-central-1.aliyuncs.com

Note

To get SDK sample code in various programming languages, use the OpenAPI Explorer online debugging tool. It automatically generates sample code for an API as you debug it.

Alibaba Cloud SDKs create default credentials by reading the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables. When you call an API operation, the program reads your AccessKey from these variables and automatically completes authentication. Before you use SDK sample code, you must configure the environment variables. For more information, see Configure authentication credentials.

The SDK is available in two versions. We recommend integrating the PLUS service described on this page. If you previously integrated the general service, see Text Moderation Enhanced 2.0 General Service SDK and Integration Guide.

Text moderation 2.0 PLUS

This SDK supports the following API operations: Text Moderation 2.0 PLUS service, text moderation service built on LLM capabilities, Text Moderation 2.0 PLUS service for large language models, and Text Moderation 2.0 multilingual PLUS service.

Java SDK

Supports Java 1.8 and later.

For the source code, see Java SDK source code or Java SDK source code (OSS path).

To use the SDK in your Maven project, add the following dependency to the pom.xml file.

1. Add the following dependency to the dependencies section.

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>green20220302</artifactId>
    <version>3.3.3</version>
</dependency>

2. The following is a Java SDK code sample.

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.TextModerationPlusRequest;
import com.aliyun.green20220302.models.TextModerationPlusResponse;
import com.aliyun.green20220302.models.TextModerationPlusResponseBody;
import com.aliyun.teaopenapi.models.Config;


public class TextModerationPlusDemo {

    public static void main(String[] args) throws Exception {
        Config config = new Config();
        /**
         * Using an AccessKey pair from your Alibaba Cloud account is a high-risk operation because it grants full permissions to all APIs.
         * To prevent security risks from AccessKey leaks, do not hard-code the AccessKey ID and AccessKey Secret in your code.
         * We recommend that you use a RAM user for API access or routine O&M.
         * Common methods for obtaining environment variables:
         * Method 1:
         *     Obtain the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
         *     Obtain the AccessKey Secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
         * Method 2:
         *     Obtain the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
         *     Obtain the AccessKey Secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
         */
        config.setAccessKeyId("

Python SDK

Supports Python 3.6 and later.

For the source code, see Python SDK source code.

1. Run the following command to install the dependency.

pip install alibabacloud_green20220302==3.2.4

2. The following is a Python SDK code sample.

# coding=utf-8
# python version >= 3.6
from alibabacloud_green20220302.client import Client
from alibabacloud_green20220302 import models
from alibabacloud_tea_openapi.models import Config
import json

config = Config(
    # Using an AccessKey pair from your Alibaba Cloud account is a high-risk operation because it grants full permissions to all APIs.
    # To prevent security risks from AccessKey leaks, do not hard-code the AccessKey ID and AccessKey Secret in your code.
    # We recommend that you obtain credentials from environment variables. For example:
    # Obtain the AccessKey ID of the RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
    # Obtain the AccessKey Secret of the RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
    access_key_id='

PHP SDK

Supports PHP 5.6 and later.

For the source code, see PHP SDK source code.

1. Run the following command to install the dependency.

composer require alibabacloud/green-20220302 3.2.4

2. Code sample for the PHP SDK.

<?php
require('vendor/autoload.php');

use AlibabaCloud\SDK\Green\V20220302\Models\TextModerationPlusRequest;
use AlibabaCloud\Tea\Exception\TeaUnableRetryError;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\SDK\Green\V20220302\Green;

$config = new Config([
    /**
     * Using an AccessKey pair from your Alibaba Cloud account is a high-risk operation because it grants full permissions to all APIs.
     * To prevent security risks from AccessKey leaks, do not hard-code the AccessKey ID and AccessKey Secret in your code.
     * We recommend that you obtain credentials from environment variables. For example:
     * Obtain the AccessKey ID of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
     * Obtain the AccessKey Secret of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
     */
    "accessKeyId" => '

Go SDK

1. Run the following command to install the dependency.

go get github.com/alibabacloud-go/green-20220302/v3

2. Code sample for the Go SDK.

package main

import (
	"encoding/json"
	"fmt"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	green20220302 "github.com/alibabacloud-go/green-20220302/v3/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"net/http"
)

func main() {
	// Hard-coding an AccessKey pair in your code poses a security risk from potential AccessKey leaks. We recommend that you use a more secure method, such as STS, for authentication.
	config := &openapi.Config{
		/**
		 * Using an AccessKey pair from your Alibaba Cloud account is a high-risk operation because it grants full permissions to all APIs.
		 * To prevent security risks from AccessKey leaks, do not hard-code the AccessKey ID and AccessKey Secret in your code.
		 * We recommend that you obtain credentials from environment variables. For example:
		 * Obtain the AccessKey ID of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
		 * Obtain the AccessKey Secret of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
		 */
		AccessKeyId: tea.String("

Node.js SDK

For the source code, see Node.js SDK source code.

1. Run the following command to install the dependency.

npm install @alicloud/green20220302@3.2.4

2. Code sample for the Node.js SDK.

const Green20220302 = require('@alicloud/green20220302');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
// Note: To improve performance and avoid creating a new connection for each request, reuse the client object.
// Hard-coding an AccessKey pair in your code poses a security risk from potential AccessKey leaks.
class Client {
    static createClient() {
        const config = new OpenApi.Config({
            // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in your runtime environment.
            accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
            // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in your runtime environment.
            accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
            endpoint: `green-cip.cn-shanghai.aliyuncs.com`,
        });
        return new Green20220302.default(config);
    }

    static async main() {
        const client = Client.createClient();
        // Construct the request object.
        const textModerationPlusRequest = new Green20220302.TextModerationPlusRequest({
            // The service for Text Moderation 2.0 PLUS. For more information, see https://help.aliyun.com/document_detail/2684669.html#p-t7m-66g-cv6.
            "service": "comment_detection_pro",
            "serviceParameters": JSON.stringify({
                // The text to be moderated. 
                "content": "Test text"})
            });
        // Create the runtime configuration object.
        const runtime = new Util.RuntimeOptions();
        try {
            // Send the request and obtain the response.
            const response = await client.textModerationPlusWithOptions(textModerationPlusRequest, runtime);
            console.log(JSON.stringify(response.body));
        } catch (error) {
            // This is for demonstration purposes only. In production, handle exceptions with caution and do not ignore them.
            // error message
            console.log('Error occurred:', error.message);
        }
    }
}

Client.main();

C# SDK

For the source code, see C# SDK source code.

1. Run the following command to install the dependency.

dotnet add package AlibabaCloud.SDK.Green20220302 --version 3.2.4

2. Code sample for the C# SDK.

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

using Newtonsoft.Json;

namespace AlibabaCloud.SDK.Green20220302
{
    public class TextModerationPlusAutoRoute
    {
        public static void Main(string[] args)
        {
            /**
            * Using an AccessKey pair from your Alibaba Cloud account is a high-risk operation because it grants full permissions to all APIs.
            * To prevent security risks from AccessKey leaks, do not hard-code the AccessKey ID and AccessKey Secret in your code.
            * We recommend that you obtain credentials from environment variables. For example:
            * Obtain the AccessKey ID of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
            * Obtain the AccessKey Secret of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
            */
            String accessKeyId = "

Native HTTPS calls

The Content Moderation 2.0 API service also supports native HTTPS calls. This method requires you to handle request signing and assembly (including the URL, body, headers, and parameters) yourself. Use native HTTPS calls only in the following scenarios. In all other cases, we recommend using an SDK.

  1. Your application has strict client-size limits.

  2. Your application has dependency library requirements that conflict with the SDK.

  • Calling conventions

    Service endpoint: https://green-cip.{region}.aliyuncs.com

    Protocol: HTTPS

    Method: POST

  • Common request parameters

    The request parameters for a Text Moderation 2.0 API operation include common request parameters and operation-specific request parameters. Common request parameters are used in all API operations. The following table describes the common request parameters.

    Parameter

    Type

    Required

    Description

    Format

    String

    Yes

    The format of the response. Valid values:

    • JSON (default)

    • XML

    Version

    String

    Yes

    The version of the API operation. The version is in the YYYY-MM-DD format. The version of this API operation is 2022-03-02.

    AccessKeyId

    String

    Yes

    The AccessKey ID that Alibaba Cloud issues to you for service access.

    Signature

    String

    Yes

    The signature string. For information about how to calculate a signature, see the "Signature method" section below.

    SignatureMethod

    String

    Yes

    The signature method. Only HMAC-SHA1 is supported.

    Timestamp

    String

    Yes

    The timestamp of the request. The timestamp must follow the ISO 8601 standard and be in UTC. The format is yyyy-MM-ddTHH:mm:ssZ. For example, 2022-12-12T01:13:14Z represents 09:13:14 on December 12, 2022 (UTC+8).

    SignatureVersion

    String

    Yes

    The version of the signature algorithm. Set the value to 1.0.

    SignatureNonce

    String

    Yes

    A unique random number (nonce) to prevent replay attacks. A new nonce must be used for each request.

    Action

    String

    Yes

    • The API operation for the Text Moderation 2.0 PLUS service: TextModerationPlus

  • Common response parameters

    Each API request returns a unique request ID (RequestId), regardless of whether the request is successful. Other response parameters include Label and Confidence. Different services return different parameters. For more information, see the documentation for the specific service.

  • Code samples

    The following response samples are formatted for readability. The actual responses are not formatted with line breaks or indentation.

    The following code provides a request sample for Text Moderation 2.0-User Nickname Detection_Professional Edition. For other API operations, see the documentation for the specific operation to obtain business request parameters.

    https://green-cip.cn-shanghai.aliyuncs.com/
        ?Format=JSON
        &Version=2022-03-02
        &Signature=vpEEL0zFHfxXYzSFV0n7%2FZiFL9o%3D
        &SignatureMethod=Hmac-SHA1
        &SignatureNonce=15215528852396
        &SignatureVersion=1.0
        &Action=TextModerationPlus
        &AccessKeyId=123****cip
        &Timestamp=2022-12-12T12:00:00Z
        &Service=nickname_detection_pro
        &ServiceParameters={"content": "Test text"}

    The following code provides a JSON response sample for Text Moderation 2.0-User Nickname Detection_Professional Edition:

    {
        "Code": 200,
        "Data": {
            "Result": [
                {
                    "Label": "political_entity",
                    "Description":"Suspected political entity",
                    "Confidence": 100.0,
                    "RiskWords": "Word A,Word B,Word C"
                },
                {
                    "Label": "political_figure",
                    "Description":"Suspected political figure",
                    "Confidence": 100.0,
                    "RiskWords": "Word A,Word B,Word C"
                }
            ],
            "RiskLevel": "high"
        },
        "Message": "OK",
        "RequestId": "AAAAAA-BBBB-CCCCC-DDDD-EEEEEEEE****"
    }
  • Signature method

    The Text Moderation 2.0 service authenticates each request. Therefore, you must include signature information in each request. The Text Moderation 2.0 service uses an AccessKey ID and an AccessKey Secret to perform symmetric encryption and verify the identity of the request sender.

    An AccessKey ID and an AccessKey Secret are issued by Alibaba Cloud. You can apply for and manage them on the Alibaba Cloud website. The AccessKey ID is used to identify a user. The AccessKey Secret is a key that is used to encrypt the signature string and to verify the signature string on the server. You must keep your AccessKey Secret confidential.

    To sign a request, follow these steps:

    1. Construct a canonicalized query string.

      1. Sort all request parameters (both common and operation-specific) alphabetically by name, excluding the Signature parameter.

      2. URL-encode the names and values of the request parameters in UTF-8.

        Note

        Most URL encoding libraries, such as java.net.URLEncoder in Java, encode strings based on the application/x-www-form-urlencoded MIME type rules. You can use this method for encoding and then replace plus signs (+) with %20, asterisks (*) with %2A, and %7E with tildes (~) to obtain the required encoded string.

        The URL encoding rules are as follows:

        • Do not encode uppercase letters (A-Z), lowercase letters (a-z), digits (0-9), and the following characters: hyphen (-), underscore (_), period (.), and tilde (~).

        • Other characters are encoded in the format %XY, where XY is the hexadecimal representation of the character's ASCII code. For example, the English double quotation mark (") is encoded as %22.

        • Extended UTF-8 characters are encoded as %XY%ZA….

        • Note that a space character ( ) must be encoded as %20, not a plus sign (+).

      3. Connect each encoded parameter name to its encoded value with an equal sign (=).

      4. Concatenate the resulting name-value pairs with ampersands (&) in the order of the sorted parameter names to obtain the canonicalized query string.

    2. Use the canonicalized query string from the previous step to construct the string-to-sign based on the following rules:

      StringToSign=
      HTTPMethod + "&" +
      percentEncode("/") + "&" +
      percentEncode(CanonicalizedQueryString)
      Note

      HTTPMethod is the HTTP method used to submit the request, such as POST. percentEncode(/) is the value obtained by encoding the / character according to the URL encoding rules described in section a.ii, that is, %2F. percentEncode(CanonicalizedQueryString) is the string obtained by encoding the canonicalized query string that is constructed in section a.i according to the URL encoding rules described in section a.ii.

    3. Calculate the HMAC value of the string-to-sign as defined in RFC 2104.

      Note

      Note that the key used to calculate the signature is your AccessKey Secret followed by an& character (ASCII:38), and the hashing algorithm is SHA1.

    4. Base64-encode the HMAC value to obtain the signature.

    5. Add the resulting signature to the request as the Signature parameter.

      Note

      When you submit the signature to the Content Moderation server, you must URL-encode it along with other parameters in accordance with RFC 3986.

For support, join our DingTalk group (group number: 35573806) to consult with our product technical experts.