Document content moderation

Updated at:

This topic describes the request syntax and provides examples for the Tongyi ZoneWit document content moderation API.

Request syntax

POST /zhiwen-chat/audit HTTP/1.1

Request parameters

Name

Type

Required

Description

Example

capabilityType

string

Yes

The capability type.

Content moderation for documents: CONTENT_REVIEW

CONTENT_REVIEW

userPrompt

string

Yes

The prompt.

You are an experienced senior document review expert, proficient in fraud detection, compliance checks, fact-checking, and professional communication. Your review standards are extremely strict, detail-oriented, and you provide constructive revision suggestions. Your task is to conduct a comprehensive and in-depth review of the provided document. Identify all issues within the document and generate a structured review report.

fileIdList

array

Yes

The list of document IDs.

[

"file_zhiwen_XXX"

]

stream

boolean

Yes

Specifies whether to return the response in a stream.

true

Response parameters

Name

Type

Description

output

object

-choices

array

-finishReason

string

Termination reason

-message

object

The message body.

-role

string

The role.

-content

string

The message content.

requestId

string

The request ID.

usage

object

The token usage information.

-inputTokens

int

The number of input tokens.

-outputTokens

int

The number of output tokens.

-totalTokens

int

The total number of tokens.

Examples

Request example

import os
import requests

'''
API name: Content Moderation
API path: https://dashscope.aliyuncs.com/api/v2/apps/zhiwen-chat/audit
Environment requirements: Python >= 3.7
'''

url = "https://dashscope.aliyuncs.com/api/v2/apps/zhiwen-chat/audit"
request_headers = {
    "Authorization": os.environ.get("DASHSCOPE_API_KEY"),  # If you have not configured the environment variable, replace your API-KEY here.
    "Content-Type": "application/json"
}
# Content moderation: CONTENT_REVIEW
request_body = {
    "capabilityType": "CONTENT_REVIEW",
    "userPrompt": "You are an experienced senior document review expert, proficient in fraud detection, compliance checks, fact-checking, and professional communication. Your review standards are extremely strict, detail-oriented, and you provide constructive revision suggestions. Your task is to conduct a comprehensive and in-depth review of the provided document. Identify all issues within the document and generate a structured review report.",
    "stream": True,
    "fileIdList": [
        "file_zhiwen_XXX"  # Replace with your document ID.
    ]
}

with requests.post(url, json=request_body, headers=request_headers) as response:
    if request_body["stream"]:
        for line in response.iter_lines():
            if line:
                line = line.decode('utf-8')
                if line.startswith('data:'):
                    print("Received:", line[5:].strip())
    else:
        print("Received:", response.json())

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.util.HashMap;
import java.util.Map;

/**
 * API name: Content Moderation
 * API path: https://dashscope.aliyuncs.com/api/v2/apps/zhiwen-chat/audit
 * Environment requirements: Java 8 or later
 */
public class AuditDemo {
    // Step 1. API address and configuration
    private static final String API_KEY = System.getenv("DASHSCOPE_API_KEY");   // Enter the API KEY from the Alibaba Cloud Model Studio platform.
    private static final String API_URL = "https://dashscope.aliyuncs.com/api/v2/apps/zhiwen-chat/audit";
    private static final String CHARSET = "UTF-8";
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static void main(String[] args) throws IOException, InterruptedException {
        // Step 2. Configure request parameters.
        // The fileId field (format: file_zhiwen_XXX) returned by the document upload API.
        String fileId = "file_zhiwen_XXX";
        // Custom prompt: Modify this based on your business needs. For an example, see the Debug page of the Tongyi ZoneWit lightweight application.
        String userPrompt = "You are an experienced senior document review expert, proficient in fraud detection, compliance checks, fact-checking, and professional communication. Your review standards are extremely strict, detail-oriented, and you provide constructive revision suggestions. Your task is to conduct a comprehensive and in-depth review of the provided document. Identify all issues within the document and generate a structured review report.";
        // Streaming: This example uses streaming output. Configure this based on your business needs.
        boolean isStreaming = true;

        // Step 3. Build the request body.
        Map<String, Object> requestBodyMap = new HashMap<>();
        requestBodyMap.put("capabilityType", "CONTENT_REVIEW");
        requestBodyMap.put("userPrompt", userPrompt);
        requestBodyMap.put("stream", isStreaming);
        requestBodyMap.put("fileIdList", new String[]{fileId});
        String requestBody = objectMapper.writeValueAsString(requestBodyMap);

        // Step 4. Configure the request timeout period.
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30 * 1000).build();

        // Step 5. Execute the request. Choose between a streaming or non-streaming request as needed.
        try (CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build()) {

            // Construct the HTTP POST request.
            HttpPost httpPost = new HttpPost(API_URL);
            buildRequestHeaders(httpPost, requestBody);

            // Execute the request: This example uses streaming output. Configure the stream parameter as needed.
            buildStreamingRequest(httpClient, httpPost); // Streaming request
            // buildNonStreamingRequest(httpClient, httpPost); // Non-streaming request
        }
    }

    /**
     * Builds common request headers.
     *
     * @param httpPost The HTTP request object.
     * @param requestBody The request body string.
     */
    private static void buildRequestHeaders(HttpPost httpPost, String requestBody) {
        httpPost.setHeader("Authorization", API_KEY);
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setEntity(new StringEntity(requestBody, CHARSET));
    }

    /**
     * Builds a streaming request.
     * @param client The HTTP client.
     * @param httpPost The HTTP request object.
     * @return The CompletableFuture object for asynchronous execution.
     */
    private static void buildStreamingRequest(CloseableHttpClient client, HttpPost httpPost) {
        System.out.println("Streaming request:");
        try (CloseableHttpResponse response = client.execute(httpPost)) {
            HttpEntity entity = response.getEntity();
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200 && entity != null) {
                try (InputStream inputStream = entity.getContent();
                     BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        if (line.startsWith("data:")) {
                            String json = line.substring(5).trim();
                            System.out.println(json);
                        }
                    }
                }
            } else {
                String errorBody = EntityUtils.toString(response.getEntity());
                System.err.println("Request failed: " + errorBody);
            }
        } catch (IOException e) {
            System.err.println("Request failed: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * Builds a non-streaming request.
     * @param client The HTTP client.
     * @param httpPost The HTTP request object.
     * @throws IOException Thrown when a network request or data read error occurs.
     */
    private static void buildNonStreamingRequest(CloseableHttpClient client, HttpPost httpPost) throws IOException {
        System.out.println("Non-streaming request:");
        try (CloseableHttpResponse response = client.execute(httpPost)) {
            HttpEntity entity = response.getEntity();
            if (entity == null) {
                System.err.println("Response body is empty");
                return;
            }
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200 && entity != null){
                String responseBody = EntityUtils.toString(entity);
                System.out.println(responseBody);
            }else{
                String errorBody = EntityUtils.toString(entity);
                System.err.println("Request failed: " + errorBody);
            }
        }catch (IOException e) {
            System.err.println("Request failed: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

Successful response example

JSON format

{
  "output": {
    "choices": [{
      "finishReason": "stop",
      "message": {
        "role": "assistant",
        "content": "**Document Review Report: XXX.pdf**\nDocument content moderation results.\n**Note**: This report is generated based on the provided text. The actual review may require further refinement based on the complete document and its context."
      }
    }]
  },
  "requestId": "08bd24d4-6c85-9b2e-9ead-c9480b4b1651",
  "usage": {
    "inputTokens": 100,
    "outputTokens": 100,
    "totalTokens": 200
  }
}

Error codes

For more information, see Error codes for Tongyi ZoneWit.