以编程方式使用文档

在将代理部署到 LangSmith 时,服务器提供了一个内置的 Postgres 支持的长期记忆存储,可通过 pgvector 进行可选的向量搜索。您可以用自己的 BaseStore 实现替换它,以使用不同的存储后端、自定义索引或专门的搜索功能。

您提供一个指向异步上下文管理器的路径,它会生成一个 BaseStore 实例,服务器会自动管理存储的生命周期。

定义存储

从一个 **现有的** LangSmith 应用程序开始,创建一个定义异步上下文管理器生成您的自定义存储的文件。如果您正在开始一个新项目,可以使用 CLI 从模板创建应用程序。

langgraph new --template=new-langgraph-project-python my_new_project

异步上下文管理器模式让服务器在应用程序生命周期的正确时间点打开和关闭存储连接。以下示例使用 AsyncSqliteStore 进行语义搜索:

# ./src/agent/store.py


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 store

配置 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

服务器日志将确认您的自定义存储已激活:

Using custom store. Skipping store TTL sweeper.

部署

您可以将此应用程序按原样部署到 LangSmith 或您自托管的平台。

后续步骤