Custom Guardrail
Build custom guardrails to validate agent behavior.
Custom Guardrail.
1"""2Custom Guardrail3=============================45Custom Guardrail.6"""78from kern.agent import Agent9from kern.exceptions import CheckTrigger, InputCheckError10from kern.guardrails.base import BaseGuardrail11from kern.models.openai import OpenAIResponses121314class TopicGuardrail(BaseGuardrail):15 """Blocks requests that ask for dangerous instructions."""1617 def check(self, run_input) -> None:18 content = (run_input.input_content or "").lower()19 blocked_terms = ["build malware", "phishing template", "exploit"]20 if any(term in content for term in blocked_terms):21 raise InputCheckError(22 "Input contains blocked security-abuse content.",23 check_trigger=CheckTrigger.INPUT_NOT_ALLOWED,24 )2526 async def async_check(self, run_input) -> None:27 self.check(run_input)282930# ---------------------------------------------------------------------------31# Create Agent32# ---------------------------------------------------------------------------33agent = Agent(34 name="Guarded Agent",35 model=OpenAIResponses(id="gpt-5.2"),36 pre_hooks=[TopicGuardrail()],37)3839# ---------------------------------------------------------------------------40# Run Agent41# ---------------------------------------------------------------------------42if __name__ == "__main__":43 agent.print_response(44 "Explain secure password management best practices.", stream=True45 )Run the Example
1# Clone and setup repo2git clone https://github.com/kern-ai/kern.git3cd kern/cookbook/02_agents/08_guardrails45# Create and activate virtual environment6./scripts/demo_setup.sh7source .venvs/demo/bin/activate89python custom_guardrail.py