Files

227 lines
8.2 KiB
Python

"""Coarena rotator for prod (2.27.98.196): OpenAI-compatible front, rotates keys, cools daily caps."""
import http.server, json, os, socketserver, threading, time, urllib.error, urllib.request
UP = "https://coarena.ai/api/v1"
KEYSF = os.environ.get("COA_KEYS", "/opt/coa-shim/coa_keys.txt")
PORT = int(os.environ.get("COA_PORT", "48960"))
LOCK = threading.Lock()
STATE = {}
MODELS_OFF = {"gpt-6-1-sol", "gpt-6-1-terra", "gpt-6-astra", "gpt-6-luna",
"gpt-6.1-sol", "gpt-6.1-terra", "gpt-6-astra", "gpt-6-luna",
"gemini-4-argon", "gemini-4-carbon", "mimo-v2.6-pro", "mimo-v2-6-pro",
"claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5",
"claude-fable-5", "claude-fable-5-1", "claude-fable-5-2"}
ALIAS = {"glm-5.3": "glm-5-3-flash", "kimi-k3": "kimi-k3-1-pro", "mimo-v2.6-pro": "mimo-v2-6-pro",
"kimi-k3.1-pro": "kimi-k3-1-pro", "minimax-m3.1-flash": "minimax-m3-1-flash"}
LAST_GOOD = {}
FAIL_UNTIL = {}
LG_FILE = os.environ.get("COA_LG", "/opt/coa-shim/last_good.json")
def load_lg():
global LAST_GOOD
try:
LAST_GOOD = json.load(open(LG_FILE))
except Exception:
LAST_GOOD = {}
def save_lg():
try:
json.dump(LAST_GOOD, open(LG_FILE, "w"))
except Exception:
pass
def load_keys():
ks = []
for line in open(KEYSF, encoding="utf8"):
line = line.strip()
if "|" in line:
name, k = line.split("|", 1)
if k.startswith("coa_"):
ks.append((name, k))
return ks
KEYS = load_keys()
IDX = {"i": 0}
print("keys", len(KEYS), flush=True)
def pick_key():
now = time.time()
with LOCK:
n = len(KEYS)
for off in range(n):
i = (IDX["i"] + off) % n
name, k = KEYS[i]
if STATE.get(k, {}).get("cool", 0) < now:
IDX["i"] = (i + 1) % n
return name, k
return min(KEYS, key=lambda p: STATE.get(p[1], {}).get("cool", 0))
def cool(k, seconds=3600):
with LOCK:
STATE.setdefault(k, {})["cool"] = time.time() + seconds
class H(http.server.BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *a):
pass
def send_json(self, code, body):
if isinstance(body, str):
body = body.encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
try:
self.wfile.write(body)
except Exception:
pass
def do_OPTIONS(self):
self.send_json(204, b"")
def _pick(self, model):
now = time.time()
lg = LAST_GOOD.get(model)
if lg:
with LOCK:
for name, k in KEYS:
if k == lg and STATE.get(k, {}).get("cool", 0) < now:
return name, k
return pick_key()
def _proxy(self, method):
ln = int(self.headers.get("Content-Length") or 0)
body = self.rfile.read(ln) if ln else None
model = ""
if body and method == "POST":
try:
model = json.loads(body).get("model") or ""
except Exception:
model = ""
if model in MODELS_OFF:
self.send_json(400, json.dumps({"error": {
"message": "%s is turned off on the Coarena Model API right now." % model,
"type": "invalid_request_error", "param": "model", "code": "model_off"}}))
return
path = self.path[3:] if self.path.startswith("/v1") else self.path
stream = False
if body:
try:
stream = bool(json.loads(body).get("stream"))
except Exception:
pass
up_model = ALIAS.get(model, model).replace(".", "-") if model else ""
if model and FAIL_UNTIL.get(model, 0) > time.time():
self.send_json(429, json.dumps({"error": {
"message": "%s: coarena quota exhausted for now, retry later" % model,
"type": "rate_limit_error", "code": "pool_capped"}}))
return
up_body = None
if body and up_model != model:
up_body = json.dumps({**json.loads(body), "model": up_model}).encode()
elif body:
up_body = body
last = (500, b'{"error":{"message":"no keys"}}')
tries = 0
while tries < 20:
tries += 1
name, k = self._pick(model)
data_body = up_body if up_body is not None else body
req = urllib.request.Request(UP + path, data=data_body, method=method,
headers={"Authorization": "Bearer " + k,
"Content-Type": "application/json",
"User-Agent": "Mozilla/5.0"})
try:
r = urllib.request.urlopen(req, timeout=120)
if model:
with LOCK:
LAST_GOOD[model] = k
save_lg()
if stream:
self.send_response(r.status)
self.send_header("Content-Type", r.headers.get("Content-Type", "text/event-stream"))
self.send_header("Cache-Control", "no-cache")
self.end_headers()
while True:
chunk = r.read1(4096) if hasattr(r, "read1") else r.read(4096)
if not chunk:
break
self.wfile.write(chunk)
self.wfile.flush()
return
d = r.read()
self.send_json(r.status, d)
return
except urllib.error.HTTPError as e:
code = e.code
data = e.read()
if code == 429:
import calendar
txt = data[:200].decode("utf-8", "replace").lower()
now_t = time.time()
gm = time.gmtime(now_t)
if "daily free limit" in txt or "quota" in txt:
midnight = calendar.timegm((gm.tm_year, gm.tm_mon, gm.tm_mday + 1, 0, 0, 0))
cool(k, max(60, midnight - now_t + 60))
else:
cool(k, 120)
last = (code, data)
continue
if code in (401, 403):
cool(k, 21600)
last = (code, data)
continue
if code == 400 and (b"usage limits" in data or b"regain access" in data):
import re
m2 = re.search(rb"regain access on (\d{4}-\d{2}-\d{2})", data)
if m2:
import calendar
y, mo, d = map(int, m2.group(1).decode().split("-"))
cool(k, max(3600, calendar.timegm((y, mo, d, 0, 0, 0)) - time.time() + 60))
else:
cool(k, 86400)
last = (429, data)
continue
if code == 400 and b"does not exist" in data[:200]:
cool(k, 600)
last = (code, data)
continue
self.send_json(code, data)
return
except Exception as e:
last = (502, json.dumps({"error": {"message": type(e).__name__}}).encode())
if model:
FAIL_UNTIL[model] = time.time() + 180
self.send_json(last[0], last[1])
def do_GET(self):
if self.path.rstrip("/") in ("/health", "/healthz"):
now = time.time()
alive = sum(1 for _, k in KEYS if STATE.get(k, {}).get("cool", 0) < now)
self.send_json(200, json.dumps({"ok": True, "keys": len(KEYS), "alive": alive}))
return
self._proxy("GET")
def do_POST(self):
self._proxy("POST")
class T(socketserver.ThreadingMixIn, http.server.HTTPServer):
daemon_threads = True
allow_reuse_address = True
if __name__ == "__main__":
load_lg()
print("listen", PORT, "last_good", len(LAST_GOOD), flush=True)
T(("127.0.0.1", PORT), H).serve_forever()