Chat History, Memory and Persistence
Chat models are stateless, so "memory" means your application stores the conversation and puts the right parts back into each request. In LangChain 1.x, short-term memory is thread-scoped agent state saved by a checkpointer (`create_agent(..., checkpointer=...)` plus a `thread_id`), and long-term memory is a store that any thread can read. Know how to keep history inside the context window (trim, delete, summarise) without breaking message structure, how to keep users isolated, and where the legacy memory classes and `RunnableWithMessageHistory` now stand.
Key points
- 1
Short-term memory: pass
checkpointer=InMemorySaver()(development) or a database-backed saver such asPostgresSaver.from_conn_string(DB_URI)withsetup()(production) tocreate_agent, then callagent.invoke(input, {"configurable": {"thread_id": "42"}}). Same thread id, same conversation; a new thread id starts empty. - 2
With a checkpointer attached, a call without
thread_idraisesValueError(the checkpointer requiresthread_id,checkpoint_nsorcheckpoint_id). Without a checkpointer, athread_iddoes nothing and each invoke starts from only the messages you pass. - 3
Long-term memory: pass
store=tocreate_agent(InMemoryStorefor development,PostgresStorewithsetup()in production). Items are JSON dicts under a namespace tuple and a key:store.put(ns, key, value),store.get(ns, key)(returnsNoneif absent),store.search(ns_prefix, filter=..., query=..., limit=10). Namespaces are hierarchical, so a prefix search covers sub-namespaces. - 4
Semantic
queryranking in a store needs an index:InMemoryStore(index={"embed": embeddings, "dims": N}). Without one, search returns items unranked withscore=None. - 5
Tools reach memory through
runtime: ToolRuntime[Ctx](hidden from the model):runtime.statefor thread state,runtime.storefor the store,runtime.contextfor per-call context such as the user id. Context is not checkpointed and must be passed on every invoke. - 6
Custom thread state: subclass
AgentState, add fields such asuser_id, and passstate_schema=; values come in with the invoke input and persist per thread with the checkpointer. - 7
The
messageskey uses theadd_messagesreducer: new ids append, an existing id replaces that message,RemoveMessage(id=...)deletes it (a missing id raisesValueError), andRemoveMessage(id=REMOVE_ALL_MESSAGES)followed by messages rewrites the list. Updates from hooks likebefore_modelare permanent in the checkpoint. - 8
trim_messages(messages, *, max_tokens, token_counter, strategy="last", allow_partial=False, end_on=None, start_on=None, include_system=False, text_splitter=None)returns a new list.token_countercan be a callable, a chat model,"approximate", orlen(counts messages). Called withoutmessages, it returns a runnable. - 9
For a valid chat history use
strategy="last",start_on="human"andinclude_system=True. The kept system message counts toward the budget, andstart_oncan return fewer messages than the budget allows. - 10
filter_messageskeeps messages that match anyinclude_*condition (names, types, ids) and noexclude_*condition;exclude_tool_calls=Trueremoves AI messages with tool calls and allToolMessages. - 11
Summarisation (for example
SummarizationMiddlewarewith atriggerandkeep) bounds context while keeping the gist, at the cost of extra model calls and possibly lost exact details. Keep exact identifiers in state or the store. - 12
Legacy:
ConversationBufferMemory,ConversationBufferWindowMemory(k=5),ConversationTokenBufferMemory,ConversationSummaryMemory,ConversationSummaryBufferMemory(max_token_limit=2000),VectorStoreRetrieverMemoryandConversationChainlive inlangchain-classicand warn that they are deprecated in favour ofcreate_agentwith checkpointing or the Store API.RunnableWithMessageHistory(config keysession_id, plusinput_messages_key,history_messages_key,output_messages_key,history_factory_config) andInMemoryChatMessageHistoryalso emit deprecation warnings inlangchain-core1.7.
Common traps
Trimming by count can start the history on an AI message or an orphaned
ToolMessage; providers reject a tool result whose requestingAIMessagewas cut. Usestart_on="human".A hard-coded
thread_idorsession_id, or a history factory that ignores its argument, makes every user share one conversation.InMemorySaverand dict-held histories are per process: lost on restart and not shared across replicas. Sticky sessions hide only half the problem.RunnableWithMessageHistoryover a chain that returns a dict needsoutput_messages_key; without it the call succeeds, a callback error is logged, and nothing is saved.Session ids go in
config["configurable"], not in the input dict, andthread_iddoes not satisfyRunnableWithMessageHistory.Using the user id as the
thread_idmerges every conversation into one ever-growing thread; put cross-conversation facts in the store instead.from langchain.memory import ...fails in 1.x; the classes are inlangchain_classic.memory.
Read the source
Further reading
Suggest a resourceNo extra reading for Chat History, Memory and Persistence yet. Found a guide, video or cheat sheet that made it click? Share it and help the next learner.
Test yourself on Chat History, Memory and Persistence
Ten questions, with the answer and explanation after each one.