Files
haze-toolkit/haze_proxy.py
T

187 lines
7.8 KiB
Python

#!/usr/bin/env python3
# Haze Gateway Proxy — OpenAI-compatible proxy over v1.usehaze.ai/ai
# Usage: python haze_proxy.py [port] (default 16450)
# Pool: tokens.json [{"token":"***","email":"...","ok":true,"fails":0}, ...]
# Endpoints: GET /v1/models, POST /v1/chat/completions (stream supported), GET /health, GET /pool
import json, os, sys, time, threading, subprocess, random
PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 16450
BASE = "https://v1.usehaze.ai/ai/v1"
DIR = os.path.dirname(os.path.abspath(__file__))
POOL_F = os.path.join(DIR, "tokens.json")
LOCK = threading.Lock()
def load_pool():
with LOCK:
if not os.path.exists(POOL_F):
# seed from token.txt if present
tok = ""
tf = os.path.join(DIR, "token.txt")
if os.path.exists(tf):
raw = open(tf).read().strip()
try:
tok = json.loads(raw).get("accessToken", raw)
except Exception:
tok = raw
pool = [{"token": tok, "email": "seed", "ok": True, "fails": 0}] if tok else []
save_pool(pool)
return pool
return json.load(open(POOL_F, encoding="utf-8"))
def save_pool(pool):
tmp = POOL_F + ".tmp"
json.dump(pool, open(tmp, "w", encoding="utf-8"), indent=1)
os.replace(tmp, POOL_F)
POOL = load_pool()
RR = [0]
def next_token():
"""round-robin over healthy tokens"""
with LOCK:
healthy = [p for p in POOL if p.get("ok", True)]
if not healthy:
healthy = POOL # last resort: try everything
if not healthy:
return None
RR[0] = (RR[0] + 1) % len(healthy)
return healthy[RR[0]]
def mark(entry, ok):
with LOCK:
for p in POOL:
if p["token"] == entry["token"]:
if ok:
p["ok"] = True; p["fails"] = 0
else:
p["fails"] = p.get("fails", 0) + 1
if p["fails"] >= 5:
p["ok"] = False
break
save_pool(POOL)
def curl_json(url, headers, data=None, timeout=120, stream=False):
cmd = ["curl", "-s", "--max-time", str(timeout), url]
for k, v in headers.items():
cmd += ["-H", f"{k}: {v}"]
if data is not None:
cmd += ["-d", json.dumps(data)]
if not stream:
cmd += ["-w", "\n@@CODE:%{http_code}"]
r = subprocess.run(cmd, capture_output=True, text=True)
out = r.stdout
code = 0
if "@@CODE:" in out:
body, _, c = out.rpartition("@@CODE:")
try: code = int(c.strip())
except Exception: code = 0
return code, body
return 0, out
else:
cmd += ["-N"]
return subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
class Handler(__import__("http.server", fromlist=["BaseHTTPRequestHandler"]).BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def _send(self, code, body, ctype="application/json"):
b = body if isinstance(body, bytes) else body.encode("utf-8")
self.send_response(code)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(b)))
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
self.wfile.write(b)
def do_OPTIONS(self):
self.send_response(204)
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Headers", "*")
self.send_header("Access-Control-Allow-Methods", "*")
self.end_headers()
def do_GET(self):
if self.path == "/health":
healthy = sum(1 for p in POOL if p.get("ok", True))
self._send(200, json.dumps({"status": "up", "pool": len(POOL), "healthy": healthy}))
elif self.path == "/pool":
with LOCK:
self._send(200, json.dumps([{"email": p.get("email"), "ok": p.get("ok", True), "fails": p.get("fails", 0)} for p in POOL]))
elif self.path in ("/v1/models", "/models"):
e = next_token()
if not e:
return self._send(503, json.dumps({"error": "empty pool"}))
code, body = curl_json(BASE + "/models", {"Authorization": "Bearer " + e["token"]})
mark(e, code == 200)
self._send(code or 502, body)
else:
self._send(404, json.dumps({"error": "not found"}))
def do_POST(self):
if self.path not in ("/v1/chat/completions", "/chat/completions"):
return self._send(404, json.dumps({"error": "not found"}))
n = int(self.headers.get("Content-Length", 0))
try:
data = json.loads(self.rfile.read(n) or b"{}")
except Exception:
return self._send(400, json.dumps({"error": "bad json"}))
stream = bool(data.get("stream"))
model = data.get("model", "")
# retry across pool + backoff on 429/502/503
attempts = min(len(POOL) * 2, 8) or 4
for i in range(attempts):
e = next_token()
if not e:
return self._send(503, json.dumps({"error": "empty pool"}))
hdrs = {"Authorization": "Bea"+"rer " + e["token"], "Content-Type": "application/json",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/154.0.0.0 Safari/537.36"}
if stream:
proc = curl_json(BASE + "/chat/completions", hdrs, data, timeout=180, stream=True)
# peek first line to detect error
first = proc.stdout.readline()
if not first.startswith(b"data:") and not first.startswith(b":"):
# upstream plain-text/HTML error (e.g. "error code: 502")
proc.kill()
if i < attempts - 1:
time.sleep(2 + random.random() * 6)
continue
return self._send(502, json.dumps({"error": "upstream stream failed", "detail": first.decode('utf-8','ignore')[:200]}))
if first.startswith(b"data: {") and b'"error"' in first:
proc.kill()
time.sleep(3 + random.random() * 4)
continue
mark(e, True)
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Cache-Control", "no-cache")
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
try:
self.wfile.write(first)
for line in proc.stdout:
self.wfile.write(line)
self.wfile.flush()
except Exception:
proc.kill()
return
else:
code, body = curl_json(BASE + "/chat/completions", hdrs, data, timeout=180)
if code == 200:
mark(e, True)
return self._send(200, body)
if code in (401, 403):
mark(e, False) # dead token
# 429/5xx = upstream problem, token stays healthy
if code in (429, 502, 503) and i < attempts - 1:
time.sleep(2 + random.random() * 5)
continue
return self._send(code or 502, body)
self._send(502, json.dumps({"error": "all attempts failed", "model": model}))
if __name__ == "__main__":
from http.server import ThreadingHTTPServer
srv = ThreadingHTTPServer(("127.0.0.1", PORT), Handler)
print(f"haze-proxy on :{PORT}, pool={len(POOL)}", flush=True)
srv.serve_forever()