Use AI Guardrails SDK for Python to detect spam content in text, including pornographic and terrorist material.
Text anti-spam uses synchronous moderation only. You are charged per text entry moderated, not per request — a single request can include multiple text entries. For pricing details, see Billing overview.
Prerequisites
Before you begin, make sure you have:
Python dependencies installed using the Python version specified in the Installation guide — using a different Python version causes operation calls to fail
The Extension.Uploader utility class downloaded and imported into your project
Your AccessKey ID and AccessKey secret stored as environment variables:
ImportantNever hardcode your AccessKey credentials directly in your code. Use environment variables or a secrets manager to keep credentials out of source control.
export ALIBABA_CLOUD_ACCESS_KEY_ID='<your-access-key-id>' export ALIBABA_CLOUD_ACCESS_KEY_SECRET='<your-access-key-secret>'
How it works
Initialize an
AcsClientwith your credentials and target region. Reuse the client across requests to improve performance and avoid repeated connections.Create a
TextScanRequestobject for each request. Request objects cannot be reused.Set the
scenesparameter toantispamand submit one or more text entries in thetasksarray.Parse the response: check
suggestionin each result to decide the next action.
For the full list of request and response parameters, see /green/text/scan.
Submit a text moderation task
Use TextScanRequest to submit text entries for anti-spam moderation.
Supported regions
| Region ID | Location |
|---|---|
cn-shanghai | China (Shanghai) |
cn-beijing | China (Beijing) |
cn-shenzhen | China (Shenzhen) |
ap-southeast-1 | Singapore |
Sample code
# coding=utf-8
from aliyunsdkcore import client
from aliyunsdkcore.profile import region_provider
from aliyunsdkgreen.request.v20180509 import TextScanRequest
import json, uuid, datetime, os
# Reuse the client across requests to improve performance.
# Obtain credentials from environment variables — never hardcode them.
clt = client.AcsClient(
os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
"cn-shanghai"
)
region_provider.modify_point('Green', 'cn-shanghai', 'green.cn-shanghai.aliyuncs.com')
# Create a new request object for each request — request objects cannot be reused.
request = TextScanRequest.TextScanRequest()
request.set_accept_format('JSON')
task1 = {
"dataId": str(uuid.uuid1()), # Unique ID for this text entry
"content": "textContentToBeModerated",
"time": datetime.datetime.now().microsecond
}
# Set scenes to antispam and include one or more tasks.
request.set_content(bytearray(
json.dumps({"tasks": [task1], "scenes": ["antispam"]}), "utf-8"
))
response = clt.do_action_with_exception(request)
result = json.loads(response)
if result["code"] == 200:
for task_result in result["data"]:
if task_result["code"] == 200:
for scene_result in task_result["results"]:
scene = scene_result["scene"]
suggestion = scene_result["suggestion"]
# Take action based on suggestion: pass, review, or block.Understanding the response
The suggestion field in each result tells you the recommended action:
| Value | Meaning |
|---|---|
pass | Content is safe — no action needed |
review | Content needs human review |
block | Content violates policy — reject or remove it |
Use custom terms
Add custom terms — such as competitor brand names — to a text library. When moderated text contains a custom term, the response returns suggestion: block.
Add terms in the AI Guardrails console or by calling an API operation.
Provide feedback on moderation results
If a result is incorrect, use TextFeedbackRequest to correct it. The system updates its text library based on your feedback and applies the correction to future submissions that match the same text pattern.
Supported regions: cn-shanghai, cn-beijing, cn-shenzhen, ap-southeast-1
Sample code
# coding=utf-8
from aliyunsdkcore import client
from aliyunsdkcore.profile import region_provider
from aliyunsdkgreen.request.v20180509 import TextFeedbackRequest
import json, os
clt = client.AcsClient(
os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
"cn-shanghai"
)
region_provider.modify_point('Green', 'cn-shanghai', 'green.cn-shanghai.aliyuncs.com')
request = TextFeedbackRequest.TextFeedbackRequest()
request.set_accept_format('JSON')
request.set_content(json.dumps({
"dataId": "<data-id>", # ID of the moderated text entry
"taskId": "<task-id>", # ID returned in the moderation response
"content": "<text-content>",
"label": "spam",
"note": "<remarks>"
}))
try:
response = clt.do_action_with_exception(request)
result = json.loads(response)
if result["code"] == 200:
print("Feedback submitted successfully.")
except Exception as err:
print(err)Required fields
| Field | Description |
|---|---|
dataId | ID of the moderated text entry |
taskId | Task ID returned in the original moderation response |
content | The text content that was moderated |
label | Correction label, for example spam |
note | Remarks explaining the correction |
What's next
/green/text/scan API reference — full parameter reference for text moderation requests
Billing overview — understand how text moderation is priced
Installation — set up AI Guardrails SDK for Python