Long-Term Memory
🎯 Introduction
Short-term memory preserves context only within the same conversation. A new conversation does not automatically give an agent access to earlier preferences or settings. Long-term memory saves information with lasting value separately so it can be read across conversations. This article covers storing and reading that memory and isolating it between users.
🧱 Why Also Use Long-Term Memory?
Suppose a user says in conversation A, “For future recommendations, I prefer mechanical keyboards. Please remember that.” A few days later, they start conversation B and ask which product they prefer.
With short-term memory, conversation B has a different thread_id and cannot automatically access A’s messages. Save the requested preference separately in a store, then read it using the same user ID even in a new conversation.
| Aspect | Short-term memory | Long-term memory |
|---|---|---|
| Identifier | Conversation ID | User or business entity ID |
| Content | Conversation messages and execution state | Information such as explicitly saved user preferences |
| Access | Restore state by conversation | Read by key or retrieve relevant memories |
| LangChain mechanism | Checkpointer | Store |
“Long-term” means information can be used across conversations. It does not require permanent retention or mean the model has been retrained to remember it.
🧱 How Does a Store Save Memory?
A store holds data that can be used across conversations. A namespace partitions the data, and a key identifies a record within it. For example, product preferences can be stored as follows:
| namespace | key | value |
|---|---|---|
['users', 'user-a'] | preference | { product: 'mechanical keyboard' } |
['users', 'user-b'] | preference | { product: 'wireless mouse' } |
The users share a key but have different namespaces, so their records do not overwrite each other. The store does not authenticate users for the application or decide which conversations are worth remembering.
Continue in agent-demo and create 02.long-memory.mjs:
import { InMemoryStore } from '@langchain/langgraph';
const store = new InMemoryStore();
InMemoryStore keeps data in the current process’s memory, letting us test memory across conversations without a database.
Temporarily add this code to try the basic store operations:
await store.put(['users', 'test-user'], 'preference', {
product: 'mechanical keyboard',
});
const item = await store.get(['users', 'test-user'], 'preference');
console.log(item?.value);
Run:
node --env-file=.env 02.long-memory.mjs
Expected output:
{ product: 'mechanical keyboard' }
put() writes data under a namespace and key; get() reads that record, returning an empty value if it does not exist. Writing to the same namespace and key updates the record rather than appending conversation history.
🧱 Let the Agent Save Preferences
Configuring a store alone does not make the agent save or read memories automatically. We will provide two tools: save_preference to save a preference and read_preference to read it.
Delete the temporary put() and get() test, keeping const store = new InMemoryStore();. Replace the imports at the top with:
import { createAgent, tool } from 'langchain';
import { InMemoryStore, MemorySaver } from '@langchain/langgraph';
import { z } from 'zod';
import { shopOptions } from './agent.mjs';
Saving and reading memory requires identifying the current user. The application supplies this ID; the model does not fill it in as a tool argument. LangChain provides these runtime context options:
| Option or property | Purpose |
|---|---|
contextSchema | Define the runtime context structure |
context | Data passed by the application when calling the agent |
runtime.context | Let tools read context for the current call |
runtime.store | Let tools access the agent’s configured store |
Define the runtime context after creating the store:
const contextSchema = z.object({
userId: z.string(),
});
This requires a userId in the runtime context. Real projects should obtain it from backend authentication rather than trusting a user’s claimed identity in a message.
Add the tool for saving preferences:
const savePreference = tool(
async ({ product }, runtime) => {
// Read the user ID supplied by the application
const userId = runtime.context.userId;
// Save the preference under the current user’s namespace
await runtime.store.put(['users', userId], 'preference', {
product,
});
return 'Product preference saved';
},
{
name: 'save_preference',
description: 'Use only when the user explicitly asks to remember or update a product preference',
schema: z.object({ product: z.string() }),
}
);
The model supplies product in the first argument; the framework supplies runtime as the second. Reading the user ID from runtime context prevents the model from selecting another user’s namespace through tool arguments.
🧱 Let the Agent Read Preferences
Add the read tool after the save tool:
const readPreference = tool(
async (_, runtime) => {
const userId = runtime.context.userId;
// Read the current user’s product preference
const item = await runtime.store.get(['users', userId], 'preference');
if (!item) {
return 'No saved product preference';
}
return JSON.stringify(item.value);
},
{
name: 'read_preference',
description: 'Read the product preference explicitly saved by the current user',
schema: z.object({}),
}
);
The read tool has an empty schema because the model need not supply any arguments.
Now create an agent with the store:
const agent = createAgent({
...shopOptions,
// Keep business tools and add memory write and read tools
tools: [...shopOptions.tools, savePreference, readPreference],
systemPrompt:
'You are a product assistant. Use lookup tools for product data. Save preferences only when the user explicitly asks to remember or update them. Use the read tool when asked about saved preferences.',
// Configure the store and runtime context available to tools
store,
contextSchema,
checkpointer: new MemorySaver(),
});
This example uses both a checkpointer and a store: the former saves each conversation’s state, while the latter holds preferences accessible across conversations.
🛠 Verify Memory Across Conversations and User Isolation
Save a Preference in Conversation A
Append to the file:
await agent.invoke(
{
messages: [{ role: 'user', content: 'Please remember my product preference: mechanical keyboard.' }],
},
{
configurable: { thread_id: 'user-a-chat-1' },
context: { userId: 'user-a' },
recursionLimit: 20,
}
);
// Read the store directly to verify that the preference was saved
const item = await store.get(['users', 'user-a'], 'preference');
console.log('Saved data:', item?.value);
Run:
node --env-file=.env 02.long-memory.mjs
One possible output:
Saved data: { product: 'mechanical keyboard' }
Inspect the actual store data rather than relying only on the model’s claim that it saved the preference.
Read It in a New Conversation for the Same User
Continue by adding:
const result = await agent.invoke(
{
messages: [{ role: 'user', content: 'What product preference did I save earlier?' }],
},
{
configurable: { thread_id: 'user-a-chat-2' },
context: { userId: 'user-a' },
recursionLimit: 20,
}
);
console.log('New conversation:', result.messages.at(-1)?.content);
Run it again:
node --env-file=.env 02.long-memory.mjs
One possible output:
Saved data: { product: 'mechanical keyboard' }
New conversation: Your saved product preference is mechanical keyboard.
Although thread_id differs, userId stays the same, so the read tool still accesses ['users', 'user-a'].
Verify Isolation with Another User
Append:
const other = await agent.invoke(
{
messages: [{ role: 'user', content: 'What product preference did I save earlier?' }],
},
{
configurable: { thread_id: 'user-b-chat-1' },
context: { userId: 'user-b' },
recursionLimit: 20,
}
);
console.log('Another user:', other.messages.at(-1)?.content);
Run it again:
node --env-file=.env 02.long-memory.mjs
One possible output:
Saved data: { product: 'mechanical keyboard' }
New conversation: Your saved product preference is mechanical keyboard.
Another user: You have no saved product preference.
User B has a different userId, so the tool reads a different namespace and cannot retrieve A’s preference.
All three calls run in the same process. InMemoryStore loses its data when that process exits. Production systems need a persistent store, such as a PostgreSQL-backed implementation.
🧱 What Should Long-Term Memory Store?
Long-term memory does not mean saving every conversation forever. Consider the following:
- Content: Keep information with lasting value, such as preferences and settings, rather than sensitive credentials such as access tokens.
- Memory management: Support updates and deletion. Deleting store data does not automatically remove historical messages from the checkpointer.
- Access control: The application validates user identity and memory permissions. Where explicit authorization is required, enforce it in code rather than relying solely on prompts. Memory content must not be executed as privileged instructions.
- Retrieval: This example reads preferences by a fixed key. With more memories, use store search to find relevant information, configuring semantic retrieval as needed.
❓ Questions and Answers
Q1: Can I use a store without a checkpointer?
Yes. A store holds data across conversations; a checkpointer restores conversation execution state. An application that only needs preferences without continuing earlier dialogue can use a store alone. The two features do not have to be used together.
🧪 Exercises
- In a new conversation for user A, ask to update the preference to wireless mouse. Verify the updated record with
store.get(). - Read preferences again using user B’s context and verify that B still has no record.
- Delete A’s preference with
await store.delete(['users', 'user-a'], 'preference'), then confirm withstore.get()that the record no longer exists.
🎉 Congratulations! You can now save, read, and isolate agent memories across conversations.
Short-Term Memory
Save conversation state with a checkpointer, use thread_id for follow-up conversations and isolation, and understand context management.
Middleware and Execution Controls
Use agent middleware to observe execution, retry transient tool failures, limit calls, manage context, and require human approval for sensitive operations.
