Pii Detection
Example demonstrating how to use PII detection guardrails with Kern Agent.
1"""2Pii Detection3=============================45Example demonstrating how to use PII detection guardrails with Kern Agent.6"""78import asyncio910from kern.agent import Agent11from kern.exceptions import InputCheckError12from kern.guardrails import PIIDetectionGuardrail13from kern.models.openai import OpenAIResponses141516# ---------------------------------------------------------------------------17# Create Agent18# ---------------------------------------------------------------------------19async def main():20 """Demonstrate PII detection guardrails functionality."""21 print("PII Detection Guardrails Demo")22 print("=" * 50)2324 # Create an agent with PII detection protection25 agent = Agent(26 name="Privacy-Protected Agent",27 model=OpenAIResponses(id="gpt-5-mini"),28 pre_hooks=[PIIDetectionGuardrail()],29 description="An agent that helps with customer service while protecting privacy.",30 instructions="You are a helpful customer service assistant. Always protect user privacy and handle sensitive information appropriately.",31 )3233 # Test 1: Normal request without PII (should work)34 print("\n[TEST 1] Normal request without PII")35 print("-" * 30)36 try:37 agent.print_response(38 input="Can you help me understand your return policy?",39 )40 print("[OK] Normal request processed successfully")41 except InputCheckError as e:42 print(f"[ERROR] Unexpected error: {e}")4344 # Test 2: Request with SSN (should be blocked)45 print("\n[TEST 2] Input containing SSN")46 print("-" * 30)47 try:48 agent.print_response(49 input="Hi, my Social Security Number is 123-45-6789. Can you help me with my account?",50 )51 print("[WARNING] This should have been blocked!")52 except InputCheckError as e:53 print(f"[BLOCKED] PII blocked: {e.message}")54 print(f" Trigger: {e.check_trigger}")5556 # Test 3: Request with credit card (should be blocked)57 print("\n[TEST 3] Input containing credit card")58 print("-" * 30)59 try:60 agent.print_response(61 input="I'd like to update my payment method. My new card number is 4532 1234 5678 9012.",62 )63 print("[WARNING] This should have been blocked!")64 except InputCheckError as e:65 print(f"[BLOCKED] PII blocked: {e.message}")66 print(f" Trigger: {e.check_trigger}")6768 # Test 4: Request with email address (should be blocked)69 print("\n[TEST 4] Input containing email address")70 print("-" * 30)71 try:72 agent.print_response(73 input="Please send the receipt to john.doe@example.com for my recent purchase.",74 )75 print("[WARNING] This should have been blocked!")76 except InputCheckError as e:77 print(f"[BLOCKED] PII blocked: {e.message}")78 print(f" Trigger: {e.check_trigger}")7980 # Test 5: Request with phone number (should be blocked)81 print("\n[TEST 5] Input containing phone number")82 print("-" * 30)83 try:84 agent.print_response(85 input="My phone number is 555-123-4567. Please call me about my order status.",86 )87 print("[WARNING] This should have been blocked!")88 except InputCheckError as e:89 print(f"[BLOCKED] PII blocked: {e.message}")90 print(f" Trigger: {e.check_trigger}")9192 # Test 6: Mixed PII in context (should be blocked)93 print("\n[TEST 6] Multiple PII types in one request")94 print("-" * 30)95 try:96 agent.print_response(97 input="Hi, I'm John Smith. My email is john@company.com and phone is 555.987.6543. I need help with my account.",98 )99 print("[WARNING] This should have been blocked!")100 except InputCheckError as e:101 print(f"[BLOCKED] PII blocked: {e.message}")102 print(f" Trigger: {e.check_trigger}")103104 # Test 7: Edge case - formatted differently (should still be blocked)105 print("\n[TEST 7] PII with different formatting")106 print("-" * 30)107 try:108 agent.print_response(109 input="Can you verify my credit card ending in 4532123456789012?",110 )111 print("[WARNING] This should have been blocked!")112 except InputCheckError as e:113 print(f"[BLOCKED] PII blocked: {e.message}")114 print(f" Trigger: {e.check_trigger}")115116 print("\n" + "=" * 50)117 print("PII Detection Demo Complete")118 print("All sensitive information was successfully blocked!")119120 # Create an agent with PII detection which masks the PII in the input121 agent = Agent(122 name="Privacy-Protected Agent (Masked)",123 model=OpenAIResponses(id="gpt-5-mini"),124 pre_hooks=[PIIDetectionGuardrail(mask_pii=True)],125 description="An agent that helps with customer service while protecting privacy.",126 instructions="You are a helpful customer service assistant. Always protect user privacy and handle sensitive information appropriately.",127 )128129 # Test 8: Request with SSN (should be masked)130 print("\n[TEST 8] Input containing SSN (masked mode)")131 print("-" * 30)132 agent.print_response(133 input="Hi, my Social Security Number is 123-45-6789. Can you help me with my account?",134 )135136137# ---------------------------------------------------------------------------138# Run Agent139# ---------------------------------------------------------------------------140if __name__ == "__main__":141 asyncio.run(main())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 pii_detection.py