Files
my-v0-server/app/main.py
T
2026-09-30 04:27:35 -07:00

57 lines
1.9 KiB
Python

"""FastAPI 应用入口"""
import asyncio
from contextlib import asynccontextmanager
from fastapi import FastAPI
from loguru import logger
from app.api.agent import router
from app.api.conversations import router as conversation_router
from app.core.exceptions import register_exception_handlers
from app.core.logging import setup_logging
@asynccontextmanager
async def lifespan(application: FastAPI):
setup_logging()
from app.clients.decision import close_decision_engine
from app.observability.tracing import flush_tracing
from app.processor.graph import build_graph
from app.services.agent import AgentService
from app.services.persistence import open_persistence
# 按配置选择 MongoDB 或进程内存,会话记录与图检查点使用同一种存储
persistence = await open_persistence()
application.state.conversation_store = persistence.store
application.state.agent_service = AgentService(
build_graph(persistence.checkpointer), persistence.store
)
try:
yield
finally:
# 共享客户端只在应用退出时关闭,追踪刷新放到线程避免阻塞事件循环
try:
await persistence.close()
finally:
try:
await close_decision_engine()
finally:
try:
await asyncio.to_thread(flush_tracing)
finally:
await logger.complete()
def create_app() -> FastAPI:
application = FastAPI(title="Screen Agent API", lifespan=lifespan)
# 统一处理请求校验、HTTP 错误和未捕获异常
register_exception_handlers(application)
# 统一 /api 前缀,方便前端代理和反向代理只配置一条规则
application.include_router(router, prefix="/api")
application.include_router(conversation_router, prefix="/api")
return application
app = create_app()