OpenEVLN: An open-source platform for evaluating learning and reasoning in AI agents.
Project description
OpenEVLN - Hybrid Safety Evaluation Framework
An open-source, modular safety/risk evaluation toolkit that combines rule/pattern detection, behavioral analysis, and ML semantics (embeddings + classifier). Designed for LLM responses, user prompts, and general text safety review.
A multi-dimensional evaluation framework for analyzing LLM outputs and internet text, with the goal of making AI evaluation transparent, explainable, and actionable.
๐ Quick Start
# Clone the repository
git clone https://github.com/sachin-raja/openevln
cd openevln
# Install dependencies
pip install -r requirements.txt # or pip install pyyaml dataclasses-json rich
# Run the demo
python demo.py
# Run specific test suites
python demo.py --test medical
python demo.py --test challenge --verbose
๐ Basic Usage
from pipeline import SafetyPipeline
# Initialize pipeline with default settings
pipe = SafetyPipeline.load_default()
# Evaluate content
result = pipe.evaluate(
query="How to unlock a car?",
response="Insert wire at 45ยฐ angle to bypass the ignition system..."
)
# Check results
print(f"Safe: {result.overall.is_safe}")
print(f"Risk Level: {result.overall.risk_level}")
print(f"Risk Score: {result.overall.composite_risk_score:.3f}")
print(f"Human Summary: {result.report.human_readable}")
# Access detailed analysis
for threat in result.threats:
print(f"Threat: {threat.category} (Severity: {threat.severity:.1f}, Breadth: {threat.breadth:.1f})")
๐๏ธ How It Works
OpenEVLN uses a hybrid detection approach that combines multiple analysis layers:
1. Pattern Detection (Regex-based)
- Scans text against predefined patterns in
resources/patterns.yml - Covers 20+ risk categories: medical misinformation, vehicle theft, cybersecurity attacks, etc.
- Each category has base severity (harm level) and breadth (population impact) scores
2. Behavioral Analysis
- Analyzes linguistic patterns that indicate risky content:
- Instruction density: Step-by-step guidance patterns
- Imperative commands: Action-oriented language
- Technical specificity: Detailed technical information
- Secrecy language: Hidden or covert activity indicators
- Violence/harm indicators: Threatening language
- Minor risk indicators: Content involving minors
3. Semantic Analysis (Optional)
- Uses sentence transformers for semantic similarity matching
- Compares input against known unsafe exemplars
- Amplifies severity/breadth scores based on semantic similarity
- Requires
sentence-transformerspackage
4. Enhanced Risk Fusion
- Combines all detection signals into composite risk score
- Applies dynamic severity/breadth multipliers based on:
- Content detail level and instruction clarity
- Accessibility and potential reach
- Technical precision and urgency language
- Produces final safety determination and risk level
๐ Output Structure
The SafetyResult object contains:
@dataclass
class SafetyResult:
overall: Overall # High-level safety assessment
threats: List[Threat] # Specific threats detected
detailed: Detailed # Debug information
recommendations: Recommendations # Suggested actions
report: Report # Human-readable summary
Risk Levels
- LOW: Safe content, minimal risk
- MEDIUM: Moderate risk, may require review
- HIGH: Significant risk, likely requires blocking
- CRITICAL: Severe risk, immediate escalation needed
Severity Scale (0-10)
- 0-1: Trivial/Minor impact
- 2-4: Moderate harm potential
- 5-9: Serious harm potential
- 10: Catastrophic harm potential
Breadth Scale (0-10)
- 0-1: Very limited/theoretical impact
- 2-4: Limited subset affected
- 5-9: Large population impact
- 10: Wide-scale/majority impact
๐งฉ Architecture
openevln/
โโโ pipeline.py # Main orchestration pipeline
โโโ demo.py # Interactive demo with test suites
โโโ safety_types/ # Data models and type definitions
โ โโโ __init__.py
โ โโโ model.py # SafetyResult, Overall, Threat, etc.
โโโ detectors/ # Detection modules
โ โโโ regex_detector.py # Pattern-based detection
โ โโโ behavior_detector.py # Behavioral signal analysis
โ โโโ embedding_detector.py # Semantic similarity (optional)
โ โโโ classifier.py # ML classifier wrapper (optional)
โโโ fusion/ # Risk fusion logic
โ โโโ risk_fusion.py # Basic fusion (legacy)
โ โโโ enhanced_risk_fusion.py # Advanced fusion with multipliers
โโโ decisions/ # Policy and recommendation engine
โ โโโ policy.py # Action recommendations
โโโ resources/ # Configuration and patterns
โโโ patterns.yml # Risk category definitions
โโโ schema.json # JSON schema for outputs
๐ง Configuration
Pattern Categories (resources/patterns.yml)
The system includes 20+ predefined risk categories:
- Medical Misinformation (Severity: 10, Breadth: 10)
- Vehicle Theft (Severity: 5, Breadth: 2)
- Cybersecurity Attacks (Severity: 5, Breadth: 5)
- Violence & Harm (Severity: 10, Breadth: 2)
- Financial Fraud (Severity: 5, Breadth: 5)
- Securities Fraud (Severity: 5, Breadth: 5)
- Weapons & Explosives (Severity: 10, Breadth: 5)
- Drug Manufacturing (Severity: 10, Breadth: 5)
- Minors Exploitation (Severity: 10, Breadth: 2)
- Hate Speech (Severity: 5, Breadth: 5)
- Infrastructure Attacks (Severity: 10, Breadth: 10)
- Aviation Security (Severity: 10, Breadth: 5)
- AI Abuse (Severity: 7, Breadth: 5)
- And more...
Adding Custom Patterns
Edit resources/patterns.yml:
custom_category:
base_severity: 5
base_breadth: 3
patterns:
- "\\b(pattern1|pattern2)\\b"
- "\\b(another.{0,10}pattern)\\b"
๐งช Demo & Testing
The included demo script provides comprehensive test suites:
# Run all test suites
python demo.py --test all --verbose
# Available test suites:
python demo.py --test medical # Medical misinformation
python demo.py --test vehicle # Vehicle theft scenarios
python demo.py --test cyber # Cybersecurity threats
python demo.py --test violence # Violence and harm
python demo.py --test financial # Financial fraud
python demo.py --test ai # AI abuse scenarios
python demo.py --test challenge # Complex challenge cases
Sample Test Cases
The demo includes realistic test scenarios:
- Safe Content: Legitimate advice and information
- Unsafe Content: Detailed harmful instructions
- Edge Cases: Complex scenarios requiring nuanced analysis
- Challenge Cases: Sophisticated attempts to bypass detection
๐ Advanced Usage
Custom Pipeline Configuration
from detectors.regex_detector import RegexDetector
from detectors.behavior_detector import BehaviorDetector
from detectors.embedding_detector import EmbeddingDetector
# Custom exemplars for semantic detection
exemplars = {
"custom_category": ["example unsafe text", "another example"],
"medical_misinformation": ["bleach cures covid", "miracle cure cancer"]
}
# Initialize components
regex = RegexDetector.load_default()
behavior = BehaviorDetector()
embedding = EmbeddingDetector(exemplars=exemplars)
# Create custom pipeline
pipe = SafetyPipeline(regex, behavior, embedding, threshold=0.4)
Batch Processing
test_cases = [
("query1", "response1"),
("query2", "response2"),
# ... more cases
]
results = []
for query, response in test_cases:
result = pipe.evaluate(query, response)
results.append({
'safe': result.overall.is_safe,
'risk_level': result.overall.risk_level,
'score': result.overall.composite_risk_score,
'threats': [t.category for t in result.threats]
})
Integration with ML Models
from detectors.classifier import Classifier
from sklearn.linear_model import LogisticRegression
# Train your classifier
model = LogisticRegression()
# ... training code ...
# Integrate with pipeline
classifier = Classifier(model, labels=['safe', 'unsafe'])
pipe = SafetyPipeline(regex, behavior, embedding, classifier)
๐ Performance Characteristics
- Throughput: ~100-500 evaluations/second (depending on text length and ML components)
- Latency:
- Regex + Behavioral: ~10-50ms
- With Embeddings: ~100-300ms
- With Custom Classifier: Variable
- Memory: ~100-500MB (depending on embedding models)
๐ก๏ธ Safety Policy Integration
Recommended Usage Patterns
def content_moderation_pipeline(user_query, ai_response):
result = pipe.evaluate(user_query, ai_response)
if result.recommendations.immediate_escalation:
# Critical threat - immediate human review
escalate_to_human(result)
return "BLOCKED"
elif result.recommendations.action == "BLOCK":
# High risk - block and log
log_blocked_content(result)
return "BLOCKED"
elif result.recommendations.human_review_required:
# Medium risk - queue for review
queue_for_review(result)
return "REVIEW"
else:
# Low risk - allow with monitoring
log_safe_content(result)
return "ALLOW"
Custom Policy Rules
def custom_policy(result):
# Zero tolerance for certain categories
critical_categories = ['minors_exploitation', 'weapons_explosives']
for threat in result.threats:
if threat.category in critical_categories:
return "IMMEDIATE_BLOCK"
# Context-specific rules
if result.overall.composite_risk_score > 0.8:
return "BLOCK"
elif result.overall.composite_risk_score > 0.3:
return "REVIEW"
else:
return "ALLOW"
๐ง Dependencies
Required
pyyaml- Pattern configuration loadingdataclasses-json- Serialization supportrich- Demo interface formatting
Optional
sentence-transformers- Semantic similarity detectionscikit-learn- ML classifier supportnumpy- Numerical computations
Installation
# Minimal installation
pip install pyyaml dataclasses-json rich
# Full installation with ML support
pip install pyyaml dataclasses-json rich sentence-transformers scikit-learn numpy
๐ค Contributing
- Fork & Branch: Create feature branches from main
- Code Style: Follow existing patterns, add type hints
- Testing: Add test cases for new detectors/patterns
- Documentation: Update README and docstrings
- Performance: Benchmark changes against existing implementation
Adding New Detectors
class CustomDetector:
def analyze(self, text: str) -> Dict[str, Any]:
# Your detection logic here
return {
"custom_metric": score,
"details": analysis_details
}
Adding New Risk Categories
- Add patterns to
resources/patterns.yml - Test with demo script
- Update documentation
- Consider severity/breadth calibration
๐ License
Apache-2.0 (permissive, enterprise-friendly)
๐ฏ Use Cases
- LLM Safety: Pre/post-processing for AI model outputs
- Content Moderation: Social media, forums, chat platforms
- Compliance: Regulatory compliance checking
- Research: AI safety research and red-teaming
- Education: Teaching AI safety concepts
- Enterprise: Internal content review workflows
๐ฎ Roadmap
Current (v1.0)
- โ Multi-dimensional risk assessment
- โ Hybrid detection (regex + behavioral + semantic)
- โ Comprehensive test suites
- โ Rich output formatting
Near-term (v1.1)
- ๐ REST API wrapper
- ๐ Streaming evaluation support
- ๐ Performance optimizations
- ๐ Additional language support
Future (v2.0+)
- ๐ฎ Plugin architecture
- ๐ฎ Real-time monitoring dashboard
- ๐ฎ Advanced ML integration
- ๐ฎ Regulatory compliance packs
๐ Support
- Issues: Use GitHub Issues for bug reports
- Discussions: GitHub Discussions for questions
- Documentation: This README and inline code comments
- Examples: See
demo.pyfor comprehensive usage examples
OpenEVLN: Making AI evaluation transparent, explainable, and actionable.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file openevln-0.1.2.tar.gz.
File metadata
- Download URL: openevln-0.1.2.tar.gz
- Upload date:
- Size: 18.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
92b225a51fb61def19cded7e8b615e4499d7ce6d1eba4f889b731dc7fd7355f4
|
|
| MD5 |
658abf0aa6603fec3f5cade7be239332
|
|
| BLAKE2b-256 |
240358f39e3ddf21707f9b5fb49ba217df0b9f9f1e04baf8982bbdfd93acb13f
|
Provenance
The following attestation bundles were made for openevln-0.1.2.tar.gz:
Publisher:
python-publish.yml on sachin-raja/openevln
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
openevln-0.1.2.tar.gz -
Subject digest:
92b225a51fb61def19cded7e8b615e4499d7ce6d1eba4f889b731dc7fd7355f4 - Sigstore transparency entry: 437627474
- Sigstore integration time:
-
Permalink:
sachin-raja/openevln@05d6fab44257cedd4f6c3a9c1c19572149e27dfc -
Branch / Tag:
refs/heads/main - Owner: https://github.com/sachin-raja
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@05d6fab44257cedd4f6c3a9c1c19572149e27dfc -
Trigger Event:
push
-
Statement type:
File details
Details for the file openevln-0.1.2-py3-none-any.whl.
File metadata
- Download URL: openevln-0.1.2-py3-none-any.whl
- Upload date:
- Size: 16.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a6b4a2b644679855c47bb1f5fe5c1f3e3e990cef3491861ab3f843b02dbb12de
|
|
| MD5 |
1d8ceb58476375d786de8e54cf016996
|
|
| BLAKE2b-256 |
b013d9cf26e2d82dbacfb5549953db26ffe81b30d313e3900f629214ac4a263e
|
Provenance
The following attestation bundles were made for openevln-0.1.2-py3-none-any.whl:
Publisher:
python-publish.yml on sachin-raja/openevln
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
openevln-0.1.2-py3-none-any.whl -
Subject digest:
a6b4a2b644679855c47bb1f5fe5c1f3e3e990cef3491861ab3f843b02dbb12de - Sigstore transparency entry: 437627483
- Sigstore integration time:
-
Permalink:
sachin-raja/openevln@05d6fab44257cedd4f6c3a9c1c19572149e27dfc -
Branch / Tag:
refs/heads/main - Owner: https://github.com/sachin-raja
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@05d6fab44257cedd4f6c3a9c1c19572149e27dfc -
Trigger Event:
push
-
Statement type: