Spaces:
Running
Running
nacho commited on
Commit ·
5470e8a
1
Parent(s): 2526df1
chore: 删除未使用的 deepseek_api.py (272行死代码)
Browse files- README.md +0 -1
- deepseek_api.py +0 -271
README.md
CHANGED
|
@@ -145,7 +145,6 @@ curl http://localhost:5001/admin/stats -H "admin-key: admin"
|
|
| 145 |
ds2api-browser/
|
| 146 |
├── main.py # FastAPI 服务器(含管理界面)
|
| 147 |
├── deepseek_browser.py # CloakBrowser 自动化核心
|
| 148 |
-
├── deepseek_api.py # DeepSeek HTTP API 客户端
|
| 149 |
├── account_manager.py # 账号池管理
|
| 150 |
├── config.py # 配置管理
|
| 151 |
├── proxy.py # 多协议代理(Claude/Gemini/Ollama)
|
|
|
|
| 145 |
ds2api-browser/
|
| 146 |
├── main.py # FastAPI 服务器(含管理界面)
|
| 147 |
├── deepseek_browser.py # CloakBrowser 自动化核心
|
|
|
|
| 148 |
├── account_manager.py # 账号池管理
|
| 149 |
├── config.py # 配置管理
|
| 150 |
├── proxy.py # 多协议代理(Claude/Gemini/Ollama)
|
deepseek_api.py
DELETED
|
@@ -1,271 +0,0 @@
|
|
| 1 |
-
import asyncio
|
| 2 |
-
import hashlib
|
| 3 |
-
import json
|
| 4 |
-
import logging
|
| 5 |
-
import random
|
| 6 |
-
import time
|
| 7 |
-
import uuid
|
| 8 |
-
from typing import AsyncGenerator, Optional, Union
|
| 9 |
-
|
| 10 |
-
import httpx
|
| 11 |
-
|
| 12 |
-
logger = logging.getLogger(__name__)
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
class DeepSeekAPI:
|
| 16 |
-
LOGIN_URL = "https://chat.deepseek.com/api/v0/users/login"
|
| 17 |
-
CREATE_SESSION_URL = "https://chat.deepseek.com/api/v0/chat_session/create"
|
| 18 |
-
CREATE_POW_URL = "https://chat.deepseek.com/api/v0/chat/create_pow_challenge"
|
| 19 |
-
COMPLETION_URL = "https://chat.deepseek.com/api/v0/chat/completion"
|
| 20 |
-
DELETE_SESSION_URL = "https://chat.deepseek.com/api/v0/chat_session/delete"
|
| 21 |
-
|
| 22 |
-
def __init__(self, email: str, password: str, proxy: Optional[str] = None):
|
| 23 |
-
self.email = email
|
| 24 |
-
self.password = password
|
| 25 |
-
self.proxy = proxy
|
| 26 |
-
self._token: Optional[str] = None
|
| 27 |
-
self._device_id = str(uuid.uuid4())
|
| 28 |
-
self._client: Optional[httpx.AsyncClient] = None
|
| 29 |
-
|
| 30 |
-
async def _get_client(self) -> httpx.AsyncClient:
|
| 31 |
-
if self._client is None or self._client.is_closed:
|
| 32 |
-
self._client = httpx.AsyncClient(
|
| 33 |
-
proxy=self.proxy,
|
| 34 |
-
timeout=60.0,
|
| 35 |
-
follow_redirects=True,
|
| 36 |
-
)
|
| 37 |
-
return self._client
|
| 38 |
-
|
| 39 |
-
async def login(self) -> str:
|
| 40 |
-
client = await self._get_client()
|
| 41 |
-
|
| 42 |
-
payload = {
|
| 43 |
-
"email": self.email,
|
| 44 |
-
"password": self.password,
|
| 45 |
-
"device_id": self._device_id,
|
| 46 |
-
"os": "android",
|
| 47 |
-
}
|
| 48 |
-
|
| 49 |
-
headers = self._base_headers()
|
| 50 |
-
|
| 51 |
-
resp = await client.post(self.LOGIN_URL, json=payload, headers=headers, timeout=30)
|
| 52 |
-
data = resp.json()
|
| 53 |
-
|
| 54 |
-
code = data.get("code", -1)
|
| 55 |
-
if code != 0:
|
| 56 |
-
raise Exception(f"Login failed: {data.get('msg', 'Unknown')}")
|
| 57 |
-
|
| 58 |
-
biz_data = data.get("data", {})
|
| 59 |
-
biz_code = biz_data.get("biz_code", -1)
|
| 60 |
-
if biz_code != 0:
|
| 61 |
-
raise Exception(f"Login failed: {biz_data.get('biz_msg', 'Unknown')}")
|
| 62 |
-
|
| 63 |
-
user = biz_data.get("biz_data", {}).get("user", {})
|
| 64 |
-
self._token = user.get("token", "")
|
| 65 |
-
|
| 66 |
-
if not self._token:
|
| 67 |
-
raise Exception("No token received")
|
| 68 |
-
|
| 69 |
-
return self._token
|
| 70 |
-
|
| 71 |
-
async def create_session(self) -> str:
|
| 72 |
-
if not self._token:
|
| 73 |
-
await self.login()
|
| 74 |
-
|
| 75 |
-
client = await self._get_client()
|
| 76 |
-
headers = self._auth_headers()
|
| 77 |
-
|
| 78 |
-
resp = await client.post(
|
| 79 |
-
self.CREATE_SESSION_URL,
|
| 80 |
-
json={"agent": "chat"},
|
| 81 |
-
headers=headers,
|
| 82 |
-
timeout=30,
|
| 83 |
-
)
|
| 84 |
-
data = resp.json()
|
| 85 |
-
|
| 86 |
-
if data.get("code") != 0:
|
| 87 |
-
raise Exception(f"Create session failed: {data.get('msg')}")
|
| 88 |
-
|
| 89 |
-
biz_data = data.get("data", {}).get("biz_data", {})
|
| 90 |
-
|
| 91 |
-
if "chat_session" in biz_data:
|
| 92 |
-
session_id = biz_data["chat_session"].get("id", "")
|
| 93 |
-
else:
|
| 94 |
-
session_id = biz_data.get("id", "")
|
| 95 |
-
|
| 96 |
-
if not session_id:
|
| 97 |
-
raise Exception("No session ID received")
|
| 98 |
-
|
| 99 |
-
return session_id
|
| 100 |
-
|
| 101 |
-
async def get_pow(self, target_path: str = "/api/v0/chat/completion") -> dict:
|
| 102 |
-
client = await self._get_client()
|
| 103 |
-
headers = self._auth_headers()
|
| 104 |
-
|
| 105 |
-
resp = await client.post(
|
| 106 |
-
self.CREATE_POW_URL,
|
| 107 |
-
json={"target_path": target_path},
|
| 108 |
-
headers=headers,
|
| 109 |
-
timeout=30,
|
| 110 |
-
)
|
| 111 |
-
data = resp.json()
|
| 112 |
-
|
| 113 |
-
if data.get("code") != 0:
|
| 114 |
-
raise Exception(f"Get PoW failed: {data.get('msg')}")
|
| 115 |
-
|
| 116 |
-
return data.get("data", {}).get("biz_data", {}).get("challenge", {})
|
| 117 |
-
|
| 118 |
-
def _compute_pow(self, challenge: dict) -> str:
|
| 119 |
-
prefix = challenge.get("prefix", "")
|
| 120 |
-
target = challenge.get("target", "")
|
| 121 |
-
expire_at = challenge.get("expire_at", 0)
|
| 122 |
-
|
| 123 |
-
nonce = 0
|
| 124 |
-
while nonce < 10000000:
|
| 125 |
-
test = f"{prefix}{nonce}"
|
| 126 |
-
hash_val = hashlib.sha256(test.encode()).hexdigest()
|
| 127 |
-
# Compare hash against target lexicographically — this handles
|
| 128 |
-
# both all-zero targets and mixed targets like "000abc".
|
| 129 |
-
if hash_val <= target:
|
| 130 |
-
break
|
| 131 |
-
nonce += 1
|
| 132 |
-
|
| 133 |
-
return json.dumps({
|
| 134 |
-
"prefix": prefix,
|
| 135 |
-
"nonce": nonce,
|
| 136 |
-
"expire_at": expire_at,
|
| 137 |
-
"target": target,
|
| 138 |
-
})
|
| 139 |
-
|
| 140 |
-
async def send_message(
|
| 141 |
-
self,
|
| 142 |
-
prompt: str,
|
| 143 |
-
model: str = "deepseek-chat",
|
| 144 |
-
stream: bool = False,
|
| 145 |
-
timeout: int = 120,
|
| 146 |
-
) -> Union[str, AsyncGenerator[str, None]]:
|
| 147 |
-
"""Send a message and return a response.
|
| 148 |
-
|
| 149 |
-
Returns:
|
| 150 |
-
str when stream=False, AsyncGenerator[str, None] when stream=True.
|
| 151 |
-
"""
|
| 152 |
-
if not self._token:
|
| 153 |
-
await self.login()
|
| 154 |
-
|
| 155 |
-
session_id = await self.create_session()
|
| 156 |
-
|
| 157 |
-
pow_challenge = await self.get_pow()
|
| 158 |
-
pow_header = self._compute_pow(pow_challenge)
|
| 159 |
-
|
| 160 |
-
client = await self._get_client()
|
| 161 |
-
headers = self._auth_headers()
|
| 162 |
-
headers["x-ds-pow-response"] = pow_header
|
| 163 |
-
|
| 164 |
-
payload = {
|
| 165 |
-
"chat_session_id": session_id,
|
| 166 |
-
"parent_message_id": None,
|
| 167 |
-
"prompt": prompt,
|
| 168 |
-
"ref_file_ids": [],
|
| 169 |
-
"thinking_enabled": True,
|
| 170 |
-
"search_enabled": "search" in model.lower(),
|
| 171 |
-
}
|
| 172 |
-
|
| 173 |
-
if stream:
|
| 174 |
-
return self._stream_completion(client, headers, payload, timeout)
|
| 175 |
-
else:
|
| 176 |
-
return await self._sync_completion(client, headers, payload, timeout)
|
| 177 |
-
|
| 178 |
-
async def _sync_completion(
|
| 179 |
-
self,
|
| 180 |
-
client: httpx.AsyncClient,
|
| 181 |
-
headers: dict,
|
| 182 |
-
payload: dict,
|
| 183 |
-
timeout: int,
|
| 184 |
-
) -> str:
|
| 185 |
-
resp = await client.post(
|
| 186 |
-
self.COMPLETION_URL,
|
| 187 |
-
json=payload,
|
| 188 |
-
headers=headers,
|
| 189 |
-
timeout=timeout,
|
| 190 |
-
)
|
| 191 |
-
|
| 192 |
-
# 处理 SSE 响应
|
| 193 |
-
full_text = ""
|
| 194 |
-
for line in resp.text.split("\n"):
|
| 195 |
-
if line.startswith("data:"):
|
| 196 |
-
data_str = line[5:].strip()
|
| 197 |
-
if data_str == "[DONE]":
|
| 198 |
-
continue
|
| 199 |
-
try:
|
| 200 |
-
data = json.loads(data_str)
|
| 201 |
-
msg = data.get("message", {})
|
| 202 |
-
content = msg.get("content", "")
|
| 203 |
-
if content:
|
| 204 |
-
full_text += content
|
| 205 |
-
except json.JSONDecodeError:
|
| 206 |
-
continue
|
| 207 |
-
|
| 208 |
-
return full_text
|
| 209 |
-
|
| 210 |
-
async def _stream_completion(
|
| 211 |
-
self,
|
| 212 |
-
client: httpx.AsyncClient,
|
| 213 |
-
headers: dict,
|
| 214 |
-
payload: dict,
|
| 215 |
-
timeout: int,
|
| 216 |
-
) -> AsyncGenerator[str, None]:
|
| 217 |
-
async with client.stream(
|
| 218 |
-
"POST",
|
| 219 |
-
self.COMPLETION_URL,
|
| 220 |
-
json=payload,
|
| 221 |
-
headers=headers,
|
| 222 |
-
timeout=timeout,
|
| 223 |
-
) as resp:
|
| 224 |
-
async for line in resp.aiter_lines():
|
| 225 |
-
if line.startswith("data:"):
|
| 226 |
-
data_str = line[5:].strip()
|
| 227 |
-
if data_str == "[DONE]":
|
| 228 |
-
return
|
| 229 |
-
try:
|
| 230 |
-
data = json.loads(data_str)
|
| 231 |
-
msg = data.get("message", {})
|
| 232 |
-
content = msg.get("content", "")
|
| 233 |
-
if content:
|
| 234 |
-
yield content
|
| 235 |
-
except json.JSONDecodeError:
|
| 236 |
-
continue
|
| 237 |
-
|
| 238 |
-
async def delete_session(self, session_id: str):
|
| 239 |
-
if not self._token:
|
| 240 |
-
return
|
| 241 |
-
|
| 242 |
-
client = await self._get_client()
|
| 243 |
-
headers = self._auth_headers()
|
| 244 |
-
|
| 245 |
-
await client.post(
|
| 246 |
-
self.DELETE_SESSION_URL,
|
| 247 |
-
json={"chat_session_id": session_id},
|
| 248 |
-
headers=headers,
|
| 249 |
-
timeout=30,
|
| 250 |
-
)
|
| 251 |
-
|
| 252 |
-
def _base_headers(self) -> dict:
|
| 253 |
-
return {
|
| 254 |
-
"Content-Type": "application/json",
|
| 255 |
-
"User-Agent": "DeepSeek/3.2.1 Android/35",
|
| 256 |
-
"x-client-platform": "android",
|
| 257 |
-
"x-client-version": "3.2.1",
|
| 258 |
-
"x-client-locale": "zh_CN",
|
| 259 |
-
"Accept-Encoding": "gzip, deflate, br",
|
| 260 |
-
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
|
| 261 |
-
}
|
| 262 |
-
|
| 263 |
-
def _auth_headers(self) -> dict:
|
| 264 |
-
headers = self._base_headers()
|
| 265 |
-
if self._token:
|
| 266 |
-
headers["authorization"] = f"Bearer {self._token}"
|
| 267 |
-
return headers
|
| 268 |
-
|
| 269 |
-
async def close(self):
|
| 270 |
-
if self._client:
|
| 271 |
-
await self._client.aclose()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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