import os # memory saving trick for Render 512MB limit! os.environ["OMP_NUM_THREADS"] = "1" os.environ["MKL_NUM_THREADS"] = "1" os.environ["OPENBLAS_NUM_THREADS"] = "1" os.environ["VECLIB_MAXIMUM_THREADS"] = "1" os.environ["NUMEXPR_NUM_THREADS"] = "1" from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse from pydantic import BaseModel from rag_chain import get_chain, ask_question import uvicorn app = FastAPI(title="Study Ocean RAG API") # Allow requests from your frontend (CORS) app.add_middleware( CORSMiddleware, allow_origins=["*"], # In production, replace with your frontend URL allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @app.get("/") def serve_frontend(): return FileResponse("frontend_demo.html") @app.get("/logo.png") def serve_logo(): if os.path.exists("logo.png"): return FileResponse("logo.png") return {"error": "Logo not found"} print("🔄 Initializing Study Ocean AI Mentor...") chain = get_chain() print("✅ API Ready to answer student doubts!") class Query(BaseModel): question: str @app.post("/api/ask") def ask(query: Query): try: # Pass the question to your LangChain RAG result = ask_question(chain, query.question) return { "answer": result["answer"], "sources": result["sources"] } except Exception as e: import traceback traceback.print_exc() return { "answer": f"Backend Error: {str(e)}", "sources": [] } if __name__ == "__main__": # Run the API on port 8000 uvicorn.run(app, host="0.0.0.0", port=8000)