Claude Platform Docs
ベストプラクティスユースケース

コンテンツモデレーション

コンテンツモデレーションは、デジタルアプリケーションにおいて安全で、敬意があり、生産的な環境を維持するための重要な側面です。このガイドでは、Claudeを使用してデジタルアプリケーション内のコンテンツをモデレートする方法について説明します。

Claudeを使用したコンテンツモデレーションの実装例については、コンテンツモデレーションクックブックをご覧ください。

Claudeで構築する前に

コンテンツモデレーションにClaudeを使用するかどうかを決定する

コンテンツモデレーションに従来のMLやルールベースのアプローチではなく、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.というコメントは、コンテンツモデレーションシステムによってフラグ付けされるべきです。

安全でないカテゴリは、特定のニーズに合わせてカスタマイズできます。たとえば、未成年者がウェブサイト上でコンテンツを作成するのを防ぎたい場合は、カテゴリに「Underage Posting」を追加できます。


Claudeを使用してコンテンツをモデレートする方法

適切なClaudeモデルを選択する

モデルを選択する際には、データのサイズを考慮することが重要です。コストが懸念される場合、Claude Haiku 4.5のような小型モデルはコスト効率が高いため優れた選択肢です。以下は、月に10億件の投稿を受け取るソーシャルメディアプラットフォームのテキストをモデレートするためのコストの見積もりです。

  • コンテンツサイズ

    • 月あたりの投稿数:10億
    • 投稿あたりの文字数:100
    • 合計文字数:1,000億
  • 推定トークン数

    • 入力トークン:286億(3.5文字あたり1トークンと仮定)
    • フラグ付けされるメッセージの割合:3%
    • フラグ付けされたメッセージあたりの出力トークン:50
    • 合計出力トークン:15億
  • Claude Haiku 4.5の推定コスト

    • 入力トークンコスト:28,600 MTok * $1.00/MTok = $28,600 USD
    • 出力トークンコスト:1,500 MTok * $5.00/MTok = $7,500 USD
    • 月額コスト:$28,600 + $7,500 = $36,100 USD
  • Claude Opus 5の推定コスト

    • 入力トークンコスト:28,600 MTok * $5.00/MTok = $143,000 USD
    • 出力トークンコスト:1,500 MTok * $25.00/MTok = $37,500 USD
    • 月額コスト:$143,000 + $37,500 = $180,500 USD
  • Claude Opus 4.8の推定コスト

    • 入力トークンコスト:28,600 MTok * $5.00/MTok = $143,000 USD
    • 出力トークンコスト:1,500 MTok * $25.00/MTok = $37,500 USD
    • 月額コスト:$143,000 + $37,500 = $180,500 USD

強力なプロンプトを構築する

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は違反したカテゴリのリストと、そのメッセージが安全でない理由の説明も返します。

プロンプトを評価する

コンテンツモデレーションは分類問題です。したがって、分類クックブックで概説されているのと同じ手法を使用して、コンテンツモデレーションシステムの精度を判断できます。

もう1つの考慮事項として、コンテンツモデレーションを二値分類問題として扱う代わりに、さまざまなリスクレベルを表す複数のカテゴリを作成することもできます。複数のリスクレベルを作成することで、モデレーションの厳しさを調整できます。たとえば、高リスクとみなされるユーザークエリは自動的にブロックし、中リスクのクエリが多いユーザーは人間によるレビューのためにフラグ付けする、といったことが考えられます。

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}")

このコードは、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.というコメントは中リスクに分類されます。

プロンプトをデプロイする

ソリューションの品質に自信が持てたら、本番環境にデプロイします。本番環境でコンテンツモデレーションを使用する際に従うべきベストプラクティスを以下に示します。

  1. ユーザーに明確なフィードバックを提供する: コンテンツモデレーションによってユーザー入力がブロックされたり、レスポンスにフラグが付けられたりした場合は、メッセージにフラグが付けられた理由と、適切に言い換える方法をユーザーが理解できるよう、有益で建設的なフィードバックを提供します。前述のコード例では、これはClaudeのレスポンスのexplanationフィールドを通じて行われます。

  2. モデレートされたコンテンツを分析する: モデレーションシステムによってフラグ付けされているコンテンツの種類を追跡し、傾向や改善の余地がある領域を特定します。

  3. 継続的に評価し改善する: 適合率や再現率の追跡などの指標を使用して、コンテンツモデレーションシステムのパフォーマンスを定期的に評価します。このデータを使用して、モデレーションプロンプト、キーワード、評価基準を反復的に改良します。


パフォーマンスを向上させる

複雑なシナリオでは、標準的なプロンプトエンジニアリング手法に加えて、パフォーマンスを向上させるための追加の戦略を検討することが役立つ場合があります。以下に高度な戦略をいくつか示します。

トピックを定義し、例を提供する

プロンプトに安全でないカテゴリを列挙することに加えて、各カテゴリに関連する定義やフレーズを提供することで、さらなる改善が可能です。

# コンテンツモデレーションで安全でないと見なされるカテゴリとその定義
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関数が、1回のClaude API呼び出しでメッセージのバッチ全体のモデレーションを処理します。 関数内では、評価対象のメッセージのリストと安全でないコンテンツカテゴリを含むプロンプトが作成されます。このプロンプトは、違反を含むすべてのメッセージを列挙したJSONオブジェクトを返すようClaudeに指示します。レスポンス内の各メッセージは、バッチ内でのメッセージの位置に対応するidによって識別されます。 特定のニーズに最適なバッチサイズを見つけるには、ある程度の実験が必要になる場合があることに留意してください。バッチサイズを大きくするとコストを下げられますが、品質がわずかに低下する可能性もあります。さらに、より長いレスポンスに対応するために、Claude API呼び出しのmax_tokensパラメータを増やす必要がある場合があります。選択したモデルが出力できる最大トークン数の詳細については、モデル比較表を参照してください。

Claudeをコンテンツモデレーションに使用する方法について、完全に実装されたコードベースの例をご覧ください。

Claudeとのやり取りをモデレートするためのガードレール手法を探索してください。

Was this page helpful?