import asyncio from contextlib import asynccontextmanager from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from app.core.config import CORS_ORIGINS from app.core.discord.discord_bot import start_discord_bot from app.core.discord.scheduler import start_scheduler from app.core.memory_kb.word_memory import seed_from_history from app.db.database import SessionLocal, init_db from app.db.models import Message from app.api import chat, memory, logs, system def _seed_word_memory_from_db() -> None: db = SessionLocal() try: rows = ( db.query(Message.content) .filter(Message.role.in_(["user", "assistant"])) .order_by(Message.created_at.desc()) .limit(200) .all() ) seed_from_history([content for (content,) in rows]) finally: db.close() @asynccontextmanager async def lifespan(app: FastAPI): init_db() _seed_word_memory_from_db() start_scheduler() asyncio.create_task(start_discord_bot()) yield app = FastAPI(title="PlayChat API", version="0.1.0", lifespan=lifespan) app.add_middleware( CORSMiddleware, allow_origins=CORS_ORIGINS, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) app.include_router(chat.router) app.include_router(memory.router) app.include_router(logs.router) app.include_router(system.router) @app.get("/health") def health(): return {"status": "ok"}