以编程方式使用文档

将代理部署到 LangSmith 时,通常需要在服务器启动时初始化数据库连接等资源,并在其关闭时确保正确关闭。生命周期事件允许您挂钩到服务器的启动和关闭序列中,以处理这些关键设置和清理任务。

这与以下方式相同 添加自定义路由。您只需要提供您自己的 Starlette app(包括 FastAPI, FastHTML 和其他兼容的应用)。

以下是使用 FastAPI 的示例。

创建应用

从 **现有** LangSmith 应用开始,将以下生命周期代码添加到您的 webapp.py file. 如果您从零开始,可以使用 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.

部署

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

后续步骤

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