langgraph.store.postgres.PostgresStore
是 LangGraph 库中 langgraph.store.postgres
模块的一个持久化键值存储类,继承自 BaseStore
和 BasePostgresStore
,基于 PostgreSQL 数据库实现。LangGraph 是 LangChain 生态的扩展框架,专注于构建复杂、有状态的 AI 系统,通过状态图(StateGraph)管理节点和边,支持动态路由、循环和状态管理。PostgresStore
提供持久化存储功能,支持层次命名空间和可选的向量搜索(通过 pgvector 扩展),适合需要长时记忆的 AI 应用,如聊天机器人或自动化工作流。
PostgresStore
是 BaseStore
和 BasePostgresStore
的子类,定义如下:
from langgraph.store.postgres import PostgresStore
class PostgresStore(BaseStore, BasePostgresStore[Conn]):
"""
使用 PostgreSQL 数据库实现的持久化键值存储类。
参数:
conn: PostgreSQL 连接或连接池(psycopg.Connection 或 psycopg.Pool)。
index_config: 可选,索引配置,用于向量搜索。
serde: 可选的序列化器,默认为 JsonPlusSerializer。
ttl_config: 可选,TTL 配置,指定数据存活时间。
示例:
import psycopg
from langgraph.store.postgres import PostgresStore
pool = psycopg.Pool("postgresql://user:password@localhost:5432/dbname")
store = PostgresStore(conn=pool)
store.setup()
"""
BaseStore
:定义键值存储的基本接口。BasePostgresStore[Conn]
:提供 PostgreSQL 特定的存储逻辑,支持泛型连接类型。psycopg
库与 PostgreSQL 交互。pgvector
扩展以实现向量搜索。("users", "user1", "profile")
,便于管理复杂结构。put
、get
、delete
、list_namespaces
等方法,类似字典操作。pgvector
扩展支持语义搜索,基于向量嵌入查找相似数据。start_ttl_sweeper()
定期清理过期数据。get
、put
、delete
等。aget
、aput
、adelete
等(通过 AsyncPostgresStore
)。conn
:
Union[psycopg.Connection, psycopg.Pool]
import psycopg
pool = psycopg.Pool("postgresql://user:password@localhost:5432/dbname")
index_config
:
Optional[dict]
None
index_config = {"index_type": "hnsw", "m": 16, "ef_construction": 64}
serde
:
Optional[SerializerProtocol]
None
(使用 JsonPlusSerializer
)ttl_config
:
Optional[dict]
None
default_ttl
(分钟)和 refresh_on_read
(是否在读取时刷新 TTL)。ttl_config = {"default_ttl": 60, "refresh_on_read": True}
import psycopg
from langgraph.store.postgres import PostgresStore
pool = psycopg.Pool("postgresql://user:password@localhost:5432/dbname")
store = PostgresStore(conn=pool, index_config={"index_type": "hnsw"})
store = PostgresStore.from_conn_string("postgresql://user:password@localhost:5432/dbname")
setup()
store
、store_vectors
),首次使用时必须调用。store.setup()
AsyncPostgresStore
):await store.setup()
store
:存储键值数据,字段包括 prefix
(命名空间)、key
(键)、value
(值)、created_at
、updated_at
、expires_at
、ttl_minutes
。store_vectors
:存储向量数据,字段包括 prefix
、key
、field_name
(如 embedding
)、embedding
(向量)、created_at
、updated_at
。pgvector
扩展:CREATE EXTENSION IF NOT EXISTS vector;
pip install langgraph psycopg[binary,pool] pgvector
langgraph
:LangGraph 核心库。psycopg
:PostgreSQL 适配器,支持连接池。pgvector
:向量扩展,支持语义搜索。pgvector
扩展:CREATE EXTENSION IF NOT EXISTS vector;
import psycopg
pool = psycopg.Pool("postgresql://user:password@localhost:5432/dbname", max_size=20)
store.put(namespace=("users", "user1"), key="profile", value={"name": "Alice", "age": 30})
profile = store.get(namespace=("users", "user1"), key="profile")
print(profile) # 输出: {'name': 'Alice', 'age': 30}
store.delete(namespace=("users", "user1"), key="profile")
namespaces = list(store.list_namespaces())
print(namespaces) # 输出: [('users', 'user1'), ...]
from langchain.embeddings import HuggingFaceEmbeddings
embeddings = HuggingFaceEmbeddings()
vector = embeddings.embed_query("I love Italian cuisine")
store.put(namespace=("food", "pref"), key="user1", value=vector, field_name="embedding")
query = embeddings.embed_query("Italian food")
results = store.search(namespace=("food",), query=query, k=5)
for result in results:
print(result) # 输出: 匹配的键值对
AsyncPostgresStore
:from langgraph.store.postgres import AsyncPostgresStore
async_store = AsyncPostgresStore.from_conn_string("postgresql://user:password@localhost:5432/dbname")
await async_store.setup()
await async_store.put(namespace=("users", "user1"), key="profile", value={"name": "Alice"})
store.start_ttl_sweeper(default_ttl=60, refresh_on_read=True)
sweep_ttl
方法定期删除过期数据。from typing import List
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START
from langgraph.store.postgres import PostgresStore
import psycopg
from langchain_core.messages import HumanMessage
# 定义状态
class State(TypedDict):
messages: List[dict]
# 定义节点
def agent_node(state: State, store: PostgresStore) -> State:
user_id = "user1"
# 获取用户偏好
profile = store.get(namespace=("users", user_id), key="profile") or {"name": "Guest"}
last_message = state["messages"][-1]["content"]
response = f"Hello {profile['name']}, you said: {last_message}"
return {"messages": state["messages"] + [{"role": "assistant", "content": response}]}
# 创建连接池
pool = psycopg.Pool("postgresql://user:password@localhost:5432/dbname", max_size=20)
# 初始化 PostgresStore
store = PostgresStore(conn=pool)
store.setup()
# 存储用户偏好
store.put(namespace=("users", "user1"), key="profile", value={"name": "Alice"})
# 构建状态图
builder = StateGraph(State)
builder.add_node("agent", lambda state: agent_node(state, store))
builder.add_edge(START, "agent")
builder.set_finish_point("agent")
# 编译图
graph = builder.compile()
# 运行对话
config = {"configurable": {"thread_id": "thread-1"}}
result = graph.invoke({"messages": [{"role": "user", "content": "Hello"}]}, config=config)
print(result["messages"][-1]["content"]) # 输出: Hello Alice, you said: Hello
State
包含消息列表,模拟对话历史。PostgresStore
保存用户偏好(如 "profile"
),支持跨会话访问。store
:存储键值数据,字段包括:
prefix
:命名空间路径(如 users.user1
)。key
:键名。value
:序列化值(JSON 格式)。created_at
、updated_at
:创建和更新时间。expires_at
、ttl_minutes
:TTL 相关字段。store_vectors
:存储向量数据,字段包括:
prefix
、key
、field_name
(如 embedding
)。embedding
:向量(pgvector 类型)。created_at
、updated_at
。psycopg
执行插入、查询、更新和删除,事务确保一致性。users.user1
),支持分层查询。prefix
字段快速定位数据。pgvector
扩展,支持向量索引(如 HNSW)。expires_at
和 ttl_minutes
字段控制数据存活时间。sweep_ttl
方法定期清理过期数据,start_ttl_sweeper
启动后台任务。psycopg.Connection
(单连接)和 psycopg.Pool
(连接池)。setup()
创建表,需启用 pgvector
扩展。特性 | PostgresStore | InMemoryStore | RedisStore |
---|---|---|---|
存储位置 | PostgreSQL 数据库 | 内存 | Redis 数据库 |
适用场景 | 生产环境、长时记忆、向量搜索 | 调试、测试、短期实验 | 高并发、快速访问 |
持久化 | 是 | 否(重启后丢失) | 是 |
安装要求 | 需 psycopg 、pgvector |
无需额外安装 | 需 redis 、redisvl |
向量搜索 | 是(需 pgvector ) |
否 | 是(需 RedisJSON) |
异步支持 | 是(AsyncPostgresStore ) |
是 | 是(AsyncRedisStore ) |
选择建议:
InMemoryStore
,快速迭代。PostgresStore
(向量搜索、事务支持)或 RedisStore
(高并发、快速访问)。PostgresStore
更适合需要复杂查询和长期存储的场景。pgvector
扩展:CREATE EXTENSION IF NOT EXISTS vector;
psycopg.Pool
)优化性能:pool = psycopg.Pool("postgresql://user:password@localhost:5432/dbname", max_size=20)
setup()
创建表,确保用户有创建权限。JsonPlusSerializer
安全可靠。PickleCheckpointSerializer
)需确保数据可信。index_config = {"index_type": "hnsw", "m": 16, "ef_construction": 64}
max_size
),避免连接耗尽。debug=True
查看存储日志。store
和 store_vectors
表。get
或 search
验证数据。pgvector
兼容(建议 14+)。psycopg
和 pgvector
版本是否匹配。pgvector
扩展。docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=password postgres:14
)。graph.get_graph().to_dot()
)分析存储行为。langgraph.store.postgres.PostgresStore
是 LangGraph 提供的持久化键值存储类,基于 PostgreSQL 数据库,支持层次命名空间和向量搜索(通过 pgvector
)。它继承自 BaseStore
,提供 put
、get
、delete
等方法,通过 setup()
初始化表结构。核心功能包括持久化存储、语义搜索和 TTL 管理,适合生产环境中需要长时记忆和内容检索的 AI 应用,如聊天机器人和复杂工作流。相比 InMemoryStore
,它提供持久化优势;相比 RedisStore
,更适合事务支持和复杂查询场景。通过示例和实践,开发者可以快速掌握其用法,构建高效、可靠的 AI 系统。
关键引用: