Zero-Config Governance with @guard¶
The @guard decorator provides the fastest way to add governance to your AI agents without writing policy files or configuration.
Quick Start¶
Install ACGP and add the decorator to any function:
from acgp import guard
@guard(max_spend=50.0, blocked_keywords=["password", "ssn"])
def process_payment(amount: float, description: str):
"""Process a payment transaction."""
# Your agent logic here
return {"status": "success", "amount": amount}
# This will be allowed
result = process_payment(25.0, "Coffee purchase")
# This will be denied (exceeds max_spend)
result = process_payment(100.0, "Large purchase") # Raises PermissionError
Features¶
Simple Tripwires¶
Use simple string expressions to define limits:
@guard(tripwires=["amount < 1000", "count <= 5"])
def execute_trade(amount: float, count: int):
return trade_logic(amount, count)
Blocked Keywords¶
Block actions that mention sensitive information:
@guard(blocked_keywords=["password", "credit_card", "ssn"])
def generate_response(user_input: str):
# Will be denied if reasoning contains blocked keywords
return ai_response(user_input)
Special Tripwires¶
Built-in shortcuts for common patterns:
@guard(tripwires=["no_pii"])
def log_user_activity(user_data: dict):
# Blocks if PII is detected in reasoning
return logger.log(user_data)
Custom Rules¶
For more complex conditions, define custom rules:
@guard(rules=[
{
"name": "high_risk_check",
"condition": "parameters.risk_score > 0.8",
"action": "review",
"message": "High risk transaction requires review"
}
])
def approve_loan(amount: float, risk_score: float):
return process_loan(amount)
Parameters¶
| Parameter | Type | Description |
|---|---|---|
tripwires |
List[str] |
Simple tripwire expressions (e.g., ["spend < 50"]) |
rules |
List[Dict] |
Custom rule dictionaries for complex logic |
max_spend |
float |
Maximum spend limit (shortcut for amount tripwire) |
blocked_keywords |
List[str] |
Keywords to block in reasoning |
action_name |
str |
Override action name (defaults to function name) |
on_deny |
Callable |
Callback when action is denied |
on_review |
Callable |
Callback when action needs review |
Handling Interventions¶
Default Behavior¶
By default:
- DENY/HALT: Raises PermissionError
- REVIEW: Logs warning and continues
- ALLOW/NUDGE/FLAG: Executes normally
Custom Callbacks¶
Handle denials and reviews with custom logic:
def handle_denial(result):
"""Called when governance denies the action."""
log.error(f"Action denied: {result.message}")
return {"status": "denied", "reason": result.message}
def handle_review(result, func, *args, **kwargs):
"""Called when action needs review."""
# Send to human review queue
review_queue.add(result, func, args, kwargs)
return {"status": "pending_review"}
@guard(
max_spend=1000.0,
on_deny=handle_denial,
on_review=handle_review
)
def high_value_transaction(amount: float):
return process_transaction(amount)
Tripwire Expression Syntax¶
Supported operators:
<,>,<=,>=,==,!=- Field references:
amount,count,parameters.field_name - Special keywords:
no_pii
Examples:
tripwires=[
"amount > 100", # Numeric comparison
"count <= 5", # Limit iterations
"parameters.risk < 0.5", # Nested field access
"no_pii", # Built-in PII check
]
When to Upgrade¶
The @guard decorator is perfect for:
- Quick prototyping
- Simple agents with basic limits
- Getting started with ACGP
- Single-file scripts
Consider upgrading to policy files when you need: - Different rules for different actions - Governance contracts (speed vs. safety) - Standard or Complete conformance - Team-shared policies - Auditability and compliance
Examples¶
E-commerce Agent¶
from acgp import guard
@guard(
max_spend=500.0,
tripwires=["quantity <= 10"],
blocked_keywords=["fraud", "stolen"]
)
def place_order(item: str, quantity: int, price: float):
total = quantity * price
return checkout(item, quantity, total)
Customer Support Bot¶
@guard(
blocked_keywords=["password", "ssn", "credit_card"],
rules=[{
"condition": "confidence < 0.7",
"action": "review",
"message": "Low confidence, escalate to human"
}]
)
def generate_support_response(query: str, confidence: float):
return llm.generate(query)
Financial Trading Agent¶
@guard(
max_spend=10000.0,
tripwires=["parameters.leverage <= 3"],
on_review=send_to_compliance_team
)
def execute_trade(symbol: str, amount: float, leverage: int):
return trading_api.execute(symbol, amount, leverage)
Migration Path¶
Start with @guard, then migrate to policy files as needed:
Step 1: Zero-config (Today)
Step 2: Policy file (As you scale)
Step 3: Advanced features (Production)
# blueprint.yaml
conformance_level: standard
contracts:
- action: my_action
risk_level: elevated_risk
performance_budget:
latency_budget_ms: 300
Best Practices¶
- Start Simple: Use
max_spendandblocked_keywordsfirst - Test Limits: Verify your tripwires with boundary cases
- Handle Errors: Use
on_denyfor graceful error handling - Add Logging: Track governance decisions for debugging
- Upgrade When Ready: Move to policy files as complexity grows