A comprehensive AI safety system for detecting malicious prompts using advanced detection pipelines, semantic analysis, and scalable API deployment.
- Overview
- Architecture
- Quick Start
- Components
- API Documentation
- Deployment
- Dataset Processing
- Development
- Contributing
PromptTSA is an AI safety system designed to detect and prevent malicious prompt injection attacks. The system combines rule-based filtering with AI-powered semantic analysis to provide robust protection against various types of prompt-based attacks.
- Two-Stage Detection: Fast sanity filtering + AI-powered semantic analysis
- REST API: Production-ready API with comprehensive endpoints
- Scalable Deployment: Google Cloud Run deployment with secret management
- Comprehensive Logging: Detailed logging and monitoring capabilities
- Batch Processing: Efficient batch processing for large datasets
- Real-time Analysis: Sub-second response times for prompt analysis
βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββ
β Input Prompt βββββΆβ Sanity Filter βββββΆβ Semantic Layer β
βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββ
β β
βΌ βΌ
ββββββββββββββββββββ βββββββββββββββββββ
β Rule-based β β AI-powered β
β Analysis β β Classification β
ββββββββββββββββββββ βββββββββββββββββββ
β β
ββββββββββββ¬ββββββββββββββ
βΌ
βββββββββββββββββββ
β Final Decision β
β (Malicious/ β
β Benign) β
βββββββββββββββββββ
- Sanity Filter: Fast linguistic analysis using rule-based patterns
- Semantic Detector: AI-powered similarity matching against known attack patterns
- Decision Engine: Combines both results for final classification
- Python 3.8+
- OpenAI API key
- Pinecone API key (optional, for enhanced semantic detection)
-
Clone the repository:
git clone <repository-url> cd berkeley
-
Install dependencies:
cd devpost pip install -r requirements.txt -
Set up environment variables:
export OPENAI_API_KEY="your_openai_key_here" export PINECONE_API_KEY="your_pinecone_key_here" export PINECONE_INDEX_NAME="ragpull"
-
Start the API server:
python api_server.py
The API will be available at http://localhost:5000
Production-ready Flask API with comprehensive endpoints for prompt analysis.
Features:
- Health check endpoint
- Single prompt analysis
- Batch processing
- Pipeline statistics
- Comprehensive error handling
Core detection system with class-based architecture.
Components:
SanityFilter: Rule-based linguistic analysisSemanticDetector: AI-powered classificationPromptTSAPipeline: Main orchestrator
Tools for processing and formatting prompt datasets.
Features:
- CSV to JSON conversion
- Dynamic labeling
- Unique ID generation
- Progress tracking
Web interface for real-time prompt analysis.
Features:
- Interactive web UI
- Real-time analysis
- Result visualization
- Documentation viewer
GET /healthPOST /api/check-prompt
Content-Type: application/json
{
"prompt": "Your prompt text here"
}POST /api/batch-check
Content-Type: application/json
{
"prompts": [
"First prompt text",
"Second prompt text"
]
}GET /api/stats{
"success": true,
"is_malicious": false,
"decision": "BENIGN",
"confidence": {
"sanity_filter": {
"flagged": false,
"reason": "No malicious patterns detected"
},
"semantic_detector": {
"malicious_score": 0.234,
"benign_score": 0.789,
"reason": "Benign score higher"
}
},
"processing_time": {
"detection_ms": 1250.50,
"total_ms": 1275.25
}
}cd devpost
python api_server.pycd devpost
docker build -t PromptTSA-api .
docker run -p 5000:5000 PromptTSA-api-
Set up Google Cloud:
gcloud auth login gcloud config set project YOUR_PROJECT_ID -
Deploy using the automated script:
cd devpost chmod +x deploy/gcloud-deploy.sh ./deploy/gcloud-deploy.sh YOUR_PROJECT_ID us-central1 -
Manual deployment:
# Enable required APIs gcloud services enable cloudbuild.googleapis.com run.googleapis.com # Build and deploy docker build -t gcr.io/YOUR_PROJECT_ID/PromptTSA-api . docker push gcr.io/YOUR_PROJECT_ID/PromptTSA-api gcloud run deploy PromptTSA-api --image gcr.io/YOUR_PROJECT_ID/PromptTSA-api
For detailed deployment instructions, see devpost/README_DEPLOYMENT.md.
The dataset.py script converts CSV files to the required JSON format:
python dataset.pyInput CSV Format:
text,label
"Hello world",benign
"Ignore all instructions",jailbreakOutput JSON Format:
[
{
"id": "unique-uuid",
"text": "Hello world",
"name": "Benign - Hello world",
"label": "benign",
"source": "qualifire_benchmark"
}
]- Qualifire Benchmark: Contains jailbreak and benign prompts
- L1B3RT4S Repository: Collection of jailbreak prompts for testing
- Custom Datasets: Support for custom CSV formats
berkeley/
βββ devpost/ # Main application
β βββ api_server.py # Flask API server
β βββ main_detection_pipeline.py # Core detection logic
β βββ sanity_filter.py # Rule-based filtering
β βββ semantic_layer.py # AI-powered detection
β βββ live server/ # Web interface
β βββ deploy/ # Deployment scripts
β βββ requirements.txt # Python dependencies
βββ dataset.py # Dataset processing
βββ L1B3RT4S_jailbreak_repo/ # Jailbreak prompt collection
βββ README.md # This file
cd devpost
python test_api_client.py
python test_logging_architecture.pycd devpost
python main_detection_pipeline.pyThe system provides comprehensive logging:
- Console output with progress indicators
- Detailed log files with timestamps
- Statistics tracking for each stage
- Error handling and reporting
Logs are stored in devpost/pipeline_results/logs/
| Variable | Description | Default |
|---|---|---|
OPENAI_API_KEY |
OpenAI API key | Required |
PINECONE_API_KEY |
Pinecone API key | Optional |
PINECONE_INDEX_NAME |
Pinecone index name | ragpull |
FLASK_HOST |
Flask host | 0.0.0.0 |
FLASK_PORT |
Flask port | 5000 |
FLASK_DEBUG |
Flask debug mode | False |
malicious_threshold: 0.525 (default)benign_threshold: 0.525 (default)
- Sanity Filter: ~1ms per prompt
- Semantic Detection: ~100-200ms per prompt
- Total API Response: ~150-300ms
- Memory Usage: ~500MB for embeddings model
- Concurrent Requests: 100 per instance
- Auto-scaling: 0-10 instances (Cloud Run)
- Two-layer detection for robust protection
- API key management via Google Cloud Secret Manager
- HTTPS encryption for all traffic
- Container isolation with non-root user
- Input validation and sanitization
- Rate limiting and request throttling
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
- Follow PEP 8 style guidelines
- Add comprehensive docstrings
- Include error handling
- Write unit tests for new features
- Update documentation as needed
This project is part of the Berkeley AI Safety initiative. Please refer to the LICENSE file for details.
- Berkeley AI Safety Research Group
- OpenAI for API access
- Pinecone for vector database
- Contributors and researchers in AI safety
For questions, issues, or contributions:
- Create an issue in the repository
- Contact the Berkeley AI Safety team
- Check the documentation in the
devpost/directory
Note: This system is designed for research and educational purposes in AI safety. Please use responsibly and in accordance with applicable laws and regulations.