AI Security

LLM Output Validation: Building Reliable AI Apps

Nicu Constantin
••14 min read
#LLM#AI safety#content moderation#output validation#guardrails

Petru Constantin is the founder of DeviDevs and designed the multi-agent platform the company runs on, with guardrails enforced in code. Code examples are written against the OpenAI omni-moderation-latest, sentence-transformers CrossEncoder with cross-encoder/nli-deberta-v3-base, and jsonschema documentation.

LLM Output Validation and Safety Filters: Building Reliable AI Applications

LLM outputs require careful validation before presenting to users or using in downstream systems. This guide covers comprehensive strategies for validating, filtering, and ensuring the safety of AI-generated content.

Content Moderation Pipeline

Multi-Layer Content Filter

# content_moderation.py
from dataclasses import dataclass
from typing import List, Dict, Optional
from enum import Enum
import re
 
from openai import OpenAI
 
class ContentCategory(Enum):
    """Content categories for moderation."""
    SAFE = "safe"
    HATE_SPEECH = "hate_speech"
    VIOLENCE = "violence"
    SEXUAL = "sexual"
    SELF_HARM = "self_harm"
    HARASSMENT = "harassment"
    DANGEROUS = "dangerous"
    MISINFORMATION = "misinformation"
 
class ModerationAction(Enum):
    """Actions for moderated content."""
    ALLOW = "allow"
    WARN = "warn"
    BLOCK = "block"
    REVIEW = "review"
 
@dataclass
class ModerationResult:
    """Result of content moderation."""
    original_content: str
    filtered_content: Optional[str]  # set only when a redaction changed the text
    categories_detected: List[ContentCategory]
    action: ModerationAction
    confidence: float
    details: Dict
 
class ContentModerator:
    """Multi-layer content moderation system."""
 
    def __init__(self, config: Dict):
        self.config = config
        self.keyword_filter = KeywordFilter(config.get('keyword_lists', {}))
        self.filters = [
            self.keyword_filter,
            SemanticFilter(config.get('semantic', {}))
        ]
 
    def moderate(self, content: str, context: Optional[Dict] = None) -> ModerationResult:
        """Apply all moderation filters to content."""
 
        detected_categories = []
        highest_severity = 0.0
        details = {}
 
        for filter_instance in self.filters:
            result = filter_instance.check(content, context)
            detected_categories.extend(result['categories'])
            highest_severity = max(highest_severity, result['severity'])
            details[filter_instance.name] = result
 
        detected_categories = list(set(detected_categories))
        action = self._determine_action(highest_severity, detected_categories)
 
        filtered_content = None
        if action != ModerationAction.BLOCK:
            redacted = self._apply_filters(content, detected_categories)
            if redacted != content:
                filtered_content = redacted
 
        return ModerationResult(
            original_content=content,
            filtered_content=filtered_content,
            categories_detected=detected_categories,
            action=action,
            confidence=highest_severity,
            details=details
        )
 
    def _determine_action(
        self,
        severity: float,
        categories: List[ContentCategory]
    ) -> ModerationAction:
        """Determine moderation action based on severity and categories."""
 
        # Always block certain categories
        block_categories = {
            ContentCategory.SELF_HARM,
            ContentCategory.DANGEROUS
        }
 
        if any(cat in block_categories for cat in categories):
            return ModerationAction.BLOCK
 
        if severity >= 0.9:
            return ModerationAction.BLOCK
        elif severity >= 0.7:
            return ModerationAction.REVIEW
        elif severity >= 0.5:
            return ModerationAction.WARN
 
        return ModerationAction.ALLOW
 
    def _apply_filters(
        self,
        content: str,
        categories: List[ContentCategory]
    ) -> str:
        """Redact keyword matches for the detected categories."""
 
        filtered = content
        for category in categories:
            pattern = self.keyword_filter.patterns.get(category.value)
            if pattern:
                filtered = pattern.sub("[removed]", filtered)
        return filtered
 
 
class KeywordFilter:
    """Filter based on keyword lists, keyed by ContentCategory value."""
 
    name = "keyword_filter"
 
    def __init__(self, keyword_lists: Dict[str, List[str]]):
        self.keyword_lists = keyword_lists
        self._compile_patterns()
 
    def _compile_patterns(self):
        """Compile keyword patterns for efficient matching."""
        self.patterns = {}
        for category, keywords in self.keyword_lists.items():
            if not keywords:
                continue  # an empty alternation would match everywhere
            pattern = '|'.join(re.escape(kw) for kw in keywords)
            self.patterns[category] = re.compile(pattern, re.IGNORECASE)
 
    def check(self, content: str, context: Optional[Dict] = None) -> Dict:
        """Check content against keyword lists."""
        categories = []
        max_severity = 0.0
 
        for category, pattern in self.patterns.items():
            matches = pattern.findall(content)
            if matches:
                categories.append(ContentCategory(category))
                # Severity based on number of matches
                severity = min(len(matches) * 0.2, 1.0)
                max_severity = max(max_severity, severity)
 
        return {
            'categories': categories,
            'severity': max_severity
        }
 
 
# OpenAI moderation categories mapped to ours
OPENAI_CATEGORY_MAP = {
    'harassment': ContentCategory.HARASSMENT,
    'harassment/threatening': ContentCategory.HARASSMENT,
    'hate': ContentCategory.HATE_SPEECH,
    'hate/threatening': ContentCategory.HATE_SPEECH,
    'illicit': ContentCategory.DANGEROUS,
    'illicit/violent': ContentCategory.DANGEROUS,
    'self-harm': ContentCategory.SELF_HARM,
    'self-harm/intent': ContentCategory.SELF_HARM,
    'self-harm/instructions': ContentCategory.SELF_HARM,
    'sexual': ContentCategory.SEXUAL,
    'sexual/minors': ContentCategory.SEXUAL,
    'violence': ContentCategory.VIOLENCE,
    'violence/graphic': ContentCategory.VIOLENCE,
}
 
 
class SemanticFilter:
    """Classifier-based filter using the OpenAI moderation endpoint.
 
    The text is sent to a third party: check that this fits your data
    processing terms before sending user content.
    """
 
    name = "semantic_filter"
 
    def __init__(self, config: Optional[Dict] = None):
        config = config or {}
        self.enabled = config.get('enabled', True)
        self.model = config.get('model', 'omni-moderation-latest')
        self.category_threshold = config.get('category_threshold', 0.5)
        self.client = OpenAI() if self.enabled else None  # reads OPENAI_API_KEY
 
    def check(self, content: str, context: Optional[Dict] = None) -> Dict:
        if not self.enabled:
            return {'categories': [], 'severity': 0.0, 'skipped': True}
 
        result = self.client.moderations.create(model=self.model, input=content).results[0]
        scores = result.category_scores.model_dump(by_alias=True)
 
        categories, severity = set(), 0.0
        for name, score in scores.items():
            category = OPENAI_CATEGORY_MAP.get(name)
            if category is None or score is None:
                continue
            severity = max(severity, score)
            if score >= self.category_threshold:
                categories.add(category)
 
        return {
            'categories': list(categories),
            'severity': severity,
            'flagged': result.flagged
        }

Hallucination Detection

Fact Verification System

# hallucination_detection.py
import re
from dataclasses import dataclass
from enum import Enum
from typing import Dict, List, Optional
 
from sentence_transformers import CrossEncoder
 
# Output order of cross-encoder/nli-deberta-v3-base, from its model card
NLI_LABELS = ['contradiction', 'entailment', 'neutral']
 
class VerificationStatus(Enum):
    VERIFIED = "verified"          # entailed by at least one source passage
    CONTRADICTED = "contradicted"  # contradicted by a source passage, none entails it
    UNVERIFIED = "unverified"      # no source passage entails or contradicts it
 
@dataclass
class VerificationResult:
    claim: str
    status: VerificationStatus
    passage: Optional[str]
    logit: float
 
class HallucinationDetector:
    """Grounding check: is each sentence of the answer supported by the sources?
 
    It catches answers that drift from the documents you gave the model (RAG).
    It cannot judge facts that are not in the sources, so without source
    documents it reports 'not_checked' instead of inventing a score.
    """
 
    def __init__(self, config: Dict):
        self.model = CrossEncoder(config.get('nli_model', 'cross-encoder/nli-deberta-v3-base'))
        self.min_claim_chars = config.get('min_claim_chars', 20)
        self.passage_sentences = config.get('passage_sentences', 3)
 
    def analyze(
        self,
        llm_output: str,
        context: Optional[str] = None,
        source_documents: Optional[List[str]] = None
    ) -> Dict:
        claims = [s for s in self._sentences(llm_output) if len(s) >= self.min_claim_chars]
        if not source_documents or not claims:
            return {
                'status': 'not_checked',
                'claims': claims,
                'verifications': [],
                'hallucination_score': None,
                'recommendation': 'No source documents or claims: grounding not checked'
            }
 
        passages = [p for doc in source_documents for p in self._passages(doc)]
        verifications = [self._verify(claim, passages) for claim in claims]
 
        contradicted = sum(v.status == VerificationStatus.CONTRADICTED for v in verifications)
        unverified = sum(v.status == VerificationStatus.UNVERIFIED for v in verifications)
        score = min(1.0, (contradicted + 0.5 * unverified) / len(verifications))
 
        return {
            'status': 'checked',
            'claims': claims,
            'verifications': verifications,
            'hallucination_score': score,
            'recommendation': self._get_recommendation(score)
        }
 
    def _verify(self, claim: str, passages: List[str]) -> VerificationResult:
        # Premise = source passage, hypothesis = claim
        scores = self.model.predict([(passage, claim) for passage in passages])
        labels = [NLI_LABELS[i] for i in scores.argmax(axis=1)]
        entail_idx = NLI_LABELS.index('entailment')
        contra_idx = NLI_LABELS.index('contradiction')
 
        entailed = [i for i, label in enumerate(labels) if label == 'entailment']
        if entailed:
            best = max(entailed, key=lambda i: scores[i][entail_idx])
            return VerificationResult(claim, VerificationStatus.VERIFIED,
                                      passages[best], float(scores[best][entail_idx]))
 
        contradicted = [i for i, label in enumerate(labels) if label == 'contradiction']
        if contradicted:
            best = max(contradicted, key=lambda i: scores[i][contra_idx])
            return VerificationResult(claim, VerificationStatus.CONTRADICTED,
                                      passages[best], float(scores[best][contra_idx]))
 
        return VerificationResult(claim, VerificationStatus.UNVERIFIED, None, 0.0)
 
    def _sentences(self, text: str) -> List[str]:
        return [s.strip() for s in re.split(r'(?<=[.!?])\s+', text) if s.strip()]
 
    def _passages(self, document: str) -> List[str]:
        sentences = self._sentences(document)
        step = self.passage_sentences
        return [' '.join(sentences[i:i + step]) for i in range(0, len(sentences), step)]
 
    def _get_recommendation(self, score: float) -> str:
        if score < 0.2:
            return "Answer is grounded in the sources"
        elif score < 0.4:
            return "Minor concerns - consider verification"
        elif score < 0.6:
            return "Significant concerns - verification recommended"
        elif score < 0.8:
            return "High risk of ungrounded content - manual review required"
        else:
            return "Mostly ungrounded or contradicted - do not use without verification"

PII Detection and Filtering

PII Filter Implementation

# pii_filter.py
import re
from dataclasses import dataclass
from typing import List, Dict, Optional
from enum import Enum
 
# US-centric regexes for illustration. They miss many formats (names, addresses,
# national IDs outside the US) and overlap with each other; for production use a
# maintained detector such as Microsoft Presidio plus validators for your country.
 
class PIIType(Enum):
    """Types of Personally Identifiable Information."""
    EMAIL = "email"
    PHONE = "phone"
    SSN = "ssn"
    CREDIT_CARD = "credit_card"
    ADDRESS = "address"
    NAME = "name"
    DATE_OF_BIRTH = "date_of_birth"
    IP_ADDRESS = "ip_address"
    MEDICAL_ID = "medical_id"
    PASSPORT = "passport"
    DRIVERS_LICENSE = "drivers_license"
    BANK_ACCOUNT = "bank_account"
 
@dataclass
class PIIDetection:
    """Detected PII instance."""
    pii_type: PIIType
    value: str
    start_position: int
    end_position: int
    confidence: float
    redacted_value: str
 
class PIIFilter:
    """Filter PII from LLM outputs."""
 
    def __init__(self, config: Optional[Dict] = None):
        self.config = config or {}
        self.patterns = self._compile_patterns()
 
    def _compile_patterns(self) -> Dict[PIIType, re.Pattern]:
        """Compile regex patterns for PII detection."""
 
        return {
            PIIType.EMAIL: re.compile(
                r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b'
            ),
            PIIType.PHONE: re.compile(
                r'\b(?:\+?1[-.\s]?)?\(?[0-9]{3}\)?[-.\s]?[0-9]{3}[-.\s]?[0-9]{4}\b'
            ),
            PIIType.SSN: re.compile(
                r'\b\d{3}[-\s]?\d{2}[-\s]?\d{4}\b'
            ),
            PIIType.CREDIT_CARD: re.compile(
                r'\b(?:\d{4}[-\s]?){3}\d{4}\b'
            ),
            PIIType.IP_ADDRESS: re.compile(
                r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b'
            ),
            PIIType.DATE_OF_BIRTH: re.compile(
                r'\b(?:DOB|Date of Birth|born)[:\s]*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})\b',
                re.IGNORECASE
            ),
            PIIType.PASSPORT: re.compile(
                r'\b[A-Z]{1,2}\d{6,9}\b'
            ),
            PIIType.BANK_ACCOUNT: re.compile(
                r'\b\d{8,17}\b'  # Bank account numbers vary by country
            )
        }
 
    def detect(self, text: str) -> List[PIIDetection]:
        """Detect PII in text; overlapping matches keep the most confident one."""
 
        detections = []
 
        for pii_type, pattern in self.patterns.items():
            for match in pattern.finditer(text):
                detection = PIIDetection(
                    pii_type=pii_type,
                    value=match.group(),
                    start_position=match.start(),
                    end_position=match.end(),
                    confidence=self._calculate_confidence(pii_type, match.group()),
                    redacted_value=self._redact(pii_type, match.group())
                )
                detections.append(detection)
 
        return self._resolve_overlaps(detections)
 
    def _resolve_overlaps(self, detections: List[PIIDetection]) -> List[PIIDetection]:
        """Keep non-overlapping spans, preferring higher confidence, then longer spans."""
        ranked = sorted(detections, key=lambda d: (-d.confidence,
                                                   -(d.end_position - d.start_position)))
        kept = []
        for d in ranked:
            if all(d.end_position <= k.start_position or d.start_position >= k.end_position
                   for k in kept):
                kept.append(d)
        return sorted(kept, key=lambda d: d.start_position)
 
    def filter(self, text: str, redaction_style: str = "mask") -> str:
        """Filter PII from text."""
 
        detections = self.detect(text)
 
        # Apply redactions from end to start to preserve positions
        filtered_text = text
        for detection in reversed(detections):
            if redaction_style == "mask":
                replacement = detection.redacted_value
            elif redaction_style == "remove":
                replacement = "[REDACTED]"
            elif redaction_style == "type_label":
                replacement = f"[{detection.pii_type.value.upper()}]"
            else:
                replacement = detection.redacted_value
 
            filtered_text = (
                filtered_text[:detection.start_position] +
                replacement +
                filtered_text[detection.end_position:]
            )
 
        return filtered_text
 
    def _calculate_confidence(self, pii_type: PIIType, value: str) -> float:
        """Calculate confidence score for PII detection."""
 
        # Base confidence from pattern match
        confidence = 0.7
 
        if pii_type == PIIType.EMAIL:
            confidence = 0.9
 
        elif pii_type == PIIType.SSN:
            confidence = 0.9 if self._is_valid_ssn(value) else 0.6
 
        elif pii_type == PIIType.CREDIT_CARD:
            # Luhn check separates card numbers from random digit runs
            confidence = 0.95 if self._luhn_check(value) else 0.5
 
        elif pii_type == PIIType.BANK_ACCOUNT:
            confidence = 0.4  # any 8-17 digit run matches, so lowest priority
 
        return confidence
 
    def _redact(self, pii_type: PIIType, value: str) -> str:
        """Create redacted version of PII value."""
 
        if pii_type == PIIType.EMAIL:
            parts = value.split('@')
            return parts[0][:2] + '***@' + parts[1]
 
        elif pii_type == PIIType.PHONE:
            clean = re.sub(r'[^\d]', '', value)
            return '***-***-' + clean[-4:]
 
        elif pii_type == PIIType.SSN:
            return 'XXX-XX-' + value[-4:]
 
        elif pii_type == PIIType.CREDIT_CARD:
            return 'XXXX-XXXX-XXXX-' + value[-4:]
 
        elif pii_type == PIIType.IP_ADDRESS:
            parts = value.split('.')
            return f"{parts[0]}.XXX.XXX.XXX"
 
        else:
            # Generic redaction
            if len(value) > 4:
                return value[:2] + '*' * (len(value) - 4) + value[-2:]
            return '*' * len(value)
 
    def _is_valid_ssn(self, value: str) -> bool:
        """Validate SSN format."""
        clean = re.sub(r'[^\d]', '', value)
        if len(clean) != 9:
            return False
 
        # Area numbers 000, 666 and 900-999 are not issued
        area = clean[:3]
        if area == '000' or area == '666' or int(area) >= 900:
            return False
 
        return True
 
    def _luhn_check(self, card_number: str) -> bool:
        """Validate credit card using Luhn algorithm."""
 
        clean = re.sub(r'[^\d]', '', card_number)
        if len(clean) < 13 or len(clean) > 19:
            return False
 
        digits = [int(d) for d in clean]
        checksum = 0
 
        for i, digit in enumerate(reversed(digits)):
            if i % 2 == 1:
                digit *= 2
                if digit > 9:
                    digit -= 9
            checksum += digit
 
        return checksum % 10 == 0

Structured Output Enforcement

JSON Schema Validation

# structured_output.py
import json
import re
from dataclasses import dataclass
from typing import Dict, List, Optional
from enum import Enum
 
import jsonschema
 
class OutputFormat(Enum):
    """Supported output formats."""
    JSON = "json"
    MARKDOWN = "markdown"
    HTML = "html"
    PLAIN_TEXT = "plain_text"
 
@dataclass
class ValidationResult:
    """Result of output validation."""
    valid: bool
    errors: List[str]
    fixed_output: Optional[str]
    original_output: str
 
class StructuredOutputValidator:
    """Validate and enforce structured LLM outputs.
 
    Auto-fix only repairs formatting (code fences, trailing commas) and fills
    fields for which the schema declares a default. It never invents values:
    a missing price must fail, not become 0.
    """
 
    def __init__(self):
        self.validators = {}
 
    def register_schema(self, name: str, schema: Dict):
        """Register a JSON schema for validation."""
        jsonschema.Draft7Validator.check_schema(schema)
        self.validators[name] = jsonschema.Draft7Validator(schema)
 
    def validate_json(
        self,
        output: str,
        schema_name: str,
        auto_fix: bool = True
    ) -> ValidationResult:
        """Validate JSON output against schema."""
 
        validator = self.validators.get(schema_name)
        if not validator:
            return ValidationResult(
                valid=False,
                errors=[f"Schema '{schema_name}' not found"],
                fixed_output=None,
                original_output=output
            )
 
        # Try to parse JSON
        try:
            data = json.loads(output)
        except json.JSONDecodeError as e:
            if auto_fix:
                fixed = self._attempt_json_fix(output)
                if fixed:
                    result = self.validate_json(fixed, schema_name, auto_fix=False)
                    result.original_output = output
                    if result.valid:
                        result.fixed_output = fixed
                    return result
 
            return ValidationResult(
                valid=False,
                errors=[f"Invalid JSON: {str(e)}"],
                fixed_output=None,
                original_output=output
            )
 
        # Validate against schema
        errors = list(validator.iter_errors(data))
 
        if errors:
            error_messages = [
                f"{list(e.path)}: {e.message}" if e.path else e.message
                for e in errors
            ]
 
            if auto_fix:
                fixed_data = self._attempt_schema_fix(data, errors, validator.schema)
                if fixed_data is not None and not list(validator.iter_errors(fixed_data)):
                    return ValidationResult(
                        valid=True,
                        errors=[],
                        fixed_output=json.dumps(fixed_data, indent=2),
                        original_output=output
                    )
 
            return ValidationResult(
                valid=False,
                errors=error_messages,
                fixed_output=None,
                original_output=output
            )
 
        return ValidationResult(
            valid=True,
            errors=[],
            fixed_output=None,
            original_output=output
        )
 
    def _attempt_json_fix(self, output: str) -> Optional[str]:
        """Repair formatting only: code fences and trailing commas."""
 
        fixed = output.strip()
 
        # Remove markdown code fences
        if fixed.startswith('```'):
            lines = fixed.split('\n')[1:]
            if lines and lines[-1].strip() == '```':
                lines = lines[:-1]
            fixed = '\n'.join(lines)
 
        # Remove trailing commas before a closing bracket
        fixed = re.sub(r',\s*([}\]])', r'\1', fixed)
 
        try:
            json.loads(fixed)
            return fixed
        except json.JSONDecodeError:
            return None
 
    def _attempt_schema_fix(
        self,
        data,
        errors: List,
        schema: Dict
    ) -> Optional[Dict]:
        """Fill missing top-level fields only where the schema declares a default."""
 
        if not isinstance(data, dict):
            return None
 
        fixed_data = dict(data)
        changed = False
 
        for error in errors:
            if error.validator == 'required' and not error.path:
                for prop in error.validator_value:
                    prop_schema = schema.get('properties', {}).get(prop, {})
                    if prop not in fixed_data and 'default' in prop_schema:
                        fixed_data[prop] = prop_schema['default']
                        changed = True
 
        return fixed_data if changed else None
 
 
# Example usage
validator = StructuredOutputValidator()
 
# Register schema for product recommendations
validator.register_schema('product_recommendation', {
    "type": "object",
    "required": ["products", "reasoning"],
    "properties": {
        "products": {
            "type": "array",
            "items": {
                "type": "object",
                "required": ["name", "price", "relevance_score"],
                "properties": {
                    "name": {"type": "string"},
                    "price": {"type": "number", "minimum": 0},
                    "relevance_score": {"type": "number", "minimum": 0, "maximum": 1}
                }
            }
        },
        "reasoning": {"type": "string"},
        "confidence": {"type": "number", "minimum": 0, "maximum": 1}
    }
})

Complete Output Validation Pipeline

# output_pipeline.py
from dataclasses import dataclass
from typing import Dict, List, Optional
 
from content_moderation import ContentModerator, ModerationAction
from hallucination_detection import HallucinationDetector
from pii_filter import PIIFilter
from structured_output import StructuredOutputValidator
 
@dataclass
class PipelineResult:
    """Result of complete validation pipeline."""
    original_output: str
    final_output: str
    passed: bool
    moderation: Dict
    hallucination: Dict
    pii: Dict
    structure: Dict
    applied_fixes: List[str]
 
class OutputValidationPipeline:
    """Complete output validation pipeline."""
 
    def __init__(self, config: Dict):
        self.moderator = ContentModerator(config.get('moderation', {}))
        self.hallucination_detector = HallucinationDetector(config.get('hallucination', {}))
        self.pii_filter = PIIFilter(config.get('pii', {}))
        self.structure_validator = StructuredOutputValidator()
        # True: answers that could not be checked against sources do not pass
        self.require_grounding = config.get('require_grounding', False)
        self.max_hallucination_score = config.get('max_hallucination_score', 0.6)
 
        # Register schemas
        for name, schema in config.get('schemas', {}).items():
            self.structure_validator.register_schema(name, schema)
 
    def process(
        self,
        output: str,
        context: Optional[Dict] = None,
        source_documents: Optional[List[str]] = None,
        expected_schema: Optional[str] = None
    ) -> PipelineResult:
        """Process output through complete validation pipeline."""
 
        applied_fixes = []
        current_output = output
 
        # Step 1: Content moderation
        moderation_result = self.moderator.moderate(current_output, context)
 
        if moderation_result.action == ModerationAction.BLOCK:
            return PipelineResult(
                original_output=output,
                final_output="[Content blocked due to policy violation]",
                passed=False,
                moderation=moderation_result.__dict__,
                hallucination={},
                pii={},
                structure={},
                applied_fixes=[]
            )
 
        if moderation_result.filtered_content:
            current_output = moderation_result.filtered_content
            applied_fixes.append("content_moderation")
 
        # Step 2: PII filtering
        pii_detections = self.pii_filter.detect(current_output)
        if pii_detections:
            current_output = self.pii_filter.filter(current_output)
            applied_fixes.append("pii_filtering")
 
        # Step 3: Grounding check against the sources
        hallucination_result = self.hallucination_detector.analyze(
            current_output,
            context.get('prompt') if context else None,
            source_documents
        )
        score = hallucination_result['hallucination_score']
        if score is None:
            grounding_ok = not self.require_grounding
        else:
            grounding_ok = score < self.max_hallucination_score
 
        # Step 4: Structure validation (if schema specified)
        structure_result = {}
        if expected_schema:
            validation = self.structure_validator.validate_json(
                current_output,
                expected_schema
            )
            structure_result = validation.__dict__
 
            if validation.fixed_output:
                current_output = validation.fixed_output
                applied_fixes.append("structure_fix")
 
        # Determine if output passed
        passed = (
            moderation_result.action in [ModerationAction.ALLOW, ModerationAction.WARN] and
            grounding_ok and
            (not expected_schema or structure_result.get('valid', False))
        )
 
        return PipelineResult(
            original_output=output,
            final_output=current_output,
            passed=passed,
            moderation=moderation_result.__dict__,
            hallucination=hallucination_result,
            pii={'detections': [d.__dict__ for d in pii_detections]},
            structure=structure_result,
            applied_fixes=applied_fixes
        )

Conclusion

Reliable LLM output validation needs several layers of defense:

  1. Content Moderation - Filter harmful or inappropriate content
  2. Hallucination Detection - Verify factual claims against sources
  3. PII Filtering - Protect sensitive personal information
  4. Structure Enforcement - Ensure outputs match expected schemas

Implementing these safeguards ensures your AI applications produce reliable, safe, and trustworthy outputs for end users.


From production

JARVIS, the multi-agent platform DeviDevs runs on Claude Code, validates output at two points: validators for the Romanian personal numeric code (CNP, with its control digit) and for IBANs (mod 97) check outgoing messages, and the same validator runs on commits. Between 7 September and 15 November 2026 the output check made 81 real blocks.

Official references

Related on this site: LLM Agent Security: Mitigating Autonomous AI Risks, LLM Guardrails Implementation: Building Safe AI Applications, LLM Hallucinations: How to Detect and Prevent Them. More articles in the AI Security category, and the engineering work behind them is on the services page.

Need an AI system built and running in production, with the scope agreed in writing and a delivery guarantee? See how a DeviDevs Sprint works →

Want AI agents and automations your business can actually run on?

We ship production AI in fixed two-week sprints, then secure them. Book a 30-minute call to scope yours.

Book a Call

Before you book, you can see what we build, how a sprint works, how our pricing works, what we have already built, or write to us directly.

Weekly AI Agents, Automation & Security Digest

How we build AI agents and automations with Claude Code, plus practical AI security, integrations, and platform notes, delivered weekly.

No spam. Unsubscribe anytime.