Moderation Agent SDK

更新时间:
复制 MD 格式

The moderation agent service supports calls made with a software development kit (SDK) or native HTTPS. We recommend that you use an SDK because it handles details such as signature verification and body format construction. This topic describes the SDKs for the moderation agent service and how to connect to them.

Step 1: Activate the service

Go to the Activate Service page and activate the Content Moderation Enhanced Edition service.

After you activate the Content Moderation Enhanced Edition service, the default billing method is pay-as-you-go. You are billed daily based on your actual usage, and you are not charged if you do not call the service. After you integrate and use the API, the system automatically generates bills based on your usage. For more information, see Billing Details.

Step 2: Create a RAM user and grant permissions

To integrate an SDK, you must create a user identity, obtain its AccessKey, and grant it permissions to access cloud resources. This topic describes how to create a RAM user, obtain an AccessKey, and grant permissions to call the image detection service of Content Moderation 2.0. For more information, see Integrate an SDK.

  1. Log in to the RAM console with your Alibaba Cloud account (root account) or a RAM user that has administrative permissions.

  2. Create a RAM user, select OpenAPI Call Access, and record the AccessKey generated for the RAM user. For more information, see Create a RAM user.

  3. Grant the AliyunYundunGreenWebFullAccess system policy to the RAM user. For more information, see Manage RAM user permissions.

Step 3: Install and connect to the SDK

The following regions are supported:

Region

Public endpoint

Private endpoint

China (Shanghai)

https://green-cip.cn-shanghai.aliyuncs.com

https://green-cip-vpc.cn-shanghai.aliyuncs.com

Note

If you need SDK sample code for other languages, you can go to the OpenAPI Developer Portal to debug an API operation online. The tool automatically generates SDK call sample code for the corresponding API.

Alibaba Cloud SDKs create default credentials by reading the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables. When you call an API operation, the program reads your AccessKey from these variables and automatically completes authentication. Before you use SDK sample code, you must configure the environment variables. For more information, see Configure authentication credentials.

For more information about the API operation fields, see Synchronous moderation agent API guide.

Java SDK

Usage notes

Moderate images that are accessible over the public network

Scenarios

When an image to be moderated is available at a public URL, the Image Moderation Enhanced Edition service can retrieve the image file from the URL to perform moderation.

  1. Add the following dependency to the pom.xml file to install the Java SDK. You can then use the SDK in your Maven project.

    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>green20220302</artifactId>
        <version>3.3.3</version>
    </dependency>
  2. Connect to the Java SDK.

    • Integration Example

    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONObject;
    import com.aliyun.green20220302.Client;
    import com.aliyun.green20220302.models.*;
    import com.aliyun.teaopenapi.models.Config;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.UUID;
    
    public class MultiModalAgentDemo {
    
        public static void main(String[] args) throws Exception {
            Config config = new Config();
            /**
             * An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you 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 a RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     Obtain the AccessKey secret of a RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             * Method 2:
             *     Obtain the AccessKey ID of a RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     Obtain the AccessKey secret of a RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             */
            config.setAccessKeyId("Obtain the AccessKey ID of your RAM user from an environment variable.");
            config.setAccessKeySecret("Obtain the AccessKey secret of your RAM user from an environment variable.");
    
            // Modify the region and endpoint as needed.
            config.setRegionId("cn-shanghai");
            config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com");
            // The read timeout period. Unit: milliseconds (ms).
            config.setReadTimeout(20000);
            // The connection timeout period. Unit: milliseconds (ms).
            config.setConnectTimeout(10000);
            // 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);
            // Process input parameters.
            JSONObject serviceParameters = new JSONObject();
            // The image to be moderated. A maximum of one image is supported.
            List<JSONObject> images = new ArrayList<>();
            JSONObject image = new JSONObject();
            image.put("imageUrl","https://img.alicdn.com/tfs/xxxxxxxxxx001.png");
            images.add(image);
            serviceParameters.put("images", images);
            // The text to be moderated. The maximum length is 2,000 characters.
            serviceParameters.put("content", "Sample text content");
            // The business ID.
            serviceParameters.put("dataId", UUID.randomUUID());
            MultiModalAgentRequest multiModalAgentRequest = new MultiModalAgentRequest();
            // The moderation type.
            // Text moderation: txt_check_agent_01
            // Image moderation: img_check_agent_01
            // Multimodal moderation: img_txt_check_agent_01
            multiModalAgentRequest.setAppID("img_txt_check_agent_01");
            multiModalAgentRequest.setServiceParameters(serviceParameters.toJSONString());
    
            try {
                MultiModalAgentResponse response = client.multiModalAgent(multiModalAgentRequest);
                if (response.getStatusCode() == 200) {
                    MultiModalAgentResponseBody result = response.getBody();
                    System.out.println(JSON.toJSONString(result));
                } else {
                    System.out.println("response not success. status:" + response.getStatusCode());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

Python SDK

Usage notes

  • Environment: Python 3.6 or later.

  • Source code: For the source code, see Python SDK source code.

  • Features: Only moderation of images that are accessible over the public network is supported.

Moderate images that are accessible over the public network

Scenarios

When an image to be moderated is available at a public URL, the Image Moderation Enhanced Edition service can retrieve the image file from the URL to perform moderation.

  1. Run the following command to install the SDK.

    python3
    pip install alibabacloud_green20220302==3.2.4
  2. Connect to the Python SDK.

  3. # 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
    import uuid
    
    config = Config(
        # An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M.
        # We strongly recommend that you do not save your AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which threatens the security of all your resources.
        # Common methods to obtain environment variables:
        # Obtain the AccessKey ID of a RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
        # Obtain the AccessKey secret of a RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
        access_key_id='Obtain the AccessKey ID of your RAM user from an environment variable.',
        access_key_secret='Obtain the AccessKey secret of your 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=20000,
        region_id='cn-shanghai',
        endpoint='green-cip.cn-shanghai.aliyuncs.com'
    )
    
    clt = Client(config)
    
    serviceParameters = {
        # The text to be moderated. The maximum length is 2,000 characters.
        'content': 'Sample text content',
        # The image to be moderated. A maximum of one image is supported.
        'images': {'imageUrl':'https://img.alicdn.com/tfs/xxxxxxxxxx001.png'},
        # The business ID.
        'dataId':uuid.uuid4().hex
    }
    multiModalAgentRequest = models.MultiModalAgentRequest(
        # The moderation type.
        # Text moderation: txt_check_agent_01
        # Image moderation: img_check_agent_01
        # Multimodal moderation: img_txt_check_agent_01
        app_id='img_txt_check_agent_01',
        service_parameters=json.dumps(serviceParameters)
    )
    
    try:
        response = clt.multi_modal_agent(multiModalAgentRequest)
        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)

If you encounter any problems, please join the DingTalk group (Group No.: 35573806) and contact a product technical expert for assistance.