将 Agent 部署到 LangSmith 时,通常需要在服务器启动时初始化数据库连接等资源,并确保在服务器关闭时正确关闭它们。生命周期事件允许您挂钩到服务器的启动和关闭序列,以处理这些关键的设置和拆卸任务。 这与添加自定义路由的工作方式相同。您只需要提供自己的 Starlette 应用程序(包括 FastAPI、FastHTML 和其他兼容的应用程序)。 下面是一个使用 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):
# 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 配置文件中。确保路径指向您上面创建的 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 停止服务器时,您应该会看到清理消息。
部署中
您可以将应用程序原样部署到云端或您的自托管平台。
后续步骤
现在您已将生命周期事件添加到您的部署中,您可以使用类似的技术添加自定义路由或自定义中间件,以进一步自定义服务器的行为。