Memory management

Memory management makes your AI system feel intelligent and personalized. Instead of treating each interaction as isolated, the system remembers past conversations, user preferences, and context, enabling continuity across sessions.

Short-term vs Long-term memory

That is exactly why you need a memory manager. It summarizes older messages and keeps only the most recent ones in full, so you stay within the context window while preserving the key facts.

patterns/08_memory_management.py
python
class ConversationMemory:
    def __init__(self):
        self.history = []
        self.user_preferences = {}

    def add_message(self, role, content):
        self.history.append({
            "role": role,
            "content": content,
            "timestamp": datetime.now().isoformat()
        })

    def get_recent_context(self, limit=5):
        recent = self.history[-limit:]
        return "\n".join(
            [f"{msg['role']}: {msg['content']}" for msg in recent]
        )

    def update_preferences(self, key, value):
        self.user_preferences[key] = value

def chat_with_memory(memory, user_input, llm):
    memory.add_message("user", user_input)
    context = memory.get_recent_context()
    prefs = memory.get_user_preferences()

    prompt = f"""
    Recent conversation: {context}
    User preferences: {prefs}
    Current message: {user_input}
    Respond naturally, referencing past context.
    """
    response = llm.generate(prompt).content
    memory.add_message("assistant", response)
    return response

A ConversationMemory class that stores history and preferences, injecting them into each LLM call.

Quiz: Quiz

Loading practice…

Matching exercise: Match memory concepts

Loading practice…

Flashcards: Flashcards

Loading practice…

Memory management is what separates a stateless chatbot from a truly intelligent assistant. Your agents can now remember past conversations, learn user preferences, and maintain context across sessions. Up next is a quick foundation assessment to solidify everything from the foundational phases.