All files moderation-client.js

98.52% Statements 134/136
85.71% Branches 12/14
100% Functions 7/7
98.52% Lines 134/136

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 1371x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 21x 21x 21x 21x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 3x 1x 1x 1x 1x 1x 2x 2x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 2x 2x 2x 2x 2x 2x 2x 4x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     2x 1x 1x 1x  
"use strict";
import { jailbreak } from "@openai/guardrails";
import OpenAI from "openai";
 
const JAILBREAK_MODEL = "gpt-5.6";
const JAILBREAK_MAX_TURNS = 10;
 
/**
 * OpenAI moderation client wrapper.
 *
 * @class
 */
class ModerationClient {
  /**
   * Initializes a new moderation client.
   *
   * @param {string} moderationApiKey - OpenAI API key used for the moderation endpoint.
   */
  constructor(moderationApiKey) {
    this.openAI = new OpenAI({
      apiKey: moderationApiKey,
    });
  }
 
  /**
   * Create the OpenAI client adapter used by LLM-based guardrails.
   *
   * OpenAI Guardrails currently adds a temperature to GPT-5 requests. GPT-5.6
   * uses reasoning by default and does not accept that parameter, so the
   * adapter removes it before forwarding the request.
   *
   * @returns {object} OpenAI-compatible client for guardrail execution.
   */
  _createGuardrailLlm() {
    return {
      baseURL: this.openAI.baseURL,
      chat: {
        completions: {
          create: (params) => {
            params = { ...params };
            delete params.temperature;
            return this.openAI.chat.completions.create(params);
          },
        },
      },
    };
  }
 
  /**
   * Convert OpenAI and guardrail execution failures to a consistent error.
   *
   * @param {unknown} error - Error raised by OpenAI or OpenAI Guardrails.
   * @returns {Error} Normalized error.
   */
  _normalizeOpenAIError(error) {
    if (error instanceof OpenAI.APIError) {
      return new Error(
        `An OpenAI error has occurred: ${error.status} ${error.type} ${error.code} ${error.message}`,
        { cause: error },
      );
    }
 
    const message =
      error instanceof Error ? error.message : String(error || "Unknown error");
    return new Error(
      `An OpenAI error has occurred: ${message.replace(/^Error:\s*/, "")}`,
      { cause: error },
    );
  }
 
  /**
   * Use OpenAI Guardrails to detect a jailbreak attempt.
   *
   * @param {string} message - Message text to inspect.
   * @param {number} [minimumJailbreakConfidenceScore=0.7] - Minimum confidence required to flag the message.
   * @param {object[]} [conversationHistory=[]] - Recent conversation messages.
   * @returns {Promise<boolean>} True when the jailbreak tripwire is triggered.
   */
  async detectJailbreakAttempt(
    message,
    minimumJailbreakConfidenceScore = 0.7,
    conversationHistory = [],
  ) {
    try {
      const result = await jailbreak(
        {
          guardrailLlm: this._createGuardrailLlm(),
          getConversationHistory: () => conversationHistory,
        },
        message,
        {
          model: JAILBREAK_MODEL,
          confidence_threshold: minimumJailbreakConfidenceScore,
          include_reasoning: false,
          max_turns: JAILBREAK_MAX_TURNS,
        },
      );
 
      if (result.executionFailed) {
        throw result.originalException;
      }
 
      return result.tripwireTriggered;
    } catch (error) {
      throw this._normalizeOpenAIError(error);
    }
  }
 
  /**
   * Use OpenAI's moderation API to check if the message violates content policy.
   *
   * @param {string} message - Message text to moderate.
   * @returns {Promise<object>} Moderation result object.
   */
  async moderate(message) {
    try {
      const moderation = await this.openAI.moderations.create({
        input: message,
      });
      const result = moderation.results[0];
      return {
        flagged: result.flagged,
        categories: result.categories,
        category_scores: result.category_scores,
        message: message,
      };
    } catch (error) {
      if (error instanceof OpenAI.APIError) {
        throw this._normalizeOpenAIError(error);
      }
      throw error;
    }
  }
}
 
export { ModerationClient as default };