
关于
使用可自定义屏蔽列表分析文本和图像中的有害内容。
name: azure-ai-contentsafety-ts description: "使用可自定义的屏蔽列表分析文本和图片中的有害内容。" risk: unknown source: community date_added: "2026-02-27"
Azure AI内容安全 REST SDK(TypeScript)
使用可自定义的屏蔽列表分析文本和图片中的有害内容。
安装
npm install @azure-rest/ai-content-safety @azure/identity @azure/core-auth
环境变量
CONTENT_SAFETY_ENDPOINT=https://<resource>.cognitiveservices.azure.com
CONTENT_SAFETY_KEY=<api-key>
认证
重要:这是一个REST客户端。ContentSafetyClient 是一个函数,不是类。
API密钥
import ContentSafetyClient from "@azure-rest/ai-content-safety";
import { AzureKeyCredential } from "@azure/core-auth";
const client = ContentSafetyClient(
process.env.CONTENT_SAFETY_ENDPOINT!,
new AzureKeyCredential(process.env.CONTENT_SAFETY_KEY!)
);
DefaultAzureCredential
import ContentSafetyClient from "@azure-rest/ai-content-safety";
import { DefaultAzureCredential } from "@azure/identity";
const client = ContentSafetyClient(
process.env.CONTENT_SAFETY_ENDPOINT!,
new DefaultAzureCredential()
);
分析文本
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";
const result = await client.path("/text:analyze").post({
body: {
text: "Text content to analyze",
categories: ["Hate", "Sexual", "Violence", "SelfHarm"],
outputType: "FourSeverityLevels" // or "EightSeverityLevels"
}
});
if (isUnexpected(result)) {
throw result.body;
}
for (const analysis of result.body.categoriesAnalysis) {
console.log(`${analysis.category}: severity ${analysis.severity}`);
}
分析图片
Base64内容
import { readFileSync } from "node:fs";
const imageBuffer = readFileSync("./image.png");
const base64Image = imageBuffer.toString("base64");
const result = await client.path("/image:analyze").post({
body: {
image: { content: base64Image }
}
});
if (isUnexpected(result)) {
throw result.body;
}
for (const analysis of result.body.categoriesAnalysis) {
console.log(`${analysis.category}: severity ${analysis.severity}`);
}
Blob URL
const result = await client.path("/image:analyze").post({
body: {
image: { blobUrl: "https://storage.blob.core.windows.net/container/image.png" }
}
});
屏蔽列表管理
创建屏蔽列表
const result = await client.path("/text/blocklists/{blocklistName}", "MyBlocklist").patch({
contentType: "application/merge-patch+json",
body: { description: "自定义屏蔽列表" }
});
添加屏蔽项
const result = await client.path("/text/blocklists/{blocklistName}:addOrUpdateBlocklistItems", "MyBlocklist").post({
body: {
blocklistItems: [
{ description: "有害词1", text: "harmful_word_1" },
{ description: "有害词2", text: "harmful_word_2" }
]
}
});
使用屏蔽列表分析
const result = await client.path("/text:analyze").post({
body: {
text: "要分析的文本",
blocklistNames: ["MyBlocklist"],
haltOnBlocklistHit: true
}
});
兼容工具
Claude CodeCursor
标签
后端开发
