Skip to main content

Automation Engine

Overview

The OWL AI Platform Automation Engine provides intelligent workflow automation for AI governance. It automatically matches incoming agent actions against configured playbooks, executes appropriate responses, and tracks performance metrics. The engine enables organizations to reduce manual review overhead while maintaining strict governance controls.

Key Capabilities

  • Playbook Matching: Automatically match actions to playbooks based on trigger conditions
  • Action Execution: Execute automated responses (approve, deny, escalate, notify)
  • Business Hours Detection: Time-aware automation with EST business hours support
  • Real-Time Metrics: Track execution counts, success rates, and cost savings
  • Audit Trail: Complete logging of all automated decisions
  • Fail-Safe Design: Graceful error handling with conservative fallbacks

How It Works

Automation Flow

┌─────────────────────────────────────────────────────────────────────────────────┐
│ AUTOMATION ENGINE FLOW │
└─────────────────────────────────────────────────────────────────────────────────┘

┌──────────────────┐
│ Agent Action │
│ Submitted │
└────────┬─────────┘

v
┌──────────────────────────────────────────────────────────────┐
│ AUTOMATION SERVICE │
│ │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ 1. MATCH PLAYBOOKS │ │
│ │ - Query active playbooks │ │
│ │ - Evaluate trigger conditions │ │
│ │ - Return first match (FIFO order) │ │
│ └───────────────────────────┬─────────────────────────────┘ │
│ │ │
│ v │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ 2. EXECUTE PLAYBOOK │ │
│ │ - Validate playbook exists │ │
│ │ - Validate action exists │ │
│ │ - Create execution record │ │
│ │ - Execute actions (approve, notify, etc.) │ │
│ │ - Update statistics │ │
│ └───────────────────────────┬─────────────────────────────┘ │
│ │ │
│ v │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ 3. RECORD METRICS │ │
│ │ - Increment execution count │ │
│ │ - Update success rate │ │
│ │ - Calculate cost savings │ │
│ └─────────────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────────────┘

v
┌──────────────────┐
│ Action Updated │
│ (Approved/etc) │
└──────────────────┘

Condition Matching Logic

The automation engine evaluates conditions in this order:

def matches_conditions(action_data, conditions):
"""
ALL specified conditions must match for playbook to trigger.
Conditions not specified are ignored.
"""

# 1. Risk Score Maximum
if 'risk_score_max' in conditions:
if action_data['risk_score'] > conditions['risk_score_max']:
return False # Risk too high

# 2. Risk Score Minimum
if 'risk_score_min' in conditions:
if action_data['risk_score'] < conditions['risk_score_min']:
return False # Risk too low

# 3. Business Hours
if conditions.get('business_hours'):
if not is_business_hours():
return False # Outside business hours

# 4. Weekend Check
if 'weekend' in conditions:
is_weekend = datetime.now().weekday() >= 5
if conditions['weekend'] != is_weekend:
return False # Weekend mismatch

# 5. Action Types
if 'action_types' in conditions:
if action_data['action_type'] not in conditions['action_types']:
return False # Action type not allowed

return True # All conditions matched

Business Hours Definition

Business hours are defined as:

  • Days: Monday through Friday (weekdays only)
  • Hours: 9:00 AM to 5:00 PM
  • Timezone: America/New_York (EST/EDT)
def is_business_hours():
"""Check if current time is during business hours"""
est = pytz.timezone('America/New_York')
now = datetime.now(est)

# Check weekday (Mon=0, Sun=6)
if now.weekday() >= 5:
return False # Weekend

# Check time range
if now.hour < 9 or now.hour >= 17:
return False # Outside 9am-5pm

return True

Configuration

Playbook Trigger Conditions

{
"trigger_conditions": {
"risk_score_max": 40,
"risk_score_min": 0,
"action_types": ["database_read", "file_read", "api_get"],
"business_hours": true,
"weekend": false
}
}

Condition Parameters

ParameterTypeDescriptionExample
risk_score_maxIntegerMaximum risk score (inclusive)40
risk_score_minIntegerMinimum risk score (inclusive)0
action_typesArrayAllowed action types["read", "list"]
business_hoursBooleanMust be during business hourstrue
weekendBooleanMust be on weekendfalse

Usage Examples

Basic Automation Setup

from owlai import OWLClient

client = OWLClient(api_key="your_api_key")

# Create a playbook for automation
playbook = client.playbooks.create(
id="pb-auto-approve-reads",
name="Auto-Approve Read Operations",
status="active",
risk_level="low",
trigger_conditions={
"risk_score_max": 35,
"action_types": ["database_read", "file_read"],
"business_hours": True
},
actions=[
{"type": "approve", "parameters": {}},
{"type": "log", "parameters": {}}
]
)

# Now when actions matching these conditions come in,
# they will be automatically approved

Using the Automation Service Directly

from services.automation_service import AutomationService, get_automation_service

# Get automation service instance
automation = get_automation_service(db)

# Check if action matches any playbook
action_data = {
'risk_score': 25,
'action_type': 'database_read',
'agent_id': 'analytics-agent',
'timestamp': datetime.utcnow()
}

matching_playbook = automation.match_playbooks(action_data)

if matching_playbook:
print(f"Matched playbook: {matching_playbook.name}")

# Execute the playbook
result = automation.execute_playbook(
playbook_id=matching_playbook.id,
action_id=12345
)

if result['success']:
print(f"Action auto-approved via playbook")
print(f"Execution ID: {result['execution_id']}")
else:
print(f"Execution failed: {result['message']}")
else:
print("No matching playbook - manual review required")

Check Business Hours

from services.automation_service import get_automation_service

automation = get_automation_service(db)

if automation.is_business_hours():
print("Currently in business hours - automation active")
else:
print("Outside business hours - stricter rules apply")

Get Playbook Metrics

# Get real-time metrics for a playbook
metrics = automation.get_playbook_metrics("pb-auto-approve-reads")

print(f"Total Executions: {metrics['execution_count']}")
print(f"Success Rate: {metrics['success_rate']}%")
print(f"Last Executed: {metrics['last_executed']}")
print(f"Triggers (24h): {metrics['triggers_last_24h']}")
print(f"Cost Savings (24h): ${metrics['cost_savings_24h']}")
print(f"Avg Response Time: {metrics['avg_response_time_seconds']}s")

# Output:
# Total Executions: 1523
# Success Rate: 98.5%
# Last Executed: 2026-01-20T14:30:00Z
# Triggers (24h): 87
# Cost Savings (24h): $1087.50
# Avg Response Time: 2s

API: Execute Automation Check

# Check if action would trigger automation
curl -X POST https://api.owlai.io/v1/automation/check \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"action_data": {
"risk_score": 25,
"action_type": "database_read",
"agent_id": "analytics-agent"
}
}'

# Response:
# {
# "would_automate": true,
# "matching_playbook": {
# "id": "pb-auto-approve-reads",
# "name": "Auto-Approve Read Operations",
# "actions": ["approve", "log"]
# },
# "matched_conditions": [
# "risk_score <= 35",
# "action_type in [database_read, file_read]",
# "business_hours = true"
# ]
# }

API: Get Automation Metrics

curl -X GET https://api.owlai.io/v1/automation/metrics \
-H "Authorization: Bearer $TOKEN"

# Response:
# {
# "total_automations_24h": 342,
# "success_rate": 98.2,
# "cost_savings_24h": 4275.00,
# "top_playbooks": [
# {
# "id": "pb-auto-approve-reads",
# "executions": 245,
# "success_rate": 99.1
# },
# {
# "id": "pb-low-risk-notify",
# "executions": 97,
# "success_rate": 96.8
# }
# ],
# "actions_by_type": {
# "approve": 287,
# "notify": 342,
# "escalate": 55
# }
# }

Playbook Execution Record

Each playbook execution creates an audit record:

{
"execution_id": 12345,
"playbook_id": "pb-auto-approve-reads",
"action_id": 67890,
"executed_by": "automation_system",
"execution_context": "automatic",
"started_at": "2026-01-20T14:30:00Z",
"completed_at": "2026-01-20T14:30:01Z",
"duration_seconds": 1,
"execution_status": "completed",
"input_data": {
"risk_score": 25,
"action_type": "database_read",
"agent_id": "analytics-agent"
},
"execution_details": {
"auto_approved": true,
"reason": "Matched playbook trigger conditions",
"playbook_name": "Auto-Approve Read Operations",
"risk_score": 25
}
}

Cost Savings Calculation

The automation engine calculates cost savings based on:

MetricDefault ValueDescription
Time per manual approval15 minutesAverage human review time
Hourly cost$50/hourFully-loaded employee cost
Cost per approval$12.5015 min x $50/hr
# Example calculation
executions_24h = 87
cost_per_approval = 12.50
cost_savings_24h = executions_24h * cost_per_approval
# = 87 x $12.50 = $1,087.50

Monthly Savings Projection

# Project monthly savings
monthly_savings = client.automation.project_savings(
playbook_id="pb-auto-approve-reads",
projection_days=30
)

print(f"Projected executions: {monthly_savings['projected_executions']}")
print(f"Projected savings: ${monthly_savings['projected_savings']}")
print(f"Time saved: {monthly_savings['hours_saved']} hours")

# Output:
# Projected executions: 2,610
# Projected savings: $32,625.00
# Time saved: 652.5 hours

Triggers and Actions

Supported Triggers

Trigger TypeDescriptionConfiguration
Risk-BasedTrigger on risk score thresholdsrisk_score_min, risk_score_max
Action-BasedTrigger on specific action typesaction_types
Time-BasedTrigger during specific hoursbusiness_hours, time_range
Agent-BasedTrigger for specific agentsagent_ids
Environment-BasedTrigger in specific environmentsenvironments

Supported Actions

ActionDescriptionResult
approveAuto-approve the actionAction status = approved
denyBlock the actionAction status = denied
escalateEscalate to higher approval levelApproval level increased
notifySend notificationEmail sent to recipients
logCreate audit entryAudit log created
quarantineTemporarily blockAction held for duration
webhookCall external URLHTTP request sent

Error Handling

Fail-Safe Behavior

The automation engine uses conservative defaults on errors:

# If playbook matching fails
try:
matching_playbook = automation.match_playbooks(action_data)
except Exception as e:
logger.error(f"Playbook matching failed: {e}")
return None # No automation - falls through to manual review

# If execution fails
try:
result = automation.execute_playbook(playbook_id, action_id)
except Exception as e:
logger.error(f"Playbook execution failed: {e}")
db.rollback()
return {'success': False, 'message': str(e)}

Error Recovery

Error TypeRecovery ActionResult
Database connectionRetry with exponential backoffContinue or fail safely
Playbook not foundLog warning, skip automationManual review required
Action not foundLog error, abort executionNo changes made
Notification failureLog error, continue executionApproval still processed

Best Practices

Automation Design

  1. Start Conservative: Begin with strict conditions and low-risk actions
  2. Monitor Closely: Watch metrics during initial rollout
  3. Gradual Expansion: Slowly expand automation scope as confidence builds
  4. Regular Review: Audit automated decisions periodically
  5. Clear Documentation: Document automation intent for future maintenance

Condition Configuration

  1. Layer Conditions: Multiple conditions reduce false positives
  2. Use Time Constraints: Limit automation to business hours initially
  3. Risk Thresholds: Keep auto-approve thresholds conservative (< 40)
  4. Action Type Specificity: Be explicit about which actions to automate

Monitoring

  1. Track Success Rates: Alert on drops below 95%
  2. Monitor Volume: Watch for unusual spikes or drops
  3. Review Failures: Investigate every automation failure
  4. Audit Decisions: Randomly sample automated approvals