Previous in LangChain
← Building a Real Weather Agent with LangChain and OpenWeatherMapLangChain Memory and Context: Building Stateful AI Conversations
June 1, 2026
LangChain Memory and Context: Building Stateful AI Conversations
Introduction
So far, our agents have been stateless.
Every time we invoke an agent, it treats the request as a completely new conversation. This means the model forgets everything that happened in previous interactions.
To build chatbots, assistants, customer support agents, and other conversational systems, we need memory.
LangChain allows us to add memory so that conversations can continue across multiple messages.
Understanding Memory
Without memory:
The second message lacks context because the agent does not remember the first interaction.
With memory:
The agent remembers previous messages and treats them as part of the same conversation.
Adding Memory with MemorySaver
LangChain agents support memory through a checkpointer.
One of the simplest options is MemorySaver.
import { MemorySaver } from '@langchain/langgraph';
const agent = createAgent({
model: 'gpt-5.4',
tools: [searchTool],
checkpointer: new MemorySaver()
});
The MemorySaver stores conversation state in memory (RAM).
This is convenient for development and testing, but the data is volatile.
If the application restarts, all conversation history is lost.
For production applications, you would typically store memory in a database.
Thread IDs
Memory works by associating messages with a specific thread.
A thread acts like a conversation identifier.
const config = {
configurable: {
thread_id: crypto.randomUUID()
}
};
When multiple requests use the same thread_id, LangChain understands that they belong to the same conversation.
Complete Example
import { createAgent, tool } from 'langchain';
import { MemorySaver } from '@langchain/langgraph';
import * as z from 'zod';
import 'dotenv/config';
const searchTool = tool(
async ({ input }) => {
const url = new URL(
`https://api.duckduckgo.com/?q=${encodeURIComponent(input)}&format=json`
);
const res = await fetch(url);
if (!res.ok) {
const body = await res.text();
throw new Error(`Search API failed (${res.status}): ${body}`);
}
const data = await res.json();
return data ?? 'No results found';
},
{
name: 'search',
description: 'Search the web for information',
schema: z.object({
input: z.string().describe('The input to search for'),
}),
}
);
const agent = createAgent({
model: 'gpt-5.4',
tools: [searchTool],
checkpointer: new MemorySaver()
});
const config = {
configurable: {
thread_id: crypto.randomUUID()
}
};
console.log(
await agent.invoke(
{
messages: [
{ role: 'human', content: 'What is FIFA?' }
],
},
config
)
);
console.log(
await agent.invoke(
{
messages: [
{ role: 'human', content: 'When do you think it will start?' }
],
},
config
)
);