Menggunakan daftar blokir
Artikel 06/01/2024
4 kontributor
Saran dan Komentar
Dalam artikel ini
Perhatian
Data sampel dalam panduan ini mungkin berisi konten yang menyinggung. Kebijaksanaan pengguna disarankan.
Pengklasifikasi AI default cukup untuk sebagian besar kebutuhan kon mode tenda rasi. Namun, Anda mungkin perlu menyaring item yang khusus untuk kasus penggunaan Anda. Daftar blokir memungkinkan Anda menambahkan istilah kustom ke pengklasifikasi AI. Anda dapat menggunakan daftar blokir untuk menyaring istilah atau frasa tertentu yang ingin Anda benderai di konten Anda.
Prasyarat
Langganan Azure - buat langganan gratis
Setelah Anda memiliki langganan Azure, buat sumber daya Content Brankas ty di portal Azure untuk mendapatkan kunci dan titik akhir Anda. Masukkan nama unik untuk sumber daya Anda, pilih langganan Anda, dan pilih grup sumber daya, wilayah yang didukung (lihat Ketersediaan wilayah), dan tingkat harga yang didukung. Lalu pilih Buat .
Sumber daya membutuhkan waktu beberapa menit untuk disebarkan. Setelah selesai, Pilih buka sumber daya . Di panel kiri, di bawah Manajemen Sumber Daya, pilih Kunci Langganan dan Titik Akhir. Titik akhir dan salah satu kunci digunakan untuk memanggil API.
Salah satu hal berikut ini terinstal:
cURL untuk panggilan REST API.
Python 3.x terinstal
Penginstalan Python Anda harus menyertakan pip . Anda dapat memeriksa apakah pip terinstal dengan menjalankan pip --version
pada baris perintah. Dapatkan pip dengan menginstal versi terbaru Python.
Jika Anda menggunakan Python, Anda harus menginstal pustaka klien Azure AI Content Brankas ty untuk Python. Jalankan perintah pip install azure-ai-contentsafety
di direktori proyek Anda.
.NET Runtime terinstal.
.NET Core SDK terinstal.
Jika Anda menggunakan .NET, Anda harus menginstal pustaka klien Azure AI Content Brankas ty untuk .NET. Jalankan perintah dotnet add package Azure.AI.ContentSafety --prerelease
di direktori proyek Anda.
Membuat variabel lingkungan
Dalam contoh ini, Anda akan menulis kredensial Anda ke variabel lingkungan pada komputer lokal yang menjalankan aplikasi.
Untuk mengatur variabel lingkungan untuk kunci dan titik akhir Anda, buka jendela konsol dan ikuti instruksi untuk sistem operasi dan lingkungan pengembangan Anda.
Untuk mengatur CONTENT_SAFETY_KEY
variabel lingkungan, ganti YOUR_CONTENT_SAFETY_KEY
dengan salah satu kunci untuk sumber daya Anda.
Untuk mengatur CONTENT_SAFETY_ENDPOINT
variabel lingkungan, ganti YOUR_CONTENT_SAFETY_ENDPOINT
dengan titik akhir untuk sumber daya Anda.
setx CONTENT_SAFETY_KEY 'YOUR_CONTENT_SAFETY_KEY'
setx CONTENT_SAFETY_ENDPOINT 'YOUR_CONTENT_SAFETY_ENDPOINT'
Setelah menambahkan variabel lingkungan, Anda mungkin perlu memulai ulang program yang sedang berjalan yang akan membaca variabel lingkungan, termasuk jendela konsol.
export CONTENT_SAFETY_KEY='YOUR_CONTENT_SAFETY_KEY'
export CONTENT_SAFETY_ENDPOINT='YOUR_CONTENT_SAFETY_ENDPOINT'
Setelah Anda menambahkan variabel lingkungan, jalankan source ~/.bashrc
dari jendela konsol Anda untuk membuat perubahan efektif.
Menganalisis teks dengan daftar blokir
Anda dapat membuat daftar blokir untuk digunakan dengan Text API. Langkah-langkah berikut membantu Anda memulai.
Membuat atau mengubah daftar blokir
Salin perintah cURL di bawah ini ke editor teks dan buat perubahan berikut:
Ganti <endpoint>
dengan URL titik akhir Anda.
Ganti <enter_your_key_here>
dengan kunci Anda.
Ganti <your_list_name>
(di URL) dengan nama kustom untuk daftar Anda. Ganti juga istilah terakhir URL REST dengan nama yang sama. Karakter yang diizinkan: 0-9, A-Z, a-z, - . _ ~
.
Secara opsional ganti nilai "description"
bidang dengan deskripsi kustom.
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"
}'
Kode respons harus 201
(membuat daftar baru) atau 200
(memperbarui daftar yang sudah ada).
Buat aplikasi konsol C# baru dan buka di editor atau IDE pilihan Anda. Tempelkan dalam kode berikut.
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);
}
Ganti <your_list_name>
dengan nama kustom untuk daftar Anda. Karakter yang diizinkan: 0-9, A-Z, a-z, - . _ ~
.
Ganti secara <description>
opsional dengan deskripsi kustom.
Menjalankan kode.
Buat aplikasi Java dan buka di editor atau IDE pilihan Anda. Tempelkan dalam kode berikut.
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.");
}
Ganti <your_list_name>
dengan nama kustom untuk daftar Anda. Karakter yang diizinkan: 0-9, A-Z, a-z, - . _ ~
.
Ganti secara <description>
opsional dengan deskripsi kustom.
Menjalankan kode.
Buat skrip Python baru dan buka di editor atau IDE pilihan Anda. Tempelkan dalam kode berikut.
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
Ganti <your_list_name>
dengan nama kustom untuk daftar Anda. Karakter yang diizinkan: 0-9, A-Z, a-z, - . _ ~
.
Ganti <description>
dengan deskripsi kustom.
Jalankan skrip.
Buat skrip JavaScript baru dan buka di editor atau IDE pilihan Anda. Tempelkan dalam kode berikut.
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);
});
Ganti <your_list_name>
dengan nama kustom untuk daftar Anda. Karakter yang diizinkan: 0-9, A-Z, a-z, - . _ ~
.
Ganti secara <description>
opsional dengan deskripsi kustom.
Jalankan skrip.
Menambahkan blocklistItems ke daftar
Catatan
Ada batas maksimum total 10.000 istilah di semua daftar. Anda dapat menambahkan paling banyak 100 blocklistItem dalam satu permintaan.
Salin perintah cURL di bawah ini ke editor teks dan buat perubahan berikut:
Ganti <endpoint>
dengan URL titik akhir Anda.
Ganti <enter_your_key_here>
dengan kunci Anda.
Ganti <your_list_name>
(di URL) dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
Secara opsional ganti nilai "description"
bidang dengan deskripsi kustom.
Ganti nilai "text"
bidang dengan item yang ingin Anda tambahkan ke daftar blokir Anda. Panjang maksimum blocklistItem adalah 128 karakter.
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"
}]'
Tip
Anda dapat menambahkan beberapa blocklistItems dalam satu panggilan API. Jadikan isi permintaan sebagai array JSON grup data:
{
"blocklistItems": [
{
"description": "string",
"text": "bleed"
},
{
"description": "string",
"text": "blood"
}
]
}
Kode respons harus 200
.
{
"blocklistItems:"[
{
"blocklistItemId": "string",
"description": "string",
"text": "bleed"
}
]
}
Buat aplikasi konsol C# baru dan buka di editor atau IDE pilihan Anda. Tempelkan dalam kode berikut.
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);
}
}
Ganti <your_list_name>
dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
Ganti nilai blocklistItemText1
bidang dan blocklistItemText2
dengan item yang ingin Anda tambahkan ke daftar blokir Anda. Panjang maksimum blockItem adalah 128 karakter.
Secara opsional tambahkan lebih banyak string blockItem ke blockItems
parameter .
Menjalankan kode.
Buat aplikasi Java dan buka di editor atau IDE pilihan Anda. Tempelkan dalam kode berikut.
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());
}
}
Ganti <your_list_name>
dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
Ganti nilai blockItemText1
bidang dan blockItemText2
dengan item yang ingin Anda tambahkan ke daftar blokir Anda. Panjang maksimum blockItem adalah 128 karakter.
Secara opsional tambahkan lebih banyak string blockItem ke blockItems
parameter .
Menjalankan kode.
Buat skrip Python baru dan buka di editor atau IDE pilihan Anda. Tempelkan dalam kode berikut.
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
Ganti <your_list_name>
dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
Ganti nilai blocklist_item_text_1
bidang dan blocklist_item_text_2
dengan item yang ingin Anda tambahkan ke daftar blokir Anda. Panjang maksimum blockItem adalah 128 karakter.
Secara opsional tambahkan lebih banyak string blockItem ke block_items
parameter .
Jalankan skrip.
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);
});
Ganti <your_list_name>
dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
Ganti nilai block_item_text_1
bidang dan block_item_text_2
dengan item yang ingin Anda tambahkan ke daftar blokir Anda. Panjang maksimum blockItem adalah 128 karakter.
Secara opsional tambahkan lebih banyak string blockItem ke blocklistItems
parameter .
Jalankan skrip.
Catatan
Akan ada beberapa penundaan setelah Anda menambahkan atau mengedit blockItem sebelum berlaku pada analisis teks, biasanya tidak lebih dari lima menit .
Menganalisis teks dengan daftar blokir
Salin perintah cURL di bawah ini ke editor teks dan buat perubahan berikut:
Ganti <endpoint>
dengan URL titik akhir Anda.
Ganti <enter_your_key_here>
dengan kunci Anda.
Ganti <your_list_name>
dengan nama yang Anda gunakan dalam langkah pembuatan daftar. Bidang "blocklistNames"
dapat berisi array dari beberapa ID daftar.
Secara opsional mengubah nilai "breakByBlocklists"
. true
menunjukkan bahwa setelah daftar blokir dicocokkan, analisis akan segera kembali tanpa output model. false
akan menyebabkan model terus melakukan analisis dalam kategori default.
Secara opsional ubah nilai bidang menjadi "text"
teks apa pun yang ingin Anda analisis.
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"
}'
Respons JSON akan berisi "blocklistMatchResults"
yang menunjukkan kecocokan dengan daftar blokir Anda. Ini melaporkan lokasi dalam string teks tempat kecocokan ditemukan.
{
"blocklistsMatch": [
{
"blocklistName": "string",
"blocklistItemId": "string",
"blocklistItemText": "bleed"
}
],
"categoriesAnalysis": [
{
"category": "Hate",
"severity": 0
}
]
}
Buat aplikasi konsol C# baru dan buka di editor atau IDE pilihan Anda. Tempelkan dalam kode berikut.
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);
}
}
Ganti <your_list_name>
dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
request
Ganti teks input dengan teks apa pun yang ingin Anda analisis.
Jalankan skrip.
Buat aplikasi Java dan buka di editor atau IDE pilihan Anda. Tempelkan dalam kode berikut.
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());
}
}
Ganti <your_list_name>
dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
request
Ganti teks input dengan teks apa pun yang ingin Anda analisis.
Jalankan skrip.
Buat skrip Python baru dan buka di editor atau IDE pilihan Anda. Tempelkan dalam kode berikut.
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
Ganti <your_list_name>
dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
input_text
Ganti variabel dengan teks apa pun yang ingin Anda analisis.
Jalankan skrip.
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);
});
Ganti <your_list_name>
dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
inputText
Ganti variabel dengan teks apa pun yang ingin Anda analisis.
Jalankan skrip.
Operasi daftar blokir lainnya
Bagian ini berisi lebih banyak operasi untuk membantu Anda mengelola dan menggunakan fitur daftar blokir.
Mencantumkan semua blocklistItems dalam daftar
Salin perintah cURL di bawah ini ke editor teks dan buat perubahan berikut:
Ganti <endpoint>
dengan URL titik akhir Anda.
Ganti <enter_your_key_here>
dengan kunci Anda.
Ganti <your_list_name>
(di URL permintaan) dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
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'
Kode status harus 200
dan isi respons akan terlihat seperti ini:
{
"values": [
{
"blocklistItemId": "string",
"description": "string",
"text": "bleed",
}
]
}
Buat aplikasi konsol C# baru dan buka di editor atau IDE pilihan Anda. Tempelkan dalam kode berikut.
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);
}
Ganti <your_list_name>
dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
Jalankan skrip.
Buat aplikasi Java dan buka di editor atau IDE pilihan Anda. Tempelkan dalam kode berikut.
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());
}
Ganti <your_list_name>
dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
Jalankan skrip.
Buat skrip Python baru dan buka di editor atau IDE pilihan Anda. Tempelkan dalam kode berikut.
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
Ganti <your_list_name>
dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
Jalankan skrip.
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);
});
Ganti <your_list_name>
dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
Jalankan skrip.
Mencantumkan semua daftar blokir
Salin perintah cURL di bawah ini ke editor teks dan buat perubahan berikut:
Ganti <endpoint>
dengan URL titik akhir Anda.
Ganti <enter_your_key_here>
dengan kunci Anda.
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'
Kode status harus 200
. Respons JSON terlihat seperti ini:
"value": [
{
"blocklistName": "string",
"description": "string"
}
]
Buat aplikasi konsol C# baru dan buka di editor atau IDE pilihan Anda. Tempelkan dalam kode berikut.
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);
}
Jalankan skrip.
Buat aplikasi Java dan buka di editor atau IDE pilihan Anda. Tempelkan dalam kode berikut.
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());
}
Jalankan skrip.
Buat skrip Python baru dan buka di editor atau IDE pilihan Anda. Tempelkan dalam kode berikut.
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
Jalankan skrip.
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);
});
Jalankan skrip.
Mendapatkan daftar blokir menurut blocklistName
Salin perintah cURL di bawah ini ke editor teks dan buat perubahan berikut:
Ganti <endpoint>
dengan URL titik akhir Anda.
Ganti <enter_your_key_here>
dengan kunci Anda.
Ganti <your_list_name>
(di URL permintaan) dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
cURL --location '<endpoint>contentsafety/text/blocklists/<your_list_name>?api-version=2023-10-01' \
--header 'Ocp-Apim-Subscription-Key: <enter_your_key_here>' \
--data ''
Kode status harus 200
. Respons JSON terlihat seperti ini:
{
"blocklistName": "string",
"description": "string"
}
Buat aplikasi konsol C# baru dan buka di editor atau IDE pilihan Anda. Tempelkan dalam kode berikut.
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);
}
Ganti <your_list_name>
dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
Jalankan skrip.
Buat aplikasi Java dan buka di editor atau IDE pilihan Anda. Tempelkan dalam kode berikut.
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());
}
Ganti <your_list_name>
dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
Jalankan skrip.
Buat skrip Python baru dan buka di editor atau IDE pilihan Anda. Tempelkan dalam kode berikut.
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
Ganti <your_list_name>
dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
Jalankan skrip.
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);
});
Ganti <your_list_name>
dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
Jalankan skrip.
Mendapatkan blocklistItem dengan blocklistName dan blocklistItemId
Salin perintah cURL di bawah ini ke editor teks dan buat perubahan berikut:
Ganti <endpoint>
dengan URL titik akhir Anda.
Ganti <enter_your_key_here>
dengan kunci Anda.
Ganti <your_list_name>
(di URL permintaan) dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
Ganti <your_item_id>
dengan nilai ID untuk blocklistItem. Ini adalah nilai bidang dari tambahkan blocklistItem atau Dapatkan semua panggilan API blocklistItems ."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 ''
Kode status harus 200
. Respons JSON terlihat seperti ini:
{
"blocklistItemId": "string",
"description": "string",
"text": "string"
}
Buat aplikasi konsol C# baru dan buka di editor atau IDE pilihan Anda. Tempelkan dalam kode berikut.
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);
Ganti <your_list_name>
dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
Ganti <your_block_item_id>
dengan ID item yang ditambahkan sebelumnya.
Jalankan skrip.
Buat aplikasi Java dan buka di editor atau IDE pilihan Anda. Tempelkan dalam kode berikut.
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());
Ganti <your_list_name>
dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
Ganti <your_block_item_id>
dengan ID item yang ditambahkan sebelumnya.
Jalankan skrip.
Buat skrip Python baru dan buka di editor atau IDE pilihan Anda. Tempelkan dalam kode berikut.
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
Ganti <your_list_name>
dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
Ganti <block_item_text>
dengan teks item blok Anda.
Jalankan skrip.
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);
});
Ganti <your_list_name>
dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
Ganti <your_block_item_id>
dengan ID item yang ingin Anda dapatkan.
Jalankan skrip.
Hapus blocklistItems dari daftar blokir.
Catatan
Akan ada beberapa penundaan setelah Anda menghapus item sebelum berlaku pada analisis teks, biasanya tidak lebih dari lima menit .
Salin perintah cURL di bawah ini ke editor teks dan buat perubahan berikut:
Ganti <endpoint>
dengan URL titik akhir Anda.
Ganti <enter_your_key_here>
dengan kunci Anda.
Ganti <your_list_name>
(di URL permintaan) dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
Ganti <item_id>
dengan nilai ID untuk blocklistItem. Ini adalah nilai bidang dari tambahkan blocklistItem atau Dapatkan semua panggilan API blocklistItems ."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>"
]'
Tip
Anda dapat menghapus beberapa blocklistItems dalam satu panggilan API. Jadikan isi permintaan sebagai array blocklistItemId
nilai.
Kode respons harus 204
.
Buat aplikasi konsol C# baru dan buka di editor atau IDE pilihan Anda. Tempelkan dalam kode berikut.
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);
}
Ganti <your_list_name>
dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
Ganti <your_block_item_id>
dengan ID item yang ditambahkan sebelumnya.
Jalankan skrip.
Buat aplikasi Java dan buka di editor atau IDE pilihan Anda. Tempelkan dalam kode berikut.
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));
Ganti <your_list_name>
dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
Ganti <your_block_item_id>
dengan ID item yang ditambahkan sebelumnya.
Jalankan skrip.
Buat skrip Python baru dan buka di editor atau IDE pilihan Anda. Tempelkan dalam kode berikut.
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
Ganti <your_list_name>
dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
Ganti <block_item_text>
dengan teks item blok Anda.
Jalankan skrip.
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);
});
Ganti <your_list_name>
dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
Ganti <your_block_item_id
dengan ID item yang ingin Anda hapus.
Jalankan skrip.
Menghapus daftar dan semua isinya
Catatan
Akan ada beberapa penundaan setelah Anda menghapus daftar sebelum berlaku pada analisis teks, biasanya tidak lebih dari lima menit .
Salin perintah cURL di bawah ini ke editor teks dan buat perubahan berikut:
Ganti <endpoint>
dengan URL titik akhir Anda.
Ganti <enter_your_key_here>
dengan kunci Anda.
Ganti <your_list_name>
(di URL permintaan) dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
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' \
Kode respons harus 204
.
Buat aplikasi konsol C# baru dan buka di editor atau IDE pilihan Anda. Tempelkan dalam kode berikut.
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.");
}
Ganti <your_list_name>
(di URL permintaan) dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
Jalankan skrip.
Buat aplikasi Java dan buka di editor atau IDE pilihan Anda. Tempelkan dalam kode berikut.
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);
Ganti <your_list_name>
(di URL permintaan) dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
Jalankan skrip.
Buat skrip Python baru dan buka di editor atau IDE pilihan Anda. Tempelkan dalam kode berikut.
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
Ganti <your_list_name>
(di URL permintaan) dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
Jalankan skrip.
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);
});
Ganti <your_list_name>
(di URL permintaan) dengan nama yang Anda gunakan dalam langkah pembuatan daftar.
Jalankan skrip.
Langkah berikutnya
Lihat dokumentasi referensi API untuk mempelajari selengkapnya tentang API yang digunakan dalam panduan ini.