オプション
家 Skill 安全 azure-ai-contentsafety-py

azure-ai-contentsafety-py

microsoft/skills microsoft/skills

Azure AI Content Safety SDK for Python を使用して、テキストや画像に含まれる有害なユーザー生成コンテンツやAI生成コンテンツを検出します。

...すべて拡張します
1
更新された時間 2026年9月14日

Python用 Azure AI コンテンツセーフティ SDK

アプリケーション内で、ユーザー生成コンテンツやAI生成コンテンツのうち、有害なものを検出します。

インストール

pip install azure-ai-contentsafety

環境変数

CONTENT_SAFETY_ENDPOINT=https://.cognitiveservices.azure.com  # すべての認証方法で必須
AZURE_TOKEN_CREDENTIALS=prod # 本番環境で DefaultAzureCredential を使用する場合にのみ必要
CONTENT_SAFETY_KEY= # 以下のレガシー API キー認証パスでのみ必要

認証とライフサイクル

🔑 以下のすべてのコードサンプルには、次の2つのルールが適用されます:

  1. DefaultAzureCredentialを優先してください。コードを変更することなく、ローカル(Azure CLI / VS Code / Developer CLI)およびAzure(マネージドID、ワークロードID)の両方で動作します。接続文字列やアカウント/APIキーの使用は避けてください。これらはEntraの監査およびローテーションの対象外となります。
    • ローカル開発:DefaultAzureCredentialはそのまま使用できます。
    • 本番環境:AZURE_TOKEN_CREDENTIALS=prod(またはAZURE_TOKEN_CREDENTIALS= )を設定し、認証情報チェーンを本番環境に適した認証情報に制限してください。
  2. すべてのクライアントをコンテキストマネージャーでラップし、HTTPトランスポート、ソケット、トークンキャッシュが確定的に解放されるようにします:
    • 同期: (...) as client:
    • 非同期:`async with(...) as client: ` および `async with DefaultAzureCredential() as credential:` (azure.identity.aio より)

スニペットではこの設定を省略している場合がありますが、本番環境のコードでは常に両方のルールに従う必要があります。

import os
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.ai.contentsafety import ContentSafetyClient
from azure.ai.contentsafety.models import AnalyzeTextOptions

# ローカル開発環境:DefaultAzureCredential。本番環境:AZURE_TOKEN_CREDENTIALS=prod または AZURE_TOKEN_CREDENTIALS=を設定
credential = DefaultAzureCredential(require_envvar=True)
# または、本番環境では特定の認証情報を直接使用することも可能です:
# https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes を参照してください
# credential = ManagedIdentityCredential()

with ContentSafetyClient(
    endpoint=os.environ["CONTENT_SAFETY_ENDPOINT"],
    credential=credential,
) as client:
    response = client.analyze_text(AnalyzeTextOptions(text="Hello, world!"))

レガシー: API キー (既存のキーベースのデプロイメント)

新しいコードでは、上記のDefaultAzureCredentialを使用してください。AzureKeyCredentialを使用するのは、まだ Entra ID へ移行されていない既存のキーベースのデプロイメントがある場合のみです。たとえば、Entra の展開がまだ完了していない規制対象環境などが該当します。

import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.contentsafety import ContentSafetyClient
from azure.ai.contentsafety.models import AnalyzeTextOptions

with ContentSafetyClient(
    endpoint=os.environ["CONTENT_SAFETY_ENDPOINT"],
    credential=AzureKeyCredential(os.environ["CONTENT_SAFETY_KEY"]),
) as client:
    response = client.analyze_text(AnalyzeTextOptions(text="Hello, world!"))

キーを使用してブロックリストを管理する必要がある場合も、BlocklistClientでは同じAzureKeyCredentialを受け付けます。

テキストの分析

from azure.ai.contentsafety import ContentSafetyClient
from azure.ai.contentsafety.models import AnalyzeTextOptions, TextCategory
from azure.identity import DefaultAzureCredential

with ContentSafetyClient(endpoint, DefaultAzureCredential()) as client:
    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}: 深刻度 {result.severity}")

画像の分析

from azure.ai.contentsafety import ContentSafetyClient
from azure.ai.contentsafety.models import AnalyzeImageOptions, ImageData
from azure.identity import DefaultAzureCredential
import base64

with ContentSafetyClient(endpoint, DefaultAzureCredential()) as client:
    # ファイルから読み込み
    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}: 深刻度 {result.severity}")

URLからの画像

from azure.ai.contentsafety.models import AnalyzeImageOptions, ImageData

request = AnalyzeImageOptions(
    image=ImageData(blob_url="https://example.com/image.jpg")
)

response = client.analyze_image(request)

テキストのブロックリスト管理

ブロックリストの作成

from azure.ai.contentsafety import BlocklistClient
from azure.ai.contentsafety.models import TextBlocklist
from azure.identity import DefaultAzureCredential

with BlocklistClient(endpoint, DefaultAzureCredential()) as blocklist_client:
    blocklist = TextBlocklist(
        blocklist_name="my-blocklist",
        description="ブロックするカスタム用語"
    )

    result = blocklist_client.create_or_update_text_blocklist(
        blocklist_name="my-blocklist",
        options=blocklist
    )

ブロック項目の追加

from azure.ai.contentsafety.models import AddOrUpdateTextBlocklistItemsOptions, TextBlocklistItem

items = AddOrUpdateTextBlocklistItemsOptions(
    blocklist_items=[
        TextBlocklistItem(text="blocked-term-1"),
        TextBlocklistItem(text="blocked-term-2")
    ]
)

result = blocklist_client.add_or_update_blocklist_items(
    blocklist_name="my-blocklist",
    options=items
)

ブロックリストを使用した分析

from azure.ai.contentsafety.models import AnalyzeTextOptions

request = AnalyzeTextOptions(
    text="Text containing blocked-term-1",
    blocklist_names=["my-blocklist"],
    halt_on_blocklist_hit=True
)

response = client.analyze_text(request)

if response.blocklists_match:
    for match in response.blocklists_match:
        print(f"ブロック対象: {match.blocklist_item_text}")

重大度レベル

テキスト分析では、デフォルトで4つの重大度レベル(0、2、4、6)が返されます。8段階(0~7)の場合は:

from azure.ai.contentsafety.models import AnalyzeTextOptions, AnalyzeTextOutputType

request = AnalyzeTextOptions(
    text="Your text",
    output_type=AnalyzeTextOutputType.EIGHT_SEVERITY_LEVELS
)

危害のカテゴリ

カテゴリ 説明
ヘイト アイデンティティ(人種、宗教、性別など)に基づく攻撃
性的な内容、関係、身体的特徴
暴力 身体的危害、武器、怪我
自傷行為 自傷行為、自殺、摂食障害

深刻度尺度

レベル テキスト範囲 画像の範囲 意味
0 安全 安全 有害なコンテンツなし
2 軽度の言及
4 中程度の表現
6 高い 過激なコンテンツ

クライアントの種類

クライアント 目的
ContentSafetyClient テキストと画像を分析する
ブロックリストクライアント カスタムブロックリストの管理

ベストプラクティス

  1. 同期(sync)または非同期(async)のいずれかを選択し、一貫性を保ってください。同じ呼び出しパス内で、azure.ai.contentsafetyの同期クライアントとazure.ai.contentsafety.aioの非同期クライアントを混在させないでください。モジュールごとに 1 つのモードを選択してください。
  2. クライアントおよび非同期認証情報には、常にコンテキストマネージャーを使用してください。すべてのクライアントを、ContentSafetyClient(...) as client:(sync) またはContentSafetyClient(...) as client:(async)ラップしてください。azure.identity.aio の async 版DefaultAzureCredentialを使用する場合も、credential: とともに asyncを使用し、トークンとトランスポートが適切にクリーンアップされるようにしてください。
  3. ドメイン固有の用語にはブロックリストを使用してください
  4. ユースケースに適した重大度しきい値を設定してください
  5. 複数のカテゴリに対応する— コンテンツはさまざまな形で有害となる可能性がある
  6. 即時拒否には `halt_on_blocklist_hit` を使用してください
  7. 監査および改善のために分析結果をログに記録してください
  8. よりきめ細かな制御のため、8段階の深刻度モードを検討する
  9. ユーザーに表示する前に、AIの出力を事前審査する
GitHubで見る
---
name: azure-ai-contentsafety-py
description: Detect harmful user-generated and AI-generated content in text and images using Azure AI Content Safety SDK for Python.
license: MIT
---

# Azure AI Content Safety SDK for Python

Detect harmful user-generated and AI-generated content in applications.

## Installation

```bash
pip install azure-ai-contentsafety
```

## Environment Variables

```bash
CONTENT_SAFETY_ENDPOINT=https://<resource>.cognitiveservices.azure.com  # Required for all auth methods
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
CONTENT_SAFETY_KEY=<your-api-key>  # Only required for the legacy API-key auth path below
```

## Authentication & Lifecycle

> **🔑 Two rules apply to every code sample below:**
>
> 1. **Prefer `DefaultAzureCredential`.** It works locally (Azure CLI / VS Code / Developer CLI) and in Azure (managed identity, workload identity) with no code change. Avoid connection strings, account/API keys — they bypass Entra audit and rotation.
>    - Local dev: `DefaultAzureCredential` works as-is.
>    - Production: set `AZURE_TOKEN_CREDENTIALS=prod` (or `AZURE_TOKEN_CREDENTIALS=<specific_credential>`) to constrain the credential chain to production-safe credentials.
> 2. **Wrap every client in a context manager** so HTTP transports, sockets, and token caches are released deterministically:
>    - Sync: `with <Client>(...) as client:`
>    - Async: `async with <Client>(...) as client:` **and** `async with DefaultAzureCredential() as credential:` (from `azure.identity.aio`)
>
> Snippets may abbreviate this setup, but production code should always follow both rules.

```python
import os
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.ai.contentsafety import ContentSafetyClient
from azure.ai.contentsafety.models import AnalyzeTextOptions

# Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
credential = DefaultAzureCredential(require_envvar=True)
# Or use a specific credential directly in production:
# See https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()

with ContentSafetyClient(
    endpoint=os.environ["CONTENT_SAFETY_ENDPOINT"],
    credential=credential,
) as client:
    response = client.analyze_text(AnalyzeTextOptions(text="Hello, world!"))
```

### Legacy: API Key (existing keyed deployments)

New code should use `DefaultAzureCredential` above. Use `AzureKeyCredential` only if you have an existing keyed deployment that hasn't been migrated to Entra ID yet — for example, regulated environments still completing their Entra rollout.

```python
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.contentsafety import ContentSafetyClient
from azure.ai.contentsafety.models import AnalyzeTextOptions

with ContentSafetyClient(
    endpoint=os.environ["CONTENT_SAFETY_ENDPOINT"],
    credential=AzureKeyCredential(os.environ["CONTENT_SAFETY_KEY"]),
) as client:
    response = client.analyze_text(AnalyzeTextOptions(text="Hello, world!"))
```

The `BlocklistClient` accepts the same `AzureKeyCredential` if you also need to manage blocklists with a key.

## Analyze Text

```python
from azure.ai.contentsafety import ContentSafetyClient
from azure.ai.contentsafety.models import AnalyzeTextOptions, TextCategory
from azure.identity import DefaultAzureCredential

with ContentSafetyClient(endpoint, DefaultAzureCredential()) as client:
    request = AnalyzeTextOptions(text="Your text content to analyze")
    response = client.analyze_text(request)

    # Check each category
    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}")
```

## Analyze Image

```python
from azure.ai.contentsafety import ContentSafetyClient
from azure.ai.contentsafety.models import AnalyzeImageOptions, ImageData
from azure.identity import DefaultAzureCredential
import base64

with ContentSafetyClient(endpoint, DefaultAzureCredential()) as client:
    # From file
    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}")
```

### Image from URL

```python
from azure.ai.contentsafety.models import AnalyzeImageOptions, ImageData

request = AnalyzeImageOptions(
    image=ImageData(blob_url="https://example.com/image.jpg")
)

response = client.analyze_image(request)
```

## Text Blocklist Management

### Create Blocklist

```python
from azure.ai.contentsafety import BlocklistClient
from azure.ai.contentsafety.models import TextBlocklist
from azure.identity import DefaultAzureCredential

with BlocklistClient(endpoint, DefaultAzureCredential()) as blocklist_client:
    blocklist = TextBlocklist(
        blocklist_name="my-blocklist",
        description="Custom terms to block"
    )

    result = blocklist_client.create_or_update_text_blocklist(
        blocklist_name="my-blocklist",
        options=blocklist
    )
```

### Add Block Items

```python
from azure.ai.contentsafety.models import AddOrUpdateTextBlocklistItemsOptions, TextBlocklistItem

items = AddOrUpdateTextBlocklistItemsOptions(
    blocklist_items=[
        TextBlocklistItem(text="blocked-term-1"),
        TextBlocklistItem(text="blocked-term-2")
    ]
)

result = blocklist_client.add_or_update_blocklist_items(
    blocklist_name="my-blocklist",
    options=items
)
```

### Analyze with Blocklist

```python
from azure.ai.contentsafety.models import AnalyzeTextOptions

request = AnalyzeTextOptions(
    text="Text containing blocked-term-1",
    blocklist_names=["my-blocklist"],
    halt_on_blocklist_hit=True
)

response = client.analyze_text(request)

if response.blocklists_match:
    for match in response.blocklists_match:
        print(f"Blocked: {match.blocklist_item_text}")
```

## Severity Levels

Text analysis returns 4 severity levels (0, 2, 4, 6) by default. For 8 levels (0-7):

```python
from azure.ai.contentsafety.models import AnalyzeTextOptions, AnalyzeTextOutputType

request = AnalyzeTextOptions(
    text="Your text",
    output_type=AnalyzeTextOutputType.EIGHT_SEVERITY_LEVELS
)
```

## Harm Categories

| Category | Description |
|----------|-------------|
| `Hate` | Attacks based on identity (race, religion, gender, etc.) |
| `Sexual` | Sexual content, relationships, anatomy |
| `Violence` | Physical harm, weapons, injury |
| `SelfHarm` | Self-injury, suicide, eating disorders |

## Severity Scale

| Level | Text Range | Image Range | Meaning |
|-------|------------|-------------|---------|
| 0 | Safe | Safe | No harmful content |
| 2 | Low | Low | Mild references |
| 4 | Medium | Medium | Moderate content |
| 6 | High | High | Severe content |

## Client Types

| Client | Purpose |
|--------|---------|
| `ContentSafetyClient` | Analyze text and images |
| `BlocklistClient` | Manage custom blocklists |

## Best Practices

1. **Pick sync OR async and stay consistent.** Do not mix `azure.ai.contentsafety` sync clients with `azure.ai.contentsafety.aio` async clients in the same call path. Choose one mode per module.
2. **Always use context managers for clients and async credentials.** Wrap every client in `with ContentSafetyClient(...) as client:` (sync) or `async with ContentSafetyClient(...) as client:` (async). For async `DefaultAzureCredential` from `azure.identity.aio`, also use `async with credential:` so tokens and transports are cleaned up.
3. **Use blocklists** for domain-specific terms
4. **Set severity thresholds** appropriate for your use case
5. **Handle multiple categories** — content can be harmful in multiple ways
6. **Use halt_on_blocklist_hit** for immediate rejection
7. **Log analysis results** for audit and improvement
8. **Consider 8-severity mode** for finer-grained control
9. **Pre-moderate AI outputs** before showing to users

すべてのファイル

0件のファイル

azure-ai-contentsafety-pyをインストール

スキルファイルをダウンロードし、.claude/skills/ ディレクトリに解凍してください。

ZIPをダウンロード

リポジトリをクローンし、スキルファイルをプロジェクトにコピーしてください。

git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-python/skills/azure-ai-contentsafety-py # Copy SKILL.md to your .claude/skills/ directory

コピー コピー
クイックセットアップ: スキルフォルダを .claude/skills/ にコピーしてください。 Claude が自動的にそのスキルを検出して使用します。
リポジトリ microsoft/skills

関連スキル

gmgn-portfolio
更新された時間 2026年7月1日
zeroize-audit
更新された時間 2026年7月1日
device-integrity
更新された時間 2026年6月29日
flutter-use-http-package
更新された時間 2026年6月30日
OR