bg5 commited on
Commit
e0b68d2
·
verified ·
1 Parent(s): fb8d4e0

Upload 85 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. Dockerfile +24 -0
  2. alembic.ini +149 -0
  3. app/__init__.py +6 -0
  4. app/admin/__init__.py +3 -0
  5. app/admin/api.py +1379 -0
  6. app/admin/auth.py +265 -0
  7. app/admin/config_manager.py +1121 -0
  8. app/admin/routes.py +227 -0
  9. app/admin/stats.py +181 -0
  10. app/admin/template_loader.py +7 -0
  11. app/core/__init__.py +30 -0
  12. app/core/captcha_client.py +196 -0
  13. app/core/chat_cleanup.py +140 -0
  14. app/core/config.py +201 -0
  15. app/core/error_handler.py +237 -0
  16. app/core/file_upload.py +180 -0
  17. app/core/headers.py +89 -0
  18. app/core/http_client.py +130 -0
  19. app/core/httpx_errors.py +80 -0
  20. app/core/message_utils.py +99 -0
  21. app/core/models.py +562 -0
  22. app/core/openai.py +234 -0
  23. app/core/openai_compat.py +171 -0
  24. app/core/request_signing.py +502 -0
  25. app/core/resin_compat.py +41 -0
  26. app/core/response_handler.py +411 -0
  27. app/core/retry_policy.py +296 -0
  28. app/core/session/__init__.py +19 -0
  29. app/core/session/session_content.py +221 -0
  30. app/core/session/session_fingerprint.py +120 -0
  31. app/core/session/session_manager.py +427 -0
  32. app/core/session/session_store.py +87 -0
  33. app/core/upstream.py +1968 -0
  34. app/core/upstream_urls.py +66 -0
  35. app/database.py +138 -0
  36. app/exceptions/__init__.py +54 -0
  37. app/exceptions/api.py +126 -0
  38. app/exceptions/base.py +93 -0
  39. app/exceptions/http.py +139 -0
  40. app/exceptions/upstream.py +144 -0
  41. app/models/__init__.py +6 -0
  42. app/models/db_models.py +88 -0
  43. app/models/schemas.py +103 -0
  44. app/services/config_dao.py +116 -0
  45. app/services/log_writer.py +136 -0
  46. app/services/request_log_dao.py +457 -0
  47. app/services/token_automation.py +357 -0
  48. app/services/token_dao.py +620 -0
  49. app/services/token_importer.py +240 -0
  50. app/services/token_stats_writer.py +187 -0
Dockerfile ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.12-slim
2
+
3
+ # Set working directory
4
+ WORKDIR /app
5
+
6
+ # Create data and logs directories with proper permissions
7
+ RUN mkdir -p /app/data /app/logs && \
8
+ chmod 755 /app/data /app/logs
9
+
10
+ # Install dependencies
11
+ COPY requirements.txt .
12
+ RUN pip install --no-cache-dir -r requirements.txt
13
+
14
+ # Copy application code
15
+ COPY . .
16
+
17
+ # Set environment variable for database path
18
+ ENV DB_PATH=/app/data/tokens.db
19
+
20
+ # Expose port
21
+ EXPOSE 8080
22
+
23
+ # Run the application
24
+ CMD ["python", "main.py"]
alembic.ini ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # A generic, single database configuration.
2
+
3
+ [alembic]
4
+ # path to migration scripts.
5
+ # this is typically a path given in POSIX (e.g. forward slashes)
6
+ # format, relative to the token %(here)s which refers to the location of this
7
+ # ini file
8
+ script_location = %(here)s/migrations
9
+
10
+ # template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
11
+ # Uncomment the line below if you want the files to be prepended with date and time
12
+ # see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
13
+ # for all available tokens
14
+ # file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
15
+ # Or organize into date-based subdirectories (requires recursive_version_locations = true)
16
+ # file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s
17
+
18
+ # sys.path path, will be prepended to sys.path if present.
19
+ # defaults to the current working directory. for multiple paths, the path separator
20
+ # is defined by "path_separator" below.
21
+ prepend_sys_path = .
22
+
23
+ # timezone to use when rendering the date within the migration file
24
+ # as well as the filename.
25
+ # If specified, requires the tzdata library which can be installed by adding
26
+ # `alembic[tz]` to the pip requirements.
27
+ # string value is passed to ZoneInfo()
28
+ # leave blank for localtime
29
+ # timezone =
30
+
31
+ # max length of characters to apply to the "slug" field
32
+ # truncate_slug_length = 40
33
+
34
+ # set to 'true' to run the environment during
35
+ # the 'revision' command, regardless of autogenerate
36
+ # revision_environment = false
37
+
38
+ # set to 'true' to allow .pyc and .pyo files without
39
+ # a source .py file to be detected as revisions in the
40
+ # versions/ directory
41
+ # sourceless = false
42
+
43
+ # version location specification; This defaults
44
+ # to <script_location>/versions. When using multiple version
45
+ # directories, initial revisions must be specified with --version-path.
46
+ # The path separator used here should be the separator specified by "path_separator"
47
+ # below.
48
+ # version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
49
+
50
+ # path_separator; This indicates what character is used to split lists of file
51
+ # paths, including version_locations and prepend_sys_path within configparser
52
+ # files such as alembic.ini.
53
+ # The default rendered in new alembic.ini files is "os", which uses os.pathsep
54
+ # to provide os-dependent path splitting.
55
+ #
56
+ # Note that in order to support legacy alembic.ini files, this default does NOT
57
+ # take place if path_separator is not present in alembic.ini. If this
58
+ # option is omitted entirely, fallback logic is as follows:
59
+ #
60
+ # 1. Parsing of the version_locations option falls back to using the legacy
61
+ # "version_path_separator" key, which if absent then falls back to the legacy
62
+ # behavior of splitting on spaces and/or commas.
63
+ # 2. Parsing of the prepend_sys_path option falls back to the legacy
64
+ # behavior of splitting on spaces, commas, or colons.
65
+ #
66
+ # Valid values for path_separator are:
67
+ #
68
+ # path_separator = :
69
+ # path_separator = ;
70
+ # path_separator = space
71
+ # path_separator = newline
72
+ #
73
+ # Use os.pathsep. Default configuration used for new projects.
74
+ path_separator = os
75
+
76
+
77
+ # set to 'true' to search source files recursively
78
+ # in each "version_locations" directory
79
+ # new in Alembic version 1.10
80
+ # recursive_version_locations = false
81
+
82
+ # the output encoding used when revision files
83
+ # are written from script.py.mako
84
+ # output_encoding = utf-8
85
+
86
+ # database URL. This is consumed by the user-maintained env.py script only.
87
+ # other means of configuring database URLs may be customized within the env.py
88
+ # file.
89
+ sqlalchemy.url = driver://user:pass@localhost/dbname
90
+
91
+
92
+ [post_write_hooks]
93
+ # post_write_hooks defines scripts or Python functions that are run
94
+ # on newly generated revision scripts. See the documentation for further
95
+ # detail and examples
96
+
97
+ # format using "black" - use the console_scripts runner, against the "black" entrypoint
98
+ # hooks = black
99
+ # black.type = console_scripts
100
+ # black.entrypoint = black
101
+ # black.options = -l 79 REVISION_SCRIPT_FILENAME
102
+
103
+ # lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module
104
+ # hooks = ruff
105
+ # ruff.type = module
106
+ # ruff.module = ruff
107
+ # ruff.options = check --fix REVISION_SCRIPT_FILENAME
108
+
109
+ # Alternatively, use the exec runner to execute a binary found on your PATH
110
+ # hooks = ruff
111
+ # ruff.type = exec
112
+ # ruff.executable = ruff
113
+ # ruff.options = check --fix REVISION_SCRIPT_FILENAME
114
+
115
+ # Logging configuration. This is also consumed by the user-maintained
116
+ # env.py script only.
117
+ [loggers]
118
+ keys = root,sqlalchemy,alembic
119
+
120
+ [handlers]
121
+ keys = console
122
+
123
+ [formatters]
124
+ keys = generic
125
+
126
+ [logger_root]
127
+ level = WARNING
128
+ handlers = console
129
+ qualname =
130
+
131
+ [logger_sqlalchemy]
132
+ level = WARNING
133
+ handlers =
134
+ qualname = sqlalchemy.engine
135
+
136
+ [logger_alembic]
137
+ level = INFO
138
+ handlers =
139
+ qualname = alembic
140
+
141
+ [handler_console]
142
+ class = StreamHandler
143
+ args = (sys.stderr,)
144
+ level = NOTSET
145
+ formatter = generic
146
+
147
+ [formatter_generic]
148
+ format = %(levelname)-5.5s [%(name)s] %(message)s
149
+ datefmt = %H:%M:%S
app/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ from app import core, models, utils
5
+
6
+ __all__ = ["core", "models", "utils"]
app/admin/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ """
2
+ 管理后台模块初始化
3
+ """
app/admin/api.py ADDED
@@ -0,0 +1,1379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 管理后台 API 接口
3
+ 用于 htmx 调用的 HTML 片段返回
4
+ """
5
+ from datetime import datetime
6
+ from html import escape
7
+ from pathlib import Path
8
+ import re
9
+ from typing import Optional
10
+
11
+ from fastapi import APIRouter, Depends, Request, UploadFile, File
12
+ from fastapi.responses import HTMLResponse, JSONResponse
13
+
14
+ from app.admin.auth import (
15
+ CSRF_COOKIE_NAME,
16
+ SESSION_COOKIE_NAME,
17
+ check_login_rate_limit,
18
+ generate_csrf_token,
19
+ record_login_failure,
20
+ require_auth,
21
+ require_csrf,
22
+ reset_login_failures,
23
+ )
24
+ from app.admin.config_manager import (
25
+ read_env_content,
26
+ reset_env_to_example,
27
+ save_form_config,
28
+ save_source_config,
29
+ )
30
+ from app.admin.stats import collect_admin_stats, normalize_trend_window
31
+ from app.admin.template_loader import templates
32
+ from app.core.config import settings
33
+ from app.services.request_log_dao import get_request_log_dao
34
+ from app.utils.format import format_compact_number
35
+ from app.utils.logger import (
36
+ DEFAULT_LOG_DIR,
37
+ logger,
38
+ log_exception,
39
+ resolve_log_file_path,
40
+ )
41
+ from app.utils.utlis import mask_token
42
+
43
+ router = APIRouter(prefix="/admin/api", tags=["admin-api"])
44
+ DEFAULT_TOKEN_NAMESPACE = "zai"
45
+
46
+
47
+ # ==================== 认证 API ====================
48
+
49
+ @router.post("/login")
50
+ async def login(request: Request):
51
+ """管理后台登录"""
52
+ from app.admin.auth import create_session
53
+
54
+ try:
55
+ client_id = request.client.host if request.client else "unknown"
56
+ if not check_login_rate_limit(client_id):
57
+ return JSONResponse(
58
+ {
59
+ "success": False,
60
+ "message": "登录尝试过于频繁,请稍后再试",
61
+ },
62
+ status_code=429,
63
+ )
64
+
65
+ data = await request.json()
66
+ password = data.get("password", "")
67
+
68
+ # 创建 session
69
+ session_token = create_session(password)
70
+
71
+ if session_token:
72
+ reset_login_failures(client_id)
73
+ csrf_token = generate_csrf_token(session_token)
74
+ is_secure = request.url.scheme == "https"
75
+ # 登录成功,设置 cookie
76
+ response = JSONResponse({
77
+ "success": True,
78
+ "message": "登录成功"
79
+ })
80
+ response.set_cookie(
81
+ key=SESSION_COOKIE_NAME,
82
+ value=session_token,
83
+ httponly=True,
84
+ max_age=86400, # 24小时
85
+ samesite="strict",
86
+ secure=is_secure,
87
+ )
88
+ response.set_cookie(
89
+ key=CSRF_COOKIE_NAME,
90
+ value=csrf_token,
91
+ httponly=False,
92
+ max_age=86400,
93
+ samesite="strict",
94
+ secure=is_secure,
95
+ )
96
+ logger.info("✅ 管理后台登录成功")
97
+ return response
98
+ else:
99
+ record_login_failure(client_id)
100
+ # 密码错误
101
+ logger.warning("❌ 管理后台登录失败:密码错误")
102
+ return JSONResponse({
103
+ "success": False,
104
+ "message": "密码错误"
105
+ }, status_code=401)
106
+
107
+ except Exception as e:
108
+ log_exception(logger, "❌ 登录异常")
109
+ return JSONResponse({
110
+ "success": False,
111
+ "message": "登录失败"
112
+ }, status_code=500)
113
+
114
+
115
+ @router.post("/logout", dependencies=[Depends(require_auth), Depends(require_csrf)])
116
+ async def logout(request: Request):
117
+ """管理后台登出"""
118
+ from app.admin.auth import delete_session, get_session_token_from_request
119
+
120
+ session_token = get_session_token_from_request(request)
121
+ delete_session(session_token)
122
+
123
+ # 清除 cookie
124
+ response = JSONResponse({
125
+ "success": True,
126
+ "message": "已登出"
127
+ })
128
+ response.delete_cookie(SESSION_COOKIE_NAME)
129
+ response.delete_cookie(CSRF_COOKIE_NAME)
130
+ logger.info("✅ 管理后台已登出")
131
+ return response
132
+
133
+
134
+ async def reload_settings():
135
+ """热重载配置(重新加载环境变量并更新 settings 对象)"""
136
+ from dotenv import load_dotenv
137
+
138
+ from app.core.openai import reset_upstream_client
139
+ from app.core.config import settings
140
+ from app.utils.guest_session_pool import close_guest_session_pool, get_guest_session_pool
141
+ from app.utils.logger import setup_logger
142
+
143
+ # 重新加载 .env 文件
144
+ load_dotenv(override=True)
145
+
146
+ # 重新创建 Settings 对象并更新全局配置
147
+ new_settings = type(settings)()
148
+
149
+ # 更新全局 settings 的所有属性
150
+ for field_name in new_settings.model_fields.keys():
151
+ setattr(settings, field_name, getattr(new_settings, field_name))
152
+
153
+ # 从数据库覆盖配置(优先级: 数据库 > 环境变量)
154
+ from app.admin.config_manager import apply_db_overrides
155
+
156
+ await apply_db_overrides(settings)
157
+ from app.utils.token_pool import normalize_token_load_balance_strategy
158
+
159
+ settings.TOKEN_LOAD_BALANCE_STRATEGY = normalize_token_load_balance_strategy(
160
+ settings.TOKEN_LOAD_BALANCE_STRATEGY
161
+ )
162
+
163
+ # 重新初始化 logger(使用新的 DEBUG_LOGGING 配置)
164
+ setup_logger(log_dir=DEFAULT_LOG_DIR, debug_mode=settings.DEBUG_LOGGING)
165
+
166
+ # 重建上游客户端单例,确保新的 API_ENDPOINT/base_url 立即生效。
167
+ await reset_upstream_client()
168
+
169
+ if not settings.ANONYMOUS_MODE and get_guest_session_pool() is not None:
170
+ logger.info("[guest_session.reload] ANONYMOUS_MODE=false, closing existing guest session pool")
171
+ await close_guest_session_pool()
172
+
173
+ try:
174
+ from app.utils.token_pool import get_token_pool
175
+
176
+ token_pool = get_token_pool()
177
+ if token_pool is not None:
178
+ await token_pool.set_strategy(settings.TOKEN_LOAD_BALANCE_STRATEGY)
179
+ except Exception:
180
+ logger.debug("更新 Token 池负载策略失败", exc_info=settings.DEBUG_LOGGING)
181
+
182
+ logger.info(f"🔄 配置已热重载 (DEBUG_LOGGING={settings.DEBUG_LOGGING})")
183
+
184
+
185
+ def _build_alert(
186
+ message: str,
187
+ *,
188
+ title: str,
189
+ level: str,
190
+ status_code: int = 200,
191
+ ) -> HTMLResponse:
192
+ level_classes = {
193
+ "success": "bg-green-100 border-green-400 text-green-700",
194
+ "warning": "bg-yellow-100 border-yellow-400 text-yellow-700",
195
+ "error": "bg-red-100 border-red-400 text-red-700",
196
+ "info": "bg-blue-100 border-blue-400 text-blue-700",
197
+ }
198
+ classes = level_classes.get(level, level_classes["info"])
199
+ safe_title = escape(title)
200
+ safe_message = escape(message)
201
+ return HTMLResponse(
202
+ f"""
203
+ <div class="{classes} border px-4 py-3 rounded relative" role="alert">
204
+ <strong class="font-bold">{safe_title}</strong>
205
+ <span class="block sm:inline">{safe_message}</span>
206
+ </div>
207
+ """,
208
+ status_code=status_code,
209
+ )
210
+
211
+
212
+ def _with_hx_trigger(response: HTMLResponse, event_name: str) -> HTMLResponse:
213
+ response.headers["HX-Trigger"] = event_name
214
+ return response
215
+
216
+
217
+ def _get_int_query_param(
218
+ request: Request,
219
+ name: str,
220
+ default: int,
221
+ *,
222
+ minimum: int = 1,
223
+ maximum: Optional[int] = None,
224
+ ) -> int:
225
+ """解析查询参数中的正整数,非法值回退到默认值。"""
226
+ raw_value = request.query_params.get(name)
227
+ if raw_value is None:
228
+ return default
229
+
230
+ try:
231
+ value = int(str(raw_value).strip())
232
+ except (TypeError, ValueError):
233
+ return default
234
+
235
+ value = max(minimum, value)
236
+ if maximum is not None:
237
+ value = min(value, maximum)
238
+ return value
239
+
240
+
241
+ def _build_pagination(
242
+ *,
243
+ total_items: int,
244
+ page: int,
245
+ page_size: int,
246
+ ) -> dict:
247
+ """构建分页上下文。"""
248
+ total_items = max(0, int(total_items))
249
+ page_size = max(1, int(page_size))
250
+ total_pages = max(1, (total_items + page_size - 1) // page_size)
251
+ current_page = min(max(1, int(page)), total_pages)
252
+
253
+ if total_items == 0:
254
+ start_item = 0
255
+ end_item = 0
256
+ else:
257
+ start_item = (current_page - 1) * page_size + 1
258
+ end_item = min(total_items, current_page * page_size)
259
+
260
+ return {
261
+ "current_page": current_page,
262
+ "page_size": page_size,
263
+ "total_items": total_items,
264
+ "total_pages": total_pages,
265
+ "has_previous": current_page > 1,
266
+ "has_next": current_page < total_pages,
267
+ "previous_page": max(1, current_page - 1),
268
+ "next_page": min(total_pages, current_page + 1),
269
+ "start_item": start_item,
270
+ "end_item": end_item,
271
+ }
272
+
273
+
274
+ def _normalize_display_value(value: str) -> str:
275
+ normalized = re.sub(r"[^a-z0-9]+", "", str(value or "").casefold())
276
+ return normalized
277
+
278
+
279
+ def _is_redundant_source(source: str, client_name: str) -> bool:
280
+ normalized_source = _normalize_display_value(source)
281
+ normalized_client = _normalize_display_value(client_name)
282
+ if not normalized_source:
283
+ return True
284
+ if not normalized_client:
285
+ return False
286
+ return normalized_source == normalized_client
287
+
288
+
289
+ def _humanize_protocol(protocol: str) -> str:
290
+ normalized = str(protocol or "").strip().lower()
291
+ if normalized == "openai":
292
+ return "OpenAI"
293
+ if normalized == "unknown":
294
+ return "Unknown"
295
+ return normalized or "Unknown"
296
+
297
+
298
+ def _read_log_tail(log_path: Path, max_bytes: int) -> tuple[str, bool, int]:
299
+ if not log_path.exists() or not log_path.is_file():
300
+ return "", False, 0
301
+
302
+ file_size = log_path.stat().st_size
303
+ read_size = min(file_size, max(1024, max_bytes))
304
+
305
+ with log_path.open("rb") as fh:
306
+ if file_size > read_size:
307
+ fh.seek(file_size - read_size)
308
+ data = fh.read(read_size)
309
+
310
+ truncated = file_size > read_size
311
+ if truncated:
312
+ first_newline = data.find(b"\n")
313
+ if first_newline >= 0:
314
+ data = data[first_newline + 1 :]
315
+
316
+ return data.decode("utf-8", errors="replace"), truncated, file_size
317
+
318
+
319
+ @router.get(
320
+ "/dashboard/usage-trend",
321
+ response_class=JSONResponse,
322
+ dependencies=[Depends(require_auth)],
323
+ )
324
+ async def get_dashboard_usage_trend(request: Request):
325
+ """返回仪表盘趋势图数据。"""
326
+ trend_window = normalize_trend_window(
327
+ request.query_params.get("window")
328
+ )
329
+ dao = get_request_log_dao()
330
+ trend_points = await dao.get_provider_usage_trend(
331
+ DEFAULT_TOKEN_NAMESPACE,
332
+ window=trend_window,
333
+ )
334
+ return JSONResponse(
335
+ {
336
+ "window": trend_window,
337
+ "points": trend_points,
338
+ }
339
+ )
340
+
341
+
342
+ @router.get(
343
+ "/runtime-log-tail",
344
+ response_class=HTMLResponse,
345
+ dependencies=[Depends(require_auth)],
346
+ )
347
+ async def get_runtime_log_tail(request: Request):
348
+ """返回运行日志文件尾部内容。"""
349
+ max_bytes = _get_int_query_param(
350
+ request,
351
+ "max_bytes",
352
+ 65536,
353
+ minimum=4096,
354
+ maximum=262144,
355
+ )
356
+ log_path = resolve_log_file_path(settings.LOG_FILE_PATH, log_dir=DEFAULT_LOG_DIR)
357
+
358
+ text, truncated, file_size = _read_log_tail(log_path, max_bytes)
359
+ context = {
360
+ "request": request,
361
+ "log_path": str(log_path),
362
+ "content": text,
363
+ "truncated": truncated,
364
+ "file_size": file_size,
365
+ "max_bytes": max_bytes,
366
+ "updated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
367
+ }
368
+ return templates.TemplateResponse(
369
+ request,
370
+ "components/runtime_log_tail.html",
371
+ context,
372
+ )
373
+
374
+
375
+ def _validate_directory_path(source_dir: str) -> str:
376
+ if not source_dir:
377
+ raise ValueError("请先填写服务端可访问的本地目录路径。")
378
+
379
+ source_path = Path(source_dir).expanduser()
380
+ if not source_path.exists():
381
+ raise ValueError(f"导入目录不存在: {source_path}")
382
+ if not source_path.is_dir():
383
+ raise ValueError(f"导入路径不是目录: {source_path}")
384
+
385
+ return str(source_path)
386
+
387
+
388
+ @router.get(
389
+ "/token-pool",
390
+ response_class=HTMLResponse,
391
+ dependencies=[Depends(require_auth)],
392
+ )
393
+ async def get_token_pool_status(request: Request):
394
+ """获取 Token 池状态(HTML 片段)"""
395
+ from app.utils.token_pool import get_token_pool
396
+
397
+ token_pool = get_token_pool()
398
+
399
+ if not token_pool:
400
+ # Token 池未初始化
401
+ context = {
402
+ "request": request,
403
+ "tokens": [],
404
+ }
405
+ return templates.TemplateResponse(
406
+ request,
407
+ "components/token_pool.html",
408
+ context,
409
+ )
410
+
411
+ # 获取 token 状态统计
412
+ pool_status = await token_pool.get_pool_status()
413
+ tokens_info = []
414
+
415
+ for idx, token_info in enumerate(pool_status.get("tokens", []), 1):
416
+ is_available = token_info.get("is_available", False)
417
+ is_healthy = token_info.get("is_healthy", False)
418
+
419
+ # 确定状态和颜色
420
+ if is_healthy:
421
+ status = "健康"
422
+ status_color = "bg-green-100 text-green-800"
423
+ elif is_available:
424
+ status = "可用"
425
+ status_color = "bg-yellow-100 text-yellow-800"
426
+ else:
427
+ status = "失败"
428
+ status_color = "bg-red-100 text-red-800"
429
+
430
+ # 格式化最后使用时间
431
+ last_success = token_info.get("last_success_time", 0)
432
+ if last_success > 0:
433
+ from datetime import datetime
434
+ last_used = datetime.fromtimestamp(last_success).strftime("%Y-%m-%d %H:%M:%S")
435
+ else:
436
+ last_used = "从未使用"
437
+
438
+ tokens_info.append({
439
+ "index": idx,
440
+ "key": token_info.get("token", "")[:20] + "...",
441
+ "status": status,
442
+ "status_color": status_color,
443
+ "last_used": last_used,
444
+ "failure_count": token_info.get("failure_count", 0),
445
+ "success_rate": token_info.get("success_rate", "0%"),
446
+ "token_type": token_info.get("token_type", "unknown"),
447
+ })
448
+
449
+ context = {
450
+ "request": request,
451
+ "tokens": tokens_info,
452
+ }
453
+
454
+ return templates.TemplateResponse(
455
+ request,
456
+ "components/token_pool.html",
457
+ context,
458
+ )
459
+
460
+
461
+ @router.get(
462
+ "/recent-logs",
463
+ response_class=HTMLResponse,
464
+ dependencies=[Depends(require_auth)],
465
+ )
466
+ async def get_recent_logs(request: Request):
467
+ """获取最近的请求日志(HTML 片段)"""
468
+ dao = get_request_log_dao()
469
+ page_size = _get_int_query_param(
470
+ request,
471
+ "page_size",
472
+ 12,
473
+ maximum=50,
474
+ )
475
+ requested_page = _get_int_query_param(request, "page", 1, maximum=100000)
476
+ total_count = await dao.count_logs()
477
+ pagination = _build_pagination(
478
+ total_items=total_count,
479
+ page=requested_page,
480
+ page_size=page_size,
481
+ )
482
+
483
+ rows = await dao.get_recent_logs(
484
+ limit=page_size,
485
+ offset=(pagination["current_page"] - 1) * page_size,
486
+ )
487
+ logs = []
488
+ for row in rows:
489
+ ts_raw = row.get("timestamp") or row.get("created_at")
490
+ if isinstance(ts_raw, datetime):
491
+ timestamp = ts_raw.strftime("%Y-%m-%d %H:%M:%S")
492
+ elif ts_raw:
493
+ timestamp = str(ts_raw)
494
+ else:
495
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
496
+
497
+ success = bool(row.get("success"))
498
+ try:
499
+ status_code = int(row.get("status_code") or (200 if success else 500))
500
+ except (ValueError, TypeError):
501
+ status_code = 200 if success else 500
502
+
503
+ try:
504
+ duration_value = float(row.get("duration") or 0.0)
505
+ except (ValueError, TypeError):
506
+ duration_value = 0.0
507
+
508
+ try:
509
+ first_token_value = float(row.get("first_token_time") or 0.0)
510
+ except (ValueError, TypeError):
511
+ first_token_value = 0.0
512
+
513
+ source = str(row.get("source") or "unknown")
514
+ client_name = str(row.get("client_name") or "Unknown")
515
+ provider = str(row.get("provider") or "-")
516
+ source_display = (
517
+ ""
518
+ if _is_redundant_source(source, client_name)
519
+ else source
520
+ )
521
+ provider_display = "" if provider == "zai" else provider
522
+ logs.append(
523
+ {
524
+ "timestamp": timestamp,
525
+ "endpoint": str(row.get("endpoint") or "-"),
526
+ "model": str(row.get("model") or "-"),
527
+ "provider": provider,
528
+ "provider_display": provider_display,
529
+ "source": source,
530
+ "source_display": source_display,
531
+ "protocol": str(row.get("protocol") or "unknown"),
532
+ "protocol_display": _humanize_protocol(
533
+ str(row.get("protocol") or "unknown")
534
+ ),
535
+ "client_name": client_name,
536
+ "auth_token_display": mask_token(str(row.get("auth_token") or "")),
537
+ "upstream_auth_token_display": mask_token(
538
+ str(row.get("upstream_auth_token") or "")
539
+ ),
540
+ "success": success,
541
+ "status_code": status_code,
542
+ "duration_display": f"{duration_value:.2f}s",
543
+ "first_token_display": (
544
+ f"{first_token_value:.2f}s"
545
+ if first_token_value > 0
546
+ else "--"
547
+ ),
548
+ "input_tokens": int(row.get("input_tokens") or 0),
549
+ "input_tokens_display": format_compact_number(row.get("input_tokens")),
550
+ "output_tokens": int(row.get("output_tokens") or 0),
551
+ "output_tokens_display": format_compact_number(row.get("output_tokens")),
552
+ "cache_creation_tokens": int(
553
+ row.get("cache_creation_tokens") or 0
554
+ ),
555
+ "cache_creation_tokens_display": format_compact_number(row.get("cache_creation_tokens")),
556
+ "cache_read_tokens": int(
557
+ row.get("cache_read_tokens") or 0
558
+ ),
559
+ "cache_read_tokens_display": format_compact_number(row.get("cache_read_tokens")),
560
+ "error_message": str(row.get("error_message") or ""),
561
+ }
562
+ )
563
+
564
+ context = {
565
+ "request": request,
566
+ "logs": logs,
567
+ "page": pagination,
568
+ }
569
+
570
+ return templates.TemplateResponse(
571
+ request,
572
+ "components/recent_logs.html",
573
+ context,
574
+ )
575
+
576
+
577
+ @router.post(
578
+ "/config/save",
579
+ dependencies=[Depends(require_auth), Depends(require_csrf)],
580
+ )
581
+ async def save_config(request: Request):
582
+ """保存结构化配置并热重载。"""
583
+ try:
584
+ form_data = await request.form()
585
+ await save_form_config(
586
+ form_data,
587
+ reload_callback=reload_settings,
588
+ )
589
+ logger.info("✅ 结构化配置已保存")
590
+ return _with_hx_trigger(
591
+ _build_alert(
592
+ "配置已保存并热重载,页面即将刷新。",
593
+ title="保存成功!",
594
+ level="success",
595
+ ),
596
+ "admin-config-refresh",
597
+ )
598
+ except ValueError as exc:
599
+ return _build_alert(
600
+ str(exc),
601
+ title="校验失败!",
602
+ level="error",
603
+ status_code=200, # return 200 so HTMX swaps the feedback
604
+ )
605
+ except Exception as exc:
606
+ log_exception(logger, "❌ 配置保存失败")
607
+ return _build_alert(
608
+ f"保存失败: {exc}",
609
+ title="错误!",
610
+ level="error",
611
+ status_code=500,
612
+ )
613
+
614
+
615
+ @router.post(
616
+ "/config/source",
617
+ dependencies=[Depends(require_auth), Depends(require_csrf)],
618
+ )
619
+ async def save_config_source(request: Request):
620
+ """保存 .env 源文件并热重载。"""
621
+ try:
622
+ form_data = await request.form()
623
+ await save_source_config(
624
+ str(form_data.get("env_content", "")),
625
+ reload_callback=reload_settings,
626
+ )
627
+ logger.info("✅ 配置源文件已保存")
628
+ return _with_hx_trigger(
629
+ _build_alert(
630
+ ".env 源文件已保存并热重载,页面即将刷新。",
631
+ title="保存成功!",
632
+ level="success",
633
+ ),
634
+ "admin-config-refresh",
635
+ )
636
+ except ValueError as exc:
637
+ return _build_alert(
638
+ str(exc),
639
+ title="源文件校验失败!",
640
+ level="error",
641
+ status_code=400,
642
+ )
643
+ except Exception as exc:
644
+ log_exception(logger, "❌ 源文件保存失败")
645
+ return _build_alert(
646
+ f"源文件保存失败: {exc}",
647
+ title="错误!",
648
+ level="error",
649
+ status_code=500,
650
+ )
651
+
652
+
653
+ @router.post(
654
+ "/config/reset",
655
+ dependencies=[Depends(require_auth), Depends(require_csrf)],
656
+ )
657
+ async def reset_config():
658
+ """将配置重置为 .env.example 并热重载。"""
659
+ try:
660
+ await reset_env_to_example(reload_callback=reload_settings)
661
+ logger.info("✅ 配置已重置为 .env.example 默认值")
662
+ return _with_hx_trigger(
663
+ _build_alert(
664
+ "配置已恢复为 .env.example 默认值,页面即将刷新。",
665
+ title="已重置!",
666
+ level="success",
667
+ ),
668
+ "admin-config-refresh",
669
+ )
670
+ except FileNotFoundError:
671
+ logger.error("❌ 未找到 .env.example,无法重置配置")
672
+ return _build_alert(
673
+ "未找到 .env.example,无法重置配置。",
674
+ title="错误!",
675
+ level="error",
676
+ status_code=404,
677
+ )
678
+ except Exception as exc:
679
+ log_exception(logger, "❌ 配置重置失败")
680
+ return _build_alert(
681
+ f"重置失败: {exc}",
682
+ title="错误!",
683
+ level="error",
684
+ status_code=500,
685
+ )
686
+
687
+
688
+ @router.get(
689
+ "/env-preview",
690
+ dependencies=[Depends(require_auth)],
691
+ )
692
+ async def get_env_preview():
693
+ """获取 .env 文件预览"""
694
+ try:
695
+ content = read_env_content()
696
+ if not content:
697
+ content = "# .env 文件不存在"
698
+ return HTMLResponse(f"<pre>{escape(content)}</pre>")
699
+ except Exception as exc:
700
+ return HTMLResponse(f"<pre># 读取失败: {escape(str(exc))}</pre>")
701
+
702
+
703
+ # ==================== Token 管理 API ====================
704
+
705
+ @router.get(
706
+ "/tokens/list",
707
+ response_class=HTMLResponse,
708
+ dependencies=[Depends(require_auth)],
709
+ )
710
+ async def get_tokens_list(request: Request):
711
+ """获取 Token 列表(HTML 片段)"""
712
+ from app.services.token_dao import get_token_dao
713
+
714
+ dao = get_token_dao()
715
+ page_size = _get_int_query_param(
716
+ request,
717
+ "page_size",
718
+ 20,
719
+ maximum=100,
720
+ )
721
+ requested_page = _get_int_query_param(request, "page", 1, maximum=100000)
722
+ total_count = await dao.count_tokens_by_provider(
723
+ DEFAULT_TOKEN_NAMESPACE,
724
+ enabled_only=False,
725
+ )
726
+ pagination = _build_pagination(
727
+ total_items=total_count,
728
+ page=requested_page,
729
+ page_size=page_size,
730
+ )
731
+ tokens = await dao.get_tokens_by_provider(
732
+ DEFAULT_TOKEN_NAMESPACE,
733
+ enabled_only=False,
734
+ limit=page_size,
735
+ offset=(pagination["current_page"] - 1) * page_size,
736
+ )
737
+
738
+ context = {
739
+ "request": request,
740
+ "tokens": tokens,
741
+ "page": pagination,
742
+ }
743
+
744
+ return templates.TemplateResponse(
745
+ request,
746
+ "components/token_list.html",
747
+ context,
748
+ )
749
+
750
+
751
+ @router.post(
752
+ "/tokens/add",
753
+ dependencies=[Depends(require_auth), Depends(require_csrf)],
754
+ )
755
+ async def add_tokens(request: Request):
756
+ """添加 Token"""
757
+ from app.services.token_dao import get_token_dao
758
+ from app.utils.token_pool import get_token_pool
759
+
760
+ form_data = await request.form()
761
+ single_token = form_data.get("single_token", "").strip()
762
+ bulk_tokens = form_data.get("bulk_tokens", "").strip()
763
+
764
+ dao = get_token_dao()
765
+ added_count = 0
766
+ failed_count = 0
767
+
768
+ # 添加单个 Token(带验证)
769
+ if single_token:
770
+ token_id = await dao.add_token(
771
+ DEFAULT_TOKEN_NAMESPACE,
772
+ single_token,
773
+ validate=True,
774
+ )
775
+ if token_id:
776
+ added_count += 1
777
+ else:
778
+ failed_count += 1
779
+
780
+ # 批量添加 Token(带验证)
781
+ if bulk_tokens:
782
+ # 支持换行和逗号分隔
783
+ tokens = []
784
+ for line in bulk_tokens.split('\n'):
785
+ line = line.strip()
786
+ if ',' in line:
787
+ tokens.extend([t.strip() for t in line.split(',') if t.strip()])
788
+ elif line:
789
+ tokens.append(line)
790
+
791
+ success, failed = await dao.bulk_add_tokens(
792
+ DEFAULT_TOKEN_NAMESPACE,
793
+ tokens,
794
+ validate=True,
795
+ )
796
+ added_count += success
797
+ failed_count += failed
798
+
799
+ # 同步 Token 池状态(如果有新增成功的 Token)
800
+ if added_count > 0:
801
+ pool = get_token_pool()
802
+ if pool:
803
+ await pool.sync_from_database(DEFAULT_TOKEN_NAMESPACE)
804
+ logger.info(f"✅ Token 池已同步,新增 {added_count} 个 Token")
805
+
806
+ # 生成响应
807
+ if added_count > 0 and failed_count == 0:
808
+ return HTMLResponse(f"""
809
+ <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative" role="alert">
810
+ <strong class="font-bold">成功!</strong>
811
+ <span class="block sm:inline">已添加 {added_count} 个有效 Token</span>
812
+ </div>
813
+ """)
814
+ elif added_count > 0 and failed_count > 0:
815
+ return HTMLResponse(f"""
816
+ <div class="bg-yellow-100 border border-yellow-400 text-yellow-700 px-4 py-3 rounded relative" role="alert">
817
+ <strong class="font-bold">部分成功!</strong>
818
+ <span class="block sm:inline">已添加 {added_count} 个 Token,{failed_count} 个失败(可能是重复、无效或匿名 Token)</span>
819
+ </div>
820
+ """)
821
+ else:
822
+ return HTMLResponse("""
823
+ <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative" role="alert">
824
+ <strong class="font-bold">失败!</strong>
825
+ <span class="block sm:inline">所有 Token 添加失败(可能是重复、无效或匿名 Token)</span>
826
+ </div>
827
+ """)
828
+
829
+
830
+ @router.post(
831
+ "/tokens/import-directory",
832
+ dependencies=[Depends(require_auth), Depends(require_csrf)],
833
+ )
834
+ async def import_tokens_from_directory_api(request: Request):
835
+ """从本地目录导入 token 文件。"""
836
+ from app.core.config import settings
837
+ from app.services.token_automation import run_directory_import
838
+
839
+ form_data = await request.form()
840
+ source_dir = str(
841
+ form_data.get("source_dir")
842
+ or settings.TOKEN_AUTO_IMPORT_SOURCE_DIR
843
+ or ""
844
+ ).strip()
845
+ try:
846
+ source_dir = _validate_directory_path(source_dir)
847
+ except ValueError as exc:
848
+ return _build_alert(
849
+ str(exc),
850
+ title="导入失败!",
851
+ level="error",
852
+ status_code=400,
853
+ )
854
+
855
+ try:
856
+ summary = await run_directory_import(
857
+ source_dir,
858
+ provider=DEFAULT_TOKEN_NAMESPACE,
859
+ validate=True,
860
+ )
861
+ except (FileNotFoundError, NotADirectoryError) as exc:
862
+ return _build_alert(
863
+ str(exc),
864
+ title="导入失败!",
865
+ level="error",
866
+ status_code=400,
867
+ )
868
+ except RuntimeError as exc:
869
+ return _build_alert(
870
+ str(exc),
871
+ title="导入稍后重试",
872
+ level="warning",
873
+ status_code=409,
874
+ )
875
+ except Exception as exc:
876
+ log_exception(logger, "❌ 本地目录导入 Token 失败")
877
+ return _build_alert(
878
+ f"目录扫描或入库异常: {exc}",
879
+ title="导入失败!",
880
+ level="error",
881
+ status_code=500,
882
+ )
883
+
884
+ if summary.imported_count > 0:
885
+ title = "导入成功!" if summary.failed_count == 0 else "导入完成!"
886
+ detail = (
887
+ f"目录 {summary.source_dir} 共扫描 {summary.scanned_files} 个文件,"
888
+ f"成功导入 {summary.imported_count} 个 Token,"
889
+ f"重复 {summary.duplicate_count} 个,"
890
+ f"无效 JSON {summary.invalid_json_count} 个,"
891
+ f"缺少 token {summary.missing_token_count} 个,"
892
+ f"验证失败 {summary.invalid_token_count} 个。"
893
+ )
894
+ return _build_alert(
895
+ detail,
896
+ title=title,
897
+ level="success" if summary.failed_count == 0 else "warning",
898
+ )
899
+
900
+ return _build_alert(
901
+ (
902
+ f"目录 {summary.source_dir} 共扫描 {summary.scanned_files} 个文件,"
903
+ f"其中重复 {summary.duplicate_count} 个,无效 JSON {summary.invalid_json_count} 个,"
904
+ f"缺少 token {summary.missing_token_count} 个,验证失败 {summary.invalid_token_count} 个。"
905
+ ),
906
+ title="未导入任何 Token!",
907
+ level="warning",
908
+ )
909
+
910
+
911
+ @router.post(
912
+ "/tokens/auto-import/save",
913
+ dependencies=[Depends(require_auth), Depends(require_csrf)],
914
+ )
915
+ async def save_auto_import_settings(request: Request):
916
+ """兼容旧入口,提示用户改到配置管理页。"""
917
+ return _build_alert(
918
+ "自动导入配置入口已迁移到 /admin/config#tokens,当前页面仅保留手动执行入口。",
919
+ title="入口已迁移",
920
+ level="info",
921
+ )
922
+
923
+
924
+ @router.post(
925
+ "/tokens/import-upload",
926
+ dependencies=[Depends(require_auth), Depends(require_csrf)],
927
+ )
928
+ async def import_tokens_from_upload_api(
929
+ files: list[UploadFile] = File(...),
930
+ ):
931
+ """通过上传 JSON 文件导入 Token(替代本地目录读取)。"""
932
+ from typing import List, Tuple
933
+
934
+ from app.services.token_importer import import_tokens_from_uploaded_files
935
+ from app.utils.token_pool import get_token_pool
936
+
937
+ if not files:
938
+ return _build_alert(
939
+ "未选择任何文件,请选择至少一个 JSON 文件。",
940
+ title="上传失败!",
941
+ level="error",
942
+ status_code=400,
943
+ )
944
+
945
+ # 读取所有上传文件内容
946
+ file_data: List[Tuple[str, bytes]] = []
947
+ for f in files:
948
+ content = await f.read()
949
+ file_data.append((f.filename or "unknown.json", content))
950
+
951
+ try:
952
+ summary = await import_tokens_from_uploaded_files(
953
+ file_data,
954
+ provider=DEFAULT_TOKEN_NAMESPACE,
955
+ validate=True,
956
+ )
957
+ except Exception as exc:
958
+ log_exception(logger, "❌ 上传 JSON 文件导入 Token 失败")
959
+ return _build_alert(
960
+ f"文件解析或入库异常: {exc}",
961
+ title="导入失败!",
962
+ level="error",
963
+ status_code=500,
964
+ )
965
+
966
+ # 导入成功后同步 Token 池
967
+ if summary.imported_count > 0:
968
+ pool = get_token_pool()
969
+ if pool:
970
+ await pool.sync_from_database(DEFAULT_TOKEN_NAMESPACE)
971
+ logger.info(f"✅ 上传导入后已同步 Token 池,新增 {summary.imported_count} 个 Token")
972
+
973
+ if summary.imported_count > 0:
974
+ title = "导入成功!" if summary.failed_count == 0 else "导入完成!"
975
+ detail = (
976
+ f"共上传 {summary.scanned_files} 个文件,"
977
+ f"成功导入 {summary.imported_count} 个 Token,"
978
+ f"重复 {summary.duplicate_count} 个,"
979
+ f"无效 JSON {summary.invalid_json_count} 个,"
980
+ f"缺少 token {summary.missing_token_count} 个,"
981
+ f"验证失败 {summary.invalid_token_count} 个。"
982
+ )
983
+ return _build_alert(
984
+ detail,
985
+ title=title,
986
+ level="success" if summary.failed_count == 0 else "warning",
987
+ )
988
+
989
+ return _build_alert(
990
+ (
991
+ f"共上传 {summary.scanned_files} 个文件,"
992
+ f"其中重复 {summary.duplicate_count} 个,无效 JSON {summary.invalid_json_count} 个,"
993
+ f"缺少 token {summary.missing_token_count} 个,验证失败 {summary.invalid_token_count} 个。"
994
+ ),
995
+ title="未导入任何 Token!",
996
+ level="warning",
997
+ )
998
+
999
+
1000
+ @router.post(
1001
+ "/tokens/maintenance/save",
1002
+ dependencies=[Depends(require_auth), Depends(require_csrf)],
1003
+ )
1004
+ async def save_auto_maintenance_settings(request: Request):
1005
+ """兼容旧入口,提示用户改到配置管理页。"""
1006
+ return _build_alert(
1007
+ "自动维护配置入口已迁移到 /admin/config#tokens,当前页面仅保留手动执行入口。",
1008
+ title="入口已迁移",
1009
+ level="info",
1010
+ )
1011
+
1012
+
1013
+ @router.post(
1014
+ "/tokens/maintenance/run",
1015
+ dependencies=[Depends(require_auth), Depends(require_csrf)],
1016
+ )
1017
+ async def run_token_maintenance_api(request: Request):
1018
+ """立即执行一次 Token 维护。"""
1019
+ from app.core.config import settings
1020
+ from app.services.token_automation import run_token_maintenance
1021
+
1022
+ form_data = await request.form()
1023
+ action_fields = (
1024
+ "auto_remove_duplicates",
1025
+ "auto_health_check",
1026
+ "auto_delete_invalid",
1027
+ )
1028
+ has_explicit_actions = any(field in form_data for field in action_fields)
1029
+
1030
+ if has_explicit_actions:
1031
+ remove_duplicates = "auto_remove_duplicates" in form_data
1032
+ run_health_check = "auto_health_check" in form_data
1033
+ delete_invalid = "auto_delete_invalid" in form_data
1034
+ else:
1035
+ remove_duplicates = settings.TOKEN_AUTO_REMOVE_DUPLICATES
1036
+ run_health_check = settings.TOKEN_AUTO_HEALTH_CHECK
1037
+ delete_invalid = settings.TOKEN_AUTO_DELETE_INVALID
1038
+
1039
+ if not any((remove_duplicates, run_health_check, delete_invalid)):
1040
+ return _build_alert(
1041
+ "当前没有可执行的维护动作,请先到 /admin/config#tokens 配置至少一个维护动作。",
1042
+ title="未执行维护!",
1043
+ level="warning",
1044
+ status_code=400,
1045
+ )
1046
+
1047
+ try:
1048
+ summary = await run_token_maintenance(
1049
+ provider=DEFAULT_TOKEN_NAMESPACE,
1050
+ remove_duplicates=remove_duplicates,
1051
+ run_health_check=run_health_check,
1052
+ delete_invalid_tokens=delete_invalid,
1053
+ )
1054
+ except RuntimeError as exc:
1055
+ return _build_alert(
1056
+ str(exc),
1057
+ title="维护稍后重试",
1058
+ level="warning",
1059
+ status_code=409,
1060
+ )
1061
+ except Exception as exc:
1062
+ log_exception(logger, "❌ 手动执行 Token 维护失败")
1063
+ return _build_alert(
1064
+ f"Token 维护失败: {exc}",
1065
+ title="维护失败!",
1066
+ level="error",
1067
+ status_code=500,
1068
+ )
1069
+
1070
+ return _build_alert(
1071
+ (
1072
+ f"本次维护共去重 {summary.duplicate_removed_count} 个,"
1073
+ f"测活 {summary.checked_count} 个(有效 {summary.valid_count} / "
1074
+ f"匿名 {summary.guest_count} / 无效 {summary.invalid_count}),"
1075
+ f"删除失效 Token {summary.deleted_invalid_count} 个。"
1076
+ ),
1077
+ title="维护完成!",
1078
+ level="success",
1079
+ )
1080
+
1081
+
1082
+ @router.post(
1083
+ "/tokens/toggle/{token_id}",
1084
+ dependencies=[Depends(require_auth), Depends(require_csrf)],
1085
+ )
1086
+ async def toggle_token(token_id: int, enabled: bool):
1087
+ """切换 Token 启用状态"""
1088
+ from app.services.token_dao import get_token_dao
1089
+ from app.utils.token_pool import get_token_pool
1090
+
1091
+ dao = get_token_dao()
1092
+ await dao.update_token_status(token_id, enabled)
1093
+
1094
+ # 同步 Token 池状态
1095
+ pool = get_token_pool()
1096
+ if pool:
1097
+ # 获取 Token 的提供商信息
1098
+ token_info = await dao.get_token_by_id(token_id)
1099
+ if token_info:
1100
+ provider = token_info["provider"]
1101
+ await pool.sync_from_database(provider)
1102
+ logger.info("✅ Token 池已同步")
1103
+
1104
+ # 根据状态返回不同样式的按钮
1105
+ if enabled:
1106
+ button_class = "bg-green-100 text-green-800 hover:bg-green-200"
1107
+ indicator_class = "bg-green-500"
1108
+ label = "已启用"
1109
+ next_state = "false"
1110
+ else:
1111
+ button_class = "bg-red-100 text-red-800 hover:bg-red-200"
1112
+ indicator_class = "bg-red-500"
1113
+ label = "已禁用"
1114
+ next_state = "true"
1115
+
1116
+ return HTMLResponse(f"""
1117
+ <button hx-post="/admin/api/tokens/toggle/{token_id}?enabled={next_state}"
1118
+ hx-swap="outerHTML"
1119
+ class="inline-flex items-center px-2.5 py-0.5 text-xs font-semibold rounded-full transition-colors {button_class}">
1120
+ <span class="h-2 w-2 rounded-full mr-1.5 {indicator_class}"></span>
1121
+ {label}
1122
+ </button>
1123
+ """)
1124
+
1125
+
1126
+ @router.delete(
1127
+ "/tokens/delete/{token_id}",
1128
+ dependencies=[Depends(require_auth), Depends(require_csrf)],
1129
+ )
1130
+ async def delete_token(token_id: int):
1131
+ """删除 Token"""
1132
+ from app.services.token_dao import get_token_dao
1133
+ from app.utils.token_pool import get_token_pool
1134
+
1135
+ dao = get_token_dao()
1136
+
1137
+ # 获取 Token 信息以确定提供商
1138
+ token_info = await dao.get_token_by_id(token_id)
1139
+ provider = token_info["provider"] if token_info else "zai"
1140
+
1141
+ await dao.delete_token(token_id)
1142
+
1143
+ # 同步 Token 池状态
1144
+ pool = get_token_pool()
1145
+ if pool:
1146
+ await pool.sync_from_database(provider)
1147
+ logger.info("✅ Token 池已同步")
1148
+
1149
+ return HTMLResponse("") # 返回空内容,让 htmx 移除元素
1150
+
1151
+
1152
+ @router.get(
1153
+ "/tokens/stats",
1154
+ response_class=HTMLResponse,
1155
+ dependencies=[Depends(require_auth)],
1156
+ )
1157
+ async def get_tokens_stats(request: Request):
1158
+ """获取 Token 统计信息(HTML 片段)"""
1159
+ stats_data = await collect_admin_stats(DEFAULT_TOKEN_NAMESPACE)
1160
+
1161
+ context = {
1162
+ "request": request,
1163
+ "stats": stats_data,
1164
+ }
1165
+
1166
+ return templates.TemplateResponse(
1167
+ request,
1168
+ "components/token_stats.html",
1169
+ context,
1170
+ )
1171
+
1172
+
1173
+ @router.post(
1174
+ "/tokens/validate",
1175
+ dependencies=[Depends(require_auth), Depends(require_csrf)],
1176
+ )
1177
+ async def validate_tokens():
1178
+ """批量验证 Token"""
1179
+ from app.services.token_dao import get_token_dao
1180
+ from app.utils.token_pool import get_token_pool
1181
+
1182
+ dao = get_token_dao()
1183
+
1184
+ # 执行批量验证
1185
+ stats = await dao.validate_all_tokens(DEFAULT_TOKEN_NAMESPACE)
1186
+
1187
+ pool = get_token_pool()
1188
+ if pool:
1189
+ await pool.sync_from_database(DEFAULT_TOKEN_NAMESPACE)
1190
+
1191
+ valid_count = stats.get("valid", 0)
1192
+ guest_count = stats.get("guest", 0)
1193
+ invalid_count = stats.get("invalid", 0)
1194
+
1195
+ # 生成通知消息
1196
+ if guest_count > 0:
1197
+ message_class = "bg-yellow-100 border-yellow-400 text-yellow-700"
1198
+ message = f"验证完成:有效 {valid_count} 个,��名 {guest_count} 个,无效 {invalid_count} 个。匿名 Token 已标记。"
1199
+ elif invalid_count > 0:
1200
+ message_class = "bg-blue-100 border-blue-400 text-blue-700"
1201
+ message = f"验证完成:有效 {valid_count} 个,无效 {invalid_count} 个。"
1202
+ else:
1203
+ message_class = "bg-green-100 border-green-400 text-green-700"
1204
+ message = f"验证完成:所有 {valid_count} 个 Token 均有效!"
1205
+
1206
+ return HTMLResponse(f"""
1207
+ <div class="{message_class} border px-4 py-3 rounded relative" role="alert">
1208
+ <strong class="font-bold">批量验证完成!</strong>
1209
+ <span class="block sm:inline">{message}</span>
1210
+ </div>
1211
+ """)
1212
+
1213
+
1214
+ @router.post(
1215
+ "/tokens/validate-single/{token_id}",
1216
+ dependencies=[Depends(require_auth), Depends(require_csrf)],
1217
+ )
1218
+ async def validate_single_token(request: Request, token_id: int):
1219
+ """验证单个 Token 并返回更新后的行"""
1220
+ from app.services.token_dao import get_token_dao
1221
+ from app.utils.token_pool import get_token_pool
1222
+
1223
+ dao = get_token_dao()
1224
+
1225
+ # 验证 Token
1226
+ await dao.validate_and_update_token(token_id)
1227
+
1228
+ pool = get_token_pool()
1229
+ if pool:
1230
+ await pool.sync_from_database(DEFAULT_TOKEN_NAMESPACE)
1231
+
1232
+ # 获取更新后的 Token 信息
1233
+ token = await dao.get_token_by_id(token_id)
1234
+
1235
+ if token:
1236
+ # 返回更新后的单行 HTML
1237
+ context = {
1238
+ "request": request,
1239
+ "token": token,
1240
+ }
1241
+ # 使用单行模板渲染
1242
+ return templates.TemplateResponse(
1243
+ request,
1244
+ "components/token_row.html",
1245
+ context,
1246
+ )
1247
+ else:
1248
+ return HTMLResponse("")
1249
+
1250
+
1251
+ @router.post(
1252
+ "/tokens/health-check",
1253
+ dependencies=[Depends(require_auth), Depends(require_csrf)],
1254
+ )
1255
+ async def health_check_tokens():
1256
+ """执行 Token 池健康检查"""
1257
+ from app.utils.token_pool import get_token_pool
1258
+
1259
+ pool = get_token_pool()
1260
+
1261
+ if not pool:
1262
+ return HTMLResponse("""
1263
+ <div class="bg-yellow-100 border border-yellow-400 text-yellow-700 px-4 py-3 rounded relative" role="alert">
1264
+ <strong class="font-bold">提示!</strong>
1265
+ <span class="block sm:inline">Token 池未初始化,请重启服务。</span>
1266
+ </div>
1267
+ """)
1268
+
1269
+ # 执行健康检查
1270
+ await pool.health_check_all()
1271
+
1272
+ # 获取健康状态
1273
+ status = await pool.get_pool_status()
1274
+ healthy_count = status.get("healthy_tokens", 0)
1275
+ total_count = status.get("total_tokens", 0)
1276
+
1277
+ if healthy_count == total_count:
1278
+ message_class = "bg-green-100 border-green-400 text-green-700"
1279
+ message = f"所有 {total_count} 个 Token 均健康!"
1280
+ elif healthy_count > 0:
1281
+ message_class = "bg-blue-100 border-blue-400 text-blue-700"
1282
+ message = f"健康检查完成:{healthy_count}/{total_count} 个 Token 健康。"
1283
+ else:
1284
+ message_class = "bg-red-100 border-red-400 text-red-700"
1285
+ message = f"警告:0/{total_count} 个 Token 健康,请检查配置。"
1286
+
1287
+ return HTMLResponse(f"""
1288
+ <div class="{message_class} border px-4 py-3 rounded relative" role="alert">
1289
+ <strong class="font-bold">健康检查完成!</strong>
1290
+ <span class="block sm:inline">{message}</span>
1291
+ </div>
1292
+ """)
1293
+
1294
+
1295
+ @router.post(
1296
+ "/tokens/sync-pool",
1297
+ dependencies=[Depends(require_auth), Depends(require_csrf)],
1298
+ )
1299
+ async def sync_token_pool():
1300
+ """手动同步 Token 池(从数据库重新加载)"""
1301
+ from app.utils.token_pool import get_token_pool
1302
+
1303
+ pool = get_token_pool()
1304
+
1305
+ if not pool:
1306
+ return HTMLResponse("""
1307
+ <div class="bg-yellow-100 border border-yellow-400 text-yellow-700 px-4 py-3 rounded relative" role="alert">
1308
+ <strong class="font-bold">提示!</strong>
1309
+ <span class="block sm:inline">Token 池未初始化,请重启服务。</span>
1310
+ </div>
1311
+ """)
1312
+
1313
+ # 从数据库同步
1314
+ await pool.sync_from_database(DEFAULT_TOKEN_NAMESPACE)
1315
+
1316
+ # 获取同步后的状态
1317
+ status = await pool.get_pool_status()
1318
+ total_count = status.get("total_tokens", 0)
1319
+ available_count = status.get("available_tokens", 0)
1320
+ user_count = status.get("user_tokens", 0)
1321
+
1322
+ logger.info(
1323
+ f"✅ Token 池手动同步完成,总计 {total_count} 个 Token, 可用 {available_count} 个, 认证用户 {user_count} 个"
1324
+ )
1325
+
1326
+ if total_count == 0:
1327
+ message_class = "bg-yellow-100 border-yellow-400 text-yellow-700"
1328
+ message = "同步完成:当前没有可用 Token,请在数据库中启用 Token。"
1329
+ elif available_count == 0:
1330
+ message_class = "bg-orange-100 border-orange-400 text-orange-700"
1331
+ message = f"同步完成:共 {total_count} 个 Token,但无可用 Token(可能都已禁用)。"
1332
+ else:
1333
+ message_class = "bg-green-100 border-green-400 text-green-700"
1334
+ message = f"同步完成:共 {total_count} 个 Token,{available_count} 个可用,{user_count} 个认证用户。"
1335
+
1336
+ return HTMLResponse(f"""
1337
+ <div class="{message_class} border px-4 py-3 rounded relative" role="alert">
1338
+ <strong class="font-bold">Token 池同步完成!</strong>
1339
+ <span class="block sm:inline">{message}</span>
1340
+ </div>
1341
+ """)
1342
+
1343
+
1344
+ # ==================== 模型管理 API ====================
1345
+
1346
+ @router.post(
1347
+ "/models/refresh",
1348
+ dependencies=[Depends(require_auth), Depends(require_csrf)],
1349
+ )
1350
+ async def refresh_online_models():
1351
+ """手动刷新在线模型列表(从上游拉取并重新解析变体)。"""
1352
+ from app.core.openai import get_upstream_client
1353
+
1354
+ client = get_upstream_client()
1355
+ # 强制清除缓存时间,使 get_online_models 重新请求上游
1356
+ client._online_models_time = 0.0
1357
+
1358
+ try:
1359
+ models = await client.get_online_models()
1360
+ count = len(models)
1361
+ supported = client.get_supported_models()
1362
+ variant_count = len(supported)
1363
+
1364
+ return _with_hx_trigger(
1365
+ _build_alert(
1366
+ f"从上游获取 {count} 个模型,生成 {variant_count} 个变体。",
1367
+ title="模型刷新成功!",
1368
+ level="success",
1369
+ ),
1370
+ "admin-models-refresh",
1371
+ )
1372
+ except Exception as exc:
1373
+ log_exception(logger, "❌ 在线模型刷新失败")
1374
+ return _build_alert(
1375
+ f"刷新失败: {exc}",
1376
+ title="错误!",
1377
+ level="error",
1378
+ status_code=500,
1379
+ )
app/admin/auth.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 管理后台认证中间件
3
+ """
4
+ from fastapi import Request, HTTPException, status
5
+ from typing import Optional
6
+ import secrets
7
+ import base64
8
+ import hmac
9
+ import json
10
+ import time
11
+
12
+ from app.core.config import settings
13
+
14
+ # Session 有效期(小时)
15
+ SESSION_EXPIRE_HOURS = 24
16
+ SESSION_COOKIE_NAME = "admin_session"
17
+ CSRF_COOKIE_NAME = "admin_csrf"
18
+ CSRF_HEADER_NAME = "X-CSRF-Token"
19
+
20
+ LOGIN_WINDOW_SECONDS = 300
21
+ LOGIN_MAX_ATTEMPTS = 5
22
+ _login_attempts: dict[str, list[float]] = {}
23
+
24
+ # ── Session 吊销黑名单(进程内存,重启后清空)─────────────────────────────
25
+ # 键: session token 原始字符串, 值: 吊销时间戳
26
+ _revoked_sessions: dict[str, float] = {}
27
+ _last_prune_time: float = 0.0
28
+ _PRUNE_INTERVAL = 60.0
29
+
30
+
31
+ def _sign_payload(payload: str) -> str:
32
+ secret = settings.SESSION_SECRET_KEY or ""
33
+ return hmac.new(secret.encode("utf-8"), payload.encode("utf-8"), "sha256").hexdigest()
34
+
35
+
36
+ def _encode_session(payload: dict) -> str:
37
+ raw = json.dumps(payload, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
38
+ b64 = base64.urlsafe_b64encode(raw).decode("utf-8").rstrip("=")
39
+ signature = _sign_payload(b64)
40
+ return f"{b64}.{signature}"
41
+
42
+
43
+ def _decode_session(token: str) -> Optional[dict]:
44
+ if not token or "." not in token:
45
+ return None
46
+ b64, signature = token.split(".", 1)
47
+ expected = _sign_payload(b64)
48
+ if not hmac.compare_digest(signature, expected):
49
+ return None
50
+ padded = b64 + "=" * (-len(b64) % 4)
51
+ try:
52
+ raw = base64.urlsafe_b64decode(padded.encode("utf-8"))
53
+ return json.loads(raw.decode("utf-8"))
54
+ except Exception:
55
+ return None
56
+
57
+
58
+ def _now() -> float:
59
+ return time.time()
60
+
61
+
62
+ def _prune_attempts(attempts: list[float]) -> list[float]:
63
+ cutoff = _now() - LOGIN_WINDOW_SECONDS
64
+ return [ts for ts in attempts if ts >= cutoff]
65
+
66
+
67
+ def check_login_rate_limit(client_id: str) -> bool:
68
+ attempts = _login_attempts.get(client_id, [])
69
+ attempts = _prune_attempts(attempts)
70
+ if attempts:
71
+ _login_attempts[client_id] = attempts
72
+ else:
73
+ _login_attempts.pop(client_id, None)
74
+ return len(attempts) < LOGIN_MAX_ATTEMPTS
75
+
76
+
77
+ def record_login_failure(client_id: str) -> None:
78
+ attempts = _login_attempts.get(client_id, [])
79
+ attempts = _prune_attempts(attempts)
80
+ attempts.append(_now())
81
+ _login_attempts[client_id] = attempts
82
+
83
+
84
+ def reset_login_failures(client_id: str) -> None:
85
+ _login_attempts.pop(client_id, None)
86
+
87
+
88
+ def create_session(password: str) -> Optional[str]:
89
+ """
90
+ 创建 session
91
+
92
+ Args:
93
+ password: 用户输入的密码
94
+
95
+ Returns:
96
+ session_token 或 None(密码错误)
97
+ """
98
+ # 常数时间密码比较,防止时序侧信道
99
+ if not hmac.compare_digest(password.encode("utf-8"), settings.ADMIN_PASSWORD.encode("utf-8")):
100
+ return None
101
+
102
+ issued_at = int(_now())
103
+ expires_at = int((_now() + SESSION_EXPIRE_HOURS * 3600))
104
+ payload = {
105
+ "iat": issued_at,
106
+ "exp": expires_at,
107
+ "auth": True,
108
+ # 每个 session 携带唯一 jti,确保吊销时能精确匹配
109
+ "jti": secrets.token_hex(16),
110
+ }
111
+ return _encode_session(payload)
112
+
113
+
114
+ def verify_session(session_token: Optional[str]) -> bool:
115
+ """
116
+ 验证 session 是否有效
117
+
118
+ Args:
119
+ session_token: Session token
120
+
121
+ Returns:
122
+ 是否已认证
123
+ """
124
+ if not session_token:
125
+ return False
126
+
127
+ # 惰性清理:距上次清理超过 _PRUNE_INTERVAL 秒时顺便执行
128
+ now = _now()
129
+ global _last_prune_time
130
+ if now - _last_prune_time > _PRUNE_INTERVAL:
131
+ _prune_revoked_sessions()
132
+ _last_prune_time = now
133
+
134
+ # 检查吊销黑名单
135
+ if session_token in _revoked_sessions:
136
+ return False
137
+
138
+ session = _decode_session(session_token)
139
+ if not session:
140
+ return False
141
+
142
+ exp = session.get("exp")
143
+ if isinstance(exp, (int, float)) and _now() > float(exp):
144
+ return False
145
+
146
+ return bool(session.get("auth"))
147
+
148
+
149
+ def delete_session(session_token: Optional[str]) -> None:
150
+ """将 session token 加入吊销黑名单(真正的登出)"""
151
+ if session_token:
152
+ _revoked_sessions[session_token] = _now()
153
+ _prune_revoked_sessions()
154
+
155
+
156
+ def _prune_revoked_sessions() -> None:
157
+ """清理已过期的黑名单条目(避免内存无限增长)"""
158
+ cutoff = _now() - SESSION_EXPIRE_HOURS * 3600
159
+ expired_keys = [k for k, ts in _revoked_sessions.items() if ts < cutoff]
160
+ for k in expired_keys:
161
+ del _revoked_sessions[k]
162
+
163
+
164
+ def get_session_token_from_request(request: Request) -> Optional[str]:
165
+ """从请求中获取 session token"""
166
+ return request.cookies.get(SESSION_COOKIE_NAME)
167
+
168
+
169
+ # ── CSRF: 绑�� Session 的 Double Submit Cookie ────────────────────────────
170
+ # 格式: <random_part>.<hmac_tag>
171
+ # hmac_tag = HMAC-SHA256(secret, random_part + ":" + session_token)[0:16]
172
+ # 这样即使攻击者能注入任意 Cookie,也无法伪造与当前 Session 绑定的 CSRF token
173
+
174
+ def generate_csrf_token(session_token: str) -> str:
175
+ """生成与 Session 密码学绑定的 CSRF token"""
176
+ random_part = secrets.token_urlsafe(32)
177
+ secret = settings.SESSION_SECRET_KEY or ""
178
+ tag = hmac.new(
179
+ secret.encode("utf-8"),
180
+ f"{random_part}:{session_token}".encode("utf-8"),
181
+ "sha256",
182
+ ).hexdigest()[:16]
183
+ return f"{random_part}.{tag}"
184
+
185
+
186
+ def verify_csrf_token(csrf_token: str, session_token: str) -> bool:
187
+ """校验 CSRF token 是否与当前 Session 匹配"""
188
+ if not csrf_token or "." not in csrf_token:
189
+ return False
190
+ random_part, tag = csrf_token.rsplit(".", 1)
191
+ secret = settings.SESSION_SECRET_KEY or ""
192
+ expected_tag = hmac.new(
193
+ secret.encode("utf-8"),
194
+ f"{random_part}:{session_token}".encode("utf-8"),
195
+ "sha256",
196
+ ).hexdigest()[:16]
197
+ return hmac.compare_digest(tag, expected_tag)
198
+
199
+
200
+ def get_csrf_token_from_request(request: Request) -> Optional[str]:
201
+ """从请求中获取 CSRF token(Cookie)"""
202
+ return request.cookies.get(CSRF_COOKIE_NAME)
203
+
204
+
205
+ def get_csrf_header_from_request(request: Request) -> Optional[str]:
206
+ return request.headers.get(CSRF_HEADER_NAME)
207
+
208
+
209
+ async def require_auth(request: Request):
210
+ """
211
+ 认证依赖项:要求用户已登录
212
+
213
+ 在路由中使用:
214
+ @router.get("/admin", dependencies=[Depends(require_auth)])
215
+ """
216
+ session_token = get_session_token_from_request(request)
217
+
218
+ if not verify_session(session_token):
219
+ # 未认证,重定向到登录页
220
+ raise HTTPException(
221
+ status_code=status.HTTP_303_SEE_OTHER,
222
+ detail="未登录",
223
+ headers={"Location": "/admin/login"}
224
+ )
225
+
226
+
227
+ async def require_csrf(request: Request):
228
+ """CSRF 保护,仅针对非安全方法(POST/PUT/DELETE/PATCH)"""
229
+ if request.method.upper() in {"GET", "HEAD", "OPTIONS"}:
230
+ return
231
+
232
+ session_token = get_session_token_from_request(request)
233
+ csrf_cookie = get_csrf_token_from_request(request)
234
+ csrf_header = get_csrf_header_from_request(request)
235
+
236
+ # header 必须与 cookie 一致(Double Submit)
237
+ if not csrf_cookie or not csrf_header or not hmac.compare_digest(csrf_cookie, csrf_header):
238
+ raise HTTPException(
239
+ status_code=status.HTTP_403_FORBIDDEN,
240
+ detail="Invalid CSRF token",
241
+ )
242
+
243
+ # 进一步验证 token 是否与当前 Session 绑定(防 Cookie 注入绕过)
244
+ if not session_token or not verify_csrf_token(csrf_cookie, session_token):
245
+ raise HTTPException(
246
+ status_code=status.HTTP_403_FORBIDDEN,
247
+ detail="Invalid CSRF token",
248
+ )
249
+
250
+
251
+ def get_authenticated_user(request: Request) -> bool:
252
+ """
253
+ 获取当前认证状态(用于模板)
254
+
255
+ Returns:
256
+ 是否已认证
257
+ """
258
+ session_token = get_session_token_from_request(request)
259
+ return verify_session(session_token)
260
+
261
+
262
+ def cleanup_expired_sessions():
263
+ """清理过期的黑名单条目(定时任务调用)"""
264
+ _prune_revoked_sessions()
265
+ return len(_revoked_sessions)
app/admin/config_manager.py ADDED
@@ -0,0 +1,1121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Admin config metadata and helpers for the configuration console."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+ from typing import Any, Awaitable, Callable, Mapping
9
+
10
+ from dotenv import dotenv_values
11
+
12
+ from app.core.config import settings
13
+ from app.utils.env_file import update_env_file
14
+ from app.utils.logger import logger
15
+
16
+ ENV_PATH = Path(".env")
17
+ ENV_EXAMPLE_PATH = Path(".env.example")
18
+ _ENV_SOURCE_LINE_PATTERN = re.compile(
19
+ r"^\s*(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*\s*=.*$"
20
+ )
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class ConfigFieldSpec:
25
+ key: str
26
+ label: str
27
+ description: str
28
+ value_type: str
29
+ default_value: object
30
+ input_type: str = "text"
31
+ placeholder: str = ""
32
+ required: bool = False
33
+ wide: bool = False
34
+ sensitive: bool = False
35
+ restart_required: bool = False
36
+ min_value: int | None = None
37
+ max_value: int | None = None
38
+ db_persist: bool = True
39
+ options: tuple[str, ...] = () # 仅 input_type="select" 时使用
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class ConfigSectionSpec:
44
+ id: str
45
+ title: str
46
+ description: str
47
+ fields: tuple[ConfigFieldSpec, ...]
48
+ icon: str = ""
49
+
50
+
51
+ CONFIG_SECTIONS: tuple[ConfigSectionSpec, ...] = (
52
+ ConfigSectionSpec(
53
+ id="access",
54
+ title="接入与认证",
55
+ description="控制上游接口地址、客户端鉴权和 Function Call 行为。",
56
+ icon="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z",
57
+ fields=(
58
+ ConfigFieldSpec(
59
+ key="API_ENDPOINT",
60
+ label="上游 API 地址",
61
+ description="代理请求实际转发到的上游聊天完成接口。",
62
+ value_type="str",
63
+ default_value="https://chat.z.ai/api/v2/chat/completions",
64
+ input_type="url",
65
+ placeholder="https://chat.z.ai/api/v2/chat/completions",
66
+ required=True,
67
+ wide=True,
68
+ ),
69
+ ConfigFieldSpec(
70
+ key="RESIN_COMPAT_ENABLED",
71
+ label="启用 Resin 兼容账号头",
72
+ description="为出站请求附加 X-Resin-Account,并使用上游 token 的稳定哈希值作为账号,便于 Resin 按同一 token 复用出口 IP。",
73
+ value_type="bool",
74
+ default_value=False,
75
+ ),
76
+ ConfigFieldSpec(
77
+ key="AUTH_TOKEN",
78
+ label="客户端认证密钥",
79
+ description="客户端访问本服务时使用的 Bearer Token。",
80
+ value_type="str",
81
+ default_value="sk-your-api-key",
82
+ input_type="password",
83
+ placeholder="sk-your-api-key",
84
+ wide=True,
85
+ sensitive=True,
86
+ ),
87
+ ConfigFieldSpec(
88
+ key="SKIP_AUTH_TOKEN",
89
+ label="跳过客户端认证",
90
+ description="仅建议开发环境使用,开启后不校验 AUTH_TOKEN。",
91
+ value_type="bool",
92
+ default_value=False,
93
+ ),
94
+ ConfigFieldSpec(
95
+ key="UPSTREAM_BACKGROUND_TASKS",
96
+ label="上游背景任务",
97
+ description="是否允许上游执行标题生成、搜索总结等背景任务(开启可能消耗更多额度/时间)。",
98
+ value_type="bool",
99
+ default_value=False,
100
+ ),
101
+ ConfigFieldSpec(
102
+ key="SESSION_ENABLED",
103
+ label="会话管理",
104
+ description="启用官方链式会话复用,关闭则每次请求使用独立会话。",
105
+ value_type="bool",
106
+ default_value=False,
107
+ ),
108
+ ConfigFieldSpec(
109
+ key="SESSION_SYSTEM_INJECT",
110
+ label="System 注入模式",
111
+ description="控制 system 提示词是否并入用户消息。",
112
+ value_type="bool",
113
+ default_value=False,
114
+ ),
115
+ ConfigFieldSpec(
116
+ key="PRECREATE_CHAT",
117
+ label="预创建 Chat ID",
118
+ description="直接模式下通过上游接口预创建 chat_id,而非使用随机 UUID。仅在关闭会话管理时生效。",
119
+ value_type="bool",
120
+ default_value=False,
121
+ ),
122
+ ),
123
+ ),
124
+ ConfigSectionSpec(
125
+ id="server",
126
+ title="服务运行",
127
+ description="服务监听、日志、数据库路径和反向代理前缀。",
128
+ fields=(
129
+ ConfigFieldSpec(
130
+ key="SERVICE_NAME",
131
+ label="服务名称",
132
+ description="显示在进程列表中的服务名称。",
133
+ value_type="str",
134
+ default_value="api-proxy-server",
135
+ placeholder="api-proxy-server",
136
+ required=True,
137
+ restart_required=True,
138
+ db_persist=False,
139
+ ),
140
+ ConfigFieldSpec(
141
+ key="LISTEN_PORT",
142
+ label="监听端口",
143
+ description="HTTP 服务监听端口。",
144
+ value_type="int",
145
+ default_value=8080,
146
+ input_type="number",
147
+ min_value=1,
148
+ max_value=65535,
149
+ required=True,
150
+ restart_required=True,
151
+ placeholder="8080",
152
+ db_persist=False,
153
+ ),
154
+ ConfigFieldSpec(
155
+ key="ROOT_PATH",
156
+ label="反向代理路径前缀",
157
+ description="例如 /api,部署在子路径时使用。",
158
+ value_type="str",
159
+ default_value="",
160
+ placeholder="/api",
161
+ restart_required=True,
162
+ db_persist=False,
163
+ ),
164
+ ConfigFieldSpec(
165
+ key="DEBUG_LOGGING",
166
+ label="启用调试日志",
167
+ description="开启后控制台和日志文件统一输出 DEBUG,并使用详细格式。",
168
+ value_type="bool",
169
+ default_value=False,
170
+ db_persist=False,
171
+ ),
172
+ ConfigFieldSpec(
173
+ key="LOG_FILE_PATH",
174
+ label="日志文件路径",
175
+ description="相对路径默认相对于项目根目录解析。",
176
+ value_type="str",
177
+ default_value="logs/app.log",
178
+ placeholder="logs/app.log",
179
+ wide=True,
180
+ db_persist=False,
181
+ ),
182
+ ConfigFieldSpec(
183
+ key="LOG_FILE_MAX_BYTES",
184
+ label="单个日志文件上限 (Bytes)",
185
+ description="超过该大小后自动轮转到备份文件。",
186
+ value_type="int",
187
+ default_value=5242880,
188
+ input_type="number",
189
+ min_value=1024,
190
+ placeholder="5242880",
191
+ db_persist=False,
192
+ ),
193
+ ConfigFieldSpec(
194
+ key="LOG_FILE_BACKUP_COUNT",
195
+ label="日志备份数量",
196
+ description="保留的轮转备份文件数量。",
197
+ value_type="int",
198
+ default_value=3,
199
+ input_type="number",
200
+ min_value=1,
201
+ placeholder="3",
202
+ db_persist=False,
203
+ ),
204
+ ConfigFieldSpec(
205
+ key="DB_PATH",
206
+ label="数据库路径",
207
+ description="SQLite 数据库文件位置。",
208
+ value_type="str",
209
+ default_value="tokens.db",
210
+ placeholder="tokens.db",
211
+ required=True,
212
+ wide=True,
213
+ restart_required=True,
214
+ db_persist=False,
215
+ ),
216
+ ConfigFieldSpec(
217
+ key="DATABASE_URL",
218
+ label="PostgreSQL 连接串",
219
+ description="(可选)如果使用 PostgreSQL,请填写形如 postgresql://user:pass@localhost:5432/dbname 的地址。留空则使用 SQLite。",
220
+ value_type="str",
221
+ default_value="",
222
+ placeholder="postgresql://user:pass@localhost:5432/dbname",
223
+ wide=True,
224
+ restart_required=True,
225
+ db_persist=False,
226
+ ),
227
+ ConfigFieldSpec(
228
+ key="MAX_UPLOAD_FILE_SIZE",
229
+ label="文件上传限制 (Bytes)",
230
+ description="允许上传到上游的最大文件大小(默认 10MB)。",
231
+ value_type="int",
232
+ default_value=10485760,
233
+ input_type="number",
234
+ min_value=0,
235
+ placeholder="10485760",
236
+ ),
237
+ ),
238
+ ),
239
+ ConfigSectionSpec(
240
+ id="tokens",
241
+ title="Token 池策略",
242
+ description="失败判定、恢复时间和自动导入、自动维护计划任务。",
243
+ icon="M4 7v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2H6c-1.1 0-2 .9-2 2zm0 4h16m-16 4h16",
244
+ fields=(
245
+ ConfigFieldSpec(
246
+ key="TOKEN_FAILURE_THRESHOLD",
247
+ label="失败阈值",
248
+ description="连续失败多少次后将 Token 标记为不可用。",
249
+ value_type="int",
250
+ default_value=3,
251
+ input_type="number",
252
+ min_value=1,
253
+ required=True,
254
+ restart_required=True,
255
+ ),
256
+ ConfigFieldSpec(
257
+ key="TOKEN_RECOVERY_TIMEOUT",
258
+ label="恢复超时(秒)",
259
+ description="失败 Token 重新参与调度前的等待时间。",
260
+ value_type="int",
261
+ default_value=1800,
262
+ input_type="number",
263
+ min_value=1,
264
+ required=True,
265
+ restart_required=True,
266
+ ),
267
+ ConfigFieldSpec(
268
+ key="TOKEN_LOAD_BALANCE_STRATEGY",
269
+ label="负载策略",
270
+ description="控制认证 Token 的分配方式:轮询、最少活跃请求优先,或平滑加权轮询。",
271
+ value_type="str",
272
+ default_value="smooth_weighted_round_robin",
273
+ input_type="select",
274
+ options=(
275
+ "round_robin",
276
+ "least_loaded",
277
+ "smooth_weighted_round_robin",
278
+ ),
279
+ required=True,
280
+ ),
281
+ ConfigFieldSpec(
282
+ key="TOKEN_AUTO_IMPORT_ENABLED",
283
+ label="启用自动导入",
284
+ description="按固定周期扫描服务端目录并导入 Token。",
285
+ value_type="bool",
286
+ default_value=False,
287
+ ),
288
+ ConfigFieldSpec(
289
+ key="TOKEN_AUTO_IMPORT_SOURCE_DIR",
290
+ label="自动导入目录",
291
+ description="服务端本地目录,开启自动导入时需要可访问。",
292
+ value_type="str",
293
+ default_value="",
294
+ placeholder="E:\\tokens\\input",
295
+ wide=True,
296
+ ),
297
+ ConfigFieldSpec(
298
+ key="TOKEN_AUTO_IMPORT_INTERVAL",
299
+ label="自动导入间隔(秒)",
300
+ description="自动导入的扫描周期。",
301
+ value_type="int",
302
+ default_value=300,
303
+ input_type="number",
304
+ min_value=1,
305
+ required=True,
306
+ ),
307
+ ConfigFieldSpec(
308
+ key="TOKEN_AUTO_MAINTENANCE_ENABLED",
309
+ label="启用自动维护",
310
+ description="定时执行去重、健康检查和删除失效 Token。",
311
+ value_type="bool",
312
+ default_value=False,
313
+ ),
314
+ ConfigFieldSpec(
315
+ key="TOKEN_AUTO_MAINTENANCE_INTERVAL",
316
+ label="自动维护间隔(秒)",
317
+ description="自动维护的执行周期。",
318
+ value_type="int",
319
+ default_value=1800,
320
+ input_type="number",
321
+ min_value=1,
322
+ required=True,
323
+ ),
324
+ ConfigFieldSpec(
325
+ key="TOKEN_AUTO_REMOVE_DUPLICATES",
326
+ label="自动去重",
327
+ description="自动维护时清理重复 Token。",
328
+ value_type="bool",
329
+ default_value=True,
330
+ ),
331
+ ConfigFieldSpec(
332
+ key="TOKEN_AUTO_HEALTH_CHECK",
333
+ label="自动健康检查",
334
+ description="自动维护时验证 Token 可用性。",
335
+ value_type="bool",
336
+ default_value=True,
337
+ ),
338
+ ConfigFieldSpec(
339
+ key="TOKEN_AUTO_DELETE_INVALID",
340
+ label="自动删除失效 Token",
341
+ description="自动维护时移除已验证为无效的 Token。",
342
+ value_type="bool",
343
+ default_value=False,
344
+ ),
345
+ ),
346
+ ),
347
+ ConfigSectionSpec(
348
+ id="guest",
349
+ title="匿名 Guest 会话池",
350
+ description="没有用户 Token 时,控制匿名会话池的容量和维护策略。",
351
+ icon="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z",
352
+ fields=(
353
+ ConfigFieldSpec(
354
+ key="ANONYMOUS_MODE",
355
+ label="启用匿名模式",
356
+ description="无可用用户 Token 时允许使用匿名会话。",
357
+ value_type="bool",
358
+ default_value=True,
359
+ restart_required=True,
360
+ ),
361
+ ConfigFieldSpec(
362
+ key="GUEST_POOL_SIZE",
363
+ label="Guest 池容量",
364
+ description="启动和维持的 guest 会话数量。",
365
+ value_type="int",
366
+ default_value=3,
367
+ input_type="number",
368
+ min_value=1,
369
+ required=True,
370
+ restart_required=True,
371
+ ),
372
+ ConfigFieldSpec(
373
+ key="GUEST_SESSION_MAX_AGE",
374
+ label="Guest 最大存活时间(秒)",
375
+ description="单个 guest 会话的最长存活时长。",
376
+ value_type="int",
377
+ default_value=480,
378
+ input_type="number",
379
+ min_value=1,
380
+ required=True,
381
+ restart_required=True,
382
+ ),
383
+ ConfigFieldSpec(
384
+ key="GUEST_POOL_MAINTENANCE_INTERVAL",
385
+ label="Guest 维护间隔(秒)",
386
+ description="后台维护匿名会话池的频率。",
387
+ value_type="int",
388
+ default_value=30,
389
+ input_type="number",
390
+ min_value=1,
391
+ required=True,
392
+ restart_required=True,
393
+ ),
394
+ ConfigFieldSpec(
395
+ key="GUEST_CLEANUP_PARALLELISM",
396
+ label="清理并行度",
397
+ description="并行回收空闲 guest 会话的数量。",
398
+ value_type="int",
399
+ default_value=4,
400
+ input_type="number",
401
+ min_value=1,
402
+ required=True,
403
+ restart_required=True,
404
+ ),
405
+ ConfigFieldSpec(
406
+ key="GUEST_HTTP_MAX_KEEPALIVE_CONNECTIONS",
407
+ label="Keep-Alive 连接数",
408
+ description="guest 会话 HTTP 连接池 keep-alive 上限。",
409
+ value_type="int",
410
+ default_value=20,
411
+ input_type="number",
412
+ min_value=1,
413
+ required=True,
414
+ restart_required=True,
415
+ ),
416
+ ConfigFieldSpec(
417
+ key="GUEST_HTTP_MAX_CONNECTIONS",
418
+ label="HTTP 总连接数",
419
+ description="guest 会话 HTTP 连接池的总连接数上限。",
420
+ value_type="int",
421
+ default_value=50,
422
+ input_type="number",
423
+ min_value=1,
424
+ required=True,
425
+ restart_required=True,
426
+ ),
427
+ ),
428
+ ),
429
+ ConfigSectionSpec(
430
+ id="models",
431
+ title="模型设置",
432
+ description="在线模型自动解析与变体生成。模型列表从上游拉取后自动生成 Thinking / Search / Agent / advanced-search 变体。",
433
+ icon="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4",
434
+ fields=(
435
+ ConfigFieldSpec(
436
+ key="MODEL_BLACKLIST",
437
+ label="模型黑名单",
438
+ description="逗号分隔的上游模型 ID 列表,解析在线模型时跳过这些模型。例如:glm-4-flash,test-model",
439
+ value_type="str",
440
+ default_value="glm-4-flash",
441
+ placeholder="glm-4-flash",
442
+ wide=True,
443
+ ),
444
+ ConfigFieldSpec(
445
+ key="MODEL_ALIASES",
446
+ label="模型别名映射",
447
+ description="自定义别名,让客户端可以用自定义名称访问模型。格式:别名=目标模型名,逗号分隔。例如:gpt-4o=GLM-5,gpt-4o-mini=GLM-4.7",
448
+ value_type="str",
449
+ default_value="",
450
+ placeholder="gpt-4o=GLM-5,gpt-4o-mini=GLM-4.7",
451
+ wide=True,
452
+ ),
453
+ ConfigFieldSpec(
454
+ key="MODEL_AUTO_REFRESH_HOURS",
455
+ label="自动刷新周期(小时)",
456
+ description="定时从上游拉取在线模型列表并重新生成变体。设为 0 表示禁用自动刷新,仅手动刷新。",
457
+ value_type="int",
458
+ input_type="number",
459
+ default_value=0,
460
+ placeholder="0",
461
+ min_value=0,
462
+ max_value=168,
463
+ restart_required=True,
464
+ ),
465
+ ),
466
+ ),
467
+ ConfigSectionSpec(
468
+ id="proxy",
469
+ title="网络代理",
470
+ description="用于所有上游访问的全局网络代理配置。",
471
+ icon="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9",
472
+ fields=(
473
+ ConfigFieldSpec(
474
+ key="HTTP_PROXY",
475
+ label="代理服务器地址",
476
+ description="统一代理,支持 http://, https://, socks5:// 等格式。例如:http://127.0.0.1:10808 或 socks5://127.0.0.1:1080。",
477
+ value_type="str",
478
+ default_value="",
479
+ wide=True,
480
+ ),
481
+ ),
482
+ ),
483
+ ConfigSectionSpec(
484
+ id="timeouts",
485
+ title="超时控制",
486
+ description="系统各环节的超时时间(单位:秒)。支持小数,修改即时生效。",
487
+ icon="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z",
488
+ fields=(
489
+ ConfigFieldSpec(
490
+ key="HTTP_CONNECT_TIMEOUT",
491
+ label="连接超时",
492
+ description="建立 TCP/TLS 连接的最大时间。",
493
+ value_type="float",
494
+ default_value=5.0,
495
+ input_type="number",
496
+ min_value=0.1,
497
+ placeholder="5.0",
498
+ db_persist=False,
499
+ ),
500
+ ConfigFieldSpec(
501
+ key="HTTP_WRITE_TIMEOUT",
502
+ label="写入超时",
503
+ description="向网络套接字写入请求数据的最大时间。",
504
+ value_type="float",
505
+ default_value=10.0,
506
+ input_type="number",
507
+ min_value=0.1,
508
+ placeholder="10.0",
509
+ db_persist=False,
510
+ ),
511
+ ConfigFieldSpec(
512
+ key="HTTP_POOL_TIMEOUT",
513
+ label="连接池等待超时",
514
+ description="从 HTTP 连接池获取可用连接的最大等待时间。",
515
+ value_type="float",
516
+ default_value=5.0,
517
+ input_type="number",
518
+ min_value=0.1,
519
+ placeholder="5.0",
520
+ db_persist=False,
521
+ ),
522
+ ConfigFieldSpec(
523
+ key="HTTP_DEFAULT_READ_TIMEOUT",
524
+ label="非流式读取超时",
525
+ description="普通请求(如鉴权、获取模型列表)的单次读取超时时间。",
526
+ value_type="float",
527
+ default_value=60.0,
528
+ input_type="number",
529
+ min_value=1.0,
530
+ placeholder="60.0",
531
+ db_persist=False,
532
+ ),
533
+ ConfigFieldSpec(
534
+ key="HTTP_STREAM_READ_TIMEOUT",
535
+ label="流式单步读取超时",
536
+ description="流式聊天中,相邻两个数据块(chunk)之间允许的最大静默时间。",
537
+ value_type="float",
538
+ default_value=120.0,
539
+ input_type="number",
540
+ min_value=1.0,
541
+ placeholder="120.0",
542
+ db_persist=False,
543
+ ),
544
+ ConfigFieldSpec(
545
+ key="HTTP_MODEL_FETCH_TIMEOUT",
546
+ label="模型拉取超时",
547
+ description="请求上游 /v1/models 接口的超时时间。",
548
+ value_type="float",
549
+ default_value=10.0,
550
+ input_type="number",
551
+ min_value=1.0,
552
+ placeholder="10.0",
553
+ db_persist=False,
554
+ ),
555
+ ConfigFieldSpec(
556
+ key="CHAT_TOTAL_TIMEOUT",
557
+ label="非流式端到端总超时",
558
+ description="单次非流式聊天请求的总处理时间上限(包含所有内部重试)。",
559
+ value_type="float",
560
+ default_value=300.0,
561
+ input_type="number",
562
+ min_value=1.0,
563
+ placeholder="300.0",
564
+ db_persist=False,
565
+ wide=True,
566
+ ),
567
+ ConfigFieldSpec(
568
+ key="HTTP_STREAM_TOTAL_TIMEOUT",
569
+ label="流式端到端总超时",
570
+ description="单次流式聊天请求的总处理时间上限(包含首包等待及所有抛出数据的总耗时)。",
571
+ value_type="float",
572
+ default_value=600.0,
573
+ input_type="number",
574
+ min_value=1.0,
575
+ placeholder="600.0",
576
+ db_persist=False,
577
+ wide=True,
578
+ ),
579
+ ),
580
+ ),
581
+ ConfigSectionSpec(
582
+ id="captcha",
583
+ title="Captcha 验证码",
584
+ description="控制验证码服务的启用、地址、超时和重试策略。Captcha token 由独立的 Captcha Token Service 通过浏览器生成。",
585
+ icon="M12 2L4 5v6.09c0 5.05 3.41 9.76 8 10.91 4.59-1.15 8-5.86 8-10.91V5l-8-3zm-1 13l-3-3 1.41-1.41L11 14.17l5.59-5.59L18 10l-7 5z",
586
+ fields=(
587
+ ConfigFieldSpec(
588
+ key="CAPTCHA_ENABLED",
589
+ label="启用 Captcha",
590
+ description="关闭后主服务不再调用 captcha 服务获取 verify_param。",
591
+ value_type="bool",
592
+ default_value=True,
593
+ ),
594
+ ConfigFieldSpec(
595
+ key="CAPTCHA_SERVICE_URL",
596
+ label="Captcha 服务地址",
597
+ description="独立部署的 Captcha Token Service 地址。",
598
+ value_type="str",
599
+ default_value="http://127.0.0.1:9000",
600
+ placeholder="http://127.0.0.1:9000",
601
+ wide=True,
602
+ ),
603
+ ConfigFieldSpec(
604
+ key="CAPTCHA_SERVICE_TIMEOUT",
605
+ label="Captcha 服务超时(秒)",
606
+ description="调用 captcha 服务的超时时间,包含浏览器生成 token 的时间。",
607
+ value_type="float",
608
+ default_value=18.0,
609
+ input_type="number",
610
+ min_value=1.0,
611
+ placeholder="18.0",
612
+ ),
613
+ ConfigFieldSpec(
614
+ key="CAPTCHA_MAX_RETRIES",
615
+ label="Captcha 最大重试次数",
616
+ description="captcha 验证失败时最多重试次数,每次重试会重新获取 token。",
617
+ value_type="int",
618
+ default_value=3,
619
+ input_type="number",
620
+ min_value=1,
621
+ placeholder="3",
622
+ ),
623
+ ),
624
+ ),
625
+ ConfigSectionSpec(
626
+ id="admin",
627
+ title="后台安全",
628
+ description="管理后台密码和会话密钥。修改后建议重新登录。",
629
+ icon="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z",
630
+ fields=(
631
+ ConfigFieldSpec(
632
+ key="ADMIN_PASSWORD",
633
+ label="后台密码",
634
+ description="管理后台登录密码。",
635
+ value_type="str",
636
+ default_value="admin123",
637
+ input_type="password",
638
+ placeholder="admin123",
639
+ required=True,
640
+ sensitive=True,
641
+ ),
642
+ ConfigFieldSpec(
643
+ key="SESSION_SECRET_KEY",
644
+ label="会话密钥",
645
+ description="用于后台会话签名的密钥。",
646
+ value_type="str",
647
+ default_value="your-secret-key-change-in-production",
648
+ input_type="password",
649
+ placeholder="your-secret-key-change-in-production",
650
+ required=True,
651
+ sensitive=True,
652
+ wide=True,
653
+ ),
654
+ ),
655
+ ),
656
+ ConfigSectionSpec(
657
+ id="personalization",
658
+ title="上游个性化",
659
+ description="配置发送给上游的用户画像变量,用于自定义模型回复风格。",
660
+ icon="M5.121 17.804A13.937 13.937 0 0112 16c2.5 0 4.847.655 6.879 1.804M15 10a3 3 0 11-6 0 3 3 0 016 0zm6 2a9 9 0 11-18 0 9 9 0 0118 0z",
661
+ fields=(
662
+ ConfigFieldSpec(
663
+ key="UPSTREAM_USER_NAME",
664
+ label="用户名称",
665
+ description="上游上下文中的 {{USER_NAME}} 变量。",
666
+ value_type="str",
667
+ default_value="Guest",
668
+ ),
669
+ ConfigFieldSpec(
670
+ key="UPSTREAM_USER_LOCATION",
671
+ label="用户位置",
672
+ description="上游上下文中的 {{USER_LOCATION}} 变量。",
673
+ value_type="str",
674
+ default_value="Unknown",
675
+ ),
676
+ ConfigFieldSpec(
677
+ key="UPSTREAM_USER_TIMEZONE",
678
+ label="用户时区",
679
+ description="上游上下文中的 {{CURRENT_TIMEZONE}} 变量。",
680
+ value_type="str",
681
+ default_value="Asia/Shanghai",
682
+ ),
683
+ ConfigFieldSpec(
684
+ key="UPSTREAM_USER_LANGUAGE",
685
+ label="用户语言",
686
+ description="上游上下文中的 {{USER_LANGUAGE}} 变量。",
687
+ value_type="str",
688
+ default_value="zh-CN",
689
+ ),
690
+ ),
691
+ ),
692
+ )
693
+
694
+ CONFIG_FIELD_SPECS = {
695
+ field.key: field
696
+ for section in CONFIG_SECTIONS
697
+ for field in section.fields
698
+ }
699
+ MANAGED_ENV_KEYS = tuple(CONFIG_FIELD_SPECS.keys())
700
+ DB_PERSIST_KEYS = frozenset(
701
+ key for key, field in CONFIG_FIELD_SPECS.items() if field.db_persist
702
+ )
703
+ ReloadCallback = Callable[[], Awaitable[None]]
704
+
705
+
706
+ def read_env_content(env_path: str | Path = ENV_PATH) -> str:
707
+ path = Path(env_path)
708
+ if not path.exists():
709
+ return ""
710
+ return path.read_text(encoding="utf-8")
711
+
712
+
713
+ def get_config_source_snapshot(
714
+ *,
715
+ env_values: Mapping[str, str] | None = None,
716
+ db_values: Mapping[str, Any] | None = None,
717
+ keys: tuple[str, ...] = (),
718
+ ) -> dict[str, dict[str, Any]]:
719
+ snapshot: dict[str, dict[str, Any]] = {}
720
+ db_items = db_values or {}
721
+ source_env = env_values or {}
722
+
723
+ for key in keys:
724
+ field = CONFIG_FIELD_SPECS.get(key)
725
+ if field is None:
726
+ continue
727
+ snapshot[key] = {
728
+ "env": source_env.get(key, "<unset>"),
729
+ "db": db_items.get(key, "<unset>"),
730
+ "db_persist": field.db_persist,
731
+ }
732
+
733
+ return snapshot
734
+
735
+
736
+ def validate_env_source(content: str) -> str:
737
+ normalized = content.replace("\r\n", "\n").replace("\r", "\n")
738
+
739
+ for line_number, line in enumerate(normalized.splitlines(), start=1):
740
+ stripped = line.strip()
741
+ if not stripped or stripped.startswith("#"):
742
+ continue
743
+ if not _ENV_SOURCE_LINE_PATTERN.match(line):
744
+ raise ValueError(
745
+ f"第 {line_number} 行不是合法的 KEY=VALUE 格式。"
746
+ )
747
+
748
+ return normalized
749
+
750
+
751
+ def _serialize_config_value(value: object) -> str:
752
+ """将 Python 值序列化为数据库存储的字符串。"""
753
+ if isinstance(value, bool):
754
+ return "true" if value else "false"
755
+ if value is None:
756
+ return ""
757
+ return str(value)
758
+
759
+
760
+ def _parse_db_value(raw: str, value_type: str) -> Any:
761
+ """按字段类型解析数据库中的字符串值。"""
762
+ if value_type == "bool":
763
+ return raw.lower() in ("true", "1", "yes")
764
+ if value_type == "int":
765
+ try:
766
+ return int(raw)
767
+ except (ValueError, TypeError):
768
+ return None
769
+ if value_type == "float":
770
+ try:
771
+ return float(raw)
772
+ except (ValueError, TypeError):
773
+ return None
774
+ return raw
775
+
776
+
777
+ def _is_valid_option_value(field: ConfigFieldSpec, value: Any) -> bool:
778
+ if field.input_type != "select" or not field.options:
779
+ return True
780
+ return str(value or "") in field.options
781
+
782
+
783
+ def _is_valid_db_override_value(field: ConfigFieldSpec, raw_value: str) -> bool:
784
+ parsed = _parse_db_value(raw_value, field.value_type)
785
+ if parsed is None and field.value_type != "str":
786
+ return False
787
+ return _is_valid_option_value(field, parsed)
788
+
789
+
790
+ async def load_db_overrides() -> dict[str, Any]:
791
+ """从数据库加载可持久化的配置值,按类型解析后返回。
792
+
793
+ 仅返回解析成功且属于 DB_PERSIST_KEYS 的条目。
794
+ 如果数据库不可用则静默返回空字典。
795
+ """
796
+ try:
797
+ from app.services.config_dao import get_config_dao
798
+
799
+ dao = get_config_dao()
800
+ raw_items = await dao.get_all()
801
+ except Exception as exc:
802
+ logger.debug(
803
+ "读取数据库配置失败,回退到环境变量",
804
+ exc_info=settings.DEBUG_LOGGING,
805
+ )
806
+ return {}
807
+
808
+ overrides: dict[str, Any] = {}
809
+ for key, raw_value in raw_items.items():
810
+ if key not in DB_PERSIST_KEYS:
811
+ continue
812
+ field = CONFIG_FIELD_SPECS.get(key)
813
+ if field is None:
814
+ continue
815
+ parsed = _parse_db_value(raw_value, field.value_type)
816
+ if not _is_valid_db_override_value(field, raw_value):
817
+ logger.warning("忽略无效的数据库配置项: %s=%s", key, raw_value)
818
+ continue
819
+ if parsed is not None or field.value_type == "str":
820
+ overrides[key] = parsed
821
+ return overrides
822
+
823
+
824
+ async def apply_db_overrides(settings_obj: Any = settings) -> None:
825
+ """从数据库加载配置并覆盖到 settings 对象上。"""
826
+ overrides = await load_db_overrides()
827
+ for key, value in overrides.items():
828
+ setattr(settings_obj, key, value)
829
+ if overrides:
830
+ logger.debug("已从数据库加载 %s 项配置覆盖", len(overrides))
831
+
832
+
833
+ def build_config_page_data(
834
+ *,
835
+ settings_obj: Any = settings,
836
+ env_path: str | Path = ENV_PATH,
837
+ env_example_path: str | Path = ENV_EXAMPLE_PATH,
838
+ db_values: dict[str, str] | None = None,
839
+ ) -> dict[str, Any]:
840
+ env_file = Path(env_path)
841
+ env_content = read_env_content(env_file)
842
+ env_values = dotenv_values(env_file) if env_file.exists() else {}
843
+ valid_db_keys = {
844
+ key
845
+ for key, raw_value in (db_values or {}).items()
846
+ if (
847
+ (field := CONFIG_FIELD_SPECS.get(key)) is not None
848
+ and _is_valid_db_override_value(field, raw_value)
849
+ )
850
+ }
851
+ sections: list[dict[str, Any]] = []
852
+ total_fields = 0
853
+ overridden_fields = 0
854
+ sensitive_fields = 0
855
+ restart_required_fields = 0
856
+
857
+ for section in CONFIG_SECTIONS:
858
+ rendered_fields: list[dict[str, Any]] = []
859
+ for field in section.fields:
860
+ total_fields += 1
861
+ if field.sensitive:
862
+ sensitive_fields += 1
863
+ if field.restart_required:
864
+ restart_required_fields += 1
865
+
866
+ # 判断来源优先级:数据库 > .env > 默认值
867
+ in_db = field.key in valid_db_keys
868
+ in_env = field.key in env_values
869
+ if in_db:
870
+ source_label = "数据库"
871
+ source_badge_class = (
872
+ "bg-blue-50 text-blue-700 ring-blue-200"
873
+ )
874
+ overridden_fields += 1
875
+ elif in_env:
876
+ source_label = ".env"
877
+ source_badge_class = (
878
+ "bg-emerald-50 text-emerald-700 ring-emerald-200"
879
+ )
880
+ overridden_fields += 1
881
+ else:
882
+ source_label = "默认值"
883
+ source_badge_class = (
884
+ "bg-slate-100 text-slate-600 ring-slate-200"
885
+ )
886
+
887
+ value = getattr(settings_obj, field.key, field.default_value)
888
+ if value is None:
889
+ value = ""
890
+
891
+ rendered_fields.append(
892
+ {
893
+ "key": field.key,
894
+ "label": field.label,
895
+ "description": field.description,
896
+ "value_type": field.value_type,
897
+ "value": value,
898
+ "input_type": field.input_type,
899
+ "placeholder": field.placeholder,
900
+ "required": field.required,
901
+ "wide": field.wide,
902
+ "sensitive": field.sensitive,
903
+ "restart_required": field.restart_required,
904
+ "min_value": field.min_value,
905
+ "max_value": field.max_value,
906
+ "source_label": source_label,
907
+ "source_badge_class": source_badge_class,
908
+ "options": field.options,
909
+ }
910
+ )
911
+
912
+ sections.append(
913
+ {
914
+ "id": section.id,
915
+ "title": section.title,
916
+ "description": section.description,
917
+ "icon": section.icon,
918
+ "fields": rendered_fields,
919
+ "field_count": len(rendered_fields),
920
+ }
921
+ )
922
+
923
+ return {
924
+ "sections": sections,
925
+ "env_content": env_content,
926
+ "overview": {
927
+ "total_sections": len(CONFIG_SECTIONS),
928
+ "total_fields": total_fields,
929
+ "overridden_fields": overridden_fields,
930
+ "default_fields": total_fields - overridden_fields,
931
+ "sensitive_fields": sensitive_fields,
932
+ "restart_required_fields": restart_required_fields,
933
+ "env_exists": env_file.exists(),
934
+ "env_path": str(env_file.resolve()),
935
+ "env_line_count": len(env_content.splitlines()) if env_content else 0,
936
+ "example_exists": Path(env_example_path).exists(),
937
+ },
938
+ }
939
+
940
+
941
+ def build_form_updates(form_data: Mapping[str, Any]) -> dict[str, object]:
942
+ updates: dict[str, object] = {}
943
+
944
+ for key in MANAGED_ENV_KEYS:
945
+ field = CONFIG_FIELD_SPECS[key]
946
+
947
+ if field.value_type == "bool":
948
+ updates[key] = key in form_data
949
+ continue
950
+
951
+ raw_value = str(form_data.get(key, "") or "").strip()
952
+ if field.required and raw_value == "":
953
+ raise ValueError(f"{field.label} 不能为空。")
954
+
955
+ if field.value_type == "int":
956
+ try:
957
+ parsed = int(raw_value)
958
+ except ValueError as exc:
959
+ raise ValueError(f"{field.label} 必须是整数。") from exc
960
+
961
+ if field.min_value is not None and parsed < field.min_value:
962
+ raise ValueError(
963
+ f"{field.label} 不能小于 {field.min_value}。"
964
+ )
965
+ if field.max_value is not None and parsed > field.max_value:
966
+ raise ValueError(
967
+ f"{field.label} 不能大于 {field.max_value}。"
968
+ )
969
+ updates[key] = parsed
970
+ continue
971
+
972
+ if field.value_type == "float":
973
+ try:
974
+ parsed_float = float(raw_value)
975
+ except ValueError as exc:
976
+ raise ValueError(f"{field.label} 必须是数字。") from exc
977
+
978
+ if field.min_value is not None and parsed_float < field.min_value:
979
+ raise ValueError(
980
+ f"{field.label} 不能小于 {field.min_value}。"
981
+ )
982
+ if field.max_value is not None and parsed_float > field.max_value:
983
+ raise ValueError(
984
+ f"{field.label} 不能大于 {field.max_value}。"
985
+ )
986
+ updates[key] = parsed_float
987
+ continue
988
+
989
+ if field.input_type == "select" and field.options and raw_value not in field.options:
990
+ raise ValueError(
991
+ f"{field.label} 必须是以下选项之一:{', '.join(field.options)}。"
992
+ )
993
+
994
+ updates[key] = raw_value
995
+
996
+ return updates
997
+
998
+
999
+ async def _apply_env_change(
1000
+ writer: Callable[[Path], None],
1001
+ *,
1002
+ reload_callback: ReloadCallback,
1003
+ env_path: str | Path = ENV_PATH,
1004
+ ) -> None:
1005
+ path = Path(env_path)
1006
+ had_existing_file = path.exists()
1007
+ previous_content = read_env_content(path) if had_existing_file else ""
1008
+
1009
+ try:
1010
+ writer(path)
1011
+ await reload_callback()
1012
+ except Exception:
1013
+ if had_existing_file:
1014
+ path.write_text(previous_content, encoding="utf-8")
1015
+ elif path.exists():
1016
+ path.unlink()
1017
+
1018
+ try:
1019
+ await reload_callback()
1020
+ except Exception as restore_exc:
1021
+ logger.warning(f"⚠️ 回滚配置后重新加载失败: {restore_exc}")
1022
+ raise
1023
+
1024
+
1025
+ async def save_form_config(
1026
+ form_data: Mapping[str, Any],
1027
+ *,
1028
+ reload_callback: ReloadCallback,
1029
+ env_path: str | Path = ENV_PATH,
1030
+ ) -> dict[str, object]:
1031
+ updates = build_form_updates(form_data)
1032
+
1033
+ # 分流:db_persist=True → 数据库,其余 → .env
1034
+ db_updates: dict[str, str] = {}
1035
+ env_updates: dict[str, object] = {}
1036
+ for key, value in updates.items():
1037
+ if key in DB_PERSIST_KEYS:
1038
+ db_updates[key] = _serialize_config_value(value)
1039
+ else:
1040
+ env_updates[key] = value
1041
+
1042
+ # 写入数据库
1043
+ if db_updates:
1044
+ try:
1045
+ from app.services.config_dao import get_config_dao
1046
+
1047
+ dao = get_config_dao()
1048
+ await dao.set_many(db_updates)
1049
+ logger.debug("已保存 %s 项配置到数据库", len(db_updates))
1050
+ except Exception as exc:
1051
+ logger.warning(
1052
+ "⚠️ 数据库保存失败,回退到环境变量",
1053
+ exc_info=settings.DEBUG_LOGGING,
1054
+ )
1055
+ env_updates.update(updates) # fallback: 全部写入 .env
1056
+ db_updates.clear()
1057
+
1058
+ # 写入 .env(仅非数据库字段或回退字段)
1059
+ if env_updates:
1060
+ async def _reload() -> None:
1061
+ await reload_callback()
1062
+
1063
+ def _writer(target_path: Path) -> None:
1064
+ update_env_file(env_updates, env_path=target_path)
1065
+
1066
+ await _apply_env_change(
1067
+ _writer, reload_callback=_reload, env_path=env_path
1068
+ )
1069
+ else:
1070
+ # 即使没有 env 变更,也需要重新加载以应用 DB 值
1071
+ await reload_callback()
1072
+
1073
+ return updates
1074
+
1075
+
1076
+ async def save_source_config(
1077
+ env_content: str,
1078
+ *,
1079
+ reload_callback: ReloadCallback,
1080
+ env_path: str | Path = ENV_PATH,
1081
+ ) -> None:
1082
+ normalized = validate_env_source(env_content)
1083
+
1084
+ def _writer(target_path: Path) -> None:
1085
+ content = normalized.rstrip("\n")
1086
+ target_path.write_text(
1087
+ f"{content}\n" if content else "",
1088
+ encoding="utf-8",
1089
+ )
1090
+
1091
+ await _apply_env_change(
1092
+ _writer,
1093
+ reload_callback=reload_callback,
1094
+ env_path=env_path,
1095
+ )
1096
+
1097
+
1098
+ async def reset_env_to_example(
1099
+ *,
1100
+ reload_callback: ReloadCallback,
1101
+ env_path: str | Path = ENV_PATH,
1102
+ env_example_path: str | Path = ENV_EXAMPLE_PATH,
1103
+ ) -> None:
1104
+ example_path = Path(env_example_path)
1105
+ if not example_path.exists():
1106
+ raise FileNotFoundError(".env.example 不存在")
1107
+
1108
+ example_content = example_path.read_text(encoding="utf-8")
1109
+
1110
+ def _writer(target_path: Path) -> None:
1111
+ content = example_content.rstrip("\n")
1112
+ target_path.write_text(
1113
+ f"{content}\n" if content else "",
1114
+ encoding="utf-8",
1115
+ )
1116
+
1117
+ await _apply_env_change(
1118
+ _writer,
1119
+ reload_callback=reload_callback,
1120
+ env_path=env_path,
1121
+ )
app/admin/routes.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 管理后台路由模块
3
+ """
4
+ from datetime import datetime
5
+
6
+ from fastapi import APIRouter, Depends, Request
7
+ from fastapi.responses import HTMLResponse
8
+
9
+ from app.admin.auth import require_auth
10
+ from app.admin.config_manager import build_config_page_data
11
+ from app.admin.stats import (
12
+ DEFAULT_TREND_WINDOW,
13
+ TREND_WINDOW_OPTIONS,
14
+ collect_admin_stats,
15
+ get_process_uptime,
16
+ )
17
+ from app.admin.template_loader import templates
18
+ from app.utils.logger import logger, log_exception
19
+
20
+ router = APIRouter(prefix="/admin", tags=["admin"])
21
+ DEFAULT_TOKEN_NAMESPACE = "zai"
22
+
23
+
24
+ def _page_headers() -> dict[str, str]:
25
+ return {
26
+ "Cache-Control": "no-store, no-cache, must-revalidate, max-age=0",
27
+ "Pragma": "no-cache",
28
+ "Expires": "0",
29
+ }
30
+
31
+
32
+ def _base_context(request: Request) -> dict:
33
+ return {
34
+ "request": request,
35
+ "root_path": request.scope.get("root_path", ""),
36
+ }
37
+
38
+
39
+ @router.get("/login", response_class=HTMLResponse)
40
+ async def login_page(request: Request):
41
+ """登录页面"""
42
+ try:
43
+ return templates.TemplateResponse(
44
+ request,
45
+ "login.html",
46
+ _base_context(request),
47
+ headers=_page_headers(),
48
+ )
49
+ except Exception:
50
+ log_exception(logger, "渲染管理后台登录页失败")
51
+ return HTMLResponse(
52
+ "<h1>Admin login page failed to render</h1>",
53
+ status_code=500,
54
+ headers=_page_headers(),
55
+ )
56
+
57
+
58
+ @router.get("/", response_class=HTMLResponse, dependencies=[Depends(require_auth)])
59
+ async def dashboard(request: Request):
60
+ """仪表盘首页"""
61
+ try:
62
+ stats = await collect_admin_stats(
63
+ DEFAULT_TOKEN_NAMESPACE,
64
+ trend_window=DEFAULT_TREND_WINDOW,
65
+ )
66
+ stats["uptime"] = get_process_uptime()
67
+
68
+ context = {
69
+ **_base_context(request),
70
+ "stats": stats,
71
+ "current_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
72
+ "trend_windows": TREND_WINDOW_OPTIONS,
73
+ }
74
+
75
+ return templates.TemplateResponse(
76
+ request,
77
+ "index.html",
78
+ context,
79
+ headers=_page_headers(),
80
+ )
81
+ except Exception:
82
+ log_exception(logger, "渲染管理后台仪表盘失败")
83
+ raise
84
+
85
+
86
+ @router.get(
87
+ "/config",
88
+ response_class=HTMLResponse,
89
+ dependencies=[Depends(require_auth)],
90
+ )
91
+ async def config_page(request: Request):
92
+ """配置管理页面"""
93
+ try:
94
+ # 加载数据库中的配置值,用于展示来源标识
95
+ try:
96
+ from app.services.config_dao import get_config_dao
97
+
98
+ dao = get_config_dao()
99
+ db_values = await dao.get_all()
100
+ except Exception:
101
+ db_values = {}
102
+
103
+ page_data = build_config_page_data(db_values=db_values)
104
+
105
+ # 模型状态数据
106
+ model_list = []
107
+ model_parsed = False
108
+ try:
109
+ from app.core.openai import get_upstream_client_if_ready
110
+
111
+ client = get_upstream_client_if_ready()
112
+ if client:
113
+ mgr = client._model_manager
114
+ model_parsed = mgr._parsed
115
+ for name in mgr.get_supported_models():
116
+ caps = mgr.get_model_capabilities(name)
117
+ upstream_id = mgr.get_upstream_model_id(name) or ""
118
+ mcp = mgr.get_mcp_servers(name)
119
+ scene = mgr.get_scene_defaults(name)
120
+ model_list.append({
121
+ "name": name,
122
+ "upstream_id": upstream_id,
123
+ "tool_use": caps.get("tool_use", False),
124
+ "vision": caps.get("vision", False),
125
+ "thinking": caps.get("thinking", False),
126
+ "web_search": caps.get("web_search", False),
127
+ "agent": caps.get("agent", False),
128
+ "mcp_servers": mcp,
129
+ "scene_defaults": scene,
130
+ })
131
+ except Exception:
132
+ pass
133
+
134
+ context = {
135
+ **_base_context(request),
136
+ "sections": page_data["sections"],
137
+ "env_content": page_data["env_content"],
138
+ "overview": page_data["overview"],
139
+ "model_list": model_list,
140
+ "model_parsed": model_parsed,
141
+ "model_count": len(model_list),
142
+ }
143
+ return templates.TemplateResponse(
144
+ request,
145
+ "config.html",
146
+ context,
147
+ headers=_page_headers(),
148
+ )
149
+ except Exception:
150
+ log_exception(logger, "渲染管理后台配置页失败")
151
+ raise
152
+
153
+
154
+ @router.get("/request-logs", response_class=HTMLResponse, dependencies=[Depends(require_auth)])
155
+ async def request_logs_page(request: Request):
156
+ """请求日志页面"""
157
+ try:
158
+ return templates.TemplateResponse(
159
+ request,
160
+ "request_logs.html",
161
+ _base_context(request),
162
+ headers=_page_headers(),
163
+ )
164
+ except Exception:
165
+ log_exception(logger, "渲染管理后台请求日志页失败")
166
+ raise
167
+
168
+
169
+ @router.get("/runtime-logs", response_class=HTMLResponse, dependencies=[Depends(require_auth)])
170
+ async def runtime_logs_page(request: Request):
171
+ """运行日志页面"""
172
+ try:
173
+ return templates.TemplateResponse(
174
+ request,
175
+ "runtime_logs.html",
176
+ _base_context(request),
177
+ headers=_page_headers(),
178
+ )
179
+ except Exception:
180
+ log_exception(logger, "渲染管理后台运行日志页失败")
181
+ raise
182
+
183
+
184
+ @router.get(
185
+ "/tokens",
186
+ response_class=HTMLResponse,
187
+ dependencies=[Depends(require_auth)],
188
+ )
189
+ async def tokens_page(request: Request):
190
+ """Token 管理页面"""
191
+ try:
192
+ from app.core.config import settings
193
+
194
+ maintenance_actions: list[str] = []
195
+ if settings.TOKEN_AUTO_REMOVE_DUPLICATES:
196
+ maintenance_actions.append("删除重复 Token")
197
+ if settings.TOKEN_AUTO_HEALTH_CHECK:
198
+ maintenance_actions.append("批量测活")
199
+ if settings.TOKEN_AUTO_DELETE_INVALID:
200
+ maintenance_actions.append("删除失效 Token")
201
+
202
+ context = {
203
+ **_base_context(request),
204
+ "automation": {
205
+ "config_url": f"{request.scope.get('root_path', '')}/admin/config#tokens",
206
+ "import_enabled": settings.TOKEN_AUTO_IMPORT_ENABLED,
207
+ "import_source_dir": settings.TOKEN_AUTO_IMPORT_SOURCE_DIR,
208
+ "import_interval": settings.TOKEN_AUTO_IMPORT_INTERVAL,
209
+ "has_import_source_dir": bool(
210
+ settings.TOKEN_AUTO_IMPORT_SOURCE_DIR.strip()
211
+ ),
212
+ "maintenance_enabled": settings.TOKEN_AUTO_MAINTENANCE_ENABLED,
213
+ "maintenance_interval": settings.TOKEN_AUTO_MAINTENANCE_INTERVAL,
214
+ "maintenance_actions": maintenance_actions,
215
+ "has_maintenance_actions": bool(maintenance_actions),
216
+ "load_balance_strategy": settings.TOKEN_LOAD_BALANCE_STRATEGY,
217
+ },
218
+ }
219
+ return templates.TemplateResponse(
220
+ request,
221
+ "tokens.html",
222
+ context,
223
+ headers=_page_headers(),
224
+ )
225
+ except Exception:
226
+ log_exception(logger, "渲染管理后台 Token 页失败")
227
+ raise
app/admin/stats.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """管理后台统计聚合辅助函数。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import time
7
+ from typing import Any, Dict, Optional
8
+
9
+ try:
10
+ import psutil
11
+ except ImportError:
12
+ psutil = None
13
+
14
+ from app.services.request_log_dao import RequestLogDAO, get_request_log_dao
15
+ from app.services.token_dao import TokenDAO, get_token_dao
16
+ from app.utils.format import format_compact_number
17
+ from app.utils.token_pool import TokenPool, get_token_pool
18
+
19
+ _TOKEN_POOL_SENTINEL = object()
20
+ DEFAULT_TREND_WINDOW = "7d"
21
+ TREND_WINDOW_OPTIONS = (
22
+ {"key": "24h", "label": "24 小时"},
23
+ {"key": "7d", "label": "7 天"},
24
+ {"key": "30d", "label": "30 天"},
25
+ )
26
+
27
+
28
+ def _coerce_int(value: Any) -> int:
29
+ """将数据库聚合结果安全转换为整数。"""
30
+ return int(value or 0)
31
+
32
+
33
+ def calculate_success_rate(
34
+ successful_requests: int,
35
+ total_requests: int,
36
+ ) -> float:
37
+ """计算成功率百分比。"""
38
+ if total_requests <= 0:
39
+ return 0.0
40
+ return round(successful_requests / total_requests * 100, 1)
41
+
42
+
43
+
44
+
45
+
46
+ def normalize_trend_window(value: Any) -> str:
47
+ """规范化趋势窗口参数,非法值回退到默认值。"""
48
+ normalized = str(value or "").strip().lower()
49
+ if normalized in {"24h", "7d", "30d"}:
50
+ return normalized
51
+ if normalized == "1d":
52
+ return "24h"
53
+ return DEFAULT_TREND_WINDOW
54
+
55
+
56
+ def format_uptime(total_seconds: int) -> str:
57
+ """格式化运行时长。"""
58
+ total_seconds = max(0, int(total_seconds))
59
+ days, remainder = divmod(total_seconds, 86400)
60
+ hours, remainder = divmod(remainder, 3600)
61
+ minutes, seconds = divmod(remainder, 60)
62
+
63
+ parts = []
64
+ if days:
65
+ parts.append(f"{days}天")
66
+ if days or hours:
67
+ parts.append(f"{hours}小时")
68
+ if days or hours or minutes:
69
+ parts.append(f"{minutes}分钟")
70
+ parts.append(f"{seconds}秒")
71
+
72
+ return " ".join(parts)
73
+
74
+
75
+ def get_process_uptime() -> str:
76
+ """获取当前进程运行时长。"""
77
+ if psutil is None:
78
+ return "未知"
79
+ created_at = psutil.Process(os.getpid()).create_time()
80
+ return format_uptime(int(time.time() - created_at))
81
+
82
+
83
+ async def collect_admin_stats(
84
+ provider: str,
85
+ *,
86
+ token_dao: Optional[TokenDAO] = None,
87
+ request_log_dao: Optional[RequestLogDAO] = None,
88
+ token_pool: Any = _TOKEN_POOL_SENTINEL,
89
+ trend_window: str = DEFAULT_TREND_WINDOW,
90
+ ) -> Dict[str, Any]:
91
+ """聚合管理后台所需的 Token 与请求统计。"""
92
+ token_dao = token_dao or get_token_dao()
93
+ request_log_dao = request_log_dao or get_request_log_dao()
94
+ if token_pool is _TOKEN_POOL_SENTINEL:
95
+ token_pool = get_token_pool()
96
+ trend_window = normalize_trend_window(trend_window)
97
+
98
+ token_counts = await token_dao.get_provider_token_counts(provider)
99
+ request_stats = await request_log_dao.get_provider_request_stats(provider)
100
+ usage_trend = await request_log_dao.get_provider_usage_trend(
101
+ provider,
102
+ window=trend_window,
103
+ )
104
+
105
+ pool_status: Dict[str, Any] = {}
106
+ if isinstance(token_pool, TokenPool) or hasattr(token_pool, "get_pool_status"):
107
+ pool_status = await token_pool.get_pool_status() if token_pool else {}
108
+
109
+ total_tokens = _coerce_int(token_counts.get("total_tokens"))
110
+ enabled_tokens = _coerce_int(token_counts.get("enabled_tokens"))
111
+ user_tokens = _coerce_int(token_counts.get("user_tokens"))
112
+ guest_tokens = _coerce_int(token_counts.get("guest_tokens"))
113
+ unknown_tokens = _coerce_int(token_counts.get("unknown_tokens"))
114
+
115
+ pool_total_tokens = _coerce_int(pool_status.get("total_tokens"))
116
+ if pool_total_tokens == 0 and token_pool is None:
117
+ pool_total_tokens = max(0, enabled_tokens - guest_tokens)
118
+
119
+ available_tokens = _coerce_int(pool_status.get("available_tokens"))
120
+ healthy_tokens = _coerce_int(pool_status.get("healthy_tokens"))
121
+ unhealthy_tokens = _coerce_int(pool_status.get("unhealthy_tokens"))
122
+
123
+ total_requests = _coerce_int(request_stats.get("total_requests"))
124
+ successful_requests = _coerce_int(request_stats.get("successful_requests"))
125
+ failed_requests = _coerce_int(request_stats.get("failed_requests"))
126
+ input_tokens = _coerce_int(request_stats.get("input_tokens"))
127
+ output_tokens = _coerce_int(request_stats.get("output_tokens"))
128
+ total_consumed_tokens = _coerce_int(request_stats.get("total_tokens"))
129
+ cache_creation_tokens = _coerce_int(
130
+ request_stats.get("cache_creation_tokens")
131
+ )
132
+ cache_read_tokens = _coerce_int(request_stats.get("cache_read_tokens"))
133
+ cache_creation_requests = _coerce_int(
134
+ request_stats.get("cache_creation_requests")
135
+ )
136
+ cache_hit_requests = _coerce_int(request_stats.get("cache_hit_requests"))
137
+ average_latency = round(float(request_stats.get("avg_duration") or 0.0), 2)
138
+ average_first_token_latency = round(
139
+ float(request_stats.get("avg_first_token_time") or 0.0),
140
+ 2,
141
+ )
142
+ total_cache_tokens = cache_creation_tokens + cache_read_tokens
143
+
144
+ return {
145
+ "total_tokens": total_tokens,
146
+ "enabled_tokens": enabled_tokens,
147
+ "user_tokens": user_tokens,
148
+ "guest_tokens": guest_tokens,
149
+ "unknown_tokens": unknown_tokens,
150
+ "pool_total_tokens": pool_total_tokens,
151
+ "available_tokens": available_tokens,
152
+ "healthy_tokens": healthy_tokens,
153
+ "unhealthy_tokens": unhealthy_tokens,
154
+ "total_requests": total_requests,
155
+ "successful_requests": successful_requests,
156
+ "failed_requests": failed_requests,
157
+ "input_tokens": input_tokens,
158
+ "output_tokens": output_tokens,
159
+ "total_consumed_tokens": total_consumed_tokens,
160
+ "cache_creation_tokens": cache_creation_tokens,
161
+ "cache_read_tokens": cache_read_tokens,
162
+ "total_cache_tokens": total_cache_tokens,
163
+ "cache_creation_requests": cache_creation_requests,
164
+ "cache_hit_requests": cache_hit_requests,
165
+ "average_latency": average_latency,
166
+ "average_first_token_latency": average_first_token_latency,
167
+ "trend_window": trend_window,
168
+ "usage_trend": usage_trend,
169
+ "total_consumed_tokens_display": format_compact_number(
170
+ total_consumed_tokens
171
+ ),
172
+ "total_cache_tokens_display": format_compact_number(
173
+ total_cache_tokens
174
+ ),
175
+ "input_tokens_display": format_compact_number(input_tokens),
176
+ "output_tokens_display": format_compact_number(output_tokens),
177
+ "success_rate": calculate_success_rate(
178
+ successful_requests,
179
+ total_requests,
180
+ ),
181
+ }
app/admin/template_loader.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+
3
+ from fastapi.templating import Jinja2Templates
4
+
5
+
6
+ TEMPLATES_DIR = Path(__file__).resolve().parent.parent / "templates"
7
+ templates = Jinja2Templates(directory=str(TEMPLATES_DIR))
app/core/__init__.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """app.core package.
5
+
6
+ Keep package import side effects minimal; callers should import the
7
+ submodules they actually use.
8
+ """
9
+
10
+ from importlib import import_module
11
+
12
+ __all__ = [
13
+ "config",
14
+ "file_upload",
15
+ "headers",
16
+ "http_client",
17
+ "models",
18
+ "openai",
19
+ "request_signing",
20
+ "response_handler",
21
+ "retry_policy",
22
+ ]
23
+
24
+
25
+ def __getattr__(name: str):
26
+ if name not in __all__:
27
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
28
+ module = import_module(f"{__name__}.{name}")
29
+ globals()[name] = module
30
+ return module
app/core/captcha_client.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """Captcha 服务客户端。
5
+
6
+ 通过 HTTP 调用独立的 Captcha Token Service 获取 captcha_verify_param。
7
+ 支持重试、超时、连接错误处理,与项目 SharedHttpClients 模式一致。
8
+ """
9
+
10
+ import asyncio
11
+ from typing import Optional
12
+
13
+ import httpx
14
+
15
+ from app.core.config import settings
16
+ from app.core.http_client import build_timeout, get_proxy_config
17
+ from app.utils.logger import logger
18
+
19
+
20
+ class CaptchaServiceError(Exception):
21
+ """Captcha 服务不可用(连接失败、超时、非 200 响应)。"""
22
+
23
+
24
+ class CaptchaTokenError(Exception):
25
+ """Captcha token 获取失败(服务返回错误)。"""
26
+
27
+
28
+ class CaptchaClient:
29
+ """Captcha Token Service 的 HTTP 客户端。
30
+
31
+ 按需调用远端 captcha 服务获取验证码 token,
32
+ 内置重试和指数退避。
33
+ """
34
+
35
+ def __init__(
36
+ self,
37
+ service_url: Optional[str] = None,
38
+ timeout: Optional[float] = None,
39
+ ) -> None:
40
+ self._service_url = (service_url or settings.CAPTCHA_SERVICE_URL).rstrip("/")
41
+ self._timeout = timeout or settings.CAPTCHA_SERVICE_TIMEOUT
42
+ self._client: Optional[httpx.AsyncClient] = None
43
+ self._max_retries = 3
44
+
45
+ @property
46
+ def token_url(self) -> str:
47
+ return f"{self._service_url}/token"
48
+
49
+ @property
50
+ def health_url(self) -> str:
51
+ return f"{self._service_url}/health"
52
+
53
+ async def _get_client(self) -> httpx.AsyncClient:
54
+ if self._client is None or self._client.is_closed:
55
+ self._client = httpx.AsyncClient(
56
+ timeout=build_timeout(read_timeout=self._timeout),
57
+ proxy=get_proxy_config(),
58
+ trust_env=False,
59
+ )
60
+ return self._client
61
+
62
+ async def get_token(self, jwt_token: str) -> str:
63
+ """获取一个新鲜的 captcha_verify_param。
64
+
65
+ Args:
66
+ jwt_token: 用户的 Z.ai JWT token。
67
+
68
+ Returns:
69
+ captcha_verify_param 字符串(base64 编码的 captcha 数据)。
70
+
71
+ Raises:
72
+ CaptchaServiceError: 服务不可用或超时。
73
+ CaptchaTokenError: 服务返回错误。
74
+ """
75
+ last_error: Optional[Exception] = None
76
+
77
+ for attempt in range(self._max_retries):
78
+ try:
79
+ client = await self._get_client()
80
+ response = await client.post(
81
+ self.token_url,
82
+ json={"jwt_token": jwt_token},
83
+ )
84
+
85
+ if response.status_code == 200:
86
+ data = response.json()
87
+ token = data.get("captcha_verify_param")
88
+ if token:
89
+ logger.info(
90
+ "[captcha] token obtained certify_id=%s attempt=%d",
91
+ data.get("certify_id", "unknown"),
92
+ attempt + 1,
93
+ )
94
+ return token
95
+ raise CaptchaTokenError(
96
+ f"Captcha service returned empty token: {data}"
97
+ )
98
+
99
+ error_text = response.text[:500]
100
+ if response.status_code == 503:
101
+ if attempt < self._max_retries - 1:
102
+ wait = 2 ** attempt
103
+ logger.warning(
104
+ "[captcha] service unavailable (503), retry in %ds (attempt %d/%d): %s",
105
+ wait, attempt + 1, self._max_retries, error_text,
106
+ )
107
+ await asyncio.sleep(wait)
108
+ last_error = CaptchaServiceError(
109
+ f"Captcha service unavailable: {error_text}"
110
+ )
111
+ continue
112
+ raise CaptchaServiceError(
113
+ f"Captcha service unavailable after {self._max_retries} attempts: {error_text}"
114
+ )
115
+
116
+ raise CaptchaTokenError(
117
+ f"Captcha service returned {response.status_code}: {error_text}"
118
+ )
119
+
120
+ except (httpx.ConnectError, httpx.ConnectTimeout, httpx.ReadTimeout) as e:
121
+ if attempt < self._max_retries - 1:
122
+ wait = 2 ** attempt
123
+ logger.warning(
124
+ "[captcha] connection failed, retry in %ds (attempt %d/%d): %s",
125
+ wait, attempt + 1, self._max_retries, e,
126
+ )
127
+ await asyncio.sleep(wait)
128
+ last_error = e
129
+ continue
130
+ raise CaptchaServiceError(
131
+ f"Cannot reach captcha service at {self._service_url}: {e}"
132
+ ) from e
133
+
134
+ except (CaptchaServiceError, CaptchaTokenError):
135
+ raise
136
+ except Exception as e:
137
+ if attempt < self._max_retries - 1:
138
+ wait = 2 ** attempt
139
+ logger.warning(
140
+ "[captcha] unexpected error, retry in %ds (attempt %d/%d): %s",
141
+ wait, attempt + 1, self._max_retries, e,
142
+ )
143
+ await asyncio.sleep(wait)
144
+ last_error = e
145
+ continue
146
+ raise CaptchaServiceError(f"Captcha client error: {e}") from e
147
+
148
+ raise CaptchaServiceError(
149
+ f"Failed to get captcha token after {self._max_retries} attempts"
150
+ ) from last_error
151
+
152
+ async def health(self) -> dict:
153
+ """检查 captcha 服务健康状态。"""
154
+ try:
155
+ client = await self._get_client()
156
+ response = await client.get(self.health_url)
157
+ return response.json() if response.status_code == 200 else {"status": "error"}
158
+ except Exception:
159
+ return {"status": "unreachable"}
160
+
161
+ async def close(self) -> None:
162
+ if self._client and not self._client.is_closed:
163
+ await self._client.aclose()
164
+
165
+
166
+ # Module-level singleton
167
+ _captcha_client: Optional[CaptchaClient] = None
168
+
169
+
170
+ def get_captcha_client() -> Optional[CaptchaClient]:
171
+ """获取 captcha 客户端单例。未初始化时返回 None。"""
172
+ return _captcha_client
173
+
174
+
175
+ def create_captcha_client(
176
+ service_url: Optional[str] = None,
177
+ timeout: Optional[float] = None,
178
+ ) -> CaptchaClient:
179
+ """创建并注册 captcha 客户端单例。"""
180
+ global _captcha_client
181
+ _captcha_client = CaptchaClient(service_url=service_url, timeout=timeout)
182
+ logger.info(
183
+ "[captcha] client initialized service_url=%s timeout=%s",
184
+ _captcha_client._service_url,
185
+ _captcha_client._timeout,
186
+ )
187
+ return _captcha_client
188
+
189
+
190
+ async def close_captcha_client() -> None:
191
+ """关闭 captcha 客户端连接。"""
192
+ global _captcha_client
193
+ if _captcha_client:
194
+ await _captcha_client.close()
195
+ _captcha_client = None
196
+ logger.info("[captcha] client closed")
app/core/chat_cleanup.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Background service for token chat cleanup."""
2
+
3
+ import asyncio
4
+ import time
5
+ from dataclasses import dataclass
6
+ from typing import Optional
7
+
8
+ from app.core.config import settings
9
+ from app.core.headers import build_dynamic_headers
10
+ from app.core.http_client import SharedHttpClients
11
+ from app.core.resin_compat import apply_resin_account_header
12
+ from app.core.upstream_urls import build_upstream_url
13
+ from app.services.token_dao import TokenDAO, get_token_dao
14
+ from app.utils.fe_version import get_latest_fe_version
15
+ from app.utils.logger import logger
16
+
17
+ @dataclass(frozen=True)
18
+ class ChatCleanupSummary:
19
+ total_checked: int = 0
20
+ success_count: int = 0
21
+ failed_count: int = 0
22
+
23
+ async def delete_chats_for_token(
24
+ token: str,
25
+ clients: Optional[SharedHttpClients] = None,
26
+ *,
27
+ token_id: Optional[int] = None,
28
+ ) -> bool:
29
+ """Delete all chat sessions for a given token."""
30
+ owns_clients = clients is None
31
+ if clients is None:
32
+ clients = SharedHttpClients()
33
+ client = clients.get_client()
34
+
35
+ fe_version = await get_latest_fe_version()
36
+ headers = build_dynamic_headers(fe_version)
37
+ headers["Authorization"] = f"Bearer {token}"
38
+ apply_resin_account_header(headers, token)
39
+ headers["Origin"] = "https://chat.z.ai"
40
+ headers["Referer"] = "https://chat.z.ai/"
41
+ chats_url = build_upstream_url("/api/v1/chats/")
42
+
43
+ started_at = time.perf_counter()
44
+ try:
45
+ response = await client.request(
46
+ method="DELETE",
47
+ url=chats_url,
48
+ headers=headers,
49
+ json=None
50
+ )
51
+ elapsed_ms = (time.perf_counter() - started_at) * 1000
52
+ logger.debug(
53
+ "[token.chat_cleanup] token_id=%s status=%s bytes=%s elapsed_ms=%.1f",
54
+ token_id,
55
+ response.status_code,
56
+ response.headers.get("content-length") or len(response.content or b""),
57
+ elapsed_ms,
58
+ )
59
+ if response.status_code == 200:
60
+ return True
61
+ logger.warning(
62
+ "⚠️ 清理会话失败 (Token ID: %s, Token: %s...): HTTP %s %s",
63
+ token_id,
64
+ token[:15],
65
+ response.status_code,
66
+ response.text,
67
+ )
68
+ return False
69
+ except Exception as e:
70
+ logger.warning(
71
+ "⚠️ 清理会话时发生错误 (Token ID: %s, Token: %s...)",
72
+ token_id,
73
+ token[:15],
74
+ exc_info=settings.DEBUG_LOGGING,
75
+ )
76
+ return False
77
+ finally:
78
+ if owns_clients:
79
+ await clients.close()
80
+
81
+ async def run_chat_cleanup(
82
+ interval_days: int,
83
+ dao: Optional[TokenDAO] = None
84
+ ) -> ChatCleanupSummary:
85
+ """Clean up chat sessions for tokens that haven't been cleaned in `interval_days`."""
86
+ token_dao = dao or get_token_dao()
87
+ started_at = time.perf_counter()
88
+
89
+ # 获取需要清理的 Token (启用的 zai Token)
90
+ tokens = await token_dao.get_tokens_needing_chat_cleanup("zai", interval_days)
91
+ if not tokens:
92
+ return ChatCleanupSummary()
93
+
94
+ logger.info(
95
+ "[token.chat_cleanup.batch] start total_tokens=%s mode=serial interval_days=%s",
96
+ len(tokens),
97
+ interval_days,
98
+ )
99
+ logger.info(f"🧹 开始执行周期会话清理,共有 {len(tokens)} 个 Token 到期需要清理")
100
+
101
+ success_count = 0
102
+ failed_count = 0
103
+ clients = SharedHttpClients()
104
+ try:
105
+ for token_record in tokens:
106
+ token_id = int(token_record["id"])
107
+ token_str = str(token_record["token"])
108
+
109
+ success = await delete_chats_for_token(
110
+ token_str,
111
+ clients=clients,
112
+ token_id=token_id,
113
+ )
114
+ if success:
115
+ await token_dao.update_last_chat_cleanup(token_id)
116
+ success_count += 1
117
+ logger.debug("成功清理 Token 的会话: id=%s", token_id)
118
+ else:
119
+ failed_count += 1
120
+ logger.debug("清理 Token 的会话失败: id=%s", token_id)
121
+
122
+ # 间隔2秒,避免并发过高或被风控
123
+ await asyncio.sleep(3.0)
124
+ finally:
125
+ await clients.close()
126
+
127
+ elapsed_ms = (time.perf_counter() - started_at) * 1000
128
+ logger.info(
129
+ "[token.chat_cleanup.batch] done total_tokens=%s success=%s failed=%s mode=serial elapsed_ms=%.1f",
130
+ len(tokens),
131
+ success_count,
132
+ failed_count,
133
+ elapsed_ms,
134
+ )
135
+
136
+ return ChatCleanupSummary(
137
+ total_checked=len(tokens),
138
+ success_count=success_count,
139
+ failed_count=failed_count
140
+ )
app/core/config.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ import os
5
+ from pathlib import Path
6
+ from typing import Optional
7
+
8
+ from pydantic_settings import BaseSettings
9
+ from dotenv import dotenv_values
10
+
11
+
12
+ _ENV_PATH = Path(__file__).resolve().parents[2] / ".env"
13
+ if _ENV_PATH.exists():
14
+ for _key, _value in dotenv_values(_ENV_PATH).items():
15
+ if _value is not None:
16
+ os.environ[_key] = _value
17
+ if _key == "HTTP_PROXY":
18
+ for _proxy_key in (
19
+ "HTTP_PROXY",
20
+ "http_proxy",
21
+ "HTTPS_PROXY",
22
+ "https_proxy",
23
+ "ALL_PROXY",
24
+ "all_proxy",
25
+ ):
26
+ os.environ[_proxy_key] = _value
27
+
28
+
29
+ class Settings(BaseSettings):
30
+ """Application settings"""
31
+
32
+ # API Configuration
33
+ API_ENDPOINT: str = "https://chat.z.ai/api/v2/chat/completions"
34
+ RESIN_COMPAT_ENABLED: bool = (
35
+ os.getenv("RESIN_COMPAT_ENABLED", "false").lower() == "true"
36
+ )
37
+
38
+ # Authentication
39
+ AUTH_TOKEN: Optional[str] = os.getenv("AUTH_TOKEN")
40
+
41
+ # Token池配置
42
+ TOKEN_FAILURE_THRESHOLD: int = int(os.getenv("TOKEN_FAILURE_THRESHOLD", "3")) # 失败3次后标记为不可用
43
+ TOKEN_RECOVERY_TIMEOUT: int = int(os.getenv("TOKEN_RECOVERY_TIMEOUT", "1800")) # 30分钟后重试失败的token
44
+ TOKEN_LOAD_BALANCE_STRATEGY: str = os.getenv(
45
+ "TOKEN_LOAD_BALANCE_STRATEGY",
46
+ "smooth_weighted_round_robin",
47
+ )
48
+ TOKEN_AUTO_IMPORT_ENABLED: bool = (
49
+ os.getenv("TOKEN_AUTO_IMPORT_ENABLED", "false").lower() == "true"
50
+ )
51
+ TOKEN_AUTO_IMPORT_SOURCE_DIR: str = os.getenv("TOKEN_AUTO_IMPORT_SOURCE_DIR", "")
52
+ TOKEN_AUTO_IMPORT_INTERVAL: int = int(
53
+ os.getenv("TOKEN_AUTO_IMPORT_INTERVAL", "300")
54
+ )
55
+ TOKEN_AUTO_MAINTENANCE_ENABLED: bool = (
56
+ os.getenv("TOKEN_AUTO_MAINTENANCE_ENABLED", "false").lower() == "true"
57
+ )
58
+ TOKEN_AUTO_MAINTENANCE_INTERVAL: int = int(
59
+ os.getenv("TOKEN_AUTO_MAINTENANCE_INTERVAL", "1800")
60
+ )
61
+ TOKEN_AUTO_REMOVE_DUPLICATES: bool = (
62
+ os.getenv("TOKEN_AUTO_REMOVE_DUPLICATES", "true").lower() == "true"
63
+ )
64
+ TOKEN_AUTO_HEALTH_CHECK: bool = (
65
+ os.getenv("TOKEN_AUTO_HEALTH_CHECK", "true").lower() == "true"
66
+ )
67
+ TOKEN_AUTO_DELETE_INVALID: bool = (
68
+ os.getenv("TOKEN_AUTO_DELETE_INVALID", "false").lower() == "true"
69
+ )
70
+
71
+ # Chat Cleanup
72
+ CHAT_CLEANUP_ENABLED: bool = (
73
+ os.getenv("CHAT_CLEANUP_ENABLED", "true").lower() == "true"
74
+ )
75
+ CHAT_CLEANUP_INTERVAL_DAYS: int = int(os.getenv("CHAT_CLEANUP_INTERVAL_DAYS", "7"))
76
+
77
+ # Request Log Cleanup
78
+ LOG_CLEANUP_INTERVAL_DAYS: int = int(os.getenv("LOG_CLEANUP_INTERVAL_DAYS", "1"))
79
+ LOG_RETENTION_DAYS: int = int(os.getenv("LOG_RETENTION_DAYS", "30"))
80
+
81
+ # Model Configuration
82
+ GLM45_MODEL: str = os.getenv("GLM45_MODEL", "GLM-4.5")
83
+ GLM45_THINKING_MODEL: str = os.getenv("GLM45_THINKING_MODEL", "GLM-4.5-Thinking")
84
+ GLM45_SEARCH_MODEL: str = os.getenv("GLM45_SEARCH_MODEL", "GLM-4.5-Search")
85
+ GLM45_AIR_MODEL: str = os.getenv("GLM45_AIR_MODEL", "GLM-4.5-Air")
86
+ GLM46V_MODEL: str = os.getenv("GLM46V_MODEL", "GLM-4.6V")
87
+ GLM46V_ADVANCED_SEARCH_MODEL: str = os.getenv("GLM46V_ADVANCED_SEARCH_MODEL", "GLM-4.6V-advanced-search")
88
+ GLM5_MODEL: str = os.getenv("GLM5_MODEL", "GLM-5")
89
+ GLM5_THINKING_MODEL: str = os.getenv("GLM5_THINKING_MODEL", "GLM-5-Thinking")
90
+ GLM5_AGENT_MODEL: str = os.getenv("GLM5_AGENT_MODEL", "GLM-5-Agent")
91
+ GLM5_ADVANCED_SEARCH_MODEL: str = os.getenv("GLM5_ADVANCED_SEARCH_MODEL", "GLM-5-advanced-search")
92
+ GLM47_MODEL: str = os.getenv("GLM47_MODEL", "GLM-4.7")
93
+ GLM47_THINKING_MODEL: str = os.getenv("GLM47_THINKING_MODEL", "GLM-4.7-Thinking")
94
+ GLM47_SEARCH_MODEL: str = os.getenv("GLM47_SEARCH_MODEL", "GLM-4.7-Search")
95
+ GLM47_ADVANCED_SEARCH_MODEL: str = os.getenv("GLM47_ADVANCED_SEARCH_MODEL", "GLM-4.7-advanced-search")
96
+ MODEL_BLACKLIST: str = os.getenv("MODEL_BLACKLIST", "glm-4-flash")
97
+ # 模型别名映射,格式:别名=目标模型名,逗号分隔。例如:gpt-4o=GLM-5,gpt-4o-mini=GLM-4.7
98
+ MODEL_ALIASES: str = os.getenv("MODEL_ALIASES", "")
99
+ # 在线模型自动刷新周期(小时),0 表示禁用自动刷新
100
+ MODEL_AUTO_REFRESH_HOURS: int = int(os.getenv("MODEL_AUTO_REFRESH_HOURS", "0"))
101
+
102
+ # Server Configuration
103
+ LISTEN_PORT: int = int(os.getenv("LISTEN_PORT", "8080"))
104
+ DEBUG_LOGGING: bool = os.getenv("DEBUG_LOGGING", "false").lower() == "true"
105
+ SERVICE_NAME: str = os.getenv("SERVICE_NAME", "api-proxy-server")
106
+ ROOT_PATH: str = os.getenv("ROOT_PATH", "") # For Nginx reverse proxy path prefix, e.g., "/api" or "/path-prefix"
107
+ LOG_FILE_PATH: str = os.getenv("LOG_FILE_PATH", "logs/app.log")
108
+ LOG_FILE_MAX_BYTES: int = int(
109
+ os.getenv("LOG_FILE_MAX_BYTES", str(5 * 1024 * 1024))
110
+ )
111
+ LOG_FILE_BACKUP_COUNT: int = int(os.getenv("LOG_FILE_BACKUP_COUNT", "3"))
112
+
113
+ ANONYMOUS_MODE: bool = os.getenv("ANONYMOUS_MODE", "true").lower() == "true"
114
+ GUEST_POOL_SIZE: int = int(os.getenv("GUEST_POOL_SIZE", "3"))
115
+ GUEST_SESSION_MAX_AGE: int = int(os.getenv("GUEST_SESSION_MAX_AGE", "480"))
116
+ GUEST_POOL_MAINTENANCE_INTERVAL: int = int(
117
+ os.getenv("GUEST_POOL_MAINTENANCE_INTERVAL", "30")
118
+ )
119
+ GUEST_CLEANUP_PARALLELISM: int = int(
120
+ os.getenv("GUEST_CLEANUP_PARALLELISM", "4")
121
+ )
122
+ GUEST_HTTP_MAX_KEEPALIVE_CONNECTIONS: int = int(
123
+ os.getenv("GUEST_HTTP_MAX_KEEPALIVE_CONNECTIONS", "20")
124
+ )
125
+ GUEST_HTTP_MAX_CONNECTIONS: int = int(
126
+ os.getenv("GUEST_HTTP_MAX_CONNECTIONS", "50")
127
+ )
128
+
129
+ # File Upload
130
+ # 上传文件大小限制(字节),默认 10MB,0 表示不限制
131
+ MAX_UPLOAD_FILE_SIZE: int = int(os.getenv("MAX_UPLOAD_FILE_SIZE", str(10 * 1024 * 1024)))
132
+
133
+ # Upstream User Variables
134
+ UPSTREAM_USER_NAME: str = os.getenv("UPSTREAM_USER_NAME", "User")
135
+ UPSTREAM_USER_LOCATION: str = os.getenv("UPSTREAM_USER_LOCATION", "Unknown")
136
+ UPSTREAM_USER_TIMEZONE: str = os.getenv("UPSTREAM_USER_TIMEZONE", "Asia/Shanghai")
137
+ UPSTREAM_USER_LANGUAGE: str = os.getenv("UPSTREAM_USER_LANGUAGE", "zh-CN")
138
+
139
+ # Upstream Background Tasks (title/tag generation)
140
+ # 代理场景下每次请求都是新 chat_id, 无需上游生成标题/标签
141
+ UPSTREAM_BACKGROUND_TASKS: bool = (
142
+ os.getenv("UPSTREAM_BACKGROUND_TASKS", "false").lower() == "true"
143
+ )
144
+
145
+ # Session / Continuous Conversation Configuration
146
+ SESSION_ENABLED: bool = os.getenv("SESSION_ENABLED", "false").lower() == "true"
147
+ SESSION_TTL: int = int(os.getenv("SESSION_TTL", "3600")) # 会话 TTL(秒)
148
+ SESSION_MAX_PER_CLIENT: int = int(os.getenv("SESSION_MAX_PER_CLIENT", "50")) # 每客户端最大会话数
149
+ SESSION_CLEANUP_INTERVAL: int = int(os.getenv("SESSION_CLEANUP_INTERVAL", "300")) # 清理间隔(秒)
150
+ SESSION_SYSTEM_INJECT: bool = os.getenv("SESSION_SYSTEM_INJECT", "false").lower() == "true"
151
+ SKIP_AUTH_TOKEN: bool = os.getenv("SKIP_AUTH_TOKEN", "false").lower() == "true"
152
+ PRECREATE_CHAT: bool = os.getenv("PRECREATE_CHAT", "false").lower() == "true"
153
+
154
+ # HTTP Timeout Configuration (单位: 秒)
155
+ HTTP_CONNECT_TIMEOUT: float = float(os.getenv("HTTP_CONNECT_TIMEOUT", "5.0"))
156
+ HTTP_WRITE_TIMEOUT: float = float(os.getenv("HTTP_WRITE_TIMEOUT", "10.0"))
157
+ HTTP_POOL_TIMEOUT: float = float(os.getenv("HTTP_POOL_TIMEOUT", "5.0"))
158
+ # 普通短请求 (鉴权/文件上传/模型列表) 的读取超时
159
+ HTTP_DEFAULT_READ_TIMEOUT: float = float(os.getenv("HTTP_DEFAULT_READ_TIMEOUT", "60.0"))
160
+ # 流式聊天的读取超时 (即相邻两个 chunk 之间允许的最大空闲时间)
161
+ HTTP_STREAM_READ_TIMEOUT: float = float(os.getenv("HTTP_STREAM_READ_TIMEOUT", "120.0"))
162
+ # 在线模型列表拉取超时
163
+ HTTP_MODEL_FETCH_TIMEOUT: float = float(os.getenv("HTTP_MODEL_FETCH_TIMEOUT", "10.0"))
164
+ # 非流式请求端到端总超时(含所有重试)
165
+ CHAT_TOTAL_TIMEOUT: float = float(os.getenv("CHAT_TOTAL_TIMEOUT", "300.0"))
166
+ # 流式请求端到端总超时(含所有重试)
167
+ HTTP_STREAM_TOTAL_TIMEOUT: float = float(os.getenv("HTTP_STREAM_TOTAL_TIMEOUT", "600.0"))
168
+ # 空回响应最大重试次数
169
+ EMPTY_RESPONSE_MAX_RETRIES: int = int(os.getenv("EMPTY_RESPONSE_MAX_RETRIES", "10"))
170
+
171
+ # Captcha Service Configuration
172
+ # 是否需要 captcha_verify_param(关闭后主服务不再调用 captcha 服务)
173
+ CAPTCHA_ENABLED: bool = (
174
+ os.getenv("CAPTCHA_ENABLED", "true").lower() == "true"
175
+ )
176
+ # Captcha token 服务的地址(独立部署时改为实际 IP:Port)
177
+ CAPTCHA_SERVICE_URL: str = os.getenv(
178
+ "CAPTCHA_SERVICE_URL", "http://127.0.0.1:9000"
179
+ )
180
+ # 调用 captcha 服务的超时时间(秒),包含浏览器生成 token 的时间
181
+ CAPTCHA_SERVICE_TIMEOUT: float = float(
182
+ os.getenv("CAPTCHA_SERVICE_TIMEOUT", "18.0")
183
+ )
184
+ # captcha 验证失败时最多重试次数(每次重试会重新获取 token)
185
+ CAPTCHA_MAX_RETRIES: int = int(os.getenv("CAPTCHA_MAX_RETRIES", "3"))
186
+
187
+ # Proxy Configuration (统一网络代理, 支持 HTTP/HTTPS/SOCKS5)
188
+ HTTP_PROXY: Optional[str] = os.getenv("HTTP_PROXY") # 统一代理, 默认使用本地 10808 端口
189
+
190
+ # Admin Panel Authentication
191
+ ADMIN_PASSWORD: str = os.getenv("ADMIN_PASSWORD", "admin123") # 管理后台密码
192
+ SESSION_SECRET_KEY: str = os.getenv("SESSION_SECRET_KEY", "your-secret-key-change-in-production") # Session 密钥
193
+ DB_PATH: str = os.getenv("DB_PATH", "tokens.db")
194
+ DATABASE_URL: Optional[str] = os.getenv("DATABASE_URL")
195
+
196
+ class Config:
197
+ env_file = ".env"
198
+ extra = "ignore" # 忽略额外字段,防止环境变量中的未知字段导致验证错误
199
+
200
+
201
+ settings = Settings()
app/core/error_handler.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """全局错误处理器。
5
+
6
+ 提供统一的异常处理机制:
7
+ - AppError 及其子类 → 结构化错误响应
8
+ - RequestValidationError → 验证错误响应
9
+ - HTTPException → 保持原有行为
10
+ - Exception → 兜底处理
11
+
12
+ 所有错误响应遵循 OpenAI API 格式。
13
+ """
14
+
15
+ import time
16
+ from typing import Any, Callable, Dict
17
+
18
+ from fastapi import Request, status
19
+ from fastapi.encoders import jsonable_encoder
20
+ from fastapi.exceptions import HTTPException, RequestValidationError
21
+ from fastapi.responses import JSONResponse
22
+
23
+ from app.exceptions import AppError
24
+ from app.utils.logger import logger, log_exception
25
+
26
+
27
+ # -----------------------------------------------------------------------
28
+ # OpenAI 兼容错误响应格式
29
+ # -----------------------------------------------------------------------
30
+
31
+ def create_error_response(
32
+ message: str,
33
+ error_type: str,
34
+ code: str,
35
+ status_code: int = 500,
36
+ details: Dict[str, Any] | None = None,
37
+ ) -> Dict[str, Any]:
38
+ """创建 OpenAI 兼容的错误响应体。"""
39
+ error: Dict[str, Any] = {
40
+ "message": message,
41
+ "type": error_type,
42
+ "code": code,
43
+ }
44
+ if details:
45
+ error["details"] = details
46
+ return {"error": error}
47
+
48
+
49
+ # -----------------------------------------------------------------------
50
+ # 异常处理器
51
+ # -----------------------------------------------------------------------
52
+
53
+ async def app_error_handler(request: Request, exc: AppError) -> JSONResponse:
54
+ """处理 AppError 及其子类。
55
+
56
+ 记录错误日志并返回结构化的错误响应。
57
+ """
58
+ # 根据状态码选择日志级别
59
+ if exc.status_code >= 500:
60
+ log_func = logger.error
61
+ elif exc.status_code >= 400:
62
+ log_func = logger.warning
63
+ else:
64
+ log_func = logger.info
65
+
66
+ log_func(
67
+ "API error: %s (code=%s, status=%d, path=%s)",
68
+ exc.message,
69
+ exc.code,
70
+ exc.status_code,
71
+ request.url.path,
72
+ extra={
73
+ "error_code": exc.code,
74
+ "status_code": exc.status_code,
75
+ "path": request.url.path,
76
+ "method": request.method,
77
+ "details": exc.details,
78
+ },
79
+ )
80
+
81
+ return JSONResponse(
82
+ status_code=exc.status_code,
83
+ content=exc.to_dict(),
84
+ )
85
+
86
+
87
+ async def validation_error_handler(
88
+ request: Request,
89
+ exc: RequestValidationError,
90
+ ) -> JSONResponse:
91
+ """处理 FastAPI 请求验证错误。"""
92
+ errors = exc.errors()
93
+
94
+ # 提取第一个错误作为主要消息
95
+ if errors:
96
+ first_error = errors[0]
97
+ field = ".".join(str(loc) for loc in first_error.get("loc", []))
98
+ message = first_error.get("msg", "Validation failed")
99
+ if field:
100
+ message = f"{field}: {message}"
101
+ else:
102
+ message = "Request validation failed"
103
+
104
+ logger.warning(
105
+ "Validation error: %s (path=%s)",
106
+ message,
107
+ request.url.path,
108
+ extra={
109
+ "path": request.url.path,
110
+ "method": request.method,
111
+ "validation_errors": errors,
112
+ },
113
+ )
114
+
115
+ return JSONResponse(
116
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
117
+ content=create_error_response(
118
+ message=message,
119
+ error_type="ValidationError",
120
+ code="validation_error",
121
+ status_code=422,
122
+ details={"errors": errors},
123
+ ),
124
+ )
125
+
126
+
127
+ async def http_exception_handler(request: Request, exc: HTTPException) -> JSONResponse:
128
+ """处理 FastAPI HTTPException。
129
+
130
+ 将 HTTPException 转换为 OpenAI 兼容格式。
131
+ """
132
+ # 特殊处理重定向
133
+ if exc.status_code in (301, 302, 303, 307, 308):
134
+ return JSONResponse(
135
+ status_code=exc.status_code,
136
+ content={"detail": exc.detail},
137
+ headers=exc.headers,
138
+ )
139
+
140
+ logger.warning(
141
+ "HTTP exception: %s (status=%d, path=%s)",
142
+ exc.detail,
143
+ exc.status_code,
144
+ request.url.path,
145
+ )
146
+
147
+ return JSONResponse(
148
+ status_code=exc.status_code,
149
+ content=create_error_response(
150
+ message=str(exc.detail),
151
+ error_type="HTTPException",
152
+ code=f"http_{exc.status_code}",
153
+ status_code=exc.status_code,
154
+ ),
155
+ headers=exc.headers,
156
+ )
157
+
158
+
159
+ async def generic_error_handler(request: Request, exc: Exception) -> JSONResponse:
160
+ """兜底处理未知异常。
161
+
162
+ 记录完整堆栈,返回通用错误响应。
163
+ """
164
+ log_exception(
165
+ logger,
166
+ "Unhandled exception: %s (path=%s, method=%s)",
167
+ type(exc).__name__,
168
+ request.url.path,
169
+ request.method,
170
+ error=exc,
171
+ )
172
+
173
+ return JSONResponse(
174
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
175
+ content=create_error_response(
176
+ message="Internal server error",
177
+ error_type="InternalServerError",
178
+ code="internal_error",
179
+ ),
180
+ )
181
+
182
+
183
+ # -----------------------------------------------------------------------
184
+ # 流式响应错误处理
185
+ # -----------------------------------------------------------------------
186
+
187
+ def format_sse_error(
188
+ message: str,
189
+ code: str = "internal_error",
190
+ error_type: str = "InternalError",
191
+ ) -> str:
192
+ """格式化 SSE 错误响应。
193
+
194
+ 用于流式响应中的错误传递。
195
+
196
+ Args:
197
+ message: 错误消息
198
+ code: 错误码
199
+ error_type: 错误类型
200
+
201
+ Returns:
202
+ SSE 格式的错误字符串
203
+ """
204
+ import json
205
+ error_data = {
206
+ "error": {
207
+ "message": message,
208
+ "type": error_type,
209
+ "code": code,
210
+ }
211
+ }
212
+ return f"data: {json.dumps(error_data, ensure_ascii=False)}\n\n"
213
+
214
+
215
+ def format_sse_done() -> str:
216
+ """返回 SSE 结束标记。"""
217
+ return "data: [DONE]\n\n"
218
+
219
+
220
+ # -----------------------------------------------------------------------
221
+ # 注册函数
222
+ # -----------------------------------------------------------------------
223
+
224
+ def register_exception_handlers(app) -> None:
225
+ """注册所有异常处理器到 FastAPI 应用。
226
+
227
+ Args:
228
+ app: FastAPI 应用实例
229
+ """
230
+ from fastapi.exceptions import HTTPException, RequestValidationError
231
+
232
+ app.add_exception_handler(AppError, app_error_handler)
233
+ app.add_exception_handler(RequestValidationError, validation_error_handler)
234
+ app.add_exception_handler(HTTPException, http_exception_handler)
235
+ app.add_exception_handler(Exception, generic_error_handler)
236
+
237
+ logger.info("✅ Global exception handlers registered")
app/core/file_upload.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """文件上传模块。
5
+
6
+ 将原 UpstreamClient.upload_file() 提取为独立函数,
7
+ 解耦对 UpstreamClient 实例的依赖,便于独立测试和复用。
8
+ 所有原参数保留,增加 client 和 base_url 两个注入参数。
9
+ """
10
+
11
+ import base64
12
+ import time
13
+ import uuid
14
+ from typing import Any, Dict, Optional
15
+ from urllib.parse import quote
16
+
17
+ import httpx
18
+
19
+ from app.core.resin_compat import apply_resin_account_header
20
+ from app.core.httpx_errors import normalize_httpx_exception, normalize_httpx_response
21
+ from app.utils.logger import logger, log_exception
22
+ from app.core.config import settings
23
+
24
+
25
+ async def upload_file(
26
+ client: httpx.AsyncClient,
27
+ base_url: str,
28
+ data_url: str,
29
+ chat_id: str,
30
+ token: str,
31
+ user_id: str,
32
+ auth_mode: str = "authenticated",
33
+ message_id: str = "",
34
+ ) -> Optional[Dict[str, Any]]:
35
+ """上传文件(图片/文档)到上游服务器。
36
+
37
+ Args:
38
+ client: 可复用的 httpx.AsyncClient 实例。
39
+ base_url: 上游服务基础 URL(如 "https://chat.z.ai")。
40
+ data_url: ``data:mime/type;base64,...`` 格式的文件数据。
41
+ chat_id: 当前对话 ID。
42
+ token: 认证令牌。
43
+ user_id: 用户 ID。
44
+ auth_mode: 当前鉴权模式,``guest`` 模式下禁止上传。
45
+ message_id: 关联的用户消息 ID,用于文件引用溯源。
46
+
47
+ Returns:
48
+ 上传成功返回完整的文件信息字典,失败或 guest 模式返回 None。
49
+ """
50
+ if auth_mode == "guest" or not data_url.startswith("data:"):
51
+ return None
52
+
53
+ try:
54
+ # 解析 data URL
55
+ header, encoded = data_url.split(",", 1)
56
+
57
+ # 解码前先预估文件大小,避免大文件 OOM
58
+ if settings.MAX_UPLOAD_FILE_SIZE > 0:
59
+ # base64 编码后大小约为原始大小的 4/3,反推原始大小估算
60
+ estimated_size = len(encoded) * 3 // 4
61
+ if estimated_size > settings.MAX_UPLOAD_FILE_SIZE:
62
+ limit_kb = settings.MAX_UPLOAD_FILE_SIZE // 1024
63
+ logger.warning(
64
+ f"⚠️ 文件过大,预估 {estimated_size // 1024}KB 超过限制 {limit_kb}KB,已跳过上传"
65
+ )
66
+ return None
67
+
68
+ mime_type = (
69
+ header.split(";")[0].split(":")[1]
70
+ if ":" in header
71
+ else "application/octet-stream"
72
+ )
73
+ file_data = base64.b64decode(encoded)
74
+ del encoded # Release base64 string memory early
75
+
76
+ # 判断文件类型
77
+ is_image = mime_type.startswith("image/")
78
+ media_type = "image" if is_image else "file"
79
+
80
+ # 生成文件名
81
+ ext_map = {
82
+ "image/jpeg": ".jpg",
83
+ "image/png": ".png",
84
+ "image/gif": ".gif",
85
+ "image/webp": ".webp",
86
+ "application/pdf": ".pdf",
87
+ "text/plain": ".txt",
88
+ "text/markdown": ".md",
89
+ "application/octet-stream": "",
90
+ }
91
+ ext = ext_map.get(mime_type, "")
92
+ filename = f"{uuid.uuid4()}{ext}"
93
+
94
+ logger.debug(
95
+ "上传%s: %s, 大小: %s bytes", media_type, filename, len(file_data)
96
+ )
97
+
98
+ # 构建上传请求头(保留所有原 header 字段)
99
+ upload_url = f"{base_url}/api/v1/files/"
100
+ headers = {
101
+ "Accept": "*/*",
102
+ "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
103
+ "Cache-Control": "no-cache",
104
+ "Pragma": "no-cache",
105
+ "Connection": "keep-alive",
106
+ "Origin": base_url,
107
+ "Referer": (
108
+ f"{base_url}/c/{chat_id}" if chat_id else f"{base_url}/"
109
+ ),
110
+ "Sec-Ch-Ua": '"Not:A-Brand";v="99", "Microsoft Edge";v="145", "Chromium";v="145"',
111
+ "Sec-Ch-Ua-Mobile": "?0",
112
+ "Sec-Ch-Ua-Platform": '"Windows"',
113
+ "Sec-Fetch-Dest": "empty",
114
+ "Sec-Fetch-Mode": "cors",
115
+ "Sec-Fetch-Site": "same-origin",
116
+ "Authorization": f"Bearer {token}",
117
+ }
118
+ apply_resin_account_header(headers, token)
119
+
120
+ upload_files = {"file": (filename, file_data, mime_type)}
121
+ response = await client.post(upload_url, files=upload_files, headers=headers)
122
+
123
+ if response.status_code != 200:
124
+ logger.error(
125
+ "❌ 文件上传失败: %s",
126
+ normalize_httpx_response(
127
+ response.status_code,
128
+ response.text,
129
+ content_type=response.headers.get("content-type"),
130
+ method="POST",
131
+ url=upload_url,
132
+ context="file_upload",
133
+ ),
134
+ )
135
+ return None
136
+
137
+ result = response.json()
138
+ file_id = result.get("id")
139
+ file_name = result.get("filename", filename)
140
+ file_meta = result.get("meta", {})
141
+
142
+ logger.debug("[file] upload success: %s (%s)", file_id, file_name)
143
+
144
+ # 使用上游返回的完整 meta(包含 oss_endpoint, cdn_url 等)
145
+ return {
146
+ "type": media_type,
147
+ "file": {
148
+ "id": file_id,
149
+ "user_id": result.get("user_id", user_id),
150
+ "hash": result.get("hash"),
151
+ "filename": file_name,
152
+ "data": result.get("data", {}),
153
+ "meta": file_meta,
154
+ "created_at": result.get("created_at", int(time.time())),
155
+ "updated_at": result.get("updated_at", int(time.time())),
156
+ },
157
+ "id": file_id,
158
+ "url": f"/api/v1/files/{file_id}",
159
+ "name": quote(file_name),
160
+ "status": "uploaded",
161
+ "size": file_meta.get("size", len(file_data)),
162
+ "error": "",
163
+ "itemId": str(uuid.uuid4()),
164
+ "media": media_type,
165
+ "ref_user_msg_id": message_id,
166
+ }
167
+
168
+ except Exception as e:
169
+ log_exception(
170
+ logger,
171
+ "❌ 文件上传异常: %s",
172
+ normalize_httpx_exception(
173
+ e,
174
+ method="POST",
175
+ url=upload_url,
176
+ context="file_upload",
177
+ ),
178
+ append_error=False,
179
+ )
180
+ return None
app/core/headers.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """统一浏览器 headers 生成。
5
+
6
+ 提供 build_dynamic_headers() 作为唯一入口。
7
+
8
+ ⚠️ 此处只生成真实浏览器同源 fetch 请求中实际带的最小集合,避免被阿里云 ESA/WAF
9
+ 按"非浏览器指纹"判别拦截(参见 chat.z.ai 抓包对比)。
10
+ - 不发 Origin(同源请求浏览器不发)
11
+ - 不发 Cache-Control / Pragma / Connection(fetch 不发)
12
+ - 不发 Sec-Fetch-*(fetch 自身管理,写死反而成为指纹)
13
+ - 不发 Referer 路径(chat.z.ai 前端的 referrer policy 让其为空)
14
+ """
15
+
16
+ import random
17
+ from typing import Dict
18
+
19
+ from app.utils.user_agent import get_random_user_agent
20
+
21
+
22
+ def build_dynamic_headers(fe_version: str, chat_id: str = "") -> Dict[str, str]:
23
+ """生成上游请求所需的最小浏览器 headers。
24
+
25
+ Args:
26
+ fe_version: 前端版本号,填充到 X-FE-Version header。
27
+ chat_id: 当前对话 ID(保留参数以兼容现有调用方,不再用于构造 Referer)。
28
+
29
+ Returns:
30
+ 与真实浏览器同源 fetch 一致的最小 header 集合。
31
+ Firefox UA 不带 sec-ch-ua 系列;Chromium 系带。
32
+ """
33
+ del chat_id # 兼容旧签名;真实浏览器同源请求里 Referer 为空,不再据此拼接
34
+ browser_choices = ["chrome", "chrome", "chrome", "edge", "edge", "firefox", "safari"]
35
+ browser_type = random.choice(browser_choices)
36
+ user_agent = get_random_user_agent(browser_type)
37
+
38
+ chrome_version = "139"
39
+ edge_version = "139"
40
+
41
+ if "Chrome/" in user_agent:
42
+ try:
43
+ chrome_version = user_agent.split("Chrome/")[1].split(".")[0]
44
+ except Exception:
45
+ pass
46
+
47
+ if "Edg/" in user_agent:
48
+ try:
49
+ edge_version = user_agent.split("Edg/")[1].split(".")[0]
50
+ sec_ch_ua = (
51
+ f'"Microsoft Edge";v="{edge_version}", '
52
+ f'"Chromium";v="{chrome_version}", "Not_A Brand";v="24"'
53
+ )
54
+ except Exception:
55
+ sec_ch_ua = (
56
+ f'"Not_A Brand";v="8", "Chromium";v="{chrome_version}", '
57
+ f'"Google Chrome";v="{chrome_version}"'
58
+ )
59
+ elif "Firefox/" in user_agent:
60
+ sec_ch_ua = None
61
+ else:
62
+ sec_ch_ua = (
63
+ f'"Not_A Brand";v="8", "Chromium";v="{chrome_version}", '
64
+ f'"Google Chrome";v="{chrome_version}"'
65
+ )
66
+
67
+ if "Windows" in user_agent:
68
+ platform = '"Windows"'
69
+ elif "Macintosh" in user_agent or "Mac OS X" in user_agent:
70
+ platform = '"macOS"'
71
+ elif "Linux" in user_agent:
72
+ platform = '"Linux"'
73
+ else:
74
+ platform = '"Windows"'
75
+
76
+ headers: Dict[str, str] = {
77
+ "Content-Type": "application/json",
78
+ "User-Agent": user_agent,
79
+ "Accept-Language": "en-US",
80
+ "X-FE-Version": fe_version,
81
+ "X-Region": "overseas",
82
+ }
83
+
84
+ if sec_ch_ua:
85
+ headers["sec-ch-ua"] = sec_ch_ua
86
+ headers["sec-ch-ua-mobile"] = "?0"
87
+ headers["sec-ch-ua-platform"] = platform
88
+
89
+ return headers
app/core/http_client.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """统一 HTTP 客户端工厂。
5
+
6
+ 提供代理配置、超时设置、连接池配置的统一构建函数,
7
+ 以及管理共享 AsyncClient 生命周期的 SharedHttpClients 类。
8
+ 可被 upstream.py 和 guest_session_pool.py 等模块复用。
9
+ """
10
+
11
+ from typing import Optional
12
+
13
+ import httpx
14
+
15
+ from app.core.config import settings
16
+
17
+
18
+ def get_proxy_config() -> Optional[str]:
19
+ """获取代理配置。
20
+
21
+ 统一获取全局的网络代理。支持 http(s):// 或 socks5://。
22
+ 返回 httpx 接受的代理 URL 字符串,无代理时返回 None。
23
+ """
24
+ proxy = settings.HTTP_PROXY
25
+ return proxy if proxy else None
26
+
27
+
28
+ def build_timeout(read_timeout: Optional[float] = None) -> httpx.Timeout:
29
+ """构建 httpx 超时配置。
30
+
31
+ Args:
32
+ read_timeout: 读取超时(秒)。None 时使用 settings.HTTP_DEFAULT_READ_TIMEOUT。
33
+ """
34
+ return httpx.Timeout(
35
+ connect=settings.HTTP_CONNECT_TIMEOUT,
36
+ read=read_timeout if read_timeout is not None else settings.HTTP_DEFAULT_READ_TIMEOUT,
37
+ write=settings.HTTP_WRITE_TIMEOUT,
38
+ pool=settings.HTTP_POOL_TIMEOUT,
39
+ )
40
+
41
+
42
+ def build_limits(
43
+ max_keepalive_connections: Optional[int] = None,
44
+ max_connections: Optional[int] = None,
45
+ ) -> httpx.Limits:
46
+ """构建 httpx 连接池限制。
47
+
48
+ Args:
49
+ max_keepalive_connections: 最大持久连接数,None 时使用全局配置。
50
+ max_connections: 最大连接数,None 时使用全局配置。
51
+ """
52
+ keepalive = max_keepalive_connections if max_keepalive_connections is not None else settings.GUEST_HTTP_MAX_KEEPALIVE_CONNECTIONS
53
+ connections = max_connections if max_connections is not None else settings.GUEST_HTTP_MAX_CONNECTIONS
54
+ return httpx.Limits(
55
+ max_keepalive_connections=max(1, keepalive),
56
+ max_connections=max(1, connections),
57
+ )
58
+
59
+
60
+ class SharedHttpClients:
61
+ """管理共享 httpx.AsyncClient 生命周期。
62
+
63
+ 维护两类客户端:
64
+ - ``client``:用于短请求(鉴权、文件上传、模型列表),读取超时由
65
+ ``settings.HTTP_DEFAULT_READ_TIMEOUT`` 控制。
66
+ - ``stream_client``:用于流式聊天,读取超时由
67
+ ``settings.HTTP_STREAM_READ_TIMEOUT`` 控制,启用 HTTP/2。
68
+
69
+ 使用示例::
70
+
71
+ clients = SharedHttpClients()
72
+ client = clients.get_client()
73
+ stream_client = clients.get_stream_client()
74
+ await clients.close()
75
+ """
76
+
77
+ def __init__(self, *, follow_redirects: bool = False) -> None:
78
+ self._follow_redirects = follow_redirects
79
+ self._client: Optional[httpx.AsyncClient] = None
80
+ self._stream_client: Optional[httpx.AsyncClient] = None
81
+
82
+ def get_client(self) -> httpx.AsyncClient:
83
+ """获取通用共享客户端。
84
+
85
+ 首次调用时惰性创建,后续调用复用同一实例(除非已关闭)。
86
+ """
87
+ if self._client is None or self._client.is_closed:
88
+ self._client = httpx.AsyncClient(
89
+ timeout=build_timeout(
90
+ read_timeout=settings.HTTP_DEFAULT_READ_TIMEOUT,
91
+ ),
92
+ limits=build_limits(
93
+ max_keepalive_connections=20,
94
+ max_connections=50,
95
+ ),
96
+ follow_redirects=self._follow_redirects,
97
+ proxy=get_proxy_config(),
98
+ trust_env=False,
99
+ )
100
+ return self._client
101
+
102
+ def get_stream_client(self) -> httpx.AsyncClient:
103
+ """获取流式专用客户端(启用 HTTP/2)。
104
+
105
+ 流式读取超时由 ``settings.HTTP_STREAM_READ_TIMEOUT`` 控制,
106
+ 即相邻两个 SSE chunk 之间允许的最大空闲时间。
107
+ 首次调用时惰性创建,后续调用复用同一实例(除非已关闭)。
108
+ """
109
+ if self._stream_client is None or self._stream_client.is_closed:
110
+ self._stream_client = httpx.AsyncClient(
111
+ timeout=build_timeout(
112
+ read_timeout=settings.HTTP_STREAM_READ_TIMEOUT,
113
+ ),
114
+ http2=True,
115
+ limits=build_limits(
116
+ max_keepalive_connections=20,
117
+ max_connections=50,
118
+ ),
119
+ follow_redirects=self._follow_redirects,
120
+ proxy=get_proxy_config(),
121
+ trust_env=False,
122
+ )
123
+ return self._stream_client
124
+
125
+ async def close(self) -> None:
126
+ """关闭所有共享客户端连接。"""
127
+ if self._client and not self._client.is_closed:
128
+ await self._client.aclose()
129
+ if self._stream_client and not self._stream_client.is_closed:
130
+ await self._stream_client.aclose()
app/core/httpx_errors.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """Helpers for normalized httpx error logging."""
5
+
6
+ from __future__ import annotations
7
+
8
+ from typing import TYPE_CHECKING, Optional
9
+
10
+ if TYPE_CHECKING:
11
+ from app.core.openai_compat import get_error_message
12
+ from app.core.retry_policy import summarize_upstream_error_text
13
+
14
+
15
+ _DEFAULT_MAX_BODY = 240
16
+
17
+
18
+ def _format_context(context: str) -> str:
19
+ if not context:
20
+ return ""
21
+ return f"[{context}] "
22
+
23
+
24
+ def _sanitize_text(text: str, max_length: int = _DEFAULT_MAX_BODY) -> str:
25
+ if not text:
26
+ return ""
27
+ sanitized = " ".join(text.split())
28
+ if len(sanitized) > max_length:
29
+ return sanitized[:max_length].rstrip() + "..."
30
+ return sanitized
31
+
32
+
33
+ def _format_attempt(attempt: Optional[int]) -> str:
34
+ if attempt is None:
35
+ return ""
36
+ return f" attempt={attempt}"
37
+
38
+
39
+ def normalize_httpx_exception(
40
+ exc: Exception,
41
+ *,
42
+ method: str,
43
+ url: str,
44
+ context: str = "",
45
+ attempt: Optional[int] = None,
46
+ ) -> str:
47
+ """Normalize httpx exception into a short log message."""
48
+ from app.core.openai_compat import get_error_message
49
+
50
+ friendly = get_error_message(exc)
51
+ if not friendly:
52
+ friendly = repr(exc)
53
+ return (
54
+ f"{_format_context(context)}HTTP {method.upper()} {url}"
55
+ f" failed{_format_attempt(attempt)}: {friendly}"
56
+ )
57
+
58
+
59
+ def normalize_httpx_response(
60
+ status_code: int,
61
+ body_text: str,
62
+ *,
63
+ content_type: Optional[str] = None,
64
+ method: str,
65
+ url: str,
66
+ context: str = "",
67
+ ) -> str:
68
+ """Normalize non-200 response into a short log message."""
69
+ from app.core.retry_policy import summarize_upstream_error_text
70
+
71
+ summarized = summarize_upstream_error_text(
72
+ status_code,
73
+ body_text or "",
74
+ content_type=content_type,
75
+ )
76
+ summarized = _sanitize_text(summarized, max_length=_DEFAULT_MAX_BODY)
77
+ message = f"{_format_context(context)}HTTP {method.upper()} {url} returned {status_code}"
78
+ if summarized:
79
+ return f"{message}: {summarized}"
80
+ return message
app/core/message_utils.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """Simplified OpenAI message preprocessing utilities."""
5
+
6
+ import json
7
+ from typing import Any, Dict, List
8
+
9
+
10
+ # ---------------------------------------------------------------------------
11
+ # Content extraction helper
12
+ # ---------------------------------------------------------------------------
13
+
14
+
15
+ def _extract_text_from_content(
16
+ content: Any,
17
+ *,
18
+ include_structured: bool = False,
19
+ ) -> str:
20
+ """Extract text parts from OpenAI-compatible content payloads."""
21
+ if isinstance(content, str):
22
+ return content
23
+
24
+ if isinstance(content, list):
25
+ parts: List[str] = []
26
+ for item in content:
27
+ if isinstance(item, dict) and item.get("type") == "text":
28
+ parts.append(str(item.get("text", "")))
29
+ elif include_structured and isinstance(item, dict):
30
+ try:
31
+ parts.append(json.dumps(item, ensure_ascii=False))
32
+ except Exception:
33
+ parts.append(str(item))
34
+ return " ".join(part for part in parts if part).strip()
35
+
36
+ if content is None:
37
+ return ""
38
+
39
+ try:
40
+ return json.dumps(content, ensure_ascii=False)
41
+ except Exception:
42
+ return str(content)
43
+
44
+
45
+ # ---------------------------------------------------------------------------
46
+ # Last user text extraction
47
+ # ---------------------------------------------------------------------------
48
+
49
+
50
+ def extract_last_user_text(messages: List[Dict[str, Any]]) -> str:
51
+ """Extract the last user text from the original OpenAI message history."""
52
+ for message in reversed(messages):
53
+ if message.get("role") != "user":
54
+ continue
55
+ content = _extract_text_from_content(message.get("content"))
56
+ if content:
57
+ return content
58
+ return ""
59
+
60
+
61
+ # ---------------------------------------------------------------------------
62
+ # Simplified message preprocessing
63
+ # ---------------------------------------------------------------------------
64
+
65
+
66
+ def preprocess_openai_messages(
67
+ messages: List[Dict[str, Any]],
68
+ ) -> List[Dict[str, Any]]:
69
+ """Normalize OpenAI history into shapes accepted by the upstream service.
70
+
71
+ Simplified conversions:
72
+ - ``developer`` role -> ``system``
73
+ - Everything else passes through unchanged
74
+
75
+ Args:
76
+ messages: OpenAI-format message list (already model_dump'd).
77
+
78
+ Returns:
79
+ Normalized message list suitable for upstream consumption.
80
+ """
81
+ normalized: List[Dict[str, Any]] = []
82
+
83
+ for message in messages:
84
+ if not isinstance(message, dict):
85
+ continue
86
+
87
+ role = message.get("role")
88
+
89
+ # developer -> system
90
+ if role == "developer":
91
+ converted = dict(message)
92
+ converted["role"] = "system"
93
+ normalized.append(converted)
94
+ continue
95
+
96
+ # Everything else passes through unchanged
97
+ normalized.append(dict(message))
98
+
99
+ return normalized
app/core/models.py ADDED
@@ -0,0 +1,562 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """Model management module.
5
+
6
+ Centrally manages model mapping, MCP server configuration, scene defaults,
7
+ model capabilities, and model feature resolution logic. Supports both
8
+ hardcoded fallback data and dynamic parsing from online model metadata.
9
+ """
10
+
11
+ from dataclasses import dataclass, field
12
+ from typing import Any, Dict, List, Optional
13
+
14
+ from app.core.config import settings
15
+ from app.models.schemas import OpenAIRequest
16
+ from app.utils.logger import logger
17
+
18
+
19
+ @dataclass
20
+ class ParsedModel:
21
+ """Structured representation of an online model after parsing."""
22
+
23
+ upstream_id: str
24
+ display_name: str
25
+ capabilities: Dict[str, Any] = field(default_factory=dict)
26
+ mcp_server_ids: List[str] = field(default_factory=list)
27
+ params: Dict[str, Any] = field(default_factory=dict)
28
+ is_active: bool = True
29
+ tags: List[str] = field(default_factory=list)
30
+
31
+
32
+ class ModelManager:
33
+ """Model configuration manager.
34
+
35
+ Manages four configuration dictionaries:
36
+ 1. ``model_mapping`` -- external model name -> upstream model ID
37
+ 2. ``model_mcp_servers`` -- model -> default MCP server list
38
+ 3. ``model_scene_defaults``-- model -> scene default parameters
39
+ 4. ``model_capabilities`` -- model -> capability declarations
40
+
41
+ On startup, hardcoded defaults are loaded. When
42
+ :meth:`load_from_online_models` is called with fresh upstream data the
43
+ hardcoded values are replaced with dynamically generated variants.
44
+ """
45
+
46
+ def __init__(self) -> None:
47
+ self._init_hardcoded_defaults()
48
+ self._parsed: bool = False # True after successful online parse
49
+ self._casefold_index: Dict[str, str] = {}
50
+ # Apply aliases to hardcoded defaults (online path re-applies after parse)
51
+ self.apply_aliases()
52
+
53
+ # ------------------------------------------------------------------
54
+ # Hardcoded fallback (kept for offline / pre-fetch scenarios)
55
+ # ------------------------------------------------------------------
56
+
57
+ def _init_hardcoded_defaults(self) -> None:
58
+ """Initialise all model dictionaries with hardcoded defaults."""
59
+
60
+ # External model name -> upstream model ID
61
+ self.model_mapping: Dict[str, str] = {
62
+ settings.GLM45_MODEL: "0727-360B-API",
63
+ settings.GLM45_THINKING_MODEL: "0727-360B-API",
64
+ settings.GLM45_SEARCH_MODEL: "0727-360B-API",
65
+ settings.GLM45_AIR_MODEL: "0727-106B-API",
66
+ settings.GLM46V_MODEL: "glm-4.6v",
67
+ settings.GLM46V_ADVANCED_SEARCH_MODEL: "glm-4.6v",
68
+ settings.GLM5_MODEL: "glm-5",
69
+ settings.GLM5_THINKING_MODEL: "glm-5",
70
+ settings.GLM5_AGENT_MODEL: "glm-5",
71
+ settings.GLM5_ADVANCED_SEARCH_MODEL: "glm-5",
72
+ settings.GLM47_MODEL: "glm-4.7",
73
+ settings.GLM47_THINKING_MODEL: "glm-4.7",
74
+ settings.GLM47_SEARCH_MODEL: "glm-4.7",
75
+ settings.GLM47_ADVANCED_SEARCH_MODEL: "glm-4.7",
76
+ }
77
+
78
+ # Default MCP servers per model
79
+ self.model_mcp_servers: Dict[str, List[str]] = {
80
+ settings.GLM5_ADVANCED_SEARCH_MODEL: ["advanced-search"],
81
+ settings.GLM46V_ADVANCED_SEARCH_MODEL: ["advanced-search"],
82
+ settings.GLM47_ADVANCED_SEARCH_MODEL: ["advanced-search"],
83
+ }
84
+
85
+ # Scene defaults per model
86
+ self.model_scene_defaults: Dict[str, Dict[str, Any]] = {
87
+ settings.GLM5_AGENT_MODEL: {
88
+ "flags": ["general_agent"],
89
+ "enable_thinking": True,
90
+ "auto_web_search": False,
91
+ },
92
+ settings.GLM5_ADVANCED_SEARCH_MODEL: {
93
+ "enable_thinking": True,
94
+ "web_search": True,
95
+ "auto_web_search": True,
96
+ },
97
+ settings.GLM46V_ADVANCED_SEARCH_MODEL: {
98
+ "enable_thinking": True,
99
+ "web_search": True,
100
+ "auto_web_search": True,
101
+ },
102
+ settings.GLM47_ADVANCED_SEARCH_MODEL: {
103
+ "enable_thinking": True,
104
+ "web_search": True,
105
+ "auto_web_search": True,
106
+ },
107
+ settings.GLM45_SEARCH_MODEL: {
108
+ "web_search": True,
109
+ "auto_web_search": True,
110
+ },
111
+ settings.GLM47_SEARCH_MODEL: {
112
+ "web_search": True,
113
+ "auto_web_search": True,
114
+ },
115
+ }
116
+
117
+ # Model capability declarations
118
+ self.model_capabilities: Dict[str, Dict[str, bool]] = {
119
+ settings.GLM45_MODEL: {
120
+ "tool_use": False, "vision": False,
121
+ "web_search": False, "thinking": False,
122
+ },
123
+ settings.GLM45_THINKING_MODEL: {
124
+ "tool_use": False, "vision": False,
125
+ "web_search": False, "thinking": True,
126
+ },
127
+ settings.GLM45_SEARCH_MODEL: {
128
+ "tool_use": False, "vision": False,
129
+ "web_search": True, "thinking": False,
130
+ },
131
+ settings.GLM45_AIR_MODEL: {
132
+ "tool_use": False, "vision": False,
133
+ "web_search": False, "thinking": False,
134
+ },
135
+ settings.GLM46V_MODEL: {
136
+ "tool_use": False, "vision": True,
137
+ "web_search": False, "thinking": False,
138
+ },
139
+ settings.GLM46V_ADVANCED_SEARCH_MODEL: {
140
+ "tool_use": False, "vision": True,
141
+ "web_search": True, "thinking": True,
142
+ },
143
+ settings.GLM5_MODEL: {
144
+ "tool_use": False, "vision": False,
145
+ "web_search": False, "thinking": False,
146
+ },
147
+ settings.GLM5_THINKING_MODEL: {
148
+ "tool_use": False, "vision": False,
149
+ "web_search": False, "thinking": True,
150
+ },
151
+ settings.GLM5_AGENT_MODEL: {
152
+ "tool_use": False, "vision": False,
153
+ "web_search": False, "thinking": True,
154
+ "agent": True,
155
+ },
156
+ settings.GLM5_ADVANCED_SEARCH_MODEL: {
157
+ "tool_use": False, "vision": False,
158
+ "web_search": True, "thinking": True,
159
+ },
160
+ settings.GLM47_MODEL: {
161
+ "tool_use": False, "vision": False,
162
+ "web_search": False, "thinking": False,
163
+ },
164
+ settings.GLM47_THINKING_MODEL: {
165
+ "tool_use": False, "vision": False,
166
+ "web_search": False, "thinking": True,
167
+ },
168
+ settings.GLM47_SEARCH_MODEL: {
169
+ "tool_use": False, "vision": False,
170
+ "web_search": True, "thinking": False,
171
+ },
172
+ settings.GLM47_ADVANCED_SEARCH_MODEL: {
173
+ "tool_use": False, "vision": False,
174
+ "web_search": True, "thinking": True,
175
+ },
176
+ }
177
+
178
+ # Hardcoded supported model list (fallback order)
179
+ self._hardcoded_supported_models: List[str] = [
180
+ settings.GLM45_MODEL,
181
+ settings.GLM45_THINKING_MODEL,
182
+ settings.GLM45_SEARCH_MODEL,
183
+ settings.GLM45_AIR_MODEL,
184
+ settings.GLM46V_MODEL,
185
+ settings.GLM46V_ADVANCED_SEARCH_MODEL,
186
+ settings.GLM5_MODEL,
187
+ settings.GLM5_THINKING_MODEL,
188
+ settings.GLM5_AGENT_MODEL,
189
+ settings.GLM5_ADVANCED_SEARCH_MODEL,
190
+ settings.GLM47_MODEL,
191
+ settings.GLM47_THINKING_MODEL,
192
+ settings.GLM47_SEARCH_MODEL,
193
+ settings.GLM47_ADVANCED_SEARCH_MODEL,
194
+ ]
195
+
196
+ # Will be populated by load_from_online_models
197
+ self._dynamic_supported_models: List[str] = []
198
+
199
+ # ------------------------------------------------------------------
200
+ # Online model parsing
201
+ # ------------------------------------------------------------------
202
+
203
+ def load_from_online_models(self, online_models: List[Dict[str, Any]]) -> None:
204
+ """Parse online model metadata and generate variant configurations.
205
+
206
+ For each non-blacklisted active model, up to five variants are
207
+ generated (base, Thinking, Search, Agent, advanced-search) depending
208
+ on the upstream capability flags. The four core dictionaries are
209
+ fully replaced on success.
210
+
211
+ Args:
212
+ online_models: List of model dicts as returned by
213
+ :meth:`upstream.UpstreamClient.get_online_models`.
214
+ """
215
+ # Read blacklist from settings (comma-separated upstream IDs)
216
+ blacklist_raw = getattr(settings, "MODEL_BLACKLIST", "glm-4-flash")
217
+ blacklist = {
218
+ item.strip().lower()
219
+ for item in blacklist_raw.split(",")
220
+ if item.strip()
221
+ }
222
+
223
+ # Parse each raw dict into a ParsedModel
224
+ parsed: List[ParsedModel] = []
225
+ skipped_inactive = 0
226
+ skipped_blacklisted = 0
227
+
228
+ for raw in online_models:
229
+ upstream_id = raw.get("id", "")
230
+ if not upstream_id:
231
+ continue
232
+
233
+ # Blacklist check (case-insensitive on upstream ID)
234
+ if upstream_id.lower() in blacklist:
235
+ skipped_blacklisted += 1
236
+ continue
237
+
238
+ is_active = raw.get("is_active", True)
239
+ if not is_active:
240
+ skipped_inactive += 1
241
+ continue
242
+
243
+ display_name = raw.get("name") or upstream_id
244
+ capabilities = raw.get("capabilities") or {}
245
+ mcp_server_ids = raw.get("mcpServerIds") or []
246
+ tags = raw.get("tags") or []
247
+
248
+ parsed.append(ParsedModel(
249
+ upstream_id=upstream_id,
250
+ display_name=display_name,
251
+ capabilities=capabilities,
252
+ mcp_server_ids=mcp_server_ids,
253
+ params={},
254
+ is_active=is_active,
255
+ tags=tags,
256
+ ))
257
+
258
+ # Build fresh dictionaries from parsed models
259
+ new_mapping: Dict[str, str] = {}
260
+ new_capabilities: Dict[str, Dict[str, bool]] = {}
261
+ new_mcp_servers: Dict[str, List[str]] = {}
262
+ new_scene_defaults: Dict[str, Dict[str, Any]] = {}
263
+ new_supported: List[str] = []
264
+
265
+ total_variants = 0
266
+
267
+ for model in parsed:
268
+ variants = self._generate_variants(model)
269
+ for v_name, v_caps, v_scene, v_mcp in variants:
270
+ new_mapping[v_name] = model.upstream_id
271
+ new_capabilities[v_name] = v_caps
272
+ if v_scene:
273
+ new_scene_defaults[v_name] = v_scene
274
+ if v_mcp:
275
+ new_mcp_servers[v_name] = v_mcp
276
+ new_supported.append(v_name)
277
+ total_variants += 1
278
+
279
+ # Atomically replace all dictionaries
280
+ self.model_mapping = new_mapping
281
+ self.model_capabilities = new_capabilities
282
+ self.model_mcp_servers = new_mcp_servers
283
+ self.model_scene_defaults = new_scene_defaults
284
+ self._dynamic_supported_models = new_supported
285
+ self._parsed = True
286
+
287
+ logger.debug(
288
+ "Online model parsing complete: %d models parsed, "
289
+ "%d variants generated, %d blacklisted, %d inactive",
290
+ len(parsed), total_variants,
291
+ skipped_blacklisted, skipped_inactive,
292
+ )
293
+
294
+ # Apply user-defined aliases on top of generated variants
295
+ self.apply_aliases()
296
+
297
+ @staticmethod
298
+ def _generate_variants(
299
+ model: ParsedModel,
300
+ ) -> List[tuple]:
301
+ """Generate variant tuples for a single parsed model.
302
+
303
+ Returns:
304
+ List of (variant_name, capabilities_dict, scene_defaults_dict,
305
+ mcp_servers_list) tuples.
306
+ """
307
+ caps = model.capabilities
308
+ name = model.display_name
309
+ name_lower = name.lower()
310
+ mcp_ids = model.mcp_server_ids
311
+
312
+ # Derive base capability flags from upstream capabilities
313
+ has_return_fc = bool(caps.get("returnFc", False))
314
+ has_vision = bool(caps.get("vision", False))
315
+ has_think = bool(caps.get("think", False))
316
+ has_web_search = bool(caps.get("web_search", False))
317
+ has_agent_mode = bool(caps.get("agent_mode", False))
318
+ has_deep_web_search = "deep-web-search" in mcp_ids
319
+ has_advanced_search = "advanced-search" in mcp_ids
320
+
321
+ base_caps: Dict[str, bool] = {
322
+ "tool_use": False,
323
+ "vision": has_vision,
324
+ }
325
+
326
+ variants: List[tuple] = []
327
+
328
+ # --- 1. Base variant (always generated) ---
329
+ variants.append((
330
+ name,
331
+ {**base_caps, "web_search": False, "thinking": False},
332
+ {}, # no scene defaults for base
333
+ [], # no MCP servers for base
334
+ ))
335
+
336
+ # --- 2. Thinking variant ---
337
+ if has_think and "thinking" not in name_lower:
338
+ thinking_name = f"{name}-Thinking"
339
+ variants.append((
340
+ thinking_name,
341
+ {**base_caps, "web_search": False, "thinking": True},
342
+ {"enable_thinking": True},
343
+ [],
344
+ ))
345
+
346
+ # --- 3. Search variant ---
347
+ if (has_web_search or has_deep_web_search) and "search" not in name_lower:
348
+ search_name = f"{name}-Search"
349
+ variants.append((
350
+ search_name,
351
+ {**base_caps, "web_search": True, "thinking": False},
352
+ {"web_search": True, "auto_web_search": True},
353
+ [],
354
+ ))
355
+
356
+ # --- 4. Agent variant ---
357
+ if has_agent_mode and "agent" not in name_lower:
358
+ agent_name = f"{name}-Agent"
359
+ variants.append((
360
+ agent_name,
361
+ {**base_caps, "web_search": False, "thinking": True, "agent": True},
362
+ {"flags": ["general_agent"], "enable_thinking": True},
363
+ [],
364
+ ))
365
+
366
+ # --- 5. advanced-search variant ---
367
+ if has_advanced_search and "advanced-search" not in name_lower:
368
+ adv_search_name = f"{name}-advanced-search"
369
+ variants.append((
370
+ adv_search_name,
371
+ {**base_caps, "web_search": True, "thinking": True},
372
+ {"enable_thinking": True, "web_search": True, "auto_web_search": True},
373
+ ["advanced-search"],
374
+ ))
375
+
376
+ return variants
377
+
378
+ # ------------------------------------------------------------------
379
+ # Alias mapping
380
+ # ------------------------------------------------------------------
381
+
382
+ def apply_aliases(self, aliases_str: Optional[str] = None) -> None:
383
+ """Apply model aliases from a comma-separated ``alias=target`` string.
384
+
385
+ Each alias inherits the target model's upstream mapping, capabilities,
386
+ MCP servers, and scene defaults. Unknown targets are silently skipped.
387
+
388
+ Args:
389
+ aliases_str: Alias definitions. Falls back to
390
+ ``settings.MODEL_ALIASES`` when *None*.
391
+ """
392
+ if aliases_str is None:
393
+ aliases_str = getattr(settings, "MODEL_ALIASES", "")
394
+ if not aliases_str or not aliases_str.strip():
395
+ self._rebuild_casefold_index()
396
+ return
397
+
398
+ applied = 0
399
+ for pair in aliases_str.split(","):
400
+ pair = pair.strip()
401
+ if "=" not in pair:
402
+ continue
403
+ alias, target = pair.split("=", 1)
404
+ alias = alias.strip()
405
+ target = target.strip()
406
+ if not alias or not target:
407
+ continue
408
+
409
+ # Target must exist in current mapping
410
+ if target not in self.model_mapping:
411
+ logger.warning(
412
+ "Alias target %r not found in model mapping, "
413
+ "skipping alias %r",
414
+ target, alias,
415
+ )
416
+ continue
417
+
418
+ # Copy all properties from target
419
+ self.model_mapping[alias] = self.model_mapping[target]
420
+ if target in self.model_capabilities:
421
+ self.model_capabilities[alias] = dict(self.model_capabilities[target])
422
+ if target in self.model_mcp_servers:
423
+ self.model_mcp_servers[alias] = list(self.model_mcp_servers[target])
424
+ if target in self.model_scene_defaults:
425
+ self.model_scene_defaults[alias] = dict(self.model_scene_defaults[target])
426
+
427
+ # Add to supported models list
428
+ if self._parsed and alias not in self._dynamic_supported_models:
429
+ self._dynamic_supported_models.append(alias)
430
+ elif not self._parsed and alias not in self._hardcoded_supported_models:
431
+ self._hardcoded_supported_models.append(alias)
432
+
433
+ applied += 1
434
+
435
+ if applied:
436
+ logger.debug("Applied %d model alias(es)", applied)
437
+
438
+ self._rebuild_casefold_index()
439
+
440
+ # ------------------------------------------------------------------
441
+ # Case-insensitive model name resolution
442
+ # ------------------------------------------------------------------
443
+
444
+ def _rebuild_casefold_index(self) -> None:
445
+ """Rebuild case-insensitive lookup index from model_mapping keys."""
446
+ self._casefold_index = {k.casefold(): k for k in self.model_mapping}
447
+
448
+ def _resolve_name(self, model_name: str) -> Optional[str]:
449
+ """Resolve model_name to its canonical key (case-insensitive).
450
+
451
+ Tries exact match first, then falls back to case-insensitive lookup.
452
+ """
453
+ if model_name in self.model_mapping:
454
+ return model_name
455
+ return self._casefold_index.get(model_name.casefold())
456
+
457
+ # ------------------------------------------------------------------
458
+ # Public query API (signatures unchanged)
459
+ # ------------------------------------------------------------------
460
+
461
+ def get_upstream_model_id(self, model_name: str) -> Optional[str]:
462
+ """Return the upstream model ID for *model_name*, or None."""
463
+ canonical = self._resolve_name(model_name)
464
+ return self.model_mapping[canonical] if canonical else None
465
+
466
+ def get_mcp_servers(self, model_name: str) -> List[str]:
467
+ """Return the default MCP server list for *model_name*."""
468
+ return self.model_mcp_servers.get(
469
+ self._resolve_name(model_name) or model_name, []
470
+ )
471
+
472
+ def get_scene_defaults(self, model_name: str) -> Dict[str, Any]:
473
+ """Return scene default parameters for *model_name*."""
474
+ return self.model_scene_defaults.get(
475
+ self._resolve_name(model_name) or model_name, {}
476
+ )
477
+
478
+ def get_model_capabilities(self, model_name: str) -> Dict[str, bool]:
479
+ """Return capability declarations for *model_name*.
480
+
481
+ Unregistered models receive a minimal base capability set.
482
+ """
483
+ return self.model_capabilities.get(
484
+ self._resolve_name(model_name) or model_name, {
485
+ "tool_use": False,
486
+ "vision": False,
487
+ "web_search": False,
488
+ "thinking": False,
489
+ }
490
+ )
491
+
492
+ def get_supported_models(self) -> List[str]:
493
+ """Return the list of externally exposed supported models.
494
+
495
+ Uses dynamically generated list when online parsing has succeeded,
496
+ otherwise falls back to the hardcoded list.
497
+ """
498
+ if self._parsed and self._dynamic_supported_models:
499
+ return list(self._dynamic_supported_models)
500
+ return list(self._hardcoded_supported_models)
501
+
502
+ # ------------------------------------------------------------------
503
+ # Feature resolution (signature unchanged)
504
+ # ------------------------------------------------------------------
505
+
506
+ def resolve_model_features(self, request: OpenAIRequest) -> Dict[str, Any]:
507
+ """Resolve model feature parameters from request context.
508
+
509
+ Priority order: explicit client parameters > scene defaults >
510
+ model-suffix inference.
511
+
512
+ Args:
513
+ request: OpenAI-compatible request object.
514
+
515
+ Returns:
516
+ Dict with keys: upstream_model_id, enable_thinking, web_search,
517
+ auto_web_search, mcp_servers, extra, flags.
518
+ """
519
+ requested_model = request.model
520
+ is_thinking_model = "-thinking" in requested_model.casefold()
521
+ is_search_model = "-search" in requested_model.casefold()
522
+
523
+ scene_defaults = self.get_scene_defaults(requested_model)
524
+
525
+ # enable_thinking: client > scene default > suffix inference
526
+ enable_thinking = request.enable_thinking
527
+ if enable_thinking is None:
528
+ enable_thinking = scene_defaults.get("enable_thinking", is_thinking_model)
529
+
530
+ # web_search: client > scene default > suffix inference
531
+ web_search = request.web_search
532
+ if web_search is None:
533
+ web_search = scene_defaults.get("web_search", is_search_model)
534
+
535
+ # auto_web_search: scene default > False
536
+ auto_web_search = scene_defaults.get("auto_web_search", False)
537
+
538
+ # Upstream model ID
539
+ upstream_model_id = self.get_upstream_model_id(requested_model)
540
+ if upstream_model_id is None:
541
+ raise ValueError(f"Unsupported model: {requested_model}")
542
+
543
+ # mcp_servers: client pass-through takes priority
544
+ mcp_servers = (
545
+ request.mcp_servers
546
+ if request.mcp_servers is not None
547
+ else self.get_mcp_servers(requested_model)
548
+ )
549
+
550
+ # extra and flags: client > scene default > empty
551
+ extra = request.extra if request.extra is not None else scene_defaults.get("extra", {})
552
+ flags = request.flags if request.flags is not None else scene_defaults.get("flags", [])
553
+
554
+ return {
555
+ "upstream_model_id": upstream_model_id,
556
+ "enable_thinking": enable_thinking,
557
+ "web_search": web_search,
558
+ "auto_web_search": auto_web_search,
559
+ "mcp_servers": mcp_servers,
560
+ "extra": extra,
561
+ "flags": flags,
562
+ }
app/core/openai.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """OpenAI 兼容 API 端点。
5
+
6
+ 提供 /v1/models 和 /v1/chat/completions 端点。
7
+ """
8
+
9
+ import time
10
+ from typing import Optional
11
+
12
+ from fastapi import APIRouter, Header, Request
13
+ from fastapi.responses import JSONResponse, StreamingResponse
14
+
15
+ from app.core.config import settings
16
+ from app.exceptions import (
17
+ AppError,
18
+ AuthenticationError,
19
+ UpstreamError,
20
+ )
21
+ from app.models.schemas import (
22
+ Model,
23
+ ModelsResponse,
24
+ OpenAIRequest,
25
+ )
26
+ from app.core.openai_compat import resolve_http_error_status
27
+ from app.core.upstream import UpstreamClient
28
+ from app.utils.logger import logger
29
+ from app.utils.token_pool import get_token_pool
30
+ from app.utils.request_logging import (
31
+ _openai_response_has_output,
32
+ extract_openai_usage,
33
+ wrap_openai_stream_with_logging,
34
+ write_request_log,
35
+ )
36
+ from app.utils.request_source import detect_request_source, format_request_source
37
+
38
+ router = APIRouter()
39
+
40
+ _upstream_client: Optional[UpstreamClient] = None
41
+
42
+
43
+ def get_upstream_client() -> UpstreamClient:
44
+ """获取懒加载的上游适配器单例。"""
45
+ global _upstream_client
46
+ if _upstream_client is None:
47
+ _upstream_client = UpstreamClient()
48
+ return _upstream_client
49
+
50
+
51
+ def get_upstream_client_if_ready() -> Optional[UpstreamClient]:
52
+ """Return upstream client if already initialized."""
53
+ return _upstream_client
54
+
55
+
56
+ async def reset_upstream_client() -> None:
57
+ """Close and clear the cached upstream client singleton."""
58
+ global _upstream_client
59
+ if _upstream_client is not None:
60
+ await _upstream_client.close()
61
+ _upstream_client = None
62
+
63
+
64
+ @router.get("/v1/models")
65
+ async def list_models():
66
+ """返回当前服务支持的模型列表(含能力声明)。"""
67
+ client = get_upstream_client()
68
+ current_time = int(time.time())
69
+ model_manager = client._model_manager
70
+ response = ModelsResponse(
71
+ data=[
72
+ Model(
73
+ id=model_id,
74
+ created=current_time,
75
+ owned_by=settings.SERVICE_NAME,
76
+ capabilities=model_manager.get_model_capabilities(model_id),
77
+ )
78
+ for model_id in client.get_supported_models()
79
+ ]
80
+ )
81
+ return JSONResponse(content=response.model_dump(exclude_none=True))
82
+
83
+
84
+ @router.post("/v1/chat/completions")
85
+ async def chat_completions(
86
+ body: OpenAIRequest,
87
+ http_request: Request,
88
+ authorization: Optional[str] = Header(None),
89
+ ):
90
+ """直接调用上游适配器处理请求。"""
91
+ source_info = detect_request_source(
92
+ http_request,
93
+ protocol_hint="openai",
94
+ )
95
+ source_prefix = format_request_source(source_info)
96
+ started_at = time.perf_counter()
97
+ body.started_at = started_at
98
+ bearer_token = (
99
+ authorization[7:]
100
+ if authorization and authorization.startswith("Bearer ")
101
+ else None
102
+ )
103
+
104
+ logger.debug(
105
+ "%s OpenAI req - model: %s, stream: %s, messages: %s",
106
+ source_prefix, body.model, body.stream, len(body.messages),
107
+ )
108
+ logger.debug("%s 客户端请求原样数据: %s", source_prefix, body)
109
+ upstream_auth_token: Optional[str] = None
110
+
111
+ # 认证检查
112
+ if not settings.SKIP_AUTH_TOKEN:
113
+ if not bearer_token:
114
+ raise AuthenticationError("Missing or invalid Authorization header")
115
+
116
+ if bearer_token != settings.AUTH_TOKEN:
117
+ raise AuthenticationError("Invalid API key")
118
+
119
+ # 调用上游
120
+ client = get_upstream_client()
121
+ result, upstream_auth_token = await client.chat_completion(
122
+ body,
123
+ http_request=http_request,
124
+ )
125
+
126
+ # 处理上游错误
127
+ if isinstance(result, dict) and "error" in result:
128
+ error_info = result["error"]
129
+ error_message = error_info.get("message", "Unknown upstream error")
130
+ error_code = error_info.get("code")
131
+ error_type = error_info.get("type")
132
+ status_code = resolve_http_error_status(error_code, error_type)
133
+
134
+ # 记录错误日志
135
+ await write_request_log(
136
+ provider="zai",
137
+ model=body.model,
138
+ source_info=source_info,
139
+ auth_token=bearer_token,
140
+ upstream_auth_token=upstream_auth_token,
141
+ success=False,
142
+ started_at=started_at,
143
+ status_code=status_code,
144
+ error_message=error_message,
145
+ )
146
+
147
+ raise UpstreamError(
148
+ message=error_message,
149
+ upstream_code=error_code if isinstance(error_code, int) else None,
150
+ upstream_status=status_code,
151
+ upstream_type=error_type,
152
+ )
153
+
154
+ # 流式响应
155
+ if body.stream:
156
+ if hasattr(result, "__aiter__"):
157
+ return StreamingResponse(
158
+ wrap_openai_stream_with_logging(
159
+ result,
160
+ provider="zai",
161
+ model=body.model,
162
+ source_info=source_info,
163
+ auth_token=bearer_token,
164
+ upstream_auth_token=upstream_auth_token,
165
+ started_at=started_at,
166
+ ),
167
+ media_type="text/event-stream",
168
+ headers={
169
+ "Cache-Control": "no-cache",
170
+ "Connection": "keep-alive",
171
+ },
172
+ )
173
+ raise UpstreamError(
174
+ message="Expected streaming response but got non-streaming result",
175
+ )
176
+
177
+ # 非流式响应
178
+ if isinstance(result, dict):
179
+ usage = extract_openai_usage(result)
180
+ has_error = "error" in result
181
+ is_empty = not _openai_response_has_output(result)
182
+
183
+ if is_empty:
184
+ error_message = "Empty response: no content in choices"
185
+ await write_request_log(
186
+ provider="zai",
187
+ model=body.model,
188
+ source_info=source_info,
189
+ auth_token=bearer_token,
190
+ upstream_auth_token=upstream_auth_token,
191
+ success=False,
192
+ started_at=started_at,
193
+ status_code=502,
194
+ input_tokens=usage["input_tokens"],
195
+ output_tokens=usage["output_tokens"],
196
+ cache_creation_tokens=usage["cache_creation_tokens"],
197
+ cache_read_tokens=usage["cache_read_tokens"],
198
+ total_tokens=usage["total_tokens"],
199
+ error_message=error_message,
200
+ )
201
+ token_pool = get_token_pool()
202
+ if token_pool and upstream_auth_token:
203
+ await token_pool.record_token_failure(
204
+ upstream_auth_token,
205
+ Exception(error_message),
206
+ )
207
+ raise UpstreamError(message=error_message)
208
+
209
+ await write_request_log(
210
+ provider="zai",
211
+ model=body.model,
212
+ source_info=source_info,
213
+ auth_token=bearer_token,
214
+ upstream_auth_token=upstream_auth_token,
215
+ success=not has_error,
216
+ started_at=started_at,
217
+ status_code=200 if not has_error else 500,
218
+ input_tokens=usage["input_tokens"],
219
+ output_tokens=usage["output_tokens"],
220
+ cache_creation_tokens=usage["cache_creation_tokens"],
221
+ cache_read_tokens=usage["cache_read_tokens"],
222
+ total_tokens=usage["total_tokens"],
223
+ error_message=(
224
+ (result.get("error") or {}).get("message")
225
+ if has_error
226
+ else None
227
+ ),
228
+ )
229
+ return JSONResponse(content=result)
230
+
231
+ # 不应该到达这里
232
+ raise UpstreamError(
233
+ message="Unexpected non-stream result type from upstream",
234
+ )
app/core/openai_compat.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """OpenAI 兼容响应辅助函数。
5
+
6
+ 提供:
7
+ - OpenAI 格式的响应构建
8
+ - 错误消息提取
9
+ - 错误响应构建
10
+ - HTTP 状态码映射
11
+ """
12
+
13
+ import json
14
+ import time
15
+ from typing import Any, Dict, Optional
16
+
17
+ from app.core.retry_policy import summarize_upstream_error_text
18
+ from app.exceptions import AppError, UpstreamError, ValidationError
19
+ from app.utils.logger import logger
20
+
21
+ SYSTEM_FINGERPRINT = "fp_api_proxy_001"
22
+
23
+
24
+ def create_openai_chunk(
25
+ chat_id: str,
26
+ model: str,
27
+ delta: Dict[str, Any],
28
+ finish_reason: Optional[str] = None,
29
+ created: Optional[int] = None,
30
+ ) -> Dict[str, Any]:
31
+ """创建 OpenAI 格式的流式响应块。"""
32
+ return {
33
+ "id": chat_id,
34
+ "object": "chat.completion.chunk",
35
+ "created": created if created is not None else int(time.time()),
36
+ "model": model,
37
+ "choices": [
38
+ {
39
+ "index": 0,
40
+ "delta": delta,
41
+ "finish_reason": finish_reason,
42
+ }
43
+ ],
44
+ "system_fingerprint": SYSTEM_FINGERPRINT,
45
+ }
46
+
47
+
48
+ def create_openai_response_with_reasoning(
49
+ chat_id: str,
50
+ model: str,
51
+ content: str,
52
+ reasoning_content: Optional[str] = None,
53
+ usage: Optional[Dict[str, Any]] = None,
54
+ ) -> Dict[str, Any]:
55
+ """创建包含 reasoning 的 OpenAI 响应。"""
56
+ message: Dict[str, Any] = {
57
+ "role": "assistant",
58
+ "content": content,
59
+ }
60
+
61
+ if reasoning_content and reasoning_content.strip():
62
+ message["reasoning_content"] = reasoning_content
63
+
64
+ return {
65
+ "id": chat_id,
66
+ "object": "chat.completion",
67
+ "created": int(time.time()),
68
+ "model": model,
69
+ "choices": [
70
+ {
71
+ "index": 0,
72
+ "message": message,
73
+ "finish_reason": "stop",
74
+ "logprobs": None,
75
+ }
76
+ ],
77
+ "usage": usage
78
+ or {
79
+ "prompt_tokens": 0,
80
+ "completion_tokens": 0,
81
+ "total_tokens": 0,
82
+ },
83
+ "system_fingerprint": SYSTEM_FINGERPRINT,
84
+ }
85
+
86
+
87
+ def format_sse_chunk(chunk: Dict[str, Any]) -> str:
88
+ """格式化 SSE 响应块。"""
89
+ return f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n"
90
+
91
+
92
+ def format_sse_done() -> str:
93
+ """格式化 SSE 结束标记。"""
94
+ return "data: [DONE]\n\n"
95
+
96
+
97
+ def get_error_message(error: Exception) -> str:
98
+ """从异常中提取更友好的错误消息。"""
99
+ error_str = str(error).strip()
100
+ if not error_str:
101
+ error_str = repr(error)
102
+
103
+ summarized = summarize_upstream_error_text(None, error_str)
104
+ if summarized != error_str:
105
+ return summarized
106
+
107
+ # 特殊处理 SSL 错误
108
+ if "SSL" in error_str or "ssl" in error_str:
109
+ return f"SSL/TLS 连接握手失败,请检查证书或网络环境: {error_str}"
110
+
111
+ # 特殊处理代理错误
112
+ if "proxy" in error_str.lower() or "Proxy" in error_str:
113
+ return f"代理连接失败,请检查代理设置或服务器联通性: {error_str}"
114
+
115
+ # 处理超时
116
+ if "timeout" in error_str.lower():
117
+ return f"连接上游响应超时: {error_str}"
118
+
119
+ return error_str
120
+
121
+
122
+ def resolve_http_error_status(error_code: Any, error_type: Any) -> int:
123
+ """根据标准 error.code / error.type 推导 HTTP 状态码。"""
124
+ if error_code == "model_not_found":
125
+ return 404
126
+ if isinstance(error_code, int) and 400 <= error_code <= 599:
127
+ return error_code
128
+ if (
129
+ error_type == "invalid_request_error"
130
+ or error_code == "invalid_request_error"
131
+ ):
132
+ return 400
133
+ return 500
134
+
135
+
136
+ def handle_error(error: Exception, context: str = "") -> Dict[str, Any]:
137
+ """统一错误处理。
138
+
139
+ 将异常转换为 OpenAI 兼容的错误响应格式。
140
+ 注意:此函数主要用于向后兼容,新代码应直接抛出 AppError 子类。
141
+ """
142
+ from app.exceptions import ModelNotFoundError
143
+
144
+ # 如果已经是 AppError,直接返回其字典形式
145
+ if isinstance(error, AppError):
146
+ return error.to_dict()
147
+
148
+ # 未知模型 → ModelNotFoundError (404)
149
+ error_str = str(error)
150
+ if isinstance(error, ValueError) and ("Unsupported model" in error_str or "不支持的模型" in error_str):
151
+ # 从错误消息中提取模型名称
152
+ import re
153
+ # 匹配 "Unsupported model: xxx" 或 "不支持的模型: xxx"
154
+ match = re.search(r"(?:Unsupported model|不支持的模型)[:\s]*(\S+)", error_str)
155
+ model = match.group(1) if match else "unknown"
156
+ exc = ModelNotFoundError(model)
157
+ logger.warning(error_str)
158
+ return exc.to_dict()
159
+
160
+ if isinstance(error, ValueError):
161
+ exc = ValidationError(str(error))
162
+ logger.warning("invalid request: %s", error)
163
+ return exc.to_dict()
164
+
165
+ # 其他异常 → UpstreamError
166
+ friendly_msg = get_error_message(error)
167
+ error_msg = f"上游{context}错误: {friendly_msg}" if context else f"上游错误: {friendly_msg}"
168
+ logger.error("%s (raw: %s)", error_msg, error)
169
+
170
+ exc = UpstreamError(message=error_msg)
171
+ return exc.to_dict()
app/core/request_signing.py ADDED
@@ -0,0 +1,502 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """请求构建与双层 HMAC 签名模块。
5
+
6
+ 将原 UpstreamClient.transform_request() 中的请求体构建、多模态消息处理
7
+ 和签名逻辑提取为独立函数。
8
+ """
9
+
10
+ import asyncio
11
+ import time
12
+ import uuid
13
+ from datetime import datetime
14
+ import mimetypes
15
+ from typing import Any, Dict, List, Optional, Tuple
16
+ from urllib.parse import urlencode
17
+
18
+ import httpx
19
+
20
+ from app.core.config import settings
21
+ from app.core.headers import build_dynamic_headers
22
+ from app.core.file_upload import upload_file
23
+ from app.utils.fe_version import get_latest_fe_version
24
+ from app.utils.logger import logger, log_exception
25
+ from app.utils.signature import generate_signature
26
+ from app.core.resin_compat import apply_resin_account_header
27
+
28
+
29
+ def _extract_image_url(part: Dict[str, Any]) -> str:
30
+ image_url = part.get("image_url")
31
+ if isinstance(image_url, dict):
32
+ return str(image_url.get("url") or "")
33
+ if isinstance(image_url, str):
34
+ return image_url
35
+ return ""
36
+
37
+
38
+ def _extract_file_payload(part: Dict[str, Any]) -> Dict[str, Any]:
39
+ payload = part.get("file")
40
+ if isinstance(payload, dict):
41
+ return {
42
+ key: value
43
+ for key, value in payload.items()
44
+ if value is not None
45
+ }
46
+
47
+ return {
48
+ key: value
49
+ for key in ("file_id", "file_url", "file_data", "filename")
50
+ for value in [part.get(key)]
51
+ if value is not None
52
+ }
53
+
54
+
55
+ def _build_file_data_url(file_payload: Dict[str, Any]) -> Optional[str]:
56
+ file_data = file_payload.get("file_data")
57
+ if isinstance(file_data, str) and file_data.strip():
58
+ if file_data.startswith("data:"):
59
+ return file_data
60
+ filename = str(file_payload.get("filename") or "attachment").strip()
61
+ mime_type = mimetypes.guess_type(filename)[0] or "application/octet-stream"
62
+ return f"data:{mime_type};base64,{file_data}"
63
+
64
+ file_url = file_payload.get("file_url")
65
+ if isinstance(file_url, str) and file_url.startswith("data:"):
66
+ return file_url
67
+
68
+ return None
69
+
70
+
71
+ async def _append_image_part(
72
+ *,
73
+ image_url: str,
74
+ token: str,
75
+ user_id: str,
76
+ chat_id: str,
77
+ auth_mode: str,
78
+ http_client: httpx.AsyncClient,
79
+ base_url: str,
80
+ ) -> Tuple[Optional[Dict[str, Any]], Optional[Dict[str, Any]], Optional[str]]:
81
+ """Upload an image and return (image_part, file_info, error_text)."""
82
+ if not image_url:
83
+ return None, None, None
84
+
85
+ logger.debug("检测到图片: %s...", image_url[:50])
86
+ if image_url.startswith("data:") and auth_mode != "guest":
87
+ logger.debug("[image] upload base64 image to upstream service")
88
+ file_info = await upload_file(
89
+ http_client,
90
+ base_url,
91
+ image_url,
92
+ chat_id,
93
+ token,
94
+ user_id,
95
+ auth_mode=auth_mode,
96
+ )
97
+ if file_info:
98
+ logger.debug("[image] image added to files array")
99
+ image_ref = f"{file_info['id']}_{file_info['name']}"
100
+ image_part = {
101
+ "type": "image_url",
102
+ "image_url": {"url": image_ref},
103
+ }
104
+ logger.debug("图片引用: %s", image_ref)
105
+ return image_part, file_info, None
106
+
107
+ logger.warning("⚠️ 图片上传失败")
108
+ return None, None, "[系统提示: 图片上传失败]"
109
+
110
+ if auth_mode != "guest":
111
+ logger.warning("⚠️ 非 base64 图片或匿名模式,保留原始URL")
112
+ image_part = {
113
+ "type": "image_url",
114
+ "image_url": {"url": image_url},
115
+ }
116
+ return image_part, None, None
117
+
118
+
119
+ async def _append_file_part(
120
+ *,
121
+ part: Dict[str, Any],
122
+ token: str,
123
+ user_id: str,
124
+ chat_id: str,
125
+ auth_mode: str,
126
+ http_client: httpx.AsyncClient,
127
+ base_url: str,
128
+ ) -> Dict[str, Any]:
129
+ """Upload a file attachment and return the file_info dict."""
130
+ file_payload = _extract_file_payload(part)
131
+ if not file_payload:
132
+ raise ValueError("file content part requires file_id, file_url, or file_data")
133
+
134
+ data_url = _build_file_data_url(file_payload)
135
+ if not data_url:
136
+ if file_payload.get("file_id"):
137
+ raise ValueError(
138
+ "file_id references are not supported on this upstream; provide file_data instead"
139
+ )
140
+ raise ValueError(
141
+ "file_url is only supported when provided as a data URL"
142
+ )
143
+
144
+ if auth_mode == "guest":
145
+ raise ValueError("file attachments require an authenticated upstream session")
146
+
147
+ file_info = await upload_file(
148
+ http_client,
149
+ base_url,
150
+ data_url,
151
+ chat_id,
152
+ token,
153
+ user_id,
154
+ auth_mode=auth_mode,
155
+ )
156
+ if not file_info:
157
+ raise ValueError("file upload failed")
158
+
159
+ logger.debug("[file] file added to files array")
160
+ return file_info
161
+
162
+
163
+ async def process_multimodal_messages(
164
+ normalized_messages: List[Dict[str, Any]],
165
+ token: str,
166
+ user_id: str,
167
+ chat_id: str,
168
+ auth_mode: str,
169
+ http_client: httpx.AsyncClient,
170
+ base_url: str,
171
+ ) -> tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
172
+ """处理多模态消息:分离文本与图片,并上传 base64 图片。
173
+
174
+ Uploads are collected and executed concurrently via asyncio.gather,
175
+ then merged back in original order.
176
+
177
+ Args:
178
+ normalized_messages: 经过预处理的消息列表。
179
+ token: 认证令牌。
180
+ user_id: 用户 ID。
181
+ chat_id: 对话 ID。
182
+ auth_mode: 鉴权模式,guest 模式禁止上传。
183
+ http_client: 可复用 HTTP 客户端。
184
+ base_url: 上游服务基础 URL。
185
+
186
+ Returns:
187
+ ``(messages, files)`` 元组:
188
+ - ``messages``: 上游格式的消息列表。
189
+ - ``files``: 已上传文件信息列表(仅认证模式且有图片时非空)。
190
+ """
191
+ messages: List[Dict[str, Any]] = []
192
+ files: List[Dict[str, Any]] = []
193
+
194
+ # Per-message state for deferred upload assembly
195
+ # Each entry: (msg_index, role, text_parts, upload_slots)
196
+ # upload_slots: list of (slot_index, type, coroutine)
197
+ deferred_messages: List[Tuple[str, List[str], List]] = []
198
+ pending_coroutines: List = [] # (msg_idx, slot_idx, type, coro)
199
+
200
+ for msg in normalized_messages:
201
+ role = str(msg.get("role", "user"))
202
+ content = msg.get("content")
203
+
204
+ if isinstance(content, str):
205
+ messages.append({"role": role, "content": content})
206
+ continue
207
+
208
+ if isinstance(content, list):
209
+ text_parts: List[str] = []
210
+ upload_slots: List = [] # (slot_idx, type("image"|"file"), part_data)
211
+
212
+ for part in content:
213
+ if isinstance(part, dict) and part.get("type") == "text":
214
+ text_parts.append(str(part.get("text") or ""))
215
+ continue
216
+
217
+ if isinstance(part, dict) and part.get("type") == "image_url":
218
+ slot_idx = len(upload_slots)
219
+ image_url = _extract_image_url(part)
220
+ coro = _append_image_part(
221
+ image_url=image_url,
222
+ token=token,
223
+ user_id=user_id,
224
+ chat_id=chat_id,
225
+ auth_mode=auth_mode,
226
+ http_client=http_client,
227
+ base_url=base_url,
228
+ )
229
+ upload_slots.append(("image", coro))
230
+ pending_coroutines.append((len(deferred_messages), slot_idx, "image", coro))
231
+ continue
232
+
233
+ if isinstance(part, dict) and part.get("type") in ("file", "input_file"):
234
+ slot_idx = len(upload_slots)
235
+ coro = _append_file_part(
236
+ part=part,
237
+ token=token,
238
+ user_id=user_id,
239
+ chat_id=chat_id,
240
+ auth_mode=auth_mode,
241
+ http_client=http_client,
242
+ base_url=base_url,
243
+ )
244
+ upload_slots.append(("file", coro))
245
+ pending_coroutines.append((len(deferred_messages), slot_idx, "file", coro))
246
+ continue
247
+
248
+ if isinstance(part, dict) and part.get("type") == "input_audio":
249
+ raise ValueError(
250
+ "input_audio is not supported by this upstream yet"
251
+ )
252
+
253
+ if isinstance(part, str):
254
+ text_parts.append(part)
255
+
256
+ deferred_messages.append((role, text_parts, upload_slots))
257
+ continue
258
+
259
+ # Execute all uploads concurrently
260
+ if pending_coroutines:
261
+ coroutines = [item[3] for item in pending_coroutines]
262
+ results = await asyncio.gather(*coroutines, return_exceptions=True)
263
+
264
+ # Build a lookup: (msg_idx, slot_idx) -> result
265
+ result_map: Dict[Tuple[int, int], Any] = {}
266
+ for (msg_idx, slot_idx, upload_type, _coro), result in zip(pending_coroutines, results):
267
+ result_map[(msg_idx, slot_idx)] = (upload_type, result)
268
+
269
+ # Assemble deferred messages
270
+ for msg_idx, (role, text_parts, upload_slots) in enumerate(deferred_messages):
271
+ image_parts: List[Dict[str, Any]] = []
272
+
273
+ for slot_idx, (slot_type, _) in enumerate(upload_slots):
274
+ key = (msg_idx, slot_idx)
275
+ upload_type, result = result_map[key]
276
+
277
+ if isinstance(result, Exception):
278
+ if upload_type == "image":
279
+ text_parts.append("[系统提示: 图片上传失败]")
280
+ logger.warning("⚠️ 图片上传异常: %s", result)
281
+ else:
282
+ logger.warning("⚠️ 文件上传异常: %s", result)
283
+ continue
284
+
285
+ if upload_type == "image":
286
+ # result is (image_part, file_info, error_text)
287
+ image_part, file_info, error_text = result
288
+ if error_text:
289
+ text_parts.append(error_text)
290
+ if file_info:
291
+ files.append(file_info)
292
+ if image_part:
293
+ image_parts.append(image_part)
294
+ else:
295
+ # result is file_info dict
296
+ files.append(result)
297
+
298
+ message_content: List[Dict[str, Any]] = []
299
+ combined_text = " ".join(text_parts).strip()
300
+ if combined_text:
301
+ message_content.append({"type": "text", "text": combined_text})
302
+ message_content.extend(image_parts)
303
+
304
+ if message_content:
305
+ messages.append({"role": role, "content": message_content})
306
+ else:
307
+ # No uploads needed — assemble deferred messages directly
308
+ for role, text_parts, upload_slots in deferred_messages:
309
+ message_content_list: List[Dict[str, Any]] = []
310
+ combined_text = " ".join(text_parts).strip()
311
+ if combined_text:
312
+ message_content_list.append({"type": "text", "text": combined_text})
313
+ if message_content_list:
314
+ messages.append({"role": role, "content": message_content_list})
315
+
316
+ return messages, files
317
+
318
+
319
+ def build_upstream_body(
320
+ messages: List[Dict[str, Any]],
321
+ files: List[Dict[str, Any]],
322
+ upstream_model_id: str,
323
+ last_user_text: str,
324
+ chat_id: str,
325
+ message_id: str,
326
+ enable_thinking: bool,
327
+ web_search: bool,
328
+ auto_web_search: bool,
329
+ flags: List[str],
330
+ extra: Dict[str, Any],
331
+ mcp_servers: List[str],
332
+ temperature: Optional[float],
333
+ max_tokens: Optional[int],
334
+ parent_message_id: Optional[str] = None,
335
+ captcha_verify_param: Optional[str] = None,
336
+ ) -> Dict[str, Any]:
337
+ """构建发送到上游的请求 JSON body。
338
+
339
+ Args:
340
+ messages: 上游格式消息列表。
341
+ files: 已上传文件信息列表。
342
+ upstream_model_id: 上游实际模型 ID。
343
+ last_user_text: 最后一条用户消息(用于签名占位符)。
344
+ chat_id: 对话 ID。
345
+ message_id: 消息 ID(当前消息的 UUID)。
346
+ enable_thinking: 是否启用思考模式。
347
+ web_search: 是否启用网络搜索。
348
+ auto_web_search: 是否启用自动网络搜索。
349
+ flags: 功能标志列表(如 ["general_agent"])。
350
+ extra: 额外参数字典。
351
+ mcp_servers: MCP 服务器 ID 列表。
352
+ temperature: 采样温度,None 时不添加到 params。
353
+ max_tokens: 最大 token 数,None 时不添加到 params。
354
+ parent_message_id: 父消息 ID(用于链式会话)。
355
+
356
+ Returns:
357
+ 完整的上游请求 body 字典。
358
+ """
359
+ body: Dict[str, Any] = {
360
+ "stream": True, # 总是使用流式
361
+ "model": upstream_model_id,
362
+ "messages": messages,
363
+ "signature_prompt": last_user_text, # 用于签名的最后一条用户消息
364
+ "params": {},
365
+ "extra": extra,
366
+ "features": {
367
+ "image_generation": False,
368
+ "web_search": web_search,
369
+ "auto_web_search": auto_web_search,
370
+ "preview_mode": True,
371
+ "flags": flags,
372
+ "vlm_tools_enable": False,
373
+ "vlm_web_search_enable": False,
374
+ "vlm_website_mode": False,
375
+ "enable_thinking": enable_thinking,
376
+ },
377
+ "background_tasks": {
378
+ "title_generation": settings.UPSTREAM_BACKGROUND_TASKS,
379
+ "tags_generation": settings.UPSTREAM_BACKGROUND_TASKS,
380
+ },
381
+ "variables": {
382
+ "{{USER_NAME}}": settings.UPSTREAM_USER_NAME,
383
+ "{{USER_LOCATION}}": settings.UPSTREAM_USER_LOCATION,
384
+ "{{CURRENT_DATETIME}}": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
385
+ "{{CURRENT_DATE}}": datetime.now().strftime("%Y-%m-%d"),
386
+ "{{CURRENT_TIME}}": datetime.now().strftime("%H:%M:%S"),
387
+ "{{CURRENT_WEEKDAY}}": datetime.now().strftime("%A"),
388
+ "{{CURRENT_TIMEZONE}}": settings.UPSTREAM_USER_TIMEZONE,
389
+ "{{USER_LANGUAGE}}": settings.UPSTREAM_USER_LANGUAGE,
390
+ },
391
+ "chat_id": chat_id,
392
+ "id": message_id,
393
+ "current_user_message_id": str(uuid.uuid4()),
394
+ "current_user_message_parent_id": parent_message_id,
395
+ }
396
+
397
+ # Captcha 验证参数
398
+ if captcha_verify_param:
399
+ body["captcha_verify_param"] = captcha_verify_param
400
+
401
+ # 只在有图片时才包含 files 字段
402
+ if files:
403
+ body["files"] = files
404
+
405
+ # 只在有 MCP 服务器时才包含
406
+ if mcp_servers:
407
+ body["mcp_servers"] = mcp_servers
408
+
409
+ # 处理其他参数
410
+ # if temperature is not None:
411
+ # body["params"]["temperature"] = temperature
412
+ # if max_tokens is not None:
413
+ # body["params"]["max_tokens"] = max_tokens
414
+
415
+ return body
416
+
417
+
418
+ async def sign_request(
419
+ api_endpoint: str,
420
+ user_id: str,
421
+ last_user_text: str,
422
+ chat_id: str,
423
+ token: str,
424
+ fe_version: Optional[str] = None,
425
+ ) -> tuple[str, Dict[str, str], str]:
426
+ """生成双层 HMAC 签名并构造带签名的 URL 和请求头。
427
+
428
+ Args:
429
+ api_endpoint: 上游 API 端点 URL(不含 query 参数)。
430
+ user_id: 用户 ID,用于签名元数据。
431
+ last_user_text: 最后一条用户消息文本,用于签名载荷。
432
+ chat_id: 对话 ID,用于构建 Referer 和 URL 路径。
433
+ token: 认证令牌,添加到请求头 Authorization。
434
+ fe_version: 可选前端版本号,传入时跳过网络拉取(用于并行预取)。
435
+
436
+ Returns:
437
+ ``(signed_url, headers, fe_version)`` 三元组:
438
+ - ``signed_url``: 带完整 query 参数的签名 URL。
439
+ - ``headers``: 包含 Authorization、X-Signature 等所有请求头的字典。
440
+ - ``fe_version``: 使用的前端版本号。
441
+ """
442
+ timestamp_ms = int(time.time() * 1000)
443
+ request_id = str(uuid.uuid4())
444
+ if fe_version is None:
445
+ fe_version = await get_latest_fe_version()
446
+
447
+ try:
448
+ signing_metadata = f"requestId,{request_id},timestamp,{timestamp_ms},user_id,{user_id}"
449
+ prompt_for_signature = last_user_text or ""
450
+ signature_result = generate_signature(
451
+ e=signing_metadata,
452
+ t=prompt_for_signature,
453
+ s=timestamp_ms,
454
+ )
455
+ signature = signature_result["signature"]
456
+ logger.debug(
457
+ "[上游] 生成签名成功: %s... "
458
+ "(user_id=%s, request_id=%s)",
459
+ signature[:16], user_id, request_id,
460
+ )
461
+ except Exception as e:
462
+ log_exception(logger, "[上游] 签名生成失败")
463
+ raise RuntimeError(f"签名生成失败: {e}") from e
464
+
465
+ # 构建请求头
466
+ headers = build_dynamic_headers(fe_version, chat_id)
467
+ headers.update(
468
+ {
469
+ "Authorization": f"Bearer {token}",
470
+ "X-Signature": signature,
471
+ }
472
+ )
473
+ apply_resin_account_header(headers, token)
474
+
475
+ # 构建 URL query params。
476
+ # 仅保留签名核心字段(timestamp / requestId / user_id / token / platform / version /
477
+ # signature_timestamp)。浏览器指纹类字段(user_agent、screen_*、current_url、title、
478
+ # local_time、…)放在 URL 上会让请求行超过 1KB,并触发阿里云 ESA WAF 的"嵌套 URL +
479
+ # 长 URL"规则,拒绝码就是 HTTP 405 + 拦截 HTML。
480
+ query_params = {
481
+ "timestamp": str(timestamp_ms),
482
+ "requestId": request_id,
483
+ "user_id": user_id,
484
+ "version": "0.0.1",
485
+ "platform": "web",
486
+ "token": token,
487
+ "signature_timestamp": str(timestamp_ms),
488
+ }
489
+ signed_url = f"{api_endpoint}?{urlencode(query_params)}"
490
+
491
+ logger.debug(
492
+ "[上游] 请求头: Authorization=Bearer %s, "
493
+ "X-Signature=%s...",
494
+ token, signature[:16] if signature else '(空)',
495
+ )
496
+ logger.debug(
497
+ "[上游] URL 参数: timestamp=%s, "
498
+ "requestId=%s, user_id=%s",
499
+ timestamp_ms, request_id, user_id,
500
+ )
501
+
502
+ return signed_url, headers, fe_version
app/core/resin_compat.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """Helpers for optional Resin-specific upstream request compatibility."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import hashlib
9
+ from typing import MutableMapping
10
+
11
+ from app.core.config import settings
12
+
13
+ RESIN_ACCOUNT_HEADER = "X-Resin-Account"
14
+ RESIN_ACCOUNT_PREFIX = "zai-token"
15
+
16
+
17
+ def build_resin_account(token: str) -> str:
18
+ """Build a stable, opaque Resin account key for one upstream token."""
19
+ raw = str(token or "").strip()
20
+ if not raw:
21
+ return ""
22
+
23
+ digest = hashlib.sha256(raw.encode("utf-8")).hexdigest()
24
+ return f"{RESIN_ACCOUNT_PREFIX}:{digest}"
25
+
26
+
27
+ def apply_resin_account_header(
28
+ headers: MutableMapping[str, str],
29
+ token: str,
30
+ ) -> MutableMapping[str, str]:
31
+ """Attach the Resin account header when compatibility mode is enabled."""
32
+ if not settings.RESIN_COMPAT_ENABLED:
33
+ headers.pop(RESIN_ACCOUNT_HEADER, None)
34
+ return headers
35
+
36
+ account = build_resin_account(token)
37
+ if account:
38
+ headers[RESIN_ACCOUNT_HEADER] = account
39
+ else:
40
+ headers.pop(RESIN_ACCOUNT_HEADER, None)
41
+ return headers
app/core/response_handler.py ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """Minimal SSE response handler.
5
+
6
+ Converts upstream SSE responses to OpenAI-compatible format.
7
+ """
8
+
9
+ import json
10
+ import time
11
+ import uuid
12
+ from dataclasses import dataclass, field
13
+ from typing import Any, AsyncGenerator, Dict, List, Optional, Tuple
14
+
15
+ import httpx
16
+
17
+ from app.core.openai_compat import (
18
+ create_openai_chunk,
19
+ create_openai_response_with_reasoning,
20
+ format_sse_chunk,
21
+ format_sse_done,
22
+ get_error_message,
23
+ handle_error,
24
+ )
25
+ from app.utils.logger import logger, log_exception
26
+
27
+
28
+ # ------------------------------------------------------------------
29
+ # UpstreamChunkEvent
30
+ # ------------------------------------------------------------------
31
+
32
+
33
+ @dataclass
34
+ class UpstreamChunkEvent:
35
+ delta_content: str = ""
36
+ edit_content: str = ""
37
+ edit_index: Optional[int] = None
38
+ phase: str = ""
39
+ done: bool = False
40
+ usage: Optional[Dict] = None
41
+ error: Optional[Dict] = None
42
+ data: Dict = field(default_factory=dict)
43
+ chunk_type: str = ""
44
+ raw_chunk: Optional[Dict] = None
45
+
46
+
47
+ def _parse_chunk_event(chunk: dict) -> Optional[UpstreamChunkEvent]:
48
+ if not isinstance(chunk, dict):
49
+ return None
50
+
51
+ chunk_type = str(chunk.get("type", ""))
52
+ data: Any = chunk.get("data", {}) if chunk_type == "chat:completion" else chunk
53
+ if not isinstance(data, dict):
54
+ return None
55
+
56
+ error = None
57
+ if chunk.get("error"):
58
+ err = chunk["error"]
59
+ error = err if isinstance(err, dict) else {"detail": str(err), "code": "UNKNOWN"}
60
+ elif data.get("error"):
61
+ err = data["error"]
62
+ error = err if isinstance(err, dict) else {"detail": str(err), "code": "UNKNOWN"}
63
+ elif isinstance(data.get("inner"), dict) and data["inner"].get("error"):
64
+ err = data["inner"]["error"]
65
+ error = err if isinstance(err, dict) else {"detail": str(err), "code": "UNKNOWN"}
66
+
67
+ return UpstreamChunkEvent(
68
+ delta_content=str(data.get("delta_content", "") or ""),
69
+ edit_content=str(data.get("edit_content", "") or ""),
70
+ edit_index=data.get("edit_index") if isinstance(data.get("edit_index"), int) else None,
71
+ phase=str(data.get("phase", "") or ""),
72
+ done=bool(data.get("done") is True),
73
+ usage=(
74
+ data.get("usage") if isinstance(data.get("usage"), dict)
75
+ else chunk.get("usage") if isinstance(chunk.get("usage"), dict)
76
+ else None
77
+ ),
78
+ error=error,
79
+ data=data,
80
+ chunk_type=chunk_type,
81
+ raw_chunk=chunk,
82
+ )
83
+
84
+
85
+ # ------------------------------------------------------------------
86
+ # StreamContext
87
+ # ------------------------------------------------------------------
88
+
89
+
90
+ @dataclass
91
+ class StreamContext:
92
+ chat_id: str
93
+ model: str
94
+ stream_id: Optional[str] = None
95
+ created_at: Optional[int] = None
96
+ buffered_content: str = ""
97
+ usage_info: Dict[str, Any] = field(
98
+ default_factory=lambda: {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}
99
+ )
100
+ has_sent_role: bool = False
101
+ finished: bool = False
102
+ line_count: int = 0
103
+ last_phase: Optional[str] = None
104
+
105
+ def ensure_stream_id(self, chunk_data: Optional[Dict] = None) -> str:
106
+ if self.stream_id is None:
107
+ upstream_id = chunk_data.get("id") if isinstance(chunk_data, dict) else None
108
+ self.stream_id = upstream_id or f"chatcmpl-{uuid.uuid4().hex[:12]}"
109
+ self.created_at = int(time.time())
110
+ return self.stream_id
111
+
112
+
113
+ # ------------------------------------------------------------------
114
+ # ResponseHandler
115
+ # ------------------------------------------------------------------
116
+
117
+
118
+ class ResponseHandler:
119
+
120
+ # SSE helpers
121
+
122
+ def _emit_sse(self, ctx: StreamContext, delta: Dict[str, Any]) -> List[str]:
123
+ output: List[str] = []
124
+ role_sse = self._ensure_role_sse(ctx)
125
+ if role_sse:
126
+ output.append(role_sse)
127
+ output.append(format_sse_chunk(
128
+ create_openai_chunk(ctx.ensure_stream_id(), ctx.model, delta, created=ctx.created_at)
129
+ ))
130
+ return output
131
+
132
+ def _terminal_sse(self, ctx: StreamContext, *, finish_reason: str) -> List[str]:
133
+ chunk = create_openai_chunk(ctx.ensure_stream_id(), ctx.model, {}, finish_reason, created=ctx.created_at)
134
+ chunk["usage"] = ctx.usage_info
135
+ return [format_sse_chunk(chunk), format_sse_done()]
136
+
137
+ def _ensure_role_sse(self, ctx: StreamContext) -> Optional[str]:
138
+ if ctx.has_sent_role:
139
+ return None
140
+ ctx.has_sent_role = True
141
+ return format_sse_chunk(
142
+ create_openai_chunk(ctx.ensure_stream_id(), ctx.model, {"role": "assistant"}, created=ctx.created_at)
143
+ )
144
+
145
+ # SSE line parsing
146
+
147
+ @staticmethod
148
+ def _extract_sse_payload(line: str) -> Tuple[str, str]:
149
+ if not line:
150
+ return "skip", ""
151
+ if line.startswith("data:"):
152
+ payload = line[5:].strip()
153
+ else:
154
+ stripped = line.strip()
155
+ if not stripped:
156
+ return "skip", ""
157
+ if not stripped.startswith("data:"):
158
+ return "non_data", stripped
159
+ payload = stripped[5:].strip()
160
+ if not payload:
161
+ return "skip", ""
162
+ if payload == "[DONE]" or payload.casefold() == "done":
163
+ return "done", ""
164
+ return "data", payload
165
+
166
+ def _parse_sse_line(self, line: str, ctx: StreamContext) -> Tuple[str, Optional[UpstreamChunkEvent]]:
167
+ if not line.strip():
168
+ return "skip", None
169
+ ctx.line_count += 1
170
+ state, chunk_str = self._extract_sse_payload(line)
171
+ if state == "done":
172
+ return "done", None
173
+ if state != "data":
174
+ return "skip", None
175
+ try:
176
+ chunk = json.loads(chunk_str)
177
+ except json.JSONDecodeError:
178
+ return "skip", None
179
+ if not isinstance(chunk, dict):
180
+ return "skip", None
181
+ event = _parse_chunk_event(chunk)
182
+ return ("ok", event) if event else ("skip", None)
183
+
184
+ # State update
185
+
186
+ def _update_state(self, ctx: StreamContext, event: UpstreamChunkEvent) -> None:
187
+ ctx.ensure_stream_id(event.raw_chunk)
188
+ phase = event.phase
189
+ if phase and phase != ctx.last_phase:
190
+ ctx.last_phase = phase
191
+ if event.usage and event.usage != ctx.usage_info:
192
+ ctx.usage_info = event.usage
193
+
194
+ # Content accumulation (needed for edit_index insertion)
195
+
196
+ def _accumulate(self, ctx: StreamContext, event: UpstreamChunkEvent) -> str:
197
+ max_len = 50000
198
+ if event.delta_content:
199
+ ctx.buffered_content = (ctx.buffered_content + event.delta_content)[-max_len:]
200
+ return event.delta_content
201
+ if event.edit_content:
202
+ idx = event.edit_index
203
+ if idx is not None and isinstance(idx, int):
204
+ safe = max(0, min(idx, len(ctx.buffered_content)))
205
+ ctx.buffered_content = ctx.buffered_content[:safe] + event.edit_content + ctx.buffered_content[safe:]
206
+ if len(ctx.buffered_content) > max_len:
207
+ ctx.buffered_content = ctx.buffered_content[-max_len:]
208
+ else:
209
+ ctx.buffered_content = (ctx.buffered_content + event.edit_content)[-max_len:]
210
+ return event.edit_content
211
+ return ""
212
+
213
+ # Error check
214
+
215
+ def _check_error(self, ctx: StreamContext, event: UpstreamChunkEvent) -> Optional[List[str]]:
216
+ if not event.error:
217
+ return None
218
+ code = event.error.get("code", "UNKNOWN")
219
+ detail = get_error_message(Exception(str(event.error.get("detail", "Unknown upstream error"))))
220
+ if event.done:
221
+ return None
222
+ logger.error("upstream SSE error: code=%s, detail=%s", code, detail)
223
+ output: List[str] = []
224
+ role = self._ensure_role_sse(ctx)
225
+ if role:
226
+ output.append(role)
227
+ output.append(f'data: {json.dumps({"error": {"message": detail, "type": "upstream_error", "code": code}})}\n\n')
228
+ output.append("data: [DONE]\n\n")
229
+ return output
230
+
231
+ # Search results
232
+
233
+ def _format_search(self, data: Dict[str, Any]) -> str:
234
+ info = data.get("results") or data.get("sources") or data.get("citations")
235
+ if not isinstance(info, list) or not info:
236
+ return ""
237
+ parts = []
238
+ for i, item in enumerate(info, 1):
239
+ if not isinstance(item, dict):
240
+ continue
241
+ title = item.get("title") or item.get("name") or f"Result {i}"
242
+ url = item.get("url") or item.get("link")
243
+ if url:
244
+ parts.append(f"[{i}] [{title}]({url})")
245
+ return ("\n\n---\n" + "\n".join(parts)) if parts else ""
246
+
247
+ # Phase output
248
+
249
+ def _emit_phase(self, ctx: StreamContext, event: UpstreamChunkEvent, text: str) -> List[str]:
250
+ phase = ctx.last_phase
251
+
252
+ if phase == "thinking" and event.delta_content:
253
+ return self._emit_sse(ctx, {"reasoning_content": event.delta_content})
254
+
255
+ if phase in ("answer", "other") and text:
256
+ return self._emit_sse(ctx, {"content": text})
257
+
258
+ if phase == "search" or event.chunk_type == "web_search":
259
+ citation = self._format_search(event.data)
260
+ if citation:
261
+ return self._emit_sse(ctx, {"content": citation})
262
+
263
+ return []
264
+
265
+ # Non-stream edit helper
266
+
267
+ @staticmethod
268
+ def _apply_edit(parts: List[str], edit: str, idx: Optional[int]) -> None:
269
+ if not edit:
270
+ return
271
+ if idx is not None and isinstance(idx, int):
272
+ joined = "".join(parts)
273
+ safe = max(0, min(idx, len(joined)))
274
+ parts[:] = [joined[:safe] + edit + joined[safe:]]
275
+ else:
276
+ parts.append(edit)
277
+
278
+ # ==================================================================
279
+ # Stream response (main entry)
280
+ # ==================================================================
281
+
282
+ async def handle_stream_response(
283
+ self,
284
+ response: httpx.Response,
285
+ chat_id: str,
286
+ model: str,
287
+ started_at: Optional[float] = None,
288
+ ) -> AsyncGenerator[str, None]:
289
+ if started_at:
290
+ logger.debug("[stream] start SSE, ttfb: %.3fs", time.perf_counter() - started_at)
291
+
292
+ sse_start = time.perf_counter()
293
+ ctx = StreamContext(chat_id=chat_id, model=model)
294
+
295
+ try:
296
+ async for line in response.aiter_lines():
297
+ state, event = self._parse_sse_line(line, ctx)
298
+ if state == "done":
299
+ break
300
+ if state != "ok" or event is None:
301
+ continue
302
+
303
+ err = self._check_error(ctx, event)
304
+ if err:
305
+ for sse in err:
306
+ yield sse
307
+ return
308
+
309
+ self._update_state(ctx, event)
310
+ text = self._accumulate(ctx, event)
311
+
312
+ for sse in self._emit_phase(ctx, event, text):
313
+ yield sse
314
+
315
+ if event.done:
316
+ break
317
+
318
+ if not ctx.finished:
319
+ role = self._ensure_role_sse(ctx)
320
+ if role:
321
+ yield role
322
+ for sse in self._terminal_sse(ctx, finish_reason="stop"):
323
+ yield sse
324
+ ctx.finished = True
325
+
326
+ except Exception as e:
327
+ log_exception(logger, "stream error")
328
+ if not ctx.finished:
329
+ yield format_sse_chunk(
330
+ create_openai_chunk(ctx.ensure_stream_id(), model, {}, "stop", created=ctx.created_at)
331
+ )
332
+ yield format_sse_done()
333
+ finally:
334
+ elapsed = time.perf_counter() - sse_start
335
+ total = f", total: {time.perf_counter() - started_at:.3f}s" if started_at else ""
336
+ logger.debug("[stream] done %s lines, %.3fs%s", ctx.line_count, elapsed, total)
337
+
338
+ # ==================================================================
339
+ # Non-stream response
340
+ # ==================================================================
341
+
342
+ async def handle_non_stream_response(
343
+ self,
344
+ response: httpx.Response,
345
+ chat_id: str,
346
+ model: str,
347
+ ) -> Dict[str, Any]:
348
+ content_parts: List[str] = []
349
+ reasoning_parts: List[str] = []
350
+ usage: Dict[str, Any] = {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}
351
+ last_phase = None
352
+
353
+ try:
354
+ async for line in response.aiter_lines():
355
+ state, payload = self._extract_sse_payload(line)
356
+ if state == "non_data":
357
+ try:
358
+ err = json.loads(payload)
359
+ if isinstance(err, dict) and ("error" in err or "code" in err or "message" in err):
360
+ msg = (
361
+ (err.get("error") or {}).get("message")
362
+ if isinstance(err.get("error"), dict)
363
+ else err.get("message")
364
+ ) or "upstream error"
365
+ return handle_error(Exception(msg), "API response")
366
+ except Exception:
367
+ pass
368
+ continue
369
+ if state != "data":
370
+ continue
371
+
372
+ try:
373
+ chunk = json.loads(payload)
374
+ except json.JSONDecodeError:
375
+ continue
376
+
377
+ event = _parse_chunk_event(chunk)
378
+ if event is None:
379
+ continue
380
+
381
+ phase = event.phase
382
+ if phase and phase != last_phase:
383
+ last_phase = phase
384
+
385
+ if phase == "thinking" and event.delta_content:
386
+ reasoning_parts.append(event.delta_content)
387
+ elif phase == "answer":
388
+ if event.delta_content:
389
+ content_parts.append(event.delta_content)
390
+ elif event.edit_content:
391
+ self._apply_edit(content_parts, event.edit_content, event.edit_index)
392
+ elif phase == "other" and event.edit_content:
393
+ self._apply_edit(content_parts, event.edit_content, event.edit_index)
394
+ elif phase == "search" or event.chunk_type == "web_search":
395
+ s = self._format_search(event.data)
396
+ if s:
397
+ content_parts.append(s)
398
+
399
+ if event.usage:
400
+ usage = event.usage
401
+
402
+ except Exception as e:
403
+ log_exception(logger, "non-stream error")
404
+ return handle_error(e, "non-stream aggregation")
405
+
406
+ final = "".join(content_parts).strip()
407
+ reasoning = "".join(reasoning_parts).strip()
408
+ if not final and reasoning:
409
+ final = reasoning
410
+
411
+ return create_openai_response_with_reasoning(chat_id, model, final, reasoning, usage)
app/core/retry_policy.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """双池重试策略模块。
5
+
6
+ 将原 UpstreamClient 中的双池(认证池 + 匿名池)重试决策逻辑提取为
7
+ 独立的 RetryPolicy 类,以及错误解析工具函数。
8
+ 所有方法签名与原实现保持一致。
9
+ """
10
+
11
+ import json
12
+ import re
13
+ from typing import Any, Dict, Optional, Tuple
14
+
15
+ from app.core.config import settings
16
+ from app.utils.logger import logger
17
+ from app.utils.token_pool import get_token_pool
18
+ from app.utils.guest_session_pool import get_guest_session_pool
19
+
20
+ _HTML_ERROR_PAGE_RE = re.compile(
21
+ r"<(?:!doctype|html|head|body|title|h1|div|p|code)\b",
22
+ re.IGNORECASE,
23
+ )
24
+ _HTML_CONTENT_TYPE_RE = re.compile(
25
+ r"(?:^|[;\s])(text/html|application/xhtml\+xml)(?:$|[;\s])",
26
+ re.IGNORECASE,
27
+ )
28
+
29
+
30
+ def is_upstream_page_response(
31
+ content_type: Optional[str],
32
+ error_text: str,
33
+ ) -> bool:
34
+ """判断上游响应是否为网页/拦截页,而非标准 API 错误。"""
35
+ if content_type and _HTML_CONTENT_TYPE_RE.search(content_type):
36
+ return True
37
+
38
+ text = (error_text or "").lstrip()
39
+ return bool(text) and bool(_HTML_ERROR_PAGE_RE.search(text[:2048]))
40
+
41
+
42
+ def get_upstream_page_error_message(status_code: Optional[int]) -> str:
43
+ """为网页类型错误生成统一消息。"""
44
+ if not isinstance(status_code, int):
45
+ return "上游返回网页错误"
46
+
47
+ normalized_status = status_code if status_code >= 400 else 502
48
+
49
+ if normalized_status in (401, 403, 405):
50
+ base_message = "上游网页访问被拦截"
51
+ elif normalized_status == 429:
52
+ base_message = "上游网页请求过于频繁"
53
+ elif normalized_status in (502, 504):
54
+ base_message = "上游网页网关异常"
55
+ elif normalized_status == 503:
56
+ base_message = "上游网页服务不可用"
57
+ elif normalized_status >= 500:
58
+ base_message = "上游网页服务异常"
59
+ else:
60
+ base_message = "上游返回网页错误"
61
+
62
+ return f"{base_message} (HTTP {normalized_status})"
63
+
64
+
65
+ def summarize_upstream_error_text(
66
+ status_code: Optional[int],
67
+ error_text: str,
68
+ *,
69
+ content_type: Optional[str] = None,
70
+ ) -> str:
71
+ """将冗长的上游错误文本压缩为适合返回给客户端的短消息。"""
72
+ text = (error_text or "").strip()
73
+ if not text:
74
+ return ""
75
+
76
+ if is_upstream_page_response(content_type, text):
77
+ return get_upstream_page_error_message(status_code)
78
+
79
+ return text
80
+
81
+
82
+ # ---------------------------------------------------------------------------
83
+ # 错误解析工具
84
+ # ---------------------------------------------------------------------------
85
+
86
+
87
+ def extract_upstream_error_details(
88
+ status_code: int,
89
+ error_text: str,
90
+ content_type: Optional[str] = None,
91
+ ) -> Tuple[Optional[int], str]:
92
+ """解析上游错误响应中的 code/message。
93
+
94
+ Args:
95
+ status_code: HTTP 响应状态码。
96
+ error_text: 响应 body 文本。
97
+
98
+ Returns:
99
+ ``(error_code, error_message)`` 二元组,解析失败时 code 为 None。
100
+ """
101
+ parsed_code: Optional[int] = None
102
+ fallback_message = summarize_upstream_error_text(
103
+ status_code,
104
+ error_text,
105
+ content_type=content_type,
106
+ )
107
+ parsed_message = ""
108
+
109
+ if is_upstream_page_response(content_type, error_text):
110
+ return status_code, fallback_message
111
+
112
+ try:
113
+ payload = json.loads(error_text)
114
+ except Exception:
115
+ return parsed_code, fallback_message
116
+
117
+ if not isinstance(payload, dict):
118
+ return parsed_code, fallback_message
119
+
120
+ candidates = [
121
+ payload,
122
+ payload.get("error") if isinstance(payload.get("error"), dict) else None,
123
+ payload.get("detail") if isinstance(payload.get("detail"), dict) else None,
124
+ payload.get("data") if isinstance(payload.get("data"), dict) else None,
125
+ ]
126
+
127
+ for candidate in candidates:
128
+ if not isinstance(candidate, dict):
129
+ continue
130
+
131
+ candidate_message = ""
132
+ code = candidate.get("code")
133
+ if isinstance(code, int):
134
+ parsed_code = code
135
+ elif isinstance(code, str) and code.isdigit():
136
+ parsed_code = int(code)
137
+
138
+ for key in ("message", "msg", "detail", "error"):
139
+ value = candidate.get(key)
140
+ if isinstance(value, str) and value.strip():
141
+ candidate_message = summarize_upstream_error_text(
142
+ status_code,
143
+ value.strip(),
144
+ )
145
+ parsed_message = candidate_message
146
+ break
147
+
148
+ if parsed_code is not None or candidate_message:
149
+ break
150
+
151
+ if not parsed_message:
152
+ parsed_message = fallback_message
153
+
154
+ return parsed_code, parsed_message
155
+
156
+
157
+ def is_concurrency_limited(
158
+ status_code: int,
159
+ error_code: Optional[int],
160
+ error_message: str,
161
+ ) -> bool:
162
+ """判断是否为上游并发限制/429 场景。
163
+
164
+ Args:
165
+ status_code: HTTP 状态码。
166
+ error_code: 解析出的错误 code(可能为 None)。
167
+ error_message: 解析出的错误消息文本。
168
+
169
+ Returns:
170
+ True 表示命中并发限制,需要重试。
171
+ """
172
+ message = (error_message or "").casefold()
173
+ return (
174
+ status_code == 429
175
+ or error_code == 429
176
+ or "concurrency" in message
177
+ or "too many requests" in message
178
+ )
179
+
180
+
181
+ # ---------------------------------------------------------------------------
182
+ # 重试策略
183
+ # ---------------------------------------------------------------------------
184
+
185
+
186
+ class RetryPolicy:
187
+ """双池重试策略。
188
+
189
+ 封装认证号池与匿名号池的重试预算计算和切换决策。
190
+ """
191
+
192
+ def __init__(self) -> None:
193
+ self.logger = logger
194
+
195
+ async def get_guest_retry_limit(self) -> int:
196
+ """匿名号池可提供的最大重试预算。"""
197
+ if not settings.ANONYMOUS_MODE:
198
+ return 0
199
+
200
+ guest_pool = get_guest_session_pool()
201
+ if not guest_pool:
202
+ return max(2, settings.GUEST_POOL_SIZE + 1)
203
+
204
+ pool_status = guest_pool.get_pool_status()
205
+ available_sessions = int(
206
+ pool_status.get("valid_sessions")
207
+ or pool_status.get("available_sessions")
208
+ or 0
209
+ )
210
+ return max(2, available_sessions + 1)
211
+
212
+ async def get_authenticated_retry_limit(self) -> int:
213
+ """认证号池与静态 Token 可提供的最大重试预算。"""
214
+ available_tokens = 0
215
+ token_pool = get_token_pool()
216
+ if token_pool:
217
+ status = await token_pool.get_pool_status()
218
+ available_tokens = int(status.get("available_tokens", 0) or 0)
219
+ return max(0, available_tokens)
220
+
221
+ async def get_total_retry_limit(self) -> int:
222
+ """综合认证号池与匿名号池的最大尝试次数。"""
223
+ auth_limit = await self.get_authenticated_retry_limit()
224
+ guest_limit = await self.get_guest_retry_limit()
225
+ return max(1, auth_limit + guest_limit)
226
+
227
+ def is_guest_auth(self, transformed: Dict[str, Any]) -> bool:
228
+ """判断当前请求是否使用匿名会话。"""
229
+ return str(transformed.get("auth_mode") or "") == "guest"
230
+
231
+ def should_retry_guest_session(
232
+ self,
233
+ status_code: int,
234
+ is_concurrency_limited_flag: bool,
235
+ attempt: int,
236
+ max_attempts: int,
237
+ transformed: Dict[str, Any],
238
+ ) -> bool:
239
+ """判断匿名号池是否需要刷新会话后重试。"""
240
+ return (
241
+ settings.ANONYMOUS_MODE
242
+ and self.is_guest_auth(transformed)
243
+ and (status_code == 401 or is_concurrency_limited_flag)
244
+ and attempt + 1 < max_attempts
245
+ )
246
+
247
+ def should_retry_authenticated_session(
248
+ self,
249
+ status_code: int,
250
+ is_concurrency_limited_flag: bool,
251
+ attempt: int,
252
+ max_attempts: int,
253
+ transformed: Dict[str, Any],
254
+ ) -> bool:
255
+ """判断认证号池是否需要切号重试。"""
256
+ current_token = str(transformed.get("token") or "")
257
+ return (
258
+ not self.is_guest_auth(transformed)
259
+ and bool(current_token)
260
+ and (status_code == 401 or is_concurrency_limited_flag)
261
+ and attempt + 1 < max_attempts
262
+ )
263
+
264
+ async def release_guest_session(self, transformed: Dict[str, Any]) -> None:
265
+ """释放当前匿名会话占用。"""
266
+ if not self.is_guest_auth(transformed) or not settings.ANONYMOUS_MODE:
267
+ return
268
+
269
+ guest_pool = get_guest_session_pool()
270
+ guest_user_id = str(
271
+ transformed.get("guest_user_id") or transformed.get("user_id") or ""
272
+ )
273
+ if guest_pool and guest_user_id:
274
+ guest_pool.release(guest_user_id)
275
+
276
+ async def report_guest_session_failure(
277
+ self,
278
+ transformed: Dict[str, Any],
279
+ *,
280
+ is_concurrency_limited_flag: bool = False,
281
+ ) -> None:
282
+ """上报匿名会话失败并补齐新会话。"""
283
+ if not self.is_guest_auth(transformed) or not settings.ANONYMOUS_MODE:
284
+ return
285
+
286
+ guest_pool = get_guest_session_pool()
287
+ guest_user_id = str(
288
+ transformed.get("guest_user_id") or transformed.get("user_id") or ""
289
+ )
290
+ if not guest_pool or not guest_user_id:
291
+ return
292
+
293
+ if is_concurrency_limited_flag:
294
+ await guest_pool.cleanup_idle_chats()
295
+
296
+ await guest_pool.report_failure(guest_user_id)
app/core/session/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ from app.core.session.session_manager import SessionManager, SessionResult
5
+ from app.core.session.session_content import (
6
+ build_session_body_messages,
7
+ extract_turn_content,
8
+ get_precreate_content,
9
+ inject_system_prompt,
10
+ )
11
+
12
+ __all__ = [
13
+ "SessionManager",
14
+ "SessionResult",
15
+ "build_session_body_messages",
16
+ "extract_turn_content",
17
+ "get_precreate_content",
18
+ "inject_system_prompt",
19
+ ]
app/core/session/session_content.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """Message content preparation helpers.
5
+
6
+ Provides functions to flatten message content, concatenate conversation
7
+ history, choose the correct turn content, inject system prompts, and
8
+ build the final messages list used in session / direct modes.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import Any, Dict, List
14
+
15
+
16
+ # ---------------------------------------------------------------------------
17
+ # Low-level content helpers
18
+ # ---------------------------------------------------------------------------
19
+
20
+ def content_to_text(content: Any) -> str:
21
+ """Best-effort flatten message content into plain text."""
22
+ if isinstance(content, str):
23
+ return content
24
+ if isinstance(content, list):
25
+ parts: List[str] = []
26
+ for item in content:
27
+ if isinstance(item, str) and item:
28
+ parts.append(item)
29
+ continue
30
+ if isinstance(item, dict) and item.get("type") == "text":
31
+ text = item.get("text")
32
+ if isinstance(text, str) and text:
33
+ parts.append(text)
34
+ return " ".join(parts)
35
+ if content is None:
36
+ return ""
37
+ return str(content)
38
+
39
+
40
+ def concat_history(messages: List[Dict[str, Any]]) -> str:
41
+ """Concatenate non-system messages into a single text block.
42
+
43
+ Used when a session is lost / new and we need to replay history into
44
+ a single upstream user message. System messages are skipped because
45
+ the upstream model configuration handles them separately.
46
+ """
47
+ parts: List[str] = []
48
+ for msg in messages:
49
+ role = msg.get("role", "user")
50
+ if role == "system":
51
+ continue
52
+ content = msg.get("content", "")
53
+ if isinstance(content, list):
54
+ content = " ".join(
55
+ item.get("text", "")
56
+ for item in content
57
+ if isinstance(item, dict) and item.get("type") == "text"
58
+ )
59
+ if content:
60
+ parts.append(f"[{role}]: {content}")
61
+ return "\n\n".join(parts)
62
+
63
+
64
+ def extract_turn_content(
65
+ raw_messages: List[Dict[str, Any]],
66
+ normalized_messages: List[Dict[str, Any]],
67
+ fallback_user_text: str,
68
+ ) -> str:
69
+ """Choose the appropriate content for the current turn.
70
+
71
+ - last raw role == user -> send that user text
72
+ - last raw role == tool -> send the last user text from normalized messages
73
+ - otherwise -> fallback to *fallback_user_text*
74
+ """
75
+ if raw_messages:
76
+ last_raw = raw_messages[-1]
77
+ if isinstance(last_raw, dict):
78
+ last_role = str(last_raw.get("role") or "")
79
+ if last_role == "user":
80
+ text = content_to_text(last_raw.get("content"))
81
+ if text.strip():
82
+ return text
83
+ elif last_role == "tool":
84
+ # tool messages are converted to plain user messages during normalization
85
+ for msg in reversed(normalized_messages):
86
+ if not isinstance(msg, dict) or msg.get("role") != "user":
87
+ continue
88
+ content = content_to_text(msg.get("content"))
89
+ if content.strip():
90
+ return content
91
+ return fallback_user_text
92
+
93
+
94
+ # ---------------------------------------------------------------------------
95
+ # System prompt injection (works for both session and direct modes)
96
+ # ---------------------------------------------------------------------------
97
+
98
+ def inject_system_prompt(
99
+ messages: List[Dict[str, Any]],
100
+ ) -> List[Dict[str, Any]]:
101
+ """Merge all system messages into the first user message.
102
+
103
+ Extracts every ``role=system`` entry, concatenates their text, and
104
+ prepends it to the first ``role=user`` message's content. The
105
+ system entries are removed from the returned list.
106
+
107
+ If there are no system messages or no user messages, the list is
108
+ returned unchanged (shallow copy).
109
+
110
+ This is used in **both** session mode and direct mode when
111
+ ``SESSION_SYSTEM_INJECT`` is enabled.
112
+ """
113
+ # Collect system text
114
+ system_parts: List[str] = []
115
+ for msg in messages:
116
+ if msg.get("role") == "system":
117
+ text = content_to_text(msg.get("content"))
118
+ if text.strip():
119
+ system_parts.append(text.strip())
120
+
121
+ if not system_parts:
122
+ return list(messages)
123
+
124
+ system_text = "\n\n".join(system_parts)
125
+
126
+ # Build new list: skip system, inject into first user message
127
+ result: List[Dict[str, Any]] = []
128
+ injected = False
129
+ for msg in messages:
130
+ if msg.get("role") == "system":
131
+ continue
132
+ if not injected and msg.get("role") == "user":
133
+ user_content = content_to_text(msg.get("content"))
134
+ result.append({
135
+ **msg,
136
+ "content": system_text + "\n\n" + user_content,
137
+ })
138
+ injected = True
139
+ else:
140
+ result.append(msg)
141
+
142
+ return result
143
+
144
+
145
+ # ---------------------------------------------------------------------------
146
+ # High-level session body builders
147
+ # ---------------------------------------------------------------------------
148
+
149
+ def build_session_body_messages(
150
+ normalized_messages: List[Dict[str, Any]],
151
+ session_turn_content: str,
152
+ is_new_session: bool,
153
+ inject_system: bool = True,
154
+ ) -> List[Dict[str, Any]]:
155
+ """Build the messages list for session mode body.
156
+
157
+ Args:
158
+ normalized_messages: Full preprocessed message list (for extracting
159
+ system prompts and history).
160
+ session_turn_content: The current turn's content (from
161
+ ``extract_turn_content``).
162
+ is_new_session: ``True`` if no existing session was found.
163
+ inject_system: If ``True``, concatenate the system prompt into the
164
+ user message content. If ``False``, pass the system prompt as
165
+ a separate ``system`` message.
166
+
167
+ Returns:
168
+ Messages list for the upstream body. In session mode this is
169
+ typically 1 message (inject) or 2 messages (pass-through with
170
+ system).
171
+ """
172
+ if not is_new_session:
173
+ # Reuse session: upstream already has the system prompt from turn 1
174
+ return [{"role": "user", "content": session_turn_content}]
175
+
176
+ # ---- New session: handle system prompt ----
177
+ system_parts: List[str] = []
178
+ for msg in normalized_messages:
179
+ if msg.get("role") != "system":
180
+ continue
181
+ system_text_part = content_to_text(msg.get("content")).strip()
182
+ if system_text_part:
183
+ system_parts.append(system_text_part)
184
+ system_text = "\n\n".join(system_parts)
185
+
186
+ # Build history content (for multi-message recovery)
187
+ raw_msg_count = sum(1 for m in normalized_messages if m.get("role") != "system")
188
+ if raw_msg_count > 1:
189
+ # Multiple non-system messages: concatenate history
190
+ history_text = concat_history(normalized_messages)
191
+ else:
192
+ history_text = session_turn_content
193
+
194
+ if not system_text:
195
+ # No system prompt: just send user content
196
+ return [{"role": "user", "content": history_text}]
197
+
198
+ if inject_system:
199
+ # Inject mode: concatenate system + content into single user message
200
+ return [{"role": "user", "content": system_text + "\n\n" + history_text}]
201
+ else:
202
+ # Pass-through mode: system as separate message
203
+ return [
204
+ {"role": "system", "content": system_text},
205
+ {"role": "user", "content": history_text},
206
+ ]
207
+
208
+
209
+ def get_precreate_content(
210
+ session_body_messages: List[Dict[str, Any]],
211
+ ) -> str:
212
+ """Extract the text content to pass to ``_precreate_chat`` from session body messages.
213
+
214
+ Simply concatenates all message contents into a single string.
215
+ """
216
+ parts: List[str] = []
217
+ for msg in session_body_messages:
218
+ text = content_to_text(msg.get("content")).strip()
219
+ if text:
220
+ parts.append(text)
221
+ return "\n\n".join(parts)
app/core/session/session_fingerprint.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """会话指纹生成与匹配。
5
+
6
+ 使用 blake2s(stdlib,比 MD5 更快)生成消息和客户端指纹。
7
+ """
8
+
9
+ import hashlib
10
+ from typing import Any, Dict, List, Optional
11
+
12
+ from app.utils.logger import logger
13
+
14
+
15
+ def _fast_hash(data: str, length: int = 16) -> str:
16
+ """快速哈希:blake2s(stdlib 内置,比 MD5 约快 30-50%)。"""
17
+ return hashlib.blake2s(data.encode("utf-8"), digest_size=8).hexdigest()[:length]
18
+
19
+
20
+ class SessionFingerprint:
21
+ """处理会话指纹生成和匹配。"""
22
+
23
+ # 每个会话最多保留最近多少条消息的指纹
24
+ MAX_CACHED_FINGERPRINTS = 10
25
+
26
+ @staticmethod
27
+ def generate_client_fingerprint(identifier: str, model: str) -> str:
28
+ """生成客户端指纹(token + model → 固定 16 字符)。
29
+
30
+ Args:
31
+ identifier: 认证 token 或 client_id。
32
+ model: 请求模型名。
33
+
34
+ Returns:
35
+ 16 字符十六进制指纹。
36
+ """
37
+ base = identifier or ""
38
+ prefix = base[:20] if len(base) > 20 else base
39
+ return _fast_hash(f"{prefix}:{model}", length=16)
40
+
41
+ @staticmethod
42
+ def message_fingerprint(message: Dict[str, Any]) -> str:
43
+ """生成单条消息的指纹(role + content)。"""
44
+ role = message.get("role", "")
45
+ content = message.get("content", "")
46
+ # 对列表内容(多模态)做简化处理:转为字符串
47
+ if isinstance(content, list):
48
+ content = str(content)
49
+ return _fast_hash(f"{role}:{content}", length=16)
50
+
51
+ @staticmethod
52
+ def collect_fingerprints(messages: List[Dict[str, Any]]) -> List[str]:
53
+ """收集消息列表末尾 N 条的指纹(用于存储到会话中)。"""
54
+ fps = [SessionFingerprint.message_fingerprint(m) for m in messages]
55
+ return fps[-SessionFingerprint.MAX_CACHED_FINGERPRINTS:]
56
+
57
+ @staticmethod
58
+ def is_continuous_session(
59
+ new_messages: List[Dict[str, Any]],
60
+ cached_fingerprints: List[str],
61
+ ) -> bool:
62
+ """判断当前请求是否为已知会话的延续。
63
+
64
+ 判定规则(适配 OpenAI 多轮对话格式):
65
+ - 消息数 <= 1:必然是新对话(首轮消息)
66
+ - 消息数 == 3:3 条 (user/assistant/user) 时,检查第 1 条是否命中缓存
67
+ - 消息数 >= 5:检查倒数第 3~5 条,命中 2 条以上即视为连续
68
+
69
+ Args:
70
+ new_messages: 当前请求的完整消息列表。
71
+ cached_fingerprints: 上次会话保存的指纹列表。
72
+
73
+ Returns:
74
+ True 表示是连续会话,False 表示新对话。
75
+ """
76
+ msg_count = len(new_messages)
77
+
78
+ if msg_count <= 1:
79
+ return False
80
+
81
+ if not cached_fingerprints:
82
+ return False
83
+
84
+ new_fps = [SessionFingerprint.message_fingerprint(m) for m in new_messages]
85
+ cached_set = set(cached_fingerprints)
86
+
87
+ # 3 条消息:首条匹配即认为连续
88
+ if msg_count == 3:
89
+ if new_fps[0] in cached_set:
90
+ logger.debug("连续会话命中:3 条消息首条匹配缓存")
91
+ return True
92
+ return False
93
+
94
+ # 5 条及以上:检查倒数 3~5 条,命中 >= 2 条视为连续
95
+ if msg_count >= 5:
96
+ check_indices = [-5, -4, -3]
97
+ match_count = sum(
98
+ 1 for idx in check_indices
99
+ if abs(idx) <= len(new_fps) and new_fps[idx] in cached_set
100
+ )
101
+ if match_count >= 2:
102
+ logger.debug("连续会话命中:%s 条消息,倒数命中 %s/3 条", msg_count, match_count)
103
+ return True
104
+
105
+ # 4 条(user/assistant/user/assistant 或其他):任意一条历史匹配
106
+ if msg_count == 4:
107
+ # 检查前 2 条(历史部分)
108
+ match_count = sum(1 for fp in new_fps[:2] if fp in cached_set)
109
+ if match_count >= 1:
110
+ logger.debug("连续会话命中:4 条消息,历史部分匹配")
111
+ return True
112
+
113
+ return False
114
+
115
+ @staticmethod
116
+ def hash_token(token: Optional[str]) -> Optional[str]:
117
+ """生成 token 哈希(用于日志脱敏)。"""
118
+ if not token:
119
+ return None
120
+ return _fast_hash(token, length=16)
app/core/session/session_manager.py ADDED
@@ -0,0 +1,427 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """会话管理器:连续会话的核心协调模块。
5
+
6
+ 职责:
7
+ 1. 通过指纹匹配检测连续会话
8
+ 2. 维护 chat_id / parent_id 的生命周期
9
+ 3. 后台定期清理过期会话
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import asyncio
15
+ import time
16
+ import uuid
17
+ from dataclasses import dataclass, field
18
+ from typing import Any, Dict, List, Optional
19
+
20
+ from app.core.session.session_fingerprint import SessionFingerprint
21
+ from app.core.session.session_store import SessionStore
22
+ from app.core.config import settings
23
+ from app.utils.logger import logger
24
+
25
+
26
+ def _new_uuid() -> str:
27
+ return str(uuid.uuid4())
28
+
29
+
30
+ # ──────────────────────────────────────────────────────────────────────────────
31
+ # 数据类
32
+ # ──────────────────────────────────────────────────────────────────────────────
33
+
34
+ @dataclass
35
+ class SessionResult:
36
+ """会话查找/创建的结果,供 transform_request 使用。"""
37
+
38
+ chat_id: str
39
+ """复用或新建的对话 ID。"""
40
+
41
+ message_id: str
42
+ """本次请求生成的用户消息 ID(current_user_message_id)。"""
43
+
44
+ parent_id: Optional[str]
45
+ """连续会话时指向上次的 current_user_message_id,新对话时为 None。"""
46
+
47
+ is_new: bool
48
+ """True = 新建对话,False = 复用已有会话。"""
49
+
50
+ bound_token: Optional[str] = None
51
+ """复用会话时绑定的原始 token,新对话时为 None。"""
52
+
53
+
54
+ # ──────────────────────────────────────────────────────────────────────────────
55
+ # 存储键辅助
56
+ # ──────────────────────────────────────────────────────────────────────────────
57
+
58
+ _SESSION_PREFIX = "session"
59
+ _FP_INDEX_PREFIX = "fp_index"
60
+
61
+
62
+ def _session_key(client_fp: str, chat_id: str) -> str:
63
+ return f"{_SESSION_PREFIX}:{client_fp}:{chat_id}"
64
+
65
+
66
+ def _fp_index_key(client_fp: str) -> str:
67
+ return f"{_FP_INDEX_PREFIX}:{client_fp}"
68
+
69
+
70
+ # ──────────────────────────────────────────────────────────────────────────────
71
+ # SessionManager
72
+ # ──────────────────────────────────────────────────────────────────────────────
73
+
74
+ class SessionManager:
75
+ """连续会话管理器。
76
+
77
+ 单例使用方式(由 UpstreamClient 持有):
78
+ self._session_manager = SessionManager()
79
+ """
80
+
81
+ def __init__(
82
+ self,
83
+ session_ttl: int = 3600,
84
+ max_sessions_per_client: int = 50,
85
+ cleanup_interval: int = 300,
86
+ ) -> None:
87
+ self._ttl = session_ttl
88
+ self._max_per_client = max(1, max_sessions_per_client)
89
+ self._cleanup_interval = cleanup_interval
90
+ self._store = SessionStore()
91
+ self._fp = SessionFingerprint()
92
+
93
+ self._cleanup_task: Optional[asyncio.Task] = None
94
+
95
+ # ──────────────────────────────────────────────────────────────────
96
+ # 公共接口
97
+ # ──────────────────────────────────────────────────────────────────
98
+
99
+ async def find_session(
100
+ self,
101
+ model: str,
102
+ messages: List[Dict[str, Any]],
103
+ client_id: Optional[str] = None,
104
+ ) -> Optional[SessionResult]:
105
+ """Find matching continuous session by fingerprint. Returns None if not found.
106
+
107
+ This method is intentionally read-only. It only returns the matched
108
+ session and the IDs needed for the current request; the caller must
109
+ commit the new current_user_message_id after the upstream request is
110
+ accepted.
111
+
112
+ Args:
113
+ model: Model name used for index grouping.
114
+ messages: Full message list (OpenAI format) for fingerprint matching.
115
+ client_id: Optional explicit client ID (used for index key if provided).
116
+
117
+ Returns:
118
+ SessionResult on match, None otherwise.
119
+ """
120
+ self._ensure_cleanup_started()
121
+
122
+ index_identifier = client_id or model
123
+ client_fp = self._fp.generate_client_fingerprint(index_identifier, model)
124
+
125
+ match = await self._match_session(client_fp, messages)
126
+ if not match:
127
+ return None
128
+
129
+ session = match
130
+ message_id = _new_uuid()
131
+ chat_id = session["chat_id"]
132
+ parent_id = session.get("last_message_id") or None
133
+
134
+ logger.debug(
135
+ "连续会话复用: chat_id=%s... "
136
+ "parent_id=%s...",
137
+ chat_id[:8],
138
+ parent_id[:8] if parent_id else 'None',
139
+ )
140
+ return SessionResult(
141
+ chat_id=chat_id,
142
+ message_id=message_id,
143
+ parent_id=parent_id,
144
+ is_new=False,
145
+ bound_token=session.get("auth_token"),
146
+ )
147
+
148
+ async def create_session(
149
+ self,
150
+ auth_token: str,
151
+ model: str,
152
+ messages: List[Dict[str, Any]],
153
+ chat_id: str,
154
+ message_id: str,
155
+ client_id: Optional[str] = None,
156
+ ) -> SessionResult:
157
+ """Create a new session with an externally-provided chat_id (from upstream).
158
+
159
+ This is the counterpart to find_session: the caller has already obtained
160
+ a chat_id from the upstream /chats/new endpoint and wants to store it
161
+ for future reuse.
162
+
163
+ Args:
164
+ auth_token: Upstream auth token (stored for bound_token on reuse).
165
+ model: Model name for index grouping.
166
+ messages: Full message list (OpenAI format) for fingerprint collection.
167
+ chat_id: Chat ID returned by the upstream pre-create endpoint.
168
+ message_id: current_user_message_id generated for this turn.
169
+ client_id: Optional explicit client ID (used for index key if provided).
170
+
171
+ Returns:
172
+ SessionResult with is_new=True.
173
+ """
174
+ self._ensure_cleanup_started()
175
+
176
+ index_identifier = client_id or model
177
+ client_fp = self._fp.generate_client_fingerprint(index_identifier, model)
178
+
179
+ fingerprints = self._fp.collect_fingerprints(messages)
180
+ record: Dict[str, Any] = {
181
+ "chat_id": chat_id,
182
+ "client_fingerprint": client_fp,
183
+ "fingerprints": fingerprints,
184
+ "last_message_id": message_id,
185
+ "model": model,
186
+ "token_hash": self._fp.hash_token(auth_token),
187
+ "auth_token": auth_token,
188
+ "created_at": time.time(),
189
+ "last_update": time.time(),
190
+ }
191
+ await self._save_session(client_fp, chat_id, record)
192
+ await self._update_fp_index(client_fp, chat_id)
193
+
194
+ logger.debug("新建会话: chat_id=%s... model=%s", chat_id[:8], model)
195
+ return SessionResult(
196
+ chat_id=chat_id,
197
+ message_id=message_id,
198
+ parent_id=None,
199
+ is_new=True,
200
+ )
201
+
202
+ async def commit_session_turn(
203
+ self,
204
+ model: str,
205
+ messages: List[Dict[str, Any]],
206
+ chat_id: str,
207
+ message_id: str,
208
+ client_id: Optional[str] = None,
209
+ ) -> None:
210
+ """在上游成功接收请求后,推进连续会话链指针。
211
+
212
+ Args:
213
+ model: Model name for index grouping.
214
+ messages: Full message list (OpenAI format) for fingerprint update.
215
+ chat_id: Existing upstream chat ID.
216
+ message_id: Accepted current_user_message_id for this turn.
217
+ client_id: Optional explicit client ID (used for index key if provided).
218
+ """
219
+ self._ensure_cleanup_started()
220
+
221
+ index_identifier = client_id or model
222
+ client_fp = self._fp.generate_client_fingerprint(index_identifier, model)
223
+ session = await self._store.get(_session_key(client_fp, chat_id))
224
+ if not session:
225
+ logger.warning(
226
+ "提交连续会话失败: 未找到 chat_id=%s 的会话记录",
227
+ chat_id[:8],
228
+ )
229
+ return
230
+
231
+ session["fingerprints"] = self._fp.collect_fingerprints(messages)
232
+ session["last_message_id"] = message_id
233
+ session["last_update"] = time.time()
234
+ await self._save_session(client_fp, chat_id, session)
235
+ await self._touch_fp_index(client_fp, chat_id)
236
+ logger.debug(
237
+ "连续会话已提交: chat_id=%s last_message_id=%s",
238
+ chat_id[:8],
239
+ message_id[:8],
240
+ )
241
+
242
+ async def update_session_message_id(
243
+ self,
244
+ client_fp_or_chat_id: str,
245
+ chat_id: str,
246
+ new_message_id: str,
247
+ ) -> None:
248
+ """(可选)手动刷新会话的 last_message_id。
249
+
250
+ 通常无需调用——会话状态会在上游成功接收请求后提交。
251
+ 当需要显式修正 current_user_message_id 时可调用。
252
+ """
253
+ # 先尝试按 chat_id 找 client_fp(遍历 fp_index)
254
+ # 简化:若调用方已知 client_fp 则直接操作
255
+ session = await self._store.get(_session_key(client_fp_or_chat_id, chat_id))
256
+ if not session:
257
+ return
258
+ session["last_message_id"] = new_message_id
259
+ session["last_update"] = time.time()
260
+ await self._store.set(
261
+ _session_key(client_fp_or_chat_id, chat_id), session, ttl=self._ttl
262
+ )
263
+
264
+ async def clear_session(self, client_fp: str, chat_id: str) -> None:
265
+ """清除单个会话及其指纹索引条目。"""
266
+ await self._store.delete(_session_key(client_fp, chat_id))
267
+ await self._remove_from_fp_index(client_fp, chat_id)
268
+
269
+ async def get_stats(self) -> Dict[str, Any]:
270
+ """返回存储统计信息(用于 Admin 面板)。"""
271
+ session_keys = await self._store.keys(f"{_SESSION_PREFIX}:")
272
+ fp_keys = await self._store.keys(f"{_FP_INDEX_PREFIX}:")
273
+ return {
274
+ "total_sessions": len(session_keys),
275
+ "total_clients": len(fp_keys),
276
+ "store_size": self._store.size(),
277
+ "session_ttl": self._ttl,
278
+ "max_per_client": self._max_per_client,
279
+ }
280
+
281
+ async def close(self) -> None:
282
+ """停止后台清理任务。"""
283
+ if self._cleanup_task and not self._cleanup_task.done():
284
+ self._cleanup_task.cancel()
285
+ try:
286
+ await self._cleanup_task
287
+ except asyncio.CancelledError:
288
+ pass
289
+ async with self._store._lock:
290
+ self._store._data.clear()
291
+
292
+ # ──────────────────────────────────────────────────────────────────
293
+ # 内部:会话匹配
294
+ # ──────────────────────────────────────────────────────────────────
295
+
296
+ async def _match_session(
297
+ self,
298
+ client_fp: str,
299
+ messages: List[Dict[str, Any]],
300
+ ) -> Optional[Dict[str, Any]]:
301
+ """在该客户端的会话列表中查找匹配的连续会话。"""
302
+ index = await self._store.get(_fp_index_key(client_fp))
303
+ if not index:
304
+ return None
305
+
306
+ chat_ids: List[str] = index.get("chat_ids", [])
307
+ if not chat_ids:
308
+ return None
309
+
310
+ # 待确认会话精确匹配时惰性计算
311
+ pending_fps: Optional[List[str]] = None
312
+
313
+ # 从最新的会话开始倒序匹配
314
+ for chat_id in reversed(chat_ids):
315
+ session = await self._store.get(_session_key(client_fp, chat_id))
316
+ if not session:
317
+ # 已过期,从索引中清理
318
+ await self._remove_from_fp_index(client_fp, chat_id)
319
+ continue
320
+ cached_fps: List[str] = session.get("fingerprints", [])
321
+
322
+ # 待确认会话(precreate 成功但 completions 未确认):
323
+ # is_continuous_session 对首轮消息(≤2 条)返回 False,
324
+ # 因此改用精确指纹比对来匹配同一请求的重试。
325
+ if not session.get("last_message_id"):
326
+ if pending_fps is None:
327
+ pending_fps = self._fp.collect_fingerprints(messages)
328
+ if pending_fps == cached_fps:
329
+ return session
330
+ continue
331
+
332
+ if self._fp.is_continuous_session(messages, cached_fps):
333
+ return session
334
+
335
+ return None
336
+
337
+ # ──────────────────────────────────────────────────────────────────
338
+ # 内部:存储操作
339
+ # ──────────────────────────────────────────────────────────────────
340
+
341
+ async def _save_session(
342
+ self, client_fp: str, chat_id: str, session: Dict[str, Any]
343
+ ) -> None:
344
+ key = _session_key(client_fp, chat_id)
345
+ await self._store.set(key, session, ttl=self._ttl)
346
+
347
+ async def _update_fp_index(self, client_fp: str, chat_id: str) -> None:
348
+ """新增 chat_id 到指纹索引,超出上限时驱逐最旧的。"""
349
+ index_key = _fp_index_key(client_fp)
350
+ index = await self._store.get(index_key) or {
351
+ "client_fingerprint": client_fp,
352
+ "chat_ids": [],
353
+ "created_at": time.time(),
354
+ }
355
+ chat_ids: List[str] = index.get("chat_ids", [])
356
+ if chat_id in chat_ids:
357
+ chat_ids.remove(chat_id)
358
+ chat_ids.append(chat_id)
359
+
360
+ # 超出上限:驱逐最旧的会话
361
+ while len(chat_ids) > self._max_per_client:
362
+ evict_id = chat_ids.pop(0)
363
+ await self._store.delete(_session_key(client_fp, evict_id))
364
+ logger.debug("驱逐超限会话: %s...", evict_id[:8])
365
+
366
+ index["chat_ids"] = chat_ids
367
+ index["most_recent"] = chat_id
368
+ index["last_update"] = time.time()
369
+ await self._store.set(index_key, index, ttl=self._ttl)
370
+
371
+ async def _touch_fp_index(self, client_fp: str, chat_id: str) -> None:
372
+ """将已匹配的 chat_id 移到列表末尾(最近使用),并刷新 TTL。"""
373
+ index_key = _fp_index_key(client_fp)
374
+ index = await self._store.get(index_key)
375
+ if not index:
376
+ return
377
+ chat_ids: List[str] = index.get("chat_ids", [])
378
+ if chat_id in chat_ids:
379
+ chat_ids.remove(chat_id)
380
+ chat_ids.append(chat_id)
381
+ index["chat_ids"] = chat_ids
382
+ index["most_recent"] = chat_id
383
+ index["last_update"] = time.time()
384
+ await self._store.set(index_key, index, ttl=self._ttl)
385
+
386
+ async def _remove_from_fp_index(self, client_fp: str, chat_id: str) -> None:
387
+ """从指纹索引中移除 chat_id(会话已过期或已删除)。"""
388
+ index_key = _fp_index_key(client_fp)
389
+ index = await self._store.get(index_key)
390
+ if not index:
391
+ return
392
+ chat_ids: List[str] = index.get("chat_ids", [])
393
+ if chat_id in chat_ids:
394
+ chat_ids.remove(chat_id)
395
+ if chat_ids:
396
+ index["chat_ids"] = chat_ids
397
+ index["last_update"] = time.time()
398
+ await self._store.set(index_key, index, ttl=self._ttl)
399
+ else:
400
+ await self._store.delete(index_key)
401
+
402
+ # ──────────────────────────────────────────────────────────────────
403
+ # 内部:后台清理
404
+ # ──────────────────────────────────────────────────────────────────
405
+
406
+ def _ensure_cleanup_started(self) -> None:
407
+ """惰性启动后台清理协程(仅在事件循环中首次调用时启动)。"""
408
+ if self._cleanup_task is None or self._cleanup_task.done():
409
+ try:
410
+ self._cleanup_task = asyncio.get_event_loop().create_task(
411
+ self._cleanup_loop()
412
+ )
413
+ except RuntimeError:
414
+ pass # 无事件循环(测试环境)时忽略
415
+
416
+ async def _cleanup_loop(self) -> None:
417
+ """定期清理过期会话。"""
418
+ while True:
419
+ try:
420
+ await asyncio.sleep(self._cleanup_interval)
421
+ removed = await self._store.cleanup_expired()
422
+ if removed:
423
+ logger.debug("会话清理:清除 %s 条过期记录", removed)
424
+ except asyncio.CancelledError:
425
+ break
426
+ except Exception as exc:
427
+ logger.warning("会话清理异常", exc_info=settings.DEBUG_LOGGING)
app/core/session/session_store.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """轻量级内存会话存储(支持 TTL 自动过期)。
5
+
6
+ 设计原则:
7
+ - 无外部依赖(纯 Python,stdlib 仅需 dict + asyncio)
8
+ - 惰性过期:访问时检查 TTL,周期性后台清理
9
+ - 线程安全:通过 asyncio.Lock 保护共享状态
10
+ """
11
+
12
+ import asyncio
13
+ import time
14
+ from typing import Any, Dict, List, Optional, Tuple
15
+
16
+ from app.utils.logger import logger
17
+
18
+
19
+ class SessionStore:
20
+ """基于内存的 KV 存储,支持 TTL 过期。
21
+
22
+ 存储格式:
23
+ - Key: 字符串(如 "session:{fp}:{chat_id}" 或 "fp_index:{fp}")
24
+ - Value: 任意可序列化 dict
25
+ - TTL: 过期秒数,0 表示永不过期
26
+ """
27
+
28
+ def __init__(self) -> None:
29
+ # {key: (value, expire_at)} expire_at=0 表示永不过期
30
+ self._data: Dict[str, Tuple[Any, float]] = {}
31
+ self._lock = asyncio.Lock()
32
+
33
+ async def get(self, key: str) -> Optional[Dict[str, Any]]:
34
+ """获取 key 对应值,已过期返回 None。"""
35
+ async with self._lock:
36
+ entry = self._data.get(key)
37
+ if entry is None:
38
+ return None
39
+ value, expire_at = entry
40
+ if expire_at and time.monotonic() > expire_at:
41
+ del self._data[key]
42
+ return None
43
+ return value
44
+
45
+ async def set(self, key: str, value: Dict[str, Any], ttl: int = 3600) -> None:
46
+ """设置 key 的值,ttl 秒后过期(ttl=0 永不过期)。"""
47
+ expire_at = (time.monotonic() + ttl) if ttl > 0 else 0.0
48
+ async with self._lock:
49
+ self._data[key] = (value, expire_at)
50
+
51
+ async def delete(self, key: str) -> None:
52
+ """删除指定 key。"""
53
+ async with self._lock:
54
+ self._data.pop(key, None)
55
+
56
+ async def exists(self, key: str) -> bool:
57
+ """检查 key 是否存在且未过期。"""
58
+ return await self.get(key) is not None
59
+
60
+ async def keys(self, prefix: str = "") -> List[str]:
61
+ """返回所有匹配前缀的未过期 key 列表。"""
62
+ now = time.monotonic()
63
+ async with self._lock:
64
+ result = []
65
+ # 顺便清理已过期的 key
66
+ expired = []
67
+ for k, (_, expire_at) in self._data.items():
68
+ if expire_at and now > expire_at:
69
+ expired.append(k)
70
+ elif not prefix or k.startswith(prefix):
71
+ result.append(k)
72
+ for k in expired:
73
+ del self._data[k]
74
+ return result
75
+
76
+ async def cleanup_expired(self) -> int:
77
+ """主动清理所有过期条目,返回清理数量。"""
78
+ now = time.monotonic()
79
+ async with self._lock:
80
+ expired = [k for k, (_, exp) in self._data.items() if exp and now > exp]
81
+ for k in expired:
82
+ del self._data[k]
83
+ return len(expired)
84
+
85
+ def size(self) -> int:
86
+ """返回当前存储条目数(含已过期但未清理的)。"""
87
+ return len(self._data)
app/core/upstream.py ADDED
@@ -0,0 +1,1968 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """上游适配器。
5
+
6
+ UpstreamClient 作为薄集成层,组合各子模块完成完整的请求/响应处理流程:
7
+ - http_client.py — HTTP 客户端管理
8
+ - headers.py — 动态浏览器 headers
9
+ - models.py — 模型映射与特性解析
10
+ - message_utils.py — 消息预处理
11
+ - request_signing.py — 请求体构建与签名
12
+ - retry_policy.py — 双池重试策略
13
+ - response_handler.py — 流式/非流式响应处理
14
+ - file_upload.py — 文件上传
15
+
16
+ 所有公有方法签名与原实现完全一致。
17
+ """
18
+
19
+ import asyncio
20
+ import json
21
+ import time
22
+ import uuid
23
+ from dataclasses import dataclass
24
+ from typing import Any, AsyncGenerator, Dict, List, Optional, Set, Union
25
+
26
+ import httpx
27
+
28
+ from app.core.config import settings
29
+ from app.core.http_client import SharedHttpClients
30
+ from app.core.headers import build_dynamic_headers
31
+ from app.core.models import ModelManager
32
+ from app.utils.jwt_utils import extract_user_id_from_token
33
+ from app.core.message_utils import extract_last_user_text, preprocess_openai_messages
34
+ from app.core.request_signing import (
35
+ process_multimodal_messages,
36
+ build_upstream_body,
37
+ sign_request,
38
+ )
39
+ from app.core.retry_policy import (
40
+ RetryPolicy,
41
+ extract_upstream_error_details,
42
+ get_upstream_page_error_message,
43
+ is_concurrency_limited,
44
+ is_upstream_page_response,
45
+ )
46
+ from app.core.response_handler import ResponseHandler
47
+ from app.core.session import SessionManager
48
+ from app.core.session.session_content import (
49
+ build_session_body_messages,
50
+ extract_turn_content,
51
+ get_precreate_content,
52
+ inject_system_prompt,
53
+ )
54
+ from app.core.file_upload import upload_file as _upload_file
55
+ from app.core.httpx_errors import normalize_httpx_exception, normalize_httpx_response
56
+ from app.core.openai_compat import (
57
+ get_error_message,
58
+ handle_error,
59
+ )
60
+ from app.core.resin_compat import apply_resin_account_header
61
+ from app.core.upstream_urls import build_upstream_url, get_api_endpoint, get_upstream_base_url
62
+ from app.models.schemas import OpenAIRequest
63
+ from app.utils.fe_version import get_latest_fe_version
64
+ from app.core.captcha_client import get_captcha_client
65
+ from app.utils.logger import logger
66
+ from app.utils.token_pool import get_token_pool
67
+ from app.utils.guest_session_pool import get_guest_session_pool
68
+ from app.utils.request_logging import _openai_response_has_output, _sse_chunk_has_output, write_request_log
69
+ from app.utils.request_source import RequestSourceInfo
70
+
71
+
72
+ def generate_uuid() -> str:
73
+ """生成UUID v4"""
74
+ return str(uuid.uuid4())
75
+
76
+
77
+ @dataclass
78
+ class PreparedConversationRequest:
79
+ """请求准备阶段收敛后的统一结果。"""
80
+
81
+ token: str
82
+ user_id: str
83
+ auth_mode: str
84
+ token_source: str
85
+ guest_user_id: Optional[str]
86
+ chat_id: str
87
+ message_id: str
88
+ user_message_id: str
89
+ parent_id: Optional[str]
90
+ body_messages: List[Dict[str, Any]]
91
+ session_commit: Optional[Dict[str, Any]]
92
+
93
+
94
+
95
+ # --------------------------------------------------------------------------
96
+ # UpstreamClient
97
+ # --------------------------------------------------------------------------
98
+
99
+ class UpstreamClient:
100
+ """当前服务使用的上游适配器(薄集成层)。"""
101
+
102
+ def __init__(self):
103
+ self.name = "upstream"
104
+ self.logger = logger
105
+ self.api_endpoint = get_api_endpoint()
106
+
107
+ # 当前上游特定配置
108
+ self.base_url = get_upstream_base_url()
109
+ self.auth_url = build_upstream_url("/api/v1/auths/")
110
+
111
+ # 子模块
112
+ self._http_clients = SharedHttpClients()
113
+ self._model_manager = ModelManager()
114
+ self._retry_policy = RetryPolicy()
115
+ self._response_handler = ResponseHandler()
116
+ self._session_manager = SessionManager(
117
+ session_ttl=settings.SESSION_TTL,
118
+ max_sessions_per_client=settings.SESSION_MAX_PER_CLIENT,
119
+ cleanup_interval=settings.SESSION_CLEANUP_INTERVAL,
120
+ )
121
+
122
+ # 在线模型缓存(实例变量,避免多实例混用)
123
+ self._online_models: Optional[List[Dict[str, Any]]] = None
124
+ self._online_models_time: float = 0.0
125
+ self._online_models_lock: asyncio.Lock = asyncio.Lock()
126
+
127
+ # ------------------------------------------------------------------
128
+ # HTTP 客户端访问
129
+ # ------------------------------------------------------------------
130
+
131
+ def _get_shared_client(self) -> httpx.AsyncClient:
132
+ return self._http_clients.get_client()
133
+
134
+ def _get_shared_stream_client(self) -> httpx.AsyncClient:
135
+ return self._http_clients.get_stream_client()
136
+
137
+ async def close(self) -> None:
138
+ """关闭共享 HTTP 客户端连接和会话管理器。"""
139
+ await self._http_clients.close()
140
+ await self._session_manager.close()
141
+
142
+ # ------------------------------------------------------------------
143
+ # 重试预算(委托到 RetryPolicy)
144
+ # ------------------------------------------------------------------
145
+
146
+ async def _get_guest_retry_limit(self) -> int:
147
+ """匿名号池可提供的最大重试预算。"""
148
+ return await self._retry_policy.get_guest_retry_limit()
149
+
150
+ async def _get_authenticated_retry_limit(self) -> int:
151
+ """认证号池与静态 Token 可提供的最大重试预算。"""
152
+ return await self._retry_policy.get_authenticated_retry_limit()
153
+
154
+ async def _get_total_retry_limit(self) -> int:
155
+ """综合认证号池与匿名号池的最大尝试次数。"""
156
+ return await self._retry_policy.get_total_retry_limit()
157
+
158
+ # ------------------------------------------------------------------
159
+ # 重试决策(委托到 RetryPolicy)
160
+ # ------------------------------------------------------------------
161
+
162
+ def _is_guest_auth(self, transformed: Dict[str, Any]) -> bool:
163
+ """判断当前请求是否使用匿名会话。"""
164
+ return self._retry_policy.is_guest_auth(transformed)
165
+
166
+ def _should_retry_guest_session(
167
+ self,
168
+ status_code: int,
169
+ is_concurrency_limited_flag: bool,
170
+ attempt: int,
171
+ max_attempts: int,
172
+ transformed: Dict[str, Any],
173
+ ) -> bool:
174
+ """判断匿名号池是否需要刷新会话后重试。"""
175
+ return self._retry_policy.should_retry_guest_session(
176
+ status_code, is_concurrency_limited_flag, attempt, max_attempts, transformed
177
+ )
178
+
179
+ def _should_retry_authenticated_session(
180
+ self,
181
+ status_code: int,
182
+ is_concurrency_limited_flag: bool,
183
+ attempt: int,
184
+ max_attempts: int,
185
+ transformed: Dict[str, Any],
186
+ ) -> bool:
187
+ """判断认证号池是否需要切号重试。"""
188
+ return self._retry_policy.should_retry_authenticated_session(
189
+ status_code, is_concurrency_limited_flag, attempt, max_attempts, transformed
190
+ )
191
+
192
+ async def _release_guest_session(self, transformed: Dict[str, Any]) -> None:
193
+ """释放当前匿名会话占用。"""
194
+ await self._retry_policy.release_guest_session(transformed)
195
+
196
+ async def _release_authenticated_token_allocation(
197
+ self,
198
+ transformed: Optional[Dict[str, Any]],
199
+ ) -> None:
200
+ """释放认证 token 的并发占用,不记录成功或失败。"""
201
+ if not transformed or self._is_guest_auth(transformed):
202
+ return
203
+
204
+ token = str(transformed.get("token") or "")
205
+ if not token:
206
+ return
207
+
208
+ token_pool = get_token_pool()
209
+ if token_pool:
210
+ await token_pool.release_token_allocation(token)
211
+
212
+ async def _report_guest_session_failure(
213
+ self,
214
+ transformed: Dict[str, Any],
215
+ *,
216
+ is_concurrency_limited: bool = False,
217
+ ) -> None:
218
+ """上报匿名会话失败并补齐新会话。"""
219
+ await self._retry_policy.report_guest_session_failure(
220
+ transformed, is_concurrency_limited_flag=is_concurrency_limited
221
+ )
222
+
223
+ async def _refresh_guest_request(
224
+ self,
225
+ request: OpenAIRequest,
226
+ attempt: int,
227
+ excluded_tokens: Set[str],
228
+ excluded_guest_user_ids: Set[str],
229
+ failed_transformed: Dict[str, Any],
230
+ is_concurrency_limited: bool = False,
231
+ ) -> Dict[str, Any]:
232
+ """匿名会话失效或并发受限后切换会话并重签请求。"""
233
+ retry_number = attempt + 2
234
+ self.logger.warning(
235
+ "匿名会话不可用,正在切换匿名会话并进行第 "
236
+ "%s 次请求",
237
+ retry_number,
238
+ )
239
+ await self._report_guest_session_failure(
240
+ failed_transformed,
241
+ is_concurrency_limited=is_concurrency_limited,
242
+ )
243
+ return await self.transform_request(
244
+ request,
245
+ excluded_tokens=excluded_tokens,
246
+ excluded_guest_user_ids=excluded_guest_user_ids,
247
+ )
248
+
249
+ async def _refresh_authenticated_request(
250
+ self,
251
+ request: OpenAIRequest,
252
+ attempt: int,
253
+ excluded_tokens: Set[str],
254
+ excluded_guest_user_ids: Set[str],
255
+ ) -> Dict[str, Any]:
256
+ """认证模式下切换到下一枚 Token,并允许回退匿名池。"""
257
+ retry_number = attempt + 2
258
+ self.logger.warning(
259
+ "检测到认证会话不可用,正在切换认证 Token/回退匿名池并进行第 "
260
+ "%s 次请求",
261
+ retry_number,
262
+ )
263
+ return await self.transform_request(
264
+ request,
265
+ excluded_tokens=excluded_tokens,
266
+ excluded_guest_user_ids=excluded_guest_user_ids,
267
+ )
268
+
269
+ async def _commit_session_if_needed(self, transformed: Dict[str, Any]) -> None:
270
+ """在上���已接受请求后,提交连续会话状态。"""
271
+ commit_info = transformed.pop("session_commit", None)
272
+ if not isinstance(commit_info, dict):
273
+ return
274
+
275
+ action = str(commit_info.get("action") or "")
276
+ try:
277
+ if action == "reuse":
278
+ await self._session_manager.commit_session_turn(
279
+ model=str(commit_info["model"]),
280
+ messages=list(commit_info["messages"]),
281
+ chat_id=str(commit_info["chat_id"]),
282
+ message_id=str(commit_info["message_id"]),
283
+ )
284
+ return
285
+
286
+ self.logger.warning("未知会话提交动作: %s", action)
287
+ except Exception as exc:
288
+ self.logger.warning(
289
+ "提交会话状态失败",
290
+ exc_info=settings.DEBUG_LOGGING,
291
+ )
292
+
293
+ # ------------------------------------------------------------------
294
+ # 错误解析(委托到 retry_policy 工具函数)
295
+ # ------------------------------------------------------------------
296
+
297
+ def _extract_upstream_error_details(
298
+ self,
299
+ status_code: int,
300
+ error_text: str,
301
+ content_type: Optional[str] = None,
302
+ ):
303
+ """解析上游错误响应中的 code/message。"""
304
+ return extract_upstream_error_details(
305
+ status_code,
306
+ error_text,
307
+ content_type=content_type,
308
+ )
309
+
310
+ def _is_concurrency_limited(
311
+ self,
312
+ status_code: int,
313
+ error_code,
314
+ error_message: str,
315
+ ) -> bool:
316
+ """判断是否为上游并发限制/429 场景。"""
317
+ return is_concurrency_limited(status_code, error_code, error_message)
318
+
319
+ @staticmethod
320
+ def _build_upstream_error_response(
321
+ status_code: int,
322
+ error_code: Optional[int],
323
+ error_message: str,
324
+ *,
325
+ is_page_error: bool = False,
326
+ ) -> Dict[str, Any]:
327
+ """统一构建对客户端返回的上游错误对象。"""
328
+ normalized_status = (
329
+ status_code if isinstance(status_code, int) and status_code >= 400 else 502
330
+ )
331
+
332
+ if is_page_error:
333
+ return {
334
+ "error": {
335
+ "message": get_upstream_page_error_message(normalized_status),
336
+ "type": "upstream_page_error",
337
+ "code": normalized_status,
338
+ }
339
+ }
340
+
341
+ message = (error_message or "").strip() or f"Upstream error: {status_code}"
342
+ code = error_code if isinstance(error_code, int) else status_code
343
+
344
+ return {
345
+ "error": {
346
+ "message": message,
347
+ "type": "upstream_error",
348
+ "code": code,
349
+ }
350
+ }
351
+
352
+ # ------------------------------------------------------------------
353
+ # 会话预创建(对齐浏览器 /api/v1/chats/new 流程)
354
+ # ------------------------------------------------------------------
355
+
356
+ async def _precreate_chat(
357
+ self,
358
+ token: str,
359
+ fe_version: str,
360
+ model: str,
361
+ user_msg_id: str,
362
+ content: str,
363
+ enable_thinking: bool = False,
364
+ auto_web_search: bool = False,
365
+ mcp_servers: Optional[List[str]] = None,
366
+ allow_fallback: bool = True,
367
+ max_retries: int = 3,
368
+ ) -> str:
369
+ """调用 /api/v1/chats/new 预创建会话,返回服务端分配的 chat_id。
370
+
371
+ 浏览器在发 completions 之前会先调用此接口创建会话;
372
+ 缺少此步骤会导致上游在 done 阶段返回 INTERNAL_ERROR。
373
+ """
374
+ now_ts = int(time.time())
375
+ body = {
376
+ "chat": {
377
+ "id": "",
378
+ "title": "新聊天",
379
+ "models": [model],
380
+ "params": {},
381
+ "history": {
382
+ "messages": {
383
+ user_msg_id: {
384
+ "id": user_msg_id,
385
+ "parentId": None,
386
+ "childrenIds": [],
387
+ "role": "user",
388
+ "content": content or "hi",
389
+ "timestamp": now_ts,
390
+ "models": [model],
391
+ }
392
+ },
393
+ "currentId": user_msg_id,
394
+ },
395
+ "tags": [],
396
+ "flags": [],
397
+ "features": [
398
+ {
399
+ "type": "tool_selector",
400
+ "server": "tool_selector_h",
401
+ "status": "hidden",
402
+ }
403
+ ],
404
+ "mcp_servers": mcp_servers or [],
405
+ "enable_thinking": enable_thinking,
406
+ "auto_web_search": auto_web_search,
407
+ "message_version": 1,
408
+ "extra": {},
409
+ "timestamp": int(time.time() * 1000),
410
+ }
411
+ }
412
+
413
+ headers = build_dynamic_headers(fe_version)
414
+ headers["Authorization"] = f"Bearer {token}"
415
+ apply_resin_account_header(headers, token)
416
+
417
+ client = self._get_shared_client()
418
+ attempts = max(1, max_retries)
419
+ for attempt in range(attempts):
420
+ try:
421
+ resp = await client.post(
422
+ f"{self.base_url}/api/v1/chats/new",
423
+ json=body,
424
+ headers=headers,
425
+ )
426
+ if resp.status_code == 200:
427
+ chat_id = resp.json().get("id", "")
428
+ if chat_id:
429
+ self.logger.debug(
430
+ "[chat] pre-created chat_id=%s", chat_id
431
+ )
432
+ return chat_id
433
+ self.logger.warning(
434
+ "[chat] pre-create failed: HTTP %s (attempt %s/%s)",
435
+ resp.status_code,
436
+ attempt + 1,
437
+ attempts,
438
+ )
439
+ except Exception as e:
440
+ self.logger.warning(
441
+ "[chat] pre-create error (attempt %s/%s)",
442
+ attempt + 1,
443
+ attempts,
444
+ exc_info=settings.DEBUG_LOGGING,
445
+ )
446
+
447
+ if attempt + 1 < attempts:
448
+ await asyncio.sleep(min(2 ** attempt, 8))
449
+
450
+ if allow_fallback:
451
+ # 降级:使用随机 chat_id(会触发 done 阶段 INTERNAL_ERROR,但内容不受影响)
452
+ self.logger.warning(
453
+ "[chat] pre-create failed after %s attempts, fallback to random chat_id",
454
+ attempts,
455
+ )
456
+ return generate_uuid()
457
+
458
+ raise RuntimeError(
459
+ f"pre-create chat_id failed after {attempts} attempts"
460
+ )
461
+
462
+ async def _prepare_session_request(
463
+ self,
464
+ request: OpenAIRequest,
465
+ *,
466
+ raw_messages: List[Dict[str, Any]],
467
+ normalized_messages: List[Dict[str, Any]],
468
+ session_turn_content: str,
469
+ features: Dict[str, Any],
470
+ token: str,
471
+ user_id: str,
472
+ auth_mode: str,
473
+ token_source: str,
474
+ guest_user_id: Optional[str],
475
+ fe_version: str,
476
+ auth_info: Dict[str, Any],
477
+ ) -> PreparedConversationRequest:
478
+ session_result = await self._session_manager.find_session(
479
+ model=request.model,
480
+ messages=raw_messages,
481
+ )
482
+
483
+ if (
484
+ session_result
485
+ and not session_result.parent_id
486
+ and session_result.bound_token
487
+ and session_result.bound_token != token
488
+ ):
489
+ self.logger.debug(
490
+ "Token 已切换,跳过待确认会话 chat_id=%s",
491
+ session_result.chat_id[:8],
492
+ )
493
+ session_result = None
494
+
495
+ if session_result:
496
+ chat_id = session_result.chat_id
497
+ if session_result.bound_token and session_result.bound_token != token:
498
+ self.logger.debug(
499
+ "链式会话 token 亲和: 切换到 bound_token (chat_id=%s)",
500
+ chat_id[:8],
501
+ )
502
+ await self._release_guest_session(auth_info)
503
+ token = session_result.bound_token
504
+ user_id = extract_user_id_from_token(token)
505
+ auth_mode = "authenticated"
506
+ token_source = "session_bound"
507
+ guest_user_id = None
508
+ auth_info["token"] = token
509
+ auth_info["user_id"] = user_id
510
+ auth_info["auth_mode"] = auth_mode
511
+ auth_info["token_source"] = token_source
512
+ auth_info["guest_user_id"] = guest_user_id
513
+
514
+ user_message_id = session_result.message_id
515
+ message_id = generate_uuid()
516
+ parent_id = session_result.parent_id
517
+ is_first_turn_retry = not parent_id
518
+ self.logger.debug(
519
+ "%s chat_id=%s, parent_id=%s",
520
+ "首轮重试复用" if is_first_turn_retry else "复用会话",
521
+ chat_id[:8],
522
+ parent_id[:8] if parent_id else "None",
523
+ )
524
+ body_messages = build_session_body_messages(
525
+ normalized_messages=normalized_messages,
526
+ session_turn_content=session_turn_content,
527
+ is_new_session=is_first_turn_retry,
528
+ inject_system=settings.SESSION_SYSTEM_INJECT,
529
+ )
530
+ return PreparedConversationRequest(
531
+ token=token,
532
+ user_id=user_id,
533
+ auth_mode=auth_mode,
534
+ token_source=token_source,
535
+ guest_user_id=guest_user_id,
536
+ chat_id=chat_id,
537
+ message_id=message_id,
538
+ user_message_id=user_message_id,
539
+ parent_id=parent_id,
540
+ body_messages=body_messages,
541
+ session_commit={
542
+ "action": "reuse",
543
+ "model": request.model,
544
+ "messages": raw_messages,
545
+ "chat_id": chat_id,
546
+ "message_id": user_message_id,
547
+ },
548
+ )
549
+
550
+ message_id = generate_uuid()
551
+ user_message_id = generate_uuid()
552
+ body_messages = build_session_body_messages(
553
+ normalized_messages=normalized_messages,
554
+ session_turn_content=session_turn_content,
555
+ is_new_session=True,
556
+ inject_system=settings.SESSION_SYSTEM_INJECT,
557
+ )
558
+ precreate_content = get_precreate_content(body_messages)
559
+ chat_id = await self._precreate_chat(
560
+ token=token,
561
+ fe_version=fe_version,
562
+ model=features["upstream_model_id"],
563
+ user_msg_id=user_message_id,
564
+ content=precreate_content,
565
+ enable_thinking=features["enable_thinking"],
566
+ auto_web_search=features["auto_web_search"],
567
+ mcp_servers=features.get("mcp_servers", []),
568
+ allow_fallback=False,
569
+ )
570
+ await self._session_manager.create_session(
571
+ auth_token=token,
572
+ model=request.model,
573
+ messages=raw_messages,
574
+ chat_id=chat_id,
575
+ message_id="",
576
+ )
577
+ return PreparedConversationRequest(
578
+ token=token,
579
+ user_id=user_id,
580
+ auth_mode=auth_mode,
581
+ token_source=token_source,
582
+ guest_user_id=guest_user_id,
583
+ chat_id=chat_id,
584
+ message_id=message_id,
585
+ user_message_id=user_message_id,
586
+ parent_id=None,
587
+ body_messages=body_messages,
588
+ session_commit={
589
+ "action": "reuse",
590
+ "model": request.model,
591
+ "messages": raw_messages,
592
+ "chat_id": chat_id,
593
+ "message_id": user_message_id,
594
+ },
595
+ )
596
+
597
+ async def _prepare_direct_request(
598
+ self,
599
+ *,
600
+ normalized_messages: List[Dict[str, Any]],
601
+ features: Dict[str, Any],
602
+ token: str,
603
+ user_id: str,
604
+ auth_mode: str,
605
+ token_source: str,
606
+ guest_user_id: Optional[str],
607
+ fe_version: str,
608
+ ) -> PreparedConversationRequest:
609
+ message_id = generate_uuid()
610
+ user_message_id = generate_uuid()
611
+ body_messages = (
612
+ inject_system_prompt(normalized_messages)
613
+ if settings.SESSION_SYSTEM_INJECT
614
+ else normalized_messages
615
+ )
616
+ if settings.PRECREATE_CHAT:
617
+ precreate_content = get_precreate_content(body_messages)
618
+ chat_id = await self._precreate_chat(
619
+ token=token,
620
+ fe_version=fe_version,
621
+ model=features["upstream_model_id"],
622
+ user_msg_id=user_message_id,
623
+ content=precreate_content,
624
+ enable_thinking=features["enable_thinking"],
625
+ auto_web_search=features["auto_web_search"],
626
+ mcp_servers=features.get("mcp_servers", []),
627
+ allow_fallback=False,
628
+ )
629
+ else:
630
+ chat_id = generate_uuid()
631
+
632
+ return PreparedConversationRequest(
633
+ token=token,
634
+ user_id=user_id,
635
+ auth_mode=auth_mode,
636
+ token_source=token_source,
637
+ guest_user_id=guest_user_id,
638
+ chat_id=chat_id,
639
+ message_id=message_id,
640
+ user_message_id=user_message_id,
641
+ parent_id=None,
642
+ body_messages=body_messages,
643
+ session_commit=None,
644
+ )
645
+
646
+ # 在线模型(缓存层保留在本类)
647
+ # ------------------------------------------------------------------
648
+
649
+ async def get_online_models(self) -> List[Dict[str, Any]]:
650
+ """获取上游在线模型详细信息(缓存1小时,asyncio.Lock 防并发刷新)。"""
651
+ now = time.time()
652
+ # 快速路径:缓存命中,无需加锁
653
+ if self._online_models and (now - self._online_models_time < 3600):
654
+ return self._online_models
655
+
656
+ async with self._online_models_lock:
657
+ # 加锁后二次检查,避免多协程同时刷新
658
+ now = time.time()
659
+ if self._online_models and (now - self._online_models_time < 3600):
660
+ return self._online_models
661
+
662
+ try:
663
+ fe_version = await get_latest_fe_version()
664
+ headers = build_dynamic_headers(fe_version=fe_version)
665
+ auth_info = await self.get_auth_info()
666
+ token = auth_info.get("token", "")
667
+ if token:
668
+ headers["Authorization"] = f"Bearer {token}"
669
+ apply_resin_account_header(headers, token)
670
+ client = self._get_shared_client()
671
+ response = await client.get(
672
+ f"{self.base_url}/api/models", headers=headers, timeout=10.0
673
+ )
674
+
675
+ if response.status_code == 200:
676
+ data = response.json()
677
+ models_data = data.get("data", [])
678
+
679
+ parsed_models = []
680
+ for item in models_data:
681
+ model_id = item.get("id")
682
+ if not model_id:
683
+ continue
684
+
685
+ owned_by = item.get("owned_by", "openai")
686
+
687
+ info = item.get("info", {})
688
+ display_name = info.get("name") or item.get("name") or model_id
689
+ is_active = info.get("is_active", True)
690
+ created_at = info.get("created_at") or int(now)
691
+ updated_at = info.get("updated_at")
692
+
693
+ meta = info.get("meta") or {}
694
+ capabilities = meta.get("capabilities") or {}
695
+ mcp_servers = meta.get("mcpServerIds") or []
696
+
697
+ raw_tags = meta.get("tags") or []
698
+ tags = [
699
+ tag.get("name")
700
+ for tag in raw_tags
701
+ if isinstance(tag, dict) and tag.get("name")
702
+ ]
703
+
704
+ parsed_models.append({
705
+ "id": model_id,
706
+ "name": display_name,
707
+ "owned_by": owned_by,
708
+ "is_active": is_active,
709
+ "created": created_at,
710
+ "updated_at": updated_at,
711
+ "capabilities": capabilities,
712
+ "mcpServerIds": mcp_servers,
713
+ "tags": tags,
714
+ })
715
+
716
+ self._online_models = parsed_models
717
+ self._online_models_time = now
718
+ self._model_manager.load_from_online_models(parsed_models)
719
+ # 持久化到数据库
720
+ await self._save_models_cache(parsed_models)
721
+ self.logger.debug(
722
+ "在线模型同步成功,共获取 %s 个模型", len(parsed_models)
723
+ )
724
+ return parsed_models
725
+ else:
726
+ self.logger.warning(
727
+ "%s",
728
+ normalize_httpx_response(
729
+ response.status_code,
730
+ response.text,
731
+ content_type=response.headers.get("content-type"),
732
+ method="GET",
733
+ url=f"{self.base_url}/api/models",
734
+ context="upstream.models",
735
+ ),
736
+ )
737
+ except Exception as exc:
738
+ self.logger.warning(
739
+ "%s",
740
+ normalize_httpx_exception(
741
+ exc,
742
+ method="GET",
743
+ url=f"{self.base_url}/api/models",
744
+ context="upstream.models",
745
+ ),
746
+ exc_info=settings.DEBUG_LOGGING,
747
+ )
748
+
749
+ return self._online_models or []
750
+
751
+ _MODELS_CACHE_KEY = "online_models_cache"
752
+
753
+ async def _save_models_cache(self, models: List[Dict[str, Any]]) -> None:
754
+ """将在线模型数据持久化到 config_items 表。"""
755
+ try:
756
+ from app.services.config_dao import get_config_dao
757
+ dao = get_config_dao()
758
+ await dao.set(self._MODELS_CACHE_KEY, json.dumps(models, ensure_ascii=False))
759
+ self.logger.debug("在线模型缓存已写入数据库")
760
+ except Exception as exc:
761
+ self.logger.warning(
762
+ "在线模型缓存写入数据库失败",
763
+ exc_info=settings.DEBUG_LOGGING,
764
+ )
765
+
766
+ async def load_cached_models(self) -> bool:
767
+ """从数据库加载缓存的在线模型数据,成功返回 True。"""
768
+ try:
769
+ from app.services.config_dao import get_config_dao
770
+ dao = get_config_dao()
771
+ raw = await dao.get(self._MODELS_CACHE_KEY)
772
+ if not raw:
773
+ return False
774
+ models = json.loads(raw)
775
+ if not isinstance(models, list) or not models:
776
+ return False
777
+ self._online_models = models
778
+ self._online_models_time = time.time()
779
+ self._model_manager.load_from_online_models(models)
780
+ self.logger.debug(
781
+ "从数据库缓存加载 %s 个在线模型,"
782
+ "生成 %s 个变体",
783
+ len(models),
784
+ len(self._model_manager.get_supported_models()),
785
+ )
786
+ return True
787
+ except Exception as exc:
788
+ self.logger.warning(
789
+ "从数据库加载在线模型缓存失败",
790
+ exc_info=settings.DEBUG_LOGGING,
791
+ )
792
+ return False
793
+
794
+ def get_supported_models(self) -> List[str]:
795
+ """获取支持的模型列表"""
796
+ return self._model_manager.get_supported_models()
797
+
798
+ # ------------------------------------------------------------------
799
+ # 鉴权
800
+ # ------------------------------------------------------------------
801
+
802
+ async def _fetch_direct_guest_auth(self) -> Dict[str, Any]:
803
+ """匿名号池缺席时,兜底直连拉取一个访客令牌。"""
804
+ max_retries = 3
805
+
806
+ for retry_count in range(max_retries):
807
+ try:
808
+ fe_version = await get_latest_fe_version()
809
+ headers = build_dynamic_headers(fe_version=fe_version)
810
+ self.logger.debug(
811
+ "尝试获取访客令牌 (第%s次): %s", retry_count + 1, self.auth_url
812
+ )
813
+
814
+ client = self._get_shared_client()
815
+ response = await client.get(self.auth_url, headers=headers)
816
+
817
+ if response.status_code == 200:
818
+ data = response.json()
819
+ token = str(data.get("token") or "").strip()
820
+ if token:
821
+ user_id = str(
822
+ data.get("id")
823
+ or data.get("user_id")
824
+ or extract_user_id_from_token(token)
825
+ )
826
+ username = str(
827
+ data.get("name")
828
+ or str(data.get("email") or "").split("@")[0]
829
+ or "Guest"
830
+ )
831
+ self.logger.debug(
832
+ "直连获取匿名令牌成功: %s...", token[:20]
833
+ )
834
+ return {
835
+ "token": token,
836
+ "user_id": user_id,
837
+ "username": username or "Guest",
838
+ "auth_mode": "guest",
839
+ "token_source": "guest_direct",
840
+ "guest_user_id": user_id,
841
+ }
842
+
843
+ self.logger.warning("响应中未找到 token 字段: %s", data)
844
+ elif response.status_code == 405:
845
+ self.logger.error(
846
+ "🚫 请求被 WAF 拦截 (405),无法直连获取匿名令牌"
847
+ )
848
+ break
849
+ else:
850
+ self.logger.warning(
851
+ "%s",
852
+ normalize_httpx_response(
853
+ response.status_code,
854
+ response.text,
855
+ content_type=response.headers.get("content-type"),
856
+ method="GET",
857
+ url=self.auth_url,
858
+ context="guest_auth.direct",
859
+ ),
860
+ )
861
+ except httpx.TimeoutException as exc:
862
+ self.logger.warning(
863
+ "%s",
864
+ normalize_httpx_exception(
865
+ exc,
866
+ method="GET",
867
+ url=self.auth_url,
868
+ context="guest_auth.direct",
869
+ attempt=retry_count + 1,
870
+ ),
871
+ )
872
+ except httpx.ConnectError as exc:
873
+ self.logger.warning(
874
+ "%s",
875
+ normalize_httpx_exception(
876
+ exc,
877
+ method="GET",
878
+ url=self.auth_url,
879
+ context="guest_auth.direct",
880
+ attempt=retry_count + 1,
881
+ ),
882
+ )
883
+ except json.JSONDecodeError as exc:
884
+ self.logger.warning(
885
+ "直连获取匿名令牌 JSON 解析错误 (第%s次): %s", retry_count + 1, exc
886
+ )
887
+ except Exception as exc:
888
+ self.logger.warning(
889
+ "%s",
890
+ normalize_httpx_exception(
891
+ exc,
892
+ method="GET",
893
+ url=self.auth_url,
894
+ context="guest_auth.direct",
895
+ attempt=retry_count + 1,
896
+ ),
897
+ exc_info=settings.DEBUG_LOGGING,
898
+ )
899
+
900
+ if retry_count + 1 < max_retries:
901
+ # 指数退避: 1s → 2s → 4s(最大 8s)
902
+ await asyncio.sleep(min(2 ** retry_count, 8))
903
+
904
+ return {
905
+ "token": "",
906
+ "user_id": "guest",
907
+ "username": "Guest",
908
+ "auth_mode": "guest",
909
+ "token_source": "guest_direct",
910
+ "guest_user_id": None,
911
+ }
912
+
913
+ async def get_auth_info(
914
+ self,
915
+ excluded_tokens: Optional[Set[str]] = None,
916
+ excluded_guest_user_ids: Optional[Set[str]] = None,
917
+ ) -> Dict[str, Any]:
918
+ """优先获取认证 Token,必要时回退匿名会话池。"""
919
+ token_pool = get_token_pool()
920
+ if token_pool:
921
+ token = await token_pool.get_next_token(exclude_tokens=excluded_tokens)
922
+ if token:
923
+ user_id = extract_user_id_from_token(token)
924
+ self.logger.debug("从认证号池获取令牌: %s...", token[:20])
925
+ return {
926
+ "token": token,
927
+ "user_id": user_id,
928
+ "username": "User",
929
+ "auth_mode": "authenticated",
930
+ "token_source": "auth_pool",
931
+ "guest_user_id": None,
932
+ }
933
+
934
+ if settings.ANONYMOUS_MODE:
935
+ guest_pool = get_guest_session_pool()
936
+ if guest_pool:
937
+ try:
938
+ session = await guest_pool.acquire(
939
+ exclude_user_ids=excluded_guest_user_ids
940
+ )
941
+ self.logger.debug(
942
+ "认证池不可用,回退匿名会话池: "
943
+ "user_id=%s",
944
+ session.user_id,
945
+ )
946
+ return {
947
+ "token": session.token,
948
+ "user_id": session.user_id,
949
+ "username": session.username,
950
+ "auth_mode": "guest",
951
+ "token_source": "guest_pool",
952
+ "guest_user_id": session.user_id,
953
+ }
954
+ except Exception as exc:
955
+ self.logger.warning(
956
+ "匿名会话池获取失败,转为直连访客鉴权",
957
+ exc_info=settings.DEBUG_LOGGING,
958
+ )
959
+
960
+ return await self._fetch_direct_guest_auth()
961
+
962
+ self.logger.info(
963
+ "[guest_session.disabled] ANONYMOUS_MODE=false, skip guest pool and direct guest auth fallback"
964
+ )
965
+
966
+ self.logger.error("❌ 无法获取有效的上游令牌")
967
+ return {
968
+ "token": "",
969
+ "user_id": "",
970
+ "username": "",
971
+ "auth_mode": "authenticated",
972
+ "token_source": "none",
973
+ "guest_user_id": None,
974
+ }
975
+
976
+ async def mark_token_failure(self, token: str, error: Exception = None):
977
+ """标记token使用失败"""
978
+ token_pool = get_token_pool()
979
+ if token_pool:
980
+ await token_pool.record_token_failure(token, error)
981
+
982
+ # ------------------------------------------------------------------
983
+ # 文件上传(委托到 file_upload 模块)
984
+ # ------------------------------------------------------------------
985
+
986
+ async def upload_file(
987
+ self,
988
+ data_url: str,
989
+ chat_id: str,
990
+ token: str,
991
+ user_id: str,
992
+ auth_mode: str = "authenticated",
993
+ message_id: str = "",
994
+ ) -> Optional[Dict]:
995
+ """上传文件(图片/文档)到上游服务器。
996
+
997
+ Args:
998
+ data_url: data:mime/type;base64,... 格式的文件数据
999
+ chat_id: 当前对话ID
1000
+ token: 认证令牌
1001
+ user_id: 用户ID
1002
+ auth_mode: 当前鉴权模式,guest 模式下禁止上传
1003
+ message_id: 关联的用户消息ID
1004
+
1005
+ Returns:
1006
+ 上传成功返回完整的文件信息字典,失败返回 None
1007
+ """
1008
+ return await _upload_file(
1009
+ client=self._get_shared_client(),
1010
+ base_url=self.base_url,
1011
+ data_url=data_url,
1012
+ chat_id=chat_id,
1013
+ token=token,
1014
+ user_id=user_id,
1015
+ auth_mode=auth_mode,
1016
+ message_id=message_id,
1017
+ )
1018
+
1019
+ # ------------------------------------------------------------------
1020
+ # 请求转换
1021
+ # ------------------------------------------------------------------
1022
+
1023
+ async def transform_request(
1024
+ self,
1025
+ request: OpenAIRequest,
1026
+ excluded_tokens: Optional[Set[str]] = None,
1027
+ excluded_guest_user_ids: Optional[Set[str]] = None,
1028
+ ) -> Dict[str, Any]:
1029
+ """转换 OpenAI 请求为上游格式。"""
1030
+ self.logger.debug("转换 OpenAI 请求到上游格式: %s", request.model)
1031
+
1032
+ auth_info: Optional[Dict[str, Any]] = None # 用于 finally 中 guest session 清理
1033
+
1034
+ raw_messages = [
1035
+ message.model_dump(exclude_none=True) for message in request.messages
1036
+ ]
1037
+
1038
+ normalized_messages = preprocess_openai_messages(raw_messages)
1039
+
1040
+ # 并行拉取 auth_info 和 fe_version,减少 TTFB
1041
+ auth_info, fe_version = await asyncio.gather(
1042
+ self.get_auth_info(
1043
+ excluded_tokens=excluded_tokens,
1044
+ excluded_guest_user_ids=excluded_guest_user_ids,
1045
+ ),
1046
+ get_latest_fe_version(),
1047
+ )
1048
+ token = str(auth_info.get("token") or "")
1049
+ if not token:
1050
+ # guest session 已 acquire,失败时需归还
1051
+ await self._release_guest_session(auth_info)
1052
+ raise RuntimeError("无法获取上游认证令牌")
1053
+
1054
+ user_id = str(
1055
+ auth_info.get("user_id") or extract_user_id_from_token(token)
1056
+ )
1057
+ auth_mode = str(auth_info.get("auth_mode") or "authenticated")
1058
+ token_source = str(auth_info.get("token_source") or "unknown")
1059
+ guest_user_id = auth_info.get("guest_user_id")
1060
+
1061
+ try:
1062
+ # 提取最后一条用户消息(用于签名和会话预创建,两种模式均需要)
1063
+ last_user_text = extract_last_user_text(raw_messages)
1064
+ session_turn_content = extract_turn_content(
1065
+ raw_messages=raw_messages,
1066
+ normalized_messages=normalized_messages,
1067
+ fallback_user_text=last_user_text,
1068
+ )
1069
+
1070
+ # 解析模型特性(两种模式均需要,precreate 路径也依赖 features)
1071
+ features = self._model_manager.resolve_model_features(request)
1072
+ self.logger.debug(
1073
+ "Resolved model features for %s: %s, temperature=%s, max_tokens=%s",
1074
+ request.model,
1075
+ features,
1076
+ request.temperature,
1077
+ request.max_tokens,
1078
+ )
1079
+
1080
+ if settings.SESSION_ENABLED:
1081
+ prepared = await self._prepare_session_request(
1082
+ request,
1083
+ raw_messages=raw_messages,
1084
+ normalized_messages=normalized_messages,
1085
+ session_turn_content=session_turn_content,
1086
+ features=features,
1087
+ token=token,
1088
+ user_id=user_id,
1089
+ auth_mode=auth_mode,
1090
+ token_source=token_source,
1091
+ guest_user_id=guest_user_id,
1092
+ fe_version=fe_version,
1093
+ auth_info=auth_info,
1094
+ )
1095
+ else:
1096
+ prepared = await self._prepare_direct_request(
1097
+ normalized_messages=normalized_messages,
1098
+ features=features,
1099
+ token=token,
1100
+ user_id=user_id,
1101
+ auth_mode=auth_mode,
1102
+ token_source=token_source,
1103
+ guest_user_id=guest_user_id,
1104
+ fe_version=fe_version,
1105
+ )
1106
+
1107
+ messages, files = await process_multimodal_messages(
1108
+ normalized_messages=prepared.body_messages,
1109
+ token=prepared.token,
1110
+ user_id=prepared.user_id,
1111
+ chat_id=prepared.chat_id,
1112
+ auth_mode=prepared.auth_mode,
1113
+ http_client=self._get_shared_client(),
1114
+ base_url=self.base_url,
1115
+ )
1116
+
1117
+ # 构建请求体
1118
+ body = build_upstream_body(
1119
+ messages=messages,
1120
+ files=files,
1121
+ upstream_model_id=features["upstream_model_id"],
1122
+ last_user_text=last_user_text,
1123
+ chat_id=prepared.chat_id,
1124
+ message_id=prepared.message_id,
1125
+ enable_thinking=features["enable_thinking"],
1126
+ web_search=features["web_search"],
1127
+ auto_web_search=features["auto_web_search"],
1128
+ flags=features["flags"],
1129
+ extra=features["extra"],
1130
+ mcp_servers=features["mcp_servers"],
1131
+ temperature=request.temperature,
1132
+ max_tokens=request.max_tokens,
1133
+ parent_message_id=prepared.parent_id,
1134
+ )
1135
+ # 对齐浏览器:current_user_message_id 使用和 chats/new 一致的 ID
1136
+ body["current_user_message_id"] = prepared.user_message_id
1137
+
1138
+ # Captcha 验证参数
1139
+ if settings.CAPTCHA_ENABLED:
1140
+ try:
1141
+ captcha_client = get_captcha_client()
1142
+ if captcha_client:
1143
+ captcha_param = await captcha_client.get_token(token)
1144
+ body["captcha_verify_param"] = captcha_param
1145
+ self.logger.info("[captcha] token added to body")
1146
+ except Exception as e:
1147
+ self.logger.warning("[captcha] failed to get token: %s", e)
1148
+ # 继续不带 captcha,让上游返回错误后走重试流程
1149
+
1150
+ self.logger.debug("Upstream request body: %s", body)
1151
+
1152
+ # 签名并生成最终 URL 和 headers(复用已并行拉取的 fe_version)
1153
+ signed_url, headers, _fe_version = await sign_request(
1154
+ api_endpoint=self.api_endpoint,
1155
+ user_id=prepared.user_id,
1156
+ last_user_text=last_user_text,
1157
+ chat_id=prepared.chat_id,
1158
+ token=prepared.token,
1159
+ fe_version=fe_version,
1160
+ )
1161
+
1162
+ except Exception:
1163
+ # 签名/构建失败时归还 guest session,避免永久占用
1164
+ await self._release_authenticated_token_allocation(auth_info)
1165
+ await self._release_guest_session(auth_info)
1166
+ raise
1167
+
1168
+ return {
1169
+ "url": signed_url,
1170
+ "headers": headers,
1171
+ "body": body,
1172
+ "token": prepared.token,
1173
+ "chat_id": prepared.chat_id,
1174
+ "model": request.model,
1175
+ "user_id": prepared.user_id,
1176
+ "auth_mode": prepared.auth_mode,
1177
+ "token_source": prepared.token_source,
1178
+ "guest_user_id": prepared.guest_user_id,
1179
+ "session_commit": prepared.session_commit,
1180
+ }
1181
+
1182
+
1183
+ # ------------------------------------------------------------------
1184
+ # 聊天完成
1185
+ # ------------------------------------------------------------------
1186
+
1187
+ async def chat_completion(
1188
+ self,
1189
+ request: OpenAIRequest,
1190
+ *,
1191
+ http_request=None,
1192
+ **kwargs
1193
+ ) -> tuple[Union[Dict[str, Any], AsyncGenerator[str, None]], Optional[str]]:
1194
+ """聊天完成接口。
1195
+
1196
+ Args:
1197
+ request: OpenAI 请求对象。
1198
+ http_request: FastAPI Request 对象,用于检测客户端断开。
1199
+ """
1200
+ self.logger.debug("%s 处理请求: %s", self.name, request.model)
1201
+ self.logger.debug(" 消息数量: %s", len(request.messages))
1202
+ self.logger.debug(" 流式模式: %s", request.stream)
1203
+
1204
+ transformed: Dict[str, Any] = {}
1205
+ try:
1206
+ transformed = await self.transform_request(request)
1207
+ max_attempts = await self._get_total_retry_limit()
1208
+
1209
+ if request.stream:
1210
+ result = await self._create_stream_response(
1211
+ request, transformed, http_request=http_request,
1212
+ )
1213
+ return result, str(transformed.get("token") or "") or None
1214
+
1215
+ client = self._get_shared_client()
1216
+ excluded_tokens: Set[str] = set()
1217
+ excluded_guest_user_ids: Set[str] = set()
1218
+ empty_retries = 0
1219
+ captcha_retries = 0
1220
+
1221
+ async with asyncio.timeout(settings.CHAT_TOTAL_TIMEOUT):
1222
+ for attempt in range(max_attempts):
1223
+ response = await client.post(
1224
+ transformed["url"],
1225
+ headers=transformed["headers"],
1226
+ json=transformed["body"],
1227
+ )
1228
+ response_text = response.text
1229
+ content_type = response.headers.get("content-type")
1230
+ is_page_error = is_upstream_page_response(
1231
+ content_type,
1232
+ response_text,
1233
+ )
1234
+
1235
+ error_code, error_message = extract_upstream_error_details(
1236
+ response.status_code,
1237
+ response_text,
1238
+ content_type=content_type,
1239
+ )
1240
+ is_concurrency_limited_flag = (
1241
+ not is_page_error
1242
+ and is_concurrency_limited(
1243
+ response.status_code,
1244
+ error_code,
1245
+ error_message,
1246
+ )
1247
+ )
1248
+
1249
+ if (
1250
+ settings.CAPTCHA_ENABLED
1251
+ and error_message
1252
+ and "FRONTEND_CAPTCHA_REQUIRED" in str(error_message)
1253
+ and captcha_retries < settings.CAPTCHA_MAX_RETRIES
1254
+ ):
1255
+ captcha_retries += 1
1256
+ captcha_client = get_captcha_client()
1257
+ if captcha_client:
1258
+ try:
1259
+ fresh_token = await captcha_client.get_token(
1260
+ str(transformed.get("token") or "")
1261
+ )
1262
+ transformed["body"]["captcha_verify_param"] = fresh_token
1263
+ self.logger.warning(
1264
+ "captcha required, retrying with fresh token "
1265
+ "(captcha_retry %s/%s)",
1266
+ captcha_retries,
1267
+ settings.CAPTCHA_MAX_RETRIES,
1268
+ )
1269
+ continue
1270
+ except Exception as e:
1271
+ self.logger.warning(
1272
+ "[captcha] retry get token failed: %s", e
1273
+ )
1274
+
1275
+ if is_page_error:
1276
+ await self._release_authenticated_token_allocation(
1277
+ transformed
1278
+ )
1279
+ await self._release_guest_session(transformed)
1280
+ self.logger.error(
1281
+ "%s",
1282
+ normalize_httpx_response(
1283
+ response.status_code,
1284
+ response_text,
1285
+ content_type=content_type,
1286
+ method="POST",
1287
+ url=transformed["url"],
1288
+ context="upstream.non_stream.page",
1289
+ ),
1290
+ )
1291
+ return (
1292
+ self._build_upstream_error_response(
1293
+ response.status_code,
1294
+ error_code,
1295
+ error_message,
1296
+ is_page_error=True,
1297
+ ),
1298
+ str(transformed.get("token") or "") or None,
1299
+ )
1300
+
1301
+ if self._should_retry_guest_session(
1302
+ response.status_code,
1303
+ is_concurrency_limited_flag,
1304
+ attempt,
1305
+ max_attempts,
1306
+ transformed,
1307
+ ):
1308
+ guest_user_id = str(
1309
+ transformed.get("guest_user_id")
1310
+ or transformed.get("user_id")
1311
+ or ""
1312
+ )
1313
+ if guest_user_id:
1314
+ excluded_guest_user_ids.add(guest_user_id)
1315
+ transformed = await self._refresh_guest_request(
1316
+ request,
1317
+ attempt,
1318
+ excluded_tokens,
1319
+ excluded_guest_user_ids,
1320
+ transformed,
1321
+ is_concurrency_limited=is_concurrency_limited_flag,
1322
+ )
1323
+ continue
1324
+
1325
+ if self._should_retry_authenticated_session(
1326
+ response.status_code,
1327
+ is_concurrency_limited_flag,
1328
+ attempt,
1329
+ max_attempts,
1330
+ transformed,
1331
+ ):
1332
+ current_token = str(transformed.get("token") or "")
1333
+ if current_token:
1334
+ excluded_tokens.add(current_token)
1335
+ await self.mark_token_failure(
1336
+ current_token,
1337
+ Exception(error_message or "上游认证会话不可用"),
1338
+ )
1339
+ self.logger.warning(
1340
+ "认证会话不可用,准备切换认证 Token/回退匿名池: %s...",
1341
+ current_token[:20],
1342
+ )
1343
+ transformed = await self._refresh_authenticated_request(
1344
+ request,
1345
+ attempt,
1346
+ excluded_tokens,
1347
+ excluded_guest_user_ids,
1348
+ )
1349
+ continue
1350
+
1351
+ if not response.is_success:
1352
+ error_msg = f"上游 API 错误: {response.status_code}"
1353
+ if not self._is_guest_auth(transformed):
1354
+ current_token = str(transformed.get("token") or "")
1355
+ if current_token:
1356
+ await self.mark_token_failure(
1357
+ current_token,
1358
+ Exception(error_message or error_msg),
1359
+ )
1360
+ await self._release_guest_session(transformed)
1361
+ self.logger.error(
1362
+ "%s",
1363
+ normalize_httpx_response(
1364
+ response.status_code,
1365
+ response_text,
1366
+ content_type=content_type,
1367
+ method="POST",
1368
+ url=transformed["url"],
1369
+ context="upstream.non_stream.response",
1370
+ ),
1371
+ )
1372
+ return (
1373
+ self._build_upstream_error_response(
1374
+ response.status_code,
1375
+ error_code,
1376
+ error_message or error_msg,
1377
+ ),
1378
+ str(transformed.get("token") or "") or None,
1379
+ )
1380
+
1381
+ try:
1382
+ result = await self._response_handler.handle_non_stream_response(
1383
+ response,
1384
+ transformed["chat_id"],
1385
+ transformed["model"],
1386
+ )
1387
+ finally:
1388
+ await self._release_guest_session(transformed)
1389
+
1390
+ current_token = str(transformed.get("token") or "")
1391
+
1392
+ # 空回检测:上游返回 200 但 choices 无实际内容
1393
+ if not _openai_response_has_output(result):
1394
+ self.logger.warning(
1395
+ "空回响应 (attempt %s/%s, empty_retry %s/%s), token: %s...",
1396
+ attempt + 1,
1397
+ max_attempts,
1398
+ empty_retries + 1,
1399
+ settings.EMPTY_RESPONSE_MAX_RETRIES,
1400
+ current_token[:20] if current_token else "guest",
1401
+ )
1402
+ await write_request_log(
1403
+ provider="zai",
1404
+ model=str(transformed.get("model") or ""),
1405
+ source_info=RequestSourceInfo(
1406
+ source="upstream", protocol="openai",
1407
+ client_name="retry", endpoint="/v1/chat/completions",
1408
+ user_agent="",
1409
+ ),
1410
+ auth_token=None,
1411
+ upstream_auth_token=current_token or None,
1412
+ success=False,
1413
+ started_at=time.perf_counter(),
1414
+ status_code=200,
1415
+ error_message="Empty response: no content in choices",
1416
+ )
1417
+ if self._is_guest_auth(transformed):
1418
+ guest_user_id = str(
1419
+ transformed.get("guest_user_id")
1420
+ or transformed.get("user_id")
1421
+ or ""
1422
+ )
1423
+ if guest_user_id:
1424
+ excluded_guest_user_ids.add(guest_user_id)
1425
+ elif current_token:
1426
+ excluded_tokens.add(current_token)
1427
+ await self.mark_token_failure(
1428
+ current_token,
1429
+ Exception("Empty response: no content in choices"),
1430
+ )
1431
+ if attempt + 1 < max_attempts and empty_retries < settings.EMPTY_RESPONSE_MAX_RETRIES:
1432
+ empty_retries += 1
1433
+ if self._is_guest_auth(transformed):
1434
+ transformed = await self._refresh_guest_request(
1435
+ request,
1436
+ attempt,
1437
+ excluded_tokens,
1438
+ excluded_guest_user_ids,
1439
+ transformed,
1440
+ )
1441
+ else:
1442
+ transformed = await self._refresh_authenticated_request(
1443
+ request,
1444
+ attempt,
1445
+ excluded_tokens,
1446
+ excluded_guest_user_ids,
1447
+ )
1448
+ continue
1449
+ # 所有重试已耗尽
1450
+ return result, current_token or None
1451
+
1452
+ await self._commit_session_if_needed(transformed)
1453
+
1454
+ if not self._is_guest_auth(transformed):
1455
+ if current_token:
1456
+ token_pool = get_token_pool()
1457
+ if token_pool:
1458
+ await token_pool.record_token_success(current_token)
1459
+
1460
+ return result, current_token or None
1461
+
1462
+ except Exception as e:
1463
+ self.logger.error(
1464
+ "%s 响应失败: %s",
1465
+ self.name,
1466
+ get_error_message(e),
1467
+ exc_info=settings.DEBUG_LOGGING,
1468
+ )
1469
+ try:
1470
+ await self._release_authenticated_token_allocation(transformed)
1471
+ await self._release_guest_session(transformed)
1472
+ except Exception:
1473
+ pass
1474
+ return handle_error(e, "请求处理"), None
1475
+
1476
+ async def _create_stream_response(
1477
+ self,
1478
+ request: OpenAIRequest,
1479
+ transformed: Dict[str, Any],
1480
+ *,
1481
+ http_request=None,
1482
+ ) -> Union[Dict[str, Any], AsyncGenerator[str, None]]:
1483
+ """创建流式响应,并在首包前支持双池重试。
1484
+
1485
+ Args:
1486
+ request: OpenAI 请求对象。
1487
+ transformed: 已转换的上游请求参数字典。
1488
+ http_request: FastAPI Request 对象,用于检测客户端断开。
1489
+ """
1490
+ max_attempts = await self._get_total_retry_limit()
1491
+ excluded_tokens: Set[str] = set()
1492
+ excluded_guest_user_ids: Set[str] = set()
1493
+ current_token = str(transformed.get("token") or "")
1494
+ empty_retries = 0
1495
+ captcha_retries = 0
1496
+
1497
+ client = self._get_shared_stream_client()
1498
+ loop = asyncio.get_running_loop()
1499
+ stream_deadline = loop.time() + settings.HTTP_STREAM_TOTAL_TIMEOUT
1500
+
1501
+ def _remaining_timeout() -> float:
1502
+ return stream_deadline - loop.time()
1503
+
1504
+ for attempt in range(max_attempts):
1505
+ if _remaining_timeout() <= 0:
1506
+ await self._release_authenticated_token_allocation(transformed)
1507
+ await self._release_guest_session(transformed)
1508
+ return {
1509
+ "error": {
1510
+ "message": "流式请求总超时,请重试。",
1511
+ "type": "stream_timeout",
1512
+ "code": 504,
1513
+ }
1514
+ }
1515
+
1516
+ self.logger.debug("发送请求到上游: %s", transformed["url"])
1517
+ req = client.build_request(
1518
+ "POST",
1519
+ transformed["url"],
1520
+ json=transformed["body"],
1521
+ headers=transformed["headers"],
1522
+ )
1523
+
1524
+ try:
1525
+ response = await asyncio.wait_for(
1526
+ client.send(req, stream=True),
1527
+ timeout=max(0.1, _remaining_timeout()),
1528
+ )
1529
+ except asyncio.TimeoutError as e:
1530
+ self.logger.error(
1531
+ "%s",
1532
+ normalize_httpx_exception(
1533
+ e,
1534
+ method="POST",
1535
+ url=transformed["url"],
1536
+ context="upstream.stream.connect",
1537
+ ),
1538
+ )
1539
+ if self._is_guest_auth(transformed):
1540
+ await self._release_guest_session(transformed)
1541
+ elif current_token:
1542
+ await self.mark_token_failure(current_token, e)
1543
+ return {
1544
+ "error": {
1545
+ "message": "上游连接超时,请重试。",
1546
+ "type": "stream_timeout",
1547
+ "code": 504,
1548
+ }
1549
+ }
1550
+ except Exception as e:
1551
+ friendly_msg = get_error_message(e)
1552
+ self.logger.error(
1553
+ "%s (raw: %s)",
1554
+ normalize_httpx_exception(
1555
+ e,
1556
+ method="POST",
1557
+ url=transformed["url"],
1558
+ context="upstream.stream.connect",
1559
+ ),
1560
+ e,
1561
+ )
1562
+ if self._is_guest_auth(transformed):
1563
+ await self._release_guest_session(transformed)
1564
+ elif current_token:
1565
+ await self.mark_token_failure(current_token, e)
1566
+ return {
1567
+ "error": {
1568
+ "message": f"上游连接异常: {friendly_msg}",
1569
+ "type": "stream_error",
1570
+ }
1571
+ }
1572
+
1573
+ try:
1574
+ error_text = b""
1575
+ content_type = response.headers.get("content-type")
1576
+ should_read_error_body = (
1577
+ response.status_code != 200
1578
+ or is_upstream_page_response(content_type, "")
1579
+ )
1580
+ if should_read_error_body:
1581
+ error_text = await asyncio.wait_for(
1582
+ response.aread(),
1583
+ timeout=max(0.1, _remaining_timeout()),
1584
+ )
1585
+ error_msg = error_text.decode("utf-8", errors="ignore")
1586
+ is_page_error = is_upstream_page_response(content_type, error_msg)
1587
+ error_code, parsed_error_message = (
1588
+ extract_upstream_error_details(
1589
+ response.status_code,
1590
+ error_msg,
1591
+ content_type=content_type,
1592
+ )
1593
+ if should_read_error_body
1594
+ else (None, "")
1595
+ )
1596
+ is_concurrency_limited_flag = (
1597
+ not is_page_error
1598
+ and is_concurrency_limited(
1599
+ response.status_code,
1600
+ error_code,
1601
+ parsed_error_message,
1602
+ )
1603
+ )
1604
+
1605
+ if (
1606
+ settings.CAPTCHA_ENABLED
1607
+ and parsed_error_message
1608
+ and "FRONTEND_CAPTCHA_REQUIRED" in str(parsed_error_message)
1609
+ and captcha_retries < settings.CAPTCHA_MAX_RETRIES
1610
+ ):
1611
+ captcha_retries += 1
1612
+ await response.aclose()
1613
+ captcha_client = get_captcha_client()
1614
+ if captcha_client:
1615
+ try:
1616
+ fresh_token = await captcha_client.get_token(
1617
+ str(transformed.get("token") or "")
1618
+ )
1619
+ transformed["body"]["captcha_verify_param"] = fresh_token
1620
+ self.logger.warning(
1621
+ "captcha required, retrying with fresh token "
1622
+ "(captcha_retry %s/%s)",
1623
+ captcha_retries,
1624
+ settings.CAPTCHA_MAX_RETRIES,
1625
+ )
1626
+ continue
1627
+ except Exception as e:
1628
+ self.logger.warning(
1629
+ "[captcha] retry get token failed: %s", e
1630
+ )
1631
+
1632
+ if is_page_error:
1633
+ await response.aclose()
1634
+ await self._release_authenticated_token_allocation(
1635
+ transformed
1636
+ )
1637
+ self.logger.error(
1638
+ "%s",
1639
+ normalize_httpx_response(
1640
+ response.status_code,
1641
+ error_msg,
1642
+ content_type=content_type,
1643
+ method="POST",
1644
+ url=transformed["url"],
1645
+ context="upstream.stream.page",
1646
+ ),
1647
+ )
1648
+ await self._release_guest_session(transformed)
1649
+ return self._build_upstream_error_response(
1650
+ response.status_code,
1651
+ error_code,
1652
+ parsed_error_message,
1653
+ is_page_error=True,
1654
+ )
1655
+
1656
+ if self._should_retry_guest_session(
1657
+ response.status_code,
1658
+ is_concurrency_limited_flag,
1659
+ attempt,
1660
+ max_attempts,
1661
+ transformed,
1662
+ ):
1663
+ await response.aclose()
1664
+ guest_user_id = str(
1665
+ transformed.get("guest_user_id")
1666
+ or transformed.get("user_id")
1667
+ or ""
1668
+ )
1669
+ if guest_user_id:
1670
+ excluded_guest_user_ids.add(guest_user_id)
1671
+ transformed = await self._refresh_guest_request(
1672
+ request,
1673
+ attempt,
1674
+ excluded_tokens,
1675
+ excluded_guest_user_ids,
1676
+ transformed,
1677
+ is_concurrency_limited=is_concurrency_limited_flag,
1678
+ )
1679
+ current_token = str(transformed.get("token") or "")
1680
+ continue
1681
+
1682
+ if self._should_retry_authenticated_session(
1683
+ response.status_code,
1684
+ is_concurrency_limited_flag,
1685
+ attempt,
1686
+ max_attempts,
1687
+ transformed,
1688
+ ):
1689
+ await response.aclose()
1690
+ if current_token:
1691
+ excluded_tokens.add(current_token)
1692
+ await self.mark_token_failure(
1693
+ current_token,
1694
+ Exception(
1695
+ parsed_error_message or "上游认证会话不可用"
1696
+ ),
1697
+ )
1698
+ self.logger.warning(
1699
+ "流式请求命中认证会话限制,准备切号/回退匿名池: %s...",
1700
+ current_token[:20],
1701
+ )
1702
+ transformed = await self._refresh_authenticated_request(
1703
+ request,
1704
+ attempt,
1705
+ excluded_tokens,
1706
+ excluded_guest_user_ids,
1707
+ )
1708
+ current_token = str(transformed.get("token") or "")
1709
+ continue
1710
+
1711
+ if response.status_code != 200:
1712
+ await response.aclose()
1713
+ self.logger.error(
1714
+ "%s",
1715
+ normalize_httpx_response(
1716
+ response.status_code,
1717
+ error_msg,
1718
+ content_type=content_type,
1719
+ method="POST",
1720
+ url=transformed["url"],
1721
+ context="upstream.stream.response",
1722
+ ),
1723
+ )
1724
+
1725
+ if not self._is_guest_auth(transformed) and current_token:
1726
+ await self.mark_token_failure(
1727
+ current_token,
1728
+ Exception(
1729
+ parsed_error_message
1730
+ or f"Upstream error: {response.status_code}"
1731
+ ),
1732
+ )
1733
+ await self._release_guest_session(transformed)
1734
+ return self._build_upstream_error_response(
1735
+ response.status_code,
1736
+ error_code,
1737
+ parsed_error_message,
1738
+ )
1739
+
1740
+ chat_id = transformed["chat_id"]
1741
+ model = transformed["model"]
1742
+
1743
+ # Peek at stream to detect empty response before committing
1744
+ response_iter = self._response_handler.handle_stream_response(
1745
+ response,
1746
+ chat_id,
1747
+ model,
1748
+ started_at=getattr(request, "started_at", None),
1749
+ )
1750
+ buffer: list[str] = []
1751
+ found_output = False
1752
+ try:
1753
+ remaining = _remaining_timeout()
1754
+ if remaining > 0:
1755
+ async with asyncio.timeout(max(0.1, remaining)):
1756
+ async for chunk in response_iter:
1757
+ buffer.append(chunk)
1758
+ if _sse_chunk_has_output(chunk):
1759
+ found_output = True
1760
+ break
1761
+ except (asyncio.TimeoutError, Exception):
1762
+ pass
1763
+
1764
+ if not found_output:
1765
+ await response.aclose()
1766
+ self.logger.warning(
1767
+ "流式空回响应 (attempt %s/%s, empty_retry %s/%s), token: %s...",
1768
+ attempt + 1, max_attempts,
1769
+ empty_retries + 1, settings.EMPTY_RESPONSE_MAX_RETRIES,
1770
+ current_token[:20] if current_token else "guest",
1771
+ )
1772
+ await write_request_log(
1773
+ provider="zai",
1774
+ model=str(transformed.get("model") or ""),
1775
+ source_info=RequestSourceInfo(
1776
+ source="upstream", protocol="openai",
1777
+ client_name="retry", endpoint="/v1/chat/completions",
1778
+ user_agent="",
1779
+ ),
1780
+ auth_token=None,
1781
+ upstream_auth_token=current_token or None,
1782
+ success=False,
1783
+ started_at=time.perf_counter(),
1784
+ status_code=200,
1785
+ error_message="Empty stream: no content in response",
1786
+ )
1787
+ if self._is_guest_auth(transformed):
1788
+ guest_user_id = str(
1789
+ transformed.get("guest_user_id")
1790
+ or transformed.get("user_id")
1791
+ or ""
1792
+ )
1793
+ if guest_user_id:
1794
+ excluded_guest_user_ids.add(guest_user_id)
1795
+ elif current_token:
1796
+ excluded_tokens.add(current_token)
1797
+ await self.mark_token_failure(
1798
+ current_token,
1799
+ Exception("Empty stream: no content"),
1800
+ )
1801
+ await self._release_guest_session(transformed)
1802
+ if attempt + 1 < max_attempts and empty_retries < settings.EMPTY_RESPONSE_MAX_RETRIES:
1803
+ empty_retries += 1
1804
+ if self._is_guest_auth(transformed):
1805
+ transformed = await self._refresh_guest_request(
1806
+ request, attempt, excluded_tokens,
1807
+ excluded_guest_user_ids, transformed,
1808
+ )
1809
+ else:
1810
+ transformed = await self._refresh_authenticated_request(
1811
+ request, attempt, excluded_tokens,
1812
+ excluded_guest_user_ids,
1813
+ )
1814
+ current_token = str(transformed.get("token") or "")
1815
+ continue
1816
+ return {
1817
+ "error": {
1818
+ "message": "Empty stream: no content in response",
1819
+ "type": "stream_error",
1820
+ "code": 502,
1821
+ }
1822
+ }
1823
+
1824
+ await self._commit_session_if_needed(transformed)
1825
+
1826
+ async def stream_generator() -> AsyncGenerator[str, None]:
1827
+ success = False
1828
+ disconnect_task: Optional[asyncio.Task] = None
1829
+
1830
+ async def _wait_for_disconnect() -> None:
1831
+ """后台任务:每 0.5s 轮询一次,检测到客户端断开后
1832
+ 立即关闭上游 HTTP 响应,使 aiter_lines() 退出。"""
1833
+ try:
1834
+ while True:
1835
+ if await http_request.is_disconnected():
1836
+ self.logger.debug(
1837
+ "[stream] client disconnected, closing upstream stream (chat_id=%s)",
1838
+ chat_id,
1839
+ )
1840
+ await response.aclose()
1841
+ return
1842
+ await asyncio.sleep(0.5)
1843
+ except asyncio.CancelledError:
1844
+ pass
1845
+
1846
+ try:
1847
+ if http_request is not None:
1848
+ disconnect_task = asyncio.create_task(
1849
+ _wait_for_disconnect()
1850
+ )
1851
+
1852
+ remaining = _remaining_timeout()
1853
+ if remaining <= 0:
1854
+ raise asyncio.TimeoutError(
1855
+ "stream total timeout before consume"
1856
+ )
1857
+
1858
+ async with asyncio.timeout(remaining):
1859
+ for chunk in buffer:
1860
+ yield chunk
1861
+ async for chunk in response_iter:
1862
+ yield chunk
1863
+ success = True
1864
+ except asyncio.TimeoutError as e:
1865
+ self.logger.error("流处理超时: %s", e)
1866
+ if not self._is_guest_auth(transformed) and current_token:
1867
+ await self.mark_token_failure(current_token, e)
1868
+ error_response = {
1869
+ "error": {
1870
+ "message": "流处理超时,请重试。",
1871
+ "type": "stream_timeout",
1872
+ "code": 504,
1873
+ }
1874
+ }
1875
+ yield f"data: {json.dumps(error_response)}\n\n"
1876
+ yield "data: [DONE]\n\n"
1877
+ except asyncio.CancelledError:
1878
+ self.logger.debug(
1879
+ "[stream] stream task cancelled (chat_id=%s)",
1880
+ chat_id,
1881
+ )
1882
+ if (
1883
+ not self._is_guest_auth(transformed)
1884
+ and current_token
1885
+ ):
1886
+ await self._release_authenticated_token_allocation(
1887
+ transformed
1888
+ )
1889
+ except Exception as e:
1890
+ friendly_msg = get_error_message(e)
1891
+ self.logger.error(
1892
+ "流处理错误: %s (raw: %s)",
1893
+ friendly_msg,
1894
+ e,
1895
+ )
1896
+ if not self._is_guest_auth(transformed) and current_token:
1897
+ await self.mark_token_failure(current_token, e)
1898
+ error_response = {
1899
+ "error": {
1900
+ "message": f"流处理错误: {friendly_msg}",
1901
+ "type": "stream_error",
1902
+ }
1903
+ }
1904
+ yield f"data: {json.dumps(error_response)}\n\n"
1905
+ yield "data: [DONE]\n\n"
1906
+ finally:
1907
+ if disconnect_task is not None and not disconnect_task.done():
1908
+ disconnect_task.cancel()
1909
+ try:
1910
+ await disconnect_task
1911
+ except asyncio.CancelledError:
1912
+ pass
1913
+ await response.aclose()
1914
+ await self._release_guest_session(transformed)
1915
+ if (
1916
+ success
1917
+ and not self._is_guest_auth(transformed)
1918
+ and current_token
1919
+ ):
1920
+ token_pool = get_token_pool()
1921
+ if token_pool:
1922
+ await token_pool.record_token_success(current_token)
1923
+
1924
+ return stream_generator()
1925
+
1926
+ except asyncio.TimeoutError as e:
1927
+ await response.aclose()
1928
+ self.logger.error("流处理超时: %s", e)
1929
+ if self._is_guest_auth(transformed):
1930
+ await self._release_guest_session(transformed)
1931
+ elif current_token:
1932
+ await self.mark_token_failure(current_token, e)
1933
+ return {
1934
+ "error": {
1935
+ "message": "流处理超时,请重试。",
1936
+ "type": "stream_timeout",
1937
+ "code": 504,
1938
+ }
1939
+ }
1940
+ except Exception as e:
1941
+ await response.aclose()
1942
+ friendly_msg = get_error_message(e)
1943
+ self.logger.error(
1944
+ "流处理错误: %s (raw: %s)",
1945
+ friendly_msg,
1946
+ e,
1947
+ )
1948
+ if self._is_guest_auth(transformed):
1949
+ await self._release_guest_session(transformed)
1950
+ elif current_token:
1951
+ await self.mark_token_failure(current_token, e)
1952
+
1953
+ return {
1954
+ "error": {
1955
+ "message": f"流处理错误: {friendly_msg}",
1956
+ "type": "stream_error",
1957
+ }
1958
+ }
1959
+
1960
+ await self._release_authenticated_token_allocation(transformed)
1961
+ await self._release_guest_session(transformed)
1962
+ return {
1963
+ "error": {
1964
+ "message": "Max retry attempts exhausted.",
1965
+ "type": "stream_error",
1966
+ "code": 500
1967
+ }
1968
+ }
app/core/upstream_urls.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """Helpers for deriving upstream URLs from the configured chat endpoint."""
5
+
6
+ from __future__ import annotations
7
+
8
+ from urllib.parse import urlsplit, urlunsplit
9
+
10
+ from app.core.config import settings
11
+
12
+ DEFAULT_CHAT_COMPLETION_ENDPOINT = "https://chat.z.ai/api/v2/chat/completions"
13
+ _KNOWN_CHAT_COMPLETION_SUFFIXES = (
14
+ "/api/v2/chat/completions",
15
+ "/api/v1/chat/completions",
16
+ "/v1/chat/completions",
17
+ "/chat/completions",
18
+ )
19
+
20
+
21
+ def get_api_endpoint() -> str:
22
+ """Return the configured chat-completion endpoint with a safe fallback."""
23
+ endpoint = str(settings.API_ENDPOINT or "").strip()
24
+ return endpoint or DEFAULT_CHAT_COMPLETION_ENDPOINT
25
+
26
+
27
+ def derive_upstream_base_url(api_endpoint: str) -> str:
28
+ """Derive a reusable upstream base URL from a chat-completion endpoint.
29
+
30
+ Examples:
31
+ https://chat.z.ai/api/v2/chat/completions
32
+ -> https://chat.z.ai
33
+ http://host/token/platform/https/chat.z.ai/api/v2/chat/completions
34
+ -> http://host/token/platform/https/chat.z.ai
35
+ """
36
+ endpoint = str(api_endpoint or "").strip()
37
+ if not endpoint:
38
+ endpoint = DEFAULT_CHAT_COMPLETION_ENDPOINT
39
+
40
+ parts = urlsplit(endpoint)
41
+ if not parts.scheme or not parts.netloc:
42
+ return endpoint.rstrip("/")
43
+
44
+ path = parts.path.rstrip("/")
45
+ for suffix in _KNOWN_CHAT_COMPLETION_SUFFIXES:
46
+ if path.endswith(suffix):
47
+ base_path = path[: -len(suffix)].rstrip("/")
48
+ return urlunsplit((parts.scheme, parts.netloc, base_path, "", ""))
49
+
50
+ if not path:
51
+ return urlunsplit((parts.scheme, parts.netloc, "", "", ""))
52
+
53
+ base_path = path.rsplit("/", 1)[0]
54
+ return urlunsplit((parts.scheme, parts.netloc, base_path, "", ""))
55
+
56
+
57
+ def get_upstream_base_url() -> str:
58
+ """Return the configured base URL for upstream auxiliary endpoints."""
59
+ return derive_upstream_base_url(get_api_endpoint())
60
+
61
+
62
+ def build_upstream_url(path: str) -> str:
63
+ """Join a relative upstream path onto the configured upstream base URL."""
64
+ base_url = get_upstream_base_url().rstrip("/")
65
+ normalized_path = path if path.startswith("/") else f"/{path}"
66
+ return f"{base_url}{normalized_path}"
app/database.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import ssl as _stdlib_ssl
3
+ from typing import AsyncGenerator
4
+ from urllib.parse import urlparse, parse_qs, urlencode, urlunparse
5
+ from contextlib import asynccontextmanager
6
+
7
+ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
8
+
9
+ from app.core.config import settings
10
+
11
+
12
+ def _clean_db_url(url: str) -> tuple[str, dict]:
13
+ """Strip unsupported parameters from a PostgreSQL URL and return (cleaned_url, connect_args).
14
+
15
+ - asyncpg does not accept `sslmode` as a query-string parameter (that is a
16
+ libpq / psycopg2 convention). We translate it into asyncpg's `ssl`
17
+ connect-arg instead.
18
+ - asyncpg does not accept `channel_binding`. We strip it.
19
+ """
20
+ parsed = urlparse(url)
21
+ qs = parse_qs(parsed.query)
22
+ sslmode = qs.pop("sslmode", [None])[0]
23
+ # Remove channel_binding to prevent TypeError in asyncpg connect()
24
+ qs.pop("channel_binding", None)
25
+
26
+ # Rebuild the URL without the stripped parameters
27
+ new_query = urlencode({k: v[0] for k, v in qs.items()})
28
+ cleaned_url = urlunparse(parsed._replace(query=new_query))
29
+
30
+ connect_args: dict = {}
31
+ if sslmode:
32
+ if sslmode == "disable":
33
+ connect_args["ssl"] = False
34
+ elif sslmode in ("require", "prefer"):
35
+ # asyncpg accepts an ssl.SSLContext or the string "require" (>= 0.29)
36
+ # Use a permissive SSLContext that skips certificate verification,
37
+ # which matches the behavior of libpq's `sslmode=require`.
38
+ ctx = _stdlib_ssl.create_default_context()
39
+ ctx.check_hostname = False
40
+ ctx.verify_mode = _stdlib_ssl.CERT_NONE
41
+ connect_args["ssl"] = ctx
42
+ elif sslmode in ("verify-ca", "verify-full"):
43
+ connect_args["ssl"] = True # uses default SSL context with verification
44
+
45
+ return cleaned_url, connect_args
46
+
47
+
48
+ def get_db_url(db_url: str = None) -> tuple[str, dict]:
49
+ """获取数据库连接 URL 和 connect_args"""
50
+ url = db_url or settings.DATABASE_URL
51
+ connect_args: dict = {}
52
+
53
+ if url:
54
+ if url.startswith("postgres://"):
55
+ url = url.replace("postgres://", "postgresql+asyncpg://", 1)
56
+ elif url.startswith("postgresql://"):
57
+ url = url.replace("postgresql://", "postgresql+asyncpg://", 1)
58
+ # 如果已经是 postgresql+asyncpg 或者是 sqlite+aiosqlite,则直接使用
59
+ elif url.startswith("sqlite"):
60
+ if not url.startswith("sqlite+aiosqlite"):
61
+ url = url.replace("sqlite://", "sqlite+aiosqlite://", 1)
62
+
63
+ # Strip unsupported parameters for asyncpg compatibility
64
+ if "asyncpg" in url:
65
+ url, connect_args = _clean_db_url(url)
66
+
67
+ return url, connect_args
68
+
69
+ db_path = settings.DB_PATH
70
+ if not os.path.isabs(db_path):
71
+ db_path = os.path.abspath(db_path)
72
+ return f"sqlite+aiosqlite:///{db_path}", {}
73
+
74
+ # 1. 声明全局变量为 None,绝不在这里直接实例化
75
+ engine = None
76
+ async_session = None
77
+
78
+ def get_session_maker():
79
+ """懒加载:获取真实的 session_maker,如果不存在则在当前进程初始化"""
80
+ global engine, async_session
81
+ if engine is None:
82
+ _db_url, _connect_args = get_db_url()
83
+ engine = create_async_engine(
84
+ _db_url,
85
+ echo=False,
86
+ pool_pre_ping=True,
87
+ pool_size=5,
88
+ max_overflow=10,
89
+ pool_recycle=3600,
90
+ pool_timeout=30,
91
+ connect_args=_connect_args
92
+ )
93
+ async_session = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
94
+ return async_session
95
+
96
+ @asynccontextmanager
97
+ async def get_db_session() -> AsyncGenerator[AsyncSession, None]:
98
+ """推荐的上下文管理器用法,自动获取 maker 并管理 session"""
99
+ maker = get_session_maker()
100
+ async with maker() as session:
101
+ yield session
102
+
103
+ async def init_db():
104
+ """初始化数据库表"""
105
+ from app.utils.logger import logger, log_exception
106
+
107
+ # 确保 engine 已被当前 Worker 进程创建
108
+ get_session_maker()
109
+ global engine
110
+
111
+ async with engine.begin() as conn:
112
+ try:
113
+ from alembic.config import Config
114
+ from alembic import command
115
+ import os
116
+
117
+ logger.debug("自动数据库迁移: 准备执行 Alembic...")
118
+
119
+ base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
120
+ alembic_cfg = Config(os.path.join(base_dir, "alembic.ini"))
121
+ alembic_cfg.set_main_option("script_location", os.path.join(base_dir, "migrations"))
122
+
123
+ def run_upgrade(connection):
124
+ alembic_cfg.attributes['connection'] = connection
125
+ command.upgrade(alembic_cfg, "head")
126
+
127
+ await conn.run_sync(run_upgrade)
128
+ logger.debug("迁移成功")
129
+ except Exception as e:
130
+ log_exception(logger, "自动迁移过程中出错")
131
+
132
+ async def close_db():
133
+ """关闭数据库连接"""
134
+ global engine, async_session
135
+ if engine is not None:
136
+ await engine.dispose()
137
+ engine = None # 释放后重置为 None
138
+ async_session = None
app/exceptions/__init__.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """统一异常包。
5
+
6
+ 提供标准化的异常类层次结构,支持:
7
+ - 统一的错误码和 HTTP 状态码映射
8
+ - 结构化的错误详情
9
+ - OpenAI 兼容的错误响应格式
10
+ """
11
+
12
+ from app.exceptions.base import AppError
13
+ from app.exceptions.api import (
14
+ AuthenticationError,
15
+ AuthorizationError,
16
+ ValidationError,
17
+ ModelNotFoundError,
18
+ RateLimitError,
19
+ )
20
+ from app.exceptions.upstream import (
21
+ UpstreamError,
22
+ UpstreamRateLimited,
23
+ UpstreamTimeout,
24
+ UpstreamConnectionError,
25
+ )
26
+ from app.exceptions.http import (
27
+ HttpError,
28
+ HttpConnectionError,
29
+ SSLError,
30
+ ProxyError,
31
+ HttpTimeoutError,
32
+ )
33
+
34
+ __all__ = [
35
+ # Base
36
+ "AppError",
37
+ # API errors
38
+ "AuthenticationError",
39
+ "AuthorizationError",
40
+ "ValidationError",
41
+ "ModelNotFoundError",
42
+ "RateLimitError",
43
+ # Upstream errors
44
+ "UpstreamError",
45
+ "UpstreamRateLimited",
46
+ "UpstreamTimeout",
47
+ "UpstreamConnectionError",
48
+ # HTTP errors
49
+ "HttpError",
50
+ "HttpConnectionError",
51
+ "SSLError",
52
+ "ProxyError",
53
+ "HttpTimeoutError",
54
+ ]
app/exceptions/api.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """API 层异常类。
5
+
6
+ 用于 API 端点层的错误,如认证、授权、验证等。
7
+ """
8
+
9
+ from typing import Any, Dict, Optional
10
+
11
+ from app.exceptions.base import AppError
12
+
13
+
14
+ class AuthenticationError(AppError):
15
+ """认证失败异常。
16
+
17
+ 当用户未提供认证信息或认证信息无效时抛出。
18
+
19
+ Example:
20
+ >>> raise AuthenticationError("Missing Authorization header")
21
+ >>> raise AuthenticationError("Invalid API key")
22
+ """
23
+
24
+ def __init__(
25
+ self,
26
+ message: str = "Authentication failed",
27
+ details: Optional[Dict[str, Any]] = None,
28
+ ) -> None:
29
+ super().__init__(
30
+ message=message,
31
+ code="authentication_error",
32
+ status_code=401,
33
+ details=details,
34
+ )
35
+
36
+
37
+ class AuthorizationError(AppError):
38
+ """授权失败异常。
39
+
40
+ 当用户已认证但权限不足时抛出。
41
+
42
+ Example:
43
+ >>> raise AuthorizationError("Access denied to this resource")
44
+ """
45
+
46
+ def __init__(
47
+ self,
48
+ message: str = "Permission denied",
49
+ details: Optional[Dict[str, Any]] = None,
50
+ ) -> None:
51
+ super().__init__(
52
+ message=message,
53
+ code="authorization_error",
54
+ status_code=403,
55
+ details=details,
56
+ )
57
+
58
+
59
+ class ValidationError(AppError):
60
+ """请求验证失败异常。
61
+
62
+ 当请求数据不符合预期格式或约束时抛出。
63
+
64
+ Example:
65
+ >>> raise ValidationError("Invalid email format", field="email")
66
+ >>> raise ValidationError("messages cannot be empty")
67
+ """
68
+
69
+ def __init__(
70
+ self,
71
+ message: str,
72
+ field: Optional[str] = None,
73
+ details: Optional[Dict[str, Any]] = None,
74
+ ) -> None:
75
+ final_details = details or {}
76
+ if field:
77
+ final_details["field"] = field
78
+ super().__init__(
79
+ message=message,
80
+ code="validation_error",
81
+ status_code=400,
82
+ details=final_details,
83
+ )
84
+
85
+
86
+ class ModelNotFoundError(AppError):
87
+ """模型不存在异常。
88
+
89
+ 当请求的模型不在支持列表中时抛出。
90
+
91
+ Example:
92
+ >>> raise ModelNotFoundError("gpt-5")
93
+ """
94
+
95
+ def __init__(self, model: str) -> None:
96
+ super().__init__(
97
+ message=f"Model '{model}' not found",
98
+ code="model_not_found",
99
+ status_code=404,
100
+ details={"model": model},
101
+ )
102
+
103
+
104
+ class RateLimitError(AppError):
105
+ """请求频率限制异常。
106
+
107
+ 当客户端请求过于频繁时抛出。
108
+
109
+ Example:
110
+ >>> raise RateLimitError(retry_after=60)
111
+ """
112
+
113
+ def __init__(
114
+ self,
115
+ message: str = "Rate limit exceeded",
116
+ retry_after: Optional[int] = None,
117
+ ) -> None:
118
+ details = {}
119
+ if retry_after is not None:
120
+ details["retry_after"] = retry_after
121
+ super().__init__(
122
+ message=message,
123
+ code="rate_limit_exceeded",
124
+ status_code=429,
125
+ details=details,
126
+ )
app/exceptions/base.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """基础异常类。
5
+
6
+ 所有应用异常的基类,提供:
7
+ - 标准化的错误消息
8
+ - 错误码 (code)
9
+ - HTTP 状态码 (status_code)
10
+ - 结构化详情 (details)
11
+ - OpenAI 兼容的 to_dict() 方法
12
+ """
13
+
14
+ from typing import Any, Dict, Optional
15
+
16
+
17
+ class AppError(Exception):
18
+ """应用基础异常类。
19
+
20
+ 所有业务异常应继承此类,确保统一的错误处理。
21
+
22
+ Attributes:
23
+ message: 人类可读的错误消息
24
+ code: 错误码,用于程序识别
25
+ status_code: HTTP 状态码
26
+ details: 额外的错误详情
27
+
28
+ Example:
29
+ >>> raise AppError("Something went wrong", code="internal_error", status_code=500)
30
+ >>> raise ValidationError("Invalid email", field="email")
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ message: str,
36
+ code: str = "internal_error",
37
+ status_code: int = 500,
38
+ details: Optional[Dict[str, Any]] = None,
39
+ ) -> None:
40
+ self.message = message
41
+ self.code = code
42
+ self.status_code = status_code
43
+ self.details = details or {}
44
+ super().__init__(message)
45
+
46
+ def to_dict(self) -> Dict[str, Any]:
47
+ """转换为 OpenAI 兼容的错误响应格式。
48
+
49
+ Returns:
50
+ 符合 OpenAI API 规范的错误字典
51
+ """
52
+ error: Dict[str, Any] = {
53
+ "message": self.message,
54
+ "type": self.__class__.__name__,
55
+ "code": self.code,
56
+ }
57
+ if self.details:
58
+ error["details"] = self.details
59
+ return {"error": error}
60
+
61
+ def __repr__(self) -> str:
62
+ return f"{self.__class__.__name__}(message={self.message!r}, code={self.code!r}, status_code={self.status_code})"
63
+
64
+
65
+ class ErrorContext:
66
+ """错误上下文管理器,用于自动捕获和转换异常。
67
+
68
+ Example:
69
+ >>> async with ErrorContext("Processing request", request_id="123"):
70
+ ... await process_request()
71
+ """
72
+
73
+ def __init__(
74
+ self,
75
+ operation: str,
76
+ **context: Any,
77
+ ) -> None:
78
+ self.operation = operation
79
+ self.context = context
80
+
81
+ def __enter__(self) -> "ErrorContext":
82
+ return self
83
+
84
+ def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> bool:
85
+ if exc_val is not None and not isinstance(exc_val, AppError):
86
+ # 将非 AppError 异常包装为 AppError
87
+ raise AppError(
88
+ message=f"{self.operation} failed: {exc_val}",
89
+ code="internal_error",
90
+ status_code=500,
91
+ details=self.context,
92
+ ) from exc_val
93
+ return False
app/exceptions/http.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """HTTP 客户端异常类。
5
+
6
+ 用于处理 HTTP 请求过程中的错误,如网络问题、SSL、代理等。
7
+ """
8
+
9
+ from typing import Any, Dict, Optional
10
+
11
+ from app.exceptions.base import AppError
12
+
13
+
14
+ class HttpError(AppError):
15
+ """HTTP 客户端错误基类。
16
+
17
+ 当 HTTP 请求失败时抛出。
18
+
19
+ Attributes:
20
+ url: 请求的 URL
21
+ method: HTTP 方法
22
+
23
+ Example:
24
+ >>> raise HttpError("Request failed", url="https://api.example.com", method="POST")
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ message: str,
30
+ url: Optional[str] = None,
31
+ method: Optional[str] = None,
32
+ details: Optional[Dict[str, Any]] = None,
33
+ ) -> None:
34
+ final_details = details or {}
35
+ if url:
36
+ final_details["url"] = url
37
+ if method:
38
+ final_details["method"] = method
39
+ super().__init__(
40
+ message=message,
41
+ code="http_error",
42
+ status_code=502,
43
+ details=final_details,
44
+ )
45
+
46
+
47
+ class HttpConnectionError(HttpError):
48
+ """连接失败异常。
49
+
50
+ 当无法建立 TCP 连接时抛出。
51
+
52
+ Example:
53
+ >>> raise HttpConnectionError("https://api.example.com", "Connection refused")
54
+ """
55
+
56
+ def __init__(
57
+ self,
58
+ url: str,
59
+ reason: str,
60
+ ) -> None:
61
+ super().__init__(
62
+ message=f"Connection failed: {reason}",
63
+ url=url,
64
+ )
65
+ self.code = "connection_error"
66
+ self.status_code = 503
67
+
68
+
69
+ class SSLError(HttpError):
70
+ """SSL/TLS 错误异常。
71
+
72
+ 当 SSL 握手失败或证书验证失败时抛出。
73
+
74
+ Example:
75
+ >>> raise SSLError("https://api.example.com", "Certificate verify failed")
76
+ """
77
+
78
+ def __init__(
79
+ self,
80
+ url: str,
81
+ reason: str,
82
+ ) -> None:
83
+ super().__init__(
84
+ message=f"SSL/TLS error: {reason}",
85
+ url=url,
86
+ )
87
+ self.code = "ssl_error"
88
+
89
+
90
+ class ProxyError(HttpError):
91
+ """代理错误异常。
92
+
93
+ 当代理连接失败或代理返回错误时抛出。
94
+
95
+ Example:
96
+ >>> raise ProxyError("https://api.example.com", "Proxy connection refused")
97
+ """
98
+
99
+ def __init__(
100
+ self,
101
+ url: str,
102
+ reason: str,
103
+ ) -> None:
104
+ super().__init__(
105
+ message=f"Proxy error: {reason}",
106
+ url=url,
107
+ )
108
+ self.code = "proxy_error"
109
+
110
+
111
+ class HttpTimeoutError(HttpError):
112
+ """请求超时异常。
113
+
114
+ 当请求超时时抛出。
115
+
116
+ Example:
117
+ >>> raise HttpTimeoutError("https://api.example.com", "POST", timeout=30.0)
118
+ """
119
+
120
+ def __init__(
121
+ self,
122
+ url: str,
123
+ method: str,
124
+ timeout: Optional[float] = None,
125
+ ) -> None:
126
+ message = f"Request timeout"
127
+ if timeout is not None:
128
+ message += f" after {timeout}s"
129
+ details = {}
130
+ if timeout is not None:
131
+ details["timeout_seconds"] = timeout
132
+ super().__init__(
133
+ message=message,
134
+ url=url,
135
+ method=method,
136
+ details=details,
137
+ )
138
+ self.code = "timeout_error"
139
+ self.status_code = 504
app/exceptions/upstream.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """上游服务异常类。
5
+
6
+ 用于处理上游 API(如 z.ai)返回的错误。
7
+ """
8
+
9
+ from typing import Any, Dict, Optional
10
+
11
+ from app.exceptions.base import AppError
12
+
13
+
14
+ class UpstreamError(AppError):
15
+ """上游服务错误基类。
16
+
17
+ 当上游 API 返回错误时抛出。
18
+
19
+ Attributes:
20
+ upstream_code: 上游返回的错误码
21
+ upstream_status: 上游返回的 HTTP 状态码
22
+
23
+ Example:
24
+ >>> raise UpstreamError("Upstream API error", upstream_code=50001, upstream_status=500)
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ message: str,
30
+ upstream_code: Optional[int] = None,
31
+ upstream_status: Optional[int] = None,
32
+ upstream_type: Optional[str] = None,
33
+ details: Optional[Dict[str, Any]] = None,
34
+ ) -> None:
35
+ final_details = details or {}
36
+ if upstream_code is not None:
37
+ final_details["upstream_code"] = upstream_code
38
+ if upstream_status is not None:
39
+ final_details["upstream_status"] = upstream_status
40
+ if upstream_type is not None:
41
+ final_details["upstream_type"] = upstream_type
42
+
43
+ super().__init__(
44
+ message=message,
45
+ code="upstream_error",
46
+ status_code=502, # Bad Gateway
47
+ details=final_details,
48
+ )
49
+
50
+
51
+ class UpstreamRateLimited(UpstreamError):
52
+ """上游限流异常。
53
+
54
+ 当上游 API 返回 429 状态码时抛出。
55
+
56
+ Example:
57
+ >>> raise UpstreamRateLimited(retry_after=30)
58
+ """
59
+
60
+ def __init__(
61
+ self,
62
+ message: str = "Upstream rate limited",
63
+ retry_after: Optional[int] = None,
64
+ ) -> None:
65
+ details = {}
66
+ if retry_after is not None:
67
+ details["retry_after"] = retry_after
68
+ super().__init__(
69
+ message=message,
70
+ upstream_status=429,
71
+ details=details,
72
+ )
73
+ self.code = "rate_limited"
74
+ self.status_code = 429
75
+
76
+
77
+ class UpstreamTimeout(UpstreamError):
78
+ """上游超时异常。
79
+
80
+ 当上游 API 响应超时时抛出。
81
+
82
+ Example:
83
+ >>> raise UpstreamTimeout(timeout=30.0)
84
+ """
85
+
86
+ def __init__(
87
+ self,
88
+ message: str = "Upstream request timeout",
89
+ timeout: Optional[float] = None,
90
+ ) -> None:
91
+ details = {}
92
+ if timeout is not None:
93
+ details["timeout_seconds"] = timeout
94
+ super().__init__(message=message, details=details)
95
+ self.code = "upstream_timeout"
96
+ self.status_code = 504 # Gateway Timeout
97
+
98
+
99
+ class UpstreamConnectionError(UpstreamError):
100
+ """上游连接失败异常。
101
+
102
+ 当无法连接到上游 API 时抛出。
103
+
104
+ Example:
105
+ >>> raise UpstreamConnectionError("Connection refused")
106
+ """
107
+
108
+ def __init__(
109
+ self,
110
+ message: str = "Failed to connect to upstream",
111
+ reason: Optional[str] = None,
112
+ ) -> None:
113
+ details = {}
114
+ if reason:
115
+ details["reason"] = reason
116
+ super().__init__(message=message, details=details)
117
+ self.code = "upstream_connection_error"
118
+ self.status_code = 503 # Service Unavailable
119
+
120
+
121
+ class UpstreamAuthenticationError(UpstreamError):
122
+ """上游认证失败异常。
123
+
124
+ 当上游 Token 失效或无效时抛出。
125
+
126
+ Example:
127
+ >>> raise UpstreamAuthenticationError("Token expired")
128
+ """
129
+
130
+ def __init__(
131
+ self,
132
+ message: str = "Upstream authentication failed",
133
+ token_hint: Optional[str] = None,
134
+ ) -> None:
135
+ details = {}
136
+ if token_hint:
137
+ details["token_hint"] = token_hint
138
+ super().__init__(
139
+ message=message,
140
+ upstream_status=401,
141
+ details=details,
142
+ )
143
+ self.code = "upstream_auth_error"
144
+ self.status_code = 401
app/models/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ from app.models import schemas
5
+
6
+ __all__ = ["schemas"]
app/models/db_models.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlalchemy import (
2
+ Boolean,
3
+ DateTime,
4
+ Float,
5
+ ForeignKey,
6
+ Index,
7
+ Integer,
8
+ String,
9
+ Text,
10
+ UniqueConstraint,
11
+ )
12
+ from sqlalchemy.orm import DeclarativeBase, mapped_column, relationship
13
+ from sqlalchemy.sql import func, text
14
+
15
+
16
+ class Base(DeclarativeBase):
17
+ pass
18
+
19
+
20
+ class Token(Base):
21
+ __tablename__ = "tokens"
22
+
23
+ id = mapped_column(Integer, primary_key=True, autoincrement=True)
24
+ provider = mapped_column(String, nullable=False)
25
+ token = mapped_column(String, nullable=False)
26
+ token_type = mapped_column(String, default="user", nullable=False)
27
+ priority = mapped_column(Integer, default=0, server_default=text("0"), nullable=False)
28
+ is_enabled = mapped_column(Boolean, default=True, server_default=text("true"), nullable=False)
29
+ created_at = mapped_column(DateTime, default=func.now(), server_default=func.now(), nullable=False)
30
+ last_chat_cleanup = mapped_column(DateTime, nullable=True)
31
+
32
+ __table_args__ = (
33
+ UniqueConstraint("provider", "token", name="uq_provider_token"),
34
+ )
35
+
36
+ stats = relationship("TokenStats", back_populates="token_rel", uselist=False, cascade="all, delete-orphan")
37
+
38
+
39
+ class TokenStats(Base):
40
+ __tablename__ = "token_stats"
41
+
42
+ id = mapped_column(Integer, primary_key=True, autoincrement=True)
43
+ token_id = mapped_column(
44
+ Integer, ForeignKey("tokens.id", ondelete="CASCADE"), nullable=False, unique=True
45
+ )
46
+ total_requests = mapped_column(Integer, default=0, server_default=text("0"), nullable=False)
47
+ successful_requests = mapped_column(Integer, default=0, server_default=text("0"), nullable=False)
48
+ failed_requests = mapped_column(Integer, default=0, server_default=text("0"), nullable=False)
49
+ last_success_time = mapped_column(DateTime, nullable=True)
50
+ last_failure_time = mapped_column(DateTime, nullable=True)
51
+
52
+ token_rel = relationship("Token", back_populates="stats")
53
+
54
+
55
+ class RequestLog(Base):
56
+ __tablename__ = "request_logs"
57
+ __table_args__ = (
58
+ Index("ix_request_logs_timestamp", "timestamp"),
59
+ Index("ix_request_logs_provider_timestamp", "provider", "timestamp"),
60
+ )
61
+
62
+ id = mapped_column(Integer, primary_key=True, autoincrement=True)
63
+ provider = mapped_column(String, nullable=False)
64
+ endpoint = mapped_column(String, nullable=False, default="", server_default=text("''"))
65
+ source = mapped_column(String, nullable=False, default="unknown", server_default=text("'unknown'"))
66
+ protocol = mapped_column(String, nullable=False, default="unknown", server_default=text("'unknown'"))
67
+ client_name = mapped_column(String, nullable=False, default="Unknown", server_default=text("'Unknown'"))
68
+ auth_token = mapped_column(Text, nullable=True)
69
+ upstream_auth_token = mapped_column(Text, nullable=True)
70
+ model = mapped_column(String, nullable=False)
71
+ status_code = mapped_column(Integer, nullable=False, default=200, server_default=text("200"))
72
+ success = mapped_column(Boolean, nullable=False)
73
+ duration = mapped_column(Float, nullable=False, default=0.0, server_default=text("0.0"))
74
+ first_token_time = mapped_column(Float, nullable=False, default=0.0, server_default=text("0.0"))
75
+ input_tokens = mapped_column(Integer, nullable=False, default=0, server_default=text("0"))
76
+ output_tokens = mapped_column(Integer, nullable=False, default=0, server_default=text("0"))
77
+ cache_creation_tokens = mapped_column(Integer, nullable=False, default=0, server_default=text("0"))
78
+ cache_read_tokens = mapped_column(Integer, nullable=False, default=0, server_default=text("0"))
79
+ total_tokens = mapped_column(Integer, nullable=False, default=0, server_default=text("0"))
80
+ error_message = mapped_column(Text, nullable=True)
81
+ timestamp = mapped_column(DateTime, default=func.now(), server_default=func.now(), nullable=False)
82
+
83
+
84
+ class ConfigItem(Base):
85
+ __tablename__ = "config_items"
86
+
87
+ key = mapped_column(String, primary_key=True)
88
+ value = mapped_column(Text, nullable=False)
app/models/schemas.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ from typing import Dict, List, Optional, Any, Union
5
+ from pydantic import BaseModel
6
+
7
+
8
+ class ImageUrl(BaseModel):
9
+ """Image URL model for vision content"""
10
+ url: str
11
+ detail: Optional[str] = None
12
+
13
+ model_config = {"extra": "allow"}
14
+
15
+
16
+ class InputAudio(BaseModel):
17
+ """Input audio payload for multimodal requests."""
18
+
19
+ data: str
20
+ format: str
21
+
22
+ model_config = {"extra": "allow"}
23
+
24
+
25
+ class FilePayload(BaseModel):
26
+ """File payload for chat-compatible requests."""
27
+
28
+ file_id: Optional[str] = None
29
+ file_data: Optional[str] = None
30
+ file_url: Optional[str] = None
31
+ filename: Optional[str] = None
32
+
33
+ model_config = {"extra": "allow"}
34
+
35
+
36
+ class ContentPart(BaseModel):
37
+ """Content part model for OpenAI's new content format"""
38
+
39
+ type: str
40
+ text: Optional[str] = None
41
+ image_url: Optional[ImageUrl] = None
42
+ input_audio: Optional[InputAudio] = None
43
+ file: Optional[FilePayload] = None
44
+ file_id: Optional[str] = None
45
+ file_data: Optional[str] = None
46
+ file_url: Optional[str] = None
47
+ filename: Optional[str] = None
48
+
49
+ model_config = {"extra": "allow"}
50
+
51
+
52
+ class Message(BaseModel):
53
+ """Chat message model"""
54
+
55
+ role: str
56
+ content: Optional[Union[str, List[ContentPart]]] = None
57
+ reasoning_content: Optional[str] = None
58
+ tool_calls: Optional[List[Dict[str, Any]]] = None
59
+ tool_call_id: Optional[str] = None
60
+ name: Optional[str] = None
61
+ is_error: Optional[bool] = None
62
+
63
+
64
+ class OpenAIRequest(BaseModel):
65
+ """OpenAI-compatible request model"""
66
+
67
+ model: str
68
+ messages: List[Message]
69
+ stream: Optional[bool] = False
70
+ temperature: Optional[float] = None
71
+ max_tokens: Optional[int] = None
72
+ tools: Optional[List[Dict[str, Any]]] = None
73
+ tool_choice: Optional[Any] = None
74
+ parallel_tool_calls: Optional[bool] = None
75
+ enable_thinking: Optional[bool] = None
76
+ web_search: Optional[bool] = None
77
+
78
+ # 场景透传字段(客户端可直接指定上游场景配置)
79
+ mcp_servers: Optional[List[str]] = None
80
+ extra: Optional[Dict[str, Any]] = None
81
+ flags: Optional[List[str]] = None
82
+ started_at: Optional[float] = None
83
+
84
+ class Model(BaseModel):
85
+ """Model information for listing"""
86
+
87
+ id: str
88
+ object: str = "model"
89
+ created: int
90
+ owned_by: str
91
+ name: Optional[str] = None
92
+ is_active: Optional[bool] = None
93
+ updated_at: Optional[int] = None
94
+ capabilities: Optional[Dict[str, Any]] = None
95
+ mcpServerIds: Optional[List[str]] = None
96
+ tags: Optional[List[str]] = None
97
+
98
+
99
+ class ModelsResponse(BaseModel):
100
+ """Models list response model"""
101
+
102
+ object: str = "list"
103
+ data: List[Model]
app/services/config_dao.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 配置项数据访问层 (DAO) - SQLAlchemy 版
3
+ 提供配置项的 CRUD 操作
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from typing import Any, Dict, Optional
9
+
10
+ from sqlalchemy import delete, select
11
+ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
12
+
13
+ from app.database import get_db_session as global_async_session
14
+ from app.models.db_models import ConfigItem
15
+ from app.utils.logger import logger
16
+
17
+ _config_dao: Optional["ConfigDAO"] = None
18
+
19
+
20
+ class ConfigDAO:
21
+ """配置项数据访问对象 - SQLAlchemy 版"""
22
+
23
+ def __init__(self, db_path: str = None, db_url: str = None):
24
+ """
25
+ 初始化 DAO。
26
+ 提供 db_path 或 db_url 可以用于测试隔离,默认使用全局 session 工厂。
27
+ """
28
+ if db_url:
29
+ self._engine = create_async_engine(db_url, echo=False)
30
+ self.session_factory = async_sessionmaker(self._engine, expire_on_commit=False, class_=AsyncSession)
31
+ elif db_path:
32
+ url = f"sqlite+aiosqlite:///{db_path}"
33
+ self._engine = create_async_engine(url, echo=False)
34
+ self.session_factory = async_sessionmaker(self._engine, expire_on_commit=False, class_=AsyncSession)
35
+ else:
36
+ self._engine = None
37
+ self.session_factory = global_async_session
38
+
39
+ async def init_database(self) -> None:
40
+ """初始化配置表(为保持接口兼容性保留,实际建表由全局统一处理)"""
41
+ if self._engine:
42
+ from app.models.db_models import Base
43
+ async with self._engine.begin() as conn:
44
+ await conn.run_sync(Base.metadata.create_all)
45
+ logger.debug("✅ 配置表初始化调用完成 (SQLAlchemy)")
46
+
47
+ async def get(self, key: str) -> Optional[str]:
48
+ """读取单个配置值"""
49
+ async with self.session_factory() as session:
50
+ stmt = select(ConfigItem).filter(ConfigItem.key == key)
51
+ result = await session.execute(stmt)
52
+ item = result.scalar_one_or_none()
53
+ return item.value if item else None
54
+
55
+ async def get_all(self) -> Dict[str, str]:
56
+ """读取全部配置"""
57
+ async with self.session_factory() as session:
58
+ stmt = select(ConfigItem)
59
+ result = await session.execute(stmt)
60
+ return {item.key: item.value for item in result.scalars()}
61
+
62
+ async def set(self, key: str, value: str) -> None:
63
+ """写入/更新单条配置(UPSERT)"""
64
+ async with self.session_factory() as session:
65
+ stmt = select(ConfigItem).filter(ConfigItem.key == key)
66
+ result = await session.execute(stmt)
67
+ item = result.scalar_one_or_none()
68
+ if item:
69
+ item.value = value
70
+ else:
71
+ session.add(ConfigItem(key=key, value=value))
72
+ await session.commit()
73
+
74
+ async def set_many(self, items: Dict[str, str]) -> None:
75
+ """批量写入/更新配置"""
76
+ if not items:
77
+ return
78
+ async with self.session_factory() as session:
79
+ keys = list(items.keys())
80
+ stmt = select(ConfigItem).filter(ConfigItem.key.in_(keys))
81
+ result = await session.execute(stmt)
82
+ existing_items = {item.key: item for item in result.scalars()}
83
+
84
+ for key, value in items.items():
85
+ if key in existing_items:
86
+ existing_items[key].value = value
87
+ else:
88
+ session.add(ConfigItem(key=key, value=value))
89
+ await session.commit()
90
+
91
+ async def delete(self, key: str) -> None:
92
+ """删除单条配置"""
93
+ async with self.session_factory() as session:
94
+ stmt = delete(ConfigItem).where(ConfigItem.key == key)
95
+ await session.execute(stmt)
96
+ await session.commit()
97
+
98
+ async def close(self) -> None:
99
+ """关闭数据库连接"""
100
+ if self._engine:
101
+ await self._engine.dispose()
102
+ self._engine = None
103
+
104
+
105
+ def get_config_dao() -> ConfigDAO:
106
+ """获取全局 ConfigDAO 实例"""
107
+ global _config_dao
108
+ if _config_dao is None:
109
+ _config_dao = ConfigDAO()
110
+ return _config_dao
111
+
112
+
113
+ async def init_config_database() -> None:
114
+ """初始化配置数据库"""
115
+ dao = get_config_dao()
116
+ await dao.init_database()
app/services/log_writer.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Async batch log writer.
2
+
3
+ Accepts log entries via an asyncio.Queue and flushes them to the database
4
+ in batches (every ``flush_interval`` seconds or when ``batch_size`` entries
5
+ accumulate), reducing per-request SQLite write-lock contention.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ from typing import List, Optional
12
+
13
+ from app.models.db_models import RequestLog
14
+ from app.utils.logger import logger, log_exception
15
+
16
+
17
+ class AsyncLogWriter:
18
+ """Queue-based batch writer for request logs."""
19
+
20
+ def __init__(
21
+ self,
22
+ *,
23
+ batch_size: int = 50,
24
+ flush_interval: float = 2.0,
25
+ max_queue_size: int = 10000,
26
+ ) -> None:
27
+ self._batch_size = batch_size
28
+ self._flush_interval = flush_interval
29
+ self._queue: asyncio.Queue[RequestLog] = asyncio.Queue(maxsize=max_queue_size)
30
+ self._task: Optional[asyncio.Task] = None
31
+
32
+ # ------------------------------------------------------------------
33
+ # Lifecycle
34
+ # ------------------------------------------------------------------
35
+
36
+ async def start(self) -> None:
37
+ if self._task is not None:
38
+ return
39
+ self._task = asyncio.create_task(self._run(), name="log-writer")
40
+ logger.debug("AsyncLogWriter started")
41
+
42
+ async def stop(self) -> None:
43
+ if self._task is None:
44
+ return
45
+ self._task.cancel()
46
+ try:
47
+ await self._task
48
+ except asyncio.CancelledError:
49
+ pass
50
+ self._task = None
51
+ # Drain remaining entries
52
+ await self._flush_all()
53
+ logger.debug("AsyncLogWriter stopped")
54
+
55
+ # ------------------------------------------------------------------
56
+ # Public API
57
+ # ------------------------------------------------------------------
58
+
59
+ def enqueue(self, log_entry: RequestLog) -> None:
60
+ """Non-blocking enqueue; drops entry on full queue."""
61
+ try:
62
+ self._queue.put_nowait(log_entry)
63
+ except asyncio.QueueFull:
64
+ logger.warning("Log queue full, dropping entry")
65
+
66
+ # ------------------------------------------------------------------
67
+ # Internal
68
+ # ------------------------------------------------------------------
69
+
70
+ async def _run(self) -> None:
71
+ while True:
72
+ try:
73
+ batch = await self._collect_batch()
74
+ if batch:
75
+ await self._write_batch(batch)
76
+ except asyncio.CancelledError:
77
+ raise
78
+ except Exception as exc:
79
+ log_exception(logger, "AsyncLogWriter flush error")
80
+ await asyncio.sleep(1)
81
+
82
+ async def _collect_batch(self) -> List[RequestLog]:
83
+ """Wait for items up to flush_interval or batch_size."""
84
+ batch: List[RequestLog] = []
85
+ try:
86
+ # Block until at least one item arrives
87
+ item = await asyncio.wait_for(
88
+ self._queue.get(), timeout=self._flush_interval
89
+ )
90
+ batch.append(item)
91
+ except asyncio.TimeoutError:
92
+ return batch
93
+
94
+ # Drain up to batch_size without waiting
95
+ while len(batch) < self._batch_size:
96
+ try:
97
+ batch.append(self._queue.get_nowait())
98
+ except asyncio.QueueEmpty:
99
+ break
100
+ return batch
101
+
102
+ async def _flush_all(self) -> None:
103
+ """Drain every remaining item in the queue."""
104
+ batch: List[RequestLog] = []
105
+ while not self._queue.empty():
106
+ try:
107
+ batch.append(self._queue.get_nowait())
108
+ except asyncio.QueueEmpty:
109
+ break
110
+ if batch:
111
+ await self._write_batch(batch)
112
+
113
+ @staticmethod
114
+ async def _write_batch(batch: List[RequestLog]) -> None:
115
+ from app.database import get_db_session
116
+
117
+ try:
118
+ async with get_db_session() as session:
119
+ session.add_all(batch)
120
+ await session.commit()
121
+ except Exception as exc:
122
+ log_exception(logger, "Batch log write failed (%d entries)", len(batch))
123
+
124
+
125
+ # ------------------------------------------------------------------
126
+ # Module-level singleton
127
+ # ------------------------------------------------------------------
128
+
129
+ _log_writer: Optional[AsyncLogWriter] = None
130
+
131
+
132
+ def get_log_writer() -> AsyncLogWriter:
133
+ global _log_writer
134
+ if _log_writer is None:
135
+ _log_writer = AsyncLogWriter()
136
+ return _log_writer
app/services/request_log_dao.py ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 请求日志数据访问层 (DAO) - SQLAlchemy 版
3
+ 提供请求日志的 CRUD 操作和查询功能
4
+ """
5
+ from datetime import datetime, timedelta
6
+ from typing import Dict, List, Optional
7
+
8
+ from sqlalchemy import delete, func, select, text
9
+ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
10
+
11
+ from app.database import get_db_session as global_async_session
12
+ from app.models.db_models import RequestLog
13
+ from app.utils.logger import logger, log_exception
14
+
15
+
16
+
17
+
18
+ def _normalize_trend_window(window: Optional[str], days: Optional[int]) -> str:
19
+ """统一趋势窗口参数,兼容旧版 `days` 调用。"""
20
+ if window:
21
+ normalized = str(window).strip().lower()
22
+ elif days == 30:
23
+ normalized = "30d"
24
+ elif days == 1:
25
+ normalized = "24h"
26
+ else:
27
+ normalized = "7d"
28
+
29
+ if normalized in {"24h", "7d", "30d"}:
30
+ return normalized
31
+ if normalized == "1d":
32
+ return "24h"
33
+ return "7d"
34
+
35
+ class RequestLogDAO:
36
+ def __init__(self, db_path: str = None, db_url: str = None):
37
+ if db_url:
38
+ self._engine = create_async_engine(db_url, echo=False)
39
+ self.session_factory = async_sessionmaker(self._engine, expire_on_commit=False, class_=AsyncSession)
40
+ elif db_path:
41
+ url = f"sqlite+aiosqlite:///{db_path}"
42
+ self._engine = create_async_engine(url, echo=False)
43
+ self.session_factory = async_sessionmaker(self._engine, expire_on_commit=False, class_=AsyncSession)
44
+ else:
45
+ self._engine = None
46
+ self.session_factory = global_async_session
47
+
48
+ async def init_db(self):
49
+ """初始化数据库表"""
50
+ if self._engine:
51
+ from app.models.db_models import Base
52
+ async with self._engine.begin() as conn:
53
+ await conn.run_sync(Base.metadata.create_all)
54
+
55
+ async def add_log(
56
+ self,
57
+ provider: str,
58
+ endpoint: str,
59
+ source: str,
60
+ protocol: str,
61
+ client_name: str,
62
+ auth_token: Optional[str],
63
+ upstream_auth_token: Optional[str],
64
+ model: str,
65
+ status_code: int,
66
+ success: bool,
67
+ duration: float = 0.0,
68
+ first_token_time: float = 0.0,
69
+ input_tokens: int = 0,
70
+ output_tokens: int = 0,
71
+ cache_creation_tokens: int = 0,
72
+ cache_read_tokens: int = 0,
73
+ total_tokens: Optional[int] = None,
74
+ error_message: str = None
75
+ ) -> int:
76
+ if total_tokens is None:
77
+ total_tokens = input_tokens + output_tokens
78
+
79
+ log_item = RequestLog(
80
+ provider=provider,
81
+ endpoint=endpoint,
82
+ source=source,
83
+ protocol=protocol,
84
+ client_name=client_name,
85
+ auth_token=auth_token,
86
+ upstream_auth_token=upstream_auth_token,
87
+ model=model,
88
+ status_code=status_code,
89
+ success=success,
90
+ duration=duration,
91
+ first_token_time=first_token_time,
92
+ input_tokens=input_tokens,
93
+ output_tokens=output_tokens,
94
+ cache_creation_tokens=cache_creation_tokens,
95
+ cache_read_tokens=cache_read_tokens,
96
+ total_tokens=total_tokens,
97
+ error_message=error_message,
98
+ )
99
+ async with self.session_factory() as session:
100
+ session.add(log_item)
101
+ await session.commit()
102
+ return log_item.id
103
+
104
+ def add_log_nowait(
105
+ self,
106
+ provider: str,
107
+ endpoint: str,
108
+ source: str,
109
+ protocol: str,
110
+ client_name: str,
111
+ auth_token: Optional[str],
112
+ upstream_auth_token: Optional[str],
113
+ model: str,
114
+ status_code: int,
115
+ success: bool,
116
+ duration: float = 0.0,
117
+ first_token_time: float = 0.0,
118
+ input_tokens: int = 0,
119
+ output_tokens: int = 0,
120
+ cache_creation_tokens: int = 0,
121
+ cache_read_tokens: int = 0,
122
+ total_tokens: Optional[int] = None,
123
+ error_message: str = None,
124
+ ) -> None:
125
+ """Enqueue a log entry for async batch write (non-blocking)."""
126
+ if total_tokens is None:
127
+ total_tokens = input_tokens + output_tokens
128
+
129
+ log_item = RequestLog(
130
+ provider=provider,
131
+ endpoint=endpoint,
132
+ source=source,
133
+ protocol=protocol,
134
+ client_name=client_name,
135
+ auth_token=auth_token,
136
+ upstream_auth_token=upstream_auth_token,
137
+ model=model,
138
+ status_code=status_code,
139
+ success=success,
140
+ duration=duration,
141
+ first_token_time=first_token_time,
142
+ input_tokens=input_tokens,
143
+ output_tokens=output_tokens,
144
+ cache_creation_tokens=cache_creation_tokens,
145
+ cache_read_tokens=cache_read_tokens,
146
+ total_tokens=total_tokens,
147
+ error_message=error_message,
148
+ )
149
+ from app.services.log_writer import get_log_writer
150
+ get_log_writer().enqueue(log_item)
151
+
152
+ async def get_recent_logs(
153
+ self,
154
+ limit: int = 100,
155
+ offset: int = 0,
156
+ provider: str = None,
157
+ model: str = None,
158
+ success: bool = None,
159
+ source: str = None,
160
+ ) -> List[Dict]:
161
+ stmt = select(RequestLog.__table__)
162
+ if provider:
163
+ stmt = stmt.where(RequestLog.provider == provider)
164
+ if model:
165
+ stmt = stmt.where(RequestLog.model == model)
166
+ if success is not None:
167
+ stmt = stmt.where(RequestLog.success == success)
168
+ if source:
169
+ stmt = stmt.where(RequestLog.source == source)
170
+
171
+ stmt = stmt.order_by(RequestLog.timestamp.desc(), RequestLog.id.desc())
172
+ stmt = stmt.limit(limit).offset(max(0, offset))
173
+
174
+ async with self.session_factory() as session:
175
+ result = await session.execute(stmt)
176
+ return [dict(row._mapping) for row in result.all()]
177
+
178
+ async def count_logs(
179
+ self,
180
+ provider: str = None,
181
+ model: str = None,
182
+ success: bool = None,
183
+ source: str = None,
184
+ ) -> int:
185
+ stmt = select(func.count()).select_from(RequestLog)
186
+ if provider:
187
+ stmt = stmt.where(RequestLog.provider == provider)
188
+ if model:
189
+ stmt = stmt.where(RequestLog.model == model)
190
+ if success is not None:
191
+ stmt = stmt.where(RequestLog.success == success)
192
+ if source:
193
+ stmt = stmt.where(RequestLog.source == source)
194
+
195
+ async with self.session_factory() as session:
196
+ result = await session.execute(stmt)
197
+ return result.scalar() or 0
198
+
199
+ async def get_logs_by_time_range(
200
+ self,
201
+ start_time: datetime,
202
+ end_time: datetime,
203
+ provider: str = None,
204
+ model: str = None,
205
+ limit: int = 10000,
206
+ ) -> List[Dict]:
207
+ stmt = select(RequestLog.__table__).where(
208
+ RequestLog.timestamp.between(start_time, end_time)
209
+ )
210
+ if provider:
211
+ stmt = stmt.where(RequestLog.provider == provider)
212
+ if model:
213
+ stmt = stmt.where(RequestLog.model == model)
214
+
215
+ stmt = stmt.order_by(RequestLog.timestamp.desc(), RequestLog.id.desc()).limit(limit)
216
+
217
+ async with self.session_factory() as session:
218
+ result = await session.execute(stmt)
219
+ return [dict(row._mapping) for row in result.all()]
220
+
221
+ async def get_provider_request_stats(self, provider: Optional[str] = None) -> Dict:
222
+ # Use raw SQL explicitly because of complex aggregations
223
+ from sqlalchemy import text
224
+ query = """
225
+ SELECT
226
+ COUNT(*) as total_requests,
227
+ SUM(CASE WHEN success = true THEN 1 ELSE 0 END) as successful_requests,
228
+ SUM(CASE WHEN success = false THEN 1 ELSE 0 END) as failed_requests,
229
+ SUM(input_tokens) as input_tokens,
230
+ SUM(output_tokens) as output_tokens,
231
+ SUM(total_tokens) as total_tokens,
232
+ SUM(cache_creation_tokens) as cache_creation_tokens,
233
+ SUM(cache_read_tokens) as cache_read_tokens,
234
+ SUM(CASE WHEN cache_creation_tokens > 0 THEN 1 ELSE 0 END) as cache_creation_requests,
235
+ SUM(CASE WHEN cache_read_tokens > 0 THEN 1 ELSE 0 END) as cache_hit_requests,
236
+ AVG(duration) as avg_duration,
237
+ AVG(CASE WHEN first_token_time > 0 THEN first_token_time ELSE NULL END) as avg_first_token_time
238
+ FROM request_logs
239
+ """
240
+ params = {}
241
+ if provider:
242
+ query += " WHERE provider = :provider"
243
+ params["provider"] = provider
244
+
245
+ try:
246
+ async with self.session_factory() as session:
247
+ result = await session.execute(text(query), params)
248
+ row = result.mappings().first()
249
+
250
+ if not row or not row.get("total_requests"):
251
+ return {
252
+ "total_requests": 0, "successful_requests": 0, "failed_requests": 0,
253
+ "input_tokens": 0, "output_tokens": 0, "total_tokens": 0,
254
+ "cache_creation_tokens": 0, "cache_read_tokens": 0,
255
+ "cache_creation_requests": 0, "cache_hit_requests": 0,
256
+ "avg_duration": 0.0, "avg_first_token_time": 0.0,
257
+ }
258
+
259
+ return {
260
+ "total_requests": int(row["total_requests"] or 0),
261
+ "successful_requests": int(row["successful_requests"] or 0),
262
+ "failed_requests": int(row["failed_requests"] or 0),
263
+ "input_tokens": int(row["input_tokens"] or 0),
264
+ "output_tokens": int(row["output_tokens"] or 0),
265
+ "total_tokens": int(row["total_tokens"] or 0),
266
+ "cache_creation_tokens": int(row["cache_creation_tokens"] or 0),
267
+ "cache_read_tokens": int(row["cache_read_tokens"] or 0),
268
+ "cache_creation_requests": int(row["cache_creation_requests"] or 0),
269
+ "cache_hit_requests": int(row["cache_hit_requests"] or 0),
270
+ "avg_duration": float(row["avg_duration"] or 0.0),
271
+ "avg_first_token_time": float(row["avg_first_token_time"] or 0.0),
272
+ }
273
+ except Exception as e:
274
+ log_exception(logger, "❌ 获取请求统计失败")
275
+ return {
276
+ "total_requests": 0, "successful_requests": 0, "failed_requests": 0,
277
+ "input_tokens": 0, "output_tokens": 0, "total_tokens": 0,
278
+ "cache_creation_tokens": 0, "cache_read_tokens": 0,
279
+ "cache_creation_requests": 0, "cache_hit_requests": 0,
280
+ "avg_duration": 0.0, "avg_first_token_time": 0.0,
281
+ }
282
+
283
+ async def get_provider_usage_trend(
284
+ self,
285
+ provider: Optional[str] = None,
286
+ days: Optional[int] = None,
287
+ *,
288
+ window: Optional[str] = None,
289
+ now: Optional[datetime] = None,
290
+ ) -> List[Dict]:
291
+ trend_window = _normalize_trend_window(window, days)
292
+ current_time = now or datetime.utcnow()
293
+ async with self.session_factory() as session:
294
+ is_pg = self._is_postgres(session)
295
+
296
+ if trend_window == "24h":
297
+ bucket_count = 24
298
+ current_hour = current_time.replace(minute=0, second=0, microsecond=0)
299
+ start_time = current_hour - timedelta(hours=bucket_count - 1)
300
+ bucket_expression = self._hourly_bucket_expr(is_pg)
301
+
302
+ row_key = "trend_bucket"
303
+ label_format = "%H:%M"
304
+ tooltip_format = "%Y-%m-%d %H:00"
305
+ rows = await self._query_usage_trend_rows(session, provider, start_time, bucket_expression, row_key)
306
+
307
+ rows_by_bucket = {str(row[row_key]): dict(row) for row in rows}
308
+ trend = []
309
+ for offset in range(bucket_count):
310
+ bucket_time = start_time + timedelta(hours=offset)
311
+ bucket_key = bucket_time.strftime("%Y-%m-%d %H:00:00")
312
+ trend.append(self._build_usage_trend_point(
313
+ row=rows_by_bucket.get(bucket_key, {}),
314
+ bucket=bucket_key,
315
+ label=bucket_time.strftime(label_format),
316
+ tooltip_label=bucket_time.strftime(tooltip_format),
317
+ ))
318
+ return trend
319
+
320
+ bucket_count = 30 if trend_window == "30d" else 7
321
+ start_date = current_time.date() - timedelta(days=bucket_count - 1)
322
+ start_time = datetime.combine(start_date, datetime.min.time())
323
+
324
+ bucket_expression = "DATE(timestamp)"
325
+
326
+ rows = await self._query_usage_trend_rows(session, provider, start_time, bucket_expression, "trend_bucket")
327
+ rows_by_bucket = {str(row["trend_bucket"])[:10]: dict(row) for row in rows}
328
+ trend = []
329
+
330
+ for offset in range(bucket_count):
331
+ bucket_date = start_date + timedelta(days=offset)
332
+ bucket_key = bucket_date.isoformat()
333
+ trend.append(self._build_usage_trend_point(
334
+ row=rows_by_bucket.get(bucket_key, {}),
335
+ bucket=bucket_key,
336
+ label=bucket_date.strftime("%m-%d"),
337
+ tooltip_label=bucket_date.strftime("%Y-%m-%d"),
338
+ ))
339
+ return trend
340
+
341
+ @staticmethod
342
+ def _is_postgres(session) -> bool:
343
+ return session.bind.dialect.name == "postgresql" if session.bind else False
344
+
345
+ @staticmethod
346
+ def _hourly_bucket_expr(is_postgres: bool) -> str:
347
+ if is_postgres:
348
+ return "to_char(timestamp, 'YYYY-MM-DD HH24:00:00')"
349
+ return "strftime('%Y-%m-%d %H:00:00', timestamp)"
350
+
351
+ async def _query_usage_trend_rows(self, session, provider: Optional[str], start_time: datetime, bucket_expression: str, bucket_alias: str):
352
+ query = f"""
353
+ SELECT
354
+ {bucket_expression} as {bucket_alias},
355
+ COUNT(*) as total_requests,
356
+ SUM(CASE WHEN success = true THEN 1 ELSE 0 END) as successful_requests,
357
+ SUM(input_tokens) as input_tokens,
358
+ SUM(output_tokens) as output_tokens,
359
+ SUM(total_tokens) as total_tokens,
360
+ SUM(cache_creation_tokens) as cache_creation_tokens,
361
+ SUM(cache_read_tokens) as cache_read_tokens
362
+ FROM request_logs
363
+ WHERE timestamp >= :start_time
364
+ """
365
+ params = {"start_time": start_time}
366
+ if provider:
367
+ query += " AND provider = :provider"
368
+ params["provider"] = provider
369
+
370
+ query += f" GROUP BY {bucket_expression} ORDER BY {bucket_alias} ASC"
371
+
372
+ result = await session.execute(text(query), params)
373
+ return result.mappings().all()
374
+
375
+ def _build_usage_trend_point(self, *, row: Dict, bucket: str, label: str, tooltip_label: str) -> Dict:
376
+ total_requests = int(row.get("total_requests") or 0)
377
+ successful_requests = int(row.get("successful_requests") or 0)
378
+ cache_creation_tokens = int(row.get("cache_creation_tokens") or 0)
379
+ cache_read_tokens = int(row.get("cache_read_tokens") or 0)
380
+ return {
381
+ "bucket": bucket,
382
+ "label": label,
383
+ "tooltip_label": tooltip_label,
384
+ "total_requests": total_requests,
385
+ "successful_requests": successful_requests,
386
+ "failed_requests": max(0, total_requests - successful_requests),
387
+ "input_tokens": int(row.get("input_tokens") or 0),
388
+ "output_tokens": int(row.get("output_tokens") or 0),
389
+ "total_tokens": int(row.get("total_tokens") or 0),
390
+ "cache_creation_tokens": cache_creation_tokens,
391
+ "cache_read_tokens": cache_read_tokens,
392
+ "cache_total_tokens": cache_creation_tokens + cache_read_tokens,
393
+ "success_rate": round((successful_requests / total_requests * 100) if total_requests > 0 else 0, 1),
394
+ }
395
+
396
+ async def get_model_stats_from_db(self, hours: int = 24) -> Dict:
397
+ start_time = datetime.utcnow() - timedelta(hours=hours)
398
+ query = """
399
+ SELECT
400
+ model,
401
+ COUNT(*) as total,
402
+ SUM(CASE WHEN success = true THEN 1 ELSE 0 END) as success,
403
+ SUM(CASE WHEN success = false THEN 1 ELSE 0 END) as failed,
404
+ SUM(input_tokens) as input_tokens,
405
+ SUM(output_tokens) as output_tokens,
406
+ SUM(total_tokens) as total_tokens,
407
+ AVG(duration) as avg_duration,
408
+ AVG(CASE WHEN first_token_time > 0 THEN first_token_time ELSE NULL END) as avg_first_token_time
409
+ FROM request_logs
410
+ WHERE timestamp >= :start_time
411
+ GROUP BY model
412
+ ORDER BY total DESC
413
+ """
414
+ async with self.session_factory() as session:
415
+ result = await session.execute(text(query), {"start_time": start_time})
416
+ rows = result.mappings().all()
417
+
418
+ out = {}
419
+ for row in rows:
420
+ model = row['model']
421
+ out[model] = {
422
+ 'total': row['total'],
423
+ 'success': row['success'],
424
+ 'failed': row['failed'],
425
+ 'input_tokens': row['input_tokens'] or 0,
426
+ 'output_tokens': row['output_tokens'] or 0,
427
+ 'total_tokens': row['total_tokens'] or 0,
428
+ 'avg_duration': round(row['avg_duration'] or 0, 2),
429
+ 'avg_first_token_time': round(row['avg_first_token_time'] or 0, 2),
430
+ 'success_rate': round((row['success'] / row['total'] * 100) if row['total'] > 0 else 0, 1),
431
+ }
432
+ return out
433
+
434
+ async def delete_old_logs(self, days: int = 30) -> int:
435
+ cutoff_time = datetime.utcnow() - timedelta(days=days)
436
+ async with self.session_factory() as session:
437
+ stmt = delete(RequestLog).where(RequestLog.timestamp < cutoff_time)
438
+ result = await session.execute(stmt)
439
+ await session.commit()
440
+ return result.rowcount
441
+
442
+ async def close(self) -> None:
443
+ if self._engine:
444
+ await self._engine.dispose()
445
+ self._engine = None
446
+
447
+ _request_log_dao: Optional[RequestLogDAO] = None
448
+
449
+ def get_request_log_dao() -> RequestLogDAO:
450
+ global _request_log_dao
451
+ if _request_log_dao is None:
452
+ _request_log_dao = RequestLogDAO()
453
+ return _request_log_dao
454
+
455
+ def init_request_log_dao():
456
+ dao = get_request_log_dao()
457
+ return dao
app/services/token_automation.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Background automation for token import and maintenance."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from dataclasses import dataclass
7
+ from typing import Optional
8
+
9
+ from app.core.config import settings
10
+ from app.services.request_log_dao import get_request_log_dao
11
+ from app.services.token_dao import TokenDAO, get_token_dao
12
+ from app.services.token_importer import TokenImportSummary, import_tokens_from_directory
13
+ from app.utils.logger import logger, log_exception
14
+ from app.utils.token_pool import TokenPool, get_token_pool
15
+
16
+ DEFAULT_TOKEN_PROVIDER = "zai"
17
+ _AUTO_IMPORT_LOCK = asyncio.Lock()
18
+ _AUTO_MAINTENANCE_LOCK = asyncio.Lock()
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class TokenMaintenanceSummary:
23
+ provider: str
24
+ checked_count: int = 0
25
+ duplicate_removed_count: int = 0
26
+ valid_count: int = 0
27
+ guest_count: int = 0
28
+ invalid_count: int = 0
29
+ deleted_invalid_count: int = 0
30
+
31
+
32
+ async def run_directory_import(
33
+ source_dir: str,
34
+ *,
35
+ provider: str = DEFAULT_TOKEN_PROVIDER,
36
+ validate: bool = True,
37
+ dao: Optional[TokenDAO] = None,
38
+ pool: Optional[TokenPool] = None,
39
+ ) -> TokenImportSummary:
40
+ """Import tokens from a configured directory and refresh the pool if needed."""
41
+ if _AUTO_IMPORT_LOCK.locked():
42
+ raise RuntimeError("目录导入任务正在执行,请稍后再试")
43
+
44
+ async with _AUTO_IMPORT_LOCK:
45
+ summary = await import_tokens_from_directory(
46
+ source_dir,
47
+ provider=provider,
48
+ validate=validate,
49
+ dao=dao,
50
+ )
51
+
52
+ active_pool = pool if pool is not None else get_token_pool()
53
+ if active_pool and summary.imported_count > 0:
54
+ await active_pool.sync_from_database(provider)
55
+ logger.info("✅ 目录导入后已同步 Token 池")
56
+
57
+ return summary
58
+
59
+
60
+ async def run_token_maintenance(
61
+ *,
62
+ provider: str = DEFAULT_TOKEN_PROVIDER,
63
+ remove_duplicates: bool = True,
64
+ run_health_check: bool = True,
65
+ delete_invalid_tokens: bool = False,
66
+ dao: Optional[TokenDAO] = None,
67
+ pool: Optional[TokenPool] = None,
68
+ ) -> TokenMaintenanceSummary:
69
+ """Run dedupe, validation, and invalid-token cleanup as one maintenance cycle."""
70
+ if _AUTO_MAINTENANCE_LOCK.locked():
71
+ raise RuntimeError("Token 自动维护任务正在执行,请稍后再试")
72
+
73
+ token_dao = dao or get_token_dao()
74
+ duplicate_removed_count = 0
75
+ checked_count = 0
76
+ valid_count = 0
77
+ guest_count = 0
78
+ invalid_count = 0
79
+ deleted_invalid_count = 0
80
+
81
+ async with _AUTO_MAINTENANCE_LOCK:
82
+ if remove_duplicates:
83
+ duplicate_removed_count = await token_dao.remove_duplicate_tokens(provider)
84
+
85
+ should_validate = run_health_check or delete_invalid_tokens
86
+ invalid_token_ids: list[int] = []
87
+
88
+ if should_validate:
89
+ validation_result = await token_dao.validate_tokens_detailed(provider)
90
+ checked_count = int(validation_result.get("checked", 0) or 0)
91
+ valid_count = int(validation_result.get("valid", 0) or 0)
92
+ guest_count = int(validation_result.get("guest", 0) or 0)
93
+ invalid_count = int(validation_result.get("invalid", 0) or 0)
94
+ invalid_token_ids = list(
95
+ validation_result.get("invalid_token_ids", []) or []
96
+ )
97
+
98
+ if delete_invalid_tokens and invalid_token_ids:
99
+ deleted_invalid_count = await token_dao.delete_tokens_by_ids(
100
+ invalid_token_ids
101
+ )
102
+
103
+ active_pool = pool if pool is not None else get_token_pool()
104
+ if active_pool:
105
+ await active_pool.sync_from_database(provider)
106
+ logger.info("✅ Token 维护后已同步 Token 池")
107
+
108
+ return TokenMaintenanceSummary(
109
+ provider=provider,
110
+ checked_count=checked_count,
111
+ duplicate_removed_count=duplicate_removed_count,
112
+ valid_count=valid_count,
113
+ guest_count=guest_count,
114
+ invalid_count=invalid_count,
115
+ deleted_invalid_count=deleted_invalid_count,
116
+ )
117
+
118
+
119
+ class TokenAutomationScheduler:
120
+ """Run token import and maintenance loops in the application background."""
121
+
122
+ def __init__(self) -> None:
123
+ self._stop_event = asyncio.Event()
124
+ self._tasks: list[asyncio.Task] = []
125
+ self._import_warning: Optional[str] = None
126
+ self._maintenance_warning: Optional[str] = None
127
+
128
+ async def start(self) -> None:
129
+ if self._tasks:
130
+ return
131
+
132
+ self._stop_event.clear()
133
+ self._tasks = [
134
+ asyncio.create_task(
135
+ self._auto_import_loop(),
136
+ name="token-auto-import",
137
+ ),
138
+ asyncio.create_task(
139
+ self._auto_maintenance_loop(),
140
+ name="token-auto-maintenance",
141
+ ),
142
+ asyncio.create_task(
143
+ self._auto_chat_cleanup_loop(),
144
+ name="token-auto-chat-cleanup",
145
+ ),
146
+ asyncio.create_task(
147
+ self._auto_log_cleanup_loop(),
148
+ name="token-auto-log-cleanup",
149
+ ),
150
+ ]
151
+ logger.info("✅ Token 自动任务调度器已启动")
152
+
153
+ async def stop(self) -> None:
154
+ if not self._tasks:
155
+ return
156
+
157
+ self._stop_event.set()
158
+ for task in self._tasks:
159
+ task.cancel()
160
+
161
+ await asyncio.gather(*self._tasks, return_exceptions=True)
162
+ self._tasks.clear()
163
+ self._import_warning = None
164
+ self._maintenance_warning = None
165
+ logger.info("🛑 Token 自动任务调度器已停止")
166
+
167
+ async def _auto_import_loop(self) -> None:
168
+ while not self._stop_event.is_set():
169
+ wait_seconds = 15
170
+ try:
171
+ if settings.TOKEN_AUTO_IMPORT_ENABLED:
172
+ wait_seconds = max(int(settings.TOKEN_AUTO_IMPORT_INTERVAL), 30)
173
+ source_dir = settings.TOKEN_AUTO_IMPORT_SOURCE_DIR.strip()
174
+ if not source_dir:
175
+ self._log_import_warning_once(
176
+ "已启用自动导入,但未配置导入目录"
177
+ )
178
+ else:
179
+ self._import_warning = None
180
+ summary = await run_directory_import(
181
+ source_dir,
182
+ provider=DEFAULT_TOKEN_PROVIDER,
183
+ )
184
+ logger.debug(
185
+ "自动导入完成: scanned=%s imported=%s duplicate=%s invalid=%s",
186
+ summary.scanned_files,
187
+ summary.imported_count,
188
+ summary.duplicate_count,
189
+ summary.invalid_json_count + summary.invalid_token_count,
190
+ )
191
+ except asyncio.CancelledError:
192
+ raise
193
+ except RuntimeError as exc:
194
+ logger.debug("跳过本轮自动导入: %s", exc)
195
+ except (FileNotFoundError, NotADirectoryError) as exc:
196
+ self._log_import_warning_once(str(exc))
197
+ except Exception as exc:
198
+ log_exception(logger, "❌ 自动导入 Token 失败")
199
+
200
+ await self._wait_or_stop(wait_seconds)
201
+
202
+ async def _auto_maintenance_loop(self) -> None:
203
+ while not self._stop_event.is_set():
204
+ wait_seconds = 15
205
+ try:
206
+ if settings.TOKEN_AUTO_MAINTENANCE_ENABLED:
207
+ wait_seconds = max(
208
+ int(settings.TOKEN_AUTO_MAINTENANCE_INTERVAL),
209
+ 30,
210
+ )
211
+ logger.debug(
212
+ "[token.auto_maintenance] cycle enabled=%s interval=%s remove_duplicates=%s health_check=%s delete_invalid=%s",
213
+ settings.TOKEN_AUTO_MAINTENANCE_ENABLED,
214
+ wait_seconds,
215
+ settings.TOKEN_AUTO_REMOVE_DUPLICATES,
216
+ settings.TOKEN_AUTO_HEALTH_CHECK,
217
+ settings.TOKEN_AUTO_DELETE_INVALID,
218
+ )
219
+ if not self._has_enabled_maintenance_action():
220
+ self._log_maintenance_warning_once(
221
+ "已启用自动维护,但未选择任何维护动作"
222
+ )
223
+ else:
224
+ self._maintenance_warning = None
225
+ summary = await run_token_maintenance(
226
+ provider=DEFAULT_TOKEN_PROVIDER,
227
+ remove_duplicates=settings.TOKEN_AUTO_REMOVE_DUPLICATES,
228
+ run_health_check=settings.TOKEN_AUTO_HEALTH_CHECK,
229
+ delete_invalid_tokens=settings.TOKEN_AUTO_DELETE_INVALID,
230
+ )
231
+ logger.debug(
232
+ "自动维护完成: dedupe=%s checked=%s valid=%s guest=%s invalid=%s deleted=%s",
233
+ summary.duplicate_removed_count,
234
+ summary.checked_count,
235
+ summary.valid_count,
236
+ summary.guest_count,
237
+ summary.invalid_count,
238
+ summary.deleted_invalid_count,
239
+ )
240
+ except asyncio.CancelledError:
241
+ raise
242
+ except RuntimeError as exc:
243
+ logger.debug("跳过本轮自动维护: %s", exc)
244
+ except Exception as exc:
245
+ log_exception(logger, "❌ Token 自动维护失败")
246
+
247
+ await self._wait_or_stop(wait_seconds)
248
+
249
+ async def _auto_chat_cleanup_loop(self) -> None:
250
+ while not self._stop_event.is_set():
251
+ wait_seconds = 86400 # 默认一天执行一次
252
+
253
+ try:
254
+ if getattr(settings, "CHAT_CLEANUP_ENABLED", True):
255
+ from app.core.chat_cleanup import run_chat_cleanup
256
+ interval_days = getattr(settings, "CHAT_CLEANUP_INTERVAL_DAYS", 7)
257
+ logger.debug(
258
+ "[token.auto_chat_cleanup] cycle enabled=%s interval_days=%s",
259
+ getattr(settings, "CHAT_CLEANUP_ENABLED", True),
260
+ interval_days,
261
+ )
262
+
263
+ summary = await run_chat_cleanup(interval_days=interval_days)
264
+ if summary.total_checked > 0:
265
+ logger.debug(
266
+ "定期会话清理完成: checked=%s success=%s failed=%s",
267
+ summary.total_checked,
268
+ summary.success_count,
269
+ summary.failed_count,
270
+ )
271
+ except asyncio.CancelledError:
272
+ raise
273
+ except Exception as exc:
274
+ log_exception(logger, "❌ 定期会话清理失败")
275
+ wait_seconds = 3600 # 执行出错的话,过 1 小时再重试
276
+
277
+ await self._wait_or_stop(wait_seconds)
278
+
279
+ async def _auto_log_cleanup_loop(self) -> None:
280
+ while not self._stop_event.is_set():
281
+ wait_seconds = 86400 # 默认一天执行一次
282
+
283
+ try:
284
+ interval_days = max(
285
+ int(getattr(settings, "LOG_CLEANUP_INTERVAL_DAYS", 1)),
286
+ 1,
287
+ )
288
+ retention_days = max(
289
+ int(getattr(settings, "LOG_RETENTION_DAYS", 30)),
290
+ 1,
291
+ )
292
+ wait_seconds = interval_days * 86400
293
+
294
+ request_log_dao = get_request_log_dao()
295
+ deleted_count = await request_log_dao.delete_old_logs(
296
+ days=retention_days
297
+ )
298
+ logger.debug(
299
+ "定期请求日志清理完成: retention_days=%s deleted=%s",
300
+ retention_days,
301
+ deleted_count,
302
+ )
303
+ except asyncio.CancelledError:
304
+ raise
305
+ except Exception as exc:
306
+ log_exception(logger, "❌ 定期请求日志清理失败")
307
+ wait_seconds = 3600 # 执行出错的话,过 1 小时再重试
308
+
309
+ await self._wait_or_stop(wait_seconds)
310
+
311
+ async def _wait_or_stop(self, timeout: int) -> None:
312
+ try:
313
+ await asyncio.wait_for(self._stop_event.wait(), timeout=timeout)
314
+ except asyncio.TimeoutError:
315
+ return
316
+
317
+ def _has_enabled_maintenance_action(self) -> bool:
318
+ return any(
319
+ (
320
+ settings.TOKEN_AUTO_REMOVE_DUPLICATES,
321
+ settings.TOKEN_AUTO_HEALTH_CHECK,
322
+ settings.TOKEN_AUTO_DELETE_INVALID,
323
+ )
324
+ )
325
+
326
+ def _log_import_warning_once(self, message: str) -> None:
327
+ if self._import_warning == message:
328
+ return
329
+ self._import_warning = message
330
+ logger.warning(f"⚠️ {message}")
331
+
332
+ def _log_maintenance_warning_once(self, message: str) -> None:
333
+ if self._maintenance_warning == message:
334
+ return
335
+ self._maintenance_warning = message
336
+ logger.warning(f"⚠️ {message}")
337
+
338
+
339
+ _scheduler: Optional[TokenAutomationScheduler] = None
340
+
341
+
342
+ def get_token_automation_scheduler() -> TokenAutomationScheduler:
343
+ global _scheduler
344
+ if _scheduler is None:
345
+ _scheduler = TokenAutomationScheduler()
346
+ return _scheduler
347
+
348
+
349
+ async def start_token_automation_scheduler() -> None:
350
+ await get_token_automation_scheduler().start()
351
+
352
+
353
+ async def stop_token_automation_scheduler() -> None:
354
+ global _scheduler
355
+ if _scheduler is None:
356
+ return
357
+ await _scheduler.stop()
app/services/token_dao.py ADDED
@@ -0,0 +1,620 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Token 数据访问层 (DAO) - SQLAlchemy 版
3
+ 提供 Token 的 CRUD 操作和查询功能
4
+ """
5
+ import os
6
+ import time
7
+ from typing import Any, Dict, List, Optional, Tuple
8
+
9
+ from sqlalchemy import delete, func, select, update
10
+ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
11
+
12
+ from app.database import get_db_session as global_async_session
13
+ from app.models.db_models import Token, TokenStats
14
+ from app.utils.logger import logger, log_exception
15
+
16
+
17
+ class TokenDAO:
18
+ """Token 数据访问对象"""
19
+
20
+ def __init__(self, db_path: str = None, db_url: str = None):
21
+ """初始化 DAO"""
22
+ if db_url:
23
+ self._engine = create_async_engine(db_url, echo=False)
24
+ self.session_factory = async_sessionmaker(self._engine, expire_on_commit=False, class_=AsyncSession)
25
+ elif db_path:
26
+ url = f"sqlite+aiosqlite:///{db_path}"
27
+ self._engine = create_async_engine(url, echo=False)
28
+ self.session_factory = async_sessionmaker(self._engine, expire_on_commit=False, class_=AsyncSession)
29
+ else:
30
+ self._engine = None
31
+ self.session_factory = global_async_session
32
+
33
+ async def init_database(self):
34
+ """初始化数据库表结构"""
35
+ if self._engine:
36
+ from app.models.db_models import Base
37
+ async with self._engine.begin() as conn:
38
+ await conn.run_sync(Base.metadata.create_all)
39
+ logger.debug("Token 数据库初始化调用完成 (SQLAlchemy)")
40
+
41
+ # ==================== Token CRUD 操作 ====================
42
+
43
+ async def add_token(
44
+ self,
45
+ provider: str,
46
+ token: str,
47
+ token_type: str = "user",
48
+ priority: int = 0,
49
+ validate: bool = True
50
+ ) -> Optional[int]:
51
+ try:
52
+ # 对于 zai 提供商,强制验证 Token
53
+ if provider == "zai" and validate:
54
+ from app.utils.token_pool import ZAITokenValidator
55
+
56
+ validated_type, is_valid, error_msg = await ZAITokenValidator.validate_token(token)
57
+
58
+ # 拒绝 guest token
59
+ if validated_type == "guest":
60
+ logger.warning("拒绝添加匿名用户 Token: %s... - %s", token[:20], error_msg)
61
+ return None
62
+
63
+ # 拒绝无效 token
64
+ if not is_valid:
65
+ logger.warning("Token 验证失败: %s... - %s", token[:20], error_msg)
66
+ return None
67
+
68
+ # 使用验证后的类型
69
+ token_type = validated_type
70
+
71
+ async with self.session_factory() as session:
72
+ # 检查是否存在
73
+ stmt = select(Token).filter_by(provider=provider, token=token)
74
+ existing = (await session.execute(stmt)).scalar_one_or_none()
75
+ if existing:
76
+ logger.debug("Token 已存在: %s - %s...", provider, token[:20])
77
+ return None
78
+
79
+ new_token = Token(
80
+ provider=provider,
81
+ token=token,
82
+ token_type=token_type,
83
+ priority=priority,
84
+ )
85
+ session.add(new_token)
86
+ await session.flush() # 获得 ID
87
+
88
+ # 同时创建统计记录
89
+ new_stats = TokenStats(token_id=new_token.id)
90
+ session.add(new_stats)
91
+ await session.commit()
92
+
93
+ logger.debug("添加 Token: %s (%s) - %s...", provider, token_type, token[:20])
94
+ return new_token.id
95
+ except Exception as e:
96
+ log_exception(logger, "❌ 添加 Token 失败")
97
+ return None
98
+
99
+ def _format_token_row(self, token_item: Token) -> Dict:
100
+ """Helper to format Token with related stats"""
101
+ d = {
102
+ "id": token_item.id,
103
+ "provider": token_item.provider,
104
+ "token": token_item.token,
105
+ "token_type": token_item.token_type,
106
+ "priority": token_item.priority,
107
+ "is_enabled": 1 if token_item.is_enabled else 0,
108
+ "created_at": str(token_item.created_at) if token_item.created_at else None,
109
+ "total_requests": getattr(token_item.stats, "total_requests", 0) if token_item.stats else 0,
110
+ "successful_requests": getattr(token_item.stats, "successful_requests", 0) if token_item.stats else 0,
111
+ "failed_requests": getattr(token_item.stats, "failed_requests", 0) if token_item.stats else 0,
112
+ "last_success_time": str(token_item.stats.last_success_time) if token_item.stats and token_item.stats.last_success_time else None,
113
+ "last_failure_time": str(token_item.stats.last_failure_time) if token_item.stats and token_item.stats.last_failure_time else None,
114
+ "last_chat_cleanup": str(token_item.last_chat_cleanup) if token_item.last_chat_cleanup else None,
115
+ }
116
+ return d
117
+
118
+ async def get_tokens_by_provider(
119
+ self,
120
+ provider: str,
121
+ enabled_only: bool = True,
122
+ limit: Optional[int] = None,
123
+ offset: int = 0,
124
+ ) -> List[Dict]:
125
+ try:
126
+ from sqlalchemy.orm import selectinload
127
+ async with self.session_factory() as session:
128
+ stmt = select(Token).options(selectinload(Token.stats)).filter_by(provider=provider)
129
+ if enabled_only:
130
+ stmt = stmt.filter_by(is_enabled=True)
131
+
132
+ stmt = stmt.order_by(Token.priority.desc(), Token.id.asc())
133
+ if limit is not None:
134
+ stmt = stmt.limit(limit).offset(max(0, offset))
135
+
136
+ result = await session.execute(stmt)
137
+ return [self._format_token_row(t) for t in result.scalars()]
138
+ except Exception as e:
139
+ log_exception(logger, "❌ 查询 Token 失败")
140
+ return []
141
+
142
+ async def get_tokens_needing_chat_cleanup(self, provider: str, interval_days: int) -> List[Dict]:
143
+ try:
144
+ from sqlalchemy.orm import selectinload
145
+ from datetime import timedelta, datetime, timezone
146
+
147
+ async with self.session_factory() as session:
148
+ threshold_time = datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(days=interval_days)
149
+
150
+ stmt = select(Token).options(selectinload(Token.stats)).filter_by(provider=provider, is_enabled=True)
151
+ stmt = stmt.filter(
152
+ (Token.last_chat_cleanup == None) | (Token.last_chat_cleanup <= threshold_time)
153
+ )
154
+
155
+ stmt = stmt.order_by(Token.priority.desc(), Token.id.asc())
156
+ result = await session.execute(stmt)
157
+ return [self._format_token_row(t) for t in result.scalars()]
158
+ except Exception as e:
159
+ log_exception(logger, "❌ 查询需要清理会话的 Token 失败")
160
+ return []
161
+
162
+ async def get_all_tokens(self, enabled_only: bool = False) -> List[Dict]:
163
+ try:
164
+ from sqlalchemy.orm import selectinload
165
+ async with self.session_factory() as session:
166
+ stmt = select(Token).options(selectinload(Token.stats))
167
+ if enabled_only:
168
+ stmt = stmt.filter_by(is_enabled=True)
169
+
170
+ stmt = stmt.order_by(Token.provider, Token.priority.desc(), Token.id.asc())
171
+ result = await session.execute(stmt)
172
+ return [self._format_token_row(t) for t in result.scalars()]
173
+ except Exception as e:
174
+ log_exception(logger, "❌ 查询所有 Token 失败")
175
+ return []
176
+
177
+ async def update_token_status(self, token_id: int, is_enabled: bool):
178
+ try:
179
+ async with self.session_factory() as session:
180
+ stmt = update(Token).where(Token.id == token_id).values(is_enabled=is_enabled)
181
+ await session.execute(stmt)
182
+ await session.commit()
183
+ except Exception as e:
184
+ log_exception(logger, "❌ 更新 Token 状态失败")
185
+
186
+ async def update_last_chat_cleanup(self, token_id: int):
187
+ try:
188
+ from datetime import datetime, timezone
189
+ async with self.session_factory() as session:
190
+ now = datetime.now(timezone.utc).replace(tzinfo=None)
191
+ stmt = update(Token).where(Token.id == token_id).values(last_chat_cleanup=now)
192
+ await session.execute(stmt)
193
+ await session.commit()
194
+ logger.debug("更新 Token 会话清理时间: id=%s", token_id)
195
+ except Exception as e:
196
+ log_exception(logger, "❌ 更新 Token 会话清理时间失败")
197
+
198
+ async def update_token_type(self, token_id: int, token_type: str):
199
+ try:
200
+ async with self.session_factory() as session:
201
+ stmt = update(Token).where(Token.id == token_id).values(token_type=token_type)
202
+ await session.execute(stmt)
203
+ await session.commit()
204
+ except Exception as e:
205
+ log_exception(logger, "❌ 更新 Token 类型失败")
206
+
207
+ async def delete_token(self, token_id: int):
208
+ try:
209
+ async with self.session_factory() as session:
210
+ stmt = delete(Token).where(Token.id == token_id)
211
+ await session.execute(stmt)
212
+ await session.commit()
213
+ except Exception as e:
214
+ log_exception(logger, "❌ 删除 Token 失败")
215
+
216
+ async def delete_tokens_by_ids(self, token_ids: List[int]) -> int:
217
+ if not token_ids:
218
+ return 0
219
+ try:
220
+ async with self.session_factory() as session:
221
+ stmt = delete(Token).where(Token.id.in_(token_ids))
222
+ result = await session.execute(stmt)
223
+ await session.commit()
224
+ deleted_count = result.rowcount
225
+ logger.info(f"✅ 批量删除 Token: {deleted_count} 个")
226
+ return deleted_count
227
+ except Exception as e:
228
+ log_exception(logger, "❌ 批量删除 Token 失败")
229
+ return 0
230
+
231
+ async def delete_tokens_by_provider(self, provider: str):
232
+ try:
233
+ async with self.session_factory() as session:
234
+ stmt = delete(Token).where(Token.provider == provider)
235
+ await session.execute(stmt)
236
+ await session.commit()
237
+ logger.info(f"✅ 删除提供商所有 Token: {provider}")
238
+ except Exception as e:
239
+ log_exception(logger, "❌ 删除提供商 Token 失败")
240
+
241
+ # ==================== Token 统计操作 ====================
242
+
243
+ async def record_success(self, token_id: int):
244
+ try:
245
+ async with self.session_factory() as session:
246
+ stmt = update(TokenStats).where(TokenStats.token_id == token_id).values(
247
+ total_requests=TokenStats.total_requests + 1,
248
+ successful_requests=TokenStats.successful_requests + 1,
249
+ last_success_time=func.now()
250
+ )
251
+ await session.execute(stmt)
252
+ await session.commit()
253
+ except Exception as e:
254
+ log_exception(logger, "❌ 记录成功失败")
255
+
256
+ async def record_failure(self, token_id: int):
257
+ try:
258
+ async with self.session_factory() as session:
259
+ stmt = update(TokenStats).where(TokenStats.token_id == token_id).values(
260
+ total_requests=TokenStats.total_requests + 1,
261
+ failed_requests=TokenStats.failed_requests + 1,
262
+ last_failure_time=func.now()
263
+ )
264
+ await session.execute(stmt)
265
+ await session.commit()
266
+ except Exception as e:
267
+ log_exception(logger, "❌ 记录失败失败")
268
+
269
+ async def record_stats_batch(self, updates: Dict[int, Dict[str, Any]]) -> None:
270
+ """批量累加 Token 统计,减少热路径上的频繁提交。"""
271
+ if not updates:
272
+ return
273
+
274
+ try:
275
+ async with self.session_factory() as session:
276
+ for token_id, values in updates.items():
277
+ success_delta = int(values.get("successful_requests", 0) or 0)
278
+ failure_delta = int(values.get("failed_requests", 0) or 0)
279
+ if success_delta <= 0 and failure_delta <= 0:
280
+ continue
281
+
282
+ stmt_values: Dict[str, Any] = {
283
+ "total_requests": TokenStats.total_requests + success_delta + failure_delta,
284
+ }
285
+ if success_delta > 0:
286
+ stmt_values["successful_requests"] = (
287
+ TokenStats.successful_requests + success_delta
288
+ )
289
+ stmt_values["last_success_time"] = func.now()
290
+ if failure_delta > 0:
291
+ stmt_values["failed_requests"] = (
292
+ TokenStats.failed_requests + failure_delta
293
+ )
294
+ stmt_values["last_failure_time"] = func.now()
295
+
296
+ stmt = (
297
+ update(TokenStats)
298
+ .where(TokenStats.token_id == token_id)
299
+ .values(**stmt_values)
300
+ )
301
+ await session.execute(stmt)
302
+ await session.commit()
303
+ except Exception as e:
304
+ log_exception(logger, "❌ 批量记录 Token 统计失败")
305
+ raise
306
+
307
+ async def get_token_stats(self, token_id: int) -> Optional[Dict]:
308
+ try:
309
+ async with self.session_factory() as session:
310
+ stmt = select(TokenStats).filter_by(token_id=token_id)
311
+ result = await session.execute(stmt)
312
+ stats = result.scalar_one_or_none()
313
+ if not stats:
314
+ return None
315
+ return {
316
+ "id": stats.id,
317
+ "token_id": stats.token_id,
318
+ "total_requests": stats.total_requests,
319
+ "successful_requests": stats.successful_requests,
320
+ "failed_requests": stats.failed_requests,
321
+ "last_success_time": str(stats.last_success_time) if stats.last_success_time else None,
322
+ "last_failure_time": str(stats.last_failure_time) if stats.last_failure_time else None,
323
+ }
324
+ except Exception as e:
325
+ log_exception(logger, "❌ 获取统计信息失败")
326
+ return None
327
+
328
+ # ==================== 批量操作 ====================
329
+
330
+ async def bulk_add_tokens(
331
+ self,
332
+ provider: str,
333
+ tokens: List[str],
334
+ token_type: str = "user",
335
+ validate: bool = True
336
+ ) -> Tuple[int, int]:
337
+ added_count = 0
338
+ failed_count = 0
339
+
340
+ for token in tokens:
341
+ if token.strip():
342
+ # SQLAlchemy 没有方便的 bulk insert + override 并支持验证的方法,
343
+ # 所以我们还是复用 add_token 提供验证和统计记录的同时插入。
344
+ token_id = await self.add_token(
345
+ provider,
346
+ token.strip(),
347
+ token_type,
348
+ validate=validate
349
+ )
350
+ if token_id:
351
+ added_count += 1
352
+ else:
353
+ failed_count += 1
354
+
355
+ logger.info(f"✅ 批量添加完成: {provider} - 成功 {added_count}/{len(tokens)},失败 {failed_count}")
356
+ return added_count, failed_count
357
+
358
+ async def replace_tokens(self, provider: str, tokens: List[str],
359
+ token_type: str = "user"):
360
+ await self.delete_tokens_by_provider(provider)
361
+ added_count, _ = await self.bulk_add_tokens(provider, tokens, token_type)
362
+ logger.info(f"✅ 替换 Token 完成: {provider} - {added_count} 个")
363
+ return added_count
364
+
365
+ async def remove_duplicate_tokens(self, provider: Optional[str] = None) -> int:
366
+ try:
367
+ tokens = (
368
+ await self.get_tokens_by_provider(provider, enabled_only=False)
369
+ if provider
370
+ else await self.get_all_tokens(enabled_only=False)
371
+ )
372
+
373
+ seen_keys: set[tuple[str, str]] = set()
374
+ duplicate_ids: list[int] = []
375
+
376
+ for token_record in tokens:
377
+ token_value = str(token_record.get("token") or "").strip()
378
+ token_provider = str(token_record.get("provider") or "")
379
+ key = (token_provider, token_value)
380
+
381
+ if key in seen_keys:
382
+ duplicate_ids.append(int(token_record["id"]))
383
+ continue
384
+
385
+ seen_keys.add(key)
386
+
387
+ deleted_count = await self.delete_tokens_by_ids(duplicate_ids)
388
+ if deleted_count > 0:
389
+ logger.info(f"✅ 已清理重复 Token: {deleted_count} 个")
390
+ return deleted_count
391
+ except Exception as e:
392
+ log_exception(logger, "❌ 清理重复 Token 失败")
393
+ return 0
394
+
395
+ # ==================== 实用方法 ====================
396
+
397
+ async def get_token_by_id(self, token_id: int) -> Optional[Dict]:
398
+ try:
399
+ from sqlalchemy.orm import selectinload
400
+ async with self.session_factory() as session:
401
+ stmt = select(Token).options(selectinload(Token.stats)).filter_by(id=token_id)
402
+ result = await session.execute(stmt)
403
+ token_item = result.scalar_one_or_none()
404
+ if not token_item:
405
+ return None
406
+ return self._format_token_row(token_item)
407
+ except Exception as e:
408
+ log_exception(logger, "❌ 查询 Token 失败")
409
+ return None
410
+
411
+ async def get_token_by_value(self, provider: str, token: str) -> Optional[Dict]:
412
+ try:
413
+ from sqlalchemy.orm import selectinload
414
+ async with self.session_factory() as session:
415
+ stmt = select(Token).options(selectinload(Token.stats)).filter_by(provider=provider, token=token)
416
+ result = await session.execute(stmt)
417
+ token_item = result.scalar_one_or_none()
418
+ if not token_item:
419
+ return None
420
+ return self._format_token_row(token_item)
421
+ except Exception as e:
422
+ log_exception(logger, "❌ 查询 Token 失败")
423
+ return None
424
+
425
+ async def get_provider_stats(self, provider: str) -> Dict:
426
+ try:
427
+ async with self.session_factory() as session:
428
+ from sqlalchemy import text
429
+ query = text("""
430
+ SELECT
431
+ COUNT(*) as total_tokens,
432
+ SUM(CASE WHEN is_enabled = true THEN 1 ELSE 0 END) as enabled_tokens,
433
+ SUM(ts.total_requests) as total_requests,
434
+ SUM(ts.successful_requests) as successful_requests,
435
+ SUM(ts.failed_requests) as failed_requests
436
+ FROM tokens t
437
+ LEFT JOIN token_stats ts ON t.id = ts.token_id
438
+ WHERE t.provider = :provider
439
+ """)
440
+ result = await session.execute(query, {"provider": provider})
441
+ row = result.mappings().first()
442
+ if not row or not row.get("total_tokens"):
443
+ return {}
444
+ return dict(row)
445
+ except Exception as e:
446
+ log_exception(logger, "❌ 获取提供商统计失败")
447
+ return {}
448
+
449
+ async def get_provider_token_counts(self, provider: str) -> Dict[str, int]:
450
+ try:
451
+ async with self.session_factory() as session:
452
+ from sqlalchemy import text
453
+ query = text("""
454
+ SELECT
455
+ COUNT(*) as total_tokens,
456
+ SUM(CASE WHEN is_enabled = true THEN 1 ELSE 0 END) as enabled_tokens,
457
+ SUM(CASE WHEN token_type = 'user' THEN 1 ELSE 0 END) as user_tokens,
458
+ SUM(CASE WHEN token_type = 'guest' THEN 1 ELSE 0 END) as guest_tokens,
459
+ SUM(CASE WHEN token_type = 'unknown' THEN 1 ELSE 0 END) as unknown_tokens
460
+ FROM tokens
461
+ WHERE provider = :provider
462
+ """)
463
+ result = await session.execute(query, {"provider": provider})
464
+ row = result.mappings().first()
465
+
466
+ if not row or not row.get('total_tokens'):
467
+ return {
468
+ "total_tokens": 0, "enabled_tokens": 0,
469
+ "user_tokens": 0, "guest_tokens": 0, "unknown_tokens": 0,
470
+ }
471
+
472
+ return {
473
+ "total_tokens": int(row["total_tokens"] or 0),
474
+ "enabled_tokens": int(row["enabled_tokens"] or 0),
475
+ "user_tokens": int(row["user_tokens"] or 0),
476
+ "guest_tokens": int(row["guest_tokens"] or 0),
477
+ "unknown_tokens": int(row["unknown_tokens"] or 0),
478
+ }
479
+ except Exception as e:
480
+ log_exception(logger, "❌ 获取 Token 数量统计失败")
481
+ return {
482
+ "total_tokens": 0, "enabled_tokens": 0,
483
+ "user_tokens": 0, "guest_tokens": 0, "unknown_tokens": 0,
484
+ }
485
+
486
+ async def count_tokens_by_provider(
487
+ self,
488
+ provider: str,
489
+ enabled_only: bool = False,
490
+ ) -> int:
491
+ try:
492
+ async with self.session_factory() as session:
493
+ stmt = select(func.count(Token.id)).filter_by(provider=provider)
494
+ if enabled_only:
495
+ stmt = stmt.filter_by(is_enabled=True)
496
+ result = await session.execute(stmt)
497
+ return result.scalar() or 0
498
+ except Exception as e:
499
+ log_exception(logger, "❌ 统计 Token 总数失败")
500
+ return 0
501
+
502
+ # ==================== Token 验证操作 ====================
503
+ async def validate_and_update_token(self, token_id: int) -> bool:
504
+ try:
505
+ token_info = await self.get_token_by_id(token_id)
506
+ if not token_info:
507
+ logger.error(f"❌ Token ID {token_id} 不存在")
508
+ return False
509
+
510
+ provider = token_info["provider"]
511
+ token = token_info["token"]
512
+
513
+ if provider != "zai":
514
+ logger.info(f"⏭️ 跳过非 zai 提供商的 Token 验证: {provider}")
515
+ return True
516
+
517
+ from app.utils.token_pool import ZAITokenValidator
518
+
519
+ token_type, is_valid, error_msg = await ZAITokenValidator.validate_token(token)
520
+ await self.update_token_type(token_id, token_type)
521
+
522
+ if not is_valid:
523
+ logger.warning(f"⚠️ Token 验证失败: id={token_id}, type={token_type}, error={error_msg}")
524
+
525
+ return is_valid
526
+
527
+ except Exception as e:
528
+ log_exception(logger, "❌ 验证 Token 失败")
529
+ return False
530
+
531
+ async def validate_tokens_detailed(self, provider: str = "zai") -> Dict[str, Any]:
532
+ try:
533
+ tokens = await self.get_tokens_by_provider(provider, enabled_only=False)
534
+
535
+ if not tokens:
536
+ logger.warning(f"⚠️ 没有需要验证的 {provider} Token")
537
+ return {
538
+ "checked": 0, "valid": 0, "guest": 0, "invalid": 0, "invalid_token_ids": [],
539
+ }
540
+
541
+ started_at = time.perf_counter()
542
+ logger.info(
543
+ "[token.validate.batch] start provider=%s total_tokens=%s mode=serial",
544
+ provider,
545
+ len(tokens),
546
+ )
547
+ logger.info(f"🔍 开始批量验证 {len(tokens)} 个 {provider} Token...")
548
+
549
+ from app.utils.token_pool import ZAITokenValidator
550
+
551
+ stats: Dict[str, Any] = {
552
+ "checked": len(tokens), "valid": 0, "guest": 0, "invalid": 0, "invalid_token_ids": [],
553
+ }
554
+
555
+ for token_record in tokens:
556
+ token_id = int(token_record["id"])
557
+ token = str(token_record["token"])
558
+
559
+ token_type, is_valid, error_msg = await ZAITokenValidator.validate_token(token)
560
+ await self.update_token_type(token_id, token_type)
561
+
562
+ if token_type == "user" and is_valid:
563
+ stats["valid"] += 1
564
+ elif token_type == "guest":
565
+ stats["guest"] += 1
566
+ stats["invalid_token_ids"].append(token_id)
567
+ else:
568
+ stats["invalid"] += 1
569
+ stats["invalid_token_ids"].append(token_id)
570
+ if error_msg:
571
+ logger.warning("Token 验证失败: id=%s, type=%s, error=%s", token_id, token_type, error_msg)
572
+
573
+ elapsed_ms = (time.perf_counter() - started_at) * 1000
574
+ logger.info(
575
+ "[token.validate.batch] done provider=%s total_tokens=%s valid=%s guest=%s invalid=%s mode=serial elapsed_ms=%.1f",
576
+ provider,
577
+ stats["checked"],
578
+ stats["valid"],
579
+ stats["guest"],
580
+ stats["invalid"],
581
+ elapsed_ms,
582
+ )
583
+ logger.info("批量验证完成: 有效 %s, 匿名 %s, 无效 %s", stats["valid"], stats["guest"], stats["invalid"])
584
+ return stats
585
+
586
+ except Exception as e:
587
+ log_exception(logger, "❌ 批量验证失败")
588
+ return {
589
+ "checked": 0, "valid": 0, "guest": 0, "invalid": 0, "invalid_token_ids": [],
590
+ }
591
+
592
+ async def validate_all_tokens(self, provider: str = "zai") -> Dict[str, int]:
593
+ stats = await self.validate_tokens_detailed(provider)
594
+ return {
595
+ "valid": int(stats.get("valid", 0) or 0),
596
+ "guest": int(stats.get("guest", 0) or 0),
597
+ "invalid": int(stats.get("invalid", 0) or 0),
598
+ }
599
+
600
+ async def close(self) -> None:
601
+ """关闭数据库连接"""
602
+ if self._engine:
603
+ await self._engine.dispose()
604
+ self._engine = None
605
+
606
+
607
+ # 全局单例
608
+ _token_dao: Optional[TokenDAO] = None
609
+
610
+ def get_token_dao() -> TokenDAO:
611
+ """获取全局 TokenDAO 实例"""
612
+ global _token_dao
613
+ if _token_dao is None:
614
+ _token_dao = TokenDAO()
615
+ return _token_dao
616
+
617
+ async def init_token_database():
618
+ """初始化 Token 数据库"""
619
+ dao = get_token_dao()
620
+ await dao.init_database()
app/services/token_importer.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """本地目录 / 上传文件 token 导入服务。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+ from typing import List, Optional, Tuple
9
+
10
+ from app.services.token_dao import TokenDAO, get_token_dao
11
+ from app.utils.logger import logger
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class TokenImportSummary:
16
+ source_dir: str
17
+ scanned_files: int
18
+ imported_count: int
19
+ duplicate_count: int
20
+ invalid_json_count: int
21
+ missing_token_count: int
22
+ invalid_token_count: int
23
+
24
+ @property
25
+ def failed_count(self) -> int:
26
+ return (
27
+ self.duplicate_count
28
+ + self.invalid_json_count
29
+ + self.missing_token_count
30
+ + self.invalid_token_count
31
+ )
32
+
33
+
34
+ def _load_token_payload(file_path: Path) -> dict:
35
+ try:
36
+ return json.loads(file_path.read_text(encoding="utf-8"))
37
+ except json.JSONDecodeError as exc:
38
+ raise ValueError(f"JSON 解析失败: {exc}") from exc
39
+
40
+
41
+ def _parse_token_bytes(data: bytes, filename: str = "<upload>") -> dict:
42
+ """将上传的 bytes 解析为 dict,失败时抛出 ValueError。"""
43
+ try:
44
+ return json.loads(data)
45
+ except json.JSONDecodeError as exc:
46
+ raise ValueError(f"JSON 解析失败 ({filename}): {exc}") from exc
47
+
48
+
49
+ async def import_tokens_from_directory(
50
+ source_dir: str | Path,
51
+ *,
52
+ provider: str = "zai",
53
+ validate: bool = True,
54
+ dao: Optional[TokenDAO] = None,
55
+ ) -> TokenImportSummary:
56
+ """
57
+ 从本地目录导入 token。
58
+
59
+ 目录中的每个 JSON 文件应至少包含 `token` 字段。
60
+ """
61
+ source_path = Path(source_dir).expanduser().resolve()
62
+ if not source_path.exists():
63
+ raise FileNotFoundError(f"导入目录不存在: {source_path}")
64
+ if not source_path.is_dir():
65
+ raise NotADirectoryError(f"导入路径不是目录: {source_path}")
66
+
67
+ token_dao = dao or get_token_dao()
68
+ token_files = sorted(source_path.rglob("*.json"))
69
+ seen_tokens: set[str] = set()
70
+ imported_count = 0
71
+ duplicate_count = 0
72
+ invalid_json_count = 0
73
+ missing_token_count = 0
74
+ invalid_token_count = 0
75
+
76
+ for file_path in token_files:
77
+ try:
78
+ payload = _load_token_payload(file_path)
79
+ except ValueError as exc:
80
+ invalid_json_count += 1
81
+ logger.warning(f"⚠️ 跳过无效 JSON 文件: {file_path} - {exc}")
82
+ continue
83
+
84
+ if not isinstance(payload, dict):
85
+ invalid_json_count += 1
86
+ logger.warning(f"⚠️ 跳过非对象 JSON 文件: {file_path}")
87
+ continue
88
+
89
+ token = str(payload.get("token") or "").strip()
90
+ email = str(payload.get("email") or "").strip()
91
+ if not token:
92
+ missing_token_count += 1
93
+ logger.warning(f"⚠️ 文件缺少 token 字段: {file_path}")
94
+ continue
95
+
96
+ if token in seen_tokens:
97
+ duplicate_count += 1
98
+ logger.debug("跳过本批次重复 Token: %s", file_path.name)
99
+ continue
100
+ seen_tokens.add(token)
101
+
102
+ existing = await token_dao.get_token_by_value(provider, token)
103
+ if existing is not None:
104
+ duplicate_count += 1
105
+ logger.debug(
106
+ "Token 已存在,跳过导入: %s (%s)",
107
+ file_path.name,
108
+ email or "unknown",
109
+ )
110
+ continue
111
+
112
+ token_id = await token_dao.add_token(
113
+ provider=provider,
114
+ token=token,
115
+ token_type="user",
116
+ validate=validate,
117
+ )
118
+ if token_id is None:
119
+ invalid_token_count += 1
120
+ logger.warning(f"⚠️ Token 导入失败: {file_path.name} ({email or 'unknown'})")
121
+ continue
122
+
123
+ imported_count += 1
124
+ logger.debug("已导入 Token: %s (%s)", file_path.name, email or "unknown")
125
+
126
+ summary = TokenImportSummary(
127
+ source_dir=str(source_path),
128
+ scanned_files=len(token_files),
129
+ imported_count=imported_count,
130
+ duplicate_count=duplicate_count,
131
+ invalid_json_count=invalid_json_count,
132
+ missing_token_count=missing_token_count,
133
+ invalid_token_count=invalid_token_count,
134
+ )
135
+ logger.info(
136
+ "Token 目录导入完成: "
137
+ "scanned=%s, imported=%s, duplicate=%s, invalid_json=%s, "
138
+ "missing_token=%s, invalid_token=%s",
139
+ summary.scanned_files,
140
+ summary.imported_count,
141
+ summary.duplicate_count,
142
+ summary.invalid_json_count,
143
+ summary.missing_token_count,
144
+ summary.invalid_token_count,
145
+ )
146
+ return summary
147
+
148
+
149
+ async def import_tokens_from_uploaded_files(
150
+ files: List[Tuple[str, bytes]],
151
+ *,
152
+ provider: str = "zai",
153
+ validate: bool = True,
154
+ dao: Optional[TokenDAO] = None,
155
+ ) -> TokenImportSummary:
156
+ """
157
+ 从上传的 JSON 文件列表导入 token。
158
+
159
+ 每个元素为 (filename, file_bytes),JSON 应至少包含 `token` 字段。
160
+ 与 import_tokens_from_directory 保持一致的去重 / 验证逻辑。
161
+ """
162
+ token_dao = dao or get_token_dao()
163
+ seen_tokens: set[str] = set()
164
+ imported_count = 0
165
+ duplicate_count = 0
166
+ invalid_json_count = 0
167
+ missing_token_count = 0
168
+ invalid_token_count = 0
169
+
170
+ for filename, data in files:
171
+ try:
172
+ payload = _parse_token_bytes(data, filename)
173
+ except ValueError as exc:
174
+ invalid_json_count += 1
175
+ logger.warning(f"⚠️ 跳过无效 JSON 文件: {filename} - {exc}")
176
+ continue
177
+
178
+ if not isinstance(payload, dict):
179
+ invalid_json_count += 1
180
+ logger.warning(f"⚠️ 跳过非对象 JSON 文件: {filename}")
181
+ continue
182
+
183
+ token = str(payload.get("token") or "").strip()
184
+ email = str(payload.get("email") or "").strip()
185
+ if not token:
186
+ missing_token_count += 1
187
+ logger.warning(f"⚠️ 文件缺少 token 字段: {filename}")
188
+ continue
189
+
190
+ if token in seen_tokens:
191
+ duplicate_count += 1
192
+ logger.debug("跳过本批次重复 Token: %s", filename)
193
+ continue
194
+ seen_tokens.add(token)
195
+
196
+ existing = await token_dao.get_token_by_value(provider, token)
197
+ if existing is not None:
198
+ duplicate_count += 1
199
+ logger.debug(
200
+ "Token 已存在,跳过导入: %s (%s)",
201
+ filename,
202
+ email or "unknown",
203
+ )
204
+ continue
205
+
206
+ token_id = await token_dao.add_token(
207
+ provider=provider,
208
+ token=token,
209
+ token_type="user",
210
+ validate=validate,
211
+ )
212
+ if token_id is None:
213
+ invalid_token_count += 1
214
+ logger.warning(f"⚠️ Token 导入失败: {filename} ({email or 'unknown'})")
215
+ continue
216
+
217
+ imported_count += 1
218
+ logger.debug("已导入 Token: %s (%s)", filename, email or "unknown")
219
+
220
+ summary = TokenImportSummary(
221
+ source_dir="upload",
222
+ scanned_files=len(files),
223
+ imported_count=imported_count,
224
+ duplicate_count=duplicate_count,
225
+ invalid_json_count=invalid_json_count,
226
+ missing_token_count=missing_token_count,
227
+ invalid_token_count=invalid_token_count,
228
+ )
229
+ logger.info(
230
+ "Token 文件上传导入完成: "
231
+ "scanned=%s, imported=%s, duplicate=%s, invalid_json=%s, "
232
+ "missing_token=%s, invalid_token=%s",
233
+ summary.scanned_files,
234
+ summary.imported_count,
235
+ summary.duplicate_count,
236
+ summary.invalid_json_count,
237
+ summary.missing_token_count,
238
+ summary.invalid_token_count,
239
+ )
240
+ return summary
app/services/token_stats_writer.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Async batch writer for token usage statistics."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from dataclasses import dataclass
7
+ from typing import Any, Dict, List, Optional
8
+
9
+ from app.utils.logger import logger, log_exception
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class TokenStatsUpdate:
14
+ token: str
15
+ token_id: int
16
+ successful_requests: int = 0
17
+ failed_requests: int = 0
18
+
19
+
20
+ class AsyncTokenStatsWriter:
21
+ """Queue-based batch writer for token stats."""
22
+
23
+ def __init__(
24
+ self,
25
+ *,
26
+ batch_size: int = 200,
27
+ flush_interval: float = 1.0,
28
+ max_queue_size: int = 20000,
29
+ ) -> None:
30
+ self._batch_size = batch_size
31
+ self._flush_interval = flush_interval
32
+ self._queue: asyncio.Queue[TokenStatsUpdate] = asyncio.Queue(
33
+ maxsize=max_queue_size
34
+ )
35
+ self._task: Optional[asyncio.Task] = None
36
+ self._flush_lock = asyncio.Lock()
37
+
38
+ async def start(self) -> None:
39
+ if self._task is not None:
40
+ return
41
+ self._task = asyncio.create_task(self._run(), name="token-stats-writer")
42
+ logger.debug("AsyncTokenStatsWriter started")
43
+
44
+ async def stop(self) -> None:
45
+ if self._task is not None:
46
+ await self._cancel_worker(restart=False)
47
+ else:
48
+ await self._drain_queue()
49
+ logger.debug("AsyncTokenStatsWriter stopped")
50
+
51
+ def enqueue(
52
+ self,
53
+ *,
54
+ token: str,
55
+ token_id: int,
56
+ successful_requests: int = 0,
57
+ failed_requests: int = 0,
58
+ ) -> bool:
59
+ if successful_requests <= 0 and failed_requests <= 0:
60
+ return True
61
+
62
+ try:
63
+ self._queue.put_nowait(
64
+ TokenStatsUpdate(
65
+ token=token,
66
+ token_id=token_id,
67
+ successful_requests=successful_requests,
68
+ failed_requests=failed_requests,
69
+ )
70
+ )
71
+ return True
72
+ except asyncio.QueueFull:
73
+ logger.warning("Token stats queue full, skipping async enqueue")
74
+ return False
75
+
76
+ async def flush_now(self) -> None:
77
+ if self._task is not None:
78
+ await self._cancel_worker(restart=True)
79
+ return
80
+ await self._drain_queue()
81
+
82
+ async def _drain_queue(self) -> None:
83
+ async with self._flush_lock:
84
+ while not self._queue.empty():
85
+ batch = await self._collect_batch(wait_for_first=False)
86
+ if not batch:
87
+ break
88
+ await asyncio.shield(self._write_batch(batch))
89
+
90
+ async def _cancel_worker(self, *, restart: bool) -> None:
91
+ task = self._task
92
+ if task is None:
93
+ if restart:
94
+ await self.start()
95
+ return
96
+
97
+ self._task = None
98
+ task.cancel()
99
+ try:
100
+ await task
101
+ except asyncio.CancelledError:
102
+ pass
103
+
104
+ await self._drain_queue()
105
+ if restart:
106
+ await self.start()
107
+
108
+ async def _run(self) -> None:
109
+ while True:
110
+ batch: List[TokenStatsUpdate] = []
111
+ try:
112
+ batch = await self._collect_batch(wait_for_first=True)
113
+ if batch:
114
+ async with self._flush_lock:
115
+ await asyncio.shield(self._write_batch(batch))
116
+ except asyncio.CancelledError:
117
+ if batch:
118
+ async with self._flush_lock:
119
+ await asyncio.shield(self._write_batch(batch))
120
+ raise
121
+ except Exception as exc:
122
+ log_exception(logger, "AsyncTokenStatsWriter flush error")
123
+ await asyncio.sleep(1)
124
+
125
+ async def _collect_batch(self, *, wait_for_first: bool) -> List[TokenStatsUpdate]:
126
+ batch: List[TokenStatsUpdate] = []
127
+ if wait_for_first:
128
+ try:
129
+ item = await asyncio.wait_for(
130
+ self._queue.get(), timeout=self._flush_interval
131
+ )
132
+ batch.append(item)
133
+ except asyncio.TimeoutError:
134
+ return batch
135
+
136
+ while len(batch) < self._batch_size:
137
+ try:
138
+ batch.append(self._queue.get_nowait())
139
+ except asyncio.QueueEmpty:
140
+ break
141
+ return batch
142
+
143
+ @staticmethod
144
+ def _merge_batch(
145
+ batch: List[TokenStatsUpdate],
146
+ ) -> Dict[int, Dict[str, Any]]:
147
+ merged: Dict[int, Dict[str, Any]] = {}
148
+ for item in batch:
149
+ entry = merged.setdefault(
150
+ item.token_id,
151
+ {
152
+ "token": item.token,
153
+ "successful_requests": 0,
154
+ "failed_requests": 0,
155
+ },
156
+ )
157
+ entry["successful_requests"] += item.successful_requests
158
+ entry["failed_requests"] += item.failed_requests
159
+ return merged
160
+
161
+ @staticmethod
162
+ async def _write_batch(batch: List[TokenStatsUpdate]) -> None:
163
+ from app.services.token_dao import get_token_dao
164
+ from app.utils.token_pool import get_token_pool
165
+
166
+ merged = AsyncTokenStatsWriter._merge_batch(batch)
167
+ dao = get_token_dao()
168
+ await dao.record_stats_batch(merged)
169
+
170
+ pool = get_token_pool()
171
+ if pool:
172
+ for entry in merged.values():
173
+ await pool.mark_stats_synced(
174
+ token=str(entry["token"]),
175
+ successful_requests=int(entry["successful_requests"]),
176
+ failed_requests=int(entry["failed_requests"]),
177
+ )
178
+
179
+
180
+ _token_stats_writer: Optional[AsyncTokenStatsWriter] = None
181
+
182
+
183
+ def get_token_stats_writer() -> AsyncTokenStatsWriter:
184
+ global _token_stats_writer
185
+ if _token_stats_writer is None:
186
+ _token_stats_writer = AsyncTokenStatsWriter()
187
+ return _token_stats_writer