Skip to content

Enforcement

Enforcement is the core mechanism by which Guardrails enforce safety policies. When a guardrail detects a violation, it triggers enforcement. By default, enforcement is suppressed (results are returned instead of raising exceptions).

How Enforcement Works

  1. Automatic Execution: Guardrails run on every API call
  2. Enforcement Detection: Violations trigger enforcement
  3. Default Behavior: Enforcement is suppressed (results returned, no exceptions raised)
  4. Custom Handling: Set suppress_enforcement=False to raise exceptions on violations

Default Behavior: Non-Blocking

Enforcement is suppressed by default (returns results instead of raising exceptions):

Python

from pathlib import Path
from mendguardrails import MendGuardrailsAsyncOpenAI, GuardrailEnforcementTriggered

client = MendGuardrailsAsyncOpenAI(config=Path("guardrails_config.json"))

# To raise exceptions on violations, set suppress_enforcement=False
try:
    response = await client.responses.create(
        model="gpt-5",
        input="Tell me a secret",
        suppress_enforcement=False  # Raises exception on violations
    )
    print(response.output_text)

except GuardrailEnforcementTriggered as exc:
    print(f"Guardrail triggered: {exc.guardrail_result.info}")

Enabling Enforcement Exceptions

To raise exceptions on violations, set suppress_enforcement=False:

Python

# By default, suppress_enforcement=True, so violations don't raise exceptions
response = await client.responses.create(
    model="gpt-5",
    input="Tell me a secret"
)

# Check guardrail results
for result in response.guardrail_results.all_results:
    if result.enforcement_triggered:
        print(f"Guardrail '{result.info.get('guardrail_name')}' triggered!")

To raise exceptions on violations instead:

response = await client.responses.create(
    model="gpt-5",
    input="Tell me a secret",
    suppress_enforcement=False  # Raises GuardrailEnforcementTriggered on violations
)

Enforcement Results

The GuardrailEnforcementTriggered exception contains:

  • enforcement_triggered (bool): Always True
  • info (dict): Guardrail-specific information

Python

except GuardrailEnforcementTriggered as exc:
    result = exc.guardrail_result
    guardrail_name = result.info.get('guardrail_name')
    stage = result.info.get('stage_name')

Next Steps