使用 OpenAI Moderation API 过滤有害内容,并给出错误提示

解读

在国内真实业务场景里,面试官想考察的不仅是“调一个接口”这么简单,而是:

  1. 合规意识:境外 API 调用需走企业备案通道,数据不得出境,必须做本地缓存/脱敏。
  2. 鲁棒性:OpenAI 接口超时、限流、返回格式变动、国内网络抖动都要兜底。
  3. 性能:高并发场景下不能每次请求都同步调用 Moderation,需要本地布隆过滤器+缓存+异步队列。
  4. 可观测:错误提示要区分“用户内容违规”与“系统异常”,同时打点到 Prometheus,方便告警。
  5. 可扩展:后续可能接入百度内容审核、阿里云绿网,需要策略模式一键切换。

知识点

  • 境外 API 合规调用:企业 VPN、固定出口 IP、HTTPS 代理、请求头脱敏。
  • 缓存策略:Redis + BloomFilter 预过滤,TTL 按业务等级 5~30 min。
  • 重试与熔断:async-retry + opossum,失败率 50% 或连续 5 次错误即熔断 30 s。
  • 错误码设计:业务层 40001 内容违规、40002 系统繁忙、50001 第三方异常。
  • 日志规范:使用 pino,输出 traceId、uid、原始文本哈希(脱敏)、耗时、响应码。
  • 框架集成:NestJS 自定义 Guard + Pipe,把审核逻辑前置到 Controller 层,失败直接抛 422。
  • 单测:nock 模拟网络异常、msw 模拟返回违规字段,覆盖 200/429/500 全场景。
  • 性能压测: autocannon 1w qps,p99 审核延迟 < 120 ms,本地缓存命中率 > 85%。

答案

// src/moderation/moderation.service.ts
import { Injectable, HttpException, HttpStatus, Logger } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { firstValueFrom } from 'rxjs';
import { CacheService } from '../cache/cache.service';
import { ConfigService } from '@nestjs/config';
import * as crypto from 'crypto';

@Injectable()
export class ModerationService {
  private readonly logger = new Logger(ModerationService.name);
  private readonly OPENAI_URL = 'https://api.openai.com/v1/moderations';
  constructor(
    private readonly http: HttpService,
    private readonly cache: CacheService,
    private readonly cfg: ConfigService,
  ) {}

  /** 对外唯一入口 */
  async check(text: string, uid: string): Promise<void> {
    if (!text) return;
    const hash = crypto.createHash('sha256').update(text).digest('hex');
    const cached = await this.cache.get(`mod:${hash}`);
    if (cached === '1') return; // 已审核通过
    if (cached === '0') {
      throw new HttpException(
        { code: 40001, message: '输入内容涉嫌违规' },
        HttpStatus.UNPROCESSABLE_ENTITY,
      );
    }

    try {
      const res = await firstValueFrom(
        this.http.post(
          this.OPENAI_URL,
          { input: text },
          {
            headers: {
              Authorization: `Bearer ${this.cfg.get('OPENAI_KEY')}`,
              'Content-Type': 'application/json',
            },
            timeout: 3000,
            httpsAgent: this.cfg.get('HTTPS_PROXY'), // 企业代理
          },
        ),
      );
      const flagged = res.data.results?.[0]?.flagged;
      if (flagged) {
        await this.cache.set(`mod:${hash}`, '0', 600);
        throw new HttpException(
          { code: 40001, message: '输入内容涉嫌违规' },
          HttpStatus.UNPROCESSABLE_ENTITY,
        );
      }
      await this.cache.set(`mod:${hash}`, '1', 600);
    } catch (err) {
      // 网络/限流/格式错误统一走兜底
      this.logger.error({ uid, err: err.message });
      throw new HttpException(
        { code: 40002, message: '内容审核服务繁忙,请稍后重试' },
        HttpStatus.SERVICE_UNAVAILABLE,
      );
    }
  }
}

// src/moderation/moderation.guard.ts
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { ModerationService } from './moderation.service';

@Injectable()
export class ModerationGuard implements CanActivate {
  constructor(private mod: ModerationService) {}
  async canActivate(ctx: ExecutionContext): Promise<boolean> {
    const req = ctx.switchToHttp().getRequest();
    const body = req.body;
    const text = body.content || body.text || body.message || '';
    await this.mod.check(text, req.user?.uid || '0');
    return true;
  }
}

// 使用
@Post('comment')
@UseGuards(ModerationGuard)
async createComment(@Body() dto: CreateCommentDto) {
  // 走到这里说明已通过审核
  return this.commentService.save(dto);
}

拓展思考

  1. 多租户场景下,不同客户对“违规”定义不同,可引入策略链:先走本地关键词,再走 OpenAI,最后走客户自定义正则,全部可配置化。
  2. 若政策要求数据不出境,可训练轻量中文模型(如基于 bert-base-chinese)部署在内部 TFServing,与 OpenAI 结果做 diff 持续校正,逐步降低对外依赖。
  3. 对 UGC 场景,可前置“机审+人审”双通道:机审失败直接拒绝,机审通过但置信度低(0.6~0.8)的进入 Kafka 队列,由人工审核员在 5 min 内二次确认,避免误杀。
  4. 审核结果可作为特征存入用户画像,后续风控系统对“多次违规”用户提升验证码难度或限制发帖频率,实现内容安全与用户安全的闭环。