# ๐ Stinger - AI Guardrails Framework
A powerful, easy-to-use Python framework for safeguarding LLM applications with comprehensive content filtering and moderation capabilities.
> **Alpha Release Available!** Install with `pip install stinger-guardrails-alpha`
## โจ Features
- **๐ก๏ธ Comprehensive Guardrails**: Toxicity detection, PII protection, code generation prevention, and more
- **๐ Security Audit Trail**: Complete logging of all security decisions for compliance and forensics
- **๐ฏ Simple API**: Get started in 3 lines of code
- **๐ REST API**: Language-agnostic HTTP/REST interface for non-Python integration
- **โก High Performance**: Async-ready with synchronous convenience wrapper
- **๐ง Configurable**: YAML-based configuration with runtime updates
- **๐งช Production Ready**: Comprehensive testing and error handling
- **๐ Well Documented**: Complete API reference and examples
## ๐ Quick Start
### Installation
```bash
# Install the alpha release
pip install stinger-guardrails-alpha
# Or install from source for development
pip install .
```
### Basic Usage
```python
from stinger import GuardrailPipeline
from stinger.core import audit
# Enable security audit trail (zero-config)
audit.enable() # Tracks all security decisions
# Create a pipeline from preset
pipeline = GuardrailPipeline.from_preset("customer_service")
# Check input content
result = pipeline.check_input("My credit card is 4532-1234-5678-9012")
if result['blocked']:
print(f"Input blocked: {result['reasons']}")
# Audit trail automatically logs: user input, guardrail decision, reasons
# Check output content
result = pipeline.check_output("Here's the code: import os; os.system('rm -rf /')")
if result['blocked']:
print(f"Output blocked: {result['reasons']}")
```
## ๐ค Python Library vs REST API
Choose the right approach for your use case:
| Feature | Python Library | REST API |
|---------|---------------|----------|
| **Setup** | `import stinger` | `stinger-api` server |
| **Performance** | โก Fastest (no network) | ๐ Fast (adds ~1-5ms) |
| **Language Support** | ๐ Python only | ๐ Any language |
| **Deployment** | ๐ฆ Part of your app | ๐ฅ๏ธ Separate service |
| **Scaling** | ๐ Scale with your app | ๐ Independent scaling |
| **Use When** | Building Python apps | Non-Python apps, microservices |
**Quick Decision**: Building a Python app? Use the library. Building anything else? Use the REST API.
## ๐ฅ๏ธ Command Line Interface (CLI)
After installing Stinger, you can use the CLI:
```sh
stinger demo
stinger check-prompt "My SSN is 123-45-6789."
stinger check-response "Here is your password: hunter2"
```
## ๐ REST API Service
Stinger provides a REST API for language-agnostic integration, browser extensions, and microservices:
### Starting the API Server
```bash
# Install with API support
pip install stinger-guardrails-alpha[api]
# Start the server
stinger-api
# Or start in background
stinger-api --detached
# Custom port
stinger-api --port 8080
```
### API Endpoints
- `GET /health` - Service health check
- `POST /v1/check` - Check content against guardrails
- `GET /v1/rules` - Get active guardrail configuration
### Quick Example
```bash
# Check content via API
curl -X POST http://localhost:8888/v1/check \
-H "Content-Type: application/json" \
-d '{
"text": "My SSN is 123-45-6789",
"kind": "prompt",
"preset": "customer_service"
}'
# Response
{
"action": "block",
"reasons": ["pii_check: PII detected (regex): ssn"],
"warnings": [],
"metadata": {"processing_time_ms": 12}
}
```
### Use Cases
- ๐ **Browser Extensions**: CORS-enabled for Chrome/Firefox extensions
- ๐ **Microservices**: Language-agnostic guardrail service
- ๐ฑ **Mobile Apps**: REST API for iOS/Android integration
- ๐ **Non-Python Apps**: Use Stinger from any language
See [REST API example](./examples/getting_started/12_rest_api_usage.py) for detailed usage.
## ๐ Interactive Demos
### Web Demo - Real-Time Guardrail Visualization
Experience Stinger's power through our interactive web interface that shows guardrails in action:
```bash
# Start the web demo (simplest method)
cd demos/web_demo
python start_demo.py
# Or run in background mode (useful for tools with timeouts)
python start_demo.py --detached
# Open http://127.0.0.1:8000 in your browser (use HTTP, not HTTPS)
```
**Features:**
- ๐ฌ Interactive chat interface with real-time guardrail feedback
- ๐ฆ Visual indicators showing which guardrails triggered
- ๐ Live audit trail visualization
- ๐ Switch between presets (customer service, medical, financial)
- โก See guardrails activate as you type
### Management Console - System Monitoring Dashboard
Monitor your Stinger deployment with our real-time management console:
```bash
# Start the management console (simplest method)
cd management-console
./start_console.sh
# Or run in background mode (useful for tools with timeouts)
./start_console.sh --detached
# Open http://localhost:3001 in your browser
```
**Features:**
- ๐ Real-time metrics and performance monitoring
- ๐ Active conversation tracking
- ๐ Guardrail trigger statistics
- ๐ฅ System health monitoring
- ๐ Historical data visualization
## ๐ก๏ธ Available Guardrails
Stinger offers multiple levels of protection with both fast regex-based and sophisticated AI-powered guardrails:
### ๐ Simple/Fast Guardrails (No API Key Required)
- **Simple PII Detection**: Regex-based detection of SSNs, credit cards, emails, phone numbers
- **Simple Toxicity Detection**: Keyword-based profanity and hate speech filtering
- **Simple Code Generation**: Pattern-based code snippet detection
- **Keyword Blocking**: Block specific words or phrases
- **URL Filtering**: Block or allow specific domains
- **Length Limiting**: Control input/output length
- **Regex Filtering**: Custom pattern matching
### ๐ค AI-Powered Guardrails (Requires OpenAI API Key)
- **AI PII Detection**: Context-aware PII detection using language models
- **AI Toxicity Detection**: Nuanced understanding of harmful content
- **AI Code Generation**: Sophisticated code pattern recognition
- **Content Moderation**: General inappropriate content detection
- **Topic Filtering**: AI-based allowed/blocked topic enforcement
### ๐ Prompt Injection Protection (Three Levels)
1. **Quick/Local Detection**: Fast pattern matching for common injection attempts
2. **AI-Powered Detection**: Single-turn analysis using language models
3. **Conversation-Aware AI**: Multi-turn context analysis for sophisticated attacks
- Configurable strategies: 'recent', 'suspicious', or 'mixed' context
- Risk levels: low, medium, high, critical
### ๐ฏ Usage Examples
```python
# Use simple guardrails for speed (no API key needed)
pipeline = GuardrailPipeline.from_preset("customer_service") # Uses simple versions
# Enable AI guardrails for better accuracy (requires API key)
export OPENAI_API_KEY="sk-..."
pipeline = GuardrailPipeline.from_preset("medical") # Uses AI versions
# Mix and match as needed
config = {
"input": [
{"type": "simple_pii_detection"}, # Fast PII check
{"type": "ai_toxicity_detection"}, # AI toxicity check
{"type": "prompt_injection", # Multi-turn injection detection
"config": {"conversation_aware": True}}
]
}
```
## ๐ Security Audit Trail
Stinger provides comprehensive security audit logging for compliance and forensic analysis:
### Zero-Config Audit Trail
```python
from stinger.core import audit
# Enable with smart defaults (just works!)
audit.enable()
# Or specify destination
audit.enable("./logs/security.log")
# With PII redaction for compliance
audit.enable("./logs/audit.log", redact_pii=True)
```
### Complete Security Tracking
- **User Prompts**: All user inputs logged with attribution
- **LLM Responses**: All AI responses tracked with context
- **Guardrail Decisions**: Every security decision with full reasoning
- **Conversation Flow**: Complete conversation reconstruction
- **User Attribution**: IP, session, user ID tracking for forensics
### Compliance-Standard Ready
- **PII Redaction Capabilities**: Automatically redact sensitive data while preserving audit value (useful for GDPR, HIPAA, and other privacy regulations)
- **Complete Audit Trail**: Comprehensive logging suitable for enterprise security reviews
- **Data Retention Controls**: Configurable retention policies for different data types
- **Forensic Analysis**: Full incident reconstruction capabilities
- **Export Formats**: Generate compliance-ready reports in standard formats
### Audit Trail Features
- **Smart Environment Detection**: Auto-configures for dev/prod/docker
- **Async Buffering**: Background processing with <10ms latency impact
- **Query Tools**: Easy audit trail searching and analysis
- **Export Capabilities**: CSV/JSON export for compliance reporting
- **Cannot be disabled in production**: Ensures audit trail integrity
## ๐ Configuration
Stinger uses YAML configuration files:
```yaml
version: "1.0"
pipeline:
input:
- name: toxicity_check
type: simple_toxicity_detection
enabled: true
confidence_threshold: 0.7
categories: [hate_speech, harassment, threats]
- name: pii_check
type: simple_pii_detection
enabled: true
confidence_threshold: 0.8
categories: [credit_card, ssn, email]
output:
- name: code_generation_check
type: simple_code_generation
enabled: true
confidence_threshold: 0.6
categories: [programming_keywords, code_blocks]
```
## ๐ฏ API Reference
### GuardrailPipeline
The main class for using Stinger guardrails.
```python
# Initialize
pipeline = GuardrailPipeline("config.yaml")
# Check content
result = pipeline.check_input(content)
result = pipeline.check_output(content)
# Get status
status = pipeline.get_guardrail_status()
# Dynamic configuration
pipeline.enable_guardrail("toxicity_check")
pipeline.disable_guardrail("pii_check")
pipeline.update_guardrail_config("toxicity_check", {"confidence_threshold": 0.9})
```
### Result Format
```python
{
'blocked': bool, # Whether content was blocked
'warnings': List[str], # List of warning messages
'reasons': List[str], # List of blocking reasons
'details': Dict[str, Any], # Detailed results from each guardrail
'pipeline_type': str # Type of pipeline ("input" or "output")
}
```
### Audit Trail API
```python
from stinger.core import audit
# Enable audit trail
audit.enable("./logs/audit.log")
# Query audit trail
records = audit.query(
conversation_id="conv_123",
user_id="user_456",
last_hour=True
)
# Export for compliance
audit.export_csv("./logs/audit.log", "compliance_report.csv")
# Get performance stats
stats = audit.get_stats()
print(f"Queued: {stats['queued']}, Written: {stats['written']}")
```
## ๐ Examples
### Basic Usage
```python
from stinger import GuardrailPipeline
pipeline = GuardrailPipeline("config.yaml")
# Simple content checking
result = pipeline.check_input("User input here")
if result['blocked']:
print(f"Blocked: {result['reasons']}")
elif result['warnings']:
print(f"Warnings: {result['warnings']}")
else:
print("Content approved")
```
### Advanced Usage
```python
from stinger import GuardrailPipeline, audit
# Enable security audit trail
audit.enable("./logs/audit.log", redact_pii=True)
# Initialize with custom config
pipeline = GuardrailPipeline("my_config.yaml")
# Get pipeline status
status = pipeline.get_guardrail_status()
print(f"Pipeline has {status['total_enabled']} enabled guardrails")
# Dynamically configure guardrails
pipeline.disable_guardrail("pii_check")
pipeline.enable_guardrail("toxicity_check")
# Update configuration
pipeline.update_guardrail_config("toxicity_check", {
'confidence_threshold': 0.9
})
# Process content with detailed results
result = pipeline.check_input("Test content")
print(f"Blocked: {result['blocked']}")
print(f"Reasons: {result['reasons']}")
print(f"Warnings: {result['warnings']}")
print(f"Details: {result['details']}")
# All security decisions automatically logged to audit trail
```
## ๐งช Testing
Run the demo to see Stinger in action:
```bash
# Run the tech support demo
cd demos/tech_support
python3 demo.py
# Run the simple example
python3 examples/getting_started/01_basic_installation.py
```
## ๐ Learning Resources
### Examples (`/examples`)
**Start here** - Minimal, focused code examples that mirror the Getting Started guide:
- `01_basic_installation.py` - Installation and basic setup
- `02_simple_guardrail.py` - Simple guardrail usage
- `03_global_rate_limiting.py` - Rate limiting configuration
- `04_conversation_api.py` - Conversation-based filtering
- `05_conversation_rate_limiting.py` - Conversation rate limiting
- `06_health_monitoring.py` - Health monitoring and status
- `07_cli_and_yaml_config.py` - CLI and YAML configuration
- `08_security_audit_trail.py` - Security audit trail setup and usage
- `09_troubleshooting_and_testing.py` - Testing and debugging
**Run examples:**
```bash
cd examples/getting_started
python 01_basic_installation.py
```
### Demos (`/demos`)
Advanced demonstrations showcasing specific features and scenarios:
- `conversation_aware_prompt_injection_demo.py` - Advanced prompt injection detection
- `global_rate_limiting_demo.py` - Rate limiting demonstrations
- `topic_filter_demo.py` - Topic-based filtering
- `tech_support/` - Complete tech support scenario with audit trail
**Run demos:**
```bash
cd demos
python conversation_aware_prompt_injection_demo.py
```
### Learning Path
1. **Start with examples** - Run through the numbered examples in order
2. **Explore demos** - Try the advanced demonstrations
3. **Check the tech support scenario** - See a complete real-world implementation
4. **Review API docs** - Deep dive into the complete API reference
## ๐ง Development
> **Note:** Stinger uses a modern `src/` layout. All package code is under `src/stinger/`.
### Installation from Source
```bash
git clone https://github.com/virtualsteve-star/stinger.git
cd stinger
pip install -e .
```
### Running Tests
```bash
pytest tests/
```
### Project Structure
```
src/
โโโ stinger/
โโโ core/ # Core components and high-level API
โโโ guardrails/ # Guardrail implementations
โโโ data/ # Keyword lists and data files
โโโ scenarios/ # Pre-configured scenarios
โโโ utils/ # Utilities and exceptions
โโโ adapters/ # Model adapters
โโโ cli.py # CLI entry point
โโโ ...
```
## ๐ค Contributing
We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.
## ๐ License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## ๐ Support
- ๐ [Documentation](docs/)
- ๐ [Issues](https://github.com/virtualsteve-star/stinger/issues)
---
**Made with โค๏ธ for safer AI applications**
Raw data
{
"_id": null,
"home_page": null,
"name": "stinger-guardrails-alpha",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.8",
"maintainer_email": "Steve <steve@example.com>",
"keywords": "ai, llm, guardrails, safety, security, content-moderation, prompt-injection, pii-detection",
"author": null,
"author_email": "Steve <steve@example.com>",
"download_url": "https://files.pythonhosted.org/packages/98/49/9b8dd7180296f53cf0553bb2fb786418cf9a4c2c9a5b8aad4d204d10e266/stinger_guardrails_alpha-0.1.0a5.tar.gz",
"platform": null,
"description": "# \ud83d\ude80 Stinger - AI Guardrails Framework\n\nA powerful, easy-to-use Python framework for safeguarding LLM applications with comprehensive content filtering and moderation capabilities.\n\n> **Alpha Release Available!** Install with `pip install stinger-guardrails-alpha`\n\n## \u2728 Features\n\n- **\ud83d\udee1\ufe0f Comprehensive Guardrails**: Toxicity detection, PII protection, code generation prevention, and more\n- **\ud83d\udd12 Security Audit Trail**: Complete logging of all security decisions for compliance and forensics\n- **\ud83c\udfaf Simple API**: Get started in 3 lines of code\n- **\ud83c\udf10 REST API**: Language-agnostic HTTP/REST interface for non-Python integration\n- **\u26a1 High Performance**: Async-ready with synchronous convenience wrapper\n- **\ud83d\udd27 Configurable**: YAML-based configuration with runtime updates\n- **\ud83e\uddea Production Ready**: Comprehensive testing and error handling\n- **\ud83d\udcda Well Documented**: Complete API reference and examples\n\n## \ud83d\ude80 Quick Start\n\n### Installation\n\n```bash\n# Install the alpha release\npip install stinger-guardrails-alpha\n\n# Or install from source for development\npip install .\n```\n\n### Basic Usage\n\n```python\nfrom stinger import GuardrailPipeline\nfrom stinger.core import audit\n\n# Enable security audit trail (zero-config)\naudit.enable() # Tracks all security decisions\n\n# Create a pipeline from preset\npipeline = GuardrailPipeline.from_preset(\"customer_service\")\n\n# Check input content\nresult = pipeline.check_input(\"My credit card is 4532-1234-5678-9012\")\nif result['blocked']:\n print(f\"Input blocked: {result['reasons']}\")\n # Audit trail automatically logs: user input, guardrail decision, reasons\n\n# Check output content\nresult = pipeline.check_output(\"Here's the code: import os; os.system('rm -rf /')\")\nif result['blocked']:\n print(f\"Output blocked: {result['reasons']}\")\n```\n\n## \ud83e\udd14 Python Library vs REST API\n\nChoose the right approach for your use case:\n\n| Feature | Python Library | REST API |\n|---------|---------------|----------|\n| **Setup** | `import stinger` | `stinger-api` server |\n| **Performance** | \u26a1 Fastest (no network) | \ud83d\ude80 Fast (adds ~1-5ms) |\n| **Language Support** | \ud83d\udc0d Python only | \ud83c\udf10 Any language |\n| **Deployment** | \ud83d\udce6 Part of your app | \ud83d\udda5\ufe0f Separate service |\n| **Scaling** | \ud83d\udcc8 Scale with your app | \ud83d\udd04 Independent scaling |\n| **Use When** | Building Python apps | Non-Python apps, microservices |\n\n**Quick Decision**: Building a Python app? Use the library. Building anything else? Use the REST API.\n\n## \ud83d\udda5\ufe0f Command Line Interface (CLI)\n\nAfter installing Stinger, you can use the CLI:\n\n```sh\nstinger demo\nstinger check-prompt \"My SSN is 123-45-6789.\"\nstinger check-response \"Here is your password: hunter2\"\n```\n\n## \ud83c\udf10 REST API Service\n\nStinger provides a REST API for language-agnostic integration, browser extensions, and microservices:\n\n### Starting the API Server\n\n```bash\n# Install with API support\npip install stinger-guardrails-alpha[api]\n\n# Start the server\nstinger-api\n\n# Or start in background\nstinger-api --detached\n\n# Custom port\nstinger-api --port 8080\n```\n\n### API Endpoints\n\n- `GET /health` - Service health check\n- `POST /v1/check` - Check content against guardrails\n- `GET /v1/rules` - Get active guardrail configuration\n\n### Quick Example\n\n```bash\n# Check content via API\ncurl -X POST http://localhost:8888/v1/check \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"text\": \"My SSN is 123-45-6789\",\n \"kind\": \"prompt\",\n \"preset\": \"customer_service\"\n }'\n\n# Response\n{\n \"action\": \"block\",\n \"reasons\": [\"pii_check: PII detected (regex): ssn\"],\n \"warnings\": [],\n \"metadata\": {\"processing_time_ms\": 12}\n}\n```\n\n### Use Cases\n\n- \ud83c\udf10 **Browser Extensions**: CORS-enabled for Chrome/Firefox extensions\n- \ud83d\udd17 **Microservices**: Language-agnostic guardrail service\n- \ud83d\udcf1 **Mobile Apps**: REST API for iOS/Android integration\n- \ud83d\ude80 **Non-Python Apps**: Use Stinger from any language\n\nSee [REST API example](./examples/getting_started/12_rest_api_usage.py) for detailed usage.\n\n## \ud83c\udf1f Interactive Demos\n\n### Web Demo - Real-Time Guardrail Visualization\n\nExperience Stinger's power through our interactive web interface that shows guardrails in action:\n\n```bash\n# Start the web demo (simplest method)\ncd demos/web_demo\npython start_demo.py\n\n# Or run in background mode (useful for tools with timeouts)\npython start_demo.py --detached\n\n# Open http://127.0.0.1:8000 in your browser (use HTTP, not HTTPS)\n```\n\n**Features:**\n- \ud83d\udcac Interactive chat interface with real-time guardrail feedback\n- \ud83d\udea6 Visual indicators showing which guardrails triggered\n- \ud83d\udcca Live audit trail visualization\n- \ud83d\udd04 Switch between presets (customer service, medical, financial)\n- \u26a1 See guardrails activate as you type\n\n### Management Console - System Monitoring Dashboard\n\nMonitor your Stinger deployment with our real-time management console:\n\n```bash\n# Start the management console (simplest method)\ncd management-console\n./start_console.sh\n\n# Or run in background mode (useful for tools with timeouts)\n./start_console.sh --detached\n\n# Open http://localhost:3001 in your browser\n```\n\n**Features:**\n- \ud83d\udcc8 Real-time metrics and performance monitoring\n- \ud83d\udd0d Active conversation tracking\n- \ud83d\udcca Guardrail trigger statistics\n- \ud83c\udfe5 System health monitoring\n- \ud83d\udcc9 Historical data visualization\n\n## \ud83d\udee1\ufe0f Available Guardrails\n\nStinger offers multiple levels of protection with both fast regex-based and sophisticated AI-powered guardrails:\n\n### \ud83d\ude80 Simple/Fast Guardrails (No API Key Required)\n- **Simple PII Detection**: Regex-based detection of SSNs, credit cards, emails, phone numbers\n- **Simple Toxicity Detection**: Keyword-based profanity and hate speech filtering \n- **Simple Code Generation**: Pattern-based code snippet detection\n- **Keyword Blocking**: Block specific words or phrases\n- **URL Filtering**: Block or allow specific domains\n- **Length Limiting**: Control input/output length\n- **Regex Filtering**: Custom pattern matching\n\n### \ud83e\udd16 AI-Powered Guardrails (Requires OpenAI API Key)\n- **AI PII Detection**: Context-aware PII detection using language models\n- **AI Toxicity Detection**: Nuanced understanding of harmful content\n- **AI Code Generation**: Sophisticated code pattern recognition\n- **Content Moderation**: General inappropriate content detection\n- **Topic Filtering**: AI-based allowed/blocked topic enforcement\n\n### \ud83d\udd10 Prompt Injection Protection (Three Levels)\n1. **Quick/Local Detection**: Fast pattern matching for common injection attempts\n2. **AI-Powered Detection**: Single-turn analysis using language models\n3. **Conversation-Aware AI**: Multi-turn context analysis for sophisticated attacks\n - Configurable strategies: 'recent', 'suspicious', or 'mixed' context\n - Risk levels: low, medium, high, critical\n\n### \ud83c\udfaf Usage Examples\n```python\n# Use simple guardrails for speed (no API key needed)\npipeline = GuardrailPipeline.from_preset(\"customer_service\") # Uses simple versions\n\n# Enable AI guardrails for better accuracy (requires API key)\nexport OPENAI_API_KEY=\"sk-...\"\npipeline = GuardrailPipeline.from_preset(\"medical\") # Uses AI versions\n\n# Mix and match as needed\nconfig = {\n \"input\": [\n {\"type\": \"simple_pii_detection\"}, # Fast PII check\n {\"type\": \"ai_toxicity_detection\"}, # AI toxicity check\n {\"type\": \"prompt_injection\", # Multi-turn injection detection\n \"config\": {\"conversation_aware\": True}}\n ]\n}\n```\n\n## \ud83d\udd12 Security Audit Trail\n\nStinger provides comprehensive security audit logging for compliance and forensic analysis:\n\n### Zero-Config Audit Trail\n```python\nfrom stinger.core import audit\n\n# Enable with smart defaults (just works!)\naudit.enable()\n\n# Or specify destination\naudit.enable(\"./logs/security.log\")\n\n# With PII redaction for compliance\naudit.enable(\"./logs/audit.log\", redact_pii=True)\n```\n\n### Complete Security Tracking\n- **User Prompts**: All user inputs logged with attribution\n- **LLM Responses**: All AI responses tracked with context\n- **Guardrail Decisions**: Every security decision with full reasoning\n- **Conversation Flow**: Complete conversation reconstruction\n- **User Attribution**: IP, session, user ID tracking for forensics\n\n### Compliance-Standard Ready\n- **PII Redaction Capabilities**: Automatically redact sensitive data while preserving audit value (useful for GDPR, HIPAA, and other privacy regulations)\n- **Complete Audit Trail**: Comprehensive logging suitable for enterprise security reviews\n- **Data Retention Controls**: Configurable retention policies for different data types\n- **Forensic Analysis**: Full incident reconstruction capabilities\n- **Export Formats**: Generate compliance-ready reports in standard formats\n\n### Audit Trail Features\n- **Smart Environment Detection**: Auto-configures for dev/prod/docker\n- **Async Buffering**: Background processing with <10ms latency impact\n- **Query Tools**: Easy audit trail searching and analysis\n- **Export Capabilities**: CSV/JSON export for compliance reporting\n- **Cannot be disabled in production**: Ensures audit trail integrity\n\n## \ud83d\udccb Configuration\n\nStinger uses YAML configuration files:\n\n```yaml\nversion: \"1.0\"\n\npipeline:\n input:\n - name: toxicity_check\n type: simple_toxicity_detection\n enabled: true\n confidence_threshold: 0.7\n categories: [hate_speech, harassment, threats]\n \n - name: pii_check\n type: simple_pii_detection\n enabled: true\n confidence_threshold: 0.8\n categories: [credit_card, ssn, email]\n \n output:\n - name: code_generation_check\n type: simple_code_generation\n enabled: true\n confidence_threshold: 0.6\n categories: [programming_keywords, code_blocks]\n```\n\n## \ud83c\udfaf API Reference\n\n### GuardrailPipeline\n\nThe main class for using Stinger guardrails.\n\n```python\n# Initialize\npipeline = GuardrailPipeline(\"config.yaml\")\n\n# Check content\nresult = pipeline.check_input(content)\nresult = pipeline.check_output(content)\n\n# Get status\nstatus = pipeline.get_guardrail_status()\n\n# Dynamic configuration\npipeline.enable_guardrail(\"toxicity_check\")\npipeline.disable_guardrail(\"pii_check\")\npipeline.update_guardrail_config(\"toxicity_check\", {\"confidence_threshold\": 0.9})\n```\n\n### Result Format\n\n```python\n{\n 'blocked': bool, # Whether content was blocked\n 'warnings': List[str], # List of warning messages\n 'reasons': List[str], # List of blocking reasons\n 'details': Dict[str, Any], # Detailed results from each guardrail\n 'pipeline_type': str # Type of pipeline (\"input\" or \"output\")\n}\n```\n\n### Audit Trail API\n\n```python\nfrom stinger.core import audit\n\n# Enable audit trail\naudit.enable(\"./logs/audit.log\")\n\n# Query audit trail\nrecords = audit.query(\n conversation_id=\"conv_123\",\n user_id=\"user_456\",\n last_hour=True\n)\n\n# Export for compliance\naudit.export_csv(\"./logs/audit.log\", \"compliance_report.csv\")\n\n# Get performance stats\nstats = audit.get_stats()\nprint(f\"Queued: {stats['queued']}, Written: {stats['written']}\")\n```\n\n## \ud83d\udcd6 Examples\n\n### Basic Usage\n```python\nfrom stinger import GuardrailPipeline\n\npipeline = GuardrailPipeline(\"config.yaml\")\n\n# Simple content checking\nresult = pipeline.check_input(\"User input here\")\nif result['blocked']:\n print(f\"Blocked: {result['reasons']}\")\nelif result['warnings']:\n print(f\"Warnings: {result['warnings']}\")\nelse:\n print(\"Content approved\")\n```\n\n### Advanced Usage\n```python\nfrom stinger import GuardrailPipeline, audit\n\n# Enable security audit trail\naudit.enable(\"./logs/audit.log\", redact_pii=True)\n\n# Initialize with custom config\npipeline = GuardrailPipeline(\"my_config.yaml\")\n\n# Get pipeline status\nstatus = pipeline.get_guardrail_status()\nprint(f\"Pipeline has {status['total_enabled']} enabled guardrails\")\n\n# Dynamically configure guardrails\npipeline.disable_guardrail(\"pii_check\")\npipeline.enable_guardrail(\"toxicity_check\")\n\n# Update configuration\npipeline.update_guardrail_config(\"toxicity_check\", {\n 'confidence_threshold': 0.9\n})\n\n# Process content with detailed results\nresult = pipeline.check_input(\"Test content\")\nprint(f\"Blocked: {result['blocked']}\")\nprint(f\"Reasons: {result['reasons']}\")\nprint(f\"Warnings: {result['warnings']}\")\nprint(f\"Details: {result['details']}\")\n\n# All security decisions automatically logged to audit trail\n```\n\n## \ud83e\uddea Testing\n\nRun the demo to see Stinger in action:\n\n```bash\n# Run the tech support demo\ncd demos/tech_support\npython3 demo.py\n\n# Run the simple example\npython3 examples/getting_started/01_basic_installation.py\n```\n\n## \ud83d\udcda Learning Resources\n\n### Examples (`/examples`)\n**Start here** - Minimal, focused code examples that mirror the Getting Started guide:\n- `01_basic_installation.py` - Installation and basic setup\n- `02_simple_guardrail.py` - Simple guardrail usage\n- `03_global_rate_limiting.py` - Rate limiting configuration\n- `04_conversation_api.py` - Conversation-based filtering\n- `05_conversation_rate_limiting.py` - Conversation rate limiting\n- `06_health_monitoring.py` - Health monitoring and status\n- `07_cli_and_yaml_config.py` - CLI and YAML configuration\n- `08_security_audit_trail.py` - Security audit trail setup and usage\n- `09_troubleshooting_and_testing.py` - Testing and debugging\n\n**Run examples:**\n```bash\ncd examples/getting_started\npython 01_basic_installation.py\n```\n\n### Demos (`/demos`)\nAdvanced demonstrations showcasing specific features and scenarios:\n- `conversation_aware_prompt_injection_demo.py` - Advanced prompt injection detection\n- `global_rate_limiting_demo.py` - Rate limiting demonstrations\n- `topic_filter_demo.py` - Topic-based filtering\n- `tech_support/` - Complete tech support scenario with audit trail\n\n**Run demos:**\n```bash\ncd demos\npython conversation_aware_prompt_injection_demo.py\n```\n\n### Learning Path\n1. **Start with examples** - Run through the numbered examples in order\n2. **Explore demos** - Try the advanced demonstrations\n3. **Check the tech support scenario** - See a complete real-world implementation\n4. **Review API docs** - Deep dive into the complete API reference\n\n## \ud83d\udd27 Development\n\n> **Note:** Stinger uses a modern `src/` layout. All package code is under `src/stinger/`.\n\n### Installation from Source\n\n```bash\ngit clone https://github.com/virtualsteve-star/stinger.git\ncd stinger\npip install -e .\n```\n\n### Running Tests\n\n```bash\npytest tests/\n```\n\n### Project Structure\n\n```\nsrc/\n \u2514\u2500\u2500 stinger/\n \u251c\u2500\u2500 core/ # Core components and high-level API\n \u251c\u2500\u2500 guardrails/ # Guardrail implementations\n \u251c\u2500\u2500 data/ # Keyword lists and data files\n \u251c\u2500\u2500 scenarios/ # Pre-configured scenarios\n \u251c\u2500\u2500 utils/ # Utilities and exceptions\n \u251c\u2500\u2500 adapters/ # Model adapters\n \u251c\u2500\u2500 cli.py # CLI entry point\n \u2514\u2500\u2500 ...\n```\n\n## \ud83e\udd1d Contributing\n\nWe welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.\n\n## \ud83d\udcc4 License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## \ud83c\udd98 Support\n\n- \ud83d\udcd6 [Documentation](docs/)\n- \ud83d\udc1b [Issues](https://github.com/virtualsteve-star/stinger/issues)\n\n---\n\n**Made with \u2764\ufe0f for safer AI applications** \n",
"bugtrack_url": null,
"license": "MIT",
"summary": "AI Guardrails Framework - Comprehensive LLM safety toolkit (Alpha)",
"version": "0.1.0a5",
"project_urls": {
"Documentation": "https://github.com/virtualsteve-star/stinger#readme",
"Homepage": "https://github.com/virtualsteve-star/stinger",
"Issues": "https://github.com/virtualsteve-star/stinger/issues",
"Repository": "https://github.com/virtualsteve-star/stinger"
},
"split_keywords": [
"ai",
" llm",
" guardrails",
" safety",
" security",
" content-moderation",
" prompt-injection",
" pii-detection"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "f17c58d4a54a79c93102f586d4e9d994b43df786b40d7fc771f0fda5839f21d6",
"md5": "7cd830114d8cfc85744816380206e691",
"sha256": "4464ed88de89f4721fe1eb9f962b213a76747c5fe5b9f7eb5d0be61cf688eab3"
},
"downloads": -1,
"filename": "stinger_guardrails_alpha-0.1.0a5-py3-none-any.whl",
"has_sig": false,
"md5_digest": "7cd830114d8cfc85744816380206e691",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.8",
"size": 126926,
"upload_time": "2025-07-11T22:36:31",
"upload_time_iso_8601": "2025-07-11T22:36:31.802713Z",
"url": "https://files.pythonhosted.org/packages/f1/7c/58d4a54a79c93102f586d4e9d994b43df786b40d7fc771f0fda5839f21d6/stinger_guardrails_alpha-0.1.0a5-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "98499b8dd7180296f53cf0553bb2fb786418cf9a4c2c9a5b8aad4d204d10e266",
"md5": "a369d2663531e865b9e9a16c3a24e5a2",
"sha256": "f3cbd0c6a8fb44e0527d9257e619b88b900b2ed031847d0dac50996e84e37a95"
},
"downloads": -1,
"filename": "stinger_guardrails_alpha-0.1.0a5.tar.gz",
"has_sig": false,
"md5_digest": "a369d2663531e865b9e9a16c3a24e5a2",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.8",
"size": 102525,
"upload_time": "2025-07-11T22:36:33",
"upload_time_iso_8601": "2025-07-11T22:36:33.081830Z",
"url": "https://files.pythonhosted.org/packages/98/49/9b8dd7180296f53cf0553bb2fb786418cf9a4c2c9a5b8aad4d204d10e266/stinger_guardrails_alpha-0.1.0a5.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-07-11 22:36:33",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "virtualsteve-star",
"github_project": "stinger#readme",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"requirements": [
{
"name": "pyyaml",
"specs": [
[
">=",
"6.0"
]
]
},
{
"name": "pytest",
"specs": [
[
">=",
"7.0"
]
]
},
{
"name": "pytest-asyncio",
"specs": [
[
">=",
"0.21.0"
]
]
},
{
"name": "watchdog",
"specs": [
[
">=",
"3.0.0"
]
]
},
{
"name": "cryptography",
"specs": [
[
">=",
"41.0.0"
]
]
},
{
"name": "openai",
"specs": [
[
">=",
"1.0.0"
]
]
},
{
"name": "jsonschema",
"specs": []
},
{
"name": "anyio",
"specs": [
[
">=",
"4.4.0"
]
]
},
{
"name": "h11",
"specs": [
[
">=",
"0.16.0"
]
]
},
{
"name": "zipp",
"specs": [
[
">=",
"3.19.1"
]
]
}
],
"lcname": "stinger-guardrails-alpha"
}