LangChain Conversation Memory——Checkpointer
By default, each independent call of the Agent invoke() does not automatically remember the content of the previous conversation.
For example, if you tell the AI "My name is Xiaoming" in the first round and then ask "What is my name?" in the second round, without passing in the history messages, the Agent usually cannot answer.
LangChain provides the Checkpointer, which enables multi-turn memory for the same conversation thread by saving and restoring the Agent State.
This section introduces InMemorySaver、SqliteSaver、PostgresSaver、thread_id, state management, historical checkpoints, and the application of conversation memory in real projects.
1. What happens without a Checkpointer?
Let's first look at an example that does not use a Checkpointer.
Each time the Agent is called, only the current user question is sent, without actively passing in the previous messages.
Example: Two independent conversations
Example
from
dotenv
import
load_dotenv
from
langchain.
agents
import
create_agent
load_dotenv
(
)
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
]
,
system_prompt
=
"You are a Chinese programming assistant for Runoob Tutorial RUNOOB."
)
result1
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"My name is Xiaoming, and I am learning Python."
}
]
}
)
(
"First round:"
,
result1
[
"messages"
]
[
1
]
.
content
)
result2
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"What is my name?"
}
]
}
)
(
"Second round:"
,
result2
[
"messages"
]
[
1
]
.
content
)
You might get:
第一轮:你好,小明!Python 是很适合入门的编程语言。
第二轮:你还没有告诉我你的名字。
The reason is that only the new user question was passed in during the second call.
For the current model request, the Agent cannot automatically obtain the history messages from the previous independent call.
**Note:** Not having a Checkpointer does not mean multi-turn conversation is completely impossible. You can also manually maintain the message history in your application and pass it in with each call.
The advantage of a Checkpointer is that state persistence is managed uniformly by LangGraph, reducing the work of manually assembling history messages.
2. Using InMemorySaver to remember conversations
The simplest Checkpointer is InMemorySaver, which stores the Agent State in the Python process memory.
You only need to pass in when creating the Agent checkpointer:
checkpointer=InMemorySaver()
Then through thread_id to identify a conversation thread.
Complete example: Two-turn conversation memory
Example
from
dotenv
import
load_dotenv
from
langchain.
agents
import
create_agent
from
langgraph.
checkpoint
.
memory
import
InMemorySaver
load_dotenv
(
)
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
]
,
checkpointer
=
InMemorySaver
(
)
,
system_prompt
=
"You are a Chinese programming assistant for Runoob Tutorial RUNOOB."
)
config
=
{
"configurable"
:
{
"thread_id"
:
"learning-001"
}
}
result1
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"My name is Xiaoming, and I am learning Python."
}
]
}
,
config
=
config
)
(
"First round:"
,
result1
[
"messages"
]
[
1
]
.
content
)
result2
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"What is my name? What am I learning?"
}
]
}
,
config
=
config
)
(
"Second round:"
,
result2
[
"messages"
]
[
1
]
.
content
)
The second round might yield:
你叫小明,正在学习 Python。
The reason is that both calls used the same:
thread_id = "learning-001"
LangGraph restores the state already saved for the thread on the next call, then merges the new messages from the current round.
**Note:** The actual reply from the model is not fixed. Even if history is saved, there is no guarantee that the model will accurately recall all details every time.
3. thread_id: Conversation thread identifier
thread_id is the key parameter for the Checkpointer to manage conversation state.
The same thread_id represents the same logical conversation thread, while different thread_ids are used to distinguish different sessions.
| Parameters | Purpose | Example |
|---|---|---|
thread_id |
Identify a conversation thread | chat-001 |
checkpoint_id |
Identify a specific checkpoint within a thread | Generated by the Checkpointer |
checkpoint_ns |
Distinguish checkpoint namespaces | Usually managed by the framework |
One user can have multiple thread_ids:
用户 user-001
├── chat-001:Python 学习
├── chat-002:Java 学习
└── chat-003:项目调试
Different users can also use the same Agent instance, but independent threads must be assigned to each of their sessions.
Example: Creating two independent sessions
Example
alice
=
{
"configurable"
:
{
"thread_id"
:
"alice-chat-001"
}
}
bob
=
{
"configurable"
:
{
"thread_id"
:
"bob-chat-001"
}
}
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"I am Alice."
}
]
}
,
config
=
alice
)
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"I am Bob."
}
]
}
,
config
=
bob
)
alice_state
=
agent.
get_state
(
alice
)
bob_state
=
agent.
get_state
(
bob
)
(
"Alice:"
,
alice_state.
values
[
"messages"
]
[
0
]
.
content
)
(
"Bob:"
,
bob_state.
values
[
"messages"
]
[
0
]
.
content
)
Output:
Alice: 我是 Alice。
Bob: 我是 Bob。
This shows that the two threads saved different states.
**Important:** thread_id is not an authentication token, nor a security isolation mechanism. Web applications must check on the backend whether the current user has permission to read or continue a certain thread_id.
You must not allow users to access other users' conversations by arbitrarily modifying URLs or request parameters.
4. How the Checkpointer works
A Checkpointer is not just a "chat log database"; it stores state checkpoints during the LangGraph execution process.
A simplified execution process:
第一次 invoke()
↓
识别 thread_id
↓
读取已有 Checkpoint(如果存在)
↓
合并用户输入
↓
执行 Agent 节点
↓
保存状态检查点
↓
返回结果
第二次 invoke()(相同 thread_id)
↓
恢复该线程最新状态
↓
合并新的用户消息
↓
继续执行 Agent
↓
保存新的检查点
A checkpoint can record:
- Message history
messages。 - Custom AgentState fields.
- Current execution state.
- Subsequent nodes to be executed.
- Checkpoint information related to execution resumption.
LangGraph can create checkpoints step by step during execution, rather than only saving after the task is completely finished.
This is also an important reason why the Checkpointer can support interrupt resumption and state history viewing.
5. Viewing the current conversation state with get_state()
Use agent.get_state(config) You can read the currently saved State of a specified thread.
returns a StateSnapshot, which contains the state values and execution-related information.
Example: Viewing messages and execution state
Example
state
=
agent.
get_state
(
config
)
(
"Next node: "
,
state.
next
)
(
"Message count: "
,
len
(
state.
values
.
get
(
"messages"
,
[
]
)
)
)
(
"Checkpoint configuration: "
,
state.
config
)
for
msg
in
state.
values
.
get
(
"messages"
,
[
]
)
:
(
f
"[{msg.type}] {str(msg.content)[:80]}"
)
For a simple Agent that has completed normally,state.next is usually:
()
indicates that the current checkpoint has no subsequent nodes waiting to be executed.
If the Agent is in an interrupted or waiting state,state.next it may contain the names of nodes to be executed.
Common StateSnapshot attributes
| property | Description |
|---|---|
values |
Current State fields and values |
next |
Nodes planned for execution next |
config |
Configuration information of the current checkpoint |
metadata |
Checkpoint metadata |
created_at |
Checkpoint creation time |
tasks |
Current related task information |
**Note:** A checkpoint for the corresponding thread must exist before you can read meaningful historical state.
6. Viewing state changes across multiple conversation turns
Below, we observe how the message history grows through three consecutive calls.
Example: Three-turn conversation
Example
from
dotenv
import
load_dotenv
from
langchain.
agents
import
create_agent
from
langgraph.
checkpoint
.
memory
import
InMemorySaver
load_dotenv
(
)
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
]
,
checkpointer
=
InMemorySaver
(
)
)
config
=
{
"configurable"
:
{
"thread_id"
:
"demo-003"
}
}
questions
=
[
"My name is Xiaoming."
,
"I'm learning Python."
,
"Summarize the information about me that was just introduced."
]
for
i
,
question
in
enumerate
(
questions
,
1
)
:
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
: question
}
]
}
,
config
=
config
)
state
=
agent.
get_state
(
config
)
(
f
"Round {i}: message count={len(state.values['messages'])}, next={state.next}"
)
(
"Reply:"
,
str
(
result
[
"messages"
]
[
1
]
.
content
)
[
:
80
]
)
If there is only one model reply per round, you might get:
第1轮:消息数=2,next=()
第2轮:消息数=4,next=()
第3轮:消息数=6,next=()
But if the model uses tools or Middleware to add messages, the actual message count may be higher.
Therefore, you cannot simply assume that "each round necessarily adds two messages".
7. Types of Checkpointer
LangGraph provides multiple checkpoint storage implementations that can be selected according to the application scale.
| Type | Storage location | Retained after process restart | Applicable scenarios |
|---|---|---|---|
InMemorySaver |
Python process memory | No | Development, debugging, testing |
SqliteSaver |
SQLite database file | Is | Single machine, small applications |
PostgresSaver |
PostgreSQL database | Is | Production applications, multi-instance deployment |
Corresponding installation methods:
# 基础 Checkpointer
pip install -U langgraph
# SQLite
pip install -U langgraph-checkpoint-sqlite
# PostgreSQL
pip install -U langgraph-checkpoint-postgres "psycopg[binary]"
Among them, InMemorySaver is provided with the base LangGraph dependencies, while the SQLite and PostgreSQL checkpoint implementations require additional installation.
Production deployments should also consider database access permissions, connection pooling, backups, state cleanup, and sensitive information protection.
8. SqliteSaver: Saving conversations to a database
SqliteSaver You can persist the Agent State to a SQLite file.
Even if the Python program exits, as long as the database file is not lost, you can still restore the session with the original thread_id later.
SQLite is well suited for local tools, small learning projects, and single-machine applications.
Complete example: SQLite conversation memory
Filename:sqlite_memory.py
Example
from
dotenv
import
load_dotenv
from
langchain.
agents
import
create_agent
from
langgraph.
checkpoint
.
sqlite
import
SqliteSaver
load_dotenv
(
)
with
SqliteSaver.
from_conn_string
(
"conversations.db"
)
as
checkpointer:
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
]
,
checkpointer
=
checkpointer
,
system_prompt
=
"You are a learning assistant for Runoob Tutorial RUNOOB."
)
config
=
{
"configurable"
:
{
"thread_id"
:
"student-001"
}
}
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"I am learning Python decorators."
}
]
}
,
config
=
config
)
(
"AI:"
,
result
[
"messages"
]
[
1
]
.
content
)
After running, the program will create or use in the current working directory:
conversations.db
The database will save the state checkpoints for that thread.
Rerun the program to restore history
When starting the program the second time, still use the same database file and thread_id:
Example
from
dotenv
import
load_dotenv
from
langchain.
agents
import
create_agent
from
langgraph.
checkpoint
.
sqlite
import
SqliteSaver
load_dotenv
(
)
with
SqliteSaver.
from_conn_string
(
"conversations.db"
)
as
checkpointer:
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
]
,
checkpointer
=
checkpointer
)
config
=
{
"configurable"
:
{
"thread_id"
:
"student-001"
}
}
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"What topic was I learning before?"
}
]
}
,
config
=
config
)
(
result
[
"messages"
]
[
1
]
.
content
)
If the previous state was saved successfully, the model can answer based on the history messages, for example:
你之前正在学习 Python 装饰器。
Note:
- Both examples must use the same database file.
- The same thread_id must be used.
- The database file must have the correct read and write permissions.
withAfter the code block ends, the database connection is closed.
For long-running web services, the lifecycle of the Checkpointer should be managed uniformly by the application, and it should not be meaninglessly created and closed in every HTTP request.
9. PostgresSaver: Persistence in production environments
When the Agent needs to serve a large number of users, or is deployed across multiple application instances, you can use PostgreSQL to save checkpoints.
PostgreSQL supports more complete database management capabilities and is better suited for production environments.
Install dependencies
pip install -U langgraph-checkpoint-postgres "psycopg[binary]"
Example: Using PostgreSQL to save memory
Example
import
os
from
dotenv
import
load_dotenv
from
langchain.
agents
import
create_agent
from
langgraph.
checkpoint
.
postgres
import
PostgresSaver
load_dotenv
(
)
DB_URI
=
os
.
environ
[
"POSTGRES_URI"
]
with
PostgresSaver.
from_conn_string
(
DB_URI
)
as
checkpointer:
checkpointer.
setup
(
)
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
]
,
checkpointer
=
checkpointer
)
config
=
{
"configurable"
:
{
"thread_id"
:
"student-001"
}
}
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Please introduce Python lists."
}
]
}
,
config
=
config
)
(
result
[
"messages"
]
[
1
]
.
content
)
corresponding .env:
DEEPSEEK_API_KEY=your_deepseek_api_key
POSTGRES_URI=postgresql://user:password@localhost:5432/langchain_db
Here, checkpointer.setup() initializes the required database tables and must be executed on first use.
Typically, the database schema setup can be completed during application initialization, rather than running setup on every ordinary request.
**Note:** Production database connections should use reliable credential management, access control, and appropriate encrypted connection settings. Do not commit real database passwords to public code repositories.
10. Asynchronous Checkpointer
If the Agent runs through ainvoke() or astream() asynchronously, you can use the corresponding asynchronous database checkpoint implementation.
| Synchronous version | Asynchronous version |
|---|---|
| SqliteSaver | AsyncSqliteSaver |
| PostgresSaver | AsyncPostgresSaver |
Example: AsyncSqliteSaver
Example
import
asyncio
from
dotenv
import
load_dotenv
from
langchain.
agents
import
create_agent
from
langgraph.
checkpoint
.
sqlite
.
aio
import
AsyncSqliteSaver
load_dotenv
(
)
async
def
main
(
)
:
async
with
AsyncSqliteSaver.
from_conn_string
(
"async_chat.db"
)
as
checkpointer:
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
]
,
checkpointer
=
checkpointer
)
config
=
{
"configurable"
:
{
"thread_id"
:
"async-001"
}
}
result
=
await agent.
ainvoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Hello, I am learning Python."
}
]
}
,
config
=
config
)
(
result
[
"messages"
]
[
1
]
.
content
)
if
name
==
"main"
:
asyncio.
run
(
main
(
)
)
Asynchronous calls use:
await agent.ainvoke(...)
If you need to read asynchronous state, you can use:
state = await agent.aget_state(config)
For PostgreSQL, the asynchronous implementation can complete initialization via AsyncPostgresSaver and await checkpointer.setup() .
11. get_state_history(): Viewing historical checkpoints
The Checkpointer can not only save the latest state, but also record multiple checkpoints produced in a thread.
Use get_state_history() You can iterate over these historical state snapshots.
Example: Listing historical checkpoints
Example
config
=
{
"configurable"
:
{
"thread_id"
:
"demo-003"
}
}
for
i
,
snapshot
in
enumerate
(
agent.
get_state_history
(
config
)
,
1
)
:
checkpoint_id
=
snapshot.
config
[
"configurable"
]
.
get
(
"checkpoint_id"
)
count
=
len
(
snapshot.
values
.
get
(
"messages"
,
[
]
)
)
(
f
"{i}. checkpoint={checkpoint_id}, message count={count}"
)
if
i
=
5
:
break
Possible output:
1. checkpoint=...,消息数=6
2. checkpoint=...,消息数=5
3. checkpoint=...,消息数=4
4. checkpoint=...,消息数=3
5. checkpoint=...,消息数=2
This is just an illustration; the actual number of checkpoints and saved states depend on the graph's execution steps.
A single Agent call may produce multiple checkpoints, so you cannot simply assume that "one Checkpoint equals one conversation turn".
**Note:** get_state_history() is mainly used for state tracking and historical checkpoint management, and should not be directly treated as an ordinary chat log pagination interface.
12. checkpoint_id: Reading a specific historical version
If you need to view the Agent State at a certain point in the past, you can read the corresponding state based on the historical checkpoint ID.
Example: Reading a previous checkpoint
Example
config
=
{
"configurable"
:
{
"thread_id"
:
"demo-003"
}
}
history
=
list
(
agent.
get_state_history
(
config
)
)
if
len
(
history
)
=
2
:
old_config
=
history
[
1
]
.
config
old_state
=
agent.
get_state
(
old_config
)
(
"Historical message count:"
,
len
(
old_state.
values
.
get
(
"messages"
,
[
]
)
)
)
(
"Historical checkpoint:"
,
old_config
[
"configurable"
]
.
get
(
"checkpoint_id"
)
)
Here, the specific checkpoint_id is obtained from the config in the historical snapshot, rather than constructing the checkpoint ID yourself.
This approach is suitable for debugging historical states and understanding the Agent execution process.
LangGraph also supports advanced features such as time travel, state branching, and execution replay based on historical checkpoints.
However, execution replay involves the behavior of graph nodes and external tools, which does not mean real business operations can be repeated without risk.
13. update_state(): Manually modifying conversation state
Some scenarios require modifying the saved state after the Agent has finished executing.
For example, modifying the current learning progress or supplementing custom information.
You can use:
agent.update_state(config, values)
Note thatupdate_state() writes an update to the graph state and creates a new checkpoint, rather than directly modifying all old versions of the state records in the database.
Example: Updating learning progress
First, define a State that contains custom fields.
Example
from
typing_extensions
import
NotRequired
from
langchain.
agents
import
create_agent
,
AgentState
from
langgraph.
checkpoint
.
memory
import
InMemorySaver
class
LearningState
(
AgentState
)
:
current_topic: NotRequired
[
str
]
user_level: NotRequired
[
str
]
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
]
,
state_schema
=
LearningState
,
checkpointer
=
InMemorySaver
(
)
)
config
=
{
"configurable"
:
{
"thread_id"
:
"learning-state-001"
}
}
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"I'm learning Python."
}
]
,
"current_topic"
:
"Variable"
,
"user_level"
:
"Beginner"
}
,
config
=
config
)
agent.
update_state
(
config
,
{
"current_topic"
:
"Decorator"
}
)
(
agent.
get_state
(
config
)
.
values
[
"current_topic"
]
)
Output:
装饰器
Here, what is updated is a custom business state field, rather than expressing learning progress through fabricated conversation messages.
**Note:** If actual user progress needs to be shared across multiple sessions, it is usually more appropriate to use a persistent Store or a business database.
14. Modifying or deleting message history
In AgentState, the messages Use add_messages Reducer。
Therefore, directly submitting:
agent.update_state(config, {"messages": []})
does not guarantee that all history messages will be cleared.
If you need to delete a specific message, you should use RemoveMessage。
Delete a specific message
Example
from
langchain.
messages
import
RemoveMessage
state
=
agent.
get_state
(
config
)
messages
=
state.
values
.
get
(
"messages"
,
[
]
)
if
messages:
agent.
update_state
(
config
,
{
"messages"
:
[
RemoveMessage
(
id
=
messages
[
0
]
.
id
)
]
}
)
This removes the message with the corresponding ID from the message list of the latest State.
Clear all messages
If you want to clear the message list of the current thread, you can use REMOVE_ALL_MESSAGES:
Example
from
langchain.
messages
import
RemoveMessage
from
langgraph.
graph
.
message
import
REMOVE_ALL_MESSAGES
agent.
update_state
(
config
,
{
"messages"
:
[
RemoveMessage
(
id
=
REMOVE_ALL_MESSAGES
)
]
}
)
(
"Remaining messages:"
,
len
(
agent.
get_state
(
config
)
.
values
.
get
(
"messages"
,
[
]
)
)
)
Under normal circumstances, the message list in the latest state will be cleared.
But you should pay special attention to:
- Clearing messages does not mean deleting the entire thread.
- Clearing the latest State does not mean physically deleting all old checkpoints.
- If there are custom state fields, these fields will not be cleared automatically.
- When deleting part of the history, you must ensure that the relationship between AI tool requests and ToolMessage remains valid.
For "starting a completely new conversation", the simplest approach is usually to create a new thread_id.
For the need to "completely delete user data", you need to combine the specific Checkpointer's thread deletion capability, database cleanup, and data retention policies.
15. The difference between Checkpointer and Store
The Checkpointer handles state persistence within the same thread, while the Store is used to store long-term information across sessions.
| Comparison Item | Checkpointer | Store |
|---|---|---|
| Main Use | Save Agent execution state | Save long-term memory and shared data |
| Data scope | Usually distinguished by thread_id | Organized by Namespace, Key, etc. |
| Typical data | Message history, current task state | User preferences, long-term learning records |
| Cross-session sharing | Does not automatically share across different threads | Can be designed for cross-thread reading based on business needs |
| Persistence capability | Depends on the Checkpointer implementation | Depends on the Store implementation |
For example, a programming learning website could be designed like this:
Checkpointer:
当前聊天消息
当前任务进度
Agent 执行检查点
Store / Database:
用户完成的课程
长期学习偏好
学习记录
会员和权限信息
Among these, membership status and permissions should be based on a trusted business database, rather than letting the model judge on its own based on conversation messages.
16. Production environment considerations
1. Do not directly trust the thread_id passed in by the client
The application backend must check whether the current user has permission to access the specified session.
You must not allow reading another user's chat history just because the user knows a certain thread_id.
2. Control concurrent calls to the same thread
If multiple requests modify the same conversation thread simultaneously, issues such as state races or execution order not meeting expectations may arise.
It is recommended to serialize writes to the same session according to application requirements, or adopt an explicit concurrency control strategy.
3. Control the length of conversation history
The Checkpointer saves messages, but does not automatically guarantee that the model context will never exceed the limit.
Long conversations can be combined with SummarizationMiddleware, message trimming, or other context management approaches.
4. Protect persisted data
Database checkpoints may contain user input, model replies, tool results, and custom state.
You should consider data encryption, least privilege, backups, log desensitization, and data retention periods.
5. Do not treat the Checkpointer as a long-term user profile database
Conversation history is suitable for storage by thread, while long-term user preferences, orders, and permissions should be placed in dedicated business storage.
6. Handle database connection lifecycle
Connections to SQLite and PostgreSQL should be properly managed by the application.
For web services, it is recommended to use connection management and asynchronous implementations suitable for the deployment environment, rather than recreating a database connection for every request.
17. Frequently Asked Questions
1. Can multi-turn conversation be achieved without a Checkpointer?
No, that is not correct. You can maintain the message history yourself and pass it to the Agent, but the Checkpointer provides a unified state saving and restoration mechanism.
2. Is thread_id a user ID?
No. thread_id is a session identifier; one user can have multiple conversation threads.
3. Is data from different thread_ids shared automatically?
Thread state is not shared automatically. If you need to share long-term information, you should use a Store or a business database.
4. Does data in InMemorySaver persist after a restart?
Usually not. It uses process memory to save checkpoints.
5. Does SqliteSaver support restoration after a restart?
Yes. As long as the saved database file still exists and the same thread_id is used.
6. Why does PostgresSaver need setup()?
Because the checkpoint-related tables and schema need to be initialized on first use.
7. How many checkpoints does one invoke() produce?
It varies. LangGraph can save checkpoints step by step during execution, not just the final state.
8. What is the difference between get_state() and get_state_history()?
get_state() is used to read a specified checkpoint or the current thread state; get_state_history() is used to view multiple historical state snapshots.
9. Does update_state() overwrite all historical checkpoints?
No. It updates the state according to the Reducer and creates a new checkpoint, rather than directly modifying all old versions.
10. How do I clear the conversation history?
You can create a new thread_id, or update the message list of an existing thread via RemoveMessage.
11. Does clearing messages equal deleting user data?
No. Old checkpoints, backups, and other business storage may still hold the related data, which needs to be handled uniformly according to data retention and deletion policies.
12. Can the Checkpointer guarantee that the model accurately remembers everything?
No. It is responsible for saving state, but the model is still affected by the context window, information interference, and generation accuracy.
Summary
The Checkpointer is an important mechanism for LangChain Agent to achieve short-term memory and state persistence.
This chapter introduces:
InMemorySaver: In-process checkpoints.SqliteSaver: SQLite database persistence.PostgresSaver: PostgreSQL persistence.thread_id: Distinguish conversation threads.get_state(): Read the current or a specified checkpoint state.get_state_history(): View historical checkpoints.update_state(): Manually submit state updates.RemoveMessage: Delete a specified historical message.REMOVE_ALL_MESSAGES: Clear the message list of the latest State.Store: Save long-term memory across sessions.
The most common usage:
agent = create_agent(
model="deepseek:deepseek-flash",
checkpointer=InMemorySaver()
)
config = {"configurable": {"thread_id": "chat-001"}}
agent.invoke({"messages": [{"role": "user", "content": "我叫小明"}]}, config=config)
agent.invoke({"messages": [{"role": "user", "content": "我叫什么?"}]}, config=config)
Core principles:The Checkpointer is responsible for saving Agent thread state, thread_id is responsible for distinguishing sessions, and the Store or business database handles long-term data. For online applications, you must also handle session authorization, database persistence, context management, and sensitive information protection properly.