You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
67 lines
3.0 KiB
67 lines
3.0 KiB
import json
|
|
import requests as req_lib
|
|
|
|
|
|
class GeoApiClient:
|
|
def __init__(self, api_base: str, spider_token: str, vendor_token: str = ""):
|
|
self.api_base = api_base.rstrip("/")
|
|
self.spider_token = spider_token.strip()
|
|
self.vendor_token = vendor_token.strip() or self.spider_token
|
|
if not self.spider_token:
|
|
raise ValueError("缺少 spider_token。请在 worker_config.json 中填写 spider_token 后重试")
|
|
|
|
def _headers(self, use_vendor=False) -> dict:
|
|
token = self.vendor_token if use_vendor else self.spider_token
|
|
if not token.lower().startswith("bearer "):
|
|
token = f"Bearer {token}"
|
|
return {
|
|
"Authorization": token,
|
|
"Content-Type": "application/json",
|
|
"Accept": "application/json",
|
|
"User-Agent": "xueliu-task-worker/2.0",
|
|
}
|
|
|
|
def get_tasks(self, platforms: str, count: int = 1) -> list[dict]:
|
|
url = f"{self.api_base}/api/open/mt/get_task"
|
|
resp = req_lib.get(url, params={"platforms": platforms, "count": count}, headers=self._headers(), timeout=30)
|
|
try:
|
|
data = resp.json()
|
|
except Exception:
|
|
raise RuntimeError(f"get_task 非 JSON 响应 HTTP {resp.status_code}: {resp.text[:300]}")
|
|
|
|
code = data.get("code")
|
|
if code not in (0, 200, None) and code != "0":
|
|
if not data.get("data"):
|
|
msg = data.get("msg") or data.get("message") or str(data)
|
|
if any(k in str(msg) for k in ("无任务", "empty", "no task", "没有任务")):
|
|
return []
|
|
if code in (40001, 401, 403) or "token" in str(msg).lower():
|
|
raise PermissionError(f"get_task 鉴权失败: {msg}")
|
|
if code not in (0, 200):
|
|
print(f" [get_task] code={code} msg={msg}")
|
|
return []
|
|
items = data.get("data") or []
|
|
if isinstance(items, dict):
|
|
items = [items]
|
|
return items
|
|
|
|
def task_commit(self, task: dict) -> dict:
|
|
url = f"{self.api_base}/api/open/mt/task_commit"
|
|
body = {
|
|
"dispatchId": str(task.get("dispatchId") or task.get("id") or ""),
|
|
"prompt": (task.get("prompt") or "").strip(),
|
|
"platform": task.get("platform") or "",
|
|
"clientType": task.get("clientType") or "web",
|
|
"deepThinking": int(task.get("deepThinking") or 0),
|
|
"webSearch": int(task.get("webSearch") if task.get("webSearch") is not None else 1),
|
|
"model": task.get("model") or "",
|
|
}
|
|
if not body["dispatchId"] or not body["prompt"] or not body["platform"]:
|
|
raise ValueError(f"task_commit 缺少必要字段: {body}")
|
|
resp = req_lib.post(url, headers=self._headers(use_vendor=True), json=body, timeout=30)
|
|
return resp.json()
|
|
|
|
def submit(self, payload: dict) -> dict:
|
|
url = f"{self.api_base}/api/open/mt/submit"
|
|
resp = req_lib.post(url, headers=self._headers(), json=payload, timeout=60)
|
|
return resp.json()
|