AI_YLF / src /main.py
Youssefebrahim1's picture
upload src
5dc8851 verified
Raw
History Blame Contribute Delete
2.02 kB
# main.py
import asyncio
from pydantic import BaseModel
from fastapi import FastAPI
from src.chatbot.engine import call_llm
from fastapi.middleware.cors import CORSMiddleware
import logging
import uuid
# Logging setup
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("ylf-api")
app = FastAPI(title="YLF AI Platform")
# Allows the frontend to talk to backend
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
def home():
return {"message": "API is running 🚀"}
class ChatRequest(BaseModel):
message: str
mode: str = "socratic"
# Optional session_id; if not provided, a new one will be generated
session_id: str = None
@app.post("/chat")
async def chat_endpoint(request: ChatRequest):
# Optimize session_id generation to be compatible with Engine logs
session_id = request.session_id or f"user_{uuid.uuid4().hex[:8]}"
try:
# Execute the enhanced Engine (contains Fallback and Smart Routing logic)
# Using to_thread because the Engine performs blocking HTTP requests
answer = await asyncio.to_thread(
call_llm,
user_query=request.message,
mode=request.mode,
session_id=session_id
)
# Critical check: Verify if the Engine returned a total failure message
if "All models failed" in answer:
logger.error(f"Critical Engine Failure: {answer}")
return {
"answer": "Sorry, our AI engines are currently under heavy load. Please try again in a minute.",
"session_id": session_id,
"status": "temporary_failure"
}
return {"answer": answer, "session_id": session_id, "status": "success"}
except Exception as e:
logger.error(f"API Logic Error: {str(e)}")
return {"error": "Internal API Error", "session_id": session_id}