fraudTech commited on
Commit
ee67bad
·
1 Parent(s): e4e1dd9

refactor: Simplify gateway to login, register, me, health, chat/stream only

Browse files
Files changed (1) hide show
  1. app.py +21 -497
app.py CHANGED
@@ -1,4 +1,5 @@
1
- # app.py in GATEWAY Space
 
2
 
3
  import os
4
  from flask import Flask, request, jsonify, Response, stream_with_context
@@ -20,8 +21,7 @@ CORS(app)
20
 
21
 
22
  @app.errorhandler(Exception)
23
- def _handle_unexpected_exception(e: Exception):
24
- """Return JSON for uncaught exceptions (avoids HTML 500 responses)."""
25
  request_id = uuid.uuid4().hex[:12]
26
  try:
27
  app.logger.exception("Unhandled exception request_id=%s", request_id)
@@ -29,25 +29,24 @@ def _handle_unexpected_exception(e: Exception):
29
  pass
30
 
31
  status_code = 500
32
- public_message = "Internal Server Error"
33
  if isinstance(e, HTTPException):
34
  status_code = int(getattr(e, "code", 500) or 500)
35
- public_message = getattr(e, "description", public_message) or public_message
36
-
37
- payload: dict = {"ok": False, "error": public_message, "request_id": request_id}
38
 
 
39
  if (os.environ.get("EXPOSE_ERRORS") or "").strip() == "1":
40
  payload["type"] = type(e).__name__
41
  payload["details"] = str(e)
42
 
43
  return jsonify(payload), status_code
44
 
45
- # Strong secret key via HF Space secret
46
  app.config["JWT_SECRET_KEY"] = os.environ.get("JWT_SECRET_KEY")
47
  app.config["JWT_ACCESS_TOKEN_EXPIRES"] = timedelta(hours=24)
48
  jwt = JWTManager(app)
49
 
50
- BACKEND_BASE = "https://deepthoughtai-prolog-backend.hf.space"
51
  HF_TOKEN = os.environ.get("HF_TOKEN")
52
 
53
 
@@ -58,7 +57,7 @@ def _backend_headers() -> dict:
58
 
59
 
60
  # ============================================================
61
- # LOGIN ENDPOINT
62
  # ============================================================
63
  @app.post("/login")
64
  def login():
@@ -69,9 +68,6 @@ def login():
69
  if not username or not password:
70
  return jsonify({"ok": False, "error": "Missing credentials"}), 400
71
 
72
- if HF_TOKEN is None:
73
- return jsonify({"ok": False, "error": "HF_TOKEN not configured"}), 500
74
-
75
  try:
76
  resp = requests.post(
77
  f"{BACKEND_BASE}/auth/login",
@@ -85,33 +81,23 @@ def login():
85
  try:
86
  backend_json = resp.json()
87
  except ValueError:
88
- return jsonify({"ok": False, "error": f"Backend returned non-JSON: {resp.text[:200]}"}), 502
89
 
90
  if not resp.ok or not backend_json.get("ok"):
91
- return (
92
- jsonify({"ok": False, "error": backend_json.get("error") or "Login failed"}),
93
- resp.status_code,
94
- )
95
 
96
  access_token = create_access_token(identity=username)
97
  return jsonify({"ok": True, "token": access_token}), 200
98
 
99
 
100
  # ============================================================
101
- # REGISTER ENDPOINT (ADMIN ONLY)
102
  # ============================================================
103
  @app.post("/register")
104
  @jwt_required()
105
  def register():
106
  identity = (get_jwt_identity() or "").strip()
107
- if HF_TOKEN is None:
108
- return jsonify({"ok": False, "error": "HF_TOKEN not configured"}), 500
109
-
110
- try:
111
- data = request.get_json(force=True) or {}
112
- except Exception:
113
- return jsonify({"ok": False, "error": "Invalid JSON"}), 400
114
-
115
  username = (data.get("username") or "").strip()
116
  password = (data.get("password") or "").strip()
117
  overwrite = bool(data.get("overwrite", False))
@@ -133,33 +119,23 @@ def register():
133
  headers=_backend_headers(),
134
  timeout=20,
135
  )
 
136
  except Exception as e:
137
  return jsonify({"ok": False, "error": f"Gateway request failed: {e}"}), 502
138
 
139
- try:
140
- backend_json = resp.json()
141
- except ValueError:
142
- return jsonify({"ok": False, "error": f"Backend returned non-JSON: {resp.text[:200]}"}), 502
143
-
144
  if not resp.ok or not backend_json.get("ok"):
145
- return (
146
- jsonify({"ok": False, "error": backend_json.get("error") or "Register failed"}),
147
- resp.status_code,
148
- )
149
 
150
  return jsonify({"ok": True, "username": backend_json.get("username") or username}), 200
151
 
152
 
153
  # ============================================================
154
- # CURRENT USER INFO (JWT REQUIRED)
155
  # ============================================================
156
  @app.get("/me")
157
  @jwt_required()
158
  def me():
159
  identity = (get_jwt_identity() or "").strip()
160
- if HF_TOKEN is None:
161
- return jsonify({"ok": False, "error": "HF_TOKEN not configured"}), 500
162
-
163
  try:
164
  resp = requests.get(
165
  f"{BACKEND_BASE}/auth/me",
@@ -167,66 +143,22 @@ def me():
167
  headers=_backend_headers(),
168
  timeout=20,
169
  )
 
170
  except Exception as e:
171
  return jsonify({"ok": False, "error": f"Gateway request failed: {e}"}), 502
172
 
173
- try:
174
- backend_json = resp.json()
175
- except ValueError:
176
- return jsonify({"ok": False, "error": f"Backend returned non-JSON: {resp.text[:200]}"}), 502
177
-
178
  if not resp.ok or not backend_json.get("ok"):
179
- return (
180
- jsonify({"ok": False, "error": backend_json.get("error") or "Failed to fetch user info"}),
181
- resp.status_code,
182
- )
183
 
184
  return jsonify({"ok": True, "username": identity, "is_admin": bool(backend_json.get("is_admin"))}), 200
185
 
186
 
187
  # ============================================================
188
- # NON-STREAMING CHAT (JSON → JSON)
189
- # ============================================================
190
- @app.route("/chat", methods=["POST"])
191
- @jwt_required()
192
- def proxy_chat():
193
- if HF_TOKEN is None:
194
- return jsonify({"ok": False, "error": "HF_TOKEN not configured"}), 500
195
-
196
- try:
197
- payload = request.get_json(force=True) or {}
198
- except Exception:
199
- return jsonify({"ok": False, "error": "Invalid JSON"}), 400
200
-
201
- try:
202
- resp = requests.post(
203
- f"{BACKEND_BASE}/chat",
204
- json=payload,
205
- headers={"Authorization": f"Bearer {HF_TOKEN}"},
206
- timeout=60,
207
- )
208
- except Exception as e:
209
- return jsonify({"ok": False, "error": f"Gateway request failed: {e}"}), 502
210
-
211
- try:
212
- data = resp.json()
213
- except ValueError:
214
- return jsonify(
215
- {"ok": False, "error": f"Backend returned non-JSON: {resp.text[:200]}"}
216
- ), 502
217
-
218
- return jsonify(data), resp.status_code
219
-
220
-
221
- # ============================================================
222
- # STREAMING CHAT (TEXT STREAM → TEXT STREAM)
223
  # ============================================================
224
  @app.route("/chat/stream", methods=["POST"])
225
  @jwt_required()
226
  def proxy_chat_stream():
227
- if HF_TOKEN is None:
228
- return Response("HF_TOKEN not configured", status=500)
229
-
230
  try:
231
  payload = request.get_json(force=True) or {}
232
  except Exception:
@@ -236,18 +168,13 @@ def proxy_chat_stream():
236
  with requests.post(
237
  f"{BACKEND_BASE}/chat/stream",
238
  json=payload,
239
- headers={"Authorization": f"Bearer {HF_TOKEN}", "Accept": "text/plain"},
240
  stream=True,
241
  timeout=300,
242
  ) as r:
243
-
244
  if r.status_code != 200:
245
- # Surface backend error as a single line
246
  yield f"[Backend error {r.status_code}]"
247
  return
248
-
249
- # Use iter_content so we DON'T strip newlines.
250
- # Smaller chunks improve perceived streaming latency.
251
  for chunk in r.iter_content(chunk_size=128):
252
  if chunk:
253
  yield chunk.decode("utf-8")
@@ -261,416 +188,13 @@ def proxy_chat_stream():
261
 
262
 
263
  # ============================================================
264
- # RAW PROLOG QUERY PROXY
265
- # ============================================================
266
- @app.route("/prolog/query", methods=["POST"])
267
- @jwt_required()
268
- def proxy_prolog_query():
269
- if HF_TOKEN is None:
270
- return jsonify({"ok": False, "error": "HF_TOKEN not configured"}), 500
271
-
272
- try:
273
- payload = request.get_json(force=True) or {}
274
- except Exception:
275
- return jsonify({"ok": False, "error": "Invalid JSON"}), 400
276
-
277
- try:
278
- resp = requests.post(
279
- f"{BACKEND_BASE}/prolog/query",
280
- json=payload,
281
- headers={"Authorization": f"Bearer {HF_TOKEN}"},
282
- timeout=60,
283
- )
284
- except Exception as e:
285
- return jsonify({"ok": False, "error": f"Gateway request failed: {e}"}), 502
286
-
287
- try:
288
- data = resp.json()
289
- except ValueError:
290
- return jsonify(
291
- {"ok": False, "error": f"Backend returned non-JSON: {resp.text[:200]}"}
292
- ), 502
293
-
294
- return jsonify(data), resp.status_code
295
-
296
-
297
- # ============================================================
298
- # PROLOG PROOF TRACE PROXY
299
- # ============================================================
300
- @app.route("/prolog/prove", methods=["POST"])
301
- @jwt_required()
302
- def proxy_prolog_prove():
303
- if HF_TOKEN is None:
304
- return jsonify({"ok": False, "error": "HF_TOKEN not configured"}), 500
305
-
306
- try:
307
- payload = request.get_json(force=True) or {}
308
- except Exception:
309
- return jsonify({"ok": False, "error": "Invalid JSON"}), 400
310
-
311
- try:
312
- resp = requests.post(
313
- f"{BACKEND_BASE}/prolog/prove",
314
- json=payload,
315
- headers={"Authorization": f"Bearer {HF_TOKEN}"},
316
- timeout=60,
317
- )
318
- except Exception as e:
319
- return jsonify({"ok": False, "error": f"Gateway request failed: {e}"}), 502
320
-
321
- try:
322
- data = resp.json()
323
- except ValueError:
324
- return jsonify(
325
- {"ok": False, "error": f"Backend returned non-JSON: {resp.text[:200]}"}
326
- ), 502
327
-
328
- return jsonify(data), resp.status_code
329
-
330
-
331
- # ============================================================
332
- # PROLOG UPLOAD PROXY
333
- # ============================================================
334
- @app.route("/prolog/upload", methods=["POST"])
335
- @jwt_required()
336
- def proxy_prolog_upload():
337
- if HF_TOKEN is None:
338
- return jsonify({"ok": False, "error": "HF_TOKEN not configured"}), 500
339
-
340
- try:
341
- payload = request.get_json(force=True) or {}
342
- except Exception:
343
- return jsonify({"ok": False, "error": "Invalid JSON"}), 400
344
-
345
- try:
346
- resp = requests.post(
347
- f"{BACKEND_BASE}/prolog/upload",
348
- json=payload,
349
- headers={"Authorization": f"Bearer {HF_TOKEN}"},
350
- timeout=60,
351
- )
352
- except Exception as e:
353
- return jsonify({"ok": False, "error": f"Gateway request failed: {e}"}), 502
354
-
355
- try:
356
- data = resp.json()
357
- except ValueError:
358
- return jsonify(
359
- {"ok": False, "error": f"Backend returned non-JSON: {resp.text[:200]}"}
360
- ), 502
361
-
362
- return jsonify(data), resp.status_code
363
-
364
-
365
- # ============================================================
366
- # KB METADATA PROXY
367
- # ============================================================
368
- @app.route("/prolog/metadata", methods=["GET"])
369
- @jwt_required()
370
- def proxy_kb_metadata():
371
- if HF_TOKEN is None:
372
- return jsonify({"ok": False, "error": "HF_TOKEN not configured"}), 500
373
-
374
- try:
375
- resp = requests.get(
376
- f"{BACKEND_BASE}/prolog/metadata",
377
- headers={"Authorization": f"Bearer {HF_TOKEN}"},
378
- timeout=30,
379
- )
380
- except Exception as e:
381
- return jsonify({"ok": False, "error": f"Gateway request failed: {e}"}), 502
382
-
383
- try:
384
- data = resp.json()
385
- except ValueError:
386
- return jsonify(
387
- {"ok": False, "error": f"Backend returned non-JSON: {resp.text[:200]}"}
388
- ), 502
389
-
390
- return jsonify(data), resp.status_code
391
-
392
-
393
- # ============================================================
394
- # MATH DISCOVERY (HYBRID)
395
- # ============================================================
396
- @app.route("/math/discover", methods=["POST"])
397
- @jwt_required()
398
- def proxy_math_discover():
399
- if HF_TOKEN is None:
400
- return jsonify({"ok": False, "error": "HF_TOKEN not configured"}), 500
401
-
402
- try:
403
- payload = request.get_json(force=True) or {}
404
- except Exception:
405
- return jsonify({"ok": False, "error": "Invalid JSON"}), 400
406
-
407
- try:
408
- resp = requests.post(
409
- f"{BACKEND_BASE}/math/discover",
410
- json=payload,
411
- headers={"Authorization": f"Bearer {HF_TOKEN}"},
412
- timeout=120,
413
- )
414
- except Exception as e:
415
- return jsonify({"ok": False, "error": f"Gateway request failed: {e}"}), 502
416
-
417
- try:
418
- data = resp.json()
419
- except ValueError:
420
- return jsonify({"ok": False, "error": f"Backend returned non-JSON: {resp.text[:200]}"}), 502
421
-
422
- return jsonify(data), resp.status_code
423
-
424
-
425
- # ============================================================
426
- # INGESTION (DOCUMENTS → SESSION STAGING)
427
- # ============================================================
428
- @app.route("/ingest/arxiv", methods=["POST"])
429
- @jwt_required()
430
- def proxy_ingest_arxiv():
431
- if HF_TOKEN is None:
432
- return jsonify({"ok": False, "error": "HF_TOKEN not configured"}), 500
433
-
434
- try:
435
- payload = request.get_json(force=True) or {}
436
- except Exception:
437
- return jsonify({"ok": False, "error": "Invalid JSON"}), 400
438
-
439
- try:
440
- resp = requests.post(
441
- f"{BACKEND_BASE}/ingest/arxiv",
442
- json=payload,
443
- headers={"Authorization": f"Bearer {HF_TOKEN}"},
444
- timeout=600,
445
- )
446
- except Exception as e:
447
- return jsonify({"ok": False, "error": f"Gateway request failed: {e}"}), 502
448
-
449
- try:
450
- data = resp.json()
451
- except ValueError:
452
- return jsonify({"ok": False, "error": f"Backend returned non-JSON: {resp.text[:200]}"}), 502
453
-
454
- return jsonify(data), resp.status_code
455
-
456
-
457
- @app.route("/ingest/story", methods=["POST"])
458
- @jwt_required()
459
- def proxy_ingest_story():
460
- if HF_TOKEN is None:
461
- return jsonify({"ok": False, "error": "HF_TOKEN not configured"}), 500
462
-
463
- try:
464
- payload = request.get_json(force=True) or {}
465
- except Exception:
466
- return jsonify({"ok": False, "error": "Invalid JSON"}), 400
467
-
468
- try:
469
- resp = requests.post(
470
- f"{BACKEND_BASE}/ingest/story",
471
- json=payload,
472
- headers={"Authorization": f"Bearer {HF_TOKEN}"},
473
- timeout=300,
474
- )
475
- except Exception as e:
476
- return jsonify({"ok": False, "error": f"Gateway request failed: {e}"}), 502
477
-
478
- try:
479
- data = resp.json()
480
- except ValueError:
481
- return jsonify({"ok": False, "error": f"Backend returned non-JSON: {resp.text[:200]}"}), 502
482
-
483
- return jsonify(data), resp.status_code
484
-
485
-
486
- # ============================================================
487
- # SESSION LEMMAS (LIST/CLEAR)
488
- # ============================================================
489
- @app.route("/session/lemmas", methods=["POST"])
490
- @jwt_required()
491
- def proxy_session_lemmas():
492
- if HF_TOKEN is None:
493
- return jsonify({"ok": False, "error": "HF_TOKEN not configured"}), 500
494
-
495
- try:
496
- payload = request.get_json(force=True) or {}
497
- except Exception:
498
- return jsonify({"ok": False, "error": "Invalid JSON"}), 400
499
-
500
- try:
501
- resp = requests.post(
502
- f"{BACKEND_BASE}/session/lemmas",
503
- json=payload,
504
- headers={"Authorization": f"Bearer {HF_TOKEN}"},
505
- timeout=30,
506
- )
507
- except Exception as e:
508
- return jsonify({"ok": False, "error": f"Gateway request failed: {e}"}), 502
509
-
510
- try:
511
- data = resp.json()
512
- except ValueError:
513
- return jsonify({"ok": False, "error": f"Backend returned non-JSON: {resp.text[:200]}"}), 502
514
-
515
- return jsonify(data), resp.status_code
516
-
517
-
518
- @app.route("/session/clear", methods=["POST"])
519
- @jwt_required()
520
- def proxy_session_clear():
521
- if HF_TOKEN is None:
522
- return jsonify({"ok": False, "error": "HF_TOKEN not configured"}), 500
523
-
524
- try:
525
- payload = request.get_json(force=True) or {}
526
- except Exception:
527
- return jsonify({"ok": False, "error": "Invalid JSON"}), 400
528
-
529
- try:
530
- resp = requests.post(
531
- f"{BACKEND_BASE}/session/clear",
532
- json=payload,
533
- headers={"Authorization": f"Bearer {HF_TOKEN}"},
534
- timeout=30,
535
- )
536
- except Exception as e:
537
- return jsonify({"ok": False, "error": f"Gateway request failed: {e}"}), 502
538
-
539
- try:
540
- data = resp.json()
541
- except ValueError:
542
- return jsonify({"ok": False, "error": f"Backend returned non-JSON: {resp.text[:200]}"}), 502
543
-
544
- return jsonify(data), resp.status_code
545
-
546
-
547
- @app.route("/session/export", methods=["POST"])
548
- @jwt_required()
549
- def proxy_session_export():
550
- if HF_TOKEN is None:
551
- return jsonify({"ok": False, "error": "HF_TOKEN not configured"}), 500
552
-
553
- try:
554
- payload = request.get_json(force=True) or {}
555
- except Exception:
556
- return jsonify({"ok": False, "error": "Invalid JSON"}), 400
557
-
558
- try:
559
- resp = requests.post(
560
- f"{BACKEND_BASE}/session/export",
561
- json=payload,
562
- headers={"Authorization": f"Bearer {HF_TOKEN}"},
563
- timeout=60,
564
- )
565
- except Exception as e:
566
- return jsonify({"ok": False, "error": f"Gateway request failed: {e}"}), 502
567
-
568
- try:
569
- data = resp.json()
570
- except ValueError:
571
- return jsonify({"ok": False, "error": f"Backend returned non-JSON: {resp.text[:200]}"}), 502
572
-
573
- return jsonify(data), resp.status_code
574
-
575
-
576
- @app.route("/session/docs", methods=["POST"])
577
- @jwt_required()
578
- def proxy_session_docs():
579
- if HF_TOKEN is None:
580
- return jsonify({"ok": False, "error": "HF_TOKEN not configured"}), 500
581
-
582
- try:
583
- payload = request.get_json(force=True) or {}
584
- except Exception:
585
- return jsonify({"ok": False, "error": "Invalid JSON"}), 400
586
-
587
- try:
588
- resp = requests.post(
589
- f"{BACKEND_BASE}/session/docs",
590
- json=payload,
591
- headers={"Authorization": f"Bearer {HF_TOKEN}"},
592
- timeout=60,
593
- )
594
- except Exception as e:
595
- return jsonify({"ok": False, "error": f"Gateway request failed: {e}"}), 502
596
-
597
- try:
598
- data = resp.json()
599
- except ValueError:
600
- return jsonify({"ok": False, "error": f"Backend returned non-JSON: {resp.text[:200]}"}), 502
601
-
602
- return jsonify(data), resp.status_code
603
-
604
-
605
- @app.route("/session/rollback", methods=["POST"])
606
- @jwt_required()
607
- def proxy_session_rollback():
608
- if HF_TOKEN is None:
609
- return jsonify({"ok": False, "error": "HF_TOKEN not configured"}), 500
610
-
611
- try:
612
- payload = request.get_json(force=True) or {}
613
- except Exception:
614
- return jsonify({"ok": False, "error": "Invalid JSON"}), 400
615
-
616
- try:
617
- resp = requests.post(
618
- f"{BACKEND_BASE}/session/rollback",
619
- json=payload,
620
- headers={"Authorization": f"Bearer {HF_TOKEN}"},
621
- timeout=60,
622
- )
623
- except Exception as e:
624
- return jsonify({"ok": False, "error": f"Gateway request failed: {e}"}), 502
625
-
626
- try:
627
- data = resp.json()
628
- except ValueError:
629
- return jsonify({"ok": False, "error": f"Backend returned non-JSON: {resp.text[:200]}"}), 502
630
-
631
- return jsonify(data), resp.status_code
632
-
633
-
634
- @app.route("/session/promote", methods=["POST"])
635
- @jwt_required()
636
- def proxy_session_promote():
637
- if HF_TOKEN is None:
638
- return jsonify({"ok": False, "error": "HF_TOKEN not configured"}), 500
639
-
640
- try:
641
- payload = request.get_json(force=True) or {}
642
- except Exception:
643
- return jsonify({"ok": False, "error": "Invalid JSON"}), 400
644
-
645
- try:
646
- resp = requests.post(
647
- f"{BACKEND_BASE}/session/promote",
648
- json=payload,
649
- headers={"Authorization": f"Bearer {HF_TOKEN}"},
650
- timeout=300,
651
- )
652
- except Exception as e:
653
- return jsonify({"ok": False, "error": f"Gateway request failed: {e}"}), 502
654
-
655
- try:
656
- data = resp.json()
657
- except ValueError:
658
- return jsonify({"ok": False, "error": f"Backend returned non-JSON: {resp.text[:200]}"}), 502
659
-
660
- return jsonify(data), resp.status_code
661
-
662
-
663
- # ============================================================
664
- # HEALTH CHECK
665
  # ============================================================
666
  @app.get("/")
667
  def health():
668
  return "Gateway OK", 200
669
 
670
 
671
- # ============================================================
672
- # MAIN
673
- # ============================================================
674
  if __name__ == "__main__":
675
  port = int(os.environ.get("PORT", 7860))
676
  app.run(host="0.0.0.0", port=port)
 
1
+ # app.py - Prolog AI Gateway
2
+ # JWT authentication + proxy to backend for chat/stream
3
 
4
  import os
5
  from flask import Flask, request, jsonify, Response, stream_with_context
 
21
 
22
 
23
  @app.errorhandler(Exception)
24
+ def _handle_exception(e: Exception):
 
25
  request_id = uuid.uuid4().hex[:12]
26
  try:
27
  app.logger.exception("Unhandled exception request_id=%s", request_id)
 
29
  pass
30
 
31
  status_code = 500
32
+ message = "Internal Server Error"
33
  if isinstance(e, HTTPException):
34
  status_code = int(getattr(e, "code", 500) or 500)
35
+ message = getattr(e, "description", message) or message
 
 
36
 
37
+ payload: dict = {"ok": False, "error": message, "request_id": request_id}
38
  if (os.environ.get("EXPOSE_ERRORS") or "").strip() == "1":
39
  payload["type"] = type(e).__name__
40
  payload["details"] = str(e)
41
 
42
  return jsonify(payload), status_code
43
 
44
+
45
  app.config["JWT_SECRET_KEY"] = os.environ.get("JWT_SECRET_KEY")
46
  app.config["JWT_ACCESS_TOKEN_EXPIRES"] = timedelta(hours=24)
47
  jwt = JWTManager(app)
48
 
49
+ BACKEND_BASE = os.environ.get("BACKEND_URL", "https://deepthoughtai-prolog-backend.hf.space")
50
  HF_TOKEN = os.environ.get("HF_TOKEN")
51
 
52
 
 
57
 
58
 
59
  # ============================================================
60
+ # LOGIN
61
  # ============================================================
62
  @app.post("/login")
63
  def login():
 
68
  if not username or not password:
69
  return jsonify({"ok": False, "error": "Missing credentials"}), 400
70
 
 
 
 
71
  try:
72
  resp = requests.post(
73
  f"{BACKEND_BASE}/auth/login",
 
81
  try:
82
  backend_json = resp.json()
83
  except ValueError:
84
+ return jsonify({"ok": False, "error": "Backend returned non-JSON"}), 502
85
 
86
  if not resp.ok or not backend_json.get("ok"):
87
+ return jsonify({"ok": False, "error": backend_json.get("error") or "Login failed"}), resp.status_code
 
 
 
88
 
89
  access_token = create_access_token(identity=username)
90
  return jsonify({"ok": True, "token": access_token}), 200
91
 
92
 
93
  # ============================================================
94
+ # REGISTER (ADMIN ONLY)
95
  # ============================================================
96
  @app.post("/register")
97
  @jwt_required()
98
  def register():
99
  identity = (get_jwt_identity() or "").strip()
100
+ data = request.get_json(force=True) or {}
 
 
 
 
 
 
 
101
  username = (data.get("username") or "").strip()
102
  password = (data.get("password") or "").strip()
103
  overwrite = bool(data.get("overwrite", False))
 
119
  headers=_backend_headers(),
120
  timeout=20,
121
  )
122
+ backend_json = resp.json()
123
  except Exception as e:
124
  return jsonify({"ok": False, "error": f"Gateway request failed: {e}"}), 502
125
 
 
 
 
 
 
126
  if not resp.ok or not backend_json.get("ok"):
127
+ return jsonify({"ok": False, "error": backend_json.get("error") or "Register failed"}), resp.status_code
 
 
 
128
 
129
  return jsonify({"ok": True, "username": backend_json.get("username") or username}), 200
130
 
131
 
132
  # ============================================================
133
+ # CURRENT USER
134
  # ============================================================
135
  @app.get("/me")
136
  @jwt_required()
137
  def me():
138
  identity = (get_jwt_identity() or "").strip()
 
 
 
139
  try:
140
  resp = requests.get(
141
  f"{BACKEND_BASE}/auth/me",
 
143
  headers=_backend_headers(),
144
  timeout=20,
145
  )
146
+ backend_json = resp.json()
147
  except Exception as e:
148
  return jsonify({"ok": False, "error": f"Gateway request failed: {e}"}), 502
149
 
 
 
 
 
 
150
  if not resp.ok or not backend_json.get("ok"):
151
+ return jsonify({"ok": False, "error": backend_json.get("error") or "Failed"}), resp.status_code
 
 
 
152
 
153
  return jsonify({"ok": True, "username": identity, "is_admin": bool(backend_json.get("is_admin"))}), 200
154
 
155
 
156
  # ============================================================
157
+ # STREAMING CHAT (core endpoint)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
  # ============================================================
159
  @app.route("/chat/stream", methods=["POST"])
160
  @jwt_required()
161
  def proxy_chat_stream():
 
 
 
162
  try:
163
  payload = request.get_json(force=True) or {}
164
  except Exception:
 
168
  with requests.post(
169
  f"{BACKEND_BASE}/chat/stream",
170
  json=payload,
171
+ headers={**_backend_headers(), "Accept": "text/plain"},
172
  stream=True,
173
  timeout=300,
174
  ) as r:
 
175
  if r.status_code != 200:
 
176
  yield f"[Backend error {r.status_code}]"
177
  return
 
 
 
178
  for chunk in r.iter_content(chunk_size=128):
179
  if chunk:
180
  yield chunk.decode("utf-8")
 
188
 
189
 
190
  # ============================================================
191
+ # HEALTH
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
  # ============================================================
193
  @app.get("/")
194
  def health():
195
  return "Gateway OK", 200
196
 
197
 
 
 
 
198
  if __name__ == "__main__":
199
  port = int(os.environ.get("PORT", 7860))
200
  app.run(host="0.0.0.0", port=port)