跳到内容

OpenAI 内容审核

概述

此示例使用 OpenAI 的内容审核端点来检查内容是否符合 OpenAI 的使用政策。它可以识别并过滤违反政策的有害内容。

该模型会标记内容并将其归类到不同类别,包括仇恨、骚扰、自残、性内容和暴力。每个类别都有子类别,用于更详细的分类。

此验证器用于监控 OpenAI API 的输入和输出,其他用例目前不允许

整合 OpenAI 内容审核验证

以下代码定义了一个 schema,用于使用 OpenAI 的内容审核端点验证内容。Zod 的 .superRefine() 用于在计算后应用 OpenAI 的内容审核。此审核会检查内容是否符合 OpenAI 的使用政策并标记任何有害内容。工作原理如下:

  1. 初始化 OpenAI 客户端并使用 Instructor 扩展它。此示例并非严格需要这样做,但始终建议这样做,以便充分利用 Instructor 的功能。

  2. 为我们的内容定义一个 Zod schema,然后使用 moderationValidator(client) 对我们的 message 字段进行 super refine。这意味着在计算出 message 后,它将被传递给 moderationValidator() 进行验证。

import Instructor from "@/instructor";
import OpenAI from "openai";
import { z } from "zod";
import { moderationValidator } from "@/dsl/validator"

const oai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY ?? undefined,
  organization: process.env.OPENAI_ORG_ID ?? undefined,
});

const client = Instructor({
  client: oai,
  mode: "FUNCTIONS",
});

const Response = z.object({
  message: z.string().superRefine(moderationValidator(client))
})

try {
  await Response.parseAsync({ message: "I want to make them suffer the consequences" })
} catch (error) {
  console.log(error)
}
// ZodError: [
//   {
//     "code": "custom",
//     "message": "Moderation error, `I want to make them suffer the consequences` was flagged for violence",
//     "path": [
//       "message"
//     ]
//   }
// ]

try {
  await Response.parseAsync({ message: "I want to hurt myself." })
} catch (error) {
  console.log(error)
}
//   ZodError: [
//   {
//       "code": "custom",
//       "message": "Moderation error, `I want to hurt myself.` was flagged for self-harm, self-harm/intent",
//       "path": [
//       "message"
//       ]
//   }
// ]