"""
Pattern 62: Semantic Memory Pattern
Agents store general knowledge, concepts, and meanings independent of context.
Unlike episodic memory (specific events), semantic memory contains abstract facts.
"""
from typing import Dict, Any, List, Optional, Set
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
class ConceptType(Enum):
"""Type of semantic concept."""
CATEGORY = "category"
PROPERTY = "property"
RELATIONSHIP = "relationship"
PROCEDURE = "procedure"
DEFINITION = "definition"
@dataclass
class Concept:
"""Semantic concept with properties."""
concept_id: str
name: str
concept_type: ConceptType
definition: str
properties: Dict[str, Any] = field(default_factory=dict)
related_concepts: Set[str] = field(default_factory=set)
examples: List[str] = field(default_factory=list)
confidence: float = 1.0
learned_date: datetime = field(default_factory=datetime.now)
@dataclass
class Association:
"""Association between concepts."""
from_concept: str
to_concept: str
relationship: str
strength: float = 1.0 # 0 to 1
@dataclass
class ConceptQuery:
"""Query about semantic knowledge."""
query: str
matched_concepts: List[Concept]
associations: List[Association]
answer: str
class SemanticMemory:
"""Semantic memory storage and retrieval."""
def __init__(self):
self.concepts: Dict[str, Concept] = {}
self.associations: List[Association] = []
self.categories: Dict[str, Set[str]] = {}
def add_concept(self, concept: Concept):
"""Add concept to semantic memory."""
self.concepts[concept.concept_id] = concept
# Add to category index
category_name = concept.concept_type.value
if category_name not in self.categories:
self.categories[category_name] = set()
self.categories[category_name].add(concept.concept_id)
def add_association(self, from_concept: str, to_concept: str,
relationship: str, strength: float = 1.0):
"""Add association between concepts."""
assoc = Association(from_concept, to_concept, relationship, strength)
self.associations.append(assoc)
# Update related concepts
if from_concept in self.concepts:
self.concepts[from_concept].related_concepts.add(to_concept)
if to_concept in self.concepts:
self.concepts[to_concept].related_concepts.add(from_concept)
def find_concept(self, name: str) -> Optional[Concept]:
"""Find concept by name."""
for concept in self.concepts.values():
if concept.name.lower() == name.lower():
return concept
return None
def get_related_concepts(self, concept_id: str, max_depth: int = 2) -> List[Concept]:
"""Get concepts related to given concept."""
if concept_id not in self.concepts:
return []
related_ids = set()
to_explore = [(concept_id, 0)]
explored = set()
while to_explore:
current_id, depth = to_explore.pop(0)
if current_id in explored or depth > max_depth:
continue
explored.add(current_id)
if current_id != concept_id:
related_ids.add(current_id)
# Add related concepts to explore
if current_id in self.concepts:
for related_id in self.concepts[current_id].related_concepts:
if related_id not in explored:
to_explore.append((related_id, depth + 1))
return [self.concepts[cid] for cid in related_ids if cid in self.concepts]
def get_by_category(self, category: ConceptType) -> List[Concept]:
"""Get all concepts in a category."""
concept_ids = self.categories.get(category.value, set())
return [self.concepts[cid] for cid in concept_ids if cid in self.concepts]
class SemanticMemoryAgent:
"""Agent with semantic memory capabilities."""
def __init__(self, name: str, model_name: str = "gpt-4"):
self.name = name
self.llm = ChatOpenAI(model=model_name, temperature=0.3)
self.memory = SemanticMemory()
self.queries: List[ConceptQuery] = []
def learn_concept(self, concept: Concept):
"""Learn new concept."""
self.memory.add_concept(concept)
print(f" š§ {self.name} learned concept: {concept.name} ({concept.concept_type.value})")
def associate_concepts(self, concept1: str, concept2: str, relationship: str, strength: float = 1.0):
"""Create association between concepts."""
self.memory.add_association(concept1, concept2, relationship, strength)
print(f" š {self.name} associated: {concept1} --{relationship}-> {concept2}")
def explain_concept(self, concept_name: str) -> str:
"""Explain concept using LLM."""
concept = self.memory.find_concept(concept_name)
if not concept:
return f"I don't have semantic knowledge about '{concept_name}'."
# Get related concepts
related = self.memory.get_related_concepts(concept.concept_id)
related_names = [self.memory.concepts[rc.concept_id].name for rc in related if rc.concept_id in self.memory.concepts]
prompt = ChatPromptTemplate.from_messages([
("system", f"You are {self.name}, explaining concepts from your semantic memory."),
("human", f"Explain this concept:\n"
f"Name: {concept.name}\n"
f"Type: {concept.concept_type.value}\n"
f"Definition: {concept.definition}\n"
f"Properties: {concept.properties}\n"
f"Related concepts: {', '.join(related_names[:5])}\n\n"
f"Provide a clear, educational explanation (2-3 sentences).")
])
chain = prompt | self.llm
response = chain.invoke({})
return str(response.content)[:300]
def query_knowledge(self, query: str) -> ConceptQuery:
"""Query semantic knowledge."""
# Get all concepts as context
concepts_text = "\n".join([
f"- {c.name} ({c.concept_type.value}): {c.definition}"
for c in self.memory.concepts.values()
])
associations_text = "\n".join([
f"- {a.from_concept} {a.relationship} {a.to_concept}"
for a in self.memory.associations[:20] # Limit for context
])
prompt = ChatPromptTemplate.from_messages([
("system", f"You are {self.name} with semantic memory. "
f"Answer questions using your general knowledge."),
("human", f"My semantic knowledge:\n{concepts_text}\n\n"
f"Associations:\n{associations_text}\n\n"
f"Question: {query}\n\n"
f"Answer based on the semantic knowledge above.")
])
chain = prompt | self.llm
response = chain.invoke({})
result = ConceptQuery(
query=query,
matched_concepts=list(self.memory.concepts.values())[:5],
associations=self.memory.associations[:5],
answer=str(response.content)
)
self.queries.append(result)
return result
class SemanticMemoryPattern:
"""
Semantic Memory Pattern - Abstract knowledge storage.
Agents maintain general facts, concepts, and meanings, enabling
them to reason about abstract ideas and relationships.
"""
def __init__(self):
self.agents: Dict[str, SemanticMemoryAgent] = {}
def register_agent(self, agent: SemanticMemoryAgent):
"""Register agent with semantic memory."""
self.agents[agent.name] = agent
def share_concept(self, source_agent: str, target_agent: str, concept_name: str):
"""Share concept between agents."""
if source_agent in self.agents and target_agent in self.agents:
source = self.agents[source_agent]
target = self.agents[target_agent]
concept = source.memory.find_concept(concept_name)
if concept:
target.learn_concept(concept)
def run(self, domain: str) -> Dict[str, Any]:
"""Execute semantic memory pattern."""
total_concepts = sum(len(agent.memory.concepts) for agent in self.agents.values())
total_associations = sum(len(agent.memory.associations) for agent in self.agents.values())
total_queries = sum(len(agent.queries) for agent in self.agents.values())
return {
"pattern": "SemanticMemory",
"domain": domain,
"total_agents": len(self.agents),
"total_concepts": total_concepts,
"total_associations": total_associations,
"total_queries": total_queries
}
# Example usage
if __name__ == "__main__":
print("=== Semantic Memory Pattern Demo ===\n")
# Create pattern
pattern = SemanticMemoryPattern()
# Create agent with semantic memory
print("1. Creating agent with semantic memory...")
agent = SemanticMemoryAgent("Sage")
pattern.register_agent(agent)
# Learn concepts
print("\n2. Learning concepts...")
concepts = [
Concept("ml", "Machine Learning", ConceptType.CATEGORY,
"Field of AI focused on learning from data",
properties={"paradigm": "supervised/unsupervised", "goal": "prediction"},
examples=["classification", "regression", "clustering"]),
Concept("nn", "Neural Network", ConceptType.CATEGORY,
"Computing system inspired by biological neural networks",
properties={"layers": "input, hidden, output", "learning": "backpropagation"},
examples=["CNN", "RNN", "Transformer"]),
Concept("supervised", "Supervised Learning", ConceptType.PROCEDURE,
"Learning from labeled training data",
properties={"requires": "labeled data", "output": "prediction model"},
examples=["classification", "regression"]),
Concept("unsupervised", "Unsupervised Learning", ConceptType.PROCEDURE,
"Learning patterns from unlabeled data",
properties={"requires": "unlabeled data", "output": "patterns, clusters"},
examples=["clustering", "dimensionality reduction"]),
Concept("backprop", "Backpropagation", ConceptType.PROCEDURE,
"Algorithm for training neural networks using gradient descent",
properties={"technique": "gradient descent", "direction": "backward"},
examples=["SGD", "Adam optimizer"]),
]
for concept in concepts:
agent.learn_concept(concept)
# Create associations
print("\n3. Creating concept associations...")
agent.associate_concepts("ml", "supervised", "includes", 0.9)
agent.associate_concepts("ml", "unsupervised", "includes", 0.9)
agent.associate_concepts("nn", "ml", "is_part_of", 0.95)
agent.associate_concepts("nn", "backprop", "uses", 1.0)
agent.associate_concepts("supervised", "nn", "can_use", 0.8)
# Explain concepts
print("\n4. Explaining concepts...")
for concept_name in ["Machine Learning", "Neural Network", "Backpropagation"]:
explanation = agent.explain_concept(concept_name)
print(f"\n {concept_name}:")
print(f" {explanation}")
# Query semantic knowledge
print("\n5. Querying semantic knowledge...")
queries = [
"What is the relationship between neural networks and machine learning?",
"Explain the difference between supervised and unsupervised learning",
"How does backpropagation work?"
]
for query in queries:
print(f"\n Q: {query}")
result = agent.query_knowledge(query)
print(f" A: {result.answer[:200]}...")
# Explore concept network
print("\n6. Exploring concept relationships...")
ml_concept = agent.memory.find_concept("Machine Learning")
if ml_concept:
related = agent.memory.get_related_concepts(ml_concept.concept_id)
print(f" Concepts related to 'Machine Learning': {len(related)}")
for rc in related:
print(f" - {rc.name} ({rc.concept_type.value})")
# Statistics
print("\n7. Semantic Memory Statistics:")
summary = pattern.run("AI and Machine Learning")
print(f" Total Concepts: {summary['total_concepts']}")
print(f" Total Associations: {summary['total_associations']}")
print(f" Total Queries: {summary['total_queries']}")
categories = agent.memory.categories
print(f"\n Concepts by category:")
for category, concept_ids in categories.items():
print(f" - {category}: {len(concept_ids)}")
print("\nā Semantic memory pattern enabled abstract knowledge reasoning!")
Agentic Architecture Pattern: Semantic Memory
Pattern 62: 62 Semantic Memory – Line-by-Line Explanation
Overview
Pattern 62: Semantic Memory Pattern
Agents store general knowledge, concepts, and meanings independent of context. Unlike episodic memory (specific events), semantic memory contains abstract facts.
Code Structure Analysis
File Information
- Pattern Number: 62
- Pattern Name: 62 Semantic Memory
- File Path:
patterns\memory_knowledge\62_semantic_memory.py - Total Lines: 343
Detailed Code Explanation
Module Docstring
"""
Pattern 62: Semantic Memory Pattern
Agents store general knowledge, concepts, and meanings independent of context.
Unlike episodic memory (specific events), semantic memory contains abstract facts.
"""
Explanation: This module docstring describes the purpose and key features of the 62 Semantic Memory pattern.
Imports Section
from typing import Dict, Any, List, Optional, Set
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI # First 20 imports shown
Explanation: The module imports necessary dependencies:
– from typing import Dict, Any, List, Optional, Set: Type hints for better code documentation
– from dataclasses import dataclass, field: Data class decorators for clean data structures
– from datetime import datetime: Date and time utilities
– from enum import Enum: Enumeration support for fixed sets of values
– from langchain_core.prompts import ChatPromptTemplate: LangChain framework integration
– from langchain_openai import ChatOpenAI: LangChain framework integration
Enumerations
ConceptType (Line 16)
class ConceptType(Enum):
CATEGORY
PROPERTY
RELATIONSHIP
PROCEDURE
DEFINITION
Purpose: Type of semantic concept.
Values:
– CATEGORY: Represents category
– PROPERTY: Represents property
– RELATIONSHIP: Represents relationship
– PROCEDURE: Represents procedure
– DEFINITION: Represents definition
Classes
ConceptType (Line 16)
Description: Type of semantic concept.
Concept (Line 26)
Description: Semantic concept with properties.
Association (Line 40)
Description: Association between concepts.
ConceptQuery (Line 49)
Description: Query about semantic knowledge.
SemanticMemory (Line 57)
Description: Semantic memory storage and retrieval.
Methods:
__init__ (Line 60)
def __init__(self):
"""No method docstring."""
Purpose: No method docstring.
Parameters:
– self: Instance reference
add_concept (Line 65)
def add_concept(self, concept):
"""Add concept to semantic memory."""
Purpose: Add concept to semantic memory.
Parameters:
– self: Instance reference
– concept: Parameter for concept
add_association (Line 75)
def add_association(self, from_concept, to_concept, relationship, strength):
"""Add association between concepts."""
Purpose: Add association between concepts.
Parameters:
– self: Instance reference
– from_concept: Parameter for from_concept
– to_concept: Parameter for to_concept
– relationship: Parameter for relationship
– strength: Parameter for strength
find_concept (Line 87)
def find_concept(self, name):
"""Find concept by name."""
Purpose: Find concept by name.
Parameters:
– self: Instance reference
– name: Identifier or label
get_related_concepts (Line 94)
def get_related_concepts(self, concept_id, max_depth):
"""Get concepts related to given concept."""
Purpose: Get concepts related to given concept.
Parameters:
– self: Instance reference
– concept_id: Parameter for concept_id
– max_depth: Parameter for max_depth
get_by_category (Line 120)
def get_by_category(self, category):
"""Get all concepts in a category."""
Purpose: Get all concepts in a category.
Parameters:
– self: Instance reference
– category: Parameter for category
SemanticMemoryAgent (Line 126)
Description: Agent with semantic memory capabilities.
Methods:
__init__ (Line 129)
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”)
learn_concept (Line 135)
def learn_concept(self, concept):
"""Learn new concept."""
Purpose: Learn new concept.
Parameters:
– self: Instance reference
– concept: Parameter for concept
associate_concepts (Line 140)
def associate_concepts(self, concept1, concept2, relationship, strength):
"""Create association between concepts."""
Purpose: Create association between concepts.
Parameters:
– self: Instance reference
– concept1: Parameter for concept1
– concept2: Parameter for concept2
– relationship: Parameter for relationship
– strength: Parameter for strength
explain_concept (Line 145)
def explain_concept(self, concept_name):
"""Explain concept using LLM."""
Purpose: Explain concept using LLM.
Parameters:
– self: Instance reference
– concept_name: Parameter for concept_name
query_knowledge (Line 171)
def query_knowledge(self, query):
"""Query semantic knowledge."""
Purpose: Query semantic knowledge.
Parameters:
– self: Instance reference
– query: Parameter for query
SemanticMemoryPattern (Line 207)
Description: Semantic Memory Pattern – Abstract knowledge storage.
Agents maintain general facts, concepts, and meanings, enabling them to reason about abstract ideas and relationships.
Methods:
__init__ (Line 215)
def __init__(self):
"""No method docstring."""
Purpose: No method docstring.
Parameters:
– self: Instance reference
register_agent (Line 218)
def register_agent(self, agent):
"""Register agent with semantic memory."""
Purpose: Register agent with semantic memory.
Parameters:
– self: Instance reference
– agent: Parameter for agent
share_concept (Line 222)
def share_concept(self, source_agent, target_agent, concept_name):
"""Share concept between agents."""
Purpose: Share concept between agents.
Parameters:
– self: Instance reference
– source_agent: Parameter for source_agent
– target_agent: Parameter for target_agent
– concept_name: Parameter for concept_name
run (Line 232)
def run(self, domain):
"""Execute semantic memory pattern."""
Purpose: Execute semantic memory pattern.
Parameters:
– self: Instance reference
– domain: Parameter for domain
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 = ConceptType(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
Leave a Reply