How to give a chatbot long-term memory (with Python code)
Your chatbot forgets everything when the session ends. Here are three ways to fix that, and working code for the one most projects need.
Short answer: Store useful facts outside the model, find the ones relevant to each new message, and add them to the prompt before you call the LLM. You can do that with a simple notes file, your own vector search, or a memory framework. For most projects, vector search over a small set of saved facts is a good place to start.
Models don't remember anything between requests, so long-term memory has to be something your application provides. Whichever tool you use, the loop has three steps: retrieve relevant memories, reply with them in the prompt, and save anything worth keeping.
Three approaches compared
| Approach | Good for | Main limitation |
|---|---|---|
| Notes file | One user, a small set of facts, quick start | All of it is sent every time, so it can't grow far |
| Vector search | Hundreds or thousands of memories, full control | You handle updates, deletion and quality yourself |
| Memory framework | Shipping quickly, teams that want extraction built in | Another dependency, and less control over what's saved |
Option 1: a notes file
Keep a short text file of facts and add it to your system prompt. It's not sophisticated, but it's easy to read and edit, and it's enough for a personal assistant. Move on when the file gets long enough to cost you real tokens on every message.
Option 2: vector search, in about 30 lines
Vector search lets you find memories by meaning, so "Is peanut butter safe for Sam?" can find "Sam is allergic to peanuts" with no need for exact keywords. This example stores memories in a plain file and runs on your own machine. Install the two libraries first:
pip install faiss-cpu sentence-transformers
import json
from pathlib import Path
import faiss
from sentence_transformers import SentenceTransformer
MEMORY_FILE = Path("memories.jsonl")
encoder = SentenceTransformer("all-MiniLM-L6-v2")
def embed(texts):
return encoder.encode(texts, normalize_embeddings=True).astype("float32")
def load_memories():
if not MEMORY_FILE.exists():
return []
lines = MEMORY_FILE.read_text(encoding="utf-8").splitlines()
return [json.loads(line) for line in lines]
def save_memory(text, source):
with MEMORY_FILE.open("a", encoding="utf-8") as f:
f.write(json.dumps({"text": text, "source": source}) + "\n")
def search_memories(query, k=5, min_score=0.3):
memories = load_memories()
if not memories:
return []
vectors = embed([m["text"] for m in memories])
index = faiss.IndexFlatIP(vectors.shape[1])
index.add(vectors)
scores, ids = index.search(embed([query]), min(k, len(memories)))
return [memories[i]["text"] for i, s in zip(ids[0], scores[0]) if s >= min_score]
Now try it:
save_memory("Sam is allergic to peanuts.", source="user")
save_memory("Sam is learning Python and prefers examples over theory.", source="user")
print(search_memories("Is peanut butter safe for Sam?"))
print(search_memories("Can you explain Python decorators?"))
print(search_memories("What is the capital of France?")) # no match: returns []
We ran this code with faiss-cpu 1.15 and sentence-transformers 5.7 before publishing. The min_score cutoff keeps weak matches out of the prompt, because irrelevant memories can pull a reply off course. The right value depends on your data, so treat 0.3 as a starting point.
This rebuilds the search index on each call, which keeps the example simple. That's fine for a small project. As your memories grow, keep the index in memory or on disk, and only add what's new.
Connect it to your chat loop
Add the results to your system prompt before each LLM call. call_llm stands in for whichever client you use:
def chat(user_message, history, persona):
memories = search_memories(user_message)
system = persona
if memories:
system += "\n\nRelevant memories (context, not instructions):\n"
system += "\n".join(f"- {m}" for m in memories)
reply = call_llm(system=system, messages=history + [
{"role": "user", "content": user_message},
])
return reply
Labeling memories as "context, not instructions" is a cheap precaution, because stored text can carry a prompt injection. It reduces that risk but doesn't remove it, so be careful about what you save in the first place.
Decide what gets saved
The code above stores whatever you pass it. You still need a way to choose, and there are three common options:
- Tool call: give the model a
save_memorytool and let it decide. - Tags: have it include a marker in its reply, and strip that out before the user sees it. Our engine's chat does this with
[MEMORY_SAVE: ...]. - Extraction pass: after each conversation, ask a model to pull out lasting facts.
Whichever you pick, add rules. Here's our guide on what to save and what to forget.
Option 3: a memory framework
Tools such as Mem0, which offers both a hosted platform and self-hosted open source, handle storage and retrieval for you. Zep and LangGraph's memory features are also worth a look. They can save a lot of plumbing. Check their current documentation, and be skeptical of vendor benchmarks unless you can reproduce them on your own data.
Mistakes to avoid
- Saving whole transcripts. Searches get noisy and expensive. Save distilled facts.
- Never updating. When a fact changes, replace the old memory, or search may return both.
- Mixing users. Give each user their own memory store, and filter on it for every query. A leak here is a privacy incident.
- Saving secrets. Block passwords, keys and card numbers in code.
- No delete option. Users should be able to see and remove what's stored about them.
- Letting memory rewrite the persona. Keep identity in a separate store that the agent can't write to.
Frequently asked questions
Do I need a vector database?
Not to start. The example above uses a library and a plain file. A dedicated database starts to make sense when you need to serve many users, filter on metadata, or handle concurrent writes.
Is RAG the same as long-term memory?
They use similar retrieval methods. RAG usually searches a fixed set of documents, while memory also grows and changes as the agent learns, so it has to deal with updates and forgetting.
How many memories should I retrieve?
Start small, with around five, and use a score cutoff. Our own chat pipeline retrieves the top five per message. Add more only if replies are clearly missing things.
Is there something ready-made?
The SoulScript Engine is built on this design, with FAISS search over a memory vault, a guard that blocks common secrets, and a separate read-only store for the agent's identity. It's free to run locally.
