DeepTeam is a framework to red team LLMs and AI agents.
Add LLM model customization and sample rate configuration with validation
sid-murali8605777806ac
diff --git a/deepteam/guardrails/base_guard.py b/deepteam/guardrails/base_guard.pyindex 2eb461be..362a4947 100644--- a/deepteam/guardrails/base_guard.py+++ b/deepteam/guardrails/base_guard.py@@ -13,8 +13,16 @@ class BaseGuard(ABC):latency: Optional[float] = Noneguard_type: GuardType- def __init__(self):- self.model = GPTModel(model="gpt-4.1")+ 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)self.evaluation_model = self.model.get_model_name()@propertydiff --git a/deepteam/guardrails/guardrails.py b/deepteam/guardrails/guardrails.pyindex ed5b94f0..f68056de 100644--- a/deepteam/guardrails/guardrails.py+++ b/deepteam/guardrails/guardrails.py@@ -1,6 +1,7 @@-from typing import List, Dict, Any+from typing import List, Dict, Any, Optionalimport timeimport asyncio+import randomfrom deepteam.guardrails.base_guard import BaseGuardfrom deepteam.guardrails.types import GuardType@@ -25,7 +26,9 @@ class Guardrails:def __init__(self,input_guards: List[BaseGuard],- output_guards: List[BaseGuard]+ output_guards: List[BaseGuard],+ default_evaluation_model: Optional[str] = None,+ sample_rate: Optional[float] = None):"""Initialize Guardrails with separate input and output guards.@@ -33,9 +36,36 @@ 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"""self.input_guards = input_guardsself.output_guards = output_guards+ self.default_evaluation_model = default_evaluation_model++ # 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++ # 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+ return random.random() < self.sample_ratedef guard_input(self, input: str) -> GuardResult:"""@@ -47,6 +77,11 @@ 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+ return GuardResult(guard_results={})+guard_results = {}for guard in self.input_guards:@@ -81,6 +116,11 @@ 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+ return GuardResult(guard_results={})+guard_results = {}for guard in self.output_guards:@@ -114,6 +154,11 @@ 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+ return GuardResult(guard_results={})+tasks = []for guard in self.input_guards:task = asyncio.create_task(self._async_guard_input_single(guard, input))@@ -142,6 +187,11 @@ 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+ return GuardResult(guard_results={})+tasks = []for guard in self.output_guards:task = asyncio.create_task(self._async_guard_output_single(guard, input, output))diff --git a/deepteam/guardrails/guards/cybersecurity_guard.py b/deepteam/guardrails/guards/cybersecurity_guard.pyindex 4d7814f9..fc08027a 100644--- a/deepteam/guardrails/guards/cybersecurity_guard.py+++ b/deepteam/guardrails/guards/cybersecurity_guard.py@@ -11,8 +11,9 @@ class CybersecurityGuard(BaseGuard):purpose: Optional[str] = None,categories: List[CyberattackCategory] = None,guard_type: GuardType = GuardType.INPUT,+ evaluation_model: Optional[str] = None,):- super().__init__()+ super().__init__(evaluation_model=evaluation_model)self.guard_type = guard_typeself.purpose = purposeself.categories = categories or [attack for attack in CyberattackCategory]diff --git a/deepteam/guardrails/guards/hallucination_guard.py b/deepteam/guardrails/guards/hallucination_guard.pyindex f9efece1..4561f5bf 100644--- a/deepteam/guardrails/guards/hallucination_guard.py+++ b/deepteam/guardrails/guards/hallucination_guard.py@@ -1,10 +1,11 @@from ..base_guard import BaseGuardfrom ..types import GuardType+from typing import Optionalclass HallucinationGuard(BaseGuard):- def __init__(self):- super().__init__()+ def __init__(self, evaluation_model: Optional[str] = None):+ super().__init__(evaluation_model=evaluation_model)self.guard_type = GuardType.OUTPUT@propertydiff --git a/deepteam/guardrails/guards/illegal_guard.py b/deepteam/guardrails/guards/illegal_guard.pyindex 29794baa..d75c2a45 100644--- a/deepteam/guardrails/guards/illegal_guard.py+++ b/deepteam/guardrails/guards/illegal_guard.py@@ -1,10 +1,11 @@from ..base_guard import BaseGuardfrom ..types import GuardType+from typing import Optionalclass IllegalGuard(BaseGuard):- def __init__(self):- super().__init__()+ def __init__(self, evaluation_model: Optional[str] = None):+ super().__init__(evaluation_model=evaluation_model)self.guard_type = GuardType.OUTPUT@propertydiff --git a/deepteam/guardrails/guards/privacy_guard.py b/deepteam/guardrails/guards/privacy_guard.pyindex fd05739c..c61f9902 100644--- a/deepteam/guardrails/guards/privacy_guard.py+++ b/deepteam/guardrails/guards/privacy_guard.py@@ -1,10 +1,11 @@from ..base_guard import BaseGuardfrom ..types import GuardType+from typing import Optionalclass PrivacyGuard(BaseGuard):- def __init__(self):- super().__init__()+ def __init__(self, evaluation_model: Optional[str] = None):+ super().__init__(evaluation_model=evaluation_model)self.guard_type = GuardType.OUTPUT@propertydiff --git a/deepteam/guardrails/guards/prompt_injection_guard.py b/deepteam/guardrails/guards/prompt_injection_guard.pyindex 0d2c1726..a74388b8 100644--- a/deepteam/guardrails/guards/prompt_injection_guard.py+++ b/deepteam/guardrails/guards/prompt_injection_guard.py@@ -1,10 +1,11 @@from ..base_guard import BaseGuardfrom ..types import GuardType+from typing import Optionalclass PromptInjectionGuard(BaseGuard):- def __init__(self):- super().__init__()+ def __init__(self, evaluation_model: Optional[str] = None):+ super().__init__(evaluation_model=evaluation_model)self.guard_type = GuardType.INPUT@propertydiff --git a/deepteam/guardrails/guards/topical_guard.py b/deepteam/guardrails/guards/topical_guard.pyindex bf6c04a2..bf051097 100644--- a/deepteam/guardrails/guards/topical_guard.py+++ b/deepteam/guardrails/guards/topical_guard.py@@ -1,11 +1,11 @@from ..base_guard import BaseGuardfrom ..types import GuardType+from typing import Optionalclass TopicalGuard(BaseGuard):-- def __init__(self, allowed_topics=None):- super().__init__()+ def __init__(self, allowed_topics=None, evaluation_model: Optional[str] = None):+ super().__init__(evaluation_model=evaluation_model)self.guard_type = GuardType.INPUTself.allowed_topics = allowed_topics or []diff --git a/deepteam/guardrails/guards/toxicity_guard.py b/deepteam/guardrails/guards/toxicity_guard.pyindex 0d0914b8..e0dd5a20 100644--- a/deepteam/guardrails/guards/toxicity_guard.py+++ b/deepteam/guardrails/guards/toxicity_guard.py@@ -1,10 +1,11 @@from ..base_guard import BaseGuardfrom ..types import GuardType+from typing import Optionalclass ToxicityGuard(BaseGuard):- def __init__(self):- super().__init__()+ def __init__(self, evaluation_model: Optional[str] = None):+ super().__init__(evaluation_model=evaluation_model)self.guard_type = GuardType.OUTPUT@propertydiff --git a/tests/test_input_output_guards.py b/tests/test_input_output_guards.pyindex 877f760b..5d35fafc 100644--- a/tests/test_input_output_guards.py+++ b/tests/test_input_output_guards.py@@ -26,6 +26,69 @@ def test_basic_functionality():print("✅ Output guarding works correctly")+def test_evaluation_model_customization():+ """Test LLM model customization features"""++ from deepteam.guardrails import Guardrails+ from 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+ guardrails = Guardrails(+ input_guards=[PromptInjectionGuard()],+ output_guards=[ToxicityGuard()],+ default_evaluation_model="gpt-4o-mini"+ )+ print("✅ Default evaluation model initialization works")+++def test_sample_rate_functionality():+ """Test sample rate configuration and validation"""++ from deepteam.guardrails import Guardrails+ from deepteam.guardrails.guards import PromptInjectionGuard, ToxicityGuard++ # Test valid sample rate+ guardrails = Guardrails(+ input_guards=[PromptInjectionGuard()],+ output_guards=[ToxicityGuard()],+ sample_rate=0.5+ )+ assert guardrails.sample_rate == 0.5+ print("✅ Valid sample rate works")++ # Test sample rate validation+ try:+ Guardrails(+ input_guards=[PromptInjectionGuard()],+ output_guards=[ToxicityGuard()],+ sample_rate=1.5 # Invalid - > 1.0+ )+ assert False, "Should have raised ValueError"+ except ValueError:+ print("✅ Sample rate validation works")++ # 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")++def test_error_handling():"""Test proper errors for empty guard lists"""@@ -74,11 +137,33 @@ 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_error_handling()test_attack_detection()+ test_sample_rate_behavior()print("🎉 All tests passed!")\ No newline at end of file