主题
如何使用自定义 store
在 agent 部署中,用自定义 BaseStore 实现替换内置的 Postgres store。
将 agent 部署到 LangSmith 时,服务器会提供一个内置的、由 Postgres 支持的长期记忆 store,并可通过 pgvector 提供可选的向量搜索。你可以用自己的 BaseStore 实现替换它,以使用不同的存储后端、自定义索引或专门的搜索能力。
你提供一个异步上下文管理器的路径,该管理器会 yield 一个 BaseStore 实例,服务器会自动管理该 store 的生命周期。
WARNING
自定义 store 处于 alpha 阶段。此功能可能会在次版本更新中发生破坏性变更。
定义 store
从现有的 LangSmith 应用开始,创建一个文件,在其中定义可 yield 自定义 store 的异步上下文管理器。如果要开始新项目,你可以使用 CLI 从模板创建应用。
bash
langgraph new --template=new-langgraph-project-python my_new_project异步上下文管理器模式让服务器可以在应用生命周期的正确节点打开和关闭 store 连接。以下示例使用带语义搜索的 AsyncSqliteStore:
NOTE
不建议在生产部署中使用 SQLite。
python
# ./src/agent/store.py
import contextlib
from langchain.embeddings import init_embeddings
from langgraph.store.base import IndexConfig
from langgraph.store.sqlite import AsyncSqliteStore
embeddings = init_embeddings("openai:text-embedding-3-small")
@contextlib.asynccontextmanager
async def generate_store():
"""Yield a BaseStore, open for the duration of the server."""
async with AsyncSqliteStore.from_conn_string(
"./custom_store.sql",
index=IndexConfig(
dims=1536,
embed=embeddings,
fields=["$"],
),
) as store:
await store.setup()
yield storeNOTE
配置自定义 store 后,它会完全替换内置的 Postgres store。语义搜索和 TTL 清理等能力取决于你的实现。
配置 langgraph.json
将 store 键添加到你的 langgraph.json 配置文件。path 指向你先前定义的异步上下文管理器。
json
{
"dependencies": ["."],
"graphs": {
"agent": "./src/agent/graph.py:graph"
},
"env": ".env",
"store": {
"path": "./src/agent/store.py:generate_store"
}
}启动服务器
在本地测试服务器:
bash
langgraph dev --no-browser服务器日志会确认你的自定义 store 已生效:
Using custom store. Skipping store TTL sweeper.部署
你可以将此应用按原样部署到 LangSmith 或自托管平台。
后续步骤
- 使用自定义 checkpointer 替换内置的 checkpoint 存储。
- 了解 LangGraph 中的持久化与记忆。