-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackend.py
64 lines (53 loc) · 1.96 KB
/
backend.py
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
from fastapi import FastAPI, HTTPException
import os
import uvicorn
from pymongo import MongoClient
from pymongo.server_api import ServerApi
from dotenv import load_dotenv
# ✅ Load environment variables
load_dotenv()
# ✅ MongoDB Connection
MONGO_URI = os.getenv("MONGO_URI")
DB_NAME = os.getenv("MONGO_DB_NAME", "lucydetect") # Default database name
# ✅ Ensure MongoDB URI is set
if not MONGO_URI:
raise ValueError("❌ ERROR: No MongoDB URI found. Set MONGO_URI in Render Secrets.")
try:
client = MongoClient(MONGO_URI, server_api=ServerApi('1'))
db = client[DB_NAME]
collection = db["responses"]
client.admin.command('ping') # ✅ Check if MongoDB is reachable
print("✅ Connected to MongoDB!")
except Exception as e:
print(f"❌ MongoDB Connection Failed: {e}")
collection = None
# ✅ Initialize FastAPI app
app = FastAPI()
@app.get("/")
def home():
"""Health check endpoint."""
return {"message": "Backend is running!"}
@app.post("/save")
def save_data(data: dict):
"""Save LLM response to MongoDB."""
if not collection:
raise HTTPException(status_code=500, detail="❌ Database connection failed.")
try:
collection.insert_one(data)
return {"status": "✅ Saved successfully"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"❌ Error saving data: {str(e)}")
@app.get("/recent")
def get_recent_responses(limit: int = 5):
"""Fetch recent LLM responses from MongoDB."""
if not collection:
raise HTTPException(status_code=500, detail="❌ Database connection failed.")
try:
recent_responses = list(collection.find({}, {"_id": 0}).sort("timestamp", -1).limit(limit))
return recent_responses
except Exception as e:
raise HTTPException(status_code=500, detail=f"❌ Error fetching data: {str(e)}")
# ✅ Run test if executed directly
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)