跳到内容

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

将代理部署到 LangGraph 平台时,您通常需要在服务器启动时初始化数据库连接等资源,并确保在服务器关闭时正确关闭它们。生命周期事件允许您介入服务器的启动和关闭序列,以处理这些关键的设置和拆卸任务。

这与添加自定义路由的方式相同。您只需提供自己的 Starlette 应用程序(包括 FastAPIFastHTML 和其他兼容的应用程序)。

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

仅限 Python

目前,我们仅支持使用 langgraph-api>=0.0.26 在 Python 部署中添加自定义生命周期事件。

创建应用

现有的 LangGraph 平台应用程序开始,将以下生命周期代码添加到您的 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):
    # for example...
    engine = create_async_engine("postgresql+asyncpg://user:pass@localhost/db")
    # Create reusable session factory
    async_session = sessionmaker(engine, class_=AsyncSession)
    # Store in app state
    app.state.db_session = async_session
    yield
    # Clean up connections
    await engine.dispose()

app = FastAPI(lifespan=lifespan)

# ... can add custom routes if needed.

配置 langgraph.json

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

{
  "dependencies": ["."],
  "graphs": {
    "agent": "./src/agent/graph.py:graph"
  },
  "env": ".env",
  "http": {
    "app": "./src/agent/webapp.py:app"
  }
  // Other configuration options like auth, store, etc.
}

启动服务器

在本地测试服务器

langgraph dev --no-browser

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

部署

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

后续步骤

现在您已将生命周期事件添加到部署中,您可以使用类似的技术添加自定义路由自定义中间件,以进一步自定义服务器的行为。