Claudeを使用したコンテンツモデレーションの実装例については、コンテンツモデレーションクックブックをご覧ください。
コンテンツモデレーションに従来のMLやルールベースのアプローチではなく、ClaudeのようなLLMを使用すべき主な指標を以下に示します:
コンテンツモデレーションソリューションを開発する前に、まずフラグ付けすべきコンテンツとフラグ付けすべきでないコンテンツの例を作成します。コンテンツモデレーションシステムが効果的に処理するのが難しいエッジケースや困難なシナリオを含めるようにしてください。その後、例を確認して、明確に定義されたモデレーションカテゴリのリストを作成します。 例えば、ソーシャルメディアプラットフォームが生成する例には以下のようなものが含まれるかもしれません:
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!'
]
# Sample user comments to test the content moderation
user_comments = allowed_user_comments + disallowed_user_comments
# List of categories considered unsafe for content moderation
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. はコンテンツモデレーションシステムによってフラグ付けされるべきです。
unsafe_categories リストは、特定のニーズに合わせてカスタマイズできます。例えば、未成年者がウェブサイトでコンテンツを作成することを防止したい場合は、リストに「Underage Posting」を追加できます。
モデルを選択する際は、データのサイズを考慮することが重要です。コストが懸念される場合、Claude Haiku 3のような小型モデルはコスト効率が高いため優れた選択肢です。以下は、月間10億件の投稿を受け取るソーシャルメディアプラットフォームのテキストモデレーションコストの見積もりです:
コンテンツサイズ
推定トークン数
Claude Haiku 3 推定コスト
Claude Opus 4.6 推定コスト
explanation フィールドを削除することで、出力トークンをさらに削減できます。コンテンツモデレーションにClaudeを使用するには、Claudeがアプリケーションのモデレーション要件を理解する必要があります。まず、モデレーションニーズを定義できるプロンプトを作成しましょう:
import anthropic
import json
# Initialize the Anthropic client
client = anthropic.Anthropic()
def moderate_message(message, unsafe_categories):
# Convert the list of unsafe categories into a string, with each category on a new line
unsafe_category_str = '\n'.join(unsafe_categories)
# Construct the prompt for Claude, including the message and unsafe categories
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.]
}}"""
# Send the request to Claude for content moderation
response = client.messages.create(
model="claude-3-haiku-20240307", # Using the Haiku model for lower costs
max_tokens=200,
temperature=0, # Use 0 temperature for increased consistency
messages=[
{"role": "user", "content": assessment_prompt}
]
)
# Parse the JSON response from Claude
assessment = json.loads(response.content[0].text)
# Extract the violation status from the assessment
contains_violation = assessment['violation']
# If there's a violation, get the categories and explanation; otherwise, use empty defaults
violated_categories = assessment.get('categories', []) if contains_violation else []
explanation = assessment.get('explanation') if contains_violation else None
return contains_violation, violated_categories, explanation
# Process each comment and print the results
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は違反したカテゴリのリストと、メッセージが安全でない理由の説明も返します。
コンテンツモデレーションは分類問題です。したがって、分類クックブックで概説されているのと同じ手法を使用して、コンテンツモデレーションシステムの精度を判断できます。
追加の考慮事項として、コンテンツモデレーションを二値分類問題として扱う代わりに、さまざまなリスクレベルを表す複数のカテゴリを作成することもできます。複数のリスクレベルを作成することで、モデレーションの積極性を調整できます。例えば、高リスクと判断されたユーザークエリを自動的にブロックし、中リスクのクエリが多いユーザーを人間によるレビューのためにフラグ付けすることができます。
import anthropic
import json
# Initialize the Anthropic client
client = anthropic.Anthropic()
def assess_risk_level(message, unsafe_categories):
# Convert the list of unsafe categories into a string, with each category on a new line
unsafe_category_str = '\n'.join(unsafe_categories)
# Construct the prompt for Claude, including the message, unsafe categories, and risk level definitions
assessment_prompt = f"""
Assess the risk level of the following message warrants moderation,
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>
}}"""
# Send the request to Claude for risk assessment
response = client.messages.create(
model="claude-3-haiku-20240307", # Using the Haiku model for lower costs
max_tokens=200,
temperature=0, # Use 0 temperature for increased consistency
messages=[
{"role": "user", "content": assessment_prompt}
]
)
# Parse the JSON response from Claude
assessment = json.loads(response.content[0].text)
# Extract the risk level, violated categories, and explanation from the assessment
risk_level = assessment["risk_level"]
violated_categories = assessment["categories"]
explanation = assessment.get("explanation")
return risk_level, violated_categories, explanation
# Process each comment and print the results
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}")このコードは、Claudeを使用してメッセージのリスクレベルを評価する assess_risk_level 関数を実装しています。この関数は、メッセージと安全でないカテゴリのリストを入力として受け取ります。
関数内では、評価対象のメッセージ、安全でないカテゴリ、およびリスクレベルを評価するための具体的な指示を含むプロンプトがClaudeのために生成されます。プロンプトは、リスクレベル、違反したカテゴリ、およびオプションの説明を含むJSONオブジェクトで応答するようClaudeに指示します。
このアプローチにより、リスクレベルを割り当てることで柔軟なコンテンツモデレーションが可能になります。評価されたリスクレベルに基づいて、コンテンツフィルタリングを自動化したり、人間によるレビューのためにコメントをフラグ付けしたりする大規模なシステムにシームレスに統合できます。例えば、このコードを実行すると、コメント 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 タグを通じて行われています。
モデレートされたコンテンツを分析する: モデレーションシステムによってフラグ付けされているコンテンツの種類を追跡し、トレンドと改善の可能性がある領域を特定します。
継続的に評価し改善する: 適合率や再現率の追跡などの指標を使用して、コンテンツモデレーションシステムのパフォーマンスを定期的に評価します。このデータを使用して、モデレーションプロンプト、キーワード、評価基準を反復的に改善します。
複雑なシナリオでは、標準的なプロンプトエンジニアリング手法を超えてパフォーマンスを向上させるための追加戦略を検討することが有用な場合があります。以下にいくつかの高度な戦略を示します:
プロンプトに安全でないカテゴリをリストするだけでなく、各カテゴリに関連する定義やフレーズを提供することでさらなる改善が可能です。
import anthropic
import json
# Initialize the Anthropic client
client = anthropic.Anthropic()
# Dictionary of categories considered unsafe for content moderation, with their definitions
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):
# Format unsafe categories string, with each category and its definition on a new line
unsafe_category_str = '\n'.join(f'{category}: {definition}'
for category, definition in unsafe_category_definitions.items()
)
# Construct the prompt for Claude, including the message and unsafe categories
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.]
}}"""
# Send the request to Claude for content moderation
response = client.messages.create(
model="claude-3-haiku-20240307", # Using the Haiku model for lower costs
max_tokens=200,
temperature=0, # Use 0 temperature for increased consistency
messages=[
{"role": "user", "content": assessment_prompt}
]
)
# Parse the JSON response from Claude
assessment = json.loads(response.content[0].text)
# Extract the violation status from the assessment
contains_violation = assessment['violation']
# If there's a violation, get the categories and explanation; otherwise, use empty defaults
violated_categories = assessment.get('categories', []) if contains_violation else []
explanation = assessment.get('explanation') if contains_violation else None
return contains_violation, violated_categories, explanation
# Process each comment and print the results
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's a great time to invest in gold! が、違反をトリガーするようになりました。
リアルタイムのモデレーションが不要な状況でコストを削減するには、メッセージをバッチでモデレートすることを検討してください。プロンプトのコンテキスト内に複数のメッセージを含め、どのメッセージをモデレートすべきかをClaudeに評価させます。
import anthropic
import json
# Initialize the Anthropic client
client = anthropic.Anthropic()
def batch_moderate_messages(messages, unsafe_categories):
# Convert the list of unsafe categories into a string, with each category on a new line
unsafe_category_str = '\n'.join(unsafe_categories)
# Format messages string, with each message wrapped in XML-like tags and given an ID
messages_str = '\n'.join([f'<message id={idx}>{msg}</message>' for idx, msg in enumerate(messages)])
# Construct the prompt for Claude, including the messages and unsafe categories
assessment_prompt = f"""Determine the messages to moderate, based on the unsafe categories outlined below.
Messages:
<messages>
{messages_str}
</messages>
Unsafe categories and their definitions:
<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."""
# Send the request to Claude for content moderation
response = client.messages.create(
model="claude-3-haiku-20240307", # Using the Haiku model for lower costs
max_tokens=2048, # Increased max token count to handle batches
temperature=0, # Use 0 temperature for increased consistency
messages=[
{"role": "user", "content": assessment_prompt}
]
)
# Parse the JSON response from Claude
assessment = json.loads(response.content[0].text)
return assessment
# Process the batch of comments and get the response
response_obj = batch_moderate_messages(user_comments, unsafe_categories)
# Print the results for each detected violation
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呼び出しでメッセージのバッチ全体のモデレーションを処理します。
関数内では、評価するメッセージのリスト、定義された安全でないコンテンツカテゴリ、およびその説明を含むプロンプトが作成されます。プロンプトは、違反を含むすべてのメッセージをリストするJSONオブジェクトを返すようClaudeに指示します。レスポンス内の各メッセージはそのidで識別され、入力リスト内のメッセージの位置に対応します。
特定のニーズに最適なバッチサイズを見つけるには、いくつかの実験が必要になる場合があることに留意してください。バッチサイズを大きくするとコストを削減できますが、品質がわずかに低下する可能性もあります。さらに、より長いレスポンスに対応するために、Claude API呼び出しの max_tokens パラメータを増やす必要がある場合があります。選択したモデルが出力できるトークンの最大数の詳細については、モデル比較ページを参照してください。
Claudeをコンテンツモデレーションに使用する方法の完全に実装されたコードベースの例をご覧ください。
Claudeとのインタラクションをモデレートするための手法については、ガードレールガイドをご覧ください。
Was this page helpful?