Episodic & semantic memory

This pattern combines two memory types inspired by human cognition: Episodic memory stores conversation events (what happened, when). Semantic memory stores structured facts and relationships (what is true). Together they give agents both personal history and world knowledge.

Dual memory architecture

You covered basic short-term and long-term memory earlier. This pattern adds structure: episodic memory timestamps events, and semantic memory stores facts as key-value pairs. The agent can distinguish "what happened" from "what is true."

patterns/37_episodic_semantic_memory.py
python
class MemorySystem:
    def __init__(self):
        self.episodic_memories = []  # Events
        self.semantic_memories = []   # Facts

    def store_episodic_memory(self, user_input, response):
        self.episodic_memories.append({
            "input": user_input,
            "response": response,
            "timestamp": datetime.now().isoformat()
        })

    def store_semantic_memory(self, entity, relationship, target):
        self.semantic_memories.append({
            "entity": entity,
            "relationship": relationship,
            "target": target
        })

    def retrieve_relevant_memories(self, query):
        episodic = [m for m in self.episodic_memories
                    if any(w in m["input"].lower()
                           for w in query.lower().split())]
        semantic = [m for m in self.semantic_memories
                    if query.lower() in m["entity"].lower()]
        return {"episodic": episodic, "semantic": semantic}

class MemoryEnhancedAgent:
    def process_input(self, user_input):
        memories = self.memory.retrieve_relevant_memories(user_input)
        context = self._build_memory_context(memories)
        response = self._generate_response(user_input, context)
        self.memory.store_episodic_memory(user_input, response)
        # Extract and store semantic facts
        facts = self.memory.extract_semantic_facts(response)
        for entity, rel, target in facts:
            self.memory.store_semantic_memory(entity, rel, target)
        return response

MemorySystem with episodic events and semantic facts.

Quiz: Quiz

Loading practice…

Matching exercise: Match memory types

Loading practice…

Flashcards: Flashcards

Loading practice…

You now understand how episodic and semantic memory give agents long-term learning capabilities.

Checkpoint: Advanced architectures checkpoint

Loading practice…