Replace ConversationSummaryBufferMemory with Six Lines of Code in LangChain 1.x
The article explains why the old LangChain memory classes are deprecated, breaks down the new 1.x memory architecture into three independent components, and shows how to replace ConversationSummaryBufferMemory with a concise six‑line agent setup that supports multi‑user isolation, persistence, and summarization middleware.
Why the comment hits
The original Day 6 code imports ConversationSummaryBufferMemory from langchain_classic.memory. This package name signals that the legacy memory classes were moved to a compatibility layer and are no longer recommended in the main framework.
v0.3.1 – ConversationBufferMemory and ConversationSummaryBufferMemory are marked deprecated.
v1.0 – All legacy memory classes are migrated to the langchain-classic compatibility package; the core framework is rebuilt around LangGraph and Agent Middleware.
The official migration guide states to replace the old memory class with a checkpointer .
Why switch to the three‑piece stack
Legacy memory classes were designed for the pre‑tool‑calling era and have three major shortcomings:
Single‑process: one memory object equals one conversation, no thread concept.
No concurrency: sharing a memory object across users causes cross‑talk.
No persistence: restarting the process clears the context.
LangChain 1.x separates these concerns into three independent components: create_agent – assembles the model, tools, and memory into a runnable agent. checkpointer – decides what to store and where, isolating users by thread_id; supports SQLite or Postgres backends. middleware – processes context before feeding the model (summarization, redaction, trimming, etc.).
In this architecture the checkpointer is the state layer and the middleware is the processing layer; the old memory class coupled both, limiting depth of each.
Six‑line code replacement
Core code to assemble an agent with in‑memory checkpointing and automatic summarization:
import os
from langchain_openai import ChatOpenAI
from langchain.agents import create_agent
from langchain.agents.middleware import SummarizationMiddleware
from langgraph.checkpoint.memory import InMemorySaver
llm = ChatOpenAI(
model="Pro/MiniMaxAI/MiniMax-M2.5",
base_url="https://api.siliconflow.cn/v1",
api_key=os.getenv("SF_API_KEY"),
temperature=0,
)
# Six lines that assemble the agent
agent = create_agent(
llm,
tools=[],
middleware=[SummarizationMiddleware(
model=llm,
trigger=("tokens", 100), # auto‑summarize when >100 tokens
keep=("messages", 4), # retain last 4 messages
)],
checkpointer=InMemorySaver(),
)Running three dialogue turns demonstrates automatic context storage and retrieval:
config = {"configurable": {"thread_id": "user-bob"}}
agent.invoke({"messages": "我叫李四,是后端工程师"}, config)
agent.invoke({"messages": "主要用 Python 和 FastAPI"}, config)
result = agent.invoke({"messages": "你还记得我叫什么吗?"}, config)
print(result["messages"][-1].content) # 输出:当然记得,你叫李四,是一名后端工程师Compared with the original Day 6 approach, the new method eliminates manual save_context and load_memory_variables calls, and the summarization logic is now decoupled via middleware.
Adding persistence
Replace the in‑memory saver with a SQLite‑backed saver for durable storage:
from langgraph.checkpoint.sqlite import SqliteSaver
with SqliteSaver.from_conn_string("memory.db") as checkpointer:
agent = create_agent(
llm,
tools=[],
middleware=[SummarizationMiddleware(
model=llm,
trigger=("tokens", 1000),
keep=("messages", 10),
)],
checkpointer=checkpointer,
)
config = {"configurable": {"thread_id": "user-bob"}}
agent.invoke({"messages": "记住:我的项目代号是 Phoenix"}, config)Providing the same thread_id after a process restart restores the conversation history and summary.
For production, swapping to PostgresSaver requires only a single import change; the business code remains unchanged.
RAG + Memory in 1.x
The original Day 6 RAG example manually built a chain with itemgetter and a custom chat() function. The 1.x version consolidates everything into create_agent:
import os
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain_chroma import Chroma
from langchain.agents import create_agent
from langchain.agents.middleware import SummarizationMiddleware
from langchain_core.tools import tool
from langgraph.checkpoint.sqlite import SqliteSaver
# Vector store + retriever
vectorstore = Chroma(
persist_directory="./company_kb",
embedding_function=OpenAIEmbeddings(model="text-embedding-3-small"),
)
retriever = vectorstore.as_retriever(search_kwargs={"k": 3})
@tool
def search_company_kb(query: str) -> str:
"""Search the company knowledge base and return concatenated document contents."""
docs = retriever.invoke(query)
return "
".join(d.page_content for d in docs)
llm = ChatOpenAI(
model="Pro/MiniMaxAI/MiniMax-M2.5",
base_url="https://api.siliconflow.cn/v1",
api_key=os.getenv("SF_API_KEY"),
temperature=0,
)
with SqliteSaver.from_conn_string("rag_memory.db") as checkpointer:
agent = create_agent(
llm,
tools=[search_company_kb],
system_prompt="你是公司知识助手,回答问题前先用工具查文档。",
middleware=[SummarizationMiddleware(
model=llm,
trigger=("tokens", 2000),
keep=("messages", 10),
)],
checkpointer=checkpointer,
)
config = {"configurable": {"thread_id": "employee-001"}}
print(agent.invoke({"messages": "公司有什么培训机会?"}, config)["messages"][-1].content)
print(agent.invoke({"messages": "这些培训收费吗?"}, config)["messages"][-1].content)The new approach removes three code blocks:
No itemgetter dict assembly.
No hand‑written chat(question) wrapper.
No manual memory.save_context / memory.load_memory_variables calls.
The agent decides when to call the search_company_kb tool or answer directly, turning a hard‑coded chain into a model‑driven workflow.
Migration cheat‑sheet
Old API: ConversationBufferMemory → 1.x equivalent: checkpointer=InMemorySaver(). Difference: uses thread_id to isolate multiple users.
Old API: ConversationSummaryBufferMemory → 1.x equivalent: SummarizationMiddleware(trigger=..., keep=...). Difference: decouples storage and compression; middleware can be swapped.
Old API: memory.save_context() → 1.x equivalent: automatic via agent.invoke. Difference: no explicit save lines.
Old API: memory.load_memory_variables() → 1.x equivalent: automatic on next invoke. Difference: no manual retrieval.
Old API: max_token_limit=1000 → 1.x equivalent: trigger=("tokens", 1000). Difference: synonymous parameter.
Old API: single‑process memory → 1.x equivalent: SqliteSaver.from_conn_string("x.db"). Difference: persistence across restarts, shared across processes.
Old API: hard‑coded summarization in class → 1.x equivalent: middleware=[...]. Difference: middleware stack allows redaction, trimming, dynamic prompts.
When the old API is still useful
Running concepts or teaching demos in notebooks.
Maintaining legacy 0.x projects during a transition period.
Writing articles that demonstrate deprecated class behavior.
For production‑grade projects that require concurrency, persistence, or scaling, switch to the three‑piece stack: create_agent + checkpointer + SummarizationMiddleware.
Conclusion
LangChain 1.x memory is no longer a single class; it is a composable set of capabilities:
State handled by a checkpointer.
Processing handled by middleware.
Assembly handled by create_agent.
This decoupling shortens the path from prototype to production to a single import change.
Related links
LangChain v1 migration guide: https://docs.langchain.com/oss/python/migrate/langchain-v1
Agent Middleware documentation: https://docs.langchain.com/oss/python/langchain/middleware/built-in
LangGraph persistence documentation: https://docs.langchain.com/oss/python/langgraph/persistence
Short‑term memory documentation: https://docs.langchain.com/oss/python/langchain/short-term-memory
Day 6 original article: https://mp.weixin.qq.com/s/JUbc-AfoBWurYE4RIipGeQ
LangChain vs LangGraph vs DeepAgents comparison: https://mp.weixin.qq.com/s/sqCHds2zKvaW6bsoduTa6w
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Tech Ocean
Focused on AI programming, sharing ready-to-use development efficiency solutions.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
