Prerequisites

  • Python 3.10 or higher
  • PraisonAI Agents package installed
  • Basic understanding of shell commands

Shell Tools

Use Shell Tools to execute shell commands with AI agents.

1

Install Dependencies

First, install the required package:

pip install praisonaiagents
2

Import Components

Import the necessary components:

from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.tools import execute_command, list_processes, kill_process, get_system_info
3

Create Agent

Create a shell command agent:

shell_agent = Agent(
    name="ShellCommander",
    role="Shell Command Specialist",
    goal="Execute shell commands efficiently and safely.",
    backstory="Expert in command-line operations and automation.",
    tools=[execute_command, list_processes, kill_process, get_system_info],
    self_reflect=False
)
4

Define Task

Define the shell task:

shell_task = Task(
    description="List and organize files in the current directory.",
    expected_output="Organized file structure with detailed listing.",
    agent=shell_agent,
    name="file_organization"
)
5

Run Agent

Initialize and run the agent:

agents = PraisonAIAgents(
    agents=[shell_agent],
    tasks=[shell_task],
    process="sequential"
)
agents.start()

Understanding Shell Tools

What are Shell Tools?

Shell Tools provide command-line capabilities for AI agents:

  • Command execution
  • Process management
  • Output handling
  • Error handling
  • Environment management

Key Components

Shell Agent

Create specialized shell agents:

Agent(tools=[execute_command, list_processes, kill_process, get_system_info])

Shell Task

Define shell tasks:

Task(description="shell_operation")

Process Types

Sequential or parallel processing:

process="sequential"

Shell Options

Customize shell operations:

timeout=30, shell=True
from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.tools import execute_command, list_processes, kill_process, get_system_info

# Create shell agent
shell_agent = Agent(
    name="CommandExecutor",
    role="Shell Command Specialist",
    goal="Execute shell commands efficiently and safely.",
    backstory="Expert in command-line operations and scripting.",
    tools=[execute_command, list_processes, kill_process, get_system_info],
    self_reflect=False
)

# Define shell task
shell_task = Task(
    description="Clean up temporary files and organize downloads.",
    expected_output="Cleaned and organized file system.",
    agent=shell_agent,
    name="system_cleanup"
)

# Run agent
agents = PraisonAIAgents(
    agents=[shell_agent],
    tasks=[shell_task],
    process="sequential"
)
agents.start()

Advanced Shell Management with Multiple Agents

# Create command agent
command_agent = Agent(
    name="Commander",
    role="Command Executor",
    goal="Execute shell commands systematically.",
    tools=[execute_command, list_processes, kill_process, get_system_info],
    self_reflect=False
)

# Create monitoring agent
monitor_agent = Agent(
    name="Monitor",
    role="Process Monitor",
    goal="Monitor and manage running processes.",
    backstory="Expert in system monitoring and process control.",
    self_reflect=False
)

# Define tasks
command_task = Task(
    description="Execute system maintenance commands.",
    agent=command_agent,
    name="system_maintenance"
)

monitor_task = Task(
    description="Monitor system resources and processes.",
    agent=monitor_agent,
    name="process_monitoring"
)

# Run agents
agents = PraisonAIAgents(
    agents=[command_agent, monitor_agent],
    tasks=[command_task, monitor_task],
    process="sequential"
)
agents.start()

Available Functions

from praisonaiagents.tools import execute_command
from praisonaiagents.tools import list_processes
from praisonaiagents.tools import kill_process
from praisonaiagents.tools import get_system_info

Function Details

execute_command(command: str, cwd: Optional[str] = None, timeout: int = 30, shell: bool = False, env: Optional[Dict[str, str]] = None, max_output_size: int = 10000)

Safely executes shell commands:

  • Timeout protection
  • Output capture
  • Error handling
  • Environment control
  • Working directory control
# Basic command execution
result = execute_command("ls -la")

# Advanced execution
result = execute_command(
    "python script.py",
    cwd="/path/to/scripts",
    timeout=60,
    env={"PYTHONPATH": "/custom/path"},
    shell=True
)

# Returns: Dict[str, Union[str, int, bool]]
# Example output:
# {
#     'stdout': 'command output...',
#     'stderr': 'error output if any',
#     'exit_code': 0,
#     'success': True,
#     'execution_time': 0.123
# }

list_processes()

Lists running system processes:

  • Process details
  • Resource usage
  • User information
  • Performance metrics
# Get list of running processes
processes = list_processes()

# Sort by CPU usage
cpu_intensive = sorted(
    processes,
    key=lambda x: x['cpu_percent'],
    reverse=True
)[:5]

# Returns: List[Dict[str, Union[int, str, float]]]
# Example output:
# [
#     {
#         'pid': 1234,
#         'name': 'python',
#         'username': 'user',
#         'memory_percent': 2.5,
#         'cpu_percent': 15.3
#     },
#     ...
# ]

kill_process(pid: int, force: bool = False)

Terminates system processes:

  • Graceful termination
  • Force kill option
  • Error handling
  • Access control
# Graceful termination
result = kill_process(1234)

# Force kill
result = kill_process(
    pid=1234,
    force=True  # Use SIGKILL
)

# Returns: Dict[str, Union[bool, str]]
# Example output:
# {
#     'success': True,
#     'message': 'Process 1234 killed successfully'
# }
# or
# {
#     'success': False,
#     'message': 'Access denied to kill process 1234'
# }

get_system_info()

Retrieves system information:

  • CPU statistics
  • Memory usage
  • Disk space
  • Platform details
  • Boot time
# Get system information
info = get_system_info()

# Access specific metrics
print(f"CPU Usage: {info['cpu']['percent']}%")
print(f"Memory Free: {info['memory']['free']} bytes")

# Returns: Dict[str, Union[float, int, str, Dict]]
# Example output:
# {
#     'cpu': {
#         'percent': 45.2,
#         'cores': 8,
#         'physical_cores': 4
#     },
#     'memory': {
#         'total': 16000000000,
#         'available': 8000000000,
#         'percent': 50.0,
#         'used': 8000000000,
#         'free': 4000000000
#     },
#     'disk': {
#         'total': 500000000000,
#         'used': 250000000000,
#         'free': 250000000000,
#         'percent': 50.0
#     },
#     'boot_time': 1641544800,
#     'platform': 'Darwin'
# }

Example Agent Configuration

from praisonaiagents import Agent
from praisonaiagents.tools import (
    execute_command, list_processes,
    kill_process, get_system_info
)

agent = Agent(
    name="SystemManager",
    description="An agent that manages system processes and executes commands",
    tools=[
        execute_command, list_processes,
        kill_process, get_system_info
    ]
)

Dependencies

The shell tools require the following package:

  • psutil: For system and process information

This will be automatically installed when needed.

Error Handling

All functions include comprehensive error handling:

  • Command execution errors
  • Process access errors
  • Permission errors
  • Timeout errors
  • Resource errors

Errors are handled consistently:

  • Success cases return expected data type
  • Error cases return error details in result
  • All errors are logged for debugging

Common Use Cases

  1. System Monitoring:
# Monitor system resources
info = get_system_info()
if info['cpu']['percent'] > 90:
    print("High CPU usage detected!")
if info['memory']['percent'] > 80:
    print("Low memory warning!")

# List resource-intensive processes
processes = sorted(
    list_processes(),
    key=lambda x: x['memory_percent'],
    reverse=True
)[:5]
print("Top memory users:", processes)
  1. Process Management:
# Find and kill zombie processes
for process in list_processes():
    if process['name'] == 'zombie_process':
        result = kill_process(
            process['pid'],
            force=True
        )
        print(f"Kill result: {result['message']}")
  1. Command Execution:
# Run a series of maintenance commands
commands = [
    "apt-get update",
    "apt-get upgrade -y",
    "apt-get autoremove -y"
]
for cmd in commands:
    result = execute_command(
        cmd,
        timeout=300,
        shell=True
    )
    if result['success']:
        print(f"Command succeeded: {cmd}")
    else:
        print(f"Command failed: {result['stderr']}")

Best Practices

Common Patterns

Shell Command Pipeline

# Command agent
commander = Agent(
    name="Commander",
    role="Shell Commander",
    tools=[execute_command]
)

# Monitor agent
monitor = Agent(
    name="Monitor",
    role="Process Monitor"
)

# Define tasks
command_task = Task(
    description="Execute maintenance commands",
    agent=commander
)

monitor_task = Task(
    description="Monitor command execution",
    agent=monitor
)

# Run workflow
agents = PraisonAIAgents(
    agents=[commander, monitor],
    tasks=[command_task, monitor_task]
)

Was this page helpful?