> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-zh.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 如何使用自定义存储

> 在代理部署中，用自定义的 BaseStore 实现替换内置的 Postgres 存储。

当将代理部署到 LangSmith 时，服务器会提供一个内置的、基于 Postgres 的长期记忆存储，并支持通过 pgvector 进行可选的向量搜索。你可以将其替换为你自己的 [BaseStore](https://reference.langchain.com/python/langchain-core/stores/BaseStore) 实现，以使用不同的存储后端、自定义索引或专门的搜索功能。

你需要提供一个指向异步上下文管理器的路径，该管理器会生成一个 `BaseStore` 实例，服务器会自动管理存储的生命周期。

<Warning>
  自定义存储目前处于 **alpha** 阶段。此功能可能在次要版本更新中发生破坏性变更。
</Warning>

## 定义存储

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

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
langgraph new --template=new-langgraph-project-python my_new_project
```

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

<Note>
  不建议在生产部署中使用 SQLite。
</Note>

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# ./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
```

<Note>
  当配置了自定义存储时，它将 **完全替换** 内置的 Postgres 存储。诸如语义搜索和 TTL 清理等功能取决于你的实现。
</Note>

## 配置 `langgraph.json`

将 `store` 键添加到你的 [`langgraph.json` 配置文件](/langsmith/application-structure#configuration-file-concepts) 中。`path` 指向你 [之前定义](#define-the-store) 的异步上下文管理器。

```json theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{
  "dependencies": ["."],
  "graphs": {
    "agent": "./src/agent/graph.py:graph"
  },
  "env": ".env",
  "store": {
    "path": "./src/agent/store.py:generate_store"
  }
}
```

## 启动服务器

在本地测试服务器：

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
langgraph dev --no-browser
```

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

```
使用自定义存储。跳过存储 TTL 清理器。
```

## 部署

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

## 后续步骤

* [使用自定义检查点器](/langsmith/custom-checkpointer) 来替换内置的检查点存储。
* 了解 LangGraph 中的 [持久化与记忆](/oss/python/langgraph/persistence)。

***

<div className="source-links">
  <Callout icon="edit">
    [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/i18n\zh-CN\langsmith\custom-store.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
  </Callout>

  <Callout icon="terminal-2">
    [Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers.
  </Callout>
</div>
