> ## 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.

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

将智能体部署到 LangSmith 时，通常需要在服务器启动时初始化数据库连接等资源，并确保在服务器关闭时正确释放它们。生命周期事件允许你介入服务器的启动和关闭流程，以处理这些关键的初始化和清理任务。

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

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

<Note>
  "仅限 Python"
  目前我们仅在 Python 部署中支持自定义生命周期事件，且需要 `langgraph-api>=0.0.26`。
</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"
  }
  // 其他配置选项，如认证、存储等。
}
```

## 启动服务器

在本地测试服务器：

```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="edit">
    [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/i18n\zh-CN\langsmith\custom-lifespan.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>
