Agentic Architecture Pattern: Deductive Reasoning

Written by

in


    """
Pattern 203: Deductive Reasoning Pattern

Applies general rules to specific cases to draw logical conclusions.
If premises are true, conclusion must be true (valid deduction).
"""

from typing import Dict, Any, List
from dataclasses import dataclass
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI


@dataclass
class Premise:
    """A premise in deductive reasoning."""
    statement: str
    premise_type: str = "general"  # general, specific, conditional


@dataclass
class DeductiveArgument:
    """A deductive argument."""
    premises: List[Premise]
    conclusion: str
    is_valid: bool = False
    explanation: str = ""


class DeductiveReasoningPattern:
    """
    Deductive Reasoning Pattern - Logical inference from premises.
    
    Applies formal logic: given premises, deduce valid conclusions.
    Checks validity of arguments.
    """
    
    def __init__(self, model_name: str = "gpt-4"):
        self.llm = ChatOpenAI(model=model_name, temperature=0.3)
        self.arguments: List[DeductiveArgument] = []
    
    def apply_modus_ponens(self, conditional: str, antecedent: str) -> str:
        """Apply modus ponens: If P then Q, P is true, therefore Q."""
        prompt = ChatPromptTemplate.from_messages([
            ("system", "Apply modus ponens deduction: If P then Q, and P is true, then Q must be true."),
            ("human", """Conditional: {conditional}
Antecedent: {antecedent}

What can we deduce? Provide the conclusion:""")
        ])
        
        chain = prompt | self.llm
        response = chain.invoke({"conditional": conditional, "antecedent": antecedent})
        return response.content
    
    def validate_argument(self, premises: List[str], conclusion: str) -> DeductiveArgument:
        """Validate a deductive argument."""
        print(f"\n=== Validating Deductive Argument ===")
        print(f"Premises: {len(premises)}")
        
        prompt = ChatPromptTemplate.from_messages([
            ("system", "Analyze if the conclusion logically follows from the premises. "
                      "Check for validity using formal logic rules."),
            ("human", """Premises:
{premises}

Proposed Conclusion: {conclusion}

Is this argument valid? Respond: VALID or INVALID|explanation""")
        ])
        
        chain = prompt | self.llm
        response = chain.invoke({
            "premises": "\n".join([f"{i+1}. {p}" for i, p in enumerate(premises)]),
            "conclusion": conclusion
        })
        
        # Parse validity
        content = response.content.strip()
        is_valid = content.startswith("VALID")
        
        parts = content.split('|')
        explanation = parts[1].strip() if len(parts) > 1 else content
        
        argument = DeductiveArgument(
            premises=[Premise(p) for p in premises],
            conclusion=conclusion,
            is_valid=is_valid,
            explanation=explanation
        )
        
        self.arguments.append(argument)
        
        print(f"Validity: {'VALID' if is_valid else 'INVALID'}")
        return argument
    
    def run(self, premises: List[str], conclusion: str) -> Dict[str, Any]:
        """Perform deductive reasoning."""
        print(f"\n=== Deductive Reasoning Pattern ===")
        
        argument = self.validate_argument(premises, conclusion)
        
        return {
            "pattern": "DeductiveReasoning",
            "premises": premises,
            "conclusion": conclusion,
            "is_valid": argument.is_valid,
            "explanation": argument.explanation
        }


# Example usage
if __name__ == "__main__":
    print("=== Deductive Reasoning Pattern Demo ===\n")
    
    pattern = DeductiveReasoningPattern()
    
    # Classic syllogism
    print("Example 1: Classic Syllogism")
    result1 = pattern.run(
        premises=[
            "All humans are mortal",
            "Socrates is a human"
        ],
        conclusion="Socrates is mortal"
    )
    print(f"Valid: {result1['is_valid']}")
    print(f"Explanation: {result1['explanation']}")
    
    # Modus ponens
    print("\n" + "="*60)
    print("Example 2: Modus Ponens")
    result2 = pattern.run(
        premises=[
            "If it rains, the ground gets wet",
            "It is raining"
        ],
        conclusion="The ground is wet"
    )
    print(f"Valid: {result2['is_valid']}")
    
    # Invalid argument
    print("\n" + "="*60)
    print("Example 3: Invalid Argument (Affirming the consequent)")
    result3 = pattern.run(
        premises=[
            "If it rains, the ground gets wet",
            "The ground is wet"
        ],
        conclusion="It rained"
    )
    print(f"Valid: {result3['is_valid']}")
    print(f"Explanation: {result3['explanation']}")
    
    print("\nāœ“ Deductive reasoning completed!")

    

Agentic Architecture Pattern: Deductive Reasoning

Pattern 203: 203 Deductive Reasoning Pattern – Line-by-Line Explanation

Overview

Pattern 203: Deductive Reasoning Pattern

Applies general rules to specific cases to draw logical conclusions. If premises are true, conclusion must be true (valid deduction).


Code Structure Analysis

File Information

  • Pattern Number: 203
  • Pattern Name: 203 Deductive Reasoning Pattern
  • File Path: patterns\advanced_reasoning\203_deductive_reasoning_pattern.py
  • Total Lines: 156

Detailed Code Explanation

Module Docstring

"""
Pattern 203: Deductive Reasoning Pattern

Applies general rules to specific cases to draw logical conclusions.
If premises are true, conclusion must be true (valid deduction).
"""

Explanation: This module docstring describes the purpose and key features of the 203 Deductive Reasoning Pattern pattern.


Imports Section

from typing import Dict, Any, List
from dataclasses import dataclass
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: Type hints for better code documentation – from dataclasses import dataclass: Data class decorators for clean data structures – from langchain_core.prompts import ChatPromptTemplate: LangChain framework integration – from langchain_openai import ChatOpenAI: LangChain framework integration


Classes

Premise (Line 15)

Description: A premise in deductive reasoning.

DeductiveArgument (Line 22)

Description: A deductive argument.

DeductiveReasoningPattern (Line 30)

Description: Deductive Reasoning Pattern – Logical inference from premises.

Applies formal logic: given premises, deduce valid conclusions. Checks validity of arguments.

Methods:

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

apply_modus_ponens (Line 42)
def apply_modus_ponens(self, conditional, antecedent):
    """Apply modus ponens: If P then Q, P is true, therefore Q."""

Purpose: Apply modus ponens: If P then Q, P is true, therefore Q.

Parameters: – self: Instance reference – conditional: Parameter for conditional – antecedent: Parameter for antecedent

validate_argument (Line 56)
def validate_argument(self, premises, conclusion):
    """Validate a deductive argument."""

Purpose: Validate a deductive argument.

Parameters: – self: Instance reference – premises: Parameter for premises – conclusion: Parameter for conclusion

run (Line 97)
def run(self, premises, conclusion):
    """Perform deductive reasoning."""

Purpose: Perform deductive reasoning.

Parameters: – self: Instance reference – premises: Parameter for premises – conclusion: Parameter for conclusion


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 = Premise(name="example", model_name="gpt-4")

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

# Check results
print(result)

Key Concepts

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

Extension Points

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

Comments

Leave a Reply

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