Build content moderation applications with Azure AI Content Safety SDK for Java. Use when implementing text/image analysis, blocklist management, or harm detection for hate, violence, sexual content, and self-harm.
Add this skill
npx mdskills install sickn33/azure-ai-contentsafety-javaComprehensive SDK reference with clear examples, but not actionable as an agent skill
1---2name: azure-ai-contentsafety-java3description: Build content moderation applications with Azure AI Content Safety SDK for Java. Use when implementing text/image analysis, blocklist management, or harm detection for hate, violence, sexual content, and self-harm.4package: com.azure:azure-ai-contentsafety5---67# Azure AI Content Safety SDK for Java89Build content moderation applications using the Azure AI Content Safety SDK for Java.1011## Installation1213```xml14<dependency>15 <groupId>com.azure</groupId>16 <artifactId>azure-ai-contentsafety</artifactId>17 <version>1.1.0-beta.1</version>18</dependency>19```2021## Client Creation2223### With API Key2425```java26import com.azure.ai.contentsafety.ContentSafetyClient;27import com.azure.ai.contentsafety.ContentSafetyClientBuilder;28import com.azure.ai.contentsafety.BlocklistClient;29import com.azure.ai.contentsafety.BlocklistClientBuilder;30import com.azure.core.credential.KeyCredential;3132String endpoint = System.getenv("CONTENT_SAFETY_ENDPOINT");33String key = System.getenv("CONTENT_SAFETY_KEY");3435ContentSafetyClient contentSafetyClient = new ContentSafetyClientBuilder()36 .credential(new KeyCredential(key))37 .endpoint(endpoint)38 .buildClient();3940BlocklistClient blocklistClient = new BlocklistClientBuilder()41 .credential(new KeyCredential(key))42 .endpoint(endpoint)43 .buildClient();44```4546### With DefaultAzureCredential4748```java49import com.azure.identity.DefaultAzureCredentialBuilder;5051ContentSafetyClient client = new ContentSafetyClientBuilder()52 .credential(new DefaultAzureCredentialBuilder().build())53 .endpoint(endpoint)54 .buildClient();55```5657## Key Concepts5859### Harm Categories60| Category | Description |61|----------|-------------|62| Hate | Discriminatory language based on identity groups |63| Sexual | Sexual content, relationships, acts |64| Violence | Physical harm, weapons, injury |65| Self-harm | Self-injury, suicide-related content |6667### Severity Levels68- Text: 0-7 scale (default outputs 0, 2, 4, 6)69- Image: 0, 2, 4, 6 (trimmed scale)7071## Core Patterns7273### Analyze Text7475```java76import com.azure.ai.contentsafety.models.*;7778AnalyzeTextResult result = contentSafetyClient.analyzeText(79 new AnalyzeTextOptions("This is text to analyze"));8081for (TextCategoriesAnalysis category : result.getCategoriesAnalysis()) {82 System.out.printf("Category: %s, Severity: %d%n",83 category.getCategory(),84 category.getSeverity());85}86```8788### Analyze Text with Options8990```java91AnalyzeTextOptions options = new AnalyzeTextOptions("Text to analyze")92 .setCategories(Arrays.asList(93 TextCategory.HATE,94 TextCategory.VIOLENCE))95 .setOutputType(AnalyzeTextOutputType.EIGHT_SEVERITY_LEVELS);9697AnalyzeTextResult result = contentSafetyClient.analyzeText(options);98```99100### Analyze Text with Blocklist101102```java103AnalyzeTextOptions options = new AnalyzeTextOptions("I h*te you and want to k*ll you")104 .setBlocklistNames(Arrays.asList("my-blocklist"))105 .setHaltOnBlocklistHit(true);106107AnalyzeTextResult result = contentSafetyClient.analyzeText(options);108109if (result.getBlocklistsMatch() != null) {110 for (TextBlocklistMatch match : result.getBlocklistsMatch()) {111 System.out.printf("Blocklist: %s, Item: %s, Text: %s%n",112 match.getBlocklistName(),113 match.getBlocklistItemId(),114 match.getBlocklistItemText());115 }116}117```118119### Analyze Image120121```java122import com.azure.ai.contentsafety.models.*;123import com.azure.core.util.BinaryData;124import java.nio.file.Files;125import java.nio.file.Paths;126127// From file128byte[] imageBytes = Files.readAllBytes(Paths.get("image.png"));129ContentSafetyImageData imageData = new ContentSafetyImageData()130 .setContent(BinaryData.fromBytes(imageBytes));131132AnalyzeImageResult result = contentSafetyClient.analyzeImage(133 new AnalyzeImageOptions(imageData));134135for (ImageCategoriesAnalysis category : result.getCategoriesAnalysis()) {136 System.out.printf("Category: %s, Severity: %d%n",137 category.getCategory(),138 category.getSeverity());139}140```141142### Analyze Image from URL143144```java145ContentSafetyImageData imageData = new ContentSafetyImageData()146 .setBlobUrl("https://example.com/image.jpg");147148AnalyzeImageResult result = contentSafetyClient.analyzeImage(149 new AnalyzeImageOptions(imageData));150```151152## Blocklist Management153154### Create or Update Blocklist155156```java157import com.azure.core.http.rest.RequestOptions;158import com.azure.core.http.rest.Response;159import com.azure.core.util.BinaryData;160import java.util.Map;161162Map<String, String> description = Map.of("description", "Custom blocklist");163BinaryData resource = BinaryData.fromObject(description);164165Response<BinaryData> response = blocklistClient.createOrUpdateTextBlocklistWithResponse(166 "my-blocklist", resource, new RequestOptions());167168if (response.getStatusCode() == 201) {169 System.out.println("Blocklist created");170} else if (response.getStatusCode() == 200) {171 System.out.println("Blocklist updated");172}173```174175### Add Block Items176177```java178import com.azure.ai.contentsafety.models.*;179import java.util.Arrays;180181List<TextBlocklistItem> items = Arrays.asList(182 new TextBlocklistItem("badword1").setDescription("Offensive term"),183 new TextBlocklistItem("badword2").setDescription("Another term")184);185186AddOrUpdateTextBlocklistItemsResult result = blocklistClient.addOrUpdateBlocklistItems(187 "my-blocklist",188 new AddOrUpdateTextBlocklistItemsOptions(items));189190for (TextBlocklistItem item : result.getBlocklistItems()) {191 System.out.printf("Added: %s (ID: %s)%n",192 item.getText(),193 item.getBlocklistItemId());194}195```196197### List Blocklists198199```java200PagedIterable<TextBlocklist> blocklists = blocklistClient.listTextBlocklists();201202for (TextBlocklist blocklist : blocklists) {203 System.out.printf("Blocklist: %s, Description: %s%n",204 blocklist.getName(),205 blocklist.getDescription());206}207```208209### Get Blocklist210211```java212TextBlocklist blocklist = blocklistClient.getTextBlocklist("my-blocklist");213System.out.println("Name: " + blocklist.getName());214```215216### List Block Items217218```java219PagedIterable<TextBlocklistItem> items =220 blocklistClient.listTextBlocklistItems("my-blocklist");221222for (TextBlocklistItem item : items) {223 System.out.printf("ID: %s, Text: %s%n",224 item.getBlocklistItemId(),225 item.getText());226}227```228229### Remove Block Items230231```java232List<String> itemIds = Arrays.asList("item-id-1", "item-id-2");233234blocklistClient.removeBlocklistItems(235 "my-blocklist",236 new RemoveTextBlocklistItemsOptions(itemIds));237```238239### Delete Blocklist240241```java242blocklistClient.deleteTextBlocklist("my-blocklist");243```244245## Error Handling246247```java248import com.azure.core.exception.HttpResponseException;249250try {251 contentSafetyClient.analyzeText(new AnalyzeTextOptions("test"));252} catch (HttpResponseException e) {253 System.out.println("Status: " + e.getResponse().getStatusCode());254 System.out.println("Error: " + e.getMessage());255 // Common codes: InvalidRequestBody, ResourceNotFound, TooManyRequests256}257```258259## Environment Variables260261```bash262CONTENT_SAFETY_ENDPOINT=https://<resource>.cognitiveservices.azure.com/263CONTENT_SAFETY_KEY=<your-api-key>264```265266## Best Practices2672681. **Blocklist Delay**: Changes take ~5 minutes to take effect2692. **Category Selection**: Only request needed categories to reduce latency2703. **Severity Thresholds**: Typically block severity >= 4 for strict moderation2714. **Batch Processing**: Process multiple items in parallel for throughput2725. **Caching**: Cache blocklist results where appropriate273274## Trigger Phrases275276- "content safety Java"277- "content moderation Azure"278- "analyze text safety"279- "image moderation Java"280- "blocklist management"281- "hate speech detection"282- "harmful content filter"283
Full transparency — inspect the skill content before installing.