Commit 49f43a45 authored by Vũ Hoàng Anh's avatar Vũ Hoàng Anh

Fix mock API routing and retriever alias

parent 566ee233
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
import asyncio import asyncio
import os import os
import platform import platform
if platform.system() == "Windows": if platform.system() == "Windows":
print("🔧 Windows detected: Applying SelectorEventLoopPolicy globally...") print("🔧 Windows detected: Applying SelectorEventLoopPolicy globally...")
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
import logging import logging
import uvicorn import uvicorn
from fastapi import FastAPI from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
from api.chatbot_route import router as chatbot_router from api.chatbot_route import router as chatbot_router
from api.conservation_route import router as conservation_router from api.conservation_route import router as conservation_router
from api.prompt_route import router as prompt_router from api.prompt_route import router as prompt_router
from common.cache import redis_cache from common.cache import redis_cache
from common.langfuse_client import get_langfuse_client from common.langfuse_client import get_langfuse_client
from common.middleware import middleware_manager from common.middleware import middleware_manager
from config import PORT from config import PORT
# Configure Logging # Configure Logging
logging.basicConfig( logging.basicConfig(
level=logging.INFO, level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
handlers=[logging.StreamHandler()], handlers=[logging.StreamHandler()],
) )
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
langfuse_client = get_langfuse_client() langfuse_client = get_langfuse_client()
if langfuse_client: if langfuse_client:
logger.info("✅ Langfuse client ready (lazy loading)") logger.info("✅ Langfuse client ready (lazy loading)")
else: else:
logger.warning("⚠️ Langfuse client not available (missing keys or disabled)") logger.warning("⚠️ Langfuse client not available (missing keys or disabled)")
app = FastAPI( app = FastAPI(
title="Contract AI Service", title="Contract AI Service",
description="API for Contract AI Service", description="API for Contract AI Service",
version="1.0.0", version="1.0.0",
) )
# ============================================================================= # =============================================================================
# STARTUP EVENT - Initialize Redis Cache # STARTUP EVENT - Initialize Redis Cache
# ============================================================================= # =============================================================================
@app.on_event("startup") @app.on_event("startup")
async def startup_event(): async def startup_event():
"""Initialize Redis cache on startup.""" """Initialize Redis cache on startup."""
await redis_cache.initialize() await redis_cache.initialize()
logger.info("✅ Redis cache initialized for message limit") logger.info("✅ Redis cache initialized for message limit")
# ============================================================================= # =============================================================================
# MIDDLEWARE SETUP - Gom Auth + RateLimit + CORS vào một chỗ # MIDDLEWARE SETUP - Gom Auth + RateLimit + CORS vào một chỗ
# ============================================================================= # =============================================================================
middleware_manager.setup( middleware_manager.setup(
app, app,
enable_auth=True, # 👈 Bật lại Auth để test logic Guest/User enable_auth=True, # 👈 Bật lại Auth để test logic Guest/User
enable_rate_limit=True, # 👈 Bật lại SlowAPI theo yêu cầu enable_rate_limit=True, # 👈 Bật lại SlowAPI theo yêu cầu
enable_cors=True, # 👈 Bật CORS enable_cors=True, # 👈 Bật CORS
cors_origins=["*"], # 👈 Trong production nên limit origins cors_origins=["*"], # 👈 Trong production nên limit origins
) )
app.include_router(conservation_router) app.include_router(conservation_router)
app.include_router(chatbot_router) app.include_router(chatbot_router)
app.include_router(prompt_router) app.include_router(prompt_router)
# --- MOCK API FOR LOAD TESTING --- # --- MOCK API FOR LOAD TESTING ---
try: try:
from api.mock_api_route import router as mock_router from api.mock_api_route import router as mock_router
app.include_router(mock_router) app.include_router(mock_router)
print("✅ Mock API Router mounted at /mock") print("✅ Mock API Router mounted at /api/mock")
except ImportError: except ImportError:
print("⚠️ Mock Router not found, skipping...") print("⚠️ Mock Router not found, skipping...")
# ========================================== # ==========================================
# 🟢 ĐOẠN MOUNT STATIC HTML CỦA BRO ĐÂY 🟢 # 🟢 ĐOẠN MOUNT STATIC HTML CỦA BRO ĐÂY 🟢
# ========================================== # ==========================================
try: try:
static_dir = os.path.join(os.path.dirname(__file__), "static") static_dir = os.path.join(os.path.dirname(__file__), "static")
if not os.path.exists(static_dir): if not os.path.exists(static_dir):
os.makedirs(static_dir) os.makedirs(static_dir)
# Mount thư mục static để chạy file index.html # Mount thư mục static để chạy file index.html
app.mount("/static", StaticFiles(directory=static_dir, html=True), name="static") app.mount("/static", StaticFiles(directory=static_dir, html=True), name="static")
print(f"✅ Static files mounted at /static (Dir: {static_dir})") print(f"✅ Static files mounted at /static (Dir: {static_dir})")
except Exception as e: except Exception as e:
print(f"⚠️ Failed to mount static files: {e}") print(f"⚠️ Failed to mount static files: {e}")
from fastapi.responses import RedirectResponse from fastapi.responses import RedirectResponse
@app.get("/") @app.get("/")
async def root(): async def root():
return RedirectResponse(url="/static/index.html") return RedirectResponse(url="/static/index.html")
if __name__ == "__main__": if __name__ == "__main__":
print("=" * 60) print("=" * 60)
print("🚀 Contract AI Service Starting...") print("🚀 Contract AI Service Starting...")
print("=" * 60) print("=" * 60)
print(f"📡 REST API: http://localhost:{PORT}") print(f"📡 REST API: http://localhost:{PORT}")
print(f"📡 Test Chatbot: http://localhost:{PORT}/static/index.html") print(f"📡 Test Chatbot: http://localhost:{PORT}/static/index.html")
print(f"📚 API Docs: http://localhost:{PORT}/docs") print(f"📚 API Docs: http://localhost:{PORT}/docs")
print("=" * 60) print("=" * 60)
ENABLE_RELOAD = False ENABLE_RELOAD = False
print(f"⚠️ Hot reload: {ENABLE_RELOAD}") print(f"⚠️ Hot reload: {ENABLE_RELOAD}")
reload_dirs = ["common", "api", "agent"] reload_dirs = ["common", "api", "agent"]
if ENABLE_RELOAD: if ENABLE_RELOAD:
os.environ["PYTHONUNBUFFERED"] = "1" os.environ["PYTHONUNBUFFERED"] = "1"
uvicorn.run( uvicorn.run(
"server:app", "server:app",
host="0.0.0.0", host="0.0.0.0",
port=PORT, port=PORT,
reload=ENABLE_RELOAD, reload=ENABLE_RELOAD,
reload_dirs=reload_dirs, reload_dirs=reload_dirs,
log_level="info", log_level="info",
) )
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment