Luxx/luxx/__init__.py

87 lines
2.4 KiB
Python

"""FastAPI application factory"""
import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from luxx.config import config
from luxx.database import init_db
from luxx.routes import api_router
logger = logging.getLogger(__name__)
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Application lifespan manager"""
# Import all models to ensure they are registered with Base
from luxx.models import User, Conversation, Message, Project, LLMProvider, ChatRoom, RoomAgent # noqa
init_db()
# Create default admin user if not exists, using config values
from luxx.database import SessionLocal
from luxx.models import User
from luxx.utils.helpers import hash_password
db = SessionLocal()
try:
admin_username = config.auth_admin_username
admin_user = db.query(User).filter(User.username == admin_username).first()
if not admin_user:
admin_user = User(
username=admin_username,
password_hash=hash_password(config.auth_admin_password),
role="admin",
permission_level=4 # ADMIN level
)
db.add(admin_user)
db.commit()
logger.info(f"Default admin user created: {admin_username} / {config.auth_admin_password}")
finally:
db.close()
# Import and register tools
from luxx.tools.builtin import crawler, code, data
yield
def create_app() -> FastAPI:
"""Create FastAPI application"""
app = FastAPI(
title="luxx API",
description="Intelligent chat backend API with multi-model support, streaming responses, and tool calling",
version="1.0.0",
lifespan=lifespan
)
# Configure CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Should be restricted in production
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Register routes
app.include_router(api_router, prefix="/api")
# Health check
@app.get("/health")
async def health_check():
return {"status": "healthy", "service": "luxx"}
@app.get("/")
async def root():
return {
"service": "luxx API",
"version": "1.0.0",
"docs": "/docs"
}
return app
# Create application instance
app = create_app()