主题
如何添加自定义 lifespan 事件
将 agent 部署到 LangSmith 时,你通常需要在服务器启动时初始化数据库连接等资源,并确保在服务器关闭时正确关闭它们。Lifespan 事件让你可以挂钩到服务器的启动和关闭序列,以处理这些关键的初始化和清理任务。
其工作方式与添加自定义路由相同。你只需提供自己的 Starlette 应用(包括 FastAPI、FastHTML 和其他兼容应用)。
下面是一个使用 FastAPI 的示例。
NOTE
“仅 Python” 目前仅在 langgraph-api>=0.0.26 的 Python 部署中支持自定义 lifespan 事件。
创建应用
从现有的 LangSmith 应用开始,将以下 lifespan 代码添加到你的 webapp.py 文件中。如果从零开始,你可以使用 CLI 从模板创建新应用。
bash
langgraph new --template=new-langgraph-project-python my_new_project有了 LangGraph 项目后,添加以下应用代码:
python
# ./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 文件。
json
{
"dependencies": ["."],
"graphs": {
"agent": "./src/agent/graph.py:graph"
},
"env": ".env",
"http": {
"app": "./src/agent/webapp.py:app"
}
// Other configuration options like auth, store, etc.
}启动服务器
在本地测试服务器:
bash
langgraph dev --no-browser服务器启动时,你应该会看到启动消息被打印;使用 Ctrl+C 停止时,会看到清理消息。
部署
你可以将应用按原样部署到云端或自托管平台。
后续步骤
现在你已为部署添加了 lifespan 事件,可以使用类似技术添加自定义路由或自定义中间件,进一步自定义服务器行为。