注意
本指南中的示例数据可能包含冒犯性内容。 建议用户自行决定。
默认的 AI 分类器足以满足大多数内容审核需求。 但不妨筛选特定于你的用例的项目。 允许将自定义术语添加到 AI 分类器中的阻止列表。 可以使用阻止列表来筛选想要在内容中标记的特定术语或短语。
先决条件
- Azure 订阅 - 免费创建订阅
- 拥有 Azure 订阅后,请在 Azure 门户中创建 Content Safety 资源 ,以获取密钥和终结点。 输入资源的唯一名称,选择订阅,并选择资源组、支持的区域(请参阅上市区域)和支持的定价层。 然后选择“创建”。
- 部署资源需要几分钟时间。 完成后,选择“转到资源”。 在左侧窗格中的“资源管理”下,选择“订阅密钥和终结点”。 终结点和任一密钥都用于调用 API。
- 已安装以下项之一:
- REST API 调用的 cURL。
- 已安装 Python 3.x
- 你的 Python 安装应包含 pip。 可以通过在命令行上运行
pip --version
来检查是否安装了 pip。 通过安装最新版本的 Python 获取 pip。
- 如果你使用的是 Python,则需要为 Python 安装 Azure AI Content Safety 客户端库。 在项目目录中运行
pip install azure-ai-contentsafety
命令。
- 已安装 .NET 运行时。
- 已安装 .NET Core SDK。
- 如果你使用的是 .NET,则需要为 .NET 安装 Azure AI Content Safety 客户端库。 在项目目录中运行
dotnet add package Azure.AI.ContentSafety --prerelease
命令。
创建环境变量
在此示例中,你将凭据写入运行应用程序的本地计算机上的环境变量。
若要为密钥和终结点设置环境变量,请打开控制台窗口,并按照操作系统和开发环境的说明进行操作。
- 若要设置
CONTENT_SAFETY_KEY
环境变量,请将 YOUR_CONTENT_SAFETY_KEY
替换为资源的其中一个密钥。
- 若要设置
CONTENT_SAFETY_ENDPOINT
环境变量,请将 YOUR_CONTENT_SAFETY_ENDPOINT
替换为资源的终结点。
setx CONTENT_SAFETY_KEY 'YOUR_CONTENT_SAFETY_KEY'
setx CONTENT_SAFETY_ENDPOINT 'YOUR_CONTENT_SAFETY_ENDPOINT'
添加环境变量后,可能需要重启任何正在运行的、将读取环境变量的程序(包括控制台窗口)。
export CONTENT_SAFETY_KEY='YOUR_CONTENT_SAFETY_KEY'
export CONTENT_SAFETY_ENDPOINT='YOUR_CONTENT_SAFETY_ENDPOINT'
添加环境变量后,请从控制台窗口运行 source ~/.bashrc
,使更改生效。
使用阻止列表分析文本
可以创建阻止列表以便于 Text API 一起使用。 以下步骤可帮助你入门。
创建或修改阻止列表
将下面的 cURL 命令复制到文本编辑器中,并进行以下更改:
- 将
<endpoint>
替换为你的终结点 URL。
- 将
<enter_your_key_here>
替换为你的密钥。
- 将
<your_list_name>
(在 URL 中)替换为列表的自定义名称。 此外,还要将 REST URL 的最后一个术语替换为同一名称。 允许的字符:0-9,a-Z,A-Z,- . _ ~
。
- (可选)将
"description"
字段的值替换为自定义描述。
curl --___location --request PATCH '<endpoint>/contentsafety/text/blocklists/<your_list_name>?api-version=2024-09-01' \
--header 'Ocp-Apim-Subscription-Key: <enter_your_key_here>' \
--header 'Content-Type: application/json' \
--data-raw '{
"description": "This is a violence list"
}'
响应代码应为 201
(创建新列表)或 200
(更新现有列表)。
创建新的 C# 控制台应用,并在喜好的编辑器或 IDE 中打开它。 粘贴到以下代码中。
string endpoint = Environment.GetEnvironmentVariable("CONTENT_SAFETY_ENDPOINT");
string key = Environment.GetEnvironmentVariable("CONTENT_SAFETY_KEY");
BlocklistClient blocklistClient = new BlocklistClient(new Uri(endpoint), new AzureKeyCredential(key));
var blocklistName = "<your_list_name>";
var blocklistDescription = "<description>";
var data = new
{
description = blocklistDescription,
};
var createResponse = blocklistClient.CreateOrUpdateTextBlocklist(blocklistName, RequestContent.Create(data));
if (createResponse.Status == 201)
{
Console.WriteLine("\nBlocklist {0} created.", blocklistName);
}
else if (createResponse.Status == 200)
{
Console.WriteLine("\nBlocklist {0} updated.", blocklistName);
}
- 将
<your_list_name>
替换为列表的自定义名称。 允许的字符:0-9, A-Z, a-z, - . _ ~
。
- (可选)将
<description>
替换为自定义描述。
- 运行代码。
创建 Java 应用程序,并在喜好的编辑器或 IDE 中打开它。 粘贴到以下代码中。
String endpoint = Configuration.getGlobalConfiguration().get("CONTENT_SAFETY_ENDPOINT");
String key = Configuration.getGlobalConfiguration().get("CONTENT_SAFETY_KEY");
BlocklistClient blocklistClient = new BlocklistClientBuilder()
.credential(new KeyCredential(key))
.endpoint(endpoint).buildClient();
String blocklistName = "<your_list_name>";
Map<String, String> description = new HashMap<>();
description.put("description", "<description>");
BinaryData resource = BinaryData.fromObject(description);
RequestOptions requestOptions = new RequestOptions();
Response<BinaryData> response =
blocklistClient.createOrUpdateTextBlocklistWithResponse(blocklistName, resource, requestOptions);
if (response.getStatusCode() == 201) {
System.out.println("\nBlocklist " + blocklistName + " created.");
} else if (response.getStatusCode() == 200) {
System.out.println("\nBlocklist " + blocklistName + " updated.");
}
- 将
<your_list_name>
替换为列表的自定义名称。 允许的字符:0-9, A-Z, a-z, - . _ ~
。
- (可选)将
<description>
替换为自定义描述。
- 运行代码。
创建新的 Python 脚本,并在喜好的编辑器或 IDE 中打开它。 粘贴到以下代码中。
import os
from azure.ai.contentsafety import BlocklistClient
from azure.core.credentials import AzureKeyCredential
from azure.ai.contentsafety.models import TextBlocklist
from azure.core.exceptions import HttpResponseError
key = os.environ["CONTENT_SAFETY_KEY"]
endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]
# Create a Blocklist client
client = BlocklistClient(endpoint, AzureKeyCredential(key))
blocklist_name = "<your_list_name>"
blocklist_description = "<description>"
try:
blocklist = client.create_or_update_text_blocklist(
blocklist_name=blocklist_name,
options=TextBlocklist(blocklist_name=blocklist_name, description=blocklist_description),
)
if blocklist:
print("\nBlocklist created or updated: ")
print(f"Name: {blocklist.blocklist_name}, Description: {blocklist.description}")
except HttpResponseError as e:
print("\nCreate or update text blocklist failed: ")
if e.error:
print(f"Error code: {e.error.code}")
print(f"Error message: {e.error.message}")
raise
print(e)
raise
- 将
<your_list_name>
替换为列表的自定义名称。 允许的字符:0-9, A-Z, a-z, - . _ ~
。
- 将
<description>
替换为自定义描述。
- 运行该脚本。
创建新的 JavaScript 脚本,并在喜好的编辑器或 IDE 中打开它。 粘贴到以下代码中。
const ContentSafetyClient = require("@azure-rest/ai-content-safety").default,
{ isUnexpected } = require("@azure-rest/ai-content-safety");
const { AzureKeyCredential } = require("@azure/core-auth");
// Load the .env file if it exists
require("dotenv").config();
const endpoint = process.env["CONTENT_SAFETY_ENDPOINT"] || "<endpoint>";
const key = process.env["CONTENT_SAFETY_API_KEY"] || "<key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function createOrUpdateTextBlocklist() {
const blocklistName = "<your_list_name>";
const blocklistDescription = "<description>";
const createOrUpdateTextBlocklistParameters = {
contentType: "application/merge-patch+json",
body: {
description: blocklistDescription,
},
};
const result = await client
.path("/text/blocklists/{blocklistName}", blocklistName)
.patch(createOrUpdateTextBlocklistParameters);
if (isUnexpected(result)) {
throw result;
}
console.log(
"Blocklist created or updated. Name: ",
result.body.blocklistName,
", Description: ",
result.body.description
);
}
(async () => {
await createOrUpdateTextBlocklist();
})().catch((err) => {
console.error("The sample encountered an error:", err);
});
- 将
<your_list_name>
替换为列表的自定义名称。 允许的字符:0-9, A-Z, a-z, - . _ ~
。
- (可选)将
<description>
替换为自定义描述。
- 运行该脚本。
向列表添加 blocklistItem
注意
所有列表中的术语总数最多不超过 10,000 个。 在一个请求中最多可以添加 100 个 blocklistItem。
将下面的 cURL 命令复制到文本编辑器中,并进行以下更改:
- 将
<endpoint>
替换为你的终结点 URL。
- 将
<enter_your_key_here>
替换为你的密钥。
- 将
<your_list_name>
(在 URL 中)替换为你在列表创建步骤中使用的名称。
- (可选)将
"description"
字段的值替换为自定义描述。
- 将
"text"
字段的值替换为要添加到阻止列表中的项。 blocklistItem 的最大长度为 128 个字符。
curl --___location --request POST '<endpoint>/contentsafety/text/blocklists/<your_list_name>:addOrUpdateBlocklistItems?api-version=2024-09-01' \
--header 'Ocp-Apim-Subscription-Key: <enter_your_key_here>' \
--header 'Content-Type: application/json' \
--data-raw '"blocklistItems": [{
"description": "string",
"text": "bleed"
}]'
提示
可以在一个 API 调用中添加多个 blocklistItem。 使请求主体成为数据组的 JSON 数组:
{
"blocklistItems": [
{
"description": "string",
"text": "bleed"
},
{
"description": "string",
"text": "blood"
}
]
}
响应代码应为 200
。
{
"blocklistItems:"[
{
"blocklistItemId": "string",
"description": "string",
"text": "bleed"
}
]
}
创建新的 C# 控制台应用,并在喜好的编辑器或 IDE 中打开它。 粘贴到以下代码中。
string endpoint = Environment.GetEnvironmentVariable("CONTENT_SAFETY_ENDPOINT");
string key = Environment.GetEnvironmentVariable("CONTENT_SAFETY_KEY");
BlocklistClient blocklistClient = new BlocklistClient(new Uri(endpoint), new AzureKeyCredential(key));
var blocklistName = "<your_list_name>";
string blocklistItemText1 = "<block_item_text_1>";
string blocklistItemText2 = "<block_item_text_2>";
var blocklistItems = new TextBlocklistItem[] { new TextBlocklistItem(blocklistItemText1), new TextBlocklistItem(blocklistItemText2) };
var addedBlocklistItems = blocklistClient.AddOrUpdateBlocklistItems(blocklistName, new AddOrUpdateTextBlocklistItemsOptions(blocklistItems));
if (addedBlocklistItems != null && addedBlocklistItems.Value != null)
{
Console.WriteLine("\nBlocklistItems added:");
foreach (var addedBlocklistItem in addedBlocklistItems.Value.BlocklistItems)
{
Console.WriteLine("BlocklistItemId: {0}, Text: {1}, Description: {2}", addedBlocklistItem.BlocklistItemId, addedBlocklistItem.Text, addedBlocklistItem.Description);
}
}
- 将
<your_list_name>
替换为列表创建步骤中使用的名称。
- 将
blocklistItemText1
和 blocklistItemText2
字段的值替换为要添加到阻止列表中的项。 blockItem 的最大长度为 128 个字符。
- (可选)向
blockItems
参数添加更多 BlockItem 字符串。
- 运行代码。
创建 Java 应用程序,并在喜好的编辑器或 IDE 中打开它。 粘贴到以下代码中。
String endpoint = Configuration.getGlobalConfiguration().get("CONTENT_SAFETY_ENDPOINT");
String key = Configuration.getGlobalConfiguration().get("CONTENT_SAFETY_KEY");
BlocklistClient blocklistClient = new BlocklistClientBuilder()
.credential(new KeyCredential(key))
.endpoint(endpoint).buildClient();
String blocklistName = "<your_list_name>";
String blockItemText1 = "<block_item_text_1>";
String blockItemText2 = "<block_item_text_2>";
List<TextBlocklistItem> blockItems = Arrays.asList(new TextBlocklistItem(blockItemText1).setDescription("Kill word"),
new TextBlocklistItem(blockItemText2).setDescription("Hate word"));
AddOrUpdateTextBlocklistItemsResult addedBlockItems = blocklistClient.addOrUpdateBlocklistItems(blocklistName,
new AddOrUpdateTextBlocklistItemsOptions(blockItems));
if (addedBlockItems != null && addedBlockItems.getBlocklistItems() != null) {
System.out.println("\nBlockItems added:");
for (TextBlocklistItem addedBlockItem : addedBlockItems.getBlocklistItems()) {
System.out.println("BlockItemId: " + addedBlockItem.getBlocklistItemId() + ", Text: " + addedBlockItem.getText() + ", Description: " + addedBlockItem.getDescription());
}
}
- 将
<your_list_name>
替换为列表创建步骤中使用的名称。
- 将
blockItemText1
和 blockItemText2
字段的值替换为要添加到阻止列表中的项。 blockItem 的最大长度为 128 个字符。
- (可选)向
blockItems
参数添加更多 BlockItem 字符串。
- 运行代码。
创建新的 Python 脚本,并在喜好的编辑器或 IDE 中打开它。 粘贴到以下代码中。
import os
from azure.ai.contentsafety import BlocklistClient
from azure.core.credentials import AzureKeyCredential
from azure.ai.contentsafety.models import (
AddOrUpdateTextBlocklistItemsOptions, TextBlocklistItem
)
from azure.core.exceptions import HttpResponseError
key = os.environ["CONTENT_SAFETY_KEY"]
endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]
# Create a Blocklist client
client = BlocklistClient(endpoint, AzureKeyCredential(key))
blocklist_name = "<your_list_name>"
blocklist_item_text_1 = "<block_item_text_1>"
blocklist_item_text_2 = "<block_item_text_2>"
blocklist_items = [TextBlocklistItem(text=blocklist_item_text_1), TextBlocklistItem(text=blocklist_item_text_2)]
try:
result = client.add_or_update_blocklist_items(
blocklist_name=blocklist_name, options=AddOrUpdateTextBlocklistItemsOptions(blocklist_items=blocklist_items)
for blocklist_item in result.blocklist_items:
print(
f"BlocklistItemId: {blocklist_item.blocklist_item_id}, Text: {blocklist_item.text}, Description: {blocklist_item.description}"
)
except HttpResponseError as e:
print("\nAdd blocklistItems failed: ")
if e.error:
print(f"Error code: {e.error.code}")
print(f"Error message: {e.error.message}")
raise
print(e)
raise
- 将
<your_list_name>
替换为列表创建步骤中使用的名称。
- 将
blocklist_item_text_1
和 blocklist_item_text_2
字段的值替换为要添加到阻止列表中的项。 blockItem 的最大长度为 128 个字符。
- (可选)向
block_items
参数添加更多 BlockItem 字符串。
- 运行该脚本。
const ContentSafetyClient = require("@azure-rest/ai-content-safety").default,
{ isUnexpected } = require("@azure-rest/ai-content-safety");
const { AzureKeyCredential } = require("@azure/core-auth");
// Load the .env file if it exists
require("dotenv").config();
const endpoint = process.env["CONTENT_SAFETY_ENDPOINT"] || "<endpoint>";
const key = process.env["CONTENT_SAFETY_API_KEY"] || "<key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function addBlocklistItems() {
const blocklistName = "<your_list_name>";
const blocklistItemText1 = "<block_item_text_1>";
const blocklistItemText2 = "<block_item_text_2>";
const addOrUpdateBlocklistItemsParameters = {
body: {
blocklistItems: [
{
description: "Test blocklist item 1",
text: blocklistItemText1,
},
{
description: "Test blocklist item 2",
text: blocklistItemText2,
},
],
},
};
const result = await client
.path("/text/blocklists/{blocklistName}:addOrUpdateBlocklistItems", blocklistName)
.post(addOrUpdateBlocklistItemsParameters);
if (isUnexpected(result)) {
throw result;
}
console.log("Blocklist items added: ");
if (result.body.blocklistItems) {
for (const blocklistItem of result.body.blocklistItems) {
console.log(
"BlocklistItemId: ",
blocklistItem.blocklistItemId,
", Text: ",
blocklistItem.text,
", Description: ",
blocklistItem.description
);
}
}
}
(async () => {
await addBlocklistItems();
})().catch((err) => {
console.error("The sample encountered an error:", err);
});
- 将
<your_list_name>
替换为列表创建步骤中使用的名称。
- 将
block_item_text_1
和 block_item_text_2
字段的值替换为要添加到阻止列表中的项。 blockItem 的最大长度为 128 个字符。
- (可选)向
blocklistItems
参数添加更多 BlockItem 字符串。
- 运行该脚本。
注意
添加或编辑 BlockItem 后,在其对文本分析生效之前会有一些延迟,通常不会超过五分钟。
使用阻止列表分析文本
将下面的 cURL 命令复制到文本编辑器中,并进行以下更改:
- 将
<endpoint>
替换为你的终结点 URL。
- 将
<enter_your_key_here>
替换为你的密钥。
- 将
<your_list_name>
替换为列表创建步骤中使用的名称。 "blocklistNames"
字段可以包含多个列表 ID 的数组。
- (可选)更改
"breakByBlocklists"
的值。 true
表明一旦匹配了阻止列表,将立即返回分析结果,不含模型输出。 false
将导致模型继续在默认类别中进行分析。
- (可选)将
"text"
字段的值更改为要分析的任何文本。
curl --___location --request POST '<endpoint>/contentsafety/text:analyze?api-version=2024-09-01&' \
--header 'Ocp-Apim-Subscription-Key: <enter_your_key_here>' \
--header 'Content-Type: application/json' \
--data-raw '{
"text": "I want to beat you till you bleed",
"categories": [
"Hate",
"Sexual",
"SelfHarm",
"Violence"
],
"blocklistNames":["<your_list_name>"],
"haltOnBlocklistHit": false,
"outputType": "FourSeverityLevels"
}'
JSON 响应将包含一个 "blocklistMatchResults"
,这表示与你的阻止列表的任何匹配项。 它报告在文本字符串中找到匹配项的位置。
{
"blocklistsMatch": [
{
"blocklistName": "string",
"blocklistItemId": "string",
"blocklistItemText": "bleed"
}
],
"categoriesAnalysis": [
{
"category": "Hate",
"severity": 0
}
]
}
创建新的 C# 控制台应用,并在喜好的编辑器或 IDE 中打开它。 粘贴到以下代码中。
string endpoint = Environment.GetEnvironmentVariable("CONTENT_SAFETY_ENDPOINT");
string key = Environment.GetEnvironmentVariable("CONTENT_SAFETY_KEY");
ContentSafetyClient client = new ContentSafetyClient(new Uri(endpoint), new AzureKeyCredential(key));
var blocklistName = "<your_list_name>";
// After you edit your blocklist, it usually takes effect in 5 minutes, please wait some time before analyzing with blocklist after editing.
var request = new AnalyzeTextOptions("<your_input_text>");
request.BlocklistNames.Add(blocklistName);
request.HaltOnBlocklistHit = true;
Response<AnalyzeTextResult> response;
try
{
response = client.AnalyzeText(request);
}
catch (RequestFailedException ex)
{
Console.WriteLine("Analyze text failed.\nStatus code: {0}, Error code: {1}, Error message: {2}", ex.Status, ex.ErrorCode, ex.Message);
throw;
}
if (response.Value.BlocklistsMatch != null)
{
Console.WriteLine("\nBlocklist match result:");
foreach (var matchResult in response.Value.BlocklistsMatch)
{
Console.WriteLine("BlocklistName: {0}, BlocklistItemId: {1}, BlocklistText: {2}, ", matchResult.BlocklistName, matchResult.BlocklistItemId, matchResult.BlocklistItemText);
}
}
- 将
<your_list_name>
替换为列表创建步骤中使用的名称。
- 将
request
输入文本替换为要分析的任何文本。
- 运行该脚本。
创建 Java 应用程序,并在喜好的编辑器或 IDE 中打开它。 粘贴到以下代码中。
String endpoint = Configuration.getGlobalConfiguration().get("CONTENT_SAFETY_ENDPOINT");
String key = Configuration.getGlobalConfiguration().get("CONTENT_SAFETY_KEY");
ContentSafetyClient contentSafetyClient = new ContentSafetyClientBuilder()
.credential(new KeyCredential(key))
.endpoint(endpoint).buildClient();
String blocklistName = "<your_list_name>";
AnalyzeTextOptions request = new AnalyzeTextOptions("<sample_text>");
request.setBlocklistNames(Arrays.asList(blocklistName));
request.setHaltOnBlocklistHit(true);
AnalyzeTextResult analyzeTextResult;
try {
analyzeTextResult = contentSafetyClient.analyzeText(request);
} catch (HttpResponseException ex) {
System.out.println("Analyze text failed.\nStatus code: " + ex.getResponse().getStatusCode() + ", Error message: " + ex.getMessage());
throw ex;
}
if (analyzeTextResult.getBlocklistsMatch() != null) {
System.out.println("\nBlocklist match result:");
for (TextBlocklistMatch matchResult : analyzeTextResult.getBlocklistsMatch()) {
System.out.println("BlocklistName: " + matchResult.getBlocklistName() + ", BlockItemId: " + matchResult.getBlocklistItemId() + ", BlockItemText: " + matchResult.getBlocklistItemText());
}
}
- 将
<your_list_name>
替换为列表创建步骤中使用的名称。
- 将
request
输入文本替换为要分析的任何文本。
- 运行该脚本。
创建新的 Python 脚本,并在喜好的编辑器或 IDE 中打开它。 粘贴到以下代码中。
import os
from azure.ai.contentsafety import ContentSafetyClient
from azure.core.credentials import AzureKeyCredential
from azure.ai.contentsafety.models import AnalyzeTextOptions
from azure.core.exceptions import HttpResponseError
key = os.environ["CONTENT_SAFETY_KEY"]
endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]
# Create a Content Safety client
client = ContentSafetyClient(endpoint, AzureKeyCredential(key))
blocklist_name = "<your_list_name>"
input_text = "<your_input_text>"
try:
# After you edit your blocklist, it usually takes effect in 5 minutes, please wait some time before analyzing
# with blocklist after editing.
analysis_result = client.analyze_text(
AnalyzeTextOptions(text=input_text, blocklist_names=[blocklist_name], halt_on_blocklist_hit=False)
)
if analysis_result and analysis_result.blocklists_match:
print("\nBlocklist match results: ")
for match_result in analysis_result.blocklists_match:
print(
f"BlocklistName: {match_result.blocklist_name}, BlocklistItemId: {match_result.blocklist_item_id}, "
f"BlocklistItemText: {match_result.blocklist_item_text}"
)
except HttpResponseError as e:
print("\nAnalyze text failed: ")
if e.error:
print(f"Error code: {e.error.code}")
print(f"Error message: {e.error.message}")
raise
print(e)
raise
- 将
<your_list_name>
替换为列表创建步骤中使用的名称。
- 将
input_text
变量替换为要分析的任何文本。
- 运行该脚本。
const ContentSafetyClient = require("@azure-rest/ai-content-safety").default,
{ isUnexpected } = require("@azure-rest/ai-content-safety");
const { AzureKeyCredential } = require("@azure/core-auth");
// Load the .env file if it exists
require("dotenv").config();
const endpoint = process.env["CONTENT_SAFETY_ENDPOINT"] || "<endpoint>";
const key = process.env["CONTENT_SAFETY_API_KEY"] || "<key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function analyzeTextWithBlocklists() {
const blocklistName = "<your_list_name>";
const inputText = "<your_input_text>";
const analyzeTextParameters = {
body: {
text: inputText,
blocklistNames: [blocklistName],
haltOnBlocklistHit: false,
},
};
const result = await client.path("/text:analyze").post(analyzeTextParameters);
if (isUnexpected(result)) {
throw result;
}
console.log("Blocklist match results: ");
if (result.body.blocklistsMatch) {
for (const blocklistMatchResult of result.body.blocklistsMatch) {
console.log(
"BlocklistName: ",
blocklistMatchResult.blocklistName,
", BlocklistItemId: ",
blocklistMatchResult.blocklistItemId,
", BlocklistItemText: ",
blocklistMatchResult.blocklistItemText
);
}
}
}
(async () => {
await analyzeTextWithBlocklists();
})().catch((err) => {
console.error("The sample encountered an error:", err);
});
- 将
<your_list_name>
替换为列表创建步骤中使用的名称。
- 将
inputText
变量替换为要分析的任何文本。
- 运行该脚本。
其他阻止列表操作
本节包含可帮助你管理和使用阻止列表功能的更多操作。
列出列表中的所有 blocklistItem
将下面的 cURL 命令复制到文本编辑器中,并进行以下更改:
- 将
<endpoint>
替换为你的终结点 URL。
- 将
<enter_your_key_here>
替换为你的密钥。
- 将
<your_list_name>
(在请求 URL 中)替换为你在列表创建步骤中使用的名称。
curl --___location --request GET '<endpoint>/contentsafety/text/blocklists/<your_list_name>/blocklistItems?api-version=2024-09-01' \
--header 'Ocp-Apim-Subscription-Key: <enter_your_key_here>' \
--header 'Content-Type: application/json'
状态代码应为 200
,响应正文应如下所示:
{
"values": [
{
"blocklistItemId": "string",
"description": "string",
"text": "bleed",
}
]
}
创建新的 C# 控制台应用,并在喜好的编辑器或 IDE 中打开它。 粘贴到以下代码中。
string endpoint = Environment.GetEnvironmentVariable("CONTENT_SAFETY_ENDPOINT");
string key = Environment.GetEnvironmentVariable("CONTENT_SAFETY_KEY");
BlocklistClient blocklistClient = new BlocklistClient(new Uri(endpoint), new AzureKeyCredential(key));
var blocklistName = "<your_list_name>";
var allBlocklistitems = blocklistClient.GetTextBlocklistItems(blocklistName);
Console.WriteLine("\nList BlocklistItems:");
foreach (var blocklistItem in allBlocklistitems)
{
Console.WriteLine("BlocklistItemId: {0}, Text: {1}, Description: {2}", blocklistItem.BlocklistItemId, blocklistItem.Text, blocklistItem.Description);
}
- 将
<your_list_name>
替换为列表创建步骤中使用的名称。
- 运行该脚本。
创建 Java 应用程序,并在喜好的编辑器或 IDE 中打开它。 粘贴到以下代码中。
String endpoint = Configuration.getGlobalConfiguration().get("CONTENT_SAFETY_ENDPOINT");
String key = Configuration.getGlobalConfiguration().get("CONTENT_SAFETY_KEY");
BlocklistClient blocklistClient = new BlocklistClientBuilder()
.credential(new KeyCredential(key))
.endpoint(endpoint).buildClient();
String blocklistName = "<your_list_name>";
PagedIterable<TextBlocklistItem> allBlockitems = blocklistClient.listTextBlocklistItems(blocklistName);
System.out.println("\nList BlockItems:");
for (TextBlocklistItem blocklistItem : allBlockitems) {
System.out.println("BlockItemId: " + blocklistItem.getBlocklistItemId() + ", Text: " + blocklistItem.getText() + ", Description: " + blocklistItem.getDescription());
}
- 将
<your_list_name>
替换为列表创建步骤中使用的名称。
- 运行该脚本。
创建新的 Python 脚本,并在喜好的编辑器或 IDE 中打开它。 粘贴到以下代码中。
import os
from azure.ai.contentsafety import BlocklistClient
from azure.core.credentials import AzureKeyCredential
from azure.core.exceptions import HttpResponseError
key = os.environ["CONTENT_SAFETY_KEY"]
endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]
# Create a Blocklist client
client = BlocklistClient(endpoint, AzureKeyCredential(key))
blocklist_name = "<your_list_name>"
try:
blocklist_items = client.list_text_blocklist_items(blocklist_name=blocklist_name)
if blocklist_items:
print("\nList blocklist items: ")
for blocklist_item in blocklist_items:
print(
f"BlocklistItemId: {blocklist_item.blocklist_item_id}, Text: {blocklist_item.text}, "
f"Description: {blocklist_item.description}"
)
except HttpResponseError as e:
print("\nList blocklist items failed: ")
if e.error:
print(f"Error code: {e.error.code}")
print(f"Error message: {e.error.message}")
raise
print(e)
raise
- 将
<your_list_name>
替换为列表创建步骤中使用的名称。
- 运行该脚本。
const ContentSafetyClient = require("@azure-rest/ai-content-safety").default,
{ isUnexpected } = require("@azure-rest/ai-content-safety");
const { AzureKeyCredential } = require("@azure/core-auth");
// Load the .env file if it exists
require("dotenv").config();
const endpoint = process.env["CONTENT_SAFETY_ENDPOINT"] || "<endpoint>";
const key = process.env["CONTENT_SAFETY_API_KEY"] || "<key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function listBlocklistItems() {
const blocklistName = "<your_list_name>";
const result = await client
.path("/text/blocklists/{blocklistName}/blocklistItems", blocklistName)
.get();
if (isUnexpected(result)) {
throw result;
}
console.log("List blocklist items: ");
if (result.body.value) {
for (const blocklistItem of result.body.value) {
console.log(
"BlocklistItemId: ",
blocklistItem.blocklistItemId,
", Text: ",
blocklistItem.text,
", Description: ",
blocklistItem.description
);
}
}
}
(async () => {
await listBlocklistItems();
})().catch((err) => {
console.error("The sample encountered an error:", err);
});
- 将
<your_list_name>
替换为列表创建步骤中使用的名称。
- 运行该脚本。
列出所有阻止列表
将下面的 cURL 命令复制到文本编辑器中,并进行以下更改:
- 将
<endpoint>
替换为你的终结点 URL。
- 将
<enter_your_key_here>
替换为你的密钥。
curl --___location --request GET '<endpoint>/contentsafety/text/blocklists?api-version=2024-09-01' \
--header 'Ocp-Apim-Subscription-Key: <enter_your_key_here>' \
--header 'Content-Type: application/json'
状态代码应为 200
。 JSON 响应如下所示:
"value": [
{
"blocklistName": "string",
"description": "string"
}
]
创建新的 C# 控制台应用,并在喜好的编辑器或 IDE 中打开它。 粘贴到以下代码中。
string endpoint = Environment.GetEnvironmentVariable("CONTENT_SAFETY_ENDPOINT");
string key = Environment.GetEnvironmentVariable("CONTENT_SAFETY_KEY");
BlocklistClient blocklistClient = new BlocklistClient(new Uri(endpoint), new AzureKeyCredential(key));
var blocklists = blocklistClient.GetTextBlocklists();
Console.WriteLine("\nList blocklists:");
foreach (var blocklist in blocklists)
{
Console.WriteLine("BlocklistName: {0}, Description: {1}", blocklist.Name, blocklist.Description);
}
运行该脚本。
创建 Java 应用程序,并在喜好的编辑器或 IDE 中打开它。 粘贴到以下代码中。
String endpoint = Configuration.getGlobalConfiguration().get("CONTENT_SAFETY_ENDPOINT");
String key = Configuration.getGlobalConfiguration().get("CONTENT_SAFETY_KEY");
BlocklistClient blocklistClient = new BlocklistClientBuilder()
.credential(new KeyCredential(key))
.endpoint(endpoint).buildClient();
PagedIterable<TextBlocklist> allTextBlocklists = blocklistClient.listTextBlocklists();
System.out.println("\nList Blocklist:");
for (TextBlocklist blocklist : allTextBlocklists) {
System.out.println("Blocklist: " + blocklist.getName() + ", Description: " + blocklist.getDescription());
}
运行该脚本。
创建新的 Python 脚本,并在喜好的编辑器或 IDE 中打开它。 粘贴到以下代码中。
import os
from azure.ai.contentsafety import BlocklistClient
from azure.core.credentials import AzureKeyCredential
from azure.core.exceptions import HttpResponseError
key = os.environ["CONTENT_SAFETY_KEY"]
endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]
# Create a Blocklist client
client = BlocklistClient(endpoint, AzureKeyCredential(key))
try:
blocklists = client.list_text_blocklists()
if blocklists:
print("\nList blocklists: ")
for blocklist in blocklists:
print(f"Name: {blocklist.blocklist_name}, Description: {blocklist.description}")
except HttpResponseError as e:
print("\nList text blocklists failed: ")
if e.error:
print(f"Error code: {e.error.code}")
print(f"Error message: {e.error.message}")
raise
print(e)
raise
运行该脚本。
const ContentSafetyClient = require("@azure-rest/ai-content-safety").default,
{ isUnexpected } = require("@azure-rest/ai-content-safety");
const { AzureKeyCredential } = require("@azure/core-auth");
// Load the .env file if it exists
require("dotenv").config();
const endpoint = process.env["CONTENT_SAFETY_ENDPOINT"] || "<endpoint>";
const key = process.env["CONTENT_SAFETY_API_KEY"] || "<key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function listTextBlocklists() {
const result = await client.path("/text/blocklists").get();
if (isUnexpected(result)) {
throw result;
}
console.log("List blocklists: ");
if (result.body.value) {
for (const blocklist of result.body.value) {
console.log(
"BlocklistName: ",
blocklist.blocklistName,
", Description: ",
blocklist.description
);
}
}
}
(async () => {
await listTextBlocklists();
})().catch((err) => {
console.error("The sample encountered an error:", err);
});
运行该脚本。
按 blocklistName 获取阻止列表
将下面的 cURL 命令复制到文本编辑器中,并进行以下更改:
- 将
<endpoint>
替换为你的终结点 URL。
- 将
<enter_your_key_here>
替换为你的密钥。
- 将
<your_list_name>
(在请求 URL 中)替换为你在列表创建步骤中使用的名称。
cURL --___location '<endpoint>contentsafety/text/blocklists/<your_list_name>?api-version=2024-09-01' \
--header 'Ocp-Apim-Subscription-Key: <enter_your_key_here>' \
--data ''
状态代码应为 200
。 JSON 响应如下所示:
{
"blocklistName": "string",
"description": "string"
}
创建新的 C# 控制台应用,并在喜好的编辑器或 IDE 中打开它。 粘贴到以下代码中。
string endpoint = Environment.GetEnvironmentVariable("CONTENT_SAFETY_ENDPOINT");
string key = Environment.GetEnvironmentVariable("CONTENT_SAFETY_KEY");
BlocklistClient blocklistClient = new BlocklistClient(new Uri(endpoint), new AzureKeyCredential(key));
var blocklistName = "<your_list_name>";
var getBlocklist = blocklistClient.GetTextBlocklist(blocklistName);
if (getBlocklist != null && getBlocklist.Value != null)
{
Console.WriteLine("\nGet blocklist:");
Console.WriteLine("BlocklistName: {0}, Description: {1}", getBlocklist.Value.Name, getBlocklist.Value.Description);
}
- 将
<your_list_name>
替换为列表创建步骤中使用的名称。
- 运行该脚本。
创建 Java 应用程序,并在喜好的编辑器或 IDE 中打开它。 粘贴到以下代码中。
String endpoint = Configuration.getGlobalConfiguration().get("CONTENT_SAFETY_ENDPOINT");
String key = Configuration.getGlobalConfiguration().get("CONTENT_SAFETY_KEY");
BlocklistClient blocklistClient = new BlocklistClientBuilder()
.credential(new KeyCredential(key))
.endpoint(endpoint).buildClient();
String blocklistName = "<your_list_name>";
TextBlocklist getBlocklist = blocklistClient.getTextBlocklist(blocklistName);
if (getBlocklist != null) {
System.out.println("\nGet blocklist:");
System.out.println("BlocklistName: " + getBlocklist.getName() + ", Description: " + getBlocklist.getDescription());
}
- 将
<your_list_name>
替换为列表创建步骤中使用的名称。
- 运行该脚本。
创建新的 Python 脚本,并在喜好的编辑器或 IDE 中打开它。 粘贴到以下代码中。
import os
from azure.ai.contentsafety import BlocklistClient
from azure.core.credentials import AzureKeyCredential
from azure.core.exceptions import HttpResponseError
key = os.environ["CONTENT_SAFETY_KEY"]
endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]
# Create a Blocklist client
client = BlocklistClient(endpoint, AzureKeyCredential(key))
blocklist_name = "<your_list_name>"
try:
blocklist = client.get_text_blocklist(blocklist_name=blocklist_name)
if blocklist:
print("\nGet blocklist: ")
print(f"Name: {blocklist.blocklist_name}, Description: {blocklist.description}")
except HttpResponseError as e:
print("\nGet text blocklist failed: ")
if e.error:
print(f"Error code: {e.error.code}")
print(f"Error message: {e.error.message}")
raise
print(e)
raise
- 将
<your_list_name>
替换为列表创建步骤中使用的名称。
- 运行该脚本。
const ContentSafetyClient = require("@azure-rest/ai-content-safety").default,
{ isUnexpected } = require("@azure-rest/ai-content-safety");
const { AzureKeyCredential } = require("@azure/core-auth");
// Load the .env file if it exists
require("dotenv").config();
const endpoint = process.env["CONTENT_SAFETY_ENDPOINT"] || "<endpoint>";
const key = process.env["CONTENT_SAFETY_API_KEY"] || "<key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function getTextBlocklist() {
const blocklistName = "<your_list_name>";
const result = await client.path("/text/blocklists/{blocklistName}", blocklistName).get();
if (isUnexpected(result)) {
throw result;
}
console.log("Get blocklist: ");
console.log("Name: ", result.body.blocklistName, ", Description: ", result.body.description);
}
(async () => {
await getTextBlocklist();
})().catch((err) => {
console.error("The sample encountered an error:", err);
});
- 将
<your_list_name>
替换为列表创建步骤中使用的名称。
- 运行该脚本。
按 blocklistName 和 blocklistItemId 获取 blocklistItem
将下面的 cURL 命令复制到文本编辑器中,并进行以下更改:
- 将
<endpoint>
替换为你的终结点 URL。
- 将
<enter_your_key_here>
替换为你的密钥。
- 将
<your_list_name>
(在请求 URL 中)替换为你在列表创建步骤中使用的名称。
- 将
<your_item_id>
替换为 blocklistItem 的 ID 值。 这是来自添加 blocklistItem 或获取所有 blocklistItem API 调用的 "blocklistItemId"
字段的值。
cURL --___location '<endpoint>contentsafety/text/blocklists/<your_list_name>/blocklistItems/<your_item_id>?api-version=2024-09-01' \
--header 'Ocp-Apim-Subscription-Key: <enter_your_key_here>' \
--data ''
状态代码应为 200
。 JSON 响应如下所示:
{
"blocklistItemId": "string",
"description": "string",
"text": "string"
}
创建新的 C# 控制台应用,并在喜好的编辑器或 IDE 中打开它。 粘贴到以下代码中。
string endpoint = Environment.GetEnvironmentVariable("CONTENT_SAFETY_ENDPOINT");
string key = Environment.GetEnvironmentVariable("CONTENT_SAFETY_KEY");
BlocklistClient blocklistClient = new BlocklistClient(new Uri(endpoint), new AzureKeyCredential(key));
var blocklistName = "<your_list_name>";
var getBlocklistItemId = "<your_block_item_id>";
var getBlocklistItem = blocklistClient.GetTextBlocklistItem(blocklistName, getBlocklistItemId);
Console.WriteLine("\nGet BlocklistItem:");
Console.WriteLine("BlocklistItemId: {0}, Text: {1}, Description: {2}", getBlocklistItem.Value.BlocklistItemId, getBlocklistItem.Value.Text, getBlocklistItem.Value.Description);
- 将
<your_list_name>
替换为列表创建步骤中使用的名称。
- 将
<your_block_item_id>
替换为以前添加的项的 ID。
- 运行该脚本。
创建 Java 应用程序,并在喜好的编辑器或 IDE 中打开它。 粘贴到以下代码中。
String endpoint = Configuration.getGlobalConfiguration().get("CONTENT_SAFETY_ENDPOINT");
String key = Configuration.getGlobalConfiguration().get("CONTENT_SAFETY_KEY");
BlocklistClient blocklistClient = new BlocklistClientBuilder()
.credential(new KeyCredential(key))
.endpoint(endpoint).buildClient();
String blocklistName = "<your_list_name>";
String getBlockItemId = "<your_block_item_id>";
TextBlocklistItem getBlockItem = blocklistClient.getTextBlocklistItem(blocklistName, getBlockItemId);
System.out.println("\nGet BlockItem:");
System.out.println("BlockItemId: " + getBlockItem.getBlocklistItemId() + ", Text: " + getBlockItem.getText() + ", Description: " + getBlockItem.getDescription());
- 将
<your_list_name>
替换为列表创建步骤中使用的名称。
- 将
<your_block_item_id>
替换为以前添加的项的 ID。
- 运行该脚本。
创建新的 Python 脚本,并在喜好的编辑器或 IDE 中打开它。 粘贴到以下代码中。
import os
from azure.ai.contentsafety import BlocklistClient
from azure.core.credentials import AzureKeyCredential
from azure.ai.contentsafety.models import TextBlocklistItem, AddOrUpdateTextBlocklistItemsOptions
from azure.core.exceptions import HttpResponseError
key = os.environ["CONTENT_SAFETY_KEY"]
endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]
# Create a Blocklist client
client = BlocklistClient(endpoint, AzureKeyCredential(key))
blocklist_name = "<your_list_name>"
blocklist_item_text_1 = "<block_item_text>"
try:
# Add a blocklistItem
add_result = client.add_or_update_blocklist_items(
blocklist_name=blocklist_name,
options=AddOrUpdateTextBlocklistItemsOptions(blocklist_items=[TextBlocklistItem(text=blocklist_item_text_1)]),
)
if not add_result or not add_result.blocklist_items or len(add_result.blocklist_items) <= 0:
raise RuntimeError("BlocklistItem not created.")
blocklist_item_id = add_result.blocklist_items[0].blocklist_item_id
# Get this blocklistItem by blocklistItemId
blocklist_item = client.get_text_blocklist_item(blocklist_name=blocklist_name, blocklist_item_id=blocklist_item_id)
print("\nGet blocklistItem: ")
print(
f"BlocklistItemId: {blocklist_item.blocklist_item_id}, Text: {blocklist_item.text}, Description: {blocklist_item.description}"
)
except HttpResponseError as e:
print("\nGet blocklist item failed: ")
if e.error:
print(f"Error code: {e.error.code}")
print(f"Error message: {e.error.message}")
raise
print(e)
raise
- 将
<your_list_name>
替换为列表创建步骤中使用的名称。
- 将
<block_item_text>
替换为阻止项文本。
- 运行该脚本。
const ContentSafetyClient = require("@azure-rest/ai-content-safety").default,
{ isUnexpected } = require("@azure-rest/ai-content-safety");
const { AzureKeyCredential } = require("@azure/core-auth");
// Load the .env file if it exists
require("dotenv").config();
const endpoint = process.env["CONTENT_SAFETY_ENDPOINT"] || "<endpoint>";
const key = process.env["CONTENT_SAFETY_API_KEY"] || "<key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function getBlocklistItem() {
const blocklistName = "<your_list_name>";
const blocklistItemId = "<your_block_item_id>";
// Get this blocklistItem by blocklistItemId
const blocklistItem = await client
.path(
"/text/blocklists/{blocklistName}/blocklistItems/{blocklistItemId}",
blocklistName,
blocklistItemId
)
.get();
if (isUnexpected(blocklistItem)) {
throw blocklistItem;
}
console.log("Get blocklistitem: ");
console.log(
"BlocklistItemId: ",
blocklistItem.body.blocklistItemId,
", Text: ",
blocklistItem.body.text,
", Description: ",
blocklistItem.body.description
);
}
(async () => {
await getBlocklistItem();
})().catch((err) => {
console.error("The sample encountered an error:", err);
});
- 将
<your_list_name>
替换为列表创建步骤中使用的名称。
- 将
<your_block_item_id>
替换为要获取的项的 ID。
- 运行该脚本。
从阻止列表中移除 blocklistItem。
注意
在你删除某一个项后,关于这个项的文本分析不会立即生效,而是有一定的延迟,通常不会超过五分钟。
将下面的 cURL 命令复制到文本编辑器中,并进行以下更改:
- 将
<endpoint>
替换为你的终结点 URL。
- 将
<enter_your_key_here>
替换为你的密钥。
- 将
<your_list_name>
(在请求 URL 中)替换为你在列表创建步骤中使用的名称。
- 将
<item_id>
替换为 blocklistItem 的 ID 值。 这是来自添加 blocklistItem 或获取所有 blocklistItem API 调用的 "blocklistItemId"
字段的值。
curl --___location --request POST '<endpoint>/contentsafety/text/blocklists/<your_list_name>:removeBlocklistItems?api-version=2024-09-01' \
--header 'Ocp-Apim-Subscription-Key: <enter_your_key_here>' \
--header 'Content-Type: application/json'
--data-raw '"blocklistItemIds":[
"<item_id>"
]'
提示
可以在一个 API 调用中删除多个 blocklistItem。 使请求主体成为 blocklistItemId
值的数组。
响应代码应为 204
。
创建新的 C# 控制台应用,并在喜好的编辑器或 IDE 中打开它。 粘贴到以下代码中。
string endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"];
string key = os.environ["CONTENT_SAFETY_KEY"];
BlocklistClient blocklistClient = new BlocklistClient(new Uri(endpoint), new AzureKeyCredential(key));
var blocklistName = "<your_list_name>";
var removeBlocklistItemId = "<your_block_item_id>";
var removeBlocklistItemIds = new List<string> { removeBlocklistItemId };
var removeResult = blocklistClient.RemoveBlocklistItems(blocklistName, new RemoveTextBlocklistItemsOptions(removeBlocklistItemIds));
if (removeResult != null && removeResult.Status == 204)
{
Console.WriteLine("\nBlocklistItem removed: {0}.", removeBlocklistItemId);
}
- 将
<your_list_name>
替换为列表创建步骤中使用的名称。
- 将
<your_block_item_id>
替换为以前添加的项的 ID。
- 运行该脚本。
创建 Java 应用程序,并在喜好的编辑器或 IDE 中打开它。 粘贴到以下代码中。
String endpoint = Configuration.getGlobalConfiguration().get("CONTENT_SAFETY_ENDPOINT");
String key = Configuration.getGlobalConfiguration().get("CONTENT_SAFETY_KEY");
BlocklistClient blocklistClient = new BlocklistClientBuilder()
.credential(new KeyCredential(key))
.endpoint(endpoint).buildClient();
String blocklistName = "<your_list_name>";
String removeBlockItemId = "<your_block_item_id>";
List<String> removeBlockItemIds = new ArrayList<>();
removeBlockItemIds.add(removeBlockItemId);
blocklistClient.removeBlocklistItems(blocklistName, new RemoveTextBlocklistItemsOptions(removeBlockItemIds));
- 将
<your_list_name>
替换为列表创建步骤中使用的名称。
- 将
<your_block_item_id>
替换为以前添加的项的 ID。
- 运行该脚本。
创建新的 Python 脚本,并在喜好的编辑器或 IDE 中打开它。 粘贴到以下代码中。
import os
from azure.ai.contentsafety import BlocklistClient
from azure.core.credentials import AzureKeyCredential
from azure.ai.contentsafety.models import (
TextBlocklistItem,
AddOrUpdateTextBlocklistItemsOptions,
RemoveTextBlocklistItemsOptions,
)
from azure.core.exceptions import HttpResponseError
key = os.environ["CONTENT_SAFETY_KEY"]
endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]
# Create a Blocklist client
client = BlocklistClient(endpoint, AzureKeyCredential(key))
blocklist_name = "<your_list_name>"
blocklist_item_text_1 = "<block_item_text>"
try:
# Add a blocklistItem
add_result = client.add_or_update_blocklist_items(
blocklist_name=blocklist_name,
options=AddOrUpdateTextBlocklistItemsOptions(blocklist_items=[TextBlocklistItem(text=blocklist_item_text_1)]),
)
if not add_result or not add_result.blocklist_items or len(add_result.blocklist_items) <= 0:
raise RuntimeError("BlocklistItem not created.")
blocklist_item_id = add_result.blocklist_items[0].blocklist_item_id
# Remove this blocklistItem by blocklistItemId
client.remove_blocklist_items(
blocklist_name=blocklist_name, options=RemoveTextBlocklistItemsOptions(blocklist_item_ids=[blocklist_item_id])
)
print(f"\nRemoved blocklistItem: {add_result.blocklist_items[0].blocklist_item_id}")
except HttpResponseError as e:
print("\nRemove blocklist item failed: ")
if e.error:
print(f"Error code: {e.error.code}")
print(f"Error message: {e.error.message}")
raise
print(e)
raise
- 将
<your_list_name>
替换为列表创建步骤中使用的名称。
将 <block_item_text>
替换为阻止项文本。
- 运行该脚本。
const ContentSafetyClient = require("@azure-rest/ai-content-safety").default,
{ isUnexpected } = require("@azure-rest/ai-content-safety");
const { AzureKeyCredential } = require("@azure/core-auth");
// Load the .env file if it exists
require("dotenv").config();
const endpoint = process.env["CONTENT_SAFETY_ENDPOINT"] || "<endpoint>";
const key = process.env["CONTENT_SAFETY_API_KEY"] || "<key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
// Sample: Remove blocklistItems from a blocklist
async function removeBlocklistItems() {
const blocklistName = "<your_list_name>";
const blocklistItemId = "<your_block_item_id>";
// Remove this blocklistItem by blocklistItemId
const removeBlocklistItemsParameters = {
body: {
blocklistItemIds: [blocklistItemId],
},
};
const removeBlocklistItem = await client
.path("/text/blocklists/{blocklistName}:removeBlocklistItems", blocklistName)
.post(removeBlocklistItemsParameters);
if (isUnexpected(removeBlocklistItem)) {
throw removeBlocklistItem;
}
console.log("Removed blocklistItem: ", blocklistItemText);
}
(async () => {
await removeBlocklistItems();
})().catch((err) => {
console.error("The sample encountered an error:", err);
});
- 将
<your_list_name>
替换为列表创建步骤中使用的名称。
将 <your_block_item_id
替换为要删除的项的 ID。
- 运行该脚本。
删除列表及其所有内容
注意
在你删除某一个列表后,关于这个列表的文本分析不会立即生效,而是有一定的延迟,通常不会超过五分钟。
将下面的 cURL 命令复制到文本编辑器中,并进行以下更改:
- 将
<endpoint>
替换为你的终结点 URL。
- 将
<enter_your_key_here>
替换为你的密钥。
- 将
<your_list_name>
(在请求 URL 中)替换为你在列表创建步骤中使用的名称。
curl --___location --request DELETE '<endpoint>/contentsafety/text/blocklists/<your_list_name>?api-version=2024-09-01' \
--header 'Ocp-Apim-Subscription-Key: <enter_your_key_here>' \
--header 'Content-Type: application/json' \
响应代码应为 204
。
创建新的 C# 控制台应用,并在喜好的编辑器或 IDE 中打开它。 粘贴到以下代码中。
string endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"];
string key = os.environ["CONTENT_SAFETY_KEY"];
BlocklistClient blocklistClient = new BlocklistClient(new Uri(endpoint), new AzureKeyCredential(key));
var blocklistName = "<your_list_name>";
var deleteResult = blocklistClient.DeleteTextBlocklist(blocklistName);
if (deleteResult != null && deleteResult.Status == 204)
{
Console.WriteLine("\nDeleted blocklist.");
}
- 将
<your_list_name>
(在请求 URL 中)替换为你在列表创建步骤中使用的名称。
- 运行该脚本。
创建 Java 应用程序,并在喜好的编辑器或 IDE 中打开它。 粘贴到以下代码中。
String endpoint = Configuration.getGlobalConfiguration().get("CONTENT_SAFETY_ENDPOINT");
String key = Configuration.getGlobalConfiguration().get("CONTENT_SAFETY_KEY");
BlocklistClient blocklistClient = new BlocklistClientBuilder()
.credential(new KeyCredential(key))
.endpoint(endpoint).buildClient();
String blocklistName = "<your_list_name>";
blocklistClient.deleteTextBlocklist(blocklistName);
- 将
<your_list_name>
(在请求 URL 中)替换为你在列表创建步骤中使用的名称。
- 运行该脚本。
创建新的 Python 脚本,并在喜好的编辑器或 IDE 中打开它。 粘贴到以下代码中。
import os
from azure.ai.contentsafety import BlocklistClient
from azure.core.credentials import AzureKeyCredential
from azure.core.exceptions import HttpResponseError
key = os.environ["CONTENT_SAFETY_KEY"]
endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]
# Create a Blocklist client
client = BlocklistClient(endpoint, AzureKeyCredential(key))
blocklist_name = "<your_list_name>"
try:
client.delete_text_blocklist(blocklist_name=blocklist_name)
print(f"\nDeleted blocklist: {blocklist_name}")
except HttpResponseError as e:
print("\nDelete blocklist failed:")
if e.error:
print(f"Error code: {e.error.code}")
print(f"Error message: {e.error.message}")
raise
print(e)
raise
- 将
<your_list_name>
(在请求 URL 中)替换为你在列表创建步骤中使用的名称。
- 运行该脚本。
const ContentSafetyClient = require("@azure-rest/ai-content-safety").default,
{ isUnexpected } = require("@azure-rest/ai-content-safety");
const { AzureKeyCredential } = require("@azure/core-auth");
// Load the .env file if it exists
require("dotenv").config();
const endpoint = process.env["CONTENT_SAFETY_ENDPOINT"] || "<endpoint>";
const key = process.env["CONTENT_SAFETY_API_KEY"] || "<key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function deleteBlocklist() {
const blocklistName = "<your_list_name>";
const result = await client.path("/text/blocklists/{blocklistName}", blocklistName).delete();
if (isUnexpected(result)) {
throw result;
}
console.log("Deleted blocklist: ", blocklistName);
}
(async () => {
await deleteBlocklist();
})().catch((err) => {
console.error("The sample encountered an error:", err);
});
- 将
<your_list_name>
(在请求 URL 中)替换为你在列表创建步骤中使用的名称。
- 运行该脚本。
后续步骤
请参阅 API 参考文档,以详细了解有关本指南中使用的 API。