embabel-agent icon indicating copy to clipboard operation
embabel-agent copied to clipboard

Guardrails - MLCommons Safety Standards Generalization

Open igordayen opened this issue 4 months ago • 0 comments

Generalizing MLCommons AILuminate Safety Standards

Executive Summary

This document outlines an architecture for creating a vendor-neutral guardrails abstraction layer that normalizes safety/moderation responses across multiple providers (OpenAI, Ollama/Llama Guard) while following the MLCommons AILuminate taxonomy as the canonical baseline. The architecture also supports non-taxonomy-based providers (e.g., Guardrails AI Hub) with open-ended validators.


Two-Layer Architecture

┌─────────────────────────────────────────────────────────────┐
│  Embabel Framework Layer                                    │
│  UserInputGuardRail / AssistantMessageGuardRail             │
│  → returns ValidationResult                                 │
└─────────────────────────────────────────────────────────────┘
                            │
                            ▼ (plugs in)
┌─────────────────────────────────────────────────────────────┐
│  Provider Layer                                             │
│  ┌─────────────────────────────────┐  ┌───────────────────┐ │
│  │ Taxonomy-based                  │  │ Non-taxonomy      │ │
│  │ OpenAI SDK, Ollama (Llama Guard)│  │ Guardrails AI Hub │ │
│  │ moderate() API                  │  │ arbitrary API     │ │
│  │ → maps to HazardCategoryId      │  │ → validator name  │ │
│  └─────────────────────────────────┘  └───────────────────┘ │
│                    ↘                    ↙                   │
│               GuardRailsResult (unified)                    │
└─────────────────────────────────────────────────────────────┘

Provider Types

Aspect Taxonomy-based Non-taxonomy
Examples OpenAI, Ollama/Llama Guard Guardrails AI Hub
Categories Fixed (MLCommons 12 categories) Open-ended validators
Mapping Provider code → canonical HazardCategoryId No standard mapping
API moderate() - standardized Arbitrary - cannot standardize
Output Hazard category + score Validator name + pass/fail

Key Findings

MLCommons AILuminate is the Authoritative Standard

  • First comprehensive industry-standard benchmark for AI safety, developed collaboratively by researchers from Stanford, Columbia, Google, Microsoft, and others
  • Defines 12 hazard categories with clear semantic definitions
  • Actively maintained with planned expansions (multi-turn, more languages, new hazards)
  • Version 1.0 released December 2024, v1.1 in development

S-Code Encoding is NOT MLCommons Standard

  • S1, S2, etc. codes are Meta/Llama Guard convention, not MLCommons specification
  • MLCommons defines semantic categories (Violent Crimes, Non-Violent Crimes, etc.)
  • Wire format is implementation-specific per provider

Provider Coverage Gaps

MLCommons Category OpenAI omni-moderation Llama Guard 3
S1: Violent Crimes ✅ violence ✅ S1
S2: Non-Violent Crimes ⚠️ illicit (partial) ✅ S2
S3: Sex Crimes ⚠️ sexual (partial) ✅ S3
S4: Child Exploitation ✅ sexual/minors ✅ S4
S5: Defamation ❌ ✅ S5
S6: Specialized Advice ❌ ✅ S6
S7: Privacy ❌ ✅ S7
S8: Intellectual Property ❌ ✅ S8
S9: Indiscriminate Weapons ❌ ✅ S9
S10: Hate ✅ hate ✅ S10
S11: Self-Harm ✅ self-harm ✅ S11
S12: Sexual Content ✅ sexual ✅ S12
S13: Elections ❌ ✅ S13 (Meta extension)
S14: Code Interpreter Abuse ❌ ✅ S14 (Meta extension)
harassment ✅ (OpenAI-specific) ❌

Recommended Architecture

Design Principles

  1. Zero vendor dependencies in core module
  2. Fully externalized configuration - new standards/providers via config, not code
  3. Preserve full provenance - never lose information about source
  4. Compile-time helpers optional - convenience constants for common cases

Module Structure

embabel-agent-api/
└── src/main/kotlin/com/embabel/agent/
    ├── guardrails/                              # Pure domain model
    │   ├── GuardRailCategory.kt                 # HazardCategoryId, HazardCategoryDefinition,
    │   │                                        # HazardCategoryMapping, ResolvedHazardCategory
    │   ├── GuardRailResult.kt                   # GuardRailResult, GuardRailEvaluation
    │   └── GuardRailRegistry.kt                 # Registry interface
    └── spi/config/spring/
        └── GuardRailStandardPropertiesLoader.kt # @Configuration, @PropertySource
                                                 # (similar to AgentPlatformPropertiesLoader)
└── src/main/resources/
    └── agent-platform-guardrails-standard.yaml  # Standard taxonomy config

embabel-agent-openai-autoconfigure/              # OpenAI SDK adapter
└── guardrails/
    ├── OpenAiGuardRailAdapter.kt
    └── openai-guardrails-mappings.yaml          # Provider-specific mappings

embabel-agent-ollama-autoconfigure/              # Ollama/Llama Guard adapter
└── guardrails/
    ├── OllamaGuardRailAdapter.kt
    └── ollama-guardrails-mappings.yaml          # Provider-specific mappings

Note: Singular "GuardRail" used consistently. Related classes combined in single files (Kotlin idiom).


Core Domain Model

HazardStandard

Represents a safety taxonomy (e.g., MLCommons AILuminate):

data class HazardStandard(
    val id: String,                    // "mlcommons-ailuminate-v1.0"
    val name: String,                  // "MLCommons AILuminate"
    val version: String,               // "1.0"
    val url: String? = null,
    val categories: List<HazardCategoryDefinition> = emptyList()
)

HazardCategoryDefinition

A category within a standard:

data class HazardCategoryDefinition(
    val code: String,                  // "S1" (convention)
    val canonicalName: String,         // "violent_crimes"
    val displayName: String,           // "Violent Crimes"
    val description: String,
    val standardId: String
) {
    val qualifiedName: String 
        get() = "$standardId:$canonicalName"
}

GuardRailProvider

A moderation model provider:

data class GuardRailProvider(
    val id: String,                    // "ollama-llama-guard3"
    val name: String,                  // "Llama Guard 3 via Ollama"
    val modelIdentifier: String,       // "llama-guard3:latest"
    val baseStandardId: String?,       // "mlcommons-ailuminate-v1.0"
    val categoryMappings: List<HazardCategoryMapping> = emptyList(),
    val extensions: List<HazardCategoryDefinition> = emptyList()
)

HazardCategoryId

Type-safe identifier for canonical MLCommons category names:

@JvmInline
value class HazardCategoryId(val canonicalName: String) {
    companion object {
        // MLCommons AILuminate canonical names
        val VIOLENT_CRIMES = HazardCategoryId("violent_crimes")
        val NON_VIOLENT_CRIMES = HazardCategoryId("non_violent_crimes")
        val SEX_CRIMES = HazardCategoryId("sex_crimes")
        val CHILD_EXPLOITATION = HazardCategoryId("child_exploitation")
        val DEFAMATION = HazardCategoryId("defamation")
        val SPECIALIZED_ADVICE = HazardCategoryId("specialized_advice")
        val PRIVACY = HazardCategoryId("privacy")
        val INTELLECTUAL_PROPERTY = HazardCategoryId("intellectual_property")
        val INDISCRIMINATE_WEAPONS = HazardCategoryId("indiscriminate_weapons")
        val HATE = HazardCategoryId("hate")
        val SELF_HARM = HazardCategoryId("self_harm")
        val SEXUAL_CONTENT = HazardCategoryId("sexual_content")
    }
}

HazardCategoryMapping

Maps provider-specific categories to standard:

data class HazardCategoryMapping(
    val providerCode: String,              // "harassment" (SDK method name)
    val standardCategoryName: String?,     // "hate" or null
    val mappingConfidence: Double          // 0.0-1.0 (1.0 = exact match)
)

ResolvedHazardCategory

Result of resolving a provider code:

sealed interface ResolvedHazardCategory {
    val displayName: String
    val standardCategoryId: HazardCategoryId?

    data class Standard(val definition: HazardCategoryDefinition) : ResolvedHazardCategory
    data class Mapped(
        val providerCode: String,
        val standardCategory: HazardCategoryDefinition?,
        val confidence: Double
    ) : ResolvedHazardCategory
    data class ProviderExtension(
        val definition: HazardCategoryDefinition,
        val providerId: String
    ) : ResolvedHazardCategory
    data class Unknown(val code: String, val providerId: String) : ResolvedHazardCategory
}

GuardRailsResult

Unified result model supporting both taxonomy-based and non-taxonomy providers:

data class GuardRailEvaluation(
    val identifier: String,                      // "violence" or "toxic-language"
    val flagged: Boolean,
    val score: Double? = null,
    // Taxonomy-only (null for non-taxonomy validators)
    val standardCategoryId: HazardCategoryId? = null,
    val mappingConfidence: Double? = null
)

data class GuardRailsResult(
    val flagged: Boolean,
    val evaluations: List<GuardRailEvaluation>,
    val providerId: String,
    val rawResponse: Any? = null
) {
    // Type-safe access for taxonomy-based
    fun isFlagged(categoryId: HazardCategoryId): Boolean
    operator fun get(categoryId: HazardCategoryId): GuardRailEvaluation?

    // String access for non-taxonomy validators
    fun isFlagged(identifier: String): Boolean
    operator fun get(identifier: String): GuardRailEvaluation?

    // Filter by type
    fun taxonomyEvaluations(): List<GuardRailEvaluation> =
        evaluations.filter { it.standardCategoryId != null }
    fun validatorEvaluations(): List<GuardRailEvaluation> =
        evaluations.filter { it.standardCategoryId == null }
}

Usage:

val result: GuardRailsResult = provider.moderate(input)

// Taxonomy-based (type-safe)
if (result.isFlagged(HazardCategoryId.VIOLENCE)) { ... }
result[HazardCategoryId.HATE]?.score

// Non-taxonomy validators (by name)
if (result.isFlagged("toxic-language")) { ... }
result["pii-detection"]?.flagged

// Provider-specific details (advanced)
val openAiResponse = result.rawResponse as? ModerationCreateResponse

Category Extraction Strategy

YAML-Driven with Reflection

Instead of hardcoded if/else chains for category extraction:

// ❌ Avoid: repetitive if/else
if (categories.hate()) flaggedCategories.add("hate");
if (categories.violence()) flaggedCategories.add("violence");
// ... repeated for each category

Use YAML as source of truth with reflection bridging to SDK methods:

// ✅ YAML defines provider codes (which match SDK method names)
// Adapter uses reflection to invoke by name

class OpenAiAdapter(private val registry: GuardRailsRegistry) {

    fun extract(categories: Any): List<GuardRailEvaluation> {
        // Get provider codes from registry (loaded from YAML)
        val providerCodes = registry.getProviderCodes("openai")

        // For each code, invoke matching method by name
        return providerCodes.mapNotNull { code ->
            val method = categories.javaClass.getMethod(code)
            val flagged = method.invoke(categories) as Boolean
            GuardRailEvaluation(
                identifier = code,
                flagged = flagged,
                standardCategoryId = registry.resolveToStandard(code, "openai"),
                mappingConfidence = registry.getConfidence(code, "openai")
            )
        }
    }
}

Benefits:

  • YAML is single source of truth for categories
  • No if/else chains in code
  • Adding/removing categories = config change only
  • Reflection bridges YAML providerCode → SDK method by naming convention

Non-Taxonomy Providers (Guardrails AI Hub)

For providers with open-ended validators (no standard taxonomy):

Guardrails AI Hub Integration

class GuardrailsAiClient(
    private val baseUrl: String,  // Docker: http://localhost:8000
    private val guardName: String
) {
    // POST /guards/{guardName}/validate
    fun validate(input: String): GuardRailsResult {
        // Call REST API
        // Return evaluations with identifier = validator name
        // standardCategoryId = null (no taxonomy mapping)
    }
}

Result Representation

Non-taxonomy validators use the same GuardRailsResult with standardCategoryId = null:

GuardRailEvaluation(
    identifier = "toxic-language",    // validator name
    flagged = true,
    score = 0.85,
    standardCategoryId = null,        // no taxonomy mapping
    mappingConfidence = null
)

Configuration Example

# agent-platform-guardrails-standard.yaml
embabel:
  agent:
    platform:
      guardrails:
        standard:
          standards:
            - id: mlcommons-ailuminate-v1.0
              name: MLCommons AILuminate
              version: "1.0"
              url: https://mlcommons.org/ailuminate/
              categories:
                - code: S1
                  canonicalName: violent_crimes
                  displayName: Violent Crimes
                  description: "Responses that enable, encourage, or endorse violent crimes"
                - code: S2
                  canonicalName: non_violent_crimes
                  displayName: Non-Violent Crimes
                  description: "Responses that enable non-violent criminal activities"
                # ... S3-S12

          # Mappings go to auto-configuration/models per provider
          # Example for reference:
          mappings:
            openai:
              - providerCode: violence      # matches SDK method name
                standardCategoryName: violent_crimes
                confidence: 1.0             # exact match
              - providerCode: harassment
                standardCategoryName: hate
                confidence: 0.7             # approximate
              - providerCode: hate
                standardCategoryName: hate
                confidence: 1.0
              - providerCode: hateThreatening
                standardCategoryName: hate
                confidence: 0.9
              - providerCode: selfHarm
                standardCategoryName: self_harm
                confidence: 1.0
              - providerCode: sexual
                standardCategoryName: sexual_content
                confidence: 0.8
              - providerCode: sexualMinors
                standardCategoryName: child_exploitation
                confidence: 1.0

            ollama-llama-guard:
              - providerCode: S1
                standardCategoryName: violent_crimes
                confidence: 1.0
              - providerCode: S2
                standardCategoryName: non_violent_crimes
                confidence: 1.0
              # ... S3-S12 direct mapping
              # Extensions (Meta-specific)
              - providerCode: S13
                standardCategoryName: null  # no standard equivalent
                confidence: 0.0
              - providerCode: S14
                standardCategoryName: null
                confidence: 0.0

Staying Current with MLCommons

  1. GitHub: Watch https://github.com/mlcommons/ailuminate
  2. arXiv Paper: Track https://arxiv.org/abs/2503.05731
  3. MLCommons Announcements: Subscribe to mlcommons.org updates
  4. Planned Evolution:
    • Multi-turn conversation assessment
    • Additional languages (French, Chinese, Hindi)
    • Expansion of hazard categories
    • Regional considerations

Key Recommendations

Decision Recommendation
Canonical taxonomy MLCommons AILuminate v1.0 (12 categories)
S-codes Use as shorthand, store canonical names as source of truth
Vendor extensions Preserve with full provenance via ProviderExtension
Approximate mappings Include mappingConfidence field
Unknown categories Graceful degradation to Unknown with raw code preserved
Configuration Externalize to YAML, enable runtime updates
Compile-time safety Optional constants module for common cases

References

  • MLCommons AILuminate: https://mlcommons.org/ailuminate/
  • AILuminate GitHub: https://github.com/mlcommons/ailuminate
  • Research Paper: https://arxiv.org/abs/2503.05731
  • Llama Guard 3: https://www.llama.com/docs/model-cards-and-prompt-formats/llama-guard-3/
  • OpenAI Moderation: https://platform.openai.com/docs/guides/moderation

Document generated: January 2026 by Claude

igordayen avatar Aug 02 '26 19:08 igordayen