mirror of
https://github.com/CJackHwang/ds2api.git
synced 2026-05-13 12:47:41 +08:00
feat: Initialize project with FastAPI backend, React web UI, Vercel sync, and API integrations.
This commit is contained in:
1
core/__init__.py
Normal file
1
core/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
# DS2API Core Modules
|
||||
146
core/auth.py
Normal file
146
core/auth.py
Normal file
@@ -0,0 +1,146 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""账号认证与管理模块"""
|
||||
import random
|
||||
from fastapi import HTTPException, Request
|
||||
|
||||
from .config import CONFIG, logger
|
||||
from .deepseek import login_deepseek_via_account, BASE_HEADERS
|
||||
|
||||
# -------------------------- 全局账号队列 --------------------------
|
||||
account_queue = [] # 维护所有可用账号
|
||||
claude_api_key_queue = [] # 维护所有可用的Claude API keys
|
||||
|
||||
|
||||
def init_account_queue():
|
||||
"""初始化时从配置加载账号"""
|
||||
global account_queue
|
||||
account_queue = CONFIG.get("accounts", [])[:] # 深拷贝
|
||||
random.shuffle(account_queue) # 初始随机排序
|
||||
|
||||
|
||||
def init_claude_api_key_queue():
|
||||
"""Claude API keys由用户自己的token提供,这里初始化为空"""
|
||||
global claude_api_key_queue
|
||||
claude_api_key_queue = []
|
||||
|
||||
|
||||
# 初始化
|
||||
init_account_queue()
|
||||
init_claude_api_key_queue()
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 辅助函数:获取账号唯一标识(优先 email,否则 mobile)
|
||||
# ----------------------------------------------------------------------
|
||||
def get_account_identifier(account: dict) -> str:
|
||||
"""返回账号的唯一标识,优先使用 email,否则使用 mobile"""
|
||||
return account.get("email", "").strip() or account.get("mobile", "").strip()
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 账号选择与释放
|
||||
# ----------------------------------------------------------------------
|
||||
def choose_new_account(exclude_ids=None):
|
||||
"""选择策略:
|
||||
1. 优先选择已有 token 的账号(避免登录)
|
||||
2. 遍历队列,找到第一个未被 exclude_ids 包含的账号
|
||||
3. 从队列中移除该账号
|
||||
4. 返回该账号(由后续逻辑保证最终会重新入队)
|
||||
"""
|
||||
if exclude_ids is None:
|
||||
exclude_ids = []
|
||||
|
||||
# 第一轮:优先选择已有 token 的账号
|
||||
for i in range(len(account_queue)):
|
||||
acc = account_queue[i]
|
||||
acc_id = get_account_identifier(acc)
|
||||
if acc_id and acc_id not in exclude_ids:
|
||||
if acc.get("token", "").strip(): # 已有 token
|
||||
logger.info(f"[choose_new_account] 选择已有token的账号: {acc_id}")
|
||||
return account_queue.pop(i)
|
||||
|
||||
# 第二轮:选择任意账号(需要登录)
|
||||
for i in range(len(account_queue)):
|
||||
acc = account_queue[i]
|
||||
acc_id = get_account_identifier(acc)
|
||||
if acc_id and acc_id not in exclude_ids:
|
||||
logger.info(f"[choose_new_account] 选择需登录的账号: {acc_id}")
|
||||
return account_queue.pop(i)
|
||||
|
||||
logger.warning("[choose_new_account] 没有可用的账号或所有账号都在使用中")
|
||||
return None
|
||||
|
||||
|
||||
def release_account(account: dict):
|
||||
"""将账号重新加入队列末尾"""
|
||||
account_queue.append(account)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# Claude API key 管理函数(简化版本)
|
||||
# ----------------------------------------------------------------------
|
||||
def choose_claude_api_key():
|
||||
"""选择一个可用的Claude API key - 现在直接由用户提供"""
|
||||
return None
|
||||
|
||||
|
||||
def release_claude_api_key(api_key):
|
||||
"""释放Claude API key - 现在无需操作"""
|
||||
pass
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 判断调用模式:配置模式 vs 用户自带 token
|
||||
# ----------------------------------------------------------------------
|
||||
def determine_mode_and_token(request: Request):
|
||||
"""
|
||||
根据请求头 Authorization 判断使用哪种模式:
|
||||
- 如果 Bearer token 出现在 CONFIG["keys"] 中,则为配置模式,从 CONFIG["accounts"] 中随机选择一个账号(排除已尝试账号),
|
||||
检查该账号是否已有 token,否则调用登录接口获取;
|
||||
- 否则,直接使用请求中的 Bearer 值作为 DeepSeek token。
|
||||
结果存入 request.state.deepseek_token;配置模式下同时存入 request.state.account 与 request.state.tried_accounts。
|
||||
"""
|
||||
auth_header = request.headers.get("Authorization", "")
|
||||
if not auth_header.startswith("Bearer "):
|
||||
raise HTTPException(
|
||||
status_code=401, detail="Unauthorized: missing Bearer token."
|
||||
)
|
||||
caller_key = auth_header.replace("Bearer ", "", 1).strip()
|
||||
config_keys = CONFIG.get("keys", [])
|
||||
if caller_key in config_keys:
|
||||
request.state.use_config_token = True
|
||||
request.state.tried_accounts = [] # 初始化已尝试账号
|
||||
selected_account = choose_new_account()
|
||||
if not selected_account:
|
||||
raise HTTPException(
|
||||
status_code=429,
|
||||
detail="No accounts configured or all accounts are busy.",
|
||||
)
|
||||
if not selected_account.get("token", "").strip():
|
||||
try:
|
||||
login_deepseek_via_account(selected_account)
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"[determine_mode_and_token] 账号 {get_account_identifier(selected_account)} 登录失败:{e}"
|
||||
)
|
||||
raise HTTPException(status_code=500, detail="Account login failed.")
|
||||
|
||||
request.state.deepseek_token = selected_account.get("token")
|
||||
request.state.account = selected_account
|
||||
|
||||
else:
|
||||
request.state.use_config_token = False
|
||||
request.state.deepseek_token = caller_key
|
||||
|
||||
|
||||
def get_auth_headers(request: Request) -> dict:
|
||||
"""返回 DeepSeek 请求所需的公共请求头"""
|
||||
return {**BASE_HEADERS, "authorization": f"Bearer {request.state.deepseek_token}"}
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# Claude 认证相关函数
|
||||
# ----------------------------------------------------------------------
|
||||
def determine_claude_mode_and_token(request: Request):
|
||||
"""Claude认证:沿用现有的OpenAI接口认证逻辑"""
|
||||
determine_mode_and_token(request)
|
||||
103
core/config.py
Normal file
103
core/config.py
Normal file
@@ -0,0 +1,103 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""配置管理模块"""
|
||||
import base64
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
import transformers
|
||||
|
||||
# -------------------------- 获取项目根目录 --------------------------
|
||||
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
IS_VERCEL = bool(os.getenv("VERCEL")) or bool(os.getenv("NOW_REGION"))
|
||||
|
||||
|
||||
def resolve_path(env_key: str, default_rel: str) -> str:
|
||||
"""解析路径,支持环境变量覆盖"""
|
||||
raw = os.getenv(env_key)
|
||||
if raw:
|
||||
return raw if os.path.isabs(raw) else os.path.join(BASE_DIR, raw)
|
||||
return os.path.join(BASE_DIR, default_rel)
|
||||
|
||||
|
||||
# -------------------------- 日志配置 --------------------------
|
||||
logging.basicConfig(
|
||||
level=os.getenv("LOG_LEVEL", "INFO").upper(),
|
||||
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
||||
handlers=[logging.StreamHandler(sys.stdout)],
|
||||
force=True,
|
||||
)
|
||||
logger = logging.getLogger("ds2api")
|
||||
|
||||
# -------------------------- 初始化 tokenizer --------------------------
|
||||
chat_tokenizer_dir = resolve_path("DS2API_TOKENIZER_DIR", "")
|
||||
tokenizer = transformers.AutoTokenizer.from_pretrained(
|
||||
chat_tokenizer_dir, trust_remote_code=True
|
||||
)
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 配置文件的读写函数
|
||||
# ----------------------------------------------------------------------
|
||||
CONFIG_PATH = resolve_path("DS2API_CONFIG_PATH", "config.json")
|
||||
|
||||
|
||||
def load_config() -> dict:
|
||||
"""加载配置。
|
||||
|
||||
优先从环境变量读取:
|
||||
- DS2API_CONFIG_JSON / CONFIG_JSON: 直接 JSON 字符串,或 base64 编码后的 JSON
|
||||
|
||||
若未提供环境变量,再从 CONFIG_PATH 指向的文件读取。
|
||||
"""
|
||||
raw_cfg = os.getenv("DS2API_CONFIG_JSON") or os.getenv("CONFIG_JSON")
|
||||
if raw_cfg:
|
||||
try:
|
||||
return json.loads(raw_cfg)
|
||||
except json.JSONDecodeError:
|
||||
try:
|
||||
decoded = base64.b64decode(raw_cfg).decode("utf-8")
|
||||
return json.loads(decoded)
|
||||
except Exception as e:
|
||||
logger.warning(f"[load_config] 环境变量配置解析失败: {e}")
|
||||
return {}
|
||||
|
||||
try:
|
||||
with open(CONFIG_PATH, "r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
except Exception as e:
|
||||
logger.warning(f"[load_config] 无法读取配置文件({CONFIG_PATH}): {e}")
|
||||
return {}
|
||||
|
||||
|
||||
def save_config(cfg: dict) -> None:
|
||||
"""将配置写回 config.json。
|
||||
|
||||
Vercel 环境文件系统通常是只读的;且如果配置来自环境变量,也无法回写。
|
||||
所以这里失败不应影响主流程。
|
||||
"""
|
||||
if os.getenv("DS2API_CONFIG_JSON") or os.getenv("CONFIG_JSON"):
|
||||
logger.info("[save_config] 配置来自环境变量,跳过写回")
|
||||
return
|
||||
|
||||
try:
|
||||
with open(CONFIG_PATH, "w", encoding="utf-8") as f:
|
||||
json.dump(cfg, f, ensure_ascii=False, indent=2)
|
||||
except PermissionError as e:
|
||||
logger.warning(f"[save_config] 配置文件不可写({CONFIG_PATH}): {e}")
|
||||
except Exception as e:
|
||||
logger.exception(f"[save_config] 写入 config.json 失败: {e}")
|
||||
|
||||
|
||||
# 全局配置
|
||||
CONFIG = load_config()
|
||||
if not CONFIG:
|
||||
logger.warning(
|
||||
"[config] 未加载到有效配置,请提供 config.json(路径可用 DS2API_CONFIG_PATH 指定)或设置环境变量 DS2API_CONFIG_JSON"
|
||||
)
|
||||
|
||||
# WASM 模块文件路径
|
||||
WASM_PATH = resolve_path("DS2API_WASM_PATH", "sha3_wasm_bg.7b9ca65ddd.wasm")
|
||||
|
||||
# 模板目录
|
||||
TEMPLATES_DIR = resolve_path("DS2API_TEMPLATES_DIR", "templates")
|
||||
132
core/deepseek.py
Normal file
132
core/deepseek.py
Normal file
@@ -0,0 +1,132 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""DeepSeek API 相关逻辑"""
|
||||
import time
|
||||
from curl_cffi import requests
|
||||
from fastapi import HTTPException
|
||||
|
||||
from .config import CONFIG, save_config, logger
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# DeepSeek 相关常量
|
||||
# ----------------------------------------------------------------------
|
||||
DEEPSEEK_HOST = "chat.deepseek.com"
|
||||
DEEPSEEK_LOGIN_URL = f"https://{DEEPSEEK_HOST}/api/v0/users/login"
|
||||
DEEPSEEK_CREATE_SESSION_URL = f"https://{DEEPSEEK_HOST}/api/v0/chat_session/create"
|
||||
DEEPSEEK_CREATE_POW_URL = f"https://{DEEPSEEK_HOST}/api/v0/chat/create_pow_challenge"
|
||||
DEEPSEEK_COMPLETION_URL = f"https://{DEEPSEEK_HOST}/api/v0/chat/completion"
|
||||
|
||||
BASE_HEADERS = {
|
||||
"Host": "chat.deepseek.com",
|
||||
"User-Agent": "DeepSeek/1.0.13 Android/35",
|
||||
"Accept": "application/json",
|
||||
"Accept-Encoding": "gzip",
|
||||
"Content-Type": "application/json",
|
||||
"x-client-platform": "android",
|
||||
"x-client-version": "1.3.0-auto-resume",
|
||||
"x-client-locale": "zh_CN",
|
||||
"accept-charset": "UTF-8",
|
||||
}
|
||||
|
||||
|
||||
def get_account_identifier(account: dict) -> str:
|
||||
"""返回账号的唯一标识,优先使用 email,否则使用 mobile"""
|
||||
return account.get("email", "").strip() or account.get("mobile", "").strip()
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 登录函数:支持使用 email 或 mobile 登录
|
||||
# ----------------------------------------------------------------------
|
||||
def login_deepseek_via_account(account: dict) -> str:
|
||||
"""使用 account 中的 email 或 mobile 登录 DeepSeek,
|
||||
成功后将返回的 token 写入 account 并保存至配置文件,返回新 token。
|
||||
"""
|
||||
email = account.get("email", "").strip()
|
||||
mobile = account.get("mobile", "").strip()
|
||||
password = account.get("password", "").strip()
|
||||
if not password or (not email and not mobile):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="账号缺少必要的登录信息(必须提供 email 或 mobile 以及 password)",
|
||||
)
|
||||
if email:
|
||||
payload = {
|
||||
"email": email,
|
||||
"password": password,
|
||||
"device_id": "deepseek_to_api",
|
||||
"os": "android",
|
||||
}
|
||||
else:
|
||||
payload = {
|
||||
"mobile": mobile,
|
||||
"area_code": None,
|
||||
"password": password,
|
||||
"device_id": "deepseek_to_api",
|
||||
"os": "android",
|
||||
}
|
||||
try:
|
||||
resp = requests.post(
|
||||
DEEPSEEK_LOGIN_URL, headers=BASE_HEADERS, json=payload, impersonate="safari15_3"
|
||||
)
|
||||
resp.raise_for_status()
|
||||
except Exception as e:
|
||||
logger.error(f"[login_deepseek_via_account] 登录请求异常: {e}")
|
||||
raise HTTPException(status_code=500, detail="Account login failed: 请求异常")
|
||||
try:
|
||||
logger.warning(f"[login_deepseek_via_account] {resp.text}")
|
||||
data = resp.json()
|
||||
except Exception as e:
|
||||
logger.error(f"[login_deepseek_via_account] JSON解析失败: {e}")
|
||||
raise HTTPException(
|
||||
status_code=500, detail="Account login failed: invalid JSON response"
|
||||
)
|
||||
# 校验响应数据格式是否正确
|
||||
if (
|
||||
data.get("data") is None
|
||||
or data["data"].get("biz_data") is None
|
||||
or data["data"]["biz_data"].get("user") is None
|
||||
):
|
||||
logger.error(f"[login_deepseek_via_account] 登录响应格式错误: {data}")
|
||||
raise HTTPException(
|
||||
status_code=500, detail="Account login failed: invalid response format"
|
||||
)
|
||||
new_token = data["data"]["biz_data"]["user"].get("token")
|
||||
if not new_token:
|
||||
logger.error(f"[login_deepseek_via_account] 登录响应中缺少 token: {data}")
|
||||
raise HTTPException(
|
||||
status_code=500, detail="Account login failed: missing token"
|
||||
)
|
||||
account["token"] = new_token
|
||||
save_config(CONFIG)
|
||||
return new_token
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 封装对话接口调用的重试机制
|
||||
# ----------------------------------------------------------------------
|
||||
def call_completion_endpoint(payload: dict, headers: dict, max_attempts: int = 3):
|
||||
"""调用 DeepSeek 对话接口,支持重试"""
|
||||
attempts = 0
|
||||
while attempts < max_attempts:
|
||||
try:
|
||||
deepseek_resp = requests.post(
|
||||
DEEPSEEK_COMPLETION_URL,
|
||||
headers=headers,
|
||||
json=payload,
|
||||
stream=True,
|
||||
impersonate="safari15_3",
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"[call_completion_endpoint] 请求异常: {e}")
|
||||
time.sleep(1)
|
||||
attempts += 1
|
||||
continue
|
||||
if deepseek_resp.status_code == 200:
|
||||
return deepseek_resp
|
||||
else:
|
||||
logger.warning(
|
||||
f"[call_completion_endpoint] 调用对话接口失败, 状态码: {deepseek_resp.status_code}"
|
||||
)
|
||||
deepseek_resp.close()
|
||||
time.sleep(1)
|
||||
attempts += 1
|
||||
return None
|
||||
118
core/messages.py
Normal file
118
core/messages.py
Normal file
@@ -0,0 +1,118 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""消息处理模块"""
|
||||
import re
|
||||
|
||||
from .config import CONFIG, logger
|
||||
|
||||
# Claude 默认模型
|
||||
CLAUDE_DEFAULT_MODEL = "claude-sonnet-4-20250514"
|
||||
|
||||
# 预编译正则表达式(性能优化)
|
||||
_MARKDOWN_IMAGE_PATTERN = re.compile(r"!\[(.*?)\]\((.*?)\)")
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 消息预处理函数,将多轮对话合并成最终 prompt
|
||||
# ----------------------------------------------------------------------
|
||||
def messages_prepare(messages: list) -> str:
|
||||
"""处理消息列表,合并连续相同角色的消息,并添加角色标签:
|
||||
- 对于 assistant 消息,加上 <|Assistant|> 前缀及 <|end▁of▁sentence|> 结束标签;
|
||||
- 对于 user/system 消息(除第一条外)加上 <|User|> 前缀;
|
||||
- 如果消息 content 为数组,则提取其中 type 为 "text" 的部分;
|
||||
- 最后移除 markdown 图片格式的内容。
|
||||
"""
|
||||
processed = []
|
||||
for m in messages:
|
||||
role = m.get("role", "")
|
||||
content = m.get("content", "")
|
||||
if isinstance(content, list):
|
||||
texts = [
|
||||
item.get("text", "") for item in content if item.get("type") == "text"
|
||||
]
|
||||
text = "\n".join(texts)
|
||||
else:
|
||||
text = str(content)
|
||||
processed.append({"role": role, "text": text})
|
||||
if not processed:
|
||||
return ""
|
||||
# 合并连续同一角色的消息
|
||||
merged = [processed[0]]
|
||||
for msg in processed[1:]:
|
||||
if msg["role"] == merged[-1]["role"]:
|
||||
merged[-1]["text"] += "\n\n" + msg["text"]
|
||||
else:
|
||||
merged.append(msg)
|
||||
# 添加标签
|
||||
parts = []
|
||||
for idx, block in enumerate(merged):
|
||||
role = block["role"]
|
||||
text = block["text"]
|
||||
if role == "assistant":
|
||||
parts.append(f"<|Assistant|>{text}<|end▁of▁sentence|>")
|
||||
elif role in ("user", "system"):
|
||||
if idx > 0:
|
||||
parts.append(f"<|User|>{text}")
|
||||
else:
|
||||
parts.append(text)
|
||||
else:
|
||||
parts.append(text)
|
||||
final_prompt = "".join(parts)
|
||||
# 仅移除 markdown 图片格式(不全部移除 !)- 使用预编译的正则表达式
|
||||
final_prompt = _MARKDOWN_IMAGE_PATTERN.sub(r"[\1](\2)", final_prompt)
|
||||
return final_prompt
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# OpenAI到Claude格式转换函数
|
||||
# ----------------------------------------------------------------------
|
||||
def convert_claude_to_deepseek(claude_request: dict) -> dict:
|
||||
"""将Claude格式的请求转换为DeepSeek格式(基于现有OpenAI接口)"""
|
||||
messages = claude_request.get("messages", [])
|
||||
model = claude_request.get("model", CLAUDE_DEFAULT_MODEL)
|
||||
|
||||
# 从配置文件读取Claude模型映射
|
||||
claude_mapping = CONFIG.get(
|
||||
"claude_model_mapping", {"fast": "deepseek-chat", "slow": "deepseek-chat"}
|
||||
)
|
||||
|
||||
# Claude模型映射到DeepSeek模型 - 基于配置和模型特征判断
|
||||
if (
|
||||
"opus" in model.lower()
|
||||
or "reasoner" in model.lower()
|
||||
or "slow" in model.lower()
|
||||
):
|
||||
deepseek_model = claude_mapping.get("slow", "deepseek-chat")
|
||||
else:
|
||||
deepseek_model = claude_mapping.get("fast", "deepseek-chat")
|
||||
|
||||
deepseek_request = {"model": deepseek_model, "messages": messages.copy()}
|
||||
|
||||
# 处理system消息 - 将system参数转换为system role消息
|
||||
if "system" in claude_request:
|
||||
system_msg = {"role": "system", "content": claude_request["system"]}
|
||||
deepseek_request["messages"].insert(0, system_msg)
|
||||
|
||||
# 添加可选参数
|
||||
if "temperature" in claude_request:
|
||||
deepseek_request["temperature"] = claude_request["temperature"]
|
||||
if "top_p" in claude_request:
|
||||
deepseek_request["top_p"] = claude_request["top_p"]
|
||||
if "stop_sequences" in claude_request:
|
||||
deepseek_request["stop"] = claude_request["stop_sequences"]
|
||||
if "stream" in claude_request:
|
||||
deepseek_request["stream"] = claude_request["stream"]
|
||||
|
||||
return deepseek_request
|
||||
|
||||
|
||||
def convert_deepseek_to_claude_format(
|
||||
deepseek_response: dict, original_claude_model: str = CLAUDE_DEFAULT_MODEL
|
||||
) -> dict:
|
||||
"""将DeepSeek响应转换为Claude格式的OpenAI响应"""
|
||||
# DeepSeek响应已经是OpenAI格式,只需要修改模型名称
|
||||
if isinstance(deepseek_response, dict):
|
||||
claude_response = deepseek_response.copy()
|
||||
claude_response["model"] = original_claude_model
|
||||
return claude_response
|
||||
|
||||
return deepseek_response
|
||||
247
core/pow.py
Normal file
247
core/pow.py
Normal file
@@ -0,0 +1,247 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""PoW (Proof of Work) 计算模块"""
|
||||
import base64
|
||||
import ctypes
|
||||
import json
|
||||
import struct
|
||||
import threading
|
||||
import time
|
||||
|
||||
from curl_cffi import requests
|
||||
from wasmtime import Engine, Linker, Module, Store
|
||||
|
||||
from .config import CONFIG, WASM_PATH, logger
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# WASM 模块缓存 - 避免每次请求都重新加载
|
||||
# ----------------------------------------------------------------------
|
||||
_wasm_cache_lock = threading.Lock()
|
||||
_wasm_engine = None
|
||||
_wasm_module = None
|
||||
|
||||
|
||||
def _get_cached_wasm_module(wasm_path: str):
|
||||
"""获取缓存的 WASM 模块,首次调用时加载"""
|
||||
global _wasm_engine, _wasm_module
|
||||
|
||||
if _wasm_module is not None:
|
||||
return _wasm_engine, _wasm_module
|
||||
|
||||
with _wasm_cache_lock:
|
||||
# 双重检查锁定
|
||||
if _wasm_module is not None:
|
||||
return _wasm_engine, _wasm_module
|
||||
|
||||
try:
|
||||
with open(wasm_path, "rb") as f:
|
||||
wasm_bytes = f.read()
|
||||
_wasm_engine = Engine()
|
||||
_wasm_module = Module(_wasm_engine, wasm_bytes)
|
||||
logger.info(f"[WASM] 已缓存 WASM 模块: {wasm_path}")
|
||||
except Exception as e:
|
||||
logger.error(f"[WASM] 加载 WASM 模块失败: {e}")
|
||||
raise RuntimeError(f"加载 wasm 文件失败: {wasm_path}, 错误: {e}")
|
||||
|
||||
return _wasm_engine, _wasm_module
|
||||
|
||||
|
||||
# 启动时预加载 WASM 模块
|
||||
try:
|
||||
_get_cached_wasm_module(WASM_PATH)
|
||||
except Exception as e:
|
||||
logger.warning(f"[WASM] 启动时预加载失败(将在首次使用时重试): {e}")
|
||||
|
||||
|
||||
def get_account_identifier(account: dict) -> str:
|
||||
"""返回账号的唯一标识"""
|
||||
return account.get("email", "").strip() or account.get("mobile", "").strip()
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 使用 WASM 模块计算 PoW 答案的辅助函数
|
||||
# ----------------------------------------------------------------------
|
||||
def compute_pow_answer(
|
||||
algorithm: str,
|
||||
challenge_str: str,
|
||||
salt: str,
|
||||
difficulty: int,
|
||||
expire_at: int,
|
||||
signature: str,
|
||||
target_path: str,
|
||||
wasm_path: str,
|
||||
) -> int:
|
||||
"""
|
||||
使用 WASM 模块计算 DeepSeekHash 答案(answer)。
|
||||
根据 JS 逻辑:
|
||||
- 拼接前缀: "{salt}_{expire_at}_"
|
||||
- 将 challenge 与前缀写入 wasm 内存后调用 wasm_solve 进行求解,
|
||||
- 从 wasm 内存中读取状态与求解结果,
|
||||
- 若状态非 0,则返回整数形式的答案,否则返回 None。
|
||||
|
||||
优化:使用缓存的 WASM 模块,避免每次请求都重新加载文件。
|
||||
"""
|
||||
if algorithm != "DeepSeekHashV1":
|
||||
raise ValueError(f"不支持的算法:{algorithm}")
|
||||
|
||||
prefix = f"{salt}_{expire_at}_"
|
||||
|
||||
# 获取缓存的 WASM 模块(避免重复加载文件)
|
||||
engine, module = _get_cached_wasm_module(wasm_path)
|
||||
|
||||
# 每次调用创建新的 Store 和实例(必须的,因为 Store 不是线程安全的)
|
||||
store = Store(engine)
|
||||
linker = Linker(engine)
|
||||
instance = linker.instantiate(store, module)
|
||||
exports = instance.exports(store)
|
||||
|
||||
try:
|
||||
memory = exports["memory"]
|
||||
add_to_stack = exports["__wbindgen_add_to_stack_pointer"]
|
||||
alloc = exports["__wbindgen_export_0"]
|
||||
wasm_solve = exports["wasm_solve"]
|
||||
except KeyError as e:
|
||||
raise RuntimeError(f"缺少 wasm 导出函数: {e}")
|
||||
|
||||
def write_memory(offset: int, data: bytes):
|
||||
size = len(data)
|
||||
base_addr = ctypes.cast(memory.data_ptr(store), ctypes.c_void_p).value
|
||||
ctypes.memmove(base_addr + offset, data, size)
|
||||
|
||||
def read_memory(offset: int, size: int) -> bytes:
|
||||
base_addr = ctypes.cast(memory.data_ptr(store), ctypes.c_void_p).value
|
||||
return ctypes.string_at(base_addr + offset, size)
|
||||
|
||||
def encode_string(text: str):
|
||||
data = text.encode("utf-8")
|
||||
length = len(data)
|
||||
ptr_val = alloc(store, length, 1)
|
||||
ptr = int(ptr_val.value) if hasattr(ptr_val, "value") else int(ptr_val)
|
||||
write_memory(ptr, data)
|
||||
return ptr, length
|
||||
|
||||
# 1. 申请 16 字节栈空间
|
||||
retptr = add_to_stack(store, -16)
|
||||
# 2. 编码 challenge 与 prefix 到 wasm 内存中
|
||||
ptr_challenge, len_challenge = encode_string(challenge_str)
|
||||
ptr_prefix, len_prefix = encode_string(prefix)
|
||||
# 3. 调用 wasm_solve(注意:difficulty 以 float 形式传入)
|
||||
wasm_solve(
|
||||
store,
|
||||
retptr,
|
||||
ptr_challenge,
|
||||
len_challenge,
|
||||
ptr_prefix,
|
||||
len_prefix,
|
||||
float(difficulty),
|
||||
)
|
||||
# 4. 从 retptr 处读取 4 字节状态和 8 字节求解结果
|
||||
status_bytes = read_memory(retptr, 4)
|
||||
if len(status_bytes) != 4:
|
||||
add_to_stack(store, 16)
|
||||
raise RuntimeError("读取状态字节失败")
|
||||
status = struct.unpack("<i", status_bytes)[0]
|
||||
value_bytes = read_memory(retptr + 8, 8)
|
||||
if len(value_bytes) != 8:
|
||||
add_to_stack(store, 16)
|
||||
raise RuntimeError("读取结果字节失败")
|
||||
value = struct.unpack("<d", value_bytes)[0]
|
||||
# 5. 恢复栈指针
|
||||
add_to_stack(store, 16)
|
||||
if status == 0:
|
||||
return None
|
||||
return int(value)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 获取 PoW 响应,融合计算 answer 逻辑
|
||||
# ----------------------------------------------------------------------
|
||||
def get_pow_response(request, get_auth_headers_func, choose_new_account_func,
|
||||
login_func, pow_url: str, max_attempts: int = 3):
|
||||
"""获取 PoW 响应"""
|
||||
from .deepseek import BASE_HEADERS
|
||||
|
||||
attempts = 0
|
||||
while attempts < max_attempts:
|
||||
headers = get_auth_headers_func(request)
|
||||
try:
|
||||
resp = requests.post(
|
||||
pow_url,
|
||||
headers=headers,
|
||||
json={"target_path": "/api/v0/chat/completion"},
|
||||
timeout=30,
|
||||
impersonate="safari15_3",
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"[get_pow_response] 请求异常: {e}")
|
||||
attempts += 1
|
||||
continue
|
||||
try:
|
||||
data = resp.json()
|
||||
except Exception as e:
|
||||
logger.error(f"[get_pow_response] JSON解析异常: {e}")
|
||||
data = {}
|
||||
if resp.status_code == 200 and data.get("code") == 0:
|
||||
challenge = data["data"]["biz_data"]["challenge"]
|
||||
difficulty = challenge.get("difficulty", 144000)
|
||||
expire_at = challenge.get("expire_at", 1680000000)
|
||||
try:
|
||||
answer = compute_pow_answer(
|
||||
challenge["algorithm"],
|
||||
challenge["challenge"],
|
||||
challenge["salt"],
|
||||
difficulty,
|
||||
expire_at,
|
||||
challenge["signature"],
|
||||
challenge["target_path"],
|
||||
WASM_PATH,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"[get_pow_response] PoW 答案计算异常: {e}")
|
||||
answer = None
|
||||
if answer is None:
|
||||
logger.warning("[get_pow_response] PoW 答案计算失败,重试中...")
|
||||
resp.close()
|
||||
attempts += 1
|
||||
continue
|
||||
pow_dict = {
|
||||
"algorithm": challenge["algorithm"],
|
||||
"challenge": challenge["challenge"],
|
||||
"salt": challenge["salt"],
|
||||
"answer": answer,
|
||||
"signature": challenge["signature"],
|
||||
"target_path": challenge["target_path"],
|
||||
}
|
||||
pow_str = json.dumps(pow_dict, separators=(",", ":"), ensure_ascii=False)
|
||||
encoded = base64.b64encode(pow_str.encode("utf-8")).decode("utf-8").rstrip()
|
||||
resp.close()
|
||||
return encoded
|
||||
else:
|
||||
code = data.get("code")
|
||||
logger.warning(
|
||||
f"[get_pow_response] 获取 PoW 失败, code={code}, msg={data.get('msg')}"
|
||||
)
|
||||
resp.close()
|
||||
if request.state.use_config_token:
|
||||
current_id = get_account_identifier(request.state.account)
|
||||
if not hasattr(request.state, "tried_accounts"):
|
||||
request.state.tried_accounts = []
|
||||
if current_id not in request.state.tried_accounts:
|
||||
request.state.tried_accounts.append(current_id)
|
||||
new_account = choose_new_account_func(request.state.tried_accounts)
|
||||
if new_account is None:
|
||||
break
|
||||
try:
|
||||
login_func(new_account)
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"[get_pow_response] 账号 {get_account_identifier(new_account)} 登录失败:{e}"
|
||||
)
|
||||
attempts += 1
|
||||
continue
|
||||
request.state.account = new_account
|
||||
request.state.deepseek_token = new_account.get("token")
|
||||
else:
|
||||
attempts += 1
|
||||
continue
|
||||
attempts += 1
|
||||
return None
|
||||
175
core/session_manager.py
Normal file
175
core/session_manager.py
Normal file
@@ -0,0 +1,175 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""会话管理模块 - 封装公共的会话创建和 PoW 获取逻辑"""
|
||||
from curl_cffi import requests as cffi_requests
|
||||
from fastapi import HTTPException, Request
|
||||
|
||||
from .config import logger
|
||||
from .auth import (
|
||||
get_auth_headers,
|
||||
choose_new_account,
|
||||
get_account_identifier,
|
||||
release_account,
|
||||
)
|
||||
from .deepseek import (
|
||||
DEEPSEEK_CREATE_SESSION_URL,
|
||||
DEEPSEEK_CREATE_POW_URL,
|
||||
login_deepseek_via_account,
|
||||
call_completion_endpoint,
|
||||
)
|
||||
from .pow import get_pow_response
|
||||
|
||||
|
||||
def create_session(request: Request, max_attempts: int = 3) -> str | None:
|
||||
"""创建 DeepSeek 会话
|
||||
|
||||
Args:
|
||||
request: FastAPI 请求对象
|
||||
max_attempts: 最大重试次数
|
||||
|
||||
Returns:
|
||||
会话 ID,如果失败返回 None
|
||||
"""
|
||||
attempts = 0
|
||||
while attempts < max_attempts:
|
||||
headers = get_auth_headers(request)
|
||||
try:
|
||||
resp = cffi_requests.post(
|
||||
DEEPSEEK_CREATE_SESSION_URL,
|
||||
headers=headers,
|
||||
json={"agent": "chat"},
|
||||
impersonate="safari15_3",
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"[create_session] 请求异常: {e}")
|
||||
attempts += 1
|
||||
continue
|
||||
|
||||
try:
|
||||
data = resp.json()
|
||||
except Exception as e:
|
||||
logger.error(f"[create_session] JSON解析异常: {e}")
|
||||
data = {}
|
||||
|
||||
if resp.status_code == 200 and data.get("code") == 0:
|
||||
session_id = data["data"]["biz_data"]["id"]
|
||||
resp.close()
|
||||
return session_id
|
||||
else:
|
||||
code = data.get("code")
|
||||
logger.warning(
|
||||
f"[create_session] 创建会话失败, code={code}, msg={data.get('msg')}"
|
||||
)
|
||||
resp.close()
|
||||
|
||||
# 配置模式下尝试切换账号
|
||||
if request.state.use_config_token:
|
||||
current_id = get_account_identifier(request.state.account)
|
||||
if not hasattr(request.state, "tried_accounts"):
|
||||
request.state.tried_accounts = []
|
||||
if current_id not in request.state.tried_accounts:
|
||||
request.state.tried_accounts.append(current_id)
|
||||
new_account = choose_new_account(request.state.tried_accounts)
|
||||
if new_account is None:
|
||||
break
|
||||
try:
|
||||
login_deepseek_via_account(new_account)
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"[create_session] 账号 {get_account_identifier(new_account)} 登录失败:{e}"
|
||||
)
|
||||
attempts += 1
|
||||
continue
|
||||
request.state.account = new_account
|
||||
request.state.deepseek_token = new_account.get("token")
|
||||
else:
|
||||
attempts += 1
|
||||
continue
|
||||
attempts += 1
|
||||
return None
|
||||
|
||||
|
||||
def get_pow(request: Request, max_attempts: int = 3) -> str | None:
|
||||
"""获取 PoW 响应的包装函数
|
||||
|
||||
Args:
|
||||
request: FastAPI 请求对象
|
||||
max_attempts: 最大重试次数
|
||||
|
||||
Returns:
|
||||
Base64 编码的 PoW 响应,如果失败返回 None
|
||||
"""
|
||||
return get_pow_response(
|
||||
request,
|
||||
get_auth_headers,
|
||||
choose_new_account,
|
||||
login_deepseek_via_account,
|
||||
DEEPSEEK_CREATE_POW_URL,
|
||||
max_attempts,
|
||||
)
|
||||
|
||||
|
||||
def prepare_completion_request(
|
||||
request: Request,
|
||||
session_id: str,
|
||||
prompt: str,
|
||||
thinking_enabled: bool = False,
|
||||
search_enabled: bool = False,
|
||||
max_attempts: int = 3,
|
||||
):
|
||||
"""准备并执行对话补全请求
|
||||
|
||||
Args:
|
||||
request: FastAPI 请求对象
|
||||
session_id: 会话 ID
|
||||
prompt: 处理后的提示词
|
||||
thinking_enabled: 是否启用思考模式
|
||||
search_enabled: 是否启用搜索
|
||||
max_attempts: 最大重试次数
|
||||
|
||||
Returns:
|
||||
DeepSeek 响应对象,如果失败返回 None
|
||||
"""
|
||||
pow_resp = get_pow(request, max_attempts)
|
||||
if not pow_resp:
|
||||
return None
|
||||
|
||||
headers = {**get_auth_headers(request), "x-ds-pow-response": pow_resp}
|
||||
payload = {
|
||||
"chat_session_id": session_id,
|
||||
"parent_message_id": None,
|
||||
"prompt": prompt,
|
||||
"ref_file_ids": [],
|
||||
"thinking_enabled": thinking_enabled,
|
||||
"search_enabled": search_enabled,
|
||||
}
|
||||
|
||||
return call_completion_endpoint(payload, headers, max_attempts)
|
||||
|
||||
|
||||
def get_model_config(model: str) -> tuple[bool, bool]:
|
||||
"""根据模型名称获取配置
|
||||
|
||||
Args:
|
||||
model: 模型名称
|
||||
|
||||
Returns:
|
||||
(thinking_enabled, search_enabled) 元组
|
||||
"""
|
||||
model_lower = model.lower()
|
||||
|
||||
if model_lower in ["deepseek-v3", "deepseek-chat"]:
|
||||
return False, False
|
||||
elif model_lower in ["deepseek-r1", "deepseek-reasoner"]:
|
||||
return True, False
|
||||
elif model_lower in ["deepseek-v3-search", "deepseek-chat-search"]:
|
||||
return False, True
|
||||
elif model_lower in ["deepseek-r1-search", "deepseek-reasoner-search"]:
|
||||
return True, True
|
||||
else:
|
||||
return None, None # 不支持的模型
|
||||
|
||||
|
||||
def cleanup_account(request: Request):
|
||||
"""清理账号资源(将账号放回队列)"""
|
||||
if getattr(request.state, "use_config_token", False) and hasattr(request.state, "account"):
|
||||
release_account(request.state.account)
|
||||
Reference in New Issue
Block a user