Text moderation 2.0 SDK and integration guide

更新时间:
复制 MD 格式

This guide walks you through activating the text moderation 2.0 service, setting up access permissions, and integrating an SDK to call the TextModeration API operation.

Prerequisites

Before you begin, make sure you have:

  • An Alibaba Cloud account

  • A RAM user with the AliyunYundunGreenWebFullAccess system policy (see Step 2 below)

  • AccessKey ID and AccessKey secret stored as environment variables (see Set up environment variables)

Step 1: Activate the service

Activate the text moderation 2.0 service on the Activate Serviceenhanced version page.

After activation, billing defaults to pay-as-you-go. You are charged daily based on actual usage. The service generates bills automatically based on your API operation usage. If you do not use the service, you are not charged.

Step 2: Grant permissions to a RAM user

To call the Content Moderation API, the RAM user must have the required permissions.

  1. Log on to the RAM console as a RAM administrator.

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

  3. Grant the AliyunYundunGreenWebFullAccess system policy to the RAM user. For details, see Grant permissions to a RAM user.

Set up environment variables

Store your AccessKey pair as environment variables so you do not need to hard-code credentials in your application.

Linux / macOS

export ALIBABA_CLOUD_ACCESS_KEY_ID="<your-access-key-id>"
export ALIBABA_CLOUD_ACCESS_KEY_SECRET="<your-access-key-secret>"

Windows (Command Prompt)

set ALIBABA_CLOUD_ACCESS_KEY_ID=<your-access-key-id>
set ALIBABA_CLOUD_ACCESS_KEY_SECRET=<your-access-key-secret>

Replace <your-access-key-id> and <your-access-key-secret> with the AccessKey ID and AccessKey secret of your RAM user.

Important

Never hard-code your AccessKey pair in source code or commit it to a code repository. Use environment variables or Security Token Service (STS) tokens to pass credentials. For more information, see Configure credentials.

Step 3: Install and integrate the SDK

Supported regions

Region

Public endpoint

VPC endpoint

China (Shanghai)

green-cip.cn-shanghai.aliyuncs.com

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

China (Chengdu)

green-cip.cn-chengdu.aliyuncs.com

N/A

China (Shenzhen)

green-cip.cn-shenzhen.aliyuncs.com

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

China (Hangzhou)

green-cip.cn-hangzhou.aliyuncs.com

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

China (Beijing)

green-cip.cn-beijing.aliyuncs.com

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

Singapore

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

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

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

N/A

UK (London)

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

N/A

For SDK samples in other languages, use OpenAPI Explorer to debug API operations and generate SDK code automatically.

All examples below use environment variables for authentication and call TextModerationWithOptions (or its language equivalent) to submit a synchronous moderation request. The response contains a labels field (the detected content category) and a reason field (the explanation).

Java SDK

Requirements: Java 1.8 or later

Source code: GitHub or Maven Central

1. Add the dependency to your `pom.xml`.

Add the following to the <dependencies> section:

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

2. Call the API.

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.TextModerationRequest;
import com.aliyun.green20220302.models.TextModerationResponse;
import com.aliyun.green20220302.models.TextModerationResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

public class TextAutoRoute {
    public static void main(String[] args) throws Exception {
        Config config = new Config();
        // Read credentials from environment variables.
        config.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
        config.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // Modify the region and endpoint as needed.
        config.setRegionId("ap-southeast-1");
        config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com");
        // Set the connection and read timeout periods (in milliseconds).
        config.setReadTimeout(6000);
        config.setConnectTimeout(3000);

        // Reuse the client instance to avoid creating multiple connections.
        Client client = new Client(config);

        // Set runtime-level timeout periods (in milliseconds).
        RuntimeOptions runtime = new RuntimeOptions();
        runtime.readTimeout = 10000;
        runtime.connectTimeout = 10000;

        // Build the moderation request.
        JSONObject serviceParameters = new JSONObject();
        serviceParameters.put("content", "text to be detected");

        if (serviceParameters.get("content") == null || serviceParameters.getString("content").trim().length() == 0) {
            System.out.println("text moderation content is empty");
            return;
        }

        TextModerationRequest textModerationRequest = new TextModerationRequest();
        // Set the service as needed.
        textModerationRequest.setService("text moderation service");
        textModerationRequest.setServiceParameters(serviceParameters.toJSONString());
        try {
            TextModerationResponse response = client.textModerationWithOptions(textModerationRequest, runtime);

            if (response != null) {
                if (response.getStatusCode() == 200) {
                    TextModerationResponseBody result = response.getBody();
                    System.out.println(JSON.toJSONString(result));
                    Integer code = result.getCode();
                    if (code != null && code == 200) {
                        TextModerationResponseBody.TextModerationResponseBodyData data = result.getData();
                        System.out.println("labels = [" + data.getLabels() + "]");
                        System.out.println("reason = [" + data.getReason() + "]");
                    } else {
                        System.out.println("text moderation not success. code:" + code);
                    }
                } else {
                    System.out.println("response not success. status:" + response.getStatusCode());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Expected output (when the request succeeds and no violations are detected):

{"code":200,"data":{"labels":"","reason":""},"requestId":"...","message":"OK"}
labels = []
reason = []

Python SDK

Requirements: Python 3.6 or later

Source code: PyPI

1. Install the package.

pip install alibabacloud_green20220302==3.2.4

2. Call the API.

Expected output (when the request succeeds and no violations are detected):

response success. result:...
labels:, reason:

PHP SDK

Requirements: PHP 5.6 or later

Source code: Packagist

1. Install the package.

composer require alibabacloud/green-20220302 3.2.4

2. Call the API.

<?php

require('vendor/autoload.php');

use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\SDK\Green\V20220302\Green;
use AlibabaCloud\SDK\Green\V20220302\Models\TextModerationRequest;

$request = new TextModerationRequest();
// Set the service as needed.
$request->service = "text moderation service";
$arr = array('content' => 'text to be detected');
$request->serviceParameters = json_encode($arr);

if (empty($arr) || empty(trim($arr["content"]))) {
    echo "text moderation content is empty";
    return;
}

// Read credentials from environment variables.
$config = new Config([
    "accessKeyId"     => getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    "accessKeySecret" => getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
    // Modify the region and endpoint as needed.
    "endpoint"        => "green-cip.ap-southeast-1.aliyuncs.com",
    "regionId"        => "ap-southeast-1"
]);

// Reuse the client instance to avoid creating multiple connections.
$client = new Green($config);

// Set runtime-level timeout periods (in milliseconds).
$runtime = new RuntimeOptions([]);
$runtime->readTimeout = 10000;
$runtime->connectTimeout = 10000;

try {
    $response = $client->textModerationWithOptions($request, $runtime);
    print_r($response->body);
} catch (Exception $e) {
    var_dump($e->getMessage());
    var_dump($e->getErrorInfo());
    var_dump($e->getLastException());
    var_dump($e->getLastRequest());
}

Expected output (when the request succeeds and no violations are detected):

AlibabaCloud\SDK\Green\V20220302\Models\TextModerationResponseBody Object
(
    [code] => 200
    [data] => AlibabaCloud\SDK\Green\V20220302\Models\TextModerationResponseBodyData Object
        (
            [labels] =>
            [reason] =>
        )
    [message] => OK
    [requestId] => ...
)

Go SDK

1. Clone the SDK.

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

2. Call the API.

package main

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

func main() {
	// Exposing your source code can leak your AccessKey pair, compromising the security of all your resources. The following sample code is for reference only. For improved security, we recommend using a more secure method, such as an STS token, for authorization. For more information, see the relevant documentation.
	// Ensure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are set.
	config := &openapi.Config{
		// Your AccessKey ID.
		AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
		// Your AccessKey secret.
		AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
		// The endpoint to access.
		Endpoint: tea.String("green-cip.ap-southeast-1.aliyuncs.com"),
		/**
		 * Set the timeout period. The server-side end-to-end processing timeout is 10 seconds. Configure the timeout period accordingly.
		 * If you set ReadTimeout to a value that is less than the time required for server-side processing, a ReadTimeout exception is returned.
		 */
		ConnectTimeout: tea.Int(3000),
		ReadTimeout:    tea.Int(6000),
	}
	client, _err := green.NewClient(config)
	if _err != nil {
		panic(_err)
	}

	serviceParameters, _ := json.Marshal(
		map[string]interface{}{
			"content": "text to be detected",
		},
	)
	request := green.TextModerationRequest{
		Service:           tea.String("text_moderation_service"),
		ServiceParameters: tea.String(string(serviceParameters)),
	}
	result, _err := client.TextModeration(&request)
	if _err != nil {
		panic(_err)
	}
	statusCode := tea.IntValue(tea.ToInt(result.StatusCode))
	if statusCode == http.StatusOK {
		textModerationResponse := result.Body
		fmt.Println("response success. response:" + textModerationResponse.String())
		if tea.IntValue(tea.ToInt(textModerationResponse.Code)) == 200 {
			textModerationResponseData := textModerationResponse.Data
			fmt.Println("response reason:" + tea.StringValue(textModerationResponseData.Reason))
			fmt.Println("response labels:" + tea.StringValue(textModerationResponseData.Labels))
		}
	} else {
		fmt.Println("request failed. status:" + tea.ToString(statusCode))
	}
}

Expected output (when the request succeeds and no violations are detected):

response success. response:...
response reason:
response labels:

Node.js SDK

1. Install the package.

npm install @alicloud/green20220302@3.2.4

2. Call the API.

const RPCClient = require("@alicloud/pop-core");

async function main() {
    // Reuse the client instance to avoid creating multiple connections.
    var client = new RPCClient({
        // Read credentials from environment variables.
        accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
        accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
        // Modify the endpoint as needed.
        endpoint: "https://green-cip.ap-southeast-1.aliyuncs.com",
        apiVersion: '2022-03-02'
    });

    var params = {
        // Set the service as needed.
        "Service": "text moderation service",
        "ServiceParameters": JSON.stringify({
            "content": "text to be detected",
        })
    };

    var serviceParameters = JSON.parse(params.ServiceParameters);
    if (!serviceParameters.hasOwnProperty("content") || serviceParameters.content.trim().length === 0) {
        console.log("text moderation content is empty");
        return;
    }

    var requestOption = {
        method: 'POST',
        formatParams: false,
    };

    try {
        var response = await client.request('TextModeration', params, requestOption);
        console.log(JSON.stringify(response));
    } catch (err) {
        console.log(err);
    }
}

main().then(function (response) { });

Expected output (when the request succeeds and no violations are detected):

{"Code":200,"Data":{"Labels":"","Reason":""},"Message":"OK","RequestId":"..."}

C# SDK

1. Add the package.

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

2. Call the API.

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace AlibabaCloud.SDK.Green20220302
{
    public class TextModerationAutoRoute
    {
        public static void Main(string[] args)
        {
            // Build the moderation request.
            AlibabaCloud.SDK.Green20220302.Models.TextModerationRequest textModerationRequest =
                new AlibabaCloud.SDK.Green20220302.Models.TextModerationRequest();
            // Set the service as needed.
            textModerationRequest.Service = "text moderation service";
            Dictionary<string, object> task = new Dictionary<string, object>();
            task.Add("content", "text to be detected");

            if (!task.ContainsKey("content") || Convert.ToString(task["content"]).Trim() == string.Empty)
            {
                Console.WriteLine("text moderation content is empty");
                return;
            }
            textModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task);

            // Read credentials from environment variables.
            AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
            {
                AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
                // Modify the endpoint as needed.
                Endpoint = "green-cip.ap-southeast-1.aliyuncs.com",
            };

            // Reuse the client instance to avoid creating multiple connections.
            AlibabaCloud.SDK.Green20220302.Client client = new AlibabaCloud.SDK.Green20220302.Client(config);

            // Set runtime-level timeout periods (in milliseconds).
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            runtime.ReadTimeout = 10000;
            runtime.ConnectTimeout = 10000;

            try
            {
                AlibabaCloud.SDK.Green20220302.Models.TextModerationResponse response =
                    client.TextModerationWithOptions(textModerationRequest, runtime);

                Console.WriteLine(response.Body.RequestId);
                Console.WriteLine(JsonConvert.SerializeObject(response.Body));
            }
            catch (Exception _err)
            {
                Console.WriteLine(_err);
            }
        }
    }
}

Expected output (when the request succeeds and no violations are detected):

<request-id>
{"Code":200,"Data":{"Labels":"","Reason":""},"Message":"OK","RequestId":"<request-id>"}

This SDK supports two service versions. If you are a new user of the text moderation enhanced version, we recommend that you use the Text Moderation PLUS service.

If you have any questions, join the DingTalk group (ID: 35573806) to contact our product and technical experts.

What's next