0
# Blocklist Management
1
2
Comprehensive text blocklist management capabilities for creating, managing, and maintaining custom lists of prohibited terms. Blocklists enable organizations to screen content for domain-specific terms that should be blocked or flagged, complementing the AI-powered content analysis.
3
4
## Capabilities
5
6
### Blocklist CRUD Operations
7
8
Create, retrieve, update, and delete text blocklists to organize prohibited terms by category, use case, or severity level.
9
10
```python { .api }
11
def create_or_update_text_blocklist(
12
self,
13
blocklist_name: str,
14
options: Union[TextBlocklist, dict, IO[bytes]],
15
**kwargs
16
) -> TextBlocklist:
17
"""
18
Create a new text blocklist or update an existing one.
19
20
Parameters:
21
- blocklist_name: Name of the blocklist to create or update
22
- options: Blocklist resource with name and optional description
23
- content_type: Body parameter content-type (default: "application/merge-patch+json")
24
- stream: Whether to stream the response (default: False)
25
26
Returns:
27
TextBlocklist: The created or updated blocklist resource
28
29
Raises:
30
HttpResponseError: On creation/update failure
31
"""
32
33
def get_text_blocklist(self, blocklist_name: str, **kwargs) -> TextBlocklist:
34
"""
35
Get details of a specific text blocklist by name.
36
37
Parameters:
38
- blocklist_name: Name of the blocklist to retrieve
39
- stream: Whether to stream the response (default: False)
40
41
Returns:
42
TextBlocklist: The blocklist resource with metadata
43
44
Raises:
45
HttpResponseError: On retrieval failure or if blocklist doesn't exist
46
"""
47
48
def list_text_blocklists(self, **kwargs) -> Iterable[TextBlocklist]:
49
"""
50
List all text blocklists in the Content Safety resource.
51
52
Parameters:
53
- maxpagesize: Maximum items per page (passed via kwargs)
54
55
Returns:
56
ItemPaged[TextBlocklist]: Paginated list of all blocklists
57
58
Raises:
59
HttpResponseError: On listing failure
60
"""
61
62
def delete_text_blocklist(self, blocklist_name: str, **kwargs) -> None:
63
"""
64
Delete a text blocklist and all its items.
65
66
Parameters:
67
- blocklist_name: Name of the blocklist to delete
68
69
Returns:
70
None
71
72
Raises:
73
HttpResponseError: On deletion failure or if blocklist doesn't exist
74
"""
75
```
76
77
**Usage Example:**
78
79
```python
80
from azure.ai.contentsafety import BlocklistClient
81
from azure.ai.contentsafety.models import TextBlocklist
82
from azure.core.credentials import AzureKeyCredential
83
84
client = BlocklistClient(
85
endpoint="https://your-resource.cognitiveservices.azure.com",
86
credential=AzureKeyCredential("your-api-key")
87
)
88
89
# Create a new blocklist
90
blocklist = TextBlocklist(
91
blocklist_name="profanity-filter",
92
description="Common profanity and inappropriate terms"
93
)
94
created_blocklist = client.create_or_update_text_blocklist("profanity-filter", blocklist)
95
print(f"Created blocklist: {created_blocklist.blocklist_name}")
96
97
# List all blocklists
98
all_blocklists = client.list_text_blocklists()
99
for bl in all_blocklists:
100
print(f"Blocklist: {bl.blocklist_name} - {bl.description}")
101
102
# Get specific blocklist
103
specific_blocklist = client.get_text_blocklist("profanity-filter")
104
print(f"Retrieved: {specific_blocklist.description}")
105
106
# Delete blocklist (when no longer needed)
107
# client.delete_text_blocklist("profanity-filter")
108
109
client.close()
110
```
111
112
### Blocklist Item Management
113
114
Add, update, retrieve, and remove individual terms within blocklists, with support for bulk operations and pagination.
115
116
```python { .api }
117
def add_or_update_blocklist_items(
118
self,
119
blocklist_name: str,
120
options: Union[AddOrUpdateTextBlocklistItemsOptions, dict, IO[bytes]],
121
**kwargs
122
) -> AddOrUpdateTextBlocklistItemsResult:
123
"""
124
Add or update items in a text blocklist (max 100 items per request).
125
126
Parameters:
127
- blocklist_name: Name of the target blocklist
128
- options: Options containing list of items to add or update
129
- content_type: Body parameter content-type (default: "application/json")
130
- stream: Whether to stream the response (default: False)
131
132
Returns:
133
AddOrUpdateTextBlocklistItemsResult: Result with added/updated items
134
135
Raises:
136
HttpResponseError: On operation failure or if blocklist doesn't exist
137
"""
138
139
def get_text_blocklist_item(
140
self,
141
blocklist_name: str,
142
blocklist_item_id: str,
143
**kwargs
144
) -> TextBlocklistItem:
145
"""
146
Get a specific blocklist item by ID.
147
148
Parameters:
149
- blocklist_name: Name of the containing blocklist
150
- blocklist_item_id: UUID of the specific item
151
- stream: Whether to stream the response (default: False)
152
153
Returns:
154
TextBlocklistItem: The requested blocklist item
155
156
Raises:
157
HttpResponseError: On retrieval failure or if item doesn't exist
158
"""
159
160
def list_text_blocklist_items(
161
self,
162
blocklist_name: str,
163
*,
164
top: Optional[int] = None,
165
skip: Optional[int] = None,
166
**kwargs
167
) -> Iterable[TextBlocklistItem]:
168
"""
169
List all items in a text blocklist with pagination support.
170
171
Parameters:
172
- blocklist_name: Name of the blocklist to query
173
- top: Maximum number of items to return
174
- skip: Number of items to skip for pagination
175
- maxpagesize: Maximum items per page (passed via kwargs)
176
177
Returns:
178
ItemPaged[TextBlocklistItem]: Paginated list of blocklist items
179
180
Raises:
181
HttpResponseError: On listing failure or if blocklist doesn't exist
182
"""
183
184
def remove_blocklist_items(
185
self,
186
blocklist_name: str,
187
options: Union[RemoveTextBlocklistItemsOptions, dict, IO[bytes]],
188
**kwargs
189
) -> None:
190
"""
191
Remove items from a text blocklist (max 100 items per request).
192
193
Parameters:
194
- blocklist_name: Name of the target blocklist
195
- options: Options containing list of item IDs to remove
196
- content_type: Body parameter content-type (default: "application/json")
197
198
Returns:
199
None
200
201
Raises:
202
HttpResponseError: On removal failure or if blocklist doesn't exist
203
"""
204
```
205
206
**Usage Example:**
207
208
```python
209
from azure.ai.contentsafety import BlocklistClient
210
from azure.ai.contentsafety.models import (
211
AddOrUpdateTextBlocklistItemsOptions,
212
RemoveTextBlocklistItemsOptions,
213
TextBlocklistItem
214
)
215
from azure.core.credentials import AzureKeyCredential
216
217
client = BlocklistClient(
218
endpoint="https://your-resource.cognitiveservices.azure.com",
219
credential=AzureKeyCredential("your-api-key")
220
)
221
222
# Add items to blocklist
223
items_to_add = [
224
TextBlocklistItem(text="inappropriate-term-1"),
225
TextBlocklistItem(text="inappropriate-term-2"),
226
TextBlocklistItem(text="inappropriate-term-3")
227
]
228
229
add_request = AddOrUpdateTextBlocklistItemsOptions(blocklist_items=items_to_add)
230
result = client.add_or_update_blocklist_items("profanity-filter", add_request)
231
232
print(f"Added {len(result.blocklist_items)} items to blocklist")
233
for item in result.blocklist_items:
234
print(f" - ID: {item.blocklist_item_id}, Text: {item.text}")
235
236
# List all items in blocklist
237
all_items = client.list_text_blocklist_items("profanity-filter")
238
for item in all_items:
239
print(f"Item: {item.text} (ID: {item.blocklist_item_id})")
240
241
# Get specific item
242
if result.blocklist_items:
243
item_id = result.blocklist_items[0].blocklist_item_id
244
specific_item = client.get_text_blocklist_item("profanity-filter", item_id)
245
print(f"Retrieved item: {specific_item.text}")
246
247
# Remove specific items
248
items_to_remove = [item.blocklist_item_id for item in result.blocklist_items[:2]]
249
remove_request = RemoveTextBlocklistItemsOptions(blocklist_item_ids=items_to_remove)
250
client.remove_blocklist_items("profanity-filter", remove_request)
251
print(f"Removed {len(items_to_remove)} items from blocklist")
252
253
client.close()
254
```
255
256
## Data Models
257
258
```python { .api }
259
class TextBlocklist:
260
"""Text blocklist resource."""
261
def __init__(
262
self,
263
*,
264
blocklist_name: str,
265
description: Optional[str] = None
266
): ...
267
268
class TextBlocklistItem:
269
"""Individual blocklist item."""
270
def __init__(
271
self,
272
*,
273
text: str,
274
description: Optional[str] = None
275
): ...
276
277
# Read-only fields set by service
278
blocklist_item_id: Optional[str] # UUID assigned by service
279
280
class AddOrUpdateTextBlocklistItemsOptions:
281
"""Options for adding or updating blocklist items."""
282
def __init__(
283
self,
284
*,
285
blocklist_items: List[TextBlocklistItem]
286
): ...
287
288
class AddOrUpdateTextBlocklistItemsResult:
289
"""Result of adding or updating blocklist items."""
290
blocklist_items: List[TextBlocklistItem]
291
292
class RemoveTextBlocklistItemsOptions:
293
"""Options for removing blocklist items."""
294
def __init__(
295
self,
296
*,
297
blocklist_item_ids: List[str]
298
): ...
299
```
300
301
## Integration with Content Analysis
302
303
Blocklists integrate seamlessly with content analysis to provide comprehensive content moderation:
304
305
```python
306
from azure.ai.contentsafety import ContentSafetyClient
307
from azure.ai.contentsafety.models import AnalyzeTextOptions
308
309
content_client = ContentSafetyClient(
310
endpoint="https://your-resource.cognitiveservices.azure.com",
311
credential=AzureKeyCredential("your-api-key")
312
)
313
314
# Analyze text with custom blocklist integration
315
request = AnalyzeTextOptions(
316
text="Text content to analyze",
317
blocklist_names=["profanity-filter", "company-specific-terms"],
318
halt_on_blocklist_hit=True # Stop analysis if blocklist match found
319
)
320
321
result = content_client.analyze_text(request)
322
323
# Check for blocklist matches
324
if result.blocklists_match:
325
print("Blocklist matches found:")
326
for match in result.blocklists_match:
327
print(f" - Blocklist: {match.blocklist_name}")
328
print(f" Item: {match.blocklist_item_text}")
329
print(f" ID: {match.blocklist_item_id}")
330
331
content_client.close()
332
```
333
334
## Error Handling
335
336
Blocklist management operations can raise various Azure Core exceptions:
337
338
```python
339
from azure.core.exceptions import HttpResponseError, ResourceNotFoundError
340
341
try:
342
blocklist = client.get_text_blocklist("non-existent-list")
343
except ResourceNotFoundError:
344
print("Blocklist not found")
345
except HttpResponseError as e:
346
print(f"Request failed: {e.status_code} - {e.message}")
347
```
348
349
Common error scenarios:
350
- **404 Not Found**: Blocklist or item doesn't exist
351
- **409 Conflict**: Blocklist name already exists during creation
352
- **400 Bad Request**: Invalid item content or too many items in request
353
- **429 Too Many Requests**: Rate limit exceeded for blocklist operations