70 lines
1.6 KiB
Python
70 lines
1.6 KiB
Python
"""FastAPI应用工厂"""
|
||
from contextlib import asynccontextmanager
|
||
from fastapi import FastAPI
|
||
from fastapi.middleware.cors import CORSMiddleware
|
||
|
||
from alcor.config import config
|
||
from alcor.database import init_db
|
||
from alcor.routes import api_router
|
||
|
||
|
||
@asynccontextmanager
|
||
async def lifespan(app: FastAPI):
|
||
"""应用生命周期管理"""
|
||
# 启动时
|
||
print("🚀 Starting up ChatBackend API...")
|
||
|
||
# 初始化数据库
|
||
init_db()
|
||
print("✅ Database initialized")
|
||
|
||
# 加载内置工具
|
||
from alcor.tools.builtin import crawler, code, data
|
||
print(f"✅ Loaded {len(api_router.routes)} API routes")
|
||
|
||
yield
|
||
|
||
# 关闭时
|
||
print("👋 Shutting down ChatBackend API...")
|
||
|
||
|
||
def create_app() -> FastAPI:
|
||
"""创建FastAPI应用"""
|
||
app = FastAPI(
|
||
title="ChatBackend API",
|
||
description="智能聊天后端API,支持多模型、流式响应、工具调用",
|
||
version="1.0.0",
|
||
lifespan=lifespan
|
||
)
|
||
|
||
# 配置CORS
|
||
app.add_middleware(
|
||
CORSMiddleware,
|
||
allow_origins=["*"], # 生产环境应限制
|
||
allow_credentials=True,
|
||
allow_methods=["*"],
|
||
allow_headers=["*"],
|
||
)
|
||
|
||
# 注册路由
|
||
app.include_router(api_router, prefix="/api")
|
||
|
||
# 健康检查
|
||
@app.get("/health")
|
||
async def health_check():
|
||
return {"status": "healthy", "service": "chat-backend"}
|
||
|
||
@app.get("/")
|
||
async def root():
|
||
return {
|
||
"service": "ChatBackend API",
|
||
"version": "1.0.0",
|
||
"docs": "/docs"
|
||
}
|
||
|
||
return app
|
||
|
||
|
||
# 创建应用实例
|
||
app = create_app()
|