Home / Insights / AI Agents and Automation

AI Agents and Automation

Memory for AI Agents: Short-Term Context, Long-Term Memory and What to Forget

An agent that forgets everything between steps is frustrating; an agent that remembers everything is a privacy, cost and accuracy problem. This guide explains the types of agent memory, how to decide what to keep, and how to design forgetting so memory stays useful, safe and compliant.

TopicsAI Agents and AutomationGenerative AI and LLMsArchitecture and Modernization

Key takeaways

  • Separate three layers: working context for the current task, session state for a conversation or job, and long-term memory that persists across sessions.
  • More context is not automatically better: research and vendor guidance both show models use long contexts unevenly, so curate what goes in.
  • Every long-term memory item needs a scope (user, team, tenant), a source, a purpose and an expiry, just like any other personal or business data.
  • Design forgetting from day one: retention limits, user-visible memory, deletion that reaches every store, and rules for what must never be remembered.
  • Treat memory as an attack surface: writes can be poisoned, and reads can leak data across users if retrieval is not permission-aware.

Most teams discover agent memory problems in the second month of a pilot. The agent that was impressive in a demo now asks the same clarifying questions every day, or forgets a decision made three steps earlier in a long task. So someone adds “memory”: the full conversation history goes into every prompt, or every message is embedded into a vector database. Costs rise, responses slow down, and soon the agent confidently recalls a preference the user changed weeks ago, or mentions something that belonged to a different customer.

Memory is not one feature. It is a set of design decisions about what an agent should know at each moment, where that knowledge lives, who it belongs to, and when it should disappear. Getting those decisions right matters as much as choosing the model.

This article is for CTOs, product leads and architects building or buying AI agents. It explains the memory layers, the trade-offs between approaches, how to decide what to store, how to forget safely and how to test it. It reflects how we design agents in our AI Agent Development work, where scoped memory and context retrieval is a documented layer alongside instructions, typed tools and oversight. If you are new to the topic, start with our practical guide to AI agents.

The three layers of agent memory

It helps to borrow a simple model from computing: fast, small memory close to the processor, and slower, larger storage further away. The MemGPT paper made this analogy explicit, proposing that an LLM system move information between memory tiers in the way an operating system does, so it can work with far more material than its context window holds. For product design, three layers are enough.

LayerWhat it holdsLifetimeWhere it livesMain risk
Working contextInstructions, the current request, relevant retrieved facts, recent tool resultsOne model callThe promptOverloading the model with irrelevant tokens
Session stateConversation history, task plan, decisions so far, intermediate resultsOne conversation or jobApplication database or agent framework state storeLosing track in long tasks; unbounded growth
Long-term memoryUser preferences, facts about accounts, past outcomes, learned proceduresWeeks to yearsDatabase records, documents or vector indexStale, wrong or leaked information; privacy obligations

Many problems come from mixing these layers, for example treating raw conversation logs as long-term memory, or putting all of long-term memory into every prompt.

Action: for your agent, list what it needs to know at each of the three layers. If you cannot say why an item is needed, it should not be stored.

Short-term memory: managing the context window

Larger context windows tempt teams to include everything. That rarely works as well as expected.

Why more context can make results worse

The “Lost in the Middle” study found that models perform best when relevant information is at the start or end of a long input, and noticeably worse when it sits in the middle, even for models built for long contexts. Anthropic’s engineering guidance on effective context engineering for AI agents describes the same effect as context rot: as the window fills, recall degrades, so context should be treated as a finite attention budget.

Techniques that work

  • Compaction: when a conversation or task approaches a limit, summarise it, keeping decisions, open questions and key facts, and start a fresh context with the summary. Clearing old tool results is the lightest version.
  • Structured notes: let the agent maintain a task file or checklist outside the context window and read it back when needed, rather than relying on the full transcript.
  • Sub-agents: delegate focused work to a sub-agent with a clean context that returns only a condensed result.
  • Just-in-time retrieval: fetch long-term facts only when the current step needs them, instead of loading a profile into every prompt.
  • Ordering: put stable instructions first and the most relevant facts near the current request.

Session state belongs in your application

Store the task plan, decisions and tool outputs as structured state in your database, keyed to the session. This makes long tasks resumable after a failure, gives you an audit trail and lets you rebuild the context window deliberately each turn.

Action: measure tokens per call and task success rate together. If token counts climb over a session while success falls, you need compaction or better retrieval, not a bigger model.

Long-term memory: what is worth remembering

Long-term memory is where most of the value and most of the risk sits. The test for every item is simple: will remembering this make a future task measurably better, and are we allowed to keep it?

Types of long-term memory

  • Explicit preferences the user stated: language, report format, approval thresholds. High value, low ambiguity.
  • Facts about entities: an account’s contract tier, a supplier’s lead times. Often better read live from the system of record than copied into memory.
  • Episodic memory: summaries of past interactions or outcomes (“last month’s reconciliation failed because the bank file was late”). Useful for continuity, but it ages quickly.
  • Procedural memory: learned ways of doing a task, such as a checklist refined after reviews. Valuable, but should be reviewed by a person before it changes behaviour for everyone.

Remember, read live or never store

InformationRecommended approachReason
User-stated preferencesRemember, user-visible and editableStable, valuable, user controls it
Customer account dataRead live from CRM or ERP via toolsThe system of record changes; copies go stale
Summaries of past tasksRemember with expiryUseful context that loses relevance over time
Refined proceduresRemember after human reviewAffects many future tasks
Passwords, card numbers, health details not needed for the taskNever store; redact on captureHigh harm, no legitimate memory purpose
Raw transcriptsKeep as logs under log retention, not as memoryNoisy, sensitive and expensive to retrieve from

How memory gets written

Decide who can write memory. Options range from explicit (“remember that I prefer weekly summaries”) to automatic extraction by the agent at the end of a session. Automatic extraction is convenient but should write to a candidate store with confidence scores and, for anything affecting other users, a review step.

Action: write a one-page memory policy listing each memory type, who can write it, who can read it and how long it lives.

Scoping memory and keeping it secure

Memory turns a stateless model into a system that stores data, so normal data-protection and security thinking applies.

Scope every item

Each memory record should carry an owner scope (user, team, tenant or global), a source (which conversation or tool produced it), a purpose and an expiry date. Retrieval must filter by scope before similarity ranking, not after.

Threats specific to memory

The OWASP Top 10 for LLM Applications (2025) entry on vector and embedding weaknesses describes several risks that apply directly to agent memory stored in vector databases:

  • Cross-context leakage: in multi-tenant stores, one group’s data can be retrieved in response to another group’s query.
  • Data poisoning: malicious content, such as hidden instructions in a document or message, enters memory and later manipulates behaviour.
  • Embedding inversion: embeddings can leak much of the original text, so they deserve the same protection as the source data.

OWASP’s recommended mitigations include permission-aware vector stores with strict partitioning, validating content before it enters the knowledge base, and detailed, tamper-resistant logs of retrieval activity.

Practical controls

  • Partition memory per tenant at the storage level, not just with a metadata filter.
  • Never let content from untrusted sources, such as inbound emails or web pages, write directly to long-term memory without validation.
  • Log every memory write and read with the session and user, so you can trace why the agent “knew” something. Our article on tracing tool calls and failures in production covers the wider observability set-up.

Action: run a test where user A plants a distinctive fact and user B in another tenant tries to elicit it. It should never appear.

Designing forgetting: retention, correction and deletion

Forgetting is a feature. It keeps memory accurate, controls cost and meets legal obligations.

Why agents must forget

  • Accuracy: preferences and facts change. An old memory that contradicts current reality is worse than none.
  • Cost and quality: an ever-growing store makes retrieval noisier and slower.
  • Legal obligations: the European Commission’s guidance on whether personal data must always be deleted on request explains that organisations must erase personal data when asked unless an exception applies, such as a legal obligation to retain it. If your agent remembers personal data, deletion has to reach memory too.

Mechanisms

  1. Time-based expiry: every memory type has a default lifetime; episodic summaries might expire after a set number of months, preferences only when changed.
  2. Supersession: when a new fact conflicts with an old one, mark the old one superseded rather than keeping both.
  3. Usage-based pruning: memories never retrieved over a long period are candidates for removal.
  4. User control: users can see what the agent remembers about them, correct it and delete it.
  5. Cascading deletion: a deletion request removes records, embeddings, cached summaries and derived notes, and is logged.

Logs are not memory

Keep audit logs and memory separate, with separate retention rules. Logs may need redaction of personal data and a shorter or legally defined retention period. Our article on PII redaction, retention and logging decisions covers this in detail.

Action: before launch, test a full deletion request for one user and confirm that nothing about them can be retrieved from any store afterwards.

Implementation options and a step-by-step plan

Storage options

OptionBest forTrade-offs
Relational records (for example PostgreSQL tables)Preferences, settings, structured facts, session statePrecise and easy to delete; no fuzzy recall
Vector index (for example pgvector)Episodic summaries and notes recalled by similarityFlexible recall; needs scoping, validation and deletion discipline
Documents or filesAgent-maintained task notes and proceduresReadable and reviewable; needs versioning
Framework-provided memoryFast start with agent frameworks such as LangGraphCheck scoping, export and deletion support before relying on it

Most production agents we would design use a combination: structured records for anything precise, a scoped vector index for fuzzy recall and documents for procedures.

Step-by-step

  1. Define tasks and success criteria first; memory is justified only by better outcomes. Our guide to writing requirements for an AI agent helps here.
  2. Write the memory policy: types, scopes, writers, readers, expiry.
  3. Implement session state and compaction before any long-term memory.
  4. Add long-term memory for one type, usually explicit user preferences, with a visible “what I remember” view.
  5. Add deletion and expiry jobs at the same time as the store, not later.
  6. Evaluate with and without memory on the same tasks to prove value.
  7. Extend to episodic or procedural memory only if evaluation shows clear gains.

For example, an illustrative accounts-payable agent might remember each approver’s preferred summary format and escalation thresholds, read supplier and invoice data live from the ERP, keep task notes for multi-day reconciliations in session state, and expire summaries of past exceptions after a fixed period.

Testing memory and a pre-launch checklist

What to test

  • Recall: does the agent use a stored preference when relevant, and ignore it when not?
  • Update: after a user changes a preference, is the old one no longer used?
  • Isolation: can one user or tenant ever retrieve another’s memories?
  • Poisoning: does injected content in an email or document end up in long-term memory?
  • Long tasks: does compaction keep decisions intact over a long session?
  • Deletion: does a deletion request remove every trace?
  • Cost: how do tokens per task and latency change as memory grows?

Pre-launch checklist

  • Memory policy written: types, scopes, writers, readers and expiry.
  • Working context assembled deliberately each turn; compaction in place for long sessions.
  • Session state stored in the application with an audit trail.
  • Long-term memory partitioned by tenant; retrieval filtered by scope first.
  • Sensitive data redacted on capture; never-store categories enforced.
  • Untrusted content validated before any memory write.
  • Users can view, correct and delete what the agent remembers.
  • Expiry, supersession and cascading deletion implemented and tested.
  • Memory reads and writes logged; logs retained under their own policy.
  • Evaluation shows memory improves task outcomes enough to justify it.

Frequently asked questions

Should we just give the agent the full conversation history every time?

Usually not. Long contexts raise cost and latency, and models use information in the middle of long inputs less reliably. Store session state in your application and build a focused context each turn, with summaries for long sessions.

Is a vector database the same as agent memory?

No. A vector index is one storage option, useful for fuzzy recall of notes and summaries. Preferences and facts are often better held as structured records or read live from your systems of record.

How long should an agent remember things?

It depends on the memory type. Set a default lifetime per type, expire episodic memories, update preferences when users change them and delete on request. Document the rules in a memory policy.

What happens to memory when a user asks for their data to be deleted?

Deletion must cascade to every store: records, embeddings, summaries and notes derived from that user’s data. Design and test this before launch, and log each deletion.

Can memory make an agent less safe?

Yes. Memory can be poisoned by malicious content and can leak across users if retrieval is not scoped. Validate what gets written, partition by tenant and log reads and writes.

Sources and methodology

Guidance reflects PoliteTech delivery experience. The external references below informed specific points in this article.

  1. arXiv: MemGPT — Towards LLMs as Operating Systems (2023) — accessed 10 November 2026. Tiered memory management analogy for extending what an LLM system can work with beyond its context window.
  2. arXiv / TACL: Lost in the Middle — How Language Models Use Long Contexts (2023) — accessed 10 November 2026. Models use information at the start and end of long inputs better than information in the middle.
  3. Anthropic Engineering: Effective context engineering for AI agents (29 September 2025) — accessed 10 November 2026. Context rot, attention budget, compaction, structured note-taking and sub-agents.
  4. OWASP Gen AI Security Project: LLM08:2025 Vector and Embedding Weaknesses — accessed 10 November 2026. Cross-context leakage, data poisoning, embedding inversion and permission-aware mitigations.
  5. European Commission: Do we always have to delete personal data if a person asks? — accessed 10 November 2026. Obligation to erase personal data on request and the main exceptions.

Is your agent remembering the right things, and forgetting the rest?

We can review your agent’s memory design, define a memory policy and implement scoped storage, compaction and deletion that hold up in production.