Study-Ocean-Official's picture
Sync from GitHub via hub-sync
adb1559 verified
Raw History Blame Contribute Delete
2.09 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, stream_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("rag frontend.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": []
}
@app.post("/api/stream")
def stream(query: Query):
from fastapi.responses import StreamingResponse
try:
return StreamingResponse(
stream_question(chain, query.question),
media_type="text/plain"
)
except Exception as e:
import traceback
traceback.print_exc()
return {"error": str(e)}
if __name__ == "__main__":
# Run the API on port 8000
uvicorn.run(app, host="0.0.0.0", port=8000)