Module 2 · Lesson 6 · 15 min read

Memory management: summarization, updating and deletion

Memory Management

Introduction

Unmanaged memory becomes a source of contradictions and risks. In this lesson we learn the four operations for managing an agent's memory: summarization, updating, deletion and retention, and we build a store that applies them all, including carrying out a user's request to forget their data.

Learning objectives

  • Apply threshold, cumulative and hierarchical summarization patterns
  • Resolve conflicting information by updating with a fixed key while keeping history
  • Design a retention policy that includes a time to live and the right to be forgotten
  • Build a managed memory store in Python

Memory needs maintenance

Building memory for an agent is only half the work. Memory that is not managed turns over time into a messy store: old information that contradicts the new, duplication that fills the context, and personal data that there is no longer any reason to keep. Memory management covers four operations: summarization, updating, deletion and retention.

RetrievalShort-term memoryShort-Term: the current context windowConversation memoryLong-term memoryLong-Term: outside the modelEpisodicEpisodic: eventsSemanticSemantic: factsStore and retrievalVector DB / keyword search
Short-term memory lives inside the context window, while long-term memory is stored outside the model and retrieved when needed.

Summarization

When the conversation grows long, we replace old messages with a short summary that keeps the essentials: the goal, the decisions and the open questions. Common patterns:

  • Threshold summarization: when the messages exceed a certain number or size, summarize the oldest of them.
  • Cumulative summarization: a single summary that is updated with each new group of messages.
  • Hierarchical summarization: summaries of sessions, then a summary of the summaries.

Updating and conflict resolution

Information changes: the student changed major, or the regulations changed. If we add the new information without handling the old, the agent will retrieve both contradictory pieces and not know which to believe. Solutions:

  • Overwriting the value under a fixed key (upsert): "the student's major" is a single key with a single current value.
  • Keeping history: saving the new value while keeping the old one tagged as "expired" with its expiry date.
  • Preferring the newest and most reliable: when retrieving, sort by date and by the source of the information.

Deletion and retention

Not everything that is saved should stay forever:

  • Time to live (TTL): temporary information such as "the student is traveling this week" expires automatically.
  • The right to be forgotten: if the user asks for their data to be deleted, it must actually be deleted from every store, including the vectors and summaries that contained it, not merely hidden.
  • Data minimization: save the least needed to perform the task.

A practical example: a managed memory store

An academic advising assistant saves student information. The requirements: update the major without contradiction, expire temporary information, carry out a "forget my data" request, and summarize the long conversation.

python
import time

class ManagedMemory:
    def __init__(self):
        self.facts = {}      # (user, key) -> record
        self.history = []    # old values for auditing
        self.messages = []

    def upsert(self, user, key, value, ttl=None):
        old = self.facts.get((user, key))
        if old:
            self.history.append({**old, "ended": time.time()})
        self.facts[(user, key)] = {"user": user, "key": key, "value": value,
                                   "saved": time.time(),
                                   "expires": time.time() + ttl if ttl else None}

    def get(self, user, key):
        rec = self.facts.get((user, key))
        if rec and rec["expires"] and rec["expires"] < time.time():
            del self.facts[(user, key)]          # expired
            return None
        return rec["value"] if rec else None

    def forget_user(self, user):
        self.facts = {k: v for k, v in self.facts.items() if k[0] != user}
        self.history = [h for h in self.history if h["user"] != user]
        self.messages = [m for m in self.messages if m["user"] != user]

    def add_message(self, user, text, threshold=4):
        self.messages.append({"user": user, "text": text})
        mine = [m for m in self.messages if m["user"] == user]
        if len(mine) > threshold:
            old = mine[:-2]
            summary = "Summary: " + " | ".join(m["text"][:20] for m in old)
            self.messages = [m for m in self.messages if m not in old]
            self.messages.insert(0, {"user": user, "text": summary})

mem = ManagedMemory()
mem.upsert("stu-9", "major", "Mathematics")
mem.upsert("stu-9", "major", "Computer science")        # an update, not a duplicate
mem.upsert("stu-9", "status", "Traveling", ttl=0.1)      # temporary information
for i in range(6):
    mem.add_message("stu-9", f"Message number {i} about the study plan")

print(mem.get("stu-9", "major"), "| Previous values:", len(mem.history))
time.sleep(0.2)
print("Status after expiry:", mem.get("stu-9", "status"))
print("Number of messages after summarization:", len(mem.messages))
mem.forget_user("stu-9")
print("After the forget request:", mem.facts, mem.history, mem.messages)

Notice that forget_user deletes from all stores: facts, history, messages and summaries. In a real system this must also cover the vectors stored in the vector database and the backups, according to the adopted policy.

Summary

Memory management covers summarization to shrink the context, updating to avoid contradiction, and deletion and retention to protect the user and minimize data. Summarization loses detail, so exact facts are saved separately before it. Updating with a fixed key while keeping previous values prevents conflicts and allows auditing. A forget request must be carried out in every store, including summaries and vectors.

Terms

TermEnglishDefinition
SummarizationSummarizationReplacing old messages with a summary that keeps the essentials
UpsertUpsertWriting a value under a fixed key that replaces the old one or creates a new one
Time to liveTTL (Time To Live)A time after which the information expires and is deleted automatically
Right to be forgottenRight to be ForgottenThe user's right to have their data actually deleted from the system
Data minimizationData MinimizationSaving the least amount of data needed for the task

Review questions

  1. What should be saved separately before summarizing a long conversation? And why?
  2. How does updating with a fixed key prevent contradictory information?
  3. Why is it not enough to hide the user's data when they ask to be forgotten?
  4. Design a retention policy for an agent that helps book appointments at the university clinic.

References