使用封鎖清單
本文內容
警告
本指南中的範例數據可能包含冒犯性內容。 建議使用者斟酌使用。
預設 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 內容安全性用戶端程式庫。 在專案目錄中執行 pip install azure-ai-contentsafety
命令。
已安裝 .NET 執行階段 。
已安裝 .NET Core SDK。
如果您使用 .NET,則必須安裝適用於 .NET 的 Azure AI 內容安全性用戶端程式庫。 在專案目錄中執行 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
,讓變更生效。
使用封鎖清單分析文字
您可以建立要與文字 API 搭配使用的封鎖清單。 下列步驟可協助您開始使用。
建立或修改封鎖清單
將下列 cURL 命令複製至文字編輯器,並進行下列變更:
使用您的端點 URL 取代 <endpoint>
。
以您的金鑰取代 <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=2023-10-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
(更新現有清單)。
在您慣用的編輯器或 IDE 中建立新的 C# 主控台應用程式並將其開啟。 貼入下列程式碼。
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>
取代為自訂描述。
執行程式碼。
在您慣用的編輯器或 IDE 中建立新的 Python 指令碼,並加以開啟。 貼入下列程式碼。
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>
取代為自訂描述。
執行指令碼。
將 blocklistItems 新增至清單
注意
所有清單的總數上限為 10,000 個字詞 。 您可以在一個要求中最多新增 100 個 blocklistItem。
將下列 cURL 命令複製至文字編輯器,並進行下列變更:
使用您的端點 URL 取代 <endpoint>
。
以您的金鑰取代 <enter_your_key_here>
。
將 [URL] 取代 <your_list_name>
為您在清單建立步驟中使用的名稱。
選擇性將 "description"
欄位的值取代為自訂描述。
將 "text"
欄位的值取代為您想新增至封鎖清單的項目。 blocklistItem 的最大長度為 128 個字元。
curl --location --request POST '<endpoint>/contentsafety/text/blocklists/<your_list_name>:addOrUpdateBlocklistItems?api-version=2023-10-01' \
--header 'Ocp-Apim-Subscription-Key: <enter_your_key_here>' \
--header 'Content-Type: application/json' \
--data-raw '"blocklistItems": [{
"description": "string",
"text": "bleed"
}]'
提示
您可以在一個 API 呼叫中新增多個 blocklistItems。 讓要求本文成為資料群組的 JSON 陣列:
{
"blocklistItems": [
{
"description": "string",
"text": "bleed"
},
{
"description": "string",
"text": "blood"
}
]
}
回應碼應該為 200
。
{
"blocklistItems:"[
{
"blocklistItemId": "string",
"description": "string",
"text": "bleed"
}
]
}
在您慣用的編輯器或 IDE 中建立新的 C# 主控台應用程式並將其開啟。 貼入下列程式碼。
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>
為您在清單建立步驟中使用的名稱。
將和 blocklistItemText2
欄位的值blocklistItemText1
取代為您想要新增至封鎖清單的專案。 blockItem 的長度上限為 128 個字元。
選擇性地將更多 blockItem 字串新增至 blockItems
參數。
執行程式碼。
建立 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>
為您在清單建立步驟中使用的名稱。
將和 blockItemText2
欄位的值blockItemText1
取代為您想要新增至封鎖清單的專案。 blockItem 的長度上限為 128 個字元。
選擇性地將更多 blockItem 字串新增至 blockItems
參數。
執行程式碼。
在您慣用的編輯器或 IDE 中建立新的 Python 指令碼,並加以開啟。 貼入下列程式碼。
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_2
欄位的值blocklist_item_text_1
取代為您想要新增至封鎖清單的專案。 blockItem 的長度上限為 128 個字元。
選擇性地將更多 blockItem 字串新增至 block_items
參數。
執行指令碼。
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_2
欄位的值block_item_text_1
取代為您想要新增至封鎖清單的專案。 blockItem 的長度上限為 128 個字元。
選擇性地將更多 blockItem 字串新增至 blocklistItems
參數。
執行指令碼。
注意
在您新增或編輯 blockItem 之後,在文字分析生效之前會有部分延遲,而這通常不超過五分鐘 。
使用封鎖清單分析文字
將下列 cURL 命令複製至文字編輯器,並進行下列變更:
使用您的端點 URL 取代 <endpoint>
。
以您的金鑰取代 <enter_your_key_here>
。
將取代 <your_list_name>
為您在清單建立步驟中使用的名稱。 "blocklistNames"
欄位可以包含多個清單識別碼的陣列。
您可以選擇性地變更 "breakByBlocklists"
值。 true
表示一旦符合封鎖清單,分析就會立即傳回,而不需要模型輸出。 false
會導致模型繼續在預設類別中進行分析。
選擇性地將欄位的值 "text"
變更為您想要分析的任何文字。
curl --location --request POST '<endpoint>/contentsafety/text:analyze?api-version=2023-10-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
}
]
}
在您慣用的編輯器或 IDE 中建立新的 C# 主控台應用程式並將其開啟。 貼入下列程式碼。
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
輸入文字取代為您想要分析的任何文字。
執行指令碼。
在您慣用的編輯器或 IDE 中建立新的 Python 指令碼,並加以開啟。 貼入下列程式碼。
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
變數取代為您想要分析的任何文字。
執行指令碼。
其他封鎖清單作業
本節包含更多作業,可協助您管理和使用封鎖清單功能。
列出清單中的所有 blocklistItems
將下列 cURL 命令複製至文字編輯器,並進行下列變更:
使用您的端點 URL 取代 <endpoint>
。
以您的金鑰取代 <enter_your_key_here>
。
將 (在要求URL中) 取代 <your_list_name>
為您在清單建立步驟中使用的名稱。
curl --location --request GET '<endpoint>/contentsafety/text/blocklists/<your_list_name>/blocklistItems?api-version=2023-10-01' \
--header 'Ocp-Apim-Subscription-Key: <enter_your_key_here>' \
--header 'Content-Type: application/json'
狀態碼應該是 200
,且回應本文看起來應該像這樣:
{
"values": [
{
"blocklistItemId": "string",
"description": "string",
"text": "bleed",
}
]
}
在您慣用的編輯器或 IDE 中建立新的 C# 主控台應用程式並將其開啟。 貼入下列程式碼。
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>
為您在清單建立步驟中使用的名稱。
執行指令碼。
在您慣用的編輯器或 IDE 中建立新的 Python 指令碼,並加以開啟。 貼入下列程式碼。
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 命令複製至文字編輯器,並進行下列變更:
使用您的端點 URL 取代 <endpoint>
。
以您的金鑰取代 <enter_your_key_here>
。
curl --location --request GET '<endpoint>/contentsafety/text/blocklists?api-version=2023-10-01' \
--header 'Ocp-Apim-Subscription-Key: <enter_your_key_here>' \
--header 'Content-Type: application/json'
狀態碼應為 200
。 JSON 回應看起來會像這樣:
"value": [
{
"blocklistName": "string",
"description": "string"
}
]
在您慣用的編輯器或 IDE 中建立新的 C# 主控台應用程式並將其開啟。 貼入下列程式碼。
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());
}
執行指令碼。
在您慣用的編輯器或 IDE 中建立新的 Python 指令碼,並加以開啟。 貼入下列程式碼。
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 命令複製至文字編輯器,並進行下列變更:
使用您的端點 URL 取代 <endpoint>
。
以您的金鑰取代 <enter_your_key_here>
。
將 (在要求URL中) 取代 <your_list_name>
為您在清單建立步驟中使用的名稱。
cURL --location '<endpoint>contentsafety/text/blocklists/<your_list_name>?api-version=2023-10-01' \
--header 'Ocp-Apim-Subscription-Key: <enter_your_key_here>' \
--data ''
狀態碼應為 200
。 JSON 回應看起來會像這樣:
{
"blocklistName": "string",
"description": "string"
}
在您慣用的編輯器或 IDE 中建立新的 C# 主控台應用程式並將其開啟。 貼入下列程式碼。
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>
為您在清單建立步驟中使用的名稱。
執行指令碼。
在您慣用的編輯器或 IDE 中建立新的 Python 指令碼,並加以開啟。 貼入下列程式碼。
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 命令複製至文字編輯器,並進行下列變更:
使用您的端點 URL 取代 <endpoint>
。
以您的金鑰取代 <enter_your_key_here>
。
將 (在要求URL中) 取代 <your_list_name>
為您在清單建立步驟中使用的名稱。
將取代 <your_item_id>
為 blocklistItem 的標識碼值。 這是 Add blocklistItem 或 Get all blocklistItems API 呼叫中的欄位值"blocklistItemId"
。
cURL --location '<endpoint>contentsafety/text/blocklists/<your_list_name>/blocklistItems/<your_item_id>?api-version=2023-10-01' \
--header 'Ocp-Apim-Subscription-Key: <enter_your_key_here>' \
--data ''
狀態碼應為 200
。 JSON 回應看起來會像這樣:
{
"blocklistItemId": "string",
"description": "string",
"text": "string"
}
在您慣用的編輯器或 IDE 中建立新的 C# 主控台應用程式並將其開啟。 貼入下列程式碼。
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>
為先前新增專案的識別碼。
執行指令碼。
建立 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>
為先前新增專案的識別碼。
執行指令碼。
在您慣用的編輯器或 IDE 中建立新的 Python 指令碼,並加以開啟。 貼入下列程式碼。
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>
為您想要取得之項目的標識碼。
執行指令碼。
從封鎖清單中移除 blocklistItems。
注意
在您刪除項目之後,在文字分析生效之前會有部分延遲,而這通常不超過五分鐘 。
將下列 cURL 命令複製至文字編輯器,並進行下列變更:
使用您的端點 URL 取代 <endpoint>
。
以您的金鑰取代 <enter_your_key_here>
。
將 (在要求URL中) 取代 <your_list_name>
為您在清單建立步驟中使用的名稱。
將取代 <item_id>
為 blocklistItem 的標識碼值。 這是 Add blocklistItem 或 Get all blocklistItems API 呼叫中的欄位值"blocklistItemId"
。
curl --location --request DELETE '<endpoint>/contentsafety/text/blocklists/<your_list_name>:removeBlocklistItems?api-version=2023-10-01' \
--header 'Ocp-Apim-Subscription-Key: <enter_your_key_here>' \
--header 'Content-Type: application/json'
--data-raw '"blocklistItemIds":[
"<item_id>"
]'
提示
您可以在一個 API 呼叫中刪除多個 blocklistItems。 讓要求本文成為 blocklistItemId
值的陣列。
回應碼應該為 204
。
在您慣用的編輯器或 IDE 中建立新的 C# 主控台應用程式並將其開啟。 貼入下列程式碼。
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>
為先前新增專案的識別碼。
執行指令碼。
建立 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>
為先前新增專案的識別碼。
執行指令碼。
在您慣用的編輯器或 IDE 中建立新的 Python 指令碼,並加以開啟。 貼入下列程式碼。
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
為您要移除之項目的識別碼。
執行指令碼。
刪除清單及其所有內容
注意
在您刪除清單之後,在文字分析生效之前會有部分延遲,而這通常不超過五分鐘 。
將下列 cURL 命令複製至文字編輯器,並進行下列變更:
使用您的端點 URL 取代 <endpoint>
。
以您的金鑰取代 <enter_your_key_here>
。
將 (在要求URL中) 取代 <your_list_name>
為您在清單建立步驟中使用的名稱。
curl --location --request DELETE '<endpoint>/contentsafety/text/blocklists/<your_list_name>?api-version=2023-10-01' \
--header 'Ocp-Apim-Subscription-Key: <enter_your_key_here>' \
--header 'Content-Type: application/json' \
回應碼應該為 204
。
在您慣用的編輯器或 IDE 中建立新的 C# 主控台應用程式並將其開啟。 貼入下列程式碼。
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.");
}
將 (在要求URL中) 取代 <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>";
blocklistClient.deleteTextBlocklist(blocklistName);
將 (在要求URL中) 取代 <your_list_name>
為您在清單建立步驟中使用的名稱。
執行指令碼。
在您慣用的編輯器或 IDE 中建立新的 Python 指令碼,並加以開啟。 貼入下列程式碼。
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
將 (在要求URL中) 取代 <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 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);
});
將 (在要求URL中) 取代 <your_list_name>
為您在清單建立步驟中使用的名稱。
執行指令碼。
下一步
請參閱 API 參考文件,以深入了解本指南中使用的 API。