Skip to main content
from praisonaiagents import Agent

agent = Agent(name="safe-assistant", instructions="Be helpful and stay within policy.")
agent.start("Draft a customer-facing reply")
Guardrails validate agent output against your criteria and automatically retry if the output fails. The user sends a prompt; guardrails validate input and output before the agent responds or calls tools.

Quick Start

1

Simple Usage

Pass a validation function to an agent:
from praisonaiagents import Agent

def validate_length(output):
    word_count = len(output.raw.split())
    if word_count < 100:
        return False, f"Too short: {word_count} words (need 100+)"
    return True, output

agent = Agent(
    name="Writer",
    instructions="Write detailed articles",
    guardrails=validate_length
)

result = agent.start("Write about renewable energy")
2

With Configuration

Use GuardrailConfig for LLM-based validation with retry settings:
from praisonaiagents import Agent, GuardrailConfig

agent = Agent(
    name="Writer",
    instructions="Write professional articles",
    guardrails=GuardrailConfig(
        llm_validator="Ensure the response is professional, accurate, and at least 150 words",
        max_retries=3,
        on_fail="retry",
    )
)

result = agent.start("Write about machine learning trends")

Which Validator Should I Use?

Pick a validator strategy based on how you need to check the output.

How It Works

Guardrails work identically in sync (.start(), .chat()) and async (.astart(), .achat()) execution paths.

Configuration Options

GuardrailConfig SDK Reference

Full parameter reference for GuardrailConfig
Precedence ladder — choose the level you need:
# Level 1: Callable (function validator)
agent = Agent(guardrails=my_validator_fn)

# Level 2: String (natural language criteria)
agent = Agent(guardrails="Ensure response is professional and helpful")

# Level 3: List (policy strings)
agent = Agent(guardrails=["policy:strict", "pii:redact"])

# Level 4: GuardrailConfig (full control)
agent = Agent(guardrails=GuardrailConfig(
    validator=my_validator_fn,
    max_retries=3,
    on_fail="retry",
))
from praisonaiagents import Agent, GuardrailConfig

agent = Agent(
    instructions="...",
    guardrails=GuardrailConfig(
        validator=my_function,
        llm_validator="Natural language validation criteria",
        max_retries=3,
        on_fail="retry",
    )
)
OptionTypeDefaultDescription
validatorCallable | NoneNoneFunction (output) -> (bool, Any) for programmatic validation
llm_validatorstr | NoneNoneNatural language criteria for LLM-based validation
max_retriesint3Maximum retry attempts on validation failure
on_failstr"retry"Action on failure: "retry", "skip", or "raise"
policiesList[str][]Policy strings like ["policy:strict", "pii:redact"]

Common Patterns

Function-Based Validation

from praisonaiagents import Agent

def validate_json(output):
    import json
    try:
        json.loads(output.raw)
        return True, output
    except json.JSONDecodeError as e:
        return False, f"Invalid JSON: {e}"

agent = Agent(
    name="DataAgent",
    instructions="Always respond with valid JSON",
    guardrails=validate_json
)

result = agent.start("Give me a list of 3 fruits as JSON")

Natural Language Validation

from praisonaiagents import Agent

agent = Agent(
    name="Writer",
    instructions="Write product descriptions",
    guardrails="Must be professional, 100-200 words, include a call to action, and contain no pricing"
)

result = agent.start("Write a description for our premium coffee mug")

Multi-Agent with Guardrails

from praisonaiagents import Agent, Task, PraisonAIAgents

def check_accuracy(output):
    if "estimate" in output.raw.lower() or "approximately" in output.raw.lower():
        return False, "Response must use exact values, not estimates"
    return True, output

researcher = Agent(name="Researcher", instructions="Research and provide exact facts")
writer = Agent(name="Writer", instructions="Write clear summaries")

task1 = Task(
    description="Find the population of Tokyo",
    agent=researcher,
    guardrails=check_accuracy,
    expected_output="Exact population figure"
)
task2 = Task(
    description="Write a summary using the research",
    agent=writer,
    expected_output="One-paragraph summary"
)

agents = PraisonAIAgents(agents=[researcher, writer], tasks=[task1, task2])
result = agents.start()

Best Practices

Vague guardrails like “be good” are hard to enforce. Use concrete criteria: “must be between 100 and 200 words” or “must contain a JSON array”.
When validating JSON, code, or data formats, use a function validator. LLM validators are slower and better suited for qualitative criteria like tone or completeness.
The (False, "reason") message is passed back to the agent as feedback. Make it actionable — tell the agent exactly what to fix.
Start with max_retries=2. Increasing retries adds latency and cost. If the agent fails repeatedly, the validator criteria or instructions may need refinement.

Approval

Add human-in-the-loop approval steps

Hooks

Intercept and modify agent behavior at lifecycle points

Gateway Self-Lifecycle Guard

Block agent commands that would stop or restart this gateway