Semantic memory: durable facts and preferences
Semantic memory keeps stable facts and preferences about a user or domain, extracted from conversations and retrieved when relevant. Use it so an assistant remembers who it is helping across sessions.
Semantic memory in 60 seconds
- What: a store of specific, stable facts, such as preferences, settings, and background, kept per user or per domain.
- How it works: extract facts from conversations, merge them with what is stored, and retrieve the relevant ones for a new question.
- Best for: personal assistants, support bots, and tutors that should not ask the same questions every session.
- Weak spots: wrong or outdated facts, privacy exposure, and retrieving facts that are not relevant.
- Framing: CoALA (Sumers et al., 2023) separates semantic memory, which holds facts, from episodic memory, which holds events.
Where this type fits
In the types of memory hub, long-term memory has three kinds: semantic, episodic, and procedural. Semantic memory holds what is true, such as 'prefers email over phone'. Episodic memory holds what happened, and procedural memory holds how to do things. Unlike session memory, semantic memory survives after a conversation ends.
The problem it solves
An assistant with only session memory starts every new conversation as a stranger. A returning customer must again say which plan they have, what language they prefer, and what they use the product for. The assistant seems forgetful, and users lose patience with repeating themselves.
Keeping whole old transcripts does not fix this. They are long, noisy, and costly to resend, and the one useful fact sits in the middle of small talk. What the assistant needs is the distilled fact, such as 'uses the Team plan', stored on its own and found quickly.
Semantic memory does that distilling. It turns conversations into short facts, keeps one current version of each, and fetches only the facts that relate to the present question. The prompt stays small, the assistant seems to know the user, and the facts can be shown, corrected, or deleted by the user.
How it works
- Observe: after a conversation or a meaningful exchange, pass the new messages to an extraction step.
- Extract: a model call lists candidate facts that are specific and stable, such as a preference or a setting. It skips one-off remarks and guesses.
- Merge: compare each candidate with stored facts. If it repeats one, update its timestamp. If it contradicts one, replace the old one and keep a note. If it is new, add it.
- Store: save each fact as a short sentence with a user id, a type, a source, a confidence, and dates, plus an embedding for search.
- Retrieve: when a new question arrives, embed it, find the closest facts for that user, and filter by relevance and freshness.
- Use: add the few matching facts to the prompt in a labelled section, so the model can use them but knows where they came from.
The top row is the write path and the bottom row is the read path. They run at different times. Writing can happen in the background after a chat ends, so it adds no delay for the user. Reading happens on the live request, so it must be fast, usually one embedding and one search.
The merge step is what separates a fact store from a heap of notes. Without it, the store fills with duplicates and contradictions, such as three versions of a user's city. With it, there is one current answer per fact. The CoALA framework (Sumers et al., 2023) names semantic memory as its own kind, because facts need different handling from events.
A worked example
Acme runs a project tool with an assistant. On 2 March, user Omar says in chat: 'I manage a team of eight, we ship every second Friday, and please keep answers short. Oh, and I moved to the Berlin office last month.' The extraction step reads the exchange.
[
{"fact": "Manages a team of eight", "type": "background", "confidence": 0.9, "merge": "added"},
{"fact": "Team ships every second Friday", "type": "background", "confidence": 0.9, "merge": "added"},
{"fact": "Prefers short answers", "type": "preference", "confidence": 0.95, "merge": "updated timestamp"},
{"fact": "Works in the Berlin office", "type": "background", "confidence": 0.8, "merge": "replaced 'Works in the London office'"}
]Three weeks later, Omar opens a new session and asks, 'Can you plan the next release?' The system embeds the question and searches Omar's facts. It returns 'Team ships every second Friday', 'Manages a team of eight', and 'Prefers short answers'. The Berlin fact scores low and is left out, since location does not bear on this question. These three lines add about 40 tokens. The assistant proposes a Friday date and a brief plan, without asking about cadence or team size.
If Omar says, 'I do not manage the team any more,' the next extraction pass flags a contradiction, lowers the confidence of the old fact, and replaces it. He can also open a 'what you remember about me' page and delete any fact himself.
Building it
import json
import time
# llm, embed(), and fact_store are placeholders for your own model call,
# embedding function, and per-user vector store.
MATCH_THRESHOLD = 0.88 # similarity above which two facts are 'the same slot'
TOP_K = 5 # facts retrieved per question
MIN_RELEVANCE = 0.55 # below this, a fact is not worth the tokens
MAX_FACT_AGE = 365 * 24 * 3600 # seconds; older facts need reconfirming
def extract_facts(messages):
raw = llm.generate(
'List stable facts or preferences the USER stated. Skip guesses and '
'one-off remarks. Reply as JSON list of {fact, type, confidence}.\n'
+ '\n'.join(messages))
try:
return json.loads(raw)
except json.JSONDecodeError:
return [] # a bad extraction should store nothing, not garbage
def merge(user_id, candidate):
if candidate['confidence'] < 0.7:
return # low-confidence facts are not stored
vector = embed(candidate['fact'])
near = fact_store.nearest(user_id, vector, k=1)
now = time.time()
if near and near[0]['score'] >= MATCH_THRESHOLD:
old = near[0]
# Ask the model whether it repeats or contradicts the old fact.
verdict = llm.generate(
f"Old: {old['fact']}\nNew: {candidate['fact']}\nReply SAME or CONFLICT.")
if 'CONFLICT' in verdict:
fact_store.replace(old['id'], candidate['fact'], vector, updated=now,
previous=old['fact'])
else:
fact_store.touch(old['id'], updated=now)
else:
fact_store.add(user_id, candidate['fact'], vector, candidate['type'], created=now)
def recall(user_id, question):
hits = fact_store.nearest(user_id, embed(question), k=TOP_K)
now = time.time()
keep = [h for h in hits
if h['score'] >= MIN_RELEVANCE and now - h['updated'] < MAX_FACT_AGE]
return [h['fact'] for h in keep]
def forget(user_id, fact_id):
fact_store.delete(user_id, fact_id) # users must be able to remove factsEvery lookup is scoped by user id, so one person's facts can never match another's question. The extraction step only reads what the user said, since facts the assistant itself stated may be wrong. Run the whole write path in the background and keep only the read path on the live request.
Design decisions
- Storage: default to a vector store with user id as a required filter, plus plain columns for type, source, and dates. Keep facts as short sentences.
- What counts as a fact: specific and stable. Store preferences, settings, and background. Do not store moods, guesses, or sensitive categories unless you need them and have consent.
- Write timing: extract in the background after the session, so the user waits for nothing and you can batch the model calls.
- Conflict handling: keep one current value per fact, and record the previous value and date. Prefer the user's latest statement over older ones.
- Retrieval limits: return at most 3 to 5 facts, with a minimum relevance score. Extra facts cost tokens and can distract.
- Access and privacy: isolate by user, encrypt at rest, let users view, correct, and delete facts, and set a retention period.
- Versioning: record the extraction prompt version and embedding model version on each fact, so you can re-extract or re-embed when they change.
Measuring it
- Extraction precision: facts a person judges correct and worth storing, divided by all facts extracted. Sample 100 conversations.
- Extraction recall: stable facts present in the transcript that were captured, divided by all such facts. Use a hand-labelled set.
- Retrieval hit rate: for test questions with a known needed fact, the share where that fact appears in the top results.
- Irrelevant-fact rate: retrieved facts that a person marks as not helpful, divided by all retrieved facts.
- Staleness: the share of stored facts that are no longer true, found by sampling and asking users or checking against records.
- Personalisation lift: compare answer quality or task success with and without memory on the same test set.
def retrieval_hit_rate(cases, k=5):
# cases: list of {'user_id': ..., 'question': ..., 'needed_fact': ...}
hits = 0
for case in cases:
facts = recall(case['user_id'], case['question'])[:k]
if any(case['needed_fact'].lower() in f.lower() for f in facts):
hits += 1
return hits / len(cases) if cases else 0.0When to use it, and when not to
| Situation | Use this type? | Why |
|---|---|---|
| Returning users who expect to be remembered | Yes | Stable preferences and background save repeated questions. |
| Support bot that needs plan or account context | Yes, but prefer live records | If a system of record exists, read it directly. Memory is for what records lack. |
| Tutor tracking what a learner knows | Yes | Skill and preference facts personalise the lessons. |
| Anonymous one-off visitors | No | There is no user to attach facts to, and storing them raises privacy risk. |
| Facts that change daily, such as stock or order status | No | Stored facts go stale. Fetch them live with a tool. |
| Need to recall what happened in a past task | No, use episodic | Events and outcomes belong in episodic memory. |
| Regulated or sensitive personal data | Only with consent and controls | Storing it creates legal duties around access, correction, and deletion. |
Trade-offs
| Dimension | Effect | What to do about it |
|---|---|---|
| Quality | Personal context improves relevance, but a wrong fact misleads every future chat | Store only confident facts, show them to users, and let users correct them. |
| Latency | One embedding and one search on the live path, which is small | Run extraction in the background and keep retrieval limits tight. |
| Cost | Extra model calls to extract and merge, plus storage | Batch after sessions, skip short chats, and use a smaller model for extraction. |
| Complexity | Extraction, merge rules, deletion, and consent handling | Start with a small fact schema and one fact type, then widen. |
| Failure modes | Stale facts, contradictions, cross-user leakage, and over-personalisation | Date every fact, scope by user id, test isolation, and expire old facts. |
Compared with related types
Session memory keeps the story of one conversation and expires. Semantic memory keeps the lasting facts and does not. Episodic memory keeps events with their outcomes, such as how a past task went, while semantic memory keeps timeless statements. A fact like 'prefers short answers' is semantic. 'Last Tuesday the refund failed and was retried' is episodic.
RAG with memory shows how stored facts and history can shape retrieval from documents. The two stores differ in source: semantic memory is learned about a user from their own chats, while a document index holds shared knowledge. Keep them separate.
What this means for your role
Common mistakes
Further reading
- Types of memory: the hub that compares every memory type.
- Cognitive Architectures for Language Agents (CoALA), Sumers et al., 2023: a framework that organises language-agent memory into working, episodic, semantic, and procedural memory.
- Vector search and chunking: how facts are embedded and found by meaning.
- Guardrails and safety: controls for handling personal data in AI systems.
Semantic memory works when facts are few, current, and owned by the user. Start with a handful of fact types, keep the merge rules strict, and let people see what you remember.