Agentic Architecture Pattern: Agent Lifecycle Management

Written by

in


    """
Pattern 166: Agent Lifecycle Management Pattern with LangChain/LangGraph

Purpose: Manage complete lifecycle of agents from creation to termination with LLM insights.
States: Created → Initialized → Active → Suspended → Terminated
"""

from typing import Dict, Any, List, Optional, TypedDict
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from enum import Enum
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from langgraph.graph import StateGraph, END
import statistics


class LifecycleState(Enum):
    """Agent lifecycle states."""
    CREATED = "created"
    INITIALIZED = "initialized"
    ACTIVE = "active"
    SUSPENDED = "suspended"
    TERMINATED = "terminated"


class TransitionTrigger(Enum):
    """Lifecycle transition triggers."""
    MANUAL = "manual"
    AUTOMATIC = "automatic"
    SCHEDULED = "scheduled"
    ERROR = "error"
    RESOURCE_LIMIT = "resource_limit"


class HealthStatus(Enum):
    """Agent health status."""
    HEALTHY = "healthy"
    DEGRADED = "degraded"
    UNHEALTHY = "unhealthy"
    UNKNOWN = "unknown"


class ResourceType(Enum):
    """Resource types for agents."""
    CPU = "cpu"
    MEMORY = "memory"
    NETWORK = "network"
    STORAGE = "storage"


@dataclass
class LifecycleEvent:
    """Event in agent lifecycle."""
    event_id: str
    from_state: LifecycleState
    to_state: LifecycleState
    trigger: TransitionTrigger
    reason: str
    metadata: Dict[str, Any] = field(default_factory=dict)
    timestamp: datetime = field(default_factory=datetime.now)


@dataclass
class ResourceAllocation:
    """Resource allocation for an agent."""
    cpu_cores: float
    memory_mb: int
    network_bandwidth_mbps: int
    storage_gb: int
    allocated_at: datetime = field(default_factory=datetime.now)


@dataclass
class AgentHealth:
    """Agent health metrics."""
    status: HealthStatus
    cpu_usage: float
    memory_usage: float
    error_count: int
    last_active: datetime
    uptime_seconds: float


@dataclass
class ManagedAgent:
    """Agent with comprehensive lifecycle management."""
    id: str
    name: str
    agent_type: str
    state: LifecycleState = LifecycleState.CREATED
    created_at: datetime = field(default_factory=datetime.now)
    events: List[LifecycleEvent] = field(default_factory=list)
    resources: Optional[ResourceAllocation] = None
    health: Optional[AgentHealth] = None
    configuration: Dict[str, Any] = field(default_factory=dict)
    tags: Dict[str, str] = field(default_factory=dict)


@dataclass
class LifecyclePolicy:
    """Policy for lifecycle management."""
    policy_id: str
    auto_suspend_after_idle_seconds: Optional[int] = None
    auto_terminate_after_suspended_seconds: Optional[int] = None
    max_error_count: Optional[int] = None
    health_check_interval_seconds: int = 60


class LifecycleManagementState(TypedDict):
    """State for lifecycle management workflow."""
    agent_id: str
    current_state: str
    target_state: str
    validation_result: bool
    health_check: Dict[str, Any]
    recommendations: List[str]
    transition_approved: bool


class LifecycleManager:
    """
    Advanced lifecycle manager with LangChain/LangGraph integration.
    """
    
    def __init__(self, model_name: str = "gpt-4", temperature: float = 0.3):
        self.llm = ChatOpenAI(model=model_name, temperature=temperature)
        self.agents: Dict[str, ManagedAgent] = {}
        self.agent_llms: Dict[str, ChatOpenAI] = {}
        self.policies: Dict[str, LifecyclePolicy] = {}
        self.workflow = self._build_lifecycle_workflow()
        
        # Statistics
        self.stats = {
            "total_agents_created": 0,
            "total_state_transitions": 0,
            "agents_by_state": {state: 0 for state in LifecycleState},
            "transitions_by_trigger": {trigger: 0 for trigger in TransitionTrigger},
            "avg_agent_lifetime_seconds": 0.0,
            "health_checks_performed": 0
        }
    
    def _build_lifecycle_workflow(self) -> StateGraph:
        """Build LangGraph workflow for lifecycle management."""
        workflow = StateGraph(LifecycleManagementState)
        
        # Add nodes
        workflow.add_node("validate_transition", self._validate_transition_node)
        workflow.add_node("check_health", self._check_health_node)
        workflow.add_node("analyze_impact", self._analyze_impact_node)
        workflow.add_node("approve_transition", self._approve_transition_node)
        workflow.add_node("provide_recommendations", self._provide_recommendations_node)
        
        # Define edges
        workflow.set_entry_point("validate_transition")
        workflow.add_edge("validate_transition", "check_health")
        workflow.add_edge("check_health", "analyze_impact")
        workflow.add_edge("analyze_impact", "approve_transition")
        workflow.add_edge("approve_transition", "provide_recommendations")
        workflow.add_edge("provide_recommendations", END)
        
        return workflow.compile()
    
    def _validate_transition_node(self, state: LifecycleManagementState) -> LifecycleManagementState:
        """Validate if state transition is allowed."""
        agent_id = state["agent_id"]
        current = state["current_state"]
        target = state["target_state"]
        
        # Valid transitions
        valid_transitions = {
            LifecycleState.CREATED.value: [LifecycleState.INITIALIZED.value, LifecycleState.TERMINATED.value],
            LifecycleState.INITIALIZED.value: [LifecycleState.ACTIVE.value, LifecycleState.TERMINATED.value],
            LifecycleState.ACTIVE.value: [LifecycleState.SUSPENDED.value, LifecycleState.TERMINATED.value],
            LifecycleState.SUSPENDED.value: [LifecycleState.ACTIVE.value, LifecycleState.TERMINATED.value],
            LifecycleState.TERMINATED.value: []
        }
        
        is_valid = target in valid_transitions.get(current, [])
        state["validation_result"] = is_valid
        
        return state
    
    def _check_health_node(self, state: LifecycleManagementState) -> LifecycleManagementState:
        """Check agent health."""
        agent_id = state["agent_id"]
        agent = self.agents.get(agent_id)
        
        health_data = {}
        if agent and agent.health:
            health_data = {
                "status": agent.health.status.value,
                "cpu_usage": agent.health.cpu_usage,
                "memory_usage": agent.health.memory_usage,
                "error_count": agent.health.error_count,
                "uptime_seconds": agent.health.uptime_seconds
            }
        else:
            health_data = {
                "status": HealthStatus.UNKNOWN.value,
                "message": "Health data not available"
            }
        
        state["health_check"] = health_data
        self.stats["health_checks_performed"] += 1
        
        return state
    
    def _analyze_impact_node(self, state: LifecycleManagementState) -> LifecycleManagementState:
        """Analyze impact of state transition using LLM."""
        current = state["current_state"]
        target = state["target_state"]
        health = state["health_check"]
        
        # Use LLM to analyze transition impact
        prompt = ChatPromptTemplate.from_template(
            "Analyze the impact of this agent lifecycle transition:\n"
            "Current State: {current_state}\n"
            "Target State: {target_state}\n"
            "Agent Health: {health_data}\n\n"
            "Provide a brief analysis of potential impacts and risks."
        )
        
        chain = prompt | self.llm
        response = chain.invoke({
            "current_state": current,
            "target_state": target,
            "health_data": str(health)
        })
        
        # Store analysis in recommendations for now
        state["recommendations"] = [str(response.content)[:200]]
        
        return state
    
    def _approve_transition_node(self, state: LifecycleManagementState) -> LifecycleManagementState:
        """Approve or reject transition based on validation and health."""
        validation = state["validation_result"]
        health = state["health_check"]
        
        # Approve if validation passes and agent is not critically unhealthy
        approved = validation
        if health.get("status") == HealthStatus.UNHEALTHY.value:
            # Still allow termination even if unhealthy
            if state["target_state"] != LifecycleState.TERMINATED.value:
                approved = False
        
        state["transition_approved"] = approved
        
        return state
    
    def _provide_recommendations_node(self, state: LifecycleManagementState) -> LifecycleManagementState:
        """Provide recommendations for lifecycle management."""
        approved = state["transition_approved"]
        health = state["health_check"]
        
        recommendations = []
        
        if not approved:
            recommendations.append("Transition not approved - check validation rules and agent health")
        
        if health.get("error_count", 0) > 5:
            recommendations.append("High error count detected - consider investigating before proceeding")
        
        if health.get("cpu_usage", 0) > 80:
            recommendations.append("High CPU usage - may need resource scaling")
        
        if health.get("memory_usage", 0) > 80:
            recommendations.append("High memory usage - check for memory leaks")
        
        if recommendations:
            state["recommendations"] = recommendations
        
        return state
    
    def create_agent(
        self,
        agent_id: str,
        name: str,
        agent_type: str = "general",
        configuration: Optional[Dict[str, Any]] = None,
        tags: Optional[Dict[str, str]] = None
    ) -> ManagedAgent:
        """Create a new managed agent."""
        if agent_id in self.agents:
            raise ValueError(f"Agent {agent_id} already exists")
        
        agent = ManagedAgent(
            id=agent_id,
            name=name,
            agent_type=agent_type,
            configuration=configuration or {},
            tags=tags or {}
        )
        
        self.agents[agent_id] = agent
        self.stats["total_agents_created"] += 1
        self.stats["agents_by_state"][LifecycleState.CREATED] += 1
        
        # Record event
        self._record_event(
            agent_id,
            LifecycleState.CREATED,
            LifecycleState.CREATED,
            TransitionTrigger.MANUAL,
            "Agent created"
        )
        
        return agent
    
    def initialize_agent(
        self,
        agent_id: str,
        model: str = "gpt-4",
        resources: Optional[ResourceAllocation] = None
    ) -> bool:
        """Initialize agent with resources."""
        result = self._execute_transition(
            agent_id,
            LifecycleState.INITIALIZED,
            TransitionTrigger.MANUAL,
            "Initialization requested"
        )
        
        if result:
            # Allocate resources
            if resources:
                self.agents[agent_id].resources = resources
            else:
                self.agents[agent_id].resources = ResourceAllocation(
                    cpu_cores=1.0,
                    memory_mb=512,
                    network_bandwidth_mbps=100,
                    storage_gb=10
                )
            
            # Initialize LLM
            self.agent_llms[agent_id] = ChatOpenAI(model=model, temperature=0.7)
            
            # Initialize health
            self.agents[agent_id].health = AgentHealth(
                status=HealthStatus.HEALTHY,
                cpu_usage=0.0,
                memory_usage=0.0,
                error_count=0,
                last_active=datetime.now(),
                uptime_seconds=0.0
            )
        
        return result
    
    def activate_agent(self, agent_id: str) -> bool:
        """Activate agent for work."""
        return self._execute_transition(
            agent_id,
            LifecycleState.ACTIVE,
            TransitionTrigger.MANUAL,
            "Activation requested"
        )
    
    def suspend_agent(
        self,
        agent_id: str,
        reason: str = "Manual suspension",
        trigger: TransitionTrigger = TransitionTrigger.MANUAL
    ) -> bool:
        """Suspend active agent."""
        return self._execute_transition(
            agent_id,
            LifecycleState.SUSPENDED,
            trigger,
            reason
        )
    
    def resume_agent(self, agent_id: str) -> bool:
        """Resume suspended agent."""
        return self._execute_transition(
            agent_id,
            LifecycleState.ACTIVE,
            TransitionTrigger.MANUAL,
            "Resume requested"
        )
    
    def terminate_agent(
        self,
        agent_id: str,
        reason: str = "Normal termination",
        trigger: TransitionTrigger = TransitionTrigger.MANUAL
    ) -> bool:
        """Terminate agent and cleanup resources."""
        result = self._execute_transition(
            agent_id,
            LifecycleState.TERMINATED,
            trigger,
            reason
        )
        
        if result:
            # Cleanup resources
            if agent_id in self.agent_llms:
                del self.agent_llms[agent_id]
            
            # Clear resource allocation
            if self.agents[agent_id].resources:
                self.agents[agent_id].resources = None
        
        return result
    
    def _execute_transition(
        self,
        agent_id: str,
        target_state: LifecycleState,
        trigger: TransitionTrigger,
        reason: str
    ) -> bool:
        """Execute state transition with workflow validation."""
        agent = self.agents.get(agent_id)
        if not agent:
            return False
        
        # Prepare workflow state
        initial_state: LifecycleManagementState = {
            "agent_id": agent_id,
            "current_state": agent.state.value,
            "target_state": target_state.value,
            "validation_result": False,
            "health_check": {},
            "recommendations": [],
            "transition_approved": False
        }
        
        # Run workflow
        result = self.workflow.invoke(initial_state)
        
        # Execute transition if approved
        if result["transition_approved"]:
            self._record_event(
                agent_id,
                agent.state,
                target_state,
                trigger,
                reason
            )
            
            # Update state counts
            self.stats["agents_by_state"][agent.state] -= 1
            agent.state = target_state
            self.stats["agents_by_state"][target_state] += 1
            self.stats["total_state_transitions"] += 1
            self.stats["transitions_by_trigger"][trigger] += 1
            
            return True
        
        return False
    
    def _record_event(
        self,
        agent_id: str,
        from_state: LifecycleState,
        to_state: LifecycleState,
        trigger: TransitionTrigger,
        reason: str,
        metadata: Optional[Dict[str, Any]] = None
    ):
        """Record a lifecycle event."""
        agent = self.agents[agent_id]
        event = LifecycleEvent(
            event_id=f"{agent_id}_event_{len(agent.events)}",
            from_state=from_state,
            to_state=to_state,
            trigger=trigger,
            reason=reason,
            metadata=metadata or {}
        )
        agent.events.append(event)
    
    def update_agent_health(
        self,
        agent_id: str,
        cpu_usage: float,
        memory_usage: float,
        error_count: int = 0
    ):
        """Update agent health metrics."""
        agent = self.agents.get(agent_id)
        if not agent or not agent.health:
            return
        
        agent.health.cpu_usage = cpu_usage
        agent.health.memory_usage = memory_usage
        agent.health.error_count = error_count
        agent.health.last_active = datetime.now()
        
        # Calculate uptime
        agent.health.uptime_seconds = (datetime.now() - agent.created_at).total_seconds()
        
        # Determine health status
        if error_count > 10 or cpu_usage > 95 or memory_usage > 95:
            agent.health.status = HealthStatus.UNHEALTHY
        elif error_count > 5 or cpu_usage > 80 or memory_usage > 80:
            agent.health.status = HealthStatus.DEGRADED
        else:
            agent.health.status = HealthStatus.HEALTHY
    
    def apply_policy(self, agent_id: str, policy: LifecyclePolicy):
        """Apply lifecycle policy to an agent."""
        self.policies[agent_id] = policy
    
    def check_policies(self):
        """Check and enforce lifecycle policies."""
        now = datetime.now()
        
        for agent_id, policy in self.policies.items():
            agent = self.agents.get(agent_id)
            if not agent or not agent.health:
                continue
            
            # Auto-suspend after idle
            if policy.auto_suspend_after_idle_seconds:
                idle_time = (now - agent.health.last_active).total_seconds()
                if (idle_time > policy.auto_suspend_after_idle_seconds and 
                    agent.state == LifecycleState.ACTIVE):
                    self.suspend_agent(
                        agent_id,
                        f"Auto-suspended after {idle_time:.0f}s idle",
                        TransitionTrigger.AUTOMATIC
                    )
            
            # Auto-terminate after suspended
            if policy.auto_terminate_after_suspended_seconds:
                if agent.state == LifecycleState.SUSPENDED:
                    suspended_time = (now - agent.events[-1].timestamp).total_seconds()
                    if suspended_time > policy.auto_terminate_after_suspended_seconds:
                        self.terminate_agent(
                            agent_id,
                            f"Auto-terminated after {suspended_time:.0f}s suspended",
                            TransitionTrigger.AUTOMATIC
                        )
            
            # Terminate on error threshold
            if policy.max_error_count:
                if agent.health.error_count > policy.max_error_count:
                    self.terminate_agent(
                        agent_id,
                        f"Error count exceeded: {agent.health.error_count}",
                        TransitionTrigger.ERROR
                    )
    
    def get_agent_history(self, agent_id: str) -> List[Dict[str, Any]]:
        """Get lifecycle history of agent."""
        agent = self.agents.get(agent_id)
        if not agent:
            return []
        
        return [
            {
                "event_id": e.event_id,
                "from_state": e.from_state.value,
                "to_state": e.to_state.value,
                "trigger": e.trigger.value,
                "reason": e.reason,
                "timestamp": e.timestamp.isoformat()
            }
            for e in agent.events
        ]
    
    def get_agents_by_state(self, state: LifecycleState) -> List[ManagedAgent]:
        """Get all agents in a specific state."""
        return [agent for agent in self.agents.values() if agent.state == state]
    
    def get_statistics(self) -> Dict[str, Any]:
        """Get comprehensive lifecycle statistics."""
        # Calculate average lifetime for terminated agents
        terminated_agents = self.get_agents_by_state(LifecycleState.TERMINATED)
        if terminated_agents:
            lifetimes = [
                (agent.events[-1].timestamp - agent.created_at).total_seconds()
                for agent in terminated_agents
                if agent.events
            ]
            self.stats["avg_agent_lifetime_seconds"] = statistics.mean(lifetimes) if lifetimes else 0.0
        
        return {
            "total_agents_created": self.stats["total_agents_created"],
            "total_active_agents": len(self.agents),
            "total_state_transitions": self.stats["total_state_transitions"],
            "agents_by_state": {
                state.value: count
                for state, count in self.stats["agents_by_state"].items()
            },
            "transitions_by_trigger": {
                trigger.value: count
                for trigger, count in self.stats["transitions_by_trigger"].items()
            },
            "avg_agent_lifetime_seconds": round(self.stats["avg_agent_lifetime_seconds"], 2),
            "health_checks_performed": self.stats["health_checks_performed"],
            "policies_applied": len(self.policies)
        }


class AgentLifecycleManagementPattern:
    """
    Comprehensive agent lifecycle management pattern coordinator with LangChain/LangGraph.
    """
    
    def __init__(self, model_name: str = "gpt-4"):
        self.manager = LifecycleManager(model_name=model_name)
    
    def create(
        self,
        agent_id: str,
        name: str,
        agent_type: str = "general"
    ) -> ManagedAgent:
        """Create a new agent."""
        return self.manager.create_agent(agent_id, name, agent_type)
    
    def initialize(self, agent_id: str, model: str = "gpt-4") -> bool:
        """Initialize agent."""
        return self.manager.initialize_agent(agent_id, model)
    
    def activate(self, agent_id: str) -> bool:
        """Activate agent."""
        return self.manager.activate_agent(agent_id)
    
    def suspend(self, agent_id: str, reason: str = "Manual suspension") -> bool:
        """Suspend agent."""
        return self.manager.suspend_agent(agent_id, reason)
    
    def resume(self, agent_id: str) -> bool:
        """Resume agent."""
        return self.manager.resume_agent(agent_id)
    
    def terminate(self, agent_id: str, reason: str = "Normal termination") -> bool:
        """Terminate agent."""
        return self.manager.terminate_agent(agent_id, reason)
    
    def update_health(
        self,
        agent_id: str,
        cpu_usage: float,
        memory_usage: float,
        error_count: int = 0
    ):
        """Update agent health."""
        self.manager.update_agent_health(agent_id, cpu_usage, memory_usage, error_count)
    
    def get_history(self, agent_id: str) -> List[Dict[str, Any]]:
        """Get agent history."""
        return self.manager.get_agent_history(agent_id)
    
    def get_statistics(self) -> Dict[str, Any]:
        """Get statistics."""
        return self.manager.get_statistics()



if __name__ == "__main__":
    print("=== Agent Lifecycle Management Pattern with LangChain/LangGraph Demo ===\n")
    
    # Note: This demo shows the structure. In production, you'd need:
    # - export OPENAI_API_KEY="your-key-here"
    # - Actual LLM calls would be made
    
    print("Scenario 1: Complete Lifecycle")
    print("-" * 50)
    manager = AgentLifecycleManagementPattern(model_name="gpt-4")
    
    # Create agents
    agent1 = manager.create("agent-001", "DataProcessor", "data_processing")
    print(f"✓ Created {agent1.name} ({agent1.id})")
    
    agent2 = manager.create("agent-002", "APIWorker", "api_integration")
    print(f"✓ Created {agent2.name} ({agent2.id})")
    
    agent3 = manager.create("agent-003", "MonitorAgent", "monitoring")
    print(f"✓ Created {agent3.name} ({agent3.id})")
    
    # Initialize agents
    print("\nInitializing agents...")
    manager.initialize("agent-001", "gpt-4")
    manager.initialize("agent-002", "gpt-3.5-turbo")
    manager.initialize("agent-003", "gpt-4")
    print("✓ All agents initialized")
    
    # Activate agents
    print("\nActivating agents...")
    manager.activate("agent-001")
    manager.activate("agent-002")
    manager.activate("agent-003")
    print("✓ All agents activated")
    
    print("\nScenario 2: Health Monitoring")
    print("-" * 50)
    
    # Simulate health updates
    health_updates = [
        ("agent-001", 45.5, 60.2, 0),
        ("agent-002", 78.3, 85.1, 3),
        ("agent-003", 92.5, 88.0, 8),
    ]
    
    print("Updating agent health metrics:")
    for agent_id, cpu, mem, errors in health_updates:
        manager.update_health(agent_id, cpu, mem, errors)
        agent = manager.manager.agents[agent_id]
        print(f"  {agent_id}: CPU={cpu}%, MEM={mem}%, Errors={errors}")
        if agent.health:
            print(f"    Health Status: {agent.health.status.value}")
    
    print("\nScenario 3: Suspension and Resumption")
    print("-" * 50)
    
    # Suspend unhealthy agent
    print("Suspending agent with high error count...")
    success = manager.suspend("agent-003", "High error rate detected")
    if success:
        print("✓ agent-003 suspended successfully")
    
    # Resume agent after fix
    print("\nResuming agent after fixes...")
    success = manager.resume("agent-003")
    if success:
        print("✓ agent-003 resumed successfully")
    
    print("\nScenario 4: Lifecycle Policies")
    print("-" * 50)
    
    # Apply auto-management policy
    policy = LifecyclePolicy(
        policy_id="aggressive_cleanup",
        auto_suspend_after_idle_seconds=300,
        auto_terminate_after_suspended_seconds=600,
        max_error_count=10
    )
    
    manager.manager.apply_policy("agent-002", policy)
    print(f"✓ Applied policy '{policy.policy_id}' to agent-002")
    print(f"  - Auto-suspend after {policy.auto_suspend_after_idle_seconds}s idle")
    print(f"  - Auto-terminate after {policy.auto_terminate_after_suspended_seconds}s suspended")
    print(f"  - Max errors: {policy.max_error_count}")
    
    # Check policies (would normally run in background)
    print("\nChecking policy enforcement...")
    manager.manager.check_policies()
    print("✓ Policy check complete")
    
    print("\nScenario 5: Lifecycle History")
    print("-" * 50)
    
    # Get detailed history for agent
    history = manager.get_history("agent-001")
    print(f"Lifecycle history for agent-001:")
    for event in history:
        print(f"  {event['from_state']} → {event['to_state']}")
        print(f"    Trigger: {event['trigger']}")
        print(f"    Reason: {event['reason']}")
        print(f"    Time: {event['timestamp']}")
    
    print("\nScenario 6: Agent Termination")
    print("-" * 50)
    
    # Terminate agents
    terminations = [
        ("agent-001", "Task completed successfully"),
        ("agent-002", "Resource reallocation"),
    ]
    
    print("Terminating agents:")
    for agent_id, reason in terminations:
        success = manager.terminate(agent_id, reason)
        if success:
            print(f"✓ {agent_id} terminated: {reason}")
    
    print("\nScenario 7: State Distribution")
    print("-" * 50)
    
    # Get agents by state
    active_agents = manager.manager.get_agents_by_state(LifecycleState.ACTIVE)
    terminated_agents = manager.manager.get_agents_by_state(LifecycleState.TERMINATED)
    
    print(f"Active agents: {len(active_agents)}")
    for agent in active_agents:
        print(f"  - {agent.id} ({agent.name})")
    
    print(f"\nTerminated agents: {len(terminated_agents)}")
    for agent in terminated_agents:
        print(f"  - {agent.id} ({agent.name})")
    
    print("\nScenario 8: Statistics")
    print("-" * 50)
    
    stats = manager.get_statistics()
    print(f"Total Agents Created: {stats['total_agents_created']}")
    print(f"Total Active Agents: {stats['total_active_agents']}")
    print(f"Total State Transitions: {stats['total_state_transitions']}")
    print(f"Health Checks Performed: {stats['health_checks_performed']}")
    print(f"Policies Applied: {stats['policies_applied']}")
    
    print("\nAgents by State:")
    for state, count in stats['agents_by_state'].items():
        if count > 0:
            print(f"  {state}: {count}")
    
    print("\nTransitions by Trigger:")
    for trigger, count in stats['transitions_by_trigger'].items():
        if count > 0:
            print(f"  {trigger}: {count}")
    
    if stats['avg_agent_lifetime_seconds'] > 0:
        print(f"\nAverage Agent Lifetime: {stats['avg_agent_lifetime_seconds']:.2f}s")
    
    print("\n" + "=" * 50)
    print("Agent lifecycle management pattern demonstration complete!")
    print("=" * 50)

    

Agentic Architecture Pattern: Agent Lifecycle Management

Pattern 166: 166 Agent Lifecycle Management – Line-by-Line Explanation

Overview

Pattern 166: Agent Lifecycle Management Pattern with LangChain/LangGraph

Purpose: Manage complete lifecycle of agents from creation to termination with LLM insights. States: Created → Initialized → Active → Suspended → Terminated


Code Structure Analysis

File Information

  • Pattern Number: 166
  • Pattern Name: 166 Agent Lifecycle Management
  • File Path: patterns\scaling\166_agent_lifecycle_management.py
  • Total Lines: 816

Detailed Code Explanation

Module Docstring

"""
Pattern 166: Agent Lifecycle Management Pattern with LangChain/LangGraph

Purpose: Manage complete lifecycle of agents from creation to termination with LLM insights.
States: Created → Initialized → Active → Suspended → Terminated
"""

Explanation: This module docstring describes the purpose and key features of the 166 Agent Lifecycle Management pattern.


Imports Section

from typing import Dict, Any, List, Optional, TypedDict
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from enum import Enum
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from langgraph.graph import StateGraph, END
import statistics  # First 20 imports shown

Explanation: The module imports necessary dependencies: – from typing import Dict, Any, List, Optional, TypedDict: Type hints for better code documentation – from dataclasses import dataclass, field: Data class decorators for clean data structures – from datetime import datetime, timedelta: Date and time utilities – from enum import Enum: Enumeration support for fixed sets of values – from langchain_core.prompts import ChatPromptTemplate: LangChain framework integration – from langchain_openai import ChatOpenAI: LangChain framework integration – from langgraph.graph import StateGraph, END: LangGraph for workflow orchestration


Enumerations

LifecycleState (Line 18)

class LifecycleState(Enum):
    CREATED
    INITIALIZED
    ACTIVE
    SUSPENDED
    TERMINATED

Purpose: Agent lifecycle states.

Values: – CREATED: Represents created – INITIALIZED: Represents initialized – ACTIVE: Currently operational – SUSPENDED: Represents suspended – TERMINATED: Represents terminated

TransitionTrigger (Line 27)

class TransitionTrigger(Enum):
    MANUAL
    AUTOMATIC
    SCHEDULED
    ERROR
    RESOURCE_LIMIT

Purpose: Lifecycle transition triggers.

Values: – MANUAL: Represents manual – AUTOMATIC: Represents automatic – SCHEDULED: Represents scheduled – ERROR: Error severity level – RESOURCE_LIMIT: Represents resource limit

HealthStatus (Line 36)

class HealthStatus(Enum):
    HEALTHY
    DEGRADED
    UNHEALTHY
    UNKNOWN

Purpose: Agent health status.

Values: – HEALTHY: Represents healthy – DEGRADED: Represents degraded – UNHEALTHY: Represents unhealthy – UNKNOWN: Represents unknown

ResourceType (Line 44)

class ResourceType(Enum):
    CPU
    MEMORY
    NETWORK
    STORAGE

Purpose: Resource types for agents.

Values: – CPU: Represents cpu – MEMORY: Represents memory – NETWORK: Represents network – STORAGE: Represents storage


Classes

LifecycleState (Line 18)

Description: Agent lifecycle states.

TransitionTrigger (Line 27)

Description: Lifecycle transition triggers.

HealthStatus (Line 36)

Description: Agent health status.

ResourceType (Line 44)

Description: Resource types for agents.

LifecycleEvent (Line 53)

Description: Event in agent lifecycle.

ResourceAllocation (Line 65)

Description: Resource allocation for an agent.

AgentHealth (Line 75)

Description: Agent health metrics.

ManagedAgent (Line 86)

Description: Agent with comprehensive lifecycle management.

LifecyclePolicy (Line 101)

Description: Policy for lifecycle management.

LifecycleManagementState (Line 110)

Description: State for lifecycle management workflow.

LifecycleManager (Line 121)

Description: Advanced lifecycle manager with LangChain/LangGraph integration.

Methods:

__init__ (Line 126)
def __init__(self, model_name, temperature):
    """No method docstring."""

Purpose: No method docstring.

Parameters: – self: Instance reference – model_name: LLM model to use (e.g., “gpt-4”) – temperature: Randomness in LLM responses (0.0-1.0)

_build_lifecycle_workflow (Line 143)
def _build_lifecycle_workflow(self):
    """Build LangGraph workflow for lifecycle management."""

Purpose: Build LangGraph workflow for lifecycle management.

Parameters: – self: Instance reference

_validate_transition_node (Line 164)
def _validate_transition_node(self, state):
    """Validate if state transition is allowed."""

Purpose: Validate if state transition is allowed.

Parameters: – self: Instance reference – state: Current workflow state

_check_health_node (Line 184)
def _check_health_node(self, state):
    """Check agent health."""

Purpose: Check agent health.

Parameters: – self: Instance reference – state: Current workflow state

_analyze_impact_node (Line 209)
def _analyze_impact_node(self, state):
    """Analyze impact of state transition using LLM."""

Purpose: Analyze impact of state transition using LLM.

Parameters: – self: Instance reference – state: Current workflow state

_approve_transition_node (Line 236)
def _approve_transition_node(self, state):
    """Approve or reject transition based on validation and health."""

Purpose: Approve or reject transition based on validation and health.

Parameters: – self: Instance reference – state: Current workflow state

_provide_recommendations_node (Line 252)
def _provide_recommendations_node(self, state):
    """Provide recommendations for lifecycle management."""

Purpose: Provide recommendations for lifecycle management.

Parameters: – self: Instance reference – state: Current workflow state

create_agent (Line 276)
def create_agent(self, agent_id, name, agent_type, configuration, tags):
    """Create a new managed agent."""

Purpose: Create a new managed agent.

Parameters: – self: Instance reference – agent_id: Parameter for agent_id – name: Identifier or label – agent_type: Parameter for agent_type – configuration: Parameter for configuration – tags: Parameter for tags

initialize_agent (Line 311)
def initialize_agent(self, agent_id, model, resources):
    """Initialize agent with resources."""

Purpose: Initialize agent with resources.

Parameters: – self: Instance reference – agent_id: Parameter for agent_id – model: Parameter for model – resources: Parameter for resources

activate_agent (Line 352)
def activate_agent(self, agent_id):
    """Activate agent for work."""

Purpose: Activate agent for work.

Parameters: – self: Instance reference – agent_id: Parameter for agent_id

suspend_agent (Line 361)
def suspend_agent(self, agent_id, reason, trigger):
    """Suspend active agent."""

Purpose: Suspend active agent.

Parameters: – self: Instance reference – agent_id: Parameter for agent_id – reason: Parameter for reason – trigger: Parameter for trigger

resume_agent (Line 375)
def resume_agent(self, agent_id):
    """Resume suspended agent."""

Purpose: Resume suspended agent.

Parameters: – self: Instance reference – agent_id: Parameter for agent_id

terminate_agent (Line 384)
def terminate_agent(self, agent_id, reason, trigger):
    """Terminate agent and cleanup resources."""

Purpose: Terminate agent and cleanup resources.

Parameters: – self: Instance reference – agent_id: Parameter for agent_id – reason: Parameter for reason – trigger: Parameter for trigger

_execute_transition (Line 409)
def _execute_transition(self, agent_id, target_state, trigger, reason):
    """Execute state transition with workflow validation."""

Purpose: Execute state transition with workflow validation.

Parameters: – self: Instance reference – agent_id: Parameter for agent_id – target_state: Parameter for target_state – trigger: Parameter for trigger – reason: Parameter for reason

_record_event (Line 456)
def _record_event(self, agent_id, from_state, to_state, trigger, reason, metadata):
    """Record a lifecycle event."""

Purpose: Record a lifecycle event.

Parameters: – self: Instance reference – agent_id: Parameter for agent_id – from_state: Parameter for from_state – to_state: Parameter for to_state – trigger: Parameter for trigger – reason: Parameter for reason – metadata: Parameter for metadata

…and 6 more methods

AgentLifecycleManagementPattern (Line 601)

Description: Comprehensive agent lifecycle management pattern coordinator with LangChain/LangGraph.

Methods:

__init__ (Line 606)
def __init__(self, model_name):
    """No method docstring."""

Purpose: No method docstring.

Parameters: – self: Instance reference – model_name: LLM model to use (e.g., “gpt-4”)

create (Line 609)
def create(self, agent_id, name, agent_type):
    """Create a new agent."""

Purpose: Create a new agent.

Parameters: – self: Instance reference – agent_id: Parameter for agent_id – name: Identifier or label – agent_type: Parameter for agent_type

initialize (Line 618)
def initialize(self, agent_id, model):
    """Initialize agent."""

Purpose: Initialize agent.

Parameters: – self: Instance reference – agent_id: Parameter for agent_id – model: Parameter for model

activate (Line 622)
def activate(self, agent_id):
    """Activate agent."""

Purpose: Activate agent.

Parameters: – self: Instance reference – agent_id: Parameter for agent_id

suspend (Line 626)
def suspend(self, agent_id, reason):
    """Suspend agent."""

Purpose: Suspend agent.

Parameters: – self: Instance reference – agent_id: Parameter for agent_id – reason: Parameter for reason

resume (Line 630)
def resume(self, agent_id):
    """Resume agent."""

Purpose: Resume agent.

Parameters: – self: Instance reference – agent_id: Parameter for agent_id

terminate (Line 634)
def terminate(self, agent_id, reason):
    """Terminate agent."""

Purpose: Terminate agent.

Parameters: – self: Instance reference – agent_id: Parameter for agent_id – reason: Parameter for reason

update_health (Line 638)
def update_health(self, agent_id, cpu_usage, memory_usage, error_count):
    """Update agent health."""

Purpose: Update agent health.

Parameters: – self: Instance reference – agent_id: Parameter for agent_id – cpu_usage: Parameter for cpu_usage – memory_usage: Parameter for memory_usage – error_count: Parameter for error_count

get_history (Line 648)
def get_history(self, agent_id):
    """Get agent history."""

Purpose: Get agent history.

Parameters: – self: Instance reference – agent_id: Parameter for agent_id

get_statistics (Line 652)
def get_statistics(self):
    """Get statistics."""

Purpose: Get statistics.

Parameters: – self: Instance reference


Design Patterns Used

  • Strategy Pattern: Different execution strategies for various scenarios
  • State Pattern: Managing different states in the workflow
  • Chain of Responsibility: Sequential processing through workflow nodes
  • Observer Pattern: Tracking and monitoring pattern execution
  • Factory Pattern: Creating instances with proper configuration

Usage Example

# Initialize the pattern
pattern = LifecycleState(name="example", model_name="gpt-4")

# Configure and execute
result = pattern.execute(data={"key": "value"})

# Check results
print(result)

Key Concepts

  • LLM Integration: Uses LangChain/OpenAI for intelligent decision-making
  • Workflow Orchestration: LangGraph manages execution flow through nodes
  • State Management: TypedDict defines workflow state structure
  • Error Handling: Comprehensive error handling and fallback mechanisms
  • Extensibility: Designed for easy customization and extension

Extension Points

This pattern can be extended by: 1. Adding custom workflow nodes 2. Implementing additional validation logic 3. Integrating with external services 4. Customizing LLM prompts and responses 5. Adding monitoring and logging capabilities

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *