Long-Term Knowledge Storage and Retrieval › Storing Information for Later

Michael BrenndoerferJuly 3, 20251 min read
AI Agent HandbookAll chapters
Part 6 of 15Memory and Retrieval - How Agents Remember
Chapter 16Long-Term Knowledge Storage and Retrieval › Storing Information for Later
Reading section 3 of 13 · Storing Information for Later · 1 minSection 3 of 13 · 1 min

Book contents

Section 3 of 13 · 1 min read

Long-Term Knowledge Storage and Retrieval › Storing Information for LaterOne section · Sections in this chapter3 / 13 ↓
Reading tools Definitions & inline links

Toggle tooltip visibility. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

The simplest form of long-term memory is a key-value store. You save information with a label (the key) and retrieve it later using that same label.

Here's a basic example using a Python dictionary that persists to a file:

In[3]:
Code
import json
import os


class SimpleMemory:
    def __init__(self, memory_file="assistant_memory.json"):
        self.memory_file = memory_file
        self.memory = self._load_memory()

    def _load_memory(self):
        """Load memory from file if it exists"""
        if os.path.exists(self.memory_file):
            with open(self.memory_file, "r") as f:
                return json.load(f)
        return {}

    def _save_memory(self):
        """Save memory to file"""
        with open(self.memory_file, "w") as f:
            json.dump(self.memory, f, indent=2)

    def store(self, key, value):
        """Store a fact in long-term memory"""
        self.memory[key] = value
        self._save_memory()
        return f"Remembered: {key}"

    def retrieve(self, key):
        """Retrieve a fact from long-term memory"""
        return self.memory.get(key, "I don't have that information stored.")


## Example usage
memory = SimpleMemory()
memory.store("user_birthday", "July 20")
memory.store("favorite_restaurant", "Luigi's Italian Kitchen")

## Later, even after restarting the program
print(memory.retrieve("user_birthday"))  # Output: July 20
Out[3]:
Console
July 20

This works, but it has a limitation: you need to know the exact key to retrieve information. What if you want to ask, "What do you know about my food preferences?" The assistant would need to search through all stored information to find relevant facts.