访问内容审核 cookbook,查看使用 Claude 实现内容审核的示例。
以下是一些关键指标,表明您应该使用像 Claude 这样的 LLM,而不是传统的机器学习或基于规则的方法来进行内容审核:
在开发内容审核解决方案之前,首先创建应该被标记的内容和不应该被标记的内容的示例。确保包含边缘情况和具有挑战性的场景,这些场景可能难以被内容审核系统有效处理。之后,审查您的示例以创建一个明确定义的审核类别列表。 例如,社交媒体平台生成的示例可能包括以下内容:
client = anthropic.Anthropic()
allowed_user_comments = [
"This movie was great, I really enjoyed it. The main actor really killed it!",
"I hate Mondays.",
"It is a great time to invest in gold!",
]
disallowed_user_comments = [
"Delete this post now or you better hide. I am coming after you and your family.",
"Stay away from the 5G cellphones!! They are using 5G to control you.",
"Congratulations! You have won a $1,000 gift card. Click here to claim your prize!",
]
# 用于测试内容审核的示例用户评论
user_comments = allowed_user_comments + disallowed_user_comments
# 内容审核中被视为不安全的类别
unsafe_categories = [
"Child Exploitation",
"Conspiracy Theories",
"Hate",
"Indiscriminate Weapons",
"Intellectual Property",
"Non-Violent Crimes",
"Privacy",
"Self-Harm",
"Sex Crimes",
"Sexual Content",
"Specialized Advice",
"Violent Crimes",
]有效地审核这些示例需要对语言有细致入微的理解。在评论 This movie was great, I really enjoyed it. The main actor really killed it! 中,内容审核系统需要识别出 "killed it" 是一种比喻,而不是实际暴力的表示。相反,尽管没有明确提及暴力,评论 Delete this post now or you better hide. I am coming after you and your family. 应该被内容审核系统标记。
不安全类别可以根据您的特定需求进行自定义。例如,如果您想防止未成年人在您的网站上创建内容,您可以在类别中添加"未成年人发帖"。
在选择模型时,考虑数据的规模非常重要。如果成本是一个考虑因素,像 Claude Haiku 4.5 这样的较小模型因其成本效益而是一个绝佳的选择。以下是对一个每月收到 10 亿条帖子的社交媒体平台进行文本审核的成本估算:
内容规模
预估令牌数
Claude Haiku 4.5 预估成本
Claude Opus 5 预估成本
Claude Opus 4.8 预估成本
explanation 字段,可以进一步减少输出令牌。要使用 Claude 进行内容审核,Claude 必须理解您应用程序的审核要求。首先编写一个提示,让您能够定义您的审核需求:
def moderate_message(message, unsafe_categories):
# 将不安全类别转换为字符串,每个类别占一行
unsafe_category_str = "\n".join(unsafe_categories)
# 构建发送给 Claude 的提示,包含消息和不安全类别
assessment_prompt = f"""
Determine whether the following message warrants moderation,
based on the unsafe categories outlined below.
Message:
<message>{message}</message>
Unsafe Categories:
<categories>
{unsafe_category_str}
</categories>
Respond with ONLY a JSON object, using the format below:
{{
"violation": <Boolean field denoting whether the message should be moderated>,
"categories": [Comma-separated list of violated categories],
"explanation": [Optional. Only include if there is a violation.]
}}
Do not include markdown formatting or code fences in your response."""
# 向 Claude 发送内容审核请求
response = client.messages.create(
model="claude-haiku-4-5-20251001", # Using the Haiku model for lower costs
max_tokens=200,
messages=[{"role": "user", "content": assessment_prompt}],
)
# 解析 Claude 返回的 JSON 响应
text_block = next(block for block in response.content if block.type == "text")
assessment = json.loads(text_block.text)
# 从评估结果中提取违规状态
contains_violation = assessment["violation"]
# 如果存在违规,获取类别和解释;否则使用空的默认值
violated_categories = assessment.get("categories", []) if contains_violation else []
explanation = assessment.get("explanation") if contains_violation else None
return contains_violation, violated_categories, explanation
# 处理每条评论并打印结果
for comment in user_comments:
print(f"\nComment: {comment}")
violation, violated_categories, explanation = moderate_message(
comment, unsafe_categories
)
if violation:
print(f"Violated Categories: {', '.join(violated_categories)}")
print(f"Explanation: {explanation}")
else:
print("No issues detected.")在此示例中,moderate_message 函数包含一个评估提示,其中包括不安全内容类别和要评估的消息。该提示要求 Claude 根据您之前定义的不安全类别来评估消息是否应该被审核。
然后解析模型的评估结果以确定是否存在违规。如果存在违规,Claude 还会返回违规类别列表以及该消息不安全的原因解释。
内容审核是一个分类问题。因此,您可以使用分类 cookbook 中概述的相同技术来确定内容审核系统的准确性。
另一个需要考虑的因素是,您可以创建多个类别来表示不同的风险级别,而不是将内容审核视为二元分类问题。创建多个风险级别可以让您调整审核的严格程度。例如,您可能希望自动阻止被认为高风险的用户查询,而将有许多中等风险查询的用户标记为需要人工审查。
def assess_risk_level(message, unsafe_categories):
# 将不安全类别转换为字符串,每个类别占一行
unsafe_category_str = "\n".join(unsafe_categories)
# 构建发送给 Claude 的提示,包含消息、不安全类别和风险等级定义
assessment_prompt = f"""
Assess the risk level of the following message,
based on the unsafe categories listed below.
Message:
<message>{message}</message>
Unsafe Categories:
<categories>
{unsafe_category_str}
</categories>
Assign a risk level based on your confidence that the user's message should be moderated
based on the defined unsafe categories:
0 - No risk
1 - Low risk
2 - Medium risk
3 - High risk
Respond with ONLY a JSON object, using the format below:
{{
"risk_level": <Numerical field denoting the risk level>,
"categories": [Comma-separated list of violated categories],
"explanation": <Optional. Only include if risk level is greater than 0>
}}
Do not include markdown formatting or code fences in your response."""
# 向 Claude 发送风险评估请求
response = client.messages.create(
model="claude-haiku-4-5-20251001", # Using the Haiku model for lower costs
max_tokens=200,
messages=[{"role": "user", "content": assessment_prompt}],
)
# 解析 Claude 返回的 JSON 响应
text_block = next(block for block in response.content if block.type == "text")
assessment = json.loads(text_block.text)
# 从评估结果中提取风险等级、违规类别和解释
risk_level = assessment["risk_level"]
violated_categories = assessment["categories"]
explanation = assessment.get("explanation")
return risk_level, violated_categories, explanation
# 处理每条评论并打印结果
for comment in user_comments:
print(f"\nComment: {comment}")
risk_level, violated_categories, explanation = assess_risk_level(
comment, unsafe_categories
)
print(f"Risk Level: {risk_level}")
if violated_categories:
print(f"Violated Categories: {', '.join(violated_categories)}")
if explanation:
print(f"Explanation: {explanation}")此代码实现了一个 assess_risk_level 函数,该函数使用 Claude 来评估消息的风险级别。该函数接受消息和不安全类别作为输入。
在函数内部,为 Claude 生成一个提示,其中包括要评估的消息、不安全类别以及评估风险级别的具体说明。该提示指示 Claude 以 JSON 对象的形式响应,其中包括风险级别、违规类别和可选的解释。
这种方法通过分配风险级别实现了灵活的内容审核。它可以无缝集成到更大的系统中,根据评估的风险级别自动过滤内容或标记评论以供人工审查。例如,运行此代码时,评论 Delete this post now or you better hide. I am coming after you and your family. 因其危险威胁而被识别为高风险。相反,评论 Stay away from the 5G cellphones!! They are using 5G to control you. 被归类为中等风险。
一旦您对解决方案的质量有信心,就可以将其部署到生产环境中。以下是在生产环境中使用内容审核时应遵循的一些最佳实践:
向用户提供清晰的反馈: 当用户输入因内容审核而被阻止或响应被标记时,提供信息丰富且具有建设性的反馈,帮助用户理解为什么他们的消息被标记以及如何适当地重新表述。在前面的编码示例中,这是通过 Claude 响应中的 explanation 字段完成的。
分析被审核的内容: 跟踪您的审核系统标记的内容类型,以识别趋势和潜在的改进领域。
持续评估和改进: 使用精确率和召回率跟踪等指标定期评估内容审核系统的性能。使用这些数据迭代地优化您的审核提示、关键词和评估标准。
在复杂场景中,除了标准的提示工程技术之外,考虑其他策略来提升性能可能会有所帮助。以下是一些高级策略:
除了在提示中列出不安全类别之外,还可以通过提供与每个类别相关的定义和短语来进一步改进。
# 内容审核中被视为不安全的类别及其定义
unsafe_category_definitions = {
"Child Exploitation": "Content that depicts child nudity or that enables, encourages, excuses, or depicts the sexual abuse of children.",
"Conspiracy Theories": """Content that promotes or endorses unfounded, false, or misleading theories about events, situations, or individuals,
which can incite harm or undermine public trust in institutions or facts.""",
"Hate": """Content that is hateful toward people on the basis of their protected characteristics
(race, color, ethnicity, national origin, disability, religious affiliation, caste, sexual orientation, sex, gender identity and serious disease),
or content that perpetuates negative stereotypes.""",
"Indiscriminate Weapons": "Content that enables the creation of weapons of mass destruction.",
"Intellectual Property": "Content that violates the intellectual property rights of third parties.",
"Non-Violent Crimes": "Content that enables, encourages, or excuses the commission of non-violent crimes.",
"Privacy": "Content that contains sensitive, personal information about private individuals.",
"Self-Harm": "Content that enables, encourages, or excuses acts of intentional self-harm.",
"Sex Crimes": "Content that enables, encourages, or excuses the commission of sex crimes.",
"Sexual Content": "Content that contains erotic descriptions or explicit depictions of sex acts.",
"Specialized Advice": """Content that contains financial, medical, or legal advice.
Financial advice includes guidance on investments, stocks, bonds, or any financial planning.""",
"Violent Crimes": "Content that enables, encourages, or excuses the commission of violent crimes.",
}
def moderate_message_with_definitions(message, unsafe_category_definitions):
# 格式化不安全类别字符串,每个类别及其定义占一行
unsafe_category_str = "\n".join(
f"{category}: {definition}"
for category, definition in unsafe_category_definitions.items()
)
# 构建发送给 Claude 的提示,包含消息和不安全类别
assessment_prompt = f"""Determine whether the following message warrants moderation, based on the unsafe categories outlined below.
Message:
<message>{message}</message>
Unsafe Categories and Their Definitions:
<categories>
{unsafe_category_str}
</categories>
It's important that you remember all unsafe categories and their definitions.
Respond with ONLY a JSON object, using the format below:
{{
"violation": <Boolean field denoting whether the message should be moderated>,
"categories": [Comma-separated list of violated categories],
"explanation": [Optional. Only include if there is a violation.]
}}
Do not include markdown formatting or code fences in your response."""
# 向 Claude 发送内容审核请求
response = client.messages.create(
model="claude-haiku-4-5-20251001", # Using the Haiku model for lower costs
max_tokens=200,
messages=[{"role": "user", "content": assessment_prompt}],
)
# 解析 Claude 返回的 JSON 响应
text_block = next(block for block in response.content if block.type == "text")
assessment = json.loads(text_block.text)
# 从评估结果中提取违规状态
contains_violation = assessment["violation"]
# 如果存在违规,获取类别和解释;否则使用空的默认值
violated_categories = assessment.get("categories", []) if contains_violation else []
explanation = assessment.get("explanation") if contains_violation else None
return contains_violation, violated_categories, explanation
# 处理每条评论并打印结果
for comment in user_comments:
print(f"\nComment: {comment}")
violation, violated_categories, explanation = moderate_message_with_definitions(
comment, unsafe_category_definitions
)
if violation:
print(f"Violated Categories: {', '.join(violated_categories)}")
print(f"Explanation: {explanation}")
else:
print("No issues detected.")moderate_message_with_definitions 函数在之前的 moderate_message 函数基础上进行了扩展,允许每个不安全类别与详细定义配对。这在代码中通过将原始函数中的 unsafe_categories 集合替换为 unsafe_category_definitions 映射来实现。此映射将每个不安全类别与其相应的定义配对。类别名称及其定义都包含在提示中。
值得注意的是,Specialized Advice 类别的定义现在指定了应该被禁止的金融建议类型。因此,之前通过 moderate_message 评估的评论 It is a great time to invest in gold! 现在会触发违规。
为了在不需要实时审核的情况下降低成本,可以考虑批量审核消息。在提示的上下文中包含多条消息,并要求 Claude 评估哪些消息应该被审核。
def batch_moderate_messages(messages, unsafe_categories):
# 将不安全类别转换为字符串,每个类别占一行
unsafe_category_str = "\n".join(unsafe_categories)
# 格式化消息字符串,每条消息用类 XML 标签包裹并分配一个 ID
messages_str = "\n".join(
[f"<message id={idx}>{msg}</message>" for idx, msg in enumerate(messages)]
)
# 构建发送给 Claude 的提示,包含消息和不安全类别
assessment_prompt = f"""Determine the messages to moderate, based on the unsafe categories outlined below.
Messages:
<messages>
{messages_str}
</messages>
Unsafe Categories:
<categories>
{unsafe_category_str}
</categories>
Respond with ONLY a JSON object, using the format below:
{{
"violations": [
{{
"id": <message id>,
"categories": [list of violated categories],
"explanation": <Explanation of why there's a violation>
}}
]
}}
Important Notes:
- Remember to analyze every message for a violation.
- Select any number of violations that reasonably apply.
- Do not include markdown formatting or code fences in your response."""
# 向 Claude 发送内容审核请求
response = client.messages.create(
model="claude-haiku-4-5-20251001", # Using the Haiku model for lower costs
max_tokens=2048, # Increased max token count to handle batches
messages=[{"role": "user", "content": assessment_prompt}],
)
# 解析 Claude 返回的 JSON 响应
text_block = next(block for block in response.content if block.type == "text")
assessment = json.loads(text_block.text)
return assessment
# 批量处理评论并获取响应
response_obj = batch_moderate_messages(user_comments, unsafe_categories)
# 打印每个检测到的违规的结果
for violation in response_obj["violations"]:
print(f"""Comment: {user_comments[violation["id"]]}
Violated Categories: {", ".join(violation["categories"])}
Explanation: {violation["explanation"]}
""")在此示例中,batch_moderate_messages 函数通过单次 Claude API 调用处理整批消息的审核。
在函数内部,创建一个提示,其中包括要评估的消息列表和不安全内容类别。该提示指示 Claude 返回一个 JSON 对象,列出所有包含违规的消息。响应中的每条消息都通过其 id 进行标识,该 id 对应于消息在批次中的位置。
请记住,为您的特定需求找到最佳批次大小可能需要一些实验。虽然较大的批次大小可以降低成本,但也可能导致质量略有下降。此外,您可能需要增加 Claude API 调用中的 max_tokens 参数以容纳更长的响应。有关您所选模型可以输出的最大令牌数的详细信息,请参阅模型比较表。
查看如何使用 Claude 进行内容审核的完整代码实现示例。
探索护栏指南,了解审核与 Claude 交互的技术。
Was this page helpful?