371 lines
13 KiB
Python
371 lines
13 KiB
Python
"""QwenWork -> OpenAI compatible shim (stdlib only).
|
|
|
|
Endpoints:
|
|
POST /v1/chat/completions (JSON or SSE stream)
|
|
GET /v1/models
|
|
GET /healthz
|
|
|
|
Protocol (reverse engineered):
|
|
POST {base}/api/chat-sessions {agent_id, mode, initial_prompt:{text}, extra_data:{user_language}, channel:"qwenwork_web"}
|
|
GET {base}/api/chat-sessions/{sid}/events?after=N
|
|
-> items[]: type=method method=session sub_type=prompt|agent_thought_chunk|agent_message_chunk
|
|
type=result sub_type=prompt_response
|
|
DELETE {base}/api/chat-sessions/{sid} close (best effort, does not lift the credit hold)
|
|
|
|
Env:
|
|
QW_POOL path to accounts jsonl {email, jwt} (default ./accounts.jsonl)
|
|
QW_PORT listen port (default 48981)
|
|
QW_BASE upstream (default https://qwenwork.ai)
|
|
QW_AGENT agent id (default: the web agent used by /app)
|
|
QW_POLL per-turn poll budget in seconds (default 150)
|
|
"""
|
|
import json
|
|
import os
|
|
import sys
|
|
import time
|
|
import threading
|
|
import uuid
|
|
import urllib.request
|
|
import urllib.error
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
|
|
BASE = os.environ.get("QW_BASE", "https://qwenwork.ai")
|
|
AGENT_ID = os.environ.get("QW_AGENT", "7270e986-63e5-3c79-aeca-ffbd92bdef83")
|
|
PORT = int(os.environ.get("QW_PORT", "48981"))
|
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
POOL_PATH = os.environ.get("QW_POOL", os.path.join(HERE, "accounts.jsonl"))
|
|
POLL_MAX = float(os.environ.get("QW_POLL", "150"))
|
|
COOLDOWN = int(os.environ.get("QW_COOL", "900")) # seconds an account is skipped after 402
|
|
|
|
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
|
"(KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36")
|
|
|
|
# iishko model name -> qwenwork chat mode
|
|
MODES = {
|
|
"flash": "flash",
|
|
"standard": "flash",
|
|
"pro": "advanced",
|
|
"advanced": "advanced",
|
|
"flagship": "pro",
|
|
"qwen4-max": "qwen4-max",
|
|
"qwen3.8-max": "qwen3.8-max",
|
|
"qwen3.8-flash": "qwen3.8-flash",
|
|
"deepseek-v4.1-flash": "deepseek-flash",
|
|
"glm-5.3": "glm-5.3",
|
|
"glm-5.3-flash": "glm-5.3-flash",
|
|
"kimi-k3.1-pro": "kimi-k3.1-pro",
|
|
"minimax-m3.1-flash": "minimax-m3.1-flash",
|
|
}
|
|
|
|
_lock = threading.Lock()
|
|
_cursor = [0]
|
|
_accounts = []
|
|
_pool_mtime = 0.0
|
|
COOL_FILE = os.environ.get("QW_COOL_FILE", "/opt/qw-shim/cool.json")
|
|
_cool = {} # email -> unix ts until which the account is skipped
|
|
|
|
def load_cool():
|
|
try:
|
|
d = json.load(open(COOL_FILE, encoding="utf-8"))
|
|
now = time.time()
|
|
for k, v in d.items():
|
|
if isinstance(v, (int, float)) and v > now:
|
|
_cool[k] = float(v)
|
|
except Exception:
|
|
pass
|
|
|
|
def save_cool():
|
|
try:
|
|
now = time.time()
|
|
d = {k: v for k, v in _cool.items() if v > now}
|
|
tmp = COOL_FILE + ".tmp"
|
|
json.dump(d, open(tmp, "w", encoding="utf-8"))
|
|
os.replace(tmp, COOL_FILE)
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
class QWError(Exception):
|
|
def __init__(self, code, msg):
|
|
self.code = code
|
|
self.msg = msg
|
|
super().__init__("%s: %s" % (code, msg))
|
|
|
|
|
|
def load_pool():
|
|
global _accounts, _pool_mtime
|
|
acc = []
|
|
if os.path.exists(POOL_PATH):
|
|
try:
|
|
_pool_mtime = os.path.getmtime(POOL_PATH)
|
|
except OSError:
|
|
_pool_mtime = 0.0
|
|
for line in open(POOL_PATH, encoding="utf-8"):
|
|
line = line.strip()
|
|
if not line:
|
|
continue
|
|
try:
|
|
d = json.loads(line)
|
|
except Exception:
|
|
continue
|
|
if d.get("jwt"):
|
|
acc.append(d)
|
|
_accounts = acc
|
|
load_cool()
|
|
return len(acc)
|
|
|
|
|
|
def maybe_reload():
|
|
"""Pick up accounts appended by the farm without a service restart."""
|
|
try:
|
|
mt = os.path.getmtime(POOL_PATH)
|
|
except OSError:
|
|
return
|
|
if mt != _pool_mtime:
|
|
load_pool()
|
|
|
|
|
|
def pick(skip=None):
|
|
with _lock:
|
|
n = len(_accounts)
|
|
if not n:
|
|
return None
|
|
now = time.time()
|
|
for i in range(n):
|
|
a = _accounts[(_cursor[0] + i) % n]
|
|
if skip and a["email"] in skip:
|
|
continue
|
|
if _cool.get(a["email"], 0) > now:
|
|
continue
|
|
_cursor[0] = (_cursor[0] + i + 1) % n
|
|
return a
|
|
return None
|
|
|
|
|
|
def hdrs(jwt):
|
|
return {
|
|
"Authorization": "Bearer " + jwt,
|
|
"User-Agent": UA,
|
|
"Origin": BASE,
|
|
"Referer": BASE + "/app/",
|
|
"Content-Type": "application/json",
|
|
"X-Client-Source": "web",
|
|
"X-Mule-Language": "en-US",
|
|
}
|
|
|
|
|
|
def normalize(messages):
|
|
parts = []
|
|
for m in messages or []:
|
|
c = m.get("content")
|
|
if isinstance(c, list):
|
|
c = "".join(x.get("text", "") for x in c if isinstance(x, dict))
|
|
c = (c or "").strip()
|
|
if not c:
|
|
continue
|
|
role = m.get("role", "user")
|
|
parts.append(("[%s] " % role) + c if role in ("system", "assistant") else c)
|
|
return "\n\n".join(parts).strip()
|
|
|
|
|
|
def create_session(jwt, mode, text):
|
|
body = {
|
|
"agent_id": AGENT_ID,
|
|
"initial_prompt": {"text": text},
|
|
"mode": mode,
|
|
"extra_data": {"user_language": "en-US"},
|
|
"channel": "qwenwork_web",
|
|
}
|
|
req = urllib.request.Request(BASE + "/api/chat-sessions",
|
|
data=json.dumps(body).encode(), method="POST", headers=hdrs(jwt))
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=90) as r:
|
|
return json.loads(r.read().decode())
|
|
except urllib.error.HTTPError as e:
|
|
raise QWError(e.code, e.read().decode("utf-8", "replace")[:300])
|
|
|
|
|
|
def events(jwt, sid, after):
|
|
req = urllib.request.Request("%s/api/chat-sessions/%s/events?after=%d" % (BASE, sid, after),
|
|
headers=hdrs(jwt))
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=60) as r:
|
|
return json.loads(r.read().decode())
|
|
except urllib.error.HTTPError as e:
|
|
raise QWError(e.code, e.read().decode("utf-8", "replace")[:200])
|
|
|
|
|
|
def close_session(jwt, sid):
|
|
try:
|
|
req = urllib.request.Request("%s/api/chat-sessions/%s" % (BASE, sid),
|
|
method="DELETE", headers=hdrs(jwt))
|
|
urllib.request.urlopen(req, timeout=20).read()
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def run_turn(jwt, mode, text):
|
|
"""Return (answer, reasoning, sid). Waits for real agent_message_chunk, not just result."""
|
|
d = create_session(jwt, mode, text)
|
|
sid = d.get("id")
|
|
answer, thought, seq = [], [], 0
|
|
t0 = time.time()
|
|
last = [0.0]
|
|
done = False
|
|
while time.time() - t0 < POLL_MAX:
|
|
ev = events(jwt, sid, seq)
|
|
items = ev.get("items") or []
|
|
idle = time.time() - last[0]
|
|
for it in items:
|
|
params = (it.get("raw") or {}).get("params") or {}
|
|
meta = params.get("_meta") or {}
|
|
if isinstance(meta.get("seq_id"), int):
|
|
seq = max(seq, meta["seq_id"])
|
|
sub = it.get("sub_type") or ""
|
|
content = (params.get("update") or {}).get("content") or {}
|
|
txt = content.get("text") if isinstance(content, dict) else None
|
|
if sub == "agent_message_chunk" and txt:
|
|
answer.append(txt)
|
|
last[0] = time.time()
|
|
elif sub == "agent_thought_chunk" and txt:
|
|
thought.append(txt)
|
|
last[0] = time.time()
|
|
elif it.get("type") == "result":
|
|
done = True
|
|
if done and answer:
|
|
break
|
|
if done and not answer and idle > 12:
|
|
break # result without text -> upstream refused silently
|
|
time.sleep(0.4 if items else 0.8)
|
|
close_session(jwt, sid)
|
|
return "".join(answer), "".join(thought), sid
|
|
|
|
|
|
class H(BaseHTTPRequestHandler):
|
|
protocol_version = "HTTP/1.1"
|
|
|
|
def log_message(self, format, *args):
|
|
sys.stderr.write("[qw] " + (format % args) + "\n")
|
|
|
|
def _json(self, code, obj):
|
|
b = 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(b)))
|
|
self.end_headers()
|
|
self.wfile.write(b)
|
|
|
|
def do_GET(self):
|
|
maybe_reload()
|
|
if self.path.startswith("/healthz"):
|
|
return self._json(200, {"ok": True, "accounts": len(_accounts), "models": len(MODES),
|
|
"cooling": len([1 for v in _cool.values() if v > time.time()]),
|
|
"available": sum(1 for a in _accounts if _cool.get(a["email"], 0) <= time.time())})
|
|
if self.path.startswith("/v1/models"):
|
|
return self._json(200, {"object": "list", "data": [
|
|
{"id": k, "object": "model", "owned_by": "qwenwork"} for k in MODES]})
|
|
return self._json(404, {"error": "not found"})
|
|
|
|
def do_POST(self):
|
|
if not self.path.startswith("/v1/chat/completions"):
|
|
return self._json(404, {"error": "not found"})
|
|
try:
|
|
ln = int(self.headers.get("Content-Length") or 0)
|
|
req = json.loads(self.rfile.read(ln) or b"{}")
|
|
except Exception:
|
|
return self._json(400, {"error": {"message": "bad json"}})
|
|
|
|
maybe_reload()
|
|
model = req.get("model") or "qw-flash"
|
|
mode = MODES.get(model)
|
|
if not mode:
|
|
return self._json(404, {"error": {"message": "model %s not found" % model,
|
|
"type": "invalid_request_error"}})
|
|
text = normalize(req.get("messages"))
|
|
if not text:
|
|
return self._json(400, {"error": {"message": "empty prompt"}})
|
|
stream = bool(req.get("stream"))
|
|
|
|
acc = pick()
|
|
if not acc:
|
|
return self._json(503, {"error": {"message": "no qwenwork account available "
|
|
"(pool empty or all cooling)"}})
|
|
tried, ans, sid, last_err = set(), None, None, None
|
|
# [NORETRY 1121] one account per request: every attempt creates a session and burns
|
|
# the whole wallet, so a 4x retry loop cost 4 accounts per empty answer.
|
|
for _ in range(1):
|
|
try:
|
|
ans, _thought, sid = run_turn(acc["jwt"], mode, text)
|
|
if ans:
|
|
last_err = None
|
|
break
|
|
last_err = QWError(502, "empty answer (session created but no text)")
|
|
except QWError as e:
|
|
last_err = e
|
|
tried.add(acc["email"])
|
|
if last_err.code in (401, 402, 403):
|
|
_cool[acc["email"]] = time.time() + (COOLDOWN if last_err.code != 402 else int(os.environ.get("QW_COOL_402", "21600")))
|
|
save_cool()
|
|
acc = pick(skip=tried)
|
|
if not acc:
|
|
break
|
|
|
|
if ans is None:
|
|
code = last_err.code if last_err and isinstance(last_err.code, int) else 502
|
|
return self._json(code, {"error": {"message": (last_err.msg if last_err else "upstream failed"),
|
|
"type": "upstream_error"}})
|
|
ans = ans or ""
|
|
if not ans.strip():
|
|
# [EMPTY502 1121] upstream created the session but never emitted agent_message_chunk;
|
|
# returning an empty 200 poisons the gateway (user sees nothing, credits burned).
|
|
return self._json(502, {"error": {"message": "empty answer from qwenwork (no agent_message_chunk)",
|
|
"type": "upstream_error"},
|
|
"x_qwenwork_session": sid})
|
|
|
|
tid = "chatcmpl-" + uuid.uuid4().hex[:24]
|
|
created = int(time.time())
|
|
if not stream:
|
|
return self._json(200, {
|
|
"id": tid, "object": "chat.completion", "created": created, "model": model,
|
|
"choices": [{"index": 0, "message": {"role": "assistant", "content": ans},
|
|
"finish_reason": "stop"}],
|
|
"usage": {"prompt_tokens": max(1, len(text) // 4),
|
|
"completion_tokens": max(1, len(ans) // 4),
|
|
"total_tokens": max(1, (len(text) + len(ans)) // 4)},
|
|
"x_qwenwork_session": sid,
|
|
})
|
|
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "text/event-stream")
|
|
self.send_header("Cache-Control", "no-cache")
|
|
self.send_header("Connection", "keep-alive")
|
|
self.end_headers()
|
|
|
|
def chunk(delta, finish=None):
|
|
payload = {"id": tid, "object": "chat.completion.chunk", "created": created, "model": model,
|
|
"choices": [{"index": 0, "delta": delta, "finish_reason": finish}]}
|
|
self.wfile.write(("data: " + json.dumps(payload, ensure_ascii=False) + "\n\n").encode())
|
|
self.wfile.flush()
|
|
|
|
try:
|
|
chunk({"role": "assistant", "content": ""})
|
|
step = 60
|
|
for i in range(0, len(ans), step):
|
|
chunk({"content": ans[i:i + step]})
|
|
chunk({}, "stop")
|
|
self.wfile.write(b"data: [DONE]\n\n")
|
|
self.wfile.flush()
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def main():
|
|
n = load_pool()
|
|
print("[qw] pool=%d port=%d base=%s" % (n, PORT, BASE), flush=True)
|
|
srv = ThreadingHTTPServer(("127.0.0.1", PORT), H)
|
|
srv.daemon_threads = True
|
|
srv.serve_forever()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |