Apply Guardrail

Run an LLM-backed content check that fails closed on error — block, allow, or raise

apply_guardrail runs a single LLM-backed content check and, since it fails closed by default, blocks content whenever the check itself cannot complete.

python
from praisonaiagents import Agent
from praisonai.capabilities import apply_guardrail

def policy_check(output: str):
    result = apply_guardrail(output, rules=["no_pii", "no_profanity"])
    return (result.passed, output if result.passed else "Blocked by guardrail.")

agent = Agent(
    name="safe-assistant",
    instructions="Draft a customer-facing reply.",
    guardrails=policy_check,
)
agent.start("Write a reply to the customer.")

The agent produces output, the guardrail LLM checks it against your rules, and the content is blocked, allowed, or the error is raised — depending on on_error.

Diagram

Apply Guardrail

passed

violation

check failed

📥 Content

🛡️ LLM check

✅ Allow

⛔ Block

⚠️ on_error

Quick Start

  1. Use it as an agent guardrail

    Wrap apply_guardrail in a validator and pass it to guardrails=.

    python
    from praisonaiagents import Agent
    from praisonai.capabilities import apply_guardrail
    
    def validator(output: str):
        result = apply_guardrail(output, rules=["no_pii"])
        return (result.passed, output)
    
    agent = Agent(
        name="assistant",
        instructions="Answer the user politely.",
        guardrails=validator,
    )
    agent.start("Summarise the account status.")
  2. Call it directly

    Run a one-off check on any string.

    python
    from praisonai.capabilities import apply_guardrail
    
    result = apply_guardrail("Some content", rules=["no_pii", "no_profanity"])
    print(result.passed)
    print(result.violations)
  3. Await the async twin

    Use aapply_guardrail inside an event loop.

    python
    import asyncio
    from praisonai.capabilities import aapply_guardrail
    
    async def main():
        result = await aapply_guardrail("Some content", rules=["no_pii"])
        print(result.passed)
    
    asyncio.run(main())

How It Works

The check runs an LLM against your rules and returns a GuardrailResult. Any failure inside the check is routed through on_error.

Diagram
LLMapply_guardrailCallerLLMapply_guardrailCalleralt[check succeeds][check fails (timeout / bad JSON /bad schema)]apply_guardrail(content, rules=[…])check content against rules{“passed”: bool, …}GuardrailResult(passed=…)on_error → block / allow / raise

Choosing on_error

on_error decides what happens when the check itself cannot produce a valid decision.

Diagram

block default

allow

raise

⚠️ Check failed

on_error

⛔ passed=False

✅ passed=True

💥 exception re-raised

ModeWhen the check failsUse when
"block" (default)passed=False, content blockedSafety matters more than availability
"allow"passed=True, content passesYou prefer availability (old behaviour)
"raise"Underlying exception re-raisedYou want to handle the error yourself

Parameters

ParameterTypeDefaultDescription
contentstr—Content to check
guardrail_namestr"default"Name of the guardrail
rulesList[str]NoneRules to check against (falls back to built-in PII / profanity / harm / misinformation rules)
modelstr"gpt-4o-mini"Model used for the check
timeoutfloat60.0Request timeout in seconds
api_keystrNoneOptional API key override
api_basestrNoneOptional API base URL override
metadataDict[str, Any]NoneMetadata carried onto the result
on_error`”block” \“allow” \“raise”`"block"What to do when the check fails

aapply_guardrail takes the same parameters and returns the same GuardrailResult.


GuardrailResult

Both functions return a GuardrailResult.

FieldTypeDescription
passedboolWhether the content passed the check
violationsList[Dict[str, Any]]Violations found, or [{"reason": "guardrail_unavailable", "error": "..."}] when the check failed
modified_contentstrCleaned content, if the model returned one
original_contentstrThe content that was checked
guardrail_namestrName passed in guardrail_name
metadataDict[str, Any]Your metadata; on failure also carries "error" and "on_error" keys

Common Patterns

Restore the old permissive behaviour

python
from praisonai.capabilities import apply_guardrail

result = apply_guardrail("Some content", rules=["no_pii"], on_error="allow")

Handle the error yourself

python
from praisonai.capabilities import apply_guardrail

try:
    result = apply_guardrail("Some content", on_error="raise")
except Exception as exc:
    print(f"Guardrail check failed: {exc}")

Compose with an agent

python
from praisonaiagents import Agent
from praisonai.capabilities import apply_guardrail

def validator(output: str):
    result = apply_guardrail(output, rules=["no_pii", "no_harmful_content"])
    return (result.passed, output)

agent = Agent(name="assistant", instructions="Help the user.", guardrails=validator)
agent.start("Draft a reply.")

Best Practices

Keep the fail-closed default in production

The "block" default protects you when the check LLM is rate-limited or returns malformed output. Only switch to "allow" when availability outranks safety for that specific check.

Pass explicit rules

Naming your rules (rules=["no_pii", "no_profanity"]) gives the check LLM a clear contract. With no rules, the built-in PII / profanity / harm / misinformation set is used.

Use the async twin inside event loops

Call aapply_guardrail from async code so the check does not block the event loop. Use the sync apply_guardrail from plain scripts.

Inspect violations on block

When blocked, read result.violations — a failed check surfaces {"reason": "guardrail_unavailable", "error": "..."} so you can tell a policy violation apart from an outage.


Related