
关于
适用于 Python 的 Azure AI 内容安全 SDK。用于检测文本和图像中的有害内容,支持多严重级别分类。
name: azure-ai-contentsafety-py description: "Azure AI内容安全Python SDK。用于检测文本和图像中的有害内容,支持多严重级别分类。" risk: unknown source: community date_added: '2026-02-27'
Azure AI 内容安全 Python SDK
检测应用程序中有害的用户生成和AI生成内容。
安装
pip install azure-ai-contentsafety
环境变量
CONTENT_SAFETY_ENDPOINT=https://<resource>.cognitiveservices.azure.com
CONTENT_SAFETY_KEY=<your-api-key>
认证
API Key
from azure.ai.contentsafety import ContentSafetyClient
from azure.core.credentials import AzureKeyCredential
import os
client = ContentSafetyClient(
endpoint=os.environ["CONTENT_SAFETY_ENDPOINT"],
credential=AzureKeyCredential(os.environ["CONTENT_SAFETY_KEY"])
)
Entra ID
from azure.ai.contentsafety import ContentSafetyClient
from azure.identity import DefaultAzureCredential
client = ContentSafetyClient(
endpoint=os.environ["CONTENT_SAFETY_ENDPOINT"],
credential=DefaultAzureCredential()
)
分析文本
from azure.ai.contentsafety.models import AnalyzeTextOptions, TextCategory
request = AnalyzeTextOptions(text="要分析的文本内容")
response = client.analyze_text(request)
# 检查每个类别
for category in [TextCategory.HATE, TextCategory.SELF_HARM,
TextCategory.SEXUAL, TextCategory.VIOLENCE]:
result = next((r for r in response.categories_analysis
if r.category == category), None)
if result:
print(f"{category}: severity {result.severity}")
分析图像
from azure.ai.contentsafety.models import AnalyzeImageOptions, ImageData
import base64
# 从文件
with open("image.jpg", "rb") as f:
image_data = base64.b64encode(f.read()).decode("utf-8")
request = AnalyzeImageOptions(image=ImageData(content=image_data))
response = client.analyze_image(request)
for result in response.categories_analysis:
print(f"{result.category}: severity {result.severity}")
从URL分析图像
request = AnalyzeImageOptions(
image=ImageData(blob_url="https://example.com/image.jpg")
)
严重级别
| 级别 | 含义 | |------|------| | 0 | 安全 | | 2 | 低严重度 | | 4 | 中严重度 | | 6 | 高严重度 |
类别
- Hate:仇恨和歧视内容
- SelfHarm:自我伤害相关内容
- Sexual:性相关内容
- Violence:暴力内容
自定义黑名单
from azure.ai.contentsafety.models import (
TextBlocklist, AddOrUpdateTextBlocklistItemsOptions,
TextBlocklistItem
)
# 创建黑名单
client.create_or_update_text_blocklist(
blocklist_name="custom-blocklist",
options=TextBlocklist(description="自定义屏蔽词列表")
)
# 添加屏蔽项
client.add_or_update_blocklist_items(
blocklist_name="custom-blocklist",
options=AddOrUpdateTextBlocklistItemsOptions(
blocklist_items=[TextBlocklistItem(text="屏蔽词")]
)
)
常见问题
- 401错误:检查API密钥或Entra ID凭证
- 严重级别为0:内容被判定为安全
- 超时:大文本建议分段分析
兼容工具
Claude CodeCursor
标签
后端开发
