All Products
Search
Document Center

AI Guardrails:SDK Reference

Last Updated:Mar 31, 2026

Integrate the Guardrails software development kit (SDK) into your application to start moderating content programmatically.

Prerequisites

Before you begin, make sure you have:

  • An Alibaba Cloud account

  • A Resource Access Management (RAM) user with the AliyunYundunGreenWebFullAccess system policy attached

Step 1: Activate the service

Go to the Guardrails service activation page and activate the service. The default billing method is pay-as-you-go. You are billed for actual usage daily. No charges apply until you make API calls.

Step 2: Set up a RAM user

Grant API access to a RAM user before integrating the SDK.

  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.

  4. Create an AccessKey pair for the RAM user. For details, see Obtain an AccessKey pair.

After completing these steps, the RAM user can call the Content Moderation API.

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)
}

Step 3: Install and integrate the SDK

Supported regions

RegionPublic endpointVPC endpoint
Singaporegreen-cip.ap-southeast-1.aliyuncs.comgreen-cip-vpc.ap-southeast-1.aliyuncs.com

Set environment variables

Store your AccessKey pair as environment variables so you don't hard-code credentials in your project code.

Linux/macOS:

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

Windows:

setx ALIBABA_CLOUD_ACCESS_KEY_ID <your-access-key-id>
setx 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.

For more credential configuration options, see Configure credentials.

To get sample code in other programming languages, use OpenAPI Explorer. OpenAPI Explorer automatically generates sample code for all API operations.

Java SDK

Java 1.8 or later is required.

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

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

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

2. Run a text moderation request.

All examples use the TextModerationPlus API operation with the query_security_check_intl detection type.

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();
        // Read credentials from environment variables
        config.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
        config.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        config.setRegionId("ap-southeast-1");
        config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com");
        // Read timeout: 6,000 ms; connection timeout: 3,000 ms
        config.setReadTimeout(6000);
        config.setConnectTimeout(3000);
        // Uncomment to set a proxy
        // config.setHttpProxy("http://xx.xx.xx.xx:xxxx");
        // 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 request = new TextModerationPlusRequest();
        request.setService("query_security_check_intl");
        request.setServiceParameters(serviceParameters.toJSONString());

        try {
            TextModerationPlusResponse response = client.textModerationPlus(request);
            if (response.getStatusCode() == 200) {
                TextModerationPlusResponseBody result = response.getBody();
                System.out.println("requestId = " + result.getRequestId());
                System.out.println("code = " + result.getCode());
                System.out.println("msg = " + result.getMessage());
                if (200 == result.getCode()) {
                    TextModerationPlusResponseBody.TextModerationPlusResponseBodyData data = result.getData();
                    System.out.println(JSON.toJSONString(data, true));
                } else {
                    System.out.println("text moderation failed. code: " + result.getCode());
                }
            } else {
                System.out.println("request failed. status: " + response.getStatusCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Python SDK

Python 3.6 or later is required.

For the source code, see Python SDK source code.

1. Install the package.

pip install alibabacloud_green20220302==2.20.3

2. Run a text moderation request.

# coding=utf-8
import os
import json
from alibabacloud_green20220302.client import Client
from alibabacloud_green20220302 import models
from alibabacloud_tea_openapi.models import Config

config = Config(
    # Read credentials from environment variables
    access_key_id=os.environ["ALIBABA_CLOUD_ACCESS_KEY_ID"],
    access_key_secret=os.environ["ALIBABA_CLOUD_ACCESS_KEY_SECRET"],
    connect_timeout=10000,  # Connection timeout: 10,000 ms
    read_timeout=3000,      # Read timeout: 3,000 ms
    region_id="ap-southeast-1",
    endpoint="green-cip.ap-southeast-1.aliyuncs.com"
)

clt = Client(config)

service_parameters = {"content": "Sample text for testing"}
request = models.TextModerationPlusRequest(
    service="query_security_check_intl",
    service_parameters=json.dumps(service_parameters)
)

try:
    response = clt.text_moderation_plus(request)
    if response.status_code == 200:
        result = response.body
        print("response success. result: {}".format(result))
    else:
        print("request failed. status: {}, result: {}".format(response.status_code, response))
except Exception as err:
    print(err)

PHP SDK

PHP 5.6 or later is required.

For the source code, see PHP SDK source code.

1. Install the package.

composer require alibabacloud/green-20220302

2. Run a text moderation request.

Reuse the client instance across requests to avoid repeated connections and improve performance.
<?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([
    // Read credentials from environment variables
    "accessKeyId"     => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
    "accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
    // Uncomment to set a proxy
    // "httpProxy"  => "http://10.10.xx.xx:xxxx",
    // "httpsProxy" => "https://10.10.xx.xx:xxxx",
    "endpoint" => "green-cip.ap-southeast-1.aliyuncs.com",
    "regionId" => "ap-southeast-1"
]);

$client = new Green($config);

$request = new TextModerationPlusRequest();
$request->service = "query_security_check_intl";
$request->serviceParameters = json_encode(["content" => "Sample text for testing"]);

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

try {
    $response = $client->textModerationPlusWithOptions($request, $runtime);
    if (200 != $response->statusCode) {
        print_r("request failed. 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 failed. code: " . $body->code);
        return;
    }
    print_r("data = " . json_encode($body->data));
} catch (TeaUnableRetryError $e) {
    var_dump($e->getMessage());
    var_dump($e->getErrorInfo());
    var_dump($e->getLastException());
    var_dump($e->getLastRequest());
}

Go SDK

1. Install the package.

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

2. Run a text moderation request.

The server-side processing timeout is 10 seconds. Set ReadTimeout to at least 10,000 ms to avoid premature ReadTimeout errors.
package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"os"

	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"
)

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")),
		// Uncomment to set a proxy
		// HttpProxy:  tea.String("http://xx.xx.xx.xx:xxxx"),
		// 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"),
		ConnectTimeout: tea.Int(3000),
		ReadTimeout:    tea.Int(6000),
	}
	client, err := green20220302.NewClient(config)
	if err != nil {
		panic(err)
	}

	// RuntimeOptions overrides the Config timeout values
	runtime := &util.RuntimeOptions{}
	runtime.ReadTimeout = tea.Int(10000)
	runtime.ConnectTimeout = tea.Int(10000)

	serviceParameters, _ := json.Marshal(map[string]interface{}{
		"content": "Sample text for testing",
	})
	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("request failed. status: %d\n", *result.StatusCode)
		return
	}
	body := result.Body
	fmt.Printf("requestId: %s, code: %d, msg: %s\n", *body.RequestId, *body.Code, *body.Message)
	if *body.Code != http.StatusOK {
		fmt.Printf("text moderation failed. code: %d\n", *body.Code)
		return
	}
	fmt.Printf("data: %s\n", *body.Data)
}