Skip to content

Commit 5280492

Browse files
authored
Merge pull request #6084 from diberry/diberry/0716-content-safety-blocklist
Content safety blocklist qs - JS & Ts
2 parents a3dcfe1 + 80c4417 commit 5280492

File tree

6 files changed

+642
-16
lines changed

6 files changed

+642
-16
lines changed
Lines changed: 266 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,266 @@
1+
---
2+
title: "Quickstart: Use a blocklist with JavaScript"
3+
description: In this quickstart, get started using the Azure AI Content Safety JavaScript SDK to create and use a text blocklist.
4+
author: PatrickFarley
5+
manager: nitinme
6+
ms.service: azure-ai-content-safety
7+
ms.custom:
8+
ms.topic: include
9+
ms.date: 07/16/2025
10+
ms.author: pafarley
11+
---
12+
13+
[Reference documentation](https://www.npmjs.com/package/@azure-rest/ai-content-safety/v/1.0.0) | [Library source code](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/contentsafety/ai-content-safety-rest) | [Package (npm)](https://www.npmjs.com/package/@azure-rest/ai-content-safety) | [Samples](https://github.com/Azure-Samples/AzureAIContentSafety/tree/main/js/1.0.0) |
14+
15+
16+
## Prerequisites
17+
18+
* An Azure subscription - [Create one for free](https://azure.microsoft.com/free/cognitive-services/)
19+
* [Node.js LTS](https://nodejs.org/)
20+
* [Visual Studio Code](https://code.visualstudio.com/)
21+
* Once you have your Azure subscription, <a href="https://aka.ms/acs-create" title="Create a Content Safety resource" target="_blank">create a Content Safety resource </a> in the Azure portal to get your key and endpoint. Enter a unique name for your resource, select your subscription, and select a resource group, supported region (see [Region availability](/azure/ai-services/content-safety/overview#region-availability)), and supported pricing tier. Then select **Create**.
22+
* The resource takes a few minutes to deploy. After it finishes, Select **go to resource**. In the left pane, under **Resource Management**, select **Subscription Key and Endpoint**. The endpoint and either of the keys are used to call APIs.
23+
24+
## Set up local development environment
25+
26+
1. Create a new directory for your project and navigate to it:
27+
28+
```console
29+
mkdir content-safety-blocklist-analysis
30+
cd content-safety-blocklist-analysis
31+
code .
32+
```
33+
34+
1. Create a new package for ESM modules in your project directory:
35+
36+
```console
37+
npm init -y
38+
npm pkg set type=module
39+
```
40+
41+
1. Install the required packages:
42+
43+
```console
44+
npm install @azure-rest/ai-content-safety
45+
```
46+
47+
1. Create a `src` directory for your JavaScript code.
48+
49+
[!INCLUDE [Create environment variables](../env-vars.md)]
50+
51+
## Create and use a blocklist
52+
53+
Create a new file in your `src` directory, `index.js` and paste in the following code.
54+
55+
56+
```javascript
57+
import ContentSafetyClient, {
58+
isUnexpected
59+
} from "@azure-rest/ai-content-safety";
60+
import { AzureKeyCredential } from "@azure/core-auth";
61+
62+
// Get endpoint and key from environment variables
63+
const key = process.env.CONTENT_SAFETY_KEY;
64+
const endpoint = process.env.CONTENT_SAFETY_ENDPOINT;
65+
66+
if (!key || !endpoint) {
67+
throw new Error("Missing required environment variables: CONTENT_SAFETY_KEY or CONTENT_SAFETY_ENDPOINT");
68+
}
69+
70+
// Define your blocklist information
71+
// This creates a custom blocklist for words/phrases you want to specifically block
72+
const blocklistName = "company-prohibited-terms";
73+
const blocklistDescription = "Custom blocklist for company-specific prohibited terms and phrases";
74+
75+
// Define items to block - these are specific words or phrases you want to flag
76+
// Even if Azure AI doesn't naturally flag them, these will be caught
77+
const blocklistItemText1 = "confidential project alpha";
78+
const blocklistItemText2 = "internal revenue data";
79+
80+
// Define sample text for analysis that contains one of our blocked terms
81+
const inputText = "Please don't share the confidential project alpha details with external teams.";
82+
83+
/**
84+
* Step 1: Create or update a custom blocklist container
85+
*/
86+
async function createBlocklistContainer(
87+
client,
88+
name,
89+
description
90+
) {
91+
92+
const blocklistData = {
93+
blocklistName: name,
94+
description: description
95+
};
96+
97+
const createBlocklistParams = {
98+
body: blocklistData,
99+
contentType: "application/merge-patch+json"
100+
};
101+
102+
const blocklistResult =
103+
await client.path("/text/blocklists/{blocklistName}", name).patch(createBlocklistParams);
104+
105+
if (isUnexpected(blocklistResult)) {
106+
throw blocklistResult;
107+
}
108+
109+
console.log("✅ Blocklist created successfully!");
110+
console.log(` Name: ${blocklistResult.body.blocklistName}`);
111+
console.log(` Description: ${blocklistResult.body.description || "No description"}\n`);
112+
}
113+
114+
/**
115+
* Step 2: Add specific prohibited terms to the blocklist
116+
*/
117+
async function addProhibitedTerms(
118+
client,
119+
blocklistName,
120+
terms
121+
) {
122+
123+
const blocklistItems = terms.map(text => ({ text }));
124+
125+
const addItemsParams = {
126+
body: { blocklistItems: blocklistItems }
127+
};
128+
129+
const addItemsResult =
130+
await client.path("/text/blocklists/{blocklistName}:addOrUpdateBlocklistItems", blocklistName).post(addItemsParams);
131+
132+
if (isUnexpected(addItemsResult)) {
133+
throw addItemsResult;
134+
}
135+
136+
console.log("✅ Terms added to blocklist successfully!");
137+
for (const item of addItemsResult.body.blocklistItems) {
138+
console.log(` BlocklistItemId: ${item.blocklistItemId}`);
139+
console.log(` Text: "${item.text}"`);
140+
console.log(` Description: ${item.description || "No description"}\n`);
141+
}
142+
}
143+
144+
/**
145+
* Step 3: Wait for blocklist changes to propagate through Azure's system
146+
*/
147+
async function waitForBlocklistActivation(seconds = 5) {
148+
await new Promise(resolve => setTimeout(resolve, seconds * 1000));
149+
}
150+
151+
/**
152+
* Step 4: Analyze text against the custom blocklist
153+
*/
154+
async function analyzeTextAgainstBlocklist(
155+
client,
156+
textToAnalyze,
157+
blocklistName
158+
) {
159+
160+
const analyzeTextOption = {
161+
text: textToAnalyze,
162+
blocklistNames: [blocklistName], // Use our custom blocklist
163+
haltOnBlocklistHit: false // Continue analysis even if blocklist match found
164+
};
165+
166+
const analyzeTextParams = { body: analyzeTextOption };
167+
168+
const analysisResult =
169+
await client.path("/text:analyze").post(analyzeTextParams);
170+
171+
if (isUnexpected(analysisResult)) {
172+
throw analysisResult;
173+
}
174+
175+
return analysisResult;
176+
}
177+
178+
/**
179+
* Step 5: Display analysis results and explain what they mean
180+
*/
181+
function displayAnalysisResults(analysisResult) {
182+
183+
if (analysisResult.body.blocklistsMatch && analysisResult.body.blocklistsMatch.length > 0) {
184+
console.log("🚨 BLOCKED CONTENT DETECTED!");
185+
console.log("The following prohibited terms were found:\n");
186+
187+
for (const match of analysisResult.body.blocklistsMatch) {
188+
console.log(` Blocklist: ${match.blocklistName}`);
189+
console.log(` Matched Term: "${match.blocklistItemText}"`);
190+
console.log(` Item ID: ${match.blocklistItemId}\n`);
191+
}
192+
193+
} else {
194+
console.log("✅ No blocked content found.");
195+
console.log("The text does not contain any terms from your custom blocklist.");
196+
}
197+
}
198+
199+
try {
200+
const credential = new AzureKeyCredential(key);
201+
const client = ContentSafetyClient(endpoint, credential);
202+
203+
// Execute the five main steps
204+
await createBlocklistContainer(client, blocklistName, blocklistDescription);
205+
await addProhibitedTerms(client, blocklistName, [blocklistItemText1, blocklistItemText2]);
206+
207+
console.log("⏳ Waiting for blocklist changes to take effect...");
208+
await waitForBlocklistActivation();
209+
210+
const analysisResult = await analyzeTextAgainstBlocklist(client, inputText, blocklistName);
211+
212+
displayAnalysisResults(analysisResult);
213+
214+
} catch (error) {
215+
console.error("❌ An error occurred:", error.message);
216+
if (error.code) {
217+
console.error(`Error code: ${error.code}`);
218+
}
219+
if (error.details) {
220+
console.error("Error details:", error.details);
221+
}
222+
}
223+
```
224+
225+
This code:
226+
227+
- Creates a custom blocklist.
228+
- Adds prohibited terms to it.
229+
- Analyzes text against the blocklist.
230+
231+
232+
The TypeScript implementation provides strong typing for better development experience and error checking.
233+
234+
## Run the sample
235+
236+
Run the application with the `node` command on your quickstart file.
237+
238+
```console
239+
node -r dotenv/config src/index.js
240+
```
241+
242+
## Output
243+
244+
When you run the application, you should see output similar to this:
245+
246+
```console
247+
✅ Blocklist created successfully!
248+
Name: company-prohibited-terms
249+
Description: Custom blocklist for company-specific prohibited terms and phrases
250+
251+
✅ Terms added to blocklist successfully!
252+
BlocklistItemId: 6fe21688-f65d-4d0b-9ff5-c6e5859ea83a
253+
Text: "internal revenue data"
254+
Description: No description
255+
256+
BlocklistItemId: b48f958b-a58b-4d49-9e33-8ece75fc6c3b
257+
Text: "confidential project alpha"
258+
Description: No description
259+
260+
🚨 BLOCKED CONTENT DETECTED!
261+
The following prohibited terms were found:
262+
263+
Blocklist: company-prohibited-terms
264+
Matched Term: "confidential project alpha"
265+
Item ID: b48f958b-a58b-4d49-9e33-8ece75fc6c3b
266+
```

0 commit comments

Comments
 (0)