Spaces:
Runtime error
Runtime error
Download api.py from StudyOcean/Study-Ocean-AI_Mentor: direct link, hf CLI and curl.
- Browser
- Download file 1.71 kB
-
https://huggingface.co/spaces/StudyOcean/Study-Ocean-AI_Mentor/resolve/main/api.py
- Command line
-
hf download hf://spaces/StudyOcean/Study-Ocean-AI_Mentor/api.py
-
curl -L -o api.py https://huggingface.co/spaces/StudyOcean/Study-Ocean-AI_Mentor/resolve/main/api.py
1.71 kB
| 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=["*"], | |
| ) | |
| def serve_frontend(): | |
| return FileResponse("frontend_demo.html") | |
| 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 | |
| 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) | |