[AOP][Examples for persistence and network stuff]

pull/996/merge
Kye Gomez 2 days ago
parent 6c6b9911e0
commit abe4197845

@ -0,0 +1,147 @@
#!/usr/bin/env python3
"""
Comprehensive AOP Example - Raw Code
This example demonstrates all AOP features including persistence,
network error handling, and queue management without any print statements or functions.
"""
import time
import threading
from swarms import Agent
from swarms.structs.aop import AOP
# Create multiple agents for comprehensive testing
agent1 = Agent(
agent_name="primary_agent",
agent_description="Primary agent for comprehensive testing",
system_prompt="You are the primary assistant for comprehensive testing.",
)
agent2 = Agent(
agent_name="secondary_agent",
agent_description="Secondary agent for comprehensive testing",
system_prompt="You are the secondary assistant for comprehensive testing.",
)
agent3 = Agent(
agent_name="monitoring_agent",
agent_description="Agent for monitoring and status reporting",
system_prompt="You are a monitoring assistant for system status.",
)
# Create AOP with all features enabled
aop = AOP(
server_name="Comprehensive AOP Server",
description="A comprehensive AOP server with all features enabled",
agents=[agent1, agent2, agent3],
port=8005,
host="localhost",
transport="streamable-http",
verbose=True,
traceback_enabled=True,
queue_enabled=True, # Enable queue-based execution
max_workers_per_agent=2,
max_queue_size_per_agent=100,
processing_timeout=30,
retry_delay=1.0,
persistence=True, # Enable persistence
max_restart_attempts=10,
restart_delay=5.0,
network_monitoring=True, # Enable network monitoring
max_network_retries=8,
network_retry_delay=3.0,
network_timeout=15.0,
log_level="INFO",
)
# Get comprehensive server information
server_info = aop.get_server_info()
# Get persistence status
persistence_status = aop.get_persistence_status()
# Get network status
aop.get_network_status()
# Get queue statistics
aop.get_queue_stats()
# List all agents
agent_list = aop.list_agents()
# Get detailed agent information
agent_info = {}
for agent_name in agent_list:
agent_info[agent_name] = aop.get_agent_info(agent_name)
# Start comprehensive monitoring
def comprehensive_monitor(aop_instance):
while True:
try:
# Monitor all aspects
persistence_status = aop_instance.get_persistence_status()
aop_instance.get_network_status()
aop_instance.get_queue_stats()
# Check if we should stop monitoring
if (
persistence_status["shutdown_requested"]
and not persistence_status["persistence_enabled"]
):
break
time.sleep(5) # Update every 5 seconds
except Exception:
time.sleep(5)
monitor_thread = threading.Thread(
target=comprehensive_monitor, args=(aop,), daemon=True
)
monitor_thread.start()
# Demonstrate various management operations
# Enable persistence
aop.enable_persistence()
# Pause all queues
pause_results = aop.pause_all_queues()
# Resume all queues
resume_results = aop.resume_all_queues()
# Clear all queues
clear_results = aop.clear_all_queues()
# Reset restart count
aop.reset_restart_count()
# Reset network retry count
aop.reset_network_retry_count()
# Request shutdown
aop.request_shutdown()
# Disable persistence
aop.disable_persistence()
# Run the comprehensive server
try:
aop.run()
except KeyboardInterrupt:
pass
except Exception:
pass
finally:
# Comprehensive cleanup
aop.disable_persistence()
aop.request_shutdown()
# Pause all queues
aop.pause_all_queues()
# Clear all queues
aop.clear_all_queues()

@ -0,0 +1,48 @@
#!/usr/bin/env python3
"""
AOP Network Error Handling Example - Raw Code
This example demonstrates the AOP network error handling feature with
custom error messages and automatic retry logic without any print statements or functions.
"""
from swarms import Agent
from swarms.structs.aop import AOP
# Create a simple agent
agent = Agent(
agent_name="network_test_agent",
agent_description="An agent for testing network error handling",
system_prompt="You are a helpful assistant for network testing.",
)
# Create AOP with network monitoring enabled
aop = AOP(
server_name="Network Resilient AOP Server",
description="An AOP server with network error handling and retry logic",
agents=[agent],
port=8003,
host="localhost",
persistence=True, # Enable persistence for automatic restart
max_restart_attempts=3,
restart_delay=2.0,
network_monitoring=True, # Enable network monitoring
max_network_retries=5, # Allow up to 5 network retries
network_retry_delay=3.0, # Wait 3 seconds between network retries
network_timeout=10.0, # 10 second network timeout
verbose=True,
)
# Show initial network status
network_status = aop.get_network_status()
# Show persistence status
persistence_status = aop.get_persistence_status()
# Run with network monitoring enabled
try:
aop.run()
except KeyboardInterrupt:
pass
except Exception:
pass

@ -0,0 +1,83 @@
#!/usr/bin/env python3
"""
AOP Network Management Example - Raw Code
This example demonstrates AOP network management and monitoring
with real-time status updates without any print statements or functions.
"""
import time
import threading
from swarms import Agent
from swarms.structs.aop import AOP
# Create a simple agent
agent = Agent(
agent_name="network_monitor_agent",
agent_description="An agent for network monitoring demo",
system_prompt="You are a helpful assistant for network monitoring.",
)
# Create AOP with comprehensive network monitoring
aop = AOP(
server_name="Network Managed AOP Server",
description="An AOP server with comprehensive network management",
agents=[agent],
port=8004,
host="localhost",
persistence=True,
max_restart_attempts=5,
restart_delay=3.0,
network_monitoring=True,
max_network_retries=10,
network_retry_delay=2.0,
network_timeout=5.0,
verbose=True,
)
# Show initial configuration
server_name = aop.server_name
host = aop.host
port = aop.port
persistence = aop.persistence
network_monitoring = aop.network_monitoring
max_network_retries = aop.max_network_retries
network_timeout = aop.network_timeout
# Start monitoring in background
def monitor_network_status(aop_instance):
while True:
try:
network_status = aop_instance.get_network_status()
persistence_status = aop_instance.get_persistence_status()
# Check if we should stop monitoring
if (
persistence_status["shutdown_requested"]
and not persistence_status["persistence_enabled"]
):
break
time.sleep(5) # Update every 5 seconds
except Exception:
time.sleep(5)
monitor_thread = threading.Thread(
target=monitor_network_status, args=(aop,), daemon=True
)
monitor_thread.start()
# Run the server
try:
aop.run()
except KeyboardInterrupt:
pass
except Exception:
pass
finally:
# Clean shutdown
aop.disable_persistence()
aop.request_shutdown()

@ -0,0 +1,40 @@
#!/usr/bin/env python3
"""
AOP Persistence Example - Raw Code
This example demonstrates the AOP persistence feature with automatic restart
and failsafe protection without any print statements or functions.
"""
from swarms import Agent
from swarms.structs.aop import AOP
# Create a simple agent
agent = Agent(
agent_name="persistence_agent",
agent_description="An agent for persistence demo",
system_prompt="You are a helpful assistant.",
)
# Create AOP with persistence enabled
aop = AOP(
server_name="Persistent AOP Server",
description="A persistent AOP server that auto-restarts",
agents=[agent],
port=8001,
persistence=True, # Enable persistence
max_restart_attempts=5, # Allow up to 5 restarts
restart_delay=3.0, # Wait 3 seconds between restarts
verbose=True,
)
# Show persistence status
status = aop.get_persistence_status()
# Run with persistence enabled
try:
aop.run()
except KeyboardInterrupt:
pass
except Exception:
pass

@ -0,0 +1,87 @@
#!/usr/bin/env python3
"""
AOP Persistence Management Example - Raw Code
This example demonstrates AOP persistence management methods
for controlling persistence mode at runtime without any print statements or functions.
"""
import time
import threading
from swarms import Agent
from swarms.structs.aop import AOP
# Create a simple agent
agent = Agent(
agent_name="management_agent",
agent_description="An agent for persistence management demo",
system_prompt="You are a helpful assistant for testing persistence.",
)
# Create AOP with persistence initially disabled
aop = AOP(
server_name="Managed AOP Server",
description="An AOP server with runtime persistence management",
agents=[agent],
port=8002,
persistence=False, # Start with persistence disabled
max_restart_attempts=3,
restart_delay=2.0,
verbose=True,
)
# Show initial status
status = aop.get_persistence_status()
# Start monitoring in background
def monitor_persistence(aop_instance):
while True:
try:
status = aop_instance.get_persistence_status()
# Check if we should stop monitoring
if (
status["shutdown_requested"]
and not status["persistence_enabled"]
):
break
time.sleep(10) # Check every 10 seconds
except Exception:
time.sleep(10)
monitor_thread = threading.Thread(
target=monitor_persistence, args=(aop,), daemon=True
)
monitor_thread.start()
# Demonstrate persistence management
# Enable persistence
aop.enable_persistence()
# Get updated status
updated_status = aop.get_persistence_status()
# Request shutdown
aop.request_shutdown()
# Disable persistence
aop.disable_persistence()
# Reset restart count
aop.reset_restart_count()
# Run the server
try:
aop.run()
except KeyboardInterrupt:
pass
except Exception:
pass
finally:
# Clean shutdown
aop.disable_persistence()
aop.request_shutdown()

@ -1,119 +0,0 @@
#!/usr/bin/env python3
"""
Example demonstrating the AOP network error handling feature.
This example shows how the AOP server handles network connection issues
with custom error messages and automatic retry logic.
"""
from swarms import Agent
from swarms.structs.aop import AOP
def main():
"""Demonstrate AOP network error handling functionality."""
# Create a simple agent
agent = Agent(
agent_name="network_test_agent",
agent_description="An agent for testing network error handling",
system_prompt="You are a helpful assistant for network testing.",
)
# Create AOP with network monitoring enabled
aop = AOP(
server_name="Network Resilient AOP Server",
description="An AOP server with network error handling and retry logic",
agents=[agent],
port=8003,
host="localhost",
persistence=True, # Enable persistence for automatic restart
max_restart_attempts=3,
restart_delay=2.0,
network_monitoring=True, # Enable network monitoring
max_network_retries=5, # Allow up to 5 network retries
network_retry_delay=3.0, # Wait 3 seconds between network retries
network_timeout=10.0, # 10 second network timeout
verbose=True,
)
print("AOP Network Error Handling Demo")
print("=" * 40)
print()
# Show initial network status
print("Initial network status:")
network_status = aop.get_network_status()
for key, value in network_status.items():
print(f" {key}: {value}")
print()
# Show persistence status
print("Persistence status:")
persistence_status = aop.get_persistence_status()
for key, value in persistence_status.items():
print(f" {key}: {value}")
print()
print("Network error handling features:")
print("✅ Custom error messages with emojis")
print("✅ Automatic network connectivity testing")
print("✅ Configurable retry attempts and delays")
print("✅ Network error detection and classification")
print("✅ Graceful degradation and recovery")
print()
print("To test network error handling:")
print("1. Start the server (it will run on localhost:8003)")
print("2. Simulate network issues by:")
print(" - Disconnecting your network")
print(" - Blocking the port with firewall")
print(" - Stopping the network service")
print("3. Watch the custom error messages and retry attempts")
print("4. Reconnect and see automatic recovery")
print()
try:
print("Starting server with network monitoring...")
print("Press Ctrl+C to stop the demo")
print()
# This will run with network monitoring enabled
aop.run()
except KeyboardInterrupt:
print("\nDemo interrupted by user")
print("Network status at shutdown:")
network_status = aop.get_network_status()
for key, value in network_status.items():
print(f" {key}: {value}")
except Exception as e:
print(f"\nUnexpected error: {e}")
print("This demonstrates how non-network errors are handled")
def simulate_network_issues():
"""
Simulate various network issues for testing.
This function can be used to test the network error handling
in a controlled environment.
"""
print("Network Issue Simulation:")
print("1. Connection Refused - Server not running")
print("2. Connection Reset - Server closed connection")
print("3. Timeout - Server not responding")
print("4. Host Resolution Failed - Invalid hostname")
print("5. Network Unreachable - No route to host")
print()
print("The AOP server will detect these errors and:")
print("- Display custom error messages with emojis")
print("- Attempt automatic reconnection")
print("- Test network connectivity before retry")
print("- Give up after max retry attempts")
if __name__ == "__main__":
main()
print("\n" + "=" * 40)
simulate_network_issues()

@ -1,223 +0,0 @@
#!/usr/bin/env python3
"""
Example demonstrating AOP network management and monitoring.
This example shows how to monitor and manage network connectivity
in an AOP server with real-time status updates.
"""
import time
import threading
from swarms import Agent
from swarms.structs.aop import AOP
def monitor_network_status(aop_instance):
"""Monitor network status in a separate thread."""
while True:
try:
network_status = aop_instance.get_network_status()
persistence_status = aop_instance.get_persistence_status()
print(f"\n{'='*60}")
print(
f"📊 REAL-TIME STATUS MONITOR - {time.strftime('%H:%M:%S')}"
)
print(f"{'='*60}")
# Network Status
print("🌐 NETWORK STATUS:")
print(
f" Monitoring: {'✅ Enabled' if network_status['network_monitoring_enabled'] else '❌ Disabled'}"
)
print(
f" Connected: {'✅ Yes' if network_status['network_connected'] else '❌ No'}"
)
print(
f" Retry Count: {network_status['network_retry_count']}/{network_status['max_network_retries']}"
)
print(
f" Remaining Retries: {network_status['remaining_network_retries']}"
)
print(
f" Host: {network_status['host']}:{network_status['port']}"
)
print(f" Timeout: {network_status['network_timeout']}s")
print(
f" Retry Delay: {network_status['network_retry_delay']}s"
)
if network_status["last_network_error"]:
print(
f" Last Error: {network_status['last_network_error']}"
)
# Persistence Status
print("\n🔄 PERSISTENCE STATUS:")
print(
f" Enabled: {'✅ Yes' if persistence_status['persistence_enabled'] else '❌ No'}"
)
print(
f" Shutdown Requested: {'❌ Yes' if persistence_status['shutdown_requested'] else '✅ No'}"
)
print(
f" Restart Count: {persistence_status['restart_count']}/{persistence_status['max_restart_attempts']}"
)
print(
f" Remaining Restarts: {persistence_status['remaining_restarts']}"
)
print(
f" Restart Delay: {persistence_status['restart_delay']}s"
)
# Connection Health
if network_status["network_connected"]:
print("\n💚 CONNECTION HEALTH: Excellent")
elif network_status["network_retry_count"] == 0:
print("\n🟡 CONNECTION HEALTH: Unknown")
elif network_status["remaining_network_retries"] > 0:
print(
f"\n🟠 CONNECTION HEALTH: Recovering ({network_status['remaining_network_retries']} retries left)"
)
else:
print(
"\n🔴 CONNECTION HEALTH: Critical (No retries left)"
)
print(f"{'='*60}")
# Check if we should stop monitoring
if (
persistence_status["shutdown_requested"]
and not persistence_status["persistence_enabled"]
):
print("🛑 Shutdown requested, stopping monitor...")
break
time.sleep(5) # Update every 5 seconds
except Exception as e:
print(f"❌ Monitor error: {e}")
time.sleep(5)
def main():
"""Demonstrate AOP network management."""
# Create a simple agent
agent = Agent(
agent_name="network_monitor_agent",
agent_description="An agent for network monitoring demo",
system_prompt="You are a helpful assistant for network monitoring.",
)
# Create AOP with comprehensive network monitoring
aop = AOP(
server_name="Network Managed AOP Server",
description="An AOP server with comprehensive network management",
agents=[agent],
port=8004,
host="localhost",
persistence=True,
max_restart_attempts=5,
restart_delay=3.0,
network_monitoring=True,
max_network_retries=10,
network_retry_delay=2.0,
network_timeout=5.0,
verbose=True,
)
print("AOP Network Management Demo")
print("=" * 50)
print()
# Show initial configuration
print("Initial Configuration:")
print(f" Server: {aop.server_name}")
print(f" Host: {aop.host}:{aop.port}")
print(f" Persistence: {aop.persistence}")
print(f" Network Monitoring: {aop.network_monitoring}")
print(f" Max Network Retries: {aop.max_network_retries}")
print(f" Network Timeout: {aop.network_timeout}s")
print()
# Start monitoring in background
print("Starting network status monitor...")
monitor_thread = threading.Thread(
target=monitor_network_status, args=(aop,), daemon=True
)
monitor_thread.start()
print("Available commands:")
print(" 'start' - Start the server")
print(" 'status' - Show current status")
print(" 'reset_network' - Reset network retry counter")
print(" 'disable_network' - Disable network monitoring")
print(" 'enable_network' - Enable network monitoring")
print(" 'shutdown' - Request graceful shutdown")
print(" 'quit' - Exit the program")
print()
try:
while True:
command = input("Enter command: ").strip().lower()
if command == "start":
print(
"Starting server... (Press Ctrl+C to test network error handling)"
)
try:
aop.run()
except KeyboardInterrupt:
print("Server interrupted!")
elif command == "status":
print("\nCurrent Status:")
network_status = aop.get_network_status()
persistence_status = aop.get_persistence_status()
print("Network:")
for key, value in network_status.items():
print(f" {key}: {value}")
print("\nPersistence:")
for key, value in persistence_status.items():
print(f" {key}: {value}")
elif command == "reset_network":
aop.reset_network_retry_count()
print("Network retry counter reset!")
elif command == "disable_network":
aop.network_monitoring = False
print("Network monitoring disabled!")
elif command == "enable_network":
aop.network_monitoring = True
print("Network monitoring enabled!")
elif command == "shutdown":
aop.request_shutdown()
print("Shutdown requested!")
elif command == "quit":
print("Exiting...")
break
else:
print(
"Unknown command. Try: start, status, reset_network, disable_network, enable_network, shutdown, quit"
)
except KeyboardInterrupt:
print("\nExiting...")
finally:
# Clean shutdown
aop.disable_persistence()
aop.request_shutdown()
print("Cleanup completed")
if __name__ == "__main__":
main()

@ -1,62 +0,0 @@
#!/usr/bin/env python3
"""
Example demonstrating the AOP persistence feature.
This example shows how to use the persistence mode to create a server
that automatically restarts when stopped, with failsafe protection.
"""
from swarms import Agent
from swarms.structs.aop import AOP
def main():
"""Demonstrate AOP persistence functionality."""
# Create a simple agent
agent = Agent(
agent_name="example_agent",
agent_description="An example agent for persistence demo",
system_prompt="You are a helpful assistant.",
)
# Create AOP with persistence enabled
aop = AOP(
server_name="Persistent AOP Server",
description="A persistent AOP server that auto-restarts",
agents=[agent],
port=8001,
persistence=True, # Enable persistence
max_restart_attempts=5, # Allow up to 5 restarts
restart_delay=3.0, # Wait 3 seconds between restarts
verbose=True,
)
print("Starting persistent AOP server...")
print("Press Ctrl+C to test the restart functionality")
print("The server will restart automatically up to 5 times")
print("After 5 failed restarts, it will shut down permanently")
print()
# Show persistence status
status = aop.get_persistence_status()
print(f"Persistence Status: {status}")
print()
try:
# This will run with persistence enabled
aop.run()
except KeyboardInterrupt:
print("\nReceived interrupt signal")
print(
"In persistence mode, the server would normally restart"
)
print(
"To disable persistence and shut down gracefully, call:"
)
print(" aop.disable_persistence()")
print(" aop.request_shutdown()")
if __name__ == "__main__":
main()

@ -1,141 +0,0 @@
#!/usr/bin/env python3
"""
Example demonstrating AOP persistence management methods.
This example shows how to control persistence mode at runtime,
including enabling/disabling persistence and monitoring status.
"""
import time
import threading
from swarms import Agent
from swarms.structs.aop import AOP
def monitor_persistence(aop_instance):
"""Monitor persistence status in a separate thread."""
while True:
status = aop_instance.get_persistence_status()
print("\n[Monitor] Persistence Status:")
print(f" - Enabled: {status['persistence_enabled']}")
print(
f" - Shutdown Requested: {status['shutdown_requested']}"
)
print(f" - Restart Count: {status['restart_count']}")
print(
f" - Remaining Restarts: {status['remaining_restarts']}"
)
print(
f" - Max Restart Attempts: {status['max_restart_attempts']}"
)
print(f" - Restart Delay: {status['restart_delay']}s")
if status["shutdown_requested"]:
break
time.sleep(10) # Check every 10 seconds
def main():
"""Demonstrate AOP persistence management."""
# Create a simple agent
agent = Agent(
agent_name="management_agent",
agent_description="An agent for persistence management demo",
system_prompt="You are a helpful assistant for testing persistence.",
)
# Create AOP with persistence initially disabled
aop = AOP(
server_name="Managed AOP Server",
description="An AOP server with runtime persistence management",
agents=[agent],
port=8002,
persistence=False, # Start with persistence disabled
max_restart_attempts=3,
restart_delay=2.0,
verbose=True,
)
print("AOP Persistence Management Demo")
print("=" * 40)
print()
# Show initial status
print("Initial persistence status:")
status = aop.get_persistence_status()
for key, value in status.items():
print(f" {key}: {value}")
print()
# Start monitoring in background
monitor_thread = threading.Thread(
target=monitor_persistence, args=(aop,), daemon=True
)
monitor_thread.start()
print("Available commands:")
print(" 'enable' - Enable persistence mode")
print(" 'disable' - Disable persistence mode")
print(" 'shutdown' - Request graceful shutdown")
print(" 'reset' - Reset restart counter")
print(" 'status' - Show current status")
print(" 'start' - Start the server")
print(" 'quit' - Exit the program")
print()
try:
while True:
command = input("Enter command: ").strip().lower()
if command == "enable":
aop.enable_persistence()
print("Persistence enabled!")
elif command == "disable":
aop.disable_persistence()
print("Persistence disabled!")
elif command == "shutdown":
aop.request_shutdown()
print("Shutdown requested!")
elif command == "reset":
aop.reset_restart_count()
print("Restart counter reset!")
elif command == "status":
status = aop.get_persistence_status()
print("Current status:")
for key, value in status.items():
print(f" {key}: {value}")
elif command == "start":
print(
"Starting server... (Press Ctrl+C to test restart)"
)
try:
aop.run()
except KeyboardInterrupt:
print("Server interrupted!")
elif command == "quit":
print("Exiting...")
break
else:
print(
"Unknown command. Try: enable, disable, shutdown, reset, status, start, quit"
)
except KeyboardInterrupt:
print("\nExiting...")
finally:
# Clean shutdown
aop.disable_persistence()
aop.request_shutdown()
if __name__ == "__main__":
main()

@ -1,9 +1,3 @@
"""
Simplified test suite for AgentRouter class using pytest.
This module contains focused tests for the core functionality of the AgentRouter class.
"""
import pytest
from unittest.mock import Mock, patch

Loading…
Cancel
Save