from praisonaiagents import Agentfrom praisonaiagents.approval import require_approval, set_approval_callback# Create a tool requiring approval@require_approval(risk_level="high")def delete_file(filepath: str): """Delete a file from the system""" import os os.remove(filepath) return f"Deleted {filepath}"# Create agent with the toolagent = Agent( name="File Manager", tools=[delete_file])# Tool will request approval before executionagent.start("Delete the file config.old")
from praisonaiagents.approval import add_approval_requirement# Add approval to existing functionadd_approval_requirement( function=existing_function, risk_level="high")# Add approval by function nameadd_approval_requirement( function_name="dangerous_operation", risk_level="critical")
from praisonaiagents import Agent, Task, PraisonAIAgentsfrom praisonaiagents.approval import require_approval, set_approval_callback, ApprovalDecisionimport logging# Configure logginglogging.basicConfig(level=logging.INFO)# Define approval-required tools@require_approval(risk_level="low")def check_disk_space(path: str = "/"): import shutil stats = shutil.disk_usage(path) return f"Free space: {stats.free / (1024**3):.2f} GB"@require_approval(risk_level="medium")def clean_temp_files(directory: str = "/tmp"): import os import glob files = glob.glob(f"{directory}/*") size = sum(os.path.getsize(f) for f in files if os.path.isfile(f)) for file in files: if os.path.isfile(file): os.remove(file) return f"Cleaned {len(files)} files ({size / 1024**2:.2f} MB)"@require_approval(risk_level="high")def restart_service(service_name: str): import subprocess result = subprocess.run( ["systemctl", "restart", service_name], capture_output=True, text=True ) if result.returncode == 0: return f"Successfully restarted {service_name}" else: return f"Failed to restart {service_name}: {result.stderr}"# Custom approval logicdef smart_approval(function_name, arguments, risk_level): # Auto-approve disk checks if function_name == "check_disk_space": return ApprovalDecision(approved=True) # Approve temp cleaning with restrictions if function_name == "clean_temp_files": directory = arguments.get("directory", "") if directory.startswith("/tmp"): logging.info(f"Auto-approved temp cleaning: {directory}") return ApprovalDecision(approved=True) else: logging.warning(f"Manual approval required for: {directory}") return None # Always require manual approval for service restarts if function_name == "restart_service": service = arguments.get("service_name", "") if service in ["nginx", "apache2"]: # These are considered safer return None # Still require manual approval else: # Deny potentially dangerous services return ApprovalDecision( approved=False, reason=f"Service {service} is not in allowed list" ) return None# Set approval callbackset_approval_callback(smart_approval)# Create system admin agentadmin_agent = Agent( name="System Administrator", instructions="""You are a system administrator that helps with: - Monitoring disk space - Cleaning temporary files - Managing services Always explain what you're doing and why.""", tools=[check_disk_space, clean_temp_files, restart_service])# Create maintenance taskstasks = [ Task( description="Check disk space on the root partition", agent=admin_agent, expected_output="Disk space report" ), Task( description="Clean temporary files if disk space is low", agent=admin_agent, expected_output="Cleaning report or explanation" ), Task( description="Restart the web server if needed", agent=admin_agent, expected_output="Service status report" )]# Run with approval systemagents = PraisonAIAgents( agents=[admin_agent], tasks=tasks, verbose=True)# Execute (will prompt for approvals as needed)result = agents.start()
The approval module provides a comprehensive human-in-the-loop approval system for dangerous tool operations, ensuring safety and control over high-risk agent actions.
from praisonaiagents import Agentfrom praisonaiagents.tools import ShellTool# Tools automatically require approval based on riskagent = Agent( name="System Admin", tools=[ShellTool()] # Shell commands are high-risk)# When agent tries to execute a commandagent.chat("Delete all temporary files in /tmp")# User will be prompted for approval before execution
from praisonaiagents.agents.approval import require_approval@require_approval("high")def delete_user_data(user_id: str): """Delete all data for a user - requires approval""" # Dangerous operation pass
The default callback shows a formatted prompt in the console:
Copy
from praisonaiagents.agents.approval import console_approval_callback# This is used by default, but you can customize itdef my_console_approval(tool_name, risk_level, args): # Custom console formatting response = input(f"Allow {tool_name}? (y/n): ") return ApprovalDecision( approved=response.lower() == 'y', reason="User input" )
from praisonaiagents.agents.approval import add_approval_requirement# Add custom tool to approval listadd_approval_requirement("custom_dangerous_tool", "high")# Add with specific moduleadd_approval_requirement("api_delete", "critical", module_name="my_api_tools")
from praisonaiagents import register_approval_callback# Register globallyregister_approval_callback(policy_based_approval)# Now all agents will use this callbackagent = Agent( name="Admin Bot", tools=[ShellTool(), FileTools()])
The approval system tracks approved operations within the same context:
Copy
# First call - requires approvalagent.chat("Run ls -la") # Prompts for approval# Within same context - already approvedagent.chat("Run ls -la again") # No prompt, uses previous approval