mcpField
A
azure-ai-contentsafety-java

azure-ai-contentsafety-java

github.com/sickn33その他48.7k80 回インストール今日更新
リポジトリ

azure-ai-contentsafety-java について

Azure AI Content Safety SDK を使ってコンテンツモデレーションアプリを構築する Java 開発者向けのスキルです。テキストと画像の分析、テキストブロックリストの管理に加え、重大度レベルとエラー処理を扱います。

主な機能

  1. 01有害カテゴリに基づくテキスト分析
  2. 02ファイルや URL からの画像分析
  3. 03カテゴリと重大度出力の設定
  4. 04テキストブロックリストの作成と管理
  5. 05サービスエラーへの対応

活用シーン

  1. 01Java アプリへの投稿テキストのモデレーション
  2. 02アップロード画像や画像 URL の検査
  3. 03モデレーション用禁止語リストの管理

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/sickn33/agentic-awesome-skills --skill azure-ai-contentsafety-java

インストール後、Claude Code で/azure-ai-contentsafety-javaを入力して読み込まれたか確認します。

詳細

Java 用 Azure AI Content Safety SDK

Java 用 Azure AI Content Safety SDK を使用して、コンテンツモデレーションアプリケーションを構築します。

インストール

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-ai-contentsafety</artifactId>
    <version>1.1.0-beta.1</version>
</dependency>

クライアントの作成

API キーを使用する場合
import com.azure.ai.contentsafety.ContentSafetyClient;
import com.azure.ai.contentsafety.ContentSafetyClientBuilder;
import com.azure.ai.contentsafety.BlocklistClient;
import com.azure.ai.contentsafety.BlocklistClientBuilder;
import com.azure.core.credential.KeyCredential;

String endpoint = System.getenv("CONTENT_SAFETY_ENDPOINT");
String key = System.getenv("CONTENT_SAFETY_KEY");

ContentSafetyClient contentSafetyClient = new ContentSafetyClientBuilder()
    .credential(new KeyCredential(key))
    .endpoint(endpoint)
    .buildClient();

BlocklistClient blocklistClient = new BlocklistClientBuilder()
    .credential(new KeyCredential(key))
    .endpoint(endpoint)
    .buildClient();
DefaultAzureCredential を使用する場合
import com.azure.identity.DefaultAzureCredentialBuilder;

ContentSafetyClient client = new ContentSafetyClientBuilder()
    .credential(new DefaultAzureCredentialBuilder().build())
    .endpoint(endpoint)
    .buildClient();

主な概念

有害カテゴリ
カテゴリ説明
ヘイトアイデンティティグループに基づく差別的な言葉
性的性的コンテンツ、関係、行為
暴力身体的危害、武器、負傷
自傷自傷行為、自殺に関連するコンテンツ
重大度レベル
  • テキスト:0~7 のスケール(既定の出力は 0、2、4、6)
  • 画像:0、2、4、6(短縮されたスケール)

主なパターン

テキストを分析する
import com.azure.ai.contentsafety.models.*;

AnalyzeTextResult result = contentSafetyClient.analyzeText(
    new AnalyzeTextOptions("This is text to analyze"));

for (TextCategoriesAnalysis category : result.getCategoriesAnalysis()) {
    System.out.printf("Category: %s, Severity: %d%n",
        category.getCategory(),
        category.getSeverity());
}
オプションを指定してテキストを分析する
AnalyzeTextOptions options = new AnalyzeTextOptions("Text to analyze")
    .setCategories(Arrays.asList(
        TextCategory.HATE,
        TextCategory.VIOLENCE))
    .setOutputType(AnalyzeTextOutputType.EIGHT_SEVERITY_LEVELS);

AnalyzeTextResult result = contentSafetyClient.analyzeText(options);
ブロックリストを使用してテキストを分析する
AnalyzeTextOptions options = new AnalyzeTextOptions("I h*te you and want to k*ll you")
    .setBlocklistNames(Arrays.asList("my-blocklist"))
    .setHaltOnBlocklistHit(true);

AnalyzeTextResult result = contentSafetyClient.analyzeText(options);

if (result.getBlocklistsMatch() != null) {
    for (TextBlocklistMatch match : result.getBlocklistsMatch()) {
        System.out.printf("Blocklist: %s, Item: %s, Text: %s%n",
            match.getBlocklistName(),
            match.getBlocklistItemId(),
            match.getBlocklistItemText());
    }
}
画像を分析する
import com.azure.ai.contentsafety.models.*;
import com.azure.core.util.BinaryData;
import java.nio.file.Files;
import java.nio.file.Paths;

// From file
byte[] imageBytes = Files.readAllBytes(Paths.get("image.png"));
ContentSafetyImageData imageData = new ContentSafetyImageData()
    .setContent(BinaryData.fromBytes(imageBytes));

AnalyzeImageResult result = contentSafetyClient.analyzeImage(
    new AnalyzeImageOptions(imageData));

for (ImageCategoriesAnalysis category : result.getCategoriesAnalysis()) {
    System.out.printf("Category: %s, Severity: %d%n",
        category.getCategory(),
        category.getSeverity());
}
URL から画像を分析する
ContentSafetyImageData imageData = new ContentSafetyImageData()
    .setBlobUrl("https://example.com/image.jpg");

AnalyzeImageResult result = contentSafetyClient.analyzeImage(
    new AnalyzeImageOptions(imageData));

ブロックリストの管理

ブロックリストを作成または更新する
import com.azure.core.http.rest.RequestOptions;
import com.azure.core.http.rest.Response;
import com.azure.core.util.BinaryData;
import java.util.Map;

Map<String, String> description = Map.of("description", "Custom blocklist");
BinaryData resource = BinaryData.fromObject(description);

Response<BinaryData> response = blocklistClient.createOrUpdateTextBlocklistWithResponse(
    "my-blocklist", resource, new RequestOptions());

if (response.getStatusCode() == 201) {
    System.out.println("Blocklist created");
} else if (response.getStatusCode() == 200) {
    System.out.println("Blocklist updated");
}
ブロック項目を追加する
import com.azure.ai.contentsafety.models.*;
import java.util.Arrays;

List<TextBlocklistItem> items = Arrays.asList(
    new TextBlocklistItem("badword1").setDescription("Offensive term"),
    new TextBlocklistItem("badword2").setDescription("Another term")
);

AddOrUpdateTextBlocklistItemsResult result = blocklistClient.addOrUpdateBlocklistItems(
    "my-blocklist",
    new AddOrUpdateTextBlocklistItemsOptions(items));

for (TextBlocklistItem item : result.getBlocklistItems()) {
    System.out.printf("Added: %s (ID: %s)%n",
        item.getText(),
        item.getBlocklistItemId());
}
ブロックリストを一覧表示する
PagedIterable<TextBlocklist> blocklists = blocklistClient.listTextBlocklists();

for (TextBlocklist blocklist : blocklists) {
    System.out.printf("Blocklist: %s, Description: %s%n",
        blocklist.getName(),
        blocklist.getDescription());
}
ブロックリストを取得する
TextBlocklist blocklist = blocklistClient.getTextBlocklist("my-blocklist");
System.out.println("Name: " + blocklist.getName());
ブロック項目を一覧表示する
PagedIterable<TextBlocklistItem> items = 
    blocklistClient.listTextBlocklistItems("my-blocklist");

for (TextBlocklistItem item : items) {
    System.out.printf("ID: %s, Text: %s%n",
        item.getBlocklistItemId(),
        item.getText());
}
ブロック項目を削除する
List<String> itemIds = Arrays.asList("item-id-1", "item-id-2");

blocklistClient.removeBlocklistItems(
    "my-blocklist",
    new RemoveTextBlocklistItemsOptions(itemIds));
ブロックリストを削除する
blocklistClient.deleteTextBlocklist("my-blocklist");

エラー処理

import com.azure.core.exception.HttpResponseException;

try {
    contentSafetyClient.analyzeText(new AnalyzeTextOptions("test"));
} catch (HttpResponseException e) {
    System.out.println("Status: " + e.getResponse().getStatusCode());
    System.out.println("Error: " + e.getMessage());
    // Common codes: InvalidRequestBody, ResourceNotFound, TooManyRequests
}

環境変数

CONTENT_SAFETY_ENDPOINT=https://<resource>.cognitiveservices.azure.com/
CONTENT_SAFETY_KEY=<your-api-key>

ベストプラクティス

  1. ブロックリストの反映遅延:変更が反映されるまで約 5 分かかります
  2. カテゴリの選択:レイテンシを低減するため、必要なカテゴリのみをリクエストします
  3. 重大度のしきい値:厳格なモデレーションでは、通常、重大度が 4 以上の場合にブロックします
  4. バッチ処理:スループットを高めるため、複数の項目を並行して処理します
  5. キャッシュ:適切な場合はブロックリストの結果をキャッシュします

トリガーフレーズ

  • 「content safety Java」
  • 「content moderation Azure」
  • 「analyze text safety」
  • 「image moderation Java」
  • 「blocklist management」
  • 「hate speech detection」
  • 「harmful content filter」

使用する場面

このスキルは、概要に記載されたワークフローまたはアクションを実行する場合に適用できます。

制限事項

  • このスキルは、タスクが上記の説明範囲に明確に該当する場合にのみ使用してください。
  • 出力を、環境固有の検証、テスト、または専門家によるレビューの代わりとして扱わないでください。
  • 必要な入力、権限、安全上の境界、または成功基準が不足している場合は、作業を中止して確認してください。

モデルのスコアは確率的なシグナルであり、コンテンツが安全であることを保証するものではありません。分析結果が欠落または不正な形式である場合やサービスエラーが発生した場合は、重大度がゼロなのではなく、未評価として扱ってください。アプリケーションでは、文書化されたフェイルクローズまたはエスカレーションのポリシーを選択してください。機密性の高いテキストや画像の転送を承認し、保持を最小限に抑え、バッチの同時実行数に上限を設けてください。ブロックリストの変更は稼働中のモデレーションに影響するため、意図したリソースとリストのスコープを確認してください。

コメント