azure-ai-contentsafety-ts
microsoft/skills
Analysez les textes et les images pour détecter les contenus nuisibles à l’aide d’Azure AI Content Safety, avec des listes de blocage et des seuils de gravité personnalisables.
...Développer toutSDK REST Azure AI Content Safety pour TypeScript
Analysez le texte et les images à la recherche de contenus nuisibles à l'aide de listes noires personnalisables.
Installation
npm install @azure-rest/ai-content-safety @azure/identity @azure/core-auth
Variables d'environnement
CONTENT_SAFETY_ENDPOINT=https://<resource>.cognitiveservices.azure.com
CONTENT_SAFETY_KEY=<api-key>
AZURE_TOKEN_CREDENTIALS=prod # Requis uniquement si DefaultAzureCredential est utilisé en production
</api-key></resource>Authentification
Important : Il s'agit d'un client REST. ContentSafetyClient est une fonction, et non une classe.
Clé d'API
import ContentSafetyClient from "@azure-rest/ai-content-safety";
import { AzureKeyCredential } from "@azure/core-auth";
const client = ContentSafetyClient(
process.env.CONTENT_SAFETY_ENDPOINT!,
new AzureKeyCredential(process.env.CONTENT_SAFETY_KEY!)
);
DefaultAzureCredential
import ContentSafetyClient from "@azure-rest/ai-content-safety";
import { DefaultAzureCredential, ManagedIdentityCredential } from "@azure/identity";
// Développement local : DefaultAzureCredential. Production : définissez AZURE_TOKEN_CREDENTIALS=prod ou AZURE_TOKEN_CREDENTIALS=<specific_credential>
const credential = new DefaultAzureCredential({requiredEnvVars: ["AZURE_TOKEN_CREDENTIALS"]});
// Ou utilisez un identifiant spécifique directement en production :
// Voir https://learn.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest#credential-classes
// const credential = new ManagedIdentityCredential();
const client = ContentSafetyClient(
process.env.CONTENT_SAFETY_ENDPOINT!,
credential
);
</specific_credential>Analyser le texte
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";
const result = await client.path("/text:analyze").post({
body: {
text: "Contenu textuel à analyser",
categories: ["Haine", "Sexuel", "Violence", "Auto-mutilation"],
outputType: "QuatreNiveauxDeGravité" // ou "HuitNiveauxDeGravité"
}
});
if (isUnexpected(result)) {
throw result.body;
}
for (const analysis of result.body.categoriesAnalysis) {
console.log(`${analysis.category} : gravité ${analysis.severity}`);
}
Analyser une image
Contenu Base64
import { readFileSync } from "node:fs";
const imageBuffer = readFileSync("./image.png");
const base64Image = imageBuffer.toString("base64");
const result = await client.path("/image:analyze").post({
body: {
image: { content: base64Image }
}
});
if (isUnexpected(result)) {
throw result.body;
}
for (const analysis of result.body.categoriesAnalysis) {
console.log(`${analysis.category} : gravité ${analysis.severity}`);
}
URL de blob
const result = await client.path("/image:analyze").post({
body: {
image: { blobUrl: "https://storage.blob.core.windows.net/container/image.png" }
}
});
Gestion des listes noires
Créer une liste noire
const result = await client
.path("/text/blocklists/{blocklistName}", "ma-liste-noire")
.patch({
contentType: "application/merge-patch+json",
body: {
description: "Liste noire personnalisée pour les termes interdits"
}
});
if (isUnexpected(result)) {
throw result.body;
}
console.log(`Créée : ${result.body.blocklistName}`);
Ajouter des éléments à la liste noire
const result = await client
.path("/text/blocklists/{blocklistName}:addOrUpdateBlocklistItems", "ma-liste-noire")
.post({
body: {
blocklistItems: [
{ text: "terme-interdit-1", description: "Premier terme bloqué" },
{ text: "terme-interdit-2", description: "Deuxième terme bloqué" }
]
}
});
if (isUnexpected(result)) {
throw result.body;
}
for (const item of result.body.blocklistItems ?? []) {
console.log(`Ajouté : ${item.blocklistItemId}`);
}
Analyser avec une liste noire
const result = await client.path("/text:analyze").post({
body: {
text: "Texte pouvant contenir des termes bloqués",
blocklistNames: ["ma-liste-noire"],
haltOnBlocklistHit: false
}
});
if (isUnexpected(result)) {
throw result.body;
}
// Vérifier les correspondances de la liste noire
if (result.body.blocklistsMatch) {
for (const match of result.body.blocklistsMatch) {
console.log(`Bloqué : "${match.blocklistItemText}" provenant de ${match.blocklistName}`);
}
}
Lister les listes noires
const result = await client.path("/text/blocklists").get();
if (isUnexpected(result)) {
throw result.body;
}
for (const blocklist of result.body.value ?? []) {
console.log(`${blocklist.blocklistName} : ${blocklist.description}`);
}
Supprimer une liste noire
await client.path("/text/blocklists/{blocklistName}", "ma-liste-noire").delete();
Catégories de préjudice
| Catégorie | Terme de l'API | Description |
|---|---|---|
| Discrimination et équité | `Haine` | Langue discriminatoire ciblant des groupes identitaires |
| Sexuel | `Sexuel` | Contenu sexuel, nudité, pornographie |
| Violence | `Violence` | Blessures physiques, armes, terrorisme |
| Auto-mutilation | `Auto-mutilation` | Automutilation, suicide, troubles alimentaires |
Niveaux de gravité
| Niveau | Risque | Action recommandée |
|---|---|---|
| 0 | Sûr | Autoriser |
| 2 | Faible | Vérifier ou autoriser avec avertissement |
| 4 | Moyen | Bloquer ou exiger une révision humaine |
| 6 | Élevé | Bloquer immédiatement |
Types de sortie :
QuatreNiveauxDeGravité(par défaut) : Retourne 0, 2, 4, 6HuitNiveauxDeGravité: Retourne 0-7
Assistant de modération de contenu
import ContentSafetyClient, {
isUnexpected,
TextCategoriesAnalysisOutput
} from "@azure-rest/ai-content-safety";
interface ResultatModeration {
isAllowed: boolean;
flaggedCategories: string[];
maxSeverity: number;
blocklistMatches: string[];
}
async function moderateContent(
client: ReturnType<typeof>,
text: string,
maxAllowedSeverity = 2,
blocklistNames: string[] = []
): Promise<moderationresult> {
const result = await client.path("/text:analyze").post({
body: { text, blocklistNames, haltOnBlocklistHit: false }
});
if (isUnexpected(result)) {
throw result.body;
}
const flaggedCategories = result.body.categoriesAnalysis
.filter(c => (c.severity ?? 0) > maxAllowedSeverity)
.map(c => c.category!);
const maxSeverity = Math.max(
...result.body.categoriesAnalysis.map(c => c.severity ?? 0)
);
const blocklistMatches = (result.body.blocklistsMatch ?? [])
.map(m => m.blocklistItemText!);
return {
isAllowed: flaggedCategories.length === 0 && blocklistMatches.length === 0,
flaggedCategories,
maxSeverity,
blocklistMatches
};
}
</moderationresult></typeof>Points de terminaison de l'API
| Opération | Méthode | Chemin |
|---|---|---|
| Analyser le texte | POST | `/text:analyze` |
| Analyser une image | POST | `/image:analyze` |
| Créer/Mettre à jour une liste noire | PATCH | `/text/blocklists/{blocklistName}` |
| Lister les listes noires | GET | `/text/blocklists` |
| Supprimer une liste noire | DELETE | `/text/blocklists/{blocklistName}` |
| Ajouter des éléments de liste noire | POST | `/text/blocklists/{blocklistName}:addOrUpdateBlocklistItems` |
| Lister les éléments de liste noire | GET | `/text/blocklists/{blocklistName}/blocklistItems` |
| Supprimer des éléments de liste noire | POST | `/text/blocklists/{blocklistName}:removeBlocklistItems` |
Types clés
import ContentSafetyClient, {
isUnexpected,
AnalyzeTextParameters,
AnalyzeImageParameters,
TextCategoriesAnalysisOutput,
ImageCategoriesAnalysisOutput,
TextBlocklist,
TextBlocklistItem
} from "@azure-rest/ai-content-safety";
Bonnes pratiques
- Toujours utiliser isUnexpected() - Garde de type pour la gestion des erreurs
- Définir des seuils appropriés - Différentes catégories peuvent nécessiter des seuils de gravité différents
- Utiliser des listes noires pour les termes spécifiques au domaine - Compléter la détection par l'IA avec des règles personnalisées
- Journaliser les décisions de modération - Conserver une piste d'audit pour la conformité
- Gérer les cas limites - Texte vide, texte très long, formats d'image non pris en charge
---
name: azure-ai-contentsafety-ts
description: Analyze text and images for harmful content using Azure AI Content Safety, with customizable blocklists and severity thresholds.
license: MIT
---
# Azure AI Content Safety REST SDK for TypeScript
Analyze text and images for harmful content with customizable blocklists.
## Installation
```bash
npm install @azure-rest/ai-content-safety @azure/identity @azure/core-auth
```
## Environment Variables
```bash
CONTENT_SAFETY_ENDPOINT=https://<resource>.cognitiveservices.azure.com
CONTENT_SAFETY_KEY=<api-key>
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```
## Authentication
**Important**: This is a REST client. `ContentSafetyClient` is a **function**, not a class.
### API Key
```typescript
import ContentSafetyClient from "@azure-rest/ai-content-safety";
import { AzureKeyCredential } from "@azure/core-auth";
const client = ContentSafetyClient(
process.env.CONTENT_SAFETY_ENDPOINT!,
new AzureKeyCredential(process.env.CONTENT_SAFETY_KEY!)
);
```
### DefaultAzureCredential
```typescript
import ContentSafetyClient from "@azure-rest/ai-content-safety";
import { DefaultAzureCredential, ManagedIdentityCredential } from "@azure/identity";
// Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
const credential = new DefaultAzureCredential({requiredEnvVars: ["AZURE_TOKEN_CREDENTIALS"]});
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest#credential-classes
// const credential = new ManagedIdentityCredential();
const client = ContentSafetyClient(
process.env.CONTENT_SAFETY_ENDPOINT!,
credential
);
```
## Analyze Text
```typescript
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";
const result = await client.path("/text:analyze").post({
body: {
text: "Text content to analyze",
categories: ["Hate", "Sexual", "Violence", "SelfHarm"],
outputType: "FourSeverityLevels" // or "EightSeverityLevels"
}
});
if (isUnexpected(result)) {
throw result.body;
}
for (const analysis of result.body.categoriesAnalysis) {
console.log(`${analysis.category}: severity ${analysis.severity}`);
}
```
## Analyze Image
### Base64 Content
```typescript
import { readFileSync } from "node:fs";
const imageBuffer = readFileSync("./image.png");
const base64Image = imageBuffer.toString("base64");
const result = await client.path("/image:analyze").post({
body: {
image: { content: base64Image }
}
});
if (isUnexpected(result)) {
throw result.body;
}
for (const analysis of result.body.categoriesAnalysis) {
console.log(`${analysis.category}: severity ${analysis.severity}`);
}
```
### Blob URL
```typescript
const result = await client.path("/image:analyze").post({
body: {
image: { blobUrl: "https://storage.blob.core.windows.net/container/image.png" }
}
});
```
## Blocklist Management
### Create Blocklist
```typescript
const result = await client
.path("/text/blocklists/{blocklistName}", "my-blocklist")
.patch({
contentType: "application/merge-patch+json",
body: {
description: "Custom blocklist for prohibited terms"
}
});
if (isUnexpected(result)) {
throw result.body;
}
console.log(`Created: ${result.body.blocklistName}`);
```
### Add Items to Blocklist
```typescript
const result = await client
.path("/text/blocklists/{blocklistName}:addOrUpdateBlocklistItems", "my-blocklist")
.post({
body: {
blocklistItems: [
{ text: "prohibited-term-1", description: "First blocked term" },
{ text: "prohibited-term-2", description: "Second blocked term" }
]
}
});
if (isUnexpected(result)) {
throw result.body;
}
for (const item of result.body.blocklistItems ?? []) {
console.log(`Added: ${item.blocklistItemId}`);
}
```
### Analyze with Blocklist
```typescript
const result = await client.path("/text:analyze").post({
body: {
text: "Text that might contain blocked terms",
blocklistNames: ["my-blocklist"],
haltOnBlocklistHit: false
}
});
if (isUnexpected(result)) {
throw result.body;
}
// Check blocklist matches
if (result.body.blocklistsMatch) {
for (const match of result.body.blocklistsMatch) {
console.log(`Blocked: "${match.blocklistItemText}" from ${match.blocklistName}`);
}
}
```
### List Blocklists
```typescript
const result = await client.path("/text/blocklists").get();
if (isUnexpected(result)) {
throw result.body;
}
for (const blocklist of result.body.value ?? []) {
console.log(`${blocklist.blocklistName}: ${blocklist.description}`);
}
```
### Delete Blocklist
```typescript
await client.path("/text/blocklists/{blocklistName}", "my-blocklist").delete();
```
## Harm Categories
| Category | API Term | Description |
|----------|----------|-------------|
| Hate and Fairness | `Hate` | Discriminatory language targeting identity groups |
| Sexual | `Sexual` | Sexual content, nudity, pornography |
| Violence | `Violence` | Physical harm, weapons, terrorism |
| Self-Harm | `SelfHarm` | Self-injury, suicide, eating disorders |
## Severity Levels
| Level | Risk | Recommended Action |
|-------|------|-------------------|
| 0 | Safe | Allow |
| 2 | Low | Review or allow with warning |
| 4 | Medium | Block or require human review |
| 6 | High | Block immediately |
**Output Types**:
- `FourSeverityLevels` (default): Returns 0, 2, 4, 6
- `EightSeverityLevels`: Returns 0-7
## Content Moderation Helper
```typescript
import ContentSafetyClient, {
isUnexpected,
TextCategoriesAnalysisOutput
} from "@azure-rest/ai-content-safety";
interface ModerationResult {
isAllowed: boolean;
flaggedCategories: string[];
maxSeverity: number;
blocklistMatches: string[];
}
async function moderateContent(
client: ReturnType<typeof ContentSafetyClient>,
text: string,
maxAllowedSeverity = 2,
blocklistNames: string[] = []
): Promise<ModerationResult> {
const result = await client.path("/text:analyze").post({
body: { text, blocklistNames, haltOnBlocklistHit: false }
});
if (isUnexpected(result)) {
throw result.body;
}
const flaggedCategories = result.body.categoriesAnalysis
.filter(c => (c.severity ?? 0) > maxAllowedSeverity)
.map(c => c.category!);
const maxSeverity = Math.max(
...result.body.categoriesAnalysis.map(c => c.severity ?? 0)
);
const blocklistMatches = (result.body.blocklistsMatch ?? [])
.map(m => m.blocklistItemText!);
return {
isAllowed: flaggedCategories.length === 0 && blocklistMatches.length === 0,
flaggedCategories,
maxSeverity,
blocklistMatches
};
}
```
## API Endpoints
| Operation | Method | Path |
|-----------|--------|------|
| Analyze Text | POST | `/text:analyze` |
| Analyze Image | POST | `/image:analyze` |
| Create/Update Blocklist | PATCH | `/text/blocklists/{blocklistName}` |
| List Blocklists | GET | `/text/blocklists` |
| Delete Blocklist | DELETE | `/text/blocklists/{blocklistName}` |
| Add Blocklist Items | POST | `/text/blocklists/{blocklistName}:addOrUpdateBlocklistItems` |
| List Blocklist Items | GET | `/text/blocklists/{blocklistName}/blocklistItems` |
| Remove Blocklist Items | POST | `/text/blocklists/{blocklistName}:removeBlocklistItems` |
## Key Types
```typescript
import ContentSafetyClient, {
isUnexpected,
AnalyzeTextParameters,
AnalyzeImageParameters,
TextCategoriesAnalysisOutput,
ImageCategoriesAnalysisOutput,
TextBlocklist,
TextBlocklistItem
} from "@azure-rest/ai-content-safety";
```
## Best Practices
1. **Always use isUnexpected()** - Type guard for error handling
2. **Set appropriate thresholds** - Different categories may need different severity thresholds
3. **Use blocklists for domain-specific terms** - Supplement AI detection with custom rules
4. **Log moderation decisions** - Keep audit trail for compliance
5. **Handle edge cases** - Empty text, very long text, unsupported image formats
Tous les fichiers
0 fichiersInstaller azure-ai-contentsafety-ts
Téléchargez et extrayez les fichiers de compétences dans votre répertoire .claude/skills/.
Télécharger le ZIPClonez le dépôt et copiez les fichiers de compétence dans votre projet.
git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-typescript/skills/azure-ai-contentsafety-ts # Copy SKILL.md to your .claude/skills/ directory
Copier





Maison
