Skip to main content
LangSmith에 에이전트를 배포할 때 서버가 시작될 때 데이터베이스 연결과 같은 리소스를 초기화하고 종료될 때 적절하게 닫히도록 해야 하는 경우가 많습니다. Lifespan 이벤트를 사용하면 서버의 시작 및 종료 시퀀스에 연결하여 이러한 중요한 설정 및 정리 작업을 처리할 수 있습니다. 이는 커스텀 라우트 추가와 동일한 방식으로 작동합니다. FastAPI, FastHTML 및 기타 호환 가능한 앱을 포함한 자체 Starlette 앱을 제공하기만 하면 됩니다. 다음은 FastAPI를 사용하는 예제입니다.
“Python 전용” 현재 langgraph-api>=0.0.26이 있는 Python 배포에서만 커스텀 lifespan 이벤트를 지원합니다.

앱 생성

기존 LangSmith 애플리케이션에서 시작하여 webapp.py 파일에 다음 lifespan 코드를 추가합니다. 처음부터 시작하는 경우 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로 중지할 때 정리 메시지가 출력됩니다.

배포

이 앱을 그대로 클라우드 또는 셀프 호스팅 플랫폼에 배포할 수 있습니다.

다음 단계

배포에 lifespan 이벤트를 추가했으니 유사한 기술을 사용하여 커스텀 라우트를 추가하거나 커스텀 미들웨어를 추가하여 서버의 동작을 더욱 커스터마이징할 수 있습니다.
Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I