当将代理部署到 LangSmith 时,服务器会提供一个内置的、基于 Postgres 的长期记忆存储,并支持通过 pgvector 进行可选的向量搜索。你可以将其替换为你自己的 BaseStore 实现,以使用不同的存储后端、自定义索引或专门的搜索功能。
你需要提供一个指向异步上下文管理器的路径,该管理器会生成一个 BaseStore 实例,服务器会自动管理存储的生命周期。
自定义存储目前处于 alpha 阶段。此功能可能在次要版本更新中发生破坏性变更。
定义存储
从一个 已存在 的 LangSmith 应用程序开始,创建一个文件来定义生成你的自定义存储的异步上下文管理器。如果你正在开始一个新项目,可以使用 CLI 从模板创建应用。
langgraph new --template=new-langgraph-project-python my_new_project
异步上下文管理器模式允许服务器在应用程序生命周期的正确时间点打开和关闭存储连接。以下示例使用支持语义搜索的 AsyncSqliteStore:
# ./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():
"""生成一个 BaseStore,在服务器运行期间保持打开状态。"""
async with AsyncSqliteStore.from_conn_string(
"./custom_store.sql",
index=IndexConfig(
dims=1536,
embed=embeddings,
fields=["$"],
),
) as store:
await store.setup()
yield store
当配置了自定义存储时,它将 完全替换 内置的 Postgres 存储。诸如语义搜索和 TTL 清理等功能取决于你的实现。
配置 langgraph.json
将 store 键添加到你的 langgraph.json 配置文件 中。path 指向你 之前定义 的异步上下文管理器。
{
"dependencies": ["."],
"graphs": {
"agent": "./src/agent/graph.py:graph"
},
"env": ".env",
"store": {
"path": "./src/agent/store.py:generate_store"
}
}
启动服务器
在本地测试服务器:
langgraph dev --no-browser
服务器日志将确认你的自定义存储已激活:
你可以将此应用按原样部署到 LangSmith 或你的自托管平台。
后续步骤