AI AgentsAgent Memory

What is the difference between Episodic Memory and Semantic Memory in AI agents?

Question 279 of 280 · Updated

On this page

Episodic memory stores specific experiences; semantic memory stores the general facts and knowledge that can be reused beyond any one experience. An AI agent uses episodic memory to answer “What happened last time, when, and with what result?” and semantic memory to answer “What do we know to be true?”

The two are complementary. An agent that stores only facts may know that a deployment uses PostgreSQL but forget that yesterday's migration failed. An agent that stores only event logs may remember every deployment attempt but struggle to extract the stable fact that the project uses PostgreSQL 16.

1. The core distinction#

The distinction comes from cognitive science. Endel Tulving's influential 1972 account described episodic memory as memory for dated events and their temporal or spatial relationships, while semantic memory represents organized knowledge, meanings, concepts, and relationships. AI systems borrow this useful functional distinction; they do not reproduce human consciousness or biological memory.

  • Episodic memory — experience: a particular interaction, task, observation, decision, tool call, or outcome, tied to its context and time.
  • Semantic memory — knowledge: a generalized fact, concept, relationship, preference, or state that can be used without replaying the original event.

Think of a support agent:

  • Episodic: “On 18 November, the customer reported a 503 error. We checked the service logs, restarted worker B, and requests recovered after 40 seconds.”
  • Semantic: “The customer’s application runs three workers behind a load balancer.”
  • A possible learned rule (procedural memory): “Before restarting a worker, drain its traffic and run the health check.”

These memories answer different questions. The episode preserves what actually happened. The semantic fact captures reusable knowledge. The procedure describes how to act.

2. A beginner-friendly numerical example#

Imagine an agent helps a team with deployments.

It records three events:

  1. Monday, 09:10 — release 2.4 failed because environment variable DATABASE_URL was missing.
  2. Tuesday, 14:20 — release 2.4.1 failed for the same reason in staging.
  3. Wednesday, 11:05 — release 2.4.2 succeeded after the variable was added to the staging configuration.

These are three episodic memories. Each needs its own timestamp, environment, release, action, evidence, and outcome.

After checking that the events refer to the same project and issue, a memory-consolidation process may derive a semantic memory:

> The staging deployment for Project Atlas requires DATABASE_URL to be configured.

The derived fact is useful on future deployments. It should retain links to the three source episodes, confidence, scope, and the date it was last verified. The agent must not infer that every deployment failure is caused by this variable: the episodes support a narrower conclusion.

A second numerical illustration:

  • 12 recorded support sessions mention that the user asks for short status summaries.
  • 9 of those sessions explicitly request a brief format.
  • The system may consolidate the repeated evidence into “User generally prefers concise status summaries,” with confidence 0.9 (an illustrative score, not a universal threshold).

The 12 sessions remain episodic evidence. The concise preference is a semantic summary. If the user later says “For this incident, give me the full detail,” that current instruction takes precedence for the task.

3. Side-by-side comparison#

DimensionEpisodic memorySemantic memory
Main questionWhat happened? When? Where? What followed?What is known? What is generally true?
UnitEvent or experienceFact, concept, relationship
ContextStrongly tied to time, task, actor, and situationCan be used apart from the original event
Typical contentConversation episode, tool trace, decision, resultUser preference, project fact, domain concept
OrganizationChronological, event-based, task/run-basedEntity-, concept-, attribute-, or relation-based
Retrieval cuesTime, task, participant, outcome, similar situationEntity, attribute, concept, relationship, meaning
Update patternAppend a new event; correct or annotate an event carefullyRevise, supersede, qualify, or expire a fact
Main riskMissing context or outcome; too many noisy episodesStale, overgeneralized, or conflicting facts
Best useRecall prior attempts and decisionsApply stable knowledge across tasks

This is a functional distinction, not a requirement for two separate database products. A single database can hold both types if records are typed and retrieval respects their different needs.

4. Memory representations and schemas#

Episodic representation#

An episode should preserve enough context to explain the event later. A practical record might look like:

JSON
{ "memory_type": "episodic", "event_id": "evt-1042", "tenant_id": "tenant-7", "user_id": "user-23", "agent_id": "deployment-agent", "run_id": "run-88", "event_time": "2026-11-18T09:10:00Z", "recorded_at": "2026-11-18T09:10:04Z", "task": "deploy Project Atlas release 2.4", "context": {"environment": "staging"}, "actions": ["checked logs", "inspected environment"], "observation": "DATABASE_URL was missing", "outcome": "deployment_failed", "source_refs": ["trace-991", "message-501"], "confidence": 0.98, "retention_class": "operational" }

The exact fields depend on the application. Important design points:

  • Keep event time (when it happened) separate from recorded time (when the system stored it). Late-arriving events are common.
  • Store the actor, tenant, project, run, and environment scope. An episode from one customer or project must not leak into another.
  • Preserve action and outcome separately. “Restarted service” without “recovered” or “did not recover” is incomplete experience.
  • Keep provenance: source message IDs, trace IDs, tool outputs, or document references. A generated summary is not a substitute for the underlying evidence.
  • Store only the context needed for future recall; do not copy an entire sensitive transcript by default.

Semantic representation#

Semantic memory is often best represented as a typed fact or relationship:

JSON
{ "memory_type": "semantic", "subject": "Project Atlas", "predicate": "requires_environment_variable", "object": "DATABASE_URL", "scope": "staging", "valid_from": "2026-11-18T09:10:00Z", "valid_to": null, "confidence": 0.94, "source_episode_ids": ["evt-1042", "evt-1057", "evt-1088"], "last_verified_at": "2026-11-19T11:05:00Z", "status": "active" }

Semantic records can also be stored as structured profiles, key-value attributes, relational rows, knowledge-graph triples, or concise text facts. Choose the representation based on the queries and update rules the application needs.

Important: a fact should not lose its scope or validity just because it is semantic. “Project Atlas uses PostgreSQL” may be true for one project and false for another. Facts about changing configurations should carry validity dates and provenance.

5. Storage: separate logical types, not necessarily separate databases#

A common production design uses:

  • Relational or document storage for canonical memory records, timestamps, scope, permissions, status, and provenance.
  • Vector index for embeddings and approximate semantic similarity.
  • Keyword or full-text index for exact identifiers, error codes, names, and phrases.
  • Graph or relationship index when multi-hop entity relationships matter.
  • Object storage or trace storage for larger source artifacts, with memory records holding protected references rather than duplicating them.

Episodic records tend to be append-oriented because each event is a distinct occurrence. Semantic facts need explicit update and conflict-resolution semantics: a new fact may supersede an old one, narrow its scope, or show that two facts apply to different environments.

Do not assume that episodic means short-term or semantic means long-term. Both can be retained for a short or long period. “Episodic versus semantic” describes the *kind of information*. “Short-term versus long-term” describes *retention and scope*. A timestamped episode may be retained for years for audit, while a semantic fact such as a temporary deployment region may expire tomorrow.

6. Retrieval: use the right question and ranking signals#

Retrieving episodic memory#

For “What did we try in the last deployment incident?”, filter by authorized tenant and project, then retrieve episodes using a combination of:

  1. Exact metadata filters: project, environment, task type, run, participant.
  2. Time range: recent incidents or a named date.
  3. Keyword search: release number, error code, tool name.
  4. Embedding similarity: similar symptoms or task descriptions.
  5. Outcome and status: failed attempts, successful fixes, unresolved actions.

A simple ranking function could be:

[ = 0.40R + 0.25T + 0.15O + 0.10C + 0.10P ]

where (R) is semantic relevance, (T) is time relevance, (O) is outcome match, (C) is context match, and (P) is provenance quality. These weights are illustrative and must be tuned and evaluated for the application. A “last time” query should give time and task context meaningful weight; a “similar error” query may emphasize symptom similarity.

Retrieving semantic memory#

For “Which database does Project Atlas use?”, a structured lookup by project and attribute is often safer and cheaper than vector search. For a broader question such as “What are the team's database conventions?”, hybrid retrieval can combine:

  • entity and metadata filters;
  • exact keyword matching;
  • vector similarity for paraphrased concepts;
  • graph traversal for relationships;
  • validity and confidence checks.

Embeddings help match meaning, but an embedding is not the memory itself. It is a numerical representation used to find candidate records. Similarity does not prove that a fact is true, current, authorized, or applicable.

A practical retrieval pipeline#

  1. Authenticate the caller and establish tenant/user/project scope.
  2. Classify the query: event recall, factual lookup, or both.
  3. Apply authorization and metadata filters before returning candidates.
  4. Retrieve from the appropriate memory type using structured, keyword, and/or vector search.
  5. Re-rank by relevance, recency, validity, outcome, and source quality.
  6. Return a small set of records with timestamps and provenance.
  7. Place only the minimum useful evidence into the model's active context.
  8. Ask for clarification or verify against a live source if evidence conflicts or is too weak.

Never rely on the model to remember to enforce tenant authorization after retrieval. Access control belongs in the retrieval layer.

7. Embeddings: useful for both, but not sufficient#

Both episodic and semantic records can be embedded. The embedding model maps text to vectors so semantically related records can be found even when wording differs.

Example:

  • Stored episode: “The staging rollout returned HTTP 503 after worker restart.”
  • Query: “Have we seen service-unavailable errors after a restart?”

Vector similarity may surface the episode despite the different wording.

For semantic memory:

  • Stored fact: “Project Atlas deploys to ap-south-1.”
  • Query: “Which cloud region hosts Atlas?”

An embedding can help locate the fact, but a structured field lookup is more deterministic when the question asks for a precise attribute.

Use a hybrid approach:

  • vectors for fuzzy semantic matching;
  • SQL/metadata filters for tenant, dates, scope, type, and validity;
  • keyword search for exact identifiers;
  • graph links for entity relationships.

Do not use vector similarity as a substitute for deduplication, truth validation, or authorization. Two similar memories may describe different releases, customers, or time periods.

8. Temporal context and changing facts#

Temporal metadata is especially important because episodes are inherently dated and semantic facts can change.

For each record, consider:

  • event time: when the event or fact was true;
  • recorded time: when it entered the memory system;
  • valid-from / valid-to: the period during which a fact applies;
  • last verified time: when the system last checked it;
  • supersedes / contradicts: links to older or conflicting records.

Example:

  • Semantic fact A: “Project Atlas uses PostgreSQL 14,” valid until 10 November.
  • Semantic fact B: “Project Atlas uses PostgreSQL 16,” valid from 10 November.
  • Episodic record: “On 10 November, the migration to PostgreSQL 16 completed successfully.”

The event records the migration. The semantic fact describes the current configuration. A query asking “What database version do we use now?” should select the currently valid fact, not simply the most similar or oldest record.

Recency alone is not truth. A recent unverified model inference should not automatically override an authoritative configuration file or explicit correction. Consider source authority, scope, verification, and time together.

9. Consolidation: how episodes become knowledge#

Consolidation converts useful patterns from multiple experiences into a more compact, reusable representation.

A typical pipeline:

  1. Capture an episode with source, time, context, action, and outcome.
  2. Group related episodes by entity, task, and topic.
  3. Detect repeated evidence, contradictions, and exceptions.
  4. Ask an extraction or reasoning model to propose a generalized fact.
  5. Validate the proposal against source records and applicable policy.
  6. Store the semantic fact with confidence, scope, validity, and source links.
  7. Keep the original episodes according to retention policy.
  8. Revisit or invalidate the semantic fact when new evidence arrives.

Example: five separate episodes show that a particular API returns rate-limit errors during a specific peak period. The system may derive “The API is rate-limited during the weekday 09:00–10:00 UTC peak.” It should not generalize this to “The API is always unreliable.”

Park and colleagues' *Generative Agents* architecture is a useful research example: it stores experience records, retrieves relevant memories dynamically, and periodically synthesizes higher-level reflections from them. This demonstrates an architectural pattern, not proof that an LLM-generated reflection is always correct.

Consolidation should be reviewable and reversible. Keep source episode IDs so engineers can inspect why a semantic fact exists and correct it if the abstraction is wrong.

10. Forgetting, expiration, and retention#

A memory system should not preserve every item forever.

Episodic memory policies

  • Expire low-value operational events after a defined retention period.
  • Retain incident episodes longer when required for reliability analysis or audit.
  • Deduplicate repeated ingestion using stable event IDs or source hashes.
  • Archive large traces and retain only protected references in the memory index.
  • Preserve important failure outcomes so the agent does not repeat known unsuccessful approaches.

Semantic memory policies

  • Expire temporary facts using TTL or valid-to dates.
  • Re-verify high-impact facts before acting on them.
  • Supersede outdated facts instead of leaving conflicting records equally active.
  • Remove inferred facts that lack adequate evidence.
  • Ask the user or consult an authoritative source when a conflict cannot be resolved.

A useful forgetting policy considers value, confidence, recency, access frequency, sensitivity, and legal retention requirements. Retrieval decay is not the same as deletion: lowering a score does not remove data from storage, backups, logs, or derived indexes.

11. Privacy and security#

Both memory types can contain sensitive information. Episodic records may expose detailed conversations, actions, and tool results; semantic records may retain sensitive personal or business facts for a long time.

Use these controls:

  • Minimize what is written; do not store secrets, passwords, or access tokens as ordinary memory.
  • Scope records by tenant, user, agent, project, and purpose.
  • Enforce authorization before search, including vector and graph retrieval.
  • Encrypt data in transit and at rest; protect backups, caches, and logs.
  • Store provenance and access audit events without unnecessarily copying sensitive content.
  • Provide correction, export, retention, and deletion workflows.
  • Propagate deletion or correction to embeddings, graph indexes, caches, and derived summaries.
  • Avoid injecting unrelated memories into prompts or sending them to external tools.
  • Treat retrieved memory as untrusted data, not as executable instructions. A past user message or tool output must not override system policy.

Semantic memory can create a persistent profile, so a seemingly harmless inference may become privacy-sensitive when retained and reused. Episodic memory can be even more revealing because it preserves detailed histories. Apply the same data-minimization and access-control discipline to both.

12. Latency and cost trade-offs#

The costs depend on implementation; neither type is inherently expensive.

OperationEpisodic memorySemantic memory
WriteOften frequent event capture, metadata extraction, trace referencesFact extraction, normalization, conflict checks
StorageCan grow quickly with event volume and contextOften smaller, but graph/profile complexity can grow
RetrievalMay require time, task, outcome, and similarity rankingOften fast structured lookup; broader knowledge may need hybrid search
ProcessingEvent summarization and outcome classificationFact consolidation, entity resolution, validity updates
Main cost driverVolume and context retained per episodeExtraction/update quality and retrieval correctness

Illustrative latency budget for a memory-enabled agent (not a benchmark):

  • metadata-filtered semantic fact lookup: 5–20 ms;
  • vector retrieval: 20–80 ms;
  • hybrid retrieval and re-ranking: 30–120 ms;
  • an LLM-based extraction or consolidation pass: hundreds of milliseconds to several seconds.

Actual results vary by database, network, index size, model, concurrency, and caching. Measure p50/p95/p99 latency, token use, storage growth, embedding cost, and the number of memories inserted into each prompt.

To keep costs controlled:

  • run consolidation asynchronously when immediate response latency matters;
  • cache frequently used, low-risk semantic facts with invalidation;
  • retrieve top-k candidates and re-rank rather than loading full histories;
  • summarize large episodes while retaining source references;
  • use structured lookups for exact facts instead of invoking an LLM unnecessarily.

13. Reliability and observability#

A memory subsystem needs its own quality metrics. A fluent answer is not evidence that the right memory was retrieved.

Track:

  • Write precision: proportion of stored memories that are useful and correctly extracted.
  • Write recall: important events or facts that were missed.
  • Retrieval precision@k / recall@k: whether the right episodes or facts appear in the top results.
  • Temporal accuracy: whether the returned fact was valid at the requested time.
  • Attribution accuracy: whether the source, user, project, and agent are correct.
  • Conflict rate: how often active memories disagree.
  • Staleness rate: how often retrieved facts are no longer valid.
  • Consolidation accuracy: whether derived facts are supported by their source episodes.
  • Deletion propagation: whether removed records disappear from all indexes and derived stores.
  • Latency and cost: p50/p95/p99 retrieval time, model tokens, storage, and embedding spend.

Log memory IDs, type, retrieval scores, filters, source references, and decision outcomes. Redact sensitive payloads. Maintain test cases for cross-tenant leakage, wrong-time retrieval, conflicting facts, and unsupported generalizations.

14. Common failure modes#

  1. Flattening both into one undifferentiated text store. The system retrieves a general fact when asked for a specific past event, or an old event when asked for the current state. Use memory-type metadata and query-aware retrieval.
  2. Dropping timestamps. The agent cannot distinguish an old configuration from a current one. Preserve event time and validity intervals.
  3. Storing an action without its outcome. The agent remembers that it retried an API but not that the retry failed. Record observations and outcomes separately.
  4. Promoting one episode into a universal fact. A one-time failure becomes a false general rule. Require repeated or authoritative evidence and keep confidence and provenance.
  5. Over-consolidating. Distinct incidents or environments are merged into one misleading summary. Group by scope and preserve exceptions.
  6. Using embeddings alone. Similar wording from another tenant or release is returned. Apply authorization and metadata filters before similarity ranking.
  7. Treating the newest memory as automatically correct. A recent guess overrides a verified configuration. Rank source authority and verification, not just recency.
  8. Never expiring semantic facts. Temporary state becomes permanent misinformation. Add validity and revalidation policies.
  9. Deleting only the primary record. Embeddings, caches, summaries, or logs still contain the information. Propagate deletion across the lifecycle.
  10. Putting too much memory into every prompt. Cost and distraction increase, and irrelevant sensitive information is exposed. Retrieve the minimum task-relevant context.

15. How to choose: practical selection criteria#

Choose episodic memory when the agent must:

  • recall what happened in a previous conversation or task;
  • explain which actions and tools were used;
  • remember failed attempts and their outcomes;
  • compare incidents over time;
  • resume a task with its history and decisions;
  • answer “when?”, “where?”, “who did what?”, or “what happened next?”

Choose semantic memory when the agent must:

  • retain stable facts about a user, project, or domain;
  • answer “what is true?”, “what does this mean?”, or “which system uses this?”;
  • personalize repeated interactions;
  • reuse concepts and relationships without replaying a transcript;
  • perform fast, structured lookups of known attributes.

Use both when the agent needs continuity and reliable decisions. For example, a production support agent can retrieve the current service configuration from semantic memory and the last three related incidents from episodic memory before proposing a fix. It should verify high-impact configuration against the live source of truth before executing a tool action.

A simple decision rule:

  • If the question is about a particular occurrence, retrieve an episode.
  • If it is about a reusable fact or relationship, retrieve semantic knowledge.
  • If the answer needs both “what is true now?” and “what happened before?”, retrieve both and reconcile their timestamps and provenance.
  • If the task asks how to perform a workflow, consult procedural memory or the approved runbook; do not confuse it with either of these types.

16. End-to-end example: a reliable support agent#

A customer reports that checkout requests are failing.

  1. The agent retrieves semantic memory: the service uses PostgreSQL, runs in ap-south-1, and has a 5-second upstream timeout. It checks that the configuration is still current.
  2. It retrieves episodic memory: two earlier incidents involved connection-pool exhaustion; one was resolved by increasing pool capacity, while another required rolling back a release.
  3. The agent compares current telemetry with those episodes. It does not blindly repeat the earlier fix.
  4. It proposes a diagnosis with evidence and asks for approval before a risky production action.
  5. After the incident, it stores a new episode with the symptoms, tool observations, actions, approval, and outcome.
  6. A background consolidation process may update a semantic operational fact if the evidence supports it, preserving links to the source episodes.
  7. Retention and privacy rules determine how long detailed traces remain available.

This creates a useful cycle: experience → retrieval → decision → outcome → possible knowledge consolidation. The model itself need not be fine-tuned for every new experience; the agent can improve its future context by managing external memory carefully.

17. Key takeaway#

Episodic memory is the agent's record of particular experiences; semantic memory is its reusable knowledge derived from or independent of those experiences. Episodic memory preserves time, context, actions, and outcomes. Semantic memory distills facts, concepts, and relationships. Reliable agents often need both, with typed records, provenance, temporal validity, hybrid retrieval, controlled consolidation, privacy safeguards, and explicit forgetting policies.

Related questions

Explore other topics:Large Language ModelsRetrieval-Augmented GenerationMLOps