将智能体部署到 LangSmith 时,您通常需要在服务器启动时初始化资源(如数据库连接),并确保它们在关闭时正确关闭。生命周期事件允许您挂钩到服务器的启动和关闭序列以处理这些关键的设置和拆卸任务。 这与添加自定义路由的工作方式相同。您只需提供自己的 Starlette 应用程序(包括 FastAPIFastHTML 和其他兼容应用程序)。 下面是使用 FastAPI 的示例。
“仅 Python” 我们目前仅在使用 langgraph-api>=0.0.26 的 Python 部署中支持自定义生命周期事件。

创建应用

现有的 LangSmith 应用程序开始,将以下生命周期代码添加到您的 webapp.py 文件中。如果您从头开始,可以使用 CLI 从模板创建新应用。
langgraph new --template=new-langgraph-project-python my_new_project
拥有 LangGraph 项目后,添加以下应用代码:
# ./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 文件。
{
  "dependencies": ["."],
  "graphs": {
    "agent": "./src/agent/graph.py:graph"
  },
  "env": ".env",
  "http": {
    "app": "./src/agent/webapp.py:app"
  }
  // 其他配置选项,如 auth、store 等
}

启动服务器

在本地测试服务器:
langgraph dev --no-browser
您应该在服务器启动时看到打印的启动消息,并在使用 Ctrl+C 停止服务器时看到清理消息。

部署

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

后续步骤

现在您已将生命周期事件添加到部署中,您可以使用类似的技术添加自定义路由自定义中间件以进一步自定义服务器的行为。
Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.