prolog_gateway / app.py
fraudTech's picture
refactor: Simplify gateway to login, register, me, health, chat/stream only
ee67bad
Raw History Blame Contribute Delete
6.44 kB
# app.py - Prolog AI Gateway
# JWT authentication + proxy to backend for chat/stream
import os
from flask import Flask, request, jsonify, Response, stream_with_context
from flask_cors import CORS
import requests
from datetime import timedelta
from werkzeug.exceptions import HTTPException
import uuid
from flask_jwt_extended import (
JWTManager,
create_access_token,
jwt_required,
get_jwt_identity,
)
app = Flask(__name__)
CORS(app)
@app.errorhandler(Exception)
def _handle_exception(e: Exception):
request_id = uuid.uuid4().hex[:12]
try:
app.logger.exception("Unhandled exception request_id=%s", request_id)
except Exception:
pass
status_code = 500
message = "Internal Server Error"
if isinstance(e, HTTPException):
status_code = int(getattr(e, "code", 500) or 500)
message = getattr(e, "description", message) or message
payload: dict = {"ok": False, "error": message, "request_id": request_id}
if (os.environ.get("EXPOSE_ERRORS") or "").strip() == "1":
payload["type"] = type(e).__name__
payload["details"] = str(e)
return jsonify(payload), status_code
app.config["JWT_SECRET_KEY"] = os.environ.get("JWT_SECRET_KEY")
app.config["JWT_ACCESS_TOKEN_EXPIRES"] = timedelta(hours=24)
jwt = JWTManager(app)
BACKEND_BASE = os.environ.get("BACKEND_URL", "https://deepthoughtai-prolog-backend.hf.space")
HF_TOKEN = os.environ.get("HF_TOKEN")
def _backend_headers() -> dict:
if HF_TOKEN is None:
return {}
return {"Authorization": f"Bearer {HF_TOKEN}"}
# ============================================================
# LOGIN
# ============================================================
@app.post("/login")
def login():
data = request.get_json(force=True) or {}
username = (data.get("username") or "").strip()
password = (data.get("password") or "").strip()
if not username or not password:
return jsonify({"ok": False, "error": "Missing credentials"}), 400
try:
resp = requests.post(
f"{BACKEND_BASE}/auth/login",
json={"username": username, "password": password},
headers=_backend_headers(),
timeout=20,
)
except Exception as e:
return jsonify({"ok": False, "error": f"Gateway request failed: {e}"}), 502
try:
backend_json = resp.json()
except ValueError:
return jsonify({"ok": False, "error": "Backend returned non-JSON"}), 502
if not resp.ok or not backend_json.get("ok"):
return jsonify({"ok": False, "error": backend_json.get("error") or "Login failed"}), resp.status_code
access_token = create_access_token(identity=username)
return jsonify({"ok": True, "token": access_token}), 200
# ============================================================
# REGISTER (ADMIN ONLY)
# ============================================================
@app.post("/register")
@jwt_required()
def register():
identity = (get_jwt_identity() or "").strip()
data = request.get_json(force=True) or {}
username = (data.get("username") or "").strip()
password = (data.get("password") or "").strip()
overwrite = bool(data.get("overwrite", False))
make_admin = bool(data.get("is_admin", False))
if not username or not password:
return jsonify({"ok": False, "error": "Missing credentials"}), 400
try:
resp = requests.post(
f"{BACKEND_BASE}/auth/register",
json={
"admin_username": identity,
"username": username,
"password": password,
"overwrite": overwrite,
"is_admin": make_admin,
},
headers=_backend_headers(),
timeout=20,
)
backend_json = resp.json()
except Exception as e:
return jsonify({"ok": False, "error": f"Gateway request failed: {e}"}), 502
if not resp.ok or not backend_json.get("ok"):
return jsonify({"ok": False, "error": backend_json.get("error") or "Register failed"}), resp.status_code
return jsonify({"ok": True, "username": backend_json.get("username") or username}), 200
# ============================================================
# CURRENT USER
# ============================================================
@app.get("/me")
@jwt_required()
def me():
identity = (get_jwt_identity() or "").strip()
try:
resp = requests.get(
f"{BACKEND_BASE}/auth/me",
params={"username": identity},
headers=_backend_headers(),
timeout=20,
)
backend_json = resp.json()
except Exception as e:
return jsonify({"ok": False, "error": f"Gateway request failed: {e}"}), 502
if not resp.ok or not backend_json.get("ok"):
return jsonify({"ok": False, "error": backend_json.get("error") or "Failed"}), resp.status_code
return jsonify({"ok": True, "username": identity, "is_admin": bool(backend_json.get("is_admin"))}), 200
# ============================================================
# STREAMING CHAT (core endpoint)
# ============================================================
@app.route("/chat/stream", methods=["POST"])
@jwt_required()
def proxy_chat_stream():
try:
payload = request.get_json(force=True) or {}
except Exception:
return Response("Invalid JSON", status=400)
def generate():
with requests.post(
f"{BACKEND_BASE}/chat/stream",
json=payload,
headers={**_backend_headers(), "Accept": "text/plain"},
stream=True,
timeout=300,
) as r:
if r.status_code != 200:
yield f"[Backend error {r.status_code}]"
return
for chunk in r.iter_content(chunk_size=128):
if chunk:
yield chunk.decode("utf-8")
headers = {
"Cache-Control": "no-cache",
"X-Accel-Buffering": "no",
"Connection": "keep-alive",
}
return Response(stream_with_context(generate()), mimetype="text/plain", headers=headers)
# ============================================================
# HEALTH
# ============================================================
@app.get("/")
def health():
return "Gateway OK", 200
if __name__ == "__main__":
port = int(os.environ.get("PORT", 7860))
app.run(host="0.0.0.0", port=port)