All Products
Search
Document Center

Content Moderation:SDK Reference

Last Updated:Dec 05, 2025

This topic describes how to integrate the AI Guardrails software development kit (SDK).

Step 1: Activate the service

Go to the AI Guardrails service activation page to activate the AI Guardrails service. The default billing method is pay-as-you-go. You are billed for your actual usage daily. You are not charged if you do not call the service. After you integrate and use an API operation, the system automatically generates bills based on your usage.

Step 2: Grant permissions to a RAM user

Before you integrate the SDK or an API operation, grant permissions to a Resource Access Management (RAM) user. Create an AccessKey pair for your Alibaba Cloud account or a RAM user. Use the AccessKey pair for identity verification when you call Alibaba Cloud API operations. For more information, see Obtain an AccessKey pair.

Procedure

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

  2. Create a RAM user.

    For more information, see Create a RAM user.

  3. Grant the AliyunYundunGreenWebFullAccess system policy to the RAM user.

    For more information, see Grant permissions to a RAM user.

    After completing the preceding operations, you can call the Content Moderation API as the RAM user.

Step 3: Install and integrate the SDK

The following regions are supported:

Region

Public endpoint

VPC endpoint

Singapore

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

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

Note

To obtain SDK sample code in other programming languages, test API operations in OpenAPI Explorer. OpenAPI Explorer automatically generates sample code for these API operations.

In Alibaba Cloud SDK code, you can create a default access credential by defining ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables. When you call API operations of Alibaba Cloud services, the system directly accesses the credential, reads your AccessKey pair, and then automatically completes authentication. Before you use the SDK sample code, you must configure environment variables. For more information, see Configure credentials.

Sample code

Java SDK

Java 1.8 or later is supported.

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

Add the dependency to the pom.xml file to use the SDK in a Maven project.

1. Add the following dependency to the dependencies section.

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

2. Sample Java SDK code for integration.

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();
        /**
         * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. For security, use a RAM user to call API operations or perform routine O&M.
         * Common methods to obtain 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("Obtain the AccessKey ID of the RAM user from an environment variable.");
        config.setAccessKeySecret("Obtain the AccessKey secret of the RAM user from an environment variable.");
        // Modify the region and endpoint as needed.
        config.setRegionId("ap-southeast-1");
        config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com");
        // The read timeout period. Unit: milliseconds (ms).
        config.setReadTimeout(6000);
        // The connection timeout period. Unit: milliseconds (ms).
        config.setConnectTimeout(3000);
        // Set the HTTP proxy.
        //config.setHttpProxy("http://xx.xx.xx.xx:xxxx");
        // Set the HTTPS proxy.
        //config.setHttpsProxy("https://xx.xx.xx.xx:xxxx");
        Client client = new Client(config);

        JSONObject serviceParameters = new JSONObject();
        serviceParameters.put("content", "Sample text for testing");

        TextModerationPlusRequest textModerationPlusRequest = new TextModerationPlusRequest();
        // The detection type.
        textModerationPlusRequest.setService("query_security_check_intl");
        textModerationPlusRequest.setServiceParameters(serviceParameters.toJSONString());

        try {
            TextModerationPlusResponse response = client.textModerationPlus(textModerationPlusRequest);
            if (response.getStatusCode() == 200) {
                TextModerationPlusResponseBody result = response.getBody();
                System.out.println(JSON.toJSONString(result));
                System.out.println("requestId = " + result.getRequestId());
                System.out.println("code = " + result.getCode());
                System.out.println("msg = " + result.getMessage());
                Integer code = result.getCode();
                if (200 == code) {
                    TextModerationPlusResponseBody.TextModerationPlusResponseBodyData data = result.getData();
                    System.out.println(JSON.toJSONString(data, true));
                } 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();
        }
    }
}

Python SDK

Python 3.6 or later is supported.

For the source code, see Python SDK source code.

1. Run the following command to import the dependency.

pip install alibabacloud_green20220302==2.20.3

2. Sample Python SDK code for integration.

# 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(
    # The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. For security, use a RAM user to call API operations or perform routine O&M.
    # Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised.
    # Common methods to obtain environment variables:
    # 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='Obtain the AccessKey ID of the RAM user from an environment variable',
    access_key_secret='Obtain the AccessKey secret of the RAM user from an environment variable',
    # The connection timeout period. Unit: milliseconds (ms).
    connect_timeout=10000,
    # The read timeout period. Unit: milliseconds (ms).
    read_timeout=3000,
    region_id='ap-southeast-1',
    endpoint='green-cip.ap-southeast-1.aliyuncs.com'
)

clt = Client(config)

serviceParameters = {
    'content': 'Sample text for testing'
}
textModerationPlusRequest = models.TextModerationPlusRequest(
    # The detection type.
    service='query_security_check_intl',
    service_parameters=json.dumps(serviceParameters)
)

try:
    response = clt.text_moderation_plus(textModerationPlusRequest)
    if response.status_code == 200:
        # The call is successful.
        result = response.body
        print('response success. result:{}'.format(result))
    else:
        print('response not success. status:{} ,result:{}'.format(response.status_code, response))
except Exception as err:
    print(err)

PHP SDK

PHP 5.6 or later is supported.

For the source code, see PHP SDK source code.

1. Run the following command to import the dependency.

composer require alibabacloud/green-20220302

2. Sample PHP SDK code for integration.

<?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([
    /**
     * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. For security, use a RAM user to call API operations or perform routine O&M.
     * Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised.
     * Common methods to obtain environment variables:
     * 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" => 'Obtain the AccessKey ID of the RAM user from an environment variable',
    "accessKeySecret" => 'Obtain the AccessKey secret of the RAM user from an environment variable',
    // Set the HTTP proxy.
    // "httpProxy" => "http://10.10.xx.xx:xxxx",
    // Set the HTTPS proxy.
    // "httpsProxy" => "https://10.10.xx.xx:xxxx",
    "endpoint" => "green-cip.ap-southeast-1.aliyuncs.com",
    "regionId" => "ap-southeast-1"

]);
// Note: Reuse the client instance to avoid repeated connections and improve detection performance.
$client = new Green($config);

$request = new TextModerationPlusRequest();
$request->service = "query_security_check_intl";
$serviceParameters = array("content" => "Sample text");

$request->serviceParameters = json_encode($serviceParameters);

$runtime = new RuntimeOptions();
$runtime->readTimeout = 6000;
$runtime->connectTimeout = 3000;

try {
    $response = $client->textModerationPlusWithOptions($request, $runtime);
    print_r($response->body);
    if (200 != $response->statusCode) {
        print_r("response not success. code:" . $response->statusCode);
        return;
    }
    $body = $response->body;
    print_r("requestId = " . $body->requestId . "\n");
    print_r("code = " . $body->code . "\n");
    print_r("message = " . $body->message . "\n");
    if (200 != $body->code) {
        print_r("text moderation not success. code:" . $body->code);
    }
    $data = $body->data;
    print_r("data = " . json_encode($data));
} catch (TeaUnableRetryError $e) {
    var_dump($e->getMessage());
    var_dump($e->getErrorInfo());
    var_dump($e->getLastException());
    var_dump($e->getLastRequest());
}

Go SDK

1. Run the following command to import the dependency.

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

2. Sample Go SDK code for integration.

package main

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

func main() {
	// Leaked project code may cause the AccessKey pair to be leaked and compromise the security of all resources in your account. The following sample code is for reference only. Use a more secure method, such as Security Token Service (STS).
	config := &openapi.Config{
		/**
		 * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. For security, use a RAM user to call API operations or perform routine O&M.
		 * Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised.
		 * Common methods to obtain environment variables:
		 * 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("Obtain the AccessKey ID of the RAM user from an environment variable"),
		AccessKeySecret: tea.String("Obtain the AccessKey secret of the RAM user from an environment variable"),
		// Set the HTTP proxy.
		// HttpProxy: tea.String("http://xx.xx.xx.xx:xxxx"),
		// Set the HTTPS proxy.
		// HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"),
		RegionId: tea.String("ap-southeast-1"),
		Endpoint: tea.String("green-cip.ap-southeast-1.aliyuncs.com"),
		/**
		 * Set a timeout period. The server-side end-to-end processing timeout is 10 seconds. Set the timeout period accordingly.
		 * If you set ReadTimeout to a value that is less than the server-side processing time, a ReadTimeout exception is returned.
		 */
		ConnectTimeout: tea.Int(3000),
		ReadTimeout: tea.Int(6000),
	}
	client, _err := green20220302.NewClient(config)
	if _err != nil {
		panic(_err)
	}

	// Create a RuntimeObject instance and set runtime parameters.
	runtime := &util.RuntimeOptions{}
	runtime.ReadTimeout = tea.Int(10000)
	runtime.ConnectTimeout = tea.Int(10000)

	serviceParameters, _ := json.Marshal(
		map[string]interface{}{
			"content": "Sample text",
		},
	)
	request := green20220302.TextModerationPlusRequest{
		Service: tea.String("query_security_check_intl"),
		ServiceParameters: tea.String(string(serviceParameters)),
	}

	result, _err := client.TextModerationPlusWithOptions(&request, runtime)
	if _err != nil {
		panic(_err)
	}

	if *result.StatusCode != http.StatusOK {
		fmt.Printf("response not success. status:%d\n", *result.StatusCode)
		return
	}
	body := result.Body
	fmt.Printf("response success. requestId:%s, code:%d, msg:%s\n", *body.RequestId, *body.Code, *body.Message)
	if *body.Code != http.StatusOK {
		fmt.Printf("text moderation not success. code:%d\n", *body.Code)
		return
	}

	data := body.Data
	fmt.Printf("text moderation data:%s\n", *data)
}