Tag: architecture-pattern

  • Agentic Architecture Pattern: Model Router

    
        """
    Pattern 200: Model Router Pattern
    
    Intelligently route queries to the most appropriate model based on task type,
    complexity, cost, latency requirements, or other criteria.
    """
    
    from typing import Dict, Any, List, Optional, Callable
    from dataclasses import dataclass
    from enum import Enum
    from langchain_core.prompts import ChatPromptTemplate
    from langchain_openai import ChatOpenAI
    
    
    class TaskType(Enum):
        """Types of tasks for routing."""
        SIMPLE_QA = "simple_qa"
        COMPLEX_REASONING = "complex_reasoning"
        CODE_GENERATION = "code_generation"
        CREATIVE_WRITING = "creative_writing"
        TRANSLATION = "translation"
        SUMMARIZATION = "summarization"
        CLASSIFICATION = "classification"
    
    
    @dataclass
    class Model:
        """Model configuration for routing."""
        name: str
        model_id: str
        strengths: List[TaskType]
        cost_per_token: float
        avg_latency_ms: float
        max_tokens: int
        llm: Optional[ChatOpenAI] = None
        
        def __post_init__(self):
            if self.llm is None:
                # Set temperature based on task strengths
                temp = 0.7 if TaskType.CREATIVE_WRITING in self.strengths else 0.3
                self.llm = ChatOpenAI(model=self.model_id, temperature=temp)
    
    
    class ModelRouterPattern:
        """
        Model Router Pattern - Route to optimal model.
        """
        
        def __init__(self):
            self.models: List[Model] = []
            self.router_llm = ChatOpenAI(model="gpt-4", temperature=0)
            self.routing_history: List[Dict[str, Any]] = []
        
        def register_model(self, model: Model):
            """Register a model for routing."""
            self.models.append(model)
        
        def classify_task(self, query: str) -> TaskType:
            """Classify the task type using LLM."""
            task_types = ", ".join([t.value for t in TaskType])
            
            prompt = ChatPromptTemplate.from_messages([
                ("system", f"Classify the task type. Options: {task_types}. Respond with only the task type."),
                ("human", "{query}")
            ])
            
            chain = prompt | self.router_llm
            response = chain.invoke({"query": query})
            
            # Parse response to TaskType
            response_text = str(response.content).lower().strip()
            for task_type in TaskType:
                if task_type.value in response_text:
                    return task_type
            
            return TaskType.SIMPLE_QA  # Default
        
        def select_model(self, task_type: TaskType, preferences: Optional[Dict[str, Any]] = None) -> Model:
            """Select best model for task type based on preferences."""
            preferences = preferences or {}
            
            # Filter models by task type strength
            suitable_models = [m for m in self.models if task_type in m.strengths]
            
            if not suitable_models:
                suitable_models = self.models  # Fallback to all models
            
            if not suitable_models:
                raise ValueError("No models registered")
            
            # Select based on preferences
            optimize_for = preferences.get("optimize_for", "quality")
            
            if optimize_for == "cost":
                return min(suitable_models, key=lambda m: m.cost_per_token)
            elif optimize_for == "latency":
                return min(suitable_models, key=lambda m: m.avg_latency_ms)
            elif optimize_for == "quality":
                # Assume first model in strengths list is highest quality
                return suitable_models[0]
            else:
                return suitable_models[0]
        
        def run(self, query: str, preferences: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
            """Route query to appropriate model and execute."""
            # Classify task
            task_type = self.classify_task(query)
            print(f"Task classified as: {task_type.value}")
            
            # Select model
            selected_model = self.select_model(task_type, preferences)
            print(f"Routing to model: {selected_model.name}\n")
            
            # Execute with selected model
            prompt = ChatPromptTemplate.from_messages([
                ("system", "You are a helpful AI assistant."),
                ("human", "{query}")
            ])
            
            chain = prompt | selected_model.llm
            response = chain.invoke({"query": query})
            
            # Track routing decision
            routing_record = {
                "query": query,
                "task_type": task_type.value,
                "selected_model": selected_model.name,
                "model_cost": selected_model.cost_per_token,
                "model_latency": selected_model.avg_latency_ms
            }
            self.routing_history.append(routing_record)
            
            return {
                "query": query,
                "task_type": task_type.value,
                "routed_to": selected_model.name,
                "result": response.content,
                "routing_metadata": {
                    "cost_per_token": selected_model.cost_per_token,
                    "avg_latency_ms": selected_model.avg_latency_ms
                }
            }
        
        def get_statistics(self) -> Dict[str, Any]:
            """Get routing statistics."""
            model_usage = {}
            for record in self.routing_history:
                model = record["selected_model"]
                model_usage[model] = model_usage.get(model, 0) + 1
            
            return {
                "total_queries": len(self.routing_history),
                "model_usage": model_usage,
                "registered_models": len(self.models)
            }
    
    
    # Example usage
    if __name__ == "__main__":
        print("=== Model Router Pattern Demo ===\n")
        
        router = ModelRouterPattern()
        
        # Register models with different capabilities
        router.register_model(Model(
            name="GPT-4",
            model_id="gpt-4",
            strengths=[TaskType.COMPLEX_REASONING, TaskType.CODE_GENERATION],
            cost_per_token=0.00003,
            avg_latency_ms=2000,
            max_tokens=8000
        ))
        
        router.register_model(Model(
            name="GPT-3.5-Turbo",
            model_id="gpt-3.5-turbo",
            strengths=[TaskType.SIMPLE_QA, TaskType.SUMMARIZATION, TaskType.CLASSIFICATION],
            cost_per_token=0.000002,
            avg_latency_ms=800,
            max_tokens=4000
        ))
        
        router.register_model(Model(
            name="GPT-4-Creative",
            model_id="gpt-4",
            strengths=[TaskType.CREATIVE_WRITING, TaskType.TRANSLATION],
            cost_per_token=0.00003,
            avg_latency_ms=2000,
            max_tokens=8000
        ))
        
        # Test different queries
        queries = [
            "What is 2 + 2?",
            "Write a Python function to implement quicksort with detailed comments",
            "Write a creative short story about a robot discovering emotions"
        ]
        
        for i, query in enumerate(queries, 1):
            print(f"\nQuery {i}: {query}")
            print("-" * 60)
            result = router.run(query, preferences={"optimize_for": "quality"})
            print(f"Routed to: {result['routed_to']}")
            print(f"Result: {result['result'][:150]}...")
            print()
        
        # Statistics
        print("\n=== Routing Statistics ===")
        stats = router.get_statistics()
        print(f"Total queries: {stats['total_queries']}")
        print(f"Model usage: {stats['model_usage']}")
    
        

    Agentic Architecture Pattern: Model Router

    Pattern 200: 200 Model Router Pattern – Line-by-Line Explanation

    Overview

    Pattern 200: Model Router Pattern

    Intelligently route queries to the most appropriate model based on task type, complexity, cost, latency requirements, or other criteria.


    Code Structure Analysis

    File Information

    • Pattern Number: 200
    • Pattern Name: 200 Model Router Pattern
    • File Path: patterns\llm_specific\200_model_router_pattern.py
    • Total Lines: 212

    Detailed Code Explanation

    Module Docstring

    """
    Pattern 200: Model Router Pattern
    
    Intelligently route queries to the most appropriate model based on task type,
    complexity, cost, latency requirements, or other criteria.
    """
    

    Explanation: This module docstring describes the purpose and key features of the 200 Model Router Pattern pattern.


    Imports Section

    from typing import Dict, Any, List, Optional, Callable
    from dataclasses import dataclass
    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, Callable: Type hints for better code documentation – from dataclasses import dataclass: Data class decorators for clean data structures – 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

    TaskType (Line 15)

    class TaskType(Enum):
        SIMPLE_QA
        COMPLEX_REASONING
        CODE_GENERATION
        CREATIVE_WRITING
        TRANSLATION
        SUMMARIZATION
        CLASSIFICATION
    

    Purpose: Types of tasks for routing.

    Values: – SIMPLE_QA: Represents simple qa – COMPLEX_REASONING: Represents complex reasoning – CODE_GENERATION: Represents code generation – CREATIVE_WRITING: Represents creative writing – TRANSLATION: Represents translation – SUMMARIZATION: Represents summarization – CLASSIFICATION: Represents classification


    Classes

    TaskType (Line 15)

    Description: Types of tasks for routing.

    Model (Line 27)

    Description: Model configuration for routing.

    Methods:

    __post_init__ (Line 37)
    def __post_init__(self):
        """No method docstring."""
    

    Purpose: No method docstring.

    Parameters: – self: Instance reference

    ModelRouterPattern (Line 44)

    Description: Model Router Pattern – Route to optimal model.

    Methods:

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

    Purpose: No method docstring.

    Parameters: – self: Instance reference

    register_model (Line 54)
    def register_model(self, model):
        """Register a model for routing."""
    

    Purpose: Register a model for routing.

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

    classify_task (Line 58)
    def classify_task(self, query):
        """Classify the task type using LLM."""
    

    Purpose: Classify the task type using LLM.

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

    select_model (Line 78)
    def select_model(self, task_type, preferences):
        """Select best model for task type based on preferences."""
    

    Purpose: Select best model for task type based on preferences.

    Parameters: – self: Instance reference – task_type: Parameter for task_type – preferences: Parameter for preferences

    run (Line 104)
    def run(self, query, preferences):
        """Route query to appropriate model and execute."""
    

    Purpose: Route query to appropriate model and execute.

    Parameters: – self: Instance reference – query: Parameter for query – preferences: Parameter for preferences

    get_statistics (Line 144)
    def get_statistics(self):
        """Get routing statistics."""
    

    Purpose: Get routing statistics.

    Parameters: – self: Instance reference


    Design Patterns Used

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

    Usage Example

    # Initialize the pattern
    pattern = TaskType(name="example", model_name="gpt-4")
    
    # Configure and execute
    result = pattern.execute(data={"key": "value"})
    
    # Check results
    print(result)
    

    Key Concepts

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

    Extension Points

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

  • Agentic Architecture Pattern: Multi Model

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

    Pattern 199: 199 Multi Model Pattern – Line-by-Line Explanation

    Overview

    Pattern 199: Multi Model Pattern

    Purpose: Enhanced implementation with full LangChain/LangGraph integration


    Code Structure Analysis

    File Information

    • Pattern Number: 199
    • Pattern Name: 199 Multi Model Pattern
    • File Path: patterns\llm_specific\199_multi_model_pattern.py
    • Total Lines: 247

    Detailed Code Explanation

    Module Docstring

    """
    Pattern 199: Multi Model Pattern
    
    Purpose: Enhanced implementation with full LangChain/LangGraph integration
    """
    

    Explanation: This module docstring describes the purpose and key features of the 199 Multi Model Pattern 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

    MultiModelConfig (Line 18)

    Description: Configuration for Multi Model Pattern.

    MultiModelState (Line 27)

    Description: State information for Multi Model Pattern.

    MultiModelAgent (Line 36)

    Description: Agent implementing Multi Model Pattern.

    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 Multi Model Pattern."""
    

    Purpose: Process input according to Multi Model Pattern.

    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

    MultiModelPattern (Line 85)

    Description: Multi Model Pattern – Enhanced implementation

    This pattern provides comprehensive functionality for multi model 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 = MultiModelConfig(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: Ensemble

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

    Pattern 198: 198 Ensemble Pattern – Line-by-Line Explanation

    Overview

    Pattern 198: Ensemble Pattern

    Purpose: Enhanced implementation with full LangChain/LangGraph integration


    Code Structure Analysis

    File Information

    • Pattern Number: 198
    • Pattern Name: 198 Ensemble Pattern
    • File Path: patterns\llm_specific\198_ensemble_pattern.py
    • Total Lines: 247

    Detailed Code Explanation

    Module Docstring

    """
    Pattern 198: Ensemble Pattern
    
    Purpose: Enhanced implementation with full LangChain/LangGraph integration
    """
    

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

    EnsembleConfig (Line 18)

    Description: Configuration for Ensemble Pattern.

    EnsembleState (Line 27)

    Description: State information for Ensemble Pattern.

    EnsembleAgent (Line 36)

    Description: Agent implementing Ensemble Pattern.

    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 Ensemble Pattern."""
    

    Purpose: Process input according to Ensemble Pattern.

    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

    EnsemblePattern (Line 85)

    Description: Ensemble Pattern – Enhanced implementation

    This pattern provides comprehensive functionality for ensemble 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 = EnsembleConfig(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: Self Consistency

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

    Pattern 197: 197 Self Consistency Pattern – Line-by-Line Explanation

    Overview

    Pattern 197: Self Consistency Pattern

    Purpose: Enhanced implementation with full LangChain/LangGraph integration


    Code Structure Analysis

    File Information

    • Pattern Number: 197
    • Pattern Name: 197 Self Consistency Pattern
    • File Path: patterns\llm_specific\197_self_consistency_pattern.py
    • Total Lines: 247

    Detailed Code Explanation

    Module Docstring

    """
    Pattern 197: Self Consistency Pattern
    
    Purpose: Enhanced implementation with full LangChain/LangGraph integration
    """
    

    Explanation: This module docstring describes the purpose and key features of the 197 Self Consistency Pattern 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

    SelfConsistencyConfig (Line 18)

    Description: Configuration for Self Consistency Pattern.

    SelfConsistencyState (Line 27)

    Description: State information for Self Consistency Pattern.

    SelfConsistencyAgent (Line 36)

    Description: Agent implementing Self Consistency Pattern.

    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 Self Consistency Pattern."""
    

    Purpose: Process input according to Self Consistency Pattern.

    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

    SelfConsistencyPattern (Line 85)

    Description: Self Consistency Pattern – Enhanced implementation

    This pattern provides comprehensive functionality for self consistency 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 = SelfConsistencyConfig(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: Constitutional Ai

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

    Pattern 196: 196 Constitutional Ai Pattern – Line-by-Line Explanation

    Overview

    Pattern 196: Constitutional Ai Pattern

    Purpose: Enhanced implementation with full LangChain/LangGraph integration


    Code Structure Analysis

    File Information

    • Pattern Number: 196
    • Pattern Name: 196 Constitutional Ai Pattern
    • File Path: patterns\llm_specific\196_constitutional_ai_pattern.py
    • Total Lines: 247

    Detailed Code Explanation

    Module Docstring

    """
    Pattern 196: Constitutional Ai Pattern
    
    Purpose: Enhanced implementation with full LangChain/LangGraph integration
    """
    

    Explanation: This module docstring describes the purpose and key features of the 196 Constitutional Ai Pattern 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

    ConstitutionalAiConfig (Line 18)

    Description: Configuration for Constitutional Ai Pattern.

    ConstitutionalAiState (Line 27)

    Description: State information for Constitutional Ai Pattern.

    ConstitutionalAiAgent (Line 36)

    Description: Agent implementing Constitutional Ai Pattern.

    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 Constitutional Ai Pattern."""
    

    Purpose: Process input according to Constitutional Ai Pattern.

    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

    ConstitutionalAiPattern (Line 85)

    Description: Constitutional Ai Pattern – Enhanced implementation

    This pattern provides comprehensive functionality for constitutional ai 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 = ConstitutionalAiConfig(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: Prompt Chaining

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

    Pattern 195: 195 Prompt Chaining Pattern – Line-by-Line Explanation

    Overview

    Pattern 195: Prompt Chaining Pattern

    Purpose: Enhanced implementation with full LangChain/LangGraph integration


    Code Structure Analysis

    File Information

    • Pattern Number: 195
    • Pattern Name: 195 Prompt Chaining Pattern
    • File Path: patterns\llm_specific\195_prompt_chaining_pattern.py
    • Total Lines: 247

    Detailed Code Explanation

    Module Docstring

    """
    Pattern 195: Prompt Chaining Pattern
    
    Purpose: Enhanced implementation with full LangChain/LangGraph integration
    """
    

    Explanation: This module docstring describes the purpose and key features of the 195 Prompt Chaining Pattern 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

    PromptChainingConfig (Line 18)

    Description: Configuration for Prompt Chaining Pattern.

    PromptChainingState (Line 27)

    Description: State information for Prompt Chaining Pattern.

    PromptChainingAgent (Line 36)

    Description: Agent implementing Prompt Chaining Pattern.

    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 Prompt Chaining Pattern."""
    

    Purpose: Process input according to Prompt Chaining Pattern.

    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

    PromptChainingPattern (Line 85)

    Description: Prompt Chaining Pattern – Enhanced implementation

    This pattern provides comprehensive functionality for prompt chaining 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 = PromptChainingConfig(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: Chain Prompting

    
        """
    Pattern 194: Chain Prompting Pattern
    
    Breaks complex tasks into a sequence of simpler prompts where each
    prompt builds on previous outputs. Creates dependency chain of prompts.
    """
    
    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 PromptStep:
        """Single step in prompt chain."""
        name: str
        prompt_template: str
        depends_on: List[str] = field(default_factory=list)
        output: Optional[str] = None
        timestamp: Optional[datetime] = None
    
    
    @dataclass
    class ChainExecution:
        """Execution trace of prompt chain."""
        steps: List[PromptStep]
        inputs: Dict[str, Any]
        outputs: Dict[str, str]
        execution_order: List[str]
        total_time: float = 0.0
    
    
    class ChainPromptingAgent:
        """Agent that executes prompt chains."""
        
        def __init__(self, name: str, model_name: str = "gpt-4"):
            self.name = name
            self.llm = ChatOpenAI(model=model_name, temperature=0.7)
            self.steps: Dict[str, PromptStep] = {}
            self.executions: List[ChainExecution] = []
        
        def add_step(self, step: PromptStep):
            """Add step to chain."""
            self.steps[step.name] = step
            print(f"  Added step: {step.name}")
        
        def _resolve_dependencies(self) -> List[str]:
            """Resolve execution order based on dependencies."""
            executed = set()
            execution_order = []
            
            def can_execute(step_name: str) -> bool:
                step = self.steps[step_name]
                return all(dep in executed for dep in step.depends_on)
            
            while len(executed)  ChainExecution:
            """Execute the prompt chain."""
            print(f"\n  {self.name}: Executing prompt chain...")
            start_time = datetime.now()
            
            # Resolve execution order
            execution_order = self._resolve_dependencies()
            print(f"  Execution order: {' → '.join(execution_order)}")
            
            # Execute steps in order
            outputs = {}
            executed_steps = []
            
            for step_name in execution_order:
                step = self.steps[step_name]
                print(f"\n  Executing: {step_name}")
                
                # Prepare input by gathering dependencies
                step_input = initial_input.copy()
                for dep in step.depends_on:
                    if dep in outputs:
                        step_input[dep] = outputs[dep]
                
                # Execute step
                prompt = ChatPromptTemplate.from_messages([
                    ("system", "You are part of a multi-step reasoning chain."),
                    ("human", step.prompt_template)
                ])
                
                chain = prompt | self.llm
                response = chain.invoke(step_input)
                
                output = response.content
                outputs[step_name] = output
                
                step.output = output
                step.timestamp = datetime.now()
                executed_steps.append(step)
                
                print(f"  Output: {output[:100]}...")
            
            end_time = datetime.now()
            execution = ChainExecution(
                steps=executed_steps,
                inputs=initial_input,
                outputs=outputs,
                execution_order=execution_order,
                total_time=(end_time - start_time).total_seconds()
            )
            
            self.executions.append(execution)
            return execution
    
    
    class ChainPromptingPattern:
        """
        Chain Prompting Pattern - Sequential prompt dependencies.
        
        Breaks complex tasks into dependent steps where each step
        uses outputs from previous steps.
        """
        
        def __init__(self):
            self.agents: Dict[str, ChainPromptingAgent] = {}
        
        def register_agent(self, agent: ChainPromptingAgent):
            """Register chain prompting agent."""
            self.agents[agent.name] = agent
        
        def run(self, initial_inputs: Dict[str, Any]) -> Dict[str, Any]:
            """Execute prompt chains."""
            print("=== Chain Prompting Pattern ===\n")
            
            results = {}
            for agent in self.agents.values():
                execution = agent.execute_chain(initial_inputs)
                results[agent.name] = execution.outputs
            
            return {
                "pattern": "ChainPrompting",
                "agents": len(self.agents),
                "results": results,
                "total_steps": sum(len(a.steps) for a in self.agents.values())
            }
    
    
    # Example usage
    if __name__ == "__main__":
        print("=== Chain Prompting Pattern Demo ===\n")
        
        # Create pattern and agent
        pattern = ChainPromptingPattern()
        agent = ChainPromptingAgent("ArticleWriter")
        
        # Build prompt chain for article writing
        print("1. Building prompt chain...\n")
        
        # Step 1: Research (no dependencies)
        agent.add_step(PromptStep(
            name="research",
            prompt_template="Research key facts about: {topic}. List 5 important facts.",
            depends_on=[]
        ))
        
        # Step 2: Outline (depends on research)
        agent.add_step(PromptStep(
            name="outline",
            prompt_template="Create an article outline about {topic} using these facts:\n{research}",
            depends_on=["research"]
        ))
        
        # Step 3: Introduction (depends on outline)
        agent.add_step(PromptStep(
            name="introduction",
            prompt_template="Write an engaging introduction for this article:\nTopic: {topic}\nOutline: {outline}",
            depends_on=["outline"]
        ))
        
        # Step 4: Body (depends on outline and research)
        agent.add_step(PromptStep(
            name="body",
            prompt_template="Write the main body using:\nOutline: {outline}\nFacts: {research}",
            depends_on=["outline", "research"]
        ))
        
        # Step 5: Conclusion (depends on all previous)
        agent.add_step(PromptStep(
            name="conclusion",
            prompt_template="Write a conclusion that ties together:\nIntro: {introduction}\nBody: {body}",
            depends_on=["introduction", "body"]
        ))
        
        pattern.register_agent(agent)
        
        # Execute chain
        print("\n2. Executing chain...\n")
        summary = pattern.run({"topic": "Artificial Intelligence in Healthcare"})
        
        print(f"\n3. Summary:")
        print(f"   Total steps: {summary['total_steps']}")
        print(f"   Steps executed: {len(agent.executions[0].execution_order)}")
        
        print(f"\n4. Chain Outputs:")
        for step_name, output in agent.executions[0].outputs.items():
            print(f"\n   {step_name}:")
            print(f"   {output[:150]}...")
        
        print(f"\n   Total execution time: {agent.executions[0].total_time:.2f}s")
        
        print("\nāœ“ Chain prompting: sequential dependent prompts!")
    
        

    Agentic Architecture Pattern: Chain Prompting

    Pattern 194: 194 Chain Prompting Pattern – Line-by-Line Explanation

    Overview

    Pattern 194: Chain Prompting Pattern

    Breaks complex tasks into a sequence of simpler prompts where each prompt builds on previous outputs. Creates dependency chain of prompts.


    Code Structure Analysis

    File Information

    • Pattern Number: 194
    • Pattern Name: 194 Chain Prompting Pattern
    • File Path: patterns\llm_specific\194_chain_prompting_pattern.py
    • Total Lines: 221

    Detailed Code Explanation

    Module Docstring

    """
    Pattern 194: Chain Prompting Pattern
    
    Breaks complex tasks into a sequence of simpler prompts where each
    prompt builds on previous outputs. Creates dependency chain of prompts.
    """
    

    Explanation: This module docstring describes the purpose and key features of the 194 Chain Prompting Pattern 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

    PromptStep (Line 16)

    Description: Single step in prompt chain.

    ChainExecution (Line 26)

    Description: Execution trace of prompt chain.

    ChainPromptingAgent (Line 35)

    Description: Agent that executes prompt chains.

    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”)

    add_step (Line 44)
    def add_step(self, step):
        """Add step to chain."""
    

    Purpose: Add step to chain.

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

    _resolve_dependencies (Line 49)
    def _resolve_dependencies(self):
        """Resolve execution order based on dependencies."""
    

    Purpose: Resolve execution order based on dependencies.

    Parameters: – self: Instance reference

    execute_chain (Line 71)
    def execute_chain(self, initial_input):
        """Execute the prompt chain."""
    

    Purpose: Execute the prompt chain.

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

    ChainPromptingPattern (Line 125)

    Description: Chain Prompting Pattern – Sequential prompt dependencies.

    Breaks complex tasks into dependent steps where each step uses outputs from previous steps.

    Methods:

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

    Purpose: No method docstring.

    Parameters: – self: Instance reference

    register_agent (Line 136)
    def register_agent(self, agent):
        """Register chain prompting agent."""
    

    Purpose: Register chain prompting agent.

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

    run (Line 140)
    def run(self, initial_inputs):
        """Execute prompt chains."""
    

    Purpose: Execute prompt chains.

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


    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 = PromptStep(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: Zero Shot Learning

    
        """
    Pattern 193: Zero-Shot Learning Pattern
    
    LLM performs tasks without any training examples, relying solely on pre-trained knowledge.
    Demonstrates ability to generalize to new tasks using instructions alone.
    """
    
    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_core.output_parsers import StrOutputParser
    from langchain_openai import ChatOpenAI
    
    
    class TaskCategory(Enum):
        """Categories of zero-shot tasks."""
        CLASSIFICATION = "classification"
        GENERATION = "generation"
        TRANSLATION = "translation"
        SUMMARIZATION = "summarization"
        QUESTION_ANSWERING = "question_answering"
        REASONING = "reasoning"
        EXTRACTION = "extraction"
    
    
    @dataclass
    class ZeroShotTask:
        """A task to be performed without examples."""
        task_name: str
        category: TaskCategory
        instruction: str
        expected_output_format: Optional[str] = None
        constraints: List[str] = field(default_factory=list)
    
    
    @dataclass
    class ZeroShotResult:
        """Result from zero-shot execution."""
        task_name: str
        category: TaskCategory
        input: str
        output: str
        instruction_used: str
        confidence_estimate: Optional[float] = None
        timestamp: datetime = field(default_factory=datetime.now)
    
    
    class ZeroShotAgent:
        """Agent that performs tasks without examples."""
        
        def __init__(self, name: str, model_name: str = "gpt-4", temperature: float = 0.7):
            self.name = name
            self.llm = ChatOpenAI(model=model_name, temperature=temperature)
            self.task_registry: Dict[str, ZeroShotTask] = {}
            self.results: List[ZeroShotResult] = []
        
        def register_task(self, task: ZeroShotTask):
            """Register a task the agent can perform."""
            self.task_registry[task.task_name] = task
            print(f"šŸ“‹ {self.name} registered task: {task.task_name} ({task.category.value})")
        
        def create_zero_shot_prompt(self, task: ZeroShotTask, input_text: str) -> str:
            """Create prompt for zero-shot execution."""
            prompt_parts = []
            
            # Task instruction
            prompt_parts.append(f"Task: {task.instruction}")
            
            # Output format if specified
            if task.expected_output_format:
                prompt_parts.append(f"\nExpected Output Format: {task.expected_output_format}")
            
            # Constraints if any
            if task.constraints:
                prompt_parts.append("\nConstraints:")
                for constraint in task.constraints:
                    prompt_parts.append(f"- {constraint}")
            
            # The actual input
            prompt_parts.append(f"\nInput: {input_text}")
            prompt_parts.append("\nOutput:")
            
            return "\n".join(prompt_parts)
        
        def execute_task(self, task_name: str, input_text: str) -> ZeroShotResult:
            """Execute a registered task on input."""
            if task_name not in self.task_registry:
                raise ValueError(f"Task '{task_name}' not registered")
            
            task = self.task_registry[task_name]
            prompt_text = self.create_zero_shot_prompt(task, input_text)
            
            # Execute with LLM
            prompt = ChatPromptTemplate.from_messages([
                ("system", f"You are {self.name}, a capable AI assistant. "
                          f"Follow the instructions precisely and provide high-quality output."),
                ("human", "{prompt}")
            ])
            
            chain = prompt | self.llm | StrOutputParser()
            output = chain.invoke({"prompt": prompt_text})
            
            result = ZeroShotResult(
                task_name=task_name,
                category=task.category,
                input=input_text,
                output=output,
                instruction_used=task.instruction
            )
            
            self.results.append(result)
            return result
        
        def execute_adhoc(self, instruction: str, input_text: str, 
                         category: TaskCategory = TaskCategory.GENERATION) -> ZeroShotResult:
            """Execute an ad-hoc task without prior registration."""
            adhoc_task = ZeroShotTask(
                task_name=f"adhoc_{len(self.results)}",
                category=category,
                instruction=instruction
            )
            
            prompt_text = self.create_zero_shot_prompt(adhoc_task, input_text)
            
            prompt = ChatPromptTemplate.from_messages([
                ("system", f"You are {self.name}. Follow instructions and provide quality output."),
                ("human", "{prompt}")
            ])
            
            chain = prompt | self.llm | StrOutputParser()
            output = chain.invoke({"prompt": prompt_text})
            
            result = ZeroShotResult(
                task_name=adhoc_task.task_name,
                category=category,
                input=input_text,
                output=output,
                instruction_used=instruction
            )
            
            self.results.append(result)
            return result
        
        def get_statistics(self) -> Dict[str, Any]:
            """Get agent statistics."""
            category_counts = {}
            for result in self.results:
                cat = result.category.value
                category_counts[cat] = category_counts.get(cat, 0) + 1
            
            return {
                "name": self.name,
                "registered_tasks": len(self.task_registry),
                "total_executions": len(self.results),
                "tasks_by_category": category_counts
            }
    
    
    class ZeroShotLearningPattern:
        """
        Zero-Shot Learning Pattern - Task execution without training examples.
        
        Leverages LLM's pre-trained knowledge to perform tasks based solely
        on natural language instructions, without any demonstration examples.
        """
        
        def __init__(self, model_name: str = "gpt-4"):
            self.model_name = model_name
            self.agents: Dict[str, ZeroShotAgent] = {}
            self.task_library: Dict[str, ZeroShotTask] = {}
        
        def create_agent(self, name: str) -> ZeroShotAgent:
            """Create a zero-shot capable agent."""
            agent = ZeroShotAgent(name, self.model_name)
            self.agents[name] = agent
            return agent
        
        def register_task_template(self, task: ZeroShotTask):
            """Register a task template in the library."""
            self.task_library[task.task_name] = task
            print(f"šŸ“š Task template registered: {task.task_name}")
        
        def create_task(self, task_name: str, category: TaskCategory, 
                       instruction: str, **kwargs) -> ZeroShotTask:
            """Create and register a task template."""
            task = ZeroShotTask(
                task_name=task_name,
                category=category,
                instruction=instruction,
                expected_output_format=kwargs.get('expected_output_format'),
                constraints=kwargs.get('constraints', [])
            )
            self.register_task_template(task)
            return task
        
        def assign_task_to_agent(self, agent_name: str, task_name: str):
            """Assign a task from library to an agent."""
            if agent_name not in self.agents:
                raise ValueError(f"Agent '{agent_name}' not found")
            if task_name not in self.task_library:
                raise ValueError(f"Task '{task_name}' not in library")
            
            agent = self.agents[agent_name]
            task = self.task_library[task_name]
            agent.register_task(task)
        
        def get_statistics(self) -> Dict[str, Any]:
            """Get pattern statistics."""
            return {
                "total_agents": len(self.agents),
                "task_templates": len(self.task_library),
                "agents": {name: agent.get_statistics() for name, agent in self.agents.items()}
            }
    
    
    # Example usage
    if __name__ == "__main__":
        print("=== Zero-Shot Learning Pattern Demo ===\n")
        
        # Create pattern
        print("1. Creating zero-shot learning pattern...")
        pattern = ZeroShotLearningPattern()
        
        # Create agent
        agent = pattern.create_agent("ZeroShotMaster")
        
        # Task 1: Text Classification
        print(f"\n{'='*70}")
        print("šŸ“ Task 1: Text Classification (Zero-Shot)")
        print(f"{'='*70}\n")
        
        classification_task = pattern.create_task(
            task_name="sentiment_classification",
            category=TaskCategory.CLASSIFICATION,
            instruction="Classify the sentiment of the given text as Positive, Negative, or Neutral.",
            expected_output_format="Single word: Positive, Negative, or Neutral",
            constraints=["Provide only the classification", "No explanation needed"]
        )
        
        pattern.assign_task_to_agent("ZeroShotMaster", "sentiment_classification")
        
        test_texts = [
            "This is absolutely fantastic! Best purchase ever!",
            "Completely disappointed. Waste of money.",
            "It's okay, does what it's supposed to do."
        ]
        
        print("Testing zero-shot classification:\n")
        for text in test_texts:
            result = agent.execute_task("sentiment_classification", text)
            print(f"Text: {result.input}")
            print(f"Classification: {result.output.strip()}\n")
        
        # Task 2: Question Answering
        print(f"\n{'='*70}")
        print("ā“ Task 2: Question Answering (Zero-Shot)")
        print(f"{'='*70}\n")
        
        qa_task = pattern.create_task(
            task_name="question_answering",
            category=TaskCategory.QUESTION_ANSWERING,
            instruction="Answer the question concisely based on general knowledge.",
            expected_output_format="2-3 sentences maximum",
            constraints=["Be factual and accurate", "Cite key points only"]
        )
        
        pattern.assign_task_to_agent("ZeroShotMaster", "question_answering")
        
        questions = [
            "What is the capital of France?",
            "How does photosynthesis work?",
            "Who wrote Romeo and Juliet?"
        ]
        
        print("Testing zero-shot Q&A:\n")
        for question in questions:
            result = agent.execute_task("question_answering", question)
            print(f"Q: {result.input}")
            print(f"A: {result.output.strip()}\n")
        
        # Task 3: Ad-hoc Execution (no prior registration)
        print(f"\n{'='*70}")
        print("šŸš€ Task 3: Ad-hoc Execution (Zero-Shot)")
        print(f"{'='*70}\n")
        
        adhoc_result = agent.execute_adhoc(
            instruction="Extract all email addresses from the text",
            input_text="Contact us at support@example.com or sales@company.org for more info.",
            category=TaskCategory.EXTRACTION
        )
        
        print(f"Instruction: {adhoc_result.instruction_used}")
        print(f"Input: {adhoc_result.input}")
        print(f"Extracted: {adhoc_result.output.strip()}\n")
        
        # Task 4: Translation
        print(f"\n{'='*70}")
        print("šŸŒ Task 4: Translation (Zero-Shot)")
        print(f"{'='*70}\n")
        
        translation_task = pattern.create_task(
            task_name="english_to_spanish",
            category=TaskCategory.TRANSLATION,
            instruction="Translate the English text to Spanish.",
            expected_output_format="Spanish translation only"
        )
        
        pattern.assign_task_to_agent("ZeroShotMaster", "english_to_spanish")
        
        translate_texts = [
            "Hello, how are you?",
            "The weather is beautiful today.",
            "I love learning new things."
        ]
        
        print("Testing zero-shot translation:\n")
        for text in translate_texts:
            result = agent.execute_task("english_to_spanish", text)
            print(f"English: {result.input}")
            print(f"Spanish: {result.output.strip()}\n")
        
        # Statistics
        print(f"\n{'='*70}")
        print("šŸ“Š Zero-Shot Learning Statistics")
        print(f"{'='*70}")
        
        stats = pattern.get_statistics()
        
        print(f"   Total agents: {stats['total_agents']}")
        print(f"   Task templates: {stats['task_templates']}")
        
        for agent_name, agent_stats in stats['agents'].items():
            print(f"\n   Agent: {agent_name}")
            print(f"   - Registered tasks: {agent_stats['registered_tasks']}")
            print(f"   - Total executions: {agent_stats['total_executions']}")
            print(f"   - Tasks by category:")
            for category, count in agent_stats['tasks_by_category'].items():
                print(f"     * {category}: {count}")
        
        print("\nāœ“ Zero-shot learning enabled task execution without examples!")
    
        

    Agentic Architecture Pattern: Zero Shot Learning

    Pattern 193: 193 Zero Shot Learning Pattern – Line-by-Line Explanation

    Overview

    Pattern 193: Zero-Shot Learning Pattern

    LLM performs tasks without any training examples, relying solely on pre-trained knowledge. Demonstrates ability to generalize to new tasks using instructions alone.


    Code Structure Analysis

    File Information

    • Pattern Number: 193
    • Pattern Name: 193 Zero Shot Learning Pattern
    • File Path: patterns\llm_specific\193_zero_shot_learning_pattern.py
    • Total Lines: 343

    Detailed Code Explanation

    Module Docstring

    """
    Pattern 193: Zero-Shot Learning Pattern
    
    LLM performs tasks without any training examples, relying solely on pre-trained knowledge.
    Demonstrates ability to generalize to new tasks using instructions alone.
    """
    

    Explanation: This module docstring describes the purpose and key features of the 193 Zero Shot Learning Pattern 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_core.output_parsers import StrOutputParser
    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_core.output_parsers import StrOutputParser: LangChain framework integration – from langchain_openai import ChatOpenAI: LangChain framework integration


    Enumerations

    TaskCategory (Line 17)

    class TaskCategory(Enum):
        CLASSIFICATION
        GENERATION
        TRANSLATION
        SUMMARIZATION
        QUESTION_ANSWERING
        REASONING
        EXTRACTION
    

    Purpose: Categories of zero-shot tasks.

    Values: – CLASSIFICATION: Represents classification – GENERATION: Represents generation – TRANSLATION: Represents translation – SUMMARIZATION: Represents summarization – QUESTION_ANSWERING: Represents question answering – REASONING: Represents reasoning – EXTRACTION: Represents extraction


    Classes

    TaskCategory (Line 17)

    Description: Categories of zero-shot tasks.

    ZeroShotTask (Line 29)

    Description: A task to be performed without examples.

    ZeroShotResult (Line 39)

    Description: Result from zero-shot execution.

    ZeroShotAgent (Line 50)

    Description: Agent that performs tasks without examples.

    Methods:

    __init__ (Line 53)
    def __init__(self, name, model_name, temperature):
        """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”) – temperature: Randomness in LLM responses (0.0-1.0)

    register_task (Line 59)
    def register_task(self, task):
        """Register a task the agent can perform."""
    

    Purpose: Register a task the agent can perform.

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

    create_zero_shot_prompt (Line 64)
    def create_zero_shot_prompt(self, task, input_text):
        """Create prompt for zero-shot execution."""
    

    Purpose: Create prompt for zero-shot execution.

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

    execute_task (Line 87)
    def execute_task(self, task_name, input_text):
        """Execute a registered task on input."""
    

    Purpose: Execute a registered task on input.

    Parameters: – self: Instance reference – task_name: Parameter for task_name – input_text: Parameter for input_text

    execute_adhoc (Line 116)
    def execute_adhoc(self, instruction, input_text, category):
        """Execute an ad-hoc task without prior registration."""
    

    Purpose: Execute an ad-hoc task without prior registration.

    Parameters: – self: Instance reference – instruction: Parameter for instruction – input_text: Parameter for input_text – category: Parameter for category

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

    Purpose: Get agent statistics.

    Parameters: – self: Instance reference

    ZeroShotLearningPattern (Line 161)

    Description: Zero-Shot Learning Pattern – Task execution without training examples.

    Leverages LLM’s pre-trained knowledge to perform tasks based solely on natural language instructions, without any demonstration examples.

    Methods:

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

    Purpose: No method docstring.

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

    create_agent (Line 174)
    def create_agent(self, name):
        """Create a zero-shot capable agent."""
    

    Purpose: Create a zero-shot capable agent.

    Parameters: – self: Instance reference – name: Identifier or label

    register_task_template (Line 180)
    def register_task_template(self, task):
        """Register a task template in the library."""
    

    Purpose: Register a task template in the library.

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

    create_task (Line 185)
    def create_task(self, task_name, category, instruction):
        """Create and register a task template."""
    

    Purpose: Create and register a task template.

    Parameters: – self: Instance reference – task_name: Parameter for task_name – category: Parameter for category – instruction: Parameter for instruction

    assign_task_to_agent (Line 198)
    def assign_task_to_agent(self, agent_name, task_name):
        """Assign a task from library to an agent."""
    

    Purpose: Assign a task from library to an agent.

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

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

    Purpose: Get pattern statistics.

    Parameters: – self: Instance reference


    Design Patterns Used

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

    Usage Example

    # Initialize the pattern
    pattern = TaskCategory(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: Few Shot Learning

    
        """
    Pattern 192: Few-Shot Learning Pattern
    
    LLM learns to perform tasks from a small number of examples provided in the prompt.
    Demonstrates in-context learning where the model adapts based on examples.
    """
    
    from typing import Dict, Any, List, Optional, Callable
    from dataclasses import dataclass, field
    from datetime import datetime
    from enum import Enum
    from langchain_core.prompts import ChatPromptTemplate, FewShotPromptTemplate, PromptTemplate
    from langchain_core.output_parsers import StrOutputParser
    from langchain_openai import ChatOpenAI
    
    
    class ExampleFormat(Enum):
        """Format for few-shot examples."""
        QA_PAIRS = "qa_pairs"  # Question-Answer format
        INPUT_OUTPUT = "input_output"  # Input-Output format
        DEMONSTRATION = "demonstration"  # Step-by-step demonstration
        LABELED = "labeled"  # Labeled examples with categories
    
    
    @dataclass
    class Example:
        """A single few-shot example."""
        input: str
        output: str
        explanation: Optional[str] = None
        label: Optional[str] = None
        metadata: Dict[str, Any] = field(default_factory=dict)
    
    
    @dataclass
    class FewShotTask:
        """A task to be performed using few-shot learning."""
        task_name: str
        description: str
        examples: List[Example]
        example_format: ExampleFormat
        instruction: Optional[str] = None
    
    
    @dataclass
    class FewShotResult:
        """Result from few-shot learning."""
        task_name: str
        input: str
        output: str
        examples_used: int
        confidence: Optional[float] = None
        timestamp: datetime = field(default_factory=datetime.now)
    
    
    class FewShotLearner:
        """Agent that learns from few examples."""
        
        def __init__(self, name: str, model_name: str = "gpt-4", temperature: float = 0.7):
            self.name = name
            self.llm = ChatOpenAI(model=model_name, temperature=temperature)
            self.learned_tasks: Dict[str, FewShotTask] = {}
            self.results: List[FewShotResult] = []
        
        def learn_task(self, task: FewShotTask):
            """Learn a new task from examples."""
            self.learned_tasks[task.task_name] = task
            print(f"šŸ“š {self.name} learned task '{task.task_name}' from {len(task.examples)} examples")
        
        def create_few_shot_prompt(self, task: FewShotTask, input_text: str) -> str:
            """Create prompt with few-shot examples."""
            prompt_parts = []
            
            # Add task description
            if task.description:
                prompt_parts.append(f"Task: {task.description}\n")
            
            if task.instruction:
                prompt_parts.append(f"Instructions: {task.instruction}\n")
            
            # Add examples based on format
            if task.example_format == ExampleFormat.QA_PAIRS:
                prompt_parts.append("Examples:")
                for i, ex in enumerate(task.examples, 1):
                    prompt_parts.append(f"\nQ{i}: {ex.input}")
                    prompt_parts.append(f"A{i}: {ex.output}")
                    if ex.explanation:
                        prompt_parts.append(f"Explanation: {ex.explanation}")
            
            elif task.example_format == ExampleFormat.INPUT_OUTPUT:
                prompt_parts.append("Examples:")
                for i, ex in enumerate(task.examples, 1):
                    prompt_parts.append(f"\nInput {i}: {ex.input}")
                    prompt_parts.append(f"Output {i}: {ex.output}")
            
            elif task.example_format == ExampleFormat.DEMONSTRATION:
                prompt_parts.append("Here's how to do it:")
                for i, ex in enumerate(task.examples, 1):
                    prompt_parts.append(f"\nExample {i}:")
                    prompt_parts.append(f"Given: {ex.input}")
                    prompt_parts.append(f"Steps: {ex.explanation or 'See output'}")
                    prompt_parts.append(f"Result: {ex.output}")
            
            elif task.example_format == ExampleFormat.LABELED:
                prompt_parts.append("Labeled examples:")
                for ex in task.examples:
                    label = ex.label or "unlabeled"
                    prompt_parts.append(f"\n[{label}] {ex.input} → {ex.output}")
            
            # Add new input
            prompt_parts.append(f"\n\nNow apply the same pattern:")
            if task.example_format == ExampleFormat.QA_PAIRS:
                prompt_parts.append(f"Q: {input_text}")
                prompt_parts.append("A:")
            else:
                prompt_parts.append(f"Input: {input_text}")
                prompt_parts.append("Output:")
            
            return "\n".join(prompt_parts)
        
        def execute_task(self, task_name: str, input_text: str) -> FewShotResult:
            """Execute learned task on new input."""
            if task_name not in self.learned_tasks:
                raise ValueError(f"Task '{task_name}' not learned yet")
            
            task = self.learned_tasks[task_name]
            prompt_text = self.create_few_shot_prompt(task, input_text)
            
            # Execute with LLM
            prompt = ChatPromptTemplate.from_messages([
                ("system", f"You are {self.name}. Follow the pattern shown in the examples."),
                ("human", "{prompt}")
            ])
            
            chain = prompt | self.llm | StrOutputParser()
            output = chain.invoke({"prompt": prompt_text})
            
            result = FewShotResult(
                task_name=task_name,
                input=input_text,
                output=output,
                examples_used=len(task.examples)
            )
            
            self.results.append(result)
            return result
        
        def get_statistics(self) -> Dict[str, Any]:
            """Get learning statistics."""
            return {
                "name": self.name,
                "tasks_learned": len(self.learned_tasks),
                "total_executions": len(self.results),
                "tasks": {name: len(task.examples) for name, task in self.learned_tasks.items()}
            }
    
    
    class FewShotLearningPattern:
        """
        Few-Shot Learning Pattern - Learn tasks from small number of examples.
        
        Enables LLMs to quickly adapt to new tasks by providing a few
        demonstration examples in the prompt context.
        """
        
        def __init__(self, model_name: str = "gpt-4"):
            self.model_name = model_name
            self.learners: Dict[str, FewShotLearner] = {}
            self.task_library: Dict[str, FewShotTask] = {}
        
        def create_learner(self, name: str) -> FewShotLearner:
            """Create a few-shot learner."""
            learner = FewShotLearner(name, self.model_name)
            self.learners[name] = learner
            return learner
        
        def register_task(self, task: FewShotTask):
            """Register a task in the library."""
            self.task_library[task.task_name] = task
            print(f"šŸ“‹ Task registered: {task.task_name} ({len(task.examples)} examples)")
        
        def create_task(self, task_name: str, description: str, 
                       examples: List[Example], example_format: ExampleFormat,
                       instruction: Optional[str] = None) -> FewShotTask:
            """Create and register a task."""
            task = FewShotTask(
                task_name=task_name,
                description=description,
                examples=examples,
                example_format=example_format,
                instruction=instruction
            )
            self.register_task(task)
            return task
        
        def teach_learner(self, learner_name: str, task_name: str):
            """Teach a task to a learner."""
            if learner_name not in self.learners:
                raise ValueError(f"Learner '{learner_name}' not found")
            if task_name not in self.task_library:
                raise ValueError(f"Task '{task_name}' not in library")
            
            learner = self.learners[learner_name]
            task = self.task_library[task_name]
            learner.learn_task(task)
        
        def get_statistics(self) -> Dict[str, Any]:
            """Get pattern statistics."""
            return {
                "total_learners": len(self.learners),
                "tasks_in_library": len(self.task_library),
                "learners": {name: learner.get_statistics() for name, learner in self.learners.items()}
            }
    
    
    # Example usage
    if __name__ == "__main__":
        print("=== Few-Shot Learning Pattern Demo ===\n")
        
        # Create pattern
        print("1. Creating few-shot learning pattern...")
        pattern = FewShotLearningPattern()
        
        # Create learner
        learner = pattern.create_learner("QuickLearner")
        
        # Task 1: Sentiment Analysis
        print(f"\n{'='*70}")
        print("šŸ“š Task 1: Sentiment Analysis")
        print(f"{'='*70}\n")
        
        sentiment_examples = [
            Example(
                input="I love this product! It's amazing!",
                output="Positive",
                explanation="Enthusiastic language with positive words"
            ),
            Example(
                input="Terrible experience. Very disappointed.",
                output="Negative",
                explanation="Strong negative words expressing dissatisfaction"
            ),
            Example(
                input="It's okay, nothing special.",
                output="Neutral",
                explanation="Lukewarm response without strong emotion"
            )
        ]
        
        sentiment_task = pattern.create_task(
            task_name="sentiment_analysis",
            description="Classify the sentiment of text as Positive, Negative, or Neutral",
            examples=sentiment_examples,
            example_format=ExampleFormat.QA_PAIRS,
            instruction="Analyze the emotional tone and classify accordingly"
        )
        
        pattern.teach_learner("QuickLearner", "sentiment_analysis")
        
        # Test sentiment analysis
        test_inputs = [
            "This is the best thing ever!",
            "I'm not impressed at all.",
            "It works as expected."
        ]
        
        print("Testing learned task:\n")
        for test_input in test_inputs:
            result = learner.execute_task("sentiment_analysis", test_input)
            print(f"Input: {result.input}")
            print(f"Output: {result.output}")
            print(f"Examples used: {result.examples_used}\n")
        
        # Task 2: Code Documentation
        print(f"\n{'='*70}")
        print("šŸ“š Task 2: Code Documentation")
        print(f"{'='*70}\n")
        
        doc_examples = [
            Example(
                input="def add(a, b): return a + b",
                output="Adds two numbers and returns their sum.",
                label="math_function"
            ),
            Example(
                input="def is_even(n): return n % 2 == 0",
                output="Checks if a number is even, returns True if divisible by 2.",
                label="boolean_function"
            )
        ]
        
        doc_task = pattern.create_task(
            task_name="code_documentation",
            description="Generate concise documentation for Python functions",
            examples=doc_examples,
            example_format=ExampleFormat.LABELED,
            instruction="Describe what the function does in one clear sentence"
        )
        
        pattern.teach_learner("QuickLearner", "code_documentation")
        
        # Test code documentation
        code_inputs = [
            "def factorial(n): return 1 if n == 0 else n * factorial(n-1)",
            "def reverse_string(s): return s[::-1]"
        ]
        
        print("Testing learned task:\n")
        for code_input in code_inputs:
            result = learner.execute_task("code_documentation", code_input)
            print(f"Code: {result.input}")
            print(f"Doc: {result.output}\n")
        
        # Statistics
        print(f"\n{'='*70}")
        print("šŸ“Š Learning Statistics")
        print(f"{'='*70}")
        
        stats = pattern.get_statistics()
        
        print(f"   Total learners: {stats['total_learners']}")
        print(f"   Tasks in library: {stats['tasks_in_library']}")
        
        for learner_name, learner_stats in stats['learners'].items():
            print(f"\n   Learner: {learner_name}")
            print(f"   - Tasks learned: {learner_stats['tasks_learned']}")
            print(f"   - Total executions: {learner_stats['total_executions']}")
            print(f"   - Task details:")
            for task_name, num_examples in learner_stats['tasks'].items():
                print(f"     * {task_name}: {num_examples} examples")
        
        print("\nāœ“ Few-shot learning enabled rapid task adaptation!")
    
        

    Agentic Architecture Pattern: Few Shot Learning

    Pattern 192: 192 Few Shot Learning Pattern – Line-by-Line Explanation

    Overview

    Pattern 192: Few-Shot Learning Pattern

    LLM learns to perform tasks from a small number of examples provided in the prompt. Demonstrates in-context learning where the model adapts based on examples.


    Code Structure Analysis

    File Information

    • Pattern Number: 192
    • Pattern Name: 192 Few Shot Learning Pattern
    • File Path: patterns\llm_specific\192_few_shot_learning_pattern.py
    • Total Lines: 333

    Detailed Code Explanation

    Module Docstring

    """
    Pattern 192: Few-Shot Learning Pattern
    
    LLM learns to perform tasks from a small number of examples provided in the prompt.
    Demonstrates in-context learning where the model adapts based on examples.
    """
    

    Explanation: This module docstring describes the purpose and key features of the 192 Few Shot Learning Pattern pattern.


    Imports Section

    from typing import Dict, Any, List, Optional, Callable
    from dataclasses import dataclass, field
    from datetime import datetime
    from enum import Enum
    from langchain_core.prompts import ChatPromptTemplate, FewShotPromptTemplate, PromptTemplate
    from langchain_core.output_parsers import StrOutputParser
    from langchain_openai import ChatOpenAI  # 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 enum import Enum: Enumeration support for fixed sets of values – from langchain_core.prompts import ChatPromptTemplate, FewShotPromptTemplate, PromptTemplate: LangChain framework integration – from langchain_core.output_parsers import StrOutputParser: LangChain framework integration – from langchain_openai import ChatOpenAI: LangChain framework integration


    Enumerations

    ExampleFormat (Line 17)

    class ExampleFormat(Enum):
        QA_PAIRS
        INPUT_OUTPUT
        DEMONSTRATION
        LABELED
    

    Purpose: Format for few-shot examples.

    Values: – QA_PAIRS: Represents qa pairs – INPUT_OUTPUT: Represents input output – DEMONSTRATION: Represents demonstration – LABELED: Represents labeled


    Classes

    ExampleFormat (Line 17)

    Description: Format for few-shot examples.

    Example (Line 26)

    Description: A single few-shot example.

    FewShotTask (Line 36)

    Description: A task to be performed using few-shot learning.

    FewShotResult (Line 46)

    Description: Result from few-shot learning.

    FewShotLearner (Line 56)

    Description: Agent that learns from few examples.

    Methods:

    __init__ (Line 59)
    def __init__(self, name, model_name, temperature):
        """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”) – temperature: Randomness in LLM responses (0.0-1.0)

    learn_task (Line 65)
    def learn_task(self, task):
        """Learn a new task from examples."""
    

    Purpose: Learn a new task from examples.

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

    create_few_shot_prompt (Line 70)
    def create_few_shot_prompt(self, task, input_text):
        """Create prompt with few-shot examples."""
    

    Purpose: Create prompt with few-shot examples.

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

    execute_task (Line 121)
    def execute_task(self, task_name, input_text):
        """Execute learned task on new input."""
    

    Purpose: Execute learned task on new input.

    Parameters: – self: Instance reference – task_name: Parameter for task_name – input_text: Parameter for input_text

    get_statistics (Line 148)
    def get_statistics(self):
        """Get learning statistics."""
    

    Purpose: Get learning statistics.

    Parameters: – self: Instance reference

    FewShotLearningPattern (Line 158)

    Description: Few-Shot Learning Pattern – Learn tasks from small number of examples.

    Enables LLMs to quickly adapt to new tasks by providing a few demonstration examples in the prompt context.

    Methods:

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

    Purpose: No method docstring.

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

    create_learner (Line 171)
    def create_learner(self, name):
        """Create a few-shot learner."""
    

    Purpose: Create a few-shot learner.

    Parameters: – self: Instance reference – name: Identifier or label

    register_task (Line 177)
    def register_task(self, task):
        """Register a task in the library."""
    

    Purpose: Register a task in the library.

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

    create_task (Line 182)
    def create_task(self, task_name, description, examples, example_format, instruction):
        """Create and register a task."""
    

    Purpose: Create and register a task.

    Parameters: – self: Instance reference – task_name: Parameter for task_name – description: Parameter for description – examples: Parameter for examples – example_format: Parameter for example_format – instruction: Parameter for instruction

    teach_learner (Line 196)
    def teach_learner(self, learner_name, task_name):
        """Teach a task to a learner."""
    

    Purpose: Teach a task to a learner.

    Parameters: – self: Instance reference – learner_name: Parameter for learner_name – task_name: Parameter for task_name

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

    Purpose: Get pattern statistics.

    Parameters: – self: Instance reference


    Design Patterns Used

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

    Usage Example

    # Initialize the pattern
    pattern = ExampleFormat(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: Prompt Engineering

    
        """
    Pattern 191: Prompt Engineering Pattern
    
    Systematic design and optimization of prompts for LLMs.
    Implements multiple prompt engineering techniques for effective LLM interaction.
    """
    
    from typing import Dict, Any, List, Optional, Callable
    from dataclasses import dataclass, field
    from datetime import datetime
    from enum import Enum
    from langchain_core.prompts import ChatPromptTemplate, PromptTemplate
    from langchain_core.output_parsers import StrOutputParser
    from langchain_openai import ChatOpenAI
    
    
    class PromptTechnique(Enum):
        """Prompt engineering techniques."""
        ZERO_SHOT = "zero_shot"
        FEW_SHOT = "few_shot"
        CHAIN_OF_THOUGHT = "chain_of_thought"
        ROLE_BASED = "role_based"
        TEMPLATE = "template"
        STRUCTURED = "structured"
    
    
    @dataclass
    class PromptExample:
        """Example for few-shot learning."""
        input: str
        output: str
        explanation: Optional[str] = None
    
    
    @dataclass
    class PromptTemplate:
        """Prompt template with variables."""
        name: str
        technique: PromptTechnique
        system_message: str
        user_template: str
        variables: List[str]
        examples: List[PromptExample] = field(default_factory=list)
        output_format: Optional[str] = None
    
    
    @dataclass
    class PromptResult:
        """Result of prompt execution."""
        prompt_used: str
        technique: PromptTechnique
        response: str
        metadata: Dict[str, Any] = field(default_factory=dict)
        timestamp: datetime = field(default_factory=datetime.now)
    
    
    class PromptEngineer:
        """Engineer with multiple prompt techniques."""
        
        def __init__(self, model_name: str = "gpt-4", temperature: float = 0.7):
            self.llm = ChatOpenAI(model=model_name, temperature=temperature)
            self.templates: Dict[str, PromptTemplate] = {}
            self.results: List[PromptResult] = []
        
        def create_zero_shot_prompt(self, task: str, context: Optional[str] = None) -> str:
            """Create zero-shot prompt."""
            if context:
                return f"Context: {context}\n\nTask: {task}\n\nProvide a clear and comprehensive answer."
            return f"Task: {task}\n\nProvide a clear and comprehensive answer."
        
        def create_few_shot_prompt(self, task: str, examples: List[PromptExample]) -> str:
            """Create few-shot prompt with examples."""
            prompt_parts = ["Here are some examples:\n"]
            
            for i, ex in enumerate(examples, 1):
                prompt_parts.append(f"\nExample {i}:")
                prompt_parts.append(f"Input: {ex.input}")
                prompt_parts.append(f"Output: {ex.output}")
                if ex.explanation:
                    prompt_parts.append(f"Why: {ex.explanation}")
            
            prompt_parts.append(f"\n\nNow, apply the same pattern:")
            prompt_parts.append(f"Input: {task}")
            prompt_parts.append("Output:")
            
            return "\n".join(prompt_parts)
        
        def create_chain_of_thought_prompt(self, task: str) -> str:
            """Create chain-of-thought prompt."""
            return (f"{task}\n\n"
                    f"Let's approach this step-by-step:\n"
                    f"1. First, identify the key components\n"
                    f"2. Then, analyze the relationships\n"
                    f"3. Finally, synthesize the answer\n\n"
                    f"Think through each step carefully:")
        
        def create_role_based_prompt(self, task: str, role: str, expertise: List[str]) -> str:
            """Create role-based prompt."""
            expertise_text = ", ".join(expertise)
            return (f"You are a {role} with expertise in {expertise_text}. "
                    f"Use your specialized knowledge to address this:\n\n{task}")
        
        def execute_prompt(self, prompt: str, technique: PromptTechnique, 
                          system_message: Optional[str] = None) -> PromptResult:
            """Execute prompt and return result."""
            messages = []
            
            if system_message:
                messages.append(("system", system_message))
            
            messages.append(("human", prompt))
            
            chat_prompt = ChatPromptTemplate.from_messages(messages)
            chain = chat_prompt | self.llm | StrOutputParser()
            
            response = chain.invoke({})
            
            result = PromptResult(
                prompt_used=prompt,
                technique=technique,
                response=response,
                metadata={"system_message": system_message}
            )
            
            self.results.append(result)
            return result
        
        def register_template(self, template: PromptTemplate):
            """Register a reusable prompt template."""
            self.templates[template.name] = template
        
        def use_template(self, template_name: str, **kwargs) -> PromptResult:
            """Use a registered template with variables."""
            if template_name not in self.templates:
                raise ValueError(f"Template '{template_name}' not found")
            
            template = self.templates[template_name]
            
            # Substitute variables
            prompt = template.user_template
            for var in template.variables:
                if var in kwargs:
                    prompt = prompt.replace(f"{{{var}}}", str(kwargs[var]))
            
            # Add examples if few-shot
            if template.technique == PromptTechnique.FEW_SHOT and template.examples:
                prompt = self.create_few_shot_prompt(prompt, template.examples)
            
            # Add output format if specified
            if template.output_format:
                prompt += f"\n\nOutput format: {template.output_format}"
            
            return self.execute_prompt(prompt, template.technique, template.system_message)
    
    
    class PromptEngineeringPattern:
        """
        Prompt Engineering Pattern - Systematic prompt design and optimization.
        
        Provides multiple techniques for crafting effective prompts including
        zero-shot, few-shot, chain-of-thought, and role-based prompting.
        """
        
        def __init__(self, model_name: str = "gpt-4"):
            self.engineer = PromptEngineer(model_name)
            self.technique_usage: Dict[PromptTechnique, int] = {t: 0 for t in PromptTechnique}
        
        def zero_shot(self, task: str, context: Optional[str] = None) -> PromptResult:
            """Execute zero-shot prompting."""
            prompt = self.engineer.create_zero_shot_prompt(task, context)
            result = self.engineer.execute_prompt(prompt, PromptTechnique.ZERO_SHOT)
            self.technique_usage[PromptTechnique.ZERO_SHOT] += 1
            return result
        
        def few_shot(self, task: str, examples: List[PromptExample]) -> PromptResult:
            """Execute few-shot prompting."""
            prompt = self.engineer.create_few_shot_prompt(task, examples)
            result = self.engineer.execute_prompt(prompt, PromptTechnique.FEW_SHOT)
            self.technique_usage[PromptTechnique.FEW_SHOT] += 1
            return result
        
        def chain_of_thought(self, task: str) -> PromptResult:
            """Execute chain-of-thought prompting."""
            prompt = self.engineer.create_chain_of_thought_prompt(task)
            result = self.engineer.execute_prompt(
                prompt, 
                PromptTechnique.CHAIN_OF_THOUGHT,
                "You are a careful thinker who explains reasoning step-by-step."
            )
            self.technique_usage[PromptTechnique.CHAIN_OF_THOUGHT] += 1
            return result
        
        def role_based(self, task: str, role: str, expertise: List[str]) -> PromptResult:
            """Execute role-based prompting."""
            prompt = self.engineer.create_role_based_prompt(task, role, expertise)
            result = self.engineer.execute_prompt(prompt, PromptTechnique.ROLE_BASED)
            self.technique_usage[PromptTechnique.ROLE_BASED] += 1
            return result
        
        def create_template(self, name: str, technique: PromptTechnique, 
                           system_message: str, user_template: str, 
                           variables: List[str], **kwargs) -> PromptTemplate:
            """Create and register a prompt template."""
            template = PromptTemplate(
                name=name,
                technique=technique,
                system_message=system_message,
                user_template=user_template,
                variables=variables,
                examples=kwargs.get('examples', []),
                output_format=kwargs.get('output_format')
            )
            self.engineer.register_template(template)
            return template
        
        def get_statistics(self) -> Dict[str, Any]:
            """Get usage statistics."""
            total = sum(self.technique_usage.values())
            
            return {
                "total_prompts": total,
                "techniques_used": {t.value: count for t, count in self.technique_usage.items() if count > 0},
                "unique_templates": len(self.engineer.templates),
                "avg_response_length": sum(len(r.response) for r in self.engineer.results) / max(len(self.engineer.results), 1)
            }
    
    
    # Example usage
    if __name__ == "__main__":
        print("=== Prompt Engineering Pattern Demo ===\n")
        
        # Create pattern
        print("1. Creating prompt engineering pattern...")
        pattern = PromptEngineeringPattern()
        
        # Test zero-shot
        print(f"\n{'='*70}")
        print("šŸ“ Zero-Shot Prompting")
        print(f"{'='*70}\n")
        
        result = pattern.zero_shot(
            "Explain the concept of 'emergence' in complex systems",
            context="Focus on practical examples"
        )
        print(f"Task: Explain emergence")
        print(f"Technique: {result.technique.value}")
        print(f"Response: {result.response[:200]}...\n")
        
        # Test few-shot
        print(f"\n{'='*70}")
        print("šŸ“š Few-Shot Prompting")
        print(f"{'='*70}\n")
        
        examples = [
            PromptExample(
                input="What is photosynthesis?",
                output="Photosynthesis is the process plants use to convert light energy into chemical energy (glucose).",
                explanation="Simple, clear definition with key components"
            ),
            PromptExample(
                input="What is mitosis?",
                output="Mitosis is cell division that produces two identical daughter cells from one parent cell.",
                explanation="Concise explanation of the core process"
            )
        ]
        
        result = pattern.few_shot("What is osmosis?", examples)
        print(f"Task: What is osmosis?")
        print(f"Technique: {result.technique.value}")
        print(f"Examples provided: {len(examples)}")
        print(f"Response: {result.response[:200]}...\n")
        
        # Test chain-of-thought
        print(f"\n{'='*70}")
        print("šŸ”— Chain-of-Thought Prompting")
        print(f"{'='*70}\n")
        
        result = pattern.chain_of_thought(
            "If a store has a 20% discount and then adds 8% sales tax, "
            "how much would a $50 item cost?"
        )
        print(f"Task: Calculate final price with discount and tax")
        print(f"Technique: {result.technique.value}")
        print(f"Response: {result.response[:300]}...\n")
        
        # Test role-based
        print(f"\n{'='*70}")
        print("šŸŽ­ Role-Based Prompting")
        print(f"{'='*70}\n")
        
        result = pattern.role_based(
            "How should I optimize database queries for a high-traffic application?",
            role="Senior Database Administrator",
            expertise=["SQL optimization", "indexing strategies", "query planning"]
        )
        print(f"Task: Database optimization advice")
        print(f"Technique: {result.technique.value}")
        print(f"Role: Senior Database Administrator")
        print(f"Response: {result.response[:200]}...\n")
        
        # Create and use template
        print(f"\n{'='*70}")
        print("šŸ“‹ Template-Based Prompting")
        print(f"{'='*70}\n")
        
        template = pattern.create_template(
            name="code_review",
            technique=PromptTechnique.STRUCTURED,
            system_message="You are an expert code reviewer focusing on best practices.",
            user_template="Review this {language} code for {aspect}:\n\n{code}",
            variables=["language", "aspect", "code"],
            output_format="1. Issues found\n2. Recommendations\n3. Severity"
        )
        
        result = pattern.engineer.use_template(
            "code_review",
            language="Python",
            aspect="performance and readability",
            code="def calc(x):\n    return [i*2 for i in range(x)]"
        )
        
        print(f"Template: {template.name}")
        print(f"Response: {result.response[:200]}...\n")
        
        # Statistics
        print(f"\n{'='*70}")
        print("šŸ“Š Usage Statistics")
        print(f"{'='*70}")
        
        stats = pattern.get_statistics()
        
        print(f"   Total prompts executed: {stats['total_prompts']}")
        print(f"   Unique templates created: {stats['unique_templates']}")
        print(f"   Avg response length: {stats['avg_response_length']:.0f} chars")
        
        print(f"\n   Techniques used:")
        for technique, count in stats['techniques_used'].items():
            print(f"   - {technique}: {count} times")
        
        print("\nāœ“ Prompt engineering pattern demonstrated multiple techniques!")
    
        

    Agentic Architecture Pattern: Prompt Engineering

    Pattern 191: 191 Prompt Engineering Pattern – Line-by-Line Explanation

    Overview

    Pattern 191: Prompt Engineering Pattern

    Systematic design and optimization of prompts for LLMs. Implements multiple prompt engineering techniques for effective LLM interaction.


    Code Structure Analysis

    File Information

    • Pattern Number: 191
    • Pattern Name: 191 Prompt Engineering Pattern
    • File Path: patterns\llm_specific\191_prompt_engineering_pattern.py
    • Total Lines: 341

    Detailed Code Explanation

    Module Docstring

    """
    Pattern 191: Prompt Engineering Pattern
    
    Systematic design and optimization of prompts for LLMs.
    Implements multiple prompt engineering techniques for effective LLM interaction.
    """
    

    Explanation: This module docstring describes the purpose and key features of the 191 Prompt Engineering Pattern pattern.


    Imports Section

    from typing import Dict, Any, List, Optional, Callable
    from dataclasses import dataclass, field
    from datetime import datetime
    from enum import Enum
    from langchain_core.prompts import ChatPromptTemplate, PromptTemplate
    from langchain_core.output_parsers import StrOutputParser
    from langchain_openai import ChatOpenAI  # 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 enum import Enum: Enumeration support for fixed sets of values – from langchain_core.prompts import ChatPromptTemplate, PromptTemplate: LangChain framework integration – from langchain_core.output_parsers import StrOutputParser: LangChain framework integration – from langchain_openai import ChatOpenAI: LangChain framework integration


    Enumerations

    PromptTechnique (Line 17)

    class PromptTechnique(Enum):
        ZERO_SHOT
        FEW_SHOT
        CHAIN_OF_THOUGHT
        ROLE_BASED
        TEMPLATE
        STRUCTURED
    

    Purpose: Prompt engineering techniques.

    Values: – ZERO_SHOT: Represents zero shot – FEW_SHOT: Represents few shot – CHAIN_OF_THOUGHT: Represents chain of thought – ROLE_BASED: Represents role based – TEMPLATE: Represents template – STRUCTURED: Represents structured


    Classes

    PromptTechnique (Line 17)

    Description: Prompt engineering techniques.

    PromptExample (Line 28)

    Description: Example for few-shot learning.

    PromptTemplate (Line 36)

    Description: Prompt template with variables.

    PromptResult (Line 48)

    Description: Result of prompt execution.

    PromptEngineer (Line 57)

    Description: Engineer with multiple prompt techniques.

    Methods:

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

    Purpose: No method docstring.

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

    create_zero_shot_prompt (Line 65)
    def create_zero_shot_prompt(self, task, context):
        """Create zero-shot prompt."""
    

    Purpose: Create zero-shot prompt.

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

    create_few_shot_prompt (Line 71)
    def create_few_shot_prompt(self, task, examples):
        """Create few-shot prompt with examples."""
    

    Purpose: Create few-shot prompt with examples.

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

    create_chain_of_thought_prompt (Line 88)
    def create_chain_of_thought_prompt(self, task):
        """Create chain-of-thought prompt."""
    

    Purpose: Create chain-of-thought prompt.

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

    create_role_based_prompt (Line 97)
    def create_role_based_prompt(self, task, role, expertise):
        """Create role-based prompt."""
    

    Purpose: Create role-based prompt.

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

    execute_prompt (Line 103)
    def execute_prompt(self, prompt, technique, system_message):
        """Execute prompt and return result."""
    

    Purpose: Execute prompt and return result.

    Parameters: – self: Instance reference – prompt: Parameter for prompt – technique: Parameter for technique – system_message: Parameter for system_message

    register_template (Line 128)
    def register_template(self, template):
        """Register a reusable prompt template."""
    

    Purpose: Register a reusable prompt template.

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

    use_template (Line 132)
    def use_template(self, template_name):
        """Use a registered template with variables."""
    

    Purpose: Use a registered template with variables.

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

    PromptEngineeringPattern (Line 156)

    Description: Prompt Engineering Pattern – Systematic prompt design and optimization.

    Provides multiple techniques for crafting effective prompts including zero-shot, few-shot, chain-of-thought, and role-based prompting.

    Methods:

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

    zero_shot (Line 168)
    def zero_shot(self, task, context):
        """Execute zero-shot prompting."""
    

    Purpose: Execute zero-shot prompting.

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

    few_shot (Line 175)
    def few_shot(self, task, examples):
        """Execute few-shot prompting."""
    

    Purpose: Execute few-shot prompting.

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

    chain_of_thought (Line 182)
    def chain_of_thought(self, task):
        """Execute chain-of-thought prompting."""
    

    Purpose: Execute chain-of-thought prompting.

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

    role_based (Line 193)
    def role_based(self, task, role, expertise):
        """Execute role-based prompting."""
    

    Purpose: Execute role-based prompting.

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

    create_template (Line 200)
    def create_template(self, name, technique, system_message, user_template, variables):
        """Create and register a prompt template."""
    

    Purpose: Create and register a prompt template.

    Parameters: – self: Instance reference – name: Identifier or label – technique: Parameter for technique – system_message: Parameter for system_message – user_template: Parameter for user_template – variables: Parameter for variables

    get_statistics (Line 216)
    def get_statistics(self):
        """Get usage statistics."""
    

    Purpose: Get usage statistics.

    Parameters: – self: Instance reference


    Design Patterns Used

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

    Usage Example

    # Initialize the pattern
    pattern = PromptTechnique(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