Short-Term Memory
🎯 Introduction
If an agent does not save conversation state and each call contains only the current question, the model cannot use earlier exchanges. Short-term memory saves and restores message history and execution state within a conversation, allowing follow-up questions and continued tasks. This article covers checkpointers, conversation isolation, and growing message histories.
🧱 Why Do We Need Short-Term Memory?
For example, a user tells the product assistant, “I want to buy 15 mechanical keyboards,” then asks, “How many units am I planning to buy?” If each agent.invoke() call contains just one user message and no conversation memory is configured, the model cannot know the quantity provided earlier.
A model can answer only from the context in its current request. User messages, tool calls, and results from the first run must be restored in the next request to remain available.
We could manually save result.messages and send the old and new messages together next time. However, an agent’s state includes not just user-assistant exchanges but potentially several rounds of tool requests and results. LangChain provides checkpointers to save and restore this execution state.
🧱 Checkpointers and Conversation State
A checkpointer saves state during agent execution. Here, we focus on message history: user messages, model messages, and tool results.
Each conversation is identified by a thread_id. The agent restores existing state using that ID, and the checkpointer records state updates during execution. Subsequent calls in the same conversation need only new user messages, without manually rebuilding the full history.
The diagram below shows separate state for different conversations:
thread_id is an application-assigned conversation identifier, not proof of user identity. Real systems should associate conversation IDs with authenticated users and check access on the backend so arbitrary IDs cannot expose other users’ messages.
🛠 Add Conversation Memory
Reuse shopOptions from agent-demo; no new dependencies are needed. Create 01.short-memory.mjs:
import { createAgent } from 'langchain';
import { MemorySaver } from '@langchain/langgraph';
import { shopOptions } from './agent.mjs';
// Store conversation state in memory
const checkpointer = new MemorySaver();
const agent = createAgent({
...shopOptions,
checkpointer,
});
MemorySaver keeps checkpoints in the current process’s memory, making it useful for learning and local tests. We create another agent to add a checkpointer to the existing configuration, without recreating the model or tools.
Start the Conversation
Append to the file:
const config = {
// Identify the conversation for this call
configurable: { thread_id: 'shop-a' },
recursionLimit: 20,
};
const first = await agent.invoke(
{
messages: [{ role: 'user', content: 'I want to buy 15 mechanical keyboards. Please check current stock.' }],
},
config
);
console.log('First call:', first.messages.at(-1)?.content);
Run:
node --env-file=.env 01.short-memory.mjs
One possible output:
First call: There are 12 mechanical keyboards in stock, so you need 3 more.
During execution, the checkpointer saves the task’s message state under shop-a.
Ask a Follow-Up in the Same Conversation
Append after the preceding code:
const second = await agent.invoke(
{
messages: [{ role: 'user', content: 'How many units am I planning to buy, then?' }],
},
config
);
console.log('Second call:', second.messages.at(-1)?.content);
Run the entire script again. You may see:
First call: There are 12 mechanical keyboards in stock, so you need 3 more.
Second call: You are planning to buy 15 units.
The second request does not mention “15 units,” but the agent restores earlier history with the same thread_id, allowing the model to answer.
This example deliberately asks about the user’s stated purchasing quantity rather than reusing old stock data. Stock can change, so a question about current stock should trigger a fresh tool lookup. Memory is not a source of up-to-date business data.
🧱 Isolate Conversations
Append a third call with a different conversation ID:
const otherConfig = {
// Use a different conversation ID
configurable: { thread_id: 'shop-b' },
recursionLimit: 20,
};
const other = await agent.invoke(
{
messages: [{ role: 'user', content: 'How many units am I planning to buy?' }],
},
otherConfig
);
console.log('Another conversation:', other.messages.at(-1)?.content);
Run the entire script again. You may see:
First call: There are 12 mechanical keyboards in stock, so you need 3 more.
Second call: You are planning to buy 15 units.
Another conversation: You have not told me how many units you plan to buy.
shop-b has none of shop-a’s history. Even with the same agent instance, sharing a model or tools does not automatically share messages.
In-Memory Storage and Persistence
To restore state with MemorySaver, reuse the same checkpointer instance within the same Node.js process. Its data is lost when the process exits. Running the script again creates the conversation from the first message; it does not restore the previous process’s history.
To restore conversations after service restarts, use a database-backed checkpointer, such as a PostgreSQL implementation. The original thread_id can then restore conversation state after a restart.
🧱 Manage Growing Context
Repeated messages in one conversation make its history grow. A checkpointer does not remove the model’s context window limit, and sending more history increases latency and token usage.
Two common approaches are:
| Approach | Description |
|---|---|
| Message trimming | Send only recent or necessary messages to the model |
| Message summarization | Summarize older messages while keeping recent ones |
Both approaches must preserve essential information and keep tool calls paired with their results. LangChain provides summarization middleware, covered later in “Middleware and Execution Controls.”
❓ Questions and Answers
Q1: With a checkpointer, must I still pass the full history to every invoke() call?
Usually not. Use the same thread_id and send only new messages. Resending saved history may duplicate messages or add unnecessary context overhead.
🧪 Exercises
In the same script, create shop-c and tell the agent you plan to buy 2 wireless mice. Ask for the planned quantity in both shop-a and shop-c. Verify that they retain 15 and 2 units respectively without mixing them up. Keep the original agent.mjs; the next article reuses its product configuration.
🎉 Congratulations! You can now save agent conversation state and isolate conversations.
