Agent Memory

Keep the last few messages word for word and move older ones into notes, so long conversations still fit the context window.

AI · intermediate · 6 min · 23 steps · free

What you'll learn

memory.py

MAX_RECENT = 3

def remember(memory, role, text):
    memory['recent'].append(f'{role}: {text}')
    if len(memory['recent']) > MAX_RECENT:
        oldest = memory['recent'].pop(0)
        memory['notes'].append(oldest)

memory = {'notes': [], 'recent': []}
remember(memory, 'user', 'my name is Ada')
remember(memory, 'bot', 'hi Ada')
remember(memory, 'user', 'I like tea')
remember(memory, 'bot', 'tea noted')
print(memory['recent'])
print(memory['notes'])

Step by step

  1. MAX_RECENT is created with the value 3.
  2. Python defines the function remember(). Its body does not run yet: it runs each time the function is called.
  3. memory is created and points to a new dict: {notes: a list, recent: a list}.
  4. Python calls remember(), with memory = {notes: a list, recent: a list}, role = 'user' and text = 'my name is Ada'. It gets its own names.
  5. The first message goes into recent memory.
  6. len(memory['recent']) > MAX_RECENT is false, so the block under it is skipped.
  7. remember() has finished, so its names are gone.
  8. Python calls remember(), with memory = {notes: a list, recent: a list}, role = 'bot' and text = 'hi Ada'. It gets its own names.
  9. 'bot: hi Ada' is added to the end of the list object.
  10. len(memory['recent']) > MAX_RECENT is false, so the block under it is skipped.
  11. remember() has finished, so its names are gone.
  12. Python calls remember(), with memory = {notes: a list, recent: a list}, role = 'user' and text = 'I like tea'. It gets its own names.
  13. 'user: I like tea' is added to the end of the list object.
  14. len(memory['recent']) > MAX_RECENT is false, so the block under it is skipped.
  15. remember() has finished, so its names are gone.
  16. Python calls remember(), with memory = {notes: a list, recent: a list}, role = 'bot' and text = 'tea noted'. It gets its own names.
  17. 'bot: tea noted' is added to the end of the list object.
  18. Four messages, but only 3 fit in recent memory.
  19. oldest is created with the value 'user: my name is Ada'. 'user: my name is Ada' is removed from the start of the list object.
  20. The oldest message moves to notes instead of being lost.
  21. remember() has finished, so its names are gone.
  22. It prints ['bot: hi Ada', 'user: I like tea', 'bot: tea noted'].
  23. It prints ['user: my name is Ada'].

Common mistakes

Best practices

Key takeaways

Check yourself

Why not keep every message?

Answer: The context window and cost are limited

Where would "my name is Ada" best live?

Answer: Long-term notes

·

More in Agents