"""
Pattern 112: Common Sense Reasoning
Description:
Common Sense Reasoning enables agents to apply implicit, everyday knowledge
that humans take for granted. This pattern integrates common sense knowledge
bases (like ConceptNet) with LLM reasoning to make inferences about the
physical world, social norms, causality, and typical behaviors.
The pattern helps agents understand context, make reasonable assumptions,
avoid absurd conclusions, and reason about unstated but obvious facts.
It bridges the gap between explicit knowledge and implicit understanding.
Key Components:
1. Knowledge Base: ConceptNet or similar common sense KB
2. Reasoning Engine: Inference over common sense facts
3. Context Integrator: Applies common sense to situations
4. Plausibility Checker: Validates conclusions
5. Assumption Generator: Makes reasonable assumptions
Common Sense Categories:
- Physical: Objects fall down, water is wet
- Social: Greetings are polite, lying is wrong
- Causal: Rain makes things wet, fire causes heat
- Temporal: Events have order, time moves forward
- Spatial: Objects can't be in two places
- Functional: Tools have purposes, actions have effects
Use Cases:
- Natural language understanding
- Story comprehension and generation
- Situation interpretation
- Question answering with implicit knowledge
- Robotics and embodied AI
LangChain Implementation:
Uses ConceptNet integration, reasoning chains, and validation logic to
apply common sense knowledge to agent reasoning.
"""
import os
from typing import List, Dict, Any, Optional, Tuple
from dotenv import load_dotenv
from datetime import datetime
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser, JsonOutputParser
from langchain.chains import LLMChain
load_dotenv()
class CommonSenseKnowledgeBase:
"""Simulated common sense knowledge base (in practice, use ConceptNet API)"""
def __init__(self):
self.knowledge = {
# Physical laws
"gravity": "Objects fall downward when dropped",
"water_wet": "Water makes things wet",
"fire_hot": "Fire is hot and can burn",
"ice_cold": "Ice is cold and can freeze",
"glass_fragile": "Glass is fragile and can break",
# Social norms
"greeting_polite": "Greeting people is considered polite",
"stealing_wrong": "Taking things without permission is wrong",
"helping_good": "Helping others is generally good",
"lying_negative": "Lying usually has negative consequences",
# Causal relationships
"rain_wet": "Rain makes outdoor surfaces wet",
"eating_hunger": "Eating satisfies hunger",
"sleep_rest": "Sleep provides rest and recovery",
"exercise_fitness": "Exercise improves fitness",
# Temporal facts
"time_forward": "Time moves forward, not backward",
"aging_continuous": "Living things age continuously",
"seasons_cycle": "Seasons cycle in a predictable pattern",
# Spatial facts
"one_place": "Physical objects can't be in two places at once",
"inside_outside": "Something inside a closed container is not outside",
"solid_through": "Solid objects can't pass through solid walls",
# Functional knowledge
"key_lock": "Keys are used to open locks",
"knife_cut": "Knives are used for cutting",
"chair_sit": "Chairs are for sitting on",
"umbrella_rain": "Umbrellas protect from rain",
}
self.categories = {
"physical": ["gravity", "water_wet", "fire_hot", "ice_cold", "glass_fragile"],
"social": ["greeting_polite", "stealing_wrong", "helping_good", "lying_negative"],
"causal": ["rain_wet", "eating_hunger", "sleep_rest", "exercise_fitness"],
"temporal": ["time_forward", "aging_continuous", "seasons_cycle"],
"spatial": ["one_place", "inside_outside", "solid_through"],
"functional": ["key_lock", "knife_cut", "chair_sit", "umbrella_rain"],
}
def query(self, concept: str) -> Optional[str]:
"""Query knowledge base for common sense fact"""
return self.knowledge.get(concept)
def get_category(self, category: str) -> List[str]:
"""Get all facts in a category"""
concept_ids = self.categories.get(category, [])
return [self.knowledge[cid] for cid in concept_ids if cid in self.knowledge]
def get_relevant_facts(self, context: str) -> List[str]:
"""Get facts relevant to context"""
# Simple keyword matching (in practice, use embeddings)
relevant = []
context_lower = context.lower()
for key, fact in self.knowledge.items():
if any(word in context_lower for word in key.split("_")):
relevant.append(fact)
return relevant
class CommonSenseReasoner:
"""Agent that applies common sense reasoning"""
def __init__(self, model_name: str = "gpt-4"):
self.llm = ChatOpenAI(model=model_name, temperature=0.7)
self.kb = CommonSenseKnowledgeBase()
# Reasoning with common sense
self.reasoning_prompt = ChatPromptTemplate.from_messages([
("system", """You are a reasoning agent that applies common sense knowledge.
Given a question or situation, use the provided common sense facts to reason
about the answer. Make reasonable assumptions based on everyday knowledge.
Common sense facts:
{facts}
Question: {question}
Provide your reasoning and answer:"""),
("human", "{question}")
])
# Plausibility checking
self.plausibility_prompt = ChatPromptTemplate.from_messages([
("system", """Evaluate if a conclusion is plausible based on common sense.
Common sense facts:
{facts}
Proposed conclusion: {conclusion}
Rate plausibility from 0-10 and explain why:"""),
("human", "{conclusion}")
])
# Assumption generation
self.assumption_prompt = ChatPromptTemplate.from_messages([
("system", """Given a scenario, generate reasonable assumptions based on common sense.
Scenario: {scenario}
List 5 reasonable assumptions that most people would make:"""),
("human", "{scenario}")
])
self.reasoning_chain = self.reasoning_prompt | self.llm | StrOutputParser()
self.plausibility_chain = self.plausibility_prompt | self.llm | StrOutputParser()
self.assumption_chain = self.assumption_prompt | self.llm | StrOutputParser()
def reason_with_common_sense(self, question: str) -> Dict[str, Any]:
"""Apply common sense reasoning to answer a question"""
print(f"\n{'='*60}")
print(f"Question: {question}")
print(f"{'='*60}")
# Get relevant common sense facts
relevant_facts = self.kb.get_relevant_facts(question)
if not relevant_facts:
relevant_facts = list(self.kb.knowledge.values())[:10]
facts_str = "\n".join(f"- {fact}" for fact in relevant_facts)
print(f"\nRelevant common sense facts:")
for fact in relevant_facts:
print(f" - {fact}")
# Reason with facts
reasoning = self.reasoning_chain.invoke({
"question": question,
"facts": facts_str
})
print(f"\nReasoning:")
print(reasoning)
return {
"question": question,
"facts": relevant_facts,
"reasoning": reasoning,
"timestamp": datetime.now().isoformat()
}
def check_plausibility(self, conclusion: str, context: str = "") -> Dict[str, Any]:
"""Check if a conclusion is plausible"""
print(f"\n{'='*60}")
print(f"Checking plausibility: {conclusion}")
print(f"{'='*60}")
# Get relevant facts
relevant_facts = self.kb.get_relevant_facts(conclusion + " " + context)
if not relevant_facts:
relevant_facts = list(self.kb.knowledge.values())[:10]
facts_str = "\n".join(f"- {fact}" for fact in relevant_facts)
# Check plausibility
evaluation = self.plausibility_chain.invoke({
"conclusion": conclusion,
"facts": facts_str
})
print(f"\nEvaluation:")
print(evaluation)
return {
"conclusion": conclusion,
"facts": relevant_facts,
"evaluation": evaluation,
"timestamp": datetime.now().isoformat()
}
def generate_assumptions(self, scenario: str) -> Dict[str, Any]:
"""Generate reasonable assumptions for a scenario"""
print(f"\n{'='*60}")
print(f"Scenario: {scenario}")
print(f"{'='*60}")
# Generate assumptions
assumptions = self.assumption_chain.invoke({
"scenario": scenario
})
print(f"\nGenerated assumptions:")
print(assumptions)
return {
"scenario": scenario,
"assumptions": assumptions,
"timestamp": datetime.now().isoformat()
}
def explain_with_common_sense(self, observation: str) -> Dict[str, Any]:
"""Explain an observation using common sense"""
print(f"\n{'='*60}")
print(f"Observation: {observation}")
print(f"{'='*60}")
# Get causal facts
causal_facts = self.kb.get_category("causal")
facts_str = "\n".join(f"- {fact}" for fact in causal_facts)
explanation_prompt = f"""Using common sense causal knowledge, explain this observation:
Observation: {observation}
Common sense causal facts:
{facts_str}
Provide a simple, common sense explanation:"""
explanation = self.llm.invoke(explanation_prompt).content
print(f"\nExplanation:")
print(explanation)
return {
"observation": observation,
"causal_facts": causal_facts,
"explanation": explanation,
"timestamp": datetime.now().isoformat()
}
def demonstrate_common_sense_reasoning():
"""Demonstrate common sense reasoning patterns"""
print("\n" + "="*70)
print("COMMON SENSE REASONING DEMONSTRATION")
print("="*70)
reasoner = CommonSenseReasoner()
# Example 1: Question answering with common sense
print("\n" + "="*70)
print("Example 1: Question Answering with Common Sense")
print("="*70)
question1 = "If I drop a glass cup on the floor, what will happen?"
result1 = reasoner.reason_with_common_sense(question1)
question2 = "Should I use an umbrella when it's raining?"
result2 = reasoner.reason_with_common_sense(question2)
# Example 2: Plausibility checking
print("\n" + "="*70)
print("Example 2: Plausibility Checking")
print("="*70)
conclusion1 = "I can walk through a solid brick wall"
plausibility1 = reasoner.check_plausibility(conclusion1)
conclusion2 = "If I leave ice cream outside in the sun, it will melt"
plausibility2 = reasoner.check_plausibility(conclusion2)
# Example 3: Assumption generation
print("\n" + "="*70)
print("Example 3: Assumption Generation")
print("="*70)
scenario = "A person enters a restaurant and sits at a table"
assumptions = reasoner.generate_assumptions(scenario)
# Example 4: Explanation with common sense
print("\n" + "="*70)
print("Example 4: Explaining Observations")
print("="*70)
observation1 = "The sidewalk is wet even though no one watered it"
explanation1 = reasoner.explain_with_common_sense(observation1)
observation2 = "The person looks tired and is yawning"
explanation2 = reasoner.explain_with_common_sense(observation2)
# Summary
print("\n" + "="*70)
print("SUMMARY")
print("="*70)
print("""
Common Sense Reasoning Pattern demonstrated:
Key Features:
1. Knowledge Base Integration - Access to common sense facts
2. Contextual Reasoning - Apply relevant facts to situations
3. Plausibility Checking - Validate conclusions against common sense
4. Assumption Generation - Make reasonable implicit assumptions
5. Causal Explanation - Explain observations with common sense
Applications:
- Natural language understanding
- Question answering systems
- Story comprehension
- Situation interpretation
- Robotics and embodied AI
Common sense reasoning helps agents bridge the gap between explicit
knowledge and implicit understanding that humans naturally possess.
""")
if __name__ == "__main__":
demonstrate_common_sense_reasoning()
Agentic Design Pattern: Common Sense Reasoning
Pattern 112: Common Sense Reasoning – Line-by-Line Explanation
Overview
This document provides a detailed line-by-line explanation of the Common Sense Reasoning pattern implementation.
Pattern Description
Pattern 112: Common Sense Reasoning
Description: Common Sense Reasoning enables agents to apply implicit, everyday knowledge that humans take for granted. This pattern integrates common sense knowledge bases (like ConceptNet) with LLM reasoning to make inferences about the physical world, social norms, causality, and typical behaviors.
The pattern helps agents understand context, make reasonable assumptions,
avoid absurd conclusions, and reason about unstated but obvious facts.
It bridges the gap between explicit knowledge and implicit understanding.
Key Components: 1. Knowledge Base: ConceptNet or similar common sense KB 2. Reasoning Engine: Inference over common sense facts 3. Context Integrator: Applies common sense to situations 4. Plausibility Checker: Validates conclusions 5. Assumption Generator: Makes reasonable assumptions
Common Sense Categories: – Physical: Objects fall down, water is wet – Social: Greetings are polite, lying is wrong – Causal: Rain makes things wet, fire causes heat – Temporal: Events have order, time moves forward – Spatial: Objects can’t be in two places – Functional: Tools have purposes, actions have effects
Use Cases: – Natural language understanding – Story comprehension and generation – Situation interpretation – Question answering with implicit knowledge – Robotics and embodied AI
LangChain Implementation: Uses ConceptNet integration, reasoning chains, and validation logic to apply common sense knowledge to agent reasoning.
File Statistics
- Total Lines: 365
- Classes: 2
- Functions: 1
- Constants: 0
Module Documentation
"""
Pattern 112: Common Sense Reasoning
Description:
Common Sense Reasoning enables agents to apply implicit, everyday knowledge
that humans take for granted. This pattern integrates common sense knowledge
bases (like ConceptNet) with LLM reasoning to make inferences about the
physical world, social norms, causality, and typical behaviors.
The pattern helps agents understand context, make reasonable assumptions,
avoid absurd conclusions, and reason about unstated but obvious facts.
It bridges the gap between explicit knowledge and implicit understanding.
Key Components:
1. Knowledge Base: ConceptNet or similar common sense KB
2. Reasoning Engine: Inference over common sense facts
3. Context Integrator: Applies common sense to situations
4. Plausibility Checker: Validates conclusions
5. Assumption Generator: Makes reasonable assumptions
Common Sense Categories:
- Physical: Objects fall down, water is wet
- Social: Greetings are polite, lying is wrong
- Causal: Rain makes things wet, fire causes heat
- Temporal: Events have order, time moves forward
- Spatial: Objects can't be in two places
- Functional: Tools have purposes, actions have effects
Use Cases:
- Natural language understanding
- Story comprehension and generation
- Situation interpretation
- Question answering with implicit knowledge
- Robotics and embodied AI
LangChain Implementation:
Uses ConceptNet integration, reasoning chains, and validation logic to
apply common sense knowledge to agent reasoning.
"""
Purpose: This module implements the Common Sense Reasoning pattern, providing a structured approach to agent design and implementation.
Import Statements
Standard Library Imports
import datetime.datetime
import langchain_core.output_parsers.JsonOutputParser
import langchain_core.output_parsers.StrOutputParser
import langchain_core.prompts.ChatPromptTemplate
import os
import typing.Any
import typing.Dict
import typing.List
import typing.Optional
import typing.Tuple
Purpose: Core Python functionality:
– datetime.datetime: Date and time handling
– langchain_core.output_parsers.JsonOutputParser: Regular expression operations
– langchain_core.output_parsers.StrOutputParser: Regular expression operations
– langchain_core.prompts.ChatPromptTemplate: Regular expression operations
– os: Environment variable access and system operations
– typing.Any: Type hints for better code documentation (List, Dict, Any, Optional)
– typing.Dict: Type hints for better code documentation (List, Dict, Any, Optional)
– typing.List: Type hints for better code documentation (List, Dict, Any, Optional)
– typing.Optional: Type hints for better code documentation (List, Dict, Any, Optional)
– typing.Tuple: Type hints for better code documentation (List, Dict, Any, Optional)
LangChain Imports
from langchain.chains.LLMChain
from langchain_openai.ChatOpenAI
Purpose: LangChain framework components: – LLM Interface: Wrapper for OpenAI models – Chains: Composable building blocks for complex workflows
Other Imports
from dotenv.load_dotenv
Purpose: Additional dependencies for specialized functionality.
Classes
Class: CommonSenseKnowledgeBase
Lines 54-121
Purpose:
Simulated common sense knowledge base (in practice, use ConceptNet API)
Methods:
__init__(self)
Lines 57-102
Purpose: Initialize the class instance with required parameters.
Parameters:
query(self, concept)
Lines 104-106
Purpose:
Query knowledge base for common sense fact
Parameters:
– concept: Concept
Returns: <ast.Subscript object at 0x000001A06D6156D0>
get_category(self, category)
Lines 108-111
Purpose:
Get all facts in a category
Parameters:
– category: Category
Returns: <ast.Subscript object at 0x000001A06D6168D0>
get_relevant_facts(self, context)
Lines 113-121
Purpose:
Get facts relevant to context
Parameters:
– context: Context
Returns: <ast.Subscript object at 0x000001A06D73A2D0>
Class: CommonSenseReasoner
Lines 124-285
Purpose:
Agent that applies common sense reasoning
Methods:
__init__(self, model_name)
Lines 127-172
Purpose: Initialize the class instance with required parameters.
Parameters:
– model_name: Language model instance
reason_with_common_sense(self, question)
Lines 174-205
Purpose:
Apply common sense reasoning to answer a question
Parameters:
– question: Question to answer
Returns: <ast.Subscript object at 0x000001A06D16E510>
check_plausibility(self, conclusion, context)
Lines 207-234
Purpose:
Check if a conclusion is plausible
Parameters:
– conclusion: Conclusion
– context: Context
Returns: <ast.Subscript object at 0x000001A06D824AD0>
generate_assumptions(self, scenario)
Lines 236-254
Purpose:
Generate reasonable assumptions for a scenario
Parameters:
– scenario: Scenario
Returns: <ast.Subscript object at 0x000001A06D68C590>
explain_with_common_sense(self, observation)
Lines 256-285
Purpose:
Explain an observation using common sense
Parameters:
– observation: Observation
Returns: <ast.Subscript object at 0x000001A06D888FD0>
Functions
demonstrate_common_sense_reasoning()
Lines 288-360
Purpose:
Demonstrate common sense reasoning patterns
Key Concepts Summary
Pattern Overview
The Common Sense Reasoning pattern provides a structured approach to building AI agents with specific capabilities and behaviors. This implementation leverages LangChain’s composable components to create a robust and maintainable solution.
Core Components
- Agent Class: Main implementation of the pattern logic
- Prompt Engineering: Carefully crafted prompts to guide LLM behavior
- Tool Integration: Optional tools for extended functionality
- Memory Management: State handling across interactions
- Output Parsing: Structured response processing
When to Use
✅ Good for: – Scenarios requiring this specific pattern’s strengths – Applications needing structured agent behavior – Systems where explainability is important – Production environments requiring reliability
❌ Not ideal for: – Simple single-prompt tasks – Scenarios requiring different pattern characteristics – Resource-constrained environments (if computationally intensive)
Best Practices Demonstrated
1. Environment Configuration
- ✅ Use
.envfiles for API keys - ✅ Never hardcode credentials
- ✅ Validate environment variables on startup
2. Error Handling
- ✅ Graceful degradation on failures
- ✅ Informative error messages
- ✅ Logging for debugging
3. Prompt Engineering
- ✅ Clear, specific instructions
- ✅ Structured output formats
- ✅ Few-shot examples when beneficial
4. Code Organization
- ✅ Separation of concerns (class-based design)
- ✅ Type hints for clarity
- ✅ Docstrings for documentation
5. Performance Optimization
- ✅ Appropriate temperature settings
- ✅ Token budget management
- ✅ Caching where applicable
LangChain Components Used
- ChatOpenAI: OpenAI model interface
- Chains: Sequential component composition
Why LangChain? – Composable abstractions for LLM applications – Rich ecosystem of integrations – Production-ready patterns – Active community and development
Execution Flow
1. Initialize agent with configuration
↓
2. Load environment and dependencies
↓
3. Prepare prompt with input data
↓
4. Invoke LLM through LangChain
↓
5. Parse and validate response
↓
6. Return formatted result
Key Decision Points: – Model selection (temperature, model type) – Prompt structure (few-shot vs zero-shot) – Error handling strategy – Output format validation
Performance Considerations
Computational Cost
- LLM Calls: Primary cost factor (based on tokens)
- Latency: Depends on model and input size
- Memory: Minimal for most patterns
Optimization Strategies
- Prompt Optimization: Minimize tokens while maintaining clarity
- Caching: Cache repeated queries/responses
- Model Selection: Use smaller models when appropriate
- Batch Processing: Group similar requests
- Streaming: For long responses, stream tokens
Cost Estimates (Approximate)
- GPT-3.5-turbo: ~$0.002 per request
- GPT-4: ~$0.03 per request
- GPT-4-turbo: ~$0.01 per request
Actual costs vary based on input/output token counts
Common Pitfalls to Avoid
1. Prompt Design Issues
❌ Vague or ambiguous instructions
✅ Clear, specific, testable prompts
2. Error Handling
❌ Ignoring API errors or rate limits
✅ Implement retry logic and graceful degradation
3. Token Management
❌ Exceeding model token limits
✅ Truncate inputs, chunk processing
4. Security
❌ Exposing API keys in code
✅ Use environment variables
5. Testing
❌ Only testing happy paths
✅ Test edge cases, failures, malformed inputs
6. Cost Management
❌ Unmonitored API usage
✅ Implement budgets, alerts, and monitoring
Further Improvements
Production Enhancements
- Monitoring: Add logging, metrics, tracing
- Validation: Input/output schema validation
- Rate Limiting: Implement request throttling
- Caching: Redis or in-memory cache for responses
- Async Support: Non-blocking operations for scalability
Feature Extensions
- Multi-Model Support: Switch between providers
- Fallback Models: Graceful degradation strategy
- Custom Tools: Domain-specific function calling
- Advanced Memory: Vector stores for long-term memory
- Evaluation: Automated testing and benchmarking
Code Quality
- Testing: Unit tests, integration tests
- Documentation: API docs, usage examples
- Type Safety: Stricter type hints
- Configuration: Externalized config files
Related Patterns
- Pattern 111
- Pattern 113
Pattern Families: – Reasoning Patterns (001-011) – Multi-Agent Patterns (012-019) – Tool Use Patterns (020-025) – Memory Patterns (026-031) – And many more…
Summary
The Common Sense Reasoning pattern provides a powerful approach to building AI agents with specific capabilities. This implementation demonstrates:
✅ Key Strengths: – Clean, maintainable code structure – LangChain integration for composability – Type hints and documentation – Production-ready patterns
🎯 Best Use Cases: – Applications requiring this pattern’s characteristics – Systems needing structured agent behavior – Production environments requiring reliability
📚 Learning Resources: – LangChain Documentation: https://python.langchain.com/ – Pattern Documentation: See related patterns – OpenAI API Reference: https://platform.openai.com/docs/
File: 112_common_sense_reasoning.py
Total Lines: 365
Pattern Category: AI Agent Design Pattern #112
Generated from actual implementation code
For educational and reference purposes
Leave a Reply