選項
首頁首頁 Skill 安全 azure-ai-contentsafety-java

azure-ai-contentsafety-java

microsoft/skills microsoft/skills

使用 Azure AI 內容安全 SDK(Java 版)分析文字和圖片中的有害內容。支援仇恨言論、暴力、色情內容及自殘行為的偵測,並具備黑名單管理功能。

...展開全部
0
更新時間 2026-09-14

Azure AI 內容安全 SDK(Java 版)

使用 Azure AI 內容安全 SDK(Java 版)建立內容審查應用程式。

安裝


    com.azure
    azure-ai-contentsafety
    1.1.0-beta.1

建立客戶端

使用 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.core.credential.TokenCredential;
import com.azure.identity.AzureIdentityEnvVars;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.ManagedIdentityCredentialBuilder;

TokenCredential credential = new DefaultAzureCredentialBuilder()
    .requireEnvVars(AzureIdentityEnvVars.AZURE_TOKEN_CREDENTIALS)
    .build();
// 或者在生產環境中直接使用特定的憑證:
// 請參閱 https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#credential-classes
// TokenCredential credential = new ManagedIdentityCredentialBuilder().build();

ContentSafetyClient client = new ContentSafetyClientBuilder()
    .credential(credential)
    .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("這是待分析的文字"));

for (TextCategoriesAnalysis category : result.getCategoriesAnalysis()) {
    System.out.printf("類別:%s,嚴重程度:%d%n",
        category.getCategory(),
        category.getSeverity());
}

使用選項分析文字

AnalyzeTextOptions options = new AnalyzeTextOptions("待分析的文字")
    .setCategories(Arrays.asList(
        TextCategory.HATE,
        TextCategory.VIOLENCE))
    .setOutputType(AnalyzeTextOutputType.EIGHT_SEVERITY_LEVELS);

AnalyzeTextResult result = contentSafetyClient.analyzeText(options);

使用封鎖清單分析文字

AnalyzeTextOptions 選項 = new AnalyzeTextOptions("我 h*ate 你,還想 k*ll 你")
    .setBlocklistNames(Arrays.asList("my-blocklist"))
    .setHaltOnBlocklistHit(true);

AnalyzeTextResult result = contentSafetyClient.analyzeText(options);

if (result.getBlocklistsMatch() != null) {
    for (TextBlocklistMatch match : result.getBlocklistsMatch()) {
        System.out.printf("封鎖清單:%s,項目:%s,文字:%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;

// 從檔案讀取
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("類別:%s,嚴重程度:%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 description = Map.of("description", "自訂封鎖清單");
BinaryData resource = BinaryData.fromObject(description);

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

if (response.getStatusCode() == 201) {
    System.out.println("封鎖清單已建立");
} else if (response.getStatusCode() == 200) {
    System.out.println("封鎖清單已更新");
}

新增封鎖項目

import com.azure.ai.contentsafety.models.*;
import java.util.Arrays;

List items = Arrays.asList(
    new TextBlocklistItem("badword1").setDescription("冒犯性詞彙"),
    new TextBlocklistItem("badword2").setDescription("另一個詞彙")
);

AddOrUpdateTextBlocklistItemsResult 結果 = blocklistClient.addOrUpdateBlocklistItems(
    "my-blocklist",
    new AddOrUpdateTextBlocklistItemsOptions(項目));

for (TextBlocklistItem item : result.getBlocklistItems()) {
    System.out.printf("已新增:%s (ID:%s)%n",
        item.getText(),
        item.getBlocklistItemId());
}

列出封鎖清單

PagedIterable blocklists = blocklistClient.listTextBlocklists();

for (TextBlocklist 封鎖清單 : 封鎖清單) {
    System.out.printf("封鎖清單:%s,說明:%s%n",
        封鎖清單.getName(),
        封鎖清單.getDescription());
}

取得封鎖清單

TextBlocklist 阻擋清單 = blocklistClient.getTextBlocklist("my-blocklist");
System.out.println("名稱: " + 阻擋清單.getName());

列出封鎖項目

PagedIterable items = 
    blocklistClient.listTextBlocklistItems("my-blocklist");

for (TextBlocklistItem item : items) {
    System.out.printf("ID: %s, 內容: %s%n",
        item.getBlocklistItemId(),
        item.getText());
}

移除區塊項目

List 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("狀態: " + e.getResponse().getStatusCode());
    System.out.println("錯誤: " + e.getMessage());
    // 常見錯誤代碼:InvalidRequestBody、ResourceNotFound、TooManyRequests
}

環境變數

 CONTENT_SAFETY_ENDPOINT=https://.cognitiveservices.azure.com/ # 所有驗證方法皆需此參數
CONTENT_SAFETY_ENDPOINT=https:// .cognitiveservices.azure.com/ # 所有驗證方式皆需此變數
AZURE_TOKEN_CREDENTIALS=prod  # 僅在生產環境中使用 DefaultAzureCredential 時才需此變數

最佳實務

  1. 黑名單延遲:變更約需 5 分鐘才會生效
  2. 類別選取:僅請求所需的類別以減少延遲
  3. 嚴重性閾值:通常應將嚴重性閾值設為 >= 4 以進行嚴格審核
  4. 批次處理:並行處理多個項目以提升吞吐量
  5. 快取:在適當情況下快取封鎖清單結果

觸發詞彙

  • 「內容安全 Java」
  • 「內容審核 Azure」
  • 「分析文字安全性」
  • 「Java 圖片審核」
  • 「黑名單管理」
  • 「仇恨言論偵測」
  • 「有害內容過濾器」
在 GitHub 上查看
---
name: azure-ai-contentsafety-java
description: Analyze text and images for harmful content using Azure AI Content Safety SDK for Java. Supports hate, violence, sexual content, and self-harm detection with blocklist management.
license: MIT
---

# Azure AI Content Safety SDK for Java

Build content moderation applications using the Azure AI Content Safety SDK for Java.

## Installation

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

## Client Creation

### With API Key

```java
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();
```

### With DefaultAzureCredential

```java
import com.azure.core.credential.TokenCredential;
import com.azure.identity.AzureIdentityEnvVars;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.ManagedIdentityCredentialBuilder;

TokenCredential credential = new DefaultAzureCredentialBuilder()
    .requireEnvVars(AzureIdentityEnvVars.AZURE_TOKEN_CREDENTIALS)
    .build();
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#credential-classes
// TokenCredential credential = new ManagedIdentityCredentialBuilder().build();

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

## Key Concepts

### Harm Categories
| Category | Description |
|----------|-------------|
| Hate | Discriminatory language based on identity groups |
| Sexual | Sexual content, relationships, acts |
| Violence | Physical harm, weapons, injury |
| Self-harm | Self-injury, suicide-related content |

### Severity Levels
- Text: 0-7 scale (default outputs 0, 2, 4, 6)
- Image: 0, 2, 4, 6 (trimmed scale)

## Core Patterns

### Analyze Text

```java
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());
}
```

### Analyze Text with Options

```java
AnalyzeTextOptions options = new AnalyzeTextOptions("Text to analyze")
    .setCategories(Arrays.asList(
        TextCategory.HATE,
        TextCategory.VIOLENCE))
    .setOutputType(AnalyzeTextOutputType.EIGHT_SEVERITY_LEVELS);

AnalyzeTextResult result = contentSafetyClient.analyzeText(options);
```

### Analyze Text with Blocklist

```java
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());
    }
}
```

### Analyze Image

```java
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());
}
```

### Analyze Image from URL

```java
ContentSafetyImageData imageData = new ContentSafetyImageData()
    .setBlobUrl("https://example.com/image.jpg");

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

## Blocklist Management

### Create or Update Blocklist

```java
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");
}
```

### Add Block Items

```java
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());
}
```

### List Blocklists

```java
PagedIterable<TextBlocklist> blocklists = blocklistClient.listTextBlocklists();

for (TextBlocklist blocklist : blocklists) {
    System.out.printf("Blocklist: %s, Description: %s%n",
        blocklist.getName(),
        blocklist.getDescription());
}
```

### Get Blocklist

```java
TextBlocklist blocklist = blocklistClient.getTextBlocklist("my-blocklist");
System.out.println("Name: " + blocklist.getName());
```

### List Block Items

```java
PagedIterable<TextBlocklistItem> items = 
    blocklistClient.listTextBlocklistItems("my-blocklist");

for (TextBlocklistItem item : items) {
    System.out.printf("ID: %s, Text: %s%n",
        item.getBlocklistItemId(),
        item.getText());
}
```

### Remove Block Items

```java
List<String> itemIds = Arrays.asList("item-id-1", "item-id-2");

blocklistClient.removeBlocklistItems(
    "my-blocklist",
    new RemoveTextBlocklistItemsOptions(itemIds));
```

### Delete Blocklist

```java
blocklistClient.deleteTextBlocklist("my-blocklist");
```

## Error Handling

```java
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
}
```

## Environment Variables

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

## Best Practices

1. **Blocklist Delay**: Changes take ~5 minutes to take effect
2. **Category Selection**: Only request needed categories to reduce latency
3. **Severity Thresholds**: Typically block severity >= 4 for strict moderation
4. **Batch Processing**: Process multiple items in parallel for throughput
5. **Caching**: Cache blocklist results where appropriate

## Trigger Phrases

- "content safety Java"
- "content moderation Azure"
- "analyze text safety"
- "image moderation Java"
- "blocklist management"
- "hate speech detection"
- "harmful content filter"

所有檔案

0 個檔案

安裝 azure-ai-contentsafety-java

請將技能檔案下載並解壓縮至您的 .claude/skills/ 目錄中。

下載 ZIP

複製儲存庫並將技能檔案複製到您的專案中。

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

複製 複製
快速設定: 將技能資料夾複製到 .claude/skills/ Claude 會自動偵測並使用該技能
儲存庫 microsoft/skills

相關技能

gmgn-portfolio
更新時間 2026-07-01
zeroize-audit
更新時間 2026-07-01
device-integrity
更新時間 2026-06-29
flutter-use-http-package
更新時間 2026-06-30
OR