Building State: A Deep Dive into LangChain Memory for Conversational AI
LangChain's old memory classes, such as ConversationBufferMemory and ConversationSummaryBufferMemory, are deprecated. This guide maps each one to its current replacement: a checkpointer with a thread ID, a trimming middleware, SummarizationMiddleware and the long-term Store API. The memory patterns are tested with a fake model, so you can check them without an API key.

This guide is for Python developers who want a LangChain chatbot that remembers what the user said. You will add memory the current way: a checkpointer that keeps each conversation's history, a window that trims old messages, a summary that keeps the gist, and a store for facts that last across sessions. The memory patterns are tested with a fake model, so you can check them without an API key.
Key takeaways
- LangChain's old memory classes, such as
ConversationBufferMemory, are deprecated. New code passes a checkpointer tocreate_agentand athread_idwith each call. - Trim or summarize long histories with middleware.
SummarizationMiddlewarereplacesConversationSummaryBufferMemory. - Facts that must outlive one conversation go in a store with a namespace per user, not in the chat history.
Why chatbots need memory
LLMs are stateless. The model sees only the messages you send in the current request. If the user says "What is my name?" and the earlier "I'm Priya" is not in that request, the model cannot answer.
So memory in a chatbot means one thing: choosing which past messages and facts go into the next prompt. The trade-off is simple:
- Too little memory: the bot loses the thread of the conversation.
- Too much memory: each call gets slower and costs more, and you hit the context limit.
LangChain's short-term memory docs add a third problem: even when a long history fits, models often do worse on it, because stale or off-topic messages distract them.
Short-term memory in LangChain is the message history of one conversation (a thread), saved by a checkpointer and sent back to the model on each turn. Long-term memory is data saved in a store that any conversation can read later.
This post is part 10 of the LLM & LangChain Fundamentals series. In part 9 you built agent memory from scratch in plain Python. Here you use LangChain's own tools for the same jobs.
What changed in LangChain memory
The earlier version of this post used ConversationChain with classes from langchain.memory. That module is gone from the langchain package. The classes now live in langchain-classic, marked deprecated since 0.3.1 and due for removal in 2.0.0. The reference names create_agent as the alternative.
Here is how each old class maps to the current approach:
| Old class | Current replacement | Trade-off | Use it when |
|---|---|---|---|
ConversationBufferMemory |
create_agent with a checkpointer |
Full recall, but the prompt grows every turn | Short chats |
ConversationBufferWindowMemory |
A @before_model trimming middleware |
Cheap, but older turns are gone | Task bots that need only recent context |
ConversationSummaryMemory and ConversationSummaryBufferMemory |
SummarizationMiddleware |
Keeps the gist, but costs extra model calls | Long chats |
VectorStoreRetrieverMemory |
The Store API with a search index | Recalls facts across sessions, but needs a write policy | Facts that must last |
RedisChatMessageHistory and similar |
A database-backed checkpointer, such as PostgresSaver |
Survives restarts, but needs a database | Production |
Set up
You need Python 3.10 or newer. Install the packages in a virtual environment:
pip install -U langchain langchain-openai langgraph numpy
numpy is only for the fake embeddings in the test at the end.
Step 1: Keep the whole conversation
Create memory_chat.py. A checkpointer saves the agent's state after each step. The thread_id in the config picks which conversation to load, like an email thread:
# memory_chat.py
import os
from dataclasses import dataclass
from typing import Any
from uuid import uuid4
from langchain.agents import AgentState, create_agent
from langchain.agents.middleware import SummarizationMiddleware, before_model
from langchain.messages import RemoveMessage
from langchain.tools import ToolRuntime, tool
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph.message import REMOVE_ALL_MESSAGES
from langgraph.runtime import Runtime
from langgraph.store.memory import InMemoryStore
def build_buffer_agent(model):
"""Full history: every message in the thread goes back to the model."""
return create_agent(model, tools=[], checkpointer=InMemorySaver())
def chat(agent, thread_id, text, **kwargs):
config = {"configurable": {"thread_id": thread_id}}
result = agent.invoke({"messages": [{"role": "user", "content": text}]}, config, **kwargs)
return result["messages"][-1].text
Checked against langchain@1.4.7, langchain-core@1.7.1, langchain-openai@1.7.3 and langgraph@1.2.18, 2026-10-29.
Call chat(agent, "user-42", "Hi, I'm Priya."), then chat(agent, "user-42", "What is my name?"). The second call sees both messages because they share a thread. A different thread_id starts a clean conversation.
InMemorySaver keeps checkpoints in RAM, so the LangGraph persistence docs note they are lost on restart. That is fine for learning and tests. Step 5 swaps in a database.
Step 2: Keep only the recent turns
For a task bot, a greeting from twenty messages ago rarely helps. A trimming middleware runs before each model call and keeps only the last few messages. This is the current form of ConversationBufferWindowMemory:
WINDOW = 4 # at most 4 messages, always starting with a user message
@before_model
def keep_recent(state: AgentState, runtime: Runtime) -> dict[str, Any] | None:
messages = state["messages"]
if len(messages) <= WINDOW:
return None
recent = messages[-WINDOW:]
while recent and recent[0].type != "human":
recent = recent[1:] # the history must start with a user message
return {"messages": [RemoveMessage(id=REMOVE_ALL_MESSAGES), *recent]}
def build_window_agent(model):
return create_agent(model, tools=[], middleware=[keep_recent], checkpointer=InMemorySaver())
Two details matter here. First, this pattern rewrites the saved history, so trimmed messages are gone for good. Second, the docs warn that the remaining history must stay valid for your provider. It should start with a user message and keep each tool call next to its result. The while loop handles the first rule for a chat without tools.
Step 3: Summarize older messages
A window forgets. A summary keeps the gist of older turns and the exact text of recent ones. In my own micro-SaaS tools, this is the memory type I use most often.
ConversationSummaryBufferMemory did this with a max_token_limit. The class is deprecated, and the current replacement is SummarizationMiddleware:
def build_summary_agent(model, summary_model):
return create_agent(
model,
tools=[],
middleware=[
SummarizationMiddleware(
model=summary_model, # a small, cheap model is enough
trigger=("tokens", 4000), # summarize once history passes ~4,000 tokens
keep=("messages", 20), # keep the last 20 messages word for word
)
],
checkpointer=InMemorySaver(),
)
trigger decides when summarizing starts. It accepts a token count, a message count or a fraction of the context window. keep decides how much recent history stays as it is, and defaults to 20 messages. If you leave out trigger, the docs say summarizing never starts on its own.
The trade-off is the same as before: each summary costs an extra model call, but later calls send fewer tokens. The middleware counts tokens by characters unless you pass a token_counter, so treat the threshold as approximate.
Step 4: Remember facts across conversations
Checkpointers are scoped to one thread. To remember that a user prefers TypeScript next week, in a new thread, use a store. The long-term memory docs describe a store as JSON documents, each under a namespace (like a folder) and a key (like a file name).
Give the agent two tools: one to save a fact and one to search saved facts. The runtime argument gives each tool the store and the current user:
@dataclass
class Context:
user_id: str
@tool
def save_fact(fact: str, runtime: ToolRuntime[Context]) -> str:
"""Save a lasting fact about the user, such as a preference or a decision."""
runtime.store.put(("facts", runtime.context.user_id), str(uuid4()), {"text": fact})
return "Saved."
@tool
def recall_facts(query: str, runtime: ToolRuntime[Context]) -> str:
"""Search saved facts about the user."""
items = runtime.store.search(("facts", runtime.context.user_id), query=query, limit=3)
return "\n".join(item.value["text"] for item in items) or "Nothing saved yet."
def build_long_term_agent(model, embeddings, dims):
store = InMemoryStore(index={"embed": embeddings, "dims": dims})
return create_agent(
model,
tools=[save_fact, recall_facts],
context_schema=Context,
store=store,
checkpointer=InMemorySaver(),
)
The index setting turns on search by meaning, so recall_facts("what language do I like?") can find "prefers TypeScript". The namespace includes the user ID, so one user's facts never show up for another. Pass the user at call time: chat(agent, "thread-7", "...", context=Context(user_id="user-42")).
This replaces VectorStoreRetrieverMemory. The model now decides when to save and when to look things up, which is easier to inspect than a hidden retrieval step.
Run it with a real model
Put the real model calls under a main guard, so the test can import the file without an API key:
if __name__ == "__main__":
from langchain.chat_models import init_chat_model
# Needs OPENAI_API_KEY. Check the provider's models page for current ids.
model = init_chat_model(os.getenv("CHAT_MODEL", "openai:gpt-6-luna"))
agent = build_summary_agent(model, summary_model=model)
print(chat(agent, "user-42", "Hi, I'm Priya and I build with TypeScript."))
print(chat(agent, "user-42", "What is my name?"))
On the date above, OpenAI's models page lists gpt-6-luna as its most efficient model. Model ids change often, so check that page and set CHAT_MODEL to switch. For Claude, install langchain-anthropic and use an id from Anthropic's models page, such as anthropic:claude-haiku-5-5.
Step 5: Persist memory in production
InMemorySaver and InMemoryStore vanish when the process stops. The LangChain docs use Postgres for production. Install langgraph-checkpoint-postgres (checked with 3.2.0) and psycopg[binary], then:
# prod_memory.py
import os
from langchain.agents import create_agent
from langgraph.checkpoint.postgres import PostgresSaver
DB_URI = os.environ["DATABASE_URL"] # e.g. postgresql://user:pass@host:5432/db
with PostgresSaver.from_conn_string(DB_URI) as checkpointer:
checkpointer.setup() # creates the tables on first run
# Needs OPENAI_API_KEY. Use the agent inside this block: the connection closes when it exits.
agent = create_agent(os.getenv("CHAT_MODEL", "openai:gpt-6-luna"), tools=[], checkpointer=checkpointer)
The store has a Postgres version too, PostgresStore from langgraph.store.postgres, set up the same way. The docs also point to SQLite and Azure Cosmos DB checkpointer libraries. Keep your connection string in an environment variable, never in code.
Test it without an API key
The LangChain unit-testing docs recommend fake chat models for this. FakeListChatModel returns the replies you give it, in order. For tool calls you need GenericFakeChatModel, with a small subclass so create_agent can bind tools to it:
# test_memory_chat.py
from langchain_core.embeddings import DeterministicFakeEmbedding
from langchain_core.language_models import FakeListChatModel
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain.messages import AIMessage, ToolCall
from memory_chat import (
Context, build_buffer_agent, build_long_term_agent, build_summary_agent, build_window_agent, chat,
)
class FakeToolModel(GenericFakeChatModel):
def bind_tools(self, tools, **kwargs):
return self
# 1. Buffer: both turns share the thread; a new thread starts empty.
agent = build_buffer_agent(FakeListChatModel(responses=["Hi Priya!", "Your name is Priya."]))
chat(agent, "t1", "Hi, I'm Priya.")
chat(agent, "t1", "What is my name?")
assert len(agent.get_state({"configurable": {"thread_id": "t1"}}).values["messages"]) == 4
assert agent.get_state({"configurable": {"thread_id": "t2"}}).values == {}
# 2. Window: after five turns, only the last messages remain.
agent = build_window_agent(FakeListChatModel(responses=["ok"]))
for i in range(5):
chat(agent, "w", f"message {i}")
kept = agent.get_state({"configurable": {"thread_id": "w"}}).values["messages"]
assert kept[0].type == "human" and len(kept) <= 5
# 3. Summary: old turns are folded into a summary written by the summary model.
agent = build_summary_agent(FakeListChatModel(responses=["ok"]), FakeListChatModel(responses=["SUMMARY"]))
for i in range(30):
chat(agent, "s", "x" * 600)
history = agent.get_state({"configurable": {"thread_id": "s"}}).values["messages"]
assert any("SUMMARY" in m.text for m in history) and len(history) < 60
# 4. Store: a fact saved in one thread is found from another thread.
model = FakeToolModel(messages=iter([
AIMessage(content="", tool_calls=[ToolCall(name="save_fact", args={"fact": "prefers TypeScript"}, id="1")]),
AIMessage(content="Noted."),
AIMessage(content="", tool_calls=[ToolCall(name="recall_facts", args={"query": "prefers TypeScript"}, id="2")]),
AIMessage(content="You prefer TypeScript."),
]))
agent = build_long_term_agent(model, DeterministicFakeEmbedding(size=64), dims=64)
user = Context(user_id="user-42")
chat(agent, "thread-a", "I prefer TypeScript.", context=user)
chat(agent, "thread-b", "What language do I like?", context=user)
tool_reply = agent.get_state({"configurable": {"thread_id": "thread-b"}}).values["messages"][-2]
assert tool_reply.text == "prefers TypeScript"
print("memory patterns work")
If a test fails, the message tells you which pattern broke before you spend a token. The summary test uses long messages so the history passes the 4,000-token trigger.
Frequently asked questions
Is ConversationBufferMemory deprecated?
Yes. It and the other langchain.memory classes moved to the langchain-classic package and are deprecated, with removal planned for 2.0.0. New code passes a checkpointer to create_agent and a thread_id with each call.
What replaced ConversationSummaryBufferMemory?
SummarizationMiddleware from langchain.agents.middleware. Set trigger to say when to summarize and keep to say how many recent messages stay word for word. Add it to create_agent with a checkpointer so the summary is saved with the thread.
What is a thread_id in LangChain?
It is the key that picks which conversation the checkpointer loads and saves. Use one per conversation, such as a chat session ID. Calls with the same thread_id share history, and calls with a new one start fresh.
How do I keep chat history after a server restart?
Use a database-backed checkpointer instead of InMemorySaver. The LangChain docs show PostgresSaver from langgraph-checkpoint-postgres, and the persistence docs list SQLite and other options. Call setup() once to create its tables.
Should I use a summary or a vector store for memory?
They solve different problems. A summary keeps the gist of one long conversation. A store with search keeps specific facts that later conversations need. Many apps use both: summarization inside the thread and a store for user facts.
Next in the series, you will give your agent new abilities with custom tools in LangChain, the same kind of tools that save_fact and recall_facts are.
Sources
Verified against the sources below on October 29, 2026. Products and docs change often: check the linked sources if something looks different.
- LangChain docs: Short-term memory
- LangChain docs: Long-term memory
- LangChain docs: Prebuilt middleware (SummarizationMiddleware)
- LangGraph docs: Persistence
- LangChain reference: ConversationSummaryBufferMemory (langchain-classic, deprecated)
- LangChain docs: Unit testing (fake chat models)
- OpenAI API: Models
- OpenAI API: Embeddings guide
- langchain on PyPI
- langgraph on PyPI
All 14 parts in this series
- Part 01What Is LangChain? When to Use It and When to Write Your Own Code
- Part 02LangChain vs. LlamaIndex vs. Vanilla: The Builder's Stack Selection Matrix
- Part 03Structured JSON Output from LLMs: Schema Injection, Pydantic and Retry Loops
- Part 04Building Your First LLM Chain: A Developer's Guide to Sequential Logic
- Part 05Building Your First RAG Pipeline: A Developer’s Guide to Context-Aware AI
- Part 06Building Robust RAG Pipelines: A Deep Dive into LangChain Document Loaders
- Part 07Stop Overthinking Vector Databases: A Builder’s Decision Framework
- Part 08Building Long-Term Memory: Setting Up Vector Databases for Semantic Search in LangChain
- Part 09From Chatbot to Agent: The Engineer's Guide to LLM Memory Systems
- Part 10Building State: A Deep Dive into LangChain Memory for Conversational AI
- Part 11Beyond Built-ins: Architecting Custom Tools in LangChain
- Part 12Unmasking the Black Box: Mastering LangChain Callbacks for Debugging
- Part 13Architecting Autonomous Agents: A Builder’s Guide to Complex Workflows
- Part 14Best Practices for Deploying LangChain Apps to Production
AI Automation Engineer & Salesforce Developer
Salesforce developer since June 2018. I build AI agents, n8n workflows and Salesforce integrations, and write up what holds up in real use.



Comments
Loading comments...