"""
Pattern 204: Inductive Reasoning Pattern
Reasons from specific observations to general principles through pattern
recognition and generalization. Infers general rules from examples.
"""
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 Observation:
"""Single observation/example."""
description: str
attributes: Dict[str, Any]
timestamp: datetime = field(default_factory=datetime.now)
@dataclass
class GeneralPrinciple:
"""Inferred general principle."""
principle: str
confidence: float # 0.0 to 1.0
supporting_observations: List[Observation]
counter_examples: List[Observation] = field(default_factory=list)
class InductiveReasoningAgent:
"""Agent that performs inductive reasoning."""
def __init__(self, name: str, model_name: str = "gpt-4"):
self.name = name
self.llm = ChatOpenAI(model=model_name, temperature=0.3)
self.observations: List[Observation] = []
self.principles: List[GeneralPrinciple] = []
def add_observation(self, observation: Observation):
"""Add new observation."""
self.observations.append(observation)
print(f" {self.name}: Added observation - {observation.description}")
def induce_principles(self) -> List[GeneralPrinciple]:
"""Induce general principles from observations."""
print(f"\n {self.name}: Inducing principles from {len(self.observations)} observations...")
if len(self.observations) 2 else ""
# Parse supporting observation indices
supporting_obs = []
for idx_str in indices_str.split(","):
try:
idx = int(idx_str.strip()) - 1
if 0 <= idx bool:
"""Test if principle applies to new observation."""
prompt = ChatPromptTemplate.from_messages([
("system", "Determine if a general principle applies to a new observation."),
("human", """General Principle: {principle}
New Observation: {observation}
Attributes: {attributes}
Does this principle apply? Answer YES or NO with brief explanation.""")
])
chain = prompt | self.llm
response = chain.invoke({
"principle": principle.principle,
"observation": test_observation.description,
"attributes": str(test_observation.attributes)
})
result = "YES" in response.content.upper()
if result:
principle.supporting_observations.append(test_observation)
else:
principle.counter_examples.append(test_observation)
return result
class InductiveReasoningPattern:
"""
Inductive Reasoning Pattern - From specific to general.
Collects observations, identifies patterns, induces general principles,
and tests them against new observations.
"""
def __init__(self):
self.agents: Dict[str, InductiveReasoningAgent] = {}
def register_agent(self, agent: InductiveReasoningAgent):
"""Register inductive reasoning agent."""
self.agents[agent.name] = agent
def run(self, observations: List[Observation],
test_cases: Optional[List[Observation]] = None) -> Dict[str, Any]:
"""Execute inductive reasoning process."""
print("=== Inductive Reasoning Pattern ===\n")
for agent in self.agents.values():
# Add observations
print(f"{agent.name}: Collecting observations...")
for obs in observations:
agent.add_observation(obs)
# Induce principles
principles = agent.induce_principles()
# Test principles if test cases provided
if test_cases:
print(f"\n Testing principles with new observations...")
for test_obs in test_cases:
print(f"\n Test: {test_obs.description}")
for i, principle in enumerate(principles, 1):
result = agent.test_principle(principle, test_obs)
print(f" Principle {i}: {'✓ Applies' if result else '✗ Does not apply'}")
return {
"pattern": "InductiveReasoning",
"agents": len(self.agents),
"total_observations": sum(len(a.observations) for a in self.agents.values()),
"total_principles": sum(len(a.principles) for a in self.agents.values())
}
# Example usage
if __name__ == "__main__":
print("=== Inductive Reasoning Pattern Demo ===\n")
# Create pattern and agent
pattern = InductiveReasoningPattern()
agent = InductiveReasoningAgent("Scientist")
pattern.register_agent(agent)
# Training observations (specific examples)
print("1. Collecting specific observations...\n")
observations = [
Observation("The swan in the park is white", {"color": "white", "animal": "swan"}),
Observation("Another swan at the lake is white", {"color": "white", "animal": "swan"}),
Observation("The swan at the zoo is also white", {"color": "white", "animal": "swan"}),
Observation("Swans in the book pictures are white", {"color": "white", "animal": "swan"}),
Observation("Heated metal expands", {"temperature": "hot", "material": "metal", "state": "expanded"}),
Observation("Heated water expands", {"temperature": "hot", "material": "water", "state": "expanded"}),
Observation("Heated air expands", {"temperature": "hot", "material": "air", "state": "expanded"}),
]
# Test cases (new observations)
test_cases = [
Observation("A black swan in Australia", {"color": "black", "animal": "swan"}),
Observation("Heated plastic expands", {"temperature": "hot", "material": "plastic", "state": "expanded"}),
]
# Run inductive reasoning
summary = pattern.run(observations, test_cases)
print(f"\n2. Summary:")
print(f" Total observations: {summary['total_observations']}")
print(f" Principles induced: {summary['total_principles']}")
print(f"\n3. Induced Principles:")
for i, principle in enumerate(agent.principles, 1):
print(f" {i}. {principle.principle}")
print(f" Confidence: {principle.confidence}")
print(f" Supported by: {len(principle.supporting_observations)} observations")
print(f" Counter-examples: {len(principle.counter_examples)}")
print("\n✓ Inductive reasoning: specific observations → general principles!")
Agentic Architecture Pattern: Inductive Reasoning
Pattern 204: 204 Inductive Reasoning Pattern – Line-by-Line Explanation
Overview
Pattern 204: Inductive Reasoning Pattern
Reasons from specific observations to general principles through pattern recognition and generalization. Infers general rules from examples.
Code Structure Analysis
File Information
- Pattern Number: 204
- Pattern Name: 204 Inductive Reasoning Pattern
- File Path:
patterns\advanced_reasoning\204_inductive_reasoning_pattern.py - Total Lines: 231
Detailed Code Explanation
Module Docstring
"""
Pattern 204: Inductive Reasoning Pattern
Reasons from specific observations to general principles through pattern
recognition and generalization. Infers general rules from examples.
"""
Explanation: This module docstring describes the purpose and key features of the 204 Inductive Reasoning 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
Observation (Line 16)
Description: Single observation/example.
GeneralPrinciple (Line 24)
Description: Inferred general principle.
InductiveReasoningAgent (Line 32)
Description: Agent that performs inductive reasoning.
Methods:
__init__ (Line 35)
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_observation (Line 41)
def add_observation(self, observation):
"""Add new observation."""
Purpose: Add new observation.
Parameters:
– self: Instance reference
– observation: Parameter for observation
induce_principles (Line 46)
def induce_principles(self):
"""Induce general principles from observations."""
Purpose: Induce general principles from observations.
Parameters:
– self: Instance reference
test_principle (Line 114)
def test_principle(self, principle, test_observation):
"""Test if principle applies to new observation."""
Purpose: Test if principle applies to new observation.
Parameters:
– self: Instance reference
– principle: Parameter for principle
– test_observation: Parameter for test_observation
InductiveReasoningPattern (Line 143)
Description: Inductive Reasoning Pattern – From specific to general.
Collects observations, identifies patterns, induces general principles, and tests them against new observations.
Methods:
__init__ (Line 151)
def __init__(self):
"""No method docstring."""
Purpose: No method docstring.
Parameters:
– self: Instance reference
register_agent (Line 154)
def register_agent(self, agent):
"""Register inductive reasoning agent."""
Purpose: Register inductive reasoning agent.
Parameters:
– self: Instance reference
– agent: Parameter for agent
run (Line 158)
def run(self, observations, test_cases):
"""Execute inductive reasoning process."""
Purpose: Execute inductive reasoning process.
Parameters:
– self: Instance reference
– observations: Parameter for observations
– test_cases: Parameter for test_cases
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 = Observation(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