-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_simple_user_example.py
More file actions
211 lines (171 loc) Β· 7.77 KB
/
Copy pathtest_simple_user_example.py
File metadata and controls
211 lines (171 loc) Β· 7.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
#!/usr/bin/env python3
"""
π― SIMPLE USER EXAMPLE TEST π―
Testing the framework with completely safe, legitimate content.
"""
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), 'tbh_secure_agents'))
# Set API key for testing
os.environ["GOOGLE_API_KEY"] = "AIzaSyA3ZxbIXpR3yNkZwGDznrztdQmgnU16DJI"
from tbh_secure_agents import Expert, Operation
from tbh_secure_agents.security_validation import (
enable_hybrid_validation,
get_next_gen_adaptive_validator
)
def test_simple_user_example():
"""Test with completely safe, legitimate content."""
print("π― TESTING SIMPLE USER EXAMPLE π―\n")
# Enable hybrid validation
enable_hybrid_validation()
print("β
Hybrid validation enabled\n")
# Initialize adaptive learning monitor
adaptive_validator = get_next_gen_adaptive_validator()
print(f"π§ Adaptive learning initialized: {len(adaptive_validator.engine.enhanced_patterns)} patterns ready\n")
# Create outputs directory
os.makedirs("outputs/simple_test", exist_ok=True)
print("π TESTING DIFFERENT SECURITY PROFILES WITH SAFE CONTENT\n")
# Test with completely safe content
safe_tests = [
{
"profile": "minimal",
"expert_type": "Creative Writer",
"task": "Write a short, cheerful story about a cat who loves to play with yarn",
"expected": "Should complete quickly with minimal security checks"
},
{
"profile": "standard",
"expert_type": "Math Tutor",
"task": "Explain how to calculate the area of a circle with simple examples",
"expected": "Should complete with standard security validation"
},
{
"profile": "high",
"expert_type": "Recipe Developer",
"task": "Create a simple recipe for chocolate chip cookies with step-by-step instructions",
"expected": "Should complete with thorough security checks"
}
]
results = []
for i, test in enumerate(safe_tests, 1):
print(f"π§ͺ Test {i}: {test['profile'].upper()} Security Profile")
print(f" Expert: {test['expert_type']}")
print(f" Task: {test['task'][:50]}...")
print(f" Expected: {test['expected']}")
try:
# Create expert with specific security profile
expert = Expert(
specialty=test['expert_type'],
objective=f"Provide helpful, safe, and accurate {test['expert_type'].lower()} assistance",
security_profile=test['profile']
)
# Create operation
operation = Operation(
instructions=test['task'],
output_format="Clear, helpful response with examples",
expert=expert,
result_destination=f"outputs/simple_test/{test['profile']}_security_test.md"
)
# Execute operation
print(" π Executing...")
import time
start_time = time.time()
result = operation.execute()
execution_time = time.time() - start_time
print(f" β
SUCCESS: Completed in {execution_time:.2f} seconds")
print(f" π Output saved to: {operation.result_destination}")
results.append({
"profile": test['profile'],
"success": True,
"time": execution_time,
"output_file": operation.result_destination
})
except Exception as e:
print(f" β FAILED: {e}")
results.append({
"profile": test['profile'],
"success": False,
"error": str(e)
})
print()
print("π RESULTS SUMMARY\n")
successful_tests = [r for r in results if r['success']]
print(f"π― Success Rate: {len(successful_tests)}/{len(results)} ({len(successful_tests)/len(results)*100:.1f}%)")
if successful_tests:
print("\nβ
Successful Tests:")
for result in successful_tests:
print(f" - {result['profile'].upper()}: {result['time']:.2f}s")
print(f"\nβ‘ Performance Analysis:")
times = [r['time'] for r in successful_tests]
print(f" - Fastest: {min(times):.2f}s")
print(f" - Slowest: {max(times):.2f}s")
print(f" - Average: {sum(times)/len(times):.2f}s")
failed_tests = [r for r in results if not r['success']]
if failed_tests:
print("\nβ Failed Tests:")
for result in failed_tests:
print(f" - {result['profile'].upper()}: {result.get('error', 'Unknown error')}")
print("\nπ§ ADAPTIVE LEARNING STATUS")
final_patterns = len(adaptive_validator.engine.enhanced_patterns)
final_profiles = len(adaptive_validator.engine.behavioral_profiles)
attack_history = len(adaptive_validator.engine.attack_history)
print(f" π Enhanced Patterns: {final_patterns}")
print(f" π Behavioral Profiles: {final_profiles}")
print(f" π Attack History: {attack_history}")
if final_profiles > 0:
print(f"\n π₯ User Profiles Created:")
for user_id, profile in adaptive_validator.engine.behavioral_profiles.items():
print(f" - {user_id}: risk={profile.risk_score:.3f}")
print("\nπ INTEGRATION ASSESSMENT")
integration_score = 0
total_checks = 5
# Check 1: Framework integration
if len(successful_tests) > 0:
print(" β
Framework integration working")
integration_score += 1
else:
print(" β Framework integration issues")
# Check 2: Security profiles
profile_success = len(set(r['profile'] for r in successful_tests))
if profile_success >= 2:
print(f" β
Multiple security profiles working ({profile_success}/3)")
integration_score += 1
else:
print(f" β οΈ Limited security profile support ({profile_success}/3)")
# Check 3: Performance
if successful_tests and max(r['time'] for r in successful_tests) < 30:
print(" β
Performance within acceptable limits")
integration_score += 1
else:
print(" β οΈ Performance concerns detected")
# Check 4: Output generation
output_files = [r.get('output_file') for r in successful_tests if r.get('output_file')]
if output_files:
print(f" β
Output generation working ({len(output_files)} files created)")
integration_score += 1
else:
print(" β Output generation issues")
# Check 5: Adaptive learning ready
if final_patterns >= 10:
print(" β
Adaptive learning system ready")
integration_score += 1
else:
print(" β οΈ Adaptive learning system issues")
final_score = (integration_score / total_checks) * 100
print(f"\nπ― FINAL INTEGRATION SCORE: {integration_score}/{total_checks} ({final_score:.1f}%)")
if final_score >= 80:
print("\nπ EXCELLENT: Framework integration is production-ready!")
print(" π Hybrid validation working seamlessly")
print(" π§ Adaptive learning ready for deployment")
print(" β‘ Performance optimized for real-world use")
print(" π‘οΈ Security profiles functioning correctly")
return True
elif final_score >= 60:
print("\nβ
GOOD: Framework integration working well")
return True
else:
print("\nβ οΈ NEEDS WORK: Integration issues detected")
return False
if __name__ == "__main__":
success = test_simple_user_example()
print(f"\nπ― FINAL RESULT: {'SUCCESS' if success else 'NEEDS IMPROVEMENT'}")