Agent memory, short-term and long-term
Models are stateless. Every call starts from nothing but the tokens you send, so "memory" in an agent is really a set of decisions about what to put back into the context window and where to keep everything else. I find it clearest to split it into two layers: short-term memory (what this run is working with right now) and long-term memory (what survives across runs and sessions).
Why it matters
Two things break agents that ignore memory design. First, long runs fill the context window with old tool output, and quality degrades well before the hard limit (Anthropic's context engineering post calls this "context rot"). Second, users expect an assistant to remember their preferences and past decisions, and re-asking every session feels broken.
Good memory design also controls cost. Every token you carry forward is billed on every subsequent call, so a lean context is both cheaper and smarter.
How it works
Short-term memory (the working context)
This is the message history of the current run, scoped to a thread or session. Techniques to keep it healthy:
- Trimming. Drop the oldest turns once you exceed a budget. Simple, but you lose information.
- Tool result clearing. Replace large, already-used tool outputs with a short placeholder. Anthropic describes this as the lightest-touch form of compaction.
- Compaction (summarisation). When the context nears its limit, have the model summarise the conversation so far (decisions, open issues, next steps) and restart from the summary.
- Structured note-taking. The agent writes progress to an external file or record (a
NOTES.md, a to-do list) and re-reads it after a reset. - Sub-agents. Push exploratory work into a child agent with its own context and return only a condensed result.
Frameworks give you checkpointed threads for this: LangGraph's checkpointer persists state per thread_id, and the OpenAI Agents SDK offers sessions such as SQLiteSession that load and save history automatically.
Long-term memory (across sessions)
LangGraph's docs borrow a human analogy that I find useful:
- Semantic memory: facts. "The user prefers metric units." "Customer Acme is on the enterprise plan."
- Episodic memory: experiences. A record of a past run: what was tried, what worked. Often used as few-shot examples.
- Procedural memory: rules and skills. Updated system prompts, playbooks, or learned instructions.
How you store it:
- Vector memory. Embed memory text and retrieve by similarity. Good for fuzzy recall ("anything relevant to travel?"). Weak at exact facts and updates.
- Structured memory. Rows or JSON documents keyed by user and type, such as a profile object. Good for facts that change, because you can update in place instead of piling up contradictory snippets.
- File-based memory. Anthropic's memory tool gives Claude a
/memoriesdirectory it can view, create and edit through client-side file operations that your application implements. Simple, inspectable, and easy for humans to audit.
Rendering diagram…
Reference architecture
Rendering diagram…
The memory writer can run in the hot path (the agent calls a "save memory" tool) or in the background after the conversation ends. Background writing keeps latency down and lets a separate prompt decide what is worth remembering.
Code
LangGraph's store holds JSON documents under a namespace tuple and a key, with optional semantic search. This example writes two memories for a user and retrieves the relevant one.
import uuid
from langchain.embeddings import init_embeddings
from langgraph.store.memory import InMemoryStore
# InMemoryStore is for development; use a database-backed store such as PostgresStore in production
store = InMemoryStore(
index={
"embed": init_embeddings("openai:text-embedding-3-small"),
"dims": 1536,
}
)
user_id = "user-42"
namespace = (user_id, "memories")
store.put(namespace, str(uuid.uuid4()), {"text": "Prefers answers in metric units", "kind": "semantic"})
store.put(namespace, str(uuid.uuid4()), {"text": "Trip to Lisbon booked for March", "kind": "episodic"})
hits = store.search(namespace, query="How far is the walk from the hotel?", limit=2)
for item in hits:
print(item.key, item.value["text"], item.score)
# Structured memory: one profile document, updated in place
store.put((user_id, "profile"), "main", {"units": "metric", "home_city": "Singapore"})
profile = store.get((user_id, "profile"), "main")
print(profile.value)
When you compile a LangGraph graph with store=store, the store is injected into your nodes, so the agent can read and write memories during a run.
Trade-offs and pitfalls
- Remembering too much. Saving every message as a memory produces noisy retrieval and contradictions. Be selective: extract durable facts, not chatter.
- Stale and conflicting facts. Vector stores happily return both "lives in London" and "moved to Berlin". Prefer structured records for mutable facts, store timestamps, and let newer entries win.
- Compaction loses details. Summaries drop things. Tune the compaction prompt for recall first, then trim, and keep the raw transcript elsewhere for audits.
- Privacy and retention. Long-term memory is personal data. Namespace by user and tenant, support deletion, and do not store secrets.
- Memory as an injection vector. If a malicious document gets written into memory, it can influence every future session. Validate what gets saved and keep provenance.
- Retrieval is a ranking problem. Everything you know about RAG (chunking, hybrid search, reranking) applies to vector memory too.
Checklist
- Short-term history is scoped per thread and checkpointed durably.
- Large tool outputs are cleared or truncated once used.
- Compaction triggers before the context limit and preserves decisions and open issues.
- Long-term memories are namespaced by tenant and user.
- Mutable facts live in structured records; fuzzy recall uses vector search.
- Memory writes are selective, timestamped and carry provenance.
- Users can view and delete what the agent remembers.