Category: aiml-architecture

  • Agentic Architecture Pattern: Learning Agent

    
        """
    Pattern 10: Learning Agent
    
    Purpose: Enhanced implementation with full LangChain/LangGraph integration
    """
    
    from typing import Dict, Any, List, Optional
    from dataclasses import dataclass, field
    from datetime import datetime
    from enum import Enum
    from langchain_core.prompts import ChatPromptTemplate
    from langchain_openai import ChatOpenAI
    from langgraph.graph import StateGraph, END
    from typing_extensions import TypedDict
    
    
    @dataclass
    class LearningAgentConfig:
        """Configuration for Learning Agent."""
        model_name: str = "gpt-4"
        temperature: float = 0.7
        max_iterations: int = 10
        enable_logging: bool = True
    
    
    @dataclass
    class LearningAgentState:
        """State information for Learning Agent."""
        current_step: int = 0
        data: Dict[str, Any] = field(default_factory=dict)
        results: List[Any] = field(default_factory=list)
        metadata: Dict[str, Any] = field(default_factory=dict)
        timestamp: datetime = field(default_factory=datetime.now)
    
    
    class LearningAgentAgent:
        """Agent implementing Learning Agent."""
        
        def __init__(self, name: str, config: LearningAgentConfig = None):
            self.name = name
            self.config = config or LearningAgentConfig()
            self.llm = ChatOpenAI(
                model=self.config.model_name,
                temperature=self.config.temperature
            )
            self.state = LearningAgentState()
            self.execution_history: List[Dict[str, Any]] = []
        
        def process(self, input_data: Any) -> Dict[str, Any]:
            """Process input according to Learning Agent."""
            self.state.current_step += 1
            
            prompt = ChatPromptTemplate.from_messages([
                ("system", f"You are {self.name}, implementing Learning Agent. "
                          f"Provide clear, structured responses."),
                ("human", "Process this input: {input_data}")
            ])
            
            chain = prompt | self.llm
            response = chain.invoke({"input_data": str(input_data)})
            
            result = {
                "agent": self.name,
                "step": self.state.current_step,
                "input": input_data,
                "output": str(response.content),
                "timestamp": datetime.now()
            }
            
            self.execution_history.append(result)
            self.state.results.append(result)
            
            return result
        
        def get_statistics(self) -> Dict[str, Any]:
            """Get agent statistics."""
            return {
                "name": self.name,
                "total_executions": len(self.execution_history),
                "current_step": self.state.current_step,
                "results_count": len(self.state.results)
            }
    
    
    class LearningAgentPattern:
        """
        Learning Agent - Enhanced implementation
        
        This pattern provides comprehensive functionality for learning agent
        with full LangChain/LangGraph integration.
        
        Features:
        - Multi-agent coordination
        - State management
        - Execution tracking
        - LangGraph workflow integration
        """
        
        def __init__(self, config: LearningAgentConfig = None):
            self.config = config or LearningAgentConfig()
            self.agents: Dict[str, LearningAgentAgent] = {}
            self.workflow = self._build_workflow()
            self.execution_log: List[Dict[str, Any]] = []
        
        def _build_workflow(self) -> StateGraph:
            """Build LangGraph workflow for pattern execution."""
            
            class WorkflowState(TypedDict):
                input: str
                processed: str
                output: str
                metadata: Dict[str, Any]
            
            def process_input(state: WorkflowState) -> WorkflowState:
                """Process input node."""
                return {
                    **state,
                    "processed": f"Processed: {state['input']}",
                    "metadata": {"step": "process_input"}
                }
            
            def generate_output(state: WorkflowState) -> WorkflowState:
                """Generate output node."""
                llm = ChatOpenAI(model=self.config.model_name, temperature=self.config.temperature)
                
                prompt = ChatPromptTemplate.from_messages([
                    ("system", "You are implementing Learning Agent. Generate comprehensive output."),
                    ("human", "{input}")
                ])
                
                chain = prompt | llm
                response = chain.invoke({"input": state["processed"]})
                
                return {
                    **state,
                    "output": str(response.content),
                    "metadata": {**state.get("metadata", {}), "step": "generate_output"}
                }
            
            # Build workflow graph
            workflow = StateGraph(WorkflowState)
            workflow.add_node("process", process_input)
            workflow.add_node("generate", generate_output)
            workflow.set_entry_point("process")
            workflow.add_edge("process", "generate")
            workflow.add_edge("generate", END)
            
            return workflow.compile()
        
        def register_agent(self, agent: LearningAgentAgent):
            """Register an agent with the pattern."""
            self.agents[agent.name] = agent
            if self.config.enable_logging:
                print(f"Registered agent: {agent.name}")
        
        def execute(self, input_data: Any, agent_name: str = None) -> Dict[str, Any]:
            """Execute the pattern with given input."""
            
            # Use workflow if no specific agent requested
            if agent_name is None:
                result = self.workflow.invoke({
                    "input": str(input_data),
                    "processed": "",
                    "output": "",
                    "metadata": {}
                })
                
                execution_record = {
                    "pattern": "Learning Agent",
                    "input": input_data,
                    "output": result.get("output", ""),
                    "metadata": result.get("metadata", {}),
                    "timestamp": datetime.now()
                }
                
                self.execution_log.append(execution_record)
                return execution_record
            
            # Execute with specific agent
            agent = self.agents.get(agent_name)
            if not agent:
                raise ValueError(f"Agent {agent_name} not found")
            
            result = agent.process(input_data)
            self.execution_log.append(result)
            return result
        
        def run(self, input_data: Any) -> Dict[str, Any]:
            """Main execution method."""
            return self.execute(input_data)
        
        def get_statistics(self) -> Dict[str, Any]:
            """Get pattern statistics."""
            return {
                "pattern": "Learning Agent",
                "total_executions": len(self.execution_log),
                "registered_agents": len(self.agents),
                "agents": [agent.get_statistics() for agent in self.agents.values()]
            }
    
    
    # Example usage
    if __name__ == "__main__":
        print("=== Learning Agent Demo ===\n")
        
        # Create configuration
        config = LearningAgentConfig(
            model_name="gpt-4",
            temperature=0.7,
            enable_logging=True
        )
        
        # Create pattern
        pattern = LearningAgentPattern(config)
        
        # Create and register agents
        agent1 = LearningAgentAgent("Agent1", config)
        agent2 = LearningAgentAgent("Agent2", config)
        pattern.register_agent(agent1)
        pattern.register_agent(agent2)
        
        print("\nExecuting pattern workflow...")
        
        # Execute with workflow
        result1 = pattern.run("Demonstrate learning agent functionality")
        print(f"\nWorkflow Result:")
        print(f"  Output: {result1['output'][:150]}...")
        
        # Execute with specific agents
        result2 = pattern.execute("Specific task for Agent1", agent_name="Agent1")
        print(f"\nAgent1 Result:")
        print(f"  Output: {result2['output'][:150]}...")
        
        result3 = pattern.execute("Specific task for Agent2", agent_name="Agent2")
        print(f"\nAgent2 Result:")
        print(f"  Output: {result3['output'][:150]}...")
        
        # Show statistics
        print("\n=== Statistics ===")
        stats = pattern.get_statistics()
        print(f"Pattern: {stats['pattern']}")
        print(f"Total Executions: {stats['total_executions']}")
        print(f"Registered Agents: {stats['registered_agents']}")
        print(f"\nAgent Statistics:")
        for agent_stats in stats['agents']:
            print(f"  {agent_stats['name']}: {agent_stats['total_executions']} executions")
    
        

    Agentic Architecture Pattern: Learning Agent

    Pattern 10: 10 Learning Agent – Line-by-Line Explanation

    Overview

    Pattern 10: Learning Agent

    Purpose: Enhanced implementation with full LangChain/LangGraph integration


    Code Structure Analysis

    File Information

    • Pattern Number: 10
    • Pattern Name: 10 Learning Agent
    • File Path: patterns\core_agent\10_learning_agent.py
    • Total Lines: 247

    Detailed Code Explanation

    Module Docstring

    """
    Pattern 10: Learning Agent
    
    Purpose: Enhanced implementation with full LangChain/LangGraph integration
    """
    

    Explanation: This module docstring describes the purpose and key features of the 10 Learning Agent pattern.


    Imports Section

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

    Explanation: The module imports necessary dependencies: – from typing import Dict, Any, List, Optional: Type hints for better code documentation – from dataclasses import dataclass, field: Data class decorators for clean data structures – from datetime import datetime: 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 – from typing_extensions import TypedDict: Type hints for better code documentation


    Classes

    LearningAgentConfig (Line 18)

    Description: Configuration for Learning Agent.

    LearningAgentState (Line 27)

    Description: State information for Learning Agent.

    LearningAgentAgent (Line 36)

    Description: Agent implementing Learning Agent.

    Methods:

    __init__ (Line 39)
    def __init__(self, name, config):
        """No method docstring."""
    

    Purpose: No method docstring.

    Parameters: – self: Instance reference – name: Identifier or label – config: Configuration settings

    process (Line 49)
    def process(self, input_data):
        """Process input according to Learning Agent."""
    

    Purpose: Process input according to Learning Agent.

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

    get_statistics (Line 75)
    def get_statistics(self):
        """Get agent statistics."""
    

    Purpose: Get agent statistics.

    Parameters: – self: Instance reference

    LearningAgentPattern (Line 85)

    Description: Learning Agent – Enhanced implementation

    This pattern provides comprehensive functionality for learning agent with full LangChain/LangGraph integration.

    Features: – Multi-agent coordination – State management – Execution tracking – LangGraph workflow integration

    Methods:

    __init__ (Line 99)
    def __init__(self, config):
        """No method docstring."""
    

    Purpose: No method docstring.

    Parameters: – self: Instance reference – config: Configuration settings

    _build_workflow (Line 105)
    def _build_workflow(self):
        """Build LangGraph workflow for pattern execution."""
    

    Purpose: Build LangGraph workflow for pattern execution.

    Parameters: – self: Instance reference

    register_agent (Line 150)
    def register_agent(self, agent):
        """Register an agent with the pattern."""
    

    Purpose: Register an agent with the pattern.

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

    execute (Line 156)
    def execute(self, input_data, agent_name):
        """Execute the pattern with given input."""
    

    Purpose: Execute the pattern with given input.

    Parameters: – self: Instance reference – input_data: Parameter for input_data – agent_name: Parameter for agent_name

    run (Line 188)
    def run(self, input_data):
        """Main execution method."""
    

    Purpose: Main execution method.

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

    get_statistics (Line 192)
    def get_statistics(self):
        """Get pattern statistics."""
    

    Purpose: Get pattern statistics.

    Parameters: – self: Instance reference

    WorkflowState (Line 108)

    Description: No class docstring.


    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 = LearningAgentConfig(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

  • Agentic Architecture Pattern: Utility Based Agent

    
        """
    Pattern 09: Utility Based Agent
    
    Purpose: Enhanced implementation with full LangChain/LangGraph integration
    """
    
    from typing import Dict, Any, List, Optional
    from dataclasses import dataclass, field
    from datetime import datetime
    from enum import Enum
    from langchain_core.prompts import ChatPromptTemplate
    from langchain_openai import ChatOpenAI
    from langgraph.graph import StateGraph, END
    from typing_extensions import TypedDict
    
    
    @dataclass
    class UtilityBasedAgentConfig:
        """Configuration for Utility Based Agent."""
        model_name: str = "gpt-4"
        temperature: float = 0.7
        max_iterations: int = 10
        enable_logging: bool = True
    
    
    @dataclass
    class UtilityBasedAgentState:
        """State information for Utility Based Agent."""
        current_step: int = 0
        data: Dict[str, Any] = field(default_factory=dict)
        results: List[Any] = field(default_factory=list)
        metadata: Dict[str, Any] = field(default_factory=dict)
        timestamp: datetime = field(default_factory=datetime.now)
    
    
    class UtilityBasedAgentAgent:
        """Agent implementing Utility Based Agent."""
        
        def __init__(self, name: str, config: UtilityBasedAgentConfig = None):
            self.name = name
            self.config = config or UtilityBasedAgentConfig()
            self.llm = ChatOpenAI(
                model=self.config.model_name,
                temperature=self.config.temperature
            )
            self.state = UtilityBasedAgentState()
            self.execution_history: List[Dict[str, Any]] = []
        
        def process(self, input_data: Any) -> Dict[str, Any]:
            """Process input according to Utility Based Agent."""
            self.state.current_step += 1
            
            prompt = ChatPromptTemplate.from_messages([
                ("system", f"You are {self.name}, implementing Utility Based Agent. "
                          f"Provide clear, structured responses."),
                ("human", "Process this input: {input_data}")
            ])
            
            chain = prompt | self.llm
            response = chain.invoke({"input_data": str(input_data)})
            
            result = {
                "agent": self.name,
                "step": self.state.current_step,
                "input": input_data,
                "output": str(response.content),
                "timestamp": datetime.now()
            }
            
            self.execution_history.append(result)
            self.state.results.append(result)
            
            return result
        
        def get_statistics(self) -> Dict[str, Any]:
            """Get agent statistics."""
            return {
                "name": self.name,
                "total_executions": len(self.execution_history),
                "current_step": self.state.current_step,
                "results_count": len(self.state.results)
            }
    
    
    class UtilityBasedAgentPattern:
        """
        Utility Based Agent - Enhanced implementation
        
        This pattern provides comprehensive functionality for utility based agent
        with full LangChain/LangGraph integration.
        
        Features:
        - Multi-agent coordination
        - State management
        - Execution tracking
        - LangGraph workflow integration
        """
        
        def __init__(self, config: UtilityBasedAgentConfig = None):
            self.config = config or UtilityBasedAgentConfig()
            self.agents: Dict[str, UtilityBasedAgentAgent] = {}
            self.workflow = self._build_workflow()
            self.execution_log: List[Dict[str, Any]] = []
        
        def _build_workflow(self) -> StateGraph:
            """Build LangGraph workflow for pattern execution."""
            
            class WorkflowState(TypedDict):
                input: str
                processed: str
                output: str
                metadata: Dict[str, Any]
            
            def process_input(state: WorkflowState) -> WorkflowState:
                """Process input node."""
                return {
                    **state,
                    "processed": f"Processed: {state['input']}",
                    "metadata": {"step": "process_input"}
                }
            
            def generate_output(state: WorkflowState) -> WorkflowState:
                """Generate output node."""
                llm = ChatOpenAI(model=self.config.model_name, temperature=self.config.temperature)
                
                prompt = ChatPromptTemplate.from_messages([
                    ("system", "You are implementing Utility Based Agent. Generate comprehensive output."),
                    ("human", "{input}")
                ])
                
                chain = prompt | llm
                response = chain.invoke({"input": state["processed"]})
                
                return {
                    **state,
                    "output": str(response.content),
                    "metadata": {**state.get("metadata", {}), "step": "generate_output"}
                }
            
            # Build workflow graph
            workflow = StateGraph(WorkflowState)
            workflow.add_node("process", process_input)
            workflow.add_node("generate", generate_output)
            workflow.set_entry_point("process")
            workflow.add_edge("process", "generate")
            workflow.add_edge("generate", END)
            
            return workflow.compile()
        
        def register_agent(self, agent: UtilityBasedAgentAgent):
            """Register an agent with the pattern."""
            self.agents[agent.name] = agent
            if self.config.enable_logging:
                print(f"Registered agent: {agent.name}")
        
        def execute(self, input_data: Any, agent_name: str = None) -> Dict[str, Any]:
            """Execute the pattern with given input."""
            
            # Use workflow if no specific agent requested
            if agent_name is None:
                result = self.workflow.invoke({
                    "input": str(input_data),
                    "processed": "",
                    "output": "",
                    "metadata": {}
                })
                
                execution_record = {
                    "pattern": "Utility Based Agent",
                    "input": input_data,
                    "output": result.get("output", ""),
                    "metadata": result.get("metadata", {}),
                    "timestamp": datetime.now()
                }
                
                self.execution_log.append(execution_record)
                return execution_record
            
            # Execute with specific agent
            agent = self.agents.get(agent_name)
            if not agent:
                raise ValueError(f"Agent {agent_name} not found")
            
            result = agent.process(input_data)
            self.execution_log.append(result)
            return result
        
        def run(self, input_data: Any) -> Dict[str, Any]:
            """Main execution method."""
            return self.execute(input_data)
        
        def get_statistics(self) -> Dict[str, Any]:
            """Get pattern statistics."""
            return {
                "pattern": "Utility Based Agent",
                "total_executions": len(self.execution_log),
                "registered_agents": len(self.agents),
                "agents": [agent.get_statistics() for agent in self.agents.values()]
            }
    
    
    # Example usage
    if __name__ == "__main__":
        print("=== Utility Based Agent Demo ===\n")
        
        # Create configuration
        config = UtilityBasedAgentConfig(
            model_name="gpt-4",
            temperature=0.7,
            enable_logging=True
        )
        
        # Create pattern
        pattern = UtilityBasedAgentPattern(config)
        
        # Create and register agents
        agent1 = UtilityBasedAgentAgent("Agent1", config)
        agent2 = UtilityBasedAgentAgent("Agent2", config)
        pattern.register_agent(agent1)
        pattern.register_agent(agent2)
        
        print("\nExecuting pattern workflow...")
        
        # Execute with workflow
        result1 = pattern.run("Demonstrate utility based agent functionality")
        print(f"\nWorkflow Result:")
        print(f"  Output: {result1['output'][:150]}...")
        
        # Execute with specific agents
        result2 = pattern.execute("Specific task for Agent1", agent_name="Agent1")
        print(f"\nAgent1 Result:")
        print(f"  Output: {result2['output'][:150]}...")
        
        result3 = pattern.execute("Specific task for Agent2", agent_name="Agent2")
        print(f"\nAgent2 Result:")
        print(f"  Output: {result3['output'][:150]}...")
        
        # Show statistics
        print("\n=== Statistics ===")
        stats = pattern.get_statistics()
        print(f"Pattern: {stats['pattern']}")
        print(f"Total Executions: {stats['total_executions']}")
        print(f"Registered Agents: {stats['registered_agents']}")
        print(f"\nAgent Statistics:")
        for agent_stats in stats['agents']:
            print(f"  {agent_stats['name']}: {agent_stats['total_executions']} executions")
    
        

    Agentic Architecture Pattern: Utility Based Agent

    Pattern 09: 09 Utility Based Agent – Line-by-Line Explanation

    Overview

    Pattern 09: Utility Based Agent

    Purpose: Enhanced implementation with full LangChain/LangGraph integration


    Code Structure Analysis

    File Information

    • Pattern Number: 09
    • Pattern Name: 09 Utility Based Agent
    • File Path: patterns\core_agent\09_utility_based_agent.py
    • Total Lines: 247

    Detailed Code Explanation

    Module Docstring

    """
    Pattern 09: Utility Based Agent
    
    Purpose: Enhanced implementation with full LangChain/LangGraph integration
    """
    

    Explanation: This module docstring describes the purpose and key features of the 09 Utility Based Agent pattern.


    Imports Section

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

    Explanation: The module imports necessary dependencies: – from typing import Dict, Any, List, Optional: Type hints for better code documentation – from dataclasses import dataclass, field: Data class decorators for clean data structures – from datetime import datetime: 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 – from typing_extensions import TypedDict: Type hints for better code documentation


    Classes

    UtilityBasedAgentConfig (Line 18)

    Description: Configuration for Utility Based Agent.

    UtilityBasedAgentState (Line 27)

    Description: State information for Utility Based Agent.

    UtilityBasedAgentAgent (Line 36)

    Description: Agent implementing Utility Based Agent.

    Methods:

    __init__ (Line 39)
    def __init__(self, name, config):
        """No method docstring."""
    

    Purpose: No method docstring.

    Parameters: – self: Instance reference – name: Identifier or label – config: Configuration settings

    process (Line 49)
    def process(self, input_data):
        """Process input according to Utility Based Agent."""
    

    Purpose: Process input according to Utility Based Agent.

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

    get_statistics (Line 75)
    def get_statistics(self):
        """Get agent statistics."""
    

    Purpose: Get agent statistics.

    Parameters: – self: Instance reference

    UtilityBasedAgentPattern (Line 85)

    Description: Utility Based Agent – Enhanced implementation

    This pattern provides comprehensive functionality for utility based agent with full LangChain/LangGraph integration.

    Features: – Multi-agent coordination – State management – Execution tracking – LangGraph workflow integration

    Methods:

    __init__ (Line 99)
    def __init__(self, config):
        """No method docstring."""
    

    Purpose: No method docstring.

    Parameters: – self: Instance reference – config: Configuration settings

    _build_workflow (Line 105)
    def _build_workflow(self):
        """Build LangGraph workflow for pattern execution."""
    

    Purpose: Build LangGraph workflow for pattern execution.

    Parameters: – self: Instance reference

    register_agent (Line 150)
    def register_agent(self, agent):
        """Register an agent with the pattern."""
    

    Purpose: Register an agent with the pattern.

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

    execute (Line 156)
    def execute(self, input_data, agent_name):
        """Execute the pattern with given input."""
    

    Purpose: Execute the pattern with given input.

    Parameters: – self: Instance reference – input_data: Parameter for input_data – agent_name: Parameter for agent_name

    run (Line 188)
    def run(self, input_data):
        """Main execution method."""
    

    Purpose: Main execution method.

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

    get_statistics (Line 192)
    def get_statistics(self):
        """Get pattern statistics."""
    

    Purpose: Get pattern statistics.

    Parameters: – self: Instance reference

    WorkflowState (Line 108)

    Description: No class docstring.


    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 = UtilityBasedAgentConfig(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

  • Agentic Architecture Pattern: Goal Oriented Agent

    
        """
    Pattern 08: Goal-Oriented Agent Pattern
    Agent that explicitly pursues and manages goals.
    """
    
    from typing import Dict, Any, List, Optional
    from dataclasses import dataclass, field
    from datetime import datetime
    from enum import Enum
    from langchain_core.prompts import ChatPromptTemplate
    from langchain_openai import ChatOpenAI
    
    
    class GoalStatus(Enum):
        """Status of a goal."""
        PENDING = "pending"
        IN_PROGRESS = "in_progress"
        COMPLETED = "completed"
        FAILED = "failed"
        ABANDONED = "abandoned"
    
    
    @dataclass
    class Goal:
        """A goal the agent pursues."""
        id: str
        description: str
        priority: int  # 1-10
        status: GoalStatus = GoalStatus.PENDING
        sub_goals: List[str] = field(default_factory=list)
        progress: float = 0.0  # 0.0 to 1.0
        created_at: datetime = field(default_factory=datetime.now)
        deadline: Optional[datetime] = None
    
    
    class GoalOrientedAgentPattern:
        """
        Goal-Oriented Agent that:
        - Maintains explicit goals
        - Prioritizes goals
        - Decomposes goals into sub-goals
        - Tracks progress
        - Adapts when goals fail
        """
        
        def __init__(self, name: str = "GoalAgent", model_name: str = "gpt-4"):
            self.name = name
            self.llm = ChatOpenAI(model=model_name, temperature=0.6)
            self.goals: Dict[str, Goal] = {}
            self.goal_counter = 0
            
        def add_goal(self, description: str, priority: int = 5, deadline: Optional[datetime] = None) -> str:
            """Add a new goal."""
            goal_id = f"goal_{self.goal_counter}"
            self.goal_counter += 1
            
            goal = Goal(
                id=goal_id,
                description=description,
                priority=priority,
                deadline=deadline
            )
            self.goals[goal_id] = goal
            
            print(f"🎯 New goal: {description} (priority: {priority})")
            return goal_id
        
        def decompose_goal(self, goal_id: str) -> List[str]:
            """Decompose a goal into sub-goals."""
            goal = self.goals[goal_id]
            
            prompt = ChatPromptTemplate.from_messages([
                ("system", f"You are {self.name}. Decompose goals into achievable sub-goals."),
                ("human", "Goal: {goal}\n\nBreak this down into 3-5 concrete sub-goals:")
            ])
            
            chain = prompt | self.llm
            response = chain.invoke({"goal": goal.description})
            
            # Parse sub-goals (simplified)
            sub_goals_text = str(response.content)
            sub_goals = [line.strip() for line in sub_goals_text.split("\n") if line.strip() and any(c.isdigit() for c in line)]
            
            # Create sub-goal IDs
            sub_goal_ids = []
            for sub_goal_desc in sub_goals[:5]:  # Limit to 5
                sub_id = self.add_goal(sub_goal_desc, priority=goal.priority - 1)
                sub_goal_ids.append(sub_id)
            
            goal.sub_goals = sub_goal_ids
            print(f"📋 Decomposed into {len(sub_goal_ids)} sub-goals")
            
            return sub_goal_ids
        
        def select_next_goal(self) -> Optional[Goal]:
            """Select the next goal to work on."""
            active_goals = [g for g in self.goals.values() 
                           if g.status in [GoalStatus.PENDING, GoalStatus.IN_PROGRESS]]
            
            if not active_goals:
                return None
            
            # Sort by priority, then by deadline
            active_goals.sort(key=lambda g: (
                -g.priority,  # Higher priority first
                g.deadline if g.deadline else datetime.max  # Earlier deadline first
            ))
            
            return active_goals[0]
        
        def work_on_goal(self, goal_id: str) -> Dict[str, Any]:
            """Work on achieving a goal."""
            goal = self.goals[goal_id]
            goal.status = GoalStatus.IN_PROGRESS
            
            prompt = ChatPromptTemplate.from_messages([
                ("system", f"You are {self.name} working on a goal."),
                ("human", """Goal: {goal}
                Priority: {priority}
                Current progress: {progress:.0%}
                
                What actions should I take to make progress on this goal?""")
            ])
            
            chain = prompt | self.llm
            response = chain.invoke({
                "goal": goal.description,
                "priority": goal.priority,
                "progress": goal.progress
            })
            
            actions = str(response.content)
            
            # Simulate progress
            goal.progress = min(1.0, goal.progress + 0.3)
            
            if goal.progress >= 1.0:
                goal.status = GoalStatus.COMPLETED
                print(f"✅ Goal completed: {goal.description}")
            
            return {
                "goal_id": goal_id,
                "actions": actions,
                "progress": goal.progress,
                "status": goal.status.value
            }
        
        def run(self, initial_goals: List[Dict[str, Any]], cycles: int = 3) -> Dict[str, Any]:
            """
            Run goal-oriented agent.
            
            Args:
                initial_goals: List of dicts with 'description' and 'priority'
                cycles: Number of work cycles
                
            Returns:
                Results of goal pursuit
            """
            # Add initial goals
            for goal_spec in initial_goals:
                goal_id = self.add_goal(
                    goal_spec['description'],
                    goal_spec.get('priority', 5)
                )
                # Optionally decompose complex goals
                if goal_spec.get('decompose', False):
                    self.decompose_goal(goal_id)
            
            # Work on goals
            results = []
            for cycle in range(cycles):
                print(f"\n--- Cycle {cycle + 1}/{cycles} ---")
                goal = self.select_next_goal()
                if not goal:
                    print("No active goals remaining")
                    break
                
                result = self.work_on_goal(goal.id)
                results.append(result)
            
            # Summary
            completed = sum(1 for g in self.goals.values() if g.status == GoalStatus.COMPLETED)
            in_progress = sum(1 for g in self.goals.values() if g.status == GoalStatus.IN_PROGRESS)
            
            return {
                "agent": self.name,
                "total_goals": len(self.goals),
                "completed": completed,
                "in_progress": in_progress,
                "cycles_executed": len(results),
                "work_results": results
            }
    
    
    # Example usage
    if __name__ == "__main__":
        print("\n=== Goal-Oriented Agent Example ===")
        
        agent = GoalOrientedAgentPattern(name="GoalBot")
        
        initial_goals = [
            {"description": "Learn a new programming language", "priority": 8, "decompose": True},
            {"description": "Improve physical fitness", "priority": 6},
            {"description": "Complete project documentation", "priority": 7}
        ]
        
        result = agent.run(initial_goals, cycles=4)
        
        print("\n=== Results ===")
        print(f"Agent: {result['agent']}")
        print(f"Total goals created: {result['total_goals']}")
        print(f"Completed: {result['completed']}")
        print(f"In progress: {result['in_progress']}")
        print(f"Cycles executed: {result['cycles_executed']}")
        print("\nWork done:")
        for i, work in enumerate(result['work_results'], 1):
            print(f"\n  Cycle {i}: {work['goal_id']}")
            print(f"    Progress: {work['progress']:.0%}")
            print(f"    Status: {work['status']}")
    
        

    Agentic Architecture Pattern: Goal Oriented Agent

    Pattern 08: 08 Goal Oriented Agent – Line-by-Line Explanation

    Overview

    Pattern 08: Goal-Oriented Agent Pattern Agent that explicitly pursues and manages goals.


    Code Structure Analysis

    File Information

    • Pattern Number: 08
    • Pattern Name: 08 Goal Oriented Agent
    • File Path: patterns\core_agent\08_goal_oriented_agent.py
    • Total Lines: 220

    Detailed Code Explanation

    Module Docstring

    """
    Pattern 08: Goal-Oriented Agent Pattern
    Agent that explicitly pursues and manages goals.
    """
    

    Explanation: This module docstring describes the purpose and key features of the 08 Goal Oriented Agent pattern.


    Imports Section

    from typing import Dict, Any, List, Optional
    from dataclasses import dataclass, field
    from datetime import datetime
    from enum import Enum
    from langchain_core.prompts import ChatPromptTemplate
    from langchain_openai import ChatOpenAI  # First 20 imports shown
    

    Explanation: The module imports necessary dependencies: – from typing import Dict, Any, List, Optional: Type hints for better code documentation – from dataclasses import dataclass, field: Data class decorators for clean data structures – from datetime import datetime: 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


    Enumerations

    GoalStatus (Line 14)

    class GoalStatus(Enum):
        PENDING
        IN_PROGRESS
        COMPLETED
        FAILED
        ABANDONED
    

    Purpose: Status of a goal.

    Values: – PENDING: Initial state, not yet processed – IN_PROGRESS: Represents in progress – COMPLETED: Successfully finished – FAILED: Execution failed – ABANDONED: Represents abandoned


    Classes

    GoalStatus (Line 14)

    Description: Status of a goal.

    Goal (Line 24)

    Description: A goal the agent pursues.

    GoalOrientedAgentPattern (Line 36)

    Description: Goal-Oriented Agent that: – Maintains explicit goals – Prioritizes goals – Decomposes goals into sub-goals – Tracks progress – Adapts when goals fail

    Methods:

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

    Purpose: No method docstring.

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

    add_goal (Line 52)
    def add_goal(self, description, priority, deadline):
        """Add a new goal."""
    

    Purpose: Add a new goal.

    Parameters: – self: Instance reference – description: Parameter for description – priority: Parameter for priority – deadline: Parameter for deadline

    decompose_goal (Line 68)
    def decompose_goal(self, goal_id):
        """Decompose a goal into sub-goals."""
    

    Purpose: Decompose a goal into sub-goals.

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

    select_next_goal (Line 95)
    def select_next_goal(self):
        """Select the next goal to work on."""
    

    Purpose: Select the next goal to work on.

    Parameters: – self: Instance reference

    work_on_goal (Line 111)
    def work_on_goal(self, goal_id):
        """Work on achieving a goal."""
    

    Purpose: Work on achieving a goal.

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

    run (Line 148)
    def run(self, initial_goals, cycles):
        """Run goal-oriented agent.
    
    Args:
        initial_goals: List of dicts with 'description' and 'priority'
        cycles: Number of work cycles
    
    Returns:
        Results of goal pursuit"""
    

    Purpose: Run goal-oriented agent.

    Args: initial_goals: List of dicts with ‘description’ and ‘priority’ cycles: Number of work cycles

    Returns: Results of goal pursuit

    Parameters: – self: Instance reference – initial_goals: Parameter for initial_goals – cycles: Parameter for cycles


    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 = GoalStatus(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

  • Agentic Architecture Pattern: Cognitive Agent

    
        """
    Pattern 07: Cognitive Agent Pattern
    Agent with cognitive processes: perception, memory, learning, reasoning, and decision-making.
    """
    
    from typing import Dict, Any, List, Optional
    from dataclasses import dataclass, field
    from datetime import datetime
    from langchain_core.prompts import ChatPromptTemplate
    from langchain_openai import ChatOpenAI
    from langchain.memory import ConversationBufferMemory
    
    
    @dataclass
    class CognitiveState:
        """Cognitive state of the agent."""
        attention_focus: Optional[str] = None
        working_memory: List[str] = field(default_factory=list)
        emotional_state: str = "neutral"
        cognitive_load: float = 0.0  # 0.0 to 1.0
        timestamp: datetime = field(default_factory=datetime.now)
    
    
    class CognitiveAgentPattern:
        """
        Cognitive Agent with:
        - Attention mechanisms
        - Working and long-term memory
        - Learning from experience
        - Metacognition (thinking about thinking)
        - Emotional processing
        """
        
        def __init__(self, name: str = "CognitiveAgent", model_name: str = "gpt-4"):
            self.name = name
            self.llm = ChatOpenAI(model=model_name, temperature=0.7)
            self.cognitive_state = CognitiveState()
            self.long_term_memory = ConversationBufferMemory()
            self.learned_patterns: Dict[str, int] = {}  # Pattern -> frequency
            self.metacognitive_insights: List[str] = []
            
        def perceive(self, input_data: str, priority: int = 5):
            """Perceive input with attention mechanism."""
            # Attention: focus on high priority items
            if priority >= 7 or not self.cognitive_state.attention_focus:
                self.cognitive_state.attention_focus = input_data
                print(f"👁️ Attention focused on: {input_data[:50]}...")
            
            # Add to working memory (limited capacity)
            self.cognitive_state.working_memory.append(input_data)
            if len(self.cognitive_state.working_memory) > 5:  # Working memory limit
                self.cognitive_state.working_memory.pop(0)
            
            # Update cognitive load
            self.cognitive_state.cognitive_load = min(1.0, len(self.cognitive_state.working_memory) / 5)
        
        def process_cognitively(self, task: str) -> str:
            """Process task using cognitive capabilities."""
            prompt = ChatPromptTemplate.from_messages([
                ("system", f"""You are {self.name}, a cognitive agent.
                
                Current cognitive state:
                - Attention: {self.cognitive_state.attention_focus}
                - Working memory: {self.cognitive_state.working_memory}
                - Emotional state: {self.cognitive_state.emotional_state}
                - Cognitive load: {self.cognitive_state.cognitive_load:.1%}
                
                Learned patterns: {self.learned_patterns}
                
                Use your cognitive processes to handle this task."""),
                ("human", "{task}")
            ])
            
            chain = prompt | self.llm
            response = chain.invoke({"task": task})
            result = str(response.content)
            
            # Store in long-term memory
            self.long_term_memory.save_context(
                {"input": task},
                {"output": result}
            )
            
            return result
        
        def learn_from_experience(self, experience: str):
            """Learn patterns from experiences."""
            # Simple pattern learning: track what we see frequently
            words = experience.lower().split()
            for word in words:
                if len(word) > 3:  # Ignore short words
                    self.learned_patterns[word] = self.learned_patterns.get(word, 0) + 1
            
            print(f"📚 Learned from experience. Total patterns: {len(self.learned_patterns)}")
        
        def metacognitive_reflection(self) -> str:
            """Reflect on own cognitive processes."""
            prompt = ChatPromptTemplate.from_messages([
                ("system", f"""You are {self.name}. Engage in metacognition.
                Reflect on your own thinking processes.
                
                Your cognitive state:
                - Cognitive load: {self.cognitive_state.cognitive_load:.1%}
                - Working memory items: {len(self.cognitive_state.working_memory)}
                - Learned patterns: {len(self.learned_patterns)}
                - Previous insights: {self.metacognitive_insights[-3:]}"""),
                ("human", "Reflect: How effectively am I thinking? What can I improve?")
            ])
            
            chain = prompt | self.llm
            response = chain.invoke({})
            insight = str(response.content)
            
            self.metacognitive_insights.append(insight)
            return insight
        
        def adjust_emotional_state(self, event: str):
            """Process emotional response to events."""
            prompt = ChatPromptTemplate.from_messages([
                ("system", f"Determine emotional response to event. Current state: {self.cognitive_state.emotional_state}"),
                ("human", "Event: {event}\nNew emotional state (one word):")
            ])
            
            chain = prompt | self.llm
            response = chain.invoke({"event": event})
            self.cognitive_state.emotional_state = str(response.content).strip().split()[0].lower()
            print(f"💭 Emotional state: {self.cognitive_state.emotional_state}")
        
        def run(self, task: str, experiences: Optional[List[str]] = None) -> Dict[str, Any]:
            """
            Run cognitive agent on a task.
            
            Args:
                task: Main task to process
                experiences: Optional prior experiences to learn from
                
            Returns:
                Results with cognitive state
            """
            # Learn from experiences
            if experiences:
                for exp in experiences:
                    self.learn_from_experience(exp)
            
            # Perceive task
            self.perceive(task, priority=8)
            
            # Process cognitively
            result = self.process_cognitively(task)
            
            # Emotional processing
            self.adjust_emotional_state(task)
            
            # Metacognitive reflection
            reflection = self.metacognitive_reflection()
            
            return {
                "agent": self.name,
                "task": task,
                "result": result,
                "cognitive_state": {
                    "attention": self.cognitive_state.attention_focus,
                    "working_memory_size": len(self.cognitive_state.working_memory),
                    "cognitive_load": f"{self.cognitive_state.cognitive_load:.1%}",
                    "emotional_state": self.cognitive_state.emotional_state
                },
                "learning": {
                    "patterns_learned": len(self.learned_patterns),
                    "top_patterns": sorted(self.learned_patterns.items(), key=lambda x: x[1], reverse=True)[:5]
                },
                "metacognition": reflection
            }
    
    
    # Example usage
    if __name__ == "__main__":
        print("\n=== Cognitive Agent Example ===")
        
        agent = CognitiveAgentPattern(name="CognitiveBot")
        
        # Provide experiences to learn from
        experiences = [
            "Users often ask about weather and temperature",
            "System performance issues need quick attention",
            "Data analysis requires careful attention to detail"
        ]
        
        # Run cognitive processing
        result = agent.run(
            task="Analyze the system performance data and provide recommendations",
            experiences=experiences
        )
        
        print(f"\nAgent: {result['agent']}")
        print(f"Task: {result['task']}")
        print(f"\nResult: {result['result'][:200]}...")
        print(f"\nCognitive State:")
        for key, value in result['cognitive_state'].items():
            print(f"  {key}: {value}")
        print(f"\nLearning:")
        print(f"  Patterns learned: {result['learning']['patterns_learned']}")
        print(f"  Top patterns: {result['learning']['top_patterns']}")
        print(f"\nMetacognition:")
        print(f"  {result['metacognition'][:150]}...")
    
        

    Agentic Architecture Pattern: Cognitive Agent

    Pattern 07: 07 Cognitive Agent – Line-by-Line Explanation

    Overview

    Pattern 07: Cognitive Agent Pattern Agent with cognitive processes: perception, memory, learning, reasoning, and decision-making.


    Code Structure Analysis

    File Information

    • Pattern Number: 07
    • Pattern Name: 07 Cognitive Agent
    • File Path: patterns\core_agent\07_cognitive_agent.py
    • Total Lines: 205

    Detailed Code Explanation

    Module Docstring

    """
    Pattern 07: Cognitive Agent Pattern
    Agent with cognitive processes: perception, memory, learning, reasoning, and decision-making.
    """
    

    Explanation: This module docstring describes the purpose and key features of the 07 Cognitive Agent pattern.


    Imports Section

    from typing import Dict, Any, List, Optional
    from dataclasses import dataclass, field
    from datetime import datetime
    from langchain_core.prompts import ChatPromptTemplate
    from langchain_openai import ChatOpenAI
    from langchain.memory import ConversationBufferMemory  # First 20 imports shown
    

    Explanation: The module imports necessary dependencies: – from typing import Dict, Any, List, Optional: Type hints for better code documentation – from dataclasses import dataclass, field: Data class decorators for clean data structures – from datetime import datetime: Date and time utilities – from langchain_core.prompts import ChatPromptTemplate: LangChain framework integration – from langchain_openai import ChatOpenAI: LangChain framework integration – from langchain.memory import ConversationBufferMemory: LangChain framework integration


    Classes

    CognitiveState (Line 15)

    Description: Cognitive state of the agent.

    CognitiveAgentPattern (Line 24)

    Description: Cognitive Agent with: – Attention mechanisms – Working and long-term memory – Learning from experience – Metacognition (thinking about thinking) – Emotional processing

    Methods:

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

    Purpose: No method docstring.

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

    perceive (Line 42)
    def perceive(self, input_data, priority):
        """Perceive input with attention mechanism."""
    

    Purpose: Perceive input with attention mechanism.

    Parameters: – self: Instance reference – input_data: Parameter for input_data – priority: Parameter for priority

    process_cognitively (Line 57)
    def process_cognitively(self, task):
        """Process task using cognitive capabilities."""
    

    Purpose: Process task using cognitive capabilities.

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

    learn_from_experience (Line 86)
    def learn_from_experience(self, experience):
        """Learn patterns from experiences."""
    

    Purpose: Learn patterns from experiences.

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

    metacognitive_reflection (Line 96)
    def metacognitive_reflection(self):
        """Reflect on own cognitive processes."""
    

    Purpose: Reflect on own cognitive processes.

    Parameters: – self: Instance reference

    adjust_emotional_state (Line 117)
    def adjust_emotional_state(self, event):
        """Process emotional response to events."""
    

    Purpose: Process emotional response to events.

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

    run (Line 129)
    def run(self, task, experiences):
        """Run cognitive agent on a task.
    
    Args:
        task: Main task to process
        experiences: Optional prior experiences to learn from
    
    Returns:
        Results with cognitive state"""
    

    Purpose: Run cognitive agent on a task.

    Args: task: Main task to process experiences: Optional prior experiences to learn from

    Returns: Results with cognitive state

    Parameters: – self: Instance reference – task: Parameter for task – experiences: Parameter for experiences


    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 = CognitiveState(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

  • Agentic Architecture Pattern: Hybrid Agent

    
        """
    Pattern 06: Hybrid Agent Pattern
    Combines reactive and deliberative approaches for balanced performance.
    """
    
    from typing import Dict, Any, List, Optional
    from dataclasses import dataclass, field
    from datetime import datetime
    from langchain_core.prompts import ChatPromptTemplate
    from langchain_openai import ChatOpenAI
    
    
    @dataclass
    class Stimulus:
        """Input stimulus."""
        type: str
        data: Any
        urgency: int  # 1-10
        timestamp: datetime = field(default_factory=datetime.now)
    
    
    @dataclass
    class Plan:
        """Deliberated plan."""
        goal: str
        steps: List[str]
        created_at: datetime = field(default_factory=datetime.now)
    
    
    class HybridAgentPattern:
        """
        Hybrid Agent combining:
        - Reactive layer: Fast responses to urgent stimuli
        - Deliberative layer: Planning for complex tasks
        - Intelligent switching between modes
        """
        
        def __init__(self, name: str = "HybridAgent", model_name: str = "gpt-4"):
            self.name = name
            self.llm = ChatOpenAI(model=model_name, temperature=0.5)
            self.reactive_threshold = 7  # Urgency >= 7 triggers reactive mode
            self.beliefs: Dict[str, Any] = {}
            self.plans: List[Plan] = []
            self.mode_history: List[str] = []
            
        def process(self, stimulus: Stimulus) -> Dict[str, Any]:
            """Process stimulus using hybrid approach."""
            # Decide mode based on urgency
            if stimulus.urgency >= self.reactive_threshold:
                mode = "reactive"
                response = self._react(stimulus)
            else:
                mode = "deliberative"
                response = self._deliberate(stimulus)
            
            self.mode_history.append(mode)
            
            return {
                "stimulus": stimulus.type,
                "mode": mode,
                "urgency": stimulus.urgency,
                "response": response
            }
        
        def _react(self, stimulus: Stimulus) -> str:
            """Reactive response - fast and direct."""
            prompt = ChatPromptTemplate.from_messages([
                ("system", f"You are {self.name} in REACTIVE mode. Respond quickly!"),
                ("human", "URGENT ({urgency}/10): {type} - {data}\nImmediate action:")
            ])
            
            chain = prompt | self.llm
            response = chain.invoke({
                "urgency": stimulus.urgency,
                "type": stimulus.type,
                "data": stimulus.data
            })
            return f"[REACTIVE] {response.content}"
        
        def _deliberate(self, stimulus: Stimulus) -> str:
            """Deliberative response - planned and reasoned."""
            prompt = ChatPromptTemplate.from_messages([
                ("system", f"""You are {self.name} in DELIBERATIVE mode.
                Think carefully and plan your response.
                Current beliefs: {{beliefs}}"""),
                ("human", "Stimulus: {type} ({urgency}/10)\nData: {data}\n\nPlanned response:")
            ])
            
            chain = prompt | self.llm
            response = chain.invoke({
                "urgency": stimulus.urgency,
                "type": stimulus.type,
                "data": stimulus.data,
                "beliefs": str(self.beliefs)
            })
            return f"[DELIBERATIVE] {response.content}"
        
        def update_belief(self, key: str, value: Any):
            """Update agent's beliefs (deliberative layer)."""
            self.beliefs[key] = value
        
        def create_plan(self, goal: str, steps: List[str]):
            """Create a plan (deliberative layer)."""
            plan = Plan(goal=goal, steps=steps)
            self.plans.append(plan)
        
        def run(self, stimuli: List[Stimulus]) -> Dict[str, Any]:
            """
            Process multiple stimuli using hybrid approach.
            
            Args:
                stimuli: List of stimuli to process
                
            Returns:
                Results showing mode switching
            """
            results = []
            
            for stimulus in stimuli:
                result = self.process(stimulus)
                results.append(result)
            
            # Calculate mode usage
            reactive_count = self.mode_history.count("reactive")
            deliberative_count = self.mode_history.count("deliberative")
            
            return {
                "agent": self.name,
                "total_stimuli": len(stimuli),
                "results": results,
                "mode_usage": {
                    "reactive": reactive_count,
                    "deliberative": deliberative_count
                },
                "reactive_threshold": self.reactive_threshold
            }
    
    
    # Example usage
    if __name__ == "__main__":
        print("\n=== Hybrid Agent Example ===")
        
        agent = HybridAgentPattern(name="HybridBot")
        
        # Set some beliefs for deliberative mode
        agent.update_belief("environment", "office")
        agent.update_belief("time_of_day", "morning")
        
        # Various stimuli with different urgencies
        stimuli = [
            Stimulus(type="meeting_reminder", data="Meeting in 1 hour", urgency=3),
            Stimulus(type="fire_alarm", data="Fire detected on floor 3!", urgency=10),
            Stimulus(type="email", data="New message from colleague", urgency=2),
            Stimulus(type="system_failure", data="Critical service down", urgency=9),
            Stimulus(type="question", data="What's the weather?", urgency=1),
        ]
        
        result = agent.run(stimuli)
        
        print(f"\nAgent: {result['agent']}")
        print(f"Reactive Threshold: {result['reactive_threshold']}/10")
        print(f"\nMode Usage:")
        print(f"  Reactive: {result['mode_usage']['reactive']}")
        print(f"  Deliberative: {result['mode_usage']['deliberative']}")
        print(f"\nProcessing Results:")
        for r in result['results']:
            print(f"\n  {r['stimulus']} (urgency: {r['urgency']}/10)")
            print(f"  Mode: {r['mode']}")
            print(f"  Response: {r['response'][:100]}...")
    
        

    Agentic Architecture Pattern: Hybrid Agent

    Pattern 06: 06 Hybrid Agent – Line-by-Line Explanation

    Overview

    Pattern 06: Hybrid Agent Pattern Combines reactive and deliberative approaches for balanced performance.


    Code Structure Analysis

    File Information

    • Pattern Number: 06
    • Pattern Name: 06 Hybrid Agent
    • File Path: patterns\core_agent\06_hybrid_agent.py
    • Total Lines: 170

    Detailed Code Explanation

    Module Docstring

    """
    Pattern 06: Hybrid Agent Pattern
    Combines reactive and deliberative approaches for balanced performance.
    """
    

    Explanation: This module docstring describes the purpose and key features of the 06 Hybrid Agent pattern.


    Imports Section

    from typing import Dict, Any, List, Optional
    from dataclasses import dataclass, field
    from datetime import datetime
    from langchain_core.prompts import ChatPromptTemplate
    from langchain_openai import ChatOpenAI  # First 20 imports shown
    

    Explanation: The module imports necessary dependencies: – from typing import Dict, Any, List, Optional: Type hints for better code documentation – from dataclasses import dataclass, field: Data class decorators for clean data structures – from datetime import datetime: Date and time utilities – from langchain_core.prompts import ChatPromptTemplate: LangChain framework integration – from langchain_openai import ChatOpenAI: LangChain framework integration


    Classes

    Stimulus (Line 14)

    Description: Input stimulus.

    Plan (Line 23)

    Description: Deliberated plan.

    HybridAgentPattern (Line 30)

    Description: Hybrid Agent combining: – Reactive layer: Fast responses to urgent stimuli – Deliberative layer: Planning for complex tasks – Intelligent switching between modes

    Methods:

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

    Purpose: No method docstring.

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

    process (Line 46)
    def process(self, stimulus):
        """Process stimulus using hybrid approach."""
    

    Purpose: Process stimulus using hybrid approach.

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

    _react (Line 65)
    def _react(self, stimulus):
        """Reactive response - fast and direct."""
    

    Purpose: Reactive response – fast and direct.

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

    _deliberate (Line 80)
    def _deliberate(self, stimulus):
        """Deliberative response - planned and reasoned."""
    

    Purpose: Deliberative response – planned and reasoned.

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

    update_belief (Line 98)
    def update_belief(self, key, value):
        """Update agent's beliefs (deliberative layer)."""
    

    Purpose: Update agent’s beliefs (deliberative layer).

    Parameters: – self: Instance reference – key: Parameter for key – value: Parameter for value

    create_plan (Line 102)
    def create_plan(self, goal, steps):
        """Create a plan (deliberative layer)."""
    

    Purpose: Create a plan (deliberative layer).

    Parameters: – self: Instance reference – goal: Parameter for goal – steps: Parameter for steps

    run (Line 107)
    def run(self, stimuli):
        """Process multiple stimuli using hybrid approach.
    
    Args:
        stimuli: List of stimuli to process
    
    Returns:
        Results showing mode switching"""
    

    Purpose: Process multiple stimuli using hybrid approach.

    Args: stimuli: List of stimuli to process

    Returns: Results showing mode switching

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


    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 = Stimulus(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

  • Agentic Architecture Pattern: Deliberative Agent

    
        """
    Pattern 05: Deliberative Agent Pattern
    An agent that plans and reasons before acting, using symbolic representations.
    """
    
    from typing import Dict, Any, List, Optional
    from dataclasses import dataclass, field
    from datetime import datetime
    from langchain_core.prompts import ChatPromptTemplate
    from langchain_openai import ChatOpenAI
    
    
    @dataclass
    class BeliefState:
        """Symbolic representation of agent's beliefs."""
        facts: Dict[str, Any] = field(default_factory=dict)
        rules: List[str] = field(default_factory=list)
        timestamp: datetime = field(default_factory=datetime.now)
    
    
    @dataclass
    class Plan:
        """A deliberated plan of actions."""
        goal: str
        steps: List[str]
        expected_outcome: str
        confidence: float
        created_at: datetime = field(default_factory=datetime.now)
    
    
    class DeliberativeAgentPattern:
        """
        Deliberative Agent that:
        - Maintains symbolic world model
        - Plans before acting
        - Reasons about consequences
        - Uses explicit representation of knowledge
        """
        
        def __init__(self, name: str = "DeliberativeAgent", model_name: str = "gpt-4"):
            self.name = name
            self.llm = ChatOpenAI(model=model_name, temperature=0.2)
            self.beliefs = BeliefState()
            self.plans: List[Plan] = []
            self.execution_history: List[Dict[str, Any]] = []
            
        def update_beliefs(self, fact_key: str, fact_value: Any):
            """Update the agent's belief state."""
            self.beliefs.facts[fact_key] = fact_value
            self.beliefs.timestamp = datetime.now()
            print(f"💭 Belief updated: {fact_key} = {fact_value}")
        
        def add_rule(self, rule: str):
            """Add a reasoning rule."""
            self.beliefs.rules.append(rule)
            print(f"📜 Rule added: {rule}")
        
        def deliberate(self, goal: str) -> Plan:
            """Deliberate and create a plan to achieve a goal."""
            print(f"\n🤔 Deliberating on goal: {goal}")
            
            prompt = ChatPromptTemplate.from_messages([
                ("system", f"""You are {self.name}, a deliberative agent.
                Carefully reason and plan before acting.
                
                Current beliefs:
                Facts: {{facts}}
                Rules: {{rules}}
                
                Create a detailed, step-by-step plan."""),
                ("human", "Goal: {goal}\n\nProvide a deliberated plan with steps and expected outcome:")
            ])
            
            chain = prompt | self.llm
            response = chain.invoke({
                "facts": str(self.beliefs.facts),
                "rules": str(self.beliefs.rules),
                "goal": goal
            })
            
            # Parse response into plan (simplified)
            plan_text = str(response.content)
            steps = [line.strip() for line in plan_text.split("\n") if line.strip() and any(char.isdigit() for char in line)]
            
            plan = Plan(
                goal=goal,
                steps=steps if steps else [plan_text],
                expected_outcome="Goal achieved through deliberate action",
                confidence=0.8
            )
            
            self.plans.append(plan)
            print(f"✅ Plan created with {len(plan.steps)} steps")
            return plan
        
        def reason_about_action(self, action: str) -> Dict[str, Any]:
            """Reason about the consequences of an action."""
            prompt = ChatPromptTemplate.from_messages([
                ("system", f"""You are {self.name}. Reason about action consequences.
                Beliefs: {{beliefs}}
                Rules: {{rules}}"""),
                ("human", "Action: {action}\n\nAnalyze: What are the likely consequences?")
            ])
            
            chain = prompt | self.llm
            response = chain.invoke({
                "action": action,
                "beliefs": str(self.beliefs.facts),
                "rules": str(self.beliefs.rules)
            })
            
            return {
                "action": action,
                "reasoning": str(response.content),
                "beliefs_considered": len(self.beliefs.facts)
            }
        
        def execute_plan(self, plan: Plan) -> Dict[str, Any]:
            """Execute a deliberated plan."""
            print(f"\n🎯 Executing plan for: {plan.goal}")
            results = []
            
            for i, step in enumerate(plan.steps, 1):
                print(f"  Step {i}: {step}")
                # In real implementation, this would actually execute the step
                # Here we simulate with reasoning
                reasoning = self.reason_about_action(step)
                results.append(reasoning)
            
            execution = {
                "plan": plan.goal,
                "steps_executed": len(plan.steps),
                "results": results,
                "success": True
            }
            
            self.execution_history.append(execution)
            return execution
        
        def run(self, goal: str, initial_beliefs: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
            """
            Main execution: deliberate and execute a plan for a goal.
            
            Args:
                goal: The goal to achieve
                initial_beliefs: Optional initial beliefs to set
                
            Returns:
                Dictionary with deliberation and execution results
            """
            # Set initial beliefs
            if initial_beliefs:
                for key, value in initial_beliefs.items():
                    self.update_beliefs(key, value)
            
            # Deliberate
            plan = self.deliberate(goal)
            
            # Execute
            execution = self.execute_plan(plan)
            
            return {
                "agent": self.name,
                "goal": goal,
                "plan": {
                    "steps": plan.steps,
                    "confidence": plan.confidence
                },
                "execution": execution,
                "beliefs": self.beliefs.facts
            }
    
    
    # Example usage
    if __name__ == "__main__":
        print("\n=== Deliberative Agent Example ===")
        
        # Create deliberative agent
        agent = DeliberativeAgentPattern(name="ThinkBot")
        
        # Add reasoning rules
        agent.add_rule("If weather is rainy, take umbrella")
        agent.add_rule("If traffic is heavy, leave early")
        agent.add_rule("If meeting is important, prepare materials")
        
        # Set initial beliefs
        initial_beliefs = {
            "weather": "rainy",
            "traffic": "heavy",
            "meeting_time": "10:00 AM",
            "current_time": "8:30 AM",
            "meeting_importance": "high"
        }
        
        # Run deliberative process
        result = agent.run(
            goal="Attend the important meeting on time",
            initial_beliefs=initial_beliefs
        )
        
        print("\n=== Deliberation Results ===")
        print(f"Agent: {result['agent']}")
        print(f"Goal: {result['goal']}")
        print(f"\nPlan (Confidence: {result['plan']['confidence']}):")
        for i, step in enumerate(result['plan']['steps'], 1):
            print(f"  {i}. {step}")
        print(f"\nExecution: {result['execution']['steps_executed']} steps completed")
    
        

    Agentic Architecture Pattern: Deliberative Agent

    Pattern 05: 05 Deliberative Agent – Line-by-Line Explanation

    Overview

    Pattern 05: Deliberative Agent Pattern An agent that plans and reasons before acting, using symbolic representations.


    Code Structure Analysis

    File Information

    • Pattern Number: 05
    • Pattern Name: 05 Deliberative Agent
    • File Path: patterns\core_agent\05_deliberative_agent.py
    • Total Lines: 208

    Detailed Code Explanation

    Module Docstring

    """
    Pattern 05: Deliberative Agent Pattern
    An agent that plans and reasons before acting, using symbolic representations.
    """
    

    Explanation: This module docstring describes the purpose and key features of the 05 Deliberative Agent pattern.


    Imports Section

    from typing import Dict, Any, List, Optional
    from dataclasses import dataclass, field
    from datetime import datetime
    from langchain_core.prompts import ChatPromptTemplate
    from langchain_openai import ChatOpenAI  # First 20 imports shown
    

    Explanation: The module imports necessary dependencies: – from typing import Dict, Any, List, Optional: Type hints for better code documentation – from dataclasses import dataclass, field: Data class decorators for clean data structures – from datetime import datetime: Date and time utilities – from langchain_core.prompts import ChatPromptTemplate: LangChain framework integration – from langchain_openai import ChatOpenAI: LangChain framework integration


    Classes

    BeliefState (Line 14)

    Description: Symbolic representation of agent’s beliefs.

    Plan (Line 22)

    Description: A deliberated plan of actions.

    DeliberativeAgentPattern (Line 31)

    Description: Deliberative Agent that: – Maintains symbolic world model – Plans before acting – Reasons about consequences – Uses explicit representation of knowledge

    Methods:

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

    Purpose: No method docstring.

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

    update_beliefs (Line 47)
    def update_beliefs(self, fact_key, fact_value):
        """Update the agent's belief state."""
    

    Purpose: Update the agent’s belief state.

    Parameters: – self: Instance reference – fact_key: Parameter for fact_key – fact_value: Parameter for fact_value

    add_rule (Line 53)
    def add_rule(self, rule):
        """Add a reasoning rule."""
    

    Purpose: Add a reasoning rule.

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

    deliberate (Line 58)
    def deliberate(self, goal):
        """Deliberate and create a plan to achieve a goal."""
    

    Purpose: Deliberate and create a plan to achieve a goal.

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

    reason_about_action (Line 96)
    def reason_about_action(self, action):
        """Reason about the consequences of an action."""
    

    Purpose: Reason about the consequences of an action.

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

    execute_plan (Line 118)
    def execute_plan(self, plan):
        """Execute a deliberated plan."""
    

    Purpose: Execute a deliberated plan.

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

    run (Line 140)
    def run(self, goal, initial_beliefs):
        """Main execution: deliberate and execute a plan for a goal.
    
    Args:
        goal: The goal to achieve
        initial_beliefs: Optional initial beliefs to set
    
    Returns:
        Dictionary with deliberation and execution results"""
    

    Purpose: Main execution: deliberate and execute a plan for a goal.

    Args: goal: The goal to achieve initial_beliefs: Optional initial beliefs to set

    Returns: Dictionary with deliberation and execution results

    Parameters: – self: Instance reference – goal: Parameter for goal – initial_beliefs: Parameter for initial_beliefs


    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 = BeliefState(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

  • Agentic Architecture Pattern: Reactive Agent

    
        """
    Pattern 04: Reactive Agent
    
    Purpose: Enhanced implementation with full LangChain/LangGraph integration
    """
    
    from typing import Dict, Any, List, Optional
    from dataclasses import dataclass, field
    from datetime import datetime
    from enum import Enum
    from langchain_core.prompts import ChatPromptTemplate
    from langchain_openai import ChatOpenAI
    from langgraph.graph import StateGraph, END
    from typing_extensions import TypedDict
    
    
    @dataclass
    class ReactiveAgentConfig:
        """Configuration for Reactive Agent."""
        model_name: str = "gpt-4"
        temperature: float = 0.7
        max_iterations: int = 10
        enable_logging: bool = True
    
    
    @dataclass
    class ReactiveAgentState:
        """State information for Reactive Agent."""
        current_step: int = 0
        data: Dict[str, Any] = field(default_factory=dict)
        results: List[Any] = field(default_factory=list)
        metadata: Dict[str, Any] = field(default_factory=dict)
        timestamp: datetime = field(default_factory=datetime.now)
    
    
    class ReactiveAgentAgent:
        """Agent implementing Reactive Agent."""
        
        def __init__(self, name: str, config: ReactiveAgentConfig = None):
            self.name = name
            self.config = config or ReactiveAgentConfig()
            self.llm = ChatOpenAI(
                model=self.config.model_name,
                temperature=self.config.temperature
            )
            self.state = ReactiveAgentState()
            self.execution_history: List[Dict[str, Any]] = []
        
        def process(self, input_data: Any) -> Dict[str, Any]:
            """Process input according to Reactive Agent."""
            self.state.current_step += 1
            
            prompt = ChatPromptTemplate.from_messages([
                ("system", f"You are {self.name}, implementing Reactive Agent. "
                          f"Provide clear, structured responses."),
                ("human", "Process this input: {input_data}")
            ])
            
            chain = prompt | self.llm
            response = chain.invoke({"input_data": str(input_data)})
            
            result = {
                "agent": self.name,
                "step": self.state.current_step,
                "input": input_data,
                "output": str(response.content),
                "timestamp": datetime.now()
            }
            
            self.execution_history.append(result)
            self.state.results.append(result)
            
            return result
        
        def get_statistics(self) -> Dict[str, Any]:
            """Get agent statistics."""
            return {
                "name": self.name,
                "total_executions": len(self.execution_history),
                "current_step": self.state.current_step,
                "results_count": len(self.state.results)
            }
    
    
    class ReactiveAgentPattern:
        """
        Reactive Agent - Enhanced implementation
        
        This pattern provides comprehensive functionality for reactive agent
        with full LangChain/LangGraph integration.
        
        Features:
        - Multi-agent coordination
        - State management
        - Execution tracking
        - LangGraph workflow integration
        """
        
        def __init__(self, config: ReactiveAgentConfig = None):
            self.config = config or ReactiveAgentConfig()
            self.agents: Dict[str, ReactiveAgentAgent] = {}
            self.workflow = self._build_workflow()
            self.execution_log: List[Dict[str, Any]] = []
        
        def _build_workflow(self) -> StateGraph:
            """Build LangGraph workflow for pattern execution."""
            
            class WorkflowState(TypedDict):
                input: str
                processed: str
                output: str
                metadata: Dict[str, Any]
            
            def process_input(state: WorkflowState) -> WorkflowState:
                """Process input node."""
                return {
                    **state,
                    "processed": f"Processed: {state['input']}",
                    "metadata": {"step": "process_input"}
                }
            
            def generate_output(state: WorkflowState) -> WorkflowState:
                """Generate output node."""
                llm = ChatOpenAI(model=self.config.model_name, temperature=self.config.temperature)
                
                prompt = ChatPromptTemplate.from_messages([
                    ("system", "You are implementing Reactive Agent. Generate comprehensive output."),
                    ("human", "{input}")
                ])
                
                chain = prompt | llm
                response = chain.invoke({"input": state["processed"]})
                
                return {
                    **state,
                    "output": str(response.content),
                    "metadata": {**state.get("metadata", {}), "step": "generate_output"}
                }
            
            # Build workflow graph
            workflow = StateGraph(WorkflowState)
            workflow.add_node("process", process_input)
            workflow.add_node("generate", generate_output)
            workflow.set_entry_point("process")
            workflow.add_edge("process", "generate")
            workflow.add_edge("generate", END)
            
            return workflow.compile()
        
        def register_agent(self, agent: ReactiveAgentAgent):
            """Register an agent with the pattern."""
            self.agents[agent.name] = agent
            if self.config.enable_logging:
                print(f"Registered agent: {agent.name}")
        
        def execute(self, input_data: Any, agent_name: str = None) -> Dict[str, Any]:
            """Execute the pattern with given input."""
            
            # Use workflow if no specific agent requested
            if agent_name is None:
                result = self.workflow.invoke({
                    "input": str(input_data),
                    "processed": "",
                    "output": "",
                    "metadata": {}
                })
                
                execution_record = {
                    "pattern": "Reactive Agent",
                    "input": input_data,
                    "output": result.get("output", ""),
                    "metadata": result.get("metadata", {}),
                    "timestamp": datetime.now()
                }
                
                self.execution_log.append(execution_record)
                return execution_record
            
            # Execute with specific agent
            agent = self.agents.get(agent_name)
            if not agent:
                raise ValueError(f"Agent {agent_name} not found")
            
            result = agent.process(input_data)
            self.execution_log.append(result)
            return result
        
        def run(self, input_data: Any) -> Dict[str, Any]:
            """Main execution method."""
            return self.execute(input_data)
        
        def get_statistics(self) -> Dict[str, Any]:
            """Get pattern statistics."""
            return {
                "pattern": "Reactive Agent",
                "total_executions": len(self.execution_log),
                "registered_agents": len(self.agents),
                "agents": [agent.get_statistics() for agent in self.agents.values()]
            }
    
    
    # Example usage
    if __name__ == "__main__":
        print("=== Reactive Agent Demo ===\n")
        
        # Create configuration
        config = ReactiveAgentConfig(
            model_name="gpt-4",
            temperature=0.7,
            enable_logging=True
        )
        
        # Create pattern
        pattern = ReactiveAgentPattern(config)
        
        # Create and register agents
        agent1 = ReactiveAgentAgent("Agent1", config)
        agent2 = ReactiveAgentAgent("Agent2", config)
        pattern.register_agent(agent1)
        pattern.register_agent(agent2)
        
        print("\nExecuting pattern workflow...")
        
        # Execute with workflow
        result1 = pattern.run("Demonstrate reactive agent functionality")
        print(f"\nWorkflow Result:")
        print(f"  Output: {result1['output'][:150]}...")
        
        # Execute with specific agents
        result2 = pattern.execute("Specific task for Agent1", agent_name="Agent1")
        print(f"\nAgent1 Result:")
        print(f"  Output: {result2['output'][:150]}...")
        
        result3 = pattern.execute("Specific task for Agent2", agent_name="Agent2")
        print(f"\nAgent2 Result:")
        print(f"  Output: {result3['output'][:150]}...")
        
        # Show statistics
        print("\n=== Statistics ===")
        stats = pattern.get_statistics()
        print(f"Pattern: {stats['pattern']}")
        print(f"Total Executions: {stats['total_executions']}")
        print(f"Registered Agents: {stats['registered_agents']}")
        print(f"\nAgent Statistics:")
        for agent_stats in stats['agents']:
            print(f"  {agent_stats['name']}: {agent_stats['total_executions']} executions")
    
        

    Agentic Architecture Pattern: Reactive Agent

    Pattern 04: 04 Reactive Agent – Line-by-Line Explanation

    Overview

    Pattern 04: Reactive Agent

    Purpose: Enhanced implementation with full LangChain/LangGraph integration


    Code Structure Analysis

    File Information

    • Pattern Number: 04
    • Pattern Name: 04 Reactive Agent
    • File Path: patterns\core_agent\04_reactive_agent.py
    • Total Lines: 247

    Detailed Code Explanation

    Module Docstring

    """
    Pattern 04: Reactive Agent
    
    Purpose: Enhanced implementation with full LangChain/LangGraph integration
    """
    

    Explanation: This module docstring describes the purpose and key features of the 04 Reactive Agent pattern.


    Imports Section

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

    Explanation: The module imports necessary dependencies: – from typing import Dict, Any, List, Optional: Type hints for better code documentation – from dataclasses import dataclass, field: Data class decorators for clean data structures – from datetime import datetime: 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 – from typing_extensions import TypedDict: Type hints for better code documentation


    Classes

    ReactiveAgentConfig (Line 18)

    Description: Configuration for Reactive Agent.

    ReactiveAgentState (Line 27)

    Description: State information for Reactive Agent.

    ReactiveAgentAgent (Line 36)

    Description: Agent implementing Reactive Agent.

    Methods:

    __init__ (Line 39)
    def __init__(self, name, config):
        """No method docstring."""
    

    Purpose: No method docstring.

    Parameters: – self: Instance reference – name: Identifier or label – config: Configuration settings

    process (Line 49)
    def process(self, input_data):
        """Process input according to Reactive Agent."""
    

    Purpose: Process input according to Reactive Agent.

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

    get_statistics (Line 75)
    def get_statistics(self):
        """Get agent statistics."""
    

    Purpose: Get agent statistics.

    Parameters: – self: Instance reference

    ReactiveAgentPattern (Line 85)

    Description: Reactive Agent – Enhanced implementation

    This pattern provides comprehensive functionality for reactive agent with full LangChain/LangGraph integration.

    Features: – Multi-agent coordination – State management – Execution tracking – LangGraph workflow integration

    Methods:

    __init__ (Line 99)
    def __init__(self, config):
        """No method docstring."""
    

    Purpose: No method docstring.

    Parameters: – self: Instance reference – config: Configuration settings

    _build_workflow (Line 105)
    def _build_workflow(self):
        """Build LangGraph workflow for pattern execution."""
    

    Purpose: Build LangGraph workflow for pattern execution.

    Parameters: – self: Instance reference

    register_agent (Line 150)
    def register_agent(self, agent):
        """Register an agent with the pattern."""
    

    Purpose: Register an agent with the pattern.

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

    execute (Line 156)
    def execute(self, input_data, agent_name):
        """Execute the pattern with given input."""
    

    Purpose: Execute the pattern with given input.

    Parameters: – self: Instance reference – input_data: Parameter for input_data – agent_name: Parameter for agent_name

    run (Line 188)
    def run(self, input_data):
        """Main execution method."""
    

    Purpose: Main execution method.

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

    get_statistics (Line 192)
    def get_statistics(self):
        """Get pattern statistics."""
    

    Purpose: Get pattern statistics.

    Parameters: – self: Instance reference

    WorkflowState (Line 108)

    Description: No class docstring.


    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 = ReactiveAgentConfig(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

  • Agentic Architecture Pattern: Autonomous Agent

    
        """
    Pattern 03: Autonomous Agent Pattern
    An agent that operates independently without external control, making its own decisions.
    """
    
    from typing import Dict, Any, List, Optional
    from dataclasses import dataclass, field
    from datetime import datetime
    from langchain_core.prompts import ChatPromptTemplate
    from langchain_openai import ChatOpenAI
    from langchain.agents import AgentExecutor, create_openai_tools_agent
    from langchain_core.tools import Tool
    
    
    @dataclass
    class AutonomousGoal:
        """A goal the agent pursues autonomously."""
        description: str
        priority: int  # 1-10, higher is more important
        status: str = "pending"  # pending, in_progress, completed, abandoned
        created_at: datetime = field(default_factory=datetime.now)
    
    
    class AutonomousAgentPattern:
        """
        Autonomous Agent that:
        - Sets and pursues its own goals
        - Makes independent decisions
        - Adapts to changing circumstances
        - Operates without external control
        """
        
        def __init__(self, name: str = "AutonomousAgent", model_name: str = "gpt-4"):
            self.name = name
            self.llm = ChatOpenAI(model=model_name, temperature=0.8)
            self.goals: List[AutonomousGoal] = []
            self.tools: List[Tool] = []
            self.knowledge_base: Dict[str, Any] = {}
            self.action_history: List[str] = []
            self.agent_executor = None
            
        def add_tool(self, tool: Tool):
            """Add a tool for autonomous use."""
            self.tools.append(tool)
            self._rebuild_agent()
        
        def _rebuild_agent(self):
            """Rebuild agent with current tools."""
            if not self.tools:
                return
                
            prompt = ChatPromptTemplate.from_messages([
                ("system", f"""You are {self.name}, an autonomous agent.
                You operate independently and make your own decisions.
                
                Your current goals (prioritized):
                {{goals}}
                
                Your knowledge:
                {{knowledge}}
                
                Make decisions autonomously to achieve your goals."""),
                ("human", "{input}"),
                ("placeholder", "{agent_scratchpad}"),
            ])
            
            agent = create_openai_tools_agent(self.llm, self.tools, prompt)
            self.agent_executor = AgentExecutor(agent=agent, tools=self.tools, verbose=True)
        
        def set_goal(self, description: str, priority: int = 5):
            """Set a new goal autonomously."""
            goal = AutonomousGoal(description=description, priority=priority)
            self.goals.append(goal)
            self.goals.sort(key=lambda g: g.priority, reverse=True)
            print(f"🎯 Goal set: {description} (priority: {priority})")
        
        def get_active_goals(self) -> List[AutonomousGoal]:
            """Get currently active goals."""
            return [g for g in self.goals if g.status in ["pending", "in_progress"]]
        
        def decide_next_action(self) -> str:
            """Autonomously decide the next action."""
            active_goals = self.get_active_goals()
            if not active_goals:
                return "No active goals"
            
            goals_str = "\n".join([f"- {g.description} (priority: {g.priority})" 
                                   for g in active_goals])
            
            prompt = ChatPromptTemplate.from_messages([
                ("system", f"""You are {self.name}. Decide the next best action.
                Goals: {goals_str}
                Knowledge: {self.knowledge_base}
                Recent actions: {self.action_history[-3:]}"""),
                ("human", "What should I do next to make progress on my highest priority goal?")
            ])
            
            chain = prompt | self.llm
            response = chain.invoke({})
            return str(response.content)
        
        def execute_autonomous_cycle(self) -> Dict[str, Any]:
            """Execute one autonomous decision-action cycle."""
            # Decide next action
            action = self.decide_next_action()
            
            # Execute if we have tools
            if self.agent_executor and self.get_active_goals():
                highest_goal = self.get_active_goals()[0]
                highest_goal.status = "in_progress"
                
                result = self.agent_executor.invoke({
                    "input": action,
                    "goals": str([g.description for g in self.get_active_goals()]),
                    "knowledge": str(self.knowledge_base)
                })
                
                self.action_history.append(action)
                return {"action": action, "result": result, "goal": highest_goal.description}
            else:
                return {"action": action, "result": "No tools available", "goal": "None"}
        
        def learn(self, key: str, value: Any):
            """Add knowledge to the agent's knowledge base."""
            self.knowledge_base[key] = value
            print(f"📚 Learned: {key} = {value}")
        
        def complete_goal(self, goal_description: str):
            """Mark a goal as completed."""
            for goal in self.goals:
                if goal.description == goal_description:
                    goal.status = "completed"
                    print(f"✅ Goal completed: {goal_description}")
                    break
        
        def run(self, initial_context: Optional[str] = None, cycles: int = 3) -> Dict[str, Any]:
            """
            Run the autonomous agent for specified cycles.
            
            Args:
                initial_context: Optional context to start with
                cycles: Number of autonomous cycles to execute
                
            Returns:
                Dictionary with execution results
            """
            if initial_context:
                self.learn("initial_context", initial_context)
            
            results = []
            for i in range(cycles):
                print(f"\n--- Cycle {i+1}/{cycles} ---")
                cycle_result = self.execute_autonomous_cycle()
                results.append(cycle_result)
            
            return {
                "agent": self.name,
                "cycles_executed": cycles,
                "results": results,
                "goals_status": [(g.description, g.status) for g in self.goals],
                "knowledge_acquired": len(self.knowledge_base)
            }
    
    
    # Example usage
    if __name__ == "__main__":
        print("\n=== Autonomous Agent Example ===")
        
        # Create autonomous agent
        agent = AutonomousAgentPattern(name="AutoBot")
        
        # Set autonomous goals
        agent.set_goal("Learn about the environment", priority=8)
        agent.set_goal("Optimize my performance", priority=6)
        agent.set_goal("Help users effectively", priority=9)
        
        # Provide tools
        def search_tool(query: str) -> str:
            """Simulate a search tool."""
            return f"Search results for '{query}': Found relevant information..."
        
        agent.add_tool(Tool(
            name="Search",
            func=search_tool,
            description="Search for information"
        ))
        
        # Give initial knowledge
        agent.learn("environment", "collaborative workspace")
        agent.learn("users", ["Alice", "Bob", "Carol"])
        
        # Run autonomous cycles
        result = agent.run(initial_context="I'm in a team workspace", cycles=2)
        
        print("\n=== Autonomous Agent Results ===")
        print(f"Agent: {result['agent']}")
        print(f"Cycles: {result['cycles_executed']}")
        print(f"\nGoals Status:")
        for goal_desc, status in result['goals_status']:
            print(f"  - {goal_desc}: {status}")
        print(f"\nKnowledge Items: {result['knowledge_acquired']}")
    
        

    Agentic Architecture Pattern: Autonomous Agent

    Pattern 03: 03 Autonomous Agent – Line-by-Line Explanation

    Overview

    Pattern 03: Autonomous Agent Pattern An agent that operates independently without external control, making its own decisions.


    Code Structure Analysis

    File Information

    • Pattern Number: 03
    • Pattern Name: 03 Autonomous Agent
    • File Path: patterns\core_agent\03_autonomous_agent.py
    • Total Lines: 202

    Detailed Code Explanation

    Module Docstring

    """
    Pattern 03: Autonomous Agent Pattern
    An agent that operates independently without external control, making its own decisions.
    """
    

    Explanation: This module docstring describes the purpose and key features of the 03 Autonomous Agent pattern.


    Imports Section

    from typing import Dict, Any, List, Optional
    from dataclasses import dataclass, field
    from datetime import datetime
    from langchain_core.prompts import ChatPromptTemplate
    from langchain_openai import ChatOpenAI
    from langchain.agents import AgentExecutor, create_openai_tools_agent
    from langchain_core.tools import Tool  # First 20 imports shown
    

    Explanation: The module imports necessary dependencies: – from typing import Dict, Any, List, Optional: Type hints for better code documentation – from dataclasses import dataclass, field: Data class decorators for clean data structures – from datetime import datetime: Date and time utilities – from langchain_core.prompts import ChatPromptTemplate: LangChain framework integration – from langchain_openai import ChatOpenAI: LangChain framework integration – from langchain.agents import AgentExecutor, create_openai_tools_agent: LangChain framework integration – from langchain_core.tools import Tool: LangChain framework integration


    Classes

    AutonomousGoal (Line 16)

    Description: A goal the agent pursues autonomously.

    AutonomousAgentPattern (Line 24)

    Description: Autonomous Agent that: – Sets and pursues its own goals – Makes independent decisions – Adapts to changing circumstances – Operates without external control

    Methods:

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

    Purpose: No method docstring.

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

    add_tool (Line 42)
    def add_tool(self, tool):
        """Add a tool for autonomous use."""
    

    Purpose: Add a tool for autonomous use.

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

    _rebuild_agent (Line 47)
    def _rebuild_agent(self):
        """Rebuild agent with current tools."""
    

    Purpose: Rebuild agent with current tools.

    Parameters: – self: Instance reference

    set_goal (Line 70)
    def set_goal(self, description, priority):
        """Set a new goal autonomously."""
    

    Purpose: Set a new goal autonomously.

    Parameters: – self: Instance reference – description: Parameter for description – priority: Parameter for priority

    get_active_goals (Line 77)
    def get_active_goals(self):
        """Get currently active goals."""
    

    Purpose: Get currently active goals.

    Parameters: – self: Instance reference

    decide_next_action (Line 81)
    def decide_next_action(self):
        """Autonomously decide the next action."""
    

    Purpose: Autonomously decide the next action.

    Parameters: – self: Instance reference

    execute_autonomous_cycle (Line 102)
    def execute_autonomous_cycle(self):
        """Execute one autonomous decision-action cycle."""
    

    Purpose: Execute one autonomous decision-action cycle.

    Parameters: – self: Instance reference

    learn (Line 123)
    def learn(self, key, value):
        """Add knowledge to the agent's knowledge base."""
    

    Purpose: Add knowledge to the agent’s knowledge base.

    Parameters: – self: Instance reference – key: Parameter for key – value: Parameter for value

    complete_goal (Line 128)
    def complete_goal(self, goal_description):
        """Mark a goal as completed."""
    

    Purpose: Mark a goal as completed.

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

    run (Line 136)
    def run(self, initial_context, cycles):
        """Run the autonomous agent for specified cycles.
    
    Args:
        initial_context: Optional context to start with
        cycles: Number of autonomous cycles to execute
    
    Returns:
        Dictionary with execution results"""
    

    Purpose: Run the autonomous agent for specified cycles.

    Args: initial_context: Optional context to start with cycles: Number of autonomous cycles to execute

    Returns: Dictionary with execution results

    Parameters: – self: Instance reference – initial_context: Parameter for initial_context – cycles: Parameter for cycles


    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 = AutonomousGoal(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

  • Agentic Architecture Pattern: Multi Agent System

    
        """
    Pattern 02: Multi-Agent System (MAS)
    Multiple agents working together, coordinating and collaborating to achieve goals.
    """
    
    from typing import Dict, Any, List, Optional
    from dataclasses import dataclass, field
    from datetime import datetime
    from langchain_core.prompts import ChatPromptTemplate
    from langchain_openai import ChatOpenAI
    from langgraph.graph import StateGraph, END
    from typing_extensions import TypedDict
    
    
    @dataclass
    class Message:
        """Message exchanged between agents."""
        sender: str
        receiver: str
        content: str
        timestamp: datetime = field(default_factory=datetime.now)
    
    
    class AgentState(TypedDict):
        """State shared among agents."""
        messages: List[Message]
        current_agent: str
        task: str
        results: Dict[str, Any]
        iteration: int
    
    
    class Agent:
        """Individual agent in the multi-agent system."""
        
        def __init__(self, name: str, role: str, model_name: str = "gpt-4"):
            self.name = name
            self.role = role
            self.llm = ChatOpenAI(model=model_name, temperature=0.7)
            self.memory: List[Message] = []
        
        def process(self, task: str, context: Dict[str, Any]) -> str:
            """Process a task with given context."""
            prompt = ChatPromptTemplate.from_messages([
                ("system", f"""You are {self.name}, a {self.role} agent.
                Your role is to {self.role}.
                Previous context: {context}"""),
                ("human", "{task}")
            ])
            
            chain = prompt | self.llm
            response = chain.invoke({"task": task})
            return str(response.content)
        
        def send_message(self, receiver: str, content: str) -> Message:
            """Send a message to another agent."""
            msg = Message(sender=self.name, receiver=receiver, content=content)
            self.memory.append(msg)
            return msg
        
        def receive_message(self, message: Message):
            """Receive a message from another agent."""
            self.memory.append(message)
    
    
    class MultiAgentSystemPattern:
        """
        Multi-Agent System implementation using LangGraph.
        
        Features:
        - Multiple specialized agents
        - Agent communication and coordination
        - Shared state management
        - Sequential and parallel execution
        """
        
        def __init__(self):
            self.agents: Dict[str, Agent] = {}
            self.workflow = None
            self.message_history: List[Message] = []
        
        def add_agent(self, agent: Agent):
            """Add an agent to the system."""
            self.agents[agent.name] = agent
        
        def _agent_node(self, state: AgentState, agent_name: str) -> AgentState:
            """Node function for an agent in the workflow."""
            agent = self.agents[agent_name]
            
            # Get relevant messages for this agent
            relevant_msgs = [m for m in state["messages"] if m.receiver == agent_name or m.receiver == "all"]
            context = {
                "messages": [f"{m.sender}: {m.content}" for m in relevant_msgs],
                "results": state["results"]
            }
            
            # Process task
            result = agent.process(state["task"], context)
            
            # Update state
            state["results"][agent_name] = result
            state["current_agent"] = agent_name
            state["iteration"] += 1
            
            return state
        
        def build_workflow(self, agent_sequence: List[str]):
            """Build a sequential workflow through agents."""
            workflow = StateGraph(AgentState)
            
            # Add nodes for each agent
            for agent_name in agent_sequence:
                workflow.add_node(
                    agent_name,
                    lambda state, name=agent_name: self._agent_node(state, name)
                )
            
            # Add edges to connect agents sequentially
            for i in range(len(agent_sequence) - 1):
                workflow.add_edge(agent_sequence[i], agent_sequence[i + 1])
            
            # Set entry and exit points
            workflow.set_entry_point(agent_sequence[0])
            workflow.add_edge(agent_sequence[-1], END)
            
            self.workflow = workflow.compile()
        
        def broadcast(self, sender: str, content: str):
            """Broadcast a message to all agents."""
            msg = Message(sender=sender, receiver="all", content=content)
            self.message_history.append(msg)
            for agent in self.agents.values():
                if agent.name != sender:
                    agent.receive_message(msg)
        
        def run(self, task: str, agent_sequence: Optional[List[str]] = None) -> Dict[str, Any]:
            """
            Execute the multi-agent system on a task.
            
            Args:
                task: The task for agents to work on
                agent_sequence: Optional sequence of agents to execute
                
            Returns:
                Dictionary with results from all agents
            """
            if agent_sequence is None:
                agent_sequence = list(self.agents.keys())
            
            if not self.workflow:
                self.build_workflow(agent_sequence)
            
            # Initialize state
            initial_state: AgentState = {
                "messages": [],
                "current_agent": "",
                "task": task,
                "results": {},
                "iteration": 0
            }
            
            # Execute workflow
            final_state = self.workflow.invoke(initial_state)
            
            return {
                "task": task,
                "agents": agent_sequence,
                "results": final_state["results"],
                "iterations": final_state["iteration"]
            }
    
    
    # Example usage
    if __name__ == "__main__":
        print("\n=== Multi-Agent System Example ===")
        
        # Create multi-agent system
        mas = MultiAgentSystemPattern()
        
        # Create specialized agents
        researcher = Agent("Researcher", "research and gather information")
        analyzer = Agent("Analyzer", "analyze data and identify patterns")
        writer = Agent("Writer", "write clear and comprehensive reports")
        
        # Add agents to system
        mas.add_agent(researcher)
        mas.add_agent(analyzer)
        mas.add_agent(writer)
        
        # Run a collaborative task
        task = "Create a report about the benefits of exercise"
        result = mas.run(task, ["Researcher", "Analyzer", "Writer"])
        
        print(f"\nTask: {result['task']}")
        print(f"\nAgent Sequence: {' -> '.join(result['agents'])}")
        print(f"\nResults from each agent:")
        for agent_name, output in result['results'].items():
            print(f"\n{agent_name}:")
            print(f"  {output[:200]}..." if len(output) > 200 else f"  {output}")
        
        print(f"\nTotal iterations: {result['iterations']}")
    
        

    Agentic Architecture Pattern: Multi Agent System

    Pattern 02: 02 Multi Agent System – Line-by-Line Explanation

    Overview

    Pattern 02: Multi-Agent System (MAS) Multiple agents working together, coordinating and collaborating to achieve goals.


    Code Structure Analysis

    File Information

    • Pattern Number: 02
    • Pattern Name: 02 Multi Agent System
    • File Path: patterns\core_agent\02_multi_agent_system.py
    • Total Lines: 202

    Detailed Code Explanation

    Module Docstring

    """
    Pattern 02: Multi-Agent System (MAS)
    Multiple agents working together, coordinating and collaborating to achieve goals.
    """
    

    Explanation: This module docstring describes the purpose and key features of the 02 Multi Agent System pattern.


    Imports Section

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

    Explanation: The module imports necessary dependencies: – from typing import Dict, Any, List, Optional: Type hints for better code documentation – from dataclasses import dataclass, field: Data class decorators for clean data structures – from datetime import datetime: Date and time utilities – 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 – from typing_extensions import TypedDict: Type hints for better code documentation


    Classes

    Message (Line 16)

    Description: Message exchanged between agents.

    AgentState (Line 24)

    Description: State shared among agents.

    Agent (Line 33)

    Description: Individual agent in the multi-agent system.

    Methods:

    __init__ (Line 36)
    def __init__(self, name, role, model_name):
        """No method docstring."""
    

    Purpose: No method docstring.

    Parameters: – self: Instance reference – name: Identifier or label – role: Parameter for role – model_name: LLM model to use (e.g., “gpt-4”)

    process (Line 42)
    def process(self, task, context):
        """Process a task with given context."""
    

    Purpose: Process a task with given context.

    Parameters: – self: Instance reference – task: Parameter for task – context: Parameter for context

    send_message (Line 55)
    def send_message(self, receiver, content):
        """Send a message to another agent."""
    

    Purpose: Send a message to another agent.

    Parameters: – self: Instance reference – receiver: Parameter for receiver – content: Parameter for content

    receive_message (Line 61)
    def receive_message(self, message):
        """Receive a message from another agent."""
    

    Purpose: Receive a message from another agent.

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

    MultiAgentSystemPattern (Line 66)

    Description: Multi-Agent System implementation using LangGraph.

    Features: – Multiple specialized agents – Agent communication and coordination – Shared state management – Sequential and parallel execution

    Methods:

    __init__ (Line 77)
    def __init__(self):
        """No method docstring."""
    

    Purpose: No method docstring.

    Parameters: – self: Instance reference

    add_agent (Line 82)
    def add_agent(self, agent):
        """Add an agent to the system."""
    

    Purpose: Add an agent to the system.

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

    _agent_node (Line 86)
    def _agent_node(self, state, agent_name):
        """Node function for an agent in the workflow."""
    

    Purpose: Node function for an agent in the workflow.

    Parameters: – self: Instance reference – state: Current workflow state – agent_name: Parameter for agent_name

    build_workflow (Line 107)
    def build_workflow(self, agent_sequence):
        """Build a sequential workflow through agents."""
    

    Purpose: Build a sequential workflow through agents.

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

    broadcast (Line 128)
    def broadcast(self, sender, content):
        """Broadcast a message to all agents."""
    

    Purpose: Broadcast a message to all agents.

    Parameters: – self: Instance reference – sender: Parameter for sender – content: Parameter for content

    run (Line 136)
    def run(self, task, agent_sequence):
        """Execute the multi-agent system on a task.
    
    Args:
        task: The task for agents to work on
        agent_sequence: Optional sequence of agents to execute
    
    Returns:
        Dictionary with results from all agents"""
    

    Purpose: Execute the multi-agent system on a task.

    Args: task: The task for agents to work on agent_sequence: Optional sequence of agents to execute

    Returns: Dictionary with results from all agents

    Parameters: – self: Instance reference – task: Parameter for task – agent_sequence: Parameter for agent_sequence


    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 = Message(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

  • Agentic Architecture Pattern: Single Agent

    
        """
    Pattern 01: Single Agent
    
    Purpose: Enhanced implementation with full LangChain/LangGraph integration
    """
    
    from typing import Dict, Any, List, Optional
    from dataclasses import dataclass, field
    from datetime import datetime
    from enum import Enum
    from langchain_core.prompts import ChatPromptTemplate
    from langchain_openai import ChatOpenAI
    from langgraph.graph import StateGraph, END
    from typing_extensions import TypedDict
    
    
    @dataclass
    class SingleAgentConfig:
        """Configuration for Single Agent."""
        model_name: str = "gpt-4"
        temperature: float = 0.7
        max_iterations: int = 10
        enable_logging: bool = True
    
    
    @dataclass
    class SingleAgentState:
        """State information for Single Agent."""
        current_step: int = 0
        data: Dict[str, Any] = field(default_factory=dict)
        results: List[Any] = field(default_factory=list)
        metadata: Dict[str, Any] = field(default_factory=dict)
        timestamp: datetime = field(default_factory=datetime.now)
    
    
    class SingleAgentAgent:
        """Agent implementing Single Agent."""
        
        def __init__(self, name: str, config: SingleAgentConfig = None):
            self.name = name
            self.config = config or SingleAgentConfig()
            self.llm = ChatOpenAI(
                model=self.config.model_name,
                temperature=self.config.temperature
            )
            self.state = SingleAgentState()
            self.execution_history: List[Dict[str, Any]] = []
        
        def process(self, input_data: Any) -> Dict[str, Any]:
            """Process input according to Single Agent."""
            self.state.current_step += 1
            
            prompt = ChatPromptTemplate.from_messages([
                ("system", f"You are {self.name}, implementing Single Agent. "
                          f"Provide clear, structured responses."),
                ("human", "Process this input: {input_data}")
            ])
            
            chain = prompt | self.llm
            response = chain.invoke({"input_data": str(input_data)})
            
            result = {
                "agent": self.name,
                "step": self.state.current_step,
                "input": input_data,
                "output": str(response.content),
                "timestamp": datetime.now()
            }
            
            self.execution_history.append(result)
            self.state.results.append(result)
            
            return result
        
        def get_statistics(self) -> Dict[str, Any]:
            """Get agent statistics."""
            return {
                "name": self.name,
                "total_executions": len(self.execution_history),
                "current_step": self.state.current_step,
                "results_count": len(self.state.results)
            }
    
    
    class SingleAgentPattern:
        """
        Single Agent - Enhanced implementation
        
        This pattern provides comprehensive functionality for single agent
        with full LangChain/LangGraph integration.
        
        Features:
        - Multi-agent coordination
        - State management
        - Execution tracking
        - LangGraph workflow integration
        """
        
        def __init__(self, config: SingleAgentConfig = None):
            self.config = config or SingleAgentConfig()
            self.agents: Dict[str, SingleAgentAgent] = {}
            self.workflow = self._build_workflow()
            self.execution_log: List[Dict[str, Any]] = []
        
        def _build_workflow(self) -> StateGraph:
            """Build LangGraph workflow for pattern execution."""
            
            class WorkflowState(TypedDict):
                input: str
                processed: str
                output: str
                metadata: Dict[str, Any]
            
            def process_input(state: WorkflowState) -> WorkflowState:
                """Process input node."""
                return {
                    **state,
                    "processed": f"Processed: {state['input']}",
                    "metadata": {"step": "process_input"}
                }
            
            def generate_output(state: WorkflowState) -> WorkflowState:
                """Generate output node."""
                llm = ChatOpenAI(model=self.config.model_name, temperature=self.config.temperature)
                
                prompt = ChatPromptTemplate.from_messages([
                    ("system", "You are implementing Single Agent. Generate comprehensive output."),
                    ("human", "{input}")
                ])
                
                chain = prompt | llm
                response = chain.invoke({"input": state["processed"]})
                
                return {
                    **state,
                    "output": str(response.content),
                    "metadata": {**state.get("metadata", {}), "step": "generate_output"}
                }
            
            # Build workflow graph
            workflow = StateGraph(WorkflowState)
            workflow.add_node("process", process_input)
            workflow.add_node("generate", generate_output)
            workflow.set_entry_point("process")
            workflow.add_edge("process", "generate")
            workflow.add_edge("generate", END)
            
            return workflow.compile()
        
        def register_agent(self, agent: SingleAgentAgent):
            """Register an agent with the pattern."""
            self.agents[agent.name] = agent
            if self.config.enable_logging:
                print(f"Registered agent: {agent.name}")
        
        def execute(self, input_data: Any, agent_name: str = None) -> Dict[str, Any]:
            """Execute the pattern with given input."""
            
            # Use workflow if no specific agent requested
            if agent_name is None:
                result = self.workflow.invoke({
                    "input": str(input_data),
                    "processed": "",
                    "output": "",
                    "metadata": {}
                })
                
                execution_record = {
                    "pattern": "Single Agent",
                    "input": input_data,
                    "output": result.get("output", ""),
                    "metadata": result.get("metadata", {}),
                    "timestamp": datetime.now()
                }
                
                self.execution_log.append(execution_record)
                return execution_record
            
            # Execute with specific agent
            agent = self.agents.get(agent_name)
            if not agent:
                raise ValueError(f"Agent {agent_name} not found")
            
            result = agent.process(input_data)
            self.execution_log.append(result)
            return result
        
        def run(self, input_data: Any) -> Dict[str, Any]:
            """Main execution method."""
            return self.execute(input_data)
        
        def get_statistics(self) -> Dict[str, Any]:
            """Get pattern statistics."""
            return {
                "pattern": "Single Agent",
                "total_executions": len(self.execution_log),
                "registered_agents": len(self.agents),
                "agents": [agent.get_statistics() for agent in self.agents.values()]
            }
    
    
    # Example usage
    if __name__ == "__main__":
        print("=== Single Agent Demo ===\n")
        
        # Create configuration
        config = SingleAgentConfig(
            model_name="gpt-4",
            temperature=0.7,
            enable_logging=True
        )
        
        # Create pattern
        pattern = SingleAgentPattern(config)
        
        # Create and register agents
        agent1 = SingleAgentAgent("Agent1", config)
        agent2 = SingleAgentAgent("Agent2", config)
        pattern.register_agent(agent1)
        pattern.register_agent(agent2)
        
        print("\nExecuting pattern workflow...")
        
        # Execute with workflow
        result1 = pattern.run("Demonstrate single agent functionality")
        print(f"\nWorkflow Result:")
        print(f"  Output: {result1['output'][:150]}...")
        
        # Execute with specific agents
        result2 = pattern.execute("Specific task for Agent1", agent_name="Agent1")
        print(f"\nAgent1 Result:")
        print(f"  Output: {result2['output'][:150]}...")
        
        result3 = pattern.execute("Specific task for Agent2", agent_name="Agent2")
        print(f"\nAgent2 Result:")
        print(f"  Output: {result3['output'][:150]}...")
        
        # Show statistics
        print("\n=== Statistics ===")
        stats = pattern.get_statistics()
        print(f"Pattern: {stats['pattern']}")
        print(f"Total Executions: {stats['total_executions']}")
        print(f"Registered Agents: {stats['registered_agents']}")
        print(f"\nAgent Statistics:")
        for agent_stats in stats['agents']:
            print(f"  {agent_stats['name']}: {agent_stats['total_executions']} executions")
    
        

    Agentic Architecture Pattern: Single Agent

    Pattern 01: 01 Single Agent – Line-by-Line Explanation

    Overview

    Pattern 01: Single Agent

    Purpose: Enhanced implementation with full LangChain/LangGraph integration


    Code Structure Analysis

    File Information

    • Pattern Number: 01
    • Pattern Name: 01 Single Agent
    • File Path: patterns\core_agent\01_single_agent.py
    • Total Lines: 247

    Detailed Code Explanation

    Module Docstring

    """
    Pattern 01: Single Agent
    
    Purpose: Enhanced implementation with full LangChain/LangGraph integration
    """
    

    Explanation: This module docstring describes the purpose and key features of the 01 Single Agent pattern.


    Imports Section

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

    Explanation: The module imports necessary dependencies: – from typing import Dict, Any, List, Optional: Type hints for better code documentation – from dataclasses import dataclass, field: Data class decorators for clean data structures – from datetime import datetime: 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 – from typing_extensions import TypedDict: Type hints for better code documentation


    Classes

    SingleAgentConfig (Line 18)

    Description: Configuration for Single Agent.

    SingleAgentState (Line 27)

    Description: State information for Single Agent.

    SingleAgentAgent (Line 36)

    Description: Agent implementing Single Agent.

    Methods:

    __init__ (Line 39)
    def __init__(self, name, config):
        """No method docstring."""
    

    Purpose: No method docstring.

    Parameters: – self: Instance reference – name: Identifier or label – config: Configuration settings

    process (Line 49)
    def process(self, input_data):
        """Process input according to Single Agent."""
    

    Purpose: Process input according to Single Agent.

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

    get_statistics (Line 75)
    def get_statistics(self):
        """Get agent statistics."""
    

    Purpose: Get agent statistics.

    Parameters: – self: Instance reference

    SingleAgentPattern (Line 85)

    Description: Single Agent – Enhanced implementation

    This pattern provides comprehensive functionality for single agent with full LangChain/LangGraph integration.

    Features: – Multi-agent coordination – State management – Execution tracking – LangGraph workflow integration

    Methods:

    __init__ (Line 99)
    def __init__(self, config):
        """No method docstring."""
    

    Purpose: No method docstring.

    Parameters: – self: Instance reference – config: Configuration settings

    _build_workflow (Line 105)
    def _build_workflow(self):
        """Build LangGraph workflow for pattern execution."""
    

    Purpose: Build LangGraph workflow for pattern execution.

    Parameters: – self: Instance reference

    register_agent (Line 150)
    def register_agent(self, agent):
        """Register an agent with the pattern."""
    

    Purpose: Register an agent with the pattern.

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

    execute (Line 156)
    def execute(self, input_data, agent_name):
        """Execute the pattern with given input."""
    

    Purpose: Execute the pattern with given input.

    Parameters: – self: Instance reference – input_data: Parameter for input_data – agent_name: Parameter for agent_name

    run (Line 188)
    def run(self, input_data):
        """Main execution method."""
    

    Purpose: Main execution method.

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

    get_statistics (Line 192)
    def get_statistics(self):
        """Get pattern statistics."""
    

    Purpose: Get pattern statistics.

    Parameters: – self: Instance reference

    WorkflowState (Line 108)

    Description: No class docstring.


    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 = SingleAgentConfig(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