Long-term memory the agent writes itself
Sessions remember the literal conversation. Memory remembers facts. The user told you their dog's name on Tuesday. By Thursday, the Tuesday session might be summarised or even gone. Memory is where 'dog named Max' lives so the agent can find it again.
def save_memory(topic: str, content: str) -> str:
"""Save a memory to a markdown file."""
filename = re.sub(r'[^\w\s-]', '', topic).strip().replace(' ', '-').lower()
if not filename:
filename = "misc"
filepath = MEMORY_DIR / f"{filename}.md"
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M")
entry = f"\n## {topic} ({timestamp})\n{content}\n"
with open(filepath, "a") as f:
f.write(entry)
return f"Saved memory about '{topic}' to {filepath.name}"save_memory writes a markdown file per topic. Topic becomes the filename. Entries append over time so memory grows like a journal.
def memory_search(query: str) -> str:
"""Search memory files for keywords."""
query_words = query.lower().split()
results = []
for filepath in MEMORY_DIR.glob("*.md"):
text = filepath.read_text()
matches = sum(1 for word in query_words if word in text.lower())
if matches > 0:
results.append((matches, filepath.stem, text[:500]))
if not results:
return "No memories found matching that query."
results.sort(reverse=True)
output_parts = []
for score, name, text in results[:5]:
output_parts.append(f"--- {name} (relevance: {score}) ---\n{text}")
return "\n\n".join(output_parts)Simple keyword scoring. Tokenise the query, count matches in each memory file, return the best few. No embeddings, no vector DB. The point is to see what the bare minimum looks like.
Adding the tools is the easy part. Getting the model to USE them is a SOUL question. We extend SOUL with a Memory Strategy section that says: when the user shares a fact, save it; before answering personal questions, search.
SOUL = """# OpenClaw
You are OpenClaw, a personal AI assistant.
## Personality
- Helpful, concise, and technically competent
- Friendly but professional tone
## Boundaries
- Don't pretend to browse the internet
- Don't make up information
## Memory Strategy
- When the user shares important facts (preferences, name, work, projects), proactively use save_memory to store them
- Before answering questions about the user, check memory_search first
- Reference remembered facts naturally in conversation
- Save memories with descriptive topics for easy retrieval later
"""The extended SOUL. Notice the Memory Strategy section is plain English instructions, not code.
You absolutely can, and at scale you probably should. The reason we keep it to markdown files plus keyword search is to make the mechanism visible. You can cat the memory directory and see what your agent knows. Once you can see it, you can choose to upgrade the search part with embeddings while leaving the storage layout the same.
AI prompt: Try it: train the agent on yourself
Loading practice…