Custom Guardrail

Build custom guardrails to validate agent behavior.

Custom Guardrail.

1"""
2Custom Guardrail
3=============================
4
5Custom Guardrail.
6"""
7
8from kern.agent import Agent
9from kern.exceptions import CheckTrigger, InputCheckError
10from kern.guardrails.base import BaseGuardrail
11from kern.models.openai import OpenAIResponses
12
13
14class TopicGuardrail(BaseGuardrail):
15 """Blocks requests that ask for dangerous instructions."""
16
17 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 )
25
26 async def async_check(self, run_input) -> None:
27 self.check(run_input)
28
29
30# ---------------------------------------------------------------------------
31# Create Agent
32# ---------------------------------------------------------------------------
33agent = Agent(
34 name="Guarded Agent",
35 model=OpenAIResponses(id="gpt-5.2"),
36 pre_hooks=[TopicGuardrail()],
37)
38
39# ---------------------------------------------------------------------------
40# Run Agent
41# ---------------------------------------------------------------------------
42if __name__ == "__main__":
43 agent.print_response(
44 "Explain secure password management best practices.", stream=True
45 )

Run the Example

1# Clone and setup repo
2git clone https://github.com/kern-ai/kern.git
3cd kern/cookbook/02_agents/08_guardrails
4
5# Create and activate virtual environment
6./scripts/demo_setup.sh
7source .venvs/demo/bin/activate
8
9python custom_guardrail.py