The image-text hybrid modality moderation service supports both SDK and native HTTPS calls. We recommend integrating with the SDK, as it handles complex details such as signature verification and request body construction. This topic describes how to integrate with the image-text hybrid modality moderation API.
Step 1: Activate the service
Visit theActivate Content Moderation Enhanced Edition page to activate the Enhanced Edition of Multimodal Moderation for Image-Text. After you integrate the API, the system automatically bills you based on your usage. For details, see II. Billing Description. You can also purchase a resource package. Resource packages offer tiered discounts compared to the pay-as-you-go option and are ideal for users with high, predictable usage.
After you activate the Enhanced Edition of Multimodal Moderation for Image-Text, the default billing method is pay-as-you-go. The system charges you based on actual usage and settles fees daily. You will not be charged if you do not call the service.
Step 2: Grant permissions to a RAM user
Before you integrate with the SDK or API, grant permissions to a RAM user and create an access key. This key authenticates your API calls to Alibaba Cloud. For more information, see Obtain an access key.
-
Sign in to the RAM console as a RAM administrator.
-
Create a RAM user.
For details, see Create a RAM user.
-
Grant the RAM user the following system policy permission:
AliyunYundunGreenWebFullAccess.For details, see Manage permissions for a RAM user.
You can now use the RAM user to call the content moderation API.
Step 3: Integrate the image-text moderation service
The following regions are supported:
|
Region |
Public endpoint |
Internal endpoint |
|
China (Shanghai) |
green-cip.cn-shanghai.aliyuncs.com |
green-cip-vpc.cn-shanghai.aliyuncs.com |
|
China (Beijing) |
green-cip.cn-beijing.aliyuncs.com |
green-cip-vpc.cn-beijing.aliyuncs.com |
The Alibaba Cloud SDK automatically creates default access credentials by using the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables. When you call an API, the SDK automatically uses these credentials to authenticate your request. Before you use the SDK sample code, set these environment variables. For more information, see Manage access credentials.
Java SDK
This SDK is compatible with Java 1.8 or later.
For the source code, see Java SDK Source Code or Java SDK Source Code (OSS Path).
This SDK supports two types of image moderation.
Public network images
Use cases
If your images are accessible via public URLs, the multimodal moderation Enhanced Edition service fetches the image files from the URLs and performs moderation.
-
To use the Java SDK in your Maven project, add the following dependency to your pom.xml file.
<dependency> <groupId>com.aliyun</groupId> <artifactId>green20220302</artifactId> <version>3.3.3</version> </dependency> -
Integrate the Java SDK.
-
Submit an asynchronous multimodal moderation task
import com.alibaba.fastjson.JSON; import com.aliyun.green20220302.Client; import com.aliyun.green20220302.models.DescribeMultimodalModerationResultRequest; import com.aliyun.green20220302.models.DescribeMultimodalModerationResultResponse; import com.aliyun.green20220302.models.DescribeMultimodalModerationResultResponseBody; import com.aliyun.green20220302.models.MultimodalAsyncModerationRequest; import com.aliyun.green20220302.models.MultimodalAsyncModerationResponse; import com.aliyun.teaopenapi.models.Config; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MultimodalModerationDemo { public static void main(String[] args) throws Exception { // For security, we recommend storing your AccessKey pair in environment variables. String accessKeyId = ""; String accessKeySecret = ""; String endpoint = "green-cip.cn-shanghai.aliyuncs.com"; // 1. Create a client. Client client = createClient(accessKeyId, accessKeySecret, endpoint); // 2. Request moderation. String reqId = multimodalAsyncModeration(client); System.out.println("reqId=" + reqId); } /** * Create a client for sending requests. * * @param accessKeyId * @param accessKeySecret * @param endpoint * @return * @throws Exception */ public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception { Config config = new Config(); config.setAccessKeyId(accessKeyId); config.setAccessKeySecret(accessKeySecret); // Configure an HTTP proxy. //config.setHttpProxy("http://10.10.xx.xx:xxxx"); // Configure an HTTPS proxy. //config.setHttpsProxy("https://10.10.xx.xx:xxxx"); config.setEndpoint(endpoint); return new Client(config); } private static String multimodalAsyncModeration(Client client) throws Exception { // Construct the moderation parameters. Map<String, Object> serviceParameters = new HashMap<>(); // The main content of the post. serviceParameters.put("mainData", createMainData()); // The list of comments on the post. serviceParameters.put("commentDatas", createCommentDatas()); MultimodalAsyncModerationRequest request = new MultimodalAsyncModerationRequest(); request.setService("post_text_image_detection"); request.setServiceParameters(JSON.toJSONString(serviceParameters)); MultimodalAsyncModerationResponse response = client.multimodalAsyncModeration(request); return response.getBody().getData().getReqId(); } // List of first-level comments. private static List<Map<String, Object>> createCommentDatas() { Map<String, String> image = new HashMap<>(); // A publicly accessible URL. image.put("imageUrl", "https://img.alicdn.com/tfs/xxxxxxxxxx001.png"); // Images in the first-level comment. List<Map<String, String>> images = new ArrayList<>(); images.add(image); Map<String, Object> commentData = new HashMap<>(); // Text of the first-level comment. commentData.put("content", "Text of the first-level comment"); // Images in the first-level comment. commentData.put("images", images); // List of second-level comments. commentData.put("commentDatas", createCommentDatas2()); List<Map<String, Object>> commentDatas = new ArrayList<>(); commentDatas.add(commentData); return commentDatas; } /** List of second-level comments. */ private static List<Map<String, Object>> createCommentDatas2() { Map<String, String> image = new HashMap<>(); // A publicly accessible URL. image.put("imageUrl", "https://img.alicdn.com/tfs/xxxxxxxxxx001.png"); // Images in the second-level comment. List<Map<String, String>> images = new ArrayList<>(); images.add(image); Map<String, Object> commentData = new HashMap<>(); // Text of the second-level comment. commentData.put("content", "Text of the second-level comment"); // Images in the second-level comment. commentData.put("images", images); List<Map<String, Object>> commentDatas = new ArrayList<>(); commentDatas.add(commentData); return commentDatas; } private static Map<String, Object> createMainData() { Map<String, String> mainImage = new HashMap<>(); // A publicly accessible URL. mainImage.put("imageUrl", "https://img.alicdn.com/tfs/xxxxxxxxxx001.png"); List<Map<String, String>> mainImages = new ArrayList<>(); mainImages.add(mainImage); Map<String, Object> mainData = new HashMap<>(); mainData.put("mainTitle", "Title of the post"); mainData.put("mainContent", "Content of the post"); mainData.put("mainImages", mainImages); return mainData; } } -
Query the asynchronous task result
import com.alibaba.fastjson.JSON; import com.aliyun.green20220302.Client; import com.aliyun.green20220302.models.*; import com.aliyun.teaopenapi.models.Config; import com.aliyun.green20220302.models.DescribeMultimodalModerationResultRequest; import com.aliyun.green20220302.models.DescribeMultimodalModerationResultResponse; import com.aliyun.green20220302.models.DescribeMultimodalModerationResultResponseBody; public class DescribeMultimodalAsyncModerationResult { public static void main(String[] args) throws Exception { Config config = new Config(); /** * An AccessKey pair from an Alibaba Cloud account has permissions for all APIs. For security, we recommend using a RAM user for API access and routine operations. * For more information about how to obtain environment variables, see the following topics: * 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(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("cn-shanghai"); config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com"); // The connection timeout period. Unit: milliseconds. config.setReadTimeout(6000); // The read timeout period. Unit: milliseconds. config.setConnectTimeout(3000); Client client = new Client(config); DescribeMultimodalModerationResultRequest describeMultimodalModerationResultRequest = new DescribeMultimodalModerationResultRequest(); // The reqId that is returned when the task is submitted. describeMultimodalModerationResultRequest.setReqId("1C0A0C10-950D-544D-AE2E-2033E432E8D1"); try { DescribeMultimodalModerationResultResponse response = client.describeMultimodalModerationResult(describeMultimodalModerationResultRequest); if (response.getStatusCode() == 200) { DescribeMultimodalModerationResultResponseBody result = response.getBody(); System.out.println("requestId=" + result.getRequestId()); System.out.println("code=" + result.getCode()); if (200 == result.getCode()) { DescribeMultimodalModerationResultResponseBody.DescribeMultimodalModerationResultResponseBodyData data = result.getData(); System.out.println("data = " + JSON.toJSONString(data)); } else { System.out.println("response not success. code:" + result.getCode()); } } else { System.out.println("response not success. status:" + response.getStatusCode()); } } catch (Exception e) { e.printStackTrace(); } } }
-
OSS images
Use cases
If you need to moderate image files that are stored in Alibaba Cloud Object Storage Service (OSS), you can authorize Content Moderation to access OSS by creating a service role. The multimodal image-text moderationEnhanced Edition service uses this service role to retrieve files from OSS for moderation. Visit the Cloud Resource Access Authorization page to create the service role.
-
Log on to the Cloud Resource Access Authorization page with your Alibaba Cloud root account to grant the required permissions.
-
To use the Java SDK in your Maven project, add the following dependency to your pom.xml file.
<dependency> <groupId>com.aliyun</groupId> <artifactId>green20220302</artifactId> <version>3.3.3</version> </dependency> -
Integrate the Java SDK.
Submit an asynchronous multimodal moderation task
import com.alibaba.fastjson.JSON;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.DescribeMultimodalModerationResultRequest;
import com.aliyun.green20220302.models.DescribeMultimodalModerationResultResponse;
import com.aliyun.green20220302.models.DescribeMultimodalModerationResultResponseBody;
import com.aliyun.green20220302.models.MultimodalAsyncModerationRequest;
import com.aliyun.green20220302.models.MultimodalAsyncModerationResponse;
import com.aliyun.teaopenapi.models.Config;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MultimodalAsyncModeration {
public static void main(String[] args) throws Exception {
// For security, we recommend storing your AccessKey pair in environment variables. String accessKeyId = "";
String accessKeySecret = "";
String endpoint = "green-cip.cn-shanghai.aliyuncs.com";
// 1. Create a client.
Client client = createClient(accessKeyId, accessKeySecret, endpoint);
// 2. Request moderation.
String reqId = multimodalAsyncModeration(client);
System.out.println("reqId=" + reqId);
}
/**
* Create a client for sending requests.
*
* @param accessKeyId
* @param accessKeySecret
* @param endpoint
* @return
* @throws Exception
*/
public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
Config config = new Config();
config.setAccessKeyId(accessKeyId);
config.setAccessKeySecret(accessKeySecret);
// Configure an HTTP proxy.
//config.setHttpProxy("http://10.10.xx.xx:xxxx");
// Configure an HTTPS proxy.
//config.setHttpsProxy("https://10.10.xx.xx:xxxx");
config.setEndpoint(endpoint);
return new Client(config);
}
private static String multimodalAsyncModeration(Client client) throws Exception {
// Construct the moderation parameters.
Map<String, Object> serviceParameters = new HashMap<>();
// The main content of the post.
serviceParameters.put("mainData", createMainData());
// The list of comments on the post.
serviceParameters.put("commentDatas", createCommentDatas());
MultimodalAsyncModerationRequest request = new MultimodalAsyncModerationRequest();
request.setService("post_text_image_detection");
request.setServiceParameters(JSON.toJSONString(serviceParameters));
MultimodalAsyncModerationResponse response = client.multimodalAsyncModeration(request);
return response.getBody().getData().getReqId();
}
// List of first-level comments.
private static List<Map<String, Object>> createCommentDatas() {
Map<String, String> image = new HashMap<>();
// The region of the OSS bucket. Example: cn-shanghai.
image.put("ossRegionId", "cn-shanghai");
// The name of the OSS bucket. Example: bucket001.
image.put("ossBucketName", "bucket001");
// The full path of the object in the OSS bucket. Example: image/001.jpg.
image.put("ossObjectName", "image/001.jpg");
// Images in the first-level comment.
List<Map<String, String>> images = new ArrayList<>();
images.add(image);
Map<String, Object> commentData = new HashMap<>();
// Text of the first-level comment.
commentData.put("content", "Text of the first-level comment");
// Images in the first-level comment.
commentData.put("images", images);
// List of second-level comments.
commentData.put("commentDatas", createCommentDatas2());
List<Map<String, Object>> commentDatas = new ArrayList<>();
commentDatas.add(commentData);
return commentDatas;
}
// List of second-level comments
private static List<Map<String, Object>> createCommentDatas2() {
Map<String, String> image = new HashMap<>();
// The region of the OSS bucket. Example: cn-shanghai.
image.put("ossRegionId", "cn-shanghai");
// The name of the OSS bucket. Example: bucket001.
image.put("ossBucketName", "bucket001");
// The full path of the object in the OSS bucket. Example: image/001.jpg.
image.put("ossObjectName", "image/001.jpg");
// Images in the second-level comment.
List<Map<String, String>> images = new ArrayList<>();
images.add(image);
Map<String, Object> commentData = new HashMap<>();
// Text of the second-level comment.
commentData.put("content", "Text of the second-level comment");
// Images in the second-level comment.
commentData.put("images", images);
List<Map<String, Object>> commentDatas = new ArrayList<>();
commentDatas.add(commentData);
return commentDatas;
}
private static Map<String, Object> createMainData() {
Map<String, String> mainImage = new HashMap<>();
// The region of the OSS bucket. Example: cn-shanghai.
mainImage.put("ossRegionId", "cn-shanghai");
// The name of the OSS bucket. Example: bucket001.
mainImage.put("ossBucketName", "bucket001");
// The full path of the object in the OSS bucket. Example: image/001.jpg.
mainImage.put("ossObjectName", "image/001.jpg");
List<Map<String, String>> mainImages = new ArrayList<>();
mainImages.add(mainImage);
Map<String, Object> mainData = new HashMap<>();
mainData.put("mainTitle", "Title of the post");
mainData.put("mainContent", "Content of the post");
mainData.put("mainImages", mainImages);
return mainData;
}
}
Query the asynchronous task result
import com.alibaba.fastjson.JSON;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.green20220302.models.DescribeMultimodalModerationResultRequest;
import com.aliyun.green20220302.models.DescribeMultimodalModerationResultResponse;
import com.aliyun.green20220302.models.DescribeMultimodalModerationResultResponseBody;
public class DescribeMultimodalAsyncModerationResult {
public static void main(String[] args) throws Exception {
Config config = new Config();
/**
* An AccessKey pair from an Alibaba Cloud account has permissions for all APIs. For security, we recommend using a RAM user for API access and routine operations.
* For more information about how to obtain environment variables, see the following topics:
* 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(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("cn-shanghai");
config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com");
// The connection timeout period. Unit: milliseconds.
config.setReadTimeout(6000);
// The read timeout period. Unit: milliseconds.
config.setConnectTimeout(3000);
Client client = new Client(config);
DescribeMultimodalModerationResultRequest describeMultimodalModerationResultRequest = new DescribeMultimodalModerationResultRequest();
// The reqId that is returned when the task is submitted.
describeMultimodalModerationResultRequest.setReqId("1C0A0C10-950D-544D-AE2E-2033E432E8D1");
try {
DescribeMultimodalModerationResultResponse response = client.describeMultimodalModerationResult(describeMultimodalModerationResultRequest);
if (response.getStatusCode() == 200) {
DescribeMultimodalModerationResultResponseBody result = response.getBody();
System.out.println("requestId=" + result.getRequestId());
System.out.println("code=" + result.getCode());
if (200 == result.getCode()) {
DescribeMultimodalModerationResultResponseBody.DescribeMultimodalModerationResultResponseBodyData data = result.getData();
System.out.println("data = " + JSON.toJSONString(data));
} else {
System.out.println("response not success. code:" + result.getCode());
}
} else {
System.out.println("response not success. status:" + response.getStatusCode());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Python SDK
Supports Python 3.6 and later.
For the source code, see Python SDK source code.
Public images
Use case
If your images are accessible from public URLs, the multimodal moderation Enhanced Edition service can fetch and moderate them.
-
Install the required dependencies:
pip install alibabacloud_green20220302==3.2.4 -
Integrate with the Python SDK.
-
Submit an asynchronous multimodal moderation task
# coding=utf-8 from alibabacloud_green20220302.client import Client from alibabacloud_green20220302 import models from alibabacloud_tea_openapi.models import Config import json Config = Config( # An AccessKey pair of an Alibaba Cloud account has permissions to call all APIs. We recommend that you use a RAM user to call APIs or perform routine operations and maintenance. # Do not hard-code your AccessKey ID and AccessKey Secret in your code. This prevents key leaks that could compromise all resources in your account. # The following shows 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="We recommend that you obtain the AccessKey ID of your RAM user from an environment variable", access_key_secret="We recommend that you obtain the AccessKey Secret of your RAM user from an environment variable", # Connection timeout in milliseconds. connect_timeout=3000, # Read timeout in milliseconds. read_timeout=6000, # Modify the region and endpoint based on your deployment. region_id='cn-shanghai', endpoint='green-cip.cn-shanghai.aliyuncs.com' ) clt = Client(Config) serviceParameters = { "dataId": "Multimodal0424***", "mainData": { "mainTitle": "Main title", "mainContent": "Main text content", "mainImages": [ { "imageUrl": "https://aliyun.com/240308/test001.jpg" }, { "imageUrl": "https://aliyun.com/240308/test002.jpg" } ], "mainPostTime": "2025-06-18 20:20:20" }, "commentDatas": [ { "images": [ { "imageUrl": "https://aliyun.com/240308/test003.jpg" }, { "imageUrl": "https://aliyun.com/240308/test004.jpg" } ], "content": "Comment content 1", "postTime": "", "commentDatas": [ { "content": "Reply to comment 1", "images": [ { "imageUrl": "https://aliyun.com/240308/test005.jpg" } ], "postTime": "" }, { "content": "Reply to comment 2", "images": [ { "imageUrl": "https://aliyun.com/240308/test006.jpg" } ], "postTime": "" } ] }, { "content": "Comment content 2", "images": [], "postTime": "", "commentDatas": [] }, { "content": "Comment content 3", "images": [], "postTime": "", "commentDatas": [] } ] } MultimodalAsyncModerationRequest = models.MultimodalAsyncModerationRequest( service='post_text_image_detection', service_parameters=json.dumps(serviceParameters) ) try: response = clt.multimodal_async_moderation(MultimodalAsyncModerationRequest) if response.status_code == 200: 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) -
Retrieve async results
from alibabacloud_green20220302.client import Client from alibabacloud_green20220302 import models from alibabacloud_tea_openapi.models import Config Config = Config( # An AccessKey pair of an Alibaba Cloud account has permissions to call all APIs. We recommend that you use a RAM user to call APIs or perform routine operations and maintenance. # Do not hard-code your AccessKey ID and AccessKey Secret in your code. This prevents key leaks that could compromise all resources in your account. # The following shows 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="We recommend that you obtain the AccessKey ID of your RAM user from an environment variable", access_key_secret="We recommend that you obtain the AccessKey Secret of your RAM user from an environment variable", # Connection timeout in milliseconds. connect_timeout=3000, # Read timeout in milliseconds. read_timeout=6000, # Modify the region and endpoint based on your deployment. region_id='cn-shanghai', endpoint='green-cip.cn-shanghai.aliyuncs.com' ) clt = Client(Config) DescribeMultimodalModerationResultRequest = models.DescribeMultimodalModerationResultRequest( req_id='99BE120A-8123-17AB-8F8D-51993761XXXX' ) try: response = clt.describe_multimodal_moderation_result(DescribeMultimodalModerationResultRequest) if response.status_code == 200: 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)
-
OSS images
Use case
If your images are stored in OSS, the multimodal moderation Enhanced Edition service requires access to your OSS resources. To grant access, create a service role for Content Moderation on the Cloud Resource Access Authorization page.
-
As the root account, visit the Cloud Resource Access Authorization page to grant the required permissions.
-
Install the required dependencies:
pip install alibabacloud_green20220302==3.2.4 -
Integrate with the Python SDK.
-
Submit an asynchronous multimodal moderation task
from alibabacloud_green20220302.client import Client from alibabacloud_green20220302 import models from alibabacloud_tea_openapi.models import Config import json Config = Config( # An AccessKey pair of an Alibaba Cloud account has permissions to call all APIs. We recommend that you use a RAM user to call APIs or perform routine operations and maintenance. # Do not hard-code your AccessKey ID and AccessKey Secret in your code. This prevents key leaks that could compromise all resources in your account. # The following shows 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="We recommend that you obtain the AccessKey ID of your RAM user from an environment variable", access_key_secret="We recommend that you obtain the AccessKey Secret of your RAM user from an environment variable", # Connection timeout in milliseconds. connect_timeout=3000, # Read timeout in milliseconds. read_timeout=6000, # Modify the region and endpoint based on your deployment. region_id='cn-shanghai', endpoint='green-cip.cn-shanghai.aliyuncs.com' ) clt = Client(Config) serviceParameters = { "dataId": "Multimodal0424***", "mainData": { "mainTitle": "Main title", "mainContent": "Main text content", "mainImages": [ { "ossRegionId": "cn-shanghai", "ossBucketName": "cip-test-01", "ossObjectName": "cf02.jpg" }, { "ossRegionId": "cn-shanghai", "ossBucketName": "cip-test-01", "ossObjectName": "cf02.jpg" } ], "mainPostTime": "2025-06-18 20:20:20" }, "commentDatas": [ { "images": [ { "ossRegionId": "cn-shanghai", "ossBucketName": "cip-test-01", "ossObjectName": "cf02.jpg" }, { "ossRegionId": "cn-shanghai", "ossBucketName": "cip-test-01", "ossObjectName": "cf02.jpg" } ], "content": "Comment content 1", "postTime": "", "commentDatas": [ { "content": "Reply to comment 1", "images": [ { "ossRegionId": "cn-shanghai", "ossBucketName": "cip-test-01", "ossObjectName": "cf02.jpg" } ], "postTime": "" }, { "content": "Reply to comment 2", "images": [ { "ossRegionId": "cn-shanghai", "ossBucketName": "cip-test-01", "ossObjectName": "cf02.jpg" } ], "postTime": "" } ] }, { "content": "Comment content 2", "images": [], "postTime": "", "commentDatas": [] }, { "content": "Comment content 3", "images": [], "postTime": "", "commentDatas": [] }, { "content": "Comment content 4", "images": [], "postTime": "", "commentDatas": [] } ] } MultimodalAsyncModerationRequest = models.MultimodalAsyncModerationRequest( service='post_text_image_detection', service_parameters=json.dumps(serviceParameters) ) try: response = clt.multimodal_async_moderation(MultimodalAsyncModerationRequest) if response.status_code == 200: 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) -
Retrieve the asynchronous moderation results
from alibabacloud_green20220302.client import Client from alibabacloud_green20220302 import models from alibabacloud_tea_openapi.models import Config Config = Config( # An AccessKey pair of an Alibaba Cloud account has permissions to call all APIs. We recommend that you use a RAM user to call APIs or perform routine operations and maintenance. # Do not hard-code your AccessKey ID and AccessKey Secret in your code. This prevents key leaks that could compromise all resources in your account. # The following shows 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="We recommend that you obtain the AccessKey ID of your RAM user from an environment variable", access_key_secret="We recommend that you obtain the AccessKey Secret of your RAM user from an environment variable", # Connection timeout in milliseconds. connect_timeout=3000, # Read timeout in milliseconds. read_timeout=6000, # Modify the region and endpoint based on your deployment. region_id='cn-shanghai', endpoint='green-cip.cn-shanghai.aliyuncs.com' ) clt = Client(Config) DescribeMultimodalModerationResultRequest = models.DescribeMultimodalModerationResultRequest( req_id='99BE120A-8123-17AB-8F8D-51993761XXXX' ) try: response = clt.describe_multimodal_moderation_result(DescribeMultimodalModerationResultRequest) if response.status_code == 200: 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
Supports PHP 5.6 or later.
For the source code, see PHP SDK Source Code.
This SDK supports the following two types of image moderation.
Publicly accessible images
Use cases
The multimodal image-text moderation Enhanced Edition service moderates publicly accessible images by fetching them from their URLs.
-
Install the PHP SDK.
Run the following command to install the required dependencies.
composer require alibabacloud/green-20220302 3.2.4 -
Integrate the PHP SDK.
-
Submit an asynchronous multimodal image-text moderation task
<?php require('vendor/autoload.php'); use AlibabaCloud\SDK\Green\V20220302\Models\MultimodalAsyncModerationRequest; 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([ /** * An Alibaba Cloud account's AccessKey pair grants full access to all APIs. For security, we recommend using a RAM user for API calls and daily operations. * We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your project code, as this poses a security risk if the keys are leaked. * You can obtain the keys from environment variables: * To obtain the AccessKey ID of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * To obtain the AccessKey Secret of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ "accessKeyId" => 'Obtain the AccessKey ID of your RAM user from an environment variable', "accessKeySecret" => 'Obtain the AccessKey Secret of your 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.cn-shanghai.aliyuncs.com", "regionId" => "cn-shanghai" ]); // Note: For better performance, reuse the client instance to avoid re-establishing connections. $client = new Green($config); $request = new MultimodalAsyncModerationRequest(); $request->service = "post_text_image_detection"; // Construct the main data $mainData = [ 'mainTitle' => 'Main Title', 'mainContent' => 'Main text content', 'mainImages' => [ ['imageUrl' => 'https://aliyun.com/240308/test001.jpg'], ['imageUrl' => 'https://aliyun.com/240308/test002.jpg'] ], 'mainPostTime' => '2025-06-18 20:20:20' ]; // Construct the comment data $commentDatas = [ [ 'images' => [ ['imageUrl' => 'https://aliyun.com/240308/test003.jpg'], ['imageUrl' => 'https://aliyun.com/240308/test004.jpg'] ], 'content' => 'Comment 1', 'postTime' => '', 'commentDatas' => [ [ 'content' => 'Reply 1 to Comment 1', 'images' => [ ['imageUrl' => 'https://aliyun.com/240308/test005.jpg'] ], 'postTime' => '' ], [ 'content' => 'Reply 2 to Comment 1', 'images' => [ ['imageUrl' => 'https://aliyun.com/240308/test006.jpg'] ], 'postTime' => '' ] ] ], [ 'content' => 'Comment 2', 'images' => [], 'postTime' => '', 'commentDatas' => [] ], // More comment data... [ 'content' => 'Comment 7', 'images' => [], 'postTime' => '', 'commentDatas' => [] ] ]; $serviceParameters = [ 'dataId' => uniqid(), 'mainData' => $mainData, 'commentDatas' => $commentDatas ]; $request->serviceParameters = json_encode($serviceParameters, JSON_UNESCAPED_UNICODE); $runtime = new RuntimeOptions(); $runtime->readTimeout = 6000; $runtime->connectTimeout = 3000; try { $response = $client->MultimodalAsyncModerationWithOptions($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"); if (200 != $body->code) { print_r("request not success. code:" . $body->code); } } catch (TeaUnableRetryError $e) { var_dump($e->getMessage()); var_dump($e->getErrorInfo()); var_dump($e->getLastException()); var_dump($e->getLastRequest()); } -
Get the asynchronous moderation result
<?php require('vendor/autoload.php'); use AlibabaCloud\SDK\Green\V20220302\Models\DescribeMultimodalModerationResultRequest; 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([ /** * An Alibaba Cloud account's AccessKey pair grants full access to all APIs. For security, we recommend using a RAM user for API calls and daily operations. * We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your project code, as this poses a security risk if the keys are leaked. * You can obtain the keys from environment variables: * To obtain the AccessKey ID of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * To obtain the AccessKey Secret of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ "accessKeyId" => 'Obtain the AccessKey ID of your RAM user from an environment variable', "accessKeySecret" => 'Obtain the AccessKey Secret of your 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.cn-shanghai.aliyuncs.com", "regionId" => "cn-shanghai" ]); // Note: For better performance, reuse the client instance to avoid re-establishing connections. $client = new Green($config); $request = new DescribeMultimodalModerationResultRequest(); $request->reqId = "31248665-B47E-528E-886F-EAF73910XXXX"; $runtime = new RuntimeOptions(); $runtime->readTimeout = 6000; $runtime->connectTimeout = 3000; try { $response = $client->DescribeMultimodalModerationResultWithOptions($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"); if (200 != $body->code) { print_r("request not success. code:" . $body->code); } } catch (TeaUnableRetryError $e) { var_dump($e->getMessage()); var_dump($e->getErrorInfo()); var_dump($e->getLastException()); var_dump($e->getLastRequest()); }
-
Images in OSS
Use cases
To moderate images stored in Object Storage Service (OSS), you must first grant the service access. Do this by creating and authorizing a service-linked role on the Cloud Resource Access Authorization page. The multimodal image-text moderation Enhanced Edition service then uses this role to fetch and moderate the images from OSS.
-
Use your root account to visit the Cloud Resource Access Authorization page and grant the required permissions.
-
Install the PHP SDK.
composer require alibabacloud/green-20220302 3.2.4 -
Integrate the PHP SDK.
-
Submit an asynchronous multimodal image-text moderation task
<?php require('vendor/autoload.php'); use AlibabaCloud\SDK\Green\V20220302\Models\MultimodalAsyncModerationRequest; 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([ /** * An Alibaba Cloud account's AccessKey pair grants full access to all APIs. For security, we recommend using a RAM user for API calls and daily operations. * We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your project code, as this poses a security risk if the keys are leaked. * You can obtain the keys from environment variables: * To obtain the AccessKey ID of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * To obtain the AccessKey Secret of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ "accessKeyId" => 'Obtain the AccessKey ID of your RAM user from an environment variable', "accessKeySecret" => 'Obtain the AccessKey Secret of your 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.cn-shanghai.aliyuncs.com", "regionId" => "cn-shanghai" ]); // Note: For better performance, reuse the client instance to avoid re-establishing connections. $client = new Green($config); $request = new MultimodalAsyncModerationRequest(); $request->service = "post_text_image_detection"; $mainData = [ 'mainTitle' => 'Main Title', 'mainContent' => 'Main text content', 'mainImages' => [ [ 'ossRegionId' => 'cn-shanghai', 'ossBucketName' => 'cip-test', 'ossObjectName' => '123.jpg' ], [ 'ossRegionId' => 'cn-shanghai', 'ossBucketName' => 'cip-test', 'ossObjectName' => '123.jpg' ] ], 'mainPostTime' => '2025-06-18 20:20:20' ]; $commentDatas = [ [ 'images' => [ [ 'ossRegionId' => 'cn-shanghai', 'ossBucketName' => 'cip-test', 'ossObjectName' => '123.jpg' ], [ 'ossRegionId' => 'cn-shanghai', 'ossBucketName' => 'cip-test', 'ossObjectName' => '123.jpg' ] ], 'content' => 'Comment 1', 'postTime' => '', 'commentDatas' => [ [ 'images' => [ [ 'ossRegionId' => 'cn-shanghai', 'ossBucketName' => 'cip-test', 'ossObjectName' => '123.jpg' ] ], 'content' => 'Reply 1 to Comment 1', 'postTime' => '', 'commentDatas' => [] ], [ 'images' => [ [ 'ossRegionId' => 'cn-shanghai', 'ossBucketName' => 'cip-test', 'ossObjectName' => '123.jpg' ] ], 'content' => 'Reply 2 to Comment 1', 'postTime' => '', 'commentDatas' => [] ] ] ], [ 'images' => [], 'content' => 'Comment 2', 'postTime' => '', 'commentDatas' => [] ] ]; $serviceParameters = [ 'dataId' => uniqid(), 'mainData' => $mainData, 'commentDatas' => $commentDatas ]; $request->serviceParameters = json_encode($serviceParameters, JSON_UNESCAPED_UNICODE); $runtime = new RuntimeOptions(); $runtime->readTimeout = 6000; $runtime->connectTimeout = 3000; try { $response = $client->MultimodalAsyncModerationWithOptions($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"); if (200 != $body->code) { print_r("request not success. code:" . $body->code); } } catch (TeaUnableRetryError $e) { var_dump($e->getMessage()); var_dump($e->getErrorInfo()); var_dump($e->getLastException()); var_dump($e->getLastRequest()); } -
Get the asynchronous moderation result
<?php require('vendor/autoload.php'); use AlibabaCloud\SDK\Green\V20220302\Models\DescribeMultimodalModerationResultRequest; 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([ /** * An Alibaba Cloud account's AccessKey pair grants full access to all APIs. For security, we recommend using a RAM user for API calls and daily operations. * We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your project code, as this poses a security risk if the keys are leaked. * You can obtain the keys from environment variables: * To obtain the AccessKey ID of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * To obtain the AccessKey Secret of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ "accessKeyId" => 'Obtain the AccessKey ID of your RAM user from an environment variable', "accessKeySecret" => 'Obtain the AccessKey Secret of your 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.cn-shanghai.aliyuncs.com", "regionId" => "cn-shanghai" ]); // Note: For better performance, reuse the client instance to avoid re-establishing connections. $client = new Green($config); $request = new DescribeMultimodalModerationResultRequest(); $request->reqId = "31248665-B47E-528E-886F-EAF73910XXXX"; $runtime = new RuntimeOptions(); $runtime->readTimeout = 6000; $runtime->connectTimeout = 3000; try { $response = $client->DescribeMultimodalModerationResultWithOptions($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"); if (200 != $body->code) { print_r("request not success. code:" . $body->code); } } catch (TeaUnableRetryError $e) { var_dump($e->getMessage()); var_dump($e->getErrorInfo()); var_dump($e->getLastException()); var_dump($e->getLastRequest()); }
-
Go SDK
For the source code, see Go SDK Source Code.
The following two types of image detection are supported.
Publicly accessible images
Use cases
If your images are publicly accessible via URLs, the multimodal moderationEnhanced Edition service can fetch and moderate them.
-
Install the Go SDK.
go get github.com/alibabacloud-go/green-20220302/v3 -
Integrate with the Go SDK.
-
Submit an asynchronous multimodal moderation task
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" ) func main() { config := &openapi.Config{ // Your AccessKey ID. AccessKeyId: tea.String("We recommend that you retrieve the AccessKey ID of a RAM user from an environment variable"), // Your AccessKey Secret. AccessKeySecret: tea.String("We recommend that you retrieve the AccessKey Secret of a RAM user from an environment variable"), // The service endpoint. Endpoint: tea.String("green-cip.cn-shanghai.aliyuncs.com"), /** * Set a timeout. The end-to-end processing timeout on the server-side is 10 seconds. Configure your client accordingly. * If the ReadTimeout you set is shorter than the server-side processing time, your program returns a ReadTimeout error. */ // Configure an HTTP proxy. // HttpProxy: tea.String("http://xx.xx.xx.xx:xxxx"), // Configure an HTTPS proxy. // HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"), ConnectTimeout: tea.Int(3000), ReadTimeout: tea.Int(6000), } client, _err := green.NewClient(config) if _err != nil { fmt.Println(_err) } type Image struct { ImageUrl string `json:"imageUrl"` } type CommentData struct { Images []Image `json:"images"` Content string `json:"content"` PostTime string `json:"postTime"` CommentDatas []*CommentData `json:"commentDatas"` } type MainData struct { MainTitle string `json:"mainTitle"` MainContent string `json:"mainContent"` MainImages []Image `json:"mainImages"` MainPostTime string `json:"mainPostTime"` } type RequestBody struct { DataId string `json:"dataId"` MainData MainData `json:"mainData"` CommentDatas []CommentData `json:"commentDatas"` } payload := RequestBody{ DataId: "123456", MainData: MainData{ MainTitle: "Main title", MainContent: "Main text content", MainImages: []Image{ {ImageUrl: "https://aliyun.com/240308/test001.jpg"}, {ImageUrl: "https://aliyun.com/240308/test002.jpg"}, }, MainPostTime: "2025-06-18 20:20:20", }, CommentDatas: []CommentData{ { Images: []Image{ {ImageUrl: "https://aliyun.com/240308/test003.jpg"}, {ImageUrl: "https://aliyun.com/240308/test004.jpg"}, }, Content: "Comment content 1", PostTime: "", CommentDatas: []*CommentData{ { Content: "Reply 1 to Comment 1", Images: []Image{ {ImageUrl: "https://aliyun.com/240308/test005.jpg"}, }, PostTime: "", }, { Content: "Reply 2 to Comment 1", Images: []Image{ {ImageUrl: "https://aliyun.com/240308/test006.jpg"}, }, PostTime: "", }, }, }, { Content: "Comment content 2", Images: []Image{}, PostTime: "", }, // Other comment items... { Content: "Comment content 7", Images: []Image{}, PostTime: "", }, }, } serviceParameters, err := json.Marshal(payload) if err != nil { fmt.Println("JSON serialization failed:", err) return } multimodalAsyncModerationRequest := &green.MultimodalAsyncModerationRequest{ Service: tea.String("post_text_image_detection"), ServiceParameters: tea.String(string(serviceParameters)), } result, err := client.MultimodalAsyncModeration(multimodalAsyncModerationRequest) if err != nil { fmt.Print(err.Error()) } if result != nil { statusCode := tea.IntValue(tea.ToInt(result.StatusCode)) body := result.Body if body != nil { fmt.Println("response body:" + body.String()) }else { fmt.Print("response not success. status:" + tea.ToString(statusCode)) } } } -
Asynchronous moderation result
package main import ( "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" ) func main() { config := &openapi.Config{ // Your AccessKey ID. AccessKeyId: tea.String("We recommend that you retrieve the AccessKey ID of a RAM user from an environment variable"), // Your AccessKey Secret. AccessKeySecret: tea.String("We recommend that you retrieve the AccessKey Secret of a RAM user from an environment variable"), // The service endpoint. Endpoint: tea.String("green-cip.cn-shanghai.aliyuncs.com"), /** * Set a timeout. The end-to-end processing timeout on the server-side is 10 seconds. Configure your client accordingly. * If the ReadTimeout you set is shorter than the server-side processing time, your program returns a ReadTimeout error. */ // Configure an HTTP proxy. // HttpProxy: tea.String("http://xx.xx.xx.xx:xxxx"), // Configure an HTTPS proxy. // HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"), ConnectTimeout: tea.Int(3000), ReadTimeout: tea.Int(6000), } client, _err := green.NewClient(config) if _err != nil { fmt.Println(_err) } describeMultimodalModerationResultRequest := &green.DescribeMultimodalModerationResultRequest{ ReqId: tea.String("AB7384F1-D738-5B2D-B89A-334669B7XXXX"), } result, err := client.DescribeMultimodalModerationResult(describeMultimodalModerationResultRequest) if err != nil { fmt.Print(err.Error()) } if result != nil { statusCode := tea.IntValue(tea.ToInt(result.StatusCode)) body := result.Body if body != nil { fmt.Println("response body:" + body.String()) }else { fmt.Print("response not success. status:" + tea.ToString(statusCode)) } } }
-
Images in OSS
Use cases
If the images you need to moderate are stored in Alibaba Cloud Object Storage Service (OSS), you can create and authorize a service role to allow Content Moderation to access your OSS resources. The multimodal moderationEnhanced Edition service uses this role to fetch and moderate files from OSS. To create the service role, go to the Cloud Resource Access Authorization page.
-
Use your Alibaba Cloud root account to visit the Cloud Resource Access Authorization page and grant permissions.
-
Run the following command to install the Go SDK.
go get github.com/alibabacloud-go/green-20220302/v3 -
Integrate with the Go SDK.
-
Submit an asynchronous multimodal moderation task
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" ) func main() { config := &openapi.Config{ // Your AccessKey ID. AccessKeyId: tea.String("We recommend that you retrieve the AccessKey ID of a RAM user from an environment variable"), // Your AccessKey Secret. AccessKeySecret: tea.String("We recommend that you retrieve the AccessKey Secret of a RAM user from an environment variable"), // The service endpoint. Endpoint: tea.String("green-cip.cn-shanghai.aliyuncs.com"), /** * Set a timeout. The end-to-end processing timeout on the server-side is 10 seconds. Configure your client accordingly. * If the ReadTimeout you set is shorter than the server-side processing time, your program returns a ReadTimeout error. */ // Configure an HTTP proxy. // HttpProxy: tea.String("http://xx.xx.xx.xx:xxxx"), // Configure an HTTPS proxy. // HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"), ConnectTimeout: tea.Int(3000), ReadTimeout: tea.Int(6000), } client, _err := green.NewClient(config) if _err != nil { fmt.Println(_err) } type Image struct { OssRegionId string `json:"ossRegionId"` OssBucketName string `json:"ossBucketName"` OssObjectName string `json:"ossObjectName"` } type CommentData struct { Images []Image `json:"images"` Content string `json:"content"` PostTime string `json:"postTime"` CommentDatas []*CommentData `json:"commentDatas"` } type MainData struct { MainTitle string `json:"mainTitle"` MainContent string `json:"mainContent"` MainImages []Image `json:"mainImages"` MainPostTime string `json:"mainPostTime"` } type RequestBody struct { DataId string `json:"dataId"` MainData MainData `json:"mainData"` CommentDatas []CommentData `json:"commentDatas"` } payload := RequestBody{ DataId: "123456", MainData: MainData{ MainTitle: "Main title", MainContent: "Main text content", MainImages: []Image{ {OssRegionId: "cn-shanghai" ,OssBucketName:"cip-test",OssObjectName:"123.jpg"}, {OssRegionId: "cn-shanghai" ,OssBucketName:"cip-test",OssObjectName:"123.jpg"}, }, MainPostTime: "2025-06-18 20:20:20", }, CommentDatas: []CommentData{ { Images: []Image{ {OssRegionId: "cn-shanghai" ,OssBucketName:"cip-test",OssObjectName:"123.jpg"}, }, Content: "Comment content 1", PostTime: "", CommentDatas: []*CommentData{ { Content: "Reply 1 to Comment 1", Images: []Image{ {OssRegionId: "cn-shanghai" ,OssBucketName:"cip-test",OssObjectName:"123.jpg"}, }, PostTime: "", }, { Content: "Reply 2 to Comment 1", Images: []Image{ {OssRegionId: "cn-shanghai" ,OssBucketName:"cip-test",OssObjectName:"123.jpg"}, }, PostTime: "", }, }, }, { Content: "Comment content 2", Images: []Image{}, PostTime: "", }, // Other comment items... { Content: "Comment content 3", Images: []Image{}, PostTime: "", }, }, } serviceParameters, err := json.Marshal(payload) if err != nil { fmt.Println("JSON serialization failed:", err) return } multimodalAsyncModerationRequest := &green.MultimodalAsyncModerationRequest{ Service: tea.String("post_text_image_detection"), ServiceParameters: tea.String(string(serviceParameters)), } result, err := client.MultimodalAsyncModeration(multimodalAsyncModerationRequest) if err != nil { fmt.Print(err.Error()) } if result != nil { statusCode := tea.IntValue(tea.ToInt(result.StatusCode)) body := result.Body if body != nil { fmt.Println("response body:" + body.String()) }else { fmt.Print("response not success. status:" + tea.ToString(statusCode)) } } } -
Asynchronous moderation result
package main import ( "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" ) func main() { config := &openapi.Config{ // Your AccessKey ID. AccessKeyId: tea.String("We recommend that you retrieve the AccessKey ID of a RAM user from an environment variable"), // Your AccessKey Secret. AccessKeySecret: tea.String("We recommend that you retrieve the AccessKey Secret of a RAM user from an environment variable"), // The service endpoint. Endpoint: tea.String("green-cip.cn-shanghai.aliyuncs.com"), /** * Set a timeout. The end-to-end processing timeout on the server-side is 10 seconds. Configure your client accordingly. * If the ReadTimeout you set is shorter than the server-side processing time, your program returns a ReadTimeout error. */ // Configure an HTTP proxy. // HttpProxy: tea.String("http://xx.xx.xx.xx:xxxx"), // Configure an HTTPS proxy. // HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"), ConnectTimeout: tea.Int(3000), ReadTimeout: tea.Int(6000), } client, _err := green.NewClient(config) if _err != nil { fmt.Println(_err) } describeMultimodalModerationResultRequest := &green.DescribeMultimodalModerationResultRequest{ ReqId: tea.String("AB7384F1-D738-5B2D-B89A-334669B7XXXX"), } result, err := client.DescribeMultimodalModerationResult(describeMultimodalModerationResultRequest) if err != nil { fmt.Print(err.Error()) } if result != nil { statusCode := tea.IntValue(tea.ToInt(result.StatusCode)) body := result.Body if body != nil { fmt.Println("response body:" + body.String()) }else { fmt.Print("response not success. status:" + tea.ToString(statusCode)) } } }
-
Node.js SDK
For the source code, see Node.js SDK source code.
This SDK supports two types of image moderation.
Publicly accessible images
Use cases
If your images are accessible through public URLs, the multimodal moderation Enhanced Edition service can fetch and moderate them.
-
Install the Node.js SDK.
Run the following command to install the dependencies.
npm install @alicloud/green20220302@3.2.4 -
Integrate with the Node.js SDK.
-
Submit an asynchronous multimodal moderation task
const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const Util = require('@alicloud/tea-util'); // Note: To improve moderation performance, reuse the client instance whenever possible and avoid repeatedly establishing connections. // Leaking your project's source code can expose your AccessKey and compromise the security of all resources under your account. The following code is for reference only. class Client { static createClient() { const config = new OpenApi.Config({ // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in your runtime environment. accessKeyId: 'Retrieve your AccessKey ID from an environment variable.', // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in your runtime environment. accessKeySecret: 'Retrieve your AccessKey secret from an environment variable.', endpoint: `green-cip.cn-shanghai.aliyuncs.com`, }); return new Green20220302.default(config); } static async main() { const client = Client.createClient(); // Construct the request object. const MultimodalAsyncModerationRequest = new Green20220302.MultimodalAsyncModerationRequest({ "service": "post_text_image_detection", "serviceParameters": JSON.stringify({"dataId":"Multimodal0424***","mainData":{"mainTitle":"Main title","mainContent":"Main text content","mainImages":[{"imageUrl":"https://aliyun.com/240308/test001.jpg"},{"imageUrl":"https://aliyun.com/240308/test002.jpg"}],"mainPostTime":"2025-06-18 20:20:20"},"commentDatas":[{"images":[{"imageUrl":"https://aliyun.com/240308/test003.jpg"},{"imageUrl":"https://aliyun.com/240308/test004.jpg"}],"content":"Comment content 1","postTime":"","commentDatas":[{"content":"Reply 1 to comment 1","images":[{"imageUrl":"https://aliyun.com/240308/test005.jpg"}],"postTime":""},{"content":"Reply 2 to comment 1","images":[{"imageUrl":"https://aliyun.com/240308/test006.jpg"}],"postTime":""}]},{"content":"Comment content 2","images":[],"postTime":"","commentDatas":[]},{"content":"Comment content 3","images":[],"postTime":"","commentDatas":[]},{"content":"Comment content 4","images":[],"postTime":"","commentDatas":[]},{"content":"Comment content 5","images":[],"postTime":"","commentDatas":[]},{"content":"Comment content 6","images":[],"postTime":"","commentDatas":[]},{"content":"Comment content 7","images":[],"postTime":"","commentDatas":[]}]}) }); // Create a runtime options object. const runtime = new Util.RuntimeOptions(); try { // Send the request and receive the response. const response = await client.multimodalAsyncModerationWithOptions(MultimodalAsyncModerationRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // This is for demonstration purposes only. In a production environment, handle exceptions with care and do not ignore them. // Error message console.log('Error occurred:', error.message); } } } Client.main(); -
Get asynchronous result
const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const Util = require('@alicloud/tea-util'); // Note: To improve moderation performance, reuse the client instance whenever possible and avoid repeatedly establishing connections. // Leaking your project's source code can expose your AccessKey and compromise the security of all resources under your account. The following code is for reference only. class Client { static createClient() { const config = new OpenApi.Config({ // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in your runtime environment. accessKeyId: 'Retrieve your AccessKey ID from an environment variable.', // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in your runtime environment. accessKeySecret: 'Retrieve your AccessKey secret from an environment variable.', endpoint: `green-cip.cn-shanghai.aliyuncs.com`, }); return new Green20220302.default(config); } static async main() { const client = Client.createClient(); // Construct the request object. const DescribeMultimodalModerationResultRequest = new Green20220302.DescribeMultimodalModerationResultRequest({ "reqId": "7A0095D2-865E-5FDC-B7B3-EFB5EA4CXXXX" }); // Create a runtime options object. const runtime = new Util.RuntimeOptions(); try { // Send the request and receive the response. const response = await client.describeMultimodalModerationResultWithOptions(DescribeMultimodalModerationResultRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // This is for demonstration purposes only. In a production environment, handle exceptions with care and do not ignore them. // Error message console.log('Error occurred:', error.message); } } } Client.main();
-
Images in OSS
Use cases
If your images are stored in Alibaba Cloud Object Storage Service (OSS), you must create and authorize a service role that allows Content Moderation to access your OSS resources. The multimodal moderation Enhanced Edition service uses this service role to fetch and moderate files from OSS. Visit the cloud resource access authorization page to create a service role.
-
Log on to the cloud resource access authorization page with your Alibaba Cloud account and grant the required permissions.
-
Install the Node.js SDK.
npm install @alicloud/green20220302@3.2.4 -
Integrate with the Node.js SDK.
-
Submit an asynchronous multimodal moderation task
const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const Util = require('@alicloud/tea-util'); // Note: To improve moderation performance, reuse the client instance whenever possible and avoid repeatedly establishing connections. // Leaking your project's source code can expose your AccessKey and compromise the security of all resources under your account. The following code is for reference only. class Client { static createClient() { const config = new OpenApi.Config({ // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in your runtime environment. accessKeyId: 'Retrieve your AccessKey ID from an environment variable.', // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in your runtime environment. accessKeySecret: 'Retrieve your AccessKey secret from an environment variable.', endpoint: `green-cip.cn-shanghai.aliyuncs.com`, }); return new Green20220302.default(config); } static async main() { const client = Client.createClient(); // Construct the request object. const MultimodalAsyncModerationRequest = new Green20220302.MultimodalAsyncModerationRequest({"dataId":"Multimodal0424***","mainData":{"mainTitle":"Main title","mainContent":"Main text content","mainImages":[{"ossRegionId":"cn-shanghai","ossBucketName":"cip-test","ossObjectName":"123.jpg"},{"ossRegionId":"cn-shanghai","ossBucketName":"cip-test","ossObjectName":"123.jpg"}],"mainPostTime":"2025-06-18 20:20:20"},"commentDatas":[{"images":[{"ossRegionId":"cn-shanghai","ossBucketName":"cip-test","ossObjectName":"123.jpg"},{"ossRegionId":"cn-shanghai","ossBucketName":"cip-test","ossObjectName":"123.jpg"}],"content":"Comment content 1","postTime":"","commentDatas":[{"images":[{"ossRegionId":"cn-shanghai","ossBucketName":"cip-test","ossObjectName":"123.jpg"}],"content":"Reply 1 to comment 1","postTime":"","commentDatas":[]},{"images":[{"ossRegionId":"cn-shanghai","ossBucketName":"cip-test","ossObjectName":"123.jpg"}],"content":"Reply 2 to comment 1","postTime":"","commentDatas":[]}]},{"images":[],"content":"Comment content 2","postTime":"","commentDatas":[]},{"images":[],"content":"Comment content 3","postTime":"","commentDatas":[]},{"images":[],"content":"Comment content 4","postTime":"","commentDatas":[]},{"images":[],"content":"Comment content 5","postTime":"","commentDatas":[]},{"images":[],"content":"Comment content 6","postTime":"","commentDatas":[]},{"images":[],"content":"Comment content 7","postTime":"","commentDatas":[]}]}); // Create a runtime options object. const runtime = new Util.RuntimeOptions(); try { // Send the request and receive the response. const response = await client.multimodalAsyncModerationWithOptions(MultimodalAsyncModerationRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // This is for demonstration purposes only. In a production environment, handle exceptions with care and do not ignore them. // Error message console.log('Error occurred:', error.message); } } } Client.main(); -
Get asynchronous result
const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const Util = require('@alicloud/tea-util'); // Note: To improve moderation performance, reuse the client instance whenever possible and avoid repeatedly establishing connections. // Leaking your project's source code can expose your AccessKey and compromise the security of all resources under your account. The following code is for reference only. class Client { static createClient() { const config = new OpenApi.Config({ // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in your runtime environment. accessKeyId: 'Retrieve your AccessKey ID from an environment variable.', // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in your runtime environment. accessKeySecret: 'Retrieve your AccessKey secret from an environment variable.', endpoint: `green-cip.cn-shanghai.aliyuncs.com`, }); return new Green20220302.default(config); } static async main() { const client = Client.createClient(); // Construct the request object. const DescribeMultimodalModerationResultRequest = new Green20220302.DescribeMultimodalModerationResultRequest({ "reqId": "7A0095D2-865E-5FDC-B7B3-EFB5EA4CXXXX" }); // Create a runtime options object. const runtime = new Util.RuntimeOptions(); try { // Send the request and receive the response. const response = await client.describeMultimodalModerationResultWithOptions(DescribeMultimodalModerationResultRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // This is for demonstration purposes only. In a production environment, handle exceptions with care 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.
This service supports the following two types of image detection.
Moderate public images
Use cases
If the images you want to moderate are accessible via public URLs, the multimodal moderation (Enhanced) service can fetch and moderate the image files from those URLs.
-
Install the C# SDK.
dotnet add package AlibabaCloud.SDK.Green20220302 --version 3.2.4 -
Integrate with the C# SDK.
-
Submit an asynchronous multimodal moderation task
// This file is auto-generated, don't edit it. Thanks. using Newtonsoft.Json; namespace AlibabaCloud.SDK.Green20220302 { public class MultimodalAsyncModerationAutoRoute { public class ImageData { public string imageUrl { get; set; } } public class CommentData { public List<ImageData> images { get; set; } public string content { get; set; } public string postTime { get; set; } public List<CommentData> commentDatas { get; set; } = new List<CommentData>(); } public class MainData { public string mainTitle { get; set; } public string mainContent { get; set; } public List<ImageData> mainImages { get; set; } public string mainPostTime { get; set; } } public class ServiceParameters { public string dataId { get; set; } public MainData mainData { get; set; } public List<CommentData> commentDatas { get; set; } } public static void Main(string[] args) { /** * An AccessKey pair for an Alibaba Cloud account has permissions to call all APIs. We recommend that you use a RAM user for API calls and daily operations. * We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your code. Otherwise, your AccessKey pair may be leaked and the security of all resources in your account may be compromised. * Getting environment variables: * To get the AccessKey ID of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID") * To get the AccessKey Secret of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ String accessKeyId = "We recommend that you retrieve the AccessKey ID of a RAM user from an environment variable."; String accessKeySecret = "We recommend that you retrieve the AccessKey Secret of a RAM user from an environment variable."; // Modify the region and endpoint as needed. String endpoint = "green-cip.cn-shanghai.aliyuncs.com"; // Note: To improve moderation performance, reuse the client instance whenever possible to avoid repeatedly establishing connections. Client client = createClient(accessKeyId, accessKeySecret, endpoint); // Set runtime options. These settings apply only to requests that use this runtime options instance. AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions = new AlibabaCloud.TeaUtil.Models.RuntimeOptions(); Models.MultimodalAsyncModerationRequest multimodalAsyncModerationRequest = new Models.MultimodalAsyncModerationRequest(); multimodalAsyncModerationRequest.Service = "post_text_image_detection"; // Construct the request parameters. var serviceParameters = new ServiceParameters { dataId = "Multimodal0424***", mainData = new MainData { mainTitle = "Main title", mainContent = "Main text content", mainImages = new List<ImageData> { new ImageData { imageUrl = "https://aliyun.com/240308/test001.jpg" }, new ImageData { imageUrl = "https://aliyun.com/240308/test002.jpg" } }, mainPostTime = "2025-06-18 20:20:20" }, commentDatas = new List<CommentData> { new CommentData { images = new List<ImageData> { new ImageData { imageUrl = "https://aliyun.com/240308/test003.jpg" }, new ImageData { imageUrl = "https://aliyun.com/240308/test004.jpg" } }, content = "Comment 1", postTime = "", commentDatas = new List<CommentData> { new CommentData { content = "Reply to comment 1", images = new List<ImageData> { new ImageData { imageUrl = "https://aliyun.com/240308/test005.jpg" } }, postTime = "" }, new CommentData { content = "Reply to comment 1, part 2", images = new List<ImageData> { new ImageData { imageUrl = "https://aliyun.com/240308/test006.jpg" } }, postTime = "" } } }, new CommentData { content = "Comment 2", images = new List<ImageData>(), postTime = "" }, new CommentData { content = "Comment 3", images = new List<ImageData>(), postTime = "" }, new CommentData { content = "Comment 4", images = new List<ImageData>(), postTime = "" }, new CommentData { content = "Comment 5", images = new List<ImageData>(), postTime = "" }, new CommentData { content = "Comment 6", images = new List<ImageData>(), postTime = "" }, new CommentData { content = "Comment 7", images = new List<ImageData>(), postTime = "" } } }; multimodalAsyncModerationRequest.ServiceParameters = JsonConvert.SerializeObject(serviceParameters); try { // Call the API to get the moderation result. Models.MultimodalAsyncModerationResponse response = client.MultimodalAsyncModerationWithOptions( multimodalAsyncModerationRequest, runtimeOptions ); Console.WriteLine(response.Body.RequestId); Console.WriteLine(JsonConvert.SerializeObject(response.Body)); } catch (Exception _err) { Console.WriteLine(_err); } } // Create a client. public static Client createClient( String accessKeyId, String accessKeySecret, String endpoint ) { AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config { AccessKeyId = accessKeyId, AccessKeySecret = accessKeySecret, // Configure an HTTP proxy. //HttpProxy = "http://10.10.xx.xx:xxxx", // Configure an HTTPS proxy. //HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999", // The service endpoint. Endpoint = endpoint, }; return new Client(config); } } } -
Get asynchronous result
// This file is auto-generated, don't edit it. Thanks. using Newtonsoft.Json; namespace AlibabaCloud.SDK.Green20220302 { public class DescribeMultimodalModerationResultAutoRoute { public static void Main(string[] args) { /** * An AccessKey pair for an Alibaba Cloud account has permissions to call all APIs. We recommend that you use a RAM user for API calls and daily operations. * We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your code. Otherwise, your AccessKey pair may be leaked and the security of all resources in your account may be compromised. * Getting environment variables: * To get the AccessKey ID of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID") * To get the AccessKey Secret of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ String accessKeyId = "We recommend that you retrieve the AccessKey ID of a RAM user from an environment variable."; String accessKeySecret = "We recommend that you retrieve the AccessKey Secret of a RAM user from an environment variable."; // Modify the region and endpoint as needed. String endpoint = "green-cip.cn-shanghai.aliyuncs.com"; // Note: To improve moderation performance, reuse the client instance whenever possible to avoid repeatedly establishing connections. Client client = createClient(accessKeyId, accessKeySecret, endpoint); // Set runtime options. These settings apply only to requests that use this runtime options instance. AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions = new AlibabaCloud.TeaUtil.Models.RuntimeOptions(); Models.DescribeMultimodalModerationResultRequest describeMultimodalModerationResultRequest = new Models.DescribeMultimodalModerationResultRequest(); describeMultimodalModerationResultRequest.ReqId = "55BBCC2F-0382-57B3-B001-CA4DB491XXXX"; try { // Call the API to get the moderation result. Models.DescribeMultimodalModerationResultResponse response = client.DescribeMultimodalModerationResultWithOptions( describeMultimodalModerationResultRequest, runtimeOptions ); Console.WriteLine(response.Body.RequestId); Console.WriteLine(JsonConvert.SerializeObject(response.Body)); } catch (Exception _err) { Console.WriteLine(_err); } } // Create a client. public static Client createClient( String accessKeyId, String accessKeySecret, String endpoint ) { AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config { AccessKeyId = accessKeyId, AccessKeySecret = accessKeySecret, // Configure an HTTP proxy. //HttpProxy = "http://10.10.xx.xx:xxxx", // Configure an HTTPS proxy. //HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999", // The service endpoint. Endpoint = endpoint, }; return new Client(config); } } }
-
Moderate OSS images
Use cases
If you store the images in Object Storage Service (OSS), you must authorize Content Moderation to access them. To do this, create a service role on the Cloud Resource Access Authorization page. The multimodal moderation (Enhanced) service will then use this role to fetch and moderate the image files from OSS.
-
Using your Alibaba Cloud account (the main account), go to the Cloud Resource Access Authorization page and grant the required permissions.
-
Install the C# SDK.
dotnet add package AlibabaCloud.SDK.Green20220302 --version 3.2.4 -
Integrate with the C# SDK.
-
Submit an asynchronous multimodal moderation task
// This file is auto-generated, don't edit it. Thanks. using Newtonsoft.Json; namespace AlibabaCloud.SDK.Green20220302 { public class MultimodalAsyncModerationAutoRoute { public class ImageData { public string ossRegionId { get; set; } public string ossBucketName { get; set; } public string ossObjectName { get; set; } } public class CommentData { public List<ImageData> images { get; set; } public string content { get; set; } public string postTime { get; set; } public List<CommentData> commentDatas { get; set; } = new List<CommentData>(); } public class MainData { public string mainTitle { get; set; } public string mainContent { get; set; } public List<ImageData> mainImages { get; set; } public string mainPostTime { get; set; } } public class ServiceParameters { public string dataId { get; set; } public MainData mainData { get; set; } public List<CommentData> commentDatas { get; set; } } public static void Main(string[] args) { /** * An AccessKey pair for an Alibaba Cloud account has permissions to call all APIs. We recommend that you use a RAM user for API calls and daily operations. * We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your code. Otherwise, your AccessKey pair may be leaked and the security of all resources in your account may be compromised. * Getting environment variables: * To get the AccessKey ID of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID") * To get the AccessKey Secret of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ String accessKeyId = "We recommend that you retrieve the AccessKey ID of a RAM user from an environment variable."; String accessKeySecret = "We recommend that you retrieve the AccessKey Secret of a RAM user from an environment variable."; // Modify the region and endpoint as needed. String endpoint = "green-cip.cn-shanghai.aliyuncs.com"; // Note: To improve moderation performance, reuse the client instance whenever possible to avoid repeatedly establishing connections. Client client = createClient(accessKeyId, accessKeySecret, endpoint); // Set runtime options. These settings apply only to requests that use this runtime options instance. AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions = new AlibabaCloud.TeaUtil.Models.RuntimeOptions(); Models.MultimodalAsyncModerationRequest multimodalAsyncModerationRequest = new Models.MultimodalAsyncModerationRequest(); multimodalAsyncModerationRequest.Service = "post_text_image_detection"; // Construct the request parameters. var serviceParameters = new ServiceParameters { dataId = "Multimodal0424***", mainData = new MainData { mainTitle = "Main title", mainContent = "Main text content", mainImages = new List<ImageData> { new ImageData { ossRegionId = "cn-shanghai", ossBucketName = "cip-test", ossObjectName = "123.jpg" }, new ImageData { ossRegionId = "cn-shanghai", ossBucketName = "cip-test", ossObjectName = "123.jpg" } }, mainPostTime = "2025-06-18 20:20:20" }, commentDatas = new List<CommentData> { new CommentData { images = new List<ImageData> { new ImageData { ossRegionId = "cn-shanghai", ossBucketName = "cip-test", ossObjectName = "123.jpg" }, new ImageData { ossRegionId = "cn-shanghai", ossBucketName = "cip-test", ossObjectName = "123.jpg" } }, content = "Comment 1", postTime = "", commentDatas = new List<CommentData> { new CommentData { content = "Reply to comment 1", images = new List<ImageData> { new ImageData { ossRegionId = "cn-shanghai", ossBucketName = "cip-test", ossObjectName = "123.jpg" } }, postTime = "" }, new CommentData { content = "Reply to comment 1, part 2", images = new List<ImageData> { new ImageData { ossRegionId = "cn-shanghai", ossBucketName = "cip-test", ossObjectName = "123.jpg" } }, postTime = "" } } }, new CommentData { content = "Comment 2", images = new List<ImageData>(), postTime = "" }, new CommentData { content = "Comment 3", images = new List<ImageData>(), postTime = "" }, new CommentData { content = "Comment 4", images = new List<ImageData>(), postTime = "" }, new CommentData { content = "Comment 5", images = new List<ImageData>(), postTime = "" }, new CommentData { content = "Comment 6", images = new List<ImageData>(), postTime = "" }, new CommentData { content = "Comment 7", images = new List<ImageData>(), postTime = "" } } }; multimodalAsyncModerationRequest.ServiceParameters = JsonConvert.SerializeObject(serviceParameters); try { // Call the API to get the moderation result. Models.MultimodalAsyncModerationResponse response = client.MultimodalAsyncModerationWithOptions( multimodalAsyncModerationRequest, runtimeOptions ); Console.WriteLine(response.Body.RequestId); Console.WriteLine(JsonConvert.SerializeObject(response.Body)); } catch (Exception _err) { Console.WriteLine(_err); } } // Create a client. public static Client createClient( String accessKeyId, String accessKeySecret, String endpoint ) { AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config { AccessKeyId = accessKeyId, AccessKeySecret = accessKeySecret, // Configure an HTTP proxy. //HttpProxy = "http://10.10.xx.xx:xxxx", // Configure an HTTPS proxy. //HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999", // The service endpoint. Endpoint = endpoint, }; return new Client(config); } } } -
Get asynchronous result
// This file is auto-generated, don't edit it. Thanks. using Newtonsoft.Json; namespace AlibabaCloud.SDK.Green20220302 { public class DescribeMultimodalModerationResultAutoRoute { public static void Main(string[] args) { /** * An AccessKey pair for an Alibaba Cloud account has permissions to call all APIs. We recommend that you use a RAM user for API calls and daily operations. * We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your code. Otherwise, your AccessKey pair may be leaked and the security of all resources in your account may be compromised. * Getting environment variables: * To get the AccessKey ID of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID") * To get the AccessKey Secret of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ String accessKeyId = "We recommend that you retrieve the AccessKey ID of a RAM user from an environment variable."; String accessKeySecret = "We recommend that you retrieve the AccessKey Secret of a RAM user from an environment variable."; // Modify the region and endpoint as needed. String endpoint = "green-cip.cn-shanghai.aliyuncs.com"; // Note: To improve moderation performance, reuse the client instance whenever possible to avoid repeatedly establishing connections. Client client = createClient(accessKeyId, accessKeySecret, endpoint); // Set runtime options. These settings apply only to requests that use this runtime options instance. AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions = new AlibabaCloud.TeaUtil.Models.RuntimeOptions(); Models.DescribeMultimodalModerationResultRequest describeMultimodalModerationResultRequest = new Models.DescribeMultimodalModerationResultRequest(); describeMultimodalModerationResultRequest.ReqId = "55BBCC2F-0382-57B3-B001-CA4DB491XXXX"; try { // Call the API to get the moderation result. Models.DescribeMultimodalModerationResultResponse response = client.DescribeMultimodalModerationResultWithOptions( describeMultimodalModerationResultRequest, runtimeOptions ); Console.WriteLine(response.Body.RequestId); Console.WriteLine(JsonConvert.SerializeObject(response.Body)); } catch (Exception _err) { Console.WriteLine(_err); } } // Create a client. public static Client createClient( String accessKeyId, String accessKeySecret, String endpoint ) { AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config { AccessKeyId = accessKeyId, AccessKeySecret = accessKeySecret, // Configure an HTTP proxy. //HttpProxy = "http://10.10.xx.xx:xxxx", // Configure an HTTPS proxy. //HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999", // The service endpoint. Endpoint = endpoint, }; return new Client(config); } } }
-
Native HTTPS calls
The Content Moderation Enhanced API service also supports native HTTPS calls. This method requires you to manually sign and assemble requests, including the URL, body, headers, and parameters. Native HTTPS calls are typically used only in the following two scenarios. In all other cases, we recommend using an SDK.
-
You call the API directly from an app and have strict client-size requirements.
-
Your project has specific library dependencies that conflict with the SDK or are difficult to upgrade.
-
Call method
Service request endpoint: https://green-cip.{region}.aliyuncs.com
Protocol: HTTPS
Method: POST
-
Common request parameters
API requests for multimodal moderation Enhanced include common request parameters and operation-specific parameters. Common request parameters are required for every API operation. 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 API version in YYYY-MM-DD format. The current version is 2022-03-02.
AccessKeyId
String
Yes
The AccessKey ID issued by Alibaba Cloud to authenticate your request.
Signature
String
Yes
The signature string. For information about how to calculate the signature, see the "Signature method" section below.
SignatureMethod
String
Yes
The signature method. Currently, only HMAC-SHA1 is supported.
Timestamp
String
Yes
The timestamp of the request. The time must be in UTC and follow the ISO 8601 standard. The format is yyyy-MM-ddTHH:mm:ssZ. For example, 09:13:14 on December 12, 2022 (UTC+8) is represented as 2022-12-12T01:13:14Z.
SignatureVersion
String
Yes
The signature algorithm version. Set the value to 1.0.
SignatureNonce
String
Yes
A unique random number, or nonce, used to prevent replay attacks. You must use a different nonce for each request.
Action
String
Yes
-
MultimodalAsyncModeration: Performs asynchronous multimodal moderation.
-
DescribeMultimodalModerationResult: Gets the result of a multimodal moderation task.
-
-
Common response parameters
The system returns a unique request ID for every API call, regardless of whether it is successful. Other response parameters, such as label and confidence score, vary by operation. For details, see the API reference for the specific operation.
-
Code examples
The following examples are formatted for readability. The actual responses are not formatted with line breaks or indentation.
The following example shows a request to the multimodal moderation Enhanced API. For the operation-specific parameters of other operations, see their respective API reference topics.
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=MultimodalAsyncModeration &AccessKeyId=123****cip &Timestamp=2022-12-12T12:00:00Z &Service=baselineCheck &ServiceParameters={"mainData": {"":""},"commentDatas": [{"":""}]}The following example shows the JSON response returned by the multimodal moderation Enhanced API:
{ 'Code': 200, 'Data': { 'ReqId': '60BC35C9-293F-1335-8220-F1215A94XXXX' }, 'Msg': 'success', 'RequestId': '60BC35C9-293F-1335-8220-F1215A94XXXX' } -
Signature method
The multimodal image-text moderation Enhanced Edition service authenticates every request. Therefore, you must include a signature in each request. The multimodal image-text moderation Enhanced Edition service verifies the identity of the request sender by using symmetric encryption with an AccessKey ID and an AccessKey Secret.
The AccessKey ID and AccessKey Secret are issued by Alibaba Cloud. You can apply for and manage them on the Alibaba Cloud website. The AccessKey ID identifies the user, while the AccessKey Secret is a private key used to encrypt the signature string. You must keep your AccessKey Secret strictly confidential.
To sign a request, follow these steps:
-
Create a canonicalized query string from the request parameters.
-
Sort all request parameters (including common request parameters and operation-specific parameters, but excluding the Signature parameter itself) alphabetically by parameter name.
-
URL-encode the name and value of each parameter by using the UTF-8 character set.
NoteMost libraries that support URL encoding, such as
java.net.URLEncoderin Java, follow the rules of theapplication/x-www-form-urlencodedMIME type. You can use these libraries for encoding. After encoding, replace plus signs (+) with%20, asterisks (*) with%2A, and%7Ewith 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), hyphens (-), underscores (_), periods (.), or tildes (~).
-
Other characters are encoded into the
%XYformat, where XY is the hexadecimal representation of the character's ASCII code. For example, the double quotation mark (") is encoded as%22. -
Extended UTF-8 characters are encoded into the
%XY%ZA…format. -
Note that a space character ( ) is encoded as
%20, and not a plus sign (+).
-
-
Join the encoded parameter name and its value with an equal sign (=).
-
Join the resulting key-value pairs with ampersands (&) in alphabetical order to create the canonicalized query string.
-
-
Use the canonicalized query string from Step 1 to construct the string-to-sign according to the following format:
StringToSign= HTTPMethod + "&" + percentEncode("/") + "&" + percentEncode(CanonicalizedQueryString)NoteHTTPMethod 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 a.ii, which is
%2F. percentEncode(CanonicalizedQueryString) is the string obtained by encoding the canonicalized query string constructed in a.i according to the URL encoding rules described in a.ii. -
Calculate the HMAC value of the string-to-sign as defined in RFC 2104.
NoteNote: The key used to calculate the signature is your AccessKey Secret followed by a
&character (ASCII: 38), and the hash algorithm used is SHA1. -
Encode the HMAC value with Base64 encoding to create the signature string.
-
Add the resulting signature string to the request as the
Signatureparameter. This completes the signing process.NoteWhen you add the signature to the final request, it must also be URL encoded like all other parameters, according to RFC 3986.
-