Velamuvi AIAcademy

Lesson 3 of 5 · Memory

Summarising History

Keep the gist of long agent conversations with rolling summaries: when to summarise, what to keep, summary drift, pinned facts and archiving the originals.

  • 7 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Replace old messages with a rolling summary instead of dropping them
  • Write a summary prompt that keeps facts, decisions and open tasks
  • Decide when to summarise, and with which model
  • Prevent summary drift with pinned facts and archived originals

Compress instead of forgetting

A sliding window throws old messages away. Summarising keeps their gist: when the history gets too long, the oldest messages are replaced by a short summary, and the agent keeps the summary plus the most recent messages.

Here's the mechanism. The summarise function stands in for an LLM call; it keeps sentences containing facts or decisions so you can see exactly what survives:

Try it yourselfPython
def summarise(old_summary, turns):
    """Stands in for an LLM call: 'Update the summary with the key facts and decisions from these turns.'
    Here it keeps sentences with facts or decisions, so you can see what survives."""
    keep_words = ("budget", "prefer", "decided", "allergic", "deadline", "booked", "must")
    facts = [t for _, t in turns if any(w in t.lower() for w in keep_words)]
    return (old_summary + " " + " ".join(facts)).strip()

class SummarisingMemory:
    def __init__(self, keep_recent=4, summarise_every=6):
        self.summary, self.recent = "", []
        self.keep_recent, self.summarise_every = keep_recent, summarise_every

    def add(self, role, text):
        self.recent.append((role, text))
        if len(self.recent) >= self.summarise_every:          # time to compress the oldest turns
            old = self.recent[:-self.keep_recent]
            self.recent = self.recent[-self.keep_recent:]
            self.summary = summarise(self.summary, old)

    def context(self):
        header = [("system", f"Summary of earlier conversation: {self.summary}")] if self.summary else []
        return header + self.recent

m = SummarisingMemory()
chat = [
    ("user", "We're planning the team offsite. Budget is 4,000 euros."),
    ("assistant", "Great, how many people?"),
    ("user", "Twelve people. Two are vegetarian and one is allergic to nuts."),
    ("assistant", "Noted. Any date in mind?"),
    ("user", "We decided on 12 March. The venue must be near a train station."),
    ("assistant", "I'll look for venues near stations."),
    ("user", "Also, people prefer a quiet place over a city centre."),
    ("assistant", "Understood: quiet, near a station, 12 March."),
    ("user", "What venues do you suggest?"),
]
for role, text in chat:
    m.add(role, text)

for role, text in m.context():
    print(f"{role:>9}: {text}")

Each time six messages pile up, the memory folds all but the four newest into the summary. The summary kept the budget, group size, diets and allergy, and dropped the assistant's questions. The most recent messages are still there word for word, so the agent can respond naturally to the current exchange.

A real summariser

In a real agent, the summary is written by a model. The prompt matters: tell it what to keep and what to drop.

import anthropic

client = anthropic.Anthropic()          # reads ANTHROPIC_API_KEY from the environment

SUMMARY_PROMPT = """You maintain the running summary of a conversation between a user and an assistant.
Update the summary using the new messages below. Keep:
- facts about the user and their preferences
- decisions made and the reasons for them
- numbers, dates, names and amounts, exactly as written
- open questions and tasks still to do
Drop greetings, small talk and anything already done that no longer matters.
Write short third-person notes. At most 200 words.

Current summary:
{summary}

New messages:
{messages}"""

def update_summary(summary, old_messages):
    text = "\n".join(f"{m['role']}: {m['content']}" for m in old_messages)
    response = client.messages.create(
        model="MODEL_NAME",              # a small, fast model is usually enough for summaries
        max_tokens=400,
        messages=[{"role": "user",
                   "content": SUMMARY_PROMPT.format(summary=summary or "(none yet)", messages=text)}],
    )
    return response.content[0].text

When to summarise

Summarising costs a model call, so don't do it on every turn. Common triggers:

  • A token threshold: when the history passes, say, 70–80% of your budget, summarise the oldest half in one go.
  • A message count: every N messages, as in the demo.
  • The end of a session: write a summary when the conversation finishes, ready for the next session (and for long-term memory, lesson 4).
  • In the background: summarise after replying, so the user doesn't wait for it.

Summary drift

Summaries have a weakness. Each update re-summarises the previous summary, and every pass is a chance to lose something. Facts that were mentioned once, long ago, get squeezed out by newer topics:

Try it yourselfPython
# Summary drift: when a summary is re-summarised again and again,
# older details get squeezed out by newer ones.
def short_summary(sentences, max_sentences=3):
    """Stands in for an LLM asked to 'summarise in at most 3 sentences'.
    Like many real summaries, it favours what was discussed most recently."""
    return sentences[-max_sentences:]

pinned = ["One person is allergic to nuts.", "Budget is 4,000 euros."]   # kept separately, never summarised

summary = ["Offsite for 12 people on 12 March.", "One person is allergic to nuts.", "Budget is 4,000 euros."]
new_topics = ["Shortlisted three venues near stations.", "Compared train times.", "Chose a menu with the caterer."]

for round_, topic in enumerate(new_topics, start=1):
    summary = short_summary(summary + [topic])
    print(f"Round {round_}: {' '.join(summary)}")

print()
print("Summary still mentions the allergy?", any("allergic" in s for s in summary))
print("Pinned facts still mention it?    ", any("allergic" in s for s in pinned))

After three rounds the allergy has vanished from the summary, but it's safe in the pinned facts, which are never summarised.

Three defences, best used together:

  1. Pin critical facts separately (lesson 2), so the summariser never touches them.
  2. Archive the originals. Keep the full messages in a database even after they leave the context. If the agent needs an exact detail, it can search for it (lesson 4).
  3. Tell the summariser what must survive, and test it: feed it conversations with known facts and check those facts are still in the summary.

Common mistakes

Practice exercise

Write the trigger that decides when to summarise: once the history is too long, fold the older messages into the summary and keep only the most recent ones.

Your solutionPython
history = [f"msg {i}" for i in range(1, 11)]     # 10 messages, oldest first
max_messages, keep_recent = 8, 3
summarised = []                                 # messages folded into the summary

# If history has more than max_messages, move every message except the last
# keep_recent into summarised. Then print:
# Summarised: <how many>
# Kept: <the remaining history list>
Knowledge check

Why keep pinned facts separate from the rolling summary?

Summary

  • A rolling summary replaces old messages with their gist, while recent messages stay verbatim.
  • A good summary prompt keeps facts, decisions, exact numbers and open tasks, and drops small talk.
  • Summarise on a token threshold, a message count, at session end or in the background, often with a smaller model.
  • Guard against summary drift with pinned facts, archived originals and tests.

Next: long-term memory with vector stores, remembering across sessions.

Finished reading? Tick it off to track your progress.