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
AliyunYundunGreenWebFullAccesssystem 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 Service 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.
Log on to the RAM console as a RAM administrator.
Create a RAM user. For details, see Create a RAM user.
Grant the
AliyunYundunGreenWebFullAccesssystem 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.
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 |
|---|---|---|
| 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>2.2.11</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();
// 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 a Security Token Service (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.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
config.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// Modify the region and endpoint based on your requirements.
config.setRegionId("ap-southeast-1");
config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com");
// Set the read and connection timeout in milliseconds.
config.setReadTimeout(6000);
config.setConnectTimeout(3000);
// For better performance, we strongly recommend that you reuse the client instance to avoid establishing redundant connections.
Client client = new Client(config);
// Create a RuntimeOptions instance and set runtime parameters.
RuntimeOptions runtime = new RuntimeOptions();
runtime.readTimeout = 10000;
runtime.connectTimeout = 10000;
// Construct service parameters.
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 based on your requirements.
textModerationRequest.setService("text_moderation_service");
textModerationRequest.setServiceParameters(serviceParameters.toJSONString());
try {
// Call the method to get the detection result.
TextModerationResponse response = client.textModerationWithOptions(textModerationRequest, runtime);
// Print the detection result.
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 failed. code:" + code);
}
} else {
System.out.println("request failed. 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==2.2.112. Call the API.
# coding=utf-8
import os
import json
import uuid
from alibabacloud_green20220302.client import Client
from alibabacloud_green20220302 import models
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.client import Client as UtilClient
from alibabacloud_tea_util import models as util_models
class TextAutoRoute:
@staticmethod
def main() -> None:
service_parameters = {
'content': 'text to be detected',
'dataId': str(uuid.uuid1())
}
if service_parameters.get("content") is None or len(service_parameters.get("content").strip()) == 0:
print("text moderation content is empty")
return
text_moderation_request = models.TextModerationRequest(
# Set the service as needed.
service='text moderation service',
service_parameters=json.dumps(service_parameters)
)
# Read credentials from environment variables.
config = Config(
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
# Set the connection and read timeout periods (in milliseconds).
connect_timeout=3000,
read_timeout=6000,
# Modify the region and endpoint as needed.
region_id='ap-southeast-1',
endpoint='green-cip.ap-southeast-1.aliyuncs.com'
)
# Reuse the client instance to avoid creating multiple connections.
client = Client(config)
# Set runtime-level timeout periods (in milliseconds).
runtime = util_models.RuntimeOptions()
runtime.read_timeout = 10000
runtime.connect_timeout = 10000
try:
response = client.text_moderation_with_options(text_moderation_request, runtime)
if response.status_code == 200:
result = response.body
print('response success. result:{}'.format(result))
if result.code == 200:
result_data = result.data
print('labels:{}, reason:{}'.format(result_data.labels, result_data.reason))
else:
print('response not success. status:{} ,result:{}'.format(response.status_code, response))
except Exception as err:
print(err)
if __name__ == '__main__':
TextAutoRoute.main()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 2.2.102. 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 based on your requirements.
$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;
}
$config = new Config([
// 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.
"accessKeyId" => getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
"accessKeySecret" => getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
// Modify the region and endpoint based on your requirements.
"endpoint" => "green-cip.ap-southeast-1.aliyuncs.com",
"regionId" => "ap-southeast-1"
]);
// For better performance, we strongly recommend that you reuse the client instance to avoid establishing redundant connections.
$client = new Green($config);
// Create a RuntimeOptions instance and set runtime parameters.
$runtime = new RuntimeOptions([]);
$runtime->readTimeout = 10000;
$runtime->connectTimeout = 10000;
try {
// Call the method to get the detection result.
$response = $client->textModerationWithOptions($request, $runtime);
// Print the detection result.
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.
git clone --branch v2.2.11 https://github.com/alibabacloud-go/green-20220302/v22. 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/v2/client"
"github.com/alibabacloud-go/tea/tea"
"net/http"
"os"
)
func main() {
config := &openapi.Config{
// Read credentials from environment variables.
AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
// Modify the endpoint as needed.
Endpoint: tea.String("green-cip.ap-southeast-1.aliyuncs.com"),
/**
* The server-side end-to-end processing timeout is 10 seconds.
* If ReadTimeout is less than the server processing time, the client receives a ReadTimeout error.
*/
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 moderated",
},
)
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("response not success. 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@2.2.102. 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 2.2.102. 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>"}What's next
Text moderation enhanced version 2.0 multilingual service API — full API reference for
TextModerationConfigure credentials — use STS tokens or other credential providers for production workloads
OpenAPI Explorer — debug API operations and generate SDK code online