Azure AI Content Safety 애플리케이션 및 서비스에서 유해한 사용자 생성 및 AI 생성 콘텐츠를 검색합니다. 콘텐츠 안전에는 유해한 자료를 감지할 수 있는 텍스트 및 이미지 API가 포함되어 있습니다.
- 텍스트 분석 API: 다중 심각도 수준으로 성적 콘텐츠, 폭력, 증오 및 자해에 대한 텍스트를 검색합니다.
- 이미지 분석 API: 다중 심각도 수준으로 성적 콘텐츠, 폭력, 증오 및 자해에 대한 이미지를 검색합니다.
- 텍스트 차단 목록 관리 API: 기본 AI 분류자는 대부분의 콘텐츠 안전 요구 사항에 충분합니다. 그러나 사용 사례와 관련된 용어를 확인해야 할 수 있습니다. Text API와 함께 사용할 용어의 차단 목록을 만들 수 있습니다.
이 라이브러리를 사용하려면 REST 클라이언트 문서 많이
키 링크:
- 소스 코드
- NPM(패키지)
- API 참조 설명서
- 샘플
시작
현재 지원되는 환경
- LTS 버전의 Node.js
필수 구성 요소
- 이 패키지를 사용하려면 Azure 구독 필요합니다.
- Azure AI Content Safety 리소스는 기존 리소스가 없으면 새 만들있습니다.
@azure-rest/ai-content-safety 패키지 설치
npm사용하여 JavaScript용 Azure AI Content Safety REST 클라이언트 REST 클라이언트 라이브러리를 설치합니다.
npm install @azure-rest/ai-content-safety
ContentSafetyClient 만들기 및 인증
엔드포인트 가져오기
Azure Portal 또는 Azure CLI 사용하여 Azure AI Content Safety 서비스 리소스에 대한 엔드포인트를 찾을 수 있습니다.
# Get the endpoint for the Azure AI Content Safety service resource
az cognitiveservices account show --name "resource-name" --resource-group "resource-group-name" --query "properties.endpoint"
AzureKeyCredential을 사용하여 ContentSafetyClient 만들기
- 1단계: API 키 가져오기
API 키는 Azure Portal 또는 다음 Azure CLI 명령을 실행하여 찾을 수 있습니다.
az cognitiveservices account keys list --name "<resource-name>" --resource-group "<resource-group-name>"
- 2단계: AzureKeyCredential을 사용하여 ContentSafetyClient 만들기
API 키를 credential 매개 변수로 사용하려면 키를 문자열로 AzureKeyCredential인스턴스에 전달합니다.
import { AzureKeyCredential } from "@azure/core-auth";
import ContentSafetyClient from "@azure-rest/ai-content-safety";
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const key = "<api_key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
Microsoft Entra ID(이전의 AAD(Azure Active Directory)) 토큰 자격 증명을 사용하여 ContentSafetyClient 만들기
1단계: 리소스에 대해 Microsoft Entra ID를 사용하도록 설정하려면 Microsoft Entra ID 인증하기이 Cognitive Services 인증 문서를 참조하세요. 리소스에 AAD를 사용하도록 설정하는 단계의 경우
주요 단계는 다음과 같습니다.
- 사용자 지정 하위 도메인을 사용하여 리소스를 만듭니다.
- 서비스 주체를 만들고 Cognitive Services 사용자 역할을 할당합니다.
2단계: AAD 애플리케이션의 클라이언트 ID, 테넌트 ID 및 클라이언트 암호 값을 환경 변수로 설정합니다. AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET
AAD를 사용하여 인증하려면 먼저 @azure/identitynpm 설치해야 합니다. 설치 후 사용할 @azure/identity자격 증명 유형을 선택할 수 있습니다.
예를 들어 DefaultAzureCredential 사용하여 클라이언트를 인증할 수 있습니다.
import { DefaultAzureCredential } from "@azure/identity";
import ContentSafetyClient from "@azure-rest/ai-content-safety";
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const credential = new DefaultAzureCredential();
const client = ContentSafetyClient(endpoint, credential);
주요 개념
사용 가능한 기능
이 서비스에서 사용할 수 있는 다양한 유형의 분석이 있습니다. 다음 표에서는 현재 사용 가능한 API에 대해 설명합니다.
| 특징 | 묘사 |
|---|---|
| 텍스트 분석 API | 다중 심각도 수준으로 성적 콘텐츠, 폭력, 증오 및 자해에 대한 텍스트를 검색합니다. |
| 이미지 분석 API | 다중 심각도 수준으로 성적 콘텐츠, 폭력, 증오 및 자해에 대한 이미지를 검색합니다. |
| 텍스트 차단 목록 관리 API | 기본 AI 분류자는 대부분의 콘텐츠 안전 요구 사항에 충분합니다. 그러나 사용 사례와 관련된 용어를 검사해야 할 수 있습니다. Text API와 함께 사용할 용어의 차단 목록을 만들 수 있습니다. |
피해 범주
콘텐츠 안전은 불쾌한 콘텐츠의 네 가지 범주를 인식합니다.
| 범주 | 묘사 |
|---|---|
| 미워하다 | 증오는 해당 그룹의 특정 차별화 특성에 따라 개인 또는 ID 그룹을 참조하여 조롱적이거나 차별적인 언어를 공격하거나 사용하는 모든 콘텐츠를 나타냅니다. 여기에는 인종, 민족, 국적, 성 정체성 및 표현, 성적 지향, 종교, 이민 신분, 능력 상태, 개인 외모 및 신체 크기가 포함되나 이에 국한되지 않습니다. |
| 성의 | 성적은 해부학적 장기 및 성기, 낭만적 인 관계, 에로틱하거나 애정어린 용어로 묘사 된 행위, 임신, 신체적 성적 행위 ( 폭행 또는 자신의 의지에 대한 강제 성적 폭력 행위로 묘사 된 행위 포함) , 매춘, 포르노 및 학대와 관련된 콘텐츠를 설명합니다. |
| 폭력 | 폭력은 누군가 또는 무언가를 다치게 하거나, 다치게 하거나, 손상시키거나, 죽이려는 신체적 행동과 관련된 콘텐츠를 설명합니다. 또한 무기, 총기 및 제조업체, 협회, 법률 등과 같은 관련 법인도 포함됩니다. |
| 자해 | 자해는 의도적으로 몸을 다치거나, 다치거나, 손상시키거나, 자신을 죽이기 위한 신체적 행동과 관련된 콘텐츠를 설명합니다. |
분류는 다중 레이블로 지정할 수 있습니다. 예를 들어 텍스트 샘플이 텍스트 조정 모델을 거치면 성적 콘텐츠와 폭력으로 분류될 수 있습니다.
심각도 수준
서비스가 적용되는 모든 피해 범주에는 심각도 수준 등급도 함께 제공됩니다. 심각도 수준은 플래그가 지정된 콘텐츠를 표시할 때의 결과의 심각도를 나타내기 위한 것입니다.
텍스트: 현재 버전의 텍스트 모델은 전체 0-7 심각도 배율지원합니다. 기본적으로 응답은 0, 2, 4 및 6의 4개 값을 출력합니다. 인접한 두 수준은 각각 단일 수준에 매핑됩니다. 사용자는 요청에 "outputType"을 사용하고 "EightSeverityLevels"로 설정하여 출력에서 8개 값(0,1,2,3,4,5,6,7)을 가져올 수 있습니다. 자세한 내용은 텍스트 콘텐츠 심각도 수준 정의 참조할 수 있습니다.
- [0,1] -> 0
- [2,3] -> 2
- [4,5] -> 4
- [6,7] -> 6
이미지: 이미지 모델의 현재 버전은 전체 0-7 심각도 크기 조정 트리밍된 버전을 지원합니다. 분류자는 심각도 0, 2, 4 및 6만 반환합니다. 인접한 두 수준 각각은 단일 수준에 매핑됩니다. 자세한 내용은 이미지 콘텐츠 심각도 수준 정의 참조할 수 있습니다.
- [0,1] -> 0
- [2,3] -> 2
- [4,5] -> 4
- [6,7] -> 6
텍스트 차단 목록 관리
텍스트 차단 목록을 관리하기 위해 지원되는 작업은 다음과 같습니다.
- 차단 목록 만들기 또는 수정
- 모든 차단 목록 나열
- blocklistName으로 차단 목록 가져오기
- 차단 목록에 blockItems 추가
- 차단 목록에서 blockItems 제거
- blocklistName을 사용하여 차단 목록의 모든 blockItems 나열
- blockItemId 및 blocklistName을 사용하여 차단 목록에 blockItem 가져오기
- 차단 목록 및 해당 blockItems를 모두 삭제합니다.
텍스트를 분석할 때 사용하려는 차단 목록을 설정한 다음 반환된 응답에서 차단 목록 일치 결과를 가져올 수 있습니다.
예제
다음 섹션에서는 TypeScript 및 javaScript 가장 일반적인 콘텐츠 보호 서비스 작업 중 일부를 다루는 몇 가지 코드 조각을 제공합니다.
텍스트 분석
차단 목록 없이 텍스트 분석
import { DefaultAzureCredential } from "@azure/identity";
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const credential = new DefaultAzureCredential();
const client = ContentSafetyClient(endpoint, credential);
const text = "This is a sample text";
const analyzeTextOption = { text: text };
const analyzeTextParameters = { body: analyzeTextOption };
const result = await client.path("/text:analyze").post(analyzeTextParameters);
if (isUnexpected(result)) {
throw result;
}
for (let i = 0; i < result.body.categoriesAnalysis.length; i++) {
const textCategoriesAnalysisOutput = result.body.categoriesAnalysis[i];
console.log(
textCategoriesAnalysisOutput.category,
" severity: ",
textCategoriesAnalysisOutput.severity,
);
}
차단 목록을 사용하여 텍스트 분석
import { DefaultAzureCredential } from "@azure/identity";
import ContentSafetyClient, {
CreateOrUpdateTextBlocklistParameters,
isUnexpected,
} from "@azure-rest/ai-content-safety";
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const credential = new DefaultAzureCredential();
const client = ContentSafetyClient(endpoint, credential);
async function createOrUpdateTextBlocklist() {
const blocklistName = "TestBlocklist";
const blocklistDescription = "Test blocklist management.";
const createOrUpdateTextBlocklistParameters: 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 function addBlockItems() {
const blocklistName = "TestBlocklist";
const blockItemText1 = "sample";
const blockItemText2 = "text";
const addOrUpdateBlocklistItemsParameters = {
body: {
blocklistItems: [
{
description: "Test block item 1",
text: blockItemText1,
},
{
description: "Test block item 2",
text: blockItemText2,
},
],
},
};
const result = await client
.path("/text/blocklists/{blocklistName}:addOrUpdateBlocklistItems", blocklistName)
.post(addOrUpdateBlocklistItemsParameters);
if (isUnexpected(result)) {
throw result;
}
console.log("Block items added: ");
if (result.body.blocklistItems) {
for (const blockItem of result.body.blocklistItems) {
console.log(
"BlockItemId: ",
blockItem.blocklistItemId,
", Text: ",
blockItem.text,
", Description: ",
blockItem.description,
);
}
}
}
async function analyzeTextWithBlocklists() {
const blocklistName = "TestBlocklist";
const inputText = "This is a sample to test text with blocklist.";
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,
", BlockItemId: ",
blocklistMatchResult.blocklistItemId,
", BlockItemText: ",
blocklistMatchResult.blocklistItemText,
);
}
}
}
try {
await createOrUpdateTextBlocklist();
await addBlockItems();
await analyzeTextWithBlocklists();
} catch (err) {
console.error("The sample encountered an error:", err);
}
이미지 분석
import { DefaultAzureCredential } from "@azure/identity";
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";
import { readFileSync } from "node:fs";
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const credential = new DefaultAzureCredential();
const client = ContentSafetyClient(endpoint, credential);
const image_path = "./samples-dev/example-data/image.png";
const imageBuffer = readFileSync(image_path);
const base64Image = imageBuffer.toString("base64");
const analyzeImageOption = { image: { content: base64Image } };
const analyzeImageParameters = { body: analyzeImageOption };
const result = await client.path("/image:analyze").post(analyzeImageParameters);
if (isUnexpected(result)) {
throw result;
}
for (let i = 0; i < result.body.categoriesAnalysis.length; i++) {
const imageCategoriesAnalysisOutput = result.body.categoriesAnalysis[i];
console.log(
imageCategoriesAnalysisOutput.category,
" severity: ",
imageCategoriesAnalysisOutput.severity,
);
}
텍스트 차단 목록 관리
텍스트 차단 목록 만들기 또는 업데이트
import { DefaultAzureCredential } from "@azure/identity";
import ContentSafetyClient, {
CreateOrUpdateTextBlocklistParameters,
isUnexpected,
} from "@azure-rest/ai-content-safety";
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const credential = new DefaultAzureCredential();
const client = ContentSafetyClient(endpoint, credential);
const blocklistName = "TestBlocklist";
const blocklistDescription = "Test blocklist management.";
const createOrUpdateTextBlocklistParameters: 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,
);
텍스트 차단 목록 나열
import { DefaultAzureCredential } from "@azure/identity";
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const credential = new DefaultAzureCredential();
const client = ContentSafetyClient(endpoint, credential);
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,
);
}
}
텍스트 차단 목록 가져오기
import { DefaultAzureCredential } from "@azure/identity";
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const credential = new DefaultAzureCredential();
const client = ContentSafetyClient(endpoint, credential);
const blocklistName = "TestBlocklist";
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);
텍스트 차단 목록 삭제
import { DefaultAzureCredential } from "@azure/identity";
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const credential = new DefaultAzureCredential();
const client = ContentSafetyClient(endpoint, credential);
const blocklistName = "TestBlocklist";
const result = await client.path("/text/blocklists/{blocklistName}", blocklistName).delete();
if (isUnexpected(result)) {
throw result;
}
console.log("Deleted blocklist: ", blocklistName);
blockItems 추가
import { DefaultAzureCredential } from "@azure/identity";
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const credential = new DefaultAzureCredential();
const client = ContentSafetyClient(endpoint, credential);
const blocklistName = "TestBlocklist";
const blockItemText1 = "sample";
const blockItemText2 = "text";
const addOrUpdateBlocklistItemsParameters = {
body: {
blocklistItems: [
{
description: "Test block item 1",
text: blockItemText1,
},
{
description: "Test block item 2",
text: blockItemText2,
},
],
},
};
const result = await client
.path("/text/blocklists/{blocklistName}:addOrUpdateBlocklistItems", blocklistName)
.post(addOrUpdateBlocklistItemsParameters);
if (isUnexpected(result)) {
throw result;
}
console.log("Block items added: ");
if (result.body.blocklistItems) {
for (const blockItem of result.body.blocklistItems) {
console.log(
"BlockItemId: ",
blockItem.blocklistItemId,
", Text: ",
blockItem.text,
", Description: ",
blockItem.description,
);
}
}
blockItems 나열
import { DefaultAzureCredential } from "@azure/identity";
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const credential = new DefaultAzureCredential();
const client = ContentSafetyClient(endpoint, credential);
const blocklistName = "TestBlocklist";
const result = await client
.path("/text/blocklists/{blocklistName}/blocklistItems", blocklistName)
.get();
if (isUnexpected(result)) {
throw result;
}
console.log("List block items: ");
if (result.body.value) {
for (const blockItem of result.body.value) {
console.log(
"BlockItemId: ",
blockItem.blocklistItemId,
", Text: ",
blockItem.text,
", Description: ",
blockItem.description,
);
}
}
blockItem 가져오기
TypeScript
import { DefaultAzureCredential } from "@azure/identity";
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const credential = new DefaultAzureCredential();
const client = ContentSafetyClient(endpoint, credential);
const blockItemId = "<blockItemId>";
const blocklistName = "TestBlocklist";
const blockItem = await client
.path(
"/text/blocklists/{blocklistName}/blocklistItems/{blocklistItemId}",
blocklistName,
blockItemId,
)
.get();
if (isUnexpected(blockItem)) {
throw blockItem;
}
console.log("Get blockitem: ");
console.log(
"BlockItemId: ",
blockItem.body.blocklistItemId,
", Text: ",
blockItem.body.text,
", Description: ",
blockItem.body.description,
);
blockItems 제거
import { DefaultAzureCredential } from "@azure/identity";
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const credential = new DefaultAzureCredential();
const client = ContentSafetyClient(endpoint, credential);
const blockItemId = "<blockItemId>";
const blocklistName = "TestBlocklist";
const blockItemText = "sample";
const removeBlocklistItemsParameters = {
body: {
blocklistItemIds: [blockItemId],
},
};
const removeBlockItem = await client
.path("/text/blocklists/{blocklistName}:removeBlocklistItems", blocklistName)
.post(removeBlocklistItemsParameters);
if (isUnexpected(removeBlockItem)) {
throw removeBlockItem;
}
console.log("Removed blockItem: ", blockItemText);
문제 해결
로깅
로깅을 사용하도록 설정하면 오류에 대한 유용한 정보를 파악하는 데 도움이 될 수 있습니다. HTTP 요청 및 응답 로그를 보려면 AZURE_LOG_LEVEL 환경 변수를 info설정합니다. 또는 @azure/loggersetLogLevel 호출하여 런타임에 로깅을 사용하도록 설정할 수 있습니다.
import { setLogLevel } from "@azure/logger";
setLogLevel("info");
로그를 사용하도록 설정하는 방법에 대한 자세한 지침은 @azure/로거 패키지 문서확인할 수 있습니다.
다음 단계
추가 설명서
Azure Content Safety에 대한 보다 광범위한 설명서는 learn.microsoft.com Azure AI Content Safety 참조하세요.
기여
이 라이브러리에 기여하려면 기여 가이드 읽어 코드를 빌드하고 테스트하는 방법에 대해 자세히 알아보세요.
Azure SDK for JavaScript