GuardianLayer
GuardianLayer is a meta-cognition layer for AI agents that prevents infinite loops, learns from failures, and provides self-awareness capabilities. It acts as a safety shield between your AI agent and external tools, ensuring robust and reliable agent behavior.
🌟 Key Features
🛡️ 5-Layer Protection System
- Layer 0: Smart Circuit Breaker - Three-state pattern (CLOSED/OPEN/HALF_OPEN) with automatic recovery and error classification
- Layer 1: Loop Detection - Hash-based O(1) detection of infinite loops and repetitive behavior
- Layer 2: Schema Validation - MCP-compatible tool call validation with custom hooks
- Layer 3: Experience Learning - Multi-tiered storage (Session/Process/Global) that learns from past successes and failures
- Layer 4: Advice Injection - Context-aware prompt injections to guide AI behavior
🚀 Performance
- O(1) loop detection using SHA-256 hashing instead of string comparison
- Smart caching for validation results and advice generation
- Async/await support for high-performance applications
- Pluggable backends - Bring your own database (PostgreSQL, Redis, etc.)
📊 Observability
- Health scoring (0-100) for each tool
- Detailed metrics for ROI visibility (tokens saved, loops prevented, etc.)
- Error classification (system vs user vs business errors)
- Tool reliability tracking based on historical success rates
📦 Installation
Install from PyPI:
pip install GuardianLayer
Or install from source for development:
git clone https://github.com/Mk3Ang8l/GuardianLayer.git
cd GuardianLayer
pip install -e '.[dev]'
🚀 Quick Start
Basic Usage
from GuardianLayer import GuardianLayer, AdviceStyle
# Initialize the guardian
guardian = GuardianLayer(
db_path="experience.db",
max_repeats=2,
advice_style=AdviceStyle.EXPERT
)
# Register MCP tools
mcp_tools = [{
"name": "web_search",
"description": "Search the web",
"inputSchema": {
"type": "object",
"properties": {
"query": {"type": "string"}
},
"required": ["query"]
}
}]
guardian.ingest_tools(mcp_tools)
# Check a tool call before executing
tool_call = {"tool": "web_search", "arguments": {"query": "Python tutorials"}}
result = guardian.check(tool_call)
if result["allowed"]:
# Execute the tool
response = execute_tool(tool_call)
# Report success/failure for learning
guardian.report_result(tool_call, success=True)
else:
print(f"Blocked: {result['reason']}")
print(f"Suggestion: {result['suggestion']}")
Async Usage
import asyncio
from GuardianLayer import GuardianLayer
async def main():
guardian = GuardianLayer()
# Async check
result = await guardian.check_async(tool_call)
if result["allowed"]:
response = await execute_tool_async(tool_call)
await guardian.report_result_async(tool_call, success=True)
await guardian.close_async()
asyncio.run(main())
Prompt Injection for Self-Awareness
# Get awareness context to inject into your LLM prompt
awareness = guardian.get_awareness_context()
prompt = f"""
You are an AI assistant.
{awareness}
User: {user_message}
"""
🏗️ Architecture
GuardianLayer uses a layered protection model:
┌─────────────────────────────────────┐
│ AI Agent (LLM) │
└─────────────┬───────────────────────┘
│ Proposed Tool Call
▼
┌─────────────────────────────────────┐
│ GuardianLayer │
│ ┌─────────────────────────────┐ │
│ │ L0: Circuit Breaker │ │ ← Health monitoring
│ ├─────────────────────────────┤ │
│ │ L1: Loop Detection │ │ ← Hash-based O(1)
│ ├─────────────────────────────┤ │
│ │ L2: Schema Validation │ │ ← MCP compatible
│ ├─────────────────────────────┤ │
│ │ L3: Experience Learning │ │ ← SQLite/PostgreSQL
│ ├─────────────────────────────┤ │
│ │ L4: Advice Generation │ │ ← Prompt injection
│ └─────────────────────────────┘ │
└─────────────┬───────────────────────┘
│ ✅ Allowed / ❌ Blocked
▼
┌─────────────────────────────────────┐
│ External Tools/APIs │
└─────────────────────────────────────┘
📚 Documentation
- Quick Start Guide - Get started in 5 minutes
- Architecture - Understanding the protection layers
- API Reference - Complete API documentation
- Configuration - All configuration options
- Integration Guide - Integration with LangChain, AutoGen, etc.
- Examples - Real-world usage examples
🔧 Advanced Features
Custom Storage Providers
from GuardianLayer import GuardianLayer
from GuardianLayer.interfaces import StorageProvider
class PostgreSQLStorageProvider(StorageProvider):
# Implement your custom storage backend
pass
guardian = GuardianLayer(storage_provider=PostgreSQLStorageProvider())
Custom Advice Resolvers
from GuardianLayer import AdviceContext
def my_custom_advice(context: AdviceContext) -> str:
if context.failure_count > 5:
return "🚨 CRITICAL: This tool is failing repeatedly!"
return ""
guardian.set_custom_advice_resolver(my_custom_advice)
Health Monitoring
# Get health metrics for all tools
health = guardian.health_monitor.get_all_health()
for tool_name, status in health.items():
print(f"{tool_name}: {status['score']}/100 - {status['state']}")
# Manually reset a tool's health
guardian.reset_tool("problematic_tool")
Metrics and ROI
# Get comprehensive metrics
metrics = guardian.get_metrics()
print(f"Loops prevented: {metrics['loops_prevented']}")
print(f"Circuit breaks: {metrics['circuit_breaks']}")
print(f"Estimated tokens saved: {metrics['tokens_saved']}")
print(f"Estimated latency saved: {metrics['latency_saved_ms']}ms")
🧪 Testing
Run the test suite:
pytest tests/ -v --cov=src
Run the demo examples:
python examples/demo.py
python examples/demo_v2.py
python examples/demo_cache_perf.py
🤝 Contributing
We welcome contributions! Please see CONTRIBUTING.md for guidelines.
Development Setup
# Clone the repository
git clone https://github.com/Mk3Ang8l/GuardianLayer.git
cd GuardianLayer
# Install development dependencies
pip install -e '.[dev]'
# Run tests
pytest -v
# Run linters
ruff check src/
mypy src/
📄 License
GuardianLayer is licensed under the MIT License. See LICENSE for details.
🙏 Acknowledgments
- Inspired by the need for safer AI agent systems
- Built for the MCP (Model Context Protocol) ecosystem
- Designed to work with any AI framework (LangChain, AutoGen, CrewAI, etc.)
💖 Support the Project
If you find GuardianLayer useful, consider supporting its development:
- PayPal: paypal.me/MicaPaul138
- Litecoin:
ltc1qr3qrxyccu5ssm22ny5ere5rl0ts0yergx6cy9c
Your support helps maintain and improve GuardianLayer!
📞 Support
- Documentation: https://github.com/Mk3Ang8l/GuardianLayer
- Issues: GitHub Issues
Made with ❤️ for safer AI agents
Metadata
Release files for GuardianLayer 2.0.5
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| guardianlayer-2.0.5.tar.gz | 83.9 kB | Without provenance | Details for guardianlayer-2.0.5.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| guardianlayer-2.0.5-py3-none-any.whl | Python 3 | none | any | Details for guardianlayer-2.0.5-py3-none-any.whl |
Total release size: 122.8 kB
Release files / guardianlayer-2.0.5.tar.gz
| Download URL | guardianlayer-2.0.5.tar.gz |
|---|---|
| Size | 83.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
88656ea9b35ab719591f9dd3eb88b766ce119e1249497b7f80ccbde311f5e102
|
|
BLAKE2b-256 checksum How to use checksums |
5f4f5833585ae4526ddd89ba58ac59bf3635ec2898f972cb8931a179cba34d50
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.10.19
|
Release files / guardianlayer-2.0.5-py3-none-any.whl
| Download URL | guardianlayer-2.0.5-py3-none-any.whl |
|---|---|
| Size | 38.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
cbe21804ffb9ab9db033276f94de729cab800f01f108092f33f2162d5ea42057
|
|
BLAKE2b-256 checksum How to use checksums |
b7e35d8fa5b83bfb8504aee0553c7b8266d946c65a5f9c4a521ae0896fc01618
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.10.19
|
Security for GuardianLayer 2.0.5
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.