Short-term and long-term memory
Overview
Imagine building a personal AI assistant that receives the following message on Monday:
I prefer Python examples, concise explanations, and PostgreSQL for backend applications.
On Tuesday, the user starts a completely new conversation and asks the assistant to recommend a database for a new application. Should the assistant remember Monday’s preferences?
Now imagine that, during Tuesday’s conversation, the user says, “Compare it with the previous option.” Should the assistant remember which database was previously discussed?
Both situations require memory, but they involve different scopes and purposes.
The first requires long-term memory, because information must survive across independent conversations. The second requires short-term memory, because information must remain available within the current conversation.
A language model does not automatically develop persistent memories simply because your application repeatedly calls it. Unless relevant information is supplied to the model, it cannot reliably recall previous API requests.
An agent’s memory system is therefore an application-level architecture that determines:
- What information should be retained.
- Where that information should be stored.
- Who is authorized to access it.
- When it should be retrieved.
- How it should influence future decisions.
- When it should be corrected or deleted.
In the previous lesson, you explored time travel, replay, and forking using checkpoints. This lesson builds on that persistence mechanism and introduces a separate memory layer that operates across threads.
Install the packages required for the examples:
pip install -U "langgraph>=1,<2" "langchain[openai]>=1,<2"Examples using OpenAI models or embeddings also require an OPENAI_API_KEY environment variable.
The examples follow the current LangGraph 1.x interfaces described in the official memory guide and persistence documentation. Model-independent examples are designed for deterministic testing; live execution of the examples was not verified in the lesson-authoring environment.
Short-term memory: within a thread
Understanding threads
A thread represents a particular conversation or workflow instance.
Consider a customer support assistant:
- Thread A concerns a customer’s refund.
- Thread B concerns the same customer’s delivery.
- Thread C belongs to another customer.
Each thread has independent execution state. The refund conversation should not automatically inherit the delivery conversation’s entire history.
A thread may remain active for minutes, days, or months. Consequently, short-term memory describes its scope, not necessarily its physical retention duration.
LangGraph implements this memory through graph state and checkpointing.
State and checkpoints
State can contain much more than conversation messages. It might include:
- Previously retrieved documents.
- Intermediate tool results.
- Pending approvals.
- Task progress.
- Selected products or entities.
- Variables required by subsequent nodes.
When a checkpointer is configured, LangGraph records state snapshots at graph execution boundaries. Subsequent invocations using the same thread identifier can continue from the saved state.
For conversation history, MessagesState provides a messages field with the add_messages reducer. This reducer generally appends new messages while allowing existing messages with matching IDs to be updated.
The following example demonstrates conversation continuity using a real chat model.
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.checkpoint.memory import InMemorySaver
model = init_chat_model("openai:gpt-5.4-mini")
def respond(state: MessagesState):
response = model.invoke(state["messages"])
return {"messages": [response]}
builder = StateGraph(MessagesState)
builder.add_node("respond", respond)
builder.add_edge(START, "respond")
builder.add_edge("respond", END)
graph = builder.compile(checkpointer=InMemorySaver())
config_a = {"configurable": {"thread_id": "conversation-a"}}
config_b = {"configurable": {"thread_id": "conversation-b"}}
graph.invoke(
{"messages": [HumanMessage(content="My name is Maya.")]},
config_a
)
result = graph.invoke(
{"messages": [HumanMessage(content="What is my name?")]},
config_a
)
print("Same thread:", result["messages"][-1].content)
result = graph.invoke(
{"messages": [HumanMessage(content="What is my name?")]},
config_b
)
print("Different thread:", result["messages"][-1].content)
snapshot = graph.get_state(config_a)
print("Saved messages:", len(snapshot.values["messages"]))Illustrative output:
Same thread: Your name is Maya.
Different thread: I don't know your name yet.
Saved messages: 4The exact model responses may vary, but the saved message count should be four after the two successful invocations of thread A.
Notice that the second invocation supplies only the new message. LangGraph restores the existing state and merges the input into it.
Checkpoint storage versus model context
Persisting messages does not guarantee that the model receives them. In this example, the respond node explicitly passes the complete message list to model.invoke().
This distinction becomes important for long conversations. A checkpoint may contain hundreds of messages, while the model should receive only the relevant portion.
Excessive history increases token consumption, latency, and the possibility of irrelevant information distracting the model.
Later in this chapter, you will implement message trimming, summarization, and context-window management.
Note:
InMemorySaverkeeps checkpoints in process memory. Restarting the Python process loses those checkpoints, even though they provide thread-level persistence between invocations.
Long-term memory: across threads
Short-term memory cannot independently answer questions about information stored in unrelated threads.
Using one thread per user forever is not a good solution. It mixes unrelated tasks, creates increasingly large histories, and makes independent workflow execution difficult.
Instead, LangGraph provides a separate abstraction called a store.
A store contains application-defined records organized by namespaces and keys. Unlike checkpoints, these records are not inherently tied to a specific conversation.
The following diagram illustrates how two independent threads can access a shared user memory store.
Checkpointer versus store
| Characteristic | Short-term memory | Long-term memory |
|---|---|---|
| Primary abstraction | Checkpointer | Store |
| Logical scope | Individual thread | Application-defined namespace |
| Typical content | Messages and workflow state | Preferences, facts, experiences |
| Identifier | Thread ID | Namespace and key |
| Retrieval | State restoration | Explicit lookup or search |
| Update mechanism | State updates | Store operations |
| Development backend | InMemorySaver |
InMemoryStore |
| Production backend | PostgresSaver |
PostgresStore |
These mechanisms complement one another rather than compete.
Namespaces and user identity
A namespace is a tuple of strings that groups related memory records.
For example:
("tenant_42", "user_101", "preferences")
("tenant_42", "user_101", "episodes")
("tenant_42", "assistant", "procedures")A namespace combined with a record key identifies an individual memory.
The application determines which namespaces are accessible to each user. Namespace separation alone does not implement authorization.
With LangGraph 1.x, application identity should enter nodes through runtime context. Keep thread_id in the configurable execution configuration, but supply authenticated user information through context.
Building a cross-thread memory assistant
The following deterministic example stores a preferred answer style and retrieves it from a different conversation.
from dataclasses import dataclass
from langchain.messages import HumanMessage, AIMessage
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.store.memory import InMemoryStore
from langgraph.runtime import Runtime
@dataclass
class Context:
user_id: str
def assistant(state: MessagesState, runtime: Runtime[Context]):
namespace = (runtime.context.user_id, "preferences")
text = state["messages"][-1].content.strip().lower()
if text == "remember that i prefer concise answers":
runtime.store.put(
namespace,
"answer_style",
{"style": "concise"}
)
reply = "Preference saved."
else:
memory = runtime.store.get(namespace, "answer_style")
style = memory.value["style"] if memory else "not specified"
reply = f"Your preferred answer style is {style}."
return {"messages": [AIMessage(content=reply)]}
builder = StateGraph(MessagesState, context_schema=Context)
builder.add_node("assistant", assistant)
builder.add_edge(START, "assistant")
builder.add_edge("assistant", END)
graph = builder.compile(
checkpointer=InMemorySaver(),
store=InMemoryStore()
)
def chat(user_id, thread_id, text):
result = graph.invoke(
{"messages": [HumanMessage(content=text)]},
{"configurable": {"thread_id": thread_id}},
context=Context(user_id=user_id)
)
return result["messages"][-1].content
print(chat(
"maya", "maya-1",
"Remember that I prefer concise answers"
))
print(chat(
"maya", "maya-2",
"What is my preferred answer style?"
))
print(chat(
"alex", "alex-1",
"What is my preferred answer style?"
))Expected output:
Preference saved.
Your preferred answer style is concise.
Your preferred answer style is not specified.The checkpointer maintains three independent conversations. The store allows the first two conversations to share Maya’s preference.
The third conversation accesses a different namespace and finds no saved preference.
A deterministic implementation makes it possible to verify memory isolation without introducing unpredictable model behavior.
In a real application, a model could extract the preference from natural language and use retrieved preferences when generating its answer.
Persistent memory stores
Despite representing long-term memory, InMemoryStore does not survive process restarts.
For durable deployments, use a database-backed implementation such as PostgresStore, available through the langgraph-checkpoint-postgres package.
pip install -U langgraph-checkpoint-postgres "psycopg[binary,pool]"Initialize the database tables using store.setup() and manage the store’s connection lifecycle appropriately.
A production deployment can use PostgreSQL for both checkpoint and store data while keeping their logical responsibilities separate.
Three kinds of memory
Memory scope answers the question, “Where can this information be recalled?”
Memory type answers a different question, “What does this information represent?”
A useful framework, inspired by human cognition and described in the official LangGraph memory overview, distinguishes semantic, episodic, and procedural memory.
| Memory type | Represents | Example | Typical use |
|---|---|---|---|
| Semantic | Facts and knowledge | User prefers Python | Personalization |
| Episodic | Previous experiences | A deployment failed because of permissions | Learning from outcomes |
| Procedural | Methods and behavioral rules | Validate permissions before deployment | Improving execution |
These are architectural categories, not three separate built-in LangGraph classes. All three can be implemented using the same store interface.
Semantic memory: remembering facts
Semantic memory captures knowledge that remains useful beyond the original interaction.
Examples include a user’s preferred programming language, timezone, dietary preference, or preferred report format.
A semantic record might look like this:
{
"type": "semantic",
"fact": "The user prefers PostgreSQL examples.",
"source": "explicit_user_statement",
"confidence": 1.0,
"updated_at": "2026-12-03"
}Here, confidence describes confidence in the extraction, not proof that the preference will remain true forever.
Semantic memories should distinguish enduring preferences from temporary requirements. “Use Java for this assignment” does not necessarily mean that the user prefers Java generally.
Retrieving memories by meaning
Exact key lookup works well when the application already knows which fact it needs.
However, users frequently express related concepts using different words. A request for a morning meal recommendation might benefit from a remembered breakfast preference even when the word “breakfast” is absent.
Semantic search addresses this problem using embeddings: numerical representations of text that support similarity-based retrieval.
The following example creates an indexed store and retrieves a relevant preference.
from langchain.embeddings import init_embeddings
from langgraph.store.memory import InMemoryStore
store = InMemoryStore(
index={
"embed": init_embeddings("openai:text-embedding-3-small"),
"dims": 1536,
"fields": ["text"]
}
)
namespace = ("maya", "semantic")
store.put(namespace, "food-1", {
"text": "Maya prefers vegetarian breakfasts."
})
store.put(namespace, "coding-1", {
"text": "Maya prefers Python for automation."
})
store.put(namespace, "travel-1", {
"text": "Maya prefers window seats on flights."
})
results = store.search(
namespace,
query="What should I eat in the morning?",
limit=1
)
for item in results:
print(item.value["text"])Likely output:
Maya prefers vegetarian breakfasts.Retrieval rankings depend on the embedding model. Similarity indicates relevance, not factual correctness.
Semantic search and semantic memory are distinct concepts: semantic search can also retrieve episodic records or procedural instructions.
The next lesson explores indexing and store operations in detail.
Episodic memory: remembering experiences
Episodic memory records events and their outcomes.
Imagine a deployment agent that previously attempted to deploy an application without verifying its cloud permissions.
The deployment failed, the agent diagnosed the issue, and a permission check resolved it.
A useful episode could contain:
{
"type": "episodic",
"task": "Deploy a containerized application",
"action": "Started deployment without checking permissions",
"outcome": "Deployment rejected",
"resolution": "Verified and corrected deployment permissions",
"lesson": "Check required permissions before deployment"
}When a similar task arrives, the agent can retrieve this episode as contextual guidance.
Episodic memory is particularly valuable for troubleshooting agents, research assistants, and complex workflow automation.
Do not treat previous success as proof that an action remains appropriate. Environments, permissions, dependencies, and business requirements change.
Procedural memory: remembering how to act
Procedural memory describes reusable methods, strategies, or behavioral instructions.
Examples include:
- Ask for missing requirements before generating a database schema.
- Validate SQL before executing a read-only query.
- Present a concise answer before providing optional details.
Procedural memories may originate from developers, explicit feedback, successful experiences, or reviewed optimization workflows.
Agents can retrieve relevant procedures and incorporate them into their model instructions or deterministic graph logic.
Hard requirements, such as authorization checks and restrictions on external actions, should remain enforced in application code rather than relying exclusively on remembered instructions.
Profile vs collection
There are two common ways to organize long-term memory.
Profile-based memory
A profile consolidates information into a single structured record.
For example:
{
"name": "Maya",
"preferred_language": "Python",
"preferred_database": "PostgreSQL",
"answer_style": "concise"
}Profiles are straightforward to retrieve and validate. They work particularly well for a small, predictable set of user preferences.
However, blindly replacing a profile can accidentally remove existing fields.
The following example updates a profile while preserving unrelated information.
from langgraph.store.memory import InMemoryStore
store = InMemoryStore()
namespace = ("maya", "profile")
store.put(namespace, "main", {
"language": "Python",
"database": "PostgreSQL",
"answer_style": "detailed"
})
existing = store.get(namespace, "main")
profile = dict(existing.value) if existing else {}
profile["answer_style"] = "concise"
store.put(namespace, "main", profile)
print(store.get(namespace, "main").value)Expected output:
{'language': 'Python', 'database': 'PostgreSQL', 'answer_style': 'concise'}This read-modify-write operation is suitable for a sequential demonstration. Concurrent production updates require additional coordination to avoid lost writes.
Collection-based memory
Collections store independently addressable memory records.
A user might accumulate thousands of facts, project observations, and historical experiences. Combining everything into one document would make retrieval inefficient and updates difficult.
Collections support selective retrieval and independent correction or deletion. Their main disadvantages are duplication, contradictory records, and increased retrieval complexity.
| Design consideration | Profile | Collection |
|---|---|---|
| Structure | Consolidated document | Multiple records |
| Retrieval | Direct lookup | Search or filtering |
| Updates | Modify selected fields | Insert or update records |
| Best suited for | Stable preferences | Growing knowledge |
| Common failure | Lost fields | Duplicate memories |
Many production assistants use a hybrid approach: a profile for frequently accessed preferences and collections for less predictable information.
Procedural memory that updates itself
An adaptive agent can improve its future behavior by turning feedback into revised procedural memory.
This is not model retraining. The model’s weights remain unchanged. Instead, the application modifies instructions supplied during subsequent executions.
For example, a user repeatedly complains that the assistant provides explanations before showing the requested code. An adaptive system could propose a new procedure that places code before explanations.
The following diagram illustrates a controlled procedural improvement cycle.
Implementing controlled self-updates
The following example converts explicit feedback into a constrained procedural setting. A simulated trusted approval flag represents the decision of an authorized review component.
from langgraph.store.memory import InMemoryStore
store = InMemoryStore()
namespace = ("maya", "procedures")
store.put(namespace, "response_order", {
"strategy": "explanation_first",
"version": 1
})
ALLOWED_STRATEGIES = {
"explanation_first": "Explain the concept before showing code.",
"code_first": "Show the code before explaining it."
}
def learn_from_feedback(feedback: str, approved: bool):
if feedback.strip().lower() != "show code first":
return False
candidate = "code_first"
if not approved or candidate not in ALLOWED_STRATEGIES:
return False
current = store.get(namespace, "response_order").value
if current["strategy"] == candidate:
return True
store.put(namespace, "response_order", {
"strategy": candidate,
"version": current["version"] + 1,
"source": "approved_user_feedback"
})
return True
def build_system_prompt():
memory = store.get(namespace, "response_order")
instruction = ALLOWED_STRATEGIES[memory.value["strategy"]]
return (
"You are a programming assistant. "
"Follow all application safety and access rules. "
+ instruction
)
print(build_system_prompt())
learn_from_feedback("show code first", approved=True)
print(build_system_prompt())
print(store.get(namespace, "response_order").value)The first prompt requests explanations before code. After the approved update, the second prompt requests code first and the stored procedure advances to version two.
A graph node could subsequently use SystemMessage(content=build_system_prompt()) when invoking its model.
More sophisticated systems use an LLM to propose instruction revisions and evaluate them against representative tasks before activation.
Tip: Treat adaptive procedures as versioned configuration. Preserve reviewed versions, measure regressions, and support rollback. Never give unrestricted memory-writing logic permission to rewrite security policies or expand tool permissions.
When to write memories
Memory creation can occur at different points in an agent’s lifecycle.
Hot-path memory writes
A hot-path write occurs during the execution of the current request.
When a user explicitly asks the assistant to remember a preference, writing it immediately allows subsequent conversations to retrieve it without delay.
Hot-path writes offer immediate consistency after successful storage and allow the assistant to acknowledge the result accurately.
However, extracting, validating, and storing memories can increase response latency. A model that decides what to remember also has another opportunity to make mistakes.
Use this approach for explicit memory requests, important corrections, and information required by the current workflow.
Background memory writes
A separate application worker can analyze completed interactions and produce candidate memories after the primary response.
For example, a worker might process a completed support conversation, extract useful troubleshooting episodes, detect duplicates, and update an experience collection.
This separates response generation from more expensive memory-processing operations.
However, background writes introduce eventual consistency. A new conversation might begin before the memory becomes available.
They also require operational mechanisms such as queues, retry handling, deduplication, and monitoring. Merely using an asynchronous Python node does not create a durable background-processing system.
Deciding what deserves memory
Before storing information, evaluate whether it is useful, sufficiently reliable, appropriately scoped, and permitted to be retained.
An extraction pipeline commonly identifies candidate memories, classifies their type, validates their content, checks for conflicting records, and decides whether to insert, update, or discard them.
Prefer stable keys for mutable preferences. For historical events, use stable event identifiers to prevent duplicate records during retries.
This connects directly to the previous lesson: replaying or forking graph execution does not automatically restore external store records to their earlier versions. Memory writes are external effects and should be designed accordingly.
Responsible memory
Persistent memory makes agents more useful, but it also creates privacy, security, and reliability obligations.
Consent and data minimization
Users should understand what an assistant remembers and why.
An application should not permanently retain every conversation simply because storage is available. Retain information that has a legitimate purpose and avoid saving passwords, API keys, authentication tokens, or unnecessary sensitive details.
Support memory-disabled sessions and distinguish temporary conversation context from persistent personalization.
Authorization and isolation
Obtain user identity from trusted authentication middleware, not from a model-generated tool argument.
Validate thread ownership independently of store access. A correctly scoped memory namespace cannot prevent leakage if an unauthorized user is allowed to open another user’s checkpointed conversation.
For multi-tenant systems, include tenant identity in the memory namespace and enforce access controls in the application or storage layer.
Correction, deletion, and retention
Memories become outdated.
A preference may change, an earlier extraction may be incorrect, or a user may request deletion.
Support reliable updates and deletion of memory records. A comprehensive deletion workflow must also consider retained checkpoints, logs, caches, derived records, and backups under the applicable retention policy.
Otherwise, deleted information might reappear through historical conversation processing.
Preventing memory poisoning
Memory poisoning occurs when incorrect or malicious content enters persistent memory and influences future execution.
For example, an untrusted document might instruct an agent to disable verification for future tasks.
Do not promote retrieved text directly into trusted instructions. Validate its provenance, restrict writable fields, and require appropriate approval for consequential procedural changes.
Treat memories as contextual evidence rather than unquestionable authority.
Testing memory quality
Production memory systems should be tested for more than successful retrieval.
Verify cross-user isolation, accurate preference updates, resistance to malicious instructions, duplicate prevention, deletion behavior, and persistence across process restarts when durable storage is configured.
Measure retrieval relevance, false memory extraction rates, personalization quality, and the latency introduced by memory processing.
A useful memory system improves an agent’s decisions without making those decisions less predictable or less secure.
The next lesson, The LangGraph Store API, develops the implementation foundation for these designs through namespaces, record operations, semantic indexing, filtering, and persistent storage. Those capabilities will later support the chapter project: a personal assistant that remembers user preferences across conversations while maintaining independent conversation histories.
Build a cross-thread preference assistant
Build a LangGraph assistant that remembers a user's preferred programming language across independent conversation threads. Use a checkpointer for conversation history and an InMemoryStore for user-specific preferences. Allow users to update their preferences and verify that another user cannot access those preferences. Implement the memory behavior without an LLM so that the results can be tested deterministically.
from dataclasses import dataclass
from langchain.messages import HumanMessage, AIMessage
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.store.memory import InMemoryStore
from langgraph.runtime import Runtime
@dataclass
class Context:
user_id: str
ALLOWED_LANGUAGES = {"python", "javascript", "java", "rust", "go"}
def assistant(state: MessagesState, runtime: Runtime[Context]):
namespace = (runtime.context.user_id, "preferences")
text = state["messages"][-1].content.strip().lower()
# TODO: Handle "remember language python".
# TODO: Validate the language and save the preference.
# TODO: Retrieve the preference for "what is my language?".
# TODO: Return an appropriate AIMessage.
raise NotImplementedError
builder = StateGraph(MessagesState, context_schema=Context)
builder.add_node("assistant", assistant)
builder.add_edge(START, "assistant")
builder.add_edge("assistant", END)
# TODO: Compile with a checkpointer and a store.
# TODO: Test the same user across two different threads.
# TODO: Update the preference and test another user.from dataclasses import dataclass
from langchain.messages import HumanMessage, AIMessage
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.store.memory import InMemoryStore
from langgraph.runtime import Runtime
@dataclass
class Context:
user_id: str
ALLOWED_LANGUAGES = {"python", "javascript", "java", "rust", "go"}
def assistant(state: MessagesState, runtime: Runtime[Context]):
namespace = (runtime.context.user_id, "preferences")
text = state["messages"][-1].content.strip().lower()
if text.startswith("remember language "):
language = text.removeprefix("remember language ").strip()
if language not in ALLOWED_LANGUAGES:
reply = "Unsupported programming language."
else:
runtime.store.put(
namespace,
"programming_language",
{
"language": language,
"source": "explicit_user_request"
}
)
reply = f"Remembered your preference for {language}."
elif text == "what is my language?":
memory = runtime.store.get(
namespace,
"programming_language"
)
if memory is None:
reply = "No language preference saved."
else:
reply = f"Your preferred language is {memory.value['language']}."
else:
reply = "Ask me to remember or retrieve your language."
return {"messages": [AIMessage(content=reply)]}
store = InMemoryStore()
checkpointer = InMemorySaver()
builder = StateGraph(MessagesState, context_schema=Context)
builder.add_node("assistant", assistant)
builder.add_edge(START, "assistant")
builder.add_edge("assistant", END)
graph = builder.compile(
checkpointer=checkpointer,
store=store
)
def chat(user_id: str, thread_id: str, text: str) -> str:
result = graph.invoke(
{"messages": [HumanMessage(content=text)]},
{"configurable": {"thread_id": thread_id}},
context=Context(user_id=user_id)
)
return result["messages"][-1].content
print(chat("alice", "alice-1", "remember language python"))
answer = chat("alice", "alice-2", "what is my language?")
print(answer)
assert answer == "Your preferred language is python."
print(chat("alice", "alice-2", "remember language rust"))
answer = chat("alice", "alice-3", "what is my language?")
print(answer)
assert answer == "Your preferred language is rust."
answer = chat("bob", "bob-1", "what is my language?")
print(answer)
assert answer == "No language preference saved."
snapshot = graph.get_state(
{"configurable": {"thread_id": "alice-2"}}
)
assert len(snapshot.values["messages"]) == 4
print("All memory tests passed.")Summary
- Short-term memory preserves graph state within a conversation thread using a checkpointer.
- Long-term memory uses a store to retain application-defined information across independent threads.
- Semantic memory represents facts, episodic memory represents experiences, and procedural memory represents behavioral instructions.
- Profiles maintain consolidated information while collections preserve independently retrievable memory records.
- Procedural memory can adapt agent behavior through validated and authorized instruction updates without retraining the model.
- Memory writes can occur synchronously during a request or asynchronously through a separate processing workflow.
- Production memory systems require authorization, data minimization, provenance, retention policies, and reliable correction and deletion mechanisms.