light_shirt commited on
Commit
cb8f5d0
·
1 Parent(s): f687b59

Remove legacy Grok app; keep only OpenVINO embedding Space

Browse files

Clear old app/, main.py, requirements.txt and related files so Docker
builds the Qwen3-0.6B embedding service only.

.dockerignore CHANGED
@@ -1,140 +1,17 @@
1
- # Python 运行时和缓存文件
2
- __pycache__/
3
- *.py[cod]
4
- *$py.class
5
- *.so
6
- .Python
7
- *.egg-info/
8
- dist/
9
- build/
10
- *.egg
11
- .eggs/
12
- pip-log.txt
13
- pip-delete-this-directory.txt
14
-
15
- # 虚拟环境
16
- venv/
17
- env/
18
- ENV/
19
- .venv/
20
- .virtualenv/
21
- pipenv/
22
- poetry.lock
23
- Pipfile.lock
24
-
25
- # IDE 和编辑器
26
- .vscode/
27
- .idea/
28
- *.swp
29
- *.swo
30
- *.swn
31
- .DS_Store
32
- *~
33
- .project
34
- .classpath
35
- .settings/
36
- *.sublime-project
37
- *.sublime-workspace
38
-
39
- # Git
40
- .git/
41
- .gitignore
42
- .gitattributes
43
- .gitmodules
44
-
45
- # Docker 相关
46
- Dockerfile*
47
- docker-compose*.yml
48
- .dockerignore
49
- .docker/
50
-
51
- # 文档和说明
52
- *.md
53
- !data/*.md
54
- README.md
55
- docs/
56
- LICENSE
57
- CHANGELOG*
58
- CONTRIBUTING*
59
-
60
- # 测试和质量检查
61
- tests/
62
- test/
63
- *.pytest_cache/
64
- .coverage
65
- .coverage.*
66
- htmlcov/
67
- .tox/
68
- .mypy_cache/
69
- .ruff_cache/
70
- .pytest_cache/
71
- .hypothesis/
72
- .pytype/
73
- coverage.xml
74
- *.cover
75
- .cache/
76
- nosetests.xml
77
-
78
- # 日志和运行时数据
79
- logs/
80
- *.log
81
- *.log.*
82
-
83
- # 数据临时文件
84
- data/temp/
85
- data/token.json
86
-
87
- # 数据库文件
88
- *.db
89
- *.sqlite
90
- *.sqlite3
91
-
92
- # 临时文件
93
- tmp/
94
- temp/
95
- *.tmp
96
- *.temp
97
- *.bak
98
- *.orig
99
- *.rej
100
- *.swp
101
-
102
- # CI/CD
103
- .github/
104
- .gitlab-ci.yml
105
- .travis.yml
106
- .circleci/
107
- azure-pipelines.yml
108
- .jenkins/
109
- Jenkinsfile
110
-
111
- # 环境变量和密钥
112
- .env
113
- .env.*
114
- *.key
115
- *.pem
116
- *.crt
117
- secrets/
118
-
119
- # 媒体和大文件
120
- *.mp4
121
- *.avi
122
- *.mov
123
- *.zip
124
- *.tar
125
- *.tar.gz
126
- *.rar
127
-
128
- # Node.js
129
- node_modules/
130
- npm-debug.log*
131
- yarn-debug.log*
132
- yarn-error.log*
133
- package-lock.json
134
- yarn.lock
135
-
136
- # 其他
137
- *.pyc
138
- .Python
139
- .sass-cache/
140
- .ipynb_checkpoints/
 
1
+ .venv
2
+ .claude
3
+ hf_cache
4
+ uv_cache
5
+ python
6
+ **/__pycache__
7
+ **/*.pyc
8
+ uv.lock
9
+ 使用说明.md
10
+ fix_shape.py
11
+ start.bat
12
+ start.ps1
13
+ .git
14
+ models/bge-small-zh-v1.5
15
+ models/**/*.pt
16
+ models/**/*.pth
17
+ models/**/*.onnx
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.gitignore DELETED
@@ -1,184 +0,0 @@
1
- # Byte-compiled / optimized / DLL files
2
- __pycache__/
3
- *.py[cod]
4
- *$py.class
5
- .idea
6
-
7
- # C extensions
8
- *.so
9
-
10
- # Distribution / packaging
11
- .Python
12
- build/
13
- develop-eggs/
14
- dist/
15
- downloads/
16
- eggs/
17
- .eggs/
18
- lib/
19
- lib64/
20
- parts/
21
- sdist/
22
- var/
23
- wheels/
24
- share/python-wheels/
25
- *.egg-info/
26
- .installed.cfg
27
- *.egg
28
- MANIFEST
29
-
30
- # PyInstaller
31
- # Usually these files are written by a python script from a template
32
- # before PyInstaller builds the exe, so as to inject date/other infos into it.
33
- *.manifest
34
- *.spec
35
-
36
- # Installer logs
37
- pip-log.txt
38
- pip-delete-this-directory.txt
39
-
40
- # Unit test / coverage reports
41
- htmlcov/
42
- .tox/
43
- .nox/
44
- .coverage
45
- .coverage.*
46
- .cache
47
- nosetests.xml
48
- coverage.xml
49
- *.cover
50
- *.py,cover
51
- .hypothesis/
52
- .pytest_cache/
53
- cover/
54
-
55
- # Translations
56
- *.mo
57
- *.pot
58
-
59
- # Django stuff:
60
- *.log
61
- local_settings.py
62
- db.sqlite3
63
- db.sqlite3-journal
64
-
65
- # Flask stuff:
66
- instance/
67
- .webassets-cache
68
-
69
- # Scrapy stuff:
70
- .scrapy
71
-
72
- # Sphinx documentation
73
- docs/_build/
74
-
75
- # PyBuilder
76
- .pybuilder/
77
- target/
78
-
79
- # Jupyter Notebook
80
- .ipynb_checkpoints
81
-
82
- # IPython
83
- profile_default/
84
- ipython_config.py
85
-
86
- # pyenv
87
- # For a library or package, you might want to ignore these files since the code is
88
- # intended to run in multiple environments; otherwise, check them in:
89
- # .python-version
90
-
91
- # pipenv
92
- # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
93
- # However, in case of collaboration, if having platform-specific dependencies or dependencies
94
- # having no cross-platform support, pipenv may install dependencies that don't work, or not
95
- # install all needed dependencies.
96
- #Pipfile.lock
97
-
98
- # UV
99
- # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
100
- # This is especially recommended for binary packages to ensure reproducibility, and is more
101
- # commonly ignored for libraries.
102
- #uv.lock
103
-
104
- # poetry
105
- # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
106
- # This is especially recommended for binary packages to ensure reproducibility, and is more
107
- # commonly ignored for libraries.
108
- # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
109
- #poetry.lock
110
-
111
- # pdm
112
- # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
- #pdm.lock
114
- # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
115
- # in version control.
116
- # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
117
- .pdm.toml
118
- .pdm-python
119
- .pdm-build/
120
-
121
- # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
122
- __pypackages__/
123
-
124
- # Celery stuff
125
- celerybeat-schedule
126
- celerybeat.pid
127
-
128
- # SageMath parsed files
129
- *.sage.py
130
-
131
- # Environments
132
- .env
133
- .venv
134
- env/
135
- venv/
136
- ENV/
137
- env.bak/
138
- venv.bak/
139
-
140
- logs/*
141
-
142
- # Spyder project settings
143
- .spyderproject
144
- .spyproject
145
-
146
- # Rope project settings
147
- .ropeproject
148
-
149
- # mkdocs documentation
150
- /site
151
-
152
- # mypy
153
- .mypy_cache/
154
- .dmypy.json
155
- dmypy.json
156
-
157
- # Pyre type checker
158
- .pyre/
159
-
160
- # pytype static type analyzer
161
- .pytype/
162
-
163
- # Cython debug symbols
164
- cython_debug/
165
-
166
- # PyCharm
167
- # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
168
- # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
169
- # and can be added to the global gitignore or merged into this file. For a more nuclear
170
- # option (not recommended) you can uncomment the following to ignore the entire idea folder.
171
- #.idea/
172
-
173
- # Ruff stuff:
174
- .ruff_cache/
175
-
176
- # PyPI configuration file
177
- .pypirc
178
-
179
- # Cursor
180
- # Cursor is an AI-powered code editor.`.cursorignore` specifies files/directories to
181
- # exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
182
- # refer to https://docs.cursor.com/context/ignore-files
183
- .cursorignore
184
- .cursorindexingignore
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.python-version DELETED
@@ -1 +0,0 @@
1
- 3.13
 
 
LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2025 Chenyme
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
README.md CHANGED
@@ -1,10 +1,68 @@
1
  ---
2
- title: Gr2
3
- emoji: 🏃
4
- colorFrom: green
5
- colorTo: red
6
  sdk: docker
 
7
  pinned: false
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: OpenVINO Qwen3 Embedding
3
+ emoji: 🚀
4
+ colorFrom: blue
5
+ colorTo: indigo
6
  sdk: docker
7
+ app_port: 7860
8
  pinned: false
9
+ license: apache-2.0
10
  ---
11
 
12
+ # OpenVINO Embedding (Qwen3-0.6B)
13
+
14
+ OpenAI 兼容 Embedding API,OpenVINO CPU 推理。
15
+
16
+ - 默认模型:`Qwen/Qwen3-Embedding-0.6B`(IR 预导出)
17
+ - 接口:`POST /v1/embeddings`
18
+ - 文档:`/docs`
19
+ - 健康检查:`/health`
20
+
21
+ ## 调用示例
22
+
23
+ ```bash
24
+ curl -X POST "$SPACE_URL/v1/embeddings" \
25
+ -H "Content-Type: application/json" \
26
+ -d '{
27
+ "input": "什么是向量检索?",
28
+ "model": "qwen3-embedding-0.6b"
29
+ }'
30
+ ```
31
+
32
+ ### Query instruct(推荐检索 query)
33
+
34
+ 默认开启模型自带 retrieval instruct。
35
+ **文档索引**时请显式关闭:
36
+
37
+ ```json
38
+ {
39
+ "input": "文档正文……",
40
+ "model": "qwen3-embedding-0.6b",
41
+ "instruction": ""
42
+ }
43
+ ```
44
+
45
+ 自定义任务:
46
+
47
+ ```json
48
+ {
49
+ "input": "用户问题",
50
+ "instruction": "Given a question, retrieve relevant Chinese documentation"
51
+ }
52
+ ```
53
+
54
+ ## 免费 CPU 说明
55
+
56
+ - 硬件:2 vCPU / 16GB
57
+ - 默认 `MAX_LENGTH=1024`,`CPU_MAX_BATCH=4`(可用 Space Variables 改)
58
+ - 建议上传 **INT8** IR(`export_model.py --int8 --force`),体积更小、内存更稳
59
+ - 首次冷启动需加载 IR,可能需数十秒
60
+ - 更长上下文可设 `MAX_LENGTH=2048`,但 2 核上延迟会明显上升
61
+
62
+ ## 本地导出 IR 再部署
63
+
64
+ ```powershell
65
+ uv sync
66
+ .\.venv\Scripts\python.exe export_model.py qwen3-embedding-0.6b --int8 --force
67
+ # 确认 models/qwen3-embedding-0.6b/ 下 bin 约 500~700MB 后 push 到 Space
68
+ ```
app/api/admin/manage.py DELETED
@@ -1,622 +0,0 @@
1
- """管理接口 - Token管理和系统配置"""
2
-
3
- import secrets
4
- from typing import Dict, Any, List, Optional
5
- from datetime import datetime, timedelta
6
- from pathlib import Path
7
- from fastapi import APIRouter, HTTPException, Depends, Header
8
- from fastapi.responses import HTMLResponse
9
- from pydantic import BaseModel
10
-
11
- from app.core.config import setting
12
- from app.core.logger import logger
13
- from app.services.grok.token import token_manager
14
- from app.models.grok_models import TokenType
15
-
16
-
17
- router = APIRouter(tags=["管理"])
18
-
19
- # 常量
20
- STATIC_DIR = Path(__file__).parents[2] / "template"
21
- TEMP_DIR = Path(__file__).parents[3] / "data" / "temp"
22
- IMAGE_CACHE_DIR = TEMP_DIR / "image"
23
- VIDEO_CACHE_DIR = TEMP_DIR / "video"
24
- SESSION_EXPIRE_HOURS = 24
25
- BYTES_PER_KB = 1024
26
- BYTES_PER_MB = 1024 * 1024
27
-
28
- # 会话存储
29
- _sessions: Dict[str, datetime] = {}
30
-
31
-
32
- # === 请求/响应模型 ===
33
-
34
- class LoginRequest(BaseModel):
35
- username: str
36
- password: str
37
-
38
-
39
- class LoginResponse(BaseModel):
40
- success: bool
41
- token: Optional[str] = None
42
- message: str
43
-
44
-
45
- class AddTokensRequest(BaseModel):
46
- tokens: List[str]
47
- token_type: str
48
-
49
-
50
- class DeleteTokensRequest(BaseModel):
51
- tokens: List[str]
52
- token_type: str
53
-
54
-
55
- class TokenInfo(BaseModel):
56
- token: str
57
- token_type: str
58
- created_time: Optional[int] = None
59
- remaining_queries: int
60
- heavy_remaining_queries: int
61
- status: str
62
- tags: List[str] = []
63
- note: str = ""
64
-
65
-
66
- class TokenListResponse(BaseModel):
67
- success: bool
68
- data: List[TokenInfo]
69
- total: int
70
-
71
-
72
- class UpdateSettingsRequest(BaseModel):
73
- global_config: Optional[Dict[str, Any]] = None
74
- grok_config: Optional[Dict[str, Any]] = None
75
-
76
-
77
- class UpdateTokenTagsRequest(BaseModel):
78
- token: str
79
- token_type: str
80
- tags: List[str]
81
-
82
-
83
- class UpdateTokenNoteRequest(BaseModel):
84
- token: str
85
- token_type: str
86
- note: str
87
-
88
-
89
- class TestTokenRequest(BaseModel):
90
- token: str
91
- token_type: str
92
-
93
-
94
- # === 辅助函数 ===
95
-
96
- def validate_token_type(token_type_str: str) -> TokenType:
97
- """验证Token类型"""
98
- if token_type_str not in ["sso", "ssoSuper"]:
99
- raise HTTPException(
100
- status_code=400,
101
- detail={"error": "无效的Token类型", "code": "INVALID_TYPE"}
102
- )
103
- return TokenType.NORMAL if token_type_str == "sso" else TokenType.SUPER
104
-
105
-
106
- def parse_created_time(created_time) -> Optional[int]:
107
- """解析创建时间"""
108
- if isinstance(created_time, str):
109
- return int(created_time) if created_time else None
110
- elif isinstance(created_time, int):
111
- return created_time
112
- return None
113
-
114
-
115
- def calculate_token_stats(tokens: Dict[str, Any], token_type: str) -> Dict[str, int]:
116
- """计算Token统计"""
117
- total = len(tokens)
118
- expired = sum(1 for t in tokens.values() if t.get("status") == "expired")
119
-
120
- if token_type == "normal":
121
- unused = sum(1 for t in tokens.values()
122
- if t.get("status") != "expired" and t.get("remainingQueries", -1) == -1)
123
- limited = sum(1 for t in tokens.values()
124
- if t.get("status") != "expired" and t.get("remainingQueries", -1) == 0)
125
- active = sum(1 for t in tokens.values()
126
- if t.get("status") != "expired" and t.get("remainingQueries", -1) > 0)
127
- else:
128
- unused = sum(1 for t in tokens.values()
129
- if t.get("status") != "expired" and
130
- t.get("remainingQueries", -1) == -1 and t.get("heavyremainingQueries", -1) == -1)
131
- limited = sum(1 for t in tokens.values()
132
- if t.get("status") != "expired" and
133
- (t.get("remainingQueries", -1) == 0 or t.get("heavyremainingQueries", -1) == 0))
134
- active = sum(1 for t in tokens.values()
135
- if t.get("status") != "expired" and
136
- (t.get("remainingQueries", -1) > 0 or t.get("heavyremainingQueries", -1) > 0))
137
-
138
- return {"total": total, "unused": unused, "limited": limited, "expired": expired, "active": active}
139
-
140
-
141
- def verify_admin_session(authorization: Optional[str] = Header(None)) -> bool:
142
- """验证管理员会话"""
143
- if not authorization or not authorization.startswith("Bearer "):
144
- raise HTTPException(status_code=401, detail={"error": "未授权访问", "code": "UNAUTHORIZED"})
145
-
146
- token = authorization[7:]
147
-
148
- if token not in _sessions:
149
- raise HTTPException(status_code=401, detail={"error": "会话无效", "code": "SESSION_INVALID"})
150
-
151
- if datetime.now() > _sessions[token]:
152
- del _sessions[token]
153
- raise HTTPException(status_code=401, detail={"error": "会话已过期", "code": "SESSION_EXPIRED"})
154
-
155
- return True
156
-
157
-
158
- def get_token_status(token_data: Dict[str, Any], token_type: str) -> str:
159
- """获取Token状态"""
160
- if token_data.get("status") == "expired":
161
- return "失效"
162
-
163
- remaining = token_data.get("remainingQueries", -1)
164
- heavy_remaining = token_data.get("heavyremainingQueries", -1)
165
-
166
- relevant = max(remaining, heavy_remaining) if token_type == "ssoSuper" else remaining
167
-
168
- if relevant == -1:
169
- return "未使用"
170
- elif relevant == 0:
171
- return "限流中"
172
- else:
173
- return "正常"
174
-
175
-
176
- def _calculate_dir_size(directory: Path) -> int:
177
- """计算目录大小"""
178
- total = 0
179
- for file_path in directory.iterdir():
180
- if file_path.is_file():
181
- try:
182
- total += file_path.stat().st_size
183
- except Exception as e:
184
- logger.warning(f"[Admin] 无法获取文件大小: {file_path.name}, {e}")
185
- return total
186
-
187
-
188
- def _format_size(size_bytes: int) -> str:
189
- """格式化文件大小"""
190
- size_mb = size_bytes / BYTES_PER_MB
191
- if size_mb < 1:
192
- return f"{size_bytes / BYTES_PER_KB:.1f} KB"
193
- return f"{size_mb:.1f} MB"
194
-
195
-
196
- # === 页面路由 ===
197
-
198
- @router.get("/login", response_class=HTMLResponse)
199
- async def login_page():
200
- """登录页面"""
201
- login_html = STATIC_DIR / "login.html"
202
- if login_html.exists():
203
- return login_html.read_text(encoding="utf-8")
204
- raise HTTPException(status_code=404, detail="登录页面不存在")
205
-
206
-
207
- @router.get("/manage", response_class=HTMLResponse)
208
- async def manage_page():
209
- """管理页面"""
210
- admin_html = STATIC_DIR / "admin.html"
211
- if admin_html.exists():
212
- return admin_html.read_text(encoding="utf-8")
213
- raise HTTPException(status_code=404, detail="管理页面不存在")
214
-
215
-
216
- # === API端点 ===
217
-
218
- @router.post("/api/login", response_model=LoginResponse)
219
- async def admin_login(request: LoginRequest) -> LoginResponse:
220
- """管理员登录"""
221
- try:
222
- logger.debug(f"[Admin] 登录尝试: {request.username}")
223
-
224
- expected_user = setting.global_config.get("admin_username", "")
225
- expected_pass = setting.global_config.get("admin_password", "")
226
-
227
- if request.username != expected_user or request.password != expected_pass:
228
- logger.warning(f"[Admin] 登录失败: {request.username}")
229
- return LoginResponse(success=False, message="用户名或密码错误")
230
-
231
- session_token = secrets.token_urlsafe(32)
232
- _sessions[session_token] = datetime.now() + timedelta(hours=SESSION_EXPIRE_HOURS)
233
-
234
- logger.debug(f"[Admin] 登录成功: {request.username}")
235
- return LoginResponse(success=True, token=session_token, message="登录成功")
236
-
237
- except Exception as e:
238
- logger.error(f"[Admin] 登录异常: {e}")
239
- raise HTTPException(status_code=500, detail={"error": f"登录失败: {e}", "code": "LOGIN_ERROR"})
240
-
241
-
242
- @router.post("/api/logout")
243
- async def admin_logout(_: bool = Depends(verify_admin_session), authorization: Optional[str] = Header(None)) -> Dict[str, Any]:
244
- """管理员登出"""
245
- try:
246
- if authorization and authorization.startswith("Bearer "):
247
- token = authorization[7:]
248
- if token in _sessions:
249
- del _sessions[token]
250
- logger.debug("[Admin] 登出成功")
251
- return {"success": True, "message": "登出成功"}
252
-
253
- logger.warning("[Admin] 登出失败: 无效会话")
254
- return {"success": False, "message": "无效的会话"}
255
-
256
- except Exception as e:
257
- logger.error(f"[Admin] 登出异常: {e}")
258
- raise HTTPException(status_code=500, detail={"error": f"登出失败: {e}", "code": "LOGOUT_ERROR"})
259
-
260
-
261
- @router.get("/api/tokens", response_model=TokenListResponse)
262
- async def list_tokens(_: bool = Depends(verify_admin_session)) -> TokenListResponse:
263
- """获取Token列表"""
264
- try:
265
- logger.debug("[Admin] 获取Token列表")
266
-
267
- all_tokens = token_manager.get_tokens()
268
- token_list: List[TokenInfo] = []
269
-
270
- # 普通Token
271
- for token, data in all_tokens.get(TokenType.NORMAL.value, {}).items():
272
- token_list.append(TokenInfo(
273
- token=token,
274
- token_type="sso",
275
- created_time=parse_created_time(data.get("createdTime")),
276
- remaining_queries=data.get("remainingQueries", -1),
277
- heavy_remaining_queries=data.get("heavyremainingQueries", -1),
278
- status=get_token_status(data, "sso"),
279
- tags=data.get("tags", []),
280
- note=data.get("note", "")
281
- ))
282
-
283
- # Super Token
284
- for token, data in all_tokens.get(TokenType.SUPER.value, {}).items():
285
- token_list.append(TokenInfo(
286
- token=token,
287
- token_type="ssoSuper",
288
- created_time=parse_created_time(data.get("createdTime")),
289
- remaining_queries=data.get("remainingQueries", -1),
290
- heavy_remaining_queries=data.get("heavyremainingQueries", -1),
291
- status=get_token_status(data, "ssoSuper"),
292
- tags=data.get("tags", []),
293
- note=data.get("note", "")
294
- ))
295
-
296
- logger.debug(f"[Admin] Token列表获取成功: {len(token_list)}个")
297
- return TokenListResponse(success=True, data=token_list, total=len(token_list))
298
-
299
- except Exception as e:
300
- logger.error(f"[Admin] 获取Token列表异常: {e}")
301
- raise HTTPException(status_code=500, detail={"error": f"获取失败: {e}", "code": "LIST_ERROR"})
302
-
303
-
304
- @router.post("/api/tokens/add")
305
- async def add_tokens(request: AddTokensRequest, _: bool = Depends(verify_admin_session)) -> Dict[str, Any]:
306
- """批量添加Token"""
307
- try:
308
- logger.debug(f"[Admin] 添加Token: {request.token_type}, {len(request.tokens)}个")
309
-
310
- token_type = validate_token_type(request.token_type)
311
- await token_manager.add_token(request.tokens, token_type)
312
-
313
- logger.debug(f"[Admin] Token添加成功: {len(request.tokens)}个")
314
- return {"success": True, "message": f"成功添加 {len(request.tokens)} 个Token", "count": len(request.tokens)}
315
-
316
- except HTTPException:
317
- raise
318
- except Exception as e:
319
- logger.error(f"[Admin] Token添加异常: {e}")
320
- raise HTTPException(status_code=500, detail={"error": f"添加失败: {e}", "code": "ADD_ERROR"})
321
-
322
-
323
- @router.post("/api/tokens/delete")
324
- async def delete_tokens(request: DeleteTokensRequest, _: bool = Depends(verify_admin_session)) -> Dict[str, Any]:
325
- """批量删除Token"""
326
- try:
327
- logger.debug(f"[Admin] 删除Token: {request.token_type}, {len(request.tokens)}个")
328
-
329
- token_type = validate_token_type(request.token_type)
330
- await token_manager.delete_token(request.tokens, token_type)
331
-
332
- logger.debug(f"[Admin] Token删除成功: {len(request.tokens)}个")
333
- return {"success": True, "message": f"成功删除 {len(request.tokens)} 个Token", "count": len(request.tokens)}
334
-
335
- except HTTPException:
336
- raise
337
- except Exception as e:
338
- logger.error(f"[Admin] Token删除异常: {e}")
339
- raise HTTPException(status_code=500, detail={"error": f"删除失败: {e}", "code": "DELETE_ERROR"})
340
-
341
-
342
- @router.get("/api/settings")
343
- async def get_settings(_: bool = Depends(verify_admin_session)) -> Dict[str, Any]:
344
- """获取配置"""
345
- try:
346
- logger.debug("[Admin] 获取配置")
347
- return {"success": True, "data": {"global": setting.global_config, "grok": setting.grok_config}}
348
- except Exception as e:
349
- logger.error(f"[Admin] 获取配置失败: {e}")
350
- raise HTTPException(status_code=500, detail={"error": f"获取失败: {e}", "code": "GET_SETTINGS_ERROR"})
351
-
352
-
353
- @router.post("/api/settings")
354
- async def update_settings(request: UpdateSettingsRequest, _: bool = Depends(verify_admin_session)) -> Dict[str, Any]:
355
- """更新配置"""
356
- try:
357
- logger.debug("[Admin] 更新配置")
358
- await setting.save(global_config=request.global_config, grok_config=request.grok_config)
359
- logger.debug("[Admin] 配置更新成功")
360
- return {"success": True, "message": "配置更新成功"}
361
- except Exception as e:
362
- logger.error(f"[Admin] 更新配置失败: {e}")
363
- raise HTTPException(status_code=500, detail={"error": f"更新失败: {e}", "code": "UPDATE_SETTINGS_ERROR"})
364
-
365
-
366
- @router.get("/api/cache/size")
367
- async def get_cache_size(_: bool = Depends(verify_admin_session)) -> Dict[str, Any]:
368
- """获取缓存大小"""
369
- try:
370
- logger.debug("[Admin] 获取缓存大小")
371
-
372
- image_size = _calculate_dir_size(IMAGE_CACHE_DIR) if IMAGE_CACHE_DIR.exists() else 0
373
- video_size = _calculate_dir_size(VIDEO_CACHE_DIR) if VIDEO_CACHE_DIR.exists() else 0
374
- total_size = image_size + video_size
375
-
376
- logger.debug(f"[Admin] 缓存大小: 图片{_format_size(image_size)}, 视频{_format_size(video_size)}")
377
-
378
- return {
379
- "success": True,
380
- "data": {
381
- "image_size": _format_size(image_size),
382
- "video_size": _format_size(video_size),
383
- "total_size": _format_size(total_size),
384
- "image_size_bytes": image_size,
385
- "video_size_bytes": video_size,
386
- "total_size_bytes": total_size
387
- }
388
- }
389
-
390
- except Exception as e:
391
- logger.error(f"[Admin] 获取缓存大小异常: {e}")
392
- raise HTTPException(status_code=500, detail={"error": f"获取失败: {e}", "code": "CACHE_SIZE_ERROR"})
393
-
394
-
395
- @router.post("/api/cache/clear")
396
- async def clear_cache(_: bool = Depends(verify_admin_session)) -> Dict[str, Any]:
397
- """清理所有缓存"""
398
- try:
399
- logger.debug("[Admin] 清理缓存")
400
-
401
- image_count = 0
402
- video_count = 0
403
-
404
- # 清理图片
405
- if IMAGE_CACHE_DIR.exists():
406
- for file_path in IMAGE_CACHE_DIR.iterdir():
407
- if file_path.is_file():
408
- try:
409
- file_path.unlink()
410
- image_count += 1
411
- except Exception as e:
412
- logger.error(f"[Admin] 删除失败: {file_path.name}, {e}")
413
-
414
- # 清理视频
415
- if VIDEO_CACHE_DIR.exists():
416
- for file_path in VIDEO_CACHE_DIR.iterdir():
417
- if file_path.is_file():
418
- try:
419
- file_path.unlink()
420
- video_count += 1
421
- except Exception as e:
422
- logger.error(f"[Admin] 删除失败: {file_path.name}, {e}")
423
-
424
- total = image_count + video_count
425
- logger.debug(f"[Admin] 缓存清理完成: 图片{image_count}, 视频{video_count}")
426
-
427
- return {
428
- "success": True,
429
- "message": f"成功清理缓存,删除图片 {image_count} 个,视频 {video_count} 个,共 {total} 个文件",
430
- "data": {"deleted_count": total, "image_count": image_count, "video_count": video_count}
431
- }
432
-
433
- except Exception as e:
434
- logger.error(f"[Admin] 清理缓存异常: {e}")
435
- raise HTTPException(status_code=500, detail={"error": f"清理失败: {e}", "code": "CACHE_CLEAR_ERROR"})
436
-
437
-
438
- @router.post("/api/cache/clear/images")
439
- async def clear_image_cache(_: bool = Depends(verify_admin_session)) -> Dict[str, Any]:
440
- """清理图片缓存"""
441
- try:
442
- logger.debug("[Admin] 清理图片缓存")
443
-
444
- count = 0
445
- if IMAGE_CACHE_DIR.exists():
446
- for file_path in IMAGE_CACHE_DIR.iterdir():
447
- if file_path.is_file():
448
- try:
449
- file_path.unlink()
450
- count += 1
451
- except Exception as e:
452
- logger.error(f"[Admin] 删除失败: {file_path.name}, {e}")
453
-
454
- logger.debug(f"[Admin] 图片缓存清理完成: {count}个")
455
- return {"success": True, "message": f"成功清理图片缓存,删除 {count} 个文件", "data": {"deleted_count": count, "type": "images"}}
456
-
457
- except Exception as e:
458
- logger.error(f"[Admin] 清理图片缓存异常: {e}")
459
- raise HTTPException(status_code=500, detail={"error": f"清理失败: {e}", "code": "IMAGE_CACHE_CLEAR_ERROR"})
460
-
461
-
462
- @router.post("/api/cache/clear/videos")
463
- async def clear_video_cache(_: bool = Depends(verify_admin_session)) -> Dict[str, Any]:
464
- """清理视频缓存"""
465
- try:
466
- logger.debug("[Admin] 清理视频缓存")
467
-
468
- count = 0
469
- if VIDEO_CACHE_DIR.exists():
470
- for file_path in VIDEO_CACHE_DIR.iterdir():
471
- if file_path.is_file():
472
- try:
473
- file_path.unlink()
474
- count += 1
475
- except Exception as e:
476
- logger.error(f"[Admin] 删除失败: {file_path.name}, {e}")
477
-
478
- logger.debug(f"[Admin] 视频缓存清理完成: {count}个")
479
- return {"success": True, "message": f"成功清理视频缓存,删除 {count} 个文件", "data": {"deleted_count": count, "type": "videos"}}
480
-
481
- except Exception as e:
482
- logger.error(f"[Admin] 清理视频缓存异常: {e}")
483
- raise HTTPException(status_code=500, detail={"error": f"清理失败: {e}", "code": "VIDEO_CACHE_CLEAR_ERROR"})
484
-
485
-
486
- @router.get("/api/stats")
487
- async def get_stats(_: bool = Depends(verify_admin_session)) -> Dict[str, Any]:
488
- """获取统计信息"""
489
- try:
490
- logger.debug("[Admin] 开始获取统计信息")
491
-
492
- all_tokens = token_manager.get_tokens()
493
- normal_stats = calculate_token_stats(all_tokens.get(TokenType.NORMAL.value, {}), "normal")
494
- super_stats = calculate_token_stats(all_tokens.get(TokenType.SUPER.value, {}), "super")
495
- total = normal_stats["total"] + super_stats["total"]
496
-
497
- logger.debug(f"[Admin] 统计信息获取成功 - 普通Token: {normal_stats['total']}, Super Token: {super_stats['total']}, 总计: {total}")
498
- return {"success": True, "data": {"normal": normal_stats, "super": super_stats, "total": total}}
499
-
500
- except Exception as e:
501
- logger.error(f"[Admin] 获取统计信息异常: {e}")
502
- raise HTTPException(status_code=500, detail={"error": f"获取失败: {e}", "code": "STATS_ERROR"})
503
-
504
-
505
- @router.get("/api/storage/mode")
506
- async def get_storage_mode(_: bool = Depends(verify_admin_session)) -> Dict[str, Any]:
507
- """获取存储模式"""
508
- try:
509
- logger.debug("[Admin] 获取存储模式")
510
- import os
511
- mode = os.getenv("STORAGE_MODE", "file").upper()
512
- return {"success": True, "data": {"mode": mode}}
513
- except Exception as e:
514
- logger.error(f"[Admin] 获取存储模式异常: {e}")
515
- raise HTTPException(status_code=500, detail={"error": f"获取失败: {e}", "code": "STORAGE_MODE_ERROR"})
516
-
517
-
518
- @router.post("/api/tokens/tags")
519
- async def update_token_tags(request: UpdateTokenTagsRequest, _: bool = Depends(verify_admin_session)) -> Dict[str, Any]:
520
- """更新Token标签"""
521
- try:
522
- logger.debug(f"[Admin] 更新Token标签: {request.token[:10]}..., {request.tags}")
523
-
524
- token_type = validate_token_type(request.token_type)
525
- await token_manager.update_token_tags(request.token, token_type, request.tags)
526
-
527
- logger.debug(f"[Admin] Token标签更新成功: {request.token[:10]}...")
528
- return {"success": True, "message": "标签更新成功", "tags": request.tags}
529
-
530
- except HTTPException:
531
- raise
532
- except Exception as e:
533
- logger.error(f"[Admin] Token标签更新异常: {e}")
534
- raise HTTPException(status_code=500, detail={"error": f"更新失败: {e}", "code": "UPDATE_TAGS_ERROR"})
535
-
536
-
537
- @router.get("/api/tokens/tags/all")
538
- async def get_all_tags(_: bool = Depends(verify_admin_session)) -> Dict[str, Any]:
539
- """获取所有标签"""
540
- try:
541
- logger.debug("[Admin] 获取所有标签")
542
-
543
- all_tokens = token_manager.get_tokens()
544
- tags_set = set()
545
-
546
- for token_type_data in all_tokens.values():
547
- for token_data in token_type_data.values():
548
- tags = token_data.get("tags", [])
549
- if isinstance(tags, list):
550
- tags_set.update(tags)
551
-
552
- tags_list = sorted(list(tags_set))
553
- logger.debug(f"[Admin] 标签获取成功: {len(tags_list)}个")
554
- return {"success": True, "data": tags_list}
555
-
556
- except Exception as e:
557
- logger.error(f"[Admin] 获取标签异常: {e}")
558
- raise HTTPException(status_code=500, detail={"error": f"获取失败: {e}", "code": "GET_TAGS_ERROR"})
559
-
560
-
561
- @router.post("/api/tokens/note")
562
- async def update_token_note(request: UpdateTokenNoteRequest, _: bool = Depends(verify_admin_session)) -> Dict[str, Any]:
563
- """更新Token备注"""
564
- try:
565
- logger.debug(f"[Admin] 更新Token备注: {request.token[:10]}...")
566
-
567
- token_type = validate_token_type(request.token_type)
568
- await token_manager.update_token_note(request.token, token_type, request.note)
569
-
570
- logger.debug(f"[Admin] Token备注更新成功: {request.token[:10]}...")
571
- return {"success": True, "message": "备注更新成功", "note": request.note}
572
-
573
- except HTTPException:
574
- raise
575
- except Exception as e:
576
- logger.error(f"[Admin] Token备注更新异常: {e}")
577
- raise HTTPException(status_code=500, detail={"error": f"更新失败: {e}", "code": "UPDATE_NOTE_ERROR"})
578
-
579
-
580
- @router.post("/api/tokens/test")
581
- async def test_token(request: TestTokenRequest, _: bool = Depends(verify_admin_session)) -> Dict[str, Any]:
582
- """测试Token可用性"""
583
- try:
584
- logger.debug(f"[Admin] 测试Token: {request.token[:10]}...")
585
-
586
- token_type = validate_token_type(request.token_type)
587
- auth_token = f"sso-rw={request.token};sso={request.token}"
588
-
589
- result = await token_manager.check_limits(auth_token, "grok-4-fast")
590
-
591
- if result:
592
- logger.debug(f"[Admin] Token测试成功: {request.token[:10]}...")
593
- return {
594
- "success": True,
595
- "message": "Token有效",
596
- "data": {
597
- "valid": True,
598
- "remaining_queries": result.get("remainingTokens", -1),
599
- "limit": result.get("limit", -1)
600
- }
601
- }
602
- else:
603
- logger.warning(f"[Admin] Token测试失败: {request.token[:10]}...")
604
-
605
- all_tokens = token_manager.get_tokens()
606
- token_data = all_tokens.get(token_type.value, {}).get(request.token)
607
-
608
- if token_data:
609
- if token_data.get("status") == "expired":
610
- return {"success": False, "message": "Token已失效", "data": {"valid": False, "error_type": "expired", "error_code": 401}}
611
- elif token_data.get("remainingQueries") == 0:
612
- return {"success": False, "message": "Token已被限流", "data": {"valid": False, "error_type": "limited", "error_code": "other"}}
613
- else:
614
- return {"success": False, "message": "服务器被block或网络错误", "data": {"valid": False, "error_type": "blocked", "error_code": 403}}
615
- else:
616
- return {"success": False, "message": "Token数据异常", "data": {"valid": False, "error_type": "unknown", "error_code": "data_error"}}
617
-
618
- except HTTPException:
619
- raise
620
- except Exception as e:
621
- logger.error(f"[Admin] Token测试异常: {e}")
622
- raise HTTPException(status_code=500, detail={"error": f"测试失败: {e}", "code": "TEST_TOKEN_ERROR"})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/api/v1/chat.py DELETED
@@ -1,64 +0,0 @@
1
- """聊天API路由 - OpenAI兼容的聊天接口"""
2
-
3
- from fastapi import APIRouter, Depends, HTTPException
4
- from typing import Optional
5
- from fastapi.responses import StreamingResponse
6
-
7
- from app.core.auth import auth_manager
8
- from app.core.exception import GrokApiException
9
- from app.core.logger import logger
10
- from app.services.grok.client import GrokClient
11
- from app.models.openai_schema import OpenAIChatRequest
12
-
13
-
14
- router = APIRouter(prefix="/chat", tags=["聊天"])
15
-
16
-
17
- @router.post("/completions", response_model=None)
18
- async def chat_completions(request: OpenAIChatRequest, _: Optional[str] = Depends(auth_manager.verify)):
19
- """创建聊天补全(支持流式和非流式)"""
20
- try:
21
- logger.info("[Chat] 收到聊天请求")
22
-
23
- # 调用Grok客户端
24
- result = await GrokClient.openai_to_grok(request.model_dump())
25
-
26
- # 流式响应
27
- if request.stream:
28
- return StreamingResponse(
29
- content=result,
30
- media_type="text/event-stream",
31
- headers={
32
- "Cache-Control": "no-cache",
33
- "Connection": "keep-alive",
34
- "X-Accel-Buffering": "no"
35
- }
36
- )
37
-
38
- # 非流式响应
39
- return result
40
-
41
- except GrokApiException as e:
42
- logger.error(f"[Chat] Grok API错误: {e} - 详情: {e.details}")
43
- raise HTTPException(
44
- status_code=500,
45
- detail={
46
- "error": {
47
- "message": str(e),
48
- "type": e.error_code or "grok_api_error",
49
- "code": e.error_code or "unknown"
50
- }
51
- }
52
- )
53
- except Exception as e:
54
- logger.error(f"[Chat] 处理失败: {e}")
55
- raise HTTPException(
56
- status_code=500,
57
- detail={
58
- "error": {
59
- "message": "服务器内部错误",
60
- "type": "internal_error",
61
- "code": "internal_server_error"
62
- }
63
- }
64
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/api/v1/images.py DELETED
@@ -1,53 +0,0 @@
1
- """图片服务API - 提供缓存的图片和视频文件"""
2
-
3
- from fastapi import APIRouter, HTTPException
4
- from fastapi.responses import FileResponse
5
-
6
- from app.core.logger import logger
7
- from app.services.grok.cache import image_cache_service, video_cache_service
8
-
9
-
10
- router = APIRouter()
11
-
12
-
13
- @router.get("/images/{img_path:path}")
14
- async def get_image(img_path: str):
15
- """获取缓存的图片或视频
16
-
17
- Args:
18
- img_path: 文件路径(格式:users-xxx-generated-xxx-image.jpg)
19
- """
20
- try:
21
- # 转换路径(短横线→斜杠)
22
- original_path = "/" + img_path.replace('-', '/')
23
-
24
- # 判断类型
25
- is_video = any(original_path.lower().endswith(ext) for ext in ['.mp4', '.webm', '.mov', '.avi'])
26
-
27
- if is_video:
28
- cache_path = video_cache_service.get_cached(original_path)
29
- media_type = "video/mp4"
30
- else:
31
- cache_path = image_cache_service.get_cached(original_path)
32
- media_type = "image/jpeg"
33
-
34
- if cache_path and cache_path.exists():
35
- logger.debug(f"[MediaAPI] 返回缓存: {cache_path}")
36
- return FileResponse(
37
- path=str(cache_path),
38
- media_type=media_type,
39
- headers={
40
- "Cache-Control": "public, max-age=86400",
41
- "Access-Control-Allow-Origin": "*"
42
- }
43
- )
44
-
45
- # 文件不存在
46
- logger.warning(f"[MediaAPI] 未找到: {original_path}")
47
- raise HTTPException(status_code=404, detail="File not found")
48
-
49
- except HTTPException:
50
- raise
51
- except Exception as e:
52
- logger.error(f"[MediaAPI] 获取失败: {e}")
53
- raise HTTPException(status_code=500, detail=str(e))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/api/v1/models.py DELETED
@@ -1,114 +0,0 @@
1
- """模型接口 - OpenAI兼容的模型列表端点"""
2
-
3
- import time
4
- from typing import Dict, Any, List, Optional
5
- from fastapi import APIRouter, HTTPException, Depends
6
-
7
- from app.models.grok_models import Models
8
- from app.core.auth import auth_manager
9
- from app.core.logger import logger
10
-
11
-
12
- router = APIRouter(tags=["模型"])
13
-
14
-
15
- @router.get("/models")
16
- async def list_models(_: Optional[str] = Depends(auth_manager.verify)) -> Dict[str, Any]:
17
- """获取可用模型列表"""
18
- try:
19
- logger.debug("[Models] 请求模型列表")
20
-
21
- timestamp = int(time.time())
22
- model_data: List[Dict[str, Any]] = []
23
-
24
- for model in Models:
25
- model_id = model.value
26
- config = Models.get_model_info(model_id)
27
-
28
- model_info = {
29
- "id": model_id,
30
- "object": "model",
31
- "created": timestamp,
32
- "owned_by": "x-ai",
33
- "display_name": config.get("display_name", model_id),
34
- "description": config.get("description", ""),
35
- "raw_model_path": config.get("raw_model_path", f"xai/{model_id}"),
36
- "default_temperature": config.get("default_temperature", 1.0),
37
- "default_max_output_tokens": config.get("default_max_output_tokens", 8192),
38
- "supported_max_output_tokens": config.get("supported_max_output_tokens", 131072),
39
- "default_top_p": config.get("default_top_p", 0.95)
40
- }
41
-
42
- model_data.append(model_info)
43
-
44
- logger.debug(f"[Models] 返回 {len(model_data)} 个模型")
45
- return {"object": "list", "data": model_data}
46
-
47
- except Exception as e:
48
- logger.error(f"[Models] 获取列表失败: {e}")
49
- raise HTTPException(
50
- status_code=500,
51
- detail={
52
- "error": {
53
- "message": f"Failed to retrieve models: {e}",
54
- "type": "internal_error",
55
- "code": "model_list_error"
56
- }
57
- }
58
- )
59
-
60
-
61
- @router.get("/models/{model_id}")
62
- async def get_model(model_id: str, _: Optional[str] = Depends(auth_manager.verify)) -> Dict[str, Any]:
63
- """获取特定模型信息"""
64
- try:
65
- logger.debug(f"[Models] 请求模型: {model_id}")
66
-
67
- # 验证模型
68
- if not Models.is_valid_model(model_id):
69
- logger.warning(f"[Models] 模型不存在: {model_id}")
70
- raise HTTPException(
71
- status_code=404,
72
- detail={
73
- "error": {
74
- "message": f"Model '{model_id}' not found",
75
- "type": "invalid_request_error",
76
- "code": "model_not_found"
77
- }
78
- }
79
- )
80
-
81
- timestamp = int(time.time())
82
- config = Models.get_model_info(model_id)
83
-
84
- model_info = {
85
- "id": model_id,
86
- "object": "model",
87
- "created": timestamp,
88
- "owned_by": "x-ai",
89
- "display_name": config.get("display_name", model_id),
90
- "description": config.get("description", ""),
91
- "raw_model_path": config.get("raw_model_path", f"xai/{model_id}"),
92
- "default_temperature": config.get("default_temperature", 1.0),
93
- "default_max_output_tokens": config.get("default_max_output_tokens", 8192),
94
- "supported_max_output_tokens": config.get("supported_max_output_tokens", 131072),
95
- "default_top_p": config.get("default_top_p", 0.95)
96
- }
97
-
98
- logger.debug(f"[Models] 返回模型: {model_id}")
99
- return model_info
100
-
101
- except HTTPException:
102
- raise
103
- except Exception as e:
104
- logger.error(f"[Models] 获取模型失败: {e}")
105
- raise HTTPException(
106
- status_code=500,
107
- detail={
108
- "error": {
109
- "message": f"Failed to retrieve model: {e}",
110
- "type": "internal_error",
111
- "code": "model_retrieve_error"
112
- }
113
- }
114
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/core/auth.py DELETED
@@ -1,58 +0,0 @@
1
- """认证模块 - API令牌验证"""
2
-
3
- from typing import Optional
4
- from fastapi import Depends, HTTPException
5
- from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
6
-
7
- from app.core.config import setting
8
- from app.core.logger import logger
9
-
10
-
11
- # Bearer安全方案
12
- security = HTTPBearer(auto_error=False)
13
-
14
-
15
- def _build_error(message: str, code: str = "invalid_token") -> dict:
16
- """构建认证错误"""
17
- return {
18
- "error": {
19
- "message": message,
20
- "type": "authentication_error",
21
- "code": code
22
- }
23
- }
24
-
25
-
26
- class AuthManager:
27
- """认证管理器 - 验证API令牌"""
28
-
29
- @staticmethod
30
- def verify(credentials: Optional[HTTPAuthorizationCredentials] = Depends(security)) -> Optional[str]:
31
- """验证令牌"""
32
- api_key = setting.grok_config.get("api_key")
33
-
34
- # 未设置时跳过
35
- if not api_key:
36
- logger.debug("[Auth] 未设置API_KEY,跳过验证")
37
- return credentials.credentials if credentials else None
38
-
39
- # 检查令牌
40
- if not credentials:
41
- raise HTTPException(
42
- status_code=401,
43
- detail=_build_error("缺少认证令牌", "missing_token")
44
- )
45
-
46
- # 验证令牌
47
- if credentials.credentials != api_key:
48
- raise HTTPException(
49
- status_code=401,
50
- detail=_build_error(f"令牌无效,长度: {len(credentials.credentials)}", "invalid_token")
51
- )
52
-
53
- logger.debug("[Auth] 令牌认证成功")
54
- return credentials.credentials
55
-
56
-
57
- # 全局实例
58
- auth_manager = AuthManager()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/core/config.py DELETED
@@ -1,203 +0,0 @@
1
- """配置管理器 - 管理应用配置的读写"""
2
-
3
- import toml
4
- from pathlib import Path
5
- from typing import Dict, Any, Optional, Literal
6
-
7
-
8
- # 默认配置
9
- DEFAULT_GROK = {
10
- "api_key": "",
11
- "proxy_url": "",
12
- "proxy_pool_url": "",
13
- "proxy_pool_interval": 300,
14
- "cache_proxy_url": "",
15
- "cf_clearance": "",
16
- "x_statsig_id": "",
17
- "dynamic_statsig": True,
18
- "filtered_tags": "xaiartifact,xai:tool_usage_card",
19
- "show_thinking": True,
20
- "temporary": False,
21
- "max_upload_concurrency": 20,
22
- "max_request_concurrency": 100,
23
- "stream_first_response_timeout": 30,
24
- "stream_chunk_timeout": 120,
25
- "stream_total_timeout": 600,
26
- "retry_status_codes": [401, 429], # 可重试的HTTP状态码
27
- }
28
-
29
- DEFAULT_GLOBAL = {
30
- "base_url": "http://localhost:8000",
31
- "log_level": "INFO",
32
- "image_mode": "url",
33
- "admin_password": "admin",
34
- "admin_username": "admin",
35
- "image_cache_max_size_mb": 512,
36
- "video_cache_max_size_mb": 1024,
37
- "max_upload_concurrency": 20, # 最大并发上传数
38
- "max_request_concurrency": 50, # 最大并发请求数
39
- "batch_save_interval": 1.0, # 批量保存间隔(秒)
40
- "batch_save_threshold": 10 # 触发批量保存的变更数阈值
41
- }
42
-
43
-
44
- class ConfigManager:
45
- """配置管理器"""
46
-
47
- def __init__(self) -> None:
48
- """初始化配置"""
49
- self.config_path: Path = Path(__file__).parents[2] / "data" / "setting.toml"
50
- self._storage: Optional[Any] = None
51
- self._ensure_exists()
52
- self.global_config: Dict[str, Any] = self.load("global")
53
- self.grok_config: Dict[str, Any] = self.load("grok")
54
-
55
- def _ensure_exists(self) -> None:
56
- """确保配置存在"""
57
- if not self.config_path.exists():
58
- self.config_path.parent.mkdir(parents=True, exist_ok=True)
59
- self._create_default()
60
-
61
- def _create_default(self) -> None:
62
- """创建默认配置"""
63
- default = {"grok": DEFAULT_GROK.copy(), "global": DEFAULT_GLOBAL.copy()}
64
- with open(self.config_path, "w", encoding="utf-8") as f:
65
- toml.dump(default, f)
66
-
67
- def _normalize_proxy(self, proxy: str) -> str:
68
- """标准化代理URL(sock5/socks5 → socks5h://)"""
69
- if not proxy:
70
- return proxy
71
-
72
- proxy = proxy.strip()
73
- if proxy.startswith("sock5h://"):
74
- proxy = proxy.replace("sock5h://", "socks5h://", 1)
75
- if proxy.startswith("sock5://"):
76
- proxy = proxy.replace("sock5://", "socks5://", 1)
77
- if proxy.startswith("socks5://"):
78
- return proxy.replace("socks5://", "socks5h://", 1)
79
- return proxy
80
-
81
- def _normalize_cf(self, cf: str) -> str:
82
- """标准化CF Clearance(自动添加前缀)"""
83
- if cf and not cf.startswith("cf_clearance="):
84
- return f"cf_clearance={cf}"
85
- return cf
86
-
87
- def set_storage(self, storage: Any) -> None:
88
- """设置存储实例"""
89
- self._storage = storage
90
-
91
- def load(self, section: Literal["global", "grok"]) -> Dict[str, Any]:
92
- """加载配置节"""
93
- try:
94
- with open(self.config_path, "r", encoding="utf-8") as f:
95
- config = toml.load(f)[section]
96
-
97
- # 标准化Grok配置
98
- if section == "grok":
99
- if "proxy_url" in config:
100
- config["proxy_url"] = self._normalize_proxy(config["proxy_url"])
101
- if "cache_proxy_url" in config:
102
- config["cache_proxy_url"] = self._normalize_proxy(config["cache_proxy_url"])
103
- if "cf_clearance" in config:
104
- config["cf_clearance"] = self._normalize_cf(config["cf_clearance"])
105
-
106
- return config
107
- except Exception as e:
108
- raise Exception(f"[Setting] 配置加载失败: {e}") from e
109
-
110
- async def reload(self) -> None:
111
- """重新加载配置"""
112
- self.global_config = self.load("global")
113
- self.grok_config = self.load("grok")
114
-
115
- async def _save_file(self, updates: Dict[str, Dict[str, Any]]) -> None:
116
- """保存到文件"""
117
- import aiofiles
118
-
119
- async with aiofiles.open(self.config_path, "r", encoding="utf-8") as f:
120
- config = toml.loads(await f.read())
121
-
122
- for section, data in updates.items():
123
- if section in config:
124
- config[section].update(data)
125
-
126
- async with aiofiles.open(self.config_path, "w", encoding="utf-8") as f:
127
- await f.write(toml.dumps(config))
128
-
129
- async def _save_storage(self, updates: Dict[str, Dict[str, Any]]) -> None:
130
- """保存到存储"""
131
- config = await self._storage.load_config()
132
-
133
- for section, data in updates.items():
134
- if section in config:
135
- config[section].update(data)
136
-
137
- await self._storage.save_config(config)
138
-
139
- def _prepare_grok(self, grok: Dict[str, Any]) -> Dict[str, Any]:
140
- """准备Grok配置(移除前缀)"""
141
- processed = grok.copy()
142
- if "cf_clearance" in processed:
143
- cf = processed["cf_clearance"]
144
- if cf and cf.startswith("cf_clearance="):
145
- processed["cf_clearance"] = cf.replace("cf_clearance=", "", 1)
146
- return processed
147
-
148
- async def save(self, global_config: Optional[Dict[str, Any]] = None, grok_config: Optional[Dict[str, Any]] = None) -> None:
149
- """保存配置"""
150
- updates = {}
151
-
152
- if global_config:
153
- updates["global"] = global_config
154
- if grok_config:
155
- updates["grok"] = self._prepare_grok(grok_config)
156
-
157
- # 选择存储方式
158
- if self._storage:
159
- await self._save_storage(updates)
160
- else:
161
- await self._save_file(updates)
162
-
163
- await self.reload()
164
-
165
- async def get_proxy_async(self, proxy_type: Literal["service", "cache"] = "service") -> str:
166
- """异步获取代理URL(支持代理池)
167
-
168
- Args:
169
- proxy_type: 代理类型
170
- - service: 服务代理(client/upload)
171
- - cache: 缓存代理(cache)
172
- """
173
- from app.core.proxy_pool import proxy_pool
174
-
175
- if proxy_type == "cache":
176
- cache_proxy = self.grok_config.get("cache_proxy_url", "")
177
- if cache_proxy:
178
- return cache_proxy
179
-
180
- # 从代理池获取
181
- return await proxy_pool.get_proxy() or ""
182
-
183
- def get_proxy(self, proxy_type: Literal["service", "cache"] = "service") -> str:
184
- """获取代理URL(同步方法,用于向后兼容)
185
-
186
- Args:
187
- proxy_type: 代理类型
188
- - service: 服务代理(client/upload)
189
- - cache: 缓存代理(cache)
190
- """
191
- from app.core.proxy_pool import proxy_pool
192
-
193
- if proxy_type == "cache":
194
- cache_proxy = self.grok_config.get("cache_proxy_url", "")
195
- if cache_proxy:
196
- return cache_proxy
197
-
198
- # 返回当前代理(如果是代理池,返回最后一次获取的)
199
- return proxy_pool.get_current_proxy() or self.grok_config.get("proxy_url", "")
200
-
201
-
202
- # 全局实例
203
- setting = ConfigManager()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/core/exception.py DELETED
@@ -1,118 +0,0 @@
1
- """异常处理器 - OpenAI兼容的错误响应"""
2
-
3
- from fastapi import Request, status
4
- from fastapi.responses import JSONResponse
5
- from fastapi.exceptions import RequestValidationError
6
- from starlette.exceptions import HTTPException as StarletteHTTPException
7
-
8
-
9
- # HTTP错误映射
10
- HTTP_ERROR_MAP = {
11
- 400: ("invalid_request_error", "请求格式错误或缺少必填参数"),
12
- 401: ("invalid_request_error", "令牌认证失败"),
13
- 403: ("permission_error", "没有权限访问此资源"),
14
- 404: ("invalid_request_error", "请求的资源不存在"),
15
- 429: ("rate_limit_error", "请求频率超出限制,请稍后再试"),
16
- 500: ("api_error", "内部服务器错误"),
17
- 503: ("api_error", "服务暂时不可用"),
18
- }
19
-
20
- # Grok错误码映射
21
- GROK_STATUS_MAP = {
22
- "NO_AUTH_TOKEN": status.HTTP_401_UNAUTHORIZED,
23
- "INVALID_TOKEN": status.HTTP_401_UNAUTHORIZED,
24
- "HTTP_ERROR": status.HTTP_502_BAD_GATEWAY,
25
- "NETWORK_ERROR": status.HTTP_503_SERVICE_UNAVAILABLE,
26
- "JSON_ERROR": status.HTTP_502_BAD_GATEWAY,
27
- "API_ERROR": status.HTTP_502_BAD_GATEWAY,
28
- "STREAM_ERROR": status.HTTP_502_BAD_GATEWAY,
29
- "NO_RESPONSE": status.HTTP_502_BAD_GATEWAY,
30
- "TOKEN_SAVE_ERROR": status.HTTP_500_INTERNAL_SERVER_ERROR,
31
- "NO_AVAILABLE_TOKEN": status.HTTP_503_SERVICE_UNAVAILABLE,
32
- }
33
-
34
- GROK_TYPE_MAP = {
35
- "NO_AUTH_TOKEN": "authentication_error",
36
- "INVALID_TOKEN": "authentication_error",
37
- "HTTP_ERROR": "api_error",
38
- "NETWORK_ERROR": "api_error",
39
- "JSON_ERROR": "api_error",
40
- "API_ERROR": "api_error",
41
- "STREAM_ERROR": "api_error",
42
- "NO_RESPONSE": "api_error",
43
- "TOKEN_SAVE_ERROR": "api_error",
44
- "NO_AVAILABLE_TOKEN": "api_error",
45
- }
46
-
47
-
48
- class GrokApiException(Exception):
49
- """Grok API业务异常"""
50
-
51
- def __init__(self, message: str, error_code: str = None, details: dict = None, context: dict = None):
52
- self.message = message
53
- self.error_code = error_code
54
- self.details = details or {}
55
- self.context = context or {}
56
- super().__init__(self.message)
57
-
58
-
59
- def build_error_response(message: str, error_type: str, code: str = None, param: str = None) -> dict:
60
- """构建OpenAI兼容的错误响应"""
61
- error = {"message": message, "type": error_type}
62
-
63
- if code:
64
- error["code"] = code
65
- if param:
66
- error["param"] = param
67
-
68
- return {"error": error}
69
-
70
-
71
- async def http_exception_handler(_: Request, exc: StarletteHTTPException) -> JSONResponse:
72
- """处理HTTP异常"""
73
- error_type, default_msg = HTTP_ERROR_MAP.get(exc.status_code, ("api_error", str(exc.detail)))
74
- message = str(exc.detail) if exc.detail else default_msg
75
-
76
- return JSONResponse(
77
- status_code=exc.status_code,
78
- content=build_error_response(message, error_type)
79
- )
80
-
81
-
82
- async def validation_exception_handler(_: Request, exc: RequestValidationError) -> JSONResponse:
83
- """处理验证错误"""
84
- errors = exc.errors()
85
- param = errors[0]["loc"][-1] if errors and errors[0].get("loc") else None
86
- message = errors[0]["msg"] if errors and errors[0].get("msg") else "请求参数错误"
87
-
88
- return JSONResponse(
89
- status_code=status.HTTP_400_BAD_REQUEST,
90
- content=build_error_response(message, "invalid_request_error", param=param)
91
- )
92
-
93
-
94
- async def grok_api_exception_handler(_: Request, exc: GrokApiException) -> JSONResponse:
95
- """处理Grok API异常"""
96
- http_status = GROK_STATUS_MAP.get(exc.error_code, status.HTTP_500_INTERNAL_SERVER_ERROR)
97
- error_type = GROK_TYPE_MAP.get(exc.error_code, "api_error")
98
-
99
- return JSONResponse(
100
- status_code=http_status,
101
- content=build_error_response(exc.message, error_type, exc.error_code)
102
- )
103
-
104
-
105
- async def global_exception_handler(_: Request, exc: Exception) -> JSONResponse:
106
- """处理未捕获异常"""
107
- return JSONResponse(
108
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
109
- content=build_error_response("服务器遇到意外错误,请重试", "api_error")
110
- )
111
-
112
-
113
- def register_exception_handlers(app) -> None:
114
- """注册异常处理器"""
115
- app.add_exception_handler(StarletteHTTPException, http_exception_handler)
116
- app.add_exception_handler(RequestValidationError, validation_exception_handler)
117
- app.add_exception_handler(GrokApiException, grok_api_exception_handler)
118
- app.add_exception_handler(Exception, global_exception_handler)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/core/logger.py DELETED
@@ -1,130 +0,0 @@
1
- """全局日志模块 - 单例模式的日志管理器"""
2
-
3
- import sys
4
- import logging
5
- from pathlib import Path
6
- from logging.handlers import RotatingFileHandler
7
-
8
- from app.core.config import setting
9
-
10
-
11
- # 过滤模式
12
- FILTER_PATTERNS = [
13
- "chunk: b'", # SSE原始字节
14
- "Got event:", # SSE事件
15
- "Closing", # SSE关闭
16
- ]
17
-
18
-
19
- class MCPLogFilter(logging.Filter):
20
- """MCP日志过滤器 - 过滤大量数据的DEBUG日志"""
21
-
22
- def filter(self, record: logging.LogRecord) -> bool:
23
- """过滤日志"""
24
- # 过滤SSE的DEBUG日志
25
- if record.name == "sse_starlette.sse" and record.levelno == logging.DEBUG:
26
- msg = record.getMessage()
27
- return not any(p in msg for p in FILTER_PATTERNS)
28
-
29
- # 过滤MCP streamable_http的DEBUG日志
30
- if "mcp.server.streamable_http" in record.name and record.levelno == logging.DEBUG:
31
- return False
32
-
33
- return True
34
-
35
-
36
- class LoggerManager:
37
- """日志管理器(单例)"""
38
-
39
- _instance = None
40
- _initialized = False
41
-
42
- def __new__(cls):
43
- if cls._instance is None:
44
- cls._instance = super().__new__(cls)
45
- return cls._instance
46
-
47
- def __init__(self):
48
- """初始化日志系统"""
49
- if LoggerManager._initialized:
50
- return
51
-
52
- # 配置
53
- log_dir = Path(__file__).parents[2] / "logs"
54
- log_dir.mkdir(exist_ok=True)
55
- log_level = setting.global_config.get("log_level", "INFO").upper()
56
- log_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
57
- log_file = log_dir / "app.log"
58
-
59
- # 根日志器
60
- self.logger = logging.getLogger()
61
- self.logger.setLevel(log_level)
62
-
63
- # 避免重复添加
64
- if self.logger.handlers:
65
- return
66
-
67
- # 格式器和过滤器
68
- formatter = logging.Formatter(log_format)
69
- mcp_filter = MCPLogFilter()
70
-
71
- # 控制台处理器
72
- console = logging.StreamHandler(sys.stdout)
73
- console.setLevel(log_level)
74
- console.setFormatter(formatter)
75
- console.addFilter(mcp_filter)
76
-
77
- # 文件处理器(10MB,5个备份)
78
- file_handler = RotatingFileHandler(
79
- log_file, maxBytes=10*1024*1024, backupCount=5, encoding="utf-8"
80
- )
81
- file_handler.setLevel(log_level)
82
- file_handler.setFormatter(formatter)
83
- file_handler.addFilter(mcp_filter)
84
-
85
- # 添加处理器
86
- self.logger.addHandler(console)
87
- self.logger.addHandler(file_handler)
88
-
89
- # 配置第三方库
90
- self._configure_third_party()
91
-
92
- LoggerManager._initialized = True
93
-
94
- def _configure_third_party(self):
95
- """配置第三方库日志级别"""
96
- config = {
97
- "asyncio": logging.WARNING,
98
- "uvicorn": logging.INFO,
99
- "fastapi": logging.INFO,
100
- "aiomysql": logging.WARNING,
101
- "mcp": logging.CRITICAL,
102
- "fastmcp": logging.CRITICAL,
103
- }
104
-
105
- for name, level in config.items():
106
- logging.getLogger(name).setLevel(level)
107
-
108
- def debug(self, msg: str) -> None:
109
- """调试日志"""
110
- self.logger.debug(msg)
111
-
112
- def info(self, msg: str) -> None:
113
- """信息日志"""
114
- self.logger.info(msg)
115
-
116
- def warning(self, msg: str) -> None:
117
- """警告日志"""
118
- self.logger.warning(msg)
119
-
120
- def error(self, msg: str) -> None:
121
- """错误日志"""
122
- self.logger.error(msg)
123
-
124
- def critical(self, msg: str) -> None:
125
- """严重错误日志"""
126
- self.logger.critical(msg)
127
-
128
-
129
- # 全局实例
130
- logger = LoggerManager()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/core/proxy_pool.py DELETED
@@ -1,170 +0,0 @@
1
- """代理池管理器 - 从URL动态获取代理IP"""
2
-
3
- import asyncio
4
- import aiohttp
5
- import time
6
- from typing import Optional, List
7
- from app.core.logger import logger
8
-
9
-
10
- class ProxyPool:
11
- """代理池管理器"""
12
-
13
- def __init__(self):
14
- self._pool_url: Optional[str] = None
15
- self._static_proxy: Optional[str] = None
16
- self._current_proxy: Optional[str] = None
17
- self._last_fetch_time: float = 0
18
- self._fetch_interval: int = 300 # 5分钟刷新一次
19
- self._enabled: bool = False
20
- self._lock = asyncio.Lock()
21
-
22
- def configure(self, proxy_url: str, proxy_pool_url: str = "", proxy_pool_interval: int = 300):
23
- """配置代理池
24
-
25
- Args:
26
- proxy_url: 静态代理URL(socks5h://xxx 或 http://xxx)
27
- proxy_pool_url: 代理池API URL,返回单个代理地址
28
- proxy_pool_interval: 代理池刷新间隔(秒)
29
- """
30
- self._static_proxy = self._normalize_proxy(proxy_url) if proxy_url else None
31
- pool_url = proxy_pool_url.strip() if proxy_pool_url else None
32
- if pool_url and self._looks_like_proxy_url(pool_url):
33
- normalized_proxy = self._normalize_proxy(pool_url)
34
- if not self._static_proxy:
35
- self._static_proxy = normalized_proxy
36
- logger.warning("[ProxyPool] proxy_pool_url看起来是代理地址,已作为静态代理使用,请改用proxy_url")
37
- else:
38
- logger.warning("[ProxyPool] proxy_pool_url看起来是代理地址,已忽略(使用proxy_url)")
39
- pool_url = None
40
- self._pool_url = pool_url
41
- self._fetch_interval = proxy_pool_interval
42
- self._enabled = bool(self._pool_url)
43
-
44
- if self._enabled:
45
- logger.info(f"[ProxyPool] 代理池已启用: {self._pool_url}, 刷新间隔: {self._fetch_interval}s")
46
- elif self._static_proxy:
47
- logger.info(f"[ProxyPool] 使用静态代理: {self._static_proxy}")
48
- self._current_proxy = self._static_proxy
49
- else:
50
- logger.info("[ProxyPool] 未配置代理")
51
-
52
- async def get_proxy(self) -> Optional[str]:
53
- """获取代理地址
54
-
55
- Returns:
56
- 代理URL或None
57
- """
58
- # 如果未启用代理池,返回静态代理
59
- if not self._enabled:
60
- return self._static_proxy
61
-
62
- # 检查是否需要刷新
63
- now = time.time()
64
- if not self._current_proxy or (now - self._last_fetch_time) >= self._fetch_interval:
65
- async with self._lock:
66
- # 双重检查
67
- if not self._current_proxy or (now - self._last_fetch_time) >= self._fetch_interval:
68
- await self._fetch_proxy()
69
-
70
- return self._current_proxy
71
-
72
- async def force_refresh(self) -> Optional[str]:
73
- """强制刷新代理(用于403错误重试)
74
-
75
- Returns:
76
- 新的代理URL或None
77
- """
78
- if not self._enabled:
79
- return self._static_proxy
80
-
81
- async with self._lock:
82
- await self._fetch_proxy()
83
-
84
- return self._current_proxy
85
-
86
- async def _fetch_proxy(self):
87
- """从代理池URL获取新的代理"""
88
- try:
89
- logger.debug(f"[ProxyPool] 正在从代理池获取新代理: {self._pool_url}")
90
-
91
- timeout = aiohttp.ClientTimeout(total=10)
92
- async with aiohttp.ClientSession(timeout=timeout) as session:
93
- async with session.get(self._pool_url) as response:
94
- if response.status == 200:
95
- proxy_text = await response.text()
96
- proxy = self._normalize_proxy(proxy_text.strip())
97
-
98
- # 验证代理格式
99
- if self._validate_proxy(proxy):
100
- self._current_proxy = proxy
101
- self._last_fetch_time = time.time()
102
- logger.info(f"[ProxyPool] 成功获取新代理: {proxy}")
103
- else:
104
- logger.error(f"[ProxyPool] 代理格式无效: {proxy}")
105
- # 降级到静态代理
106
- if not self._current_proxy:
107
- self._current_proxy = self._static_proxy
108
- else:
109
- logger.error(f"[ProxyPool] 获取代理失败: HTTP {response.status}")
110
- # 降级到静态代理
111
- if not self._current_proxy:
112
- self._current_proxy = self._static_proxy
113
-
114
- except asyncio.TimeoutError:
115
- logger.error("[ProxyPool] 获取代理超时")
116
- if not self._current_proxy:
117
- self._current_proxy = self._static_proxy
118
-
119
- except Exception as e:
120
- logger.error(f"[ProxyPool] 获取代理异常: {e}")
121
- # 降级到静态代理
122
- if not self._current_proxy:
123
- self._current_proxy = self._static_proxy
124
-
125
- def _validate_proxy(self, proxy: str) -> bool:
126
- """验证代理格式
127
-
128
- Args:
129
- proxy: 代理URL
130
-
131
- Returns:
132
- 是否有效
133
- """
134
- if not proxy:
135
- return False
136
-
137
- # 支持的协议
138
- valid_protocols = ['http://', 'https://', 'socks5://', 'socks5h://']
139
-
140
- return any(proxy.startswith(proto) for proto in valid_protocols)
141
-
142
- def _normalize_proxy(self, proxy: str) -> str:
143
- """标准化代理URL(sock5/socks5 → socks5h://)"""
144
- if not proxy:
145
- return proxy
146
-
147
- proxy = proxy.strip()
148
- if proxy.startswith("sock5h://"):
149
- proxy = proxy.replace("sock5h://", "socks5h://", 1)
150
- if proxy.startswith("sock5://"):
151
- proxy = proxy.replace("sock5://", "socks5://", 1)
152
- if proxy.startswith("socks5://"):
153
- return proxy.replace("socks5://", "socks5h://", 1)
154
- return proxy
155
-
156
- def _looks_like_proxy_url(self, url: str) -> bool:
157
- """判断URL是否像代理地址(避免误把代理池API当代理)"""
158
- return url.startswith(("sock5://", "sock5h://", "socks5://", "socks5h://"))
159
-
160
- def get_current_proxy(self) -> Optional[str]:
161
- """获取当前使用的代理(同步方法)
162
-
163
- Returns:
164
- 当前代理URL或None
165
- """
166
- return self._current_proxy or self._static_proxy
167
-
168
-
169
- # 全局代理池实例
170
- proxy_pool = ProxyPool()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/core/storage.py DELETED
@@ -1,445 +0,0 @@
1
- """存储抽象层 - 支持文件、MySQL和Redis存储"""
2
-
3
- import os
4
- import orjson
5
- import toml
6
- import asyncio
7
- import warnings
8
- import aiofiles
9
- from pathlib import Path
10
- from typing import Dict, Any, Optional, Literal
11
- from abc import ABC, abstractmethod
12
- from urllib.parse import urlparse, unquote
13
-
14
- from app.core.logger import logger
15
-
16
-
17
- StorageMode = Literal["file", "mysql", "redis"]
18
-
19
-
20
- class BaseStorage(ABC):
21
- """存储基类"""
22
-
23
- @abstractmethod
24
- async def init_db(self) -> None:
25
- """初始化数据库"""
26
- pass
27
-
28
- @abstractmethod
29
- async def load_tokens(self) -> Dict[str, Any]:
30
- """加载token数据"""
31
- pass
32
-
33
- @abstractmethod
34
- async def save_tokens(self, data: Dict[str, Any]) -> None:
35
- """保存token数据"""
36
- pass
37
-
38
- @abstractmethod
39
- async def load_config(self) -> Dict[str, Any]:
40
- """加载配置数据"""
41
- pass
42
-
43
- @abstractmethod
44
- async def save_config(self, data: Dict[str, Any]) -> None:
45
- """保存配置数据"""
46
- pass
47
-
48
-
49
- class FileStorage(BaseStorage):
50
- """文件存储"""
51
-
52
- def __init__(self, data_dir: Path):
53
- self.data_dir = data_dir
54
- self.token_file = data_dir / "token.json"
55
- self.config_file = data_dir / "setting.toml"
56
- self._token_lock = asyncio.Lock()
57
- self._config_lock = asyncio.Lock()
58
-
59
- async def init_db(self) -> None:
60
- """初始化文件存储"""
61
- self.data_dir.mkdir(parents=True, exist_ok=True)
62
-
63
- if not self.token_file.exists():
64
- await self._write(self.token_file, orjson.dumps({"sso": {}, "ssoSuper": {}}, option=orjson.OPT_INDENT_2).decode())
65
- logger.info("[Storage] 创建token文件")
66
-
67
- if not self.config_file.exists():
68
- default = {
69
- "global": {"api_keys": [], "admin_username": "admin", "admin_password": "admin"},
70
- "grok": {"proxy_url": "", "cf_clearance": "", "x_statsig_id": ""}
71
- }
72
- await self._write(self.config_file, toml.dumps(default))
73
- logger.info("[Storage] 创建配置文件")
74
-
75
- async def _read(self, path: Path) -> str:
76
- """读取文件"""
77
- async with aiofiles.open(path, "r", encoding="utf-8") as f:
78
- return await f.read()
79
-
80
- async def _write(self, path: Path, content: str) -> None:
81
- """写入文件"""
82
- async with aiofiles.open(path, "w", encoding="utf-8") as f:
83
- await f.write(content)
84
-
85
- async def _load_json(self, path: Path, default: Dict, lock: asyncio.Lock) -> Dict[str, Any]:
86
- """加载JSON"""
87
- try:
88
- async with lock:
89
- if not path.exists():
90
- return default
91
- return orjson.loads(await self._read(path))
92
- except Exception as e:
93
- logger.error(f"[Storage] 加载{path.name}失败: {e}")
94
- return default
95
-
96
- async def _save_json(self, path: Path, data: Dict, lock: asyncio.Lock) -> None:
97
- """保存JSON"""
98
- try:
99
- async with lock:
100
- await self._write(path, orjson.dumps(data, option=orjson.OPT_INDENT_2).decode())
101
- except Exception as e:
102
- logger.error(f"[Storage] 保存{path.name}失败: {e}")
103
- raise
104
-
105
- async def _load_toml(self, path: Path, default: Dict, lock: asyncio.Lock) -> Dict[str, Any]:
106
- """加载TOML"""
107
- try:
108
- async with lock:
109
- if not path.exists():
110
- return default
111
- return toml.loads(await self._read(path))
112
- except Exception as e:
113
- logger.error(f"[Storage] 加载{path.name}失败: {e}")
114
- return default
115
-
116
- async def _save_toml(self, path: Path, data: Dict, lock: asyncio.Lock) -> None:
117
- """保存TOML"""
118
- try:
119
- async with lock:
120
- await self._write(path, toml.dumps(data))
121
- except Exception as e:
122
- logger.error(f"[Storage] 保存{path.name}失败: {e}")
123
- raise
124
-
125
- async def load_tokens(self) -> Dict[str, Any]:
126
- """加载token"""
127
- return await self._load_json(self.token_file, {"sso": {}, "ssoSuper": {}}, self._token_lock)
128
-
129
- async def save_tokens(self, data: Dict[str, Any]) -> None:
130
- """保存token"""
131
- await self._save_json(self.token_file, data, self._token_lock)
132
-
133
- async def load_config(self) -> Dict[str, Any]:
134
- """加载配置"""
135
- return await self._load_toml(self.config_file, {"global": {}, "grok": {}}, self._config_lock)
136
-
137
- async def save_config(self, data: Dict[str, Any]) -> None:
138
- """保存配置"""
139
- await self._save_toml(self.config_file, data, self._config_lock)
140
-
141
-
142
- class MysqlStorage(BaseStorage):
143
- """MySQL存储"""
144
-
145
- def __init__(self, database_url: str, data_dir: Path):
146
- self.database_url = database_url
147
- self.data_dir = data_dir
148
- self._pool = None
149
- self._file = FileStorage(data_dir)
150
-
151
- async def init_db(self) -> None:
152
- """初始化MySQL"""
153
- try:
154
- import aiomysql
155
- parsed = self._parse_url(self.database_url)
156
- logger.info(f"[Storage] MySQL: {parsed['user']}@{parsed['host']}:{parsed['port']}/{parsed['db']}")
157
-
158
- await self._create_db(parsed)
159
- self._pool = await aiomysql.create_pool(
160
- host=parsed['host'], port=parsed['port'], user=parsed['user'],
161
- password=parsed['password'], db=parsed['db'], charset="utf8mb4",
162
- autocommit=True, maxsize=10
163
- )
164
- await self._create_tables()
165
- await self._file.init_db()
166
- await self._sync_data()
167
-
168
- except ImportError:
169
- raise Exception("aiomysql未安装")
170
- except Exception as e:
171
- logger.error(f"[Storage] MySQL初始化失败: {e}")
172
- raise
173
-
174
- def _parse_url(self, url: str) -> Dict[str, Any]:
175
- """解析URL"""
176
- p = urlparse(url)
177
- return {
178
- 'user': unquote(p.username) if p.username else "",
179
- 'password': unquote(p.password) if p.password else "",
180
- 'host': p.hostname,
181
- 'port': p.port or 3306,
182
- 'db': p.path[1:] if p.path else "grok2api"
183
- }
184
-
185
- async def _create_db(self, parsed: Dict) -> None:
186
- """创建数据库"""
187
- import aiomysql
188
- pool = await aiomysql.create_pool(
189
- host=parsed['host'], port=parsed['port'], user=parsed['user'],
190
- password=parsed['password'], charset="utf8mb4", autocommit=True, maxsize=1
191
- )
192
-
193
- try:
194
- async with pool.acquire() as conn:
195
- async with conn.cursor() as cursor:
196
- with warnings.catch_warnings():
197
- warnings.filterwarnings('ignore', message='.*database exists')
198
- await cursor.execute(
199
- f"CREATE DATABASE IF NOT EXISTS `{parsed['db']}` "
200
- f"CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
201
- )
202
- logger.info(f"[Storage] 数据库 '{parsed['db']}' 就绪")
203
- finally:
204
- pool.close()
205
- await pool.wait_closed()
206
-
207
- async def _create_tables(self) -> None:
208
- """创建表"""
209
- tables = {
210
- "grok_tokens": """
211
- CREATE TABLE IF NOT EXISTS grok_tokens (
212
- id INT AUTO_INCREMENT PRIMARY KEY,
213
- data JSON NOT NULL,
214
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
215
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
216
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
217
- """,
218
- "grok_settings": """
219
- CREATE TABLE IF NOT EXISTS grok_settings (
220
- id INT AUTO_INCREMENT PRIMARY KEY,
221
- data JSON NOT NULL,
222
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
223
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
224
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
225
- """
226
- }
227
-
228
- async with self._pool.acquire() as conn:
229
- async with conn.cursor() as cursor:
230
- with warnings.catch_warnings():
231
- warnings.filterwarnings('ignore', message='.*already exists')
232
- for sql in tables.values():
233
- await cursor.execute(sql)
234
- logger.info("[Storage] MySQL表就绪")
235
-
236
- async def _sync_data(self) -> None:
237
- """同步数据"""
238
- try:
239
- for table, key in [("grok_tokens", "sso"), ("grok_settings", "global")]:
240
- data = await self._load_db(table)
241
- if data:
242
- if table == "grok_tokens":
243
- await self._file.save_tokens(data)
244
- else:
245
- await self._file.save_config(data)
246
- logger.info(f"[Storage] {table.split('_')[1]}数据已从DB同步")
247
- else:
248
- file_data = await (self._file.load_tokens() if table == "grok_tokens" else self._file.load_config())
249
- if file_data.get(key) or (table == "grok_tokens" and file_data.get("ssoSuper")):
250
- await self._save_db(table, file_data)
251
- logger.info(f"[Storage] {table.split('_')[1]}数据已初始化到DB")
252
- except Exception as e:
253
- logger.warning(f"[Storage] 同步失败: {e}")
254
-
255
- async def _load_db(self, table: str) -> Optional[Dict]:
256
- """从DB加载"""
257
- try:
258
- async with self._pool.acquire() as conn:
259
- async with conn.cursor() as cursor:
260
- await cursor.execute(f"SELECT data FROM {table} ORDER BY id DESC LIMIT 1")
261
- result = await cursor.fetchone()
262
- return orjson.loads(result[0]) if result else None
263
- except Exception as e:
264
- logger.error(f"[Storage] 加载{table}失败: {e}")
265
- return None
266
-
267
- async def _save_db(self, table: str, data: Dict) -> None:
268
- """保存到DB"""
269
- try:
270
- async with self._pool.acquire() as conn:
271
- async with conn.cursor() as cursor:
272
- json_data = orjson.dumps(data).decode()
273
- await cursor.execute(f"SELECT id FROM {table} ORDER BY id DESC LIMIT 1")
274
- result = await cursor.fetchone()
275
-
276
- if result:
277
- await cursor.execute(f"UPDATE {table} SET data = %s WHERE id = %s", (json_data, result[0]))
278
- else:
279
- await cursor.execute(f"INSERT INTO {table} (data) VALUES (%s)", (json_data,))
280
- except Exception as e:
281
- logger.error(f"[Storage] 保存{table}失败: {e}")
282
- raise
283
-
284
- async def load_tokens(self) -> Dict[str, Any]:
285
- """加载token"""
286
- return await self._file.load_tokens()
287
-
288
- async def save_tokens(self, data: Dict[str, Any]) -> None:
289
- """保存token"""
290
- await self._file.save_tokens(data)
291
- await self._save_db("grok_tokens", data)
292
-
293
- async def load_config(self) -> Dict[str, Any]:
294
- """加载配置"""
295
- return await self._file.load_config()
296
-
297
- async def save_config(self, data: Dict[str, Any]) -> None:
298
- """保存配置"""
299
- await self._file.save_config(data)
300
- await self._save_db("grok_settings", data)
301
-
302
- async def close(self) -> None:
303
- """关闭连接"""
304
- if self._pool:
305
- self._pool.close()
306
- await self._pool.wait_closed()
307
- logger.info("[Storage] MySQL已关闭")
308
-
309
-
310
- class RedisStorage(BaseStorage):
311
- """Redis存储"""
312
-
313
- def __init__(self, redis_url: str, data_dir: Path):
314
- self.redis_url = redis_url
315
- self.data_dir = data_dir
316
- self._redis = None
317
- self._file = FileStorage(data_dir)
318
-
319
- async def init_db(self) -> None:
320
- """初始化Redis"""
321
- try:
322
- import redis.asyncio as aioredis
323
- parsed = urlparse(self.redis_url)
324
- db = int(parsed.path.lstrip('/')) if parsed.path and parsed.path != '/' else 0
325
- logger.info(f"[Storage] Redis: {parsed.hostname}:{parsed.port or 6379}/{db}")
326
-
327
- self._redis = aioredis.Redis.from_url(
328
- self.redis_url, encoding="utf-8", decode_responses=True
329
- )
330
-
331
- await self._redis.ping()
332
- logger.info(f"[Storage] Redis连接成功")
333
-
334
- await self._file.init_db()
335
- await self._sync_data()
336
-
337
- except ImportError:
338
- raise Exception("redis未安装")
339
- except Exception as e:
340
- logger.error(f"[Storage] Redis初始化失败: {e}")
341
- raise
342
-
343
- async def _sync_data(self) -> None:
344
- """同步数据"""
345
- try:
346
- for key, file_func, key_name in [
347
- ("grok:tokens", self._file.load_tokens, "sso"),
348
- ("grok:settings", self._file.load_config, "global")
349
- ]:
350
- data = await self._redis.get(key)
351
- if data:
352
- parsed = orjson.loads(data)
353
- if key == "grok:tokens":
354
- await self._file.save_tokens(parsed)
355
- else:
356
- await self._file.save_config(parsed)
357
- logger.info(f"[Storage] {key.split(':')[1]}数据已从Redis同步")
358
- else:
359
- file_data = await file_func()
360
- if file_data.get(key_name) or (key == "grok:tokens" and file_data.get("ssoSuper")):
361
- await self._redis.set(key, orjson.dumps(file_data).decode())
362
- logger.info(f"[Storage] {key.split(':')[1]}数据已初始化到Redis")
363
- except Exception as e:
364
- logger.warning(f"[Storage] 同步失败: {e}")
365
-
366
- async def _save_redis(self, key: str, data: Dict) -> None:
367
- """保存到Redis"""
368
- try:
369
- await self._redis.set(key, orjson.dumps(data).decode())
370
- except Exception as e:
371
- logger.error(f"[Storage] 保存Redis失败: {e}")
372
- raise
373
-
374
- async def load_tokens(self) -> Dict[str, Any]:
375
- """加载token"""
376
- return await self._file.load_tokens()
377
-
378
- async def save_tokens(self, data: Dict[str, Any]) -> None:
379
- """保存token"""
380
- await self._file.save_tokens(data)
381
- await self._save_redis("grok:tokens", data)
382
-
383
- async def load_config(self) -> Dict[str, Any]:
384
- """加载配置"""
385
- return await self._file.load_config()
386
-
387
- async def save_config(self, data: Dict[str, Any]) -> None:
388
- """保存配置"""
389
- await self._file.save_config(data)
390
- await self._save_redis("grok:settings", data)
391
-
392
- async def close(self) -> None:
393
- """关闭连接"""
394
- if self._redis:
395
- await self._redis.close()
396
- logger.info("[Storage] Redis已关闭")
397
-
398
-
399
- class StorageManager:
400
- """存储管理器(单例)"""
401
-
402
- _instance: Optional['StorageManager'] = None
403
- _storage: Optional[BaseStorage] = None
404
- _initialized: bool = False
405
-
406
- def __new__(cls):
407
- if cls._instance is None:
408
- cls._instance = super().__new__(cls)
409
- return cls._instance
410
-
411
- async def init(self) -> None:
412
- """初始化存储"""
413
- if self._initialized:
414
- return
415
-
416
- mode = os.getenv("STORAGE_MODE", "file").lower()
417
- url = os.getenv("DATABASE_URL", "")
418
- data_dir = Path(__file__).parents[2] / "data"
419
-
420
- classes = {"mysql": MysqlStorage, "redis": RedisStorage, "file": FileStorage}
421
-
422
- if mode in ("mysql", "redis") and not url:
423
- raise ValueError(f"{mode.upper()}模式需要DATABASE_URL")
424
-
425
- storage_class = classes.get(mode, FileStorage)
426
- self._storage = storage_class(url, data_dir) if mode != "file" else storage_class(data_dir)
427
-
428
- await self._storage.init_db()
429
- self._initialized = True
430
- logger.info(f"[Storage] 使用{mode}模式")
431
-
432
- def get_storage(self) -> BaseStorage:
433
- """获取存储实例"""
434
- if not self._initialized or not self._storage:
435
- raise RuntimeError("StorageManager未初始化")
436
- return self._storage
437
-
438
- async def close(self) -> None:
439
- """关闭存储"""
440
- if self._storage and hasattr(self._storage, 'close'):
441
- await self._storage.close()
442
-
443
-
444
- # 全局实例
445
- storage_manager = StorageManager()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/models/grok_models.py DELETED
@@ -1,163 +0,0 @@
1
- """Grok 模型配置和枚举定义"""
2
-
3
- from enum import Enum
4
- from typing import Dict, Any, Tuple
5
-
6
-
7
- # 模型配置
8
- _MODEL_CONFIG: Dict[str, Dict[str, Any]] = {
9
- "grok-3-fast": {
10
- "grok_model": ("grok-3", "MODEL_MODE_FAST"),
11
- "rate_limit_model": "grok-3",
12
- "cost": {"type": "low_cost", "multiplier": 1, "description": "计1次调用"},
13
- "requires_super": False,
14
- "display_name": "Grok 3 Fast",
15
- "description": "Fast and efficient Grok 3 model",
16
- "raw_model_path": "xai/grok-3",
17
- "default_temperature": 1.0,
18
- "default_max_output_tokens": 8192,
19
- "supported_max_output_tokens": 131072,
20
- "default_top_p": 0.95
21
- },
22
- "grok-4-fast": {
23
- "grok_model": ("grok-4-mini-thinking-tahoe", "MODEL_MODE_GROK_4_MINI_THINKING"),
24
- "rate_limit_model": "grok-4-mini-thinking-tahoe",
25
- "cost": {"type": "low_cost", "multiplier": 1, "description": "计1次调用"},
26
- "requires_super": False,
27
- "display_name": "Grok 4 Fast",
28
- "description": "Fast version of Grok 4 with mini thinking capabilities",
29
- "raw_model_path": "xai/grok-4-mini-thinking-tahoe",
30
- "default_temperature": 1.0,
31
- "default_max_output_tokens": 8192,
32
- "supported_max_output_tokens": 131072,
33
- "default_top_p": 0.95
34
- },
35
- "grok-4-fast-expert": {
36
- "grok_model": ("grok-4-mini-thinking-tahoe", "MODEL_MODE_EXPERT"),
37
- "rate_limit_model": "grok-4-mini-thinking-tahoe",
38
- "cost": {"type": "high_cost", "multiplier": 4, "description": "计4次调用"},
39
- "requires_super": False,
40
- "display_name": "Grok 4 Fast Expert",
41
- "description": "Expert mode of Grok 4 Fast with enhanced reasoning",
42
- "raw_model_path": "xai/grok-4-mini-thinking-tahoe",
43
- "default_temperature": 1.0,
44
- "default_max_output_tokens": 32768,
45
- "supported_max_output_tokens": 131072,
46
- "default_top_p": 0.95
47
- },
48
- "grok-4-expert": {
49
- "grok_model": ("grok-4", "MODEL_MODE_EXPERT"),
50
- "rate_limit_model": "grok-4",
51
- "cost": {"type": "high_cost", "multiplier": 4, "description": "计4次调用"},
52
- "requires_super": False,
53
- "display_name": "Grok 4 Expert",
54
- "description": "Full Grok 4 model with expert mode capabilities",
55
- "raw_model_path": "xai/grok-4",
56
- "default_temperature": 1.0,
57
- "default_max_output_tokens": 32768,
58
- "supported_max_output_tokens": 131072,
59
- "default_top_p": 0.95
60
- },
61
- "grok-4-heavy": {
62
- "grok_model": ("grok-4-heavy", "MODEL_MODE_HEAVY"),
63
- "rate_limit_model": "grok-4-heavy",
64
- "cost": {"type": "independent", "multiplier": 1, "description": "独立计费,只有Super用户可用"},
65
- "requires_super": True,
66
- "display_name": "Grok 4 Heavy",
67
- "description": "Most powerful Grok 4 model with heavy computational capabilities. Requires Super Token for access.",
68
- "raw_model_path": "xai/grok-4-heavy",
69
- "default_temperature": 1.0,
70
- "default_max_output_tokens": 65536,
71
- "supported_max_output_tokens": 131072,
72
- "default_top_p": 0.95
73
- },
74
- "grok-4.1": {
75
- "grok_model": ("grok-4-1-non-thinking-w-tool", "MODEL_MODE_GROK_4_1"),
76
- "rate_limit_model": "grok-4-1-non-thinking-w-tool",
77
- "cost": {"type": "low_cost", "multiplier": 1, "description": "计1次调用"},
78
- "requires_super": False,
79
- "display_name": "Grok 4.1",
80
- "description": "Latest Grok 4.1 model with tool capabilities",
81
- "raw_model_path": "xai/grok-4-1-non-thinking-w-tool",
82
- "default_temperature": 1.0,
83
- "default_max_output_tokens": 8192,
84
- "supported_max_output_tokens": 131072,
85
- "default_top_p": 0.95
86
- },
87
- "grok-4.1-thinking": {
88
- "grok_model": ("grok-4-1-thinking-1108b", "MODEL_MODE_AUTO"),
89
- "rate_limit_model": "grok-4-1-thinking-1108b",
90
- "cost": {"type": "high_cost", "multiplier": 1, "description": "计1次调用"},
91
- "requires_super": False,
92
- "display_name": "Grok 4.1 Thinking",
93
- "description": "Grok 4.1 model with advanced thinking and tool capabilities",
94
- "raw_model_path": "xai/grok-4-1-thinking-1108b",
95
- "default_temperature": 1.0,
96
- "default_max_output_tokens": 32768,
97
- "supported_max_output_tokens": 131072,
98
- "default_top_p": 0.95
99
- },
100
- "grok-imagine-0.9": {
101
- "grok_model": ("grok-3", "MODEL_MODE_FAST"),
102
- "rate_limit_model": "grok-3",
103
- "cost": {"type": "low_cost", "multiplier": 1, "description": "计1次调用"},
104
- "requires_super": False,
105
- "display_name": "Grok Imagine 0.9",
106
- "description": "Image and video generation model. Supports text-to-image and image-to-video generation.",
107
- "raw_model_path": "xai/grok-imagine-0.9",
108
- "default_temperature": 1.0,
109
- "default_max_output_tokens": 8192,
110
- "supported_max_output_tokens": 131072,
111
- "default_top_p": 0.95,
112
- "is_video_model": True
113
- }
114
- }
115
-
116
-
117
- class TokenType(Enum):
118
- """Token类型"""
119
- NORMAL = "ssoNormal"
120
- SUPER = "ssoSuper"
121
-
122
-
123
- class Models(Enum):
124
- """支持的模型"""
125
- GROK_3_FAST = "grok-3-fast"
126
- GROK_4_1 = "grok-4.1"
127
- GROK_4_1_THINKING = "grok-4.1-thinking"
128
- GROK_4_FAST = "grok-4-fast"
129
- GROK_4_FAST_EXPERT = "grok-4-fast-expert"
130
- GROK_4_EXPERT = "grok-4-expert"
131
- GROK_4_HEAVY = "grok-4-heavy"
132
- GROK_IMAGINE_0_9 = "grok-imagine-0.9"
133
-
134
- @classmethod
135
- def get_model_info(cls, model: str) -> Dict[str, Any]:
136
- """获取模型配置"""
137
- return _MODEL_CONFIG.get(model, {})
138
-
139
- @classmethod
140
- def is_valid_model(cls, model: str) -> bool:
141
- """检查模型是否有效"""
142
- return model in _MODEL_CONFIG
143
-
144
- @classmethod
145
- def to_grok(cls, model: str) -> Tuple[str, str]:
146
- """转换为Grok内部模型名和模式
147
-
148
- Returns:
149
- (模型名, 模式类型) 元组
150
- """
151
- config = _MODEL_CONFIG.get(model)
152
- return config["grok_model"] if config else (model, "MODEL_MODE_FAST")
153
-
154
- @classmethod
155
- def to_rate_limit(cls, model: str) -> str:
156
- """转换为速率限制模型名"""
157
- config = _MODEL_CONFIG.get(model)
158
- return config["rate_limit_model"] if config else model
159
-
160
- @classmethod
161
- def get_all_model_names(cls) -> list[str]:
162
- """获取所有模型名称"""
163
- return list(_MODEL_CONFIG.keys())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/models/openai_schema.py DELETED
@@ -1,103 +0,0 @@
1
- """OpenAI 请求-响应模型定义"""
2
-
3
- from fastapi import HTTPException
4
- from typing import Optional, List, Union, Dict, Any
5
- from pydantic import BaseModel, Field, field_validator
6
-
7
- from app.models.grok_models import Models
8
-
9
-
10
- class OpenAIChatRequest(BaseModel):
11
- """OpenAI聊天请求"""
12
-
13
- model: str = Field(..., description="模型名称", min_length=1)
14
- messages: List[Dict[str, Any]] = Field(..., description="消息列表", min_length=1)
15
- stream: bool = Field(False, description="流式响应")
16
- temperature: Optional[float] = Field(0.7, ge=0, le=2, description="采样温度")
17
- max_tokens: Optional[int] = Field(None, ge=1, le=100000, description="最大Token数")
18
- top_p: Optional[float] = Field(1.0, ge=0, le=1, description="采样参数")
19
-
20
- @classmethod
21
- @field_validator('messages')
22
- def validate_messages(cls, v):
23
- """验证消息格式"""
24
- if not v:
25
- raise HTTPException(status_code=400, detail="消息列表不能为空")
26
-
27
- for msg in v:
28
- if not isinstance(msg, dict):
29
- raise HTTPException(status_code=400, detail="每个消息必须是字典")
30
- if 'role' not in msg:
31
- raise HTTPException(status_code=400, detail="消息缺少 'role' 字段")
32
- if 'content' not in msg:
33
- raise HTTPException(status_code=400, detail="消息缺少 'content' 字段")
34
- if msg['role'] not in ['system', 'user', 'assistant']:
35
- raise HTTPException(
36
- status_code=400,
37
- detail=f"无效角色 '{msg['role']}', 必须是 system/user/assistant"
38
- )
39
-
40
- return v
41
-
42
- @classmethod
43
- @field_validator('model')
44
- def validate_model(cls, v):
45
- """验证模型名称"""
46
- if not Models.is_valid_model(v):
47
- supported = Models.get_all_model_names()
48
- raise HTTPException(
49
- status_code=400,
50
- detail=f"不支持的模型 '{v}', 支持: {', '.join(supported)}"
51
- )
52
- return v
53
-
54
-
55
- class OpenAIChatCompletionMessage(BaseModel):
56
- """聊天完成消息"""
57
- role: str = Field(..., description="角色")
58
- content: str = Field(..., description="内容")
59
- reference_id: Optional[str] = Field(default=None, description="参考ID")
60
- annotations: Optional[List[str]] = Field(default=None, description="注释")
61
-
62
-
63
- class OpenAIChatCompletionChoice(BaseModel):
64
- """聊天完成选项"""
65
- index: int = Field(..., description="索引")
66
- message: OpenAIChatCompletionMessage = Field(..., description="消息")
67
- logprobs: Optional[float] = Field(default=None, description="对数概率")
68
- finish_reason: str = Field(default="stop", description="完成原因")
69
-
70
-
71
- class OpenAIChatCompletionResponse(BaseModel):
72
- """聊天完成响应"""
73
- id: str = Field(..., description="响应ID")
74
- object: str = Field("chat.completion", description="对象类型")
75
- created: int = Field(..., description="创建时间戳")
76
- model: str = Field(..., description="模型")
77
- choices: List[OpenAIChatCompletionChoice] = Field(..., description="选项")
78
- usage: Optional[Dict[str, Any]] = Field(None, description="令牌使用")
79
-
80
-
81
- class OpenAIChatCompletionChunkMessage(BaseModel):
82
- """流式消息片段"""
83
- role: str = Field(..., description="角色")
84
- content: str = Field(..., description="内容")
85
-
86
-
87
- class OpenAIChatCompletionChunkChoice(BaseModel):
88
- """流式选项"""
89
- index: int = Field(..., description="索引")
90
- delta: Optional[Union[Dict[str, Any], OpenAIChatCompletionChunkMessage]] = Field(
91
- None, description="Delta数据"
92
- )
93
- finish_reason: Optional[str] = Field(None, description="完成原因")
94
-
95
-
96
- class OpenAIChatCompletionChunkResponse(BaseModel):
97
- """流式聊天响应"""
98
- id: str = Field(..., description="响应ID")
99
- object: str = Field(default="chat.completion.chunk", description="对象类型")
100
- created: int = Field(..., description="创建时间戳")
101
- model: str = Field(..., description="模型")
102
- system_fingerprint: Optional[str] = Field(default=None, description="系统指纹")
103
- choices: List[OpenAIChatCompletionChunkChoice] = Field(..., description="选项")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/services/grok/cache.py DELETED
@@ -1,244 +0,0 @@
1
- """缓存服务模块 - 提供图片和视频的下载、缓存和清理功能"""
2
-
3
- import asyncio
4
- import base64
5
- from pathlib import Path
6
- from typing import Optional, Tuple
7
- from curl_cffi.requests import AsyncSession
8
-
9
- from app.core.config import setting
10
- from app.core.logger import logger
11
- from app.services.grok.statsig import get_dynamic_headers
12
-
13
-
14
- # 常量定义
15
- MIME_TYPES = {
16
- '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png',
17
- '.gif': 'image/gif', '.webp': 'image/webp', '.bmp': 'image/bmp',
18
- }
19
- DEFAULT_MIME = 'image/jpeg'
20
- ASSETS_URL = "https://assets.grok.com"
21
-
22
-
23
- class CacheService:
24
- """缓存服务基类"""
25
-
26
- def __init__(self, cache_type: str, timeout: float = 30.0):
27
- self.cache_type = cache_type
28
- self.cache_dir = Path(f"data/temp/{cache_type}")
29
- self.cache_dir.mkdir(parents=True, exist_ok=True)
30
- self.timeout = timeout
31
- self._cleanup_lock = asyncio.Lock()
32
-
33
- def _get_path(self, file_path: str) -> Path:
34
- """转换文件路径为缓存路径"""
35
- return self.cache_dir / file_path.lstrip('/').replace('/', '-')
36
-
37
- def _log(self, level: str, msg: str):
38
- """统一日志输出"""
39
- getattr(logger, level)(f"[{self.cache_type.upper()}Cache] {msg}")
40
-
41
- def _build_headers(self, file_path: str, auth_token: str) -> dict:
42
- """构建请求头"""
43
- cf = setting.grok_config.get("cf_clearance", "")
44
- return {
45
- **get_dynamic_headers(pathname=file_path),
46
- "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
47
- "Sec-Fetch-Dest": "document",
48
- "Sec-Fetch-Mode": "navigate",
49
- "Sec-Fetch-Site": "same-site",
50
- "Sec-Fetch-User": "?1",
51
- "Upgrade-Insecure-Requests": "1",
52
- "Referer": "https://grok.com/",
53
- "Cookie": f"{auth_token};{cf}" if cf else auth_token
54
- }
55
-
56
- async def download(self, file_path: str, auth_token: str, timeout: Optional[float] = None) -> Optional[Path]:
57
- """下载并缓存文件"""
58
- cache_path = self._get_path(file_path)
59
- if cache_path.exists():
60
- self._log("debug", "文件已缓存")
61
- return cache_path
62
-
63
- # 外层重试:可配置状态码(401/429等)
64
- retry_codes = setting.grok_config.get("retry_status_codes", [401, 429])
65
- MAX_OUTER_RETRY = 3
66
-
67
- for outer_retry in range(MAX_OUTER_RETRY + 1): # +1 确保实际重试3次
68
- try:
69
- # 内层重试:403代理池重试(cache使用缓存代理,不支持代理池,所以403只重试一次)
70
- max_403_retries = 5
71
- retry_403_count = 0
72
-
73
- while retry_403_count <= max_403_retries:
74
- proxy = await setting.get_proxy_async("cache")
75
- proxies = {"http": proxy, "https": proxy} if proxy else {}
76
-
77
- if proxy and outer_retry == 0 and retry_403_count == 0:
78
- self._log("debug", f"使用代理: {proxy.split('@')[-1] if '@' in proxy else proxy}")
79
-
80
- async with AsyncSession() as session:
81
- url = f"{ASSETS_URL}{file_path}"
82
- if outer_retry == 0 and retry_403_count == 0:
83
- self._log("debug", f"下载: {url}")
84
-
85
- response = await session.get(
86
- url,
87
- headers=self._build_headers(file_path, auth_token),
88
- proxies=proxies,
89
- timeout=timeout or self.timeout,
90
- allow_redirects=True,
91
- impersonate="chrome133a"
92
- )
93
-
94
- # 检查403错误 - 内层重试(cache不使用代理池,所以直接失败)
95
- if response.status_code == 403:
96
- retry_403_count += 1
97
-
98
- if retry_403_count <= max_403_retries:
99
- self._log("warning", f"遇到403错误,正在重试 ({retry_403_count}/{max_403_retries})...")
100
- await asyncio.sleep(0.5)
101
- continue
102
-
103
- self._log("error", f"403错误,已重试{retry_403_count-1}次,放弃")
104
- return None
105
-
106
- # 检查可配置状态码错误 - 外层重试
107
- if response.status_code in retry_codes:
108
- if outer_retry < MAX_OUTER_RETRY:
109
- delay = (outer_retry + 1) * 0.1 # 渐进延迟:0.1s, 0.2s, 0.3s
110
- self._log("warning", f"遇到{response.status_code}错误,外层重试 ({outer_retry+1}/{MAX_OUTER_RETRY}),等待{delay}s...")
111
- await asyncio.sleep(delay)
112
- break # 跳出内层循环,进入外层重试
113
- else:
114
- self._log("error", f"{response.status_code}错误,已重试{outer_retry}次,放弃")
115
- return None
116
-
117
- response.raise_for_status()
118
-
119
- cache_path.write_bytes(response.content)
120
-
121
- if outer_retry > 0 or retry_403_count > 0:
122
- self._log("info", f"重试成功!")
123
- else:
124
- self._log("debug", "缓存成功")
125
-
126
- # 异步清理(带错误处理)
127
- asyncio.create_task(self._safe_cleanup())
128
- return cache_path
129
-
130
- except Exception as e:
131
- if outer_retry < MAX_OUTER_RETRY - 1:
132
- self._log("warning", f"下载异常: {e},外层重试 ({outer_retry+1}/{MAX_OUTER_RETRY})...")
133
- await asyncio.sleep(0.5)
134
- continue
135
-
136
- self._log("error", f"下载失败: {e}(已重试{outer_retry}次)")
137
- return None
138
-
139
- return None
140
-
141
- def get_cached(self, file_path: str) -> Optional[Path]:
142
- """获取已缓存的文件"""
143
- path = self._get_path(file_path)
144
- return path if path.exists() else None
145
-
146
- async def _safe_cleanup(self):
147
- """安全清理(捕获异常)"""
148
- try:
149
- await self.cleanup()
150
- except Exception as e:
151
- self._log("error", f"后台清理失败: {e}")
152
-
153
- async def cleanup(self):
154
- """清理超限缓存"""
155
- if self._cleanup_lock.locked():
156
- return
157
-
158
- async with self._cleanup_lock:
159
- try:
160
- max_mb = setting.global_config.get(f"{self.cache_type}_cache_max_size_mb", 500)
161
- max_bytes = max_mb * 1024 * 1024
162
-
163
- # 获取文件信息 (path, size, mtime)
164
- files = [(f, (s := f.stat()).st_size, s.st_mtime)
165
- for f in self.cache_dir.glob("*") if f.is_file()]
166
- total = sum(size for _, size, _ in files)
167
-
168
- if total <= max_bytes:
169
- return
170
-
171
- self._log("info", f"清理缓存 {total/1024/1024:.1f}MB -> {max_mb}MB")
172
-
173
- # 删除最旧的文件
174
- for path, size, _ in sorted(files, key=lambda x: x[2]):
175
- if total <= max_bytes:
176
- break
177
- path.unlink()
178
- total -= size
179
-
180
- self._log("info", f"清理完成: {total/1024/1024:.1f}MB")
181
- except Exception as e:
182
- self._log("error", f"清理失败: {e}")
183
-
184
-
185
- class ImageCache(CacheService):
186
- """图片缓存服务"""
187
-
188
- def __init__(self):
189
- super().__init__("image", timeout=30.0)
190
-
191
- async def download_image(self, path: str, token: str) -> Optional[Path]:
192
- """下载图片"""
193
- return await self.download(path, token)
194
-
195
- @staticmethod
196
- def to_base64(image_path: Path) -> Optional[str]:
197
- """图片转base64"""
198
- try:
199
- if not image_path.exists():
200
- logger.error(f"[ImageCache] 文件不存在: {image_path}")
201
- return None
202
-
203
- data = base64.b64encode(image_path.read_bytes()).decode()
204
- mime = MIME_TYPES.get(image_path.suffix.lower(), DEFAULT_MIME)
205
- return f"data:{mime};base64,{data}"
206
- except Exception as e:
207
- logger.error(f"[ImageCache] 转换失败: {e}")
208
- return None
209
-
210
- async def download_base64(self, path: str, token: str) -> Optional[str]:
211
- """下载并转为base64(自动删除临时文件)"""
212
- try:
213
- cache_path = await self.download(path, token)
214
- if not cache_path:
215
- return None
216
-
217
- result = self.to_base64(cache_path)
218
-
219
- # 清理临时文件
220
- try:
221
- cache_path.unlink()
222
- except Exception as e:
223
- logger.warning(f"[ImageCache] 删除临时文件失败: {e}")
224
-
225
- return result
226
- except Exception as e:
227
- logger.error(f"[ImageCache] 下载base64失败: {e}")
228
- return None
229
-
230
-
231
- class VideoCache(CacheService):
232
- """视频缓存服务"""
233
-
234
- def __init__(self):
235
- super().__init__("video", timeout=60.0)
236
-
237
- async def download_video(self, path: str, token: str) -> Optional[Path]:
238
- """下载视频"""
239
- return await self.download(path, token)
240
-
241
-
242
- # 全局实例
243
- image_cache_service = ImageCache()
244
- video_cache_service = VideoCache()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/services/grok/client.py DELETED
@@ -1,332 +0,0 @@
1
- """Grok API 客户端 - 处理OpenAI到Grok的请求转换和响应处理"""
2
-
3
- import asyncio
4
- import orjson
5
- from typing import Dict, List, Tuple, Any, Optional
6
- from curl_cffi import requests as curl_requests
7
-
8
- from app.core.config import setting
9
- from app.core.logger import logger
10
- from app.models.grok_models import Models
11
- from app.services.grok.processer import GrokResponseProcessor
12
- from app.services.grok.statsig import get_dynamic_headers
13
- from app.services.grok.token import token_manager
14
- from app.services.grok.upload import ImageUploadManager
15
- from app.services.grok.create import PostCreateManager
16
- from app.core.exception import GrokApiException
17
-
18
-
19
- # 常量
20
- API_ENDPOINT = "https://grok.com/rest/app-chat/conversations/new"
21
- TIMEOUT = 120
22
- BROWSER = "chrome133a"
23
- MAX_RETRY = 3
24
- MAX_UPLOADS = 20 # 提高并发上传限制以支持更高并发
25
-
26
-
27
- class GrokClient:
28
- """Grok API 客户端"""
29
-
30
- _upload_sem = None # 延迟初始化
31
-
32
- @staticmethod
33
- def _get_upload_semaphore():
34
- """获取上传信号量(动态配置)"""
35
- if GrokClient._upload_sem is None:
36
- # 从配置读取,如果不可用则使用默认值
37
- max_concurrency = setting.global_config.get("max_upload_concurrency", MAX_UPLOADS)
38
- GrokClient._upload_sem = asyncio.Semaphore(max_concurrency)
39
- logger.debug(f"[Client] 初始化上传并发限制: {max_concurrency}")
40
- return GrokClient._upload_sem
41
-
42
- @staticmethod
43
- async def openai_to_grok(request: dict):
44
- """转换OpenAI请求为Grok请求"""
45
- model = request["model"]
46
- content, images = GrokClient._extract_content(request["messages"])
47
- stream = request.get("stream", False)
48
-
49
- # 获取模型信息
50
- info = Models.get_model_info(model)
51
- grok_model, mode = Models.to_grok(model)
52
- is_video = info.get("is_video_model", False)
53
-
54
- # 视频模型限制
55
- if is_video and len(images) > 1:
56
- logger.warning(f"[Client] 视频模型仅支持1张图片,已截取前1张")
57
- images = images[:1]
58
-
59
- return await GrokClient._retry(model, content, images, grok_model, mode, is_video, stream)
60
-
61
- @staticmethod
62
- async def _retry(model: str, content: str, images: List[str], grok_model: str, mode: str, is_video: bool, stream: bool):
63
- """重试请求"""
64
- last_err = None
65
-
66
- for i in range(MAX_RETRY):
67
- try:
68
- token = token_manager.get_token(model)
69
- img_ids, img_uris = await GrokClient._upload(images, token)
70
-
71
- # 视频模型创建会话
72
- post_id = None
73
- if is_video and img_ids and img_uris:
74
- post_id = await GrokClient._create_post(img_ids[0], img_uris[0], token)
75
-
76
- payload = GrokClient._build_payload(content, grok_model, mode, img_ids, img_uris, is_video, post_id)
77
- return await GrokClient._request(payload, token, model, stream, post_id)
78
-
79
- except GrokApiException as e:
80
- last_err = e
81
- # 检查是否可重试
82
- if e.error_code not in ["HTTP_ERROR", "NO_AVAILABLE_TOKEN"]:
83
- raise
84
-
85
- status = e.context.get("status") if e.context else None
86
- retry_codes = setting.grok_config.get("retry_status_codes", [401, 429])
87
-
88
- if status not in retry_codes:
89
- raise
90
-
91
- if i < MAX_RETRY - 1:
92
- logger.warning(f"[Client] 失败(状态:{status}), 重试 {i+1}/{MAX_RETRY}")
93
- await asyncio.sleep(0.5)
94
-
95
- raise last_err or GrokApiException("请求失败", "REQUEST_ERROR")
96
-
97
- @staticmethod
98
- def _extract_content(messages: List[Dict]) -> Tuple[str, List[str]]:
99
- """提取文本和图片"""
100
- texts, images = [], []
101
-
102
- for msg in messages:
103
- content = msg.get("content", "")
104
-
105
- if isinstance(content, list):
106
- for item in content:
107
- if item.get("type") == "text":
108
- texts.append(item.get("text", ""))
109
- elif item.get("type") == "image_url":
110
- if url := item.get("image_url", {}).get("url"):
111
- images.append(url)
112
- else:
113
- texts.append(content)
114
-
115
- return "".join(texts), images
116
-
117
- @staticmethod
118
- async def _upload(urls: List[str], token: str) -> Tuple[List[str], List[str]]:
119
- """并发上传图片"""
120
- if not urls:
121
- return [], []
122
-
123
- async def upload_limited(url):
124
- async with GrokClient._get_upload_semaphore():
125
- return await ImageUploadManager.upload(url, token)
126
-
127
- results = await asyncio.gather(*[upload_limited(u) for u in urls], return_exceptions=True)
128
-
129
- ids, uris = [], []
130
- for url, result in zip(urls, results):
131
- if isinstance(result, Exception):
132
- logger.warning(f"[Client] 上传失败: {url} - {result}")
133
- elif isinstance(result, tuple) and len(result) == 2:
134
- fid, furi = result
135
- if fid:
136
- ids.append(fid)
137
- uris.append(furi)
138
-
139
- return ids, uris
140
-
141
- @staticmethod
142
- async def _create_post(file_id: str, file_uri: str, token: str) -> Optional[str]:
143
- """创建视频会话"""
144
- try:
145
- result = await PostCreateManager.create(file_id, file_uri, token)
146
- if result and result.get("success"):
147
- return result.get("post_id")
148
- except Exception as e:
149
- logger.warning(f"[Client] 创建会话失败: {e}")
150
- return None
151
-
152
- @staticmethod
153
- def _build_payload(content: str, model: str, mode: str, img_ids: List[str], img_uris: List[str], is_video: bool = False, post_id: str = None) -> Dict:
154
- """构建请求载荷"""
155
- # 视频模型特殊处理
156
- if is_video and img_uris:
157
- img_msg = f"https://grok.com/imagine/{post_id}" if post_id else f"https://assets.grok.com/post/{img_uris[0]}"
158
- return {
159
- "temporary": True,
160
- "modelName": "grok-3",
161
- "message": f"{img_msg} {content} --mode=custom",
162
- "fileAttachments": img_ids,
163
- "toolOverrides": {"videoGen": True}
164
- }
165
-
166
- # 标准载荷
167
- return {
168
- "temporary": setting.grok_config.get("temporary", True),
169
- "modelName": model,
170
- "message": content,
171
- "fileAttachments": img_ids,
172
- "imageAttachments": [],
173
- "disableSearch": False,
174
- "enableImageGeneration": True,
175
- "returnImageBytes": False,
176
- "returnRawGrokInXaiRequest": False,
177
- "enableImageStreaming": True,
178
- "imageGenerationCount": 2,
179
- "forceConcise": False,
180
- "toolOverrides": {},
181
- "enableSideBySide": True,
182
- "sendFinalMetadata": True,
183
- "isReasoning": False,
184
- "webpageUrls": [],
185
- "disableTextFollowUps": True,
186
- "responseMetadata": {"requestModelDetails": {"modelId": model}},
187
- "disableMemory": False,
188
- "forceSideBySide": False,
189
- "modelMode": mode,
190
- "isAsyncChat": False
191
- }
192
-
193
- @staticmethod
194
- async def _request(payload: dict, token: str, model: str, stream: bool, post_id: str = None):
195
- """发送请求"""
196
- if not token:
197
- raise GrokApiException("认证令牌缺失", "NO_AUTH_TOKEN")
198
-
199
- # 外层重试:可配置状态码(401/429等)
200
- retry_codes = setting.grok_config.get("retry_status_codes", [401, 429])
201
- MAX_OUTER_RETRY = 3
202
-
203
- for outer_retry in range(MAX_OUTER_RETRY + 1): # +1确保实际重试3次
204
- # 内层重试:403代理池重试
205
- max_403_retries = 5
206
- retry_403_count = 0
207
-
208
- while retry_403_count <= max_403_retries:
209
- try:
210
- # 构建请求
211
- headers = GrokClient._build_headers(token)
212
- if model == "grok-imagine-0.9":
213
- file_attachments = payload.get("fileAttachments", [])
214
- ref_id = post_id or (file_attachments[0] if file_attachments else "")
215
- if ref_id:
216
- headers["Referer"] = f"https://grok.com/imagine/{ref_id}"
217
-
218
- # 异步获取代理
219
- from app.core.proxy_pool import proxy_pool
220
-
221
- # 如果是403重试且使用代理池,强制刷新代理
222
- if retry_403_count > 0 and proxy_pool._enabled:
223
- logger.info(f"[Client] 403重试 {retry_403_count}/{max_403_retries},刷新代理...")
224
- proxy = await proxy_pool.force_refresh()
225
- else:
226
- proxy = await setting.get_proxy_async("service")
227
-
228
- proxies = {"http": proxy, "https": proxy} if proxy else None
229
-
230
- # 执行请求
231
- response = await asyncio.to_thread(
232
- curl_requests.post,
233
- API_ENDPOINT,
234
- headers=headers,
235
- data=orjson.dumps(payload),
236
- impersonate=BROWSER,
237
- timeout=TIMEOUT,
238
- stream=True,
239
- proxies=proxies
240
- )
241
-
242
- # 内层403重试:仅当有代理池时触发
243
- if response.status_code == 403 and proxy_pool._enabled:
244
- retry_403_count += 1
245
-
246
- if retry_403_count <= max_403_retries:
247
- logger.warning(f"[Client] 遇到403错误,正在重试 ({retry_403_count}/{max_403_retries})...")
248
- await asyncio.sleep(0.5)
249
- continue
250
-
251
- # 内层重试全部失败
252
- logger.error(f"[Client] 403错误,已重试{retry_403_count-1}次,放弃")
253
-
254
- # 检查可配置状态码错误 - 外层重试
255
- if response.status_code in retry_codes:
256
- if outer_retry < MAX_OUTER_RETRY:
257
- delay = (outer_retry + 1) * 0.1 # 渐进延迟:0.1s, 0.2s, 0.3s
258
- logger.warning(f"[Client] 遇到{response.status_code}错误,外层重试 ({outer_retry+1}/{MAX_OUTER_RETRY}),等待{delay}s...")
259
- await asyncio.sleep(delay)
260
- break # 跳出内层循环,进入外层重试
261
- else:
262
- logger.error(f"[Client] {response.status_code}错误,已重试{outer_retry}次,放弃")
263
- GrokClient._handle_error(response, token)
264
-
265
- # 检查响应状态
266
- if response.status_code != 200:
267
- GrokClient._handle_error(response, token)
268
-
269
- # 成功 - 重置失败计数
270
- asyncio.create_task(token_manager.reset_failure(token))
271
-
272
- # 如果是重试成功,记录日志
273
- if outer_retry > 0 or retry_403_count > 0:
274
- logger.info(f"[Client] 重试成功!")
275
-
276
- # 处理响应
277
- result = (GrokResponseProcessor.process_stream(response, token) if stream
278
- else await GrokResponseProcessor.process_normal(response, token, model))
279
-
280
- asyncio.create_task(GrokClient._update_limits(token, model))
281
- return result
282
-
283
- except curl_requests.RequestsError as e:
284
- logger.error(f"[Client] 网络错误: {e}")
285
- raise GrokApiException(f"网络错误: {e}", "NETWORK_ERROR") from e
286
- except GrokApiException:
287
- # 重新抛出GrokApiException(包括403错误)
288
- raise
289
- except Exception as e:
290
- logger.error(f"[Client] 请求错误: {e}")
291
- raise GrokApiException(f"请求错误: {e}", "REQUEST_ERROR") from e
292
-
293
- # 理论上不应该到这里,但以防万一
294
- raise GrokApiException("请求失败:已达到最大重试次数", "MAX_RETRIES_EXCEEDED")
295
-
296
- @staticmethod
297
- def _build_headers(token: str) -> Dict[str, str]:
298
- """构建请求头"""
299
- headers = get_dynamic_headers("/rest/app-chat/conversations/new")
300
- cf = setting.grok_config.get("cf_clearance", "")
301
- headers["Cookie"] = f"{token};{cf}" if cf else token
302
- return headers
303
-
304
- @staticmethod
305
- def _handle_error(response, token: str):
306
- """处理错误"""
307
- if response.status_code == 403:
308
- msg = "您的IP被拦截,请尝试以下方法之一: 1.更换IP 2.使用代理 3.配置CF值"
309
- data = {"cf_blocked": True, "status": 403}
310
- logger.warning(f"[Client] {msg}")
311
- else:
312
- try:
313
- data = response.json()
314
- msg = str(data)
315
- except:
316
- data = response.text
317
- msg = data[:200] if data else "未知错误"
318
-
319
- asyncio.create_task(token_manager.record_failure(token, response.status_code, msg))
320
- raise GrokApiException(
321
- f"请求失败: {response.status_code} - {msg}",
322
- "HTTP_ERROR",
323
- {"status": response.status_code, "data": data}
324
- )
325
-
326
- @staticmethod
327
- async def _update_limits(token: str, model: str):
328
- """更新速率限制"""
329
- try:
330
- await token_manager.check_limits(token, model)
331
- except Exception as e:
332
- logger.error(f"[Client] 更新限制失败: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/services/grok/create.py DELETED
@@ -1,140 +0,0 @@
1
- """Post创建管理器 - 用于视频生成前的会话创建"""
2
-
3
- import asyncio
4
- import orjson
5
- from typing import Dict, Any, Optional
6
- from curl_cffi.requests import AsyncSession
7
-
8
- from app.services.grok.statsig import get_dynamic_headers
9
- from app.core.exception import GrokApiException
10
- from app.core.config import setting
11
- from app.core.logger import logger
12
-
13
-
14
- # 常量
15
- ENDPOINT = "https://grok.com/rest/media/post/create"
16
- TIMEOUT = 30
17
- BROWSER = "chrome133a"
18
-
19
-
20
- class PostCreateManager:
21
- """会话创建管理器"""
22
-
23
- @staticmethod
24
- async def create(file_id: str, file_uri: str, auth_token: str) -> Optional[Dict[str, Any]]:
25
- """创建会话记录
26
-
27
- Args:
28
- file_id: 文件ID
29
- file_uri: 文件URI
30
- auth_token: 认证令牌
31
-
32
- Returns:
33
- 会话信息字典,包含post_id等
34
- """
35
- # 参数验证
36
- if not file_id or not file_uri:
37
- raise GrokApiException("文件ID或URI缺失", "INVALID_PARAMS")
38
- if not auth_token:
39
- raise GrokApiException("认证令牌缺失", "NO_AUTH_TOKEN")
40
-
41
- try:
42
- # 构建请求
43
- data = {
44
- "media_url": f"https://assets.grok.com/{file_uri}",
45
- "media_type": "MEDIA_POST_TYPE_IMAGE"
46
- }
47
-
48
- cf = setting.grok_config.get("cf_clearance", "")
49
- headers = {
50
- **get_dynamic_headers("/rest/media/post/create"),
51
- "Cookie": f"{auth_token};{cf}" if cf else auth_token
52
- }
53
-
54
- # 外层重试:可配置状态码(401/429等)
55
- retry_codes = setting.grok_config.get("retry_status_codes", [401, 429])
56
- MAX_OUTER_RETRY = 3
57
-
58
- for outer_retry in range(MAX_OUTER_RETRY + 1): # +1 确保实际重试3次
59
- # 内层重试:403代理池重试
60
- max_403_retries = 5
61
- retry_403_count = 0
62
-
63
- while retry_403_count <= max_403_retries:
64
- # 异步获取代理(支持代理池)
65
- from app.core.proxy_pool import proxy_pool
66
-
67
- # 如果是403重试且使用代理池,强制刷新代理
68
- if retry_403_count > 0 and proxy_pool._enabled:
69
- logger.info(f"[PostCreate] 403重试 {retry_403_count}/{max_403_retries},刷新代理...")
70
- proxy = await proxy_pool.force_refresh()
71
- else:
72
- proxy = await setting.get_proxy_async("service")
73
-
74
- proxies = {"http": proxy, "https": proxy} if proxy else None
75
-
76
- # 发送请求
77
- async with AsyncSession() as session:
78
- response = await session.post(
79
- ENDPOINT,
80
- headers=headers,
81
- json=data,
82
- impersonate=BROWSER,
83
- timeout=TIMEOUT,
84
- proxies=proxies
85
- )
86
-
87
- # 内层403重试:仅当有代理池时触发
88
- if response.status_code == 403 and proxy_pool._enabled:
89
- retry_403_count += 1
90
-
91
- if retry_403_count <= max_403_retries:
92
- logger.warning(f"[PostCreate] 遇到403错误,正在重试 ({retry_403_count}/{max_403_retries})...")
93
- await asyncio.sleep(0.5)
94
- continue
95
-
96
- # 内层重试全部失败
97
- logger.error(f"[PostCreate] 403错误,已重试{retry_403_count-1}次,放弃")
98
-
99
- # 检查可配置状态码错误 - 外层重试
100
- if response.status_code in retry_codes:
101
- if outer_retry < MAX_OUTER_RETRY:
102
- delay = (outer_retry + 1) * 0.1 # 渐进延迟:0.1s, 0.2s, 0.3s
103
- logger.warning(f"[PostCreate] 遇到{response.status_code}错误,外层重试 ({outer_retry+1}/{MAX_OUTER_RETRY}),等待{delay}s...")
104
- await asyncio.sleep(delay)
105
- break # 跳出内层循环,进入外层重试
106
- else:
107
- logger.error(f"[PostCreate] {response.status_code}错误,已重试{outer_retry}次,放弃")
108
- raise GrokApiException(f"创建失败: {response.status_code}错误", "CREATE_ERROR")
109
-
110
- if response.status_code == 200:
111
- result = response.json()
112
- post_id = result.get("post", {}).get("id", "")
113
-
114
- if outer_retry > 0 or retry_403_count > 0:
115
- logger.info(f"[PostCreate] 重试成功!")
116
-
117
- logger.debug(f"[PostCreate] 成功,会话ID: {post_id}")
118
- return {
119
- "post_id": post_id,
120
- "file_id": file_id,
121
- "file_uri": file_uri,
122
- "success": True,
123
- "data": result
124
- }
125
-
126
- # 其他错误处理
127
- try:
128
- error = response.json()
129
- msg = f"状态码: {response.status_code}, 详情: {error}"
130
- except:
131
- msg = f"状态码: {response.status_code}, 详情: {response.text[:200]}"
132
-
133
- logger.error(f"[PostCreate] 失败: {msg}")
134
- raise GrokApiException(f"创建失败: {msg}", "CREATE_ERROR")
135
-
136
- except GrokApiException:
137
- raise
138
- except Exception as e:
139
- logger.error(f"[PostCreate] 异常: {e}")
140
- raise GrokApiException(f"创建异常: {e}", "CREATE_ERROR") from e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/services/grok/processer.py DELETED
@@ -1,423 +0,0 @@
1
- """Grok API 响应处理器 - 处理流式和非流式响应"""
2
-
3
- import orjson
4
- import uuid
5
- import time
6
- import asyncio
7
- from typing import AsyncGenerator, Tuple
8
-
9
- from app.core.config import setting
10
- from app.core.exception import GrokApiException
11
- from app.core.logger import logger
12
- from app.models.openai_schema import (
13
- OpenAIChatCompletionResponse,
14
- OpenAIChatCompletionChoice,
15
- OpenAIChatCompletionMessage,
16
- OpenAIChatCompletionChunkResponse,
17
- OpenAIChatCompletionChunkChoice,
18
- OpenAIChatCompletionChunkMessage
19
- )
20
- from app.services.grok.cache import image_cache_service, video_cache_service
21
-
22
-
23
- class StreamTimeoutManager:
24
- """流式响应超时管理"""
25
-
26
- def __init__(self, chunk_timeout: int = 120, first_timeout: int = 30, total_timeout: int = 600):
27
- self.chunk_timeout = chunk_timeout
28
- self.first_timeout = first_timeout
29
- self.total_timeout = total_timeout
30
- self.start_time = asyncio.get_event_loop().time()
31
- self.last_chunk_time = self.start_time
32
- self.first_received = False
33
-
34
- def check_timeout(self) -> Tuple[bool, str]:
35
- """检查超时"""
36
- now = asyncio.get_event_loop().time()
37
-
38
- if not self.first_received and now - self.start_time > self.first_timeout:
39
- return True, f"首次响应超时({self.first_timeout}秒)"
40
-
41
- if self.total_timeout > 0 and now - self.start_time > self.total_timeout:
42
- return True, f"总超时({self.total_timeout}秒)"
43
-
44
- if self.first_received and now - self.last_chunk_time > self.chunk_timeout:
45
- return True, f"数据块超时({self.chunk_timeout}秒)"
46
-
47
- return False, ""
48
-
49
- def mark_received(self):
50
- """标记收到数据"""
51
- self.last_chunk_time = asyncio.get_event_loop().time()
52
- self.first_received = True
53
-
54
- def duration(self) -> float:
55
- """获取总耗时"""
56
- return asyncio.get_event_loop().time() - self.start_time
57
-
58
-
59
- class GrokResponseProcessor:
60
- """Grok响应处理器"""
61
-
62
- @staticmethod
63
- async def process_normal(response, auth_token: str, model: str = None) -> OpenAIChatCompletionResponse:
64
- """处理非流式响应"""
65
- response_closed = False
66
- try:
67
- for chunk in response.iter_lines():
68
- if not chunk:
69
- continue
70
-
71
- data = orjson.loads(chunk)
72
-
73
- # 错误检查
74
- if error := data.get("error"):
75
- raise GrokApiException(
76
- f"API错误: {error.get('message', '未知错误')}",
77
- "API_ERROR",
78
- {"code": error.get("code")}
79
- )
80
-
81
- grok_resp = data.get("result", {}).get("response", {})
82
-
83
- # 视频响应
84
- if video_resp := grok_resp.get("streamingVideoGenerationResponse"):
85
- if video_url := video_resp.get("videoUrl"):
86
- content = await GrokResponseProcessor._build_video_content(video_url, auth_token)
87
- result = GrokResponseProcessor._build_response(content, model or "grok-imagine-0.9")
88
- response_closed = True
89
- response.close()
90
- return result
91
-
92
- # 模型响应
93
- model_response = grok_resp.get("modelResponse")
94
- if not model_response:
95
- continue
96
-
97
- if error_msg := model_response.get("error"):
98
- raise GrokApiException(f"模型错误: {error_msg}", "MODEL_ERROR")
99
-
100
- # 构建内容
101
- content = model_response.get("message", "")
102
- model_name = model_response.get("model")
103
-
104
- # 处理图片
105
- if images := model_response.get("generatedImageUrls"):
106
- content = await GrokResponseProcessor._append_images(content, images, auth_token)
107
-
108
- result = GrokResponseProcessor._build_response(content, model_name)
109
- response_closed = True
110
- response.close()
111
- return result
112
-
113
- raise GrokApiException("无响应数据", "NO_RESPONSE")
114
-
115
- except orjson.JSONDecodeError as e:
116
- logger.error(f"[Processor] JSON解析失败: {e}")
117
- raise GrokApiException(f"JSON解析失败: {e}", "JSON_ERROR") from e
118
- except Exception as e:
119
- logger.error(f"[Processor] 处理错误: {type(e).__name__}: {e}")
120
- raise GrokApiException(f"响应处理错误: {e}", "PROCESS_ERROR") from e
121
- finally:
122
- if not response_closed and hasattr(response, 'close'):
123
- try:
124
- response.close()
125
- except Exception as e:
126
- logger.warning(f"[Processor] 关闭响应失败: {e}")
127
-
128
- @staticmethod
129
- async def process_stream(response, auth_token: str) -> AsyncGenerator[str, None]:
130
- """处理流式响应"""
131
- # 状态变量
132
- is_image = False
133
- is_thinking = False
134
- thinking_finished = False
135
- model = None
136
- filtered_tags = setting.grok_config.get("filtered_tags", "").split(",")
137
- video_progress_started = False
138
- last_video_progress = -1
139
- response_closed = False
140
- show_thinking = setting.grok_config.get("show_thinking", True)
141
-
142
- # 超时管理
143
- timeout_mgr = StreamTimeoutManager(
144
- chunk_timeout=setting.grok_config.get("stream_chunk_timeout", 120),
145
- first_timeout=setting.grok_config.get("stream_first_response_timeout", 30),
146
- total_timeout=setting.grok_config.get("stream_total_timeout", 600)
147
- )
148
-
149
- def make_chunk(content: str, finish: str = None):
150
- """生成响应块"""
151
- chunk_data = OpenAIChatCompletionChunkResponse(
152
- id=f"chatcmpl-{uuid.uuid4()}",
153
- created=int(time.time()),
154
- model=model or "grok-4-mini-thinking-tahoe",
155
- choices=[OpenAIChatCompletionChunkChoice(
156
- index=0,
157
- delta=OpenAIChatCompletionChunkMessage(
158
- role="assistant",
159
- content=content
160
- ) if content else {},
161
- finish_reason=finish
162
- )]
163
- )
164
- return f"data: {chunk_data.model_dump_json()}\n\n"
165
-
166
- try:
167
- for chunk in response.iter_lines():
168
- # 超时检查
169
- is_timeout, timeout_msg = timeout_mgr.check_timeout()
170
- if is_timeout:
171
- logger.warning(f"[Processor] {timeout_msg}")
172
- yield make_chunk("", "stop")
173
- yield "data: [DONE]\n\n"
174
- return
175
-
176
- logger.debug(f"[Processor] 收到数据块: {len(chunk)} bytes")
177
- if not chunk:
178
- continue
179
-
180
- try:
181
- data = orjson.loads(chunk)
182
-
183
- # 错误检查
184
- if error := data.get("error"):
185
- error_msg = error.get('message', '未知错误')
186
- logger.error(f"[Processor] API错误: {error_msg}")
187
- yield make_chunk(f"Error: {error_msg}", "stop")
188
- yield "data: [DONE]\n\n"
189
- return
190
-
191
- grok_resp = data.get("result", {}).get("response", {})
192
- logger.debug(f"[Processor] 解析响应: {len(grok_resp)} bytes")
193
- if not grok_resp:
194
- continue
195
-
196
- timeout_mgr.mark_received()
197
-
198
- # 更新模型
199
- if user_resp := grok_resp.get("userResponse"):
200
- if m := user_resp.get("model"):
201
- model = m
202
-
203
- # 视频处理
204
- if video_resp := grok_resp.get("streamingVideoGenerationResponse"):
205
- progress = video_resp.get("progress", 0)
206
- v_url = video_resp.get("videoUrl")
207
-
208
- # 进度更新
209
- if progress > last_video_progress:
210
- last_video_progress = progress
211
- if show_thinking:
212
- if not video_progress_started:
213
- content = f"<think>视频已生成{progress}%\n"
214
- video_progress_started = True
215
- elif progress < 100:
216
- content = f"视频已生成{progress}%\n"
217
- else:
218
- content = f"视频已生成{progress}%</think>\n"
219
- yield make_chunk(content)
220
-
221
- # 视频URL
222
- if v_url:
223
- logger.debug("[Processor] 视频生成完成")
224
- video_content = await GrokResponseProcessor._build_video_content(v_url, auth_token)
225
- yield make_chunk(video_content)
226
-
227
- continue
228
-
229
- # 图片模式
230
- if grok_resp.get("imageAttachmentInfo"):
231
- is_image = True
232
-
233
- token = grok_resp.get("token", "")
234
-
235
- # 图片处理
236
- if is_image:
237
- if model_resp := grok_resp.get("modelResponse"):
238
- image_mode = setting.global_config.get("image_mode", "url")
239
- content = ""
240
-
241
- for img in model_resp.get("generatedImageUrls", []):
242
- try:
243
- if image_mode == "base64":
244
- # Base64模式 - 分块发送
245
- base64_str = await image_cache_service.download_base64(f"/{img}", auth_token)
246
- if base64_str:
247
- # 分块发送大数据
248
- if not base64_str.startswith("data:"):
249
- parts = base64_str.split(",", 1)
250
- if len(parts) == 2:
251
- yield make_chunk(f"![Generated Image](data:{parts[0]},")
252
- # 8KB分块
253
- for i in range(0, len(parts[1]), 8192):
254
- yield make_chunk(parts[1][i:i+8192])
255
- yield make_chunk(")\n")
256
- else:
257
- yield make_chunk(f"![Generated Image]({base64_str})\n")
258
- else:
259
- yield make_chunk(f"![Generated Image]({base64_str})\n")
260
- else:
261
- yield make_chunk(f"![Generated Image](https://assets.grok.com/{img})\n")
262
- else:
263
- # URL模式
264
- await image_cache_service.download_image(f"/{img}", auth_token)
265
- img_path = img.replace('/', '-')
266
- base_url = setting.global_config.get("base_url", "")
267
- img_url = f"{base_url}/images/{img_path}" if base_url else f"/images/{img_path}"
268
- content += f"![Generated Image]({img_url})\n"
269
- except Exception as e:
270
- logger.warning(f"[Processor] 处理图片失败: {e}")
271
- content += f"![Generated Image](https://assets.grok.com/{img})\n"
272
-
273
- yield make_chunk(content.strip(), "stop")
274
- return
275
- elif token:
276
- yield make_chunk(token)
277
-
278
- # 对话处理
279
- else:
280
- if isinstance(token, list):
281
- continue
282
-
283
- if any(tag in token for tag in filtered_tags if token):
284
- continue
285
-
286
- current_is_thinking = grok_resp.get("isThinking", False)
287
- message_tag = grok_resp.get("messageTag")
288
-
289
- if thinking_finished and current_is_thinking:
290
- continue
291
-
292
- # 搜索结果处理
293
- if grok_resp.get("toolUsageCardId"):
294
- if web_search := grok_resp.get("webSearchResults"):
295
- if current_is_thinking:
296
- if show_thinking:
297
- for result in web_search.get("results", []):
298
- title = result.get("title", "")
299
- url = result.get("url", "")
300
- preview = result.get("preview", "")
301
- preview_clean = preview.replace("\n", "") if isinstance(preview, str) else ""
302
- token += f'\n- [{title}]({url} "{preview_clean}")'
303
- token += "\n"
304
- else:
305
- continue
306
- else:
307
- continue
308
- else:
309
- continue
310
-
311
- if token:
312
- content = token
313
-
314
- if message_tag == "header":
315
- content = f"\n\n{token}\n\n"
316
-
317
- # Thinking状态切换
318
- should_skip = False
319
- if not is_thinking and current_is_thinking:
320
- if show_thinking:
321
- content = f"<think>\n{content}"
322
- else:
323
- should_skip = True
324
- elif is_thinking and not current_is_thinking:
325
- if show_thinking:
326
- content = f"\n</think>\n{content}"
327
- thinking_finished = True
328
- elif current_is_thinking:
329
- if not show_thinking:
330
- should_skip = True
331
-
332
- if not should_skip:
333
- yield make_chunk(content)
334
-
335
- is_thinking = current_is_thinking
336
-
337
- except (orjson.JSONDecodeError, UnicodeDecodeError) as e:
338
- logger.warning(f"[Processor] 解析失败: {e}")
339
- continue
340
- except Exception as e:
341
- logger.warning(f"[Processor] 处理出错: {e}")
342
- continue
343
-
344
- yield make_chunk("", "stop")
345
- yield "data: [DONE]\n\n"
346
- logger.info(f"[Processor] 流式完成,耗时: {timeout_mgr.duration():.2f}秒")
347
-
348
- except Exception as e:
349
- logger.error(f"[Processor] 严重错误: {e}")
350
- yield make_chunk(f"处理错误: {e}", "error")
351
- yield "data: [DONE]\n\n"
352
- finally:
353
- if not response_closed and hasattr(response, 'close'):
354
- try:
355
- response.close()
356
- logger.debug("[Processor] 响应已关闭")
357
- except Exception as e:
358
- logger.warning(f"[Processor] 关闭失败: {e}")
359
-
360
- @staticmethod
361
- async def _build_video_content(video_url: str, auth_token: str) -> str:
362
- """构建视频内容"""
363
- logger.debug(f"[Processor] 检测到视频: {video_url}")
364
- full_url = f"https://assets.grok.com/{video_url}"
365
-
366
- try:
367
- cache_path = await video_cache_service.download_video(f"/{video_url}", auth_token)
368
- if cache_path:
369
- video_path = video_url.replace('/', '-')
370
- base_url = setting.global_config.get("base_url", "")
371
- local_url = f"{base_url}/images/{video_path}" if base_url else f"/images/{video_path}"
372
- return f'<video src="{local_url}" controls="controls" width="500" height="300"></video>\n'
373
- except Exception as e:
374
- logger.warning(f"[Processor] 缓存视频失败: {e}")
375
-
376
- return f'<video src="{full_url}" controls="controls" width="500" height="300"></video>\n'
377
-
378
- @staticmethod
379
- async def _append_images(content: str, images: list, auth_token: str) -> str:
380
- """追加图片到内容"""
381
- image_mode = setting.global_config.get("image_mode", "url")
382
-
383
- for img in images:
384
- try:
385
- if image_mode == "base64":
386
- base64_str = await image_cache_service.download_base64(f"/{img}", auth_token)
387
- if base64_str:
388
- content += f"\n![Generated Image]({base64_str})"
389
- else:
390
- content += f"\n![Generated Image](https://assets.grok.com/{img})"
391
- else:
392
- cache_path = await image_cache_service.download_image(f"/{img}", auth_token)
393
- if cache_path:
394
- img_path = img.replace('/', '-')
395
- base_url = setting.global_config.get("base_url", "")
396
- img_url = f"{base_url}/images/{img_path}" if base_url else f"/images/{img_path}"
397
- content += f"\n![Generated Image]({img_url})"
398
- else:
399
- content += f"\n![Generated Image](https://assets.grok.com/{img})"
400
- except Exception as e:
401
- logger.warning(f"[Processor] 处理图片失败: {e}")
402
- content += f"\n![Generated Image](https://assets.grok.com/{img})"
403
-
404
- return content
405
-
406
- @staticmethod
407
- def _build_response(content: str, model: str) -> OpenAIChatCompletionResponse:
408
- """构建响应对象"""
409
- return OpenAIChatCompletionResponse(
410
- id=f"chatcmpl-{uuid.uuid4()}",
411
- object="chat.completion",
412
- created=int(time.time()),
413
- model=model,
414
- choices=[OpenAIChatCompletionChoice(
415
- index=0,
416
- message=OpenAIChatCompletionMessage(
417
- role="assistant",
418
- content=content
419
- ),
420
- finish_reason="stop"
421
- )],
422
- usage=None
423
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/services/grok/statsig.py DELETED
@@ -1,80 +0,0 @@
1
- """Grok 请求头管理 - 生成动态请求头和Statsig ID"""
2
-
3
- import base64
4
- import random
5
- import string
6
- import uuid
7
- from typing import Dict
8
-
9
- from app.core.logger import logger
10
- from app.core.config import setting
11
-
12
-
13
- # 基础请求头
14
- BASE_HEADERS = {
15
- "Accept": "*/*",
16
- "Accept-Language": "zh-CN,zh;q=0.9",
17
- "Accept-Encoding": "gzip, deflate, br, zstd",
18
- "Connection": "keep-alive",
19
- "Origin": "https://grok.com",
20
- "Priority": "u=1, i",
21
- "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",
22
- "Sec-Ch-Ua": '"Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"',
23
- "Sec-Ch-Ua-Mobile": "?0",
24
- "Sec-Ch-Ua-Platform": '"macOS"',
25
- "Sec-Fetch-Dest": "empty",
26
- "Sec-Fetch-Mode": "cors",
27
- "Sec-Fetch-Site": "same-origin",
28
- "Baggage": "sentry-environment=production,sentry-public_key=b311e0f2690c81f25e2c4cf6d4f7ce1c",
29
- }
30
-
31
-
32
- def _random_string(length: int, letters_only: bool = True) -> str:
33
- """生成随机字符串"""
34
- chars = string.ascii_lowercase if letters_only else string.ascii_lowercase + string.digits
35
- return ''.join(random.choices(chars, k=length))
36
-
37
-
38
- def _generate_statsig_id() -> str:
39
- """生成x-statsig-id
40
-
41
- 随机选择两种格式:
42
- 1. e:TypeError: Cannot read properties of null (reading 'children['xxxxx']')
43
- 2. e:TypeError: Cannot read properties of undefined (reading 'xxxxxxxxxx')
44
- """
45
- if random.choice([True, False]):
46
- rand = _random_string(5, letters_only=False)
47
- msg = f"e:TypeError: Cannot read properties of null (reading 'children['{rand}']')"
48
- else:
49
- rand = _random_string(10)
50
- msg = f"e:TypeError: Cannot read properties of undefined (reading '{rand}')"
51
-
52
- return base64.b64encode(msg.encode()).decode()
53
-
54
-
55
- def get_dynamic_headers(pathname: str = "/rest/app-chat/conversations/new") -> Dict[str, str]:
56
- """获取请求头
57
-
58
- Args:
59
- pathname: 请求路径
60
-
61
- Returns:
62
- 完整的请求头字典
63
- """
64
- # 获取或生成statsig-id
65
- if setting.grok_config.get("dynamic_statsig", False):
66
- statsig_id = _generate_statsig_id()
67
- logger.debug(f"[Statsig] 动态生成: {statsig_id}")
68
- else:
69
- statsig_id = setting.grok_config.get("x_statsig_id")
70
- if not statsig_id:
71
- raise ValueError("配置文件中未设置 x_statsig_id")
72
- logger.debug(f"[Statsig] 使用固定值: {statsig_id}")
73
-
74
- # 构建请求头
75
- headers = BASE_HEADERS.copy()
76
- headers["x-statsig-id"] = statsig_id
77
- headers["x-xai-request-id"] = str(uuid.uuid4())
78
- headers["Content-Type"] = "text/plain;charset=UTF-8" if "upload-file" in pathname else "application/json"
79
-
80
- return headers
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/services/grok/token.py DELETED
@@ -1,487 +0,0 @@
1
- """Grok Token 管理器 - 单例模式的Token负载均衡和状态管理"""
2
-
3
- import orjson
4
- import time
5
- import asyncio
6
- import aiofiles
7
- import portalocker
8
- from pathlib import Path
9
- from curl_cffi.requests import AsyncSession
10
- from typing import Dict, Any, Optional, Tuple
11
-
12
- from app.models.grok_models import TokenType, Models
13
- from app.core.exception import GrokApiException
14
- from app.core.logger import logger
15
- from app.core.config import setting
16
- from app.services.grok.statsig import get_dynamic_headers
17
-
18
-
19
- # 常量
20
- RATE_LIMIT_API = "https://grok.com/rest/rate-limits"
21
- TIMEOUT = 30
22
- BROWSER = "chrome133a"
23
- MAX_FAILURES = 3
24
- TOKEN_INVALID = 401
25
- STATSIG_INVALID = 403
26
-
27
-
28
- class GrokTokenManager:
29
- """Token管理器(单例)"""
30
-
31
- _instance: Optional['GrokTokenManager'] = None
32
- _lock = asyncio.Lock()
33
-
34
- def __new__(cls) -> 'GrokTokenManager':
35
- if cls._instance is None:
36
- cls._instance = super().__new__(cls)
37
- return cls._instance
38
-
39
- def __init__(self):
40
- if hasattr(self, '_initialized'):
41
- return
42
-
43
- self.token_file = Path(__file__).parents[3] / "data" / "token.json"
44
- self._file_lock = asyncio.Lock()
45
- self.token_file.parent.mkdir(parents=True, exist_ok=True)
46
- self._storage = None
47
- self.token_data = None # 延迟加载
48
-
49
- # 批量保存队列
50
- self._save_pending = False # 标记是否有待保存的数据
51
- self._save_task = None # 后台保存任务
52
- self._shutdown = False # 关闭标志
53
-
54
- self._initialized = True
55
- logger.debug(f"[Token] 初始化完成: {self.token_file}")
56
-
57
- def set_storage(self, storage) -> None:
58
- """设置存储实例"""
59
- self._storage = storage
60
-
61
- async def _load_data(self) -> None:
62
- """异步加载Token数据(支持多进程)"""
63
- default = {TokenType.NORMAL.value: {}, TokenType.SUPER.value: {}}
64
-
65
- try:
66
- if self.token_file.exists():
67
- # 使用进程锁读取文件
68
- async with self._file_lock:
69
- with open(self.token_file, "r", encoding="utf-8") as f:
70
- portalocker.lock(f, portalocker.LOCK_SH) # 共享锁(读)
71
- try:
72
- content = f.read()
73
- self.token_data = orjson.loads(content)
74
- finally:
75
- portalocker.unlock(f)
76
- else:
77
- self.token_data = default
78
- logger.debug("[Token] 创建新数据文件")
79
- except Exception as e:
80
- logger.error(f"[Token] 加载失败: {e}")
81
- self.token_data = default
82
-
83
- async def _save_data(self) -> None:
84
- """保存Token数据(支持多进程)"""
85
- try:
86
- if not self._storage:
87
- async with self._file_lock:
88
- # 使用进程锁写入文件
89
- with open(self.token_file, "w", encoding="utf-8") as f:
90
- portalocker.lock(f, portalocker.LOCK_EX) # 独占锁(写)
91
- try:
92
- content = orjson.dumps(self.token_data, option=orjson.OPT_INDENT_2).decode()
93
- f.write(content)
94
- f.flush() # 确保写入磁盘
95
- finally:
96
- portalocker.unlock(f)
97
- else:
98
- await self._storage.save_tokens(self.token_data)
99
- except IOError as e:
100
- logger.error(f"[Token] 保存失败: {e}")
101
- raise GrokApiException(f"保存失败: {e}", "TOKEN_SAVE_ERROR", {"file": str(self.token_file)})
102
-
103
- def _mark_dirty(self) -> None:
104
- """标记有待保存的数据"""
105
- self._save_pending = True
106
-
107
- async def _batch_save_worker(self) -> None:
108
- """批量保存后台任务"""
109
- from app.core.config import setting
110
-
111
- interval = setting.global_config.get("batch_save_interval", 1.0)
112
- logger.info(f"[Token] 存储任务已启动,间隔: {interval}s")
113
-
114
- while not self._shutdown:
115
- await asyncio.sleep(interval)
116
-
117
- if self._save_pending and not self._shutdown:
118
- try:
119
- await self._save_data()
120
- self._save_pending = False
121
- logger.debug("[Token] 存储完成")
122
- except Exception as e:
123
- logger.error(f"[Token] 存储失败: {e}")
124
-
125
- async def start_batch_save(self) -> None:
126
- """启动批量保存任务"""
127
- if self._save_task is None:
128
- self._save_task = asyncio.create_task(self._batch_save_worker())
129
- logger.info("[Token] 存储任务已创建")
130
-
131
- async def shutdown(self) -> None:
132
- """关闭并刷新所有待保存数据"""
133
- self._shutdown = True
134
-
135
- if self._save_task:
136
- self._save_task.cancel()
137
- try:
138
- await self._save_task
139
- except asyncio.CancelledError:
140
- pass
141
-
142
- # 最终刷新
143
- if self._save_pending:
144
- await self._save_data()
145
- logger.info("[Token] 关闭时刷新完成")
146
-
147
- @staticmethod
148
- def _extract_sso(auth_token: str) -> Optional[str]:
149
- """提取SSO值"""
150
- if "sso=" in auth_token:
151
- return auth_token.split("sso=")[1].split(";")[0]
152
- logger.warning("[Token] 无法提取SSO值")
153
- return None
154
-
155
- def _find_token(self, sso: str) -> Tuple[Optional[str], Optional[Dict]]:
156
- """查找Token"""
157
- for token_type in [TokenType.NORMAL.value, TokenType.SUPER.value]:
158
- if sso in self.token_data[token_type]:
159
- return token_type, self.token_data[token_type][sso]
160
- return None, None
161
-
162
- async def add_token(self, tokens: list[str], token_type: TokenType) -> None:
163
- """添加Token"""
164
- if not tokens:
165
- return
166
-
167
- count = 0
168
- for token in tokens:
169
- if not token or not token.strip():
170
- continue
171
-
172
- self.token_data[token_type.value][token] = {
173
- "createdTime": int(time.time() * 1000),
174
- "remainingQueries": -1,
175
- "heavyremainingQueries": -1,
176
- "status": "active",
177
- "failedCount": 0,
178
- "lastFailureTime": None,
179
- "lastFailureReason": None,
180
- "tags": [],
181
- "note": ""
182
- }
183
- count += 1
184
-
185
- self._mark_dirty() # 批量保存
186
- logger.info(f"[Token] 添加 {count} 个 {token_type.value} Token")
187
-
188
- async def delete_token(self, tokens: list[str], token_type: TokenType) -> None:
189
- """删除Token"""
190
- if not tokens:
191
- return
192
-
193
- count = 0
194
- for token in tokens:
195
- if token in self.token_data[token_type.value]:
196
- del self.token_data[token_type.value][token]
197
- count += 1
198
-
199
- self._mark_dirty() # 批量保存
200
- logger.info(f"[Token] 删除 {count} 个 {token_type.value} Token")
201
-
202
- async def update_token_tags(self, token: str, token_type: TokenType, tags: list[str]) -> None:
203
- """更新Token标签"""
204
- if token not in self.token_data[token_type.value]:
205
- raise GrokApiException("Token不存在", "TOKEN_NOT_FOUND", {"token": token[:10]})
206
-
207
- cleaned = [t.strip() for t in tags if t and t.strip()]
208
- self.token_data[token_type.value][token]["tags"] = cleaned
209
- self._mark_dirty() # 批量保存
210
- logger.info(f"[Token] 更新标签: {token[:10]}... -> {cleaned}")
211
-
212
- async def update_token_note(self, token: str, token_type: TokenType, note: str) -> None:
213
- """更新Token备注"""
214
- if token not in self.token_data[token_type.value]:
215
- raise GrokApiException("Token不存在", "TOKEN_NOT_FOUND", {"token": token[:10]})
216
-
217
- self.token_data[token_type.value][token]["note"] = note.strip()
218
- self._mark_dirty() # 批量保存
219
- logger.info(f"[Token] 更新备注: {token[:10]}...")
220
-
221
- def get_tokens(self) -> Dict[str, Any]:
222
- """获取所有Token"""
223
- return self.token_data.copy()
224
-
225
- def _reload_if_needed(self) -> None:
226
- """在多进程模式下重新加载数据(同步版本,用于select_token)"""
227
- # 只在文件模式且多进程环境下才重新加载
228
- if self._storage:
229
- return # 数据库模式不需要
230
-
231
- try:
232
- if self.token_file.exists():
233
- with open(self.token_file, "r", encoding="utf-8") as f:
234
- portalocker.lock(f, portalocker.LOCK_SH)
235
- try:
236
- content = f.read()
237
- self.token_data = orjson.loads(content)
238
- finally:
239
- portalocker.unlock(f)
240
- except Exception as e:
241
- logger.warning(f"[Token] 重新加载失败: {e}")
242
-
243
- def get_token(self, model: str) -> str:
244
- """获取Token"""
245
- jwt = self.select_token(model)
246
- return f"sso-rw={jwt};sso={jwt}"
247
-
248
- def select_token(self, model: str) -> str:
249
- """选择最优Token(多进程安全)"""
250
- # 重新加载最新数据(多进程模式)
251
- self._reload_if_needed()
252
- def select_best(tokens: Dict[str, Any], field: str) -> Tuple[Optional[str], Optional[int]]:
253
- """选择最佳Token"""
254
- unused, used = [], []
255
-
256
- for key, data in tokens.items():
257
- # 跳过已失效的token
258
- if data.get("status") == "expired":
259
- continue
260
-
261
- # 跳过失败次数过多的token(任何错误状态码)
262
- if data.get("failedCount", 0) >= MAX_FAILURES:
263
- continue
264
-
265
- remaining = int(data.get(field, -1))
266
- if remaining == 0:
267
- continue
268
-
269
- if remaining == -1:
270
- unused.append(key)
271
- elif remaining > 0:
272
- used.append((key, remaining))
273
-
274
- if unused:
275
- return unused[0], -1
276
- if used:
277
- used.sort(key=lambda x: x[1], reverse=True)
278
- return used[0][0], used[0][1]
279
- return None, None
280
-
281
- # 快照
282
- snapshot = {
283
- TokenType.NORMAL.value: self.token_data[TokenType.NORMAL.value].copy(),
284
- TokenType.SUPER.value: self.token_data[TokenType.SUPER.value].copy()
285
- }
286
-
287
- # 选择策略
288
- if model == "grok-4-heavy":
289
- field = "heavyremainingQueries"
290
- token_key, remaining = select_best(snapshot[TokenType.SUPER.value], field)
291
- else:
292
- field = "remainingQueries"
293
- token_key, remaining = select_best(snapshot[TokenType.NORMAL.value], field)
294
- if token_key is None:
295
- token_key, remaining = select_best(snapshot[TokenType.SUPER.value], field)
296
-
297
- if token_key is None:
298
- raise GrokApiException(
299
- f"没有可用Token: {model}",
300
- "NO_AVAILABLE_TOKEN",
301
- {
302
- "model": model,
303
- "normal": len(snapshot[TokenType.NORMAL.value]),
304
- "super": len(snapshot[TokenType.SUPER.value])
305
- }
306
- )
307
-
308
- status = "未使用" if remaining == -1 else f"剩余{remaining}次"
309
- logger.debug(f"[Token] 分配Token: {model} ({status})")
310
- return token_key
311
-
312
- async def check_limits(self, auth_token: str, model: str) -> Optional[Dict[str, Any]]:
313
- """检查速率限制"""
314
- try:
315
- rate_model = Models.to_rate_limit(model)
316
- payload = {"requestKind": "DEFAULT", "modelName": rate_model}
317
-
318
- cf = setting.grok_config.get("cf_clearance", "")
319
- headers = get_dynamic_headers("/rest/rate-limits")
320
- headers["Cookie"] = f"{auth_token};{cf}" if cf else auth_token
321
-
322
- # 外层重试:可配置状态码(401/429等)
323
- retry_codes = setting.grok_config.get("retry_status_codes", [401, 429])
324
- MAX_OUTER_RETRY = 3
325
-
326
- for outer_retry in range(MAX_OUTER_RETRY + 1): # +1 确保实际重试3次
327
- # 内层重试:403代理池重试
328
- max_403_retries = 5
329
- retry_403_count = 0
330
-
331
- while retry_403_count <= max_403_retries:
332
- # 异步获取代理(支持代理池)
333
- from app.core.proxy_pool import proxy_pool
334
-
335
- # 如果是403重试且使用代理池,强制刷新代理
336
- if retry_403_count > 0 and proxy_pool._enabled:
337
- logger.info(f"[Token] 403重试 {retry_403_count}/{max_403_retries},刷新代理...")
338
- proxy = await proxy_pool.force_refresh()
339
- else:
340
- proxy = await setting.get_proxy_async("service")
341
-
342
- proxies = {"http": proxy, "https": proxy} if proxy else None
343
-
344
- async with AsyncSession() as session:
345
- response = await session.post(
346
- RATE_LIMIT_API,
347
- headers=headers,
348
- json=payload,
349
- impersonate=BROWSER,
350
- timeout=TIMEOUT,
351
- proxies=proxies
352
- )
353
-
354
- # 内层403重试:仅当有代理池时触发
355
- if response.status_code == 403 and proxy_pool._enabled:
356
- retry_403_count += 1
357
-
358
- if retry_403_count <= max_403_retries:
359
- logger.warning(f"[Token] 遇到403错误,正在重试 ({retry_403_count}/{max_403_retries})...")
360
- await asyncio.sleep(0.5)
361
- continue
362
-
363
- # 内层重试全部失败
364
- logger.error(f"[Token] 403错误,已重试{retry_403_count-1}次,放弃")
365
- sso = self._extract_sso(auth_token)
366
- if sso:
367
- await self.record_failure(auth_token, 403, "服务器被Block")
368
-
369
- # 检查可配置状态码错误 - 外层重试
370
- if response.status_code in retry_codes:
371
- if outer_retry < MAX_OUTER_RETRY:
372
- delay = (outer_retry + 1) * 0.1 # 渐进延迟:0.1s, 0.2s, 0.3s
373
- logger.warning(f"[Token] 遇到{response.status_code}错误,外层重试 ({outer_retry+1}/{MAX_OUTER_RETRY}),等待{delay}s...")
374
- await asyncio.sleep(delay)
375
- break # 跳出内层循环,进入外层重试
376
- else:
377
- logger.error(f"[Token] {response.status_code}错误,已重试{outer_retry}次,放弃")
378
- sso = self._extract_sso(auth_token)
379
- if sso:
380
- if response.status_code == 401:
381
- await self.record_failure(auth_token, 401, "Token失效")
382
- else:
383
- await self.record_failure(auth_token, response.status_code, f"错误: {response.status_code}")
384
- return None
385
-
386
- if response.status_code == 200:
387
- data = response.json()
388
- sso = self._extract_sso(auth_token)
389
-
390
- if outer_retry > 0 or retry_403_count > 0:
391
- logger.info(f"[Token] 重试成功!")
392
-
393
- if sso:
394
- if model == "grok-4-heavy":
395
- await self.update_limits(sso, normal=None, heavy=data.get("remainingQueries", -1))
396
- logger.info(f"[Token] 更新限制: {sso[:10]}..., heavy={data.get('remainingQueries', -1)}")
397
- else:
398
- await self.update_limits(sso, normal=data.get("remainingTokens", -1), heavy=None)
399
- logger.info(f"[Token] 更新限制: {sso[:10]}..., basic={data.get('remainingTokens', -1)}")
400
-
401
- return data
402
- else:
403
- # 其他错误
404
- logger.warning(f"[Token] 获取限制失败: {response.status_code}")
405
- sso = self._extract_sso(auth_token)
406
- if sso:
407
- await self.record_failure(auth_token, response.status_code, f"错误: {response.status_code}")
408
- return None
409
-
410
- except Exception as e:
411
- logger.error(f"[Token] 检查限制错误: {e}")
412
- return None
413
-
414
- async def update_limits(self, sso: str, normal: Optional[int] = None, heavy: Optional[int] = None) -> None:
415
- """更新限制"""
416
- try:
417
- for token_type in [TokenType.NORMAL.value, TokenType.SUPER.value]:
418
- if sso in self.token_data[token_type]:
419
- if normal is not None:
420
- self.token_data[token_type][sso]["remainingQueries"] = normal
421
- if heavy is not None:
422
- self.token_data[token_type][sso]["heavyremainingQueries"] = heavy
423
- self._mark_dirty() # 批量保存
424
- logger.info(f"[Token] 更新限制: {sso[:10]}...")
425
- return
426
- logger.warning(f"[Token] 未找到: {sso[:10]}...")
427
- except Exception as e:
428
- logger.error(f"[Token] 更新限制错误: {e}")
429
-
430
- async def record_failure(self, auth_token: str, status: int, msg: str) -> None:
431
- """记录失败"""
432
- try:
433
- if status == STATSIG_INVALID:
434
- logger.warning("[Token] IP被Block,请: 1.更换IP 2.使用代理 3.配置CF值")
435
- return
436
-
437
- sso = self._extract_sso(auth_token)
438
- if not sso:
439
- return
440
-
441
- _, data = self._find_token(sso)
442
- if not data:
443
- logger.warning(f"[Token] 未找到: {sso[:10]}...")
444
- return
445
-
446
- data["failedCount"] = data.get("failedCount", 0) + 1
447
- data["lastFailureTime"] = int(time.time() * 1000)
448
- data["lastFailureReason"] = f"{status}: {msg}"
449
-
450
- logger.warning(
451
- f"[Token] 失败: {sso[:10]}... (状态:{status}), "
452
- f"次数: {data['failedCount']}/{MAX_FAILURES}, 原因: {msg}"
453
- )
454
-
455
- if 400 <= status < 500 and data["failedCount"] >= MAX_FAILURES:
456
- data["status"] = "expired"
457
- logger.error(f"[Token] 标记失效: {sso[:10]}... (连续{status}错误{data['failedCount']}次)")
458
-
459
- self._mark_dirty() # 批量保存
460
-
461
- except Exception as e:
462
- logger.error(f"[Token] 记录失败错误: {e}")
463
-
464
- async def reset_failure(self, auth_token: str) -> None:
465
- """重置失败计数"""
466
- try:
467
- sso = self._extract_sso(auth_token)
468
- if not sso:
469
- return
470
-
471
- _, data = self._find_token(sso)
472
- if not data:
473
- return
474
-
475
- if data.get("failedCount", 0) > 0:
476
- data["failedCount"] = 0
477
- data["lastFailureTime"] = None
478
- data["lastFailureReason"] = None
479
- self._mark_dirty() # 批量保存
480
- logger.info(f"[Token] 重置失败计数: {sso[:10]}...")
481
-
482
- except Exception as e:
483
- logger.error(f"[Token] 重置失败错误: {e}")
484
-
485
-
486
- # 全局实例
487
- token_manager = GrokTokenManager()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/services/grok/upload.py DELETED
@@ -1,209 +0,0 @@
1
- """图片上传管理器 - 支持Base64和URL图片上传"""
2
-
3
- import asyncio
4
- import base64
5
- import re
6
- from typing import Tuple, Optional
7
- from urllib.parse import urlparse
8
- from curl_cffi.requests import AsyncSession
9
-
10
- from app.services.grok.statsig import get_dynamic_headers
11
- from app.core.exception import GrokApiException
12
- from app.core.config import setting
13
- from app.core.logger import logger
14
-
15
-
16
- # 常量
17
- UPLOAD_API = "https://grok.com/rest/app-chat/upload-file"
18
- TIMEOUT = 30
19
- BROWSER = "chrome133a"
20
-
21
- # MIME类型
22
- MIME_TYPES = {
23
- '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png',
24
- '.gif': 'image/gif', '.webp': 'image/webp', '.bmp': 'image/bmp',
25
- }
26
- DEFAULT_MIME = "image/jpeg"
27
- DEFAULT_EXT = "jpg"
28
-
29
-
30
- class ImageUploadManager:
31
- """图片上传管理器"""
32
-
33
- @staticmethod
34
- async def upload(image_input: str, auth_token: str) -> Tuple[str, str]:
35
- """上传图片(支持Base64或URL)
36
-
37
- Returns:
38
- (file_id, file_uri) 元组
39
- """
40
- try:
41
- # 判断类型并处理
42
- if ImageUploadManager._is_url(image_input):
43
- buffer, mime = await ImageUploadManager._download(image_input)
44
- filename, _ = ImageUploadManager._get_info("", mime)
45
- else:
46
- buffer = image_input.split(",")[1] if "data:image" in image_input else image_input
47
- filename, mime = ImageUploadManager._get_info(image_input)
48
-
49
- # 构建数据
50
- data = {
51
- "fileName": filename,
52
- "fileMimeType": mime,
53
- "content": buffer,
54
- }
55
-
56
-
57
- if not auth_token:
58
- raise GrokApiException("认证令牌缺失", "NO_AUTH_TOKEN")
59
-
60
- # 外层重试:可配置状态码(401/429等)
61
- retry_codes = setting.grok_config.get("retry_status_codes", [401, 429])
62
- MAX_OUTER_RETRY = 3
63
-
64
- for outer_retry in range(MAX_OUTER_RETRY + 1): # +1 确保实际重试3次
65
- try:
66
- # 内层重试:403代理池重试
67
- max_403_retries = 5
68
- retry_403_count = 0
69
-
70
- while retry_403_count <= max_403_retries:
71
- # 请求配置
72
- cf = setting.grok_config.get("cf_clearance", "")
73
- headers = {
74
- **get_dynamic_headers("/rest/app-chat/upload-file"),
75
- "Cookie": f"{auth_token};{cf}" if cf else auth_token,
76
- }
77
-
78
- # 异步获取代理(支持代理池)
79
- from app.core.proxy_pool import proxy_pool
80
-
81
- # 如果是403重试且使用代理池,强制刷新代理
82
- if retry_403_count > 0 and proxy_pool._enabled:
83
- logger.info(f"[Upload] 403重试 {retry_403_count}/{max_403_retries},刷新代理...")
84
- proxy = await proxy_pool.force_refresh()
85
- else:
86
- proxy = await setting.get_proxy_async("service")
87
-
88
- proxies = {"http": proxy, "https": proxy} if proxy else None
89
-
90
- # 上传
91
- async with AsyncSession() as session:
92
- response = await session.post(
93
- UPLOAD_API,
94
- headers=headers,
95
- json=data,
96
- impersonate=BROWSER,
97
- timeout=TIMEOUT,
98
- proxies=proxies,
99
- )
100
-
101
- # 内层403重试:仅当有代理池时触发
102
- if response.status_code == 403 and proxy_pool._enabled:
103
- retry_403_count += 1
104
-
105
- if retry_403_count <= max_403_retries:
106
- logger.warning(f"[Upload] 遇到403错误,正在重试 ({retry_403_count}/{max_403_retries})...")
107
- await asyncio.sleep(0.5)
108
- continue
109
-
110
- # 内层重试全部失败
111
- logger.error(f"[Upload] 403错误,已重试{retry_403_count-1}次,放弃")
112
-
113
- # 检查可配置状态码错误 - 外层重试
114
- if response.status_code in retry_codes:
115
- if outer_retry < MAX_OUTER_RETRY:
116
- delay = (outer_retry + 1) * 0.1 # 渐进延迟:0.1s, 0.2s, 0.3s
117
- logger.warning(f"[Upload] 遇到{response.status_code}错误,外层重试 ({outer_retry+1}/{MAX_OUTER_RETRY}),等待{delay}s...")
118
- await asyncio.sleep(delay)
119
- break # 跳出内层循环,进入外层重试
120
- else:
121
- logger.error(f"[Upload] {response.status_code}错误,已重试{outer_retry}次,放弃")
122
- return "", ""
123
-
124
- if response.status_code == 200:
125
- result = response.json()
126
- file_id = result.get("fileMetadataId", "")
127
- file_uri = result.get("fileUri", "")
128
-
129
- if outer_retry > 0 or retry_403_count > 0:
130
- logger.info(f"[Upload] 重试成功!")
131
-
132
- logger.debug(f"[Upload] 成功,ID: {file_id}")
133
- return file_id, file_uri
134
-
135
- # 其他错误直接返回
136
- logger.error(f"[Upload] 失败,状态码: {response._status_code}")
137
- return "", ""
138
-
139
- # 内层循环正常结束(非break),说明403重试全部失败
140
- return "", ""
141
-
142
- except Exception as e:
143
- if outer_retry < MAX_OUTER_RETRY - 1:
144
- logger.warning(f"[Upload] 异常: {e},外层重试 ({outer_retry+1}/{MAX_OUTER_RETRY})...")
145
- await asyncio.sleep(0.5)
146
- continue
147
-
148
- logger.warning(f"[Upload] 失败: {e}")
149
- return "", ""
150
-
151
- return "", ""
152
-
153
- except Exception as e:
154
- logger.warning(f"[Upload] 失败: {e}")
155
- return "", ""
156
-
157
- @staticmethod
158
- def _is_url(input_str: str) -> bool:
159
- """检查是否为URL"""
160
- try:
161
- result = urlparse(input_str)
162
- return all([result.scheme, result.netloc]) and result.scheme in ['http', 'https']
163
- except:
164
- return False
165
-
166
- @staticmethod
167
- async def _download(url: str) -> Tuple[str, str]:
168
- """下载图片并转Base64
169
-
170
- Returns:
171
- (base64_string, mime_type) 元组
172
- """
173
- try:
174
- async with AsyncSession() as session:
175
- response = await session.get(url, timeout=5)
176
- response.raise_for_status()
177
-
178
- content_type = response.headers.get('content-type', DEFAULT_MIME)
179
- if not content_type.startswith('image/'):
180
- content_type = DEFAULT_MIME
181
-
182
- b64 = base64.b64encode(response.content).decode()
183
- return b64, content_type
184
- except Exception as e:
185
- logger.warning(f"[Upload] 下载失败: {e}")
186
- return "", ""
187
-
188
- @staticmethod
189
- def _get_info(image_data: str, mime_type: Optional[str] = None) -> Tuple[str, str]:
190
- """获取文件名和MIME类型
191
-
192
- Returns:
193
- (file_name, mime_type) 元组
194
- """
195
- # 已提供MIME类型
196
- if mime_type:
197
- ext = mime_type.split("/")[1] if "/" in mime_type else DEFAULT_EXT
198
- return f"image.{ext}", mime_type
199
-
200
- # 从Base64提取
201
- mime = DEFAULT_MIME
202
- ext = DEFAULT_EXT
203
-
204
- if "data:image" in image_data:
205
- if match := re.search(r"data:([a-zA-Z0-9]+/[a-zA-Z0-9-.+]+);base64,", image_data):
206
- mime = match.group(1)
207
- ext = mime.split("/")[1]
208
-
209
- return f"image.{ext}", mime
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/services/mcp/__init__.py DELETED
@@ -1,6 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- """MCP模块初始化"""
3
-
4
- from app.services.mcp.server import mcp
5
-
6
- __all__ = ["mcp"]
 
 
 
 
 
 
 
app/services/mcp/server.py DELETED
@@ -1,63 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- """FastMCP服务器实例"""
3
-
4
- from fastmcp import FastMCP
5
- from fastmcp.server.auth.providers.jwt import StaticTokenVerifier
6
- from app.services.mcp.tools import ask_grok_impl
7
- from app.core.config import setting
8
-
9
-
10
- def create_mcp_server() -> FastMCP:
11
- """创建MCP服务器实例,如果配置了API密钥则启用认证"""
12
- # 检查是否配置了API密钥
13
- api_key = setting.grok_config.get("api_key")
14
-
15
- # 如果配置了API密钥,则启用静态token验证
16
- auth = None
17
- if api_key:
18
- auth = StaticTokenVerifier(
19
- tokens={
20
- api_key: {
21
- "client_id": "grok2api-client",
22
- "scopes": ["read", "write", "admin"]
23
- }
24
- },
25
- required_scopes=["read"]
26
- )
27
-
28
- # 创建FastMCP实例
29
- return FastMCP(
30
- name="Grok2API-MCP",
31
- instructions="MCP server providing Grok AI chat capabilities. Use ask_grok tool to interact with Grok AI models.",
32
- auth=auth
33
- )
34
-
35
-
36
- # 创建全局MCP实例
37
- mcp = create_mcp_server()
38
-
39
-
40
- # 注册ask_grok工具
41
- @mcp.tool
42
- async def ask_grok(
43
- query: str,
44
- model: str = "grok-3-fast",
45
- system_prompt: str = None
46
- ) -> str:
47
- """
48
- 调用Grok AI进行对话,尤其适用于当用户询问最新信息,需要调用搜索功能,或是想了解社交平台动态(如Twitter(X)、Reddit等)时。
49
-
50
- Args:
51
- query: 用户的问题或指令
52
- model: Grok模型名称,可选值: grok-3-fast(默认), grok-4-fast, grok-4-fast-expert, grok-4-expert, grok-4-heavy
53
- system_prompt: 可选的系统提示词,用于设定AI的角色或行为约束
54
-
55
- Returns:
56
- Grok AI的完整回复内容,可能包括文本和图片链接(Markdown格式)
57
-
58
- Examples:
59
- - 简单问答: ask_grok("什么是Python?")
60
- - 指定模型: ask_grok("解释量子计算", model="grok-4-fast")
61
- - 带系统提示: ask_grok("写一首诗", system_prompt="你是一位古典诗人")
62
- """
63
- return await ask_grok_impl(query, model, system_prompt)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/services/mcp/tools.py DELETED
@@ -1,77 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- """MCP Tools - Grok AI 对话工具"""
3
-
4
- import json
5
- from typing import Optional
6
- from app.services.grok.client import GrokClient
7
- from app.core.logger import logger
8
- from app.core.exception import GrokApiException
9
-
10
-
11
- async def ask_grok_impl(
12
- query: str,
13
- model: str = "grok-3-fast",
14
- system_prompt: Optional[str] = None
15
- ) -> str:
16
- """
17
- 内部实现: 调用Grok API并收集完整响应
18
-
19
- Args:
20
- query: 用户问题
21
- model: 模型名称
22
- system_prompt: 系统提示词
23
-
24
- Returns:
25
- str: 完整的Grok响应内容
26
- """
27
- try:
28
- # 构建消息列表
29
- messages = []
30
- if system_prompt:
31
- messages.append({"role": "system", "content": system_prompt})
32
- messages.append({"role": "user", "content": query})
33
-
34
- # 构建请求
35
- request_data = {
36
- "model": model,
37
- "messages": messages,
38
- "stream": True
39
- }
40
-
41
- logger.info(f"[MCP] ask_grok 调用, 模型: {model}")
42
-
43
- # 调用Grok客户端(流式)
44
- response_iterator = await GrokClient.openai_to_grok(request_data)
45
-
46
- # 收集所有流式响应块
47
- content_parts = []
48
- async for chunk in response_iterator:
49
- if isinstance(chunk, bytes):
50
- chunk = chunk.decode('utf-8')
51
-
52
- # 解析SSE格式
53
- if chunk.startswith("data: "):
54
- data_str = chunk[6:].strip()
55
- if data_str == "[DONE]":
56
- break
57
-
58
- try:
59
- data = json.loads(data_str)
60
- choices = data.get("choices", [])
61
- if choices:
62
- delta = choices[0].get("delta", {})
63
- if content := delta.get("content"):
64
- content_parts.append(content)
65
- except json.JSONDecodeError:
66
- continue
67
-
68
- result = "".join(content_parts)
69
- logger.info(f"[MCP] ask_grok 完成, 响应长度: {len(result)}")
70
- return result
71
-
72
- except GrokApiException as e:
73
- logger.error(f"[MCP] Grok API错误: {str(e)}")
74
- raise Exception(f"Grok API调用失败: {str(e)}")
75
- except Exception as e:
76
- logger.error(f"[MCP] ask_grok异常: {str(e)}", exc_info=True)
77
- raise Exception(f"处理请求时出错: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/template/admin.html DELETED
@@ -1,887 +0,0 @@
1
- <!DOCTYPE html>
2
- <html lang="zh-CN" class="h-full">
3
-
4
- <head>
5
- <meta charset="UTF-8">
6
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
7
- <title>管理控制台 - Grok2API</title>
8
- <link rel="icon" type="image/png" href="/static/favicon.png">
9
- <script src="https://cdn.tailwindcss.com"></script>
10
- <style>
11
- @keyframes slide-up {
12
- from {
13
- transform: translateY(100%);
14
- opacity: 0
15
- }
16
-
17
- to {
18
- transform: translateY(0);
19
- opacity: 1
20
- }
21
- }
22
-
23
- .animate-slide-up {
24
- animation: slide-up .3s ease-out
25
- }
26
-
27
- .tab-btn {
28
- transition: all .2s ease
29
- }
30
-
31
- .hover-card {
32
- position: relative;
33
- display: inline-block
34
- }
35
-
36
- .hover-card-trigger {
37
- cursor: pointer
38
- }
39
-
40
- .hover-card-content {
41
- position: absolute;
42
- left: 50%;
43
- transform: translateX(-50%);
44
- background: hsl(0 0% 3.9%);
45
- color: hsl(0 0% 98%);
46
- padding: 8px 12px;
47
- border-radius: 6px;
48
- font-size: 12px;
49
- font-weight: 500;
50
- white-space: nowrap;
51
- z-index: 9999;
52
- pointer-events: none;
53
- opacity: 0;
54
- visibility: hidden;
55
- transition: opacity .2s ease, transform .2s ease;
56
- box-shadow: 0 4px 12px rgba(0, 0, 0, .25);
57
- border: 1px solid hsl(0 0% 14.9%)
58
- }
59
-
60
- .hover-card:hover .hover-card-content {
61
- opacity: 1;
62
- visibility: visible
63
- }
64
-
65
- .hover-card-content.top {
66
- bottom: 100%;
67
- transform: translateX(-50%) translateY(-8px)
68
- }
69
-
70
- .hover-card-content.bottom {
71
- top: 100%;
72
- transform: translateX(-50%) translateY(8px)
73
- }
74
-
75
- .hover-card-content::after {
76
- content: '';
77
- position: absolute;
78
- left: 50%;
79
- transform: translateX(-50%);
80
- border: 6px solid transparent;
81
- z-index: 1000
82
- }
83
-
84
- .hover-card-content.top::after {
85
- top: 100%;
86
- border-top-color: hsl(0 0% 3.9%)
87
- }
88
-
89
- .hover-card-content.bottom::after {
90
- bottom: 100%;
91
- border-bottom-color: hsl(0 0% 3.9%)
92
- }
93
-
94
- .hover-card-trigger:hover+.hover-card-content {
95
- opacity: 1;
96
- visibility: visible
97
- }
98
-
99
- .btn-icon {
100
- display: inline-flex;
101
- align-items: center;
102
- justify-content: center;
103
- border-radius: 0.375rem;
104
- transition: color .2s, background-color .2s;
105
- height: 2rem;
106
- width: 2rem
107
- }
108
-
109
- .btn-icon:focus-visible {
110
- outline: 2px solid transparent;
111
- outline-offset: 2px;
112
- box-shadow: 0 0 0 1px hsl(0 0% 3.9%)
113
- }
114
-
115
- .btn-icon:hover {
116
- background-color: hsl(0 0% 96.1%);
117
- color: hsl(0 0% 9%)
118
- }
119
-
120
- .sticky-right {
121
- position: sticky;
122
- right: 0;
123
- background-color: hsl(0 0% 100%);
124
- z-index: 10;
125
- border-left: 1px solid hsl(0 0% 89%)
126
- }
127
-
128
- .cfg-label {
129
- font-size: 0.875rem;
130
- font-weight: 500;
131
- color: hsl(0 0% 45.1%);
132
- margin-bottom: 0.5rem;
133
- display: flex;
134
- align-items: center;
135
- gap: 0.25rem
136
- }
137
-
138
- .cfg-input {
139
- display: flex;
140
- height: 2.25rem;
141
- width: 100%;
142
- border-radius: 0.375rem;
143
- border: 1px solid hsl(0 0% 89%);
144
- background-color: hsl(0 0% 100%);
145
- padding: 0.5rem 0.75rem;
146
- font-size: 0.875rem
147
- }
148
-
149
- .help-icon {
150
- display: inline-flex;
151
- align-items: center;
152
- justify-content: center;
153
- width: 0.875rem;
154
- height: 0.875rem;
155
- border-radius: 9999px;
156
- border: 1px solid hsl(0 0% 45.1%);
157
- color: hsl(0 0% 45.1%);
158
- cursor: help;
159
- font-size: 10px;
160
- line-height: 1
161
- }
162
-
163
- [title] {
164
- position: relative
165
- }
166
-
167
- [title]:hover::after {
168
- content: attr(title);
169
- position: absolute;
170
- bottom: 100%;
171
- left: 50%;
172
- transform: translateX(-50%) translateY(-8px);
173
- background: hsl(0 0% 11%);
174
- color: hsl(0 0% 98%);
175
- padding: 8px 12px;
176
- border-radius: 6px;
177
- font-size: 12px;
178
- font-weight: 500;
179
- line-height: 1.4;
180
- white-space: pre-line;
181
- max-width: 350px;
182
- width: max-content;
183
- word-wrap: break-word;
184
- z-index: 1000;
185
- pointer-events: none;
186
- box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15), 0 2px 8px rgba(0, 0, 0, 0.1);
187
- opacity: 0;
188
- visibility: hidden;
189
- transition: all 0.2s ease;
190
- animation: tooltipFadeIn 0.2s ease forwards
191
- }
192
-
193
- [title]:hover::before {
194
- content: '';
195
- position: absolute;
196
- bottom: 100%;
197
- left: 50%;
198
- transform: translateX(-50%) translateY(-4px);
199
- border: 6px solid transparent;
200
- border-top-color: hsl(0 0% 11%);
201
- z-index: 1000;
202
- opacity: 0;
203
- visibility: hidden;
204
- transition: opacity 0.2s ease, visibility 0.2s ease
205
- }
206
-
207
- [title]:hover::after,
208
- [title]:hover::before {
209
- opacity: 1;
210
- visibility: visible
211
- }
212
-
213
- @keyframes tooltipFadeIn {
214
- from {
215
- opacity: 0;
216
- transform: translateX(-50%) translateY(-4px)
217
- }
218
-
219
- to {
220
- opacity: 1;
221
- transform: translateX(-50%) translateY(-8px)
222
- }
223
- }
224
- </style>
225
- <script>
226
- tailwind.config = { theme: { extend: { colors: { border: "hsl(0 0% 89%)", input: "hsl(0 0% 89%)", ring: "hsl(0 0% 3.9%)", background: "hsl(0 0% 100%)", foreground: "hsl(0 0% 3.9%)", primary: { DEFAULT: "hsl(0 0% 9%)", foreground: "hsl(0 0% 98%)" }, secondary: { DEFAULT: "hsl(0 0% 96.1%)", foreground: "hsl(0 0% 9%)" }, muted: { DEFAULT: "hsl(0 0% 96.1%)", foreground: "hsl(0 0% 45.1%)" }, accent: { DEFAULT: "hsl(0 0% 96.1%)", foreground: "hsl(0 0% 9%)" }, destructive: { DEFAULT: "hsl(0 84.2% 60.2%)", foreground: "hsl(0 0% 98%)" } } } } }
227
- </script>
228
- </head>
229
-
230
- <body class="h-full bg-background text-foreground antialiased">
231
- <!-- 导航栏 -->
232
- <header
233
- class="sticky top-0 z-50 w-full border-b border-border/40 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
234
- <div class="mx-auto flex h-14 max-w-7xl items-center px-6">
235
- <div class="mr-4 flex items-baseline gap-3">
236
- <span class="font-bold text-xl">Grok2API</span>
237
- <span class="text-xs text-gray-400">by @Chenyme</span>
238
- </div>
239
- <div class="flex flex-1 items-center justify-end">
240
- <div class="flex items-center gap-2">
241
- <div class="hover-card">
242
- <span id="storageMode"
243
- class="hover-card-trigger inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium bg-muted text-muted-foreground border">
244
- <svg class="h-3 w-3 mr-1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
245
- stroke="currentColor" stroke-width="2">
246
- <ellipse cx="12" cy="5" rx="9" ry="3" />
247
- <path d="m21 12c0 1.66-4 3-9 3s-9-1.34-9-3" />
248
- <path d="m3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5" />
249
- </svg>
250
- <span id="storageModeText">FILE</span>
251
- </span>
252
- <div id="storageModeTooltip" class="hover-card-content top">
253
- 加载中...
254
- </div>
255
- </div>
256
- <nav class="flex items-center gap-1">
257
- <a href="https://github.com/chenyme/grok2api/issues" target="_blank"
258
- class="inline-flex items-center justify-center text-xs transition-colors hover:bg-accent hover:text-accent-foreground h-7 px-2.5 gap-1">
259
- <svg class="h-3.5 w-3.5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
260
- stroke="currentColor" stroke-width="2">
261
- <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
262
- </svg>
263
- 反馈
264
- </a>
265
- <button onclick="logout()"
266
- class="inline-flex items-center justify-center text-xs transition-colors hover:bg-accent hover:text-accent-foreground h-7 px-2.5 gap-1">
267
- <svg class="h-3.5 w-3.5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
268
- stroke="currentColor" stroke-width="2">
269
- <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
270
- <polyline points="16 17 21 12 16 7" />
271
- <line x1="21" y1="12" x2="9" y2="12" />
272
- </svg>
273
- 退出
274
- </button>
275
- </nav>
276
- </div>
277
- </div>
278
- </header>
279
-
280
- <main class="mx-auto max-w-7xl px-6 py-6">
281
- <!-- Tab 导航 -->
282
- <div class="border-b border-border mb-6">
283
- <nav class="flex space-x-8">
284
- <button onclick="switchTab('tokens')" id="tabTokens"
285
- class="tab-btn border-b-2 border-primary text-sm font-medium py-3 px-1">Token 管理</button>
286
- <button onclick="switchTab('settings')" id="tabSettings"
287
- class="tab-btn border-b-2 border-transparent text-sm font-medium py-3 px-1">Setting 配置</button>
288
- </nav>
289
- </div>
290
-
291
- <!-- Token 管理面板 -->
292
- <div id="panelTokens">
293
- <!-- 统计卡片 -->
294
- <div class="grid gap-4 grid-cols-2 md:grid-cols-4 mb-6">
295
- <div class="rounded-lg border border-border bg-background p-4">
296
- <p class="text-sm font-medium text-muted-foreground mb-2">Token 总数</p>
297
- <h3 class="text-xl font-bold" id="statTotal">-</h3>
298
- </div>
299
-
300
- <div class="rounded-lg border border-border bg-background p-4">
301
- <p class="text-sm font-medium text-muted-foreground mb-2">Token 正常</p>
302
- <h3 class="text-xl font-bold text-green-600" id="statActive">-</h3>
303
- </div>
304
-
305
- <div class="rounded-lg border border-border bg-background p-4">
306
- <p class="text-sm font-medium text-muted-foreground mb-2">Token 未使用</p>
307
- <h3 class="text-xl font-bold text-gray-500" id="statUnused">-</h3>
308
- </div>
309
-
310
- <div class="rounded-lg border border-border bg-background p-4">
311
- <p class="text-sm font-medium text-muted-foreground mb-2">Token 限流中</p>
312
- <h3 class="text-xl font-bold text-orange-600" id="statLimited">-</h3>
313
- </div>
314
-
315
- <div class="rounded-lg border border-border bg-background p-4">
316
- <p class="text-sm font-medium text-muted-foreground mb-2">Token 失效</p>
317
- <h3 class="text-xl font-bold text-destructive" id="statExpired">-</h3>
318
- </div>
319
-
320
- <div class="rounded-lg border border-border bg-background p-4">
321
- <p class="text-sm font-medium text-muted-foreground mb-2">Chat 总剩余</p>
322
- <h3 class="text-xl font-bold" id="statChatRemaining">-</h3>
323
- </div>
324
-
325
- <div class="rounded-lg border border-border bg-background p-4">
326
- <p class="text-sm font-medium text-muted-foreground mb-2">Image 总剩余</p>
327
- <h3 class="text-xl font-bold text-blue-600" id="statImageRemaining">-</h3>
328
- </div>
329
-
330
- <div class="rounded-lg border border-border bg-background p-4">
331
- <p class="text-sm font-medium text-muted-foreground mb-2">Video 总剩余</p>
332
- <h3 class="text-xl font-bold text-purple-600" id="statVideoRemaining">无法统计</h3>
333
- </div>
334
- </div>
335
-
336
- <!-- Token 列表 -->
337
- <div class="rounded-lg border border-border bg-background">
338
- <!-- 工具栏 -->
339
- <div class="flex items-center justify-between gap-4 p-4 border-b border-border">
340
- <div class="flex items-center gap-3 flex-1">
341
- <div class="flex items-center gap-2">
342
- <select id="filterType" onchange="filterTokens()"
343
- class="h-8 px-1 text-sm rounded-md bg-background focus:outline-none focus:ring-1 focus:ring-ring w-[90px]">
344
- <option value="all">全部类型</option>
345
- <option value="sso">SSO</option>
346
- <option value="ssoSuper">SuperSSO</option>
347
- </select>
348
- <select id="filterStatus" onchange="filterTokens()"
349
- class="h-8 px-1 text-sm rounded-md bg-background focus:outline-none focus:ring-1 focus:ring-ring w-[90px]">
350
- <option value="all">全部状态</option>
351
- <option value="未使用">未使用</option>
352
- <option value="限流中">限流中</option>
353
- <option value="失效">失效</option>
354
- <option value="正常">正常</option>
355
- </select>
356
- <select id="filterTag" onchange="filterTokens()"
357
- class="h-8 px-1 text-sm rounded-md bg-background focus:outline-none focus:ring-1 focus:ring-ring w-[90px]">
358
- <option value="all">全部标签</option>
359
- </select>
360
- </div>
361
- </div>
362
-
363
- <div class="flex items-center gap-2">
364
- <button onclick="refreshTokens()" class="btn-icon" title="刷新列表">
365
- <svg class="h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
366
- stroke="currentColor" stroke-width="2">
367
- <polyline points="23 4 23 10 17 10" />
368
- <polyline points="1 20 1 14 7 14" />
369
- <path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15" />
370
- </svg>
371
- </button>
372
- <div id="batchActions" class="hidden items-center gap-2">
373
- <button onclick="exportSelected()" class="btn-icon" title="导出选中项">
374
- <svg class="h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
375
- stroke="currentColor" stroke-width="2">
376
- <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
377
- <polyline points="7 10 12 15 17 10" />
378
- <line x1="12" y1="15" x2="12" y2="3" />
379
- </svg>
380
- </button>
381
- <button onclick="batchDelete()" class="btn-icon hover:bg-destructive/10 hover:text-destructive"
382
- title="批量删除">
383
- <svg class="h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
384
- stroke="currentColor" stroke-width="2">
385
- <polyline points="3 6 5 6 21 6" />
386
- <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
387
- <line x1="10" y1="11" x2="10" y2="17" />
388
- <line x1="14" y1="11" x2="14" y2="17" />
389
- </svg>
390
- </button>
391
- </div>
392
- <button onclick="openAddModal()"
393
- class="inline-flex items-center justify-center rounded-md transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring bg-primary text-primary-foreground hover:bg-primary/90 h-8 px-3"
394
- title="添加 Token">
395
- <svg class="h-4 w-4 mr-2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
396
- stroke="currentColor" stroke-width="2">
397
- <line x1="12" y1="5" x2="12" y2="19" />
398
- <line x1="5" y1="12" x2="19" y2="12" />
399
- </svg>
400
- <span class="text-sm font-medium">新增</span>
401
- </button>
402
- </div>
403
- </div>
404
-
405
- <!-- 表格 -->
406
- <div class="relative w-full overflow-auto">
407
- <table class="w-full text-sm table-fixed">
408
- <thead>
409
- <tr class="border-b border-border">
410
- <th class="h-10 px-3 text-left align-middle font-medium w-12">
411
- <input type="checkbox" id="selectAll" onchange="toggleSelectAll()"
412
- class="h-3.5 w-3.5 rounded border border-input focus:ring-1 focus:ring-ring">
413
- </th>
414
- <th class="h-10 px-3 text-left align-middle text-sm font-medium text-muted-foreground w-72">Token</th>
415
- <th class="h-10 px-3 text-left align-middle text-sm font-medium text-muted-foreground w-20">类型</th>
416
- <th class="h-10 px-3 text-left align-middle text-sm font-medium text-muted-foreground w-20">状态</th>
417
- <th class="h-10 px-3 text-left align-middle text-sm font-medium text-muted-foreground w-20">普通</th>
418
- <th class="h-10 px-3 text-left align-middle text-sm font-medium text-muted-foreground w-20">高级</th>
419
- <th class="h-10 px-3 text-left align-middle text-sm font-medium text-muted-foreground w-32">标签</th>
420
- <th class="h-10 px-3 text-left align-middle text-sm font-medium text-muted-foreground w-40">备注</th>
421
- <th class="h-10 px-3 text-left align-middle text-sm font-medium text-muted-foreground w-32">创建时间</th>
422
- <th
423
- class="h-10 px-3 text-center align-middle text-sm font-medium text-muted-foreground w-28 sticky-right">
424
- 操作</th>
425
- </tr>
426
- </thead>
427
- <tbody id="tokenTableBody" class="divide-y divide-border">
428
- <!-- 动态填充 -->
429
- </tbody>
430
- </table>
431
- </div>
432
-
433
- <div id="emptyState" class="hidden flex flex-col items-center justify-center py-12">
434
- <svg class="h-10 w-10 text-muted-foreground/50 mb-3" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"
435
- fill="none" stroke="currentColor" stroke-width="2">
436
- <rect x="3" y="3" width="18" height="18" rx="2" />
437
- <path d="M9 9h6v6H9z" />
438
- </svg>
439
- <p class="text-sm text-muted-foreground">暂无数据</p>
440
- </div>
441
- </div>
442
- </div>
443
-
444
- <!-- 全局设置面板 -->
445
- <div id="panelSettings" class="hidden">
446
- <!-- 全局配置区域 -->
447
- <div class="mb-8">
448
- <div class="flex items-center justify-between mb-6">
449
- <h2 class="text-xl font-bold">全局配置</h2>
450
- <button onclick="saveGlobalSettings()"
451
- class="inline-flex items-center justify-center rounded-md text-sm font-medium bg-secondary text-secondary-foreground hover:bg-black hover:text-white h-9 px-4 transition-colors">保存配置</button>
452
- </div>
453
- <div class="grid gap-4 lg:grid-cols-3">
454
- <!-- 系统设置 -->
455
- <div class="rounded-lg border border-border bg-background p-6">
456
- <h3 class="text-sm font-semibold mb-4">系统设置</h3>
457
- <div class="space-y-4">
458
- <div>
459
- <label class="cfg-label">登陆账户<span class="help-icon" title="登录管理后台的用户名">?</span></label>
460
- <input id="cfgAdminUser" class="cfg-input" placeholder="admin">
461
- </div>
462
- <div>
463
- <label class="cfg-label">登陆密码<span class="help-icon" title="登录管理后台的密码,留空表示不修改当前密码">?</span></label>
464
- <input id="cfgAdminPass" type="password" class="cfg-input" placeholder="留空则不修改">
465
- </div>
466
- <div>
467
- <label class="cfg-label">日志级别<span class="help-icon"
468
- title="日志详细程度。DEBUG:最详细 | INFO:一般信息 | WARNING:警告 | ERROR:仅错误">?</span></label>
469
- <select id="cfgLogLevel" class="cfg-input">
470
- <option>DEBUG</option>
471
- <option>INFO</option>
472
- <option>WARNING</option>
473
- <option>ERROR</option>
474
- </select>
475
- </div>
476
- </div>
477
- </div>
478
-
479
- <!-- 媒体设置 -->
480
- <div class="rounded-lg border border-border bg-background p-6">
481
- <h3 class="text-sm font-semibold mb-4">媒体设置</h3>
482
- <div class="space-y-4">
483
- <div>
484
- <label class="cfg-label">
485
- 图片模式
486
- <span class="help-icon" title="返回图片的方式。URL:图片链接,支持图片缓存 | Base64:base64编码,不支持缓存">?</span>
487
- </label>
488
- <select id="cfgImageMode" class="cfg-input">
489
- <option value="url">URL链接</option>
490
- <option value="base64">Base64</option>
491
- </select>
492
- </div>
493
- <div>
494
- <label class="cfg-label">
495
- 服务网址
496
- <span class="help-icon" title="服务器的公网访问地址,用于构建图片URL链接(仅在图片模式为URL时需要)">?</span>
497
- </label>
498
- <input id="cfgBaseUrl" class="cfg-input" placeholder="http://localhost:8000">
499
- </div>
500
- <div class="grid grid-cols-2 gap-3">
501
- <div>
502
- <label class="cfg-label">
503
- 图片缓存 (MB)
504
- <span class="help-icon" title="图片缓存的最大容量(MB),超过后会自动清理旧缓存">?</span>
505
- </label>
506
- <input id="cfgImageCacheMaxSize" type="number" class="cfg-input" placeholder="500">
507
- </div>
508
- <div>
509
- <label class="cfg-label">
510
- 视频缓存 (MB)
511
- <span class="help-icon" title="视频缓存的最大容量(MB),超过后会自动清理旧缓存">?</span>
512
- </label>
513
- <input id="cfgVideoCacheMaxSize" type="number" class="cfg-input" placeholder="1000">
514
- </div>
515
- </div>
516
- </div>
517
- </div>
518
-
519
- <!-- 缓存管理 -->
520
- <div class="rounded-lg border border-border bg-background p-6">
521
- <h3 class="text-sm font-semibold mb-4">缓存管理</h3>
522
- <div class="space-y-4">
523
- <div>
524
- <label class="text-sm font-medium text-muted-foreground mb-2 block">图片缓存</label>
525
- <div class="flex gap-2">
526
- <input id="imageCacheSize" readonly
527
- class="flex h-9 flex-1 rounded-md border border-input bg-muted px-3 py-2 text-sm"
528
- placeholder="0 MB">
529
- <button onclick="clearImageCache()"
530
- class="inline-flex items-center justify-center rounded-md text-sm font-medium bg-secondary text-secondary-foreground hover:bg-red-600 hover:text-white h-9 w-9 p-0 transition-colors">
531
- <svg class="h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
532
- stroke="currentColor" stroke-width="2">
533
- <path
534
- d="M3 6h18M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2M10 11v6M14 11v6" />
535
- </svg>
536
- </button>
537
- </div>
538
- </div>
539
- <div>
540
- <label class="text-sm font-medium text-muted-foreground mb-2 block">视频缓存</label>
541
- <div class="flex gap-2">
542
- <input id="videoCacheSize" readonly
543
- class="flex h-9 flex-1 rounded-md border border-input bg-muted px-3 py-2 text-sm"
544
- placeholder="0 MB">
545
- <button onclick="clearVideoCache()"
546
- class="inline-flex items-center justify-center rounded-md text-sm font-medium bg-secondary text-secondary-foreground hover:bg-red-600 hover:text-white h-9 w-9 p-0 transition-colors">
547
- <svg class="h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
548
- stroke="currentColor" stroke-width="2">
549
- <path
550
- d="M3 6h18M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2M10 11v6M14 11v6" />
551
- </svg>
552
- </button>
553
- </div>
554
- </div>
555
- <div>
556
- <label class="text-sm font-medium text-muted-foreground mb-2 block">所有缓存</label>
557
- <div class="flex gap-2">
558
- <input id="totalCacheSize" readonly
559
- class="flex h-9 flex-1 rounded-md border border-input bg-muted px-3 py-2 text-sm font-medium"
560
- placeholder="0 MB">
561
- <button onclick="clearCache()"
562
- class="inline-flex items-center justify-center rounded-md text-sm font-medium bg-secondary text-secondary-foreground hover:bg-red-600 hover:text-white h-9 w-9 p-0 transition-colors">
563
- <svg class="h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
564
- stroke="currentColor" stroke-width="2">
565
- <path
566
- d="M3 6h18M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2M10 11v6M14 11v6" />
567
- </svg>
568
- </button>
569
- </div>
570
- </div>
571
- </div>
572
- </div>
573
- </div>
574
- </div>
575
-
576
- <!-- Grok 配置区域 -->
577
- <div>
578
- <div class="flex items-center justify-between mb-6">
579
- <h2 class="text-xl font-bold">Grok 配置</h2>
580
- <button onclick="saveGrokSettings()"
581
- class="inline-flex items-center justify-center rounded-md text-sm font-medium bg-secondary text-secondary-foreground hover:bg-black hover:text-white h-9 px-4 transition-colors">保存配置</button>
582
- </div>
583
- <div class="grid gap-4 lg:grid-cols-3">
584
- <!-- 基础设置 -->
585
- <div class="rounded-lg border border-border bg-background p-6">
586
- <h3 class="text-sm font-semibold mb-4">基础设置</h3>
587
- <div class="space-y-4">
588
- <div>
589
- <label class="cfg-label">
590
- API Key
591
- <span class="help-icon" title="接口调用的身份验证密钥,用于保护API访问安全">?</span>
592
- </label>
593
- <input id="cfgApiKey" class="cfg-input" placeholder="">
594
- </div>
595
- <div>
596
- <label class="cfg-label">
597
- X Statsig ID
598
- <span class="help-icon" title="Statsig统计ID,用于功能实验和统计分析">?</span>
599
- </label>
600
- <div class="flex items-center gap-3">
601
- <input id="cfgStatsigId"
602
- class="flex h-9 flex-1 rounded-md border border-input bg-background px-3 py-2 text-sm"
603
- placeholder="">
604
- <label class="inline-flex items-center gap-2 cursor-pointer" title="开启后每次请求自动生成新的 x-statsig-id">
605
- <span class="text-xs text-muted-foreground whitespace-nowrap">动态</span>
606
- <div class="relative">
607
- <input type="checkbox" id="cfgDynamicStatsig" class="sr-only peer">
608
- <div
609
- class="w-9 h-5 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-ring rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-primary">
610
- </div>
611
- </div>
612
- </label>
613
- </div>
614
- </div>
615
- <div>
616
- <label class="cfg-label">
617
- 过滤标签
618
- <span class="help-icon" title="需要过滤的响应标签,多个标签用逗号分隔。如:xaiartifact,xai:tool_usage_card">?</span>
619
- </label>
620
- <input id="cfgFilteredTags" class="cfg-input" placeholder="xaiartifact,xai:tool_usage_card">
621
- </div>
622
- <div>
623
- <label class="cfg-label">
624
- 显示思考
625
- <span class="help-icon" title="开启后会显示模型的思考过程(&lt;think&gt;标签内容);关闭后仅返回最终结果">?</span>
626
- </label>
627
- <select id="cfgShowThinking" class="cfg-input">
628
- <option value="true">开启</option>
629
- <option value="false">关闭</option>
630
- </select>
631
- </div>
632
- <div>
633
- <label class="cfg-label">
634
- 临时会话
635
- <span class="help-icon" title="开启后每次对话都创建新会话,不保留历史;关闭后可以继续之前的对话">?</span>
636
- </label>
637
- <select id="cfgTemporary" class="cfg-input">
638
- <option value="false">关闭</option>
639
- <option value="true">开启</option>
640
- </select>
641
- </div>
642
- </div>
643
- </div>
644
-
645
- <!-- 代理设置 -->
646
- <div class="rounded-lg border border-border bg-background p-6">
647
- <h3 class="text-sm font-semibold mb-4">代理设置</h3>
648
- <div class="space-y-4">
649
- <div>
650
- <label class="cfg-label">
651
- CF Clearance
652
- <span class="help-icon"
653
- title="Cloudflare验证cookie的值部分,用于绕过Cloudflare人机验证。只需输入cf_clearance=后面的值。">?</span>
654
- </label>
655
- <input id="cfgCfClearance" class="cfg-input" placeholder="">
656
- </div>
657
- <div>
658
- <label class="cfg-label">
659
- Proxy Url (服务代理)
660
- <span class="help-icon"
661
- title="API请求和上传使用的代理。支持 http、https、socks5。格式:socks5://user:pass@host:port">?</span>
662
- </label>
663
- <input id="cfgProxyUrl" class="cfg-input" placeholder="socks5://username:password@127.0.0.1:7890">
664
- </div>
665
- <div>
666
- <label class="cfg-label">
667
- Proxy Pool URL (代理池API)
668
- <span class="help-icon"
669
- title="代理池API地址,返回单个代理URL。留空则使用上方的固定代理。&#10;&#10;返回格式:纯文本,单行代理地址&#10;示例返回:socks5h://1.2.3.4:1080&#10;支持协议:http://, https://, socks5://, socks5h://&#10;API示例:http://your-api.com/get">?</span>
670
- </label>
671
- <input id="cfgProxyPoolUrl" class="cfg-input" placeholder="http://your-proxy-api.com/get">
672
- </div>
673
- <div>
674
- <label class="cfg-label">
675
- Proxy Pool Interval (刷新间隔秒)
676
- <span class="help-icon" title="代理池自动刷新间隔,单位秒。建议300-600秒(5-10分钟)">?</span>
677
- </label>
678
- <input id="cfgProxyPoolInterval" type="number" class="cfg-input" placeholder="300">
679
- </div>
680
- <div>
681
- <label class="cfg-label">
682
- Cache Proxy Url (缓存代理)
683
- <span class="help-icon" title="图片/视频缓存下载专用代理,不设置则使用服务代理。Grok的图片/视频获取接口对IP风控要求不高,可使用便宜的大流量节点">?</span>
684
- </label>
685
- <input id="cfgCacheProxyUrl" class="cfg-input" placeholder="socks5://username:password@127.0.0.1:7890">
686
- </div>
687
- </div>
688
- </div>
689
-
690
- <!-- 超时设置 -->
691
- <div class="rounded-lg border border-border bg-background p-6">
692
- <h3 class="text-sm font-semibold mb-4">超时设置</h3>
693
- <div class="space-y-4">
694
- <div>
695
- <label class="cfg-label">
696
- 首次响应超时 (秒)
697
- <span class="help-icon" title="等待API首次返回数据的最大时间(秒)。超时后会报错,建议30-60秒">?</span>
698
- </label>
699
- <input id="cfgStreamFirstResponseTimeout" type="number" class="cfg-input" placeholder="30">
700
- </div>
701
- <div>
702
- <label class="cfg-label">
703
- 流式间隔超时 (秒)
704
- <span class="help-icon" title="两次数据块之间的最大间隔时间(秒)。如果超过此时间没有收到新数据则断开,建议60-180秒">?</span>
705
- </label>
706
- <input id="cfgStreamChunkTimeout" type="number" class="cfg-input" placeholder="120">
707
- </div>
708
- <div>
709
- <label class="cfg-label">
710
- 生成总过程超时 (秒)
711
- <span class="help-icon" title="整个对话生成的最大总时长(秒)。适用于超长对话,建议300-900秒">?</span>
712
- </label>
713
- <input id="cfgStreamTotalTimeout" type="number" class="cfg-input" placeholder="600">
714
- </div>
715
- <div>
716
- <label class="cfg-label">
717
- 可重试状态码
718
- <span class="help-icon"
719
- title="遇到这些HTTP状态码时会自动换token重试。多个状态码用逗号分隔。默认:401,429&#10;常见状态码:401(未授权), 429(速率限制), 500(服务器错误), 502(网关错误), 503(服务不可用)">?</span>
720
- </label>
721
- <input id="cfgRetryStatusCodes" class="cfg-input" placeholder="401,429">
722
- </div>
723
- </div>
724
- </div>
725
- </div>
726
- </div>
727
-
728
- <!-- 配置提示 -->
729
- <div class="mt-8 rounded border border-blue-300 bg-blue-50 px-4 py-3">
730
- <div class="text-xs text-gray-800 leading-relaxed">
731
- <div class="text-base font-medium text-gray-900 mb-2.5">部分说明</div>
732
- <div class="space-y-1.5">
733
- <div><span class="font-medium">X Statsig ID:</span>反机器人验证参数。开启"动态 Statsig ID"后会自动生成,固定值将被忽略;关闭则使用上方设置的固定值
734
- </div>
735
- <div><span class="font-medium">动态 Statsig:</span>开启后每次请求自动生成新的 x-statsig-id,增强请求多样性,推荐开启</div>
736
- <div><span class="font-medium">服务网址:</span>图片/视频链接返回时需要拼接您的服务网址(如
737
- https://yourdomain.com),若您不使用视频功能且图片使用Base64模式则可留空</div>
738
- <div><span class="font-medium">代理设置:</span>服务代理用于访问Grok
739
- API和上传图片;缓存代理专门用于下载图片和视频缓存。若仅设置服务代理,缓存将使用相同的代理;若都设置,则分别使用不同的代理</div>
740
- <div><span class="font-medium">请求 403:</span>通常是被 CF 拦截了,可采用以下办法之一:1. 更换服务器IP | 2. 配置代理IP | 3.在服务器中访问
741
- grok.com 通过 CF 验证后 F12 获取 cf_clearance</div>
742
- </div>
743
- </div>
744
- </div>
745
- </div>
746
- </main>
747
-
748
- <!-- 编辑信息模态框 -->
749
- <div id="editTagsModal" class="hidden fixed inset-0 z-50 bg-black/80 flex items-center justify-center p-4">
750
- <div class="bg-background rounded-lg border border-border w-full max-w-md shadow-xl">
751
- <div class="flex items-center justify-between p-5 border-b border-border">
752
- <h3 class="text-lg font-semibold">编辑信息</h3>
753
- <button onclick="closeEditModal()" class="text-muted-foreground hover:text-foreground transition-colors">
754
- <svg class="h-3.5 w-3.5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
755
- stroke="currentColor" stroke-width="2">
756
- <line x1="18" y1="6" x2="6" y2="18" />
757
- <line x1="6" y1="6" x2="18" y2="18" />
758
- </svg>
759
- </button>
760
- </div>
761
- <div class="p-5 space-y-4">
762
- <div class="space-y-2">
763
- <label class="text-sm font-medium text-muted-foreground">Token</label>
764
- <input id="editTokenInput" readonly
765
- class="flex h-9 w-full rounded-md border border-input bg-muted px-3 py-2 text-xs font-mono" placeholder="">
766
- </div>
767
- <div class="space-y-2">
768
- <label class="text-sm font-medium text-muted-foreground">标签 <span
769
- class="text-muted-foreground">(多个标签用逗号分隔)</span></label>
770
- <input id="editTagsInput" placeholder="例如: 生产环境, 测试用"
771
- class="flex h-9 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-ring" />
772
- <div id="suggestedTags" class="flex flex-wrap gap-2 mt-2"></div>
773
- </div>
774
- <div class="space-y-2">
775
- <label class="text-sm font-medium text-muted-foreground">备注</label>
776
- <textarea id="editNoteInput" rows="3" placeholder="添加备注信息..."
777
- class="flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-ring resize-none"></textarea>
778
- </div>
779
- </div>
780
- <div class="flex items-center justify-end gap-3 p-5 border-t border-border bg-muted/30">
781
- <button onclick="closeEditModal()"
782
- class="inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 border border-input bg-background hover:bg-accent h-9 px-5">
783
- 取消
784
- </button>
785
- <button onclick="submitEditInfo()"
786
- class="inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 bg-primary text-primary-foreground hover:bg-primary/90 h-9 px-5">
787
- 保存
788
- </button>
789
- </div>
790
- </div>
791
- </div>
792
-
793
- <!-- 添加 Token 模态框 -->
794
- <div id="addModal" class="hidden fixed inset-0 z-50 bg-black/80 flex items-center justify-center p-4">
795
- <div class="bg-background rounded-lg border border-border w-full max-w-2xl max-h-[90vh] overflow-y-auto shadow-xl">
796
- <div class="flex items-center justify-between p-5 border-b border-border">
797
- <h3 class="text-lg font-semibold">添加 Token</h3>
798
- <button onclick="closeAddModal()" class="text-muted-foreground hover:text-foreground transition-colors">
799
- <svg class="h-3.5 w-3.5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
800
- stroke="currentColor" stroke-width="2">
801
- <line x1="18" y1="6" x2="6" y2="18" />
802
- <line x1="6" y1="6" x2="18" y2="18" />
803
- </svg>
804
- </button>
805
- </div>
806
- <div class="p-5 space-y-4">
807
- <div class="space-y-2">
808
- <label class="text-sm font-medium text-muted-foreground">Token 类型</label>
809
- <select id="addTokenType"
810
- class="flex h-9 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-ring">
811
- <option value="sso">SSO</option>
812
- <option value="ssoSuper">SuperSSO</option>
813
- </select>
814
- </div>
815
- <div class="space-y-2">
816
- <label class="text-sm font-medium text-muted-foreground">Token 列表 <span
817
- class="text-muted-foreground">(每行一个)</span></label>
818
- <textarea id="addTokenList" rows="12" placeholder="请输入 Token,每行一个"
819
- class="flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-ring font-mono resize-none"></textarea>
820
- </div>
821
- </div>
822
- <div class="flex items-center justify-end gap-3 p-5 border-t border-border bg-muted/30">
823
- <button onclick="closeAddModal()"
824
- class="inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 border border-input bg-background hover:bg-accent h-9 px-5">
825
- 取消
826
- </button>
827
- <button onclick="submitAddTokens()"
828
- class="inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 bg-primary text-primary-foreground hover:bg-primary/90 h-9 px-5">
829
- 添加
830
- </button>
831
- </div>
832
- </div>
833
- </div>
834
-
835
- <script>
836
- let allTokens = [], filteredTokens = [], selectedTokens = new Set(), allTagsList = [];
837
- const $ = (id) => document.getElementById(id),
838
- checkAuth = () => { const t = localStorage.getItem('adminToken'); return t || (location.href = '/login', null), t },
839
- apiRequest = async (url, opts = {}) => { const t = checkAuth(); if (!t) return null; const r = await fetch(url, { ...opts, headers: { ...opts.headers, Authorization: `Bearer ${t}`, 'Content-Type': 'application/json' } }); return r.status === 401 ? (localStorage.removeItem('adminToken'), location.href = '/login', null) : r },
840
- loadStats = async () => { try { const r = await apiRequest('/api/stats'); if (!r) return; const d = await r.json(); if (d.success) { const s = d.data; $('statTotal').textContent = s.total || 0;['Unused', 'Limited', 'Expired', 'Active'].forEach((k, i) => $(`stat${k}`).textContent = (s.normal?.[k.toLowerCase()] || 0) + (s.super?.[k.toLowerCase()] || 0)) } } catch (e) { console.error('加载统计失败:', e) } },
841
- calcRemaining = () => { let n = 0, h = 0; allTokens.forEach(t => { if (t.remaining_queries > 0) n += t.remaining_queries; if (t.heavy_remaining_queries > 0) h += t.heavy_remaining_queries }); return { normal: n, heavy: h, total: n + h } },
842
- loadTokens = async () => { try { const r = await apiRequest('/api/tokens'); if (!r) return; const d = await r.json(); d.success && (allTokens = d.data.map(t => ({ ...t, tags: t.tags || [], note: t.note || '' })), filteredTokens = allTokens, selectedTokens.clear(), renderTokens(), updateRemaining(), await loadAllTags()) } catch (e) { console.error('加载列表失败:', e) } },
843
- updateRemaining = () => { const r = calcRemaining(); const chatTotal = r.total; const imageTotal = Math.floor(chatTotal / 2); $('statChatRemaining').textContent = chatTotal === 0 ? '-' : chatTotal.toLocaleString(); $('statImageRemaining').textContent = imageTotal === 0 ? '-' : imageTotal.toLocaleString(); $('statVideoRemaining').textContent = '无法统计' }
844
-
845
- const renderTokens = () => { const tb = $('tokenTableBody'), es = $('emptyState'), ss = { '未使用': 'bg-muted text-muted-foreground', '限流中': 'bg-orange-50 text-orange-700 border-orange-200', '失效': 'bg-destructive/10 text-destructive border-destructive/20', '正常': 'bg-green-50 text-green-700 border-green-200' }, ts = { sso: 'bg-blue-50 text-blue-700 border-blue-200', ssoSuper: 'bg-purple-50 text-purple-700 border-purple-200' }, tl = { sso: 'SSO', ssoSuper: 'SuperSSO' }; if (!filteredTokens.length) { tb.innerHTML = ''; es.classList.remove('hidden'); $('selectAll').checked = false; return updateBatchActions() } es.classList.add('hidden'); tb.innerHTML = filteredTokens.map(t => { const tagsHtml = t.tags && t.tags.length ? t.tags.map(tag => `<span class="inline-flex items-center rounded px-1.5 py-0.5 text-xs bg-gray-100 text-gray-700">${tag}</span>`).join(' ') : '<span class="text-xs text-muted-foreground">-</span>'; const noteHtml = t.note && t.note.length ? `<span class="text-xs text-gray-700" title="${t.note}">${t.note.length > 20 ? t.note.substring(0, 20) + '...' : t.note}</span>` : '<span class="text-xs text-muted-foreground">-</span>'; return `<tr class="transition-colors"><td class="py-2.5 px-3 align-middle w-12"><input type="checkbox" class="token-checkbox h-3.5 w-3.5 rounded border border-input focus:ring-1 focus:ring-ring" data-token="${t.token}" data-type="${t.token_type}" ${selectedTokens.has(t.token) ? 'checked' : ''} onchange="toggleToken('${t.token}')"></td><td class="py-2.5 px-3 align-middle w-80"><div class="flex items-center gap-2"><span class="font-mono text-xs">${t.token.substring(0, 30)}...</span><button onclick="copyToken('${t.token.replace(/'/g, "\\'")}',event)" class="inline-flex items-center justify-center rounded-md transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring hover:bg-accent h-6 w-6" title="复制完整 Token"><svg class="h-3 w-3 text-muted-foreground" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg></button></div></td><td class="py-2.5 px-3 align-middle w-20"><span class="inline-flex items-center rounded-full px-1.5 py-0.5 text-xs font-medium border ${ts[t.token_type]}">${tl[t.token_type]}</span></td><td class="py-2.5 px-3 align-middle w-20"><span class="inline-flex items-center rounded-full px-1.5 py-0.5 text-xs font-medium border ${ss[t.status]}">${t.status}</span></td><td class="py-2.5 px-3 align-middle w-20 text-xs tabular-nums">${t.remaining_queries === -1 ? '-' : t.remaining_queries}</td><td class="py-2.5 px-3 align-middle w-20 text-xs tabular-nums">${t.heavy_remaining_queries === -1 ? '-' : t.heavy_remaining_queries}</td><td class="py-2.5 px-3 align-middle w-32"><div class="flex flex-wrap gap-1">${tagsHtml}</div></td><td class="py-2.5 px-3 align-middle w-40">${noteHtml}</td><td class="py-2.5 px-3 align-middle w-32 text-xs text-muted-foreground">${t.created_time ? new Date(t.created_time).toLocaleString('zh-CN', { dateStyle: 'short', timeStyle: 'short' }) : '-'}</td><td class="py-2.5 px-3 align-middle text-right w-28 sticky-right"><div class="flex items-center justify-end gap-1"><button onclick="testToken('${t.token}','${t.token_type}')" class="inline-flex items-center justify-center rounded-md text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring hover:bg-blue-50 hover:text-blue-700 h-7 w-7" title="测试Token"><svg class="h-3.5 w-3.5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg></button><button onclick="editToken('${t.token}','${t.token_type}')" class="inline-flex items-center justify-center rounded-md text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring hover:bg-accent hover:text-accent-foreground h-7 w-7" title="编辑信息"><svg class="h-3.5 w-3.5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/></svg></button><button onclick="deleteToken('${t.token}','${t.token_type}')" class="inline-flex items-center justify-center rounded-md text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring hover:bg-destructive/10 hover:text-destructive h-7 w-7" title="删除"><svg class="h-3.5 w-3.5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg></button></div></td></tr>` }).join(''); updateBatchActions() },
846
- toggleToken = t => selectedTokens[selectedTokens.has(t) ? 'delete' : 'add'](t) || updateBatchActions(),
847
- toggleSelectAll = () => { const sa = $('selectAll'); sa.checked ? filteredTokens.forEach(t => selectedTokens.add(t.token)) : selectedTokens.clear(); renderTokens() },
848
- updateBatchActions = () => { const ba = $('batchActions'), sc = $('selectedCount'), c = selectedTokens.size; ba.classList[c > 0 ? 'add' : 'remove']('flex'); ba.classList[c > 0 ? 'remove' : 'add']('hidden'); c > 0 && (sc.textContent = `已选择 ${c} 项`); $('selectAll').checked = filteredTokens.length > 0 && c === filteredTokens.length },
849
- filterTokens = () => { const tf = $('filterType').value, sf = $('filterStatus').value, tagf = $('filterTag').value; filteredTokens = allTokens.filter(t => (tf === 'all' || t.token_type === tf) && (sf === 'all' || t.status === sf) && (tagf === 'all' || t.tags && t.tags.includes(tagf))); selectedTokens.clear(); renderTokens() },
850
- loadAllTags = async () => { try { const r = await apiRequest('/api/tokens/tags/all'); if (!r) return; const d = await r.json(); if (d.success) { allTagsList = d.data; const tagFilter = $('filterTag'); const currentValue = tagFilter.value; tagFilter.innerHTML = '<option value="all">全部标签</option>' + allTagsList.map(tag => `<option value="${tag}">${tag}</option>`).join(''); tagFilter.value = currentValue } } catch (e) { console.error('加载标签列表失败:', e) } },
851
- refreshTokens = async () => { await loadTokens(); await loadStats() },
852
- openAddModal = () => $('addModal').classList.remove('hidden'),
853
- closeAddModal = () => { $('addModal').classList.add('hidden'); $('addTokenList').value = '' },
854
- deleteToken = async (t, tt) => { if (!confirm('确定要删除这个 Token 吗?')) return; try { const r = await apiRequest('/api/tokens/delete', { method: 'POST', body: JSON.stringify({ tokens: [t], token_type: tt }) }); if (!r) return; const d = await r.json(); d.success ? await refreshTokens() : showToast('删除失败: ' + (d.error || '未知错误'), 'error') } catch (e) { showToast('删除失败: ' + e.message, 'error') } },
855
- batchDelete = async () => { if (!selectedTokens.size || !confirm(`确定要删除选中的 ${selectedTokens.size} 个 Token 吗?此操作不可恢复!`)) return; const tbt = { sso: [], ssoSuper: [] }; document.querySelectorAll('.token-checkbox:checked').forEach(cb => tbt[cb.dataset.type].push(cb.dataset.token)); try { const ps = [];['sso', 'ssoSuper'].forEach(k => tbt[k].length && ps.push(apiRequest('/api/tokens/delete', { method: 'POST', body: JSON.stringify({ tokens: tbt[k], token_type: k }) }))); await Promise.all(ps); await refreshTokens() } catch (e) { showToast('批量删除失败: ' + e.message, 'error') } },
856
- submitAddTokens = async () => { const tt = $('addTokenType').value, tks = $('addTokenList').value.split('\n').map(t => t.trim()).filter(t => t); if (!tks.length) return showToast('请输入至少一个 Token', 'error'); try { const r = await apiRequest('/api/tokens/add', { method: 'POST', body: JSON.stringify({ tokens: tks, token_type: tt }) }); if (!r) return; const d = await r.json(); d.success ? (closeAddModal(), await refreshTokens()) : showToast('添加失败: ' + (d.error || '未知错误'), 'error') } catch (e) { showToast('添加失败: ' + e.message, 'error') } },
857
- copyToken = async (t, e) => { e.stopPropagation(); try { await navigator.clipboard.writeText(t); showToast('Token 已复制到剪贴板', 'success') } catch (err) { console.error('复制失败:', err); showToast('复制失败,请手动复制', 'error') } }
858
-
859
- let currentEditToken = '', currentEditTokenType = '';
860
- editToken = (token, tokenType) => { currentEditToken = token; currentEditTokenType = tokenType; const tokenData = allTokens.find(t => t.token === token); const currentTags = tokenData?.tags || []; const currentNote = tokenData?.note || ''; $('editTokenInput').value = token.substring(0, 50) + '...'; $('editTagsInput').value = currentTags.join(', '); $('editNoteInput').value = currentNote; const suggestedContainer = $('suggestedTags'); suggestedContainer.innerHTML = ''; if (allTagsList.length > 0) { suggestedContainer.innerHTML = '<div class="text-xs text-muted-foreground mb-1">常用标签:</div>' + allTagsList.map(tag => `<button onclick="addTagToInput('${tag}')" class="inline-flex items-center rounded px-2 py-1 text-xs bg-muted hover:bg-accent transition-colors">${tag}</button>`).join('') } $('editTagsModal').classList.remove('hidden') },
861
- closeEditModal = () => { $('editTagsModal').classList.add('hidden'); currentEditToken = ''; currentEditTokenType = '' },
862
- addTagToInput = (tag) => { const input = $('editTagsInput'); const currentValue = input.value.trim(); const tags = currentValue ? currentValue.split(',').map(t => t.trim()) : []; if (!tags.includes(tag)) { tags.push(tag); input.value = tags.join(', ') } },
863
- submitEditInfo = async () => { if (!currentEditToken) return; const tagsInput = $('editTagsInput').value; const note = $('editNoteInput').value.trim(); const tags = tagsInput.split(',').map(t => t.trim()).filter(t => t); const promises = []; promises.push(apiRequest('/api/tokens/tags', { method: 'POST', body: JSON.stringify({ token: currentEditToken, token_type: currentEditTokenType, tags }) })); promises.push(apiRequest('/api/tokens/note', { method: 'POST', body: JSON.stringify({ token: currentEditToken, token_type: currentEditTokenType, note }) })); try { const results = await Promise.all(promises); const allSuccess = results.every(r => r && r.ok); if (allSuccess) { closeEditModal(); await refreshTokens(); showToast('信息更新成功', 'success') } else { showToast('部分更新失败,请重试', 'error') } } catch (e) { showToast('更新失败: ' + e.message, 'error') } }
864
-
865
- testToken = async (token, tokenType) => { const btn = event.target.closest('button'); const originalHtml = btn.innerHTML; btn.disabled = true; btn.innerHTML = '<svg class="h-3.5 w-3.5 animate-spin" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>'; try { const r = await apiRequest('/api/tokens/test', { method: 'POST', body: JSON.stringify({ token, token_type: tokenType }) }); if (!r) return; const d = await r.json(); if (d.success && d.data.valid) { showToast(`Token有效!剩余: ${d.data.remaining_queries === -1 ? '无限制' : d.data.remaining_queries}次`, 'success'); await refreshTokens() } else { const errMsgs = { expired: 'Token已失效 (401错误)', blocked: '服务器被block,请稍后再试或更换IP', limited: 'Token已被限流' }; showToast(errMsgs[d.data?.error_type] || 'Token无效或已失效', 'error') } } catch (e) { showToast('测试失败: ' + e.message, 'error') } finally { btn.disabled = false; btn.innerHTML = originalHtml } }
866
-
867
- const exportSelected = () => { if (!selectedTokens.size) return showToast('请先选择要导出的 Token', 'error'); const sd = allTokens.filter(t => selectedTokens.has(t.token)), csv = [['Token', '类型', '状态', '普通调用剩余', '高级调用剩余', '创建时间'].join(','), ...sd.map(t => [`"${t.token}"`, t.token_type === 'sso' ? 'SSO' : 'SuperSSO', t.status, t.remaining_queries === -1 ? '未使用' : t.remaining_queries, t.heavy_remaining_queries === -1 ? '未使用' : t.heavy_remaining_queries, `"${t.created_time ? new Date(t.created_time).toLocaleString('zh-CN') : '-'}"`].join(','))].join('\n'), l = document.createElement('a'); l.href = URL.createObjectURL(new Blob(['\uFEFF' + csv], { type: 'text/csv;charset=utf-8;' })); l.download = `grok_tokens_${new Date().toISOString().slice(0, 10)}.csv`; l.style.display = 'none'; document.body.appendChild(l); l.click(); document.body.removeChild(l); URL.revokeObjectURL(l.href); showToast(`已导出 ${selectedTokens.size} 个 Token`, 'success') }
868
- showToast = (m, t = 'info') => { const d = document.createElement('div'), bc = { success: 'bg-green-600', error: 'bg-destructive', info: 'bg-primary' }; d.className = `fixed bottom-4 right-4 ${bc[t] || bc.info} text-white px-4 py-2.5 rounded-lg shadow-lg text-sm font-medium z-50 animate-slide-up`; d.textContent = m; document.body.appendChild(d); setTimeout(() => { d.style.opacity = '0'; d.style.transition = 'opacity .3s'; setTimeout(() => d.parentNode && document.body.removeChild(d), 300) }, 2000) }
869
- logout = async () => { if (!confirm('确定要退出登录吗?')) return; try { await apiRequest('/api/logout', { method: 'POST' }) } catch (e) { console.error('登出失败:', e) } finally { localStorage.removeItem('adminToken'); location.href = '/login' } },
870
- switchTab = t => { const cap = n => n.charAt(0).toUpperCase() + n.slice(1);['tokens', 'settings'].forEach(n => { const active = n === t; $(`panel${cap(n)}`).classList.toggle('hidden', !active); $(`tab${cap(n)}`).classList.toggle('border-primary', active); $(`tab${cap(n)}`).classList.toggle('text-primary', active); $(`tab${cap(n)}`).classList.toggle('border-transparent', !active); $(`tab${cap(n)}`).classList.toggle('text-muted-foreground', !active) }); t === 'settings' && loadSettings() },
871
- updateCacheProxyReadonly = () => { const proxyUrl = $('cfgProxyUrl').value.trim(), cacheProxyInput = $('cfgCacheProxyUrl'); if (proxyUrl) { cacheProxyInput.readOnly = false; cacheProxyInput.classList.remove('bg-muted'); cacheProxyInput.placeholder = 'socks5://username:password@127.0.0.1:7890' } else { cacheProxyInput.readOnly = true; cacheProxyInput.classList.add('bg-muted'); cacheProxyInput.value = ''; cacheProxyInput.placeholder = '设置服务代理后自动启用' } },
872
- updateStatsigIdState = () => { const dynamicToggle = $('cfgDynamicStatsig'), statsigInput = $('cfgStatsigId'); if (dynamicToggle.checked) { statsigInput.disabled = true; statsigInput.classList.add('bg-muted', 'text-muted-foreground'); statsigInput.placeholder = '已启用动态生成' } else { statsigInput.disabled = false; statsigInput.classList.remove('bg-muted', 'text-muted-foreground'); statsigInput.placeholder = '' } },
873
- loadSettings = async () => { try { const r = await apiRequest('/api/settings'); if (!r) return; const d = await r.json(); if (d.success) { const g = d.data.global, k = d.data.grok; const cfClearance = k.cf_clearance || ''; const cleanCfDisplay = cfClearance.startsWith('cf_clearance=') ? cfClearance.split('cf_clearance=')[1] : cfClearance; $('cfgAdminUser').value = g.admin_username || ''; $('cfgAdminPass').value = ''; $('cfgLogLevel').value = g.log_level || 'DEBUG'; $('cfgImageCacheMaxSize').value = g.image_cache_max_size_mb || 500; $('cfgVideoCacheMaxSize').value = g.video_cache_max_size_mb || 1000; $('cfgImageMode').value = g.image_mode || 'url'; $('cfgBaseUrl').value = g.base_url || ''; $('cfgApiKey').value = k.api_key || ''; $('cfgProxyUrl').value = k.proxy_url || ''; $('cfgProxyPoolUrl').value = k.proxy_pool_url || ''; $('cfgProxyPoolInterval').value = k.proxy_pool_interval || 300; $('cfgCacheProxyUrl').value = k.cache_proxy_url || ''; $('cfgCfClearance').value = cleanCfDisplay; $('cfgStatsigId').value = k.x_statsig_id || ''; $('cfgDynamicStatsig').checked = k.dynamic_statsig !== false; updateStatsigIdState(); $('cfgFilteredTags').value = k.filtered_tags || ''; $('cfgShowThinking').value = k.show_thinking !== false ? 'true' : 'false'; $('cfgTemporary').value = k.temporary !== false ? 'true' : 'false'; $('cfgStreamChunkTimeout').value = k.stream_chunk_timeout || 120; $('cfgStreamFirstResponseTimeout').value = k.stream_first_response_timeout || 30; $('cfgStreamTotalTimeout').value = k.stream_total_timeout || 600; $('cfgRetryStatusCodes').value = (k.retry_status_codes || [401, 429]).join(','); updateCacheProxyReadonly(); await loadCacheSize() } } catch (e) { console.error('加载配置失败:', e); showToast('加载配置失败', 'error') } },
874
- loadCacheSize = async () => { try { const r = await apiRequest('/api/cache/size'); if (!r) return; const d = await r.json(); if (d.success) { ['image', 'video', 'total'].forEach(t => $(`${t}CacheSize`).value = d.data[`${t}_size`] || '0 MB') } } catch (e) { console.error('加载缓存大小失败:', e);['image', 'video', 'total'].forEach(t => $(`${t}CacheSize`).value = '0 MB') } },
875
- clearCacheByType = async (type, url, msg) => { if (!confirm(msg)) return; try { const r = await apiRequest(url, { method: 'POST' }); if (!r) return; const d = await r.json(); d.success ? (showToast(`${type}缓存清理完成,已删除 ${d.data.deleted_count || 0} 个文件`, 'success'), await loadCacheSize()) : showToast('清理失败: ' + (d.error || '未知错误'), 'error') } catch (e) { showToast('清理失败: ' + e.message, 'error') } },
876
- clearImageCache = () => clearCacheByType('图片', '/api/cache/clear/images', '确定要清理图片缓存吗?此操作将删除所有图片缓存文件!'),
877
- clearVideoCache = () => clearCacheByType('视频', '/api/cache/clear/videos', '确定要清理视频缓存吗?此操作将删除所有视频缓存文件!'),
878
- clearCache = () => clearCacheByType('', '/api/cache/clear', '确定要清理缓存吗?此操作将删除 /data/temp 目录中的所有文件!'),
879
- saveGlobalSettings = async () => { const gc = { admin_username: $('cfgAdminUser').value, log_level: $('cfgLogLevel').value, image_cache_max_size_mb: parseInt($('cfgImageCacheMaxSize').value) || 500, video_cache_max_size_mb: parseInt($('cfgVideoCacheMaxSize').value) || 1000, image_mode: $('cfgImageMode').value, base_url: $('cfgBaseUrl').value }; if ($('cfgAdminPass').value) gc.admin_password = $('cfgAdminPass').value; try { const r = await apiRequest('/api/settings'); if (!r) return; const d = await r.json(); if (!d.success) return showToast('加载配置失败', 'error'); const s = await apiRequest('/api/settings', { method: 'POST', body: JSON.stringify({ global_config: gc, grok_config: d.data.grok }) }); if (!s) return; const sd = await s.json(); sd.success ? (showToast('全局配置保存成功', 'success'), $('cfgAdminPass').value = '') : showToast('保存失败: ' + (sd.error || '未知错误'), 'error') } catch (e) { showToast('保存失败: ' + e.message, 'error') } },
880
- saveGrokSettings = async () => { const pu = $('cfgProxyUrl').value.trim(), cf = $('cfgCfClearance').value.trim(); const cleanCf = cf.startsWith('cf_clearance=') ? cf.split('cf_clearance=')[1] : cf; const retryCodesStr = $('cfgRetryStatusCodes').value.trim(); const retryCodes = retryCodesStr ? retryCodesStr.split(',').map(c => parseInt(c.trim())).filter(c => !isNaN(c)) : [401, 429]; const kc = { api_key: $('cfgApiKey').value, proxy_url: pu, proxy_pool_url: $('cfgProxyPoolUrl').value.trim(), proxy_pool_interval: parseInt($('cfgProxyPoolInterval').value) || 300, cache_proxy_url: pu ? $('cfgCacheProxyUrl').value : '', cf_clearance: cleanCf, x_statsig_id: $('cfgStatsigId').value, dynamic_statsig: $('cfgDynamicStatsig').checked, filtered_tags: $('cfgFilteredTags').value, show_thinking: $('cfgShowThinking').value === 'true', temporary: $('cfgTemporary').value === 'true', stream_chunk_timeout: parseInt($('cfgStreamChunkTimeout').value) || 120, stream_first_response_timeout: parseInt($('cfgStreamFirstResponseTimeout').value) || 30, stream_total_timeout: parseInt($('cfgStreamTotalTimeout').value) || 600, retry_status_codes: retryCodes }; try { const r = await apiRequest('/api/settings'); if (!r) return; const d = await r.json(); if (!d.success) return showToast('加载配置失败', 'error'); const s = await apiRequest('/api/settings', { method: 'POST', body: JSON.stringify({ global_config: d.data.global, grok_config: kc }) }); if (!s) return; const sd = await s.json(); sd.success ? showToast('Grok配置保存成功', 'success') : showToast('保存失败: ' + (sd.error || '未知错误'), 'error') } catch (e) { showToast('保存失败: ' + e.message, 'error') } };
881
- updateHoverCardPosition = c => { const t = c.querySelector('.hover-card-trigger'), ct = c.querySelector('.hover-card-content'); if (!t || !ct) return; const { top, bottom } = t.getBoundingClientRect(), h = window.innerHeight; ct.classList.remove('top', 'bottom'); const { visibility: v, opacity: o } = getComputedStyle(ct); Object.assign(ct.style, { visibility: 'hidden', opacity: '1' }); const ch = ct.offsetHeight; Object.assign(ct.style, { visibility: v, opacity: o }); ct.classList.add(top > ch + 10 ? 'top' : h - bottom > ch + 10 ? 'bottom' : 'top') },
882
- loadStorageMode = async () => { const modeConfig = { MYSQL: { classes: ['bg-blue-50', 'text-blue-700', 'border-blue-200'], tooltip: '数据库连接模式 - 数据持久化存储,修改配置时可能稍慢但更安全' }, REDIS: { classes: ['bg-purple-50', 'text-purple-700', 'border-purple-200'], tooltip: 'Redis缓存模式 - 高速内存存储,数据持久化且读写性能极佳' }, FILE: { classes: ['bg-green-50', 'text-green-700', 'border-green-200'], tooltip: '文件存储模式 - 本地文件存储,读写速度快' } }; const applyMode = (mode) => { $('storageModeText').textContent = mode; const config = modeConfig[mode] || modeConfig.FILE; $('storageMode').classList.add(...config.classes); $('storageModeTooltip').textContent = config.tooltip; updateHoverCardPosition($('storageMode').closest('.hover-card')) }; try { const r = await apiRequest('/api/storage/mode'); if (!r) return; const d = await r.json(); d.success && applyMode(d.data.mode) } catch (e) { console.error('加载存储模式失败:', e); applyMode('FILE') } };
883
- window.addEventListener('DOMContentLoaded', () => { checkAuth(); loadStorageMode(); refreshTokens(); setInterval(() => { loadStats(); updateRemaining() }, 30000); window.addEventListener('resize', () => { const hoverCard = $('storageMode').closest('.hover-card'); hoverCard && updateHoverCardPosition(hoverCard) }); const hoverCard = $('storageMode').closest('.hover-card'), trigger = hoverCard?.querySelector('.hover-card-trigger'), content = hoverCard?.querySelector('.hover-card-content'); if (trigger && content) { trigger.addEventListener('mouseenter', () => { content.style.opacity = '1'; content.style.visibility = 'visible' }); trigger.addEventListener('mouseleave', () => { content.style.opacity = '0'; content.style.visibility = 'hidden' }) }; $('cfgProxyUrl').addEventListener('input', updateCacheProxyReadonly); $('cfgDynamicStatsig').addEventListener('change', updateStatsigIdState) });
884
- </script>
885
- </body>
886
-
887
- </html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/template/favicon.png DELETED

Git LFS Details

  • SHA256: d92973dce171d4f418c4c9a883cd754c6e9828a0f1f7cdf7af19d4896b852306
  • Pointer size: 131 Bytes
  • Size of remote file: 104 kB
app/template/login.html DELETED
@@ -1,54 +0,0 @@
1
- <!DOCTYPE html>
2
- <html lang="zh-CN" class="h-full">
3
- <head>
4
- <meta charset="UTF-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>登录 - Grok2API</title>
7
- <link rel="icon" type="image/png" href="/static/favicon.png">
8
- <script src="https://cdn.tailwindcss.com"></script>
9
- <script>
10
- tailwind.config={theme:{extend:{colors:{border:"hsl(0 0% 89%)",input:"hsl(0 0% 89%)",ring:"hsl(0 0% 3.9%)",background:"hsl(0 0% 100%)",foreground:"hsl(0 0% 3.9%)",primary:{DEFAULT:"hsl(0 0% 9%)",foreground:"hsl(0 0% 98%)"},secondary:{DEFAULT:"hsl(0 0% 96.1%)",foreground:"hsl(0 0% 9%)"},muted:{DEFAULT:"hsl(0 0% 96.1%)",foreground:"hsl(0 0% 45.1%)"},destructive:{DEFAULT:"hsl(0 84.2% 60.2%)",foreground:"hsl(0 0% 98%)"}}}}}
11
- </script>
12
- <style>
13
- @keyframes slide-up{from{transform:translateY(100%);opacity:0}to{transform:translateY(0);opacity:1}}
14
- .animate-slide-up{animation:slide-up .3s ease-out}
15
- </style>
16
- </head>
17
- <body class="h-full bg-background text-foreground antialiased">
18
- <div class="flex min-h-full flex-col justify-center py-12 px-4 sm:px-6 lg:px-8">
19
- <div class="sm:mx-auto sm:w-full sm:max-w-md">
20
- <div class="text-center">
21
- <h1 class="text-4xl font-bold">Grok2API</h1>
22
- <p class="mt-2 text-sm text-muted-foreground">管理员控制台</p>
23
- </div>
24
- </div>
25
-
26
- <div class="sm:mx-auto sm:w-full sm:max-w-md">
27
- <div class="bg-background py-8 px-4 sm:px-10 rounded-lg">
28
- <form id="loginForm" class="space-y-6">
29
- <div class="space-y-2">
30
- <label for="username" class="text-sm font-medium">账户</label>
31
- <input type="text" id="username" name="username" required class="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50" placeholder="请输入账户">
32
- </div>
33
- <div class="space-y-2">
34
- <label for="password" class="text-sm font-medium">密码</label>
35
- <input type="password" id="password" name="password" required class="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50" placeholder="请输入密码">
36
- </div>
37
- <button type="submit" id="loginButton" class="inline-flex items-center justify-center rounded-md font-medium transition-colors bg-primary text-primary-foreground hover:bg-primary/90 h-10 w-full disabled:opacity-50">登录</button>
38
- </form>
39
-
40
- <div class="mt-6 text-center text-xs text-muted-foreground">
41
- <p>Created By Chenyme © 2025</p>
42
- </div>
43
- </div>
44
- </div>
45
- </div>
46
-
47
- <script>
48
- const form=document.getElementById('loginForm'),btn=document.getElementById('loginButton');
49
- form.addEventListener('submit',async(e)=>{e.preventDefault();btn.disabled=true;btn.textContent='登录中...';try{const fd=new FormData(form),r=await fetch('/api/login',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({username:fd.get('username'),password:fd.get('password')})});const d=await r.json();d.success?(localStorage.setItem('adminToken',d.token),location.href='/manage'):showToast(d.message||'登录失败','error')}catch(e){showToast('网络错误,请稍后重试','error')}finally{btn.disabled=false;btn.textContent='登录'}});
50
- function showToast(m,t='error'){const d=document.createElement('div'),bc={success:'bg-green-600',error:'bg-destructive',info:'bg-primary'};d.className=`fixed bottom-4 right-4 ${bc[t]||bc.error} text-white px-4 py-2.5 rounded-lg shadow-lg text-sm font-medium z-50 animate-slide-up`;d.textContent=m;document.body.appendChild(d);setTimeout(()=>{d.style.opacity='0';d.style.transition='opacity .3s';setTimeout(()=>d.parentNode&&document.body.removeChild(d),300)},2000)}
51
- window.addEventListener('DOMContentLoaded',()=>{const t=localStorage.getItem('adminToken');t&&fetch('/api/stats',{headers:{Authorization:`Bearer ${t}`}}).then(r=>{if(r.ok)location.href='/manage'})});
52
- </script>
53
- </body>
54
- </html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
docker-compose.yml DELETED
@@ -1,25 +0,0 @@
1
- services:
2
- grok2api:
3
- image: ghcr.io/chenyme/grok2api:latest
4
- ports:
5
- - "8000:8000"
6
- volumes:
7
- - grok_data:/app/data
8
- - ./logs:/app/logs
9
- environment:
10
- # ===== 存储模式 =====
11
- # 支持 file, mysql 或 redis
12
- - STORAGE_MODE=file
13
-
14
- # ===== 数据库 =====
15
- # 仅在STORAGE_MODE=mysql或redis时需要
16
- # - DATABASE_URL=mysql://user:password@host:3306/grok2api
17
- # MySQL格式: mysql://user:password@host:port/database
18
- # Redis格式: redis://host:port/db 或 redis://user:password@host:port/db
19
-
20
- # ===== Worker数量 =====
21
- # 默认1,建议:CPU核心数 * 2,多进程模式下建议使用MySQL/Redis存储
22
- - WORKERS=1
23
-
24
- volumes:
25
- grok_data:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
docker-entrypoint.sh DELETED
@@ -1,64 +0,0 @@
1
- #!/bin/sh
2
- set -e
3
-
4
- # 初始化配置文件(如果不存在)
5
- echo "[Grok2API] 检查配置文件..."
6
-
7
- # 使用 /tmp 目录进行临时存储(因为 Spaces 不支持持久化卷)
8
- DATA_DIR="/tmp/grok_data"
9
- LOGS_DIR="/tmp/grok_logs"
10
-
11
- # 确保数据目录存在
12
- mkdir -p "$DATA_DIR/temp/image" "$DATA_DIR/temp/video" "$LOGS_DIR"
13
-
14
- # 设置环境变量指向临时目录
15
- export DATA_DIR="$DATA_DIR"
16
- export LOGS_DIR="$LOGS_DIR"
17
-
18
- # 如果 setting.toml 不存在,创建默认配置
19
- if [ ! -f "$DATA_DIR/setting.toml" ]; then
20
- echo "[Grok2API] 初始化 setting.toml..."
21
- cat > "$DATA_DIR/setting.toml" << EOF
22
- [global]
23
- base_url = "http://localhost:7860"
24
- log_level = "INFO"
25
- image_mode = "url"
26
- admin_password = "${ADMIN_PASSWORD:-admin}"
27
- admin_username = "${ADMIN_USERNAME:-admin}"
28
- image_cache_max_size_mb = 512
29
- video_cache_max_size_mb = 1024
30
- max_upload_concurrency = 20
31
- max_request_concurrency = 50
32
- batch_save_interval = 1.0
33
- batch_save_threshold = 10
34
-
35
- [grok]
36
- api_key = "${API_KEY:-}"
37
- proxy_url = "${PROXY_URL:-}"
38
- cache_proxy_url = "${CACHE_PROXY_URL:-}"
39
- cf_clearance = "${CF_CLEARANCE:-}"
40
- x_statsig_id = "${X_STATSIG_ID:-ZTpUeXBlRXJyb3I6IENhbm5vdCByZWFkIHByb3BlcnRpZXMgb2YgdW5kZWZpbmVkIChyZWFkaW5nICdjaGlsZE5vZGVzJyk=}"
41
- dynamic_statsig = true
42
- filtered_tags = "xaiartifact,xai:tool_usage_card,grok:render"
43
- stream_chunk_timeout = 120
44
- stream_total_timeout = 600
45
- stream_first_response_timeout = 30
46
- temporary = true
47
- show_thinking = true
48
- proxy_pool_url = "${PROXY_POOL_URL:-}"
49
- proxy_pool_interval = 300
50
- retry_status_codes = [401, 429]
51
- EOF
52
- fi
53
-
54
- # 如果 token.json 不存在,创建空token文件
55
- if [ ! -f "$DATA_DIR/token.json" ]; then
56
- echo "[Grok2API] 初始化 token.json..."
57
- echo '{"ssoNormal": {}, "ssoSuper": {}}' > "$DATA_DIR/token.json"
58
- fi
59
-
60
- echo "[Grok2API] 配置文件检查完成"
61
- echo "[Grok2API] 启动应用..."
62
-
63
- # 执行传入的命令
64
- exec "$@"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
main.py DELETED
@@ -1,177 +0,0 @@
1
- """Grok2API"""
2
-
3
- import os
4
- import sys
5
- from contextlib import asynccontextmanager
6
- from pathlib import Path
7
-
8
- from fastapi import FastAPI
9
- from fastapi.middleware.cors import CORSMiddleware
10
- from fastapi.staticfiles import StaticFiles
11
- from app.core.logger import logger
12
- from app.core.exception import register_exception_handlers
13
- from app.core.storage import storage_manager
14
- from app.core.config import setting
15
- from app.services.grok.token import token_manager
16
- from app.api.v1.chat import router as chat_router
17
- from app.api.v1.models import router as models_router
18
- from app.api.v1.images import router as images_router
19
- from app.api.admin.manage import router as admin_router
20
- from app.services.mcp import mcp
21
-
22
- # 0. 兼容性检测
23
- try:
24
- if sys.platform != 'win32':
25
- import uvloop
26
- uvloop.install()
27
- logger.info("[Grok2API] 启用uvloop高性能事件循环")
28
- else:
29
- logger.info("[Grok2API] Windows系统,使用默认asyncio事件循环")
30
- except ImportError:
31
- logger.info("[Grok2API] uvloop未安装,使用默认asyncio事件循环")
32
-
33
- # 1. 创建MCP的FastAPI应用实例
34
- mcp_app = mcp.http_app(stateless_http=True, transport="streamable-http")
35
-
36
- # 2. 定义应用生命周期
37
- @asynccontextmanager
38
- async def lifespan(app: FastAPI):
39
- """
40
- 启动顺序:
41
- 1. 初始化核心服务 (storage, settings, token_manager)
42
- 2. 异步加载 token 数据
43
- 3. 启动批量保存任务
44
- 4. 启动MCP服务生命周期
45
-
46
- 关闭顺序 (LIFO):
47
- 1. 关闭MCP服务生命周期
48
- 2. 关闭批量保存任务并刷新数据
49
- 3. 关闭核心服务
50
- """
51
- # --- 启动过程 ---
52
- # 1. 初始化核心服务
53
- await storage_manager.init()
54
-
55
- # 设置存储到配置和token管理器
56
- storage = storage_manager.get_storage()
57
- setting.set_storage(storage)
58
- token_manager.set_storage(storage)
59
-
60
- # 2. 重新加载配置
61
- await setting.reload()
62
- logger.info("[Grok2API] 核心服务初始化完成")
63
-
64
- # 2.5. 初始化代理池
65
- from app.core.proxy_pool import proxy_pool
66
- proxy_url = setting.grok_config.get("proxy_url", "")
67
- proxy_pool_url = setting.grok_config.get("proxy_pool_url", "")
68
- proxy_pool_interval = setting.grok_config.get("proxy_pool_interval", 300)
69
- proxy_pool.configure(proxy_url, proxy_pool_url, proxy_pool_interval)
70
-
71
- # 3. 异步加载 token 数据
72
- await token_manager._load_data()
73
- logger.info("[Grok2API] Token数据加载完成")
74
-
75
- # 4. 启动批量保存任务
76
- await token_manager.start_batch_save()
77
-
78
- # 5. 管理MCP服务的生命周期
79
- mcp_lifespan_context = mcp_app.lifespan(app)
80
- await mcp_lifespan_context.__aenter__()
81
- logger.info("[MCP] MCP服务初始化完成")
82
-
83
- logger.info("[Grok2API] 应用启动成功")
84
-
85
- try:
86
- yield
87
- finally:
88
- # --- 关闭过程 ---
89
- # 1. 退出MCP服务的生命周期
90
- await mcp_lifespan_context.__aexit__(None, None, None)
91
- logger.info("[MCP] MCP服务已关闭")
92
-
93
- # 2. 关闭批量保存任务并刷新数据
94
- await token_manager.shutdown()
95
- logger.info("[Token] Token管理器已关闭")
96
-
97
- # 3. 关闭核心服务
98
- await storage_manager.close()
99
- logger.info("[Grok2API] 应用关闭成功")
100
-
101
-
102
- # 初始化日志
103
- logger.info("[Grok2API] 应用正在启动...")
104
-
105
- # 创建FastAPI应用
106
- app = FastAPI(
107
- title="Grok2API",
108
- description="Grok API 转换服务",
109
- version="1.3.1",
110
- lifespan=lifespan
111
- )
112
-
113
- # 注册全局异常处理器
114
- register_exception_handlers(app)
115
-
116
- # 注册路由
117
- app.include_router(chat_router, prefix="/v1")
118
- app.include_router(models_router, prefix="/v1")
119
- app.include_router(images_router)
120
- app.include_router(admin_router)
121
-
122
- # 挂载静态文件
123
- app.mount("/static", StaticFiles(directory="app/template"), name="template")
124
-
125
- @app.get("/")
126
- async def root():
127
- """根路径"""
128
- from fastapi.responses import RedirectResponse
129
- return RedirectResponse(url="/login")
130
-
131
-
132
- @app.get("/health")
133
- async def health_check():
134
- """健康检查接口"""
135
- return {
136
- "status": "healthy",
137
- "service": "Grok2API",
138
- "version": "1.0.3"
139
- }
140
-
141
- # 挂载MCP服务器
142
- app.mount("", mcp_app)
143
-
144
-
145
- if __name__ == "__main__":
146
- import uvicorn
147
- import os
148
-
149
- # 读取 worker 数量,默认为 1
150
- workers = int(os.getenv("WORKERS", "1"))
151
-
152
- # 读取端口号,默认为 7860(Hugging Face Spaces 标准端口)
153
- port = int(os.getenv("PORT", "7860"))
154
-
155
- # 提示多进程模式
156
- if workers > 1:
157
- logger.info(
158
- f"[Grok2API] 多进程模式已启用 (workers={workers})。"
159
- f"建议使用 Redis/MySQL 存储以获得最佳性能。"
160
- )
161
-
162
- # 确定事件循环类型
163
- loop_type = "auto"
164
- if workers == 1 and sys.platform != 'win32':
165
- try:
166
- import uvloop
167
- loop_type = "uvloop"
168
- except ImportError:
169
- pass
170
-
171
- uvicorn.run(
172
- "main:app",
173
- host="0.0.0.0",
174
- port=port,
175
- workers=workers,
176
- loop=loop_type
177
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
pyproject.toml DELETED
@@ -1,25 +0,0 @@
1
- [project]
2
- name = "grok2api"
3
- version = "1.4.3"
4
- description = "基于 FastAPI 重构的 Grok2API,适配最新的Web调用格式,支持流式对话、图像生成、图像编辑、联网搜索、视频生成、深度思考,支持号池并发调用和自动负载均衡。"
5
- readme = "README.md"
6
- requires-python = ">=3.13"
7
- dependencies = [
8
- "aiofiles==25.1.0",
9
- "aiomysql==0.2.0",
10
- "curl-cffi==0.13.0",
11
- "fastapi==0.119.0",
12
- "pydantic==2.12.2",
13
- "python-dotenv==1.1.1",
14
- "redis==6.4.0",
15
- "requests==2.32.5",
16
- "starlette==0.48.0",
17
- "toml==0.10.2",
18
- "uvloop==0.21.0 ; sys_platform != 'win32'",
19
- "uvicorn==0.37.0",
20
- "portalocker==3.0.0",
21
- "fastmcp==2.12.4",
22
- "cryptography==46.0.3",
23
- "orjson==3.11.4",
24
- "aiohttp==3.13.2",
25
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt DELETED
@@ -1,17 +0,0 @@
1
- toml==0.10.2
2
- fastapi==0.119.0
3
- uvicorn==0.37.0
4
- uvloop==0.21.0; sys_platform != 'win32'
5
- python-dotenv==1.1.1
6
- curl_cffi==0.13.0
7
- requests==2.32.5
8
- starlette==0.48.0
9
- pydantic==2.12.2
10
- aiofiles==25.1.0
11
- portalocker==3.0.0
12
- aiomysql==0.2.0
13
- redis==6.4.0
14
- fastmcp==2.12.4
15
- cryptography==46.0.3
16
- orjson==3.11.4
17
- aiohttp==3.13.2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test/test_concurrency.py DELETED
@@ -1,276 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- Grok2API 并发性能测试脚本
4
-
5
- 测试不同并发级别下的API性能表现
6
- """
7
-
8
- import asyncio
9
- import aiohttp
10
- import time
11
- import statistics
12
- import argparse
13
- from datetime import datetime
14
- from typing import List, Dict, Any
15
- import json
16
-
17
-
18
- class ConcurrencyTester:
19
- """并发测试器"""
20
-
21
- def __init__(self, base_url: str, api_key: str = None):
22
- self.base_url = base_url.rstrip('/')
23
- self.api_key = api_key
24
- self.results: List[Dict[str, Any]] = []
25
-
26
- async def test_request(self, session: aiohttp.ClientSession, request_id: int) -> Dict[str, Any]:
27
- """发送单个测试请求"""
28
- url = f"{self.base_url}/v1/chat/completions"
29
-
30
- headers = {
31
- "Content-Type": "application/json"
32
- }
33
- if self.api_key:
34
- headers["Authorization"] = f"Bearer {self.api_key}"
35
-
36
- payload = {
37
- "model": "grok-3-fast",
38
- "messages": [
39
- {"role": "user", "content": f"测试请求 #{request_id},请简短回复OK"}
40
- ],
41
- "stream": False,
42
- "max_tokens": 10
43
- }
44
-
45
- start_time = time.time()
46
-
47
- try:
48
- async with session.post(url, json=payload, headers=headers, timeout=30) as response:
49
- status = response.status
50
-
51
- if status == 200:
52
- data = await response.json()
53
- elapsed = time.time() - start_time
54
-
55
- return {
56
- "id": request_id,
57
- "status": "success",
58
- "http_status": status,
59
- "elapsed": elapsed,
60
- "response_length": len(json.dumps(data))
61
- }
62
- else:
63
- elapsed = time.time() - start_time
64
- error_text = await response.text()
65
-
66
- return {
67
- "id": request_id,
68
- "status": "error",
69
- "http_status": status,
70
- "elapsed": elapsed,
71
- "error": error_text[:200]
72
- }
73
-
74
- except asyncio.TimeoutError:
75
- elapsed = time.time() - start_time
76
- return {
77
- "id": request_id,
78
- "status": "timeout",
79
- "elapsed": elapsed,
80
- "error": "Request timeout"
81
- }
82
-
83
- except Exception as e:
84
- elapsed = time.time() - start_time
85
- return {
86
- "id": request_id,
87
- "status": "exception",
88
- "elapsed": elapsed,
89
- "error": str(e)
90
- }
91
-
92
- async def run_concurrent_test(self, concurrency: int, total_requests: int):
93
- """运行并发测试"""
94
- print(f"\n{'='*60}")
95
- print(f"📊 测试配置:并发数 {concurrency}, 总请求数 {total_requests}")
96
- print(f"{'='*60}")
97
-
98
- connector = aiohttp.TCPConnector(limit=concurrency, limit_per_host=concurrency)
99
- timeout = aiohttp.ClientTimeout(total=60)
100
-
101
- async with aiohttp.ClientSession(connector=connector, timeout=timeout) as session:
102
- # 预热
103
- print("🔥 预热中...")
104
- await self.test_request(session, 0)
105
-
106
- # 开始测试
107
- print(f"🚀 开始并发测试...")
108
- start_time = time.time()
109
-
110
- # 创建任务
111
- tasks = []
112
- for i in range(1, total_requests + 1):
113
- task = asyncio.create_task(self.test_request(session, i))
114
- tasks.append(task)
115
-
116
- # 控制并发数
117
- if len(tasks) >= concurrency:
118
- results = await asyncio.gather(*tasks)
119
- self.results.extend(results)
120
- tasks = []
121
-
122
- # 显示进度
123
- print(f" 进度: {i}/{total_requests} ({i/total_requests*100:.1f}%)", end='\r')
124
-
125
- # 处理剩余任务
126
- if tasks:
127
- results = await asyncio.gather(*tasks)
128
- self.results.extend(results)
129
-
130
- total_time = time.time() - start_time
131
-
132
- # 统计和输出
133
- self.print_statistics(concurrency, total_requests, total_time)
134
-
135
- def print_statistics(self, concurrency: int, total_requests: int, total_time: float):
136
- """打印统计信息"""
137
- success_results = [r for r in self.results if r["status"] == "success"]
138
- error_results = [r for r in self.results if r["status"] != "success"]
139
-
140
- success_count = len(success_results)
141
- error_count = len(error_results)
142
-
143
- if success_results:
144
- latencies = [r["elapsed"] for r in success_results]
145
- avg_latency = statistics.mean(latencies)
146
- min_latency = min(latencies)
147
- max_latency = max(latencies)
148
- p50_latency = statistics.median(latencies)
149
- p95_latency = sorted(latencies)[int(len(latencies) * 0.95)] if len(latencies) > 1 else latencies[0]
150
- p99_latency = sorted(latencies)[int(len(latencies) * 0.99)] if len(latencies) > 1 else latencies[0]
151
- else:
152
- avg_latency = min_latency = max_latency = p50_latency = p95_latency = p99_latency = 0
153
-
154
- throughput = total_requests / total_time if total_time > 0 else 0
155
-
156
- print(f"\n\n{'='*60}")
157
- print(f"📈 测试结果统计")
158
- print(f"{'='*60}")
159
- print(f" 测试时间: {total_time:.2f}s")
160
- print(f" 总请求数: {total_requests}")
161
- print(f" 并发数: {concurrency}")
162
- print(f"")
163
- print(f" 成功请求: {success_count} ({success_count/total_requests*100:.1f}%)")
164
- print(f" 失败请求: {error_count} ({error_count/total_requests*100:.1f}%)")
165
- print(f"")
166
- print(f" 吞吐量: {throughput:.2f} req/s")
167
- print(f"")
168
- print(f" 延迟统计:")
169
- print(f" 最小: {min_latency*1000:.0f}ms")
170
- print(f" 平均: {avg_latency*1000:.0f}ms")
171
- print(f" 最大: {max_latency*1000:.0f}ms")
172
- print(f" P50: {p50_latency*1000:.0f}ms")
173
- print(f" P95: {p95_latency*1000:.0f}ms")
174
- print(f" P99: {p99_latency*1000:.0f}ms")
175
-
176
- # 错误详情
177
- if error_results:
178
- print(f"\n ⚠️ 错误详情:")
179
- error_types = {}
180
- for r in error_results:
181
- error_type = r.get("status", "unknown")
182
- error_types[error_type] = error_types.get(error_type, 0) + 1
183
-
184
- for error_type, count in error_types.items():
185
- print(f" {error_type}: {count}")
186
-
187
- print(f"{'='*60}\n")
188
-
189
- # 性能评级
190
- self.print_performance_rating(throughput, avg_latency)
191
-
192
- def print_performance_rating(self, throughput: float, avg_latency: float):
193
- """打印性能评级"""
194
- print(f"🎯 性能评级:")
195
-
196
- # 吞吐量评级
197
- if throughput >= 100:
198
- rating = "⭐⭐⭐⭐⭐ 优秀"
199
- elif throughput >= 60:
200
- rating = "⭐⭐⭐⭐ 良好"
201
- elif throughput >= 30:
202
- rating = "⭐⭐⭐ 中等"
203
- elif throughput >= 10:
204
- rating = "⭐⭐ 较低"
205
- else:
206
- rating = "⭐ 需优化"
207
-
208
- print(f" 吞吐量 ({throughput:.1f} req/s): {rating}")
209
-
210
- # 延迟评级
211
- if avg_latency < 0.5:
212
- rating = "⭐⭐⭐⭐⭐ 优秀"
213
- elif avg_latency < 1.0:
214
- rating = "⭐⭐⭐⭐ 良好"
215
- elif avg_latency < 2.0:
216
- rating = "⭐⭐⭐ 中等"
217
- elif avg_latency < 5.0:
218
- rating = "⭐⭐ 较高"
219
- else:
220
- rating = "⭐ 需优化"
221
-
222
- print(f" 平均延迟 ({avg_latency*1000:.0f}ms): {rating}")
223
- print()
224
-
225
-
226
- async def main():
227
- """主函数"""
228
- parser = argparse.ArgumentParser(description='Grok2API 并发性能测试')
229
- parser.add_argument('--url', default='http://localhost:8001', help='API 基础URL')
230
- parser.add_argument('--key', default='', help='API Key(可选)')
231
- parser.add_argument('-c', '--concurrency', type=int, default=10, help='并发数')
232
- parser.add_argument('-n', '--requests', type=int, default=50, help='总请求数')
233
- parser.add_argument('--multi-test', action='store_true', help='运行多级并发测试')
234
-
235
- args = parser.parse_args()
236
-
237
- print(f"""
238
- ╔══════════════════════════════════════════════════════════╗
239
- ║ Grok2API 并发性能测试工具 ║
240
- ╚══════════════════════════════════════════════════════════╝
241
-
242
- 🔗 测试目标: {args.url}
243
- 🔑 API Key: {'已设置' if args.key else '未设置'}
244
- ⏰ 开始时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
245
- """)
246
-
247
- tester = ConcurrencyTester(args.url, args.key)
248
-
249
- if args.multi_test:
250
- # 多级并发测试
251
- test_configs = [
252
- (5, 20), # 5并发,20请求
253
- (10, 50), # 10并发,50请求
254
- (20, 100), # 20并发,100请求
255
- (50, 200), # 50并发,200请求
256
- ]
257
-
258
- for concurrency, requests in test_configs:
259
- tester.results = [] # 清空结果
260
- await tester.run_concurrent_test(concurrency, requests)
261
- await asyncio.sleep(2) # 间隔2秒
262
- else:
263
- # 单次测试
264
- await tester.run_concurrent_test(args.concurrency, args.requests)
265
-
266
- print(f"\n✅ 测试完成!")
267
- print(f"⏰ 结束时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
268
-
269
-
270
- if __name__ == "__main__":
271
- try:
272
- asyncio.run(main())
273
- except KeyboardInterrupt:
274
- print("\n\n⚠️ 测试被用户中断")
275
- except Exception as e:
276
- print(f"\n\n❌ 测试失败: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test/test_concurrency.sh DELETED
@@ -1,177 +0,0 @@
1
- #!/bin/bash
2
-
3
- # Grok2API 并发测试脚本(Shell版本)
4
- # 使用 curl 和 GNU parallel 进行并发测试
5
-
6
- set -e
7
-
8
- # 配置
9
- BASE_URL="${BASE_URL:-http://localhost:8001}"
10
- API_KEY="${API_KEY:-}"
11
- CONCURRENCY="${CONCURRENCY:-10}"
12
- TOTAL_REQUESTS="${TOTAL_REQUESTS:-50}"
13
-
14
- # 颜色
15
- RED='\033[0;31m'
16
- GREEN='\033[0;32m'
17
- YELLOW='\033[1;33m'
18
- BLUE='\033[0;34m'
19
- NC='\033[0m' # No Color
20
-
21
- echo -e "${BLUE}╔══════════════════════════════════════════════════════════╗${NC}"
22
- echo -e "${BLUE}║ Grok2API 并发性能测试工具 (Shell版) ║${NC}"
23
- echo -e "${BLUE}╚══════════════════════════════════════════════════════════╝${NC}"
24
- echo ""
25
- echo -e "${GREEN}🔗 测试目标:${NC} $BASE_URL"
26
- echo -e "${GREEN}🔑 API Key:${NC} ${API_KEY:-(未设置)}"
27
- echo -e "${GREEN}📊 并发数:${NC} $CONCURRENCY"
28
- echo -e "${GREEN}📈 总请求数:${NC} $TOTAL_REQUESTS"
29
- echo ""
30
-
31
- # 检查依赖
32
- if ! command -v curl &> /dev/null; then
33
- echo -e "${RED}❌ 错误: 需要安装 curl${NC}"
34
- exit 1
35
- fi
36
-
37
- # 创建临时目录
38
- TMP_DIR=$(mktemp -d)
39
- trap "rm -rf $TMP_DIR" EXIT
40
-
41
- # 单个请求函数
42
- test_request() {
43
- local request_id=$1
44
- local start_time=$(date +%s.%N)
45
-
46
- # 构建请求
47
- local headers="Content-Type: application/json"
48
- if [ -n "$API_KEY" ]; then
49
- headers="${headers}\nAuthorization: Bearer ${API_KEY}"
50
- fi
51
-
52
- local response=$(curl -s -w "\n%{http_code}\n%{time_total}" \
53
- -X POST "${BASE_URL}/v1/chat/completions" \
54
- -H "Content-Type: application/json" \
55
- ${API_KEY:+-H "Authorization: Bearer $API_KEY"} \
56
- -d "{
57
- \"model\": \"grok-3-fast\",
58
- \"messages\": [{\"role\": \"user\", \"content\": \"测试请求 #${request_id},请简短回复OK\"}],
59
- \"stream\": false,
60
- \"max_tokens\": 10
61
- }" 2>&1)
62
-
63
- local http_code=$(echo "$response" | tail -n 2 | head -n 1)
64
- local time_total=$(echo "$response" | tail -n 1)
65
-
66
- # 记录结果
67
- echo "${request_id},${http_code},${time_total}" >> "$TMP_DIR/results.csv"
68
-
69
- # 显示进度
70
- echo -ne "\r 进度: ${request_id}/${TOTAL_REQUESTS}"
71
- }
72
-
73
- # 导出函数供 parallel 使用
74
- export -f test_request
75
- export BASE_URL API_KEY TMP_DIR
76
-
77
- # 清空结果文件
78
- echo "id,status,time" > "$TMP_DIR/results.csv"
79
-
80
- echo -e "${YELLOW}🚀 开始并发测试...${NC}"
81
- START_TIME=$(date +%s.%N)
82
-
83
- # 使用 GNU parallel(如果可用),否则使用简单循环
84
- if command -v parallel &> /dev/null; then
85
- seq 1 $TOTAL_REQUESTS | parallel -j $CONCURRENCY test_request {}
86
- else
87
- # 简单的后台任务并发
88
- for i in $(seq 1 $TOTAL_REQUESTS); do
89
- test_request $i &
90
-
91
- # 控制并发数
92
- if (( i % CONCURRENCY == 0 )); then
93
- wait
94
- fi
95
- done
96
- wait
97
- fi
98
-
99
- END_TIME=$(date +%s.%N)
100
- TOTAL_TIME=$(echo "$END_TIME - $START_TIME" | bc)
101
-
102
- echo -e "\n"
103
-
104
- # 统计结果
105
- echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
106
- echo -e "${BLUE}📈 测试结果统计${NC}"
107
- echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
108
-
109
- # 统计成功/失败
110
- SUCCESS_COUNT=$(awk -F',' '$2 == 200 {count++} END {print count+0}' "$TMP_DIR/results.csv")
111
- ERROR_COUNT=$((TOTAL_REQUESTS - SUCCESS_COUNT))
112
-
113
- echo -e " 测试时间: ${TOTAL_TIME}s"
114
- echo -e " 总请求数: ${TOTAL_REQUESTS}"
115
- echo -e " 并发数: ${CONCURRENCY}"
116
- echo ""
117
- echo -e " 成功请求: ${GREEN}${SUCCESS_COUNT}${NC} ($(echo "scale=1; $SUCCESS_COUNT * 100 / $TOTAL_REQUESTS" | bc)%)"
118
- echo -e " 失败请求: ${RED}${ERROR_COUNT}${NC} ($(echo "scale=1; $ERROR_COUNT * 100 / $TOTAL_REQUESTS" | bc)%)"
119
- echo ""
120
-
121
- # 计算吞吐量
122
- THROUGHPUT=$(echo "scale=2; $TOTAL_REQUESTS / $TOTAL_TIME" | bc)
123
- echo -e " 吞吐量: ${GREEN}${THROUGHPUT}${NC} req/s"
124
- echo ""
125
-
126
- # 延迟统计(只统计成功的请求)
127
- if [ $SUCCESS_COUNT -gt 0 ]; then
128
- echo -e " 延迟统计:"
129
-
130
- # 提取成功请求的延迟时间
131
- awk -F',' '$2 == 200 {print $3}' "$TMP_DIR/results.csv" | sort -n > "$TMP_DIR/latencies.txt"
132
-
133
- MIN=$(head -n 1 "$TMP_DIR/latencies.txt" | awk '{printf "%.0f", $1*1000}')
134
- MAX=$(tail -n 1 "$TMP_DIR/latencies.txt" | awk '{printf "%.0f", $1*1000}')
135
- AVG=$(awk '{sum+=$1; count++} END {printf "%.0f", sum/count*1000}' "$TMP_DIR/latencies.txt")
136
-
137
- # P50
138
- P50_LINE=$((SUCCESS_COUNT / 2))
139
- P50=$(sed -n "${P50_LINE}p" "$TMP_DIR/latencies.txt" | awk '{printf "%.0f", $1*1000}')
140
-
141
- # P95
142
- P95_LINE=$(echo "scale=0; $SUCCESS_COUNT * 0.95 / 1" | bc)
143
- P95=$(sed -n "${P95_LINE}p" "$TMP_DIR/latencies.txt" | awk '{printf "%.0f", $1*1000}')
144
-
145
- # P99
146
- P99_LINE=$(echo "scale=0; $SUCCESS_COUNT * 0.99 / 1" | bc)
147
- P99=$(sed -n "${P99_LINE}p" "$TMP_DIR/latencies.txt" | awk '{printf "%.0f", $1*1000}')
148
-
149
- echo -e " 最小: ${MIN}ms"
150
- echo -e " 平均: ${AVG}ms"
151
- echo -e " 最大: ${MAX}ms"
152
- echo -e " P50: ${P50}ms"
153
- echo -e " P95: ${P95}ms"
154
- echo -e " P99: ${P99}ms"
155
- fi
156
-
157
- echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
158
-
159
- # 性能评级
160
- echo -e "${YELLOW}🎯 性能评级:${NC}"
161
-
162
- if (( $(echo "$THROUGHPUT >= 100" | bc -l) )); then
163
- RATING="⭐⭐⭐⭐⭐ 优秀"
164
- elif (( $(echo "$THROUGHPUT >= 60" | bc -l) )); then
165
- RATING="⭐⭐⭐⭐ 良好"
166
- elif (( $(echo "$THROUGHPUT >= 30" | bc -l) )); then
167
- RATING="⭐⭐⭐ 中等"
168
- elif (( $(echo "$THROUGHPUT >= 10" | bc -l) )); then
169
- RATING="⭐⭐ 较低"
170
- else
171
- RATING="⭐ 需优化"
172
- fi
173
-
174
- echo -e " 吞吐量 (${THROUGHPUT} req/s): ${RATING}"
175
-
176
- echo ""
177
- echo -e "${GREEN}✅ 测试完成!${NC}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
uv.lock DELETED
The diff for this file is too large to render. See raw diff