|
| 1 | +""" |
| 2 | +Example: Using @trace() Decorator with Guardrails |
| 3 | +
|
| 4 | +This example demonstrates how to use guardrails with the @trace() decorator |
| 5 | +for function-level protection and monitoring. |
| 6 | +""" |
| 7 | + |
| 8 | +import os |
| 9 | +from typing import Dict, Any |
| 10 | +from openlayer.lib.tracing import tracer |
| 11 | +from openlayer.lib.guardrails import PIIGuardrail, BlockStrategy |
| 12 | + |
| 13 | +# Set environment variables |
| 14 | +os.environ["OPENLAYER_API_KEY"] = "your_api_key_here" |
| 15 | +os.environ["OPENLAYER_INFERENCE_PIPELINE_ID"] = "your_pipeline_id_here" |
| 16 | + |
| 17 | +def main(): |
| 18 | + """Main example demonstrating @trace() decorator with guardrails.""" |
| 19 | + print("🛡️ @trace() Decorator with Guardrails Examples") |
| 20 | + print("=" * 60) |
| 21 | + |
| 22 | + # Example 1: Basic PII Protection |
| 23 | + print("\n📋 Example 1: Basic PII Protection") |
| 24 | + |
| 25 | + pii_guard = PIIGuardrail( |
| 26 | + name="Basic PII Protection", |
| 27 | + block_strategy=BlockStrategy.RETURN_ERROR_MESSAGE, |
| 28 | + block_message="Request blocked due to sensitive information detected" |
| 29 | + ) |
| 30 | + |
| 31 | + @tracer.trace(guardrails=[pii_guard]) |
| 32 | + def process_user_query(user_input: str) -> str: |
| 33 | + """Process user input with PII protection.""" |
| 34 | + # Simulate some processing |
| 35 | + processed = f"Processed query: {user_input}" |
| 36 | + return processed |
| 37 | + |
| 38 | + # Test with safe content |
| 39 | + try: |
| 40 | + result = process_user_query("Tell me about machine learning") |
| 41 | + print(f"✅ Safe content: {result}") |
| 42 | + except Exception as e: |
| 43 | + print(f"❌ Error: {e}") |
| 44 | + |
| 45 | + # Test with PII content |
| 46 | + try: |
| 47 | + result = process_user_query("My SSN is 123-45-6789, can you help?") |
| 48 | + print(f"🛡️ PII handled: {result}") |
| 49 | + except Exception as e: |
| 50 | + print(f"🚫 PII blocked: {e}") |
| 51 | + |
| 52 | + # Example 2: Multiple Guardrails with Different Strategies |
| 53 | + print("\n📋 Example 2: Multiple Guardrails") |
| 54 | + |
| 55 | + # Strict guardrail for SSNs (blocks completely) |
| 56 | + ssn_guard = PIIGuardrail( |
| 57 | + name="SSN Protection", |
| 58 | + block_entities={"US_SSN"}, |
| 59 | + redact_entities=set(), |
| 60 | + block_strategy=BlockStrategy.RAISE_EXCEPTION, |
| 61 | + confidence_threshold=0.8 |
| 62 | + ) |
| 63 | + |
| 64 | + # Lenient guardrail for phone numbers (redacts) |
| 65 | + phone_guard = PIIGuardrail( |
| 66 | + name="Phone Protection", |
| 67 | + block_entities=set(), |
| 68 | + redact_entities={"PHONE_NUMBER"}, |
| 69 | + confidence_threshold=0.7 |
| 70 | + ) |
| 71 | + |
| 72 | + @tracer.trace(guardrails=[ssn_guard, phone_guard]) |
| 73 | + def handle_customer_data(customer_info: str) -> str: |
| 74 | + """Handle customer data with layered protection.""" |
| 75 | + return f"Customer data processed: {customer_info}" |
| 76 | + |
| 77 | + # Test with phone number (should be redacted) |
| 78 | + try: |
| 79 | + result = handle_customer_data("Contact me at 555-123-4567") |
| 80 | + print(f"📞 Phone redacted: {result}") |
| 81 | + except Exception as e: |
| 82 | + print(f"🚫 Blocked: {e}") |
| 83 | + |
| 84 | + # Test with SSN (should be blocked completely) |
| 85 | + try: |
| 86 | + result = handle_customer_data("My SSN: 987-65-4321") |
| 87 | + print(f"❌ Should not reach here: {result}") |
| 88 | + except Exception as e: |
| 89 | + print(f"🛡️ SSN blocked: {e}") |
| 90 | + |
| 91 | + # Example 3: Custom Guardrail Logic |
| 92 | + print("\n📋 Example 3: Custom Guardrail") |
| 93 | + |
| 94 | + class CustomContentFilter(PIIGuardrail): |
| 95 | + """Custom guardrail that blocks specific keywords.""" |
| 96 | + |
| 97 | + def __init__(self, **config): |
| 98 | + super().__init__(name="Custom Content Filter", **config) |
| 99 | + self.blocked_keywords = config.get("blocked_keywords", ["password", "secret"]) |
| 100 | + |
| 101 | + def check_input(self, inputs: Dict[str, Any]): |
| 102 | + text = str(inputs).lower() |
| 103 | + for keyword in self.blocked_keywords: |
| 104 | + if keyword in text: |
| 105 | + return self._create_block_result(f"Blocked keyword: {keyword}") |
| 106 | + return self._create_allow_result() |
| 107 | + |
| 108 | + def check_output(self, output: Any, inputs: Dict[str, Any]): |
| 109 | + text = str(output).lower() |
| 110 | + for keyword in self.blocked_keywords: |
| 111 | + if keyword in text: |
| 112 | + return self._create_modify_result( |
| 113 | + str(output).replace(keyword, "[REDACTED]"), |
| 114 | + f"Redacted keyword: {keyword}" |
| 115 | + ) |
| 116 | + return self._create_allow_result() |
| 117 | + |
| 118 | + custom_guard = CustomContentFilter( |
| 119 | + blocked_keywords=["password", "secret", "confidential"] |
| 120 | + ) |
| 121 | + |
| 122 | + @tracer.trace(guardrails=[custom_guard]) |
| 123 | + def process_document(content: str) -> str: |
| 124 | + """Process document with custom content filtering.""" |
| 125 | + return f"Document processed: {content}" |
| 126 | + |
| 127 | + try: |
| 128 | + result = process_document("This document contains secret information") |
| 129 | + print(f"🔍 Custom filter applied: {result}") |
| 130 | + except Exception as e: |
| 131 | + print(f"🚫 Custom filter blocked: {e}") |
| 132 | + |
| 133 | + # Example 4: Conditional Guardrails |
| 134 | + print("\n📋 Example 4: Conditional Guardrails") |
| 135 | + |
| 136 | + def create_context_aware_function(user_role: str): |
| 137 | + """Create function with role-based guardrails.""" |
| 138 | + if user_role == "admin": |
| 139 | + # Admins get lenient guardrails |
| 140 | + guards = [PIIGuardrail( |
| 141 | + name="Admin PII", |
| 142 | + confidence_threshold=0.9, # Higher threshold |
| 143 | + block_strategy=BlockStrategy.RETURN_ERROR_MESSAGE |
| 144 | + )] |
| 145 | + else: |
| 146 | + # Regular users get strict guardrails |
| 147 | + guards = [PIIGuardrail( |
| 148 | + name="User PII", |
| 149 | + confidence_threshold=0.6, # Lower threshold |
| 150 | + block_strategy=BlockStrategy.RAISE_EXCEPTION |
| 151 | + )] |
| 152 | + |
| 153 | + @tracer.trace(guardrails=guards) |
| 154 | + def handle_request(request_data: str) -> str: |
| 155 | + return f"[{user_role}] Processed: {request_data}" |
| 156 | + |
| 157 | + return handle_request |
| 158 | + |
| 159 | + # Test with different roles |
| 160 | + admin_handler = create_context_aware_function("admin") |
| 161 | + user_handler = create_context_aware_function("user") |
| 162 | + |
| 163 | + test_data = "User email: user@example.com" |
| 164 | + |
| 165 | + try: |
| 166 | + admin_result = admin_handler(test_data) |
| 167 | + print(f"👑 Admin result: {admin_result}") |
| 168 | + except Exception as e: |
| 169 | + print(f"👑 Admin blocked: {e}") |
| 170 | + |
| 171 | + try: |
| 172 | + user_result = user_handler(test_data) |
| 173 | + print(f"👤 User result: {user_result}") |
| 174 | + except Exception as e: |
| 175 | + print(f"👤 User blocked: {e}") |
| 176 | + |
| 177 | + print("\n" + "=" * 60) |
| 178 | + print("🎉 @trace() Decorator Examples Complete!") |
| 179 | + print("\n📊 Key Features Demonstrated:") |
| 180 | + print(" • Function-level PII protection") |
| 181 | + print(" • Multiple guardrails with different strategies") |
| 182 | + print(" • Custom guardrail implementations") |
| 183 | + print(" • Role-based conditional protection") |
| 184 | + print(" • Rich metadata for monitoring and analysis") |
| 185 | + |
| 186 | + |
| 187 | +if __name__ == "__main__": |
| 188 | + try: |
| 189 | + main() |
| 190 | + except ImportError as e: |
| 191 | + print(f"❌ Missing dependency: {e}") |
| 192 | + print("💡 To run with real PII detection:") |
| 193 | + print(" pip install presidio-analyzer presidio-anonymizer") |
| 194 | + print("\n✅ This example demonstrates the API structure.") |
0 commit comments