Spaces:
Running
Running
nacho commited on
Commit ·
466f6e2
1
Parent(s): 3a73b53
fix: 全面代码审查修复
Browse files- 修复 send_message 返回类型注解 (Union[str, AsyncGenerator])
- 修复 PoW 计算逻辑,使用 hash <= target 比较
- 修复 acquire() 跳过禁言账号
- 修复 delete_chat 中 .first 后 .count() 误用
- 修复 stream_message 结束后缺少 delete_chat 清理
- 修复 readyz 返回格式,避免嵌套 accounts 列表
- 移除 start.py 中硬编码凭据,改用 .env 配置
- proxy.py 密钥改为从环境变量读取
- 添加 httpx 到 requirements.txt
- 全局替换 print 为结构化 logging
- 动态生成邮箱脱敏,替代硬编码 skip_phrases
- bare except 改为 except Exception
- README 对齐实际代码(模型列表、管理界面 URL、文件结构)
- 添加 .env.example 模板
- 添加 config 格式注释
- .env.example +18 -0
- README.md +10 -12
- account_manager.py +9 -6
- config.py +2 -0
- deepseek_api.py +13 -3
- deepseek_browser.py +56 -23
- main.py +29 -5
- proxy.py +30 -16
- requirements.txt +1 -0
- start.py +5 -9
.env.example
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# DS2API Browser 环境配置
|
| 2 |
+
# 复制此文件为 .env 并填入实际值
|
| 3 |
+
|
| 4 |
+
# 多账号配置,用分号分隔
|
| 5 |
+
# 格式: email:password[:name[:proxy]]
|
| 6 |
+
DS2API_ACCOUNTS=user1@gmail.com:password1:账号1;user2@gmail.com:password2:账号2
|
| 7 |
+
|
| 8 |
+
# API 密钥(逗号分隔)
|
| 9 |
+
DS2API_KEYS=sk-test123456
|
| 10 |
+
|
| 11 |
+
# 管理员密钥
|
| 12 |
+
DS2API_ADMIN_KEY=admin
|
| 13 |
+
|
| 14 |
+
# 服务端口
|
| 15 |
+
DS2API_PORT=5001
|
| 16 |
+
|
| 17 |
+
# 无头浏览器模式
|
| 18 |
+
DS2API_HEADLESS=true
|
README.md
CHANGED
|
@@ -62,7 +62,7 @@ nohup python main.py > /tmp/ds2api-browser.log 2>&1 &
|
|
| 62 |
|
| 63 |
## Web 管理界面
|
| 64 |
|
| 65 |
-
访问 `http://localhost:5001/
|
| 66 |
|
| 67 |
- 测试 API 请求
|
| 68 |
- 导入账号(支持批量)
|
|
@@ -77,7 +77,7 @@ curl http://localhost:5001/v1/chat/completions \
|
|
| 77 |
-H "Authorization: Bearer sk-test123456" \
|
| 78 |
-H "Content-Type: application/json" \
|
| 79 |
-d '{
|
| 80 |
-
"model": "deepseek-
|
| 81 |
"messages": [{"role": "user", "content": "Hello!"}]
|
| 82 |
}'
|
| 83 |
```
|
|
@@ -89,7 +89,7 @@ curl http://localhost:5001/v1/chat/completions \
|
|
| 89 |
-H "Authorization: Bearer sk-test123456" \
|
| 90 |
-H "Content-Type: application/json" \
|
| 91 |
-d '{
|
| 92 |
-
"model": "deepseek-
|
| 93 |
"messages": [{"role": "user", "content": "Hello!"}],
|
| 94 |
"stream": true
|
| 95 |
}'
|
|
@@ -106,7 +106,7 @@ client = OpenAI(
|
|
| 106 |
)
|
| 107 |
|
| 108 |
response = client.chat.completions.create(
|
| 109 |
-
model="deepseek-
|
| 110 |
messages=[{"role": "user", "content": "Hello!"}]
|
| 111 |
)
|
| 112 |
print(response.choices[0].message.content)
|
|
@@ -116,12 +116,8 @@ print(response.choices[0].message.content)
|
|
| 116 |
|
| 117 |
| 模型 ID | 说明 |
|
| 118 |
|---------|------|
|
| 119 |
-
| deepseek-
|
| 120 |
-
| deepseek-
|
| 121 |
-
| deepseek-v4-flash-search | 快速 + 搜索 |
|
| 122 |
-
| deepseek-v4-pro-search | 专家 + 搜索 |
|
| 123 |
-
| deepseek-chat | 兼容原版 DS2API |
|
| 124 |
-
| deepseek-reasoner | 推理模式 |
|
| 125 |
|
| 126 |
## 健康检查
|
| 127 |
|
|
@@ -147,13 +143,15 @@ curl http://localhost:5001/admin/stats -H "admin-key: admin"
|
|
| 147 |
|
| 148 |
```
|
| 149 |
ds2api-browser/
|
| 150 |
-
├── main.py # FastAPI 服务器
|
| 151 |
├── deepseek_browser.py # CloakBrowser 自动化核心
|
|
|
|
| 152 |
├── account_manager.py # 账号池管理
|
| 153 |
├── config.py # 配置管理
|
|
|
|
| 154 |
├── start.py # 快速启动脚本
|
| 155 |
├── run.py # 运行入口
|
| 156 |
-
├──
|
| 157 |
├── requirements.txt # 依赖列表
|
| 158 |
└── README.md # 本文档
|
| 159 |
```
|
|
|
|
| 62 |
|
| 63 |
## Web 管理界面
|
| 64 |
|
| 65 |
+
访问 `http://localhost:5001/` 可以:
|
| 66 |
|
| 67 |
- 测试 API 请求
|
| 68 |
- 导入账号(支持批量)
|
|
|
|
| 77 |
-H "Authorization: Bearer sk-test123456" \
|
| 78 |
-H "Content-Type: application/json" \
|
| 79 |
-d '{
|
| 80 |
+
"model": "deepseek-flash",
|
| 81 |
"messages": [{"role": "user", "content": "Hello!"}]
|
| 82 |
}'
|
| 83 |
```
|
|
|
|
| 89 |
-H "Authorization: Bearer sk-test123456" \
|
| 90 |
-H "Content-Type: application/json" \
|
| 91 |
-d '{
|
| 92 |
+
"model": "deepseek-flash",
|
| 93 |
"messages": [{"role": "user", "content": "Hello!"}],
|
| 94 |
"stream": true
|
| 95 |
}'
|
|
|
|
| 106 |
)
|
| 107 |
|
| 108 |
response = client.chat.completions.create(
|
| 109 |
+
model="deepseek-flash",
|
| 110 |
messages=[{"role": "user", "content": "Hello!"}]
|
| 111 |
)
|
| 112 |
print(response.choices[0].message.content)
|
|
|
|
| 116 |
|
| 117 |
| 模型 ID | 说明 |
|
| 118 |
|---------|------|
|
| 119 |
+
| deepseek-flash | 快速模式(默认) |
|
| 120 |
+
| deepseek-pro | 专家模式(深度思考) |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
## 健康检查
|
| 123 |
|
|
|
|
| 143 |
|
| 144 |
```
|
| 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)
|
| 152 |
├── start.py # 快速启动脚本
|
| 153 |
├── run.py # 运行入口
|
| 154 |
+
├── .env.example # 环境变量模板
|
| 155 |
├── requirements.txt # 依赖列表
|
| 156 |
└── README.md # 本文档
|
| 157 |
```
|
account_manager.py
CHANGED
|
@@ -1,10 +1,13 @@
|
|
| 1 |
import asyncio
|
|
|
|
| 2 |
from collections import deque
|
| 3 |
from dataclasses import dataclass, field
|
| 4 |
from typing import Dict, Optional
|
| 5 |
|
| 6 |
from deepseek_browser import DeepSeekBrowser
|
| 7 |
|
|
|
|
|
|
|
| 8 |
|
| 9 |
@dataclass
|
| 10 |
class Account:
|
|
@@ -38,7 +41,7 @@ class AccountManager:
|
|
| 38 |
async def acquire(self) -> Account:
|
| 39 |
async with self._lock:
|
| 40 |
for account in self.accounts.values():
|
| 41 |
-
if not account.in_use and account.error_count < 3:
|
| 42 |
account.in_use = True
|
| 43 |
return account
|
| 44 |
|
|
@@ -53,7 +56,7 @@ class AccountManager:
|
|
| 53 |
|
| 54 |
async with self._lock:
|
| 55 |
for account in self.accounts.values():
|
| 56 |
-
if not account.in_use and account.error_count < 3:
|
| 57 |
account.in_use = True
|
| 58 |
return account
|
| 59 |
|
|
@@ -92,7 +95,7 @@ class AccountManager:
|
|
| 92 |
account.muted_until = account.browser.muted_until()
|
| 93 |
return account.browser
|
| 94 |
except Exception as e:
|
| 95 |
-
|
| 96 |
await self.close_browser(account)
|
| 97 |
raise
|
| 98 |
|
|
@@ -107,15 +110,15 @@ class AccountManager:
|
|
| 107 |
if account.browser:
|
| 108 |
try:
|
| 109 |
await account.browser.close()
|
| 110 |
-
except:
|
| 111 |
-
|
| 112 |
account.browser = None
|
| 113 |
account.logged_in = False
|
| 114 |
|
| 115 |
def get_stats(self) -> Dict:
|
| 116 |
total = len(self.accounts)
|
| 117 |
in_use = sum(1 for a in self.accounts.values() if a.in_use)
|
| 118 |
-
available = sum(1 for a in self.accounts.values() if not a.in_use and a.error_count < 3)
|
| 119 |
logged_in = sum(1 for a in self.accounts.values() if a.logged_in)
|
| 120 |
muted = sum(1 for a in self.accounts.values() if a.is_muted)
|
| 121 |
accounts_list = [
|
|
|
|
| 1 |
import asyncio
|
| 2 |
+
import logging
|
| 3 |
from collections import deque
|
| 4 |
from dataclasses import dataclass, field
|
| 5 |
from typing import Dict, Optional
|
| 6 |
|
| 7 |
from deepseek_browser import DeepSeekBrowser
|
| 8 |
|
| 9 |
+
logger = logging.getLogger(__name__)
|
| 10 |
+
|
| 11 |
|
| 12 |
@dataclass
|
| 13 |
class Account:
|
|
|
|
| 41 |
async def acquire(self) -> Account:
|
| 42 |
async with self._lock:
|
| 43 |
for account in self.accounts.values():
|
| 44 |
+
if not account.in_use and account.error_count < 3 and not account.is_muted:
|
| 45 |
account.in_use = True
|
| 46 |
return account
|
| 47 |
|
|
|
|
| 56 |
|
| 57 |
async with self._lock:
|
| 58 |
for account in self.accounts.values():
|
| 59 |
+
if not account.in_use and account.error_count < 3 and not account.is_muted:
|
| 60 |
account.in_use = True
|
| 61 |
return account
|
| 62 |
|
|
|
|
| 95 |
account.muted_until = account.browser.muted_until()
|
| 96 |
return account.browser
|
| 97 |
except Exception as e:
|
| 98 |
+
logger.error("Error creating browser for %s: %s", account.email, e)
|
| 99 |
await self.close_browser(account)
|
| 100 |
raise
|
| 101 |
|
|
|
|
| 110 |
if account.browser:
|
| 111 |
try:
|
| 112 |
await account.browser.close()
|
| 113 |
+
except Exception as e:
|
| 114 |
+
logger.debug("Error closing browser for %s: %s", account.email, e)
|
| 115 |
account.browser = None
|
| 116 |
account.logged_in = False
|
| 117 |
|
| 118 |
def get_stats(self) -> Dict:
|
| 119 |
total = len(self.accounts)
|
| 120 |
in_use = sum(1 for a in self.accounts.values() if a.in_use)
|
| 121 |
+
available = sum(1 for a in self.accounts.values() if not a.in_use and a.error_count < 3 and not a.is_muted)
|
| 122 |
logged_in = sum(1 for a in self.accounts.values() if a.logged_in)
|
| 123 |
muted = sum(1 for a in self.accounts.values() if a.is_muted)
|
| 124 |
accounts_list = [
|
config.py
CHANGED
|
@@ -40,9 +40,11 @@ class Config:
|
|
| 40 |
def from_env(cls) -> "Config":
|
| 41 |
accounts = []
|
| 42 |
|
|
|
|
| 43 |
account_str = os.getenv("DS2API_ACCOUNTS", "")
|
| 44 |
if account_str:
|
| 45 |
for acc in account_str.split(";"):
|
|
|
|
| 46 |
parts = acc.split(":", 3)
|
| 47 |
if len(parts) >= 2:
|
| 48 |
accounts.append(AccountConfig(
|
|
|
|
| 40 |
def from_env(cls) -> "Config":
|
| 41 |
accounts = []
|
| 42 |
|
| 43 |
+
# Format: email:password[:name[:proxy]] separated by semicolons
|
| 44 |
account_str = os.getenv("DS2API_ACCOUNTS", "")
|
| 45 |
if account_str:
|
| 46 |
for acc in account_str.split(";"):
|
| 47 |
+
# maxsplit=3 yields at most 4 parts: email, password, name, proxy
|
| 48 |
parts = acc.split(":", 3)
|
| 49 |
if len(parts) >= 2:
|
| 50 |
accounts.append(AccountConfig(
|
deepseek_api.py
CHANGED
|
@@ -1,13 +1,16 @@
|
|
| 1 |
import asyncio
|
| 2 |
import hashlib
|
| 3 |
import json
|
|
|
|
| 4 |
import random
|
| 5 |
import time
|
| 6 |
import uuid
|
| 7 |
-
from typing import AsyncGenerator, Optional
|
| 8 |
|
| 9 |
import httpx
|
| 10 |
|
|
|
|
|
|
|
| 11 |
|
| 12 |
class DeepSeekAPI:
|
| 13 |
LOGIN_URL = "https://chat.deepseek.com/api/v0/users/login"
|
|
@@ -121,7 +124,9 @@ class DeepSeekAPI:
|
|
| 121 |
while nonce < 10000000:
|
| 122 |
test = f"{prefix}{nonce}"
|
| 123 |
hash_val = hashlib.sha256(test.encode()).hexdigest()
|
| 124 |
-
|
|
|
|
|
|
|
| 125 |
break
|
| 126 |
nonce += 1
|
| 127 |
|
|
@@ -138,7 +143,12 @@ class DeepSeekAPI:
|
|
| 138 |
model: str = "deepseek-chat",
|
| 139 |
stream: bool = False,
|
| 140 |
timeout: int = 120,
|
| 141 |
-
) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
if not self._token:
|
| 143 |
await self.login()
|
| 144 |
|
|
|
|
| 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"
|
|
|
|
| 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 |
|
|
|
|
| 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 |
|
deepseek_browser.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
import asyncio
|
|
|
|
| 2 |
import random
|
| 3 |
import time
|
| 4 |
from pathlib import Path
|
|
@@ -6,6 +7,8 @@ from typing import AsyncGenerator, Optional
|
|
| 6 |
|
| 7 |
from cloakbrowser import launch_persistent_context_async
|
| 8 |
|
|
|
|
|
|
|
| 9 |
|
| 10 |
class DeepSeekBrowser:
|
| 11 |
DEEPSEEK_URL = "https://chat.deepseek.com"
|
|
@@ -30,6 +33,19 @@ class DeepSeekBrowser:
|
|
| 30 |
self._logged_in = False
|
| 31 |
self._ready = False
|
| 32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
async def start(self):
|
| 34 |
self.profile_dir.mkdir(parents=True, exist_ok=True)
|
| 35 |
|
|
@@ -79,7 +95,7 @@ class DeepSeekBrowser:
|
|
| 79 |
self._is_muted = muted
|
| 80 |
self._muted_until = until
|
| 81 |
if muted:
|
| 82 |
-
|
| 83 |
except Exception:
|
| 84 |
self._is_muted = False
|
| 85 |
self._muted_until = ""
|
|
@@ -91,7 +107,7 @@ class DeepSeekBrowser:
|
|
| 91 |
return getattr(self, '_muted_until', "")
|
| 92 |
|
| 93 |
async def _auto_login(self):
|
| 94 |
-
|
| 95 |
|
| 96 |
try:
|
| 97 |
email_input = self.page.locator('input[placeholder*="邮箱"], input[placeholder*="手机"], input[placeholder*="Email"], input[placeholder*="email"], input[type="text"]').first
|
|
@@ -102,10 +118,10 @@ class DeepSeekBrowser:
|
|
| 102 |
# Take screenshot to debug
|
| 103 |
try:
|
| 104 |
await self.page.screenshot(path=f"/tmp/login_fail_{self.email.replace('@','_at_')}.png")
|
| 105 |
-
|
| 106 |
except Exception:
|
| 107 |
pass
|
| 108 |
-
|
| 109 |
raise
|
| 110 |
|
| 111 |
try:
|
|
@@ -114,7 +130,7 @@ class DeepSeekBrowser:
|
|
| 114 |
await password_input.fill(self.password)
|
| 115 |
await asyncio.sleep(0.5)
|
| 116 |
except Exception as e:
|
| 117 |
-
|
| 118 |
raise
|
| 119 |
|
| 120 |
try:
|
|
@@ -122,14 +138,14 @@ class DeepSeekBrowser:
|
|
| 122 |
await login_button.click()
|
| 123 |
await asyncio.sleep(3)
|
| 124 |
except Exception as e:
|
| 125 |
-
|
| 126 |
raise
|
| 127 |
|
| 128 |
try:
|
| 129 |
await self.page.wait_for_selector('textarea', timeout=30000)
|
| 130 |
self._logged_in = True
|
| 131 |
self._ready = True
|
| 132 |
-
|
| 133 |
except Exception:
|
| 134 |
raise Exception("Login failed")
|
| 135 |
|
|
@@ -137,13 +153,23 @@ class DeepSeekBrowser:
|
|
| 137 |
delay = random.uniform(min_ms, max_ms) / 1000
|
| 138 |
await asyncio.sleep(delay)
|
| 139 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
async def new_chat(self):
|
| 141 |
try:
|
| 142 |
await self.page.goto(self.DEEPSEEK_URL, timeout=30000)
|
| 143 |
await asyncio.sleep(2)
|
| 144 |
await self.page.wait_for_selector('textarea', timeout=15000)
|
| 145 |
except Exception as e:
|
| 146 |
-
|
| 147 |
raise
|
| 148 |
|
| 149 |
async def delete_chat(self):
|
|
@@ -151,25 +177,25 @@ class DeepSeekBrowser:
|
|
| 151 |
# Find the sidebar and active conversation
|
| 152 |
chat_list = self.page.locator(
|
| 153 |
'nav, aside, [class*="sidebar"], [class*="Sidebar"], div:has-text("开启新对话")'
|
| 154 |
-
)
|
| 155 |
chat_list_count = await chat_list.count()
|
| 156 |
if chat_list_count == 0:
|
| 157 |
-
|
| 158 |
return
|
| 159 |
|
| 160 |
-
active_item = chat_list.locator(
|
| 161 |
'[class*="active"], [class*="selected"], [class*="current"]'
|
| 162 |
).first
|
| 163 |
active_count = await active_item.count()
|
| 164 |
if active_count == 0:
|
| 165 |
# No active item yet (first chat), skip deletion
|
| 166 |
-
|
| 167 |
return
|
| 168 |
|
| 169 |
# Get bounding box and click near right edge where "..." should be
|
| 170 |
box = await active_item.bounding_box()
|
| 171 |
if not box:
|
| 172 |
-
|
| 173 |
return
|
| 174 |
|
| 175 |
# Instead of position-based click, find the "..." element in DOM
|
|
@@ -210,7 +236,7 @@ class DeepSeekBrowser:
|
|
| 210 |
}
|
| 211 |
return 'no-icon';
|
| 212 |
}""")
|
| 213 |
-
|
| 214 |
await asyncio.sleep(0.5)
|
| 215 |
|
| 216 |
# Search for "删除" or "Delete" anywhere on page
|
|
@@ -220,7 +246,7 @@ class DeepSeekBrowser:
|
|
| 220 |
delete_count = await delete_btn.count()
|
| 221 |
|
| 222 |
if delete_count == 0:
|
| 223 |
-
|
| 224 |
return
|
| 225 |
|
| 226 |
await delete_btn.click()
|
|
@@ -234,12 +260,12 @@ class DeepSeekBrowser:
|
|
| 234 |
if await confirm_btn.count() > 0:
|
| 235 |
await confirm_btn.click()
|
| 236 |
await asyncio.sleep(1)
|
| 237 |
-
|
| 238 |
else:
|
| 239 |
-
|
| 240 |
|
| 241 |
except Exception as e:
|
| 242 |
-
|
| 243 |
|
| 244 |
async def switch_model(self, model: str):
|
| 245 |
try:
|
|
@@ -280,7 +306,7 @@ class DeepSeekBrowser:
|
|
| 280 |
|
| 281 |
return response
|
| 282 |
except Exception as e:
|
| 283 |
-
|
| 284 |
raise
|
| 285 |
|
| 286 |
async def _wait_for_response(self, timeout: int, prompt: str = "") -> str:
|
|
@@ -291,7 +317,7 @@ class DeepSeekBrowser:
|
|
| 291 |
last_text = ""
|
| 292 |
stable_count = 0
|
| 293 |
|
| 294 |
-
skip_phrases =
|
| 295 |
|
| 296 |
while time.time() < deadline:
|
| 297 |
try:
|
|
@@ -361,7 +387,7 @@ class DeepSeekBrowser:
|
|
| 361 |
last_text = ""
|
| 362 |
stable_count = 0
|
| 363 |
|
| 364 |
-
skip_phrases =
|
| 365 |
|
| 366 |
await asyncio.sleep(3)
|
| 367 |
|
|
@@ -403,14 +429,21 @@ class DeepSeekBrowser:
|
|
| 403 |
stable_count += 1
|
| 404 |
|
| 405 |
if stable_count >= 3:
|
| 406 |
-
|
| 407 |
|
| 408 |
except Exception:
|
| 409 |
pass
|
| 410 |
|
| 411 |
await asyncio.sleep(0.3)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 412 |
except Exception as e:
|
| 413 |
-
|
| 414 |
raise
|
| 415 |
|
| 416 |
async def close(self):
|
|
|
|
| 1 |
import asyncio
|
| 2 |
+
import logging
|
| 3 |
import random
|
| 4 |
import time
|
| 5 |
from pathlib import Path
|
|
|
|
| 7 |
|
| 8 |
from cloakbrowser import launch_persistent_context_async
|
| 9 |
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
|
| 13 |
class DeepSeekBrowser:
|
| 14 |
DEEPSEEK_URL = "https://chat.deepseek.com"
|
|
|
|
| 33 |
self._logged_in = False
|
| 34 |
self._ready = False
|
| 35 |
|
| 36 |
+
def _mask_email(self) -> str:
|
| 37 |
+
"""Generate a masked version of the email for skip_phrases filtering."""
|
| 38 |
+
parts = self.email.split("@")
|
| 39 |
+
if len(parts) == 2:
|
| 40 |
+
local = parts[0]
|
| 41 |
+
domain = parts[1]
|
| 42 |
+
if len(local) > 4:
|
| 43 |
+
masked = local[:4] + "*" * (len(local) - 4)
|
| 44 |
+
else:
|
| 45 |
+
masked = local[0] + "*" * (len(local) - 1)
|
| 46 |
+
return f"{masked}@{domain}"
|
| 47 |
+
return self.email
|
| 48 |
+
|
| 49 |
async def start(self):
|
| 50 |
self.profile_dir.mkdir(parents=True, exist_ok=True)
|
| 51 |
|
|
|
|
| 95 |
self._is_muted = muted
|
| 96 |
self._muted_until = until
|
| 97 |
if muted:
|
| 98 |
+
logger.warning("[mute] %s is muted until %s", self.email, until)
|
| 99 |
except Exception:
|
| 100 |
self._is_muted = False
|
| 101 |
self._muted_until = ""
|
|
|
|
| 107 |
return getattr(self, '_muted_until', "")
|
| 108 |
|
| 109 |
async def _auto_login(self):
|
| 110 |
+
logger.info("Logging in as %s...", self.email)
|
| 111 |
|
| 112 |
try:
|
| 113 |
email_input = self.page.locator('input[placeholder*="邮箱"], input[placeholder*="手机"], input[placeholder*="Email"], input[placeholder*="email"], input[type="text"]').first
|
|
|
|
| 118 |
# Take screenshot to debug
|
| 119 |
try:
|
| 120 |
await self.page.screenshot(path=f"/tmp/login_fail_{self.email.replace('@','_at_')}.png")
|
| 121 |
+
logger.error("Screenshot saved to /tmp/login_fail_%s.png", self.email.replace('@', '_at_'))
|
| 122 |
except Exception:
|
| 123 |
pass
|
| 124 |
+
logger.error("Email input error: %s", e)
|
| 125 |
raise
|
| 126 |
|
| 127 |
try:
|
|
|
|
| 130 |
await password_input.fill(self.password)
|
| 131 |
await asyncio.sleep(0.5)
|
| 132 |
except Exception as e:
|
| 133 |
+
logger.error("Password input error: %s", e)
|
| 134 |
raise
|
| 135 |
|
| 136 |
try:
|
|
|
|
| 138 |
await login_button.click()
|
| 139 |
await asyncio.sleep(3)
|
| 140 |
except Exception as e:
|
| 141 |
+
logger.error("Login button error: %s", e)
|
| 142 |
raise
|
| 143 |
|
| 144 |
try:
|
| 145 |
await self.page.wait_for_selector('textarea', timeout=30000)
|
| 146 |
self._logged_in = True
|
| 147 |
self._ready = True
|
| 148 |
+
logger.info("Login successful!")
|
| 149 |
except Exception:
|
| 150 |
raise Exception("Login failed")
|
| 151 |
|
|
|
|
| 153 |
delay = random.uniform(min_ms, max_ms) / 1000
|
| 154 |
await asyncio.sleep(delay)
|
| 155 |
|
| 156 |
+
def _get_skip_phrases(self) -> list:
|
| 157 |
+
"""Build skip phrases list, dynamically including masked email."""
|
| 158 |
+
phrases = [
|
| 159 |
+
'深度思考', '智能搜索', '快速模式', '专家模式',
|
| 160 |
+
'内容由 AI 生成', '开启新对话', '暂无历史对话', '今天',
|
| 161 |
+
]
|
| 162 |
+
masked = self._mask_email()
|
| 163 |
+
phrases.append(masked)
|
| 164 |
+
return phrases
|
| 165 |
+
|
| 166 |
async def new_chat(self):
|
| 167 |
try:
|
| 168 |
await self.page.goto(self.DEEPSEEK_URL, timeout=30000)
|
| 169 |
await asyncio.sleep(2)
|
| 170 |
await self.page.wait_for_selector('textarea', timeout=15000)
|
| 171 |
except Exception as e:
|
| 172 |
+
logger.error("New chat error: %s", e)
|
| 173 |
raise
|
| 174 |
|
| 175 |
async def delete_chat(self):
|
|
|
|
| 177 |
# Find the sidebar and active conversation
|
| 178 |
chat_list = self.page.locator(
|
| 179 |
'nav, aside, [class*="sidebar"], [class*="Sidebar"], div:has-text("开启新对话")'
|
| 180 |
+
)
|
| 181 |
chat_list_count = await chat_list.count()
|
| 182 |
if chat_list_count == 0:
|
| 183 |
+
logger.debug("[delete_chat] no sidebar")
|
| 184 |
return
|
| 185 |
|
| 186 |
+
active_item = chat_list.first.locator(
|
| 187 |
'[class*="active"], [class*="selected"], [class*="current"]'
|
| 188 |
).first
|
| 189 |
active_count = await active_item.count()
|
| 190 |
if active_count == 0:
|
| 191 |
# No active item yet (first chat), skip deletion
|
| 192 |
+
logger.debug("[delete_chat] no active item, skipping")
|
| 193 |
return
|
| 194 |
|
| 195 |
# Get bounding box and click near right edge where "..." should be
|
| 196 |
box = await active_item.bounding_box()
|
| 197 |
if not box:
|
| 198 |
+
logger.debug("[delete_chat] no bbox")
|
| 199 |
return
|
| 200 |
|
| 201 |
# Instead of position-based click, find the "..." element in DOM
|
|
|
|
| 236 |
}
|
| 237 |
return 'no-icon';
|
| 238 |
}""")
|
| 239 |
+
logger.debug("[delete_chat] icon click: %s", click_result)
|
| 240 |
await asyncio.sleep(0.5)
|
| 241 |
|
| 242 |
# Search for "删除" or "Delete" anywhere on page
|
|
|
|
| 246 |
delete_count = await delete_btn.count()
|
| 247 |
|
| 248 |
if delete_count == 0:
|
| 249 |
+
logger.debug("[delete_chat] no delete option found")
|
| 250 |
return
|
| 251 |
|
| 252 |
await delete_btn.click()
|
|
|
|
| 260 |
if await confirm_btn.count() > 0:
|
| 261 |
await confirm_btn.click()
|
| 262 |
await asyncio.sleep(1)
|
| 263 |
+
logger.debug("[delete_chat] done!")
|
| 264 |
else:
|
| 265 |
+
logger.debug("[delete_chat] no confirm btn")
|
| 266 |
|
| 267 |
except Exception as e:
|
| 268 |
+
logger.warning("[delete_chat] error: %s", e)
|
| 269 |
|
| 270 |
async def switch_model(self, model: str):
|
| 271 |
try:
|
|
|
|
| 306 |
|
| 307 |
return response
|
| 308 |
except Exception as e:
|
| 309 |
+
logger.error("Send message error: %s", e)
|
| 310 |
raise
|
| 311 |
|
| 312 |
async def _wait_for_response(self, timeout: int, prompt: str = "") -> str:
|
|
|
|
| 317 |
last_text = ""
|
| 318 |
stable_count = 0
|
| 319 |
|
| 320 |
+
skip_phrases = self._get_skip_phrases()
|
| 321 |
|
| 322 |
while time.time() < deadline:
|
| 323 |
try:
|
|
|
|
| 387 |
last_text = ""
|
| 388 |
stable_count = 0
|
| 389 |
|
| 390 |
+
skip_phrases = self._get_skip_phrases()
|
| 391 |
|
| 392 |
await asyncio.sleep(3)
|
| 393 |
|
|
|
|
| 429 |
stable_count += 1
|
| 430 |
|
| 431 |
if stable_count >= 3:
|
| 432 |
+
break
|
| 433 |
|
| 434 |
except Exception:
|
| 435 |
pass
|
| 436 |
|
| 437 |
await asyncio.sleep(0.3)
|
| 438 |
+
|
| 439 |
+
# Clean up: delete the chat after streaming is done (#17)
|
| 440 |
+
try:
|
| 441 |
+
await self.delete_chat()
|
| 442 |
+
except Exception as e:
|
| 443 |
+
logger.warning("[stream_message] delete_chat cleanup error: %s", e)
|
| 444 |
+
|
| 445 |
except Exception as e:
|
| 446 |
+
logger.error("Stream message error: %s", e)
|
| 447 |
raise
|
| 448 |
|
| 449 |
async def close(self):
|
main.py
CHANGED
|
@@ -1,11 +1,18 @@
|
|
| 1 |
import asyncio
|
| 2 |
import json
|
|
|
|
| 3 |
import os
|
| 4 |
import time
|
| 5 |
import uuid
|
| 6 |
from pathlib import Path
|
| 7 |
from typing import Optional
|
| 8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
from dotenv import load_dotenv
|
| 10 |
|
| 11 |
# 自动加载项目目录下的 .env
|
|
@@ -153,6 +160,10 @@ async def chat_completions(
|
|
| 153 |
|
| 154 |
await manager.release(account)
|
| 155 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
return {
|
| 157 |
"id": f"chatcmpl-{uuid.uuid4().hex[:8]}",
|
| 158 |
"object": "chat.completion",
|
|
@@ -166,14 +177,15 @@ async def chat_completions(
|
|
| 166 |
}
|
| 167 |
],
|
| 168 |
"usage": {
|
| 169 |
-
"prompt_tokens":
|
| 170 |
-
"completion_tokens":
|
| 171 |
-
"total_tokens":
|
| 172 |
},
|
| 173 |
}
|
| 174 |
|
| 175 |
except Exception as e:
|
| 176 |
await manager.mark_error(account)
|
|
|
|
| 177 |
raise HTTPException(status_code=503, detail=str(e))
|
| 178 |
|
| 179 |
|
|
@@ -186,7 +198,17 @@ async def healthz():
|
|
| 186 |
@app.get("/readyz")
|
| 187 |
async def readyz():
|
| 188 |
stats = manager.get_stats()
|
| 189 |
-
return {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
|
| 191 |
|
| 192 |
@app.get("/admin/stats")
|
|
@@ -234,6 +256,8 @@ async def list_accounts(admin_key: str = Header(...)):
|
|
| 234 |
"name": acc.name,
|
| 235 |
"in_use": acc.in_use,
|
| 236 |
"logged_in": acc.logged_in,
|
|
|
|
|
|
|
| 237 |
"error_count": acc.error_count,
|
| 238 |
})
|
| 239 |
|
|
@@ -256,7 +280,7 @@ async def startup():
|
|
| 256 |
proxy=acc.proxy,
|
| 257 |
)
|
| 258 |
|
| 259 |
-
|
| 260 |
|
| 261 |
|
| 262 |
ADMIN_HTML = """<!DOCTYPE html>
|
|
|
|
| 1 |
import asyncio
|
| 2 |
import json
|
| 3 |
+
import logging
|
| 4 |
import os
|
| 5 |
import time
|
| 6 |
import uuid
|
| 7 |
from pathlib import Path
|
| 8 |
from typing import Optional
|
| 9 |
|
| 10 |
+
logging.basicConfig(
|
| 11 |
+
level=logging.INFO,
|
| 12 |
+
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
| 13 |
+
)
|
| 14 |
+
logger = logging.getLogger(__name__)
|
| 15 |
+
|
| 16 |
from dotenv import load_dotenv
|
| 17 |
|
| 18 |
# 自动加载项目目录下的 .env
|
|
|
|
| 160 |
|
| 161 |
await manager.release(account)
|
| 162 |
|
| 163 |
+
# Token counts are estimated by word splitting; not exact tokenization
|
| 164 |
+
prompt_tokens = len(prompt.split())
|
| 165 |
+
completion_tokens = len(response_text.split())
|
| 166 |
+
|
| 167 |
return {
|
| 168 |
"id": f"chatcmpl-{uuid.uuid4().hex[:8]}",
|
| 169 |
"object": "chat.completion",
|
|
|
|
| 177 |
}
|
| 178 |
],
|
| 179 |
"usage": {
|
| 180 |
+
"prompt_tokens": prompt_tokens,
|
| 181 |
+
"completion_tokens": completion_tokens,
|
| 182 |
+
"total_tokens": prompt_tokens + completion_tokens,
|
| 183 |
},
|
| 184 |
}
|
| 185 |
|
| 186 |
except Exception as e:
|
| 187 |
await manager.mark_error(account)
|
| 188 |
+
logger.error("Chat completion error for model=%s: %s", request.model, e)
|
| 189 |
raise HTTPException(status_code=503, detail=str(e))
|
| 190 |
|
| 191 |
|
|
|
|
| 198 |
@app.get("/readyz")
|
| 199 |
async def readyz():
|
| 200 |
stats = manager.get_stats()
|
| 201 |
+
return {
|
| 202 |
+
"status": "ok",
|
| 203 |
+
"accounts": {
|
| 204 |
+
"total": stats["total"],
|
| 205 |
+
"in_use": stats["in_use"],
|
| 206 |
+
"available": stats["available"],
|
| 207 |
+
"logged_in": stats["logged_in"],
|
| 208 |
+
"muted": stats["muted"],
|
| 209 |
+
"queue_size": stats["queue_size"],
|
| 210 |
+
},
|
| 211 |
+
}
|
| 212 |
|
| 213 |
|
| 214 |
@app.get("/admin/stats")
|
|
|
|
| 256 |
"name": acc.name,
|
| 257 |
"in_use": acc.in_use,
|
| 258 |
"logged_in": acc.logged_in,
|
| 259 |
+
"is_muted": acc.is_muted,
|
| 260 |
+
"muted_until": acc.muted_until,
|
| 261 |
"error_count": acc.error_count,
|
| 262 |
})
|
| 263 |
|
|
|
|
| 280 |
proxy=acc.proxy,
|
| 281 |
)
|
| 282 |
|
| 283 |
+
logger.info("Loaded %d accounts", len(config.accounts))
|
| 284 |
|
| 285 |
|
| 286 |
ADMIN_HTML = """<!DOCTYPE html>
|
proxy.py
CHANGED
|
@@ -1,4 +1,6 @@
|
|
| 1 |
import json
|
|
|
|
|
|
|
| 2 |
import time
|
| 3 |
import uuid
|
| 4 |
from typing import Optional
|
|
@@ -9,6 +11,12 @@ from fastapi.middleware.cors import CORSMiddleware
|
|
| 9 |
from fastapi.responses import StreamingResponse
|
| 10 |
from pydantic import BaseModel
|
| 11 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
app = FastAPI(title="DS2API Browser Proxy")
|
| 13 |
|
| 14 |
app.add_middleware(
|
|
@@ -19,9 +27,11 @@ app.add_middleware(
|
|
| 19 |
allow_headers=["*"],
|
| 20 |
)
|
| 21 |
|
| 22 |
-
DS2API_URL = "http://127.0.0.1:5001"
|
| 23 |
-
API_KEYS =
|
| 24 |
-
ADMIN_KEY = "admin"
|
|
|
|
|
|
|
| 25 |
|
| 26 |
|
| 27 |
class Message(BaseModel):
|
|
@@ -48,12 +58,16 @@ def verify_api_key(authorization: Optional[str] = Header(None)) -> str:
|
|
| 48 |
return token
|
| 49 |
|
| 50 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
@app.get("/v1/models")
|
| 52 |
async def list_models(authorization: str = Header(...)):
|
| 53 |
verify_api_key(authorization)
|
| 54 |
|
| 55 |
async with httpx.AsyncClient() as client:
|
| 56 |
-
resp = await client.get(f"{DS2API_URL}/v1/models", headers=
|
| 57 |
return resp.json()
|
| 58 |
|
| 59 |
|
|
@@ -62,7 +76,7 @@ async def get_model(model_id: str, authorization: str = Header(...)):
|
|
| 62 |
verify_api_key(authorization)
|
| 63 |
|
| 64 |
async with httpx.AsyncClient() as client:
|
| 65 |
-
resp = await client.get(f"{DS2API_URL}/v1/models/{model_id}", headers=
|
| 66 |
return resp.json()
|
| 67 |
|
| 68 |
|
|
@@ -84,7 +98,7 @@ async def chat_completions(
|
|
| 84 |
"POST",
|
| 85 |
f"{DS2API_URL}/v1/chat/completions",
|
| 86 |
json=request.model_dump(),
|
| 87 |
-
headers=
|
| 88 |
timeout=120,
|
| 89 |
) as resp:
|
| 90 |
async for line in resp.aiter_lines():
|
|
@@ -98,7 +112,7 @@ async def chat_completions(
|
|
| 98 |
resp = await client.post(
|
| 99 |
f"{DS2API_URL}/v1/chat/completions",
|
| 100 |
json=request.model_dump(),
|
| 101 |
-
headers=
|
| 102 |
timeout=120,
|
| 103 |
)
|
| 104 |
return resp.json()
|
|
@@ -139,8 +153,8 @@ async def anthropic_messages(request: Request, authorization: str = Header(...))
|
|
| 139 |
async with stream_client.stream(
|
| 140 |
"POST",
|
| 141 |
f"{DS2API_URL}/v1/chat/completions",
|
| 142 |
-
json={"model": "deepseek-
|
| 143 |
-
headers=
|
| 144 |
timeout=120,
|
| 145 |
) as resp:
|
| 146 |
async for line in resp.aiter_lines():
|
|
@@ -165,8 +179,8 @@ async def anthropic_messages(request: Request, authorization: str = Header(...))
|
|
| 165 |
|
| 166 |
resp = await client.post(
|
| 167 |
f"{DS2API_URL}/v1/chat/completions",
|
| 168 |
-
json={"model": "deepseek-
|
| 169 |
-
headers=
|
| 170 |
timeout=120,
|
| 171 |
)
|
| 172 |
data = resp.json()
|
|
@@ -201,8 +215,8 @@ async def gemini_generate(model: str, request: Request, authorization: str = Hea
|
|
| 201 |
async with httpx.AsyncClient() as client:
|
| 202 |
resp = await client.post(
|
| 203 |
f"{DS2API_URL}/v1/chat/completions",
|
| 204 |
-
json={"model": "deepseek-
|
| 205 |
-
headers=
|
| 206 |
timeout=120,
|
| 207 |
)
|
| 208 |
data = resp.json()
|
|
@@ -243,8 +257,8 @@ async def gemini_stream_generate(model: str, request: Request, authorization: st
|
|
| 243 |
async with stream_client.stream(
|
| 244 |
"POST",
|
| 245 |
f"{DS2API_URL}/v1/chat/completions",
|
| 246 |
-
json={"model": "deepseek-
|
| 247 |
-
headers=
|
| 248 |
timeout=120,
|
| 249 |
) as resp:
|
| 250 |
async for line in resp.aiter_lines():
|
|
@@ -331,7 +345,7 @@ def main():
|
|
| 331 |
uvicorn.run(
|
| 332 |
app,
|
| 333 |
host="0.0.0.0",
|
| 334 |
-
port=5002,
|
| 335 |
)
|
| 336 |
|
| 337 |
|
|
|
|
| 1 |
import json
|
| 2 |
+
import logging
|
| 3 |
+
import os
|
| 4 |
import time
|
| 5 |
import uuid
|
| 6 |
from typing import Optional
|
|
|
|
| 11 |
from fastapi.responses import StreamingResponse
|
| 12 |
from pydantic import BaseModel
|
| 13 |
|
| 14 |
+
logging.basicConfig(
|
| 15 |
+
level=logging.INFO,
|
| 16 |
+
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
| 17 |
+
)
|
| 18 |
+
logger = logging.getLogger(__name__)
|
| 19 |
+
|
| 20 |
app = FastAPI(title="DS2API Browser Proxy")
|
| 21 |
|
| 22 |
app.add_middleware(
|
|
|
|
| 27 |
allow_headers=["*"],
|
| 28 |
)
|
| 29 |
|
| 30 |
+
DS2API_URL = os.getenv("DS2API_UPSTREAM_URL", "http://127.0.0.1:5001")
|
| 31 |
+
API_KEYS = os.getenv("DS2API_PROXY_KEYS", os.getenv("DS2API_KEYS", "sk-default")).split(",")
|
| 32 |
+
ADMIN_KEY = os.getenv("DS2API_ADMIN_KEY", "admin")
|
| 33 |
+
# Internal key used to talk to the upstream DS2API instance
|
| 34 |
+
_UPSTREAM_KEY = os.getenv("DS2API_UPSTREAM_KEY", API_KEYS[0] if API_KEYS else "sk-default")
|
| 35 |
|
| 36 |
|
| 37 |
class Message(BaseModel):
|
|
|
|
| 58 |
return token
|
| 59 |
|
| 60 |
|
| 61 |
+
def _upstream_headers() -> dict:
|
| 62 |
+
return {"Authorization": f"Bearer {_UPSTREAM_KEY}"}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
@app.get("/v1/models")
|
| 66 |
async def list_models(authorization: str = Header(...)):
|
| 67 |
verify_api_key(authorization)
|
| 68 |
|
| 69 |
async with httpx.AsyncClient() as client:
|
| 70 |
+
resp = await client.get(f"{DS2API_URL}/v1/models", headers=_upstream_headers())
|
| 71 |
return resp.json()
|
| 72 |
|
| 73 |
|
|
|
|
| 76 |
verify_api_key(authorization)
|
| 77 |
|
| 78 |
async with httpx.AsyncClient() as client:
|
| 79 |
+
resp = await client.get(f"{DS2API_URL}/v1/models/{model_id}", headers=_upstream_headers())
|
| 80 |
return resp.json()
|
| 81 |
|
| 82 |
|
|
|
|
| 98 |
"POST",
|
| 99 |
f"{DS2API_URL}/v1/chat/completions",
|
| 100 |
json=request.model_dump(),
|
| 101 |
+
headers=_upstream_headers(),
|
| 102 |
timeout=120,
|
| 103 |
) as resp:
|
| 104 |
async for line in resp.aiter_lines():
|
|
|
|
| 112 |
resp = await client.post(
|
| 113 |
f"{DS2API_URL}/v1/chat/completions",
|
| 114 |
json=request.model_dump(),
|
| 115 |
+
headers=_upstream_headers(),
|
| 116 |
timeout=120,
|
| 117 |
)
|
| 118 |
return resp.json()
|
|
|
|
| 153 |
async with stream_client.stream(
|
| 154 |
"POST",
|
| 155 |
f"{DS2API_URL}/v1/chat/completions",
|
| 156 |
+
json={"model": "deepseek-flash", "messages": [{"role": "user", "content": prompt}], "stream": True},
|
| 157 |
+
headers=_upstream_headers(),
|
| 158 |
timeout=120,
|
| 159 |
) as resp:
|
| 160 |
async for line in resp.aiter_lines():
|
|
|
|
| 179 |
|
| 180 |
resp = await client.post(
|
| 181 |
f"{DS2API_URL}/v1/chat/completions",
|
| 182 |
+
json={"model": "deepseek-flash", "messages": [{"role": "user", "content": prompt}], "stream": False},
|
| 183 |
+
headers=_upstream_headers(),
|
| 184 |
timeout=120,
|
| 185 |
)
|
| 186 |
data = resp.json()
|
|
|
|
| 215 |
async with httpx.AsyncClient() as client:
|
| 216 |
resp = await client.post(
|
| 217 |
f"{DS2API_URL}/v1/chat/completions",
|
| 218 |
+
json={"model": "deepseek-flash", "messages": [{"role": "user", "content": prompt}], "stream": False},
|
| 219 |
+
headers=_upstream_headers(),
|
| 220 |
timeout=120,
|
| 221 |
)
|
| 222 |
data = resp.json()
|
|
|
|
| 257 |
async with stream_client.stream(
|
| 258 |
"POST",
|
| 259 |
f"{DS2API_URL}/v1/chat/completions",
|
| 260 |
+
json={"model": "deepseek-flash", "messages": [{"role": "user", "content": prompt}], "stream": True},
|
| 261 |
+
headers=_upstream_headers(),
|
| 262 |
timeout=120,
|
| 263 |
) as resp:
|
| 264 |
async for line in resp.aiter_lines():
|
|
|
|
| 345 |
uvicorn.run(
|
| 346 |
app,
|
| 347 |
host="0.0.0.0",
|
| 348 |
+
port=int(os.getenv("DS2API_PROXY_PORT", "5002")),
|
| 349 |
)
|
| 350 |
|
| 351 |
|
requirements.txt
CHANGED
|
@@ -3,3 +3,4 @@ fastapi>=0.100.0
|
|
| 3 |
uvicorn>=0.23.0
|
| 4 |
pydantic>=2.0.0
|
| 5 |
python-dotenv>=1.0.0
|
|
|
|
|
|
| 3 |
uvicorn>=0.23.0
|
| 4 |
pydantic>=2.0.0
|
| 5 |
python-dotenv>=1.0.0
|
| 6 |
+
httpx>=0.24.0
|
start.py
CHANGED
|
@@ -1,18 +1,14 @@
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
-
"""Quick
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import os
|
| 4 |
import sys
|
| 5 |
|
| 6 |
sys.path.insert(0, os.path.dirname(__file__))
|
| 7 |
|
| 8 |
-
# 多账号配置,用分号分隔
|
| 9 |
-
# 格式: email:password:name:proxy
|
| 10 |
-
os.environ["DS2API_ACCOUNTS"] = "huanxiangnb+dja@gmail.com:m1234567:账号1;huanxiangnb+321fffww@gmail.com:m1234567:账号2"
|
| 11 |
-
os.environ["DS2API_KEYS"] = "sk-test123456"
|
| 12 |
-
os.environ["DS2API_ADMIN_KEY"] = "admin"
|
| 13 |
-
os.environ["DS2API_PORT"] = "5002"
|
| 14 |
-
os.environ["DS2API_HEADLESS"] = "true"
|
| 15 |
-
|
| 16 |
from main import main
|
| 17 |
|
| 18 |
if __name__ == "__main__":
|
|
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
+
"""Quick start script for DS2API Browser.
|
| 3 |
+
|
| 4 |
+
Accounts and keys are loaded from .env file automatically by main.py.
|
| 5 |
+
See .env.example for the expected format.
|
| 6 |
+
"""
|
| 7 |
import os
|
| 8 |
import sys
|
| 9 |
|
| 10 |
sys.path.insert(0, os.path.dirname(__file__))
|
| 11 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
from main import main
|
| 13 |
|
| 14 |
if __name__ == "__main__":
|