Tag: technology

  • Agentic Architecture Pattern: Mediator

    
        """
    Pattern 13: Mediator Pattern
    
    Centralizes complex communications and control between related agents.
    Mediator promotes loose coupling by keeping agents from referring to each other explicitly.
    """
    
    from typing import Dict, Any, List, Optional, Callable
    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 AgentMessage:
        """Message exchanged between agents."""
        sender: str
        recipient: Optional[str]  # None = broadcast
        content: str
        timestamp: datetime = field(default_factory=datetime.now)
        metadata: Dict[str, Any] = field(default_factory=dict)
    
    
    class MediatedAgent:
        """Agent that communicates through a mediator."""
        
        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.mediator: Optional['MediatorPattern'] = None
        
        def set_mediator(self, mediator: 'MediatorPattern'):
            """Register with mediator."""
            self.mediator = mediator
        
        def send(self, content: str, recipient: Optional[str] = None):
            """Send message via mediator."""
            if not self.mediator:
                raise ValueError(f"{self.name}: Mediator not set")
            
            message = AgentMessage(
                sender=self.name,
                recipient=recipient,
                content=content
            )
            self.mediator.relay_message(message)
        
        def receive(self, message: AgentMessage) -> str:
            """Process received message."""
            prompt = ChatPromptTemplate.from_messages([
                ("system", f"You are {self.name}, a {self.role}. "
                          f"Process this message and respond appropriately."),
                ("human", f"From {message.sender}: {message.content}")
            ])
            
            chain = prompt | self.llm
            response = chain.invoke({})
            return str(response.content)
    
    
    class MediatorState(TypedDict):
        """State for mediator graph."""
        messages: List[AgentMessage]
        active_agents: List[str]
        current_message: Optional[AgentMessage]
    
    
    class MediatorPattern:
        """
        Mediator Pattern - Centralized agent communication coordinator.
        
        Uses LangGraph to manage message routing and agent interactions.
        All agent-to-agent communication flows through the mediator.
        """
        
        def __init__(self):
            self.agents: Dict[str, MediatedAgent] = {}
            self.message_log: List[AgentMessage] = []
            self.graph = self._build_graph()
        
        def register_agent(self, agent: MediatedAgent):
            """Register agent with mediator."""
            self.agents[agent.name] = agent
            agent.set_mediator(self)
        
        def relay_message(self, message: AgentMessage):
            """Relay message to appropriate recipient(s)."""
            self.message_log.append(message)
            
            # Determine recipients
            if message.recipient:
                # Direct message
                if message.recipient in self.agents:
                    response = self.agents[message.recipient].receive(message)
                    # Log response
                    if response:
                        response_msg = AgentMessage(
                            sender=message.recipient,
                            recipient=message.sender,
                            content=response
                        )
                        self.message_log.append(response_msg)
            else:
                # Broadcast to all except sender
                for name, agent in self.agents.items():
                    if name != message.sender:
                        response = agent.receive(message)
                        if response:
                            response_msg = AgentMessage(
                                sender=name,
                                recipient=message.sender,
                                content=response
                            )
                            self.message_log.append(response_msg)
        
        def _build_graph(self) -> StateGraph:
            """Build LangGraph for mediator workflow."""
            workflow = StateGraph(MediatorState)
            
            def route_message(state: MediatorState) -> MediatorState:
                """Route messages through mediator."""
                if state["current_message"]:
                    self.relay_message(state["current_message"])
                return state
            
            workflow.add_node("route", route_message)
            workflow.set_entry_point("route")
            workflow.add_edge("route", END)
            
            return workflow.compile()
        
        def get_conversation(self, agent1: str, agent2: str) -> List[AgentMessage]:
            """Get conversation between two agents."""
            return [
                msg for msg in self.message_log
                if (msg.sender == agent1 and msg.recipient == agent2) or
                   (msg.sender == agent2 and msg.recipient == agent1)
            ]
        
        def run(self, scenario: str) -> Dict[str, Any]:
            """Execute mediator pattern."""
            return {
                "pattern": "Mediator",
                "total_agents": len(self.agents),
                "total_messages": len(self.message_log),
                "agents": list(self.agents.keys()),
                "scenario": scenario
            }
    
    
    # Example usage
    if __name__ == "__main__":
        print("=== Mediator Pattern Demo ===\n")
        
        # Create mediator
        mediator = MediatorPattern()
        
        # Create agents
        project_manager = MediatedAgent("PM", "project manager")
        developer = MediatedAgent("Dev", "developer")
        designer = MediatedAgent("Designer", "UI designer")
        tester = MediatedAgent("QA", "quality assurance")
        
        # Register agents
        for agent in [project_manager, developer, designer, tester]:
            mediator.register_agent(agent)
        
        print("1. PM broadcasts project kickoff...")
        project_manager.send("Starting new e-commerce project. Sprint 1 begins Monday.")
        
        print("\n2. Dev sends direct message to Designer...")
        developer.send("Need mockups for product listing page", recipient="Designer")
        
        print("\n3. QA reports bug to Dev...")
        tester.send("Found critical bug in checkout flow", recipient="Dev")
        
        # Get results
        result = mediator.run("Team collaboration")
        print(f"\n4. Summary:")
        print(f"   Agents: {result['agents']}")
        print(f"   Messages: {result['total_messages']}")
        print(f"   Pattern: {result['pattern']}")
        
        print("\nāœ“ Mediator pattern coordinated all agent communication!")
    
        

    Agentic Architecture Pattern: Mediator

    Pattern 13: 13 Mediator – Line-by-Line Explanation

    Overview

    Pattern 13: Mediator Pattern

    Centralizes complex communications and control between related agents. Mediator promotes loose coupling by keeping agents from referring to each other explicitly.


    Code Structure Analysis

    File Information

    • Pattern Number: 13
    • Pattern Name: 13 Mediator
    • File Path: patterns\communication\13_mediator.py
    • Total Lines: 189

    Detailed Code Explanation

    Module Docstring

    """
    Pattern 13: Mediator Pattern
    
    Centralizes complex communications and control between related agents.
    Mediator promotes loose coupling by keeping agents from referring to each other explicitly.
    """
    

    Explanation: This module docstring describes the purpose and key features of the 13 Mediator pattern.


    Imports Section

    from typing import Dict, Any, List, Optional, Callable
    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, Callable: 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

    AgentMessage (Line 18)

    Description: Message exchanged between agents.

    MediatedAgent (Line 27)

    Description: Agent that communicates through a mediator.

    Methods:

    __init__ (Line 30)
    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”)

    set_mediator (Line 36)
    def set_mediator(self, mediator):
        """Register with mediator."""
    

    Purpose: Register with mediator.

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

    send (Line 40)
    def send(self, content, recipient):
        """Send message via mediator."""
    

    Purpose: Send message via mediator.

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

    receive (Line 52)
    def receive(self, message):
        """Process received message."""
    

    Purpose: Process received message.

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

    MediatorState (Line 65)

    Description: State for mediator graph.

    MediatorPattern (Line 72)

    Description: Mediator Pattern – Centralized agent communication coordinator.

    Uses LangGraph to manage message routing and agent interactions. All agent-to-agent communication flows through the mediator.

    Methods:

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

    Purpose: No method docstring.

    Parameters: – self: Instance reference

    register_agent (Line 85)
    def register_agent(self, agent):
        """Register agent with mediator."""
    

    Purpose: Register agent with mediator.

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

    relay_message (Line 90)
    def relay_message(self, message):
        """Relay message to appropriate recipient(s)."""
    

    Purpose: Relay message to appropriate recipient(s).

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

    _build_graph (Line 120)
    def _build_graph(self):
        """Build LangGraph for mediator workflow."""
    

    Purpose: Build LangGraph for mediator workflow.

    Parameters: – self: Instance reference

    get_conversation (Line 136)
    def get_conversation(self, agent1, agent2):
        """Get conversation between two agents."""
    

    Purpose: Get conversation between two agents.

    Parameters: – self: Instance reference – agent1: Parameter for agent1 – agent2: Parameter for agent2

    run (Line 144)
    def run(self, scenario):
        """Execute mediator pattern."""
    

    Purpose: Execute mediator pattern.

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


    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 = AgentMessage(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: Contract Net

    
        """
    Pattern 12: Contract Net Protocol
    A negotiation protocol where agents bid for tasks.
    """
    
    from typing import Dict, Any, List, Optional
    from langchain_core.prompts import ChatPromptTemplate
    from langchain_openai import ChatOpenAI
    from pydantic import BaseModel, Field
    from enum import Enum
    
    
    class BidStatus(str, Enum):
        PENDING = "pending"
        ACCEPTED = "accepted"
        REJECTED = "rejected"
    
    
    class Bid(BaseModel):
        """Represents a bid from an agent."""
        agent_id: str
        task_id: str
        cost: float
        time_estimate: float
        quality_score: float
        proposal: str
        status: BidStatus = BidStatus.PENDING
    
    
    class Task(BaseModel):
        """Represents a task to be contracted."""
        id: str
        description: str
        requirements: List[str]
        deadline: Optional[float] = None
        budget: Optional[float] = None
    
    
    class ContractNetPattern:
        """
        Contract Net Protocol - Task allocation through bidding.
        Manager announces tasks, contractors bid, manager awards contracts.
        """
        
        def __init__(self, model_name: str = "gpt-4"):
            self.llm = ChatOpenAI(model=model_name, temperature=0.7)
            self.tasks: Dict[str, Task] = {}
            self.bids: Dict[str, List[Bid]] = {}
            self.contractors: Dict[str, 'ContractorAgent'] = {}
        
        def announce_task(self, task: Task) -> str:
            """Manager announces a task."""
            self.tasks[task.id] = task
            self.bids[task.id] = []
            return task.id
        
        def register_contractor(self, agent_id: str, capabilities: List[str]) -> 'ContractorAgent':
            """Register a contractor agent."""
            contractor = ContractorAgent(agent_id, capabilities, self, self.llm)
            self.contractors[agent_id] = contractor
            return contractor
        
        def receive_bid(self, bid: Bid):
            """Receive a bid from a contractor."""
            if bid.task_id in self.bids:
                self.bids[bid.task_id].append(bid)
        
        def evaluate_bids(self, task_id: str) -> Optional[Bid]:
            """Evaluate bids and select the best one."""
            if task_id not in self.bids or not self.bids[task_id]:
                return None
            
            task = self.tasks[task_id]
            bids = self.bids[task_id]
            
            # Simple evaluation: select lowest cost with acceptable quality
            acceptable_bids = [b for b in bids if b.quality_score >= 7.0]
            if acceptable_bids:
                best_bid = min(acceptable_bids, key=lambda b: b.cost)
            else:
                best_bid = min(bids, key=lambda b: b.cost)
            
            best_bid.status = BidStatus.ACCEPTED
            return best_bid
        
        def award_contract(self, task_id: str) -> Dict[str, Any]:
            """Award contract to the best bidder."""
            winning_bid = self.evaluate_bids(task_id)
            
            if not winning_bid:
                return {"success": False, "message": "No bids received"}
            
            # Mark other bids as rejected
            for bid in self.bids[task_id]:
                if bid != winning_bid:
                    bid.status = BidStatus.REJECTED
            
            return {
                "success": True,
                "task_id": task_id,
                "winner": winning_bid.agent_id,
                "cost": winning_bid.cost,
                "time_estimate": winning_bid.time_estimate,
                "all_bids": len(self.bids[task_id])
            }
    
    
    class ContractorAgent:
        """Agent that bids on tasks."""
        
        def __init__(self, agent_id: str, capabilities: List[str], 
                     contract_net: ContractNetPattern, llm):
            self.agent_id = agent_id
            self.capabilities = capabilities
            self.contract_net = contract_net
            self.llm = llm
        
        def submit_bid(self, task: Task) -> Bid:
            """Submit a bid for a task."""
            prompt = ChatPromptTemplate.from_messages([
                ("system", """You are contractor {agent_id} with capabilities: {capabilities}
                
                Create a bid for this task. Provide cost (dollars), time (hours), quality score (1-10).
                Task: {task_description}
                Requirements: {requirements}"""),
                ("human", "Provide: Cost: X, Time: Y, Quality: Z, Proposal: [text]")
            ])
            
            chain = prompt | self.llm
            response = chain.invoke({
                "agent_id": self.agent_id,
                "capabilities": ", ".join(self.capabilities),
                "task_description": task.description,
                "requirements": ", ".join(task.requirements)
            })
            
            # Parse response (simplified)
            import random
            bid = Bid(
                agent_id=self.agent_id,
                task_id=task.id,
                cost=random.uniform(500, 5000),
                time_estimate=random.uniform(10, 50),
                quality_score=random.uniform(6, 10),
                proposal=response.content[:200]
            )
            
            self.contract_net.receive_bid(bid)
            return bid
    
    
    # Example usage
    if __name__ == "__main__":
        cn = ContractNetPattern()
        
        # Register contractors
        c1 = cn.register_contractor("Agent_A", ["web_dev", "backend"])
        c2 = cn.register_contractor("Agent_B", ["web_dev", "frontend"])
        c3 = cn.register_contractor("Agent_C", ["fullstack", "devops"])
        
        # Announce task
        task = Task(
            id="task_001",
            description="Build REST API",
            requirements=["Python", "FastAPI"],
            budget=5000.0
        )
        
        cn.announce_task(task)
        
        # Submit bids
        c1.submit_bid(task)
        c2.submit_bid(task)
        c3.submit_bid(task)
        
        # Award
        result = cn.award_contract(task.id)
        print(f"Winner: {result['winner']}, Cost: ${result['cost']:.2f}")
    
        

    Agentic Architecture Pattern: Contract Net

    Pattern 12: 12 Contract Net – Line-by-Line Explanation

    Overview

    Pattern 12: Contract Net Protocol A negotiation protocol where agents bid for tasks.


    Code Structure Analysis

    File Information

    • Pattern Number: 12
    • Pattern Name: 12 Contract Net
    • File Path: patterns\communication\12_contract_net.py
    • Total Lines: 179

    Detailed Code Explanation

    Module Docstring

    """
    Pattern 12: Contract Net Protocol
    A negotiation protocol where agents bid for tasks.
    """
    

    Explanation: This module docstring describes the purpose and key features of the 12 Contract Net pattern.


    Imports Section

    from typing import Dict, Any, List, Optional
    from langchain_core.prompts import ChatPromptTemplate
    from langchain_openai import ChatOpenAI
    from pydantic import BaseModel, Field
    from enum import Enum
            import random  # First 20 imports shown
    

    Explanation: The module imports necessary dependencies: – from typing import Dict, Any, List, Optional: Type hints for better code documentation – from langchain_core.prompts import ChatPromptTemplate: LangChain framework integration – from langchain_openai import ChatOpenAI: LangChain framework integration – from enum import Enum: Enumeration support for fixed sets of values


    Enumerations

    BidStatus (Line 13)

    class BidStatus(Enum):
        PENDING
        ACCEPTED
        REJECTED
    

    Purpose: No enum docstring.

    Values: – PENDING: Initial state, not yet processed – ACCEPTED: Represents accepted – REJECTED: Represents rejected


    Classes

    BidStatus (Line 13)

    Description: No class docstring.

    Bid (Line 19)

    Description: Represents a bid from an agent.

    Task (Line 30)

    Description: Represents a task to be contracted.

    ContractNetPattern (Line 39)

    Description: Contract Net Protocol – Task allocation through bidding. Manager announces tasks, contractors bid, manager awards contracts.

    Methods:

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

    Purpose: No method docstring.

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

    announce_task (Line 51)
    def announce_task(self, task):
        """Manager announces a task."""
    

    Purpose: Manager announces a task.

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

    register_contractor (Line 57)
    def register_contractor(self, agent_id, capabilities):
        """Register a contractor agent."""
    

    Purpose: Register a contractor agent.

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

    receive_bid (Line 63)
    def receive_bid(self, bid):
        """Receive a bid from a contractor."""
    

    Purpose: Receive a bid from a contractor.

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

    evaluate_bids (Line 68)
    def evaluate_bids(self, task_id):
        """Evaluate bids and select the best one."""
    

    Purpose: Evaluate bids and select the best one.

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

    award_contract (Line 86)
    def award_contract(self, task_id):
        """Award contract to the best bidder."""
    

    Purpose: Award contract to the best bidder.

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

    ContractorAgent (Line 108)

    Description: Agent that bids on tasks.

    Methods:

    __init__ (Line 111)
    def __init__(self, agent_id, capabilities, contract_net, llm):
        """No method docstring."""
    

    Purpose: No method docstring.

    Parameters: – self: Instance reference – agent_id: Parameter for agent_id – capabilities: Parameter for capabilities – contract_net: Parameter for contract_net – llm: Parameter for llm

    submit_bid (Line 118)
    def submit_bid(self, task):
        """Submit a bid for a task."""
    

    Purpose: Submit a bid for a task.

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


    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 = BidStatus(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: Blackboard

    
        """
    Pattern 11: Blackboard
    
    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 BlackboardConfig:
        """Configuration for Blackboard."""
        model_name: str = "gpt-4"
        temperature: float = 0.7
        max_iterations: int = 10
        enable_logging: bool = True
    
    
    @dataclass
    class BlackboardState:
        """State information for Blackboard."""
        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 BlackboardAgent:
        """Agent implementing Blackboard."""
        
        def __init__(self, name: str, config: BlackboardConfig = None):
            self.name = name
            self.config = config or BlackboardConfig()
            self.llm = ChatOpenAI(
                model=self.config.model_name,
                temperature=self.config.temperature
            )
            self.state = BlackboardState()
            self.execution_history: List[Dict[str, Any]] = []
        
        def process(self, input_data: Any) -> Dict[str, Any]:
            """Process input according to Blackboard."""
            self.state.current_step += 1
            
            prompt = ChatPromptTemplate.from_messages([
                ("system", f"You are {self.name}, implementing Blackboard. "
                          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 BlackboardPattern:
        """
        Blackboard - Enhanced implementation
        
        This pattern provides comprehensive functionality for blackboard
        with full LangChain/LangGraph integration.
        
        Features:
        - Multi-agent coordination
        - State management
        - Execution tracking
        - LangGraph workflow integration
        """
        
        def __init__(self, config: BlackboardConfig = None):
            self.config = config or BlackboardConfig()
            self.agents: Dict[str, BlackboardAgent] = {}
            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 Blackboard. 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: BlackboardAgent):
            """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": "Blackboard",
                    "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": "Blackboard",
                "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("=== Blackboard Demo ===\n")
        
        # Create configuration
        config = BlackboardConfig(
            model_name="gpt-4",
            temperature=0.7,
            enable_logging=True
        )
        
        # Create pattern
        pattern = BlackboardPattern(config)
        
        # Create and register agents
        agent1 = BlackboardAgent("Agent1", config)
        agent2 = BlackboardAgent("Agent2", config)
        pattern.register_agent(agent1)
        pattern.register_agent(agent2)
        
        print("\nExecuting pattern workflow...")
        
        # Execute with workflow
        result1 = pattern.run("Demonstrate blackboard 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: Blackboard

    Pattern 11: 11 Blackboard – Line-by-Line Explanation

    Overview

    Pattern 11: Blackboard

    Purpose: Enhanced implementation with full LangChain/LangGraph integration


    Code Structure Analysis

    File Information

    • Pattern Number: 11
    • Pattern Name: 11 Blackboard
    • File Path: patterns\communication\11_blackboard.py
    • Total Lines: 247

    Detailed Code Explanation

    Module Docstring

    """
    Pattern 11: Blackboard
    
    Purpose: Enhanced implementation with full LangChain/LangGraph integration
    """
    

    Explanation: This module docstring describes the purpose and key features of the 11 Blackboard 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

    BlackboardConfig (Line 18)

    Description: Configuration for Blackboard.

    BlackboardState (Line 27)

    Description: State information for Blackboard.

    BlackboardAgent (Line 36)

    Description: Agent implementing Blackboard.

    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 Blackboard."""
    

    Purpose: Process input according to Blackboard.

    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

    BlackboardPattern (Line 85)

    Description: Blackboard – Enhanced implementation

    This pattern provides comprehensive functionality for blackboard 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 = BlackboardConfig(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: 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