Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 33 additions & 2 deletions sdk/python/src/openlit/guard/moderation.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from __future__ import annotations

import re
from typing import List, Optional
from typing import List, Optional, Tuple

from openlit.guard._base import Guard, GuardPhase, GuardResult

Expand Down Expand Up @@ -41,12 +41,43 @@
re.compile(r"\b(?:i(?:'ll| will)\s+(?:kill|hurt|destroy)\s+you)\b", re.IGNORECASE),
]

# Single alternation of the toxicity patterns, used only for redaction. The
# per-pattern list above is kept intact so classification/score detection
# retains its existing semantics.
_TOXICITY_RE = re.compile(
"|".join(f"(?:{pattern.pattern})" for pattern in _TOXICITY_PATTERNS),
re.IGNORECASE,
)


def _build_profanity_pattern(words: List[str]) -> re.Pattern:
escaped = [re.escape(w) for w in words]
return re.compile(r"\b(?:" + "|".join(escaped) + r")\b", re.IGNORECASE)


def _redact_spans(text: str, profanity_re: re.Pattern) -> str:
spans: List[Tuple[int, int, str]] = []
for match in _TOXICITY_RE.finditer(text):
spans.append((match.start(), match.end(), "[REDACTED:toxicity]"))

toxic_spans = [(start, end) for start, end, _ in spans]
for match in profanity_re.finditer(text):
start, end = match.span()
if any(start < toxic_end and end > toxic_start for toxic_start, toxic_end in toxic_spans):
continue
spans.append((start, end, "[REDACTED:profanity]"))

spans.sort(key=lambda span: span[0])
parts: List[str] = []
cursor = 0
for start, end, replacement in spans:
parts.append(text[cursor:start])
parts.append(replacement)
cursor = end
parts.append(text[cursor:])
return "".join(parts)


class Moderation(Guard):
"""
Detects profanity and toxic language.
Expand Down Expand Up @@ -90,7 +121,7 @@ def evaluate(self, text: str) -> GuardResult:

transformed: Optional[str] = None
if self._action.value == "redact":
transformed = self._profanity_re.sub("[REDACTED:profanity]", text)
transformed = _redact_spans(text, self._profanity_re)

return GuardResult(
action=self._action,
Expand Down
86 changes: 86 additions & 0 deletions sdk/python/tests/test_guard_pipeline.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
"""Tests for the Pipeline guard engine."""

from typing import List

import pytest

from openlit.guard._base import (
Guard,
GuardAction,
GuardPhase,
GuardResult,
)
from openlit.guard._pipeline import Pipeline
from openlit.guard.pii import PII
Expand All @@ -14,6 +17,21 @@
from openlit.guard.schema import Schema


class RecordingGuard(Guard):
"""Records each evaluated string so tests can inspect downstream input."""

name = "recorder"
phases = (GuardPhase.PREFLIGHT,)

def __init__(self, seen: List[str]) -> None:
super().__init__(action="allow")
self._seen = seen

def evaluate(self, text: str) -> GuardResult:
self._seen.append(text)
return GuardResult(guard_name=self.name)


class TestPipelineBasics:
"""Core pipeline behaviour: ordering, allow/deny, redaction chaining."""

Expand Down Expand Up @@ -197,3 +215,71 @@ def test_latency_recorded(self):
pipeline = Pipeline(guards=[PII(action="deny")])
result = pipeline.evaluate("[email protected]", phase="preflight")
assert result.results[0].latency_ms >= 0


class TestModerationRedaction:
"""Redact must replace every flagged span, not just profanity."""

def test_toxicity_is_redacted(self):
"""Toxicity-only text is redacted and the toxic phrase is removed."""
result = Moderation(action="redact").evaluate("kill yourself")

assert result.action == GuardAction.REDACT
assert result.classification == "toxicity"
assert result.score == 0.95
assert result.transformed_text is not None
assert "[REDACTED:toxicity]" in result.transformed_text
assert "kill yourself" not in result.transformed_text.lower()

def test_profanity_redaction_still_works(self):
"""Profanity-only redaction keeps its existing placeholder."""
result = Moderation(action="redact").evaluate("what the damn hell")

assert result.action == GuardAction.REDACT
assert result.transformed_text is not None
assert "[REDACTED:profanity]" in result.transformed_text
assert "damn" not in result.transformed_text.lower()

def test_clean_text_unchanged(self):
"""Clean text is allowed with no transformation."""
result = Moderation(action="redact").evaluate("Hello world")

assert result.action == GuardAction.ALLOW
assert result.transformed_text is None
assert result.classification == ""

def test_pipeline_forwards_redacted_toxicity(self):
"""The pipeline no longer forwards toxic text to later guards."""
pipeline = Pipeline(guards=[Moderation(action="redact")])
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
result = pipeline.evaluate("kill yourself", phase="preflight")

assert result.action == GuardAction.REDACT
assert result.transformed_text is not None
assert "[REDACTED:toxicity]" in result.transformed_text
assert "kill yourself" not in result.transformed_text.lower()

def test_overlapping_custom_word_does_not_break_toxicity_redaction(self):
"""A custom word inside a toxic phrase cannot expose the rest of it."""
result = Moderation(action="redact", custom_words=["I'll"]).evaluate("I'll kill you")

assert result.classification == "profanity, toxicity"
assert result.transformed_text == "[REDACTED:toxicity]"
assert "kill you" not in result.transformed_text

def test_long_input_keeps_unscanned_suffix(self):
"""A capped scan does not truncate the text returned to callers."""
text = "kill yourself and more text"
result = Moderation(action="redact", max_scan_length=20).run(text, GuardPhase.PREFLIGHT)

assert result.transformed_text == "[REDACTED:toxicity] and more text"

def test_later_guard_receives_redacted_toxicity(self):
"""Downstream guards see the placeholder instead of the original phrase."""
seen: List[str] = []
pipeline = Pipeline(
guards=[Moderation(action="redact"), RecordingGuard(seen)],
fail_open=False,
)
pipeline.evaluate("kill yourself", phase="preflight")

assert seen == ["[REDACTED:toxicity]"]
18 changes: 18 additions & 0 deletions sdk/typescript/src/guard/__tests__/pipeline.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,24 @@ describe('Pipeline', () => {
expect(result.transformedText).toContain('[REDACTED:ssn]');
});

it('redacts toxicity in TypeScript moderation', () => {
const result = new Moderation({ action: 'redact' }).evaluate('kill yourself');
expect(result.transformedText).toBe('[REDACTED:toxicity]');
});

it('keeps toxicity priority when a custom word overlaps it', () => {
const result = new Moderation({ action: 'redact', customWords: ["I'll"] }).evaluate(
"I'll kill you",
);
expect(result.transformedText).toBe('[REDACTED:toxicity]');
});

it('preserves the unscanned suffix after toxicity redaction', () => {
const guard = new Moderation({ action: 'redact', maxScanLength: 20 });
const result = guard.run('kill yourself and more text', GuardPhase.PREFLIGHT);
expect(result.transformedText).toBe('[REDACTED:toxicity] and more text');
});

it('fails a deny guard closed even under failOpen (deny guards never fail open)', () => {
const pipeline = new Pipeline({
guards: [new ThrowingGuard()], // action: 'deny'
Expand Down
41 changes: 40 additions & 1 deletion sdk/typescript/src/guard/moderation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,45 @@ const TOXICITY_PATTERNS: RegExp[] = [
/\b(?:i(?:'ll| will)\s+(?:kill|hurt|destroy)\s+you)\b/i,
];

const TOXICITY_REDACTION_SOURCE = TOXICITY_PATTERNS.map(
(pattern) => `(?:${pattern.source})`,
).join('|');

interface RedactionSpan {
start: number;
end: number;
replacement: string;
}

function redactModeration(text: string, profanityRe: RegExp): string {
const spans: RedactionSpan[] = [];
const toxicityRe = new RegExp(TOXICITY_REDACTION_SOURCE, 'gi');
for (const match of text.matchAll(toxicityRe)) {
const start = match.index ?? 0;
spans.push({ start, end: start + match[0].length, replacement: '[REDACTED:toxicity]' });
}

const toxicSpans = spans.map(({ start, end }) => ({ start, end }));
const customRe = new RegExp(profanityRe.source, 'gi');
for (const match of text.matchAll(customRe)) {
const start = match.index ?? 0;
const end = start + match[0].length;
const overlapsToxicity = toxicSpans.some((span) => start < span.end && end > span.start);
if (!overlapsToxicity) {
spans.push({ start, end, replacement: '[REDACTED:profanity]' });
}
}

spans.sort((a, b) => a.start - b.start);
let transformed = '';
let cursor = 0;
for (const span of spans) {
transformed += text.slice(cursor, span.start) + span.replacement;
cursor = span.end;
}
return transformed + text.slice(cursor);
}

function buildProfanityPattern(words: string[]): RegExp {
const escaped = words.map((w) => w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
return new RegExp('\\b(?:' + escaped.join('|') + ')\\b', 'gi');
Expand Down Expand Up @@ -57,7 +96,7 @@ export class Moderation extends Guard {

let transformedText: string | null = null;
if (this._action === 'redact') {
transformedText = text.replace(this._profanityRe, '[REDACTED:profanity]');
transformedText = redactModeration(text, this._profanityRe);
}

return makeGuardResult({
Expand Down
Loading