misonL commited on
Commit
df4585d
·
0 Parent(s):

Initial project commit with gitignore

Browse files
.gitignore ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python
2
+ __pycache__/
3
+ *.pyc
4
+ *.pyo
5
+ *.pyd
6
+ venv/
7
+ .venv/
8
+
9
+ # Editors/IDEs
10
+ .vscode/
11
+ .idea/
12
+
13
+ # Temporary files
14
+ *.log
15
+ *.tmp
16
+ *.swp
17
+
18
+ # Hugging Face Space nested directory (if it exists locally)
19
+ g2api-test/
Dockerfile ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 使用官方 Python 镜像作为基础镜像
2
+ FROM python:3.9-slim
3
+
4
+ # 设置工作目录
5
+ WORKDIR /app
6
+
7
+ # 复制 requirements.txt 并安装依赖
8
+ COPY requirements.txt .
9
+ RUN pip install --no-cache-dir -r requirements.txt
10
+
11
+ # 复制项目所有文件到工作目录
12
+ COPY . .
13
+
14
+ # 暴露 Flask 应用运行的端口
15
+ EXPOSE 5000
16
+
17
+ # 定义启动命令
18
+ # 使用 gunicorn 运行 Flask 应用,适配 Hugging Face Spaces
19
+ CMD ["gunicorn", "app:app", "-b", "0.0.0.0:5000"]
README.md ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Grok API 逆向封装与改造项目
2
+
3
+ ## 项目简介
4
+
5
+ 本项目旨在将现有的 Grok 网页版逆向封装为 API 的 Python Flask 程序进行全面改造。改造目标是构建一个结构专业、功能完善(包含 Web UI)、文档齐全且易于部署的应用。项目严格遵守内存数据模式,所有运行时数据仅存储在内存中,不进行本地持久化。
6
+
7
+ ## 功能列表
8
+
9
+ - **Grok API 封装:** 提供稳定可靠的 API 接口,用于访问 Grok 的核心功能。
10
+ - **Web UI 系统状态展示:** 提供一个直观的 Web 界面,展示应用程序的当前运行状态和关键信息(此功能正在开发中)。
11
+ - **模块化代码结构:** 代码按照功能和职责进行拆分,提高了可维护性和可读性。
12
+ - **Hugging Face Spaces Docker 部署支持:** 提供 Dockerfile 和相关配置,方便在 Hugging Face Spaces 等支持 Docker 的平台上进行快速部署。
13
+
14
+ ## 安装部署
15
+
16
+ 本项目支持使用 Docker 在 Hugging Face Spaces 上进行部署。
17
+
18
+ ### 前提条件
19
+
20
+ - 已安装 Docker。
21
+ - 已安装 Python 3.8 或更高版本。
22
+ - 拥有 Hugging Face 账号。
23
+
24
+ ### 本地运行 (使用 Docker)
25
+
26
+ 1. 克隆项目仓库:
27
+ ```bash
28
+ git clone <你的仓库地址>
29
+ cd <项目目录>
30
+ ```
31
+ 2. 构建 Docker 镜像:
32
+ ```bash
33
+ docker build -t grok-api-remodel .
34
+ ```
35
+ 3. 运行 Docker 容器:
36
+ ```bash
37
+ docker run -p 5000:5000 grok-api-remodel
38
+ ```
39
+ 应用程序将在本地的 5000 端口运行。
40
+
41
+ ### 部署到 Hugging Face Spaces (使用 Docker)
42
+
43
+ 1. 在 Hugging Face Spaces 上创建一个新的 Space。
44
+ 2. 选择 Docker 作为 Space SDK。
45
+ 3. 将本项目仓库关联到你的 Hugging Face Space。
46
+ 4. Hugging Face Spaces 将会自动检测项目根目录下的 `Dockerfile` 并进行构建和部署。确保你的 `Dockerfile` 配置正确,暴露了 Flask 应用运行的端口(默认为 5000)。
47
+
48
+ ## 配置说明
49
+
50
+ 本项目的部分配置通过环境变量进行管理。
51
+
52
+ - `YOUR_API_KEY`: 用于认证或访问外部服务的 API 密钥(如果需要)。
53
+ - `LISTEN_PORT`: 应用程序监听的端口(默认为 5000)。
54
+
55
+ 请根据你的部署环境设置相应的环境变量。在 Hugging Face Spaces 上,可以在 Space 的设置页面配置环境变量。
56
+
57
+ ## API 使用指南
58
+
59
+ 项目的 API 接口提供了对 Grok 功能的访问。详细的 API 文档(包括可用端点、请求方法、参数和响应格式)将在后续提供。
60
+
61
+ 通常,你可以通过向部署后的应用程序 URL 发送 HTTP 请求来使用 API。例如:
62
+
63
+ ```bash
64
+ curl -X POST <部署后的应用URL>/api/<端点> \
65
+ -H "Content-Type: application/json" \
66
+ -d '{"key": "value"}'
67
+ ```
68
+
69
+ 请参考后续提供的详细 API 文档以获取准确的使用方法。
70
+
71
+ ## Web UI 使用说明
72
+
73
+ 项目的 Web UI 提供了一个界面来监控应用程序的状态。部署成功后,直接访问应用程序的根 URL 即可访问 Web UI。
74
+
75
+ 例如:`<部署后的应用URL>/`
76
+
77
+ Web UI 将展示包括但不限于:
78
+ - 应用程序启动时间
79
+ - 当前内存使用情况
80
+ - API 请求统计(如果实现)
81
+ - 其他系统健康指标
82
+
83
+ ## 注意事项
84
+
85
+ - **内存数据模式:** 本项目设计为仅使用内存存储数据。这意味着应用程序重启后,所有运行时数据将丢失。请勿依赖本项目进行数据持久化。
86
+ - **速率限制:** 底层 Grok API 可能存在速率限制。本项目目前可能未实现复杂的速率限制处理。在使用 API 时,请注意 Grok 自身的速率限制,避免因请求频率过高导致服务不可用。
87
+ - **安全性:** 在生产环境部署时,请务必采取适当的安全措施,例如使用 HTTPS、API 密钥管理等。
88
+
89
+ ## 项目阶段
90
+
91
+ 本项目正在逐步开发中,遵循以下阶段计划:
92
+
93
+ - **阶段 1:** 规划与设计 (已完成)
94
+ - **阶段 2:** 核心功能实现 (已完成)
95
+ - **阶段 3:** 文档与部署 (当前阶段)
96
+ - 3.1 编写 README.md 文档 (当前任务)
97
+ - 3.2 准备 Docker 部署配置
98
+ - 3.3 编写详细部署文档
99
+ - **阶段 4:** Web UI 完善与优化
100
+ - **阶段 5:** 测试与发布
101
+
102
+ 感谢你的关注和支持!
app.py ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import uuid
4
+ import time
5
+ import base64
6
+ import sys
7
+ import inspect
8
+ import secrets
9
+ from dotenv import load_dotenv
10
+ import requests
11
+ from flask import Flask, request, Response, jsonify, stream_with_context, render_template, redirect, session
12
+ from curl_cffi import requests as curl_requests
13
+ from werkzeug.middleware.proxy_fix import ProxyFix
14
+
15
+ from src.core.logger import logger # 从新的位置导入 logger
16
+
17
+ current_dir = os.path.dirname(os.path.abspath(__file__))
18
+ env_path = os.path.join(current_dir, '.env')
19
+ load_dotenv(env_path)
20
+
21
+ CONFIG = {
22
+ "MODELS": {
23
+ 'grok-2': 'grok-latest',
24
+ 'grok-2-imageGen': 'grok-latest',
25
+ 'grok-2-search': 'grok-latest',
26
+ "grok-3": "grok-3",
27
+ "grok-3-search": "grok-3",
28
+ "grok-3-imageGen": "grok-3",
29
+ "grok-3-deepsearch": "grok-3",
30
+ "grok-3-reasoning": "grok-3"
31
+ },
32
+ "API": {
33
+ "IS_TEMP_CONVERSATION": os.getenv("IS_TEMP_CONVERSATION", "true").lower() == "true",
34
+ "IS_CUSTOM_SSO": os.getenv("IS_CUSTOM_SSO", "false").lower() == "true",
35
+ "BASE_URL": "https://grok.com",
36
+ "API_KEY": os.getenv("API_KEY", "sk-123456"),
37
+ "SIGNATURE_COOKIE": None,
38
+ "PICGO_KEY": os.getenv("PICGO_KEY") or None,
39
+ "TUMY_KEY": os.getenv("TUMY_KEY") or None,
40
+ "RETRY_TIME": 1000,
41
+ "PROXY": os.getenv("PROXY") or None
42
+ },
43
+ "ADMIN": {
44
+ "MANAGER_SWITCH": os.getenv("MANAGER_SWITCH") or None,
45
+ "PASSWORD": os.getenv("ADMINPASSWORD") or None
46
+ },
47
+ "SERVER": {
48
+ "COOKIE": None,
49
+ "CF_CLEARANCE":os.getenv("CF_CLEARANCE") or None,
50
+ "PORT": int(os.getenv("PORT", 5200))
51
+ },
52
+ "RETRY": {
53
+ "RETRYSWITCH": False,
54
+ "MAX_ATTEMPTS": 2
55
+ },
56
+ "SHOW_THINKING": os.getenv("SHOW_THINKING") == "true",
57
+ "IS_THINKING": False,
58
+ "IS_IMG_GEN": False,
59
+ "IS_IMG_GEN2": False,
60
+ "ISSHOW_SEARCH_RESULTS": os.getenv("ISSHOW_SEARCH_RESULTS", "true").lower() == "true"
61
+ }
62
+
63
+ DEFAULT_HEADERS = {
64
+ 'Accept': '*/*',
65
+ 'Accept-Language': 'zh-CN,zh;q=0.9',
66
+ 'Accept-Encoding': 'gzip, deflate, br, zstd',
67
+ 'Content-Type': 'text/plain;charset=UTF-8',
68
+ 'Connection': 'keep-alive',
69
+ 'Origin': 'https://grok.com',
70
+ 'Priority': 'u=1, i',
71
+ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36',
72
+ 'Sec-Ch-Ua': '"Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"',
73
+ 'Sec-Ch-Ua-Mobile': '?0',
74
+ 'Sec-Ch-Ua-Platform': '"macOS"',
75
+ 'Sec-Fetch-Dest': 'empty',
76
+ 'Sec-Fetch-Mode': 'cors',
77
+ 'Sec-Fetch-Site': 'same-origin',
78
+ 'Baggage': 'sentry-public_key=b311e0f2690c81f25e2c4cf6d4f7ce1c'
79
+ }
80
+
81
+ from src.core.auth_token_manager import AuthTokenManager # 从新的位置导入 AuthTokenManager
82
+
83
+
84
+ from src.core.utils import Utils # 从新的位置导入 Utils
85
+
86
+
87
+ from src.core.grok_api_client import GrokApiClient # 从新的位置导入 GrokApiClient
88
+
89
+
90
+ from src.core.message_processor import MessageProcessor # 从新的位置导入 MessageProcessor
91
+
92
+
93
+ def initialization():
94
+ sso_array = os.getenv("SSO", "").split(',')
95
+ logger.info("开始加载令牌", "Server")
96
+ for sso in sso_array:
97
+ if sso:
98
+ token_manager.add_token(f"sso-rw={sso};sso={sso}")
99
+ logger.info(f"成功加载令牌: {json.dumps(token_manager.get_all_tokens(), indent=2)}", "Server")
100
+ logger.info(f"令牌加载完成,共加载: {len(token_manager.get_all_tokens())}个令牌", "Server")
101
+ if CONFIG["API"]["PROXY"]:
102
+ logger.info(f"代理已设置: {CONFIG['API']['PROXY']}", "Server")
103
+ logger.info("初始化完成", "Server")
104
+
105
+
106
+ app = Flask(__name__)
107
+ app.wsgi_app = ProxyFix(app.wsgi_app)
108
+ app.secret_key = os.getenv('FLASK_SECRET_KEY') or secrets.token_hex(16)
109
+ app.json.sort_keys = False
110
+
111
+ @app.route('/manager/login', methods=['GET', 'POST'])
112
+ def manager_login():
113
+ if CONFIG["ADMIN"]["MANAGER_SWITCH"]:
114
+ if request.method == 'POST':
115
+ password = request.form.get('password')
116
+ if password == CONFIG["ADMIN"]["PASSWORD"]:
117
+ session['is_logged_in'] = True
118
+ return redirect('/manager')
119
+ return render_template('login.html', error=True)
120
+ return render_template('login.html', error=False)
121
+ else:
122
+ return redirect('/')
123
+
124
+ def check_auth():
125
+ return session.get('is_logged_in', False)
126
+
127
+ @app.route('/manager')
128
+ def manager():
129
+ if not check_auth():
130
+ return redirect('/manager/login')
131
+ return render_template('manager.html')
132
+
133
+ @app.route('/manager/api/get')
134
+ def get_manager_tokens():
135
+ if not check_auth():
136
+ return jsonify({"error": "Unauthorized"}), 401
137
+ return jsonify(token_manager.get_token_status_map())
138
+
139
+ @app.route('/manager/api/add', methods=['POST'])
140
+ def add_manager_token():
141
+ if not check_auth():
142
+ return jsonify({"error": "Unauthorized"}), 401
143
+ try:
144
+ sso = request.json.get('sso')
145
+ if not sso:
146
+ return jsonify({"error": "SSO token is required"}), 400
147
+ token_manager.add_token(f"sso-rw={sso};sso={sso}")
148
+ return jsonify({"success": True})
149
+ except Exception as e:
150
+ return jsonify({"error": str(e)}), 500
151
+
152
+ @app.route('/manager/api/delete', methods=['POST'])
153
+ def delete_manager_token():
154
+ if not check_auth():
155
+ return jsonify({"error": "Unauthorized"}), 401
156
+ try:
157
+ sso = request.json.get('sso')
158
+ if not sso:
159
+ return jsonify({"error": "SSO token is required"}), 400
160
+ token_manager.delete_token(f"sso-rw={sso};sso={sso}")
161
+ return jsonify({"success": True})
162
+ except Exception as e:
163
+ return jsonify({"error": str(e)}), 500
164
+
165
+ @app.route('/manager/api/cf_clearance', methods=['POST'])
166
+ def setCf_Manager_clearance():
167
+ if not check_auth():
168
+ return jsonify({"error": "Unauthorized"}), 401
169
+ try:
170
+ cf_clearance = request.json.get('cf_clearance')
171
+ if not cf_clearance:
172
+ return jsonify({"error": "cf_clearance is required"}), 400
173
+ CONFIG["SERVER"]['CF_CLEARANCE'] = cf_clearance
174
+ return jsonify({"success": True})
175
+ except Exception as e:
176
+ return jsonify({"error": str(e)}), 500
177
+
178
+
179
+ @app.route('/get/tokens', methods=['GET'])
180
+ def get_tokens():
181
+ auth_token = request.headers.get('Authorization', '').replace('Bearer ', '')
182
+ if CONFIG["API"]["IS_CUSTOM_SSO"]:
183
+ return jsonify({"error": '自定义的SSO令牌模式无法获取轮询sso令牌状态'}), 403
184
+ elif auth_token != CONFIG["API"]["API_KEY"]:
185
+ return jsonify({"error": 'Unauthorized'}), 401
186
+ return jsonify(token_manager.get_token_status_map())
187
+
188
+ @app.route('/add/token', methods=['POST'])
189
+ def add_token():
190
+ auth_token = request.headers.get('Authorization', '').replace('Bearer ', '')
191
+ if CONFIG["API"]["IS_CUSTOM_SSO"]:
192
+ return jsonify({"error": '自定义的SSO令牌模式无法添加sso令牌'}), 403
193
+ elif auth_token != CONFIG["API"]["API_KEY"]:
194
+ return jsonify({"error": 'Unauthorized'}), 401
195
+ try:
196
+ sso = request.json.get('sso')
197
+ token_manager.add_token(f"sso-rw={sso};sso={sso}")
198
+ return jsonify(token_manager.get_token_status_map().get(sso, {})), 200
199
+ except Exception as error:
200
+ logger.error(str(error), "Server")
201
+ return jsonify({"error": '添加sso令牌失败'}), 500
202
+
203
+ @app.route('/set/cf_clearance', methods=['POST'])
204
+ def setCf_clearance():
205
+ auth_token = request.headers.get('Authorization', '').replace('Bearer ', '')
206
+ if auth_token != CONFIG["API"]["API_KEY"]:
207
+ return jsonify({"error": 'Unauthorized'}), 401
208
+ try:
209
+ cf_clearance = request.json.get('cf_clearance')
210
+ CONFIG["SERVER"]['CF_CLEARANCE'] = cf_clearance
211
+ return jsonify({"message": '设置cf_clearance成功'}), 200
212
+ except Exception as error:
213
+ logger.error(str(error), "Server")
214
+ return jsonify({"error": '设置cf_clearance失败'}), 500
215
+
216
+ @app.route('/delete/token', methods=['POST'])
217
+ def delete_token():
218
+ auth_token = request.headers.get('Authorization', '').replace('Bearer ', '')
219
+ if CONFIG["API"]["IS_CUSTOM_SSO"]:
220
+ return jsonify({"error": '自定义的SSO令牌模式无法删除sso令牌'}), 403
221
+ elif auth_token != CONFIG["API"]["API_KEY"]:
222
+ return jsonify({"error": 'Unauthorized'}), 401
223
+ try:
224
+ sso = request.json.get('sso')
225
+ token_manager.delete_token(f"sso-rw={sso};sso={sso}")
226
+ return jsonify({"message": '删除sso令牌成功'}), 200
227
+ except Exception as error:
228
+ logger.error(str(error), "Server")
229
+ return jsonify({"error": '删除sso令牌失败'}), 500
230
+
231
+
232
+ @app.route('/v1/models', methods=['GET'])
233
+ def get_models():
234
+ return jsonify({
235
+ "object": "list",
236
+ "data": [
237
+ {
238
+ "id": model,
239
+ "object": "model",
240
+ "created": int(time.time()),
241
+ "owned_by": "grok"
242
+ } for model in CONFIG["MODELS"].keys()
243
+ ]
244
+ })
245
+
246
+ @app.route('/v1/chat/completions', methods=['POST'])
247
+ def chat_completions():
248
+ response_status_code = 500
249
+ try:
250
+ auth_token = request.headers.get('Authorization', '').replace('Bearer ', '')
251
+ if auth_token:
252
+ if CONFIG["API"]["IS_CUSTOM_SSO"]:
253
+ result = f"sso={auth_token};sso-rw={auth_token}"
254
+ token_manager.set_token(result)
255
+ elif auth_token != CONFIG["API"]["API_KEY"]:
256
+ return jsonify({"error": 'Unauthorized'}), 401
257
+ else:
258
+ return jsonify({"error": 'API_KEY缺失'}), 401
259
+
260
+ data = request.json
261
+ model = data.get("model")
262
+ stream = data.get("stream", False)
263
+ retry_count = 0
264
+ grok_client = GrokApiClient(model)
265
+ request_payload = grok_client.prepare_chat_request(data)
266
+
267
+ while retry_count < CONFIG["RETRY"]["MAX_ATTEMPTS"]:
268
+ retry_count += 1
269
+ CONFIG["API"]["SIGNATURE_COOKIE"] = Utils.create_auth_headers(model)
270
+ if not CONFIG["API"]["SIGNATURE_COOKIE"]:
271
+ raise ValueError('该模型无可用令牌')
272
+
273
+ logger.info(
274
+ f"当前令牌: {json.dumps(CONFIG['API']['SIGNATURE_COOKIE'], indent=2)}","Server")
275
+ logger.info(
276
+ f"当前可用模型的全部可用数量: {json.dumps(token_manager.get_remaining_token_request_capacity(), indent=2)}","Server")
277
+
278
+ if CONFIG['SERVER']['CF_CLEARANCE']:
279
+ CONFIG["SERVER"]['COOKIE'] = f"{CONFIG['API']['SIGNATURE_COOKIE']};{CONFIG['SERVER']['CF_CLEARANCE']}"
280
+ else:
281
+ CONFIG["SERVER"]['COOKIE'] = CONFIG['API']['SIGNATURE_COOKIE']
282
+
283
+ logger.info(json.dumps(request_payload,indent=2),"Server")
284
+
285
+ try:
286
+ proxy_options = Utils.get_proxy_options()
287
+ response = curl_requests.post(
288
+ f"{CONFIG['API']['BASE_URL']}/rest/app-chat/conversations/new",
289
+ headers={
290
+ **DEFAULT_HEADERS,
291
+ "Cookie":CONFIG["SERVER"]['COOKIE']
292
+ },
293
+ json=request_payload,
294
+ impersonate="chrome133a",
295
+ verify=False,
296
+ stream=True,
297
+ **proxy_options)
298
+
299
+ logger.info(CONFIG["SERVER"]['COOKIE'],"Server")
300
+
301
+ if response.status_code == 200:
302
+ response_status_code = 200
303
+ logger.info("请求成功", "Server")
304
+ logger.info(
305
+ f"当前{model}剩余可用令牌数: {token_manager.get_token_count_for_model(model)}","Server")
306
+ try:
307
+ if stream:
308
+ return Response(stream_with_context(
309
+ MessageProcessor.handle_stream_response(response, model)),
310
+ content_type='text/event-stream')
311
+ else:
312
+ content = MessageProcessor.handle_non_stream_response(response, model)
313
+ return jsonify(
314
+ MessageProcessor.create_chat_response(content, model))
315
+ except Exception as error:
316
+ logger.error(str(error), "Server")
317
+ if CONFIG["API"]["IS_CUSTOM_SSO"]:
318
+ raise ValueError(f"自定义SSO令牌当前模型{model}的请求次数已失效")
319
+ token_manager.remove_token_from_model(model, CONFIG["API"]["SIGNATURE_COOKIE"])
320
+ if token_manager.get_token_count_for_model(model) == 0:
321
+ raise ValueError(f"{model} 次数已达上限,请切换其他模型或者重新对话")
322
+
323
+ elif response.status_code == 403:
324
+ response_status_code = 403
325
+ token_manager.reduce_token_request_count(model,1)#重置去除当前因为错误未成功请求的次数,确保不会因为错误未成功请求的次数导致次数上限
326
+ if token_manager.get_token_count_for_model(model) == 0:
327
+ raise ValueError(f"{model} 次数已达上限,请切换其他模型或者重新对话")
328
+ raise ValueError(f"IP暂时被封无法破盾,请稍后重试或者更换ip")
329
+
330
+ elif response.status_code == 429:
331
+ response_status_code = 429
332
+ token_manager.reduce_token_request_count(model,1)
333
+ if CONFIG["API"]["IS_CUSTOM_SSO"]:
334
+ raise ValueError(f"自定义SSO令牌当前模型{model}的请求次数已失效")
335
+ token_manager.remove_token_from_model(
336
+ model, CONFIG["API"]["SIGNATURE_COOKIE"])
337
+ if token_manager.get_token_count_for_model(model) == 0:
338
+ raise ValueError(f"{model} 次数已达上限,请切换其他模型或者重新对话")
339
+ else:
340
+ if CONFIG["API"]["IS_CUSTOM_SSO"]:
341
+ raise ValueError(f"自定义SSO令牌当前模型{model}的请求次数已失效")
342
+ logger.error(f"令牌异常错误状态!status: {response.status_code}","Server")
343
+ token_manager.remove_token_from_model(model, CONFIG["API"]["SIGNATURE_COOKIE"])
344
+ logger.info(
345
+ f"当前{model}剩余可用令牌数: {token_manager.get_token_count_for_model(model)}", "Server")
346
+
347
+ except Exception as e:
348
+ logger.error(f"请求处理异常: {str(e)}", "Server")
349
+ if CONFIG["API"]["IS_CUSTOM_SSO"]:
350
+ raise
351
+ continue
352
+
353
+ if response_status_code == 403:
354
+ raise ValueError('IP暂时被封无法破盾,请稍后重试或者更换ip')
355
+ elif response_status_code == 500:
356
+ raise ValueError('当前模型所有令牌暂无可用,请稍后重试')
357
+
358
+ except Exception as error:
359
+ logger.error(str(error), "ChatAPI")
360
+ return jsonify(
361
+ {"error": {
362
+ "message": str(error),
363
+ "type": "server_error"
364
+ }}), response_status_code
365
+
366
+
367
+ @app.route('/')
368
+ def index():
369
+ """渲染系统状态展示页面"""
370
+ return render_template('index.html')
371
+
372
+ @app.route('/status')
373
+ def get_system_status():
374
+ """提供系统状态的 JSON 数据"""
375
+ # 获取配置信息 (需要根据实际CONFIG结构调整)
376
+ config_info = {
377
+ "api_base_url": CONFIG["API"]["BASE_URL"],
378
+ "log_level": logger.level, # 使用logger.level获取日志级别
379
+ "is_temp_conversation": CONFIG["API"]["IS_TEMP_CONVERSATION"],
380
+ "is_custom_sso": CONFIG["API"]["IS_CUSTOM_SSO"],
381
+ "proxy": CONFIG["API"]["PROXY"],
382
+ "manager_switch": CONFIG["ADMIN"]["MANAGER_SWITCH"],
383
+ "show_thinking": CONFIG["SHOW_THINKING"],
384
+ "isshow_search_results": CONFIG["ISSHOW_SEARCH_RESULTS"]
385
+ }
386
+
387
+ # 获取令牌状态
388
+ token_status = {
389
+ "total_tokens": token_manager.get_total_token_count(),
390
+ "available_tokens": token_manager.get_remaining_token_request_capacity(),
391
+ "total_request_count": token_manager.get_total_request_count(),
392
+ "expired_tokens_count": len(token_manager.get_expired_tokens()),
393
+ "token_details": token_manager.get_token_status_map() # 提供更详细的令牌状态
394
+ }
395
+
396
+ # 获取日志摘要
397
+ log_summary = logger.get_recent_logs()
398
+
399
+ return jsonify({
400
+ "config": config_info,
401
+ "token_status": token_status,
402
+ "log_summary": log_summary
403
+ })
404
+
405
+
406
+ if __name__ == '__main__':
407
+ token_manager = AuthTokenManager() # 创建 AuthTokenManager 实例
408
+ initialization()
409
+ app.run(
410
+ host='0.0.0.0',
411
+ port=CONFIG["SERVER"]["PORT"],
412
+ debug=False
413
+ )
dev_plan/project_remodeling_plan.md ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 项目改造计划
2
+
3
+ **目标:** 将现有的 Grok API Python Flask 程序改造为一个结构专业、功能完善(包含 Web UI)、文档齐全且易于部署(Docker on Hugging Face Spaces)的应用,同时严格遵守内存数据模式。
4
+
5
+ **阶段 1: 规划与架构设计**
6
+ * **子任务 1.1: 代码结构设计**
7
+ * **描述:** 分析现有 `app.py` 代码,识别不同的功能模块(如日志、配置、认证、API 客户端、消息处理、Flask 应用路由等)。设计清晰的目录结构和模块划分,例如:
8
+ * `src/` (存放核心代码)
9
+ * `api/` (API 路由和逻辑)
10
+ * `core/` (核心类和函数,如 Logger, AuthTokenManager, GrokApiClient, Utils)
11
+ * `web/` (Web UI 相关文件,如路由、模板、静态文件)
12
+ * `config.py` (配置加载和管理)
13
+ * `utils.py` (通用工具函数)
14
+ * `__init__.py` 等
15
+ * `templates/` (存放 Web UI 模板文件)
16
+ * `static/` (存放 Web UI 静态资源,如 CSS, JS)
17
+ * `docs/` (存放文档,如 README)
18
+ * `tests/` (存放测试文件,可选)
19
+ * **预期产出:** 详细的目录结构设计和模块职责说明。
20
+ * **子任务 1.2: Web UI 技术选型与设计**
21
+ * **描述:** 考虑到 Hugging Face Spaces 免费层的资源限制,选择轻量级的 Web 技术栈。设计 Web 页面的布局,包括展示当前的配置信息、令牌状态(总数、可用数、请求次数等)、日志摘要等。页面设计应美观且信息直观。
22
+ * **预期产出:** Web UI 技术选型报告和页面原型设计(可以是草图或简单的 HTML 结构)。
23
+ * **子任务 1.3: README 内容规划**
24
+ * **描述:** 规划 README 文档的章节和内容,至少应包含:项目简介、功能列表、安装部署(详细说明 Hugging Face Spaces Docker 部署步骤)、配置说明(环境变量等)、API 使用指南、Web UI 使用说明、注意事项(内存数据模式、速率限制等)。
25
+ * **预期产物:** README 文档大纲。
26
+ * **子任务 1.4: Dockerfile 规划**
27
+ * **描述:** 规划 Dockerfile 的内容,包括选择合适的基础镜像(如 Python 官方镜像)、安装依赖(`requirements.txt`)、复制项目文件、设置工作目录、暴露端口、定义启动命令。确保 Dockerfile 能够适配 Hugging Face Spaces 的环境。
28
+ * **预期产出:** Dockerfile 大纲。
29
+ * **子任务 1.5: 内存数据模式确认**
30
+ * **描述:** 仔细分析 `app.py` 中 `AuthTokenManager` 类的数据存储方式,确认其是否完全依赖于内存变量,没有使用文件、数据库或其他持久化存储。在后续改造中严格遵守此原则。
31
+ * **预期产出:** 内存数据模式确认报告和改造中的注意事项列表。
32
+
33
+ **阶段 2: 代码实现与改造**
34
+ * **子任务 2.1: 目录结构创建**
35
+ * **描述:** 根据阶段 1.1 的设计,在项目根目录下创建新的文件夹结构。
36
+ * **预期产出:** 创建好的项目目录结构。
37
+ * **子任务 2.2: 模块拆分与重构**
38
+ * **描述:** 将 `app.py` 中的类、函数和路由按照阶段 1.1 的规划移动到相应的模块文件中。对代码进行重构,提高模块化程度和可读性。更新相互之间的引用关系。
39
+ * **预期产物:** 拆分并重构后的代码文件。
40
+ * **子任务 2.3: Web UI 实现**
41
+ * **描述:** 根据阶段 1.2 的设计,实现 Web UI 的前端(HTML, CSS, JavaScript)和后端(Flask 路由和逻辑)代码。
42
+ * **预期产出:** 可用的 Web UI 文件。
43
+ * **子任务 2.4: API 与 Web UI 集成**
44
+ * **描述:** 修改后端代码,使 Web UI 能够调用内部函数或接口获取系统状态信息(如令牌数量、配置等),并在前端页面上展示。
45
+ * **预期产物:** 集成 API 和 Web UI 的代码。
46
+
47
+ **阶段 3: 文档与部署**
48
+ * **子任务 3.1: README 文档编写**
49
+ * **描述:** 根据阶段 1.3 的大纲,编写详细的 README.md 文档。
50
+ * **预期产出:** 完成的 README.md 文件。
51
+ * **子任务 3.2: Dockerfile 编写**
52
+ * **描述:** 根据阶段 1.4 的大纲,编写 Dockerfile 文件。
53
+ * **预期产物:** 完成的 Dockerfile 文件。
54
+ * **子任务 3.3: 部署测试**
55
+ * **描述:** 在本地使用 Docker 构建镜像并运行,验证程序是否正常工作。如果可能,尝试在 Hugging Face Spaces 上进行测试部署。
56
+ * **预期产出:** 本地 Docker 运行截图或 Hugging Face Spaces 部署成功报告。
57
+
58
+ **阶段 4: 验证与优化**
59
+ * **子任务 4.1: 功能测试**
60
+ * **描述:** 对改造后的程序进行全面的功能测试,包括 API 接口的调用和 Web UI 的交互。
61
+ * **预期产出:** 功能测试报告。
62
+ * **子任务 4.2: 内存使用验证**
63
+ * **描述:** 再次检查代码,���保所有数据存储都只在内存中进行,没有引入任何持久化机制。
64
+ * **预期产物:** 内存数据模式验证报告。
65
+ * **子任务 4.3: 部署适配优化**
66
+ * **描述:** 根据部署测试的结果,对 Dockerfile 或程序代码进行必要的调整和优化,确保在 Hugging Face Spaces 免费层上稳定运行。
67
+ * **预期产物:** 优化后的 Dockerfile 和代码。
68
+
69
+ **计划可视化 (Mermaid 图):**
70
+
71
+ ```mermaid
72
+ graph TD
73
+ A[用户任务: 改造 Grok API 程序] --> B{阶段 1: 规划与架构设计}
74
+ B --> B1[1.1 代码结构设计]
75
+ B --> B2[1.2 Web UI 技术选型与设计]
76
+ B --> B3[1.3 README 内容规划]
77
+ B --> B4[1.4 Dockerfile 规划]
78
+ B --> B5[1.5 内存数据模式确认]
79
+ B --> C{阶段 2: 代码实现与改造}
80
+ C --> C1[2.1 目录结构创建]
81
+ C --> C2[2.2 模块拆分与重构]
82
+ C --> C3[2.3 Web UI 实现]
83
+ C --> C4[2.4 API 与 Web UI 集成]
84
+ C --> D{阶段 3: 文档与部署}
85
+ D --> D1[3.1 README 文档编写]
86
+ D --> D2[3.2 Dockerfile 编写]
87
+ D --> D3[3.3 部署测试]
88
+ D --> E{阶段 4: 验证与优化}
89
+ E --> E1[4.1 功能测试]
90
+ E --> E2[4.2 内存使用验证]
91
+ E --> E3[4.3 部署适配优化]
92
+ E --> F[改造完成]
memory-bank/activeContext.md ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 活动上下文
2
+
3
+ 此文件跟踪项目的当前状态,包括最近的变更、当前目标和未解决的问题。
4
+ YYYY-MM-DD HH:mm:ss - 更新日志。
5
+
6
+ *
7
+
8
+ ## 当前焦点
9
+
10
+ *
11
+ - 对现有的 Grok API 程序进行改造规划。
12
+
13
+ ## 最近变更
14
+
15
+ *
16
+ - Memory Bank 初始化完成。
17
+
18
+ ## 未解决的问题/议题
19
+
20
+ *
21
+ - 暂无。
22
+
23
+ 2025-05-14 17:37:25 - Memory Bank 初始化。
24
+ 2025-05-14 17:39:40 - 更新当前焦点为项目改造规划。
memory-bank/decisionLog.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 决策日志
2
+
3
+ 此文件以列表格式记录架构和实现决策。
4
+ YYYY-MM-DD HH:mm:ss - 更新日志。
5
+
6
+ *
7
+
8
+ ## 决策
9
+
10
+ *
11
+
12
+ ## 理由
13
+
14
+ *
15
+
16
+ ## 实现细节
17
+
18
+ *
19
+
20
+ 2025-05-14 17:37:42 - Memory Bank 初始化。
memory-bank/productContext.md ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 产品上下文
2
+
3
+ 此文件提供项目和预期创建产品的高级概述。初始内容基于 `projectBrief.md`(如果提供)以及工作目录中所有其他与项目相关的信息。此文件应随着项目的发展而更新,并用于为所有其他模式提供项目目标和上下文的信息。
4
+ YYYY-MM-DD HH:mm:ss - 更新日志将作为脚注追加到文件末尾。
5
+
6
+ *
7
+
8
+ ## 项目目标
9
+
10
+ - 对现有的 grok 网页版逆向后封装成 API 的 Python Flask 程序进行改造。
11
+ - 以专业的项目视角对代码进行拆分,分门别类放入不同的文件夹进行管理。
12
+ - 增加一个 Web 端展示系统详细情况,网页设计要美观。
13
+ - 根据项目情况生成一份 README 文档。
14
+ - 保持程序设计只使用内存数据模式,不允许本地存储。
15
+ - 适配部署在 Hugging Face Spaces 的免费层上,使用 Docker 部署。
16
+
17
+ ## 关键功能
18
+
19
+ - 现有的 Grok API 封装功能。
20
+ - Web 端系统状态展示(待实现)。
21
+ - README 文档生成(待实现)。
22
+ - Docker 部署配置(待实现)。
23
+
24
+ ## 整体架构
25
+
26
+ - 现有的 Flask API 部分。
27
+ - 新增的 Web UI 部分。
28
+ - 代码将按照模块进行拆分和组织。
29
+ - 使用内存进行数据存储。
30
+ - 通过 Dockerfile 进行容器化部署。
31
+
32
+ 2025-05-14 17:37:10 - Memory Bank 初始化。
33
+ 2025-05-14 17:38:31 - 添加项目目标和关键功能。
memory-bank/progress.md ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 进展
2
+
3
+ 此文件使用任务列表格式跟踪项目的进展。
4
+ YYYY-MM-DD HH:mm:ss - 更新日志。
5
+
6
+ *
7
+
8
+ ## 已完成任务
9
+
10
+ *
11
+ - Memory Bank 初始化。
12
+ - 目录结构创建。
13
+ - 模块拆分与重构。
14
+
15
+ ## 当前任务
16
+
17
+ *
18
+ - 设计并实现 Web 端系统状态展示。
19
+
20
+ ## 下一步
21
+
22
+ *
23
+ - 编写 README 文档。
24
+ - 准备 Docker 部署配置。
25
+
26
+ 2025-05-14 17:37:34 - Memory Bank 初始化。
27
+ 2025-05-14 17:38:51 - 更新当前任务为项目改造规划。
28
+ 2025-05-14 17:47:37 - 标记目录结构创建为已完成,更新当前任务为模块拆分与重构。
29
+ 2025-05-14 18:04:27 - 标记模块拆分与重构为已完成,更新当前任务为设计并实现 Web 端系统状态展示。
memory-bank/systemPatterns.md ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 系统模式 *可选*
2
+
3
+ 此文件记录项目中使用的重复模式和标准。
4
+ 此文件为可选,但建议随着项目发展进行更新。
5
+ YYYY-MM-DD HH:mm:ss - 更新日志。
6
+
7
+ *
8
+
9
+ ## 编码模式
10
+
11
+ *
12
+
13
+ ## 架构模式
14
+
15
+ *
16
+
17
+ ## 测试模式
18
+
19
+ *
20
+
21
+ 2025-05-14 17:37:52 - Memory Bank 初始化。
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ python-dotenv
2
+ requests
3
+ Flask
4
+ curl_cffi
5
+ Werkzeug
6
+ loguru
src/core/auth_token_manager.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # src/core/auth_token_manager.py
2
+ import time
3
+ import json
4
+ import threading
5
+ from src.core.logger import logger # 从新的位置导入 logger
6
+
7
+ class AuthTokenManager:
8
+ def __init__(self):
9
+ self.token_model_map = {}
10
+ self.expired_tokens = set()
11
+ self.token_status_map = {}
12
+ self.model_config = {
13
+ "grok-2": {
14
+ "RequestFrequency": 30,
15
+ "ExpirationTime": 1 * 60 * 60 * 1000 # 1小时
16
+ },
17
+ "grok-3": {
18
+ "RequestFrequency": 20,
19
+ "ExpirationTime": 2 * 60 * 60 * 1000 # 2小时
20
+ },
21
+ "grok-3-deepsearch": {
22
+ "RequestFrequency": 10,
23
+ "ExpirationTime": 24 * 60 * 60 * 1000 # 24小时
24
+ },
25
+ "grok-3-reasoning": {
26
+ "RequestFrequency": 10,
27
+ "ExpirationTime": 24 * 60 * 60 * 1000 # 24小时
28
+ }
29
+ }
30
+ self.token_reset_switch = False
31
+ self.token_reset_timer = None
32
+
33
+ def add_token(self, token):
34
+ sso = token.split("sso=")[1].split(";")[0]
35
+ for model in self.model_config.keys():
36
+ if model not in self.token_model_map:
37
+ self.token_model_map[model] = []
38
+ if sso not in self.token_status_map:
39
+ self.token_status_map[sso] = {}
40
+
41
+ existing_token_entry = next((entry for entry in self.token_model_map[model] if entry["token"] == token), None)
42
+ if not existing_token_entry:
43
+ self.token_model_map[model].append({
44
+ "token": token,
45
+ "RequestCount": 0,
46
+ "AddedTime": int(time.time() * 1000),
47
+ "StartCallTime": None
48
+ })
49
+
50
+ if model not in self.token_status_map[sso]:
51
+ self.token_status_map[sso][model] = {
52
+ "isValid": True,
53
+ "invalidatedTime": None,
54
+ "totalRequestCount": 0
55
+ }
56
+
57
+ def set_token(self, token):
58
+ models = list(self.model_config.keys())
59
+ self.token_model_map = {model: [{
60
+ "token": token,
61
+ "RequestCount": 0,
62
+ "AddedTime": int(time.time() * 1000),
63
+ "StartCallTime": None
64
+ }] for model in models}
65
+ sso = token.split("sso=")[1].split(";")[0]
66
+ self.token_status_map[sso] = {model: {
67
+ "isValid": True,
68
+ "invalidatedTime": None,
69
+ "totalRequestCount": 0
70
+ } for model in models}
71
+
72
+
73
+ def delete_token(self, token):
74
+ try:
75
+ sso = token.split("sso=")[1].split(";")[0]
76
+ for model in self.token_model_map:
77
+ self.token_model_map[model] = [entry for entry in self.token_model_map[model] if entry["token"] != token]
78
+ if sso in self.token_status_map:
79
+ del self.token_status_map[sso]
80
+ logger.info(f"令牌已成功移除: {token}", "TokenManager")
81
+ return True
82
+ except Exception as error:
83
+ logger.error(f"令牌删除失败: {str(error)}")
84
+ return False
85
+
86
+ def reduce_token_request_count(self, model_id, count):
87
+ try:
88
+ normalized_model = self.normalize_model_name(model_id)
89
+ if normalized_model not in self.token_model_map:
90
+ logger.error(f"模型 {normalized_model} 不存在", "TokenManager")
91
+ return False
92
+ if not self.token_model_map[normalized_model]:
93
+ logger.error(f"模型 {normalized_model} 没有可用的token", "TokenManager")
94
+ return False
95
+
96
+ token_entry = self.token_model_map[normalized_model][0]
97
+ # 确保RequestCount不会小于0
98
+ new_count = max(0, token_entry["RequestCount"] - count)
99
+ reduction = token_entry["RequestCount"] - new_count
100
+ token_entry["RequestCount"] = new_count
101
+
102
+ # 更新token状态
103
+ if token_entry["token"]:
104
+ sso = token_entry["token"].split("sso=")[1].split(";")[0]
105
+ if sso in self.token_status_map and normalized_model in self.token_status_map[sso]:
106
+ self.token_status_map[sso][normalized_model]["totalRequestCount"] = max(
107
+ 0, self.token_status_map[sso][normalized_model]["totalRequestCount"] - reduction
108
+ )
109
+ return True
110
+ except Exception as error:
111
+ logger.error(f"重置校对token请求次数时发生错误: {str(error)}", "TokenManager")
112
+ return False
113
+
114
+
115
+ def get_next_token_for_model(self, model_id, is_return=False):
116
+ normalized_model = self.normalize_model_name(model_id)
117
+ if normalized_model not in self.token_model_map or not self.token_model_map[normalized_model]:
118
+ return None
119
+
120
+ token_entry = self.token_model_map[normalized_model][0]
121
+
122
+ if is_return:
123
+ return token_entry["token"]
124
+
125
+ if token_entry:
126
+ if token_entry["StartCallTime"] is None:
127
+ token_entry["StartCallTime"] = int(time.time() * 1000)
128
+ if not self.token_reset_switch:
129
+ self.start_token_reset_process()
130
+ self.token_reset_switch = True
131
+
132
+ token_entry["RequestCount"] += 1
133
+
134
+ if token_entry["RequestCount"] > self.model_config[normalized_model]["RequestFrequency"]:
135
+ self.remove_token_from_model(normalized_model, token_entry["token"])
136
+ next_token_entry = self.token_model_map[normalized_model][0] if self.token_model_map[normalized_model] else None
137
+ return next_token_entry["token"] if next_token_entry else None
138
+
139
+ sso = token_entry["token"].split("sso=")[1].split(";")[0]
140
+ if sso in self.token_status_map and normalized_model in self.token_status_map[sso]:
141
+ if token_entry["RequestCount"] == self.model_config[normalized_model]["RequestFrequency"]:
142
+ self.token_status_map[sso][normalized_model]["isValid"] = False
143
+ self.token_status_map[sso][normalized_model]["invalidatedTime"] = int(time.time() * 1000)
144
+ self.token_status_map[sso][normalized_model]["totalRequestCount"] += 1
145
+
146
+ return token_entry["token"]
147
+ return None
148
+
149
+ def remove_token_from_model(self, model_id, token):
150
+ normalized_model = self.normalize_model_name(model_id)
151
+ if normalized_model not in self.token_model_map:
152
+ logger.error(f"模型 {normalized_model} 不存在", "TokenManager")
153
+ return False
154
+
155
+ model_tokens = self.token_model_map[normalized_model]
156
+ token_index = next((i for i, entry in enumerate(model_tokens) if entry["token"] == token), -1)
157
+
158
+ if token_index != -1:
159
+ removed_token_entry = model_tokens.pop(token_index)
160
+ self.expired_tokens.add((
161
+ removed_token_entry["token"],
162
+ normalized_model,
163
+ int(time.time() * 1000)
164
+ ))
165
+ if not self.token_reset_switch:
166
+ self.start_token_reset_process()
167
+ self.token_reset_switch = True
168
+ logger.info(f"模型{model_id}的令牌已失效,已成功移除令牌: {token}", "TokenManager")
169
+ return True
170
+ logger.error(f"在模型 {normalized_model} 中未找到 token: {token}", "TokenManager")
171
+ return False
172
+
173
+ def get_expired_tokens(self):
174
+ return list(self.expired_tokens)
175
+
176
+ def normalize_model_name(self, model):
177
+ if model.startswith('grok-') and 'deepsearch' not in model and 'reasoning' not in model:
178
+ return '-'.join(model.split('-')[:2])
179
+ return model
180
+
181
+ def get_token_count_for_model(self, model_id):
182
+ normalized_model = self.normalize_model_name(model_id)
183
+ return len(self.token_model_map.get(normalized_model, []))
184
+
185
+ def get_remaining_token_request_capacity(self):
186
+ remaining_capacity_map = {}
187
+ for model in self.model_config.keys():
188
+ model_tokens = self.token_model_map.get(model, [])
189
+ model_request_frequency = self.model_config[model]["RequestFrequency"]
190
+ total_used_requests = sum(token_entry.get("RequestCount", 0) for token_entry in model_tokens)
191
+ remaining_capacity = (len(model_tokens) * model_request_frequency) - total_used_requests
192
+ remaining_capacity_map[model] = max(0, remaining_capacity)
193
+ return remaining_capacity_map
194
+
195
+ def get_token_array_for_model(self, model_id):
196
+ normalized_model = self.normalize_model_name(model_id)
197
+ return self.token_model_map.get(normalized_model, [])
198
+
199
+ def start_token_reset_process(self):
200
+ def reset_expired_tokens():
201
+ now = int(time.time() * 1000)
202
+ tokens_to_remove = set()
203
+ for token_info in self.expired_tokens:
204
+ token, model, expired_time = token_info
205
+ expiration_time = self.model_config[model]["ExpirationTime"]
206
+ if now - expired_time >= expiration_time:
207
+ if not any(entry["token"] == token for entry in self.token_model_map.get(model, [])):
208
+ if model not in self.token_model_map:
209
+ self.token_model_map[model] = []
210
+ self.token_model_map[model].append({
211
+ "token": token,
212
+ "RequestCount": 0,
213
+ "AddedTime": now,
214
+ "StartCallTime": None
215
+ })
216
+ sso = token.split("sso=")[1].split(";")[0]
217
+ if sso in self.token_status_map and model in self.token_status_map[sso]:
218
+ self.token_status_map[sso][model]["isValid"] = True
219
+ self.token_status_map[sso][model]["invalidatedTime"] = None
220
+ self.token_status_map[sso][model]["totalRequestCount"] = 0
221
+ tokens_to_remove.add(token_info)
222
+ self.expired_tokens -= tokens_to_remove
223
+
224
+ for model in self.model_config.keys():
225
+ if model not in self.token_model_map:
226
+ continue
227
+ for token_entry in self.token_model_map[model]:
228
+ if not token_entry.get("StartCallTime"):
229
+ continue
230
+ expiration_time = self.model_config[model]["ExpirationTime"]
231
+ if now - token_entry["StartCallTime"] >= expiration_time:
232
+ sso = token_entry["token"].split("sso=")[1].split(";")[0]
233
+ if sso in self.token_status_map and model in self.token_status_map[sso]:
234
+ self.token_status_map[sso][model]["isValid"] = True
235
+ self.token_status_map[sso][model]["invalidatedTime"] = None
236
+ self.token_status_map[sso][model]["totalRequestCount"] = 0
237
+ token_entry["RequestCount"] = 0
238
+ token_entry["StartCallTime"] = None
239
+
240
+ # 启动一个线程执行定时任务,每小时执行一次
241
+ def run_timer():
242
+ while True:
243
+ reset_expired_tokens()
244
+ time.sleep(3600)
245
+
246
+ timer_thread = threading.Thread(target=run_timer)
247
+ timer_thread.daemon = True
248
+ timer_thread.start()
249
+
250
+ def get_all_tokens(self):
251
+ all_tokens = set()
252
+ for model_tokens in self.token_model_map.values():
253
+ for entry in model_tokens:
254
+ all_tokens.add(entry["token"])
255
+ return list(all_tokens)
256
+
257
+ def get_current_token(self, model_id):
258
+ normalized_model = self.normalize_model_name(model_id)
259
+ if normalized_model not in self.token_model_map or not self.token_model_map[normalized_model]:
260
+ return None
261
+ token_entry = self.token_model_map[normalized_model][0]
262
+ return token_entry["token"]
263
+
264
+ def get_total_token_count(self):
265
+ """获取总令牌数"""
266
+ return len(self.get_all_tokens())
267
+
268
+ def get_total_request_count(self):
269
+ """获取总请求次数"""
270
+ total_count = 0
271
+ for sso_status in self.token_status_map.values():
272
+ for model_status in sso_status.values():
273
+ total_count += model_status.get("totalRequestCount", 0)
274
+ return total_count
275
+
276
+ def get_token_status_map(self):
277
+ """获取令牌状态映射"""
278
+ return self.token_status_map
src/core/grok_api_client.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # src/core/grok_api_client.py
2
+ import json
3
+ import time
4
+ import base64
5
+ import re
6
+ import requests
7
+ from curl_cffi import requests as curl_requests
8
+
9
+ from src.core.logger import logger # 从新的位置导入 logger
10
+ from src.core.utils import Utils # 从新的位置导入 Utils
11
+ from app import CONFIG, DEFAULT_HEADERS # 导入 CONFIG 和 DEFAULT_HEADERS
12
+
13
+ class GrokApiClient:
14
+ def __init__(self, model_id):
15
+ if model_id not in CONFIG["MODELS"]:
16
+ raise ValueError(f"不支持的模型: {model_id}")
17
+ self.model_id = CONFIG["MODELS"][model_id]
18
+
19
+ def process_message_content(self, content):
20
+ if isinstance(content, str):
21
+ return content
22
+ return None
23
+
24
+ def get_image_type(self, base64_string):
25
+ mime_type = 'image/jpeg'
26
+ if 'data:image' in base64_string:
27
+ import re
28
+ matches = re.search(r'data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+);base64,', base64_string)
29
+ if matches:
30
+ mime_type = matches.group(1)
31
+ extension = mime_type.split('/')[1]
32
+ file_name = f"image.{extension}"
33
+ return {
34
+ "mimeType": mime_type,
35
+ "fileName": file_name
36
+ }
37
+
38
+ def upload_base64_file(self, message, model):
39
+ try:
40
+ message_base64 = base64.b64encode(message.encode('utf-8')).decode('utf-8')
41
+ upload_data = {
42
+ "fileName": "message.txt",
43
+ "fileMimeType": "text/plain",
44
+ "content": message_base64
45
+ }
46
+ logger.info("发送文字文件请求", "Server")
47
+ cookie = f"{Utils.create_auth_headers(model, True)};{CONFIG['SERVER']['CF_CLEARANCE']}"
48
+ proxy_options = Utils.get_proxy_options()
49
+ response = curl_requests.post(
50
+ "https://grok.com/rest/app-chat/upload-file",
51
+ headers={
52
+ **DEFAULT_HEADERS,
53
+ "Cookie":cookie
54
+ },
55
+ json=upload_data,
56
+ impersonate="chrome133a",
57
+ verify=False,
58
+ **proxy_options
59
+ )
60
+ if response.status_code != 200:
61
+ logger.error(f"上传文件失败,状态码:{response.status_code}", "Server")
62
+ raise Exception(f"上传文件失败,状态码:{response.status_code}")
63
+ result = response.json()
64
+ logger.info(f"上传文件成功: {result}", "Server")
65
+ return result.get("fileMetadataId", "")
66
+ except Exception as error:
67
+ logger.error(str(error), "Server")
68
+ raise Exception(f"上传文件失败,状态码:{response.status_code}")
69
+
70
+ def upload_base64_image(self, base64_data, url):
71
+ try:
72
+ if 'data:image' in base64_data:
73
+ image_buffer = base64_data.split(',')[1]
74
+ else:
75
+ image_buffer = base64_data
76
+
77
+ image_info = self.get_image_type(base64_data)
78
+ mime_type = image_info["mimeType"]
79
+ file_name = image_info["fileName"]
80
+
81
+ upload_data = {
82
+ "rpc": "uploadFile",
83
+ "req": {
84
+ "fileName": file_name,
85
+ "fileMimeType": mime_type,
86
+ "content": image_buffer
87
+ }
88
+ }
89
+ logger.info("发送图片请求", "Server")
90
+ proxy_options = Utils.get_proxy_options()
91
+ response = curl_requests.post(
92
+ url,
93
+ headers={
94
+ **DEFAULT_HEADERS,
95
+ "Cookie":CONFIG["SERVER"]['COOKIE']
96
+ },
97
+ json=upload_data,
98
+ impersonate="chrome133a",
99
+ verify=False,
100
+ **proxy_options
101
+ )
102
+ if response.status_code != 200:
103
+ logger.error(f"上传图片失败,状态码:{response.status_code}", "Server")
104
+ return ''
105
+ result = response.json()
106
+ logger.info(f"上传图片成功: {result}", "Server")
107
+ return result.get("fileMetadataId", "")
108
+ except Exception as error:
109
+ logger.error(str(error), "Server")
110
+ return ''
111
+
112
+ def prepare_chat_request(self, request):
113
+ if ((request["model"] == 'grok-2-imageGen' or request["model"] == 'grok-3-imageGen') and not CONFIG["API"]["PICGO_KEY"] and not CONFIG["API"]["TUMY_KEY"] and request.get("stream", False)):
114
+ raise ValueError("该模型流式输出需要配置PICGO或者TUMY图床密钥!")
115
+
116
+ todo_messages = request["messages"]
117
+ if request["model"] in ['grok-2-imageGen', 'grok-3-imageGen', 'grok-3-deepsearch']:
118
+ last_message = todo_messages[-1]
119
+ if last_message["role"] != 'user':
120
+ raise ValueError('此模型最后一条消息必须是用户消息!')
121
+ todo_messages = [last_message]
122
+
123
+ file_attachments = []
124
+ messages = ''
125
+ last_role = None
126
+ last_content = ''
127
+ message_length = 0
128
+ convert_to_file = False
129
+ last_message_content = ''
130
+ search = request["model"] in ['grok-2-search', 'grok-3-search']
131
+
132
+ # 移除标签及其内容和base64图片
133
+ def remove_think_tags(text):
134
+ import re
135
+ text = re.sub(r'[\s\S]*?<\/think>', '', text).strip()
136
+ text = re.sub(r'!\[image\]\(data:.*?base64,.*?\)', '[图片]', text)
137
+ return text
138
+
139
+ def process_content(content):
140
+ if isinstance(content, list):
141
+ text_content = ''
142
+ for item in content:
143
+ if item["type"] == 'image_url':
144
+ text_content += ("[图片]" if not text_content else '\n[图片]')
145
+ elif item["type"] == 'text':
146
+ text_content += (remove_think_tags(item["text"]) if not text_content else '\n' + remove_think_tags(item["text"]))
147
+ return text_content
148
+ elif isinstance(content, dict) and content is not None:
149
+ if content["type"] == 'image_url':
150
+ return "[图片]"
151
+ elif content["type"] == 'text':
152
+ return remove_think_tags(content["text"])
153
+ return remove_think_tags(self.process_message_content(content))
154
+
155
+
156
+ for current in todo_messages:
157
+ role = 'assistant' if current["role"] == 'assistant' else 'user'
158
+ is_last_message = current == todo_messages[-1]
159
+
160
+ if is_last_message and "content" in current:
161
+ if isinstance(current["content"], list):
162
+ for item in current["content"]:
163
+ if item["type"] == 'image_url':
164
+ processed_image = self.upload_base64_image(
165
+ item["image_url"]["url"],
166
+ f"{CONFIG['API']['BASE_URL']}/api/rpc"
167
+ )
168
+ if processed_image:
169
+ file_attachments.append(processed_image)
170
+ elif isinstance(current["content"], dict) and current["content"].get("type") == 'image_url':
171
+ processed_image = self.upload_base64_image(
172
+ current["content"]["image_url"]["url"],
173
+ f"{CONFIG['API']['BASE_URL']}/api/rpc"
174
+ )
175
+ if processed_image:
176
+ file_attachments.append(processed_image)
177
+
178
+ text_content = process_content(current.get("content", ""))
179
+
180
+ if is_last_message and convert_to_file:
181
+ last_message_content = f"{role.upper()}: {text_content or '[图片]'}\n"
182
+ continue
183
+
184
+ if text_content or (is_last_message and file_attachments):
185
+ if role == last_role and text_content:
186
+ last_content += '\n' + text_content
187
+ messages = messages[:messages.rindex(f"{role.upper()}: ")] + f"{role.upper()}: {last_content}\n"
188
+ else:
189
+ messages += f"{role.upper()}: {text_content or '[图片]'}\n"
190
+ last_content = text_content
191
+ last_role = role
192
+
193
+ message_length += len(messages)
194
+ if message_length >= 40000:
195
+ convert_to_file = True
196
+
197
+ if convert_to_file:
198
+ file_id = self.upload_base64_file(messages, request["model"])
199
+ if file_id:
200
+ file_attachments.insert(0, file_id)
201
+ messages = last_message_content.strip()
202
+
203
+ if messages.strip() == '':
204
+ if convert_to_file:
205
+ messages = '基于txt文件内容进行回复:'
206
+ else:
207
+ raise ValueError('消息内容为空!')
208
+
209
+ return {
210
+ "temporary": CONFIG["API"].get("IS_TEMP_CONVERSATION", False),
211
+ "modelName": self.model_id,
212
+ "message": messages.strip(),
213
+ "fileAttachments": file_attachments[:4],
214
+ "imageAttachments": [],
215
+ "disableSearch": False,
216
+ "enableImageGeneration": True,
217
+ "returnImageBytes": False,
218
+ "enableImageStreaming": False,
219
+ "imageGenerationCount": 1,
220
+ "forceConcise": False,
221
+ "toolOverrides": {
222
+ "imageGen": request["model"] in ['grok-2-imageGen', 'grok-3-imageGen'],
223
+ "webSearch": search,
224
+ "xSearch": search,
225
+ "xMediaSearch": search,
226
+ "trendsSearch": search,
227
+ "xPostAnalyze": search
228
+ },
229
+ "enableSideBySide": True,
230
+ "isPreset": False,
231
+ "sendFinalMetadata": True,
232
+ "customInstructions": "",
233
+ "deepsearchPreset": "default" if request["model"] == 'grok-3-deepsearch' else "",
234
+ "isReasoning": request["model"] == 'grok-3-reasoning'
235
+ }
src/core/logger.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # src/core/logger.py
2
+ import sys
3
+ import inspect
4
+ import os
5
+ from loguru import logger
6
+
7
+ class Logger:
8
+ def __init__(self, level="INFO", colorize=True, format=None, max_logs=100):
9
+ """
10
+ 初始化 Logger 实例。
11
+
12
+ Args:
13
+ level (str): 日志级别。
14
+ colorize (bool): 是否彩色输出。
15
+ format (str): 日志格式。
16
+ max_logs (int): 存储的最大日志条数。
17
+ """
18
+ logger.remove()
19
+ if format is None:
20
+ format = (
21
+ "{time:YYYY-MM-DD HH:mm:ss} | "
22
+ "{level: <8} | "
23
+ "{extra[filename]}:{extra[function]}:{extra[lineno]} | "
24
+ "{message}"
25
+ )
26
+ logger.add(
27
+ sys.stderr,
28
+ level=level,
29
+ format=format,
30
+ colorize=colorize,
31
+ backtrace=True,
32
+ diagnose=True
33
+ )
34
+ self.logger = logger
35
+ self._log_history = [] # 存储日志历史
36
+ self._max_logs = max_logs # 最大日志条数
37
+
38
+ def _add_log_to_history(self, message, level, source):
39
+ """将日志添加到历史记录"""
40
+ timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
41
+ log_entry = f"{timestamp} | {level.upper(): <8} | [{source}] {message}"
42
+ self._log_history.append(log_entry)
43
+ # 保持日志历史在最大条数内
44
+ if len(self._log_history) > self._max_logs:
45
+ self._log_history = self._log_history[-self._max_logs:]
46
+
47
+ def get_recent_logs(self):
48
+ """获取最近的日志历史"""
49
+ return "\n".join(self._log_history)
50
+
51
+ def _get_caller_info(self):
52
+ frame = inspect.currentframe()
53
+ try:
54
+ caller_frame = frame.f_back.f_back
55
+ full_path = caller_frame.f_code.co_filename
56
+ function = caller_frame.f_code.co_name
57
+ lineno = caller_frame.f_lineno
58
+ filename = os.path.basename(full_path)
59
+ return {
60
+ 'filename': filename,
61
+ 'function': function,
62
+ 'lineno': lineno
63
+ }
64
+ finally:
65
+ del frame
66
+
67
+ def info(self, message, source="API"):
68
+ caller_info = self._get_caller_info()
69
+ log_message = f"[{source}] {message}"
70
+ self.logger.bind(**caller_info).info(log_message)
71
+ self._add_log_to_history(message, "INFO", source)
72
+
73
+ def error(self, message, source="API"):
74
+ caller_info = self._get_caller_info()
75
+ if isinstance(message, Exception):
76
+ log_message = f"[{source}] {str(message)}"
77
+ self.logger.bind(**caller_info).exception(log_message)
78
+ else:
79
+ log_message = f"[{source}] {message}"
80
+ self.logger.bind(**caller_info).error(log_message)
81
+ self._add_log_to_history(message, "ERROR", source)
82
+
83
+
84
+ def warning(self, message, source="API"):
85
+ caller_info = self._get_caller_info()
86
+ log_message = f"[{source}] {message}"
87
+ self.logger.bind(**caller_info).warning(log_message)
88
+ self._add_log_to_history(message, "WARNING", source)
89
+
90
+ def debug(self, message, source="API"):
91
+ caller_info = self._get_caller_info()
92
+ log_message = f"[{source}] {message}"
93
+ self.logger.bind(**caller_info).debug(log_message)
94
+ self._add_log_to_history(message, "DEBUG", source)
95
+
96
+
97
+ async def request_logger(self, request):
98
+ caller_info = self._get_caller_info()
99
+ log_message = f"请求: {request.method} {request.path}"
100
+ self.logger.bind(**caller_info).info(log_message, "Request")
101
+ self._add_log_to_history(log_message, "INFO", "Request")
102
+
103
+
104
+ # 初始化全局 logger 实例
105
+ logger = Logger(level="INFO")
src/core/message_processor.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # src/core/message_processor.py
2
+ import json
3
+ import time
4
+ import base64
5
+ import uuid
6
+ import requests
7
+ from curl_cffi import requests as curl_requests
8
+
9
+ from src.core.logger import logger # 从新的位置导入 logger
10
+ from src.core.utils import Utils # 从新的位置导入 Utils
11
+ from app import CONFIG, DEFAULT_HEADERS # 导入 CONFIG 和 DEFAULT_HEADERS
12
+
13
+ class MessageProcessor:
14
+ @staticmethod
15
+ def create_chat_response(message, model, is_stream=False):
16
+ base_response = {
17
+ "id": f"chatcmpl-{uuid.uuid4()}",
18
+ "created": int(time.time()),
19
+ "model": model
20
+ }
21
+ if is_stream:
22
+ return {
23
+ **base_response,
24
+ "object": "chat.completion.chunk",
25
+ "choices": [{
26
+ "index": 0,
27
+ "delta": {
28
+ "content": message
29
+ }
30
+ }]
31
+ }
32
+ return {
33
+ **base_response,
34
+ "object": "chat.completion",
35
+ "choices": [{
36
+ "index": 0,
37
+ "message": {
38
+ "role": "assistant",
39
+ "content": message
40
+ },
41
+ "finish_reason": "stop"
42
+ }],
43
+ "usage": None
44
+ }
45
+
46
+ def process_model_response(response, model):
47
+ result = {"token": None, "imageUrl": None}
48
+ if CONFIG["IS_IMG_GEN"]:
49
+ if response.get("cachedImageGenerationResponse") and not CONFIG["IS_IMG_GEN2"]:
50
+ result["imageUrl"] = response["cachedImageGenerationResponse"]["imageUrl"]
51
+ return result
52
+
53
+ if model == 'grok-2':
54
+ result["token"] = response.get("token")
55
+ elif model in ['grok-2-search', 'grok-3-search']:
56
+ if response.get("webSearchResults") and CONFIG["ISSHOW_SEARCH_RESULTS"]:
57
+ result["token"] = f"\r\n{Utils.organize_search_results(response['webSearchResults'])}\r\n"
58
+ else:
59
+ result["token"] = response.get("token")
60
+ elif model == 'grok-3':
61
+ result["token"] = response.get("token")
62
+ elif model == 'grok-3-deepsearch':
63
+ if response.get("messageStepId") and not CONFIG["SHOW_THINKING"]:
64
+ return result
65
+ if response.get("messageStepId") and not CONFIG["IS_THINKING"]:
66
+ result["token"] = "" + response.get("token", "")
67
+ CONFIG["IS_THINKING"] = True
68
+ elif not response.get("messageStepId") and CONFIG["IS_THINKING"] and response.get("messageTag") == "final":
69
+ result["token"] = "" + response.get("token", "")
70
+ CONFIG["IS_THINKING"] = False
71
+ elif (response.get("messageStepId") and CONFIG["IS_THINKING"] and response.get("messageTag") == "assistant") or response.get("messageTag") == "final":
72
+ result["token"] = response.get("token")
73
+ elif model == 'grok-3-reasoning':
74
+ if response.get("isThinking") and not CONFIG["SHOW_THINKING"]:
75
+ return result
76
+ if response.get("isThinking") and not CONFIG["IS_THINKING"]:
77
+ result["token"] = "" + response.get("token", "")
78
+ CONFIG["IS_THINKING"] = True
79
+ elif not response.get("isThinking") and CONFIG["IS_THINKING"]:
80
+ result["token"] = "" + response.get("token", "")
81
+ CONFIG["IS_THINKING"] = False
82
+ else:
83
+ result["token"] = response.get("token")
84
+
85
+ return result
86
+
87
+ def handle_image_response(image_url):
88
+ max_retries = 2
89
+ retry_count = 0
90
+ image_base64_response = None
91
+ while retry_count < max_retries:
92
+ try:
93
+ proxy_options = Utils.get_proxy_options()
94
+ image_base64_response = curl_requests.get(
95
+ f"https://assets.grok.com/{image_url}",
96
+ headers={
97
+ **DEFAULT_HEADERS,
98
+ "Cookie":CONFIG["SERVER"]['COOKIE']
99
+ },
100
+ impersonate="chrome133a",
101
+ **proxy_options
102
+ )
103
+ if image_base64_response.status_code == 200:
104
+ break
105
+ retry_count += 1
106
+ if retry_count == max_retries:
107
+ raise Exception(f"上游服务请求失败! status: {image_base64_response.status_code}")
108
+ time.sleep(CONFIG["API"]["RETRY_TIME"] / 1000 * retry_count)
109
+ except Exception as error:
110
+ logger.error(str(error), "Server")
111
+ retry_count += 1
112
+ if retry_count == max_retries:
113
+ raise
114
+ time.sleep(CONFIG["API"]["RETRY_TIME"] / 1000 * retry_count)
115
+
116
+ image_buffer = image_base64_response.content
117
+
118
+ if not CONFIG["API"]["PICGO_KEY"] and not CONFIG["API"]["TUMY_KEY"]:
119
+ base64_image = base64.b64encode(image_buffer).decode('utf-8')
120
+ image_content_type = image_base64_response.headers.get('content-type', 'image/jpeg')
121
+ return f"![image](data:{image_content_type};base64,{base64_image})"
122
+
123
+ logger.info("开始上传图床", "Server")
124
+ if CONFIG["API"]["PICGO_KEY"]:
125
+ files = {'source': ('image.jpg', image_buffer, 'image/jpeg')}
126
+ headers = {
127
+ "X-API-Key": CONFIG["API"]["PICGO_KEY"]
128
+ }
129
+ response_url = requests.post(
130
+ "https://www.picgo.net/api/1/upload",
131
+ files=files,
132
+ headers=headers
133
+ )
134
+ if response_url.status_code != 200:
135
+ return "生图失败,请查看PICGO图床密钥是否设置正确"
136
+ else:
137
+ logger.info("生图成功", "Server")
138
+ result = response_url.json()
139
+ return f"![image]({result['image']['url']})"
140
+ elif CONFIG["API"]["TUMY_KEY"]:
141
+ files = {'file': ('image.jpg', image_buffer, 'image/jpeg')}
142
+ headers = {
143
+ "Accept": "application/json",
144
+ 'Authorization': f"Bearer {CONFIG['API']['TUMY_KEY']}"
145
+ }
146
+ response_url = requests.post(
147
+ "https://tu.my/api/v1/upload",
148
+ files=files,
149
+ headers=headers
150
+ )
151
+ if response_url.status_code != 200:
152
+ return "生图失败,请查看TUMY图床密钥是否设置正确"
153
+ else:
154
+ try:
155
+ result = response_url.json()
156
+ logger.info("生图成功", "Server")
157
+ return f"![image]({result['data']['links']['url']})"
158
+ except Exception as error:
159
+ logger.error(str(error), "Server")
160
+ return "生图失败,请查看TUMY图床密钥是否设置正确"
161
+
162
+
163
+ def handle_non_stream_response(response, model):
164
+ try:
165
+ logger.info("开始处理非流式响应", "Server")
166
+ stream = response.iter_lines()
167
+ full_response = ""
168
+ CONFIG["IS_THINKING"] = False
169
+ CONFIG["IS_IMG_GEN"] = False
170
+ CONFIG["IS_IMG_GEN2"] = False
171
+ for chunk in stream:
172
+ if not chunk:
173
+ continue
174
+ try:
175
+ line_json = json.loads(chunk.decode("utf-8").strip())
176
+ if line_json.get("error"):
177
+ logger.error(json.dumps(line_json, indent=2), "Server")
178
+ yield json.dumps({"error": "RateLimitError"}) + "\n\n"
179
+ return
180
+
181
+ response_data = line_json.get("result", {}).get("response")
182
+ if not response_data:
183
+ continue
184
+
185
+ if response_data.get("doImgGen") or response_data.get("imageAttachmentInfo"):
186
+ CONFIG["IS_IMG_GEN"] = True
187
+
188
+ result = process_model_response(response_data, model)
189
+ if result["token"]:
190
+ full_response += result["token"]
191
+ if result["imageUrl"]:
192
+ CONFIG["IS_IMG_GEN2"] = True
193
+ return handle_image_response(result["imageUrl"])
194
+
195
+ except json.JSONDecodeError:
196
+ continue
197
+ except Exception as e:
198
+ logger.error(f"处理流式响应行时出错: {str(e)}", "Server")
199
+ continue
200
+ return full_response
201
+ except Exception as error:
202
+ logger.error(str(error), "Server")
203
+ raise
204
+
205
+ def handle_stream_response(response, model):
206
+ def generate():
207
+ logger.info("开始处理流式响应", "Server")
208
+ stream = response.iter_lines()
209
+ CONFIG["IS_THINKING"] = False
210
+ CONFIG["IS_IMG_GEN"] = False
211
+ CONFIG["IS_IMG_GEN2"] = False
212
+ for chunk in stream:
213
+ if not chunk:
214
+ continue
215
+ try:
216
+ line_json = json.loads(chunk.decode("utf-8").strip())
217
+ if line_json.get("error"):
218
+ logger.error(json.dumps(line_json, indent=2), "Server")
219
+ yield json.dumps({"error": "RateLimitError"}) + "\n\n"
220
+ return
221
+
222
+ response_data = line_json.get("result", {}).get("response")
223
+ if not response_data:
224
+ continue
225
+
226
+ if response_data.get("doImgGen") or response_data.get("imageAttachmentInfo"):
227
+ CONFIG["IS_IMG_GEN"] = True
228
+
229
+ result = process_model_response(response_data, model)
230
+ if result["token"]:
231
+ yield f"data: {json.dumps(MessageProcessor.create_chat_response(result['token'], model, True))}\n\n"
232
+ if result["imageUrl"]:
233
+ CONFIG["IS_IMG_GEN2"] = True
234
+ image_data = handle_image_response(result["imageUrl"])
235
+ yield f"data: {json.dumps(MessageProcessor.create_chat_response(image_data, model, True))}\n\n"
236
+
237
+ except json.JSONDecodeError:
238
+ continue
239
+ except Exception as e:
240
+ logger.error(f"处理流式响应行时出错: {str(e)}", "Server")
241
+ continue
242
+
243
+ yield "data: [DONE]\n\n"
244
+
245
+ return generate()
src/core/utils.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # src/core/utils.py
2
+ import json
3
+ import time
4
+ import base64
5
+ import re
6
+ import requests
7
+ from src.core.logger import logger # 从新的位置导入 logger
8
+ from src.core.auth_token_manager import AuthTokenManager # 从新的位置导入 AuthTokenManager
9
+ from app import CONFIG, DEFAULT_HEADERS, token_manager # 导入 CONFIG, DEFAULT_HEADERS 和 token_manager
10
+
11
+ class Utils:
12
+ @staticmethod
13
+ def organize_search_results(search_results):
14
+ if not search_results or 'results' not in search_results:
15
+ return ''
16
+ results = search_results['results']
17
+ formatted_results = []
18
+ for index, result in enumerate(results):
19
+ title = result.get('title', '未知标题')
20
+ url = result.get('url', '#')
21
+ preview = result.get('preview', '无预览内容')
22
+ formatted_result = f"\r\n资料[{index}]: {title}\r\n{preview}\r\n\n[Link]({url})\r\n"
23
+ formatted_results.append(formatted_result)
24
+ return '\n\n'.join(formatted_results)
25
+
26
+ @staticmethod
27
+ def create_auth_headers(model, is_return=False):
28
+ return token_manager.get_next_token_for_model(model, is_return)
29
+
30
+ @staticmethod
31
+ def get_proxy_options():
32
+ proxy = CONFIG["API"]["PROXY"]
33
+ proxy_options = {}
34
+ if proxy:
35
+ logger.info(f"使用代理: {proxy}", "Server")
36
+ if proxy.startswith("socks5://"):
37
+ proxy_options["proxy"] = proxy
38
+ if '@' in proxy:
39
+ auth_part = proxy.split('@')[0].split('://')[1]
40
+ if ':' in auth_part:
41
+ username, password = auth_part.split(':')
42
+ proxy_options["proxy_auth"] = (username, password)
43
+ else:
44
+ proxy_options["proxies"] = {"https": proxy, "http": proxy}
45
+ return proxy_options
static/script.js ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // 页面加载完成后执行
2
+ document.addEventListener('DOMContentLoaded', function() {
3
+ // 获取系统状态数据并更新页面
4
+ fetchSystemStatus();
5
+
6
+ // 可以设置定时器,定期更新数据
7
+ // setInterval(fetchSystemStatus, 5000); // 每5秒更新一次
8
+ });
9
+
10
+ function fetchSystemStatus() {
11
+ // 假设后端有一个 /status 路由返回 JSON 数据
12
+ fetch('/status')
13
+ .then(response => response.json())
14
+ .then(data => {
15
+ // 更新配置信息
16
+ document.getElementById('api-base-url').textContent = data.config.api_base_url;
17
+ document.getElementById('log-level').textContent = data.config.log_level;
18
+ // 更新其他配置项...
19
+
20
+ // 更新令牌状态
21
+ document.getElementById('total-tokens').textContent = data.token_status.total_tokens;
22
+ document.getElementById('available-tokens').textContent = data.token_status.available_tokens;
23
+ document.getElementById('request-count').textContent = data.token_status.request_count;
24
+ // 更新其他令牌状态...
25
+
26
+ // 更新日志摘要
27
+ document.getElementById('log-summary').textContent = data.log_summary;
28
+ })
29
+ .catch(error => {
30
+ console.error('获取系统状态失败:', error);
31
+ document.getElementById('config-info').textContent = '加载失败。';
32
+ document.getElementById('token-status').textContent = '加载失败。';
33
+ document.getElementById('log-summary').textContent = '加载失败。';
34
+ });
35
+ }
static/style.css ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* 通用样式 */
2
+ body {
3
+ font-family: sans-serif;
4
+ line-height: 1.6;
5
+ margin: 0;
6
+ padding: 20px;
7
+ background-color: #f4f4f4;
8
+ color: #333;
9
+ }
10
+
11
+ .container {
12
+ max-width: 900px;
13
+ margin: auto;
14
+ background: #fff;
15
+ padding: 20px;
16
+ border-radius: 8px;
17
+ box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
18
+ }
19
+
20
+ h1, h2 {
21
+ color: #0056b3;
22
+ }
23
+
24
+ h1 {
25
+ text-align: center;
26
+ margin-bottom: 20px;
27
+ }
28
+
29
+ .status-section {
30
+ margin-bottom: 20px;
31
+ padding: 15px;
32
+ border: 1px solid #ddd;
33
+ border-radius: 5px;
34
+ }
35
+
36
+ .status-section h2 {
37
+ margin-top: 0;
38
+ border-bottom: 1px solid #eee;
39
+ padding-bottom: 10px;
40
+ margin-bottom: 15px;
41
+ color: #007bff;
42
+ }
43
+
44
+ /* 配置信息和令牌状态样式 */
45
+ #config-info p,
46
+ #token-status p {
47
+ margin: 5px 0;
48
+ }
49
+
50
+ #config-info strong,
51
+ #token-status strong {
52
+ display: inline-block;
53
+ width: 120px; /* 固定宽度以便对齐 */
54
+ }
55
+
56
+ /* 日志摘要样式 */
57
+ #log-summary {
58
+ background-color: #e9e9e9;
59
+ padding: 10px;
60
+ border-radius: 4px;
61
+ white-space: pre-wrap; /* 保留换行符和空格 */
62
+ font-family: monospace;
63
+ max-height: 300px; /* 限制高度并添加滚动条 */
64
+ overflow-y: auto;
65
+ }
templates/index.html ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Grok API System Status</title>
7
+ <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
8
+ </head>
9
+ <body>
10
+ <div class="container">
11
+ <h1>Grok API 系统状态</h1>
12
+
13
+ <section class="status-section">
14
+ <h2>配置信息</h2>
15
+ <div id="config-info">
16
+ <p><strong>API Base URL:</strong> <span id="api-base-url">加载中...</span></p>
17
+ <p><strong>Log Level:</strong> <span id="log-level">加载中...</span></p>
18
+ <!-- 其他配置项 -->
19
+ </div>
20
+ </section>
21
+
22
+ <section class="status-section">
23
+ <h2>令牌状态</h2>
24
+ <div id="token-status">
25
+ <p><strong>总令牌数:</strong> <span id="total-tokens">加载中...</span></p>
26
+ <p><strong>可用令牌数:</strong> <span id="available-tokens">加载中...</span></p>
27
+ <p><strong>请求次数:</strong> <span id="request-count">加载中...</span></p>
28
+ <!-- 其他令牌状态 -->
29
+ </div>
30
+ </section>
31
+
32
+ <section class="status-section">
33
+ <h2>日志摘要</h2>
34
+ <div id="log-summary">
35
+ <p>加载中...</p>
36
+ <!-- 日志内容将在此处加载 -->
37
+ </div>
38
+ </section>
39
+ </div>
40
+
41
+ <script src="{{ url_for('static', filename='script.js') }}"></script>
42
+ </body>
43
+ </html>