201 lines
7.8 KiB
Python
201 lines
7.8 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""OpenAI-совместимый шлюз поверх DeepAI Code.
|
|
|
|
python shim.py --port 8770 --bank bank.jsonl
|
|
|
|
GET /v1/models каталог (free + premier)
|
|
POST /v1/chat/completions chat, stream и non-stream
|
|
GET /healthz состояние пула
|
|
|
|
Ротация: аккаунт с 401/403 (кроме machine_required) /429/5xx уходит в cooldown,
|
|
запрос повторяется на следующем. Заголовки lane/machine/beacon ставятся здесь.
|
|
"""
|
|
import argparse
|
|
import json
|
|
import os
|
|
import secrets
|
|
import sys
|
|
import threading
|
|
import time
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
|
|
import requests
|
|
|
|
import dpcode as D
|
|
|
|
BANK_PATH = D.BANK
|
|
COOLDOWN = 120 # сек, сколько аккаунт не трогаем после ошибки
|
|
MAX_TRIES = 14
|
|
_lock = threading.Lock()
|
|
_state = {"cool": {}, "modelcool": {}, "used": {}, "ok": 0, "fail": 0}
|
|
|
|
|
|
def accounts():
|
|
return [r for r in D.read_bank(BANK_PATH) if r.get("cookies")]
|
|
|
|
|
|
def _bal(rec):
|
|
try:
|
|
return float((rec.get("theos") or {}).get("balance") or 0)
|
|
except Exception:
|
|
return 0.0
|
|
|
|
|
|
def ordered():
|
|
recs = accounts()
|
|
now = time.time()
|
|
fresh = [r for r in recs if _state["cool"].get(r["email"], 0) <= now]
|
|
stale = [r for r in recs if _state["cool"].get(r["email"], 0) > now]
|
|
# приоритет: у кого есть Theos (для frontier), затем менее использованные
|
|
fresh.sort(key=lambda r: (-_bal(r), _state["used"].get(r["email"], 0)))
|
|
return fresh + stale
|
|
|
|
|
|
def call_upstream(model, payload, stream):
|
|
"""Возвращает (requests.Response, rec) либо (None, last_error)."""
|
|
last = None
|
|
now = time.time()
|
|
for rec in ordered()[:MAX_TRIES]:
|
|
email = rec["email"]
|
|
if _state["modelcool"].get((email, model), 0) > now:
|
|
continue # у этого аккаунта кончились Theos на эту модель — free-модели не трогаем
|
|
machine = rec.get("machine") or D.machine_header(salt=rec.get("email"))
|
|
s = D.session_from(rec)
|
|
body = dict(payload)
|
|
body["model"] = model
|
|
body["stream"] = bool(stream)
|
|
h = dict(D.lane_headers(machine))
|
|
h.update({"Accept": "text/event-stream" if stream else "application/json",
|
|
"Content-Type": "application/json"})
|
|
try:
|
|
r = requests.post(D.API + "/deepai_code/chat/completions", json=body,
|
|
headers=h, cookies=s.cookies.get_dict(), stream=stream, timeout=300)
|
|
except Exception as e:
|
|
last = str(e)[:120]
|
|
_state["cool"][rec["email"]] = time.time() + 30
|
|
continue
|
|
with _lock:
|
|
_state["used"][rec["email"]] = _state["used"].get(rec["email"], 0) + 1
|
|
if r.status_code == 200:
|
|
_state["ok"] += 1
|
|
return r, rec
|
|
text = ""
|
|
try:
|
|
text = r.text[:200]
|
|
except Exception:
|
|
pass
|
|
last = f"{r.status_code} {text}"
|
|
# кончились Theos на frontier — это НЕ мёртвый аккаунт: free-модели продолжают работать
|
|
if "Free daily Theos" in text or "Theos are not available" in text:
|
|
with _lock:
|
|
_state["modelcool"][(email, model)] = time.time() + 6 * 3600
|
|
_state["fail"] += 1
|
|
continue
|
|
# machine_required лечится пересчётом machine-id, а не сменой аккаунта
|
|
if "machine_required" in text:
|
|
rec["machine"] = D.machine_header(salt=rec["email"] + secrets.token_hex(4))
|
|
_state["cool"][rec["email"]] = time.time() + 5
|
|
continue
|
|
if r.status_code in (401, 403, 429) or r.status_code >= 500:
|
|
_state["cool"][rec["email"]] = time.time() + COOLDOWN
|
|
_state["fail"] += 1
|
|
continue
|
|
return r, rec # 400 и прочие клиентские — отдаём как есть
|
|
return None, last
|
|
|
|
|
|
class H(BaseHTTPRequestHandler):
|
|
protocol_version = "HTTP/1.1"
|
|
|
|
def log_message(self, fmt, *args):
|
|
sys.stderr.write("%s %s\n" % (time.strftime("%H:%M:%S"), fmt % args))
|
|
|
|
def _json(self, code, obj):
|
|
data = json.dumps(obj, ensure_ascii=False).encode()
|
|
self.send_response(code)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(data)))
|
|
self.end_headers()
|
|
self.wfile.write(data)
|
|
|
|
def do_GET(self):
|
|
if self.path.startswith("/healthz"):
|
|
recs = accounts()
|
|
now = time.time()
|
|
self._json(200, {
|
|
"accounts": len(recs),
|
|
"cooling": sum(1 for r in recs if _state["cool"].get(r["email"], 0) > now),
|
|
"requests_ok": _state["ok"], "requests_fail": _state["fail"],
|
|
})
|
|
return
|
|
if self.path.startswith("/v1/models"):
|
|
data = [{"id": m, "object": "model", "owned_by": "deepai",
|
|
"permission": [], "root": m, "parent": None}
|
|
for m in D.ALL_MODELS]
|
|
self._json(200, {"object": "list", "data": data})
|
|
return
|
|
self._json(404, {"error": {"message": "not found", "type": "not_found"}})
|
|
|
|
def do_POST(self):
|
|
if not self.path.startswith("/v1/chat/completions"):
|
|
self._json(404, {"error": {"message": "not found", "type": "not_found"}})
|
|
return
|
|
n = int(self.headers.get("Content-Length") or 0)
|
|
try:
|
|
payload = json.loads(self.rfile.read(n) or b"{}")
|
|
except Exception as e:
|
|
self._json(400, {"error": {"message": f"bad json: {e}", "type": "invalid_request"}})
|
|
return
|
|
model = payload.get("model") or "glm-5.3-flash"
|
|
stream = bool(payload.get("stream"))
|
|
if model not in D.ALL_MODELS:
|
|
self._json(404, {"error": {"message": f"model '{model}' not found",
|
|
"type": "model_not_found", "code": "model_not_found"}})
|
|
return
|
|
r, meta = call_upstream(model, payload, stream)
|
|
if r is None:
|
|
self._json(503, {"error": {"message": f"all accounts failed: {meta}",
|
|
"type": "no_account", "code": "no_account"}})
|
|
return
|
|
if stream and r.status_code == 200:
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "text/event-stream")
|
|
self.send_header("Cache-Control", "no-cache")
|
|
self.send_header("Connection", "close")
|
|
self.end_headers()
|
|
try:
|
|
for chunk in r.iter_lines(decode_unicode=False):
|
|
if chunk is None:
|
|
continue
|
|
self.wfile.write(chunk + b"\n\n")
|
|
self.wfile.flush()
|
|
except Exception:
|
|
pass
|
|
return
|
|
body = r.content
|
|
self.send_response(r.status_code)
|
|
self.send_header("Content-Type", r.headers.get("Content-Type", "application/json"))
|
|
self.send_header("Content-Length", str(len(body)))
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument("--port", type=int, default=8770)
|
|
ap.add_argument("--bank", default=D.BANK)
|
|
ap.add_argument("--host", default="127.0.0.1")
|
|
a = ap.parse_args()
|
|
global BANK_PATH
|
|
BANK_PATH = a.bank
|
|
recs = accounts()
|
|
D.log(f"bank={a.bank} accounts={len(recs)}")
|
|
if not recs:
|
|
D.log("WARN: банк пуст — сначала oauth.py / wave.py")
|
|
srv = ThreadingHTTPServer((a.host, a.port), H)
|
|
D.log(f"listening http://{a.host}:{a.port}")
|
|
srv.serve_forever()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |