請造訪內容審核 cookbook 以查看使用 Claude 實作內容審核的範例。
以下是一些關鍵指標,顯示您應該使用像 Claude 這樣的 LLM,而非傳統的 ML 或基於規則的方法來進行內容審核:
在開發內容審核解決方案之前,首先建立應該被標記的內容和不應該被標記的內容的範例。確保您包含邊緣案例和具有挑戰性的情境,這些可能是內容審核系統難以有效處理的。之後,審閱您的範例以建立一份明確定義的審核類別清單。 例如,社群媒體平台產生的範例可能包括以下內容:
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 這樣較小的模型因其成本效益而是絕佳的選擇。以下是為每月收到十億則貼文的社群媒體平台審核文字的成本估算:
內容規模
預估 token 數
Claude Haiku 4.5 預估成本
Claude Opus 5 預估成本
Claude Opus 4.8 預估成本
explanation 欄位,可以進一步減少輸出 token。要使用 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 參數以容納更長的回應。有關您所選模型可以輸出的最大 token 數量的詳細資訊,請參閱模型比較表。
查看如何使用 Claude 進行內容審核的完整程式碼實作範例。
探索防護措施指南,了解審核與 Claude 互動的技術。
Was this page helpful?