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
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'])MAX_RECENT is created with the value 3.remember(). Its body does not run yet: it runs each time the function is called.memory is created and points to a new dict: {notes: a list, recent: a list}.remember(), with memory = {notes: a list, recent: a list}, role = 'user' and text = 'my name is Ada'. It gets its own names.len(memory['recent']) > MAX_RECENT is false, so the block under it is skipped.remember() has finished, so its names are gone.remember(), with memory = {notes: a list, recent: a list}, role = 'bot' and text = 'hi Ada'. It gets its own names.len(memory['recent']) > MAX_RECENT is false, so the block under it is skipped.remember() has finished, so its names are gone.remember(), with memory = {notes: a list, recent: a list}, role = 'user' and text = 'I like tea'. It gets its own names.len(memory['recent']) > MAX_RECENT is false, so the block under it is skipped.remember() has finished, so its names are gone.remember(), with memory = {notes: a list, recent: a list}, role = 'bot' and text = 'tea noted'. It gets its own names.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.notes instead of being lost.remember() has finished, so its names are gone.['bot: hi Ada', 'user: I like tea', 'bot: tea noted'].['user: my name is Ada'].Answer: The context window and cost are limited
Answer: Long-term notes
← The Agent Loop: Think, Act, Observe · Planning: Breaking a Goal into Steps →