DeepTeam is a framework to red team LLMs and AI agents.
Add evaluation_model and sample_rate parameters to Guardrails class with validation
sid-murali556b034cab39
diff --git a/deepteam/guardrails/base_guard.py b/deepteam/guardrails/base_guard.pyindex 362a4947..674f7512 100644--- a/deepteam/guardrails/base_guard.py+++ b/deepteam/guardrails/base_guard.py@@ -13,16 +13,8 @@ class BaseGuard(ABC):latency: Optional[float] = Noneguard_type: GuardType- def __init__(self, evaluation_model: Optional[str] = None):- """- Initialize BaseGuard with configurable evaluation model.-- Args:- evaluation_model: OpenAI model to use for evaluation (e.g., "gpt-4o", "gpt-3.5-turbo")- Defaults to "gpt-4o" if not specified- """- model_name = evaluation_model or "gpt-4.1"- self.model = GPTModel(model=model_name)+ def __init__(self, evaluation_model: str = "gpt-4.1"):+ self.model = GPTModel(model=evaluation_model)self.evaluation_model = self.model.get_model_name()@propertydiff --git a/deepteam/guardrails/guardrails.py b/deepteam/guardrails/guardrails.pyindex f68056de..c8c580bf 100644--- a/deepteam/guardrails/guardrails.py+++ b/deepteam/guardrails/guardrails.py@@ -1,4 +1,4 @@-from typing import List, Dict, Any, Optional+from typing import List, Dict, Anyimport timeimport asyncioimport random@@ -27,8 +27,8 @@ class Guardrails:self,input_guards: List[BaseGuard],output_guards: List[BaseGuard],- default_evaluation_model: Optional[str] = None,- sample_rate: Optional[float] = None+ evaluation_model: str = "gpt-4.1",+ sample_rate: float = 1.0):"""Initialize Guardrails with separate input and output guards.@@ -36,35 +36,32 @@ class Guardrails:Args:input_guards: List of guards to check inputs before they reach your LLMoutput_guards: List of guards to check outputs before they reach your users- default_evaluation_model: Default OpenAI model for guards without explicit model- sample_rate: Fraction of requests to process (0.0 to 1.0). If None, processes all requests+ evaluation_model: OpenAI model to use for guard evaluation (default: gpt-4.1)+ sample_rate: Fraction of requests to actually guard (0.0 to 1.0, default: 1.0)"""- self.input_guards = input_guards- self.output_guards = output_guards- self.default_evaluation_model = default_evaluation_model+ # Validate sample_rate+ if not (0.0 <= sample_rate <= 1.0):+ raise ValueError(f"sample_rate must be between 0.0 and 1.0, got {sample_rate}")- # Validate and set sample rate- if sample_rate is not None:- if not 0.0 <= sample_rate <= 1.0:- raise ValueError("sample_rate must be between 0.0 and 1.0")self.sample_rate = sample_rate+ self.evaluation_model = evaluation_model- # Apply default model to guards that don't have explicit models- if default_evaluation_model:- self._apply_default_model_to_guards()-- def _apply_default_model_to_guards(self):- """Apply default evaluation model to guards that don't have explicit models"""- all_guards = self.input_guards + self.output_guards- for guard in all_guards:- # Only update if guard doesn't already have a specific model configured- if guard.evaluation_model == "gpt-4o": # Default from BaseGuard- guard.__init__(evaluation_model=self.default_evaluation_model)-- def _should_process_request(self) -> bool:- """Determine if request should be processed based on sample rate"""- if self.sample_rate is None:- return True+ # Update all guards to use the specified evaluation model+ self.input_guards = self._update_guards_model(input_guards, evaluation_model)+ self.output_guards = self._update_guards_model(output_guards, evaluation_model)++ def _update_guards_model(self, guards: List[BaseGuard], evaluation_model: str) -> List[BaseGuard]:+ """Update all guards to use the specified evaluation model"""+ updated_guards = []+ for guard in guards:+ # Create new instance with updated model+ guard_class = guard.__class__+ new_guard = guard_class(evaluation_model=evaluation_model)+ updated_guards.append(new_guard)+ return updated_guards++ def _should_sample(self) -> bool:+ """Determine if this request should be sampled based on sample_rate"""return random.random() < self.sample_ratedef guard_input(self, input: str) -> GuardResult:@@ -77,9 +74,9 @@ class Guardrails:"Guardrails cannot guard inputs when no input_guards are provided.")- # Check sample rate- if not self._should_process_request():- # Return safe result without processing+ # Check if we should sample this request+ if not self._should_sample():+ # Return empty result when not samplingreturn GuardResult(guard_results={})guard_results = {}@@ -116,9 +113,9 @@ class Guardrails:"Guardrails cannot guard outputs when no output_guards are provided.")- # Check sample rate- if not self._should_process_request():- # Return safe result without processing+ # Check if we should sample this request+ if not self._should_sample():+ # Return empty result when not samplingreturn GuardResult(guard_results={})guard_results = {}@@ -154,9 +151,9 @@ class Guardrails:"Guardrails cannot guard inputs when no input_guards are provided.")- # Check sample rate- if not self._should_process_request():- # Return safe result without processing+ # Check if we should sample this request+ if not self._should_sample():+ # Return empty result when not samplingreturn GuardResult(guard_results={})tasks = []@@ -187,9 +184,9 @@ class Guardrails:"Guardrails cannot guard outputs when no output_guards are provided.")- # Check sample rate- if not self._should_process_request():- # Return safe result without processing+ # Check if we should sample this request+ if not self._should_sample():+ # Return empty result when not samplingreturn GuardResult(guard_results={})tasks = []diff --git a/deepteam/guardrails/guards/cybersecurity_guard.py b/deepteam/guardrails/guards/cybersecurity_guard.pyindex fc08027a..dccb692a 100644--- a/deepteam/guardrails/guards/cybersecurity_guard.py+++ b/deepteam/guardrails/guards/cybersecurity_guard.py@@ -11,7 +11,6 @@ class CybersecurityGuard(BaseGuard):purpose: Optional[str] = None,categories: List[CyberattackCategory] = None,guard_type: GuardType = GuardType.INPUT,- evaluation_model: Optional[str] = None,):super().__init__(evaluation_model=evaluation_model)self.guard_type = guard_typediff --git a/deepteam/guardrails/guards/prompt_injection_guard.py b/deepteam/guardrails/guards/prompt_injection_guard.pyindex a74388b8..37a25acd 100644--- a/deepteam/guardrails/guards/prompt_injection_guard.py+++ b/deepteam/guardrails/guards/prompt_injection_guard.py@@ -1,10 +1,9 @@from ..base_guard import BaseGuardfrom ..types import GuardType-from typing import Optionalclass PromptInjectionGuard(BaseGuard):- def __init__(self, evaluation_model: Optional[str] = None):+ def __init__(self, evaluation_model: str = "gpt-4.1"):super().__init__(evaluation_model=evaluation_model)self.guard_type = GuardType.INPUTdiff --git a/deepteam/guardrails/guards/toxicity_guard.py b/deepteam/guardrails/guards/toxicity_guard.pyindex e0dd5a20..696cc7e0 100644--- a/deepteam/guardrails/guards/toxicity_guard.py+++ b/deepteam/guardrails/guards/toxicity_guard.py@@ -1,10 +1,9 @@from ..base_guard import BaseGuardfrom ..types import GuardType-from typing import Optionalclass ToxicityGuard(BaseGuard):- def __init__(self, evaluation_model: Optional[str] = None):+ def __init__(self, evaluation_model: str = "gpt-4.1"):super().__init__(evaluation_model=evaluation_model)self.guard_type = GuardType.OUTPUTdiff --git a/tests/test_input_output_guards.py b/tests/test_input_output_guards.pyindex 5d35fafc..d8bcfa50 100644--- a/tests/test_input_output_guards.py+++ b/tests/test_input_output_guards.py@@ -26,74 +26,89 @@ def test_basic_functionality():print("✅ Output guarding works correctly")-def test_evaluation_model_customization():- """Test LLM model customization features"""+def test_evaluation_model():+ """Test custom evaluation model configuration"""from deepteam.guardrails import Guardrailsfrom deepteam.guardrails.guards import PromptInjectionGuard, ToxicityGuard- # Test individual guard model specification- prompt_guard = PromptInjectionGuard(evaluation_model="gpt-3.5-turbo")- toxicity_guard = ToxicityGuard(evaluation_model="gpt-4o")-- assert "gpt-3.5-turbo" in prompt_guard.evaluation_model- assert "gpt-4o" in toxicity_guard.evaluation_model- print("✅ Individual guard model specification works")-- # Test default evaluation model+ # Test with different evaluation modelguardrails = Guardrails(input_guards=[PromptInjectionGuard()],output_guards=[ToxicityGuard()],- default_evaluation_model="gpt-4o-mini"+ evaluation_model="gpt-3.5-turbo")- print("✅ Default evaluation model initialization works")++ # Check that guards were updated with new model+ assert guardrails.evaluation_model == "gpt-3.5-turbo"+ result = guardrails.guard_input(input="Test input")+ assert len(result.guard_results) > 0+ print("✅ Custom evaluation model works")-def test_sample_rate_functionality():- """Test sample rate configuration and validation"""+def test_sample_rate():+ """Test sample rate functionality"""from deepteam.guardrails import Guardrailsfrom deepteam.guardrails.guards import PromptInjectionGuard, ToxicityGuard- # Test valid sample rate+ # Test with 0% sample rate (should never run guards)+ guardrails = Guardrails(+ input_guards=[PromptInjectionGuard()],+ output_guards=[ToxicityGuard()],+ sample_rate=0.0+ )++ result = guardrails.guard_input(input="Test input")+ assert len(result.guard_results) == 0 # Should be empty due to 0% sampling+ print("✅ Sample rate 0.0 works (no guards executed)")++ # Test with 100% sample rate (should always run guards)guardrails = Guardrails(input_guards=[PromptInjectionGuard()],output_guards=[ToxicityGuard()],- sample_rate=0.5+ sample_rate=1.0)- assert guardrails.sample_rate == 0.5- print("✅ Valid sample rate works")- # Test sample rate validation+ result = guardrails.guard_input(input="Test input")+ assert len(result.guard_results) > 0 # Should have results due to 100% sampling+ print("✅ Sample rate 1.0 works (guards executed)")+++def test_sample_rate_validation():+ """Test sample rate validation"""++ from deepteam.guardrails import Guardrails+ from deepteam.guardrails.guards import PromptInjectionGuard, ToxicityGuard++ # Test invalid sample ratestry:Guardrails(input_guards=[PromptInjectionGuard()],output_guards=[ToxicityGuard()],- sample_rate=1.5 # Invalid - > 1.0+ sample_rate=1.5 # Invalid: > 1.0)assert False, "Should have raised ValueError"except ValueError:- print("✅ Sample rate validation works")+ pass- # Test sample rate at boundaries- guardrails_0 = Guardrails(- input_guards=[PromptInjectionGuard()],- output_guards=[ToxicityGuard()],- sample_rate=0.0- )- guardrails_1 = Guardrails(- input_guards=[PromptInjectionGuard()],- output_guards=[ToxicityGuard()],- sample_rate=1.0- )- print("✅ Boundary sample rates work")+ try:+ Guardrails(+ input_guards=[PromptInjectionGuard()],+ output_guards=[ToxicityGuard()],+ sample_rate=-0.1 # Invalid: < 0.0+ )+ assert False, "Should have raised ValueError"+ except ValueError:+ pass++ print("✅ Sample rate validation works")def test_error_handling():"""Test proper errors for empty guard lists"""from deepteam.guardrails import Guardrails- from deepteam.guardrails.guards import PrivacyGuard# Test with empty listsguardrails = Guardrails(input_guards=[], output_guards=[])@@ -137,33 +152,14 @@ def test_attack_detection():print("✅ Toxic output detected")-def test_sample_rate_behavior():- """Test that sample rate actually affects processing"""-- from deepteam.guardrails import Guardrails- from deepteam.guardrails.guards import PromptInjectionGuard, ToxicityGuard-- # Test with sample_rate=0.0 (should never process)- guardrails_never = Guardrails(- input_guards=[PromptInjectionGuard()],- output_guards=[ToxicityGuard()],- sample_rate=0.0- )-- result = guardrails_never.guard_input("Test input")- assert len(result.guard_results) == 0 # No guards should run- assert not result.breached # Should be safe (no processing)- print("✅ Sample rate 0.0 behavior works")--if __name__ == "__main__":print("🧪 Testing Guardrails Input/Output Implementation")test_basic_functionality()- test_evaluation_model_customization()- test_sample_rate_functionality()+ test_evaluation_model()+ test_sample_rate()+ test_sample_rate_validation()test_error_handling()test_attack_detection()- test_sample_rate_behavior()print("🎉 All tests passed!")\ No newline at end of file