LangChain Cross-Session Storage-Store
In the previous chapter we introduced Checkpointer, which can save an Agent's conversation history and give the same thread multi-turn memory capability.
But if a user starts a new conversation with a different thread_id, the previous chat history usually does not automatically appear in the new session.
If you want the Agent to share user preferences, learning progress, or long-term information across different sessions, you can use Store (long-term storage).
LangChain 1.x provides cross-session data storage based on LangGraph Store, supports managing data by namespace, and allows reading and writing in tools through ToolRuntime.
This chapter introduces the basic operations of Store, using Store in Agents, cross-session memory, coordination with Checkpointer, PostgreSQL persistence, and data security.
1. The difference between Checkpointer and Store
Both can save data, but they are responsible for different things.
| Comparison Item | Checkpointer | Store |
|---|---|---|
| Main Use | Save Agent execution state | Save long-term information |
| Data scope | Managed by thread_id | Managed by namespace and key |
| Content Saved | Messages, state, checkpoints | JSON documents |
| Cross-session sharing | Not automatically shared across different threads | Cross-thread access can be designed according to business needs |
| Read/write method | State is saved automatically during Agent execution | Explicitly read and written by the program or tools |
| Common Use Cases | Multi-turn conversations, interrupt recovery | User preferences, learning records, knowledge materials |
You can understand it this way:
Checkpointer
├── 对话 A 的消息历史
├── 对话 B 的消息历史
└── 当前 Agent 执行状态
Store
├── 用户学习偏好
├── 已完成的课程
└── 长期学习目标
Even if the same user starts different conversations, they can read their own long-term information through Store.
**Note:** Store does not automatically extract user preferences from chats. The program or Agent tools must explicitly perform save and read operations.
2. Store's data organization structure
Store organizes data using the namespace + key + value approach.
You can understand it as:
namespace:数据所属的命名空间
key:命名空间中的唯一键
value:需要保存的 JSON 数据
For example:
namespace = ("users", "user_001")
key = "preferences"
value = {
"language": "zh-CN",
"theme": "dark"
}
Here, namespace is a tuple of strings that can be used to distinguish users, projects, or business modules.
Recommended namespace design
| Data Type | namespace | key |
|---|---|---|
| User preferences | ("users", user_id) |
preferences |
| Learning progress | ("users", user_id) |
progress |
| Personal memory | ("memories", user_id) |
memory_id |
| Public tutorials | ("runoob", "courses") |
course_id |
| Project configuration | ("projects", project_id) |
settings |
It is recommended to divide data by access scope: public data uses a public namespace, and private user data uses a namespace containing a trusted user ID.
3. Basic operations of InMemoryStore
InMemoryStore is the simplest Store implementation, with data saved in the current Python process memory.
It mainly provides four common operations:
| Method | Description |
|---|---|
put() |
Write or update data |
get() |
Read specified data |
search() |
Retrieve data in a namespace |
delete() |
Delete specified data |
Example: Reading and writing user preferences and learning progress
Example
from
langgraph.
store
.
memory
import
InMemoryStore
store
=
InMemoryStore
(
)
namespace
=
(
"users"
,
"user_001"
)
Write
store.
put
(
namespace
,
"preferences"
,
{
"theme"
:
"dark"
,
"language"
:
"zh-CN"
,
"level"
:
"Beginner"
}
)
store.
put
(
namespace
,
"progress"
,
{
"completed_courses"
:
[
"HTML basics"
,
"Python Basics"
]
,
"total_hours"
:
35
}
)
Read
prefs
=
store.
get
(
namespace
,
"preferences"
)
(
"User preferences:"
,
prefs.
value
if
prefs
else
None
)
progress
=
store.
get
(
namespace
,
"progress"
)
(
"Learning progress:"
,
progress.
value
if
progress
else
None
)
Search
for
item
in
store.
search
(
namespace
)
:
(
item.
key
,
item.
value
)
Delete
store.
delete
(
namespace
,
"preferences"
)
(
"After deletion:"
,
store.
get
(
namespace
,
"preferences"
)
)
Running result:
用户偏好: {'theme': 'dark', 'language': 'zh-CN', 'level': '入门'}
学习进度: {'completed_courses': ['HTML 基础', 'Python 基础'], 'total_hours': 35}
preferences {'theme': 'dark', 'language': 'zh-CN', 'level': '入门'}
progress {'completed_courses': ['HTML 基础', 'Python 基础'], 'total_hours': 35}
删除后: None
Note:
get()returns a Store Item, and the actual data is initem.valueit.- If the corresponding data is not found, it usually returns
None。 put()When using the same namespace and key, the corresponding data is updated.delete()What is deleted is the specified data item, not the user's other data.
**Note:** InMemoryStore is only suitable for development and testing. Data is lost after the program exits and should not be used directly as long-term production storage.
4. Understanding Store Item
Pass store.get() When reading data, what is returned is not a simple dictionary but an Item containing the data and metadata.
Example
Example
item
=
store.
get
(
namespace
,
"progress"
)
if
item:
(
"Namespace:"
,
item.
namespace
)
(
"Key:"
,
item.
key
)
(
"Data:"
,
item.
value
)
(
"Creation time:"
,
item.
created_at
)
(
"Update time:"
,
item.
updated_at
)
These attributes can help developers understand the content of the data and when it was saved.
But note that the update time does not mean the data is necessarily the latest business information.
For example, the course catalog saved in Store may be outdated and needs to be synchronized regularly by the business program.
5. Accessing Store in an Agent
When creating an Agent, through the store parameter, pass in the Store instance:
agent = create_agent(
model="deepseek:deepseek-flash",
tools=[...],
store=store
)
LangChain 1.x recommends using ToolRuntime Access Store in a tool.
Add to the tool function:
runtime: ToolRuntime
Then through:
runtime.store
read or write data.
Compared with the legacy injection approach, this approach is more concise and can uniformly access State, Context, and tool call ID.
Example: Course query tool
Example
from
dotenv
import
load_dotenv
from
langchain.
agents
import
create_agent
from
langchain.
tools
import
tool
,
ToolRuntime
from
langgraph.
store
.
memory
import
InMemoryStore
load_dotenv
(
)
store
=
InMemoryStore
(
)
store.
put
(
(
"runoob"
,
"courses"
)
,
"python3"
,
{
"name"
:
"Python3 Basic Tutorial"
,
"level"
:
"Beginner"
,
"price"
:
"Free"
}
)
@
tool
def
query_course_info
(
course_id:
str
,
runtime: ToolRuntime
)
str
:
"""Query mock course information by course ID."""
if
runtime.
store
is
None
:
return
"Course storage unavailable"
item
=
runtime.
store
.
get
(
(
"runoob"
,
"courses"
)
,
course_id
)
return
str
(
item.
value
)
if
item
else
"No relevant course found"
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
query_course_info
]
,
store
=
store
,
system_prompt
=
"You are a course advisor. Use tools when querying courses; course data is mock data for teaching purposes."
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Please use a tool to query the python3 course."
}
]
}
)
(
result
[
"messages"
]
[
1
]
.
content
)
If the model calls the tool, it may answer:
Python3 基础教程是一门免费的入门课程。
The course materials here come from InMemoryStore and do not connect to the real course database of the Runoob Tutorial website.
**Note:** The model does not necessarily call tools proactively. If a query must be executed, it should be handled by the application or a deterministic workflow.
6. ToolRuntime: Reading runtime information
ToolRuntime is the main way for tools to obtain runtime information in LangChain 1.x.
| property | Description |
|---|---|
runtime.store |
Currently configured Store |
runtime.context |
Runtime Context of the current call |
runtime.state |
Current Agent State |
runtime.tool_call_id |
Current tool call ID |
runtime.config |
Current execution configuration |
runtime.stream_writer |
Custom streaming event writer |
In the tool parameters, runtime is automatically injected by LangChain and is not sent to the large language model as a normal tool parameter.
For example:
@tool
def my_tool(keyword: str, runtime: ToolRuntime) -> str:
...
The model only needs to generate keyword parameter was added.
**Note:** Only when a Store is passed in when creating the Agent can it be guaranteed that runtime.store can be used for the corresponding storage operations.
7. Reading personal data based on a trusted user ID
If Store holds users' private information, the model should not be allowed to provide an arbitrary user_id for queries.
For example, the following tool design has a privilege escalation risk:
@tool
def get_user_info(user_id: str):
...
Because the model may generate another user's ID.
A more reasonable approach is to use context_schema to receive user information already authenticated by the application backend.
Example: Reading the current user's learning preferences
Example
from
dataclasses
import
dataclass
from
langchain.
agents
import
create_agent
from
langchain.
tools
import
tool
,
ToolRuntime
from
langgraph.
store
.
memory
import
InMemoryStore
@
dataclass
class
UserContext:
user_id:
str
store
=
InMemoryStore
(
)
store.
put
(
(
"users"
,
"user_001"
)
,
"preferences"
,
{
"language"
:
"zh-CN"
,
"level"
:
"Beginner"
,
"favorite"
:
"Python"
}
)
@
tool
def
get_my_preferences
(
runtime: ToolRuntime
[
UserContext
]
)
str
:
"""Read the current user's learning preferences."""
if
runtime.
store
is
None
:
return
"Storage service unavailable"
user_id
=
runtime.
context
.
user_id
item
=
runtime.
store
.
get
(
(
"users"
,
user_id
)
,
"preferences"
)
return
str
(
item.
value
)
if
item
else
"No learning preferences saved yet"
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
get_my_preferences
]
,
store
=
store
,
context_schema
=
UserContext
,
system_prompt
=
"You are a learning assistant. Use get_my_preferences when querying user preferences."
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Please query my learning preferences."
}
]
}
,
context
=
UserContext
(
user_id
=
"user_001"
)
)
(
result
[
"messages"
]
[
1
]
.
content
)
If the tool executes correctly, the Agent can obtain the current user's preferences:
学习语言:Python
学习级别:入门
回答语言:中文
Here, user_id is not exposed as a tool parameter the model can fill in; instead, it is obtained from the Runtime Context.
**Important:** The user_id in the Context should be injected after authentication by a trusted backend. An arbitrary user_id submitted by the user's browser cannot be directly treated as an authenticated identity.
8. Saving user long-term memory through tools
In addition to reading Store, tools can also write to Store.
For example, a user tells the learning assistant:
以后给我讲 Python 时,尽量使用简单的例子。
The Agent can call a tool to save this preference.
Example: Saving learning preferences
Example
from
langchain.
tools
import
tool
,
ToolRuntime
@
tool
def
save_learning_preference
(
preference:
str
,
runtime: ToolRuntime
[
UserContext
]
)
str
:
"""Save the learning preferences that the current user explicitly asks to remember."""
if
runtime.
store
is
None
:
return
"Storage service unavailable"
user_id
=
runtime.
context
.
user_id
namespace
=
(
"users"
,
user_id
)
item
=
runtime.
store
.
get
(
namespace
,
"preferences"
)
data
=
dict
(
item.
value
)
if
item
else
{
}
data
[
"learning_style"
]
=
preference
runtime.
store
.
put
(
namespace
,
"preferences"
,
data
)
return
"Learning preferences saved"
Here, the existing preferences are read first, and then the learning style is updated, avoiding directly overwriting previously saved fields such as language and learning level.
The stored data may be:
{
"language": "zh-CN",
"level": "入门",
"favorite": "Python",
"learning_style": "尽量使用简单的例子"
}
If you use InMemoryStore, and the data will only be retained within the process.
**Note:** Long-term preferences should be explicitly stated or confirmed by the user as much as possible, avoiding saving the model's guesses as the user's real preferences.
9. Complete example: Sharing learning preferences across two sessions
This is the most important application scenario of Store.
Below, Checkpointer The difference between Store .
two sessions use different thread_ids but the same user_id.
This achieves:
- Different sessions have independent chat histories.
- Different sessions share the same user's long-term learning preferences.
- Learning preferences are saved through Store and do not need to be re-extracted from previous chat histories.
Filename:store_memory_demo.py
Install dependencies:
pip install -U langchain langgraph langchain-deepseek python-dotenv
Configure .env:
DEEPSEEK_API_KEY=your_deepseek_api_key
Complete example
from
dataclasses
import
dataclass
from
dotenv
import
load_dotenv
from
langchain.
agents
import
create_agent
from
langchain.
tools
import
tool
,
ToolRuntime
from
langgraph.
store
.
memory
import
InMemoryStore
from
langgraph.
checkpoint
.
memory
import
InMemorySaver
load_dotenv
(
)
@
dataclass
class
UserContext:
user_id:
str
store
=
InMemoryStore
(
)
checkpointer
=
InMemorySaver
(
)
@
tool
def
save_preference
(
preference:
str
,
runtime: ToolRuntime
[
UserContext
]
)
str
:
"""Save learning preferences according to the user's request."""
if
runtime.
store
is
None
:
return
"Storage unavailable"
namespace
=
(
"users"
,
runtime.
context
.
user_id
)
runtime.
store
.
put
(
namespace
,
"learning_style"
,
{
"text"
: preference
}
)
return
"Preferences saved"
@
tool
def
read_preference
(
runtime: ToolRuntime
[
UserContext
]
)
str
:
"""Read the learning preferences saved by the current user."""
if
runtime.
store
is
None
:
return
"Storage unavailable"
item
=
runtime.
store
.
get
(
(
"users"
,
runtime.
context
.
user_id
)
,
"learning_style"
)
return
item.
value
[
"text"
]
if
item
else
"No saved learning preferences"
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
save_preference
,
read_preference
]
,
store
=
store
,
checkpointer
=
checkpointer
,
context_schema
=
UserContext
,
system_prompt
=
"You are a programming learning assistant. Call save_preference when the user asks to save preferences; call read_preference when querying preferences."
)
context
=
UserContext
(
user_id
=
"student-001"
)
chat_a
=
{
"configurable"
:
{
"thread_id"
:
"chat-a"
}
}
chat_b
=
{
"configurable"
:
{
"thread_id"
:
"chat-b"
}
}
result1
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Please remember: when explaining Python to me, use more simple code examples."
}
]
}
,
config
=
chat_a
,
context
=
context
)
(
"Session A:"
,
result1
[
"messages"
]
[
1
]
.
content
)
result2
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Please read my saved learning preferences."
}
]
}
,
config
=
chat_b
,
context
=
context
)
(
"Session B:"
,
result2
[
"messages"
]
[
1
]
.
content
)
If the model correctly calls the save and read tools, it may get:
会话 A:学习偏好已经保存。
会话 B:你希望学习 Python 时,多使用简单的代码示例。
The two thread_ids are different:
chat-a
chat-b
But the two sessions use the same:
user_id = "student-001"
Therefore, although the chat histories are different, the tools can access the long-term preferences through the same namespace.
Can be understood as:
用户 student-001
|
+---- 会话 chat-a ---- Checkpointer
|
+---- 会话 chat-b ---- Checkpointer
|
+---- 学习偏好 ----- Store
**Note:** The tool calls in this example are determined by the model. In production, if a preference must be guaranteed to be saved, the application should explicitly perform the save operation and check the result.
10. Letting the Agent automatically read long-term preferences
The previous example requires the model to proactively call a tool to read learning preferences.
But sometimes you want the Agent to automatically load saved preferences every time the user asks a question.
You can use the @dynamic_prompt, read Store before the model request, and then dynamically generate the System Prompt.
Example: Injecting preferences into the system prompt
Example
from
langchain.
agents
.
middleware
import
dynamic_prompt
,
ModelRequest
@
dynamic_prompt
def
personalized_prompt
(
request: ModelRequest
[
UserContext
]
)
str
:
"""Read the current user's learning preferences."""
base
=
"You are the programming assistant of Runoob Tutorial RUNOOB."
store
=
request.
runtime
.
store
if
store
is
None
:
return
base
namespace
=
(
"users"
,
request.
runtime
.
context
.
user_id
)
item
=
store.
get
(
namespace
,
"learning_style"
)
if
not
item:
return
base
preference
=
item.
value
.
get
(
"text"
,
""
)
return
f
"{base}\nUser's saved learning preferences: {preference}\nRefer to this preference without affecting accuracy."
Add when creating the Agent:
agent = create_agent(
model="deepseek:deepseek-flash",
tools=[],
store=store,
context_schema=UserContext,
middleware=[personalized_prompt]
)
In this way, even if the user does not actively ask about preferences, the Agent can read saved data before each model call.
**Note:** Text in Store should be treated as data, not as system instructions with the highest priority. Unverified stored content must not be allowed to override permission control or other critical application rules.
11. search(): Searching data in Store
In addition to exact reads by key, you can also use search() to query data in a namespace.
Example: Searching user memory
Example
from
langgraph.
store
.
memory
import
InMemoryStore
store
=
InMemoryStore
(
)
namespace
=
(
"memories"
,
"student-001"
)
store.
put
(
namespace
,
"memory-001"
,
{
"type"
:
"language"
,
"text"
:
"Currently learning Python"
}
)
store.
put
(
namespace
,
"memory-002"
,
{
"type"
:
"goal"
,
"text"
:
"Want to master Web development"
}
)
store.
put
(
namespace
,
"memory-003"
,
{
"type"
:
"language"
,
"text"
:
"Already learned HTML"
}
)
items
=
store.
search
(
namespace
,
filter
=
{
"type"
:
"language"
}
,
limit
=
10
)
for
item
in
items:
(
item.
key
,
item.
value
[
"text"
]
)
The running result may be:
memory-001 正在学习 Python
memory-003 已经学习 HTML
Here, the following is used filter Search based on field values.
But note in particular that a normal search() is not the same as semantic search.
If you want to query similar memories based on natural language like 'what programming language have I been learning recently', you need to additionally configure Embedding and corresponding indexes.
12. Semantic search of Store
LangGraph Store supports vector-based semantic retrieval, but requires configuring an Embedding model.
A normal InMemoryStore does not automatically build semantic vector indexes for all content by default.
For example, you can use:
InMemoryStore(index={
"embed": embedding_model,
"dims": embedding_dimensions
})
and then provide when searching:
store.search(namespace, query="Python 学习目标", limit=5)
Store can return relevant content based on vector similarity.
Note:
- The Embedding model needs to be consistent with the index dimensions.
- Vectors from different models cannot be mixed arbitrarily.
- Long-term knowledge bases should consider data updates and re-indexing.
- Large knowledge bases usually require persistent vector indexes or a dedicated retrieval system.
If you only need to save simple structured information such as user language, learning level, and topic settings, using a normal get() and put() is usually more appropriate.
13. PostgresStore: Persistent long-term memory
InMemoryStore can only be saved in the current process.
When production environments need long-term data storage, you can use the PostgreSQL-backed PostgresStore。
Install dependencies:
pip install -U langgraph-checkpoint-postgres "psycopg[binary]"
Complete example: PostgreSQL storage
in .env Configure in :
POSTGRES_URI=postgresql://user:password@localhost:5432/langchain_db
Example
import
os
from
dotenv
import
load_dotenv
from
langgraph.
store
.
postgres
import
PostgresStore
load_dotenv
(
)
DB_URI
=
os
.
environ
[
"POSTGRES_URI"
]
with
PostgresStore.
from_conn_string
(
DB_URI
)
as
store:
store.
setup
(
)
namespace
=
(
"users"
,
"student-001"
)
store.
put
(
namespace
,
"preferences"
,
{
"language"
:
"zh-CN"
,
"level"
:
"Beginner"
}
)
item
=
store.
get
(
namespace
,
"preferences"
)
(
item.
value
if
item
else
"No data"
)
store.setup() used to initialize the required database structure and needs to be executed on first use.
After the program restarts, as long as it connects to the same database, it can continue reading the saved data.
Note when using:
- The database needs to be created in advance with the corresponding access permissions.
withThe connection is closed after the code block ends.- Production environments should manage connections or a connection pool within the application lifecycle.
- Database passwords should not be written directly into public source code.
- When using semantic search, the requirements for vector indexes and related extensions must also be met.
14. Using PostgresStore in an Agent
Using PostgresStore is basically the same as using InMemoryStore.
You only need to pass the database Store object when creating the Agent:
Example
import
os
from
dotenv
import
load_dotenv
from
langchain.
agents
import
create_agent
from
langgraph.
store
.
postgres
import
PostgresStore
load_dotenv
(
)
with
PostgresStore.
from_conn_string
(
os
.
environ
[
"POSTGRES_URI"
]
)
as
store:
store.
setup
(
)
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
get_my_preferences
]
,
store
=
store
,
context_schema
=
UserContext
,
system_prompt
=
"You are a learning assistant; use get_my_preferences when querying preferences."
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Please read my learning preferences."
}
]
}
,
context
=
UserContext
(
user_id
=
"student-001"
)
)
(
result
[
"messages"
]
[
1
]
.
content
)
Here, the previously defined get_my_preferences tool and UserContext。
Note that PostgresStore and PostgresSaver are not the same object:
PostgresStore:保存长期数据
PostgresSaver:保存 Agent 检查点
If you need both long-term memory and persistent conversations, configure Store and Checkpointer separately.
15. Asynchronous Store
If you use an asynchronous web framework such as FastAPI, you can choose a Store that supports asynchronous operations.
For example, PostgreSQL provides:
AsyncPostgresStore
Common asynchronous methods:
| Synchronized method | Asynchronous methods |
|---|---|
put() |
aput() |
get() |
aget() |
search() |
asearch() |
delete() |
adelete() |
Example: Asynchronous PostgreSQL Store
Example
import
os
import
asyncio
from
dotenv
import
load_dotenv
from
langgraph.
store
.
postgres
import
AsyncPostgresStore
load_dotenv
(
)
async
def
main
(
)
:
async
with
AsyncPostgresStore.
from_conn_string
(
os
.
environ
[
"POSTGRES_URI"
]
)
as
store:
await store.
setup
(
)
namespace
=
(
"users"
,
"student-001"
)
await store.
aput
(
namespace
,
"goal"
,
{
"text"
:
"Master Python Web development"
}
)
item
=
await store.
aget
(
namespace
,
"goal"
)
(
item.
value
if
item
else
None
)
if
name
==
"main"
:
asyncio.
run
(
main
(
)
)
The asynchronous approach is suitable for reducing the blocking of the event loop by database I/O in asynchronous services.
If a tool needs to perform asynchronous database operations internally, it should also use the corresponding asynchronous tool definitions and Store methods.
16. What is the difference between Store and a normal database?
Store is essentially a data access abstraction, but it is not exactly the same as the application's full business database.
| Data scenario | Recommended storage | Reason |
|---|---|---|
| User learning preferences | Store | Suitable for Agent cross-session reading |
| User long-term memory | Store | Supports namespaces and optional semantic search |
| Course catalog cache | Store or business cache | Convenient for Agent queries |
| Membership balance, payment orders | Business database | Requires transactions, auditing, and strict permissions |
| User login and permissions | Authentication system and business database | Cannot be left to the model or uncontrolled memory data to decide |
| Conversation messages and execution state | Checkpointer | Suitable for thread state persistence |
For a learning website, Store can be regarded as the Agent's long-term memory interface, not the only database for the entire website.
Core business data such as user accounts, membership subscriptions, and course purchase records should be managed by a trusted business system.
17. Production environment considerations
1. Do not trust the user ID generated by the model
When accessing a personal Store, use the user_id provided by the backend authentication system, rather than allowing the model to specify an arbitrary user.
2. Namespace is not the same as permission control
Even if data is stored by user namespace, the backend must verify whether the caller has permission to access the corresponding data.
3. Do not treat Store as an automatic memory system
Store does not automatically remember all chat content. You need to explicitly design what is worth saving, when to save it, and how to update and delete it.
4. Limit the scope of memory writes
Do not save entire chats to long-term memory without filtering.
It is recommended to save only necessary, explicit, and continuously valuable data, and allow users to view and modify it.
5. Handle data expiration and deletion
Long-term storage does not mean permanent retention. Data update, expiration, and deletion policies should be set according to business needs.
6. Avoid treating Store content as system instructions
Data in Store may come from users or external documents and should not be allowed to override security rules, tool permissions, or system prompts.
7. Databases must be persistent and backed up
InMemoryStore loses data after a restart. When long-term storage is needed, choose a persistent backend and consider backup and recovery mechanisms.
18. Frequently asked questions
1. What is the difference between Store and Checkpointer?
Checkpointer saves thread-level Agent State; Store saves long-term data that can be accessed across threads.
2. Does Store automatically save user conversations?
No. The program or tools need to explicitly call methods such as put() to write data.
3. Must a Store's namespace contain a user_id?
No. Public data can use a public namespace, while private user data should usually be isolated by trusted user ID.
4. Can Store be shared across multiple thread_ids?
Yes. As long as different threads access the same namespace and key according to authorization rules, they can read the same Store data.
5. Can a Store's value be a string?
LangGraph Store mainly organizes data as JSON documents, and a common practice is to save a dictionary, for example {"text": "学习 Python"}。
6. Does ToolRuntime.store need manual injection?
No. Once store is passed in when creating the Agent, tools can access it automatically through ToolRuntime.
7. Why is runtime.store None?
It may be that no Store was passed in when creating the Agent, or the current execution environment has no corresponding storage configured.
8. Does search() automatically support natural language semantic search?
No. Semantic search requires configuring Embedding and corresponding indexes.
9. Does InMemoryStore support recovery after a process restart?
No. It is saved in process memory.
10. Why does PostgresStore need setup()?
The relevant database structure needs to be initialized on first use.
11. Can Store save VIP membership information?
It can save caches or display data permitted by the business, but unverified Store content cannot be used as the sole basis for payment, membership permissions, or account authentication.
12. How to delete user memory?
You can call store.delete(namespace, key) to delete the specified data. Completely deleting user data also requires considering other keys, Checkpointer, business databases, and backups.
Summary
Store is an important mechanism for LangChain Agents to achieve long-term memory and cross-session data sharing.
This chapter introduces:
InMemoryStore: In-memory Store.put(): Save or update data.get(): Read specified data.search(): Search data in a namespace.delete(): Delete specified data.ToolRuntime.store: Access Store in Agent tools.runtime.context: Obtain trusted user context.- Share long-term preferences across different thread_ids.
PostgresStore: Persist long-term data.AsyncPostgresStore: Access the database asynchronously.- The responsibility differences between Store, Checkpointer, and normal business databases.
The most common usage:
store = InMemoryStore()
store.put(("users", "user_001"), "preferences", {"language": "zh-CN"})
item = store.get(("users", "user_001"), "preferences")
print(item.value)
Use in an Agent:
agent = create_agent(
model="deepseek:deepseek-flash",
tools=[my_tool],
store=store
)
Access in a tool:
@tool
def my_tool(runtime: ToolRuntime) -> str:
item = runtime.store.get(("users",), "example")
return str(item.value) if item else "没有数据"
Core principles:Checkpointer manages the execution state of a single thread, while Store manages long-term data across sessions. Long-term memory requires explicit read and write mechanisms, while user identity, permissions, and important business data must be controlled by a trusted backend.