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

# 如何添加自定义生命周期事件

当将代理部署到 LangSmith 时，您通常需要在服务器启动时初始化数据库连接等资源，并确保在关闭时正确关闭它们。生命周期事件让您能够接入服务器的启动和关闭序列，以处理这些关键的设置和清理任务。

这与[添加自定义路由](/langsmith/custom-routes)的方式相同。您只需提供自己的 [`Starlette`](https://www.starlette.io/applications/) 应用（包括 [`FastAPI`](https://fastapi.tiangolo.com/)、[`FastHTML`](https://fastht.ml/) 及其他兼容应用）。

以下是一个使用 FastAPI 的示例。

<Note>
  "仅限 Python"
  我们目前仅支持在使用 `langgraph-api>=0.0.26` 的 Python 部署中使用自定义生命周期事件。
</Note>

## 创建应用

从一个**现有的** LangSmith 应用程序开始，将以下生命周期代码添加到您的 `webapp.py` 文件中。如果您是从头开始，可以使用 CLI 从模板创建一个新应用。

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

一旦您有了一个 LangGraph 项目，请添加以下应用代码：

```python {highlight={19}} theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# ./src/agent/webapp.py
from contextlib import asynccontextmanager
from fastapi import FastAPI
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker

@asynccontextmanager
async def lifespan(app: FastAPI):
    # 例如...
    engine = create_async_engine("postgresql+asyncpg://user:pass@localhost/db")
    # 创建可复用的会话工厂
    async_session = sessionmaker(engine, class_=AsyncSession)
    # 存储在应用状态中
    app.state.db_session = async_session
    yield
    # 清理连接
    await engine.dispose()

app = FastAPI(lifespan=lifespan)

# ... 如果需要，可以添加自定义路由。
```

## 配置 `langgraph.json`

将以下内容添加到您的 `langgraph.json` 配置文件中。确保路径指向您上面创建的 `webapp.py` 文件。

```json theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{
  "dependencies": ["."],
  "graphs": {
    "agent": "./src/agent/graph.py:graph"
  },
  "env": ".env",
  "http": {
    "app": "./src/agent/webapp.py:app"
  }
  // 其他配置选项，如 auth、store 等。
}
```

## 启动服务器

在本地测试服务器：

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

当服务器启动时，您应该会看到启动消息被打印出来；当您使用 `Ctrl+C` 停止它时，会看到清理消息。

## 部署

您可以将应用原样部署到云端或您的自托管平台。

## 后续步骤

现在您已经为部署添加了生命周期事件，您可以使用类似的技术来添加[自定义路由](/langsmith/custom-routes)或[自定义中间件](/langsmith/custom-middleware)，以进一步自定义服务器的行为。

***

<div className="source-links">
  <Callout icon="terminal-2">
    [将这些文档连接](/use-these-docs)到 Claude、VSCode 等，通过 MCP 获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/langsmith/custom-lifespan.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
