File size: 1,712 Bytes
030f984
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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)